this code line could be a simpler way to acomplish the same:
public class ProductConfiguration : EntityTypeConfiguration<Product>
{
public ProductConfiguration()
{
this.Property(m => m.Price).HasPrecision(10, 2);
}
}
For me it was caused because I renamed the entity class.When I rolled it back it was Ok.
Your model properties don't have to be 'auto properties' Even though that is easier. And the DefaultValue attribute is really only informative metadata The answer accepted here is one alternative to the constructor approach.
public class Track
{
private const int DEFAULT_LENGTH = 400;
private int _length = DEFAULT_LENGTH;
[DefaultValue(DEFAULT_LENGTH)]
public int LengthInMeters {
get { return _length; }
set { _length = value; }
}
}
vs.
public class Track
{
public Track()
{
LengthInMeters = 400;
}
public int LengthInMeters { get; set; }
}
This will only work for applications creating and consuming data using this specific class. Usually this isn't a problem if data access code is centralized. To update the value across all applications you need to configure the datasource to set a default value. Devi's answer shows how it can be done using migrations, sql, or whatever language your data source speaks.
Working with large models were very slow before the SP1, (have not tried it after the SP1, but it is said that is a snap now).
I still Design my tables first, then an in-house built tool generates the POCOs for me, so it takes the burden of doing repetitive tasks for each poco object.
when you are using source control systems, you can easily follow the history of your POCOs, it is not that easy with designer generated code.
I have a base for my POCO, which makes a lot of things quite easy.
I have views for all of my tables, each base view brings basic info for my foreign keys and my view POCOs derive from my POCO classes, which is quite usefull again.
And finally I dont like designers.
I had the same issue and in my case I was setting the date to new DateTime() instead of DateTime.Now
There re many ways to drop a database or update existing database, simply you can switched to previous migrations.
dotnet ef database update previousMigraionName
But some databases have limitations like not allow to modify after create relationships, means you have not allow privileges to drop columns from ef core database providers but most of time in ef core drop database is allowed.so you can drop DB using drop command and then you use previous migration again.
dotnet ef database drop
PMC command
PM> drop-database
OR you can do manually deleting database and do a migration.
You will have to use the fluent API to do this.
Try adding the following to your DbContext
:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.HasOptional(a => a.UserDetail)
.WithOptionalDependent()
.WillCascadeOnDelete(true);
}
You must make your foreign key nullable:
public class User
{
public int Id { get; set; }
public int? CountryId { get; set; }
public virtual Country Country { get; set; }
}
Recently added a composite key with the uniqueness of 2 columns using the approach that 'chuck' recommended, thank @chuck. Only this approached looked cleaner to me:
public int groupId {get; set;}
[Index("IX_ClientGrouping", 1, IsUnique = true)]
public int ClientId { get; set; }
[Index("IX_ClientGrouping", 2, IsUnique = true)]
public int GroupName { get; set; }
I had the same issue described in the answer that Elnaz gave. I had a requirement to change the namespace of the datalayer during a refactoring of our project. This caused the migrations to not see the existing migrations in the database. I found an excellent answer to this issue that James Chambers blogged.
I simply changed the following in the Migration configuration file.
public Configuration()
{
AutomaticMigrationsEnabled = false;
this.ContextKey = “Old_Namespace.Migrations.Configuration”;
}
Hope this helps someone else in a bind.
This is an option:
dbContext.Entry(entity).State = EntityState.Detached;
You can define foreign key by:
public class Parent
{
public int Id { get; set; }
public virtual ICollection<Child> Childs { get; set; }
}
public class Child
{
public int Id { get; set; }
// This will be recognized as FK by NavigationPropertyNameForeignKeyDiscoveryConvention
public int ParentId { get; set; }
public virtual Parent Parent { get; set; }
}
Now ParentId is foreign key property and defines required relation between child and existing parent. Saving the child without exsiting parent will throw exception.
If your FK property name doesn't consists of the navigation property name and parent PK name you must either use ForeignKeyAttribute data annotation or fluent API to map the relation
Data annotation:
// The name of related navigation property
[ForeignKey("Parent")]
public int ParentId { get; set; }
Fluent API:
modelBuilder.Entity<Child>()
.HasRequired(c => c.Parent)
.WithMany(p => p.Childs)
.HasForeignKey(c => c.ParentId);
Other types of constraints can be enforced by data annotations and model validation.
Edit:
You will get an exception if you don't set ParentId
. It is required property (not nullable). If you just don't set it it will most probably try to send default value to the database. Default value is 0 so if you don't have customer with Id = 0 you will get an exception.
My issue was similar - I had a new table i was creating that ahd to tie in to the identity users. After reading the above answers, realized it had to do with IsdentityUser and the inherited properites. I already had Identity set up as its own Context, so to avoid inherently tying the two together, rather than using the related user table as a true EF property, I set up a non-mapped property with the query to get the related entities. (DataManager is set up to retrieve the current context in which OtherEntity exists.)
[Table("UserOtherEntity")]
public partial class UserOtherEntity
{
public Guid UserOtherEntityId { get; set; }
[Required]
[StringLength(128)]
public string UserId { get; set; }
[Required]
public Guid OtherEntityId { get; set; }
public virtual OtherEntity OtherEntity { get; set; }
}
public partial class UserOtherEntity : DataManager
{
public static IEnumerable<OtherEntity> GetOtherEntitiesByUserId(string userId)
{
return Connect2Context.UserOtherEntities.Where(ue => ue.UserId == userId).Select(ue => ue.OtherEntity);
}
}
public partial class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
[NotMapped]
public IEnumerable<OtherEntity> OtherEntities
{
get
{
return UserOtherEntities.GetOtherEntitiesByUserId(this.Id);
}
}
}
You can use the NotMapped
attribute data annotation to instruct Code-First to exclude a particular property
public class Customer
{
public int CustomerID { set; get; }
public string FirstName { set; get; }
public string LastName{ set; get; }
[NotMapped]
public int Age { set; get; }
}
[NotMapped]
attribute is included in the System.ComponentModel.DataAnnotations
namespace.
You can alternatively do this with Fluent API
overriding OnModelCreating
function in your DBContext
class:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Customer>().Ignore(t => t.LastName);
base.OnModelCreating(modelBuilder);
}
http://msdn.microsoft.com/en-us/library/hh295847(v=vs.103).aspx
The version I checked is EF 4.3
, which is the latest stable version available when you use NuGet.
Edit : SEP 2017
Data annotation
If you are using asp.net core (2.0 at the time of this writing), The [NotMapped]
attribute can be used on the property level.
public class Customer
{
public int Id { set; get; }
public string FirstName { set; get; }
public string LastName { set; get; }
[NotMapped]
public int FullName { set; get; }
}
Fluent API
public class SchoolContext : DbContext
{
public SchoolContext(DbContextOptions<SchoolContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Customer>().Ignore(t => t.FullName);
base.OnModelCreating(modelBuilder);
}
public DbSet<Customer> Customers { get; set; }
}
One way to solve this error is to put the ForeignKey
attribute on top of the property you want as a foreign key and add the navigation property.
Note: In the ForeignKey
attribute, between parentheses and double quotes, place the name of the class referred to in this way.
My gut told me the same thing when I came across this design.
I am working on a code base where there are three dbContexts to one database. 2 out of the 3 dbcontexts are dependent on information from 1 dbcontext because it serves up the administrative data. This design has placed constraints on how you can query your data. I ran into this problem where you cannot join across dbcontexts. Instead what you are required to do is query the two separate dbcontexts then do a join in memory or iterate through both to get the combination of the two as a result set. The problem with that is instead of querying for a specific result set you are now loading all your records into memory and then doing a join against the two result sets in memory. It can really slow things down.
I would ask the question "just because you can, should you?"
See this article for the problem I came across related to this design.
The specified LINQ expression contains references to queries that are associated with different contexts
I had a similar problem, not exactly the same conditions and then i saw this post. Hope it helps someone. Apparently i was using one of my EF entity models a base class for a type that was not specified as a db set in my dbcontext. To fix this issue i had to create a base class that had all the properties common to the two types and inherit from the new base class among the two types.
Example:
//Bad Flow
//class defined in dbcontext as a dbset
public class Customer{
public int Id {get; set;}
public string Name {get; set;}
}
//class not defined in dbcontext as a dbset
public class DuplicateCustomer:Customer{
public object DuplicateId {get; set;}
}
//Good/Correct flow*
//Common base class
public class CustomerBase{
public int Id {get; set;}
public string Name {get; set;}
}
//entity model referenced in dbcontext as a dbset
public class Customer: CustomerBase{
}
//entity model not referenced in dbcontext as a dbset
public class DuplicateCustomer:CustomerBase{
public object DuplicateId {get; set;}
}
When using the attribute to restrict the maximum input length for text from a form on a webpage, the StringLength seems to generate the maxlength html attribute (at least in my test with MVC 5). The one to choose then depnds on how you want to alert the user that this is the maximum text length. With the stringlength attribute, the user will simply not be able to type beyond the allowed length. The maxlength attribute doesn't add this html attribute, instead it generates data validation attributes, meaning the user can type beyond the indicated length and that preventing longer input depends on the validation in javascript when he moves to the next field or clicks submit (or if javascript is disabled, server side validation). In this case the user can be notified of the restriction by an error message.
public partial class recommended_books : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.RecommendedBook",
c => new
{
RecommendedBookID = c.Int(nullable: false, identity: true),
CourseID = c.Int(nullable: false),
DepartmentID = c.Int(nullable: false),
Title = c.String(),
Author = c.String(),
PublicationDate = c.DateTime(nullable: false),
})
.PrimaryKey(t => t.RecommendedBookID)
.ForeignKey("dbo.Course", t => t.CourseID, cascadeDelete: false) // was true on migration
.ForeignKey("dbo.Department", t => t.DepartmentID, cascadeDelete: false) // was true on migration
.Index(t => t.CourseID)
.Index(t => t.DepartmentID);
}
public override void Down()
{
DropForeignKey("dbo.RecommendedBook", "DepartmentID", "dbo.Department");
DropForeignKey("dbo.RecommendedBook", "CourseID", "dbo.Course");
DropIndex("dbo.RecommendedBook", new[] { "DepartmentID" });
DropIndex("dbo.RecommendedBook", new[] { "CourseID" });
DropTable("dbo.RecommendedBook");
}
}
When your migration fails you are given a couple of options: 'Introducing FOREIGN KEY constraint 'FK_dbo.RecommendedBook_dbo.Department_DepartmentID' on table 'RecommendedBook' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. Could not create constraint or index. See previous errors.'
Here is an example of using the 'modify other FOREIGN KEY constraints' by setting 'cascadeDelete' to false in the migration file and then run 'update-database'.
It is an old question but i want to add that if you want to resize image according to viewport size only with css; you can use viewport units "vh (viewport height) or vw (viewport width)".
.img {
width: 100vw;
height: 100vh;
}
If you have this :
a = [[1, 1], [2, 1],[3, 1]]
You can easily access this by using :
print(a[0][2])
a[0][1] = 7
print(a)
The issue is seen if the nuget packages vary in multiple projects within the solution.
You can fix this by updating nuget packages to a common version with all of the PROJECTS in the SOLUTION
I've been looking through stack overflow to find a good answer and when i couldn't find one i went looking through the docs.
no one seems to have stumbled on this simple answer yet:
ViewCompat.setTranslationZ(view, translationZ);
default translation z is 0.0
The parameters of isset()
should be separated by a comma sign (,
) and not a dot sign (.
). Your current code concatenates the variables into a single parameter, instead of passing them as separate parameters.
So the original code evaluates the variables as a unified string
value:
isset($_POST['search_term'] . $_POST['postcode']) // Incorrect
While the correct form evaluates them separately as variables:
isset($_POST['search_term'], $_POST['postcode']) // Correct
The CSS tag 'margin' is actually a shorthand for the four separate margin values, top/left/bottom/right. Use css('marginTop')
, etc. - note they will have 'px' on the end if you have specified them that way.
Use parseInt()
around the result to turn it in to the number value.
NB. As noted by Omaty, the order of the shorthand 'margin' tag is:
top right bottom left
- the above list was not written in a way intended to be the list order, just a list of that specified in the tag.
Inspired by Roger Pate:
import datetime
def todayAt (hr, min=0, sec=0, micros=0):
now = datetime.datetime.now()
return now.replace(hour=hr, minute=min, second=sec, microsecond=micros)
# Usage demo1:
print todayAt (17), todayAt (17, 15)
# Usage demo2:
timeNow = datetime.datetime.now()
if timeNow < todayAt (13):
print "Too Early"
First solution is Use range_based for loop, like:
Note: When range_expression
’s type is std::map
then a range_declaration
’s type is std::pair
.
for ( range_declaration : range_expression )
//loop_statement
Code 1:
typedef std::map<std::string, std::map<std::string, std::string>> StringToStringMap;
StringToStringMap my_map;
for(const auto &pair1 : my_map)
{
// Type of pair1 is std::pair<std::string, std::map<std::string, std::string>>
// pair1.first point to std::string (first key)
// pair1.second point to std::map<std::string, std::string> (inner map)
for(const auto &pair2 : pair1.second)
{
// pair2.first is the second(inner) key
// pair2.second is the value
}
}
The Second Solution:
Code 2
typedef std::map<std::string, std::string> StringMap;
typedef std::map<std::string, StringMap> StringToStringMap;
StringToStringMap my_map;
for(StringToStringMap::iterator it1 = my_map.begin(); it1 != my_map.end(); it1++)
{
// it1->first point to first key
// it2->second point to inner map
for(StringMap::iterator it2 = it1->second.begin(); it2 != it1->second.end(); it2++)
{
// it2->second point to value
// it2->first point to second(inner) key
}
}
If you are running it locally and want to be able to step through the code:
python -m pdb script.py
Its no different to any other variable, e.g.
function sendemail($id,$userid){
echo $arr["foo"];
}
$arr = array("foo" => "bar");
sendemail($arr, $userid);
I realized that I don't need the port number in the request endpoint, so the endpoint was herokuapp.com
and not herokuapp.com:5000
.
The listen()
call can be without host and callback:
server.listen(5000);
can use simply like
<input [(ngModel)]="model.name" disabled="disabled"
I got it like this way. so i prefer.
This worked for me..
I was trying to automate multiple telnet logins which require a username and password. The telnet session needs to run in the background indefinitely since I am saving logs from different servers to my machine.
telnet.sh automates telnet login using the 'expect' command. More info can be found here: http://osix.net/modules/article/?id=30
telnet.sh
#!/usr/bin/expect
set timeout 20
set hostName [lindex $argv 0]
set userName [lindex $argv 1]
set password [lindex $argv 2]
spawn telnet $hostName
expect "User Access Verification"
expect "Username:"
send "$userName\r"
expect "Password:"
send "$password\r";
interact
sample_script.sh is used to create a background process for each of the telnet sessions by running telnet.sh. More information can be found in the comments section of the code.
sample_script.sh
#!/bin/bash
#start screen in detached mode with session-name 'default_session'
screen -dmS default_session -t screen_name
#save the generated logs in a log file 'abc.log'
screen -S default_session -p screen_name -X stuff "script -f /tmp/abc.log $(printf \\r)"
#start the telnet session and generate logs
screen -S default_session -p screen_name -X stuff "expect telnet.sh hostname username password $(printf \\r)"
Remove the dot in front of your class so it looks like this:
<div class="col-xs-2 col-xs-offset-1">col</div>
It's also possible to select attributes regardless of their content, in modern browsers
with:
[data-my-attribute] {
/* Styles */
}
[anything] {
/* Styles */
}
For example: http://codepen.io/jasonm23/pen/fADnu
Works on a very significant percentage of browsers.
Note this can also be used in a JQuery selector, or using document.querySelector
Try this header file in your code
stdbool.h
This must work
Use vertical-align:middle
in your CSS.
<table>
<tr>
<td style="vertical-align:middle">Description:</td>
<td><textarea></textarea></td>
</tr>
</table>
As long as checker
is not null
, you may use !checker
as posted. This is possible since Java 5, because this Boolean
variable will be autoboxed to the primivite boolean
value.
I know that the question has been answered, but I hope my solution helps other people.
stopPropagation
caused problems in my case, because I needed the click
event for something else. Moreover, not every element should cause the div to be closed when clicked.
My solution:
$(document).click(function(e) {
if (($(e.target).closest("#mydiv").attr("id") != "mydiv") &&
$(e.target).closest("#div-exception").attr("id") != "div-exception") {
alert("Clicked outside!");
}
});
You don't want to take care of normalizing your data in a view - what if the user changes the data that gets submitted? Instead you could take care of it in the model using the before_save
(or the before_validation
) callback. Here's an example of the relevant code for a model like yours:
class Place < ActiveRecord::Base before_save do |place| place.city = place.city.downcase.titleize place.country = place.country.downcase.titleize end end
You can also check out the Ruby on Rails guide for more info.
To answer you question more directly, something like this would work:
<%= f.text_field :city, :value => (f.object.city ? f.object.city.titlecase : '') %>
This just means if f.object.city
exists, display the titlecase
version of it, and if it doesn't display a blank string.
To write text to (or read text from) the Windows clipboard use this VBA function:
Function Clipboard$(Optional s$)
Dim v: v = s 'Cast to variant for 64-bit VBA support
With CreateObject("htmlfile")
With .parentWindow.clipboardData
Select Case True
Case Len(s): .setData "text", v
Case Else: Clipboard = .getData("text")
End Select
End With
End With
End Function
'Three examples of copying text to the clipboard:
Clipboard "Excel Hero was here."
Clipboard var1 & vbLF & var2
Clipboard 123
'To read text from the clipboard:
MsgBox Clipboard
This is a solution that does NOT use MS Forms nor the Win32 API. Instead it uses the Microsoft HTML Object Library which is fast and ubiquitous and NOT deprecated by Microsoft like MS Forms. And this solution respects line feeds. This solution also works from 64-bit Office. Finally, this solution allows both writing to and reading from the Windows clipboard. No other solution on this page has these benefits.
Use this one
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
// Get the layout inflater
LayoutInflater inflater = (activity).getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the
// dialog layout
builder.setTitle(title);
builder.setCancelable(false);
builder.setIcon(R.drawable.galleryalart);
builder.setView(inflater.inflate(R.layout.dialogue, null))
// Add action buttons
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
}
}
});
builder.create();
builder.show();
assert_has_calls
is another approach to this problem.
From the docs:
assert_has_calls (calls, any_order=False)
assert the mock has been called with the specified calls. The mock_calls list is checked for the calls.
If any_order is False (the default) then the calls must be sequential. There can be extra calls before or after the specified calls.
If any_order is True then the calls can be in any order, but they must all appear in mock_calls.
Example:
>>> from unittest.mock import call, Mock
>>> mock = Mock(return_value=None)
>>> mock(1)
>>> mock(2)
>>> mock(3)
>>> mock(4)
>>> calls = [call(2), call(3)]
>>> mock.assert_has_calls(calls)
>>> calls = [call(4), call(2), call(3)]
>>> mock.assert_has_calls(calls, any_order=True)
Source: https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock.assert_has_calls
If the DropDownList is declared in your aspx page and not in the codebehind, you can do it like this.
.aspx:
<asp:DropDownList ID="ddlStatus" runat="server" DataSource="<%# Statuses %>"
DataValueField="Key" DataTextField="Value"></asp:DropDownList>
.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
ddlStatus.DataBind();
// or use Page.DataBind() to bind everything
}
public Dictionary<int, string> Statuses
{
get
{
// do database/webservice lookup here to populate Dictionary
}
};
Format like this while selecting:
to_char(systimestamp, 'DD-MON-YYYY')
Eg:
select to_char(systimestamp, 'DD-MON-YYYY') from dual;
I need to make a POST request via Curl from the command line. Data for this request is located in a file...
All you need to do is have the --data
argument start with a @
:
curl -H "Content-Type: text/xml" --data "@path_of_file" host:port/post-file-path
For example, if you have the data in a file called stuff.xml
then you would do something like:
curl -H "Content-Type: text/xml" --data "@stuff.xml" host:port/post-file-path
The stuff.xml
filename can be replaced with a relative or full path to the file: @../xml/stuff.xml
, @/var/tmp/stuff.xml
, ...
This code generates some SQL which can achieve this on every table and column in the database:
SELECT
'UPDATE ['+T.TABLE_SCHEMA+'].[' + T.TABLE_NAME + '] SET [' + COLUMN_NAME + '] = NULL
WHERE [' + COLUMN_NAME + '] = '''''
FROM
INFORMATION_SCHEMA.columns C
INNER JOIN
INFORMATION_SCHEMA.TABLES T ON C.TABLE_NAME=T.TABLE_NAME AND C.TABLE_SCHEMA=T.TABLE_SCHEMA
WHERE
DATA_TYPE IN ('char','nchar','varchar','nvarchar')
AND C.IS_NULLABLE='YES'
AND T.TABLE_TYPE='BASE TABLE'
SELECT CASE WHEN COUNT(1) > 0 THEN 1 ELSE 0 END AS [Value]
FROM Sites S
WHERE S.Id = @SiteId and S.Status = 1 AND
(S.WebUserId = @WebUserId OR S.AllowUploads = 1)
As others have answered, the mysqli API can execute multi-queries with the msyqli_multi_query() function.
For what it's worth, PDO supports multi-query by default, and you can iterate over the multiple result sets of your multiple queries:
$stmt = $dbh->prepare("
select sql_calc_found_rows * from foo limit 1 ;
select found_rows()");
$stmt->execute();
do {
while ($row = $stmt->fetch()) {
print_r($row);
}
} while ($stmt->nextRowset());
However, multi-query is pretty widely considered a bad idea for security reasons. If you aren't careful about how you construct your query strings, you can actually get the exact type of SQL injection vulnerability shown in the classic "Little Bobby Tables" XKCD cartoon. When using an API that restrict you to single-query, that can't happen.
There are lots of great answers here. It would appear the text-shadow is probably the most reliable way to do this. I won't go into detail about how to do this with text-shadow since others have already done that, but the basic idea is that you create multiple text shadows around the text element. The larger the text outline, the more text shadows you need.
All of the answers submitted (as of this posting) provide static solutions for the text-shadow. I have taken a different approach and have written this JSFiddle that accepts outline color, blur, and width values as inputs and generates the appropriate text-shadow property for your element. Just fill in the blanks, check the preview, and click to copy the css and paste it into your stylesheet.
Apparently, answers that include a link to a JSFiddle cannot be posted unless they also contain code. You can completely ignore this appendix if you want to. This is the JavaScript from my fiddle that generates the text-shadow property. Please note that you do not need to implement this code in your own works:
function computeStyle() {
var width = document.querySelector('#outline-width').value;
width = (width === '') ? 0 : Number.parseFloat(width);
var blur = document.querySelector('#outline-blur').value;
blur = (blur === '') ? 0 : Number.parseFloat(blur);
var color = document.querySelector('#outline-color').value;
if (width < 1 || color === '') {
document.querySelector('.css-property').innerText = '';
return;
}
var style = 'text-shadow: ';
var indent = false;
for (var i = -1 * width; i <= width; ++i) {
for (var j = -1 * width; j <= width; ++j) {
if (! (i === 0 && j === 0 && blur === 0)) {
var indentation = (indent) ? '\u00a0\u00a0\u00a0\u00a0' : '';
style += indentation + i + "px " + j + "px " + blur + "px " + color + ',\n';
indent = true;
}
}
}
style = style.substring(0, style.length - 2) + '\n;';
document.querySelector('.css-property').innerText = style;
var exampleBackground = document.querySelector('#example-bg');
var exampleText = document.querySelector('#example-text');
exampleBackground.style.backgroundColor = getOppositeColor(color);
exampleText.style.color = getOppositeColor(color);
var textShadow = style.replace(/text-shadow: /, '').replace(/\n/g, '').replace(/.$/, '').replace(/\u00a0\u00a0\u00a0\u00a0/g, '');
exampleText.style.textShadow = textShadow;
}
The rules of locating classes in an archive file is that the location of the file's package declaration and the location of the file within the archive have to match. Since your class is located in WEB-INF/classes, it thinks the class is not valid to run in the current context.
The only way you can do what you're asking is to repackage the war so the .class
file resides in the mypackage
directory in the root of the archive rather than the WEB-INF/classes directory. However, if you do that you won't be able to access the file from any of your web classes anymore.
If you want to reuse this class in both the war and outside from the java command line, consider building an executable jar you can run from the command line, then putting that jar in the war
file's WEB-INF/lib directory.
You don't need javascript for doing so. Just delete the onClick and write the php Admin.php
file like this:
<!-- HTML STARTS-->
<?php
//If all the required fields are filled
if (!empty($GET_['fullname'])&&!empty($GET_['email'])&&!empty($GET_['name']))
{
function addNewContact()
{
$new = '{';
$new .= '"fullname":"' . $_GET['fullname'] . '",';
$new .= '"email":"' . $_GET['email'] . '",';
$new .= '"phone":"' . $_GET['phone'] . '",';
$new .= '}';
return $new;
}
function saveContact()
{
$datafile = fopen ("data/data.json", "a+");
if(!$datafile){
echo "<script>alert('Data not existed!')</script>";
}
else{
$contact_list = $contact_list . addNewContact();
file_put_contents("data/data.json", $contact_list);
}
fclose($datafile);
}
// Call the function saveContact()
saveContact();
echo "Thank you for joining us";
}
else //If the form is not submited or not all the required fields are filled
{ ?>
<form>
<fieldset>
<legend>Add New Contact</legend>
<input type="text" name="fullname" placeholder="First name and last name" required /> <br />
<input type="email" name="email" placeholder="[email protected]" required /> <br />
<input type="text" name="phone" placeholder="Personal phone number: mobile, home phone etc." required /> <br />
<input type="submit" name="submit" class="button" value="Add Contact"/>
<input type="button" name="cancel" class="button" value="Reset" />
</fieldset>
</form>
<?php }
?>
<!-- HTML ENDS -->
Thought I don't like the PHP bit. Do you REALLY want to create a file for contacts? It'd be MUCH better to use a mysql database. Also, adding some breaks to that file would be nice too...
Other thought, IE doesn't support placeholder.
You can change the setup.py code to this:
from cx_freeze import setup, Executable
setup( name = "foo",
version = "1.1",
description = "Description of the app here.",
executables = [Executable("foo.py")]
)
I am sure it will work. I have tried it on both windows 7 as well as ubuntu 12.04
I'm not 100% sure what you're getting at since usually you will pass in your SQL queries (parameterized or not) to the JdbcTemplate, in which case you would just log those. If you have PreparedStatement
s and you don't know which one is being executed, the toString
method should work fine. But while we're on the subject, there's a nice Jdbc logger package here which will let you automatically log your queries as well as see the bound parameters each time. Very useful. The output looks something like this:
executing PreparedStatement: 'insert into ECAL_USER_APPT
(appt_id, user_id, accepted, scheduler, id) values (?, ?, ?, ?, null)'
with bind parameters: {1=25, 2=49, 3=1, 4=1}
Try ftp://test.rebex.net/
It is read-only used for testing Rebex components to list directory and download. Allows also to test FTP/SSL and IMAP.
Username is "demo", password is "password"
See https://test.rebex.net/ for more information.
This is a way to see if any XML-files exists in that folder, yes.
To check for specific files use File.Exists(path)
, which will return a boolean indicating wheter the file at path
exists.
[Long thread, not sure if its already listed as an option...].
A simple alternative for contsants only, would be defining the const outside of class.
This will be accessible only from the module itself, unless accompanied with a getter.
This way prototype
isn't littered and you get the const
.
// will be accessible only from the module itself
const MY_CONST = 'string';
class MyClass {
// optional, if external access is desired
static get MY_CONST(){return MY_CONST;}
// access example
static someMethod(){
console.log(MY_CONST);
}
}
Use this CSS (jsFiddle example):
input:disabled.btn:hover,
input:disabled.btn:active,
input:disabled.btn:focus {
color: green
}
You have to write the most outer element on the left and the most inner element on the right.
.btn:hover input:disabled
would select any disabled input elements contained in an element with a class btn
which is currently hovered by the user.
I would prefer :disabled
over [disabled]
, see this question for a discussion: Should I use CSS :disabled pseudo-class or [disabled] attribute selector or is it a matter of opinion?
By the way, Laravel (PHP) generates the HTML - not the browser.
barplot(data)
barplot(data, yaxp=c(0, max(data), 5))
yaxp=c(minY-axis, maxY-axis, Interval)
For some reasons, all of the answers in this thread, in onActivityResult()
try to post-process the received Uri
, like getting the real path of the image and then use BitmapFactory.decodeFile(path)
to get the Bitmap
.
This step is unnecessary. The ImageView
class has a method called setImageURI(uri)
. Pass your uri to it and you should be done.
Uri imageUri = data.getData();
imageView.setImageURI(imageUri);
For a complete working example you could take a look here: http://androidbitmaps.blogspot.com/2015/04/loading-images-in-android-part-iii-pick.html
PS:
Getting the Bitmap
in a separate variable would make sense in cases where the image to be loaded is too large to fit in memory, and a scale down operation is necessary to prevent OurOfMemoryError
, like shown in the @siamii answer.
I had the exact same issue and i just needed to set the SDK for the library project of the MapsApiV2 to Android 2.3.3 (API lvl 10)
I have seen most of the articles that don't work properly that's why new developers and professional developers get confused about it.
I am explaining to you in a very simple way. In this code, I am generating a google Recaptcha token at the client side at every 3 seconds of time interval because the token is valid for only a few minutes that's why if any user takes time to fill the form then it may be expired.
First I have an index.php file where I am going to write HTML and JavaScript code.
<!DOCTYPE html>
<html>
<head>
<title>Google Recaptcha V3</title>
</head>
<body>
<h1>Google Recaptcha V3</h1>
<form action="recaptcha.php" method="post">
<label>Name</label>
<input type="text" name="name" id="name">
<input type="hidden" name="token" id="token" />
<input type="hidden" name="action" id="action" />
<input type="submit" name="submit">
</form>
<script src="https://www.google.com/recaptcha/api.js?render=put your site key here"></script>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
setInterval(function(){
grecaptcha.ready(function() {
grecaptcha.execute('put your site key here', {action: 'application_form'}).then(function(token) {
$('#token').val(token);
$('#action').val('application_form');
});
});
}, 3000);
});
</script>
</body>
</html>
Next, I have created recaptcha.php file to execute it at the server side
<?php
if ($_POST['submit']) {
$name = $_POST['name'];
$token = $_POST['token'];
$action = $_POST['action'];
$curlData = array(
'secret' => 'put your secret key here',
'response' => $token
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($curlData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$curlResponse = curl_exec($ch);
$captchaResponse = json_decode($curlResponse, true);
if ($captchaResponse['success'] == '1' && $captchaResponse['action'] == $action && $captchaResponse['score'] >= 0.5 && $captchaResponse['hostname'] == $_SERVER['SERVER_NAME']) {
echo 'Form Submitted Successfully';
} else {
echo 'You are not a human';
}
}
Source of this code. If you would like to know the explanation of this code please visit. Google reCAPTCHA V3 integration in PHP
Python allows you to use a string as an iterator:
for character in 'string':
print(character)
I'm guessing it's your job to figure out how to turn that into a while loop.
As also noted in the docs here.
Go to Python X.X/Lib
and add these lines to the site.py
there,
import sys
sys.path.append("yourpathstring")
This changes your sys.path
so that on every load, it will have that value in it..
As stated here about site.py
,
This module is automatically imported during initialization. Importing this module will append site-specific paths to the module search path and add a few builtins.
For other possible methods of adding some path to sys.path
see these docs
it is working perfectly by only using html
<p><a href="#"onclick="window.open('http://google.com');window.open('http://yahoo.com');">Click to open Google and Yahoo</a></p>
This should fix it:
jQuery(document).ready(function($){
//you can now use $ as your jQuery object.
var body = $( 'body' );
});
Put simply, WordPress runs their own scripting before you can and they release the $
var so it won't collide with other libraries. This makes total sense, as WordPress is used for all kinds of web sites, apps, and of course, blogs.
From their documentation:
The jQuery library included with WordPress is set to the noConflict() mode (see wp-includes/js/jquery/jquery.js). This is to prevent compatibility problems with other JavaScript libraries that WordPress can link.
In the noConflict() mode, the global $ shortcut for jQuery is not available...
If the file is in the same directory as the one where the .md is, then just putting [Click here](MY-FILE.md)
should work.
Otherwise, can create a path from the root directory of the project. So if the entire project/git-repo root directory is called 'my-app', and one wants to point to my-app/client/read-me.md, then try [My hyperlink](/client/read-me.md)
.
At least works from Chrome.
The way i am going to tell you, will allow you to change the labels of legend, axis, title etc with a single formula and you don't need to use memorise multiple formulas. This will not affect the font style or the design of the labels/ text of titles and axis.
I am giving the complete answer of the question below.
library(ggplot2)
rating <- c(rnorm(200), rnorm(200, mean=.8))
cond <-factor(rep(c("A", "B"), each = 200))
df <- data.frame(cond,rating
)
k<- ggplot(data=df, aes(x=rating, fill=cond))+
geom_density(alpha = .3) +
xlab("NEW RATING TITLE") +
ylab("NEW DENSITY TITLE")
# to change the cond to a different label
k$labels$fill="New Legend Title"
# to change the axis titles
k$labels$y="Y Axis"
k$labels$x="X Axis"
k
I have stored the ggplot output in a variable "k". You can name it anything you like. Later I have used
k$labels$fill ="New Legend Title"
to change the legend. "fill" is used for those labels which shows different colours. If you have labels that shows sizes like 1 point represent 100, other point 200 etc then you can use this code like this-
k$labels$size ="Size of points"
and it will change that label title.
In general, you can't do this. UTF-8 is capable of encoding any Unicode code point. ISO-8859-1 can handle only a tiny fraction of them. So, transcoding from ISO-8859-1 to UTF-8 is no problem. Going backwards from UTF-8 to ISO-8859-1 will cause "replacement characters" (�) to appear in your text when unsupported characters are found.
To transcode text:
byte[] latin1 = ...
byte[] utf8 = new String(latin1, "ISO-8859-1").getBytes("UTF-8");
or
byte[] utf8 = ...
byte[] latin1 = new String(utf8, "UTF-8").getBytes("ISO-8859-1");
You can exercise more control by using the lower-level Charset
APIs. For example, you can raise an exception when an un-encodable character is found, or use a different character for replacement text.
JULI logging levels for Tomcat
SEVERE - Serious failures
WARNING - Potential problems
INFO - Informational messages
CONFIG - Static configuration messages
FINE - Trace messages
FINER - Detailed trace messages
FINEST - Highly detailed trace messages
You can find here more https://documentation.progress.com/output/ua/OpenEdge_latest/index.html#page/pasoe-admin/tomcat-logging.html
Ok. I found a program buried deep in other files from the beginning of the year that does what I want. I can't really comment on the suggestions offered because I'm not an experienced spim or low level programmer.Here it is:
.text
.globl __start
__start:
la $a0,str1 #Load and print string asking for string
li $v0,4
syscall
li $v0,8 #take in input
la $a0, buffer #load byte space into address
li $a1, 20 # allot the byte space for string
move $t0,$a0 #save string to t0
syscall
la $a0,str2 #load and print "you wrote" string
li $v0,4
syscall
la $a0, buffer #reload byte space to primary address
move $a0,$t0 # primary address = t0 address (load pointer)
li $v0,4 # print string
syscall
li $v0,10 #end program
syscall
.data
buffer: .space 20
str1: .asciiz "Enter string(max 20 chars): "
str2: .asciiz "You wrote:\n"
###############################
#Output:
#Enter string(max 20 chars): qwerty 123
#You wrote:
#qwerty 123
#Enter string(max 20 chars): new world oreddeYou wrote:
# new world oredde //lol special character
###############################
This should be working. Please have a look at this fiddle.
$(function() {
$( "#slider" ).slider();
});//Links to jsfiddle must be accompanied by code
Make sure you're loading the libraries in this order: jQuery, jQuery UI CSS, jQuery UI, AngularJS.
You can define the default value in the database designer, or when you create the table. For instance in SQL Server you can set the default vault of a Date field to (getDate()
). Use insertable=false
as mentioned in your column definition. JPA will not specify that column on inserts and the database will generate the value for you.
You need to have your function in the componentDidMount
lifecycle since this is the function that is called when the DOM has loaded.
Make use of refs
to access the DOM element
<input type="submit" className="nameInput" id="name" value="cp-dev1" onClick={this.writeData} ref = "cpDev1"/>
componentDidMount: function(){
var name = React.findDOMNode(this.refs.cpDev1).value;
this.someOtherFunction(name);
}
See this answer for more info on How to access the dom element in React
For the instance of
render :json => @projects, :include => :tasks
You are stating that you want to render @projects
as JSON, and include the association tasks
on the Project model in the exported data.
For the instance of
render :json => @projects, :callback => 'updateRecordDisplay'
You are stating that you want to render @projects
as JSON, and wrap that data in a javascript call that will render somewhat like:
updateRecordDisplay({'projects' => []})
This allows the data to be sent to the parent window and bypass cross-site forgery issues.
I had the same problem. 2.0 worked fine. after installing up to 3.5 sp1, application gets Access Violation.
installed http://support.microsoft.com/kb/971030 and my problem is solved, even though I am not using LCG.
import android.preference.PreferenceManager;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
// then you use
prefs.getBoolean("keystring", true);
Update
According to Shared Preferences | Android Developer Tutorial (Part 13) by Sai Geetha M N,
Many applications may provide a way to capture user preferences on the settings of a specific application or an activity. For supporting this, Android provides a simple set of APIs.
Preferences are typically name value pairs. They can be stored as “Shared Preferences” across various activities in an application (note currently it cannot be shared across processes). Or it can be something that needs to be stored specific to an activity.
Shared Preferences: The shared preferences can be used by all the components (activities, services etc) of the applications.
Activity handled preferences: These preferences can only be used within the particular activity and can not be used by other components of the application.
Shared Preferences:
The shared preferences are managed with the help of getSharedPreferences
method of the Context
class. The preferences are stored in a default file (1) or you can specify a file name (2) to be used to refer to the preferences.
(1) The recommended way is to use by the default mode, without specifying the file name
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
(2) Here is how you get the instance when you specify the file name
public static final String PREF_FILE_NAME = "PrefFile";
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
MODE_PRIVATE
is the operating mode for the preferences. It is the default mode and means the created file will be accessed by only the calling application. Other two modes supported are MODE_WORLD_READABLE
and MODE_WORLD_WRITEABLE
. In MODE_WORLD_READABLE
other application can read the created file but can not modify it. In case of MODE_WORLD_WRITEABLE
other applications also have write permissions for the created file.
Finally, once you have the preferences instance, here is how you can retrieve the stored values from the preferences:
int storedPreference = preferences.getInt("storedInt", 0);
To store values in the preference file SharedPreference.Editor
object has to be used. Editor
is a nested interface in the SharedPreference
class.
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();
Editor also supports methods like remove()
and clear()
to delete the preference values from the file.
Activity Preferences:
The shared preferences can be used by other application components. But if you do not need to share the preferences with other components and want to have activity private preferences you can do that with the help of getPreferences()
method of the activity. The getPreference
method uses the getSharedPreferences()
method with the name of the activity class for the preference file name.
Following is the code to get preferences
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
int storedPreference = preferences.getInt("storedInt", 0);
The code to store values is also the same as in case of shared preferences.
SharedPreferences preferences = getPreference(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();
You can also use other methods like storing the activity state in database. Note Android also contains a package called android.preference
. The package defines classes to implement application preferences UI.
To see some more examples check Android's Data Storage post on developers site.
May be You are using pgadmin by connecting remote host then U are trying to update there from your system but it searches for that file in remote system's file system... its the error wat I faced May be its also for u check it
No-one has suggested using std::swap
, yet.
std::swap(a, b);
I don't use any temporary variables and depending on the type of a
and b
the implementation may have a specalization that doesn't either. The implementation should be written knowing whether a 'trick' is appropriate or not. There's no point in trying to second guess.
More generally, I'd probably want to do something like this, as it would work for class types enabling ADL to find a better overload if possible.
using std::swap;
swap(a, b);
Of course, the interviewer's reaction to this answer might say a lot about the vacancy.
String p1 = "example";
String p2 = "example";
String p3 = "example".intern();
String p4 = p2.intern();
String p5 = new String(p3);
String p6 = new String("example");
String p7 = p6.intern();
if (p1 == p2)
System.out.println("p1 and p2 are the same");
if (p1 == p3)
System.out.println("p1 and p3 are the same");
if (p1 == p4)
System.out.println("p1 and p4 are the same");
if (p1 == p5)
System.out.println("p1 and p5 are the same");
if (p1 == p6)
System.out.println("p1 and p6 are the same");
if (p1 == p6.intern())
System.out.println("p1 and p6 are the same when intern is used");
if (p1 == p7)
System.out.println("p1 and p7 are the same");
When two strings are created independently, intern()
allows you to compare them and also it helps you in creating a reference in the string pool if the reference didn't exist before.
When you use String s = new String(hi)
, java creates a new instance of the string, but when you use String s = "hi"
, java checks if there is an instance of word "hi" in the code or not and if it exists, it just returns the reference.
Since comparing strings is based on reference, intern()
helps in you creating a reference and allows you to compare the contents of the strings.
When you use intern()
in the code, it clears of the space used by the string referring to the same object and just returns the reference of the already existing same object in memory.
But in case of p5 when you are using:
String p5 = new String(p3);
Only contents of p3 are copied and p5 is created newly. So it is not interned.
So the output will be:
p1 and p2 are the same
p1 and p3 are the same
p1 and p4 are the same
p1 and p6 are the same when intern is used
p1 and p7 are the same
I think what you're looking for is thenBy.js: https://github.com/Teun/thenBy.js
It allows you to use the standard Array.sort, but with firstBy().thenBy().thenBy()
style.
As mentioned, ArgoUML is a decent tool for UML 1.4 and has recently (Autumn 2008) been receiving some much needed maintainance updates.
Old post I know.. but now you can do this to keep alignment and all looking consistent..
@Html.EditorFor(model => model.myField, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })
Open multiple instances of Toad and execute.
Download the developer edition. There you can choose Express as license when installing.
StringBuilder s = new StringBuilder();
s.append("a");
s.append("a");
// System.out.print(s); is return "aa"
s.delete(0, s.length());
System.out.print(s.length()); // is return 0
is the easy way.
You can Autowire the ApplicationContext, either as a field
@Autowired
private ApplicationContext context;
or a method
@Autowired
public void context(ApplicationContext context) { this.context = context; }
Finally use
context.getBean(SomeClass.class)
May be the solution could be use a padding property.
<div class="well span6" style="padding-top: 50px">
<h3>I wish this appeared on the next line without having to
gratuitously use BR!
</h3>
</div>
If your file starts with the bytes 60, 118, 56, 46 and 49, then you have an ambiguous case. It could be UTF-8 (without BOM) or any of the single byte encodings like ASCII, ANSI, ISO-8859-1 etc.
simplifily, use:
pip install -r requirement.txt
it can install all listed in requirement file.
For identifying a windows machine uniquely. Make sure when you use wmic to have a strategy of alternative methods. Since "wmic bios get serialnumber" might not work on all machines, you might need to have additional methods:
# Get serial number from bios
wmic bios get serialnumber
# If previous fails, get UUID
wmic csproduct get UUID
# If previous fails, get diskdrive serialnumber
wmic DISKDRIVE get SerialNumber
Resources: The Best Way To Uniquely Identify A Windows Machine http://www.nextofwindows.com/the-best-way-to-uniquely-identify-a-windows-machine/
I like the idea of redefining existing tags if they're unused due to the fact that the text is cleaner, at the expense of existing tags. The inline styling works but creates a lot of noise when reading the raw text.
Using VSCode I've found that custom single-letter tags, supported by a small <style>
section at the top, works well with a minimum of noise, especially for spot colour, e.g.
<style>
r { color: Red }
o { color: Orange }
g { color: Green }
</style>
# TODOs:
- <r>TODO:</r> Important thing to do
- <o>TODO:</o> Less important thing to do
- <g>DONE:</g> Breath deeply and improve karma
My use-case is orgmode-ish in-app note taking during development but I guess it might work elsewhere?
I got the answer...this seems to be working perfectly fine
public int[] test ( int[]b )
{
ArrayList<Integer> l = new ArrayList<Integer>();
Object[] returnArrayObject = l.toArray();
int returnArray[] = new int[returnArrayObject.length];
for (int i = 0; i < returnArrayObject.length; i++){
returnArray[i] = (Integer) returnArrayObject[i];
}
return returnArray;
}
function deepclone(obj) {
let newObj = {};
if (typeof obj === 'object') {
for (let key in obj) {
let property = obj[key],
type = typeof property;
switch (type) {
case 'object':
if( Object.prototype.toString.call( property ) === '[object Array]' ) {
newObj[key] = [];
for (let item of property) {
newObj[key].push(this.deepclone(item))
}
} else {
newObj[key] = deepclone(property);
}
break;
default:
newObj[key] = property;
break;
}
}
return newObj
} else {
return obj;
}
}
I ran into this problem on Windows, where calling exec
and spawn
with the exact same command (omitting arguments) worked fine for exec
(so I knew my command was on $PATH
), but spawn
would give ENOENT. Turned out that I just needed to append .exe
to the command I was using:
import { exec, spawn } from 'child_process';
// This works fine
exec('p4 changes -s submitted');
// This gives the ENOENT error
spawn('p4');
// But this resolves it
spawn('p4.exe');
// Even works with the arguments now
spawn('p4.exe', ['changes', '-s', 'submitted']);
When you are dealing with objects, you want to ignore simple id's as much as convenient.
If you change the click line to this, I think you will be well on your way:
<li class="tutorial_title {{tutorial.active}}" ng-click="loadFromMenu(tutorial)" ng-repeat="tutorial in section.tutorials">
Also, I think you may need to change
class="tutorial_title {{tutorial.active}}"
to something like
ng-class="tutorial_title {{tutorial.active}}"
See http://docs.angularjs.org/misc/faq and look for ng-class.
If you're working with .net core, you can use the dotnet CLI, for instance
dotnet add package <package name>
Simply copy all icu****.dll files from
C:\xampp\php
to
C:\xampp\apache\bin
[or]
C:\wamp\bin\php\php5.5.12
to
C:\wamp\bin\apache\apache2.4.9
intl extension will start working!!!
Splits an array in multiple arrays with a fixed maximum size.
public static <T extends Object> List<T[]> splitArray(T[] array, int max){
int x = array.length / max;
int r = (array.length % max); // remainder
int lower = 0;
int upper = 0;
List<T[]> list = new ArrayList<T[]>();
int i=0;
for(i=0; i<x; i++){
upper += max;
list.add(Arrays.copyOfRange(array, lower, upper));
lower = upper;
}
if(r > 0){
list.add(Arrays.copyOfRange(array, lower, (lower + r)));
}
return list;
}
Example - an Array of 11 shall be splitted into multiple Arrays not exceeding a size of 5:
// create and populate an array
Integer[] arr = new Integer[11];
for(int i=0; i<arr.length; i++){
arr[i] = i;
}
// split into pieces with a max. size of 5
List<Integer[]> list = ArrayUtil.splitArray(arr, 5);
// check
for(int i=0; i<list.size(); i++){
System.out.println("Array " + i);
for(int j=0; j<list.get(i).length; j++){
System.out.println(" " + list.get(i)[j]);
}
}
Output:
Array 0
0
1
2
3
4
Array 1
5
6
7
8
9
Array 2
10
Use the System.Web.UI.HtmlTextWriter class.
StringWriter writer = new StringWriter();
HtmlTextWriter html = new HtmlTextWriter(writer);
html.RenderBeginTag(HtmlTextWriterTag.H1);
html.WriteEncodedText("Heading Here");
html.RenderEndTag();
html.WriteEncodedText(String.Format("Dear {0}", userName));
html.WriteBreak();
html.RenderBeginTag(HtmlTextWriterTag.P);
html.WriteEncodedText("First part of the email body goes here");
html.RenderEndTag();
html.Flush();
string htmlString = writer.ToString();
For extensive HTML that includes the creation of style attributes HtmlTextWriter is probably the best way to go. However it can be a bit clunky to use and some developers like the markup itself to be easily read but perversly HtmlTextWriter's choices with regard indentation is a bit wierd.
In this example you can also use XmlTextWriter quite effectively:-
writer = new StringWriter();
XmlTextWriter xml = new XmlTextWriter(writer);
xml.Formatting = Formatting.Indented;
xml.WriteElementString("h1", "Heading Here");
xml.WriteString(String.Format("Dear {0}", userName));
xml.WriteStartElement("br");
xml.WriteEndElement();
xml.WriteElementString("p", "First part of the email body goes here");
xml.Flush();
see here enter link description here
html
<body>
<p>This is a paragraph.</p>
<div id="myPosition">
</div>
</body>
css
#myPosition{
background-color:red;
height:200px;
width:200px;
}
jquery
$(document).ready(function(){
$("#myPosition").click(function(e){
var elm = $(this);
var xPos = e.pageX - elm.offset().left;
var yPos = e.pageY - elm.offset().top;
alert("X position: " + xPos + ", Y position: " + yPos);
});
});
I'm unable to reproduce your problem but have you tried converting it to an integer first?
image_name_data['id'] = image_name_data['id'].astype(int).astype('str')
Then, regarding your more general question you could use map
(as in this answer). In your case:
image_name_data['id'] = image_name_data['id'].map('{:.0f}'.format)
Thank you @mfitzp. In my case (CentOS) these libs are not available in the yum repo, but actually the solution was even easier. What I did:
sudo yum install python-devel
sudo yum install zlib-devel
sudo yum install libjpeg-turbo-devel
And now pillow's installation finishes successfully.
Additional relevant info: A common need is to pass the ID of the object represented by the marker to some ajax call for the purpose of fetching more info from the server.
It seems that when we do:
marker.on('click', function(e) {...
The e
points to a MouseEvent, which does not let us get to the marker object. But there is a built-in this
object which strangely, requires us to use this.options
to get to the options
object which let us pass anything we need. In the above case, we can pass some ID in an option, let's say objid
then within the function above, we can get the value by invoking: this.options.objid
no, the difference between +
and \;
should be reversed. +
appends the files to the end of the exec command then runs the exec command and \;
runs the command for each file.
The problem is find . -type f -iname '*.cpp' -exec mv {} ./test/ \+
should be find . -type f -iname '*.cpp' -exec mv {} ./test/ +
no need to escape it or terminate the +
xargs I haven't used in a long time but I think works like +.
for this question we can also use this method :
Question from sql zoo:
Find all details of the prize won by PETER GRÜNBERG
Non-ASCII characters
ans: select*from nobel where winner like'P% GR%_%berg';
I am not sure what you understand by "execute from the Command line interface", but you're probably looking after the following select statement:
select * from dba_users;
or
select username from dba_users;
A snapshot version in Maven is one that has not been released.
The idea is that before a 1.0
release (or any other release) is done, there exists a 1.0-SNAPSHOT
. That version is what might become 1.0
. It's basically "1.0
under development". This might be close to a real 1.0
release, or pretty far (right after the 0.9
release, for example).
The difference between a "real" version and a snapshot version is that snapshots might get updates. That means that downloading 1.0-SNAPSHOT
today might give a different file than downloading it yesterday or tomorrow.
Usually, snapshot dependencies should only exist during development and no released version (i.e. no non-snapshot) should have a dependency on a snapshot version.
You could try an XPath expression like:
'//div[contains(text(), "{0}") and @class="inner"]'.format(text)
In order to build your repo after new commits, use Bitbucket Plugin.
There is just one thing to notice: When creating a POST Hook (notice that it is POST hook, not Jenkins hook), the URL works when it has a "/" in the end. Like:
URL: JENKINS_URL/bitbucket-hook/
e.g. someAddress:8080/bitbucket-hook/
Do not forget to check "Build when a change is pushed to Bitbucket" in your job configuration.
You can do the following during declaration:
String names[] = {"Ankit","Bohra","Xyz"};
And if you want to do this somewhere after declaration:
String names[];
names = new String[] {"Ankit","Bohra","Xyz"};
The solution is the /Y
switch:
xcopy "C:\Users\ADMIN\Desktop\*.*" "D:\Backup\" /K /D /H /Y
It turns out the trailing slash in the PublishDir property is escaping the end quote. Escaping the trailing slash solved my problem.
/p:PublishDir="\\BSIIS3\c$\DATA\WEBSITES\benesys.net\benesys.net\TotalEducationTest\\"
This way we can use quotes for paths that have whitespace in properties that MSBuild requires the trailing slash.
I know this is an old post, but I feel like I needed to share this with someone :-)
Nice that you brought this subject up.
This is an important thing/concept in git that a lof of git users would benefit from knowing. git rebase is a very powerful tool and enables you to squash commits together, remove commits etc. But as with any powerful tool, you basically need to know what you're doing or something might go really wrong.
When you are working locally and messing around with your local branches, you can do whatever you like as long as you haven't pushed the changes to the central repository. This means you can rewrite your own history, but not others history. By only messing around with your local stuff, nothing will have any impact on other repositories.
This is why it's important to remember that once you have pushed commits, you should not rebase them later on. The reason why this is important, is that other people might pull in your commits and base their work on your contributions to the code base, and if you later on decide to move that content from one place to another (rebase it) and push those changes, then other people will get problems and have to rebase their code. Now imagine you have 1000 developers :) It just causes a lot of unnecessary rework.
Not sure how to explain this but I ran into something similar today.
Not being able to set .user:first-of-type{}
while .user:last-of-type{}
worked fine.
This was fixed after I wrapped them inside a div without any class or styling:
https://codepen.io/adrianTNT/pen/WgEpbE
<style>
.user{
display:block;
background-color:#FFCC00;
}
.user:first-of-type{
background-color:#FF0000;
}
</style>
<p>Not working while this P additional tag exists</p>
<p class="user">A</p>
<p class="user">B</p>
<p class="user">C</p>
<p>Working while inside a div:</p>
<div>
<p class="user">A</p>
<p class="user">B</p>
<p class="user">C</p>
</div>
Use this to limit the depth to 2:
Get-ChildItem \*\*\*,\*\*,\*
The way it works is that it returns the children at each depth 2,1 and 0.
Explanation:
This command
Get-ChildItem \*\*\*
returns all items with a depth of two subfolders. Adding \* adds an additional subfolder to search in.
In line with the OP question, to limit a recursive search using get-childitem you are required to specify all the depths that can be searched.
// open in default browser
Process.Start("http://www.stackoverflow.net");
// open in Internet Explorer
Process.Start("iexplore", @"http://www.stackoverflow.net/");
// open in Firefox
Process.Start("firefox", @"http://www.stackoverflow.net/");
// open in Google Chrome
Process.Start("chrome", @"http://www.stackoverflow.net/");
I know it's an old question, but what I did is not mentioned here.
For me the following worked.
DECLARE @info NVARCHAR(MAX)
--SET @info to something big
PRINT CAST(@info AS NTEXT)
You can provide options as a parameter to format date. First parameter is for locale which you might not need and second is for options. For more info visit https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
var date = new Date(Date.UTC(2012, 1, 1, 3, 0, 0));
var options = { year: 'numeric', month: '2-digit', day: '2-digit' };
console.log(date.toLocaleDateString(undefined,options));
I feel the above answers miss a scenario where this error occurs even when your code has a main(). When you are using JNI that uses Reflection to invoke a method. During runtime if the method is not found, you will get a
java.lang.NoSuchMethodError: No virtual method
In Typescript and ES6 you can also use for..of:
for (var product of products) {
console.log(product.product_desc)
}
which will be transcoded to javascript:
for (var _i = 0, products_1 = products; _i < products_1.length; _i++) {
var product = products_1[_i];
console.log(product.product_desc);
}
What could be easier than something like this:
import tempfile
for i in range(400):
with tempfile.TemporaryFile() as tf:
for j in range(1000):
tf.write('Line {} of file {}'.format(j,i))
That creates 400 temp files and writes 1000 lines to each temp file. It executes in less than 1/2 second on my unremarkable machine. Each temp file of the total is created and deleted as the context manager opens and closes in this case. It is fast, secure, and cross platform.
Using tempfile is a lot better than trying to reinvent it.
Use git gui
, there you can see a list of what changed in your actual commit. You can also use gitk
wich provides an easy interface for reflogs. Just compare between remotes/...
and master
to see, what will be pushed. It provides an interface similar to your screenshot.
Both programs are included in git.
Gathering info from this link stackoverflow-image save doesn't work with chmod 777 and from user azerafati and Loek Bergman
if you were to look under /etc/apache/envvars file you will see something like:
export APACHE_RUN_USER=www-data
export APACHE_RUN_GROUP=www-data
Apache is run under the username 'www-data'
'0755' means the file owner can read/write/execute but group and other users cannot write. so in ur terminal, cd to the folder containing your 'images' folder. then type:
find images -type d -exec chmod 0755 {} \;
find images -type f -exec chmod 0755 {} \;
sudo chown -R www-data:www-data images
you must change persmissions first before changing owner. enter your password when prompted. this will make 'www-data' owner of the images folder.
your upload should now work.
From http://www.toptal.com/javascript/interview-questions:
function isInteger(x) { return (x^0) === x; }
Found it to be the best way to do this.
Yes you can start with the Wikipedia article explaining the Big O notation, which in a nutshell is a way of describing the "efficiency" (upper bound of complexity) of different type of algorithms. Or you can look at an earlier answer where this is explained in simple english
As of python 3.5.2, you can use:
class C(B):
def method(self, arg):
super().method(arg) # This does the same thing as:
# super(C, self).method(arg)
One option would be to create a symbolic link between a subfolder in your storage directory and public directory.
For example
ln -s /path/to/laravel/storage/avatars /path/to/laravel/public/avatars
This is also the method used by Envoyer, a deployment manager built by Taylor Otwell, the developer of Laravel.
Select getdate() -- 2010-02-05 10:03:44.527
-- To get all date format
select CONVERT(VARCHAR(12),getdate(),100) +' '+ 'Date -100- MMM DD YYYY' -- Feb 5 2010
union
select CONVERT(VARCHAR(10),getdate(),101) +' '+ 'Date -101- MM/DDYYYY'
Union
select CONVERT(VARCHAR(10),getdate(),102) +' '+ 'Date -102- YYYY.MM.DD'
Union
select CONVERT(VARCHAR(10),getdate(),103) +' '+ 'Date -103- DD/MM/YYYY'
Union
select CONVERT(VARCHAR(10),getdate(),104) +' '+ 'Date -104- DD.MM.YYYY'
Union
select CONVERT(VARCHAR(10),getdate(),105) +' '+ 'Date -105- DD-MM-YYYY'
Union
select CONVERT(VARCHAR(11),getdate(),106) +' '+ 'Date -106- DD MMM YYYY' --ex: 03 Jan 2007
Union
select CONVERT(VARCHAR(12),getdate(),107) +' '+ 'Date -107- MMM DD,YYYY' --ex: Jan 03, 2007
union
select CONVERT(VARCHAR(12),getdate(),109) +' '+ 'Date -108- MMM DD YYYY' -- Feb 5 2010
union
select CONVERT(VARCHAR(12),getdate(),110) +' '+ 'Date -110- MM-DD-YYYY' --02-05-2010
union
select CONVERT(VARCHAR(10),getdate(),111) +' '+ 'Date -111- YYYY/MM/DD'
union
select CONVERT(VARCHAR(12),getdate(),112) +' '+ 'Date -112- YYYYMMDD' -- 20100205
union
select CONVERT(VARCHAR(12),getdate(),113) +' '+ 'Date -113- DD MMM YYYY' -- 05 Feb 2010
SELECT convert(varchar, getdate(), 20) -- 2010-02-05 10:25:14
SELECT convert(varchar, getdate(), 23) -- 2010-02-05
SELECT convert(varchar, getdate(), 24) -- 10:24:20
SELECT convert(varchar, getdate(), 25) -- 2010-02-05 10:24:34.913
SELECT convert(varchar, getdate(), 21) -- 2010-02-05 10:25:02.990
---==================================
-- To get the time
select CONVERT(VARCHAR(12),getdate(),108) +' '+ 'Date -108- HH:MM:SS' -- 10:05:53
select CONVERT(VARCHAR(12),getdate(),114) +' '+ 'Date -114- HH:MM:SS:MS' -- 10:09:46:223
SELECT convert(varchar, getdate(), 22) -- 02/05/10 10:23:11 AM
----=============================================
SELECT getdate()+1
SELECT month(getdate())+1
SELECT year(getdate())+1
I just wanted to mention that if speed is required, wrapping unutbu's code in scipy's weave.inline and passing an already existing matrix as a parameter yields a 20-fold decrease in the running time.
The code (in rotation_matrix_test.py):
import numpy as np
import timeit
from math import cos, sin, sqrt
import numpy.random as nr
from scipy import weave
def rotation_matrix_weave(axis, theta, mat = None):
if mat == None:
mat = np.eye(3,3)
support = "#include <math.h>"
code = """
double x = sqrt(axis[0] * axis[0] + axis[1] * axis[1] + axis[2] * axis[2]);
double a = cos(theta / 2.0);
double b = -(axis[0] / x) * sin(theta / 2.0);
double c = -(axis[1] / x) * sin(theta / 2.0);
double d = -(axis[2] / x) * sin(theta / 2.0);
mat[0] = a*a + b*b - c*c - d*d;
mat[1] = 2 * (b*c - a*d);
mat[2] = 2 * (b*d + a*c);
mat[3*1 + 0] = 2*(b*c+a*d);
mat[3*1 + 1] = a*a+c*c-b*b-d*d;
mat[3*1 + 2] = 2*(c*d-a*b);
mat[3*2 + 0] = 2*(b*d-a*c);
mat[3*2 + 1] = 2*(c*d+a*b);
mat[3*2 + 2] = a*a+d*d-b*b-c*c;
"""
weave.inline(code, ['axis', 'theta', 'mat'], support_code = support, libraries = ['m'])
return mat
def rotation_matrix_numpy(axis, theta):
mat = np.eye(3,3)
axis = axis/sqrt(np.dot(axis, axis))
a = cos(theta/2.)
b, c, d = -axis*sin(theta/2.)
return np.array([[a*a+b*b-c*c-d*d, 2*(b*c-a*d), 2*(b*d+a*c)],
[2*(b*c+a*d), a*a+c*c-b*b-d*d, 2*(c*d-a*b)],
[2*(b*d-a*c), 2*(c*d+a*b), a*a+d*d-b*b-c*c]])
The timing:
>>> import timeit
>>>
>>> setup = """
... import numpy as np
... import numpy.random as nr
...
... from rotation_matrix_test import rotation_matrix_weave
... from rotation_matrix_test import rotation_matrix_numpy
...
... mat1 = np.eye(3,3)
... theta = nr.random()
... axis = nr.random(3)
... """
>>>
>>> timeit.repeat("rotation_matrix_weave(axis, theta, mat1)", setup=setup, number=100000)
[0.36641597747802734, 0.34883809089660645, 0.3459300994873047]
>>> timeit.repeat("rotation_matrix_numpy(axis, theta)", setup=setup, number=100000)
[7.180983066558838, 7.172032117843628, 7.180462837219238]
Try this:
System.Net.CredentialCache credentialCache = new System.Net.CredentialCache();
credentialCache.Add(
new System.Uri("http://www.yoururl.com/"),
"Basic",
new System.Net.NetworkCredential("username", "password")
);
...
...
httpWebRequest.Credentials = credentialCache;
Sorry for my bad English. Checking Mails using Python with MAPI is easier,
outlook =win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
folder = outlook.Folders[5]
Subfldr = folder.Folders[5]
messages_REACH = Subfldr.Items
message = messages_REACH.GetFirst()
Here we can get the most first mail into the Mail box, or into any sub folder. Actually, we need to check the Mailbox number & orientation. With the help of this analysis we can check each mailbox & its sub mailbox folders.
Similarly please find the below code, where we can see, the last/ earlier mails. How we need to check.
`outlook =win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
folder = outlook.Folders[5]
Subfldr = folder.Folders[5]
messages_REACH = Subfldr.Items
message = messages_REACH.GetLast()`
With this we can get most recent email into the mailbox. According to the above mentioned code, we can check our all mail boxes, & its sub folders.
Since there is so much confusion about functionality of standard service accounts, I'll try to give a quick run down.
First the actual accounts:
LocalService account (preferred)
A limited service account that is very similar to Network Service and meant to run standard least-privileged services. However, unlike Network Service it accesses the network as an Anonymous user.
NT AUTHORITY\LocalService
HKEY_USERS\S-1-5-19
)
Limited service account that is meant to run standard privileged services. This account is far more limited than Local System (or even Administrator) but still has the right to access the network as the machine (see caveat above).
NT AUTHORITY\NetworkService
MANGO$
) to remote serversHKEY_USERS\S-1-5-20
)NETWORK SERVICE
into the Select User or Group dialog
LocalSystem account (dangerous, don't use!)
Completely trusted account, more so than the administrator account. There is nothing on a single box that this account cannot do, and it has the right to access the network as the machine (this requires Active Directory and granting the machine account permissions to something)
.\LocalSystem
(can also use LocalSystem
or ComputerName\LocalSystem
)HKCU
represents the default user)MANGO$
) to remote servers
Above when talking about accessing the network, this refers solely to SPNEGO (Negotiate), NTLM and Kerberos and not to any other authentication mechanism. For example, processing running as LocalService
can still access the internet.
The general issue with running as a standard out of the box account is that if you modify any of the default permissions you're expanding the set of things everything running as that account can do. So if you grant DBO to a database, not only can your service running as Local Service or Network Service access that database but everything else running as those accounts can too. If every developer does this the computer will have a service account that has permissions to do practically anything (more specifically the superset of all of the different additional privileges granted to that account).
It is always preferable from a security perspective to run as your own service account that has precisely the permissions you need to do what your service does and nothing else. However, the cost of this approach is setting up your service account, and managing the password. It's a balancing act that each application needs to manage.
In your specific case, the issue that you are probably seeing is that the the DCOM or COM+ activation is limited to a given set of accounts. In Windows XP SP2, Windows Server 2003, and above the Activation permission was restricted significantly. You should use the Component Services MMC snapin to examine your specific COM object and see the activation permissions. If you're not accessing anything on the network as the machine account you should seriously consider using Local Service (not Local System which is basically the operating system).
In Windows Server 2003 you cannot run a scheduled task as
NT_AUTHORITY\LocalService
(aka the Local Service account), or NT AUTHORITY\NetworkService
(aka the Network Service account). That capability only was added with Task Scheduler 2.0, which only exists in Windows Vista/Windows Server 2008 and newer.
A service running as NetworkService
presents the machine credentials on the network. This means that if your computer was called mango
, it would present as the machine account MANGO$
:
If you care about the sequence of the terms, you may consider using a syntax like
select * from T where C like'%David%Moses%Robi%'
Single line, and only calculating logs once. First convert to log-space, then take the 1-period diff.
np.diff(np.log(df.price))
In earlier versions of numpy:
np.log(df.price)).diff()
If the function is from a source file available on the filesystem, then inspect.getsource(foo)
might be of help:
If foo
is defined as:
def foo(arg1,arg2):
#do something with args
a = arg1 + arg2
return a
Then:
import inspect
lines = inspect.getsource(foo)
print(lines)
Returns:
def foo(arg1,arg2):
#do something with args
a = arg1 + arg2
return a
But I believe that if the function is compiled from a string, stream or imported from a compiled file, then you cannot retrieve its source code.
Firstly freq_series.plot
returns an axis not a figure so to make my answer a little more clear I've changed your given code to refer to it as ax
rather than fig
to be more consistent with other code examples.
You can get the list of the bars produced in the plot from the ax.patches
member. Then you can use the technique demonstrated in this matplotlib
gallery example to add the labels using the ax.text
method.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Bring some raw data.
frequencies = [6, 16, 75, 160, 244, 260, 145, 73, 16, 4, 1]
# In my original code I create a series and run on that,
# so for consistency I create a series from the list.
freq_series = pd.Series.from_array(frequencies)
x_labels = [108300.0, 110540.0, 112780.0, 115020.0, 117260.0, 119500.0,
121740.0, 123980.0, 126220.0, 128460.0, 130700.0]
# Plot the figure.
plt.figure(figsize=(12, 8))
ax = freq_series.plot(kind='bar')
ax.set_title('Amount Frequency')
ax.set_xlabel('Amount ($)')
ax.set_ylabel('Frequency')
ax.set_xticklabels(x_labels)
rects = ax.patches
# Make some labels.
labels = ["label%d" % i for i in xrange(len(rects))]
for rect, label in zip(rects, labels):
height = rect.get_height()
ax.text(rect.get_x() + rect.get_width() / 2, height + 5, label,
ha='center', va='bottom')
This produces a labeled plot that looks like:
I just had an issue where I needed to solve this properly.
Via Ajax, a script gets X (0-10) messages. What I wanted to do: Add one message to the DOM every 10 Seconds.
the code I ended up with:
$.each(messages, function(idx, el){
window.setTimeout(function(){
doSomething(el);
},Math.floor(idx+1)*10000);
});
Basically, think of the timeouts as a "timeline" of your script.
This is what we WANT to code:
DoSomething();
WaitAndDoNothing(5000);
DoSomethingOther();
WaitAndDoNothing(5000);
DoEvenMore();
This is HOW WE NEED TO TELL IT TO THE JAVASCRIPT:
At Runtime 0 : DoSomething();
At Runtime 5000 : DoSomethingOther();
At Runtime 10000: DoEvenMore();
Hope this helps.
The new ASP.NET Web API is a continuation of the previous WCF Web API project (although some of the concepts have changed).
WCF was originally created to enable SOAP-based services. For simpler RESTful or RPCish services (think clients like jQuery) ASP.NET Web API should be good choice.
For us, WCF is used for SOAP and Web API for REST. I wish Web API supported SOAP too. We are not using advanced features of WCF. Here is comparison from MSDN:
ASP.net Web API is all about HTTP and REST based GET,POST,PUT,DELETE with well know ASP.net MVC style of programming and JSON returnable; web API is for all the light weight process and pure HTTP based components. For one to go ahead with WCF even for simple or simplest single web service it will bring all the extra baggage. For light weight simple service for ajax or dynamic calls always WebApi just solves the need. This neatly complements or helps in parallel to the ASP.net MVC.
Check out the podcast : Hanselminutes Podcast 264 - This is not your father's WCF - All about the WebAPI with Glenn Block by Scott Hanselman for more information.
In the scenarios listed below you should go for WCF:
WEB API is a framework for developing RESTful/HTTP services.
There are so many clients that do not understand SOAP like Browsers, HTML5, in those cases WEB APIs are a good choice.
HTTP services header specifies how to secure service, how to cache the information, type of the message body and HTTP body can specify any type of content like HTML not just XML as SOAP services.
You may use this
/^(?:(?:\+|0{0,2})91(\s*|[\-])?|[0]?)?([6789]\d{2}([ -]?)\d{3}([ -]?)\d{4})$/
Valid Entries:
6856438922
7856128945
8945562713
9998564723
+91-9883443344
09883443344
919883443344
0919883443344
+919883443344
+91-9883443344
0091-9883443344
+91 9883443344
+91-785-612-8945
+91 999 856 4723
Invalid Entries:
WAQU9876567892
ABCD9876541212
0226-895623124
0924645236
0222-895612
098-8956124
022-2413184
Validate it at https://regex101.com/
The right answer for this question is "css reset".
* {
margin: 0;
padding: 0;
}
It removes all default margin and padding for every object on the page, no holds barred, regardless of browser.
I know this has already been answered, but if you end doing this a lot, regular expressions may be a better way to go:
>>> import re
>>> re.sub(r'\s', '', string).split(',')
['blah', 'lots', 'of', 'spaces', 'here']
The \s
matches any whitespace character, and we just replace it with an empty string ''
. You can find more info here: http://docs.python.org/library/re.html#re.sub
If all other solutions did not work for your device try this guide how to make a truly universal adb and fastboot driver out of Google USB driver. The resulting driver works for adb
, recovery
and fastboot
modes in all versions of Windows.
You can use simply pd.to_datetime(then)
and pandas will convert the date elements into ISO date format- [YYYY-MM-DD]
.
You can pass this as map/apply to use it in a dataframe/series too.
Go to SETTINGS->Location and Security-> Device Administrator and deselect the admin which you want to uninstall.
Now uninstall the application. If it still says you need to deactivate the application before uninstalling, you may need to Force Stop the application before uninstalling.
If the forked repo is protected so you can't push directly into it, and your goal is to make changes to their foo, then you need to get their branch foo into your repo like so:
git remote add protected_repo https://github.com/theirusername/their_repo.git
git fetch protected_repo
git checkout --no-track protected_repo/foo
Now you have a local copy of foo with no upstream associated to it. You can commit changes to it (or not) and then push your foo to your own remote repo.
git push --set-upstream origin foo
Now foo is in your repo on GitHub and your local foo is tracking it. If they continue to make changes to foo you can fetch theirs and merge into your foo.
git checkout foo
git fetch protected_repo
git merge protected_repo/foo
You can pass multiple arguments to angular filter !
Defining my angular app and and an app level variable -
var app = angular.module('filterApp',[]);
app.value('test_obj', {'TEST' : 'test be check se'});
Your Filter will be like :-
app.filter('testFilter', [ 'test_obj', function(test_obj) {
function test_filter_function(key, dynamic_data) {
if(dynamic_data){
var temp = test_obj[key];
for(var property in dynamic_data){
temp = temp.replace(property, dynamic_data[property]);
}
return temp;
}
else{
return test_obj[key] || key;
}
}
test_filter_function.$stateful = true;
return test_filter_function;
}]);
And from HTML you will send data like :-
<span ng-bind="'TEST' | testFilter: { 'be': val, 'se': value2 }"></span>
Here I am sending a JSON object to the filter. You can also send any kind of data like string or number.
also you can pass dynamic number of arguments to filter , in that case you have to use arguments to get those arguments.
For a working demo go here - passing multiple arguments to angular filter
Kind of an old question, but I can give an answer updated for .NET Core 2.1 with C# 7 standards. Say I have a listing only in appsettings.Development.json such as:
"TestUsers": [
{
"UserName": "TestUser",
"Email": "[email protected]",
"Password": "P@ssw0rd!"
},
{
"UserName": "TestUser2",
"Email": "[email protected]",
"Password": "P@ssw0rd!"
}
]
I can extract them anywhere that the Microsoft.Extensions.Configuration.IConfiguration is implemented and wired up like so:
var testUsers = Configuration.GetSection("TestUsers")
.GetChildren()
.ToList()
//Named tuple returns, new in C# 7
.Select(x =>
(
x.GetValue<string>("UserName"),
x.GetValue<string>("Email"),
x.GetValue<string>("Password")
)
)
.ToList<(string UserName, string Email, string Password)>();
Now I have a list of a well typed object that is well typed. If I go testUsers.First(), Visual Studio should now show options for the 'UserName', 'Email', and 'Password'.
Problem below, is to compare table before and after i do big update!.
If you use Linux, you can use commands as follow:
In terminal,
mysqldump -hlocalhost -uroot -p schema_name_here table_name_here > /home/ubuntu/database_dumps/dump_table_before_running_update.sql
mysqldump -hlocalhost -uroot -p schema_name_here table_name_here > /home/ubuntu/database_dumps/dump_table_after_running_update.sql
diff -uP /home/ubuntu/database_dumps/dump_some_table_after_running_update.sql /home/ubuntu/database_dumps/dump_table_before_running_update.sql > /home/ubuntu/database_dumps/diff.txt
You will need online tools for
e.g http://www.dpriver.com/pp/sqlformat.htm [Not the best I've seen]
We have diff.txt, you have to take manually the + - showing inside, which is 1 line of insert statements, that has the values.
Do diff online for the 2 lines - & + in diff.txt, past them in online diff tool
e.g https://www.diffchecker.com [you can save and share it, and has no limit on file size!]
Note: be extra careful if its sensitive/production data!
You can use jQuery UI and do something like this
Html:
<button id="callConfirm">Confirm!</button>
<div id="dialog" title="Confirmation Required">
Are you sure about this?
</div>?
Javascript:
$("#dialog").dialog({
autoOpen: false,
modal: true,
buttons : {
"Confirm" : function() {
alert("You have confirmed!");
},
"Cancel" : function() {
$(this).dialog("close");
}
}
});
$("#callConfirm").on("click", function(e) {
e.preventDefault();
$("#dialog").dialog("open");
});
?
img
tag and add attributes
manually ,var image = document.createElement("img");
var imageParent = document.getElementById("body");
image.id = "id";
image.className = "class";
image.src = searchPic.src; // image.src = "IMAGE URL/PATH"
imageParent.appendChild(image);
pic1
document["#pic1"].src = searchPic.src;
or with getElementById
document.getElementById("pic1").src= searchPic.src;
$("#pic1").attr("src", searchPic.src);
I to use this type of declaration:
const identity: { <T>(arg: T): T } = (arg) => arg;
It allows defining additional props to your function if you ever need to and in some cases, it helps keeping the function body cleaner from the generic definition.
If you don't need the additional props (namespace sort of thing), it can be simplified to:
const identity: <T>(arg: T) => T = (arg) => arg;
You can use Apache Commons CollectionUtils:
if(CollectionUtils.containsAny(list1,list2)) {
// do whatever you want
} else {
// do other thing
}
This assumes that you have properly overloaded the equals functionality for your custom objects.
The following works for me:
form_for @user, :url => {:action => "YourActionName"}
This answer will cover most of the scenario. I can across this situation when user try to copy paste the phone number
$('#help_number').keyup(function(){
$(this).val().match(/\d+/g).join("")
});
Explanation:
str= "34%^gd 5-67 6-6ds"
str.match(/\d+/g)
It will give a array of string as output >> ["34", "56766"]
str.match(/\d+/g).join("")
join will convert and concatenate that array data into single string
output >> "3456766"
In my example I need the output as 209-356-6788 so I used replace
$('#help_number').keyup(function(){
$(this).val($(this).val().match(/\d+/g).join("").replace(/(\d{3})\-?(\d{3})\-?(\d{4})/,'$1-$2-$3'))
});
Try something like this:
try {
$w = New-Object net.WebClient
$d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
Write-Host $_.Exception.ToString()
}
The exception is in the $_
variable. You might explore $_
like this:
try {
$w = New-Object net.WebClient
$d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
$_ | fl * -Force
}
I think it will give you all the info you need.
My rule: if there is some data that is not displayed, try to use -force
.
//this is only good in .NET 4
//read your file:
List<string> ReadFile = File.ReadAllLines(@"C:\TEMP\FILE.TXT").ToList();
//manipulate data here
foreach(string line in ReadFile)
{
//do something here
}
//write back to your file:
File.WriteAllLines(@"C:\TEMP\FILE2.TXT", ReadFile);
Shortest way is Route facade
\Route::current()->getName()
This also works in laravel 5.4.*
It seems that so far you've just followed the first step of the instructions, headed "Create an offline installation folder". Have you done the second step? "Install from the offline installation folder" - that is, install the certificates and then run vs_Community.exe from inside the folder.
You can loop through the Selection object to see what was selected. Here is a code snippet from Microsoft (http://msdn.microsoft.com/en-us/library/aa203726(office.11).aspx):
Sub Count_Selection()
Dim cell As Object
Dim count As Integer
count = 0
For Each cell In Selection
count = count + 1
Next cell
MsgBox count & " item(s) selected"
End Sub
Had problems with the answers here, so I came up with this, which works for me (TM):
cmd /c node_modules\.bin\tsc
cmd /c node rollup_build.js
pause
By declaring one in your AndroidManifest.xml file with the tag (also called static)
<receiver android:name=".YourBrodcastReceiverClass" android:exported="true">
<intent-filter>
<!-- The actions you wish to listen to, below is an example -->
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
You will notice that the broadcast receiver declared above has a property of exported=”true”. This attribute tells the receiver that it can receive broadcasts from outside the scope of the application.
2. Or dynamically by registering an instance with registerReceiver (what is known as context registered)
public abstract Intent registerReceiver (BroadcastReceiver receiver,
IntentFilter filter);
public void onReceive(Context context, Intent intent) {
//Implement your logic here
}
There are three ways to send broadcasts:
The sendOrderedBroadcast method, makes sure to send broadcasts to only one receiver at a time. Each broadcast can in turn, pass along data to the one following it, or to stop the propagation of the broadcast to the receivers that follow.
The sendBroadcast is similar to the method mentioned above, with one difference. All broadcast receivers receive the message and do not depend on one another.
The LocalBroadcastManager.sendBroadcast method only sends broadcasts to receivers defined inside your application and does not exceed the scope of your application.
I had the same problem with an Angular 6+ app and ASP.NET Core 2.0
I had just previously tried to change the Angular app from CSS to SCSS.
My solution was to go to the src/angularApp
folder and running ng serve
. This helped me realize that I had missed changing the src/styles.css
file to src/styles.scss
The latest specification allows line feed character, so a simple line break inside the attribute or entity
(note that characters #
and ;
are required) are OK.
Checkout a project called Uploadify. http://www.uploadify.com/
It's a Flash + jQuery based file uploader. This uses Flash's file selection dialog, which gives you the ability to filter file types, select multiple files at the same time, etc.
This worked for me ....
#include <stdio.h>
#include <time.h> /* Needed for struct timespec */
int nsleep(long miliseconds)
{
struct timespec req, rem;
if(miliseconds > 999)
{
req.tv_sec = (int)(miliseconds / 1000); /* Must be Non-Negative */
req.tv_nsec = (miliseconds - ((long)req.tv_sec * 1000)) * 1000000; /* Must be in range of 0 to 999999999 */
}
else
{
req.tv_sec = 0; /* Must be Non-Negative */
req.tv_nsec = miliseconds * 1000000; /* Must be in range of 0 to 999999999 */
}
return nanosleep(&req , &rem);
}
int main()
{
int ret = nsleep(2500);
printf("sleep result %d\n",ret);
return 0;
}
I believe it is more to do with how your network is configured. Servlet is simply giving you the address it is finding.
I can suggest two workarounds. First try using IPV4. See this SO Answer
Also, try using the request.getRemoteHost() method to get the names of the machines. Surely the names are independent of whatever IP they are mapped to.
I still think you should discuss this with your infrastructure guys.
The two code segments work the same. However, unsigned int" route is correct. Using unsigned int types will work better with the vector in the instance you used it. Calling the size() member function on a vector returns an unsigned integer value, so you want to be comparing the variable "i" to a value of its own type.
Also, if you are still a little uneasy about how "unsigned int" looks in your code, try "uint". This is basically a shortened version of "unsigned int" and it works exactly the same. You also don't need to include other headers to use it.
I hope this is what you are looking for.
class Try:
def do_somthing(self):
print 'Hello'
if __name__ == '__main__':
obj_list = []
for obj in range(10):
obj = Try()
obj_list.append(obj)
obj_list[0].do_somthing()
Output:
Hello
Database first approach example:
Without writing any code: ASP.NET MVC / MVC3 Database First Approach / Database first
And I think it is better than other approaches because data loss is less with this approach.
Why not use the following: (from Draw custom Back button on iPhone Navigation Bar)
// Add left
UINavigationItem *previousItem = [[UINavigationItem alloc] initWithTitle:@"Back title"];
UINavigationItem *currentItem = [[UINavigationItem alloc] initWithTitle:@"Main Title"];
[self.navigationController.navigationBar setItems:[NSArray arrayWithObjects:previousItem, currentItem, nil] animated:YES];
// set the delegate to self
[self.navigationController.navigationBar setDelegate:self];
Download commons-net binary from here. Extract the files and reference the commons-net-x.x.jar file.
I believe this thread hasn't done in particular justice to HBase and Pig in particular. While I believe Hadoop is the choice of the distributed, resilient file-system for big-data lake implementations, the choice between HBase and Hive is in particular well-segregated.
As in, a lot of use-cases have a particular requirement of SQL like or No-SQL like interfaces. With Phoenix on top of HBase, though SQL like capabilities is certainly achievable, however, the performance, third-party integrations, dashboard update are a kind of painful experiences. However, it's an excellent choice for databases requiring horizontal scaling.
Pig is in particular excellent for non-recursive batch like computations or ETL pipelining (somewhere, where it outperforms Spark by a comfortable distance). Also, it's high-level dataflow implementations is an excellent choice for batch querying and scripting. The choice between Pig and Hive is also pivoted on the need of the client or server-side scripting, required file formats, etc. Pig supports Avro file format which is not true in the case of Hive. The choice for 'procedural dataflow language' vs 'declarative data flow language' is also a strong argument for the choice between pig and hive.
What you want to do is separate the content of the table from the header of the table.
You want only the <th>
elements to be scrolled.
You can easily define this separation in HTML with the <tbody>
and the <thead>
elements.
Now the header and the body of the table are still connected to each other, they will still have the same width (and same scroll properties). Now to let them not 'work' as a table anymore you can set the display: block
. This way <thead>
and <tbody>
are separated.
table tbody, table thead
{
display: block;
}
Now you can set the scroll to the body of the table:
table tbody
{
overflow: auto;
height: 100px;
}
And last, because the <thead>
doesn't share the same width as the body anymore, you should set a static width to the header of the table:
th
{
width: 72px;
}
You should also set a static width for <td>
. This solves the issue of the unaligned columns.
td
{
width: 72px;
}
<tr>
element, that includes the header row:
<tr>
<th>head1</th>
<th>head2</th>
<th>head3</th>
<th>head4</th>
</tr>
I hope this is what you meant.
Addendum
If you would like to have more control over the column widths, have them to vary in width between each other, and course keep the header and body columns aligned, you can use the following example:
table th:nth-child(1), td:nth-child(1) { min-width: 50px; max-width: 50px; }
table th:nth-child(2), td:nth-child(2) { min-width: 100px; max-width: 100px; }
table th:nth-child(3), td:nth-child(3) { min-width: 150px; max-width: 150px; }
table th:nth-child(4), td:nth-child(4) { min-width: 200px; max-width: 200px; }
If you simply open the file for writing with the truncate-option, you'll delete the content.
std::ofstream ofs;
ofs.open("test.txt", std::ofstream::out | std::ofstream::trunc);
ofs.close();
The best way to print pdf automatically from C# is using printer's "direct pdf". You just need to copy the pdf file to printer's network sharename. The rest will be taken care by printer itself.
The speed is 10 times faster than any other methods. However, the requirements are the printer model supporting for direct pdf printing and having at least 128 MB Dram which is easy for any modern printer.
#include <sstream>
#include <vector>
const char *input = "1,1,1,1,2,1,1,1,0";
int main() {
std::stringstream ss(input);
std::vector<int> output;
int i;
while (ss >> i) {
output.push_back(i);
ss.ignore(1);
}
}
Bad input (for instance consecutive separators) will mess this up, but you did say simple.
npm init
It is all you need. It will create the package.json file on the fly for you.
You can look in sys.types or use TYPE_ID:
IF TYPE_ID(N'MyType') IS NULL ...
Just a precaution: using type_id won't verify that the type is a table type--just that a type by that name exists. Otherwise gbn's query is probably better.
Your adb connection is broken.
close eclipse
open cmd-prompt type adb kill-server then adb start-server
reopen eclipse
run the project!
for me i found some solutions: it is a working solution
@echo off
title a game for youtube
explorer "https://thepythoncoding.blogspot.com/2020/11/how-to-echo-with-different-colors-in.html"
SETLOCAL EnableDelayedExpansion
for /F "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do (
set "DEL=%%a"
)
echo say the name of the colors, don't read
call :ColorText 0a "blue"
call :ColorText 0C "green"
call :ColorText 0b "red"
echo(
call :ColorText 19 "yellow"
call :ColorText 2F "black"
call :ColorText 4e "white"
goto :Beginoffile
:ColorText
echo off
<nul set /p ".=%DEL%" > "%~2"
findstr /v /a:%1 /R "^$" "%~2" nul
del "%~2" > nul 2>&1
goto :eof
:Beginoffile
** Update ** A scalars converter has been added to retrofit that allows for a String
response with less ceremony than my original answer below.
Example interface --
public interface GitHubService {
@GET("/users/{user}")
Call<String> listRepos(@Path("user") String user);
}
Add the ScalarsConverterFactory
to your retrofit builder. Note: If using ScalarsConverterFactory
and another factory, add the scalars factory first.
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(ScalarsConverterFactory.create())
// add other factories here, if needed.
.build();
You will also need to include the scalars converter in your gradle file --
implementation 'com.squareup.retrofit2:converter-scalars:2.1.0'
--- Original Answer (still works, just more code) ---
I agree with @CommonsWare that it seems a bit odd that you want to intercept the request to process the JSON yourself. Most of the time the POJO has all the data you need, so no need to mess around in JSONObject
land. I suspect your specific problem might be better solved using a custom gson TypeAdapter
or a retrofit Converter
if you need to manipulate the JSON. However, retrofit provides more the just JSON parsing via Gson. It also manages a lot of the other tedious tasks involved in REST requests. Just because you don't want to use one of the features, doesn't mean you have to throw the whole thing out. There are times you just want to get the raw stream, so here is how to do it -
First, if you are using Retrofit 2, you should start using the Call
API. Instead of sending an object to convert as the type parameter, use ResponseBody
from okhttp --
public interface GitHubService {
@GET("/users/{user}")
Call<ResponseBody> listRepos(@Path("user") String user);
}
then you can create and execute your call --
GitHubService service = retrofit.create(GitHubService.class);
Call<ResponseBody> result = service.listRepos(username);
result.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Response<ResponseBody> response) {
try {
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Throwable t) {
e.printStackTrace();
}
});
Note The code above calls string()
on the response object, which reads the entire response into a String. If you are passing the body off to something that can ingest streams, you can call charStream()
instead. See the ResponseBody
docs.
I've been using BBEdit for years. It's rock-solid, fast, and integrates into my Xcode workflow decently well. (I'm not sure anything integrates into Xcode as well as the built-in editor, but who has time to wait for the built-in editor?)
For small team projects which don't use a source control system, or for single user editing on multiple machines, SubEthaEdit comes highly recommended.
The solution for me was to update guest additions
(click Devices -> Insert Guest Additions CD image)
You might be better asking this on the WiX-users mailing list.
WiX is best used with a firm understanding of what Windows Installer is doing. You might consider getting "The Definitive Guide to Windows Installer".
The action that removes an existing product is the RemoveExistingProducts action. Because the consequences of what it does depends on where it's scheduled - namely, whether a failure causes the old product to be reinstalled, and whether unchanged files are copied again - you have to schedule it yourself.
RemoveExistingProducts
processes <Upgrade>
elements in the current installation, matching the @Id
attribute to the UpgradeCode
(specified in the <Product>
element) of all the installed products on the system. The UpgradeCode
defines a family of related products. Any products which have this UpgradeCode, whose versions fall into the range specified, and where the UpgradeVersion/@OnlyDetect
attribute is no
(or is omitted), will be removed.
The documentation for RemoveExistingProducts
mentions setting the UPGRADINGPRODUCTCODE
property. It means that the uninstall process for the product being removed receives that property, whose value is the Product/@Id
for the product being installed.
If your original installation did not include an UpgradeCode
, you will not be able to use this feature.
I'll do my best to explain it here on simple terms, but be warned that this topic takes my students a couple of months to finally grasp. You can find more information on the Chapter 2 of the Data Structures and Algorithms in Java book.
There is no mechanical procedure that can be used to get the BigOh.
As a "cookbook", to obtain the BigOh from a piece of code you first need to realize that you are creating a math formula to count how many steps of computations get executed given an input of some size.
The purpose is simple: to compare algorithms from a theoretical point of view, without the need to execute the code. The lesser the number of steps, the faster the algorithm.
For example, let's say you have this piece of code:
int sum(int* data, int N) {
int result = 0; // 1
for (int i = 0; i < N; i++) { // 2
result += data[i]; // 3
}
return result; // 4
}
This function returns the sum of all the elements of the array, and we want to create a formula to count the computational complexity of that function:
Number_Of_Steps = f(N)
So we have f(N)
, a function to count the number of computational steps. The input of the function is the size of the structure to process. It means that this function is called such as:
Number_Of_Steps = f(data.length)
The parameter N
takes the data.length
value. Now we need the actual definition of the function f()
. This is done from the source code, in which each interesting line is numbered from 1 to 4.
There are many ways to calculate the BigOh. From this point forward we are going to assume that every sentence that doesn't depend on the size of the input data takes a constant C
number computational steps.
We are going to add the individual number of steps of the function, and neither the local variable declaration nor the return statement depends on the size of the data
array.
That means that lines 1 and 4 takes C amount of steps each, and the function is somewhat like this:
f(N) = C + ??? + C
The next part is to define the value of the for
statement. Remember that we are counting the number of computational steps, meaning that the body of the for
statement gets executed N
times. That's the same as adding C
, N
times:
f(N) = C + (C + C + ... + C) + C = C + N * C + C
There is no mechanical rule to count how many times the body of the for
gets executed, you need to count it by looking at what does the code do. To simplify the calculations, we are ignoring the variable initialization, condition and increment parts of the for
statement.
To get the actual BigOh we need the Asymptotic analysis of the function. This is roughly done like this:
C
.f()
get the polynomium in its standard form
.N
approaches infinity
.Our f()
has two terms:
f(N) = 2 * C * N ^ 0 + 1 * C * N ^ 1
Taking away all the C
constants and redundant parts:
f(N) = 1 + N ^ 1
Since the last term is the one which grows bigger when f()
approaches infinity (think on limits) this is the BigOh argument, and the sum()
function has a BigOh of:
O(N)
There are a few tricks to solve some tricky ones: use summations whenever you can.
As an example, this code can be easily solved using summations:
for (i = 0; i < 2*n; i += 2) { // 1
for (j=n; j > i; j--) { // 2
foo(); // 3
}
}
The first thing you needed to be asked is the order of execution of foo()
. While the usual is to be O(1)
, you need to ask your professors about it. O(1)
means (almost, mostly) constant C
, independent of the size N
.
The for
statement on the sentence number one is tricky. While the index ends at 2 * N
, the increment is done by two. That means that the first for
gets executed only N
steps, and we need to divide the count by two.
f(N) = Summation(i from 1 to 2 * N / 2)( ... ) =
= Summation(i from 1 to N)( ... )
The sentence number two is even trickier since it depends on the value of i
. Take a look: the index i takes the values: 0, 2, 4, 6, 8, ..., 2 * N, and the second for
get executed: N times the first one, N - 2 the second, N - 4 the third... up to the N / 2 stage, on which the second for
never gets executed.
On formula, that means:
f(N) = Summation(i from 1 to N)( Summation(j = ???)( ) )
Again, we are counting the number of steps. And by definition, every summation should always start at one, and end at a number bigger-or-equal than one.
f(N) = Summation(i from 1 to N)( Summation(j = 1 to (N - (i - 1) * 2)( C ) )
(We are assuming that foo()
is O(1)
and takes C
steps.)
We have a problem here: when i
takes the value N / 2 + 1
upwards, the inner Summation ends at a negative number! That's impossible and wrong. We need to split the summation in two, being the pivotal point the moment i
takes N / 2 + 1
.
f(N) = Summation(i from 1 to N / 2)( Summation(j = 1 to (N - (i - 1) * 2)) * ( C ) ) + Summation(i from 1 to N / 2) * ( C )
Since the pivotal moment i > N / 2
, the inner for
won't get executed, and we are assuming a constant C execution complexity on its body.
Now the summations can be simplified using some identity rules:
w
)Applying some algebra:
f(N) = Summation(i from 1 to N / 2)( (N - (i - 1) * 2) * ( C ) ) + (N / 2)( C )
f(N) = C * Summation(i from 1 to N / 2)( (N - (i - 1) * 2)) + (N / 2)( C )
f(N) = C * (Summation(i from 1 to N / 2)( N ) - Summation(i from 1 to N / 2)( (i - 1) * 2)) + (N / 2)( C )
f(N) = C * (( N ^ 2 / 2 ) - 2 * Summation(i from 1 to N / 2)( i - 1 )) + (N / 2)( C )
=> Summation(i from 1 to N / 2)( i - 1 ) = Summation(i from 1 to N / 2 - 1)( i )
f(N) = C * (( N ^ 2 / 2 ) - 2 * Summation(i from 1 to N / 2 - 1)( i )) + (N / 2)( C )
f(N) = C * (( N ^ 2 / 2 ) - 2 * ( (N / 2 - 1) * (N / 2 - 1 + 1) / 2) ) + (N / 2)( C )
=> (N / 2 - 1) * (N / 2 - 1 + 1) / 2 =
(N / 2 - 1) * (N / 2) / 2 =
((N ^ 2 / 4) - (N / 2)) / 2 =
(N ^ 2 / 8) - (N / 4)
f(N) = C * (( N ^ 2 / 2 ) - 2 * ( (N ^ 2 / 8) - (N / 4) )) + (N / 2)( C )
f(N) = C * (( N ^ 2 / 2 ) - ( (N ^ 2 / 4) - (N / 2) )) + (N / 2)( C )
f(N) = C * (( N ^ 2 / 2 ) - (N ^ 2 / 4) + (N / 2)) + (N / 2)( C )
f(N) = C * ( N ^ 2 / 4 ) + C * (N / 2) + C * (N / 2)
f(N) = C * ( N ^ 2 / 4 ) + 2 * C * (N / 2)
f(N) = C * ( N ^ 2 / 4 ) + C * N
f(N) = C * 1/4 * N ^ 2 + C * N
And the BigOh is:
O(N²)
For me, the problem was I had two installations of Apache Tomcat
The following steps solved my problem:
Briefly, the error means that you can't use a static library to be linked w/ a dynamic one.
The correct way is to have a libavcodec
compiled into a .so
instead of .a
, so the other .so
library you are trying to build will link well.
The shortest way to do so is to add --enable-shared
at ./configure
options. Or even you may try to disable shared (or static) libraries at all... you choose what is suitable for you!
When you click on compose email in Gmail notice that the url changes from https://mail.google.com/mail/u/0/#inbox to https://mail.google.com/mail/u/0/#inbox?compose=new. Now when you enter say a email id [email protected] , the value for compose changes now the url became https://mail.google.com/mail/u/0/#inbox?compose=150b0f7ffb682642.
So this is working fine with my html hyperlink until the account is signed in, but if the account is not signed in it would take me the login page and when I enter the credentials somehow this compose value is lost and this does not work.
It is not possible to write the implementation of a template class in a separate cpp file and compile. All the ways to do so, if anyone claims, are workarounds to mimic the usage of separate cpp file but practically if you intend to write a template class library and distribute it with header and lib files to hide the implementation, it is simply not possible.
To know why, let us look at the compilation process. The header files are never compiled. They are only preprocessed. The preprocessed code is then clubbed with the cpp file which is actually compiled. Now if the compiler has to generate the appropriate memory layout for the object it needs to know the data type of the template class.
Actually it must be understood that template class is not a class at all but a template for a class the declaration and definition of which is generated by the compiler at compile time after getting the information of the data type from the argument. As long as the memory layout cannot be created, the instructions for the method definition cannot be generated. Remember the first argument of the class method is the 'this' operator. All class methods are converted into individual methods with name mangling and the first parameter as the object which it operates on. The 'this' argument is which actually tells about size of the object which incase of template class is unavailable for the compiler unless the user instantiates the object with a valid type argument. In this case if you put the method definitions in a separate cpp file and try to compile it the object file itself will not be generated with the class information. The compilation will not fail, it would generate the object file but it won't generate any code for the template class in the object file. This is the reason why the linker is unable to find the symbols in the object files and the build fails.
Now what is the alternative to hide important implementation details? As we all know the main objective behind separating interface from implementation is hiding implementation details in binary form. This is where you must separate the data structures and algorithms. Your template classes must represent only data structures not the algorithms. This enables you to hide more valuable implementation details in separate non-templatized class libraries, the classes inside which would work on the template classes or just use them to hold data. The template class would actually contain less code to assign, get and set data. Rest of the work would be done by the algorithm classes.
I hope this discussion would be helpful.
Short answer No. CSS is not specific to brands.
Below are the articles to implement for iOS using media only.
https://css-tricks.com/snippets/css/media-queries-for-standard-devices/
http://stephen.io/mediaqueries/
Infact you can use PHP, Javascript to detect the iOS browser and according to that you can call CSS file. For instance
NOTE: Community Edition doesn't support JEE.
First, you will need to install a local Tomcat server. It sounds like you may have already done this.
Next, on the toolbar at the top of IntelliJ, click the down arrow just to the left of the Run and Debug icons. There will be an option to Edit Configurations. In the resulting popup, click the Add icon, then click Tomcat and Local.
From that dialog, you will need to click the Configure... button next to Application Server to tell IntelliJ where Tomcat is installed.
Maybe http://plugins.jquery.com/query-object/?
This is the fork of it https://github.com/sousk/jquery.parsequery#readme.
Dont work for me, need to put scope in plural
validates_uniqueness_of :teacher_id, :scopes => [:semester_id, :class_id]
You can try this:
header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
header("Connection: close");
Hopefully it will help prevent Cache, if any!
Place mysql-connector-java-5.1.6-bin.jar to the \Apache Tomcat 6.0.18\lib folder. Your problem will be solved.
$options = array(
'options' => array('min_range' => 0)
);
if (filter_var($int, FILTER_VALIDATE_INT, $options) !== FALSE) {
// you're good
}
Here is my solution with C# in Unity.
private bool _isPointOnLine( Vector2 ptLineStart, Vector2 ptLineEnd, Vector2 ptPoint )
{
bool bRes = false;
if((Mathf.Approximately(ptPoint.x, ptLineStart.x) || Mathf.Approximately(ptPoint.x, ptLineEnd.x)))
{
if(ptPoint.y > ptLineStart.y && ptPoint.y < ptLineEnd.y)
{
bRes = true;
}
}
else if((Mathf.Approximately(ptPoint.y, ptLineStart.y) || Mathf.Approximately(ptPoint.y, ptLineEnd.y)))
{
if(ptPoint.x > ptLineStart.x && ptPoint.x < ptLineEnd.x)
{
bRes = true;
}
}
return bRes;
}
openssl pkcs12 -inkey bob_key.pem -in bob_cert.cert -export -out bob_pfx.pfx
There is always parsing by hand
>>> import re
>>> ts = ['00:00:00,000', '00:00:10,000', '00:01:04,000', '01:01:09,000']
>>> for t in ts:
... times = map(int, re.split(r"[:,]", t))
... print t, times[0]*3600+times[1]*60+times[2]+times[3]/1000.
...
00:00:00,000 0.0
00:00:10,000 10.0
00:01:04,000 64.0
01:01:09,000 3669.0
>>>
I know it's a bit old question but still people try to find efficient solution so instead you should use FULLTEXT index (it's available from MySQL 5.6.4).
Query on table with +35mil records by triple like
in where block took ~2.5s but after adding index on these fields and using BOOLEAN MODE inside match ... against ...
it took only 0.05s.
All Kafka brokers must be assigned a broker.id
. On startup a broker will create an ephemeral node in Zookeeper with a path of /broker/ids/$id
. As the node is ephemeral it will be removed as soon as the broker disconnects, e.g. by shutting down.
You can view the list of the ephemeral broker nodes like so:
echo dump | nc localhost 2181 | grep brokers
The ZooKeeper client interface exposes a number of commands; dump
lists all the sessions and ephemeral nodes for the cluster.
Note, the above assumes:
2181
) on localhost
, and that localhost
is the leader for the clusterzookeeper.connect
Kafka config doesn't specify a chroot env for your Kafka cluster i.e. it's just host:port
and not host:port/path
I was running into a similar, but not exactly the same issue with swagger. Hopefully this helps someone else.
I was using a custom document title and was not changing the folder path in the SwaggerEndPoint to match the document title. If you leave the endpoint pointing to swagger/v1/swagger.json it won't find the json file in the swagger UI.
Example:
services.AddSwaggerGen(swagger =>
{
swagger.SwaggerDoc("AppAdministration", new Info { Title = "App Administration API", Version = "v1.0" });
});
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/AppAdministration/swagger.json", "App Administration");
});
you can use Random.Next() also to generate a random number. you can see the MSDN link: http://msdn.microsoft.com/en-us/library/9b3ta19y.aspx
The error I referenced was generated in system/libraries/Input.php (about line 215 - look for function _clean_input_keys($str).
The regex there does not allow for the dot character in an index. I changed it so it would.
I had originally asked myself the question "Do I need a PDB file deployed to my customer's machine?", and after reading this post, decided to exclude the file.
Everything worked fine, until today, when I was trying to figure out why a message box containing an Exception.StackTrace
was missing the file and line number information - necessary for troubleshooting the exception. I re-read this post and found the key nugget of information: that although the PDB is not necessary for the app to run, it is necessary for the file and line numbers to be present in the StackTrace
string. I included the PDB file in the executable folder and now all is fine.
I know its been a while since the original post but I like using CTE's and this worked for me:
WITH cte_table_a
AS
(
SELECT [id] [id]
, MAX([value]) [value]
FROM table_a
GROUP BY [id]
)
UPDATE table_b
SET table_b.code = CASE WHEN cte_table_a.[value] IS NOT NULL THEN cte_table_a.[value] ELSE 124 END
FROM table_b
LEFT OUTER JOIN cte_table_a
ON table_b.id = cte_table_a.id
Try this:
package javaapplicationtest;
public class Main {
public static void main(String[] args) {
String source = "mango";
boolean isPalindrome = true;
//looping through the string and checking char by char from reverse
for(int loop = 0; loop < source.length(); loop++){
if( source.charAt(loop) != source.charAt(source.length()-loop-1)){
isPalindrome = false;
break;
}
}
if(isPalindrome == false){
System.out.println("Not a palindrome");
}
else
System.out.println("Pailndrome");
}
}
A literal translation of the mathematical definition is quite adequate in a lot of cases (remembering that Python will automatically use big number arithmetic):
from math import factorial
def calculate_combinations(n, r):
return factorial(n) // factorial(r) // factorial(n-r)
For some inputs I tested (e.g. n=1000 r=500) this was more than 10 times faster than the one liner reduce
suggested in another (currently highest voted) answer. On the other hand, it is out-performed by the snippit provided by @J.F. Sebastian.
To add new ViewController
once you have have an existing ViewController
, follow below step:
Click on background of Main.storyboard
.
Search and select ViewController
from object library at the
utility window.
Drag and drop it in background to create a new ViewController
.
public Date addMonths(String dateAsString, int nbMonths) throws ParseException {
String format = "MM/dd/yyyy" ;
SimpleDateFormat sdf = new SimpleDateFormat(format) ;
Date dateAsObj = sdf.parse(dateAsString) ;
Calendar cal = Calendar.getInstance();
cal.setTime(dateAsObj);
cal.add(Calendar.MONTH, nbMonths);
Date dateAsObjAfterAMonth = cal.getTime() ;
System.out.println(sdf.format(dateAsObjAfterAMonth));
return dateAsObjAfterAMonth ;
}`
My BASIC interpreter chops beginning and ending quotes with
str->pop_back();
str->erase(str->begin());
Of course, I always expect well-formed BASIC style strings, so I will abort with failed assert
if not:
assert(str->front() == '"' && str->back() == '"');
Just my two cents.
This should work for you: Set the height to 100% in your css for the html
and body
elements. You can then adjust the height to your needs in the div
.
html {
height: 100%;
}
body {
height: 100%;
}
div {
height: 100%; /* Set Div Height */
}
2019 Update:
While Python-iOS development is relatively immature and likely will prevent (afaik) your app from having native UI and functionality that could be achieved in an Apple-supported development language, Apple now seems to allow embedding Python interpreters in Native Swift/Obj-C apps.
This supports importing Python libraries and running Python scripts (even with supplied command-line arguments) directly from your Native Swift/Obj-C code.
My company is actually wrapping our infrastructure (originally written in Python) in a native iOS application! It works very well and communication between the parts can be easily achieved via a client-server model.
Here is a nice library by Beeware with a cookiecutter template if you want to try and run Python scripts in your iOS app: https://github.com/beeware/Python-Apple-support/tree/3.6.
You can create an object with keys as the unique value corresponding for each object in array and then filter each array based on existence of the key in other's object. It reduces the complexity of the operation.
ES6
let a = [{ value:"4a55eff3-1e0d-4a81-9105-3ddd7521d642", display:"Jamsheer"}, { value:"644838b3-604d-4899-8b78-09e4799f586f", display:"Muhammed"}, { value:"b6ee537a-375c-45bd-b9d4-4dd84a75041d", display:"Ravi"}, { value:"e97339e1-939d-47ab-974c-1b68c9cfb536", display:"Ajmal"}, { value:"a63a6f77-c637-454e-abf2-dfb9b543af6c", display:"Ryan"}];_x000D_
let b = [{ value:"4a55eff3-1e0d-4a81-9105-3ddd7521d642", display:"Jamsheer", $$hashKey:"008"}, { value:"644838b3-604d-4899-8b78-09e4799f586f", display:"Muhammed", $$hashKey:"009"}, { value:"b6ee537a-375c-45bd-b9d4-4dd84a75041d", display:"Ravi", $$hashKey:"00A"}, { value:"e97339e1-939d-47ab-974c-1b68c9cfb536", display:"Ajmal", $$hashKey:"00B"}];_x000D_
_x000D_
let valuesA = a.reduce((a,{value}) => Object.assign(a, {[value]:value}), {});_x000D_
let valuesB = b.reduce((a,{value}) => Object.assign(a, {[value]:value}), {});_x000D_
let result = [...a.filter(({value}) => !valuesB[value]), ...b.filter(({value}) => !valuesA[value])];_x000D_
console.log(result);
_x000D_
ES5
var a = [{ value:"4a55eff3-1e0d-4a81-9105-3ddd7521d642", display:"Jamsheer"}, { value:"644838b3-604d-4899-8b78-09e4799f586f", display:"Muhammed"}, { value:"b6ee537a-375c-45bd-b9d4-4dd84a75041d", display:"Ravi"}, { value:"e97339e1-939d-47ab-974c-1b68c9cfb536", display:"Ajmal"}, { value:"a63a6f77-c637-454e-abf2-dfb9b543af6c", display:"Ryan"}];_x000D_
var b = [{ value:"4a55eff3-1e0d-4a81-9105-3ddd7521d642", display:"Jamsheer", $$hashKey:"008"}, { value:"644838b3-604d-4899-8b78-09e4799f586f", display:"Muhammed", $$hashKey:"009"}, { value:"b6ee537a-375c-45bd-b9d4-4dd84a75041d", display:"Ravi", $$hashKey:"00A"}, { value:"e97339e1-939d-47ab-974c-1b68c9cfb536", display:"Ajmal", $$hashKey:"00B"}];_x000D_
_x000D_
var valuesA = a.reduce(function(a,c){a[c.value] = c.value; return a; }, {});_x000D_
var valuesB = b.reduce(function(a,c){a[c.value] = c.value; return a; }, {});_x000D_
var result = a.filter(function(c){ return !valuesB[c.value]}).concat(b.filter(function(c){ return !valuesA[c.value]}));_x000D_
console.log(result);
_x000D_
set Text box Border style to None then write this code to container form "paint" event
private void Form1_Paint(object sender, PaintEventArgs e)
{
System.Drawing.Rectangle rect = new Rectangle(TextBox1.Location.X,
TextBox1.Location.Y, TextBox1.ClientSize.Width, TextBox1.ClientSize.Height);
rect.Inflate(1, 1); // border thickness
System.Windows.Forms.ControlPaint.DrawBorder(e.Graphics, rect,
Color.DeepSkyBlue, ButtonBorderStyle.Solid);
}
Looking at your code, you need to set the frame of the movie player controller's view, and also add the movie player controller's view to your view. Also, don't forget to add MediaPlayer.framework to your target.
Here's some sample code:
#import <MediaPlayer/MediaPlayer.h>
@interface ViewController () {
MPMoviePlayerController *moviePlayerController;
}
@property (weak, nonatomic) IBOutlet UIView *movieView; // this should point to a view where the movie will play
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// Instantiate a movie player controller and add it to your view
NSString *moviePath = [[NSBundle mainBundle] pathForResource:@"foo" ofType:@"mov"];
NSURL *movieURL = [NSURL fileURLWithPath:moviePath];
moviePlayerController = [[MPMoviePlayerController alloc] initWithContentURL:movieURL];
[moviePlayerController.view setFrame:self.movieView.bounds]; // player's frame must match parent's
[self.movieView addSubview:moviePlayerController.view];
// Configure the movie player controller
moviePlayerController.controlStyle = MPMovieControlStyleNone;
[moviePlayerController prepareToPlay];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
// Start the movie
[moviePlayerController play];
}
@end