Since there are so many possibilities for what might be wrong. Here's another possibility to look at. I ran into something where I had set up my own roles on a database. (For instance, "Administrator", "Manager", "DataEntry", "Customer", each with their own kinds of limitations) The only ones who could use it were "Manager" role or above--because they were also set up as sysadmin because they were adding users to the database (and they were highly trusted). Also, the users that were being added were Windows Domain users--using their domain credentials. (Everyone with access to the database had to be on our domain, but not everyone on the domain had access to the database--and only a few of them had access to change it.)
Anyway, this working system suddenly stopped working and I was getting error messages similar to the above. What I ended up doing that solved it was to go through all the permissions for the "public" role in that database and add those permissions to all of the roles that I had created. I know that everyone is supposed to be in the "public" role even though you can't add them (or rather, you can "add" them, but they won't "stay added").
So, in "SQL Server Management Studio", I went into my application's database, in other words (my localized names are obscured within <> brackets): " (SQL Server - sa)"\Databases\\Security\Roles\Database Roles\public". Right-click on "public" and select "Properties". In the "Database Role Properties - public" dialog, select the "Securables" page. Go through the list and for each element in the list, come up with an SQL "Grant" statement to grant exactly that permission to another role. So, for instance, there is a scalar function "[dbo].[fn_diagramobjects]" on which the "public" role has "Execute" privilege. So, I added the following line:
EXEC ( 'GRANT EXECUTE ON [dbo].[fn_diagramobjects] TO [' + @RoleName + '];' )
Once I had done this for all the elements in the "Securables" list, I wrapped that up in a while loop on a cursor selecting through all the roles in my roles table. This explicitly granted all the permissions of the "public" role to my database roles. At that point, all my users were working again (even after I removed their "sysadmin" access--done as a temporary measure while I figured out what happened.)
I'm sure there's a better (more elegant) way to do this by doing some kind of a query on the database objects and selecting on the public role, but after about half and hour of investigating, I wasn't figuring it out, so I just did it the brute-force method. In case it helps someone else, here's my code.
CREATE PROCEDURE [dbo].[GrantAccess]
AS
DECLARE @AppRoleName AS sysname
DECLARE AppRoleCursor CURSOR LOCAL SCROLL_LOCKS FOR
SELECT AppRoleName FROM [dbo].[RoleList];
OPEN AppRoleCursor
FETCH NEXT FROM AppRoleCursor INTO @AppRoleName
WHILE @@FETCH_STATUS = 0
BEGIN
EXEC ( 'GRANT EXECUTE ON [dbo].[fn_diagramobjects] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT EXECUTE ON [dbo].[sp_alterdiagram] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT EXECUTE ON [dbo].[sp_creatediagram] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT EXECUTE ON [dbo].[sp_dropdiagram] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT EXECUTE ON [dbo].[sp_helpdiagramdefinition] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT EXECUTE ON [dbo].[sp_helpdiagrams] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT EXECUTE ON [dbo].[sp_renamediagram] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[all_columns] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[all_objects] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[all_parameters] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[all_sql_modules] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[all_views] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[allocation_units] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[assemblies] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[assembly_files] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[assembly_modules] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[assembly_references] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[assembly_types] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[asymmetric_keys] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[certificates] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[change_tracking_tables] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[check_constraints] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[column_type_usages] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[column_xml_schema_collection_usages] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[columns] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[computed_columns] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[conversation_endpoints] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[conversation_groups] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[conversation_priorities] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[crypt_properties] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[data_spaces] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[database_audit_specification_details] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[database_audit_specifications] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[database_files] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[database_permissions] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[database_principal_aliases] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[database_principals] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[database_role_members] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[default_constraints] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[destination_data_spaces] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[event_notifications] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[events] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[extended_procedures] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[extended_properties] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[filegroups] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[foreign_key_columns] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[foreign_keys] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[fulltext_catalogs] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[fulltext_index_catalog_usages] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[fulltext_index_columns] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[fulltext_index_fragments] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[fulltext_indexes] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[fulltext_stoplists] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[fulltext_stopwords] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[function_order_columns] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[identity_columns] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[index_columns] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[indexes] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[internal_tables] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[key_constraints] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[key_encryptions] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[message_type_xml_schema_collection_usages] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[module_assembly_usages] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[numbered_procedure_parameters] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[numbered_procedures] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[objects] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[parameter_type_usages] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[parameter_xml_schema_collection_usages] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[parameters] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[partition_functions] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[partition_parameters] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[partition_range_values] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[partition_schemes] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[partitions] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[plan_guides] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[procedures] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[remote_service_bindings] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[routes] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[schemas] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[service_contract_message_usages] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[service_contract_usages] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[service_contracts] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[service_message_types] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[service_queue_usages] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[service_queues] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[services] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[spatial_index_tessellations] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[spatial_indexes] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[sql_dependencies] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[sql_modules] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[stats] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[stats_columns] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[symmetric_keys] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[synonyms] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[syscolumns] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[syscomments] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[sysconstraints] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[sysdepends] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[sysfilegroups] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[sysfiles] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[sysforeignkeys] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[sysfulltextcatalogs] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[sysindexes] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[sysindexkeys] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[sysmembers] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[sysobjects] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[syspermissions] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[sysprotects] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[sysreferences] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[system_columns] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[system_objects] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[system_parameters] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[system_sql_modules] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[system_views] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[systypes] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[sysusers] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[table_types] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[tables] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[transmission_queue] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[trigger_events] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[triggers] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[type_assembly_usages] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[types] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[views] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[xml_indexes] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[xml_schema_attributes] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[xml_schema_collections] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[xml_schema_component_placements] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[xml_schema_components] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[xml_schema_elements] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[xml_schema_facets] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[xml_schema_model_groups] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[xml_schema_namespaces] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[xml_schema_types] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[xml_schema_wildcard_namespaces] TO [' + @AppRoleName + '];' )
EXEC ( 'GRANT SELECT ON [sys].[xml_schema_wildcards] TO [' + @AppRoleName + '];' )
FETCH NEXT FROM AppRoleCursor INTO @AppRoleName
END
CLOSE AppRoleCursor
RETURN 0
GO
Once that is in the system, I just needed to "Exec GrantAccess" to make it work. (Of course, I have a table [RoleList] which contains a "AppRoleName" field that contains the names of the database roles.
So, the mystery remains: why did all my users lose their "public" role and why could I not give it back to them? Was this part of an update to SQL Server 2008 R2? Was it because I ran another script to delete each user and add them back so to refresh their connection with the domain? Well, this solves the issue for now.
One last warning: you probably should check the "public" role on your system before running this to make sure there isn't something missing or wrong, here. It's always possible something is different about your system.
Hope this helps someone else.
Margin is a property in CSS that is used to create spaces around the elements, outside of the border. The programmer can set the margin for top, right, bottom and left. In other words, he can set those values using margin-top, margin-right, margin-bottom and margin-left.
The Margin values can be of the following types.
First, auto allows the browser to calculate the margin. Moreover, length denotes a margin in px, pt or cm, while % helps to describe a margin as a percentage relative to the width of the containing element. Finally, inherit denotes that the margin has to inherit from the parent element.
Padding is a property in CSS that helps to create space around an element inside the border. The programmer can set the padding for top, right, bottom and left. In other words, he can set those values using padding-top, padding-right, padding-bottom and padding-left.
The Padding values can be of the following types.
The length describes padding in px, pt or cm, while % denotes padding as a percentage relative to the width of the containing element. Finally, inherit describes that the padding should be inherited from the parent element.
div.special {_x000D_
width:200px; _x000D_
border-style: solid; _x000D_
border-width:thin; _x000D_
border-color:#000;_x000D_
margin:30px 20px 10px 25px;_x000D_
} _x000D_
div.special2 {_x000D_
width:200px;_x000D_
border-style: solid;_x000D_
border-width:thin;_x000D_
border-color:#000;_x000D_
padding:30px 20px 10px 25px;_x000D_
}
_x000D_
<div class="special">_x000D_
Hello its margin test _x000D_
</div>_x000D_
<div class="special2">_x000D_
Hello its padding test_x000D_
</div>
_x000D_
Difference Between Margin and Padding
Margin is a CSS property that is used to create space around the element outside the defined border, while the padding is a CSS property that is used to create space around the element, inside the defined border. Thus, this explains the main difference between margin and padding.
Values Furthermore, the values of margin can be auto, length, % or inherit, whereas the values of padding can be length, % or inherit type. Hence, this is another difference between margin and padding.
In brief, margin and padding are two properties in CSS that allows styling the web pages. It is not possible to assign negative values for those properties. The main difference between margin and padding is that margin helps to create space around the element outside the border, while padding helps to create space around the element inside the border.
HTML5 introduces a number of APIs that help in creating Web applications. These can be used together with the new elements introduced for applications:
contenteditable
attribute.draggable
attribute.If you are using sass as style preprocessor, you can switch back to native Sass compiler for dev dependency by:
npm install node-sass --save-dev
So that you can keep using /deep/ for development.
Try using following command it work.
mysql --user=root --password=root_password
Use a list instead and replace your foreach
loop with a for
loop:
@model IList<BlockedIPViewModel>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@for (var i = 0; i < Model.Count; i++)
{
<tr>
<td>
@Html.HiddenFor(x => x[i].IP)
@Html.CheckBoxFor(x => x[i].Checked)
</td>
<td>
@Html.DisplayFor(x => x[i].IP)
</td>
</tr>
}
<div>
<input type="submit" value="Unblock IPs" />
</div>
}
Alternatively you could use an editor template:
@model IEnumerable<BlockedIPViewModel>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.EditorForModel()
<div>
<input type="submit" value="Unblock IPs" />
</div>
}
and then define the template ~/Views/Shared/EditorTemplates/BlockedIPViewModel.cshtml
which will automatically be rendered for each element of the collection:
@model BlockedIPViewModel
<tr>
<td>
@Html.HiddenFor(x => x.IP)
@Html.CheckBoxFor(x => x.Checked)
</td>
<td>
@Html.DisplayFor(x => x.IP)
</td>
</tr>
The reason you were getting null in your controller is because you didn't respect the naming convention for your input fields that the default model binder expects to successfully bind to a list. I invite you to read the following article
.
Once you have read it, look at the generated HTML (and more specifically the names of the input fields) with my example and yours. Then compare and you will understand why yours doesn't work.
ldap authentication without SSL is not safe and anyone can view user credential because ldap client transfer usernamae and password during ldap bind operation So Always use ldaps protocol. source: Ldap authentication Active directory in Java Spring Security with Example
Just add empty (with no content) .gitignore
file in the empty directory you want to track.
E.g. if you want to track empty dir /project/content/posts
then create new empty file /project/content/posts/.gitignore
Note: .gitkeep is not part of official git:
If you are on branch A do:
git merge -s recursive -X theirs B
Tested on git version 1.7.8
Underscore vs Lo-Dash by Ben McCormick is the latest article comparing the two:
- Lodash's API is a superset of Underscore.js's.
- Under the hood, Lodash has been completely rewritten.
- Lodash is definitely not slower than Underscore.js.
- What has Lodash added?
- Usability improvements
- Extra functionality
- Performance gains
- Shorthand syntaxes for chaining
- Custom builds to only use what you need
- Semantic versioning and 100% code coverage
use java.util.Random
to generate a random number between 0 and array length: random_number
, and then use the random number to get the integer: array[random_number]
Another library to consider is MySqlConnector, https://mysqlconnector.net/. Mysql.Data is under a GPL license, whereas MySqlConnector is MIT.
As a supplement, calling a virtual function of an object that has not yet completed construction will face the same problem.
For example, start a new thread in the constructor of an object, and pass the object to the new thread, if the new thread calling the virtual function of that object before the object completed construction will cause unexpected result.
For example:
#include <thread>
#include <string>
#include <iostream>
#include <chrono>
class Base
{
public:
Base()
{
std::thread worker([this] {
// This will print "Base" rather than "Sub".
this->Print();
});
worker.detach();
// Try comment out this code to see different output.
std::this_thread::sleep_for(std::chrono::seconds(1));
}
virtual void Print()
{
std::cout << "Base" << std::endl;
}
};
class Sub : public Base
{
public:
void Print() override
{
std::cout << "Sub" << std::endl;
}
};
int main()
{
Sub sub;
sub.Print();
getchar();
return 0;
}
This will output:
Base
Sub
If you just want to get the highest salary from that table, by department:
SELECT MAX(Salary) FROM TableName GROUP BY DeptID
In my case, I was missing to set the header:
"Content-Type: application/json"
To my knowledge, no.
Circumstantial indications from $LC_CTYPE
, locale
and such might seem alluring, but these are completely separated from the encoding the terminal application (actually an emulator) happens to be using when displaying characters on the screen.
They only way to detect encoding for sure is to output something only present in the encoding, e.g. รค
, take a screenshot, analyze that image and check if the output character is correct.
So no, it's not possible, sadly.
Your fns is a cellstr array. You need to index in to it with {} instead of () to get the single string out as char.
fns{i}
teststruct.(fns{i})
Indexing in to it with () returns a 1-long cellstr array, which isn't the same format as the char array that the ".(name)" dynamic field reference wants. The formatting, especially in the display output, can be confusing. To see the difference, try this.
name_as_char = 'a'
name_as_cellstr = {'a'}
I would prefere
if (!myStr.empty())
{
//do something
}
Also you don't have to write std::string a = "";
. You can just write std::string a;
- it will be empty by default
I think your EmpID
column is string and you forget to use ' '
in your value.
Because when you write EmpID=" + id.Text
, your command looks like EmpID = 12345
instead of EmpID = '12345'
Change your SqlCommand
to
SqlCommand cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID='" + id.Text +"'", con);
Or as a better way you can (and should) always use parameterized queries
. This kind of string concatenations are open for SQL Injection
attacks.
SqlCommand cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID = @id", con);
cmd.Parameters.AddWithValue("@id", id.Text);
I think your EmpID
column keeps your employee id's, so it's type should some numerical type instead of character.
It's either through system property
-Dorg.slf4j.simpleLogger.defaultLogLevel=debug
or simplelogger.properties
file on the classpath
see http://www.slf4j.org/api/org/slf4j/impl/SimpleLogger.html for details
I had many issues involving C# and SqlServer. I ended up doing the following:
Also make sure that all your machines run on the same timezone.
Regarding the different result sets you get, your first example is "July First" while the second is "4th of July" ...
Also, the second example can be also interpreted as "April 7th", it depends on your server localization configuration (my solution doesn't suffer from this issue).
EDIT: hh was replaced with HH, as it doesn't seem to capture the correct hour on systems with AM/PM as opposed to systems with 24h clock. See the comments below.
The frame is the rectangle that defines the UIView with respect to its superview.
The bounds rect is the range of values that define that NSView's coordinate system.
i.e. anything in this rectangle will actually display in the UIView.
Well, this can take long time to figure out. Few points to narrow it down:
What is a
when you call Ancestors('A',a)
? If a['A']
is None, or if a['A'][0]
is None, you'd receive that exception.
If you have your project saved as a local copy of a repository, it may be better to import from git. Select local, and then browse to your git repository folder. That worked better for me than importing it as an existing project. Attempting the latter did not allow me to "finish".
I had this issue when trying to push after a rebase through Visual Studio Code, my issue was solved by just copying the command from the git output window and executing it from the terminal window in Visual Studio Code.
In my case the command was something like:
git push origin NameOfMyBranch:NameOfMyBranch
Use Lookupstage to decide whether to insert or update. Check this link for more info - http://beingoyen.blogspot.com/2010/03/ssis-how-to-update-instead-of-insert.html
Steps to do update:
Under Custom properties select SQLCOMMAND and insert update command ex:
UPDATE table1 SET col1 = ?, col2 = ? where id = ?
map columns in exact order from source to output as in update command
my issue:
# npm install -g canvas
dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.64.dylib
Referenced from: /usr/local/opt/node@8/bin/node
Reason: image not found
for now 20210118, after many try:
...
brew reinstall https://raw.githubusercontent.com/Homebrew/homebrew-core/master/Formula/icu4c.rb
brew upgrade npm
brew install node
brew uninstall --ignore-dependencies node@8 icu4c
brew install icu4c
...
Final worked solution is:
brew reinstall npm
Secure commands will not allow this, and rightly so, I'm afraid - it's a security hole you could drive a truck through.
If your command does not allow it using input redirection, or a command-line parameter, or a configuration file, then you're going to have to resort to serious trickery.
Some applications will actually open up /dev/tty
to ensure you will have a hard time defeating security. You can get around them by temporarily taking over /dev/tty
(creating your own as a pipe, for example) but this requires serious privileges and even it can be defeated.
These days we don't have to call the constructor inside the component - we can directly call state={something:""}
, otherwise previously first we have do declare constructor with super()
to inherit every thing from React.Component
class
then inside constructor we initialize our state.
If using React.createClass
then define initialize state with the getInitialState
method.
Jackson marshalling/unmarshalling requires following jar files of same version.
jackson-core
jackson-databind
jackson-annotations
Make sure that you have added all these with same version in your classpath. In your case jackson-annotations is missing in classpath.
Looks like moment.js is the most popular and with active development:
moment("2010-01-01T05:06:07", moment.ISO_8601);
This will replace all the characters except alphanumeric
replaceAll("[^A-Za-z0-9]","");
View Data
==============
@model IEnumerable<DemoApp.Models.BankInfo>
<p>
<b>Search Results</b>
</p>
@if (!Model.Any())
{
<tr>
<td colspan="4" style="text-align:center">
No Bank(s) found
</td>
</tr>
}
else
{
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Address)
</th>
<th>
@Html.DisplayNameFor(model => model.Postcode)
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Address)
</td>
<td>
@Html.DisplayFor(modelItem => item.Postcode)
</td>
<td>
<input type="button" class="btn btn-default bankdetails" value="Select" data-id="@item.Id" />
</td>
</tr>
}
</table>
}
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnSearch").off("click.search").on("click.search", function () {
if ($("#SearchBy").val() != '') {
$.ajax({
url: '/home/searchByName',
data: { 'name': $("#SearchBy").val() },
dataType: 'html',
success: function (data) {
$('#dvBanks').html(data);
}
});
}
else {
alert('Please enter Bank Name');
}
});
}
});
public ActionResult SearchByName(string name)
{
var banks = GetBanksInfo();
var filteredBanks = banks.Where(x => x.Name.ToLower().Contains(name.ToLower())).ToList();
return PartialView("_banks", filteredBanks);
}
/// <summary>
/// Get List of Banks Basically it should get from Database
/// </summary>
/// <returns></returns>
private List<BankInfo> GetBanksInfo()
{
return new List<BankInfo>
{
new BankInfo {Id = 1, Name = "Bank of America", Address = "1438 Potomoc Avenue, Pittsburge", Postcode = "PA 15220" },
new BankInfo {Id = 2, Name = "Bank of America", Address = "643 River Hwy, Mooresville", Postcode = "NC 28117" },
new BankInfo {Id = 3, Name = "Bank of Barroda", Address = "643 Hyderabad", Postcode = "500061" },
new BankInfo {Id = 4, Name = "State Bank of India", Address = "AsRao Nagar", Postcode = "500061" },
new BankInfo {Id = 5, Name = "ICICI", Address = "AsRao Nagar", Postcode = "500061" }
};
}
this would be perfect cause we are doing operation on matrix, and the answer should be a single number
sum(sum(matrix==value))
I feel like an advanced necromancer here, but this is still an issue 4 years later in MVC5.
To handle ajax requests properly the anti-forgery token needs to be passed to the server on ajax calls. Integrating it into your post data and models is messy and unnecessary. Adding the token as a custom header is clean and reusable - and you can configure it so you don't have to remember to do it every time.
There is an exception - Unobtrusive ajax does not need special treatment for ajax calls. The token is passed as usual in the regular hidden input field. Exactly the same as a regular POST.
In _layout.cshtml I have this JavaScript block. It doesn't write the token into the DOM, rather it uses jQuery to extract it from the hidden input literal that the MVC Helper generates. The Magic string that is the header name is defined as a constant in the attribute class.
<script type="text/javascript">
$(document).ready(function () {
var isAbsoluteURI = new RegExp('^(?:[a-z]+:)?//', 'i');
//http://stackoverflow.com/questions/10687099/how-to-test-if-a-url-string-is-absolute-or-relative
$.ajaxSetup({
beforeSend: function (xhr) {
if (!isAbsoluteURI.test(this.url)) {
//only add header to relative URLs
xhr.setRequestHeader(
'@.ValidateAntiForgeryTokenOnAllPosts.HTTP_HEADER_NAME',
$('@Html.AntiForgeryToken()').val()
);
}
}
});
});
</script>
Note the use of single quotes in the beforeSend function - the input element that is rendered uses double quotes that would break the JavaScript literal.
When this executes the beforeSend function above is called and the AntiForgeryToken is automatically added to the request headers.
$.ajax({
type: "POST",
url: "CSRFProtectedMethod",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
//victory
}
});
A custom attribute is required to process the non standard token. This builds on @viggity's solution, but handles unobtrusive ajax correctly. This code can be tucked away in your common library
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class ValidateAntiForgeryTokenOnAllPosts : AuthorizeAttribute
{
public const string HTTP_HEADER_NAME = "x-RequestVerificationToken";
public override void OnAuthorization(AuthorizationContext filterContext)
{
var request = filterContext.HttpContext.Request;
// Only validate POSTs
if (request.HttpMethod == WebRequestMethods.Http.Post)
{
var headerTokenValue = request.Headers[HTTP_HEADER_NAME];
// Ajax POSTs using jquery have a header set that defines the token.
// However using unobtrusive ajax the token is still submitted normally in the form.
// if the header is present then use it, else fall back to processing the form like normal
if (headerTokenValue != null)
{
var antiForgeryCookie = request.Cookies[AntiForgeryConfig.CookieName];
var cookieValue = antiForgeryCookie != null
? antiForgeryCookie.Value
: null;
AntiForgery.Validate(cookieValue, headerTokenValue);
}
else
{
new ValidateAntiForgeryTokenAttribute()
.OnAuthorization(filterContext);
}
}
}
}
Now you just apply the attribute to your Action. Even better you can apply the attribute to your controller and all requests will be validated.
[HttpPost]
[ValidateAntiForgeryTokenOnAllPosts]
public virtual ActionResult CSRFProtectedMethod()
{
return Json(true, JsonRequestBehavior.DenyGet);
}
This did the trick for me. It captures all the stdout output from the subprocess(For python 3.8):
from subprocess import check_output, STDOUT
cmd = "Your Command goes here"
try:
cmd_stdout = check_output(cmd, stderr=STDOUT, shell=True).decode()
except Exception as e:
print(e.output.decode()) # print out the stdout messages up to the exception
print(e) # To print out the exception message
@lru_cache
is not perfect with default function values
my mem
decorator:
import inspect
def get_default_args(f):
signature = inspect.signature(f)
return {
k: v.default
for k, v in signature.parameters.items()
if v.default is not inspect.Parameter.empty
}
def full_kwargs(f, kwargs):
res = dict(get_default_args(f))
res.update(kwargs)
return res
def mem(func):
cache = dict()
def wrapper(*args, **kwargs):
kwargs = full_kwargs(func, kwargs)
key = list(args)
key.extend(kwargs.values())
key = hash(tuple(key))
if key in cache:
return cache[key]
else:
res = func(*args, **kwargs)
cache[key] = res
return res
return wrapper
and code for testing:
from time import sleep
@mem
def count(a, *x, z=10):
sleep(2)
x = list(x)
x.append(z)
x.append(a)
return sum(x)
def main():
print(count(1,2,3,4,5))
print(count(1,2,3,4,5))
print(count(1,2,3,4,5, z=6))
print(count(1,2,3,4,5, z=6))
print(count(1))
print(count(1, z=10))
if __name__ == '__main__':
main()
result - only 3 times with sleep
but with @lru_cache
it will be 4 times, because this:
print(count(1))
print(count(1, z=10))
will be calculated twice (bad working with defaults)
Partial dependency implies is a situation where a non-prime attribute(An attribute that does not form part of the determinant(Primary key/Candidate key)) is functionally dependent to a portion/part of a primary key/Candidate key.
In theory SMTP can be handled by either TCP, UDP, or some 3rd party protocol.
As defined in RFC 821, RFC 2821, and RFC 5321:
SMTP is independent of the particular transmission subsystem and requires only a reliable ordered data stream channel.
In addition, the Internet Assigned Numbers Authority has allocated port 25 for both TCP and UDP for use by SMTP.
In practice however, most if not all organizations and applications only choose to implement the TCP protocol. For example, in Microsoft's port listing port 25 is only listed for TCP and not UDP.
The big difference between TCP and UDP that makes TCP ideal here is that TCP checks to make sure that every packet is received and re-sends them if they are not whereas UDP will simply send packets and not check for receipt. This makes UDP ideal for things like streaming video where every single packet isn't as important as keeping a continuous flow of packets from the server to the client.
Considering SMTP, it makes more sense to use TCP over UDP. SMTP is a mail transport protocol, and in mail every single packet is important. If you lose several packets in the middle of the message the recipient might not even receive the message and if they do they might be missing key information. This makes TCP more appropriate because it ensures that every packet is delivered.
With [email protected] or later you can install types with npm install
npm install --save-dev @types/jasmine
then import the types automatically using the typeRoots option in tsconfig.json.
"typeRoots": [
"node_modules/@types"
],
This solution does not require import {} from 'jasmine'; in each spec file.
This post was helpful for my project hence I thought of sharing my experience as well. The essential thing to note is that the POST request is possible only with a form. I had a similar requirement as I was trying to render a page with ejs. I needed to render a navigation with a list of items that would essentially be hyperlinks and when user selects any one of them, the server responds with appropriate information.
so I basically created each of the navigation items as a form using a loop as follows:
<ul>_x000D_
begin loop..._x000D_
<li>_x000D_
<form action="/" method="post">_x000D_
<input type="hidden" name="country" value="India"/>_x000D_
<button type="submit" name="button">India</button>_x000D_
</form> _x000D_
</li>_x000D_
end loop._x000D_
</ul>
_x000D_
what it did is to create a form with hidden input with a value assigned same as the text on the button. So the end user will see only text from the button and when clicked, will send a post request to the server.
Note that the value parameter of the input box and the Button text are exactly same and were values passed using ejs that I have not shown in this example above to keep the code simple.
here is a screen shot of the navigation... enter image description here
if permission issue and you have ssh access in root folder
find . -type d -exec chmod 755 {} \;
find . -type f -exec chmod 644 {} \;
will resolve your error
I have passed through that error today and did everything described above but didn't work for me. So I decided to view the core problem and logged onto the MySQL root folder in Windows 7 and did this solution:
Go to folder:
C:\AppServ\MySQL
Right click and Run as Administrator these files:
mysql_servicefix.bat
mysql_serviceinstall.bat
mysql_servicestart.bat
Then close the entire explorer window and reopen it or clear cache then login to phpMyAdmin again.
If you are entering several lines of text at once, I find this to be the most readable format.
file.write("\
Life's but a walking shadow, a poor player\n\
That struts and frets his hour upon the stage\n\
And then is heard no more: it is a tale\n\
Told by an idiot, full of sound and fury,\n\
Signifying nothing.\n\
")
The \ at the end of each line escapes the new line (which would cause an error).
Because in Python 3, print statement
has been replaced with a print() function
, with keyword arguments to replace most of the special syntax of the old print statement. So you have to write it as
print("Hello World")
But if you write this in a program and someone using Python 2.x tries to run it, they will get an error. To avoid this, it is a good practice to import print function:
from __future__ import print_function
Now your code works on both 2.x & 3.x.
Check out below examples also to get familiar with print() function.
Old: print "The answer is", 2*2
New: print("The answer is", 2*2)
Old: print x, # Trailing comma suppresses newline
New: print(x, end=" ") # Appends a space instead of a newline
Old: print # Prints a newline
New: print() # You must call the function!
Old: print >>sys.stderr, "fatal error"
New: print("fatal error", file=sys.stderr)
Old: print (x, y) # prints repr((x, y))
New: print((x, y)) # Not the same as print(x, y)!
Source: Whatโs New In Python 3.0?
Try to use the latest com.fasterxml.jackson.core/jackson-databind
.
I upgraded it to 2.9.4
and it works now.
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.4</version>
</dependency>
Execution of a python script would cause the byte code to be generated in memory and kept until the program is shutdown. In case a module is imported, for faster reusability, Python would create a cache .pyc (PYC is 'Python' 'Compiled') file where the byte code of the module being imported is cached. Idea is to speed up loading of python modules by avoiding re-compilation ( compile once, run multiple times policy ) when they are re-imported.
The name of the file is the same as the module name. The part after the initial dot indicates Python implementation that created the cache (could be CPython) followed by its version number.
You must use the equals operator not the assignment like
if(document.form1.radio1[0].checked == true) {
alert("You have selected Option 1");
}
case $(pwd) in
*path) echo "ends with path";;
path*) echo "starts with path";;
*path*) echo "contains path";;
*) echo "this is the default";;
esac
If you are doing some local testing and that you add some alias in the hosts files say
127.0.0.1 www.mysite.com
and try to use any of the above procedures you will fail. The reason is that you will import a certificate for localhost. The certificate URL won't match.
In that situation you will have to generate a self-signed certificate and THEN import it as described above.
If you are using Xampp the generation of the correct certificate can be done easily using c:\xampp\apache\makecert.bat
Have a think about wrapping the videos inside something which you can make flexible via bootsrap.
The bootstrap is not a magic tool, its just a layout engine. You almost have it in your example.
Just use the grid provided by bootstrap and remove strict sizing's on the iframe. Use the bootstrap class guides for the grid..
For example:
<iframe class="col-lg-2 col-md-6 col-sm-12 col-xs-12">
You will see how the class of the iframe will change then given your resolution.
A Fiddel too : http://jsfiddle.net/RsSAT/
I don't use named parameters for all queries. For example it is unusual to use named parameters in JpaRepository.
To workaround I use JPQL CONCAT function (this code emulate start with):
@Repository
public interface BranchRepository extends JpaRepository<Branch, String> {
private static final String QUERY = "select b from Branch b"
+ " left join b.filial f"
+ " where f.id = ?1 and b.id like CONCAT(?2, '%')";
@Query(QUERY)
List<Branch> findByFilialAndBranchLike(String filialId, String branchCode);
}
I found this technique in excellent docs: http://openjpa.apache.org/builds/1.0.1/apache-openjpa-1.0.1/docs/manual/jpa_overview_query.html
This happens because your upstream takes too much to answer the request and NGINX thinks the upstream already failed in processing the request, so it responds with an error.
Just include and increase proxy_read_timeout in location
config block.
Same thing happened to me and I used 1 hour timeout for an internal app at work:
proxy_read_timeout 3600;
With this, NGINX will wait for an hour (3600s) for its upstream to return something.
If anybody is still looking for this, this is how it worked for me.
You need to find the IP of your machine with respect to the device/emulator you are connected. For Emulators on of the way is by following below steps;
Provide this IP to access the localhost from emulator. The Port is same as you have provided while running/publishing your services.
Note #1 : Make sure you have taken care of firewalls and inbound rules.
Note #2 : Please check this IP after you restart your machine. For some reason, even If I provided "Use the following IP" The Host-Only IP got changed.
If u r using SQLite3 beware:
It takes only 't' or 'f'. Not 1 or 0. Not TRUE OR FALSE.
Just learned the hard way.
You have to do it like this:
If strMyString.Contains("Something") OrElse strMyString.Contains("Something2") Then
'[Put Code Here]
End if
Just for the record..
It is actually not a solution to your code, but I had the same error message when incorrectly accessing the method of a class instance pointed to by myPointerToClass
, e.g.
MyClass* myPointerToClass = new MyClass();
myPointerToClass.aMethodOfThatClass();
where
myPointerToClass->aMethodOfThatClass();
would obviously be correct.
Place your text file in the /assets
directory under the Android project. Use AssetManager
class to access it.
AssetManager am = context.getAssets();
InputStream is = am.open("test.txt");
Or you can also put the file in the /res/raw
directory, where the file will be indexed and is accessible by an id in the R file:
InputStream is = context.getResources().openRawResource(R.raw.test);
Note: this answer is for ANTLR3! If you're looking for an ANTLR4 example, then this Q&A demonstrates how to create a simple expression parser, and evaluator using ANTLR4.
You first create a grammar. Below is a small grammar that you can use to evaluate expressions that are built using the 4 basic math operators: +, -, * and /. You can also group expressions using parenthesis.
Note that this grammar is just a very basic one: it does not handle unary operators (the minus in: -1+9) or decimals like .99 (without a leading number), to name just two shortcomings. This is just an example you can work on yourself.
Here's the contents of the grammar file Exp.g:
grammar Exp;
/* This will be the entry point of our parser. */
eval
: additionExp
;
/* Addition and subtraction have the lowest precedence. */
additionExp
: multiplyExp
( '+' multiplyExp
| '-' multiplyExp
)*
;
/* Multiplication and division have a higher precedence. */
multiplyExp
: atomExp
( '*' atomExp
| '/' atomExp
)*
;
/* An expression atom is the smallest part of an expression: a number. Or
when we encounter parenthesis, we're making a recursive call back to the
rule 'additionExp'. As you can see, an 'atomExp' has the highest precedence. */
atomExp
: Number
| '(' additionExp ')'
;
/* A number: can be an integer value, or a decimal value */
Number
: ('0'..'9')+ ('.' ('0'..'9')+)?
;
/* We're going to ignore all white space characters */
WS
: (' ' | '\t' | '\r'| '\n') {$channel=HIDDEN;}
;
(Parser rules start with a lower case letter, and lexer rules start with a capital letter)
After creating the grammar, you'll want to generate a parser and lexer from it. Download the ANTLR jar and store it in the same directory as your grammar file.
Execute the following command on your shell/command prompt:
java -cp antlr-3.2.jar org.antlr.Tool Exp.g
It should not produce any error message, and the files ExpLexer.java, ExpParser.java and Exp.tokens should now be generated.
To see if it all works properly, create this test class:
import org.antlr.runtime.*;
public class ANTLRDemo {
public static void main(String[] args) throws Exception {
ANTLRStringStream in = new ANTLRStringStream("12*(5-6)");
ExpLexer lexer = new ExpLexer(in);
CommonTokenStream tokens = new CommonTokenStream(lexer);
ExpParser parser = new ExpParser(tokens);
parser.eval();
}
}
and compile it:
// *nix/MacOS
javac -cp .:antlr-3.2.jar ANTLRDemo.java
// Windows
javac -cp .;antlr-3.2.jar ANTLRDemo.java
and then run it:
// *nix/MacOS
java -cp .:antlr-3.2.jar ANTLRDemo
// Windows
java -cp .;antlr-3.2.jar ANTLRDemo
If all goes well, nothing is being printed to the console. This means the parser did not find any error. When you change "12*(5-6)"
into "12*(5-6"
and then recompile and run it, there should be printed the following:
line 0:-1 mismatched input '<EOF>' expecting ')'
Okay, now we want to add a bit of Java code to the grammar so that the parser actually does something useful. Adding code can be done by placing {
and }
inside your grammar with some plain Java code inside it.
But first: all parser rules in the grammar file should return a primitive double value. You can do that by adding returns [double value]
after each rule:
grammar Exp;
eval returns [double value]
: additionExp
;
additionExp returns [double value]
: multiplyExp
( '+' multiplyExp
| '-' multiplyExp
)*
;
// ...
which needs little explanation: every rule is expected to return a double value. Now to "interact" with the return value double value
(which is NOT inside a plain Java code block {...}
) from inside a code block, you'll need to add a dollar sign in front of value
:
grammar Exp;
/* This will be the entry point of our parser. */
eval returns [double value]
: additionExp { /* plain code block! */ System.out.println("value equals: "+$value); }
;
// ...
Here's the grammar but now with the Java code added:
grammar Exp;
eval returns [double value]
: exp=additionExp {$value = $exp.value;}
;
additionExp returns [double value]
: m1=multiplyExp {$value = $m1.value;}
( '+' m2=multiplyExp {$value += $m2.value;}
| '-' m2=multiplyExp {$value -= $m2.value;}
)*
;
multiplyExp returns [double value]
: a1=atomExp {$value = $a1.value;}
( '*' a2=atomExp {$value *= $a2.value;}
| '/' a2=atomExp {$value /= $a2.value;}
)*
;
atomExp returns [double value]
: n=Number {$value = Double.parseDouble($n.text);}
| '(' exp=additionExp ')' {$value = $exp.value;}
;
Number
: ('0'..'9')+ ('.' ('0'..'9')+)?
;
WS
: (' ' | '\t' | '\r'| '\n') {$channel=HIDDEN;}
;
and since our eval
rule now returns a double, change your ANTLRDemo.java into this:
import org.antlr.runtime.*;
public class ANTLRDemo {
public static void main(String[] args) throws Exception {
ANTLRStringStream in = new ANTLRStringStream("12*(5-6)");
ExpLexer lexer = new ExpLexer(in);
CommonTokenStream tokens = new CommonTokenStream(lexer);
ExpParser parser = new ExpParser(tokens);
System.out.println(parser.eval()); // print the value
}
}
Again (re) generate a fresh lexer and parser from your grammar (1), compile all classes (2) and run ANTLRDemo (3):
// *nix/MacOS
java -cp antlr-3.2.jar org.antlr.Tool Exp.g // 1
javac -cp .:antlr-3.2.jar ANTLRDemo.java // 2
java -cp .:antlr-3.2.jar ANTLRDemo // 3
// Windows
java -cp antlr-3.2.jar org.antlr.Tool Exp.g // 1
javac -cp .;antlr-3.2.jar ANTLRDemo.java // 2
java -cp .;antlr-3.2.jar ANTLRDemo // 3
and you'll now see the outcome of the expression 12*(5-6)
printed to your console!
Again: this is a very brief explanation. I encourage you to browse the ANTLR wiki and read some tutorials and/or play a bit with what I just posted.
Good luck!
EDIT:
This post shows how to extend the example above so that a Map<String, Double>
can be provided that holds variables in the provided expression.
To get this code working with a current version of Antlr (June 2014) I needed to make a few changes. ANTLRStringStream
needed to become ANTLRInputStream
, the returned value needed to change from parser.eval()
to parser.eval().value
, and I needed to remove the WS
clause at the end, because attribute values such as $channel
are no longer allowed to appear in lexer actions.
As an alternative, you could add it as a script parameter for input as part of script execution
param(
[Parameter(Mandatory = $True,valueFromPipeline=$true)][String] $value1,
[Parameter(Mandatory = $True,valueFromPipeline=$true)][String] $value2
)
marker = new google.maps.Marker({
map:map,
// draggable:true,
// animation: google.maps.Animation.DROP,
position: new google.maps.LatLng(59.32522, 18.07002),
icon: 'http://cdn.com/my-custom-icon.png' // null = default icon
});
If dgv(11, dgv.CurrentRow.Index).Selected = True Then
dgv.Rows.RemoveAt(dgv.CurrentRow.Index)
Else
Exit Sub
End If
in component:
formData.form.controls['email'].setErrors({'incorrect': true});
and in HTML:
<input mdInput placeholder="Email" type="email" name="email" required [(ngModel)]="email" #email="ngModel">
<div *ngIf="!email.valid">{{email.errors| json}}</div>
I will provide with a more elegant and robust way as follows, using unpacking:
def mark_last(iterable):
try:
*init, last = iterable
except ValueError: # if iterable is empty
return
for e in init:
yield e, True
yield last, False
Test:
for a, b in mark_last([1, 2, 3]):
print(a, b)
The result is:
1 True
2 True
3 False
Take IISReset as a suite of commands that helps you manage IIS start / stop etc.
Which means you need to specify option (/switch
) what you want to do to carry any operation.
Default behavior OR default switch is /restart
with iisreset
so you do not need to run command twice with /start
and /stop
.
Hope this clarifies your question. For reference the output of iisreset /?
is:
IISRESET.EXE (c) Microsoft Corp. 1998-2005 Usage: iisreset [computername] /RESTART Stop and then restart all Internet services. /START Start all Internet services. /STOP Stop all Internet services. /REBOOT Reboot the computer. /REBOOTONERROR Reboot the computer if an error occurs when starting, stopping, or restarting Internet services. /NOFORCE Do not forcefully terminate Internet services if attempting to stop them gracefully fails. /TIMEOUT:val Specify the timeout value ( in seconds ) to wait for a successful stop of Internet services. On expiration of this timeout the computer can be rebooted if the /REBOOTONERROR parameter is specified. The default value is 20s for restart, 60s for stop, and 0s for reboot. /STATUS Display the status of all Internet services. /ENABLE Enable restarting of Internet Services on the local system. /DISABLE Disable restarting of Internet Services on the local system.
Here is another way not depending on a library but using a regex.
You can use this single line:
text.matches("\\A\\p{ASCII}*\\z")
Whole example program:
public class Main {
public static void main(String[] args) {
char nonAscii = 0x00FF;
String asciiText = "Hello";
String nonAsciiText = "Buy: " + nonAscii;
System.out.println(asciiText.matches("\\A\\p{ASCII}*\\z"));
System.out.println(nonAsciiText.matches("\\A\\p{ASCII}*\\z"));
}
}
For the current branch, here are two good choices:
% git rev-parse --abbrev-ref --symbolic-full-name @{u}
origin/mainline
or
% git for-each-ref --format='%(upstream:short)' $(git symbolic-ref -q HEAD)
origin/mainline
That answer is also here, to a slightly different question which was (wrongly) marked as a duplicate.
The difference is that in the first case the retrieved user is not tracked by the context so when you are going to save the user back to database you must attach it and set correctly state of the user so that EF knows that it should update existing user instead of inserting a new one. In the second case you don't need to do that if you load and save the user with the same context instance because the tracking mechanism handles that for you.
import java.util.Scanner; import javax.swing.JOptionPane;
public class javaCalculator {
public static void main(String[] args)
{
int num1;
int num2;
String operation;
Scanner input = new Scanner(System.in);
System.out.println("please enter the first number");
num1 = input.nextInt();
System.out.println("please enter the second number");
num2 = input.nextInt();
Scanner op = new Scanner(System.in);
System.out.println("Please enter operation");
operation = op.next();
if (operation.equals("+"))
{
System.out.println("your answer is" + (num1 + num2));
}
else if (operation.equals("-"))
{
System.out.println("your answer is" + (num1 - num2));
}
else if (operation.equals("/"))
{
System.out.println("your answer is" + (num1 / num2));
}
else if (operation.equals("*"))
{
System.out.println("your answer is" + (num1 * num2));
}
else
{
System.out.println("Wrong selection");
}
}
}
On MacOS 10.11 with Firefox and a German keyboard layout it is Ctrl + ?
TakeScreenShot screenshot=new TakeScreenShot();
screenshot.screenShot("screenshots//TestScreenshot//password.png");
it will work , please try.
After struggling with this for hours trying to get it to work in IE8, 9, and 10 here's what worked for me.
This stripped-down CSS works in FF 26, Chrome 32, Opera 18, and IE9 -11 as of 1/7/2014:
.wrap
{
width: 320px;
height: 192px;
padding: 0;
overflow: hidden;
}
.frame
{
width: 1280px;
height: 786px;
border: 0;
-ms-transform: scale(0.25);
-moz-transform: scale(0.25);
-o-transform: scale(0.25);
-webkit-transform: scale(0.25);
transform: scale(0.25);
-ms-transform-origin: 0 0;
-moz-transform-origin: 0 0;
-o-transform-origin: 0 0;
-webkit-transform-origin: 0 0;
transform-origin: 0 0;
}
For IE8, set the width/height to match the iframe, and add -ms-zoom to the .wrap container div:
.wrap
{
width: 1280px; /* same size as frame */
height: 768px;
-ms-zoom: 0.25; /* for IE 8 ONLY */
}
Just use your favorite method for browser sniffing to conditionally include the appropriate CSS, see Is there a way to do browser specific conditional CSS inside a *.css file? for some ideas.
IE7 was a lost cause since -ms-zoom did not exist until IE8.
Here's the actual HTML I tested with:
<div class="wrap">
<iframe class="frame" src="http://time.is"></iframe>
</div>
<div class="wrap">
<iframe class="frame" src="http://apple.com"></iframe>
</div>
I believe you can accomplish it by just having single ng-view
. In the main template you can have ng-include
sections for sub views, then in the main controller define model properties for each sub template. So that they will bind automatically to ng-include
sections. This is same as having multiple ng-view
You can check the example given in ng-include
documentation
in the example when you change the template from dropdown list it changes the content. Here assume you have one main ng-view
and instead of manually selecting sub content by selecting drop down, you do it as when main view is loaded.
Check out the connection strings web site which has tons of example for your connection strings.
Basically, you need three things:
.
" or (local)
or localhost
for the local machine)For example, if you want to connect to your local machine and the AdventureWorks
database using integrated security, use:
server=(local);database=AdventureWorks;integrated security=SSPI;
Or if you have SQL Server Express on your machine in the default installation, and you want to connect to the AdventureWorksLT2008 database, use this:
server=.\SQLExpress;database=AdventureWorksLT2008;integrated Security=SSPI;
However, ngOptions provides some benefits such as reducing memory and increasing speed by not creating a new scope for each repeated instance. angular docs
Alternative solution is use ng-init
directive. You can specify function that will be initialize your default data.
$scope.init = function(){
angular.forEach($scope.units, function(item){
if(item.id === $scope.data.unit){
$scope.data.unit = item;
}
});
}
See jsfiddle
In simple words
v-model
is for two way bindings means: if you change input value, the bound data will be changed and vice versa.
but v-bind:value
is called one way binding that means: you can change input value by changing bound data but you can't change bound data by changing input value through the element.
check out this simple example: https://jsfiddle.net/gs0kphvc/
Since the string is not complex, no need to add RegEx strings. A simple match will do the trick
$line = "----start----Hello World----end----"
$line -match "Hello World"
$matches[0]
Hello World
$result = $matches[0]
$result
Hello World
There isn't a definite list, it's up to the browser. The only standard we have is DOM Level 2 HTML, according to which the only elements that have a focus()
method are
HTMLInputElement
, HTMLSelectElement
, HTMLTextAreaElement
and HTMLAnchorElement
. This notably omits HTMLButtonElement
and HTMLAreaElement
.
Today's browsers define focus()
on HTMLElement, but an element won't actually take focus unless it's one of:
disabled
(IE actually gives you an error if you try), and file uploads have unusual behaviour for security reasonstabindex
There are likely to be other subtle exceptions and additions to this behaviour depending on browser.
On Linux I also notice that :
Interruption of system calls and library functions by signal handlers
If a signal handler is invoked while a system call or library function call is blocked, then either:
the call is automatically restarted after the signal handler returns; or
the call fails with the error EINTR.
... The details vary across UNIX systems; below, the details for Linux.
If a blocked call to one of the following interfaces is interrupted by a signal handler, then the call is automatically restarted after the signal handler returns if the SA_RESTART flag was used; otherwise the call fails with the error EINTR:
- read(2), readv(2), write(2), writev(2), and ioctl(2) calls on "slow" devices.
.....
The following interfaces are never restarted after being interrupted by a signal handler, regardless of the use of SA_RESTART; they always fail with the error EINTR when interrupted by a signal handler:
"Input" socket interfaces, when a timeout (SO_RCVTIMEO) has been set on the socket using setsockopt(2): accept(2), recv(2), recvfrom(2), recvmmsg(2) (also with a non-NULL timeout argument), and recvmsg(2).
"Output" socket interfaces, when a timeout (SO_RCVTIMEO) has been set on the socket using setsockopt(2): connect(2), send(2), sendto(2), and sendmsg(2).
Check man 7 signal
for more details.
A simple usage would be use signal to avoid recvfrom
blocking indefinitely.
An example from APUE:
#include "apue.h"
#include <netdb.h>
#include <errno.h>
#include <sys/socket.h>
#define BUFLEN 128
#define TIMEOUT 20
void
sigalrm(int signo)
{
}
void
print_uptime(int sockfd, struct addrinfo *aip)
{
int n;
char buf[BUFLEN];
buf[0] = 0;
if (sendto(sockfd, buf, 1, 0, aip->ai_addr, aip->ai_addrlen) < 0)
err_sys("sendto error");
alarm(TIMEOUT);
//here
if ((n = recvfrom(sockfd, buf, BUFLEN, 0, NULL, NULL)) < 0) {
if (errno != EINTR)
alarm(0);
err_sys("recv error");
}
alarm(0);
write(STDOUT_FILENO, buf, n);
}
int
main(int argc, char *argv[])
{
struct addrinfo *ailist, *aip;
struct addrinfo hint;
int sockfd, err;
struct sigaction sa;
if (argc != 2)
err_quit("usage: ruptime hostname");
sa.sa_handler = sigalrm;
sa.sa_flags = 0;
sigemptyset(&sa.sa_mask);
if (sigaction(SIGALRM, &sa, NULL) < 0)
err_sys("sigaction error");
memset(&hint, 0, sizeof(hint));
hint.ai_socktype = SOCK_DGRAM;
hint.ai_canonname = NULL;
hint.ai_addr = NULL;
hint.ai_next = NULL;
if ((err = getaddrinfo(argv[1], "ruptime", &hint, &ailist)) != 0)
err_quit("getaddrinfo error: %s", gai_strerror(err));
for (aip = ailist; aip != NULL; aip = aip->ai_next) {
if ((sockfd = socket(aip->ai_family, SOCK_DGRAM, 0)) < 0) {
err = errno;
} else {
print_uptime(sockfd, aip);
exit(0);
}
}
fprintf(stderr, "can't contact %s: %s\n", argv[1], strerror(err));
exit(1);
}
function forEachNested(O, f, cur){
O = [ O ]; // ensure that f is called with the top-level object
while (O.length) // keep on processing the top item on the stack
if(
!f( cur = O.pop() ) && // do not spider down if `f` returns true
cur instanceof Object && // ensure cur is an object, but not null
[Object, Array].includes(cur.constructor) //limit search to [] and {}
) O.push.apply(O, Object.values(cur)); //search all values deeper inside
}
To use the above function, pass the array as the first argument and the callback function as the second argument. The callback function will receive 1 argument when called: the current item being iterated.
(function(){"use strict";
var cars = {"label":"Autos","subs":[{"label":"SUVs","subs":[]},{"label":"Trucks","subs":[{"label":"2 Wheel Drive","subs":[]},{"label":"4 Wheel Drive","subs":[{"label":"Ford","subs":[]},{"label":"Chevrolet","subs":[]}]}]},{"label":"Sedan","subs":[]}]};
var lookForCar = prompt("enter the name of the car you are looking for (e.g. 'Ford')") || 'Ford';
lookForCar = lookForCar.replace(/[^ \w]/g, ""); // incaseif the user put quotes or something around their input
lookForCar = lookForCar.toLowerCase();
var foundObject = null;
forEachNested(cars, function(currentValue){
if(currentValue.constructor === Object &&
currentValue.label.toLowerCase() === lookForCar) {
foundObject = currentValue;
}
});
if (foundObject !== null) {
console.log("Found the object: " + JSON.stringify(foundObject, null, "\t"));
} else {
console.log('Nothing found with a label of "' + lookForCar + '" :(');
}
function forEachNested(O, f, cur){
O = [ O ]; // ensure that f is called with the top-level object
while (O.length) // keep on processing the top item on the stack
if(
!f( cur = O.pop() ) && // do not spider down if `f` returns true
cur instanceof Object && // ensure cur is an object, but not null
[Object, Array].includes(cur.constructor) //limit search to [] and {}
) O.push.apply(O, Object.values(cur)); //search all values deeper inside
}
})();
_x000D_
A "cheat" alternative might be to use JSON.stringify
to iterate. HOWEVER, JSON.stringify
will call the toString
method of each object it passes over, which may produce undesirable results if you have your own special uses for the toString
.
function forEachNested(O, f, v){
typeof O === "function" ? O(v) : JSON.stringify(O,forEachNested.bind(0,f));
return v; // so that JSON.stringify keeps on recursing
}
(function(){"use strict";
var cars = {"label":"Autos","subs":[{"label":"SUVs","subs":[]},{"label":"Trucks","subs":[{"label":"2 Wheel Drive","subs":[]},{"label":"4 Wheel Drive","subs":[{"label":"Ford","subs":[]},{"label":"Chevrolet","subs":[]}]}]},{"label":"Sedan","subs":[]}]};
var lookForCar = prompt("enter the name of the car you are looking for (e.g. 'Ford')") || 'Ford';
lookForCar = lookForCar.replace(/[^ \w]/g, ""); // incaseif the user put quotes or something around their input
lookForCar = lookForCar.toLowerCase();
var foundObject = null;
forEachNested(cars, function(currentValue){
if(currentValue.constructor === Object &&
currentValue.label.toLowerCase() === lookForCar) {
foundObject = currentValue;
}
});
if (foundObject !== null)
console.log("Found the object: " + JSON.stringify(foundObject, null, "\t"));
else
console.log('Nothing found with a label of "' + lookForCar + '" :(');
function forEachNested(O, f, v){
typeof O === "function" ? O(v) : JSON.stringify(O,forEachNested.bind(0,f));
return v; // so that JSON.stringify keeps on recursing
}
})();
_x000D_
However, while the above method might be useful for demonstration purposes, Object.values
is not supported by Internet Explorer and there are many terribly illperformant places in the code:
Array.prototype.push
and Array.prototype.pop
on every single item [lines 5 & 8],Object.values
[line 8],window.Object
or window.Object.values
[line 9],Below is a much much faster version that should be far faster than any other solution. The solution below fixes all of the performance problems listed above. However, it iterates in a much different way: it iterates all the arrays first, then iterates all the objects. It continues to iterate its present type until complete exhaustion including iteration subvalues inside the current list of the current flavor being iterated. Then, the function iterates all of the other type. By iterating until exhaustion before switching over, the iteration loop gets hotter than otherwise and iterates even faster. This method also comes with an added advantage: the callback which is called on each value gets passed a second parameter. This second parameter is the array returned from Object.values
called on the parent hash Object, or the parent Array itself.
var getValues = Object.values; // localize
var type_toString = Object.prototype.toString;
function forEachNested(objectIn, functionOnEach){
"use strict";
functionOnEach( objectIn );
// for iterating arbitrary objects:
var allLists = [ ];
if (type_toString.call( objectIn ) === '[object Object]')
allLists.push( getValues(objectIn) );
var allListsSize = allLists.length|0; // the length of allLists
var indexLists = 0;
// for iterating arrays:
var allArray = [ ];
if (type_toString.call( objectIn ) === '[object Array]')
allArray.push( objectIn );
var allArraySize = allArray.length|0; // the length of allArray
var indexArray = 0;
do {
// keep cycling back and forth between objects and arrays
for ( ; indexArray < allArraySize; indexArray=indexArray+1|0) {
var currentArray = allArray[indexArray];
var currentLength = currentArray.length;
for (var curI=0; curI < currentLength; curI=curI+1|0) {
var arrayItemInner = currentArray[curI];
if (arrayItemInner === undefined &&
!currentArray.hasOwnProperty(arrayItemInner)) {
continue; // the value at this position doesn't exist!
}
functionOnEach(arrayItemInner, currentArray);
if (typeof arrayItemInner === 'object') {
var typeTag = type_toString.call( arrayItemInner );
if (typeTag === '[object Object]') {
// Array.prototype.push returns the new length
allListsSize=allLists.push( getValues(arrayItemInner) );
} else if (typeTag === '[object Array]') {
allArraySize=allArray.push( arrayItemInner );
}
}
}
allArray[indexArray] = null; // free up memory to reduce overhead
}
for ( ; indexLists < allListsSize; indexLists=indexLists+1|0) {
var currentList = allLists[indexLists];
var currentLength = currentList.length;
for (var curI=0; curI < currentLength; curI=curI+1|0) {
var listItemInner = currentList[curI];
functionOnEach(listItemInner, currentList);
if (typeof listItemInner === 'object') {
var typeTag = type_toString.call( listItemInner );
if (typeTag === '[object Object]') {
// Array.prototype.push returns the new length
allListsSize=allLists.push( getValues(listItemInner) );
} else if (typeTag === '[object Array]') {
allArraySize=allArray.push( listItemInner );
}
}
}
allLists[indexLists] = null; // free up memory to reduce overhead
}
} while (indexLists < allListsSize || indexArray < allArraySize);
}
(function(){"use strict";
var cars = {"label":"Autos","subs":[{"label":"SUVs","subs":[]},{"label":"Trucks","subs":[{"label":"2 Wheel Drive","subs":[]},{"label":"4 Wheel Drive","subs":[{"label":"Ford","subs":[]},{"label":"Chevrolet","subs":[]}]}]},{"label":"Sedan","subs":[]}]};
var lookForCar = prompt("enter the name of the car you are looking for (e.g. 'Ford')") || 'Ford';
lookForCar = lookForCar.replace(/[^ \w]/g, ""); // incaseif the user put quotes or something around their input
lookForCar = lookForCar.toLowerCase();
var getValues = Object.values; // localize
var type_toString = Object.prototype.toString;
function forEachNested(objectIn, functionOnEach){
functionOnEach( objectIn );
// for iterating arbitrary objects:
var allLists = [ ];
if (type_toString.call( objectIn ) === '[object Object]')
allLists.push( getValues(objectIn) );
var allListsSize = allLists.length|0; // the length of allLists
var indexLists = 0;
// for iterating arrays:
var allArray = [ ];
if (type_toString.call( objectIn ) === '[object Array]')
allArray.push( objectIn );
var allArraySize = allArray.length|0; // the length of allArray
var indexArray = 0;
do {
// keep cycling back and forth between objects and arrays
for ( ; indexArray < allArraySize; indexArray=indexArray+1|0) {
var currentArray = allArray[indexArray];
var currentLength = currentArray.length;
for (var curI=0; curI < currentLength; curI=curI+1|0) {
var arrayItemInner = currentArray[curI];
if (arrayItemInner === undefined &&
!currentArray.hasOwnProperty(arrayItemInner)) {
continue; // the value at this position doesn't exist!
}
functionOnEach(arrayItemInner, currentArray);
if (typeof arrayItemInner === 'object') {
var typeTag = type_toString.call( arrayItemInner );
if (typeTag === '[object Object]') {
// Array.prototype.push returns the new length
allListsSize=allLists.push( getValues(arrayItemInner) );
} else if (typeTag === '[object Array]') {
allArraySize=allArray.push( arrayItemInner );
}
}
}
allArray[indexArray] = null; // free up memory to reduce overhead
}
for ( ; indexLists < allListsSize; indexLists=indexLists+1|0) {
var currentList = allLists[indexLists];
var currentLength = currentList.length;
for (var curI=0; curI < currentLength; curI=curI+1|0) {
var listItemInner = currentList[curI];
functionOnEach(listItemInner, currentList);
if (typeof listItemInner === 'object') {
var typeTag = type_toString.call( listItemInner );
if (typeTag === '[object Object]') {
// Array.prototype.push returns the new length
allListsSize=allLists.push( getValues(listItemInner) );
} else if (typeTag === '[object Array]') {
allArraySize=allArray.push( listItemInner );
}
}
}
allLists[indexLists] = null; // free up memory to reduce overhead
}
} while (indexLists < allListsSize || indexArray < allArraySize);
}
var foundObject = null;
forEachNested(cars, function(currentValue){
if(currentValue.constructor === Object &&
currentValue.label.toLowerCase() === lookForCar) {
foundObject = currentValue;
}
});
if (foundObject !== null) {
console.log("Found the object: " + JSON.stringify(foundObject, null, "\t"));
} else {
console.log('Nothing found with a label of "' + lookForCar + '" :(');
}
})();
_x000D_
If you have a problem with circular references (e.g. having object A's values being object A itself in such as that object A contains itself), or you just need the keys then the following slower solution is available.
function forEachNested(O, f){
O = Object.entries(O);
var cur;
function applyToEach(x){return cur[1][x[0]] === x[1]}
while (O.length){
cur = O.pop();
f(cur[0], cur[1]);
if (typeof cur[1] === 'object' && cur[1].constructor === Object &&
!O.some(applyToEach))
O.push.apply(O, Object.entries(cur[1]));
}
}
Because these methods do not use any recursion of any sort, these functions are well suited for areas where you might have thousands of levels of depth. The stack limit varies greatly from browser to browser, so recursion to an unknown depth is not very wise in Javascript.
ALTER TABLE MEN DROP COLUMN Lname
Yes, you can do that, but only if #b
is after #a
in the HTML.
If #b
comes immediately after #a
: http://jsfiddle.net/u7tYE/
#a:hover + #b {
background: #ccc
}
<div id="a">Div A</div>
<div id="b">Div B</div>
That's using the adjacent sibling combinator (+
).
If there are other elements between #a
and #b
, you can use this: http://jsfiddle.net/u7tYE/1/
#a:hover ~ #b {
background: #ccc
}
<div id="a">Div A</div>
<div>random other elements</div>
<div>random other elements</div>
<div>random other elements</div>
<div id="b">Div B</div>
That's using the general sibling combinator (~
).
Both +
and ~
work in all modern browsers and IE7+
If #b
is a descendant of #a
, you can simply use #a:hover #b
.
ALTERNATIVE: You can use pure CSS to do this by positioning the second element before the first. The first div is first in markup, but positioned to the right or below the second. It will work as if it were a previous sibling.
If your lines are exactly the way you depict them(no leading or embedded spaces), the following should serve as well
awk '{$1=$1;print}' file.txt
You can simply set a system property on the server as follows...
-Dspring.profiles.active=test
Edit: To add this to tomcat in eclipse, select Run -> Run Configurations
and choose your Tomcat run configuration. Click the Arguments
tab and add -Dspring.profiles.active=test at the end of VM arguments
. Another way would be to add the property to your catalina.properties in your Servers
project, but if you add it there omit the -D
Edit: For use with Spring Boot, you have an additional choice. You can pass the property as a program argument if you prepend the property with two dashes.
Here are two examples using a Spring Boot executable jar file...
System Property
[user@host ~]$ java -jar -Dspring.profiles.active=test myproject.jar
Program Argument
[user@host ~]$ java -jar myproject.jar --spring.profiles.active=test
use array.splice
/*array.splice(index , howMany[, element1[, ...[, elementN]]])
array.splice(index) // SpiderMonkey/Firefox extension*/
array.splice(1,1)
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
As an exercise, I would suggest doing the following:
public void save(String fileName) throws FileNotFoundException {
PrintWriter pw = new PrintWriter(new FileOutputStream(fileName));
for (Club club : clubs)
pw.println(club.getName());
pw.close();
}
This will write the name of each club on a new line in your file.
Soccer Chess Football Volleyball ...
I'll leave the loading to you. Hint: You wrote one line at a time, you can then read one line at a time.
Every class in Java extends the Object
class. As such you can override its methods. In this case, you should be interested by the toString()
method. In your Club
class, you can override it to print some message about the class in any format you'd like.
public String toString() {
return "Club:" + name;
}
You could then change the above code to:
public void save(String fileName) throws FileNotFoundException {
PrintWriter pw = new PrintWriter(new FileOutputStream(fileName));
for (Club club : clubs)
pw.println(club); // call toString() on club, like club.toString()
pw.close();
}
If the message is "n commits behind master."
You need to rebase your dev branch with master. You got the above message because after checking out dev branch from master, the master branch got new commit and has moved ahead. You need to get those new commits to your dev branch.
Steps:
git checkout master
git pull #this will update your local master
git checkout yourDevBranch
git rebase master
This generally means that the owning Hibernate session has already closed. You can do one of the following to fix it:
HibernateTemplate.initialize(object name)
lazy=false
in your hbm files.If you use the static method and load the properties file from the classpath folder so you can use the below code :
//load a properties file from class path, inside static method
Properties prop = new Properties();
prop.load(Classname.class.getClassLoader().getResourceAsStream("foo.properties"));
Well, you just fire the desired click event:
$(".first").click(function(){
$(".second").click();
return false;
});
Because of things like this, as a general rule of thumb, I try to avoid as much XAML "trickery" as possible and keep the XAML as dumb and simple as possible and do the rest in the ViewModel (or attached properties or IValueConverters etc. if really necessary).
If possible I would give the ViewModel of the current DataContext a reference (i.e. property) to the relevant parent ViewModel
public class ThisViewModel : ViewModelBase
{
TypeOfAncestorViewModel Parent { get; set; }
}
and bind against that directly instead.
<TextBox Text="{Binding Parent}" />
I've added some cocoapods magic to jjrscott's answer in case you need to use CommonCrypto in your cocoapods library.
1) Add this line to your podspec:
s.script_phase = { :name => 'CommonCrypto', :script => 'sh $PROJECT_DIR/../../install_common_crypto.sh', :execution_position => :before_compile }
2) Save this in your library folder or wherever you like (however don't forget to change the script_phase accordingly ...)
# This if-statement means we'll only run the main script if the
# CommonCrypto.framework directory doesn't exist because otherwise
# the rest of the script causes a full recompile for anything
# where CommonCrypto is a dependency
# Do a "Clean Build Folder" to remove this directory and trigger
# the rest of the script to run
FRAMEWORK_DIR="${BUILT_PRODUCTS_DIR}/CommonCrypto.framework"
if [ -d "${FRAMEWORK_DIR}" ]; then
echo "${FRAMEWORK_DIR} already exists, so skipping the rest of the script."
exit 0
fi
mkdir -p "${FRAMEWORK_DIR}/Modules"
echo "module CommonCrypto [system] {
header "${SDKROOT}/usr/include/CommonCrypto/CommonCrypto.h"
export *
}" >> "${FRAMEWORK_DIR}/Modules/module.modulemap"
ln -sf "${SDKROOT}/usr/include/CommonCrypto" "${FRAMEWORK_DIR}/Headers"
Works like a charm :)
internal members are accessible within the assembly (only accessible in the same project)
private members are accessible within the same class
There are 2 projects in a solution (Project1, Project2) and Project1 has a reference to Project2.
Yes, just open the "Source" Tab in the dev-tools and navigate to the script you want to change . Make your adjustments directly in the dev tools window and then hit ctrl+s to save the script - know the new js will be used until you refresh the whole page.
For me the problem was there was was Expanded inside the column which I had to remove and it worked.
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Expanded( // remove this
flex: 2,
child: Text("content here"),
),
],
)
Let's break this down:
The error says
Cannot invoke an expression whose type lacks a call signature.
The code:
The problem is in this line public toggleBody: string;
&
it's relation to these lines:
...
return this.toggleBody(true);
...
return this.toggleBody(false);
Your saying toggleBody
is a string
but then your treating it like something that has a call signature
(i.e. the structure of something that can be called: lambdas, proc, functions, methods, etc. In JS just function tho.). You need to change the declaration to be public toggleBody: (arg: boolean) => boolean;
.
Extra Details:
"invoke" means your calling or applying a function.
"an expression" in Javascript is basically something that produces a value, so this.toggleBody()
counts as an expression.
"type" is declared on this line public toggleBody: string
"lacks a call signature" this is because your trying to call something this.toggleBody()
that doesn't have signature(i.e. the structure of something that can be called: lambdas, proc, functions, methods, etc.) that can be called. You said this.toggleBody
is something that acts like a string.
In other words the error is saying
Cannot call an expression (this.toggleBody) because it's type (:string) lacks a call signature (bc it has a string signature.)
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6);
int[] arr= stream.mapToInt(x->x.intValue()).toArray();
git checkout branch_name file_name
Example:
git checkout master App.java
This will not work if your branch name has a period in it.
git checkout "fix.june" alive.html
error: pathspec 'fix.june' did not match any file(s) known to git.
If you have a number, for example 65, and if you want to get the corresponding ASCII character, you can use the chr
function, like this
>>> chr(65)
'A'
similarly if you have 97,
>>> chr(97)
'a'
EDIT: The above solution works for 8 bit characters or ASCII characters. If you are dealing with unicode characters, you have to specify unicode value of the starting character of the alphabet to ord
and the result has to be converted using unichr
instead of chr
.
>>> print unichr(ord(u'\u0B85'))
?
>>> print unichr(1 + ord(u'\u0B85'))
?
NOTE: The unicode characters used here are of the language called "Tamil", my first language. This is the unicode table for the same http://www.unicode.org/charts/PDF/U0B80.pdf
Try this code:
CONVERT(varchar(15), date_started, 103)
<?php
session_start();
if($_SESSION['login'] != 'ok')
header('location: /dashboard.php?login=0');
if(isset($_SESSION['last-activity']) && time() - $_SESSION['last-activity'] > 600) {
// session inactive more than 10 min
header('location: /logout.php?timeout=1');
}
$_SESSION['last-activity'] = time(); // update last activity time stamp
if(time() - $_SESSION['created'] > 600) {
// session started more than 10 min ago
session_regenerate_id(true); // change session id and invalidate old session
$_SESSION['created'] = time(); // update creation time
}
?>
I experienced the same issue as the OP - Wordpress keeps redirecting to install-php after migration.
Problem was my database tables are named as prefix_tablename
and I missed the underscore from $table_prefix
in wp-config
.
$table_prefix = 'myprefix';
should have been
$table_prefix = 'myprefix_';
Only learning myself, but wrapping in a View may allow you to add styles around the button.
const Stack = StackNavigator({
Home: {
screen: HomeView,
navigationOptions: {
title: 'Home View'
}
},
CoolView: {
screen: CoolView,
navigationOptions: ({navigation}) => ({
title: 'Cool View',
headerRight: (<View style={{marginRight: 16}}><Button
title="Cool"
onPress={() => alert('cool')}
/></View>
)
})
}
})
Adding to Sani's and blak3r's answers, I've added the following to the startup code for my application, but in VB:
'** Overriding the certificate validation check.
Net.ServicePointManager.ServerCertificateValidationCallback = Function(sender, certificate, chain, sslPolicyErrors) True
Seems to do the trick.
A random value?
If you want a random value, try
<?php
$value = mt_rand($min, $max);
mt_rand() will run a bit more random if you are using many random numbers in a row, or if you might ever execute the script more than once a second. In general, you should use mt_rand() over rand() if there is any doubt.
"A picture is worth a thousand words".
I have a simple example here, it's similar to your case.
string s1 = "abc";
string s2 = s1;
s1 = "def";
Console.WriteLine(s2);
// Output: abc
This is what happened:
s1
and s2
variables reference to the same "abc"
string object."abc"
string object do not modify itself (to "def"
), but a new "def"
string object is created instead, and then s1
references to it.s2
still references to "abc"
string object, so that's the output.Here's my 2 cents: I had the same problem and I tried using Notepad++ to convert to UTF-8 no BOM, and also the old "copy to MS notepad then back again" trick, all to no avail. My problem was solved by making sure all files (and 'included' files) were the same file system; I had some files that were Windows format and some that had been copied off a remote Linux server, so were in UNIX format.
Why not just use CSS?
.parent:hover .child, .parent.hover .child { display: block; }
and then add JS for IE6 (inside a conditional comment for instance) which doesn't support :hover properly:
jQuery('.parent').hover(function () {
jQuery(this).addClass('hover');
}, function () {
jQuery(this).removeClass('hover');
});
Here's a quick example: Fiddle
There are a lot of answers here that use a set(..)
(which is fast given the elements are hashable), or a list (which has the downside that it results in an O(n2) algorithm.
The function I propose is a hybrid one: we use a set(..)
for items that are hashable, and a list(..)
for the ones that are not. Furthermore it is implemented as a generator such that we can for instance limit the number of items, or do some additional filtering.
Finally we also can use a key
argument to specify in what way the elements should be unique. For instance we can use this if we want to filter a list of strings such that every string in the output has a different length.
def uniq(iterable, key=lambda x: x):
seens = set()
seenl = []
for item in iterable:
k = key(item)
try:
seen = k in seens
except TypeError:
seen = k in seenl
if not seen:
yield item
try:
seens.add(k)
except TypeError:
seenl.append(k)
We can now for instance use this like:
>>> list(uniq(["apple", "pear", "banana", "lemon"], len))
['apple', 'pear', 'banana']
>>> list(uniq(["apple", "pear", "lemon", "banana"], len))
['apple', 'pear', 'banana']
>>> list(uniq(["apple", "pear", {}, "lemon", [], "banana"], len))
['apple', 'pear', {}, 'banana']
>>> list(uniq(["apple", "pear", {}, "lemon", [], "banana"]))
['apple', 'pear', {}, 'lemon', [], 'banana']
>>> list(uniq(["apple", "pear", {}, "lemon", {}, "banana"]))
['apple', 'pear', {}, 'lemon', 'banana']
It is thus a uniqeness filter that can work on any iterable and filter out uniques, regardless whether these are hashable or not.
It makes one assumption: that if one object is hashable, and another one is not, the two objects are never equal. This can strictly speaking happen, although it would be very uncommon.
If you have a huge data-set, then you can use an easy but faster(execution time) way of doing this using swifter:
import pandas as pd
import swifter
def fnc(m,x,c):
return m*x+c
df = pd.DataFrame({"m": [1,2,3,4,5,6], "c": [1,1,1,1,1,1], "x":[5,3,6,2,6,1]})
df["y"] = df.swifter.apply(lambda x: fnc(x.m, x.x, x.c), axis=1)
why not to take advantage of modern browsers css transition and make things simpler and fast using more css and less jquery
Here is the code for sliding up and down
Here is the code for sliding left to right
Similarly we can change the sliding from top to bottom or right to left by changing transform-origin and transform: scaleX(0) or transform: scaleY(0) appropriately.
I just want to add that if you don't inheritently know the name of a domain controller, you can get the closest one, pass it's hostname to the -Server
argument.
$dc = Get-ADDomainController -DomainName example.com -Discover -NextClosestSite
Get-ADUser -Server $dc.HostName[0] `
-Filter { EmailAddress -Like "*Smith_Karla*" } `
-Properties EmailAddress
And another expansion:
# create dummy matrix
set.seed(10)
m <- matrix(round(runif(25, 1, 5)), 5)
d <- as.data.frame(m)
If you want to assign new column names you can do following on data.frame
:
# an identical effect can be achieved with colnames()
names(d) <- LETTERS[1:5]
> d
A B C D E
1 3 2 4 3 4
2 2 2 3 1 3
3 3 2 1 2 4
4 4 3 3 3 2
5 1 3 2 4 3
If you, however run previous command on matrix
, you'll mess things up:
names(m) <- LETTERS[1:5]
> m
[,1] [,2] [,3] [,4] [,5]
[1,] 3 2 4 3 4
[2,] 2 2 3 1 3
[3,] 3 2 1 2 4
[4,] 4 3 3 3 2
[5,] 1 3 2 4 3
attr(,"names")
[1] "A" "B" "C" "D" "E" NA NA NA NA NA NA NA NA NA NA NA NA NA NA
[20] NA NA NA NA NA NA
Since matrix can be regarded as two-dimensional vector, you'll assign names only to first five values (you don't want to do that, do you?). In this case, you should stick with colnames()
.
So there...
From the official Spring documentation:
General interface that represents binding results. Extends the interface for error registration capabilities, allowing for a Validator to be applied, and adds binding-specific analysis and model building.
Serves as result holder for a DataBinder, obtained via the DataBinder.getBindingResult() method. BindingResult implementations can also be used directly, for example to invoke a Validator on it (e.g. as part of a unit test).
I hope it's simple and pythonic enough:
def is_valid_ip(ip):
m = re.match(r"^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$", ip)
return bool(m) and all(map(lambda n: 0 <= int(n) <= 255, m.groups()))
You can try this
<select name="select1" onmousedown="if(this.options.length>8){this.size=8;}" onchange='this.size=0;' onblur="this.size=0;">_x000D_
<option value="1">This is select number 1</option>_x000D_
<option value="2">This is select number 2</option>_x000D_
<option value="3">This is select number 3</option>_x000D_
<option value="4">This is select number 4</option>_x000D_
<option value="5">This is select number 5</option>_x000D_
<option value="6">This is select number 6</option>_x000D_
<option value="7">This is select number 7</option>_x000D_
<option value="8">This is select number 8</option>_x000D_
<option value="9">This is select number 9</option>_x000D_
<option value="10">This is select number 10</option>_x000D_
<option value="11">This is select number 11</option>_x000D_
<option value="12">This is select number 12</option>_x000D_
</select>
_x000D_
It worked for me
there are some mistakes in your code - the first: you havn't closed you p
-tag:
<a href="http//www.google.com"><p style="text-align:center">Search</p></a>
next: p
stands for 'paragraph' and is a block-element (so it's causing a line-break). what you wanted to use there is a span
, wich is just an inline-element for formatting:
<a href="http//www.google.com"><span style="text-align:center">Search</span></a>
but if you just want to add a style to your link, why don't you set the style for that link directly:
<a href="http//www.google.com" style="text-align:center">Search</a>
in the end, this would at least be correct html, but still not exactly what you want, because text-align:center
centers the text in that element, so you would have to set that for the element that contains this links (this piece of html isn't posted, so i can't correct you, but i hope you understand) - to show this, i'll use a simple div
:
<div style="text-align:center">
<a href="http//www.google.com">Search</a>
<!-- more links here -->
</div>
EDIT: some more additions to your question:
p
is not a 'function', but you're right, this is causing the problem (because it's a block-element)All previous examples will raise an exception in case your string is not long enough.
Another approach is to use
'yourstring'.ljust(100)[:100].strip()
.
This will give you first 100 chars. You might get a shorter string in case your string last chars are spaces.
If you have a situation where you are using dynamic columns in your pivot statement you could use the following:
DECLARE @cols NVARCHAR(MAX)
DECLARE @colsWithNoNulls NVARCHAR(MAX)
DECLARE @query NVARCHAR(MAX)
SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(Name)
FROM Hospital
WHERE Active = 1 AND StateId IS NOT NULL
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
SET @colsWithNoNulls = STUFF(
(
SELECT distinct ',ISNULL(' + QUOTENAME(Name) + ', ''No'') ' + QUOTENAME(Name)
FROM Hospital
WHERE Active = 1 AND StateId IS NOT NULL
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
EXEC ('
SELECT Clinician, ' + @colsWithNoNulls + '
FROM
(
SELECT DISTINCT p.FullName AS Clinician, h.Name, CASE WHEN phl.personhospitalloginid IS NOT NULL THEN ''Yes'' ELSE ''No'' END AS HasLogin
FROM Person p
INNER JOIN personlicense pl ON pl.personid = p.personid
INNER JOIN LicenseType lt on lt.licensetypeid = pl.licensetypeid
INNER JOIN licensetypegroup ltg ON ltg.licensetypegroupid = lt.licensetypegroupid
INNER JOIN Hospital h ON h.StateId = pl.StateId
LEFT JOIN PersonHospitalLogin phl ON phl.personid = p.personid AND phl.HospitalId = h.hospitalid
WHERE ltg.Name = ''RN'' AND
pl.licenseactivestatusid = 2 AND
h.Active = 1 AND
h.StateId IS NOT NULL
) AS Results
PIVOT
(
MAX(HasLogin)
FOR Name IN (' + @cols + ')
) p
')
There is a way to remove a child element via SimpleXml. The code looks for a element, and does nothing. Otherwise it adds the element to a string. It then writes out the string to a file. Also note that the code saves a backup before overwriting the original file.
$username = $_GET['delete_account'];
echo "DELETING: ".$username;
$xml = simplexml_load_file("users.xml");
$str = "<?xml version=\"1.0\"?>
<users>";
foreach($xml->children() as $child){
if($child->getName() == "user") {
if($username == $child['name']) {
continue;
} else {
$str = $str.$child->asXML();
}
}
}
$str = $str."
</users>";
echo $str;
$xml->asXML("users_backup.xml");
$myFile = "users.xml";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, $str);
fclose($fh);
This error occurs when you're trying to target an element that is wrapped in a condition.
So, here if I use ngIf in place of [hidden], it will give me TypeError: Cannot read property 'nativeElement' of undefined
So use [hidden], class.show or class.hide in place of *ngIf.
<button (click)="displayMap()" class="btn btn-primary">Display Map</button>
<div [hidden]="!display">
<div #mapContainer id="map">Content to render when condition is true.</div>
</div>
In addition to the accepted answer I would like to give an answer that shows how to iterate directly over the Newtonsoft collections. It uses less code and I'm guessing its more efficient as it doesn't involve converting the collections.
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
//Parse the data
JObject my_obj = JsonConvert.DeserializeObject<JObject>(your_json);
foreach (KeyValuePair<string, JToken> sub_obj in (JObject)my_obj["ADDRESS_MAP"])
{
Console.WriteLine(sub_obj.Key);
}
I started doing this myself because JsonConvert automatically deserializes nested objects as JToken (which are JObject, JValue, or JArray underneath I think).
I think the parsing works according to the following principles:
Every object is abstracted as a JToken
Cast to JObject where you expect a Dictionary
Cast to JValue if the JToken represents a terminal node and is a value
Cast to JArray if its an array
JValue.Value gives you the .NET type you need
Hope this layout works, take it to the binary representation with an XOR:
66h = 102 decimal = 01100110 binary
FAh = 250 decimal = 11111010 binary
------------------------------------
10011100 binary <------ that's 9Ch/156 decimal
but the wiki I linked earlier will give you more details if needed...thats what it looks like they are doing in the screenshot you provided
Since you need to match content without including it in the result (must
match name="
but it's not part of the desired result) some form of
zero-width matching or group capturing is required. This can be done
easily with the following tools:
With Perl you could use the n
option to loop line by line and print
the content of a capturing group if it matches:
perl -ne 'print "$1\n" if /name="(.*?)"/' filename
If you have an improved version of grep, such as GNU grep, you may have
the -P
option available. This option will enable Perl-like regex,
allowing you to use \K
which is a shorthand lookbehind. It will reset
the match position, so anything before it is zero-width.
grep -Po 'name="\K.*?(?=")' filename
The o
option makes grep print only the matched text, instead of the
whole line.
Another way is to use a text editor directly. With Vim, one of the
various ways of accomplishing this would be to delete lines without
name=
and then extract the content from the resulting lines:
:v/.*name="\v([^"]+).*/d|%s//\1
If you don't have access to these tools, for some reason, something similar could be achieved with standard grep. However, without the look around it will require some cleanup later:
grep -o 'name="[^"]*"' filename
In all of the commands above the results will be sent to stdout
. It's
important to remember that you can always save them by piping it to a
file by appending:
> result
to the end of the command.
The Control class has HorizontalContentAlignment and VerticalContentAlignment properties. These properties determine how a controlโs content fills the space within the control.
Set HorizontalContentAlignment and VerticalContentAlignment to Center.
It looks like API level 11 has support for what you need. See WebViewClient.shouldInterceptRequest()
.
With dplyr 0.7.2
, you can use the very useful case_when
function :
x=read.table(
text="V1 V2 V3 V4
1 1 2 3 5
2 2 4 4 1
3 1 4 1 1
4 4 5 1 3
5 5 5 5 4")
x$V5 = case_when(x$V1==1 & x$V2!=4 ~ 1,
x$V2==4 & x$V3!=1 ~ 2,
TRUE ~ 0)
Expressed with dplyr::mutate
, it gives:
x = x %>% mutate(
V5 = case_when(
V1==1 & V2!=4 ~ 1,
V2==4 & V3!=1 ~ 2,
TRUE ~ 0
)
)
Please note that NA
are not treated specially, as it can be misleading. The function will return NA
only when no condition is matched. If you put a line with TRUE ~ ...
, like I did in my example, the return value will then never be NA
.
Therefore, you have to expressively tell case_when
to put NA
where it belongs by adding a statement like is.na(x$V1) | is.na(x$V3) ~ NA_integer_
. Hint: the dplyr::coalesce()
function can be really useful here sometimes!
Moreover, please note that NA
alone will usually not work, you have to put special NA
values : NA_integer_
, NA_character_
or NA_real_
.
I have just seen the following:
set mem inaccessible-by-default [on|off]
It might allow you to search without regard if the memory is accessible.
And an alternative without using any arithmetic and numbers (although there is nothing wrong with that):
SQL> with some_birthdays as
2 ( select date '1968-06-09' d from dual union all
3 select date '1970-06-10' from dual union all
4 select date '1972-06-11' from dual union all
5 select date '1974-12-11' from dual union all
6 select date '1976-09-17' from dual
7 )
8 select trunc(sysdate) today
9 , d birth_date
10 , extract(year from numtoyminterval(months_between(trunc(sysdate),d),'month')) age
11 from some_birthdays
12 /
TODAY BIRTH_DATE AGE
------------------- ------------------- ----------
10-06-2010 00:00:00 09-06-1968 00:00:00 42
10-06-2010 00:00:00 10-06-1970 00:00:00 40
10-06-2010 00:00:00 11-06-1972 00:00:00 37
10-06-2010 00:00:00 11-12-1974 00:00:00 35
10-06-2010 00:00:00 17-09-1976 00:00:00 33
5 rows selected.
However, avpicture_get_size is defined.
No, as the header (<libavcodec/avcodec.h>
) just declares it.
The definition is in the library itself.
So you might like to add the linker option to link libavcodec
when invoking gcc:
-lavcodec
Please also note that libraries need to be specified on the command line after the files needing them:
gcc -I$HOME/ffmpeg/include program.c -lavcodec
Not like this:
gcc -lavcodec -I$HOME/ffmpeg/include program.c
Referring to Wyzard's comment, the complete command might look like this:
gcc -I$HOME/ffmpeg/include program.c -L$HOME/ffmpeg/lib -lavcodec
For libraries not stored in the linkers standard location the option -L
specifies an additional search path to lookup libraries specified using the -l
option, that is libavcodec.x.y.z
in this case.
For a detailed reference on GCC's linker option, please read here.
I needed to read several answers and some other info to understand what I was doing.
1. Ignore everything older than a certain commit
The file .git/info/grafts
can define fake parents for a commit. A line with just a commit id, says that the commit doesn't have a parent. If we wanted to say that we care only about the last 2000 commits, we can type:
git rev-parse HEAD~2000 > .git/info/grafts
git rev-parse gives us the commit id of the 2000th parent of the current commit. The above command will overwrite the grafts file if present. Check if it's there first.
2. Rewrite the Git history (optional)
If you want to make this grafted fake parent a real one, then run:
git filter-branch -- --all
It will change all commit ids. Every copy of this repository needs to be updated forcefully.
3. Clean up disk space
I didn't done step 2, because I wanted my copy to stay compatible with the upstream. I just wanted to save some disk space. In order to forget all the old commits:
git prune
git gc
Alternative: shallow copies
If you have a shallow copy of another repository and just want to save some disk space, you can update .git/shallow
. But be careful that nothing is pointing at a commit from before. So you could run something like this:
git fetch --prune
git rev-parse HEAD~2000 > .git/shallow
git prune
git gc
The entry in shallow works like a graft. But be careful not to use grafts and shallow at the same time. At least, don't have the same entries in there, it will fail.
If you still have some old references (tags, branches, remote heads) that point to older commits, they won't be cleaned up and you won't save more disk space.
InstallUtil classes ( ServiceInstaller ) are considered an anti-pattern by the Windows Installer community. It's a fragile, out of process, reinventing of the wheel that ignores the fact that Windows Installer has built-in support for Services.
Visual Studio deployment projects ( also not highly regarded and deprecated in the next release of Visual Studio ) do not have native support for services. But they can consume merge modules. So I would take a look at this blog article to understand how to create a merge module using Windows Installer XML that can express the service and then consume that merge module in your VDPROJ solution.
Augmenting InstallShield using Windows Installer XML - Windows Services
I had the exact same issue, found this fix on another site: powershell.exe "Get-Process processname| Stop-Process" it worked for me and I was in the same boat where I had to restart, the /T would not work.
There's no "step-by-step" here. When initialization is performed with constant expressions, the process is essentially performed at compile time. Of course, if the array is declared as a local object, it is allocated locally and initialized at run-time, but that can be still thought of as a single-step process that cannot be meaningfully subdivided.
Designated initializers allow you to supply an initializer for a specific member of struct object (or a specific element of an array). All other members get zero-initialized. So, if my_data
is declared as
typedef struct my_data {
int a;
const char *name;
double x;
} my_data;
then your
my_data data[]={
{ .name = "Peter" },
{ .name = "James" },
{ .name = "John" },
{ .name = "Mike" }
};
is simply a more compact form of
my_data data[4]={
{ 0, "Peter", 0 },
{ 0, "James", 0 },
{ 0, "John", 0 },
{ 0, "Mike", 0 }
};
I hope you know what the latter does.
User JQuery is EmptyObject to check whether array is contains elements or not.
var testArray=[1,2,3,4,5];
var testArray1=[];
console.log(jQuery.isEmptyObject(testArray)); //false
console.log(jQuery.isEmptyObject(testArray1)); //true
Click Developer Tools to inspect element. You may also use keyboard shortcuts, such as CtrlL+Shift+I, F12 (or Fn+F12), etc.
Here you can create schema using StructType in scala and pass the Empty RDD so you will able to create empty table. Following code is for the same.
import org.apache.spark.SparkConf
import org.apache.spark.SparkContext
import org.apache.spark.sql._
import org.apache.spark.sql.Row
import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.types.StructType
import org.apache.spark.sql.types.StructField
import org.apache.spark.sql.types.IntegerType
import org.apache.spark.sql.types.BooleanType
import org.apache.spark.sql.types.LongType
import org.apache.spark.sql.types.StringType
//import org.apache.hadoop.hive.serde2.objectinspector.StructField
object EmptyTable extends App {
val conf = new SparkConf;
val sc = new SparkContext(conf)
//create sparksession object
val sparkSession = SparkSession.builder().enableHiveSupport().getOrCreate()
//Created schema for three columns
val schema = StructType(
StructField("Emp_ID", LongType, true) ::
StructField("Emp_Name", StringType, false) ::
StructField("Emp_Salary", LongType, false) :: Nil)
//Created Empty RDD
var dataRDD = sc.emptyRDD[Row]
//pass rdd and schema to create dataframe
val newDFSchema = sparkSession.createDataFrame(dataRDD, schema)
newDFSchema.createOrReplaceTempView("tempSchema")
sparkSession.sql("create table Finaltable AS select * from tempSchema")
}
I know this is a jQuery
related question, but now days with JS ES6 things are much easier. Since there is no pure javascript
answer, I thought I could add a simple pure javascript
solution to this, which in my opinion is much cleaner, by using the fetch()
API. This a modern way to implements network requests. In your case, since you already have a form element we can simply use it to build our request.
const form = document.forms["orderproductForm"];
const formInputs = form.getElementsByTagName("input");
let formData = new FormData();
for (let input of formInputs) {
formData.append(input.name, input.value);
}
fetch(form.action,
{
method: form.method,
body: formData
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log(error.message))
.finally(() => console.log("Done"));
An easy way of doing this:
SELECT ('[' || to_json('Some "text"'::TEXT) || ']')::json ->> 0;
Just convert the json string into a json list
Google disallows automated access in their TOS, so if you accept their terms you would break them.
That said, I know of no lawsuit from Google against a scraper. Even Microsoft scraped Google, they powered their search engine Bing with it. They got caught in 2011 red handed :)
There are two options to scrape Google results:
1) Use their API
UPDATE 2020: Google has reprecated previous APIs (again) and has new prices and new limits. Now (https://developers.google.com/custom-search/v1/overview) you can query up to 10k results per day at 1,500 USD per month, more than that is not permitted and the results are not what they display in normal searches.
You can issue around 40 requests per hour You are limited to what they give you, it's not really useful if you want to track ranking positions or what a real user would see. That's something you are not allowed to gather.
If you want a higher amount of API requests you need to pay.
60 requests per hour cost 2000 USD per year, more queries require a custom deal.
2) Scrape the normal result pages
3) Alternatively use a scraping service (updated)
Improving the amazing answer from @Brandon, I added type to ntext and xml using castings:
BEGIN TRAN
DECLARE @SearchStr nvarchar(100) = 'SEARCH_TEXT'
DECLARE @Results TABLE (ColumnName nvarchar(370), ColumnValue nvarchar(3630))
SET NOCOUNT ON
DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
SET @TableName = ''
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')
WHILE @TableName IS NOT NULL
BEGIN
SET @ColumnName = ''
SET @TableName =
(
SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
AND OBJECTPROPERTY(
OBJECT_ID(
QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
), 'IsMSShipped'
) = 0
)
WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
BEGIN
SET @ColumnName =
(
SELECT MIN(QUOTENAME(COLUMN_NAME))
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = PARSENAME(@TableName, 2)
AND TABLE_NAME = PARSENAME(@TableName, 1)
AND DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar', 'int', 'decimal', 'ntext', 'xml')
AND QUOTENAME(COLUMN_NAME) > @ColumnName
)
IF @ColumnName IS NOT NULL
BEGIN
INSERT INTO @Results
EXEC
(
'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT((cast(' + @ColumnName + ' as nvarchar(max))), 3630)
FROM ' + @TableName + ' (NOLOCK) ' +
' WHERE (cast(' + @ColumnName + ' as nvarchar(max))) LIKE ' + @SearchStr2
)
END
END
END
SELECT ColumnName, ColumnValue FROM @Results
ROLLBACK
Below are two methods that are superior to looping. Both handle a "no-find" case.
VLOOKUP
with error-handling if the variable doesn't exist (INDEX/MATCH
may be a better route than VLOOKUP
, ie if your two columns A and B were in reverse order, or were far apart)VBAs FIND
method (matching a whole string in column A given I use the xlWhole
argument)
Sub Method1()
Dim strSearch As String
Dim strOut As String
Dim bFailed As Boolean
strSearch = "trees"
On Error Resume Next
strOut = Application.WorksheetFunction.VLookup(strSearch, Range("A:B"), 2, False)
If Err.Number <> 0 Then bFailed = True
On Error GoTo 0
If Not bFailed Then
MsgBox "corresponding value is " & vbNewLine & strOut
Else
MsgBox strSearch & " not found"
End If
End Sub
Sub Method2()
Dim rng1 As Range
Dim strSearch As String
strSearch = "trees"
Set rng1 = Range("A:A").Find(strSearch, , xlValues, xlWhole)
If Not rng1 Is Nothing Then
MsgBox "Find has matched " & strSearch & vbNewLine & "corresponding cell is " & rng1.Offset(0, 1)
Else
MsgBox strSearch & " not found"
End If
End Sub
This is significantly faster than the EXISTS
way:
SELECT [EmailAddress], [CustomerName] FROM [Customers] WHERE [EmailAddress] IN
(SELECT [EmailAddress] FROM [Customers] GROUP BY [EmailAddress] HAVING COUNT(*) > 1)
1) You can use Fetch API to fetch data from Endd Points:
Example fetching all Github
repose for a user
/* Fetch GitHub Repos */
fetchData = () => {
//show progress bar
this.setState({ isLoading: true });
//fetch repos
fetch(`https://api.github.com/users/hiteshsahu/repos`)
.then(response => response.json())
.then(data => {
if (Array.isArray(data)) {
console.log(JSON.stringify(data));
this.setState({ repos: data ,
isLoading: false});
} else {
this.setState({ repos: [],
isLoading: false
});
}
});
};
2) Other Alternative is Axios
Using axios you can cut out the middle step of passing the results of the http request to the .json() method. Axios just returns the data object you would expect.
import axios from "axios";
/* Fetch GitHub Repos */
fetchDataWithAxios = () => {
//show progress bar
this.setState({ isLoading: true });
// fetch repos with axios
axios
.get(`https://api.github.com/users/hiteshsahu/repos`)
.then(result => {
console.log(result);
this.setState({
repos: result.data,
isLoading: false
});
})
.catch(error =>
this.setState({
error,
isLoading: false
})
);
}
Now you can choose to fetch data using any of this strategies in componentDidMount
class App extends React.Component {
state = {
repos: [],
isLoading: false
};
componentDidMount() {
this.fetchData ();
}
Meanwhile you can show progress bar while data is loading
{this.state.isLoading && <LinearProgress />}
Select [Column Name] into [New Table] from [Source Table]
Other solution is:
public static T Deserialize<T>(string rawXml)
{
using (XmlReader reader = XmlReader.Create(new StringReader(rawXml)))
{
DataContractSerializer formatter0 =
new DataContractSerializer(typeof(T));
return (T)formatter0.ReadObject(reader);
}
}
One remark: sometimes it happens that raw xml contains e.g.:
<?xml version="1.0" encoding="utf-16"?>
then of course you can't use UTF8 encoding used in other examples..
const date1 = new Date('7/13/2010');_x000D_
const date2 = new Date('12/15/2010');_x000D_
const diffTime = Math.abs(date2 - date1);_x000D_
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)); _x000D_
console.log(diffTime + " milliseconds");_x000D_
console.log(diffDays + " days");
_x000D_
Observe that we need to enclose the date in quotes. The rest of the code gets the time difference in milliseconds and then divides to get the number of days. Date expects mm/dd/yyyy format.
Looks like E*Trade has an API now.
For access to historical data, I've found EODData to have reasonable prices for their data dumps. For side projects, I can't afford (rather don't want to afford) a huge subscription fee just for some data to tinker with.
EventArgs e
is a parameter called e that contains the event data, see the EventArgs MSDN page for more information.
Object Sender
is a parameter called Sender that contains a reference to the control/object that raised the event.
Event Arg Class: http://msdn.microsoft.com/en-us/library/system.eventargs.aspx
Example:
protected void btn_Click (object sender, EventArgs e){
Button btn = sender as Button;
btn.Text = "clicked!";
}
Edit: When Button is clicked, the btn_Click event handler will be fired. The "object sender" portion will be a reference to the button which was clicked
You can use the pskill
function in the R
"tools" package to interrupt the current process and return to the console. Concretely, I have the following function defined in a startup file that I source at the beginning of each script. You can also copy it directly at the start of your code, however. Then insert halt()
at any point in your code to stop script execution on the fly. This function works well on GNU/Linux and judging from the R
documentation, it should also work on Windows (but I didn't check).
# halt: interrupts the current R process; a short iddle time prevents R from
# outputting further results before the SIGINT (= Ctrl-C) signal is received
halt <- function(hint = "Process stopped.\n") {
writeLines(hint)
require(tools, quietly = TRUE)
processId <- Sys.getpid()
pskill(processId, SIGINT)
iddleTime <- 1.00
Sys.sleep(iddleTime)
}
Is it possible to do it this way, as opposed to using something like Raphael or jQuery SVG?
Definitely.
If it is possible, what's the technique?
This annotated code snippet works:
<!DOCTYPE html>
<html>
<head>
<title>SVG Illustrator Test</title>
</head>
<body>
<object data="alpha.svg" type="image/svg+xml"
id="alphasvg" width="100%" height="100%"></object>
<script>
var a = document.getElementById("alphasvg");
// It's important to add an load event listener to the object,
// as it will load the svg doc asynchronously
a.addEventListener("load",function(){
// get the inner DOM of alpha.svg
var svgDoc = a.contentDocument;
// get the inner element by id
var delta = svgDoc.getElementById("delta");
// add behaviour
delta.addEventListener("mousedown",function(){
alert('hello world!')
}, false);
}, false);
</script>
</body>
</html>
Note that a limitation of this technique is that it is restricted by the same-origin policy, so alpha.svg
must be hosted on the same domain as the .html
file, otherwise the inner DOM of the object will be inaccessible.
Important thing to run this HTML, you need host HTML file to web server like IIS, Tomcat
Here are two ways to accept a file. One using in memory provider MultipartMemoryStreamProvider and one using MultipartFormDataStreamProvider which saves to a disk. Note, this is only for one file upload at a time. You can certainty extend this to save multiple-files. The second approach can support large files. I've tested files over 200MB and it works fine. Using in memory approach does not require you to save to disk, but will throw out of memory exception if you exceed a certain limit.
private async Task<Stream> ReadStream()
{
Stream stream = null;
var provider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider);
foreach (var file in provider.Contents)
{
var buffer = await file.ReadAsByteArrayAsync();
stream = new MemoryStream(buffer);
}
return stream;
}
private async Task<Stream> ReadLargeStream()
{
Stream stream = null;
string root = Path.GetTempPath();
var provider = new MultipartFormDataStreamProvider(root);
await Request.Content.ReadAsMultipartAsync(provider);
foreach (var file in provider.FileData)
{
var path = file.LocalFileName;
byte[] content = File.ReadAllBytes(path);
File.Delete(path);
stream = new MemoryStream(content);
}
return stream;
}
This solution worked for me. Try this, add following lines in your app's build.gradle file
splits {
abi {
enable true
reset()
include 'x86', 'armeabi-v7a'
universalApk true
}
}
#/bin/bash
TESTSTR="abc,def,ghij"
for i in $(echo $TESTSTR | tr ',' '\n')
do
echo $i
done
I prefer to use tr instead of sed, becouse sed have problems with special chars like \r \n in some cases.
other solution is to set IFS to certain separator
That's my take:
<ControlTemplate>
<Grid>
<Grid.Resources>
<!--Define look / layout for both TextBoxes here. I applied custom Padding and BorderThickness for my application-->
<Style TargetType="TextBox">
<Setter Property="Padding" Value="4"/>
<Setter Property="BorderThickness" Value="2"/>
</Style>
</Grid.Resources>
<TextBox x:Name="TbSearch"/>
<TextBox x:Name="TbHint" Text="Suche" Foreground="LightGray"
Visibility="Hidden" IsHitTestVisible="False" Focusable="False"/>
</Grid>
<ControlTemplate.Triggers>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition SourceName="TbSearch" Property="Text" Value="{x:Static sys:String.Empty}"/>
<Condition SourceName="TbSearch" Property="IsKeyboardFocused" Value="False"/>
</MultiTrigger.Conditions>
<MultiTrigger.Setters>
<Setter TargetName="TbHint" Property="Visibility" Value="Visible"/>
</MultiTrigger.Setters>
</MultiTrigger>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition SourceName="TbSearch" Property="Text" Value="{x:Null}"/>
<Condition SourceName="TbSearch" Property="IsKeyboardFocused" Value="False"/>
</MultiTrigger.Conditions>
<MultiTrigger.Setters>
<Setter TargetName="TbHint" Property="Visibility" Value="Visible"/>
</MultiTrigger.Setters>
</MultiTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
Most other answers including the top one have flaws in my opinion.
This solution works under all circumstances. Pure XAML, easily reusable.
Based on unlimit's post on How to properly split a CSV using C# split() function? :
string[] tokens = System.Text.RegularExpressions.Regex.Split(paramString, ",");
NOTE: this doesn't handle escaped / nested commas, etc., and therefore is only suitable for certain simple CSV lists.
my_df = pd.DataFrame.from_dict(my_dict, orient='index', columns=['my_col'])
.. would have parsed the dict properly (putting each dict key into a separate df column, and key values into df rows), so the dicts would not get squashed into a single column in the first place.
There is very simplest way among all these answers.
Simply write following code inside onBackPressed()
method.
long back_pressed;
@Override
public void onBackPressed() {
if (back_pressed + 1000 > System.currentTimeMillis()){
super.onBackPressed();
}
else{
Toast.makeText(getBaseContext(),
"Press once again to exit!", Toast.LENGTH_SHORT)
.show();
}
back_pressed = System.currentTimeMillis();
}
You need to define back_pressed
object as long
in activity.
If you want to test the index to see if it works, here is the syntax:
SELECT *
FROM Table WITH(INDEX(Index_Name))
The WITH statement will force the index to be used.
Manually editing the .csproj file and adding the reference below worked for me.
<Reference Include="netstandard" />
Thank you to Fahad Alshaya who suggested it here.
If you can define the parent's width and height, there's a simpler way to centralize the image without having to create a container for it.
For some reason, if you define the min-width, IE will recognize max-width as well.
This solution works for IE10+, Firefox and Chrome.
<div>
<img src="http://placehold.it/350x150"/>
</div>
div {
display: -ms-flexbox;
display: flex;
-ms-flex-pack: center;
justify-content: center;
-ms-flex-align: center;
align-items: center;
border: 1px solid orange;
width: 100px;
height: 100px;
}
img{
min-width: 10%;
max-width: 100%;
min-height: 10%;
max-height: 100%;
}
Here is a sample tokenizer class that might do what you want
//Header file
class Tokenizer
{
public:
static const std::string DELIMITERS;
Tokenizer(const std::string& str);
Tokenizer(const std::string& str, const std::string& delimiters);
bool NextToken();
bool NextToken(const std::string& delimiters);
const std::string GetToken() const;
void Reset();
protected:
size_t m_offset;
const std::string m_string;
std::string m_token;
std::string m_delimiters;
};
//CPP file
const std::string Tokenizer::DELIMITERS(" \t\n\r");
Tokenizer::Tokenizer(const std::string& s) :
m_string(s),
m_offset(0),
m_delimiters(DELIMITERS) {}
Tokenizer::Tokenizer(const std::string& s, const std::string& delimiters) :
m_string(s),
m_offset(0),
m_delimiters(delimiters) {}
bool Tokenizer::NextToken()
{
return NextToken(m_delimiters);
}
bool Tokenizer::NextToken(const std::string& delimiters)
{
size_t i = m_string.find_first_not_of(delimiters, m_offset);
if (std::string::npos == i)
{
m_offset = m_string.length();
return false;
}
size_t j = m_string.find_first_of(delimiters, i);
if (std::string::npos == j)
{
m_token = m_string.substr(i);
m_offset = m_string.length();
return true;
}
m_token = m_string.substr(i, j - i);
m_offset = j;
return true;
}
Example:
std::vector <std::string> v;
Tokenizer s("split this string", " ");
while (s.NextToken())
{
v.push_back(s.GetToken());
}
Its very simple actually. Try this:
str1="a b c d"
splitStr1 = str1.split()
print splitStr1
try this:
but.onclick = callJavascriptFunction;
or create the button by wrapping it with another element and use innerHTML:
var span = document.createElement('span');
span.innerHTML = '<button id="but' + inc +'" onclick="callJavascriptFunction()" />';
If you are using Java 8+ and need a 2 dimensional Array
, perhaps for TestNG data providers, you can try:
map.entrySet()
.stream()
.map(e -> new Object[]{e.getKey(), e.getValue()})
.toArray(Object[][]::new);
If your Object
s are String
s and you need a String[][]
, try:
map.entrySet()
.stream()
.map(e -> new String[]{e.getKey(), e.getValue().toString()})
.toArray(String[][]::new);
In case you don't know the date format:
/**
* Check if the value is a valid date
*
* @param mixed $value
*
* @return boolean
*/
function isDate($value)
{
if (!$value) {
return false;
}
try {
new \DateTime($value);
return true;
} catch (\Exception $e) {
return false;
}
}
var_dump(isDate('2017-01-06')); // true
var_dump(isDate('2017-13-06')); // false
var_dump(isDate('2017-02-06T04:20:33')); // true
var_dump(isDate('2017/02/06')); // true
var_dump(isDate('3.6. 2017')); // true
var_dump(isDate(null)); // false
var_dump(isDate(true)); // false
var_dump(isDate(false)); // false
var_dump(isDate('')); // false
var_dump(isDate(45)); // false
On ipython or jupyter notebook, you can use all the above mentioned ways, but i go with
my_func?
or
?my_func
for quick summary of both method signature and docstring.
I avoid using
my_func??
(as commented by @rohan) for docstring and use it only to check the source code
I was developing for .NET core 2.1 using log4net 2.0.8 and found NealWalters code moans about 0 arguments for XmlConfigurator.Configure(). I found a solution by Matt Watson here
log4net.GlobalContext.Properties["LogFileName"] = @"E:\\file1"; //log file path
var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());
XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));
Most folks have answered how a downloaded image's dimensions can be known so I'll just try to answer other part of the question - knowing downloaded image's file-size.
You can do this using resource timing api. Very specifically transferSize, encodedBodySize and decodedBodySize properties can be used for the purpose.
Check out my answer here for code snippet and more information if you seek : JavaScript - Get size in bytes from HTML img src
I'm not sure if I understand your question correctly. It is a bit unclear. However, what might be confusing you is the following:
When passing by reference, a reference to the same object is passed to the function being called. Any changes to the object will be reflected in the original object and hence the caller will see it.
When passing by value, the copy constructor will be called. The default copy constructor will only do a shallow copy, hence, if the called function modifies an integer in the object, this will not be seen by the calling function, but if the function changes a data structure pointed to by a pointer within the object, then this will be seen by the caller due to the shallow copy.
I might have mis-understood your question, but I thought I would give it a stab anyway.
A char
variable is actually an 8-bit integral value. It will have values from 0
to 255
. These are ASCII codes. 0
stands for the C-null character, and 255
stands for an empty symbol.
So, when you write the following assignment:
char a = 'a';
It is the same thing as:
char a = 97;
So, you can compare two char
variables using the >
, <
, ==
, <=
, >=
operators:
char a = 'a';
char b = 'b';
if( a < b ) printf("%c is smaller than %c", a, b);
if( a > b ) printf("%c is smaller than %c", a, b);
if( a == b ) printf("%c is equal to %c", a, b);
This can be done with reduce using method references reduce(Integer::sum)
:
Integer reduceSum = Arrays.asList(1, 3, 4, 6, 4)
.stream()
.reduce(Integer::sum)
.get();
Or without Optional
:
Integer reduceSum = Arrays.asList(1, 3, 4, 6, 4)
.stream()
.reduce(0, Integer::sum);
I had the same problem, which went away after I listed my library last: gcc prog.c -lm
Here's a method you can use in your code to convert a url string and map of parameters to a valid encoded url string containing the query parameters.
String addQueryStringToUrlString(String url, final Map<Object, Object> parameters) throws UnsupportedEncodingException {
if (parameters == null) {
return url;
}
for (Map.Entry<Object, Object> parameter : parameters.entrySet()) {
final String encodedKey = URLEncoder.encode(parameter.getKey().toString(), "UTF-8");
final String encodedValue = URLEncoder.encode(parameter.getValue().toString(), "UTF-8");
if (!url.contains("?")) {
url += "?" + encodedKey + "=" + encodedValue;
} else {
url += "&" + encodedKey + "=" + encodedValue;
}
}
return url;
}
Here is the direct code that solves the OP's problem:
Dim str As String = "the little red hen"
Dim total As Int32
Dim Target As String = "e"
Dim Temp As Int32
Dim Temp2 As Int32 = -1
Line50:
Temp = str.IndexOf(Target, Temp2 + 1)
Temp2 = Temp
If Temp <> -1 Then
' Means there is a target there
total = total + 1
GoTo Line50
End If
MessageBox.Show(CStr(total))
Now, this is a handy function to solve the OP's problem:
Public Function CountOccurrence(ByVal YourStringToCountOccurrence As String, ByVal TargetSingleCharacterToCount As String) As Int32
Dim total As Int32
Dim Temp As Int32
Dim Temp2 As Int32 = -1
Line50:
Temp = YourStringToCountOccurrence.IndexOf(TargetSingleCharacterToCount, Temp2 + 1)
Temp2 = Temp
If Temp <> -1 Then
' Means there is a target there
total = total + 1
GoTo Line50
Else
Return total
End If
End Function
Example of using the function:
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim str As String = "the little red hen"
MessageBox.Show(CStr(CountOccurrence(str, "e")))
' It will return 4
End Sub
I would do it like this:
DirectoryInfo X = new DirectoryInfo(Path);
FileInfo[] listaDeArchivos = X.GetFiles();
string[] Coleccion = new String[] { };
foreach (FileInfo FI in listaDeArchivos)
{
Coleccion = Coleccion.Concat(new string[] { FI.Name }).ToArray();
}
return Coleccion;
I had to do this in Swift using an extension
.
I thought I'd share how I did it:
extension UIImage {
func imageWithColor(color1: UIColor) -> UIImage {
UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
color1.setFill()
let context = UIGraphicsGetCurrentContext() as CGContextRef
CGContextTranslateCTM(context, 0, self.size.height)
CGContextScaleCTM(context, 1.0, -1.0);
CGContextSetBlendMode(context, CGBlendMode.Normal)
let rect = CGRectMake(0, 0, self.size.width, self.size.height) as CGRect
CGContextClipToMask(context, rect, self.CGImage)
CGContextFillRect(context, rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext() as UIImage
UIGraphicsEndImageContext()
return newImage
}
}
Usage:
theImageView.image = theImageView.image.imageWithColor(UIColor.redColor())
Swift 4
extension UIImage {
func imageWithColor(color1: UIColor) -> UIImage {
UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
color1.setFill()
let context = UIGraphicsGetCurrentContext()
context?.translateBy(x: 0, y: self.size.height)
context?.scaleBy(x: 1.0, y: -1.0)
context?.setBlendMode(CGBlendMode.normal)
let rect = CGRect(origin: .zero, size: CGSize(width: self.size.width, height: self.size.height))
context?.clip(to: rect, mask: self.cgImage!)
context?.fill(rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
}
Usage:
theImageView.image = theImageView.image?.imageWithColor(color1: UIColor.red)
Pros
%1
, %2
, ... %*
in tact/arg
and -arg
styleCons
setlocal
for local scoping or write an accompanying :CLEAR-ARGS
routine!--force
to -f
)""
argument supportHere is an example how the following arguments relate to .bat variables:
>> testargs.bat /b 3 -c /d /e /f /g /h /i /j /k /bar 5 /foo "c:\"
echo %* | /b 3 -c /d /e /f /g /h /i /j /k /bar 5 /foo "c:\"
echo %ARG_FOO% | c:\
echo %ARG_A% |
echo %ARG_B% | 3
echo %ARG_C% | 1
echo %ARG_D% | 1
@echo off
setlocal
CALL :ARG-PARSER %*
::Print examples
echo: ALL: %*
echo: FOO: %ARG_FOO%
echo: A: %ARG_A%
echo: B: %ARG_B%
echo: C: %ARG_C%
echo: D: %ARG_D%
::*********************************************************
:: Parse commandline arguments into sane variables
:: See the following scenario as usage example:
:: >> thisfile.bat /a /b "c:\" /c /foo 5
:: >> CALL :ARG-PARSER %*
:: ARG_a=1
:: ARG_b=c:\
:: ARG_c=1
:: ARG_foo=5
::*********************************************************
:ARG-PARSER
::Loop until two consecutive empty args
:loopargs
IF "%~1%~2" EQU "" GOTO :EOF
set "arg1=%~1"
set "arg2=%~2"
shift
::Allow either / or -
set "tst1=%arg1:-=/%"
if "%arg1%" NEQ "" (
set "tst1=%tst1:~0,1%"
) ELSE (
set "tst1="
)
set "tst2=%arg2:-=/%"
if "%arg2%" NEQ "" (
set "tst2=%tst2:~0,1%"
) ELSE (
set "tst2="
)
::Capture assignments (eg. /foo bar)
IF "%tst1%" EQU "/" IF "%tst2%" NEQ "/" IF "%tst2%" NEQ "" (
set "ARG_%arg1:~1%=%arg2%"
GOTO loopargs
)
::Capture flags (eg. /foo)
IF "%tst1%" EQU "/" (
set "ARG_%arg1:~1%=1"
GOTO loopargs
)
goto loopargs
GOTO :EOF
$info = pathinfo($pathtofile);
if ($info["extension"] == "jpg") { .... }
I think you should be using "local storage" rather than global variables.
If you are concerned that "local storage" may not be supported in very old browsers, consider using an existing plug-in which checks the availability of "local storage" and uses other methods if it isn't available.
I used http://www.jstorage.info/ and I'm happy with it so far.
If you are using Notepad++ editor Goto ctrl + F choose tab 3 find in files and enter:
To get the n
most frequent values, just subset .value_counts()
and grab the index:
# get top 10 most frequent names
n = 10
dataframe['name'].value_counts()[:n].index.tolist()
In addition to the Thomas's answer , static variable are stored in non heap area which is called Method Area.
Tried other variants, this can be proper
Logger logger = Logger.getLogger(MyClass.class.getName());
Level level = Level.ALL;
for(Handler h : java.util.logging.Logger.getLogger("").getHandlers())
h.setLevel(level);
logger.setLevel(level);
// this must be shown
logger.fine("fine");
logger.info("info");
Yes, window.onfocus
and window.onblur
should work for your scenario:
http://www.thefutureoftheweb.com/blog/detect-browser-window-focus
You can use the built-in Dir function or the FileSystemObject.
Dir Function: VBA: Dir Function
FileSystemObject: VBA: FileSystemObject - Files Collection
They each have their own strengths and weaknesses.
Dir Function
The Dir Function is a built-in, lightweight method to get a list of files. The benefits for using it are:
The trick is to understand the difference between calling it with or without a parameter. Here is a very simple example to demonstrate:
Public Sub ListFilesDir(ByVal sPath As String, Optional ByVal sFilter As String)
Dim sFile As String
If Right(sPath, 1) <> "\" Then
sPath = sPath & "\"
End If
If sFilter = "" Then
sFilter = "*.*"
End If
'call with path "initializes" the dir function and returns the first file name
sFile = Dir(sPath & sFilter)
'call it again until there are no more files
Do Until sFile = ""
Debug.Print sFile
'subsequent calls without param return next file name
sFile = Dir
Loop
End Sub
If you alter any of the files inside the loop, you will get unpredictable results. It is better to read all the names into an array of strings before doing any operations on the files. Here is an example which builds on the previous one. This is a Function that returns a String Array:
Public Function GetFilesDir(ByVal sPath As String, _
Optional ByVal sFilter As String) As String()
'dynamic array for names
Dim aFileNames() As String
ReDim aFileNames(0)
Dim sFile As String
Dim nCounter As Long
If Right(sPath, 1) <> "\" Then
sPath = sPath & "\"
End If
If sFilter = "" Then
sFilter = "*.*"
End If
'call with path "initializes" the dir function and returns the first file
sFile = Dir(sPath & sFilter)
'call it until there is no filename returned
Do While sFile <> ""
'store the file name in the array
aFileNames(nCounter) = sFile
'subsequent calls without param return next file
sFile = Dir
'make sure your array is large enough for another
nCounter = nCounter + 1
If nCounter > UBound(aFileNames) Then
'preserve the values and grow by reasonable amount for performance
ReDim Preserve aFileNames(UBound(aFileNames) + 255)
End If
Loop
'truncate the array to correct size
If nCounter < UBound(aFileNames) Then
ReDim Preserve aFileNames(0 To nCounter - 1)
End If
'return the array of file names
GetFilesDir = aFileNames()
End Function
File System Object
The File System Object is a library for IO operations which supports an object-model for manipulating files. Pros for this approach:
You can add a reference to to "Windows Script Host Object Model" (or "Windows Scripting Runtime") and declare your objects like so:
Public Sub ListFilesFSO(ByVal sPath As String)
Dim oFSO As FileSystemObject
Dim oFolder As Folder
Dim oFile As File
Set oFSO = New FileSystemObject
Set oFolder = oFSO.GetFolder(sPath)
For Each oFile In oFolder.Files
Debug.Print oFile.Name
Next 'oFile
Set oFile = Nothing
Set oFolder = Nothing
Set oFSO = Nothing
End Sub
If you don't want intellisense you can do like so without setting a reference:
Public Sub ListFilesFSO(ByVal sPath As String)
Dim oFSO As Object
Dim oFolder As Object
Dim oFile As Object
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFolder = oFSO.GetFolder(sPath)
For Each oFile In oFolder.Files
Debug.Print oFile.Name
Next 'oFile
Set oFile = Nothing
Set oFolder = Nothing
Set oFSO = Nothing
End Sub
An alternative is to call the pip
module by using python2.7, as below:
python2.7 -m pip <commands>
For example, you could run python2.7 -m pip install <package>
to install your favorite python modules. Here is a reference: https://stackoverflow.com/a/50017310/4256346.
In case the pip module has not yet been installed for this version of python, you can run the following:
python2.7 -m ensurepip
Running this command will "bootstrap the pip installer". Note that running this may require administrative privileges (i.e. sudo
). Here is a reference: https://docs.python.org/2.7/library/ensurepip.html and another reference https://stackoverflow.com/a/46631019/4256346.
Installing vc_redist.x86.exe works for me even though you have a 64-bit machine.
I face this problem too. And ofc I looked for help in SO instead of use the common sense and check the error message.
The last part of the error message was the same as you.
Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang failed with exit code 11
But few lines above I found:
In file included from /Users/Ricardo/Documents/XCode/RealEstate-Finder-v1.2/RealEstateFinder/RealEstateFinder/RealEstateFinder-Prefix.pch:26:
/Users/Ricardo/Documents/XCode/RealEstate-Finder-v1.2/RealEstateFinder/RealEstateFinder/Config/Config.h:174:1: warning: type specifier missing, defaults to 'int' [-Wimplicit-int]
http://www.myserver.com/apps/mobile/rest.php?id=12
Which points to my Config.h file.
Happy coding!
I am not sure what the problem is, but I am pretty sure this will fix it.
for (i=0; i<arrChecks.length; i++)
{
var attribute = arrChecks[i].getAttribute("xid")
if (attribute == elementName)
{
if (arrChecks[i].checked == 0)
{
arrChecks[i].checked = 1;
} else {
arrChecks[i].checked = 0;
}
} else {
arrChecks[i].checked = 0;
}
}
I solved a similar problem. SVN client gave me an error:
"svn: E200002: Failed to create new lock."
I tried everything including "Cleanup" and "Still Lock" but with no success. Then I solved the problem simply, I went to my svn server and deleted the locks folder:
at "c:/svn/my_repository/locks"
It turned out that there are broken files in it.
It seems like the other answers here all misunderstood your question. If I understand correctly, you want to make requests to localhost:6379 (the default for redis) and have them be forwarded, automatically, to the same port on your redis container.
https://unix.stackexchange.com/a/101906/38639 helped me get to the right answer.
First, you'll need to install the nc
command on your image. On CentOS, this package is called nmap-ncat, so in the example below, just replace this with the appropriate package if you are using a different OS as your base image.
Next, you'll need to tell it to run a certain command each time the container boots up. You can do this using CMD.
# Add this to your Dockerfile
RUN yum install -y --setopt=skip_missing_names_on_install=False nmap-ncat
COPY cmd.sh /usr/local/bin/cmd.sh
RUN chmod +x /usr/local/bin/cmd.sh
CMD ["/usr/local/bin/cmd.sh"]
Finally, we'll need to set up port-forwarding in cmd.sh. I found that nc
, even with the -l
and -k
options, will occasionally terminate when a request is completed, so I'm using a while-loop to ensure that it's always running.
# cmd.sh
#! /usr/bin/env bash
while nc -l -p 6379 -k -c "nc redis 6379" || true; do true; done &
tail -f /dev/null # Or any other command that never exits
I'm using Eclipse and I copied your code and got the same error. I then opened up the project properties->Java Build Path -> Libraries->Add External JARs... c:\jrun4\lib\sqlitejdbc-v056.jar Worked like a charm. You may need to restart your web server if you've just copied the .jar file.
If a subquery returns more than one value, you might need to execute the outer query- if the values within the column specified in the condition match any value in the result set of the subquery. To perform this task, you need to use the in
keyword.
You can use a subquery to check if a set of records exists. For this, you need to use the exists
clause with a subquery. The exists
keyword always return true or false value.
Be careful when checking directory only with option -d !
if variable $1 is empty the check will still be successfull. To be sure, check also that the variable is not empty.
#! /bin/bash
is_directory(){
if [[ -d $1 ]] && [[ -n $1 ]] ; then
return 0
else
return 1
fi
}
#Test
if is_directory $1 ; then
echo "Directory exist"
else
echo "Directory does not exist!"
fi