In case you are using MultiBinding with your TextBox you need to use BindingOperations.GetMultiBindingExpression
method instead of BindingOperations.GetBindingExpression
.
// Get the correct binding expression based on type of binding
//(simple binding or multi binding.
BindingExpressionBase binding =
BindingOperations.GetBindingExpression(element, prop);
if (binding == null)
{
binding = BindingOperations.GetMultiBindingExpression(element, prop);
}
if (binding != null)
{
object value = element.GetValue(prop);
if (string.IsNullOrEmpty(value.ToString()) == true)
{
binding.UpdateTarget();
}
else
{
binding.UpdateSource();
}
}
if(sender is TextBox) {
var text = (sender as TextBox).Text;
}
If you don't want to add the MoreLinq library to your project just to get the DistinctBy
functionality then you can get the same end result using the overload of Linq's Distinct
method that takes in an IEqualityComparer
argument.
You begin by creating a generic custom equality comparer class that uses lambda syntax to perform custom comparison of two instances of a generic class:
public class CustomEqualityComparer<T> : IEqualityComparer<T>
{
Func<T, T, bool> _comparison;
Func<T, int> _hashCodeFactory;
public CustomEqualityComparer(Func<T, T, bool> comparison, Func<T, int> hashCodeFactory)
{
_comparison = comparison;
_hashCodeFactory = hashCodeFactory;
}
public bool Equals(T x, T y)
{
return _comparison(x, y);
}
public int GetHashCode(T obj)
{
return _hashCodeFactory(obj);
}
}
Then in your main code you use it like so:
Func<Person, Person, bool> areEqual = (p1, p2) => int.Equals(p1.Id, p2.Id);
Func<Person, int> getHashCode = (p) => p.Id.GetHashCode();
var query = people.Distinct(new CustomEqualityComparer<Person>(areEqual, getHashCode));
Voila! :)
The above assumes the following:
Person.Id
is of type int
people
collection does not contain any null elementsIf the collection could contain nulls then simply rewrite the lambdas to check for null, e.g.:
Func<Person, Person, bool> areEqual = (p1, p2) =>
{
return (p1 != null && p2 != null) ? int.Equals(p1.Id, p2.Id) : false;
};
EDIT
This approach is similar to the one in Vladimir Nesterovsky's answer but simpler.
It is also similar to the one in Joel's answer but allows for complex comparison logic involving multiple properties.
However, if your objects can only ever differ by Id
then another user gave the correct answer that all you need to do is override the default implementations of GetHashCode()
and Equals()
in your Person
class and then just use the out-of-the-box Distinct()
method of Linq to filter out any duplicates.
Jon's answer talks about TimeZone, but I'd suggest using TimeZoneInfo instead.
Personally I like keeping things in UTC where possible (at least for the past; storing UTC for the future has potential issues), so I'd suggest a structure like this:
public struct DateTimeWithZone
{
private readonly DateTime utcDateTime;
private readonly TimeZoneInfo timeZone;
public DateTimeWithZone(DateTime dateTime, TimeZoneInfo timeZone)
{
var dateTimeUnspec = DateTime.SpecifyKind(dateTime, DateTimeKind.Unspecified);
utcDateTime = TimeZoneInfo.ConvertTimeToUtc(dateTimeUnspec, timeZone);
this.timeZone = timeZone;
}
public DateTime UniversalTime { get { return utcDateTime; } }
public TimeZoneInfo TimeZone { get { return timeZone; } }
public DateTime LocalTime
{
get
{
return TimeZoneInfo.ConvertTime(utcDateTime, timeZone);
}
}
}
You may wish to change the "TimeZone" names to "TimeZoneInfo" to make things clearer - I prefer the briefer names myself.
It seems to me that you are operating on at least one false assumption.
In your question you say this:
BackgroundWorker is not the answer because it may be that I don't get the progress notification, which means there would be no call to ProgressChanged as the DoWork is a single call to an external function . . .
Actually, it does not matter whether you call the ProgressChanged
event or not. The whole purpose of that event is to temporarily transfer control back to the GUI thread to make an update that somehow reflects the progress of the work being done by the BackgroundWorker
. If you are simply displaying a marquee progress bar, it would actually be pointless to raise the ProgressChanged
event at all. The progress bar will continue rotating as long as it is displayed because the BackgroundWorker
is doing its work on a separate thread from the GUI.
(On a side note, DoWork
is an event, which means that it is not just "a single call to an external function"; you can add as many handlers as you like; and each of those handlers can contain as many function calls as it likes.)
To me it sounds like you believe that the only way for the GUI to update is by calling Application.DoEvents
:
I need to keep call the Application.DoEvents(); for the progress bar to keep rotating.
This is not true in a multithreaded scenario; if you use a BackgroundWorker
, the GUI will continue to be responsive (on its own thread) while the BackgroundWorker
does whatever has been attached to its DoWork
event. Below is a simple example of how this might work for you.
private void ShowProgressFormWhileBackgroundWorkerRuns() {
// this is your presumably long-running method
Action<string, string> exec = DoSomethingLongAndNotReturnAnyNotification;
ProgressForm p = new ProgressForm(this);
BackgroundWorker b = new BackgroundWorker();
// set the worker to call your long-running method
b.DoWork += (object sender, DoWorkEventArgs e) => {
exec.Invoke(path, parameters);
};
// set the worker to close your progress form when it's completed
b.RunWorkerCompleted += (object sender, RunWorkerCompletedEventArgs e) => {
if (p != null && p.Visible) p.Close();
};
// now actually show the form
p.Show();
// this only tells your BackgroundWorker to START working;
// the current (i.e., GUI) thread will immediately continue,
// which means your progress bar will update, the window
// will continue firing button click events and all that
// good stuff
b.RunWorkerAsync();
}
You say this:
I just need to call Application.DoEvents() so that the Marque progress bar will work, while the worker function works in the Main thread . . .
What you're asking for is simply not real. The "main" thread for a Windows Forms application is the GUI thread, which, if it's busy with your long-running method, is not providing visual updates. If you believe otherwise, I suspect you misunderstand what BeginInvoke
does: it launches a delegate on a separate thread. In fact, the example code you have included in your question to call Application.DoEvents
between exec.BeginInvoke
and exec.EndInvoke
is redundant; you are actually calling Application.DoEvents
repeatedly from the GUI thread, which would be updating anyway. (If you found otherwise, I suspect it's because you called exec.EndInvoke
right away, which blocked the current thread until the method finished.)
So yes, the answer you're looking for is to use a BackgroundWorker
.
You could use BeginInvoke
, but instead of calling EndInvoke
from the GUI thread (which will block it if the method isn't finished), pass an AsyncCallback
parameter to your BeginInvoke
call (instead of just passing null
), and close the progress form in your callback. Be aware, however, that if you do that, you're going to have to invoke the method that closes the progress form from the GUI thread, since otherwise you'll be trying to close a form, which is a GUI function, from a non-GUI thread. But really, all the pitfalls of using BeginInvoke
/EndInvoke
have already been dealt with for you with the BackgroundWorker
class, even if you think it's ".NET magic code" (to me, it's just an intuitive and useful tool).
Microsoft .NET framework 3.5 can be installed on windows 10 without having installation media. The file you need is called microsoft-windows-netfx3-ondemand-package.cab
. Just google it and you will get the download links.
After downloading it, copy that file to C:\dotnet35
and run the following command.
Dism.exe /online /enable-feature /featurename:NetFX3 /All /Source:c:\dotnet35 /LimitAccess
Tested and worked in Windows 10 without any issue.
i even tryed to avoid this, just in case doing the Abort on the thread manually, but i rather leave it with the "CompleteRequest" and move on - my code has return commands after redirects anyway. So this can be done
public static void Redirect(string VPathRedirect, global::System.Web.UI.Page Sender)
{
Sender.Response.Redirect(VPathRedirect, false);
global::System.Web.UI.HttpContext.Current.ApplicationInstance.CompleteRequest();
}
I think that if you define the logic in an extension method the code will be much more readable:
public static class EnumerableExtensions {
public static string Join<T>(this IEnumerable<T> self, string separator) {
return String.Join(separator, self.Select(e => e.ToString()).ToArray());
}
}
public class Person {
public string FirstName { get; set; }
public string LastName { get; set; }
public override string ToString() {
return string.Format("{0} {1}", FirstName, LastName);
}
}
// ...
List<Person> people = new List<Person>();
// ...
string fullNames = people.Join(", ");
string lastNames = people.Select(p => p.LastName).Join(", ");
Though you can use First()
, Dictionaries do not have order per se. Please use OrderedDictionary instead. And then you can do FirstOrDefault
. This way it will be meaningful.
Try this
var row = (from result in dt.AsEnumerable().OrderBy( result => Guid.NewGuid()) select result).Take(3) ;
Personnaly I encountered this issue while migrating a IIS6 website into IIS7, in order to fix this issue I used this command line :
%windir%\System32\inetsrv\appcmd migrate config "MyWebSite\"
Make sure to backup your web.config
you will also need to have a asp:ScriptManager control on every page that you want to use ajax controls on. you should be able to just drag the scriptmanager over from your toolbox one the toolkit is installed following Zack's instructions.
This is what worked nicely for me since all I wanted to do was set the height of the textbox. The property is Read-Only and the property is in the Unit class so you can't just set it. So I just created a new Unit and the constructor lets me set the height, then set the textbox to that unit instead.
Unit height = txtTextBox.Height;
double oldHeight = height.Value;
double newHeight = height.Value + 20; //Added 20 pixels
Unit newHeightUnit = new Unit(newHeight);
txtTextBox.Height = newHeightUnit;
Have you considered an IsNotReadOnly
property? If the object being bound is a ViewModel in a MVVM domain, then the additional property makes perfect sense. If it's a direct Entity model, you might consider composition and presenting a specialized ViewModel of your entity to the form.
You can do this in one line, using the conditional operator and the fact that you can cast null
to a nullable type (two lines, if you don't have a pre-existing int you can reuse for the output of TryParse
):
Pre C#7:
int tempVal;
int? val = Int32.TryParse(stringVal, out tempVal) ? Int32.Parse(stringVal) : (int?)null;
With C#7's updated syntax that allows you to declare an output variable in the method call, this gets even simpler.
int? val = Int32.TryParse(stringVal, out var tempVal) ? tempVal : (int?)null;
You can do something like this to count from a list of things.
IList<String> names = new List<string>() { "ToString", "Format" };
IEnumerable<String> methodNames = typeof(String).GetMethods().Select(x => x.Name);
int count = methodNames.Where(x => names.Contains(x)).Count();
To count a single element
string occur = "Test1";
IList<String> words = new List<string>() {"Test1","Test2","Test3","Test1"};
int count = words.Where(x => x.Equals(occur)).Count();
Here is a working example that get IT skills that a job candidate does not already have.
//Get a list of skills from the Skill table
IEnumerable<Skill> skillenum = skillrepository.Skill;
//Get a list of skills the candidate has
IEnumerable<CandSkill> candskillenum = candskillrepository.CandSkill
.Where(p => p.Candidate_ID == Candidate_ID);
//Using the enum lists with LINQ filter out the skills not in the candidate skill list
IEnumerable<Skill> skillenumresult = skillenum.Where(p => !candskillenum.Any(p2 => p2.Skill_ID == p.Skill_ID));
//Assign the selectable list to a viewBag
ViewBag.SelSkills = new SelectList(skillenumresult, "Skill_ID", "Skill_Name", 1);
With ASP.NET, you need to consider the reference point for a "relative URL" - is it relative to the page request, a user control, or if it is "relative" simply by virtue of using "~/"?
The Uri
class contains a simple way to convert a relative URL to an absolute URL (given an absolute URL as the reference point for the relative URL):
var uri = new Uri(absoluteUrl, relativeUrl);
If relativeUrl
is in fact an abolute URL, then the absoluteUrl
is ignored.
The only question then remains what the reference point is, and whether "~/" URLs are allowed (the Uri
constructor does not translate these).
just my couple cents... the practice that I often use is to organize the methods like this as a custom helper
public static class StreamHelpers
{
public static byte[] ReadFully(this Stream input)
{
using (MemoryStream ms = new MemoryStream())
{
input.CopyTo(ms);
return ms.ToArray();
}
}
}
add namespace to the config file and use it anywhere you wish
you can:
itemsCart.Select(c=>c.Price).Sum();
To hit the db only once do:
var itemsInCart = (from o in db.OrderLineItems
where o.OrderId == currentOrder.OrderId
select new { o.OrderLineItemId, ..., ..., o.WishListItem.Price}
).ToList();
var sum = itemsCart.Select(c=>c.Price).Sum();
The extra round-trip saved is worth it :)
Having tested several options, I finally solved this by using
contract="IMySOAPWebService"
i.e. without the full namespace in the config. For some reason the full name didn't resolve properly
In a bug I was investigating there was a Response.Redirect() and it was executing in an unexpected location (read: inappropriate location - inside a member property getter method).
If you're debugging a problem and experience the "Unable to evaluate expression..." exception:
Response.Redirect()
and either make the second parameter endResponse = false, orThis was frustrating as it would appear to execute the Redirect call before the "step through" on the debugger had reached that location.
The current Entity Framework EDM generator will create a composite key from all non-nullable fields in your view. In order to gain control over this, you will need to modify the view and underlying table columns setting the columns to nullable when you do not want them to be part of the primary key. The opposite is also true, as I encountered, the EDM generated key was causing data-duplication issues, so I had to define a nullable column as non-nullable to force the composite key in the EDM to include that column.
We use IEnumerable
and IQueryable
to manipulate the data that is retrieved from database. IQueryable
inherits from IEnumerable
, so IQueryable
does contain all the IEnumerable
features. The major difference between IQueryable
and IEnumerable
is that IQueryable
executes query with filters whereas IEnumerable
executes the query first and then it filters the data based on conditions.
Find more detailed differentiation below :
IEnumerable
IEnumerable
exists in the System.Collections
namespaceIEnumerable
execute a select query on the server side, load data in-memory on a client-side and then filter dataIEnumerable
is suitable for querying data from in-memory collections like List, ArrayIEnumerable
is beneficial for LINQ to Object and LINQ to XML queriesIQueryable
IQueryable
exists in the System.Linq
namespaceIQueryable
executes a 'select query' on server-side with all filtersIQueryable
is suitable for querying data from out-memory (like remote database, service) collectionsIQueryable
is beneficial for LINQ to SQL queriesSo IEnumerable
is generally used for dealing with in-memory collection, whereas, IQueryable
is generally used to manipulate collections.
Your collection class could have a method that returns a collection (a sublist) based on criteria passed in to define the filter. Build a new collection with the foreach loop and pass it out.
Or, have the method and loop modify the existing collection by setting a "filtered" or "active" flag (property). This one could work but could also cause poblems in multithreaded code. If other objects deped on the contents of the collection this is either good or bad depending of how you use the data.
Take a look at this article which shows the registry keys you need to look for and provides a .NET library that will do this for you.
First, you should to determine if .NET 3.5 is installed by looking at HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.5\Install, which is a DWORD value. If that value is present and set to 1, then that version of the Framework is installed.
Look at HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.5\SP, which is a DWORD value which indicates the Service Pack level (where 0 is no service pack).
To be correct about things, you really need to ensure that .NET Fx 2.0 and .NET Fx 3.0 are installed first and then check to see if .NET 3.5 is installed. If all three are true, then you can check for the service pack level.
I like a nice simple extension method
public static string ToCsv(this List<string> itemList)
{
return string.Join(",", itemList);
}
Then you can just call the method on the original list:
string CsvString = myList.ToCsv();
Cleaner and easier to read than some of the other suggestions.
Simply right click on your project in Visual Basic Solution Explorer (where your vb files are) and select properties from the menu. In the window that pops up deselect "Enable XP Visual Styles" and now when you set forecolor, it should work now.
Since this is a rather popular topic and answers differ, I had to take a fresh look on the problem.
Testing env: EF 6.1.3, SQL Server, 300k records
Table model:
class TestTable
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
}
Test code:
class Program
{
static void Main()
{
using (var context = new TestContext())
{
context.Database.Log = Console.WriteLine;
context.TestTables.Where(x => x.Surname.Contains("Surname")).Any(x => x.Id > 1000);
context.TestTables.Where(x => x.Surname.Contains("Surname") && x.Name.Contains("Name")).Any(x => x.Id > 1000);
context.TestTables.Where(x => x.Surname.Contains("Surname")).Count(x => x.Id > 1000);
context.TestTables.Where(x => x.Surname.Contains("Surname") && x.Name.Contains("Name")).Count(x => x.Id > 1000);
Console.ReadLine();
}
}
}
Results:
Any() ~ 3ms
Count() ~ 230ms for first query, ~ 400ms for second
Remarks:
For my case, EF didn't generate SQL like @Ben mentioned in his post.
string content = System.IO.File.ReadAllText( @"C:\file.txt" );
Use asp:Panel
for that. It translates into a div.
You can check the Ascii value by e.keychar on KeyPress event of TextBox.
By checking the AscII value you can check for number or character.
Similarly you can write logic to check the Email ID.
A bonus would be if I can detect the specific version(s) of Excel that is(/are) installed.
I know the question has been asked and answered a long time ago, but this same question has kept me busy until I made this observation:
To get the build number (e.g. 15.0.4569.1506
), probe HKLM\SOFTWARE\Microsoft\Office\[VER]\Common\ProductVersion::LastProduct
, where [VER]
is the major version number (12.0 for Office 2007, 14.0 for Office 2010, 15.0 for Office 2013).
On a 64-bit Windows, you need to insert Wow6432Node
between the SOFTWARE
and Microsoft
crumbs, irrespective of the bitness of the Office installation.
On my machines, this gives the version information of the originally installed version. For Office 2010 for instance, the numbers match the ones listed here, and they differ from the version reported in File > Help
, which reflects patches applied by hotfixes.
For HTTP:
<bindings>
<basicHttpBinding>
<binding name="basicHttp" allowCookies="true"
maxReceivedMessageSize="20000000"
maxBufferSize="20000000"
maxBufferPoolSize="20000000">
<readerQuotas maxDepth="200"
maxArrayLength="200000000"
maxBytesPerRead="4096"
maxStringContentLength="200000000"
maxNameTableCharCount="16384"/>
</binding>
</basicHttpBinding>
</bindings>
For TCP:
<bindings>
<netTcpBinding>
<binding name="tcpBinding"
maxReceivedMessageSize="20000000"
maxBufferSize="20000000"
maxBufferPoolSize="20000000">
<readerQuotas maxDepth="200"
maxArrayLength="200000000"
maxStringContentLength="200000000"
maxBytesPerRead="4096"
maxNameTableCharCount="16384"/>
</binding>
</netTcpBinding>
</bindings>
IMPORTANT:
If you try to pass complex object that has many connected objects (e.g: a tree data structure, a list that has many objects...), the communication will fail no matter how you increased the Quotas. In such cases, you must increase the containing objects count:
<behaviors>
<serviceBehaviors>
<behavior name="NewBehavior">
...
<dataContractSerializer maxItemsInObjectGraph="2147483646"/>
</behavior>
</serviceBehaviors>
</behaviors>
Setting the CurrentCell
and then calling BeginEdit(true)
works well for me.
The following code shows an eventHandler for the KeyDown
event that sets a cell to be editable.
My example only implements one of the required key press overrides but in theory the others should work the same. (and I'm always setting the [0][0] cell to be editable but any other cell should work)
private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Tab && dataGridView1.CurrentCell.ColumnIndex == 1)
{
e.Handled = true;
DataGridViewCell cell = dataGridView1.Rows[0].Cells[0];
dataGridView1.CurrentCell = cell;
dataGridView1.BeginEdit(true);
}
}
If you haven't found it previously, the DataGridView FAQ is a great resource, written by the program manager for the DataGridView control, which covers most of what you could want to do with the control.
Regarding whitehawk's accepted answer. I am just trying to add a bit hands on experience. Was just trying to add a comments, but SO complains it's too long.
Basically, without IE 9 installed, the registry switch FEATURE_BROWSER_EMULATION won't work AT ALL.
For example, my own experience today I was trying to get the .net webcontrol to work with IE10 mode because one html I am trying to render won't work with .netControl under VS2012, and not even work when I load the html to IE8 directly, still css won't render properly(even after I say allow blocked content). But I have tested the same html ok with IE10 on a friend's win 8 machine. That's why I am trying to set the .net webControl to IE 10 mode but just keeps failing...
Now I figured this is bcos my win 7 machine only have IE8 installed, so regardless which value I set to the FEATURE_BROWSER_EMULATION switch(value to IE9, IE10 IE11), it just won't work AT ALL !
Then I downloaded and installed IE 10 on my win 7 machine. Still it won't work, then I added the FEATURE_BROWSER_EMULATION, it started working !
Also I noticed regardless which value I set , even set it to value 0 by default, the webControl is still using IE 10 mode which still works for me.
So to summarise, If you have IE X installed but you want your .Net webControl to work under IE (X+N) N>0 modo, TWO things you need to do:
Go to MS website & download and install IE (X+N) on your machine, you will need to reboot after installation.
apply whitehawk's answer.
Basically: To control the value of this feature by using the registry, add the name of your executable file to the following setting and set the value to match the desired setting.
HKEY_LOCAL_MACHINE (or HKEY_CURRENT_USER)
SOFTWARE
Microsoft
Internet Explorer
Main
FeatureControl
FEATURE_BROWSER_EMULATION
contoso.exe = (DWORD) 00009000
Windows Internet Explorer 8 and later. The FEATURE_BROWSER_EMULATION feature defines the default emulation mode for Internet Explorer and supports the following values.
Value Description
11001 (0x2AF9 Internet Explorer 11. Webpages are displayed in IE11 edge mode, regardless of the !DOCTYPE directive.
11000 (0x2AF8) IE11. Webpages containing standards-based !DOCTYPE directives are displayed in IE11 edge mode. Default value for IE11.
10001 (0x2711) Internet Explorer 10. Webpages are displayed in IE10 Standards mode, regardless of the !DOCTYPE directive.
10000 (0x02710) Internet Explorer 10. Webpages containing standards-based !DOCTYPE directives are displayed in IE10 Standards mode. Default value for Internet Explorer 10.
9999 (0x270F) Windows Internet Explorer 9. Webpages are displayed in IE9 Standards mode, regardless of the !DOCTYPE directive.
9000 (0x2328) Internet Explorer 9. Webpages containing standards-based !DOCTYPE directives are displayed in IE9 mode. Default value for Internet Explorer 9.
Important In Internet Explorer 10, Webpages containing standards-based !DOCTYPE directives are displayed in IE10 Standards mode.
8888 (0x22B8) Webpages are displayed in IE8 Standards mode, regardless of the !DOCTYPE directive.
8000 (0x1F40) Webpages containing standards-based !DOCTYPE directives are displayed in IE8 mode. Default value for Internet Explorer 8 Important In Internet Explorer 10, Webpages containing standards-based !DOCTYPE directives are displayed in IE10 Standards mode.
7000 (0x1B58) Webpages containing standards-based !DOCTYPE directives are displayed in IE7 Standards mode. Default value for applications hosting the WebBrowser Control.
Full ref here
The ToString
method on the DateTime
struct can take a format parameter:
var dateAsString = DateTime.Now.ToString("yyyy-MM-dd");
// dateAsString = "2011-02-17"
Documentation for standard and custom format strings is available on MSDN.
In the end, both do the same thing. There are some differences in code: Web Services doesn't add a Root namespace of project, but Service Reference adds service classes to the namespace of the project. The ServiceSoapClient
class gets a different naming, which is not important. In working with TFS I'd rather use Service Reference because it works better with source control. Both work with SOAP protocols.
I find it better to use the Service Reference because it is new and will thus be better maintained.
As other guys commented before you can write your own procedure with anonymous function to solve this issue.
I used two ways to solve it:
func Find(slice interface{}, f func(value interface{}) bool) int {
s := reflect.ValueOf(slice)
if s.Kind() == reflect.Slice {
for index := 0; index < s.Len(); index++ {
if f(s.Index(index).Interface()) {
return index
}
}
}
return -1
}
Uses example:
type UserInfo struct {
UserId int
}
func main() {
var (
destinationList []UserInfo
userId int = 123
)
destinationList = append(destinationList, UserInfo {
UserId : 23,
})
destinationList = append(destinationList, UserInfo {
UserId : 12,
})
idx := Find(destinationList, func(value interface{}) bool {
return value.(UserInfo).UserId == userId
})
if idx < 0 {
fmt.Println("not found")
} else {
fmt.Println(idx)
}
}
Second method with less computational cost:
func Search(length int, f func(index int) bool) int {
for index := 0; index < length; index++ {
if f(index) {
return index
}
}
return -1
}
Uses example:
type UserInfo struct {
UserId int
}
func main() {
var (
destinationList []UserInfo
userId int = 123
)
destinationList = append(destinationList, UserInfo {
UserId : 23,
})
destinationList = append(destinationList, UserInfo {
UserId : 123,
})
idx := Search(len(destinationList), func(index int) bool {
return destinationList[index].UserId == userId
})
if idx < 0 {
fmt.Println("not found")
} else {
fmt.Println(idx)
}
}
Use the parseFloat
method to parse the strings into floating point numbers:
parseFloat(num1) + parseFloat(num2)
This was pretty well answered over here: How to make a YouTube embedded video a full page width one?
If you add '?rel=0&autoplay=1' to the end of the url in the embed code (like this)
<iframe id="video" src="//www.youtube.com/embed/5iiPC-VGFLU?rel=0&autoplay=1" frameborder="0" allowfullscreen></iframe>
of the video it should play on load. Here's a demo over at jsfiddle.
JTextField
allows us to getText()
and setText()
these are used to get and set the contents of the text field, for example.
text = texfield.getText();
hope this helps
The downloaded sdk software does not contain sdk platform tools.
For this, using cmd
go to "C:\Program Files\Android\android-sdk\tools"
directory and then type the following command to download those missing tools:
android.bat update sdk --no-ui
Then type y
to accept all the licenses in cmd
. Downloading will start in cmd
itself.
You'll need to install (or enable) the Socket PHP extension: http://www.php.net/manual/en/sockets.installation.php
You can add org.apache.http
by using below code in app:Build gradle
dependencies {
compile 'org.apache.httpcomponents:httpclient:4.5'
}
You can. Try something like this:
@Path("/todo/{varX}/{varY}")
@Produces({"application/xml", "application/json"})
public Todo whatEverNameYouLike(@PathParam("varX") String varX,
@PathParam("varY") String varY) {
Todo todo = new Todo();
todo.setSummary(varX);
todo.setDescription(varY);
return todo;
}
Then call your service with this URL;
http://localhost:8088/JerseyJAXB/rest/todo/summary/description
You need to use the various Bootstrap 4 centering methods...
text-center
for inline elements.justify-content-center
for flexbox elements (ie; form-inline
)https://codeply.com/go/Am5LvvjTxC
Also, to offset the column, the col-sm-*
must be contained within a .row
, and the .row
must be in a container...
<section id="cover">
<div id="cover-caption">
<div id="container" class="container">
<div class="row">
<div class="col-sm-10 offset-sm-1 text-center">
<h1 class="display-3">Welcome to Bootstrap 4</h1>
<div class="info-form">
<form action="" class="form-inline justify-content-center">
<div class="form-group">
<label class="sr-only">Name</label>
<input type="text" class="form-control" placeholder="Jane Doe">
</div>
<div class="form-group">
<label class="sr-only">Email</label>
<input type="text" class="form-control" placeholder="[email protected]">
</div>
<button type="submit" class="btn btn-success ">okay, go!</button>
</form>
</div>
<br>
<a href="#nav-main" class="btn btn-secondary-outline btn-sm" role="button">?</a>
</div>
</div>
</div>
</div>
</section>
I have several projects in a solution. For some of the projects, I previously added the references manually. When I used NuGet to update the WebAPI package, those references were not updated automatically.
I found out that I can either manually update those reference so they point to the v5 DLL inside the Packages folder of my solution or do the following.
According to the spec:
The Content-Length entity-header field indicates the size of the entity-body, in decimal number of OCTETs, sent to the recipient or, in the case of the HEAD method, the size of the entity-body that would have been sent had the request been a GET.
Content-Length = "Content-Length" ":" 1*DIGIT
An example is
Content-Length: 3495
Applications SHOULD use this field to indicate the transfer-length of the message-body, unless this is prohibited by the rules in section 4.4.
Any Content-Length greater than or equal to zero is a valid value. Section 4.4 describes how to determine the length of a message-body if a Content-Length is not given.
Note that the meaning of this field is significantly different from the corresponding definition in MIME, where it is an optional field used within the "message/external-body" content-type. In HTTP, it SHOULD be sent whenever the message's length can be determined prior to being transferred, unless this is prohibited by the rules in section 4.4.
You can use a BehaviorSubject
for communicating between different components throughout the app. You can define a data sharing service containing the BehaviorSubject
to which you can subscribe and emit changes.
Define a data sharing service
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable()
export class DataSharingService {
public isUserLoggedIn: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
}
Add the DataSharingService
in your AppModule
providers entry.
Next, import the DataSharingService
in your <app-header>
and in the component where you perform the sign-in operation. In <app-header>
subscribe to the changes to isUserLoggedIn
subject:
import { DataSharingService } from './data-sharing.service';
export class AppHeaderComponent {
// Define a variable to use for showing/hiding the Login button
isUserLoggedIn: boolean;
constructor(private dataSharingService: DataSharingService) {
// Subscribe here, this will automatically update
// "isUserLoggedIn" whenever a change to the subject is made.
this.dataSharingService.isUserLoggedIn.subscribe( value => {
this.isUserLoggedIn = value;
});
}
}
In your <app-header>
html template, you need to add the *ngIf
condition e.g.:
<button *ngIf="!isUserLoggedIn">Login</button>
<button *ngIf="isUserLoggedIn">Sign Out</button>
Finally, you just need to emit the event once the user has logged in e.g:
someMethodThatPerformsUserLogin() {
// Some code
// .....
// After the user has logged in, emit the behavior subject changes.
this.dataSharingService.isUserLoggedIn.next(true);
}
AllDogs.First(d => d.Id == "2").Name = "some value";
However, a safer version of that might be this:
var dog = AllDogs.FirstOrDefault(d => d.Id == "2");
if (dog != null) { dog.Name = "some value"; }
You will need to create a public/private key as the Jenkins user on your Jenkins server, then copy the public key to the user you want to do the deployment with on your target server.
Step 1, generate public and private key on build server as user jenkins
build1:~ jenkins$ whoami
jenkins
build1:~ jenkins$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/var/lib/jenkins/.ssh/id_rsa):
Created directory '/var/lib/jenkins/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /var/lib/jenkins/.ssh/id_rsa.
Your public key has been saved in /var/lib/jenkins/.ssh/id_rsa.pub.
The key fingerprint is:
[...]
The key's randomart image is:
[...]
build1:~ jenkins$ ls -l .ssh
total 2
-rw------- 1 jenkins jenkins 1679 Feb 28 11:55 id_rsa
-rw-r--r-- 1 jenkins jenkins 411 Feb 28 11:55 id_rsa.pub
build1:~ jenkins$ cat .ssh/id_rsa.pub
ssh-rsa AAAlskdjfalskdfjaslkdjf... [email protected]
Step 2, paste the pub file contents onto the target server.
target:~ bob$ cd .ssh
target:~ bob$ vi authorized_keys (paste in the stuff which was output above.)
Make sure your .ssh dir has permissoins 700 and your authorized_keys file has permissions 644
Step 3, configure Jenkins
You can use .map
: http://jsfiddle.net/9ndcL/1/.
// array of text of each td
var texts = $("td").map(function() {
return $(this).text();
});
One of these will work...
<head>_x000D_
<meta http-equiv='refresh' content='0; URL=http://example.com/'>_x000D_
</head>
_x000D_
...or it can done with JavaScript:
window.location.href = 'https://example.com/';
_x000D_
It's better to use something like this without context and activity:
Resources.getSystem().getString(R.string.my_text)
@agilityvision's answer translated to Swift4/iOS11. I haven't used localized strings, but you can change that easily:
import UIKit
/** An alert controller that can be called without a view controller.
Creates a blank view controller and presents itself over that
**/
class AlertPlusViewController: UIAlertController {
private var alertWindow: UIWindow?
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
self.alertWindow?.isHidden = true
alertWindow = nil
}
func show() {
self.showAnimated(animated: true)
}
func showAnimated(animated _: Bool) {
let blankViewController = UIViewController()
blankViewController.view.backgroundColor = UIColor.clear
let window = UIWindow(frame: UIScreen.main.bounds)
window.rootViewController = blankViewController
window.backgroundColor = UIColor.clear
window.windowLevel = UIWindowLevelAlert + 1
window.makeKeyAndVisible()
self.alertWindow = window
blankViewController.present(self, animated: true, completion: nil)
}
func presentOkayAlertWithTitle(title: String?, message: String?) {
let alertController = AlertPlusViewController(title: title, message: message, preferredStyle: .alert)
let okayAction = UIAlertAction(title: "Ok", style: .default, handler: nil)
alertController.addAction(okayAction)
alertController.show()
}
func presentOkayAlertWithError(error: NSError?) {
let title = "Error"
let message = error?.localizedDescription
presentOkayAlertWithTitle(title: title, message: message)
}
}
You must note however that the Array.filter
is not supported in all browser so, you must to prototyped:
//This prototype is provided by the Mozilla foundation and
//is distributed under the MIT license.
//http://www.ibiblio.org/pub/Linux/LICENSES/mit.license
if (!Array.prototype.filter)
{
Array.prototype.filter = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var res = new Array();
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this)
{
var val = this[i]; // in case fun mutates this
if (fun.call(thisp, val, i, this))
res.push(val);
}
}
return res;
};
}
And doing so, you can prototype any method you may need.
I use static classes as a means to define "extra functionality" that an object of a given type could use under a specific context. Usually they turn out to be utility classes.
Other than that, I think that "Use a static class as a unit of organization for methods not associated with particular objects." describe quite well their intended usage.
When you
import App from './App.jsx';
That means it will import whatever you export default
. You can rename App
class inside App.jsx
to whatever you want as long as you export default
it will work but you can only have one export default.
So you only need to export default App
and you don't need to export the rest.
If you still want to export the rest of the components, you will need named export.
https://developer.mozilla.org/en/docs/web/javascript/reference/statements/export
I've been frustrated by this problem as well. Find/Replace can be helpful though, because if you don't put anything in the "replace" field it will replace with an -actual- NULL. So the steps would be something along the lines of:
1: Place some unique string in your formula in place of the NULL output (i like to use a password-like string)
2: Run your formula
3: Open Find/Replace, and fill in the unique string as the search value. Leave "replace with" blank
4: Replace All
Obviously, this has limitations. It only works when the context allows you to do a find/replace, so for more dynamic formulas this won't help much. But, I figured I'd put it up here anyway.
You can try this:
pushd ../
maven install [...]
popd
Declare them before the while loop.
$hn = "";
$pid = "";
$datereg = "";
$prefix = "";
$fname = "";
$lname = "";
$age = "";
$sex = "";
You are getting the notice because the variables are declared and assigned inside the loop.
I have found the following script is very good at maintaining indexes, you can have this scheduled to run nightly or whatever other timeframe you wish.
Try running ssh user@remote sh ./script.unx
.
One of the putty tools is pscp.exe; it will allow you to copy files from your remote host.
Building off of Master DJon
Here is simplified function which provides the added utility of returning depth (in case you want to use logic to include the parent task or search at a specific depth)
DELIMITER $$
FUNCTION `childDepth`(pParentId INT, pId INT) RETURNS int(11)
READS SQL DATA
DETERMINISTIC
BEGIN
DECLARE depth,curId int;
SET depth = 0;
SET curId = pId;
WHILE curId IS not null AND curId <> pParentId DO
SELECT ParentId from test where id=curId limit 1 into curId;
SET depth = depth + 1;
END WHILE;
IF curId IS NULL THEN
set depth = -1;
END IF;
RETURN depth;
END$$
Usage:
select * from test where childDepth(1, id) <> -1;
I'm trying to learn how to do this myself, and it seems you can install the library like this:
cmake_minimum_required(VERSION 2.4.0)
project(mycustomlib)
# Find source files
file(GLOB SOURCES src/*.cpp)
# Include header files
include_directories(include)
# Create shared library
add_library(${PROJECT_NAME} SHARED ${SOURCES})
# Install library
install(TARGETS ${PROJECT_NAME} DESTINATION lib/${PROJECT_NAME})
# Install library headers
file(GLOB HEADERS include/*.h)
install(FILES ${HEADERS} DESTINATION include/${PROJECT_NAME})
If you are only saving a single object (your data frame), you could also use saveRDS
.
To save:
saveRDS(foo, file="data.Rda")
Then read it with:
bar <- readRDS(file="data.Rda")
The difference between saveRDS
and save
is that in the former only one object can be saved and the name of the object is not forced to be the same after you load it.
You need to put an actual tab character after the -t\ and to do that in a shell you hit ctrl-v and then the tab character. Most shells I've used support this mode of literal tab entry.
Beware, though, because copying and pasting from another place generally does not preserve tabs.
The functions mentioned above execute no matter if it has completed in previous invocation or not, this one runs after every x seconds once the execution is complete
// IIFE
(function runForever(){
// Do something here
setTimeout(runForever, 5000)
})()
// Regular function with arguments
function someFunction(file, directory){
// Do something here
setTimeout(someFunction, 5000, file, directory)
// YES, setTimeout passes any extra args to
// function being called
}
If you already have a reference to a radio button group, for example:
var myRadio = $("input[name=myRadio]");
Use the filter()
function, not find()
. (find()
is for locating child/descendant elements, whereas filter()
searches top-level elements in your selection.)
var checkedValue = myRadio.filter(":checked").val();
Notes: This answer was originally correcting another answer that recommended using find()
, which seems to have since been changed. find()
could still be useful for the situation where you already had a reference to a container element, but not to the radio buttons, e.g.:
var form = $("#mainForm");
...
var checkedValue = form.find("input[name=myRadio]:checked").val();
The guid provided is not correct format(.net Provided guid).
begin try
select convert(uniqueidentifier,'a89b1acd95016ae6b9c8aabb07da2010')
end try
begin catch
print '1'
end catch
The problem with the aforementioned solutions is, that if hour, minute or second, has only one digit (i.e. 0-9), the time would be wrong, e.g. it could be 2:3:9, but it should rather be 02:03:09.
According to this page it seems to be a better solution to use Date's "toLocaleTimeString" method.
Good answers from gdw2 and d5e5. To make it a little simpler here are the recommendations pulled together in a single series of commands:
sqlite> .mode csv
sqlite> .output test.csv
sqlite> select * from tbl1;
sqlite> .output stdout
It may have been covered elsewhere but simply changing the encoding line of the XML source to 'utf-16' allows the XML to be inserted into a SQL Server 'xml'data type.
using (DataSetTableAdapters.SQSTableAdapter tbl_SQS = new DataSetTableAdapters.SQSTableAdapter())
{
try
{
bodyXML = @"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><test></test>";
bodyXMLutf16 = bodyXML.Replace("UTF-8", "UTF-16");
tbl_SQS.Insert(messageID, receiptHandle, md5OfBody, bodyXMLutf16, sourceType);
}
catch (System.Data.SqlClient.SqlException ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}
}
The result is all of the XML text is inserted into the 'xml' data type field but the 'header' line is removed. What you see in the resulting record is just
<test></test>
Using the serialization method described in the "Answered" entry is a way of including the original header in the target field but the result is that the remaining XML text is enclosed in an XML <string></string>
tag.
The table adapter in the code is a class automatically built using the Visual Studio 2013 "Add New Data Source: wizard. The five parameters to the Insert method map to fields in a SQL Server table.
top, parent, opener (as well as window, self, and iframe) are all window objects.
window.opener
-> returns the window that opens or launches the current popup window.window.top
-> returns the topmost window, if you're using frames, this is the frameset window, if not using frames, this is the same as window or self.window.parent
-> returns the parent frame of the current frame or iframe. The parent frame may be the frameset window or another frame if you have nested frames. If not using frames, parent is the same as the current window or selfAdd this code in your app delegate -did_finish_launching_with_options function
UITabBar.appearance().tintColor = UIColor( red: CGFloat(255/255.0), green: CGFloat(99/255.0), blue: CGFloat(95/255.0), alpha: CGFloat(1.0) )
put the RGB of the required color
DON'T use (.|[\r\n])
instead of .
for multiline matching.
DO use [\s\S]
instead of .
for multiline matching
Also, avoid greediness where not needed by using *?
or +?
quantifier instead of *
or +
. This can have a huge performance impact.
See the benchmark I have made: http://jsperf.com/javascript-multiline-regexp-workarounds
Using [^]: fastest
Using [\s\S]: 0.83% slower
Using (.|\r|\n): 96% slower
Using (.|[\r\n]): 96% slower
NB: You can also use [^]
but it is deprecated in the below comment.
You could try something like
<form name="message" method="post">
<section>
<div>
<label for="name">Name</label>
<input id="name" type="text" value="" name="name">
</div>
<div>
<label for="email">Email</label>
<input id="email" type="text" value="" name="email">
</div>
</section>
<section>
<div>
<label for="subject">Subject</label>
<input id="subject" type="text" value="" name="subject">
</div>
<div class="full">
<label for="message">Message</label>
<input id="message" type="text" value="" name="message">
</div>
</section>
</form>
and then css it like
form { width: 400px; }
form section div { float: left; }
form section div.full { clear: both; }
form section div label { display: block; }
This method work for me. It open Gmail app (if installed) and set mailto.
public void openGmail(Activity activity) {
Intent emailIntent = new Intent(Intent.ACTION_VIEW);
emailIntent.setType("text/plain");
emailIntent.setType("message/rfc822");
emailIntent.setData(Uri.parse("mailto:"+activity.getString(R.string.mail_to)));
emailIntent.putExtra(Intent.EXTRA_SUBJECT, activity.getString(R.string.app_name) + " - info ");
final PackageManager pm = activity.getPackageManager();
final List<ResolveInfo> matches = pm.queryIntentActivities(emailIntent, 0);
ResolveInfo best = null;
for (final ResolveInfo info : matches)
if (info.activityInfo.packageName.endsWith(".gm") || info.activityInfo.name.toLowerCase().contains("gmail"))
best = info;
if (best != null)
emailIntent.setClassName(best.activityInfo.packageName, best.activityInfo.name);
activity.startActivity(emailIntent);
}
I am using ansible 2.5 (2.5.3 exactly), and it seems that the vars file is loaded before the hosts param is executed. So you can set the host in a vars.yml file and just write hosts: {{ host_var }}
in your playbook
For example, in my playbook.yml:
---
- hosts: "{{ host_name }}"
become: yes
vars_files:
- vars/project.yml
tasks:
...
And inside vars/project.yml:
---
# general
host_name: your-fancy-host-name
Suppose you want the value of the first item.
ListBox list = new ListBox();
Console.Write(list.Items[0].Value);
Using Backtick
Backticks are commonly used for multi-line strings or when you want to interpolate an expression within your string
let title = 'John';_x000D_
let address = 'address';_x000D_
let address2 = 'address2222';_x000D_
let address3 = 'address33333';_x000D_
let address4 = 'address44444';_x000D_
document.getElementById("address_box").innerText = `${title} _x000D_
${address}_x000D_
${address2}_x000D_
${address3} _x000D_
${address4}`;
_x000D_
<div id="address_box">_x000D_
</div>
_x000D_
There is a online decompiler for android apks
http://www.decompileandroid.com/
Upload apk from local machine
Wait some moments
download source code in zip format.
Unzip it, you can view all resources correctly but all java files are not correctly decompiled.
For full detail visit this answer
You can also do something like this...
<input @input="myHandler('foo', 'bar', ...arguments)">
Evan You himself recommended this technique in one post on Vue forum. In general some events may emit more than one argument. Also as documentation states internal variable $event is meant for passing original DOM event.
From Business Intelligence Studio:
File->New Project->Integration Services Project
Now in solution explorer there is a SSIS Packages folder, right click it and select "Add Existing Package", and there will be a drop down that can be changed to File System, and the very bottom box allows you to browse to the file. Note that this will copy the file from where ever it is into the project's directory structure.
Use:
git remote add upstream ORIGINAL_REPOSITORY_URL
This will set your upstream to the repository you forked from. Then do this:
git fetch upstream
This will fetch all the branches including master from the original repository.
Merge this data in your local master branch:
git merge upstream/master
Push the changes to your forked repository i.e. to origin:
git push origin master
Voila! You are done with the syncing the original repository.
As other have answered, the result is exactly the same, None
is returned in all cases.
The difference is stylistic, but please note that PEP8 requires the use to be consistent:
Be consistent in return statements. Either all return statements in a function should return an expression, or none of them should. If any return statement returns an expression, any return statements where no value is returned should explicitly state this as return None, and an explicit return statement should be present at the end of the function (if reachable).
Yes:
def foo(x): if x >= 0: return math.sqrt(x) else: return None def bar(x): if x < 0: return None return math.sqrt(x)
No:
def foo(x): if x >= 0: return math.sqrt(x) def bar(x): if x < 0: return return math.sqrt(x)
https://www.python.org/dev/peps/pep-0008/#programming-recommendations
Basically, if you ever return non-None
value in a function, it means the return value has meaning and is meant to be caught by callers. So when you return None
, it must also be explicit, to convey None
in this case has meaning, it is one of the possible return values.
If you don't need return at all, you function basically works as a procedure instead of a function, so just don't include the return
statement.
If you are writing a procedure-like function and there is an opportunity to return earlier (i.e. you are already done at that point and don't need to execute the remaining of the function) you may use empty an return
s to signal for the reader it is just an early finish of execution and the None
value returned implicitly doesn't have any meaning and is not meant to be caught (the procedure-like function always returns None
anyway).
If you look at the chain of exceptions, the problem is
Caused by: org.hibernate.PropertyNotFoundException: Could not find a setter for property salt in class backend.Account
The problem is that the method Account.setSalt() works fine when you create an instance but not when you retrieve an instance from the database. This is because you don't want to create a new salt each time you load an Account.
To fix this, create a method setSalt(long) with visibility private and Hibernate will be able to set the value (just a note, I think it works with Private, but you might need to make it package or protected).
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function myfun(){
$(document).ready(function(){
$("#select").click(
function(){
var data=$("#select").val();
$("#disp").val(data);
});
});
}
</script>
</head>
<body>
<p>id <input type="text" name="user" id="disp"></p>
<select id="select" onclick="myfun()">
<option name="1"value="one">1</option>
<option name="2"value="two">2</option>
<option name="3"value="three"></option>
</select>
</body>
</html>
The obvious reason that people wanted assertNotEquals() was to compare builtins without having to convert them to full blown objects first:
Verbose example:
....
assertThat(1, not(equalTo(Integer.valueOf(winningBidderId))));
....
vs.
assertNotEqual(1, winningBidderId);
Sadly since Eclipse doesn't include JUnit 4.11 by default you must be verbose.
Caveat I don't think the '1' needs to be wrapped in an Integer.valueOf() but since I'm newly returned from .NET don't count on my correctness.
queryForList returns a List of LinkedHashMap objects.
You need to cast it first like this:
List list = jdbcTemplate.queryForList(...); for (Object o : list) { Map m = (Map) o; ... }
It's helpful to add to this, even though it's an old post, that if the child view that is being inflated from xml is to be added to a viewgroup layout, you need to call inflate with a clue of what type of viewgroup it is going to be added to. Like:
View child = getLayoutInflater().inflate(R.layout.child, item, false);
The inflate method is quite overloaded and describes this part of the usage in the docs. I had a problem where a single view inflated from xml wasn't aligning in the parent properly until I made this type of change.
You need to access image IDs using R.mipmap.yourImageName
$ od -t x1 -A n -v <empty.zip | tr -dc '[:xdigit:]' && echo
504b0506000000000000000000000000000000000000
$
Use the od
tool to print single hexadecimal bytes (-t x1
) --- without address offsets (-A n
) and without eliding repeated "groups" (-v)
--- from empty.zip
, which has been redirected to standard input. Pipe that to tr
which deletes (-d
) the complement (-c
) of the hexadecimal character set ('[:xdigit:]'
). You can optionally print a trailing newline (echo
) as I've done here to separate the output from the next shell prompt.
man ssh
gives me this options would could be useful.
-i identity_file Selects a file from which the identity (private key) for RSA or DSA authentication is read. The default is ~/.ssh/identity for protocol version 1, and ~/.ssh/id_rsa and ~/.ssh/id_dsa for pro- tocol version 2. Identity files may also be specified on a per- host basis in the configuration file. It is possible to have multiple -i options (and multiple identities specified in config- uration files).
So you could create an alias in your bash config with something like
alias ssh="ssh -i /path/to/private_key"
I haven't looked into a ssh configuration file, but like the -i
option this too could be aliased
-F configfile Specifies an alternative per-user configuration file. If a configuration file is given on the command line, the system-wide configuration file (/etc/ssh/ssh_config) will be ignored. The default for the per-user configuration file is ~/.ssh/config.
Curtis's answer was very close to what I needed, but I changed it up a little.
Where he used:
$options['inputs']['name'][] = $new_input['name'];
I used:
$options[]['inputs']['name'] = $new_input['name'];
Here's my actual code using a query from a DB:
while($row=mysql_fetch_array($result)){
$dtlg_array[]['dt'] = $row['dt'];
$dtlg_array[]['lat'] = $row['lat'];
$dtlg_array[]['lng'] = $row['lng'];
}
Thanks!
For perfomance:
$('#example').children().last()
or if you want a last children with a certain class as commented above.
$('#example').children('.test').last()
or a specific child element with a specific class
$('#example').children('li.test').last()
Looks like the best approach (in 2018) is to use legend.key.size
under the theme
object. (e.g., see here).
#Set-up:
library(ggplot2)
library(gridExtra)
gp <- ggplot(data = mtcars, aes(mpg, cyl, colour = factor(cyl))) +
geom_point()
This is real easy if you are using theme_bw()
:
gpbw <- gp + theme_bw()
#Change spacing size:
g1bw <- gpbw + theme(legend.key.size = unit(0, 'lines'))
g2bw <- gpbw + theme(legend.key.size = unit(1.5, 'lines'))
g3bw <- gpbw + theme(legend.key.size = unit(3, 'lines'))
grid.arrange(g1bw,g2bw,g3bw,nrow=3)
However, this doesn't work quite so well otherwise (e.g., if you need the grey background on your legend symbol):
g1 <- gp + theme(legend.key.size = unit(0, 'lines'))
g2 <- gp + theme(legend.key.size = unit(1.5, 'lines'))
g3 <- gp + theme(legend.key.size = unit(3, 'lines'))
grid.arrange(g1,g2,g3,nrow=3)
#Notice that the legend symbol squares get bigger (that's what legend.key.size does).
#Let's [indirectly] "control" that, too:
gp2 <- g3
g4 <- gp2 + theme(legend.key = element_rect(size = 1))
g5 <- gp2 + theme(legend.key = element_rect(size = 3))
g6 <- gp2 + theme(legend.key = element_rect(size = 10))
grid.arrange(g4,g5,g6,nrow=3) #see picture below, left
Notice that white squares begin blocking legend title (and eventually the graph itself if we kept increasing the value).
#This shows you why:
gt <- gp2 + theme(legend.key = element_rect(size = 10,color = 'yellow' ))
I haven't quite found a work-around for fixing the above problem... Let me know in the comments if you have an idea, and I'll update accordingly!
$layers
...[I assume the reader has basic knowledge of Angular2+ and Forms]
It is easy to show a numerical input and put the limits, but you have to also take care of things may happen out of your predictions.
<input type="number" [min]="0.00" [max]="100.00" [step]="0.01" formControlName="rateFC">
import { FormGroup, FormControl, Validators } from '@angular/forms';
//many other things...
this.myFG = new FormGroup({
//other form controls...,
rateFC : new FormControl(0, [Validators.min(0), Validators.max(100)])
});
.form-control.ng-touched.ng-invalid{
border:2px solid red;
}
<button type="submit" [disabled]="!myFG.valid">Submit</button>
Your task declaration is incorrectly combining the Copy
task type and project.copy
method, resulting in a task that has nothing to copy and thus never runs. Besides, Copy
isn't the right choice for renaming a directory. There is no Gradle API for renaming, but a bit of Groovy code (leveraging Java's File
API) will do. Assuming Project1
is the project directory:
task renABCToXYZ { doLast { file("ABC").renameTo(file("XYZ")) } }
Looking at the bigger picture, it's probably better to add the renaming logic (i.e. the doLast
task action) to the task that produces ABC
.
make clean
generally only cleans built files in the directory containing the source code itself, and rarely touches any installed software.
Makefiles generally don't contain a target for uninstallation -- you usually have to do that yourself, by removing the files from the directory into which they were installed. For example, if you built a program and installed it (using make install
) into /usr/local
, you'd want to look through /usr/local/bin
, /usr/local/libexec
, /usr/local/share/man
, etc., and remove the unwanted files. Sometimes a Makefile includes an uninstall
target, but not always.
Of course, typically on a Linux system you install software using a package manager, which is capable of uninstalling software "automagically".
When you run your form and you want showing text in textbox is clear so you put the code : -
textBox1.text = String.Empty;
Where textBox1 is your textbox name.
Go to the start of the text
Don't forget that the status bar's frame will be in the screen's coordinate space! If you launch in landscape mode, you may find that width and height are swapped. I strongly recommend that you use this version of the code instead if you support landscape orientations:
CGRect statusBarFrame = [self.window convertRect:[UIApplication sharedApplication].statusBarFrame toView:view];
You can then read statusBarFrame's height property directly. 'View' in this instance should be the view in which you wish to make use of the measurements, most likely the application window's root view controller.
Incidentally, not only may the status bar be taller during phone calls, it can also be zero if the status bar has been deliberately hidden.
The Dir function is the way to go, but the problem is that you cannot use the Dir
function recursively, as stated here, towards the bottom.
The way that I've handled this is to use the Dir
function to get all of the sub-folders for the target folder and load them into an array, then pass the array into a function that recurses.
Here's a class that I wrote that accomplishes this, it includes the ability to search for filters. (You'll have to forgive the Hungarian Notation, this was written when it was all the rage.)
Private m_asFilters() As String
Private m_asFiles As Variant
Private m_lNext As Long
Private m_lMax As Long
Public Function GetFileList(ByVal ParentDir As String, Optional ByVal sSearch As String, Optional ByVal Deep As Boolean = True) As Variant
m_lNext = 0
m_lMax = 0
ReDim m_asFiles(0)
If Len(sSearch) Then
m_asFilters() = Split(sSearch, "|")
Else
ReDim m_asFilters(0)
End If
If Deep Then
Call RecursiveAddFiles(ParentDir)
Else
Call AddFiles(ParentDir)
End If
If m_lNext Then
ReDim Preserve m_asFiles(m_lNext - 1)
GetFileList = m_asFiles
End If
End Function
Private Sub RecursiveAddFiles(ByVal ParentDir As String)
Dim asDirs() As String
Dim l As Long
On Error GoTo ErrRecursiveAddFiles
'Add the files in 'this' directory!
Call AddFiles(ParentDir)
ReDim asDirs(-1 To -1)
asDirs = GetDirList(ParentDir)
For l = 0 To UBound(asDirs)
Call RecursiveAddFiles(asDirs(l))
Next l
On Error GoTo 0
Exit Sub
ErrRecursiveAddFiles:
End Sub
Private Function GetDirList(ByVal ParentDir As String) As String()
Dim sDir As String
Dim asRet() As String
Dim l As Long
Dim lMax As Long
If Right(ParentDir, 1) <> "\" Then
ParentDir = ParentDir & "\"
End If
sDir = Dir(ParentDir, vbDirectory Or vbHidden Or vbSystem)
Do While Len(sDir)
If GetAttr(ParentDir & sDir) And vbDirectory Then
If Not (sDir = "." Or sDir = "..") Then
If l >= lMax Then
lMax = lMax + 10
ReDim Preserve asRet(lMax)
End If
asRet(l) = ParentDir & sDir
l = l + 1
End If
End If
sDir = Dir
Loop
If l Then
ReDim Preserve asRet(l - 1)
GetDirList = asRet()
End If
End Function
Private Sub AddFiles(ByVal ParentDir As String)
Dim sFile As String
Dim l As Long
If Right(ParentDir, 1) <> "\" Then
ParentDir = ParentDir & "\"
End If
For l = 0 To UBound(m_asFilters)
sFile = Dir(ParentDir & "\" & m_asFilters(l), vbArchive Or vbHidden Or vbNormal Or vbReadOnly Or vbSystem)
Do While Len(sFile)
If Not (sFile = "." Or sFile = "..") Then
If m_lNext >= m_lMax Then
m_lMax = m_lMax + 100
ReDim Preserve m_asFiles(m_lMax)
End If
m_asFiles(m_lNext) = ParentDir & sFile
m_lNext = m_lNext + 1
End If
sFile = Dir
Loop
Next l
End Sub
To truncate a string provided by the maximum limit without breaking a word use this:
/**
* truncate a string provided by the maximum limit without breaking a word
* @param string $str
* @param integer $maxlen
* @return string
*/
public static function truncateStringWords($str, $maxlen): string
{
if (strlen($str) <= $maxlen) return $str;
$newstr = substr($str, 0, $maxlen);
if (substr($newstr, -1, 1) != ' ') $newstr = substr($newstr, 0, strrpos($newstr, " "));
return $newstr;
}
Try this:
DECLARE @Hobbies NVARCHAR(200) = ' '
SELECT @Hobbies = @Hobbies + hobbies + ',' FROM peoples_hobbies WHERE person_id = 5;
TL;DR;
set @sql='';
set @result='';
set @separator=' union \r\n';
SELECT
@sql:=concat('select ''',INFORMATION_SCHEMA.COLUMNS.COLUMN_NAME ,''' as col_name,',
INFORMATION_SCHEMA.COLUMNS.CHARACTER_MAXIMUM_LENGTH ,' as def_len ,' ,
'MAX(CHAR_LENGTH(',INFORMATION_SCHEMA.COLUMNS.COLUMN_NAME , '))as max_char_len',
' FROM ',
INFORMATION_SCHEMA.COLUMNS.TABLE_NAME
) as sql_piece, if(@result:=if(@result='',@sql,concat(@result,@separator,@sql)),'','') as dummy
FROM INFORMATION_SCHEMA.COLUMNS
WHERE
INFORMATION_SCHEMA.COLUMNS.DATA_TYPE like '%char%'
and INFORMATION_SCHEMA.COLUMNS.TABLE_SCHEMA='xxx'
and INFORMATION_SCHEMA.COLUMNS.TABLE_NAME='yyy';
select @result;
Slightly off topic but having arrived here while developing an Angular2 app I would like to share that Angular2 automatically adds the class "router-link-active" to active router links such as this one:
<li><a [routerLink]="['Dashboard']">Dashboard</a></li>
You can therefore easily style such links using CSS:
.router-link-active {
color: red;
}
The Node Knockout competition wrapped up recently, and many of the submissions are available on github. The competition site doesn't appear to be working right now, but I'm sure you could Google up a few entries to check out.
git checkout -b NEW_BRANCH_NAME COMMIT_ID
This will create a new branch called 'NEW_BRANCH_NAME' and check it out.
("check out" means "to switch to the branch")
git branch NEW_BRANCH_NAME COMMIT_ID
This just creates the new branch without checking it out.
in the comments many people seem to prefer doing this in two steps. here's how to do so in two steps:
git checkout COMMIT_ID
# you are now in the "detached head" state
git checkout -b NEW_BRANCH_NAME
If you're using React Native, you can use the array notation:
<View style={[styles.base, styles.background]} />
Check out my detailed blog post about this.
Try switching to Logback and use
ch.qos.logback.classic.Logger rootLogger = (ch.qos.logback.classic.Logger)LoggerFactory.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);
rootLogger.setLevel(Level.toLevel("info"));
I believe this will be the only call to Logback and the rest of your code will remain unchanged. Logback uses SLF4J and the migration will be painless, just the xml config files will have to be changed.
Remember to set the log level back after you're done.
At last :)
Here my story :
Add this code to your main activity, after you set layout.
try {
PackageInfo info = getPackageManager().getPackageInfo("PROJECTNAME", PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
String sign=Base64.encodeToString(md.digest(), Base64.DEFAULT);
Log.e("MY KEY HASH:", sign);
//textInstructionsOrLink = (TextView)findViewById(R.id.textstring);
//textInstructionsOrLink.setText(sign);
Toast.makeText(getApplicationContext(),sign, Toast.LENGTH_LONG).show();
}
} catch (NameNotFoundException e) {
Log.d("nope","nope");
} catch (NoSuchAlgorithmException e) {
}
Change PROJECTNAME to your package name!
I had the same issue on a remote windows environment. I tried many solutions found here or on other similars posts but nothing worked. Finally, the solution was quite simple. I had to set NO_PROXY
with cmd :
set NO_PROXY="<domain>\<username>:<password>@<host>:<port>"
pip install <packagename>
You have to use double quotes and set NO_PROXY
to upper case. You can also add NO_PROXY
as an environment variable instead of setting it each time you use the console.
I hope this will help if any other solution posted here works.
$(".excel").click(function () {
var t = $(this).closest(".tblGrid").attr("id");
window.frames["Iframe" + t].document.location.href = pagename + "?tbl=" + t;
});
this is what i use, no jquery needed for this. in this particular scenario for each table i have with an excel export icon this forces the iframe attached to that table to load the same page with a variable in the Query String that the page looks for, and if found response writes out a stream with an excel mimetype and includes the data for that table.
No. You have to make your own like this:
boolean tryParseInt(String value) {
try {
Integer.parseInt(value);
return true;
} catch (NumberFormatException e) {
return false;
}
}
...and you can use it like this:
if (tryParseInt(input)) {
Integer.parseInt(input); // We now know that it's safe to parse
}
EDIT (Based on the comment by @Erk)
Something like follows should be better
public int tryParse(String value, int defaultVal) {
try {
return Integer.parseInt(value);
} catch (NumberFormatException e) {
return defaultVal;
}
}
When you overload this with a single string parameter method, it would be even better, which will enable using with the default value being optional.
public int tryParse(String value) {
return tryParse(value, 0)
}
my issue with ANR , after much work i found out that a thread was calling a resource that did not exist in the layout, instead of returning an exception , i got ANR ...
You can create an xml bitmap and use it as background for the view. To prevent stretching you can specify android:gravity
attribute.
for example:
<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
android:src="@drawable/dvdr"
android:tileMode="disabled" android:gravity="top" >
</bitmap>
There are a lot of options you can use to customize the rendering of the image
http://developer.android.com/guide/topics/resources/drawable-resource.html#Bitmap
Try this way:
console.log(moment().format('L'));
moment().format('L'); // 05/25/2018
moment().format('l'); // 5/25/2018
Format Dates:
moment().format('MMMM Do YYYY, h:mm:ss a'); // May 25th 2018, 2:02:13 pm
moment().format('dddd'); // Friday
moment().format("MMM Do YY"); // May 25th 18
moment().format('YYYY [escaped] YYYY'); // 2018 escaped 2018
moment().format(); // 2018-05-25T14:02:13-05:00
Visit: https://momentjs.com/ for more info.
You can declare the field as a first-class attribute of your form and just set choices dynamically:
class WaypointForm(forms.Form):
waypoints = forms.ChoiceField(choices=[])
def __init__(self, user, *args, **kwargs):
super().__init__(*args, **kwargs)
waypoint_choices = [(o.id, str(o)) for o in Waypoint.objects.filter(user=user)]
self.fields['waypoints'].choices = waypoint_choices
You can also use a ModelChoiceField and set the queryset on init in a similar manner.
Here is a jQuery solution. I always let the default value reappear when a user clears the input field.
<input name="Email" value="What's your programming question ? be specific." type="text" id="Email" value="[email protected]" />
<script>
$("#Email").blur(
function (){
if ($(this).val() == "")
$(this).val($(this).prop("defaultValue"));
}
).focus(
function (){
if ($(this).val() == $(this).prop("defaultValue"))
$(this).val("");
}
);
</script>
Debug.writeline(Format(Now, "dd MMMM yyyy"))
If you're using SQL Server, after your query you can select the @@RowCount function (or if your result set might have more than 2 billion rows use the RowCount_Big() function). This will return the number of rows selected by the previous statement or number of rows affected by an insert/update/delete statement.
SELECT my_table.my_col
FROM my_table
WHERE my_table.foo = 'bar'
SELECT @@Rowcount
Or if you want to row count included in the result sent similar to Approach #2, you can use the the OVER clause.
SELECT my_table.my_col,
count(*) OVER(PARTITION BY my_table.foo) AS 'Count'
FROM my_table
WHERE my_table.foo = 'bar'
Using the OVER clause will have much better performance than using a subquery to get the row count. Using the @@RowCount will have the best performance because the there won't be any query cost for the select @@RowCount statement
Update in response to comment: The example I gave would give the # of rows in partition - defined in this case by "PARTITION BY my_table.foo". The value of the column in each row is the # of rows with the same value of my_table.foo. Since your example query had the clause "WHERE my_table.foo = 'bar'", all rows in the resultset will have the same value of my_table.foo and therefore the value in the column will be the same for all rows and equal (in this case) this the # of rows in the query.
Here is a better/simpler example of how to include a column in each row that is the total # of rows in the resultset. Simply remove the optional Partition By clause.
SELECT my_table.my_col, count(*) OVER() AS 'Count'
FROM my_table
WHERE my_table.foo = 'bar'
The Chrome Browser versión should matches with the chromeDriver versión. Go to : chrome://settings/help
How do I confirm I'm using the right chromedriver?
I used this kind of validation .... checks the pasted text and if it contains alphabets, shows an error for user and then clear out the box after delay for the user to check the text and make appropriate changes.
$('#txtbox').on('paste', function (e) {
var $this = $(this);
setTimeout(function (e) {
if (($this.val()).match(/[^0-9]/g))
{
$("#errormsg").html("Only Numerical Characters allowed").show().delay(2500).fadeOut("slow");
setTimeout(function (e) {
$this.val(null);
},2500);
}
}, 5);
});
For Windows 7 and above go to C:\Users\USERNAME\.android folder and follow below steps:
repositories.cfg
void EraseVectorRepeats(vector <int> & v){
TOP:for(int y=0; y<v.size();++y){
for(int z=0; z<v.size();++z){
if(y==z){ //This if statement makes sure the number that it is on is not erased-just skipped-in order to keep only one copy of a repeated number
continue;}
if(v[y]==v[z]){
v.erase(v.begin()+z); //whenever a number is erased the function goes back to start of the first loop because the size of the vector changes
goto TOP;}}}}
This is a function that I created that you can use to delete repeats. The header files needed are just <iostream>
and <vector>
.
As just formulated by grepsedawk, the answer lies in the -l
option of g++
, calling ld
. If you look at the man page of this command, you can either do:
g++ -l:libmagic.so.1 [...]
g++ -lmagic [...]
, if you have a symlink named libmagic.so in your libs pathnext
- it's like return
, but for blocks! (So you can use this in any proc
/lambda
too.)
That means you can also say next n
to "return" n
from the block. For instance:
puts [1, 2, 3].map do |e|
next 42 if e == 2
e
end.inject(&:+)
This will yield 46
.
Note that return
always returns from the closest def
, and never a block; if there's no surrounding def
, return
ing is an error.
Using return
from within a block intentionally can be confusing. For instance:
def my_fun
[1, 2, 3].map do |e|
return "Hello." if e == 2
e
end
end
my_fun
will result in "Hello."
, not [1, "Hello.", 2]
, because the return
keyword pertains to the outer def
, not the inner block.
The problem, in my case, was that some install at some point defined an environment variable http_proxy on my machine when I had no proxy.
Removing the http_proxy environment variable fixed the problem.
toggleAttr()
is provided by this very nice and tiny plugin.
$('#my_radio').click(function() {
$(this).toggleAttr('checked');
});
/**
* toggleAttr Plugin
*/
jQuery.fn.toggleAttr = function(attr) {
return this.each(function() {
var $this = $(this);
$this.attr(attr) ? $this.removeAttr(attr) : $this.attr(attr, attr);
});
};
You can use place your radio button inside label or button tags and do some nice things.
You need to make some changes in the compiler. In Dev C++ Compiler: 1. Go to compiler settings/compiler Options. 2. Click on General Tab 3. Check the checkbox (Add the following commands when calling the compiler. 4. write -std=c++11 5. click Ok
Use a delegated event handler bound to the container:
$('#pg_menu_content').on('click', '#btn_a', function(){
console.log(this.value);
});
That is, bind to an element that exists at the moment that the JS runs (I'm assuming #pg_menu_content
exists when the page loads), and supply a selector in the second parameter to .on()
. When a click occurs on #pg_menu_content
element jQuery checks whether it applied to a child of that element which matches the #btn_a
selector.
Either that or bind a standard (non-delegated) click handler after creating the button.
Either way, within the click handler this
will refer to the button in question, so this.value
will give you its value.
If you want to check if an object is within in array by checking an attribute on the object, you can use any?
and pass a block that evaluates to true or false:
unless @suggested_horses.any? {|h| h.id == horse.id }
@suggested_horses << horse
end
For DataTables <=1.9, @perpo's answer
$('#example').dataTable({
"bLengthChange": false
});
works fine, but for 1.10+ try this:
$('#example').dataTable({
"dom": 'ftipr'
});
where we have left out l
the "length changing input control"
(First, I'd like to recommend this useful reference site for batch: http://ss64.com/nt/)
Then just another useful explanation: http://htipe.wordpress.com/2008/10/09/the-dp0-variable/
The %~dp0 Variable
The
%~dp0
(that’s a zero) variable when referenced within a Windows batch file will expand to the drive letter and path of that batch file.The variables
%0-%9
refer to the command line parameters of the batch file.%1-%9
refer to command line arguments after the batch file name.%0
refers to the batch file itself.If you follow the percent character (
%
) with a tilde character (~
), you can insert a modifier(s) before the parameter number to alter the way the variable is expanded. Thed
modifier expands to the drive letter and thep
modifier expands to the path of the parameter.Example: Let’s say you have a directory on
C:
calledbat_files
, and in that directory is a file calledexample.bat
. In this case,%~dp0
(combining thed
andp
modifiers) will expand toC:\bat_files\
.Check out this Microsoft article for a full explanation.
Also, check out this forum thread.
And a more clear reference from here:
%CmdCmdLine%
will return the entire command line as passed to CMD.EXE
%*
will return the remainder of the command line starting at the first command line argument (in Windows NT 4, %* also includes all leading spaces)
%~dn
will return the drive letter of %n (n can range from 0 to 9) if %n is a valid path or file name (no UNC)
%~pn
will return the directory of %n if %n is a valid path or file name (no UNC)
%~nn
will return the file name only of %n if %n is a valid file name
%~xn
will return the file extension only of %n if %n is a valid file name
%~fn
will return the fully qualified path of %n if %n is a valid file name or directory
Just found some good reference for the mysterious ~
tilde operator.
The %~
string is called percent tilde operator. You can find it in situations like: %~0
.
The :~
string is called colon tilde operator. You can find it like %SOME_VAR:~0,-1%
.
%1-%9
refer to the command line args. If they are not valid path values, %~dp1
- %~dp9
will all expand to the same value as %~dp0
. But if they are valid path values, they will expand to their own driver/path value.
For example: (batch.bat)
@echo off
@echo ~dp0= %~dp0
@echo ~dp1= %~dp1
@echo ~dp2= %~dp2
@echo on
Run 1:
D:\Workbench>batch arg1 arg2
~dp0= D:\Workbench\
~dp1= D:\Workbench\
~dp2= D:\Workbench\
Run 2:
D:\Workbench>batch c:\123\a.exe e:\abc\b.exe
~dp0= D:\Workbench\
~dp1= c:\123\
~dp2= e:\abc\
or //div[@id='id-74385'][@class='guest clearfix']
you can store it as text that looks like a list and create a function that can return its data as an actual list. example:
database:
_____________________
| word | letters |
| me | '[m, e]' |
| you |'[y, o, u]' | note that the letters column is of type 'TEXT'
| for |'[f, o, r]' |
|___in___|_'[i, n]'___|
And the list compiler function (written in python, but it should be easily translatable to most other programming languages). TEXT represents the text loaded from the sql table. returns list of strings from string containing list. if you want it to return ints instead of strings, make mode equal to 'int'. Likewise with 'string', 'bool', or 'float'.
def string_to_list(string, mode):
items = []
item = ""
itemExpected = True
for char in string[1:]:
if itemExpected and char not in [']', ',', '[']:
item += char
elif char in [',', '[', ']']:
itemExpected = True
items.append(item)
item = ""
newItems = []
if mode == "int":
for i in items:
newItems.append(int(i))
elif mode == "float":
for i in items:
newItems.append(float(i))
elif mode == "boolean":
for i in items:
if i in ["true", "True"]:
newItems.append(True)
elif i in ["false", "False"]:
newItems.append(False)
else:
newItems.append(None)
elif mode == "string":
return items
else:
raise Exception("the 'mode'/second parameter of string_to_list() must be one of: 'int', 'string', 'bool', or 'float'")
return newItems
Also here is a list-to-string function in case you need it.
def list_to_string(lst):
string = "["
for i in lst:
string += str(i) + ","
if string[-1] == ',':
string = string[:-1] + "]"
else:
string += "]"
return string
Another Simple way i found in Netbeans right click on your project>libraris click add jar/folder add your comm.jar and you done.
if you dont have comm.jar download it from >>> http://llk.media.mit.edu/projects/picdev/software/javaxcomm.zip
The answers in question you linked-to are all about configuring git so that you can enter very short git push
commands and have them do whatever you want. Which is great, if you know what you want and how to spell that in Git-Ese, but you're new to git! :-)
In your case, Petr Mensik's answer is the (well, "a") right one. Here's why:
The command git push remote
roots around in your .git/config
file to find the named "remote" (e.g., origin
). The config file lists:
ssh://hostname/path
)git fetch remote
When you first cloned the repo—whenever that was—git set up default values for some of these. The URL is whatever you cloned from and the rest, if set or unset, are all "reasonable" defaults ... or, hmm, are they?
The issue with these is that people have changed their minds, over time, as to what is "reasonable". So now (depending on your version of git and whether you've configured things in detail), git may print a lot of warnings about defaults changing in the future. Adding the name of the "branch to push"—amd_qlp_tester
—(1) shuts it up, and (2) pushes just that one branch.
If you want to push more conveniently, you could do that with:
git push origin
or even:
git push
but whether that does what you want, depends on whether you agree with "early git authors" that the original defaults are reasonable, or "later git authors" that the original defaults aren't reasonable. So, when you want to do all the configuration stuff (eventually), see the question (and answers) you linked-to.
As for the name origin/amd_qlp_tester
in the first place: that's actually a local entity (a name kept inside your repo), even though it's called a "remote branch". It's git's best guess at "where amd_qlp_tester
is over there". Git updates it when it can.
Using generics:
static bool IsNullOrDefault<T>(T value)
{
return object.Equals(value, default(T));
}
//...
double d = 0;
IsNullOrDefault(d); // true
MyClass c = null;
IsNullOrDefault(c); // true
If T
it's a reference type, value
will be compared with null
( default(T)
), otherwise, if T
is a value type
, let's say double, default(t)
is 0d, for bool is false
, for char is '\0'
and so on...
You could use code like this:
public double getRandomNumber(double minimum, double maximum) {
return minimum + randomizer.nextDouble() * (maximum - minimum);
}
git --no-pager log --pretty=tformat:"%C(yellow)%h %C(cyan)%ad %Cblue%an%C(auto)%d %Creset%s" --graph --date=format:"%Y-%m-%d %H:%M" -25
I use alias
alias gitlog='git --no-pager log --pretty=tformat:"%C(yellow)%h %C(cyan)%ad %Cblue%an%C(auto)%d %Creset%s" --graph --date=format:"%Y-%m-%d %H:%M" -25'
Differences: I use tformat and isodate without seconds and time zones , with --no-pager you will see colors
You have to execute your query and add single quote to $email in the query beacuse it's a string, and remove the is_resource($query)
$query is a string, the $result will be the resource
$query = "SELECT `email` FROM `tblUser` WHERE `email` = '$email'";
$result = mysqli_query($link,$query); //$link is the connection
if(mysqli_num_rows($result) > 0 ){....}
UPDATE
Base in your edit just change:
if(is_resource($query) && mysqli_num_rows($query) > 0 ){
$query = mysqli_fetch_assoc($query);
echo $email . " email exists " . $query["email"] . "\n";
By
if(is_resource($result) && mysqli_num_rows($result) == 1 ){
$row = mysqli_fetch_assoc($result);
echo $email . " email exists " . $row["email"] . "\n";
and you will be fine
UPDATE 2
A better way should be have a Store Procedure that execute the following SQL passing the Email as Parameter
SELECT IF( EXISTS (
SELECT *
FROM `Table`
WHERE `email` = @Email)
, 1, 0) as `Exist`
and retrieve the value in php
Pseudocodigo:
$query = Call MYSQL_SP($EMAIL);
$result = mysqli_query($conn,$query);
$row = mysqli_fetch_array($result)
$exist = ($row['Exist']==1)? 'the email exist' : 'the email doesnt exist';
All you need to do is make sure that the checkbox shown below is checked.
I recommend using .htaccess
. You only need to add:
DirectoryIndex home.php
or whatever page name you want to have for it.
EDIT: basic htaccess tutorial.
1) Create .htaccess
file in the directory where you want to change the index file.
.
in front, to ensure it is a "hidden" fileEnter the line above in there. There will likely be many, many other things you will add to this (AddTypes for webfonts / media files, caching for headers, gzip declaration for compression, etc.), but that one line declares your new "home" page.
2) Set server to allow reading of .htaccess
files (may only be needed on your localhost, if your hosting servce defaults to allow it as most do)
Assuming you have access, go to your server's enabled site location. I run a Debian server for development, and the default site setup is at /etc/apache2/sites-available/default
for Debian / Ubuntu. Not sure what server you run, but just search for "sites-available" and go into the "default" document. In there you will see an entry for Directory. Modify it to look like this:
<Directory /var/www/>
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
</Directory>
Then restart your apache server. Again, not sure about your server, but the command on Debian / Ubuntu is:
sudo service apache2 restart
Technically you only need to reload, but I restart just because I feel safer with a full refresh like that.
Once that is done, your site should be reading from your .htaccess file, and you should have a new default home page! A side note, if you have a sub-directory that runs a site (like an admin section or something) and you want to have a different "home page" for that directory, you can just plop another .htaccess
file in that sub-site's root and it will overwrite the declaration in the parent.
click: WAMP icon->Apache->Apache modules->chose rewrite_module
and do restart for all services.
Use different format or pattern to get the information from the date
var myDate = new Date("2015-06-17 14:24:36");_x000D_
console.log(moment(myDate).format("YYYY-MM-DD HH:mm:ss"));_x000D_
console.log("Date: "+moment(myDate).format("YYYY-MM-DD"));_x000D_
console.log("Year: "+moment(myDate).format("YYYY"));_x000D_
console.log("Month: "+moment(myDate).format("MM"));_x000D_
console.log("Month: "+moment(myDate).format("MMMM"));_x000D_
console.log("Day: "+moment(myDate).format("DD"));_x000D_
console.log("Day: "+moment(myDate).format("dddd"));_x000D_
console.log("Time: "+moment(myDate).format("HH:mm")); // Time in24 hour format_x000D_
console.log("Time: "+moment(myDate).format("hh:mm A"));
_x000D_
<script src="https://momentjs.com/downloads/moment.js"></script>
_x000D_
For more info: https://momentjs.com/docs/#/parsing/string-format/
The solutions above using structuring do suffer from the fact that you have an used variable, which might cause complaints from ESLint if you're using that.
So here are my solutions:
const src = { a: 1, b: 2 }
const result = Object.keys(src)
.reduce((acc, k) => k === 'b' ? acc : { ...acc, [k]: src[k] }, {})
On most platforms (except IE unless using Babel), you could also do:
const src = { a: 1, b: 2 }
const result = Object.fromEntries(
Object.entries(src).filter(k => k !== 'b'))
uniq -u < file
will do the job.
You have a version conflict, please verify whether compiled version and JVM of Tomcat version are same. you can do it by examining tomcat startup .bat , looking for JAVA_HOME
Updated 2018
Do you want to close the modal after submit? Whether the form in inside the modal or external to it you should be able to use jQuery ajax to submit the form.
Here is an example with the form inside the modal:
<a href="#myModal" role="button" class="btn" data-toggle="modal">Launch demo modal</a>
<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel">Modal header</h3>
</div>
<div class="modal-body">
<form id="myForm" method="post">
<input type="hidden" value="hello" id="myField">
<button id="myFormSubmit" type="submit">Submit</button>
</form>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<button class="btn btn-primary">Save changes</button>
</div>
</div>
And the jQuery ajax to get the form fields and submit it..
$('#myFormSubmit').click(function(e){
e.preventDefault();
alert($('#myField').val());
/*
$.post('http://path/to/post',
$('#myForm').serialize(),
function(data, status, xhr){
// do something here with response;
});
*/
});
There actually is a way to do this that is allowed by C#. This gets back to C++, and rather violates the nice Object-Oriented structure of C#.
USE THIS METHOD WITH CAUTION!
Here's the way you declare and write your function with an optional parameter:
unsafe public void OptionalOutParameter(int* pOutParam = null)
{
int lInteger = 5;
// If the parameter is NULL, the caller doesn't care about this value.
if (pOutParam != null)
{
// If it isn't null, the caller has provided the address of an integer.
*pOutParam = lInteger; // Dereference the pointer and assign the return value.
}
}
Then call the function like this:
unsafe { OptionalOutParameter(); } // does nothing
int MyInteger = 0;
unsafe { OptionalOutParameter(&MyInteger); } // pass in the address of MyInteger.
In order to get this to compile, you will need to enable unsafe code in the project options. This is a really hacky solution that usually shouldn't be used, but if you for some strange, arcane, mysterious, management-inspired decision, REALLY need an optional out parameter in C#, then this will allow you to do just that.
The element.class selector is for styling situations such as this:
<span class="large"> </span>
<p class="large"> </p>
.large {
font-size:150%; font-weight:bold;
}
p.large {
color:blue;
}
Both your span and p will be assigned the font-size and font-weight from .large, but the color blue will only be assigned to p.
As others have pointed out, what you're working with is descendant selectors.
The existing answers are good but don't cover what to do when a smart pointer is not the (complete) answer to the problem you are trying to solve.
Among other things (explained well in other answers) using a smart pointer is a possible solution to How do we use a abstract class as a function return type? which has been marked as a duplicate of this question. However, the first question to ask if tempted to specify an abstract (or in fact, any) base class as a return type in C++ is "what do you really mean?". There is a good discussion (with further references) of idiomatic object oriented programming in C++ (and how this is different to other languages) in the documentation of the boost pointer container library. In summary, in C++ you have to think about ownership. Which smart pointers help you with, but are not the only solution, or always a complete solution (they don't give you polymorphic copy) and are not always a solution you want to expose in your interface (and a function return sounds an awful lot like an interface). It might be sufficient to return a reference, for example. But in all of these cases (smart pointer, pointer container or simply returning a reference) you have changed the return from a value to some form of reference. If you really needed copy you may need to add more boilerplate "idiom" or move beyond idiomatic (or otherwise) OOP in C++ to more generic polymorphism using libraries like Adobe Poly or Boost.TypeErasure.
If you want separate values for sides and top-bottom.
<table style="border-spacing: 5px 10px;">
To read the user input and store it in a variable, for later use, you can use SQL*Plus command ACCEPT
.
Accept <your variable> <variable type if needed [number|char|date]> prompt 'message'
example
accept x number prompt 'Please enter something: '
And then you can use the x
variable in a PL/SQL block as follows:
declare
a number;
begin
a := &x;
end;
/
Working with a string example:
accept x char prompt 'Please enter something: '
declare
a varchar2(10);
begin
a := '&x'; -- for a substitution variable of char data type
end; -- to be treated as a character string it needs
/ -- to be enclosed with single quotation marks
In my case,
image = cv2.imread(filepath)
final_img = cv2.resize(image, size_img)
filepath was incorrect, cv2.imshow didn't give any error in this case but due to wrong path cv2.resize was giving me error.
Springboot 1.3.8
import java.util.concurrent.TimeUnit;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.guava.GuavaCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.google.common.cache.CacheBuilder;
@Configuration
@EnableCaching
public class CacheConfig extends CachingConfigurerSupport {
@Override
@Bean
public CacheManager cacheManager() {
GuavaCacheManager cacheManager = new GuavaCacheManager();
return cacheManager;
}
@Bean
public CacheManager timeoutCacheManager() {
GuavaCacheManager cacheManager = new GuavaCacheManager();
CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder()
.maximumSize(100)
.expireAfterWrite(5, TimeUnit.SECONDS);
cacheManager.setCacheBuilder(cacheBuilder);
return cacheManager;
}
}
and
@Cacheable(value="A", cacheManager="timeoutCacheManager")
public Object getA(){
...
}
You only have tried comma-separated and semicolon-separated CSV. If you had tried tab-separated CSV (also called TSV) you would have found the answer:
UTF-16LE with BOM (byte order mark), tab-separated
But: In a comment you mention that TSV is not an option for you (I haven't been able to find this requirement in your question though). That's a pity. It often means that you allow manual editing of TSV files, which probably is not a good idea. Visual checking of TSV files is not a problem. Furthermore editors can be set to display a special character to mark tabs.
And yes, I tried this out on Windows and Mac.
This can be achieved with greater cross-browser support than the accepted answer by using pseudo-elements as exemplified by this answer: https://stackoverflow.com/a/19818268/2602816
Clearing the Google Play cache memory will also help you... Go to the app information page of Google Play and clear it.
Here's what I did in case someone finds it useful (I used a lot of things according to the rest of the answers in this thread):
First I adjusted the layout settings as needed. This changes the window size immediately so it was easier to set the exact size that I wanted. By the way I didn't know that I can also have visible width smaller than width buffer. This was nice since I usually hate a long line to be wrapped.
Then after clicking ok, I opened regedit.exe and went to "HKEY_CURRENT_USER\Console". There is a new child entry there "%SystemRoot%_system32_cmd.exe". I right clicked on that and selected Export:
I saved this as "cmd_settings.reg". Then I created a batch script that imports those settings, invokes my original batch script (name batch_script.bat) and then deletes what I imported in order for the command line window to return to default settings:
regedit /s cmd_settings.reg
start /wait batch_script.bat
reg delete "HKEY_CURRENT_USER\Console\%%SystemRoot%%_system32_cmd.exe" /f
This is a sample batch that could be invoked ("batch_script.bat"):
@echo off
echo test!
pause
exit
Don't forget the exit command at the end of your script if you want the reg delete line to run after the script execution.
This error happened because the image didn't load properly . So you have problem with the previous line cv2.imread
my suggestion is :
check if the images exist in the path you give
check the count variable if he have valid number
Those are some good out-of-the box solutions given above, but we can also try some plugins which provide multiple cursors like Sublime.
I think this one looks promising:
It seemed abandoned for a while, but has had some contributions in 2014.
It is quite powerful, although it took me a little while to get used to the flow (which is quite Sublime-like but still modal like Vim).
In my experience if you have a lot of other plugins installed, you may meet some conflicts!
There are some others attempts at this feature:
Please feel free to edit if you notice any of these undergoing improvement.
In Angular Http 7, the DELETE method accepts as a second parameter options
object in which you provide the request parameters as params
object along with the headers
object. This is different than Angular6.
See example:
this.httpClient.delete('https://api-url', {
headers: {},
params: {
'param1': paramValue1,
'param2': paramValue2
}
});
I wanted a simple one liner to make the path unique to bust the cache. This worked for me:
<script src="scripts/main.js?bust_js_cache=<%=System.IO.File.GetLastWriteTime(Server.MapPath("scripts/main.js")).ToString("HH:mm:ss")%>" type="text/javascript"></script>
If the file has been modified since the last time it was loaded on the page the browser will pull the updated file.
It generates the last modified
stamp from the .js
file and chucks it in there instead of the version which may not be easy to gain access to.
<script src="scripts/main.js?bust_js_cache=10:18:38" type="text/javascript"></script>
Another option could be to get the checksum of the file.
You'd better consider using Message Queues instead of advised methods. I'm sure this will be better solution, although it requires a little more job than just sending a request.
I had a similar issue and could not "compromise" with background images. I came up with this.
<div class="container">
<img src="http://lorempixel.com/800x600/nature">
</div>
.container {
position: relative;
width: 25%; /* whatever width you want. I was implementing this in a 4 tile grid pattern. I used javascript to set height equal to width */
border: 2px solid #fff; /* just to separate the images */
overflow: hidden; /* "crop" the image */
background: #000; /* incase the image is wider than tall/taller than wide */
}
.container img {
position: absolute;
display: block;
height: 100%; /* all images at least fill the height */
top: 50%; /* top, left, transform trick to vertically and horizontally center image */
left: 50%;
transform: translate3d(-50%,-50%,0);
}
//assuming you're using jQuery
var h = $('.container').outerWidth();
$('.container').css({height: h + 'px'});
Hope this helps!
Example: https://jsfiddle.net/cfbuwxmr/1/
In asp.net Core / MVC 6 rc2 you can set the HttpContext
var SomeController controller = new SomeController();
controller.ControllerContext = new ControllerContext();
controller.ControllerContext.HttpContext = new DefaultHttpContext();
controller.HttpContext.Session = new DummySession();
rc 1 was
var SomeController controller = new SomeController();
controller.ActionContext = new ActionContext();
controller.ActionContext.HttpContext = new DefaultHttpContext();
controller.HttpContext.Session = new DummySession();
https://stackoverflow.com/a/34022964/516748
Consider using Moq
new Mock<ISession>();
simple way to do this... here are the example
cd program files
cd poweriso
piso mount D:\<Filename.iso> <Virtual Drive>
Pause
this will mount the ISO image to the specific drive...use
In java you can use setFetchSource like this :
client.prepareSearch(index).setTypes(type)
.setFetchSource(new String[] { "field1", "field2" }, null)
You could also use something like this, by checking the OSVersion.Version.Major:
IF ([System.Environment]::OSVersion.Version.Major -ge 10) {Write-Host "Windows 10 or above"}
IF ([System.Environment]::OSVersion.Version.Major -lt 10) {Write-Host "Windows 8.1 or below"}
The FAQ session on tensor flow has an answer to exactly the same question. I will just go ahead and leave it here:
If t
is a Tensor
object, t.eval()
is shorthand for sess.run(t)
(where sess
is the current default session. The two following snippets of code are equivalent:
sess = tf.Session()
c = tf.constant(5.0)
print sess.run(c)
c = tf.constant(5.0)
with tf.Session():
print c.eval()
In the second example, the session acts as a context manager, which has the effect of installing it as the default session for the lifetime of the with
block. The context manager approach can lead to more concise code for simple use cases (like unit tests); if your code deals with multiple graphs and sessions, it may be more straightforward to explicit calls to Session.run()
.
I'd recommend that you at least skim throughout the whole FAQ, as it might clarify a lot of things.
const str = "dGhpcyBpcyBiYXNlNjQgc3RyaW5n"
const encoded = new TextEncoder().encode(str) // is Uint8Array
const buf = encoded.buffer // is ArrayBuffer
you can't change the DateTime object, it's immutable. However, you can set it to a new value, for example:
var newDate = oldDate.Date + new TimeSpan(11, 30, 55);
Thank you guys for this thread! It helped me when I wanted to figure out an exe's file version. However, I needed to figure out the last bit myself of what is called Extended Properties.
If you open properties of an exe (or dll) file in Windows Explorer, you get a Version tab, and a view of Extended Properties of that file. I wanted to access one of those values.
The solution to this is the property indexer FolderItem.ExtendedProperty and if you drop all spaces in the property's name, you'll get the value. E.g. File Version goes FileVersion, and there you have it.
Hope this helps anyone else, just thought I'd add this info to this thread. Cheers!
This is another solution which I use:
public class CustomAnimator {
private static final String TAG = "com.example.CustomAnimator";
private static Stack<AnimationEntry> animation_stack = new Stack<>();
public static final int DIRECTION_LEFT = 1;
public static final int DIRECTION_RIGHT = -1;
public static final int DIRECTION_UP = 2;
public static final int DIRECTION_DOWN = -2;
static class AnimationEntry {
View in;
View out;
int direction;
long duration;
}
public static boolean hasHistory() {
return !animation_stack.empty();
}
public static void reversePrevious() {
if (!animation_stack.empty()) {
AnimationEntry entry = animation_stack.pop();
slide(entry.out, entry.in, -entry.direction, entry.duration, false);
}
}
public static void clearHistory() {
animation_stack.clear();
}
public static void slide(final View in, View out, final int direction, long duration) {
slide(in, out, direction, duration, true);
}
private static void slide(final View in, final View out, final int direction, final long duration, final boolean save) {
ViewGroup in_parent = (ViewGroup) in.getParent();
ViewGroup out_parent = (ViewGroup) out.getParent();
if (!in_parent.equals(out_parent)) {
return;
}
int parent_width = in_parent.getWidth();
int parent_height = in_parent.getHeight();
ObjectAnimator slide_out;
ObjectAnimator slide_in;
switch (direction) {
case DIRECTION_LEFT:
default:
slide_in = ObjectAnimator.ofFloat(in, "translationX", parent_width, 0);
slide_out = ObjectAnimator.ofFloat(out, "translationX", 0, -out.getWidth());
break;
case DIRECTION_RIGHT:
slide_in = ObjectAnimator.ofFloat(in, "translationX", -out.getWidth(), 0);
slide_out = ObjectAnimator.ofFloat(out, "translationX", 0, parent_width);
break;
case DIRECTION_UP:
slide_in = ObjectAnimator.ofFloat(in, "translationY", parent_height, 0);
slide_out = ObjectAnimator.ofFloat(out, "translationY", 0, -out.getHeight());
break;
case DIRECTION_DOWN:
slide_in = ObjectAnimator.ofFloat(in, "translationY", -out.getHeight(), 0);
slide_out = ObjectAnimator.ofFloat(out, "translationY", 0, parent_height);
break;
}
AnimatorSet animations = new AnimatorSet();
animations.setDuration(duration);
animations.playTogether(slide_in, slide_out);
animations.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationCancel(Animator arg0) {
}
@Override
public void onAnimationEnd(Animator arg0) {
out.setVisibility(View.INVISIBLE);
if (save) {
AnimationEntry ae = new AnimationEntry();
ae.in = in;
ae.out = out;
ae.direction = direction;
ae.duration = duration;
animation_stack.push(ae);
}
}
@Override
public void onAnimationRepeat(Animator arg0) {
}
@Override
public void onAnimationStart(Animator arg0) {
in.setVisibility(View.VISIBLE);
}
});
animations.start();
}
}
The usage of class. Let's say you have two fragments (list and details fragments)as shown below
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ui_container"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<FrameLayout
android:id="@+id/list_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<FrameLayout
android:id="@+id/details_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone" />
</FrameLayout>
Usage
View details_container = findViewById(R.id.details_container);
View list_container = findViewById(R.id.list_container);
// You can select the direction left/right/up/down and the duration
CustomAnimator.slide(list_container, details_container,CustomAnimator.DIRECTION_LEFT, 400);
You can use the function CustomAnimator.reversePrevious();
to get the previous view when the user pressed back.
SELECT DATABASE();
p.s. I didn't want to take the liberty of modifying @cwallenpoole's answer to reflect the fact that this is a MySQL question and not an Oracle question and doesn't need DUAL
.
C:\> wmic cpu get loadpercentage
LoadPercentage
0
Or
C:\> @for /f "skip=1" %p in ('wmic cpu get loadpercentage') do @echo %p%
4%
I implemented UIGestureRecognizerDelegate methods to detect both singleTap and doubleTap.
Just do this .
UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleDoubleTapGesture:)];
[doubleTap setDelegate:self];
doubleTap.numberOfTapsRequired = 2;
[self.headerView addGestureRecognizer:doubleTap];
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleSingleTapGesture:)];
singleTap.numberOfTapsRequired = 1;
[singleTap setDelegate:self];
[doubleTap setDelaysTouchesBegan:YES];
[singleTap setDelaysTouchesBegan:YES];
[singleTap requireGestureRecognizerToFail:doubleTap];
[self.headerView addGestureRecognizer:singleTap];
Then implement these delegate methods.
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
return YES;
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
return YES;
}
Unfortunately, it is not possible to "get" the height of an element via CSS because CSS is not a language that returns any sort of data other than rules for the browser to adjust its styling.
Your resolution can be achieved with jQuery, or alternatively, you can fake it with CSS3's transform:translateY();
rule.
If we assume that your target div in this instance is 200px high - this would mean that you want the div to have a margin of 190px?
This can be achieved by using the following CSS:
.dynamic-height {
-webkit-transform: translateY(100%); //if your div is 200px, this will move it down by 200px, if it is 100px it will down by 100px etc
transform: translateY(100%); //if your div is 200px, this will move it down by 200px, if it is 100px it will down by 100px etc
margin-top: -10px;
}
In this instance, it is important to remember that translateY(100%)
will move the element in question downwards by a total of it's own length.
The problem with this route is that it will not push element below it out of the way, where a margin would.
If faking it isn't going to work for you, then your next best bet would be to implement a jQuery script to add the correct CSS for you.
jQuery(document).ready(function($){ //wait for the document to load
$('.dynamic-height').each(function(){ //loop through each element with the .dynamic-height class
$(this).css({
'margin-top' : $(this).outerHeight() - 10 + 'px' //adjust the css rule for margin-top to equal the element height - 10px and add the measurement unit "px" for valid CSS
});
});
});
O.K. after spending more time on this with the help of this SO post
Overcoming "Display forbidden by X-Frame-Options"
I managed to solve the issue by adding &output=embed
to the end of the url before posting to the google URL:
var url = data.url + "&output=embed";
window.location.replace(url);
For some people which might still see this question, there is another way on how to append another array element(s) in C. You can refer to this blog which shows a C code on how to append another element in your array
.
But you can also use memcpy()
function, to append element(s) of another array. You can use memcpy()
like this:
#include <stdio.h>
#include <string.h>
int main(void)
{
int first_array[10] = {45, 2, 48, 3, 6};
int scnd_array[] = {8, 14, 69, 23, 5};
// 5 is the number of the elements which are going to be appended
memcpy(a + 5, b, 5 * sizeof(int));
// loop through and print all the array
for (i = 0; i < 10; i++) {
printf("%d\n", a[i]);
}
}
You have to mark the single letter as optional too:
([A-Z]{1})? +.*? +
or make the whole part optional
(([A-Z]{1}) +.*? +)?
CloseableHttpClient
is the base class of the httpclient library, the one all implementations use. Other subclasses are for the most part deprecated.
The HttpClient
is an interface for this class and other classes.
You should then use the CloseableHttpClient
in your code, and create it using the HttpClientBuilder
. If you need to wrap the client to add specific behaviour you should use request and response interceptors instead of wrapping with the HttpClient
.
This answer was given in the context of httpclient-4.3.
If you are using Sql Server 2008 or better, you can use something called a Table-Valued Parameter (TVP) instead of serializing & deserializing your list data every time you want to pass it to a stored procedure.
Let's start by creating a simple schema to serve as our playground:
CREATE DATABASE [TestbedDb]
GO
USE [TestbedDb]
GO
/* First, setup the sample program's account & credentials*/
CREATE LOGIN [testbedUser] WITH PASSWORD=N'µ×?
?S[°¿Q¥½q?_Ĭ¼Ð)3õļ%dv', DEFAULT_DATABASE=[master], DEFAULT_LANGUAGE=[us_english], CHECK_EXPIRATION=OFF, CHECK_POLICY=ON
GO
CREATE USER [testbedUser] FOR LOGIN [testbedUser] WITH DEFAULT_SCHEMA=[dbo]
GO
EXEC sp_addrolemember N'db_owner', N'testbedUser'
GO
/* Now setup the schema */
CREATE TABLE dbo.Table1 ( t1Id INT NOT NULL PRIMARY KEY );
GO
INSERT INTO dbo.Table1 (t1Id)
VALUES
(1),
(2),
(3),
(4),
(5),
(6),
(7),
(8),
(9),
(10);
GO
With our schema and sample data in place, we are now ready to create our TVP stored procedure:
CREATE TYPE T1Ids AS Table (
t1Id INT
);
GO
CREATE PROCEDURE dbo.FindMatchingRowsInTable1( @Table1Ids AS T1Ids READONLY )
AS
BEGIN
SET NOCOUNT ON;
SELECT Table1.t1Id FROM dbo.Table1 AS Table1
JOIN @Table1Ids AS paramTable1Ids ON Table1.t1Id = paramTable1Ids.t1Id;
END
GO
With both our schema and API in place, we can call the TVP stored procedure from our program like so:
// Curry the TVP data
DataTable t1Ids = new DataTable( );
t1Ids.Columns.Add( "t1Id",
typeof( int ) );
int[] listOfIdsToFind = new[] {1, 5, 9};
foreach ( int id in listOfIdsToFind )
{
t1Ids.Rows.Add( id );
}
// Prepare the connection details
SqlConnection testbedConnection =
new SqlConnection(
@"Data Source=.\SQLExpress;Initial Catalog=TestbedDb;Persist Security Info=True;User ID=testbedUser;Password=letmein12;Connect Timeout=5" );
try
{
testbedConnection.Open( );
// Prepare a call to the stored procedure
SqlCommand findMatchingRowsInTable1 = new SqlCommand( "dbo.FindMatchingRowsInTable1",
testbedConnection );
findMatchingRowsInTable1.CommandType = CommandType.StoredProcedure;
// Curry up the TVP parameter
SqlParameter sqlParameter = new SqlParameter( "Table1Ids",
t1Ids );
findMatchingRowsInTable1.Parameters.Add( sqlParameter );
// Execute the stored procedure
SqlDataReader sqlDataReader = findMatchingRowsInTable1.ExecuteReader( );
while ( sqlDataReader.Read( ) )
{
Console.WriteLine( "Matching t1ID: {0}",
sqlDataReader[ "t1Id" ] );
}
}
catch ( Exception e )
{
Console.WriteLine( e.ToString( ) );
}
/* Output:
* Matching t1ID: 1
* Matching t1ID: 5
* Matching t1ID: 9
*/
There is probably a less painful way to do this using a more abstract API, such as Entity Framework. However, I do not have the time to see for myself at this time.
You can use spring-rest-template-logger to log RestTemplate
HTTP traffic.
Add a dependency to your Maven project:
<dependency>
<groupId>org.hobsoft.spring</groupId>
<artifactId>spring-rest-template-logger</artifactId>
<version>2.0.0</version>
</dependency>
Then customize your RestTemplate
as follows:
RestTemplate restTemplate = new RestTemplateBuilder()
.customizers(new LoggingCustomizer())
.build()
Ensure that debug logging is enabled in application.properties
:
logging.level.org.hobsoft.spring.resttemplatelogger.LoggingCustomizer = DEBUG
Now all RestTemplate HTTP traffic will be logged to org.hobsoft.spring.resttemplatelogger.LoggingCustomizer
at debug level.
DISCLAIMER: I wrote this library.
If you run the following in SQL Server, you'll notice that COUNT(1)
is evaluated as COUNT(*)
anyway. So it appears that there is no difference, and also that COUNT(*)
is the expression most native to the query optimizer:
SET SHOWPLAN_TEXT ON
GO
SELECT COUNT(1)
FROM <table>
GO
SET SHOWPLAN_TEXT OFF
GO
The best way to do this is in version 4.2+ which allows using of aggregation pipeline in the update document and the updateOne
, updateMany
or update
collection method. Note that the latter has been deprecated in most if not all languages drivers.
Version 4.2 also introduced the $set
pipeline stage operator which is an alias for $addFields
. I will use $set
here as it maps with what we are trying to achieve.
db.collection.<update method>(
{},
[
{"$set": {"name": { "$concat": ["$firstName", " ", "$lastName"]}}}
]
)
In 3.4+ you can use $addFields
and the $out
aggregation pipeline operators.
db.collection.aggregate(
[
{ "$addFields": {
"name": { "$concat": [ "$firstName", " ", "$lastName" ] }
}},
{ "$out": "collection" }
]
)
Note that this does not update your collection but instead replace the existing collection or create a new one. Also for update operations that require "type casting" you will need client side processing, and depending on the operation, you may need to use the find()
method instead of the .aggreate()
method.
The way we do this is by $project
ing our documents and use the $concat
string aggregation operator to return the concatenated string.
we From there, you then iterate the cursor and use the $set
update operator to add the new field to your documents using bulk operations for maximum efficiency.
var cursor = db.collection.aggregate([
{ "$project": {
"name": { "$concat": [ "$firstName", " ", "$lastName" ] }
}}
])
from this, you need to use the bulkWrite
method.
var requests = [];
cursor.forEach(document => {
requests.push( {
'updateOne': {
'filter': { '_id': document._id },
'update': { '$set': { 'name': document.name } }
}
});
if (requests.length === 500) {
//Execute per 500 operations and re-init
db.collection.bulkWrite(requests);
requests = [];
}
});
if(requests.length > 0) {
db.collection.bulkWrite(requests);
}
From this version you need to use the now deprecated Bulk
API and its associated methods.
var bulk = db.collection.initializeUnorderedBulkOp();
var count = 0;
cursor.snapshot().forEach(function(document) {
bulk.find({ '_id': document._id }).updateOne( {
'$set': { 'name': document.name }
});
count++;
if(count%500 === 0) {
// Excecute per 500 operations and re-init
bulk.execute();
bulk = db.collection.initializeUnorderedBulkOp();
}
})
// clean up queues
if(count > 0) {
bulk.execute();
}
cursor["result"].forEach(function(document) {
db.collection.update(
{ "_id": document._id },
{ "$set": { "name": document.name } }
);
})
this might help. It worked for me. try it in the terminal
setenforce 0
sweet and simple custom filter:
(but only related to simple sum of values, not sum product, I've made up sumProduct
filter and appended it as edit to this post).
angular.module('myApp', [])
.filter('total', function () {
return function (input, property) {
var i = input instanceof Array ? input.length : 0;
// if property is not defined, returns length of array
// if array has zero length or if it is not an array, return zero
if (typeof property === 'undefined' || i === 0) {
return i;
// test if property is number so it can be counted
} else if (isNaN(input[0][property])) {
throw 'filter total can count only numeric values';
// finaly, do the counting and return total
} else {
var total = 0;
while (i--)
total += input[i][property];
return total;
}
};
})
This is sumProduct
filter, it accepts any number of arguments. As a argument it accepts name of the property from input data, and it can handle nested property (nesting marked by dot: property.nested
);
here's JS Fiddle and the code
angular.module('myApp', [])
.filter('sumProduct', function() {
return function (input) {
var i = input instanceof Array ? input.length : 0;
var a = arguments.length;
if (a === 1 || i === 0)
return i;
var keys = [];
while (a-- > 1) {
var key = arguments[a].split('.');
var property = getNestedPropertyByKey(input[0], key);
if (isNaN(property))
throw 'filter sumProduct can count only numeric values';
keys.push(key);
}
var total = 0;
while (i--) {
var product = 1;
for (var k = 0; k < keys.length; k++)
product *= getNestedPropertyByKey(input[i], keys[k]);
total += product;
}
return total;
function getNestedPropertyByKey(data, key) {
for (var j = 0; j < key.length; j++)
data = data[key[j]];
return data;
}
}
})
This is because of AbstractExecutorService :: submit
is wrapping your runnable
into RunnableFuture
(nothing but FutureTask
) like below
AbstractExecutorService.java
public Future<?> submit(Runnable task) {
if (task == null) throw new NullPointerException();
RunnableFuture<Void> ftask = newTaskFor(task, null); /////////HERE////////
execute(ftask);
return ftask;
}
Then execute
will pass it to Worker
and Worker.run()
will call the below.
ThreadPoolExecutor.java
final void runWorker(Worker w) {
Thread wt = Thread.currentThread();
Runnable task = w.firstTask;
w.firstTask = null;
w.unlock(); // allow interrupts
boolean completedAbruptly = true;
try {
while (task != null || (task = getTask()) != null) {
w.lock();
// If pool is stopping, ensure thread is interrupted;
// if not, ensure thread is not interrupted. This
// requires a recheck in second case to deal with
// shutdownNow race while clearing interrupt
if ((runStateAtLeast(ctl.get(), STOP) ||
(Thread.interrupted() &&
runStateAtLeast(ctl.get(), STOP))) &&
!wt.isInterrupted())
wt.interrupt();
try {
beforeExecute(wt, task);
Throwable thrown = null;
try {
task.run(); /////////HERE////////
} catch (RuntimeException x) {
thrown = x; throw x;
} catch (Error x) {
thrown = x; throw x;
} catch (Throwable x) {
thrown = x; throw new Error(x);
} finally {
afterExecute(task, thrown);
}
} finally {
task = null;
w.completedTasks++;
w.unlock();
}
}
completedAbruptly = false;
} finally {
processWorkerExit(w, completedAbruptly);
}
}
Finally
task.run();
in the above code call will callFutureTask.run()
. Here is the exception handler code, because of this you are NOT getting the expected exception.
class FutureTask<V> implements RunnableFuture<V>
public void run() {
if (state != NEW ||
!UNSAFE.compareAndSwapObject(this, runnerOffset,
null, Thread.currentThread()))
return;
try {
Callable<V> c = callable;
if (c != null && state == NEW) {
V result;
boolean ran;
try {
result = c.call();
ran = true;
} catch (Throwable ex) { /////////HERE////////
result = null;
ran = false;
setException(ex);
}
if (ran)
set(result);
}
} finally {
// runner must be non-null until state is settled to
// prevent concurrent calls to run()
runner = null;
// state must be re-read after nulling runner to prevent
// leaked interrupts
int s = state;
if (s >= INTERRUPTING)
handlePossibleCancellationInterrupt(s);
}
}
This blog post gives a nice explanation and some background. Basically, the "permanent generation" (whose size is given by PermSize) is used to store things that the JVM has to allocate space for, but which will not (normally) be garbage-collected (hence "permanent") (+). That means for example loaded classes and static fields.
There is also a FAQ on garbage collection directly from Sun, which answers some questions about the permanent generation. Finally, here's a blog post with a lot of technical detail.
(+) Actually parts of the permanent generation will be GCed, e.g. class objects will be removed when a class is unloaded. But that was uncommon when the permanent generation was introduced into the JVM, hence the name.
The following steps solved the problem for me. I was having the issue where it was not compiling for the device or archiving, working fine for simulator.
Clean and build after doing the above steps and everything works fine now.
I think that if you define the logic in an extension method the code will be much more readable:
public static class EnumerableExtensions {
public static string Join<T>(this IEnumerable<T> self, string separator) {
return String.Join(separator, self.Select(e => e.ToString()).ToArray());
}
}
public class Person {
public string FirstName { get; set; }
public string LastName { get; set; }
public override string ToString() {
return string.Format("{0} {1}", FirstName, LastName);
}
}
// ...
List<Person> people = new List<Person>();
// ...
string fullNames = people.Join(", ");
string lastNames = people.Select(p => p.LastName).Join(", ");
select max(Salary) from EmployeeTest where Salary < ( select max(Salary) from EmployeeTest ) ;
this will work for all DBs.
pylab provides a flatten: link to numpy flatten
I had a similar import problem. I noticed that there was no __init__.py
file in the root of the google
package. So, I created an empty __init__.py
and now the import works.
you can use generic class:
class Wrapped<T> {
private T _value;
public Action ValueChanged;
public T Value
{
get => _value;
set
{
_value = value;
OnValueChanged();
}
}
protected virtual void OnValueChanged() => ValueChanged?.Invoke() ;
}
and will be able to do the following:
var i = new Wrapped<int>();
i.ValueChanged += () => { Console.WriteLine("changed!"); };
i.Value = 10;
i.Value = 10;
i.Value = 10;
i.Value = 10;
Console.ReadKey();
result:
changed!
changed!
changed!
changed!
changed!
changed!
changed!
Extending Reshure's answer
Open Run ? Run... from the menubar in Notepad++ (shortcut: F5)
In the given space, enter:
"$(FULL_CURRENT_PATH)" -1
Click Run
ta da!
From the docs, the recommended way of getting a timezone aware datetime object from seconds since epoch is:
from datetime import datetime, timezone
datetime.fromtimestamp(timestamp, timezone.utc)
from datetime import datetime
import pytz
datetime.fromtimestamp(timestamp, pytz.utc)
File file = new File(getFilePath(imageUri.getValue()));
boolean b = file.delete();
is not working in my case.
boolean b = file.delete(); // returns false
boolean b = file.getAbsolutePath.delete(); // returns false
always returns false.
The issue has been resolved by using the code below:
ContentResolver contentResolver = getContentResolver();
contentResolver.delete(uriDelete, null, null);
Simple and straight forward way to create ArrayList of String
List<String> category = Arrays.asList("everton", "liverpool", "swansea", "chelsea");
Cheers
"Format" is your response type. Could be json or html, for example. It's the format of the output your visitor will receive.
I use the command pkill
for this:
NAME
pgrep, pkill - look up or signal processes based on name and
other attributes
SYNOPSIS
pgrep [options] pattern
pkill [options] pattern
DESCRIPTION
pgrep looks through the currently running processes and lists
the process IDs which match the selection criteria to stdout.
All the criteria have to match. For example,
$ pgrep -u root sshd
will only list the processes called sshd AND owned by root.
On the other hand,
$ pgrep -u root,daemon
will list the processes owned by root OR daemon.
pkill will send the specified signal (by default SIGTERM)
to each process instead of listing them on stdout.
If your code runs via interpreter (java, python, ...) then the name of the process is the name of the interpreter. You need to user the argument --full. This matches against the command name and the arguments.
I wanted a simple regex, where it's fine to allow too much, but not to deny a valid postcode. I went with this (the input is a stripped/trimmed string):
/^([a-z0-9]\s*){5,8}$/i
This allows the shortest possible postcodes like "L1 8JQ" as well as the longest ones like "OL14 5ET".
Because it allows up to 8 characters, it will also allow incorrect 8 character postcodes if there is no space: "OL145ETX". But again, this is a simplistic regex, for when that's good enough.
Unfortunately, there's no built-in support for formatting in string templates yet, as a workaround, you can use something like:
"pi = ${pi.format(2)}"
the .format(n)
function you'd need to define yourself as
fun Double.format(digits: Int) = "%.${digits}f".format(this)
There's clearly a piece of functionality here that is missing from Kotlin at the moment, we'll fix it.
A cookie is basically just an item in a dictionary. Each item has a key and a value. For authentication, the key could be something like 'username' and the value would be the username. Each time you make a request to a website, your browser will include the cookies in the request, and the host server will check the cookies. So authentication can be done automatically like that.
To set a cookie, you just have to add it to the response the server sends back after requests. The browser will then add the cookie upon receiving the response.
There are different options you can configure for the cookie server side, like expiration times or encryption. An encrypted cookie is often referred to as a signed cookie. Basically the server encrypts the key and value in the dictionary item, so only the server can make use of the information. So then cookie would be secure.
A browser will save the cookies set by the server. In the HTTP header of every request the browser makes to that server, it will add the cookies. It will only add cookies for the domains that set them. Example.com can set a cookie and also add options in the HTTP header for the browsers to send the cookie back to subdomains, like sub.example.com. It would be unacceptable for a browser to ever sends cookies to a different domain.
Checking in from 2015: We now have native promises in most recent browser (Edge 12, Firefox 40, Chrome 43, Safari 8, Opera 32 and Android browser 4.4.4 and iOS Safari 8.4, but not Internet Explorer, Opera Mini and older versions of Android).
If we want to perform 10 async actions and get notified when they've all finished, we can use the native Promise.all
, without any external libraries:
function asyncAction(i) {
return new Promise(function(resolve, reject) {
var result = calculateResult();
if (result.hasError()) {
return reject(result.error);
}
return resolve(result);
});
}
var promises = [];
for (var i=0; i < 10; i++) {
promises.push(asyncAction(i));
}
Promise.all(promises).then(function AcceptHandler(results) {
handleResults(results),
}, function ErrorHandler(error) {
handleError(error);
});
cd /path/to/backupdir/
git clone /path/to/repo
cd /path/to/repo
git remote add backup /path/to/backupdir
git push --set-upstream backup master
this creates a backup and makes the setup, so that you can do a git push to update your backup, what is probably what you want to do. Just make sure, that /path/to/backupdir and /path/to/repo are at least different hard drives, otherwise it doesn't make that much sense to do that.
Here is a YouTube video that explains exactly what you're wanting to do: Save and load a Keras model
There are three different saving methods that Keras makes available. These are described in the video link above (with examples), as well as below.
First, the reason you're receiving the error is because you're calling load_model
incorrectly.
To save and load the weights of the model, you would first use
model.save_weights('my_model_weights.h5')
to save the weights, as you've displayed. To load the weights, you would first need to build your model, and then call load_weights
on the model, as in
model.load_weights('my_model_weights.h5')
Another saving technique is model.save(filepath)
. This save
function saves:
To load this saved model, you would use the following:
from keras.models import load_model
new_model = load_model(filepath)'
Lastly, model.to_json()
, saves only the architecture of the model. To load the architecture, you would use
from keras.models import model_from_json
model = model_from_json(json_string)
You can also use the split
method of String:
String[] lines = myString.split(System.getProperty("line.separator"));
This gives you all lines in a handy array.
I don't know about the performance of split. It uses regular expressions.
In addition to other nice answers, a quote from Linux system programming written by Google's expert Robert Love:
Advantages of
mmap( )
Manipulating files via
mmap( )
has a handful of advantages over the standardread( )
andwrite( )
system calls. Among them are:
Reading from and writing to a memory-mapped file avoids the extraneous copy that occurs when using the
read( )
orwrite( )
system calls, where the data must be copied to and from a user-space buffer.Aside from any potential page faults, reading from and writing to a memory-mapped file does not incur any system call or context switch overhead. It is as simple as accessing memory.
When multiple processes map the same object into memory, the data is shared among all the processes. Read-only and shared writable mappings are shared in their entirety; private writable mappings have their not-yet-COW (copy-on-write) pages shared.
Seeking around the mapping involves trivial pointer manipulations. There is no need for the
lseek( )
system call.For these reasons,
mmap( )
is a smart choice for many applications.Disadvantages of
mmap( )
There are a few points to keep in mind when using
mmap( )
:
Memory mappings are always an integer number of pages in size. Thus, the difference between the size of the backing file and an integer number of pages is "wasted" as slack space. For small files, a significant percentage of the mapping may be wasted. For example, with 4 KB pages, a 7 byte mapping wastes 4,089 bytes.
The memory mappings must fit into the process' address space. With a 32-bit address space, a very large number of various-sized mappings can result in fragmentation of the address space, making it hard to find large free contiguous regions. This problem, of course, is much less apparent with a 64-bit address space.
There is overhead in creating and maintaining the memory mappings and associated data structures inside the kernel. This overhead is generally obviated by the elimination of the double copy mentioned in the previous section, particularly for larger and frequently accessed files.
For these reasons, the benefits of
mmap( )
are most greatly realized when the mapped file is large (and thus any wasted space is a small percentage of the total mapping), or when the total size of the mapped file is evenly divisible by the page size (and thus there is no wasted space).
There's also a C standard built-in library to get command line arguments: getopt
You can check it on Wikipedia or in Argument-parsing helpers for C/Unix.
The easiest method is to use the OFFSET function. So for the original example, the formula would be: =offset(c2,0,-1)*1.33 ="using current cell (c2) as reference point, get the contents of cell on same row, but one column to the left (b2) and multiply it by 1.33"
Works a treat.
You can use Entry
class to read HashMap
easily.
for(Map.Entry<TypeKey, TypeKey> temp : example.entrySet()){
System.out.println(temp.getValue()); // Or something as per temp defination. can be used
}
Using SXSSF poi 3.8
package example;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class SXSSFexample {
public static void main(String[] args) throws Throwable {
FileInputStream inputStream = new FileInputStream("mytemplate.xlsx");
XSSFWorkbook wb_template = new XSSFWorkbook(inputStream);
inputStream.close();
SXSSFWorkbook wb = new SXSSFWorkbook(wb_template);
wb.setCompressTempFiles(true);
SXSSFSheet sh = (SXSSFSheet) wb.getSheetAt(0);
sh.setRandomAccessWindowSize(100);// keep 100 rows in memory, exceeding rows will be flushed to disk
for(int rownum = 4; rownum < 100000; rownum++){
Row row = sh.createRow(rownum);
for(int cellnum = 0; cellnum < 10; cellnum++){
Cell cell = row.createCell(cellnum);
String address = new CellReference(cell).formatAsString();
cell.setCellValue(address);
}
}
FileOutputStream out = new FileOutputStream("tempsxssf.xlsx");
wb.write(out);
out.close();
}
}
It requires:
You may want to use:
SELECT Name, 'Unpaid' AS Status FROM table;
The SELECT
clause syntax, as defined in MSDN: SELECT Clause (Transact-SQL), is as follows:
SELECT [ ALL | DISTINCT ]
[ TOP ( expression ) [ PERCENT ] [ WITH TIES ] ]
<select_list>
Where the expression
can be a constant, function, any combination of column names, constants, and functions connected by an operator or operators, or a subquery.
PHP can be easily utilized for reading bar codes printed on paper documents. Connecting manual barcode reader to the computer via USB significantly extends usability of PHP (or any other web programming language) into tasks involving document and product management, like finding a book records in the database or listing all bills for a particular customer.
Following sections briefly describe process of connecting and using manual bar code reader with PHP.
The usage of bar code scanners described in this article are in the same way applicable to any web programming language, such as ASP, Python or Perl. This article uses only PHP since all tests have been done with PHP applications.
What is a bar code reader (scanner)
Bar code reader is a hardware pluggable into computer that sends decoded bar code strings into computer. The trick is to know how to catch that received string. With PHP (and any other web programming language) the string will be placed into focused input HTML element in browser. Thus to catch received bar code string, following must be done:
just before reading the bar code, proper input element, such as INPUT TEXT FIELD must be focused (mouse cursor is inside of the input field). once focused, start reading the code when the code is recognized (bar code reader usually shortly beeps), it is send to the focused input field. By default, most of bar code readers will append extra special character to decoded bar code string called CRLF (ENTER). For example, if decoded bar code is "12345AB", then computer will receive "12345ABENTER". Appended character ENTER (or CRLF) emulates pressing the key ENTER causing instant submission of the HTML form:
<form action="search.php" method="post">
<input name="documentID" onmouseover="this.focus();" type="text">
</form>
Choosing the right bar code scanner
When choosing bar code reader, one should consider what types of bar codes will be read with it. Some bar codes allow only numbers, others will not have checksum, some bar codes are difficult to print with inkjet printers, some barcode readers have narrow reading pane and cannot read for example barcodes with length over 10 cm. Most of barcode readers support common barcodes, such as EAN8, EAN13, CODE 39, Interleaved 2/5, Code 128 etc.
For office purposes, the most suitable barcodes seem to be those supporting full range of alphanumeric characters, which might be:
Other important things to note:
Installing scanner drivers
Installing manual bar code reader requires installing drivers for your particular operating system and should be normally supplied with purchased bar code reader.
Once installed and ready, bar code reader turns on signal LED light. Reading the barcode starts with pressing button for reading.
Scanning the barcode - how does it work?
STEP 1 - Focused input field ready for receiving character stream from bar code scanner:
STEP 2 - Received barcode string from bar code scanner is immediatelly submitted for search into database, which creates nice "automated" effect:
STEP 3 - Results returned after searching the database with submitted bar code:
Conclusion
It seems, that utilization of PHP (and actually any web programming language) for scanning the bar codes has been quite overlooked so far. However, with natural support of emulated keypress (ENTER/CRLF) it is very easy to automate collecting & processing recognized bar code strings via simple HTML (GUI) fomular.
The key is to understand, that recognized bar code string is instantly sent to the focused HTML element, such as INPUT text field with appended trailing character ASCII 13 (=ENTER/CRLF, configurable option), which instantly sends input text field with populated received barcode as a HTML formular to any other script for further processing.
Reference: http://www.synet.sk/php/en/280-barcode-reader-scanner-in-php
Hope this helps you :)
My solution was to add a space between the $ and the {.
For example:
@Value("${appclient.port:}")
becomes
@Value("$ {appclient.port:}")
Most people would prevent the form from submitting by calling the event.preventDefault()
function.
Another means is to remove the onclick attribute of the button, and get the code in processForm()
out into .submit(function() {
as return false;
causes the form to not submit. Also, make the formBlaSubmit()
functions return Boolean based on validity, for use in processForm();
katsh
's answer is the same, just easier to digest.
(By the way, I'm new to stackoverflow, give me guidance please. )
you have to call set and add functions on chart object before calling redraw.
chart.xAxis[0].setCategories([2,4,5,6,7], false);
chart.addSeries({
name: "acx",
data: [4,5,6,7,8]
}, false);
chart.redraw();
The final
keyword has several usages in Java. It corresponds to both the sealed
and readonly
keywords in C#, depending on the context in which it is used.
To prevent subclassing (inheritance from the defined class):
Java
public final class MyFinalClass {...}
C#
public sealed class MyFinalClass {...}
Prevent overriding of a virtual
method.
Java
public class MyClass
{
public final void myFinalMethod() {...}
}
C#
public class MyClass : MyBaseClass
{
public sealed override void MyFinalMethod() {...}
}
As Joachim Sauer points out, a notable difference between the two languages here is that Java by default marks all non-static methods as virtual
, whereas C# marks them as sealed
. Hence, you only need to use the sealed
keyword in C# if you want to stop further overriding of a method that has been explicitly marked virtual
in the base class.
To only allow a variable to be assigned once:
Java
public final double pi = 3.14; // essentially a constant
C#
public readonly double pi = 3.14; // essentially a constant
As a side note, the effect of the readonly
keyword differs from that of the const
keyword in that the readonly
expression is evaluated at runtime rather than compile-time, hence allowing arbitrary expressions.
This is easy and very short:
.block {_x000D_
display: table-row;_x000D_
vertical-align: middle;_x000D_
}_x000D_
_x000D_
.tile {_x000D_
display: table-cell;_x000D_
vertical-align: middle;_x000D_
text-align: center;_x000D_
width: 500px;_x000D_
height: 100px;_x000D_
}
_x000D_
<div class="body">_x000D_
<span class="tile">_x000D_
Hello middle world! :)_x000D_
</span>_x000D_
</div>
_x000D_
The easiest way: Use gson, google's own goto json library. https://code.google.com/p/google-gson/
Here is a sample. I'm going to this free geolocator website and parsing the json and displaying my zipcode. (just put this stuff in a main method to test it out)
String sURL = "http://freegeoip.net/json/"; //just a string
// Connect to the URL using java's native library
URL url = new URL(sURL);
URLConnection request = url.openConnection();
request.connect();
// Convert to a JSON object to print data
JsonParser jp = new JsonParser(); //from gson
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //Convert the input stream to a json element
JsonObject rootobj = root.getAsJsonObject(); //May be an array, may be an object.
String zipcode = rootobj.get("zip_code").getAsString(); //just grab the zipcode
An easy way to see what a modulus operator looks like on various architectures is to use the Godbolt Compiler Explorer.
Suppose you have less data, I suggest to try 70%, 80% and 90% and test which is giving better result. In case of 90% there are chances that for 10% test you get poor accuracy.
A much easier way is to go to Data and select Group or Subtotal. Instant collapsible rows without messing with pivot tables or VBA.
Check out the apache config files. For Debian/Ubuntu theyre in /etc/apache2/sites-available/
for RedHat/CentOS/etc they're in /etc/httpd/conf.d/
. If you've just installed it, the file in there is probably named default
.
Make sure that the config file in there is pointing to the correct folder and then make sure your scripts are located there.
The line you're looking for in those files is DocumentRoot /path/to/directory
.
For a blank install, your php files most likely needs to be in /var/www/
.
What you'll also need to do is find your php.ini file, probably located at /etc/php5/apache2/php.ini
or /etc/php.ini
and find the entry for display_errors
and switch it to On
.
My beautiful non-standard solution
HTML
<div style="background-color:#f5b405"></div>
jQuery
$(this).attr("style").replace("background-color:", "");
Result
#f5b405
Use itertools.combinations(mylist, 2)
mylist = range(5)
for x,y in itertools.combinations(mylist, 2):
print x,y
0 1
0 2
0 3
0 4
1 2
1 3
1 4
2 3
2 4
3 4
const path = require('path');
if (path.sep === "\\") {
console.log("Windows");
} else {
console.log("Not Windows");
}
I know this is very old question, however there is a very lightweight (~.5Kb) JavaScript library that effectively "patches" the inconsistent firing of keyboard event handlers when using the DOM API.
The library is Keydrown.
Here's the operative code sample that has worked well for my purposes by just changing the key on which to set the listener:
kd.P.down(function () {
console.log('The "P" key is being held down!');
});
kd.P.up(function () {
console.clear();
});
// This update loop is the heartbeat of Keydrown
kd.run(function () {
kd.tick();
});
I've incorporated Keydrown into my client-side JavaScript for a proper pause animation in a Red Light Green Light game I'm writing. You can view the entire game here. (Note: If you're reading this in the future, the game should be code complete and playable :-D!)
I hope this helps.