Programs & Examples On #Kit3d

React onClick function fires on render

I had similar issue, my code was:

function RadioInput(props) {
    return (
    <div className="form-check form-check-inline">
        <input className="form-check-input" type="radio" name="inlineRadioOptions" id={props.id} onClick={props.onClick} value={props.label}></input>
        <label className="form-check-label" htmlFor={props.id}>{props.label}</label>
    </div>
    );
  }
class ScheduleType extends React.Component
{
    renderRadioInput(id,label)
    {
        id = "inlineRadio"+id;
        return(
            <RadioInput
                id = {id}
                label = {label}
                onClick = {this.props.onClick}
            />
        );

    }

Where it should be

onClick = {() => this.props.onClick()}

in RenderRadioInput

It fixed the issue for me.

What is the syntax of the enhanced for loop in Java?

Enhanced for loop:

for (String element : array) {

    // rest of code handling current element
}

Traditional for loop equivalent:

for (int i=0; i < array.length; i++) {
    String element = array[i]; 

    // rest of code handling current element
}

Take a look at these forums: https://blogs.oracle.com/CoreJavaTechTips/entry/using_enhanced_for_loops_with

http://www.java-tips.org/java-se-tips/java.lang/the-enhanced-for-loop.html

How to get first/top row of the table in Sqlite via Sql Query

Use the following query:

SELECT * FROM SAMPLE_TABLE ORDER BY ROWID ASC LIMIT 1

Note: Sqlite's row id references are detailed here.

Adding a custom header to HTTP request using angular.js

For me the following explanatory snippet worked. Perhaps you shouldn't use ' for header name?

{
   headers: { 
      Authorization: "Basic " + getAuthDigest(), 
      Accept: "text/plain" 
   }
}

I'm using $http.ajax(), though I wouldn't expect that to be a game changer.

Non-Static method cannot be referenced from a static context with methods and variables

You should place Scanner input = new Scanner (System.in); into the main method rather than creating the input object outside.

Postman: sending nested JSON object

Just for those who want to send a nested JSON object with form-data as content type.

I want to send nested custom_field in below { "description": "Details about the issue...", "subject": "Support Needed...", "type": "Others", "email": "[email protected]", "priority": 1, "status": 2, **"custom_fields" : { "cf_type_of_issue" : "Complaint" }**, "cc_emails": ["[email protected]","[email protected]"] }

enter image description here

How to get the changes on a branch in Git

To see the log of the current branch since branching off master:

git log master...

If you are currently on master, to see the log of a different branch since it branched off master:

git log ...other-branch

Running Selenium WebDriver python bindings in chrome

For Linux

  1. Check you have installed latest version of chrome brwoser-> chromium-browser -version

  2. If not, install latest version of chrome sudo apt-get install chromium-browser

  3. get appropriate version of chrome driver from here

  4. Unzip the chromedriver.zip

  5. Move the file to /usr/bin directory sudo mv chromedriver /usr/bin

  6. Goto /usr/bin directory cd /usr/bin

  7. Now, you would need to run something like sudo chmod a+x chromedriver to mark it executable.

  8. finally you can execute the code.

    from selenium import webdriver
    
    driver = webdriver.Chrome()
    driver.get("http://www.google.com")
    print driver.page_source.encode('utf-8')
    driver.quit()
    

Defining a variable with or without export

Two of the creators of UNIX, Brian Kernighan and Rob Pike, explain this in their book "The UNIX Programming Environment". Google for the title and you'll easily find a pdf version.

They address shell variables in section 3.6, and focus on the use of the export command at the end of that section:

When you want to make the value of a variable accessible in sub-shells, the shell's export command should be used. (You might think about why there is no way to export the value of a variable from a sub-shell to its parent).

Array functions in jQuery

Look into the jQuery functions .grep() and .map()

High CPU Utilization in java application - why?

You may be victim of a garbage collection problem.

When your application requires memory and it's getting low on what it's configured to use the garbage collector will run often which consume a lot of CPU cycles. If it can't collect anything your memory will stay low so it will be run again and again. When you redeploy your application the memory is cleared and the garbage collection won't happen more than required so the CPU utilization stays low until it's full again.

You should check that there is no possible memory leak in your application and that it's well configured for memory (check the -Xmx parameter, see What does Java option -Xmx stand for?)

Also, what are you using as web framework? JSF relies a lot on sessions and consumes a lot of memory, consider being stateless at most!

Uncaught syntaxerror: unexpected identifier?

There are errors here :

var formTag = document.getElementsByTagName("form"), // form tag is an array
selectListItem = $('select'),
makeSelect = document.createElement('select'),
makeSelect.setAttribute("id", "groups");

The code must change to:

var formTag = document.getElementsByTagName("form");
var selectListItem = $('select');
var makeSelect = document.createElement('select');
makeSelect.setAttribute("id", "groups");

By the way, there is another error at line 129 :

var createLi.appendChild(createSubList);

Replace it with:

createLi.appendChild(createSubList);

Entity Framework - Code First - Can't Store List<String>

I want to add that when using Npgsql (data provider for PostgreSQL), arrays and lists of primitive types are actually supported:

https://www.npgsql.org/efcore/mapping/array.html

Python JSON dump / append to .txt with each variable on new line

Your question is a little unclear. If you're generating hostDict in a loop:

with open('data.txt', 'a') as outfile:
    for hostDict in ....:
        json.dump(hostDict, outfile)
        outfile.write('\n')

If you mean you want each variable within hostDict to be on a new line:

with open('data.txt', 'a') as outfile:
    json.dump(hostDict, outfile, indent=2)

When the indent keyword argument is set it automatically adds newlines.

What exactly is RESTful programming?

RESTful (Representational state transfer) API programming is writing web applications in any programming language by following 5 basic software architectural style principles:

  1. Resource (data, information).
  2. Unique global identifier (all resources are unique identified by URI).
  3. Uniform interface - use simple and standard interface (HTTP).
  4. Representation - all communication is done by representation (e.g. XML/JSON)
  5. Stateless (every request happens in complete isolation, it's easier to cache and load-balance),

In other words you're writing simple point-to-point network applications over HTTP which uses verbs such as GET, POST, PUT or DELETE by implementing RESTful architecture which proposes standardization of the interface each “resource” exposes. It is nothing that using current features of the web in a simple and effective way (highly successful, proven and distributed architecture). It is an alternative to more complex mechanisms like SOAP, CORBA and RPC.

RESTful programming conforms to Web architecture design and, if properly implemented, it allows you to take the full advantage of scalable Web infrastructure.

Connect to mysql on Amazon EC2 from a remote server

Though this question seems to be answered, another common issue that you can get is the DB user has been mis-configured. This is a mysql administration and permissions issue:

  1. EC2_DB launched with IP 10.55.142.100
  2. EC2_web launched with IP 10.55.142.144
  3. EC2_DB and EC2_WEBare in the same security group with access across your DB port (3306)
  4. EC2_DB has a mysql DB that can be reached locally by the DB root user ('root'@'localhost')
  5. EC2_DB mysql DB has a remote user 'my_user'@'%' IDENTIFIED BY PASSWORD 'password'
  6. A bash call to mysql from EC2_WEB fails: mysql -umy_user -p -h ip-10-55-142-100.ec2.internal as does host references to the explicit IP, public DNS, etc.

Step 6 fails because the mysql DB has the wrong user permisions. It needs this:

GRANT ALL PRIVILEGES ON *.* TO 'my_user'@'ip-10-55-142-144.ec2.internal' IDENTIFIED BY PASSWORD 'password'

I would like to think that % would work for any remote server, but I did not find this to be the case.

Please let me know if this helps you.

How to recover the deleted files using "rm -R" command in linux server?

Short answer: You can't. rm removes files blindly, with no concept of 'trash'.

Some Unix and Linux systems try to limit its destructive ability by aliasing it to rm -i by default, but not all do.

Long answer: Depending on your filesystem, disk activity, and how long ago the deletion occured, you may be able to recover some or all of what you deleted. If you're using an EXT3 or EXT4 formatted drive, you can check out extundelete.

In the future, use rm with caution. Either create a del alias that provides interactivity, or use a file manager.

Run a PHP file in a cron job using CPanel

On a Hostgator CPANEL this worked for me:

php /home/here_your_user_name/public_html/cronJob.php

How to style icon color, size, and shadow of Font Awesome Icons

Try to simply use something like fa-lg,fa-2x,fa-3x,fa-4x,fa-5x to increase the icon size relative to their container

for eg:-

Open the terminal in visual studio?

View -> debug console (Ctrl+Shift+Y) next to debug console is terminal

The SELECT permission was denied on the object 'sysobjects', database 'mssqlsystemresource', schema 'sys'

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.

Escape double quotes in parameter

I cannot quickly reproduce the symptoms: if I try myscript '"test"' with a batch file myscript.bat containing just @echo.%1 or even @echo.%~1, I get all quotes: '"test"'

Perhaps you can try the escape character ^ like this: myscript '^"test^"'?

C# Inserting Data from a form into an access Database

My Code to insert data is not working. It showing no error but data is not showing in my database.

public partial class Form1 : Form { OleDbConnection connection = new OleDbConnection(check.Properties.Settings.Default.KitchenConnectionString); public Form1() { InitializeComponent(); }

    private void Form1_Load(object sender, EventArgs e)
    {
        
    }

    private void btn_add_Click(object sender, EventArgs e)
    {
        OleDbDataAdapter items = new OleDbDataAdapter();
        connection.Open();
        OleDbCommand command = new OleDbCommand("insert into Sets(SetId, SetName,  SetPassword) values('"+txt_id.Text+ "','" + txt_setname.Text + "','" + txt_password.Text + "');", connection);
        command.CommandType = CommandType.Text;
        command.ExecuteReader();
        connection.Close();
        MessageBox.Show("Insertd!");
    }
}

super() in Java

As stated, inside the default constructor there is an implicit super() called on the first line of the constructor.

This super() automatically calls a chain of constructors starting at the top of the class hierarchy and moves down the hierarchy .

If there were more than two classes in the class hierarchy of the program, the top class default constructor would get called first.

Here is an example of this:

class A {
    A() {
    System.out.println("Constructor A");
    }
}

class B extends A{

    public B() {
    System.out.println("Constructor B");
    }
}

class C extends B{ 

    public C() {
    System.out.println("Constructor C");
    }

    public static void main(String[] args) {
    C c1 = new C();
    }
} 

The above would output:

Constructor A
Constructor B
Constructor C

Maven build Compilation error : Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project Maven

Doing this in pom.xml file and after updating the project, the problem is gone.

<plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.4</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
</configuration>
</plugin>
  1. Update the pom.xml under <plugin></plugin>.

  2. Update your project.

  3. Then clean maven and install maven.

Does dispatch_async(dispatch_get_main_queue(), ^{...}); wait until done?

dispatch_queue_t queue = dispatch_queue_create("com.example.MyQueue", NULL);
dispatch_async(queue, ^{
  // Do some computation here.

  // Update UI after computation.
  dispatch_async(dispatch_get_main_queue(), ^{
    // Update the UI on the main thread.
  });
});

How to present UIActionSheet iOS Swift?

swift4 (tested)

let alertController = UIAlertController(title: "Select Photo", message: "Select atleast one photo", preferredStyle: .actionSheet)
    let action1 = UIAlertAction(title: "From Photo", style: .default) { (action) in
        print("Default is pressed.....")
    }
    let action2 = UIAlertAction(title: "Cancel", style: .cancel) { (action) in
        print("Cancel is pressed......")
    }
    let action3 = UIAlertAction(title: "Click new", style: .default) { (action) in
        print("Destructive is pressed....")

    }
    alertController.addAction(action1)
    alertController.addAction(action2)
    alertController.addAction(action3)
    self.present(alertController, animated: true, completion: nil)

}

How do I pass a string into subprocess.Popen (using the stdin argument)?

On Python 3.7+ do this:

my_data = "whatever you want\nshould match this f"
subprocess.run(["grep", "f"], text=True, input=my_data)

and you'll probably want to add capture_output=True to get the output of running the command as a string.

On older versions of Python, replace text=True with universal_newlines=True:

subprocess.run(["grep", "f"], universal_newlines=True, input=my_data)

Changing text color onclick

   <p id="text" onclick="func()">
    Click on text to change
</p>
<script>
function func()
{
    document.getElementById("text").style.color="red";
    document.getElementById("text").style.font="calibri";
}
</script>

Local package.json exists, but node_modules missing

Just had the same error message, but when I was running a package.json with:

"scripts": {
    "build": "tsc -p ./src",
}

tsc is the command to run the TypeScript compiler.

I never had any issues with this project because I had TypeScript installed as a global module. As this project didn't include TypeScript as a dev dependency (and expected it to be installed as global), I had the error when testing in another machine (without TypeScript) and running npm install didn't fix the problem. So I had to include TypeScript as a dev dependency (npm install typescript --save-dev) to solve the problem.

Quick-and-dirty way to ensure only one instance of a shell script is running at a time

The flock path is the way to go. Think about what happens when the script suddenly dies. In the flock-case you just loose the flock, but that is not a problem. Also, note that an evil trick is to take a flock on the script itself .. but that of course lets you run full-steam-ahead into permission problems.

XML Error: Extra content at the end of the document

I've found that this error is also generated if the document is empty. In this case it's also because there is no root element - but the error message "Extra content and the end of the document" is misleading in this situation.

CURL Command Line URL Parameters

Felipsmartins is correct.

It is worth mentioning that it is because you cannot really use the -d/--data option if this is not a POST request. But this is still possible if you use the -G option.

Which means you can do this:

curl -X DELETE -G 'http://localhost:5000/locations' -d 'id=3'

Here it is a bit silly but when you are on the command line and you have a lot of parameters, it is a lot tidier.

I am saying this because cURL commands are usually quite long, so it is worth making it on more than one line escaping the line breaks.

curl -X DELETE -G \
'http://localhost:5000/locations' \
-d id=3 \
-d name=Mario \
-d surname=Bros

This is obviously a lot more comfortable if you use zsh. I mean when you need to re-edit the previous command because zsh lets you go line by line. (just saying)

Hope it helps.

java.lang.UnsupportedClassVersionError: Bad version number in .class file?

Always check for the obvious too. I got this error once when I accidently grabbed the wrong resource for the server's add and remove action. It can be easy to overlook.

How to get the selected value from drop down list in jsp?

use jquery

$("#item").change(function({
    var x=$(this).val();
});

Your value will be in x variable, use this variable value in your jsp, like this {x} this statement will give the value

Function to clear the console in R and RStudio

If you are using the default R console, the key combination Option + Command + L will clear the console.

Python def function: How do you specify the end of the function?

So its the indentation that matters. As other users here have pointed out to you, when the indentation level is at the same point as the def function declaration your function has ended. Keep in mind that you cannot mix tabs and spaces in Python. Most editors provide support for this.

What is the unix command to see how much disk space there is and how much is remaining?

df -g .

Option g for Size in GBs Block and . for current working directory.

What is the difference between C++ and Visual C++?

VC++ is not actually a language but is commonly referred to like one. When VC++ is referred to as a language, it usually means Microsoft's implementation of C++, which contains various knacks that do not exist in regular C++, such as the __super keyword. It is similar to the various GNU extensions to the C language that are implemented in GCC.

EditText onClickListener in Android

I had this same problem. The code is fine but make sure you change the focusable value of the EditText to false.

<EditText
android:id="@+id/date"
android:focusable="false"/>

I hope this helps anyone who has had a similar problem!

What's the difference between eval, exec, and compile?

The short answer, or TL;DR

Basically, eval is used to evaluate a single dynamically generated Python expression, and exec is used to execute dynamically generated Python code only for its side effects.

eval and exec have these two differences:

  1. eval accepts only a single expression, exec can take a code block that has Python statements: loops, try: except:, class and function/method definitions and so on.

    An expression in Python is whatever you can have as the value in a variable assignment:

    a_variable = (anything you can put within these parentheses is an expression)
    
  2. eval returns the value of the given expression, whereas exec ignores the return value from its code, and always returns None (in Python 2 it is a statement and cannot be used as an expression, so it really does not return anything).

In versions 1.0 - 2.7, exec was a statement, because CPython needed to produce a different kind of code object for functions that used exec for its side effects inside the function.

In Python 3, exec is a function; its use has no effect on the compiled bytecode of the function where it is used.


Thus basically:

>>> a = 5
>>> eval('37 + a')   # it is an expression
42
>>> exec('37 + a')   # it is an expression statement; value is ignored (None is returned)
>>> exec('a = 47')   # modify a global variable as a side effect
>>> a
47
>>> eval('a = 47')  # you cannot evaluate a statement
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    a = 47
      ^
SyntaxError: invalid syntax

The compile in 'exec' mode compiles any number of statements into a bytecode that implicitly always returns None, whereas in 'eval' mode it compiles a single expression into bytecode that returns the value of that expression.

>>> eval(compile('42', '<string>', 'exec'))  # code returns None
>>> eval(compile('42', '<string>', 'eval'))  # code returns 42
42
>>> exec(compile('42', '<string>', 'eval'))  # code returns 42,
>>>                                          # but ignored by exec

In the 'eval' mode (and thus with the eval function if a string is passed in), the compile raises an exception if the source code contains statements or anything else beyond a single expression:

>>> compile('for i in range(3): print(i)', '<string>', 'eval')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    for i in range(3): print(i)
      ^
SyntaxError: invalid syntax

Actually the statement "eval accepts only a single expression" applies only when a string (which contains Python source code) is passed to eval. Then it is internally compiled to bytecode using compile(source, '<string>', 'eval') This is where the difference really comes from.

If a code object (which contains Python bytecode) is passed to exec or eval, they behave identically, excepting for the fact that exec ignores the return value, still returning None always. So it is possible use eval to execute something that has statements, if you just compiled it into bytecode before instead of passing it as a string:

>>> eval(compile('if 1: print("Hello")', '<string>', 'exec'))
Hello
>>>

works without problems, even though the compiled code contains statements. It still returns None, because that is the return value of the code object returned from compile.

In the 'eval' mode (and thus with the eval function if a string is passed in), the compile raises an exception if the source code contains statements or anything else beyond a single expression:

>>> compile('for i in range(3): print(i)', '<string>'. 'eval')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    for i in range(3): print(i)
      ^
SyntaxError: invalid syntax

The longer answer, a.k.a the gory details

exec and eval

The exec function (which was a statement in Python 2) is used for executing a dynamically created statement or program:

>>> program = '''
for i in range(3):
    print("Python is cool")
'''
>>> exec(program)
Python is cool
Python is cool
Python is cool
>>> 

The eval function does the same for a single expression, and returns the value of the expression:

>>> a = 2
>>> my_calculation = '42 * a'
>>> result = eval(my_calculation)
>>> result
84

exec and eval both accept the program/expression to be run either as a str, unicode or bytes object containing source code, or as a code object which contains Python bytecode.

If a str/unicode/bytes containing source code was passed to exec, it behaves equivalently to:

exec(compile(source, '<string>', 'exec'))

and eval similarly behaves equivalent to:

eval(compile(source, '<string>', 'eval'))

Since all expressions can be used as statements in Python (these are called the Expr nodes in the Python abstract grammar; the opposite is not true), you can always use exec if you do not need the return value. That is to say, you can use either eval('my_func(42)') or exec('my_func(42)'), the difference being that eval returns the value returned by my_func, and exec discards it:

>>> def my_func(arg):
...     print("Called with %d" % arg)
...     return arg * 2
... 
>>> exec('my_func(42)')
Called with 42
>>> eval('my_func(42)')
Called with 42
84
>>> 

Of the 2, only exec accepts source code that contains statements, like def, for, while, import, or class, the assignment statement (a.k.a a = 42), or entire programs:

>>> exec('for i in range(3): print(i)')
0
1
2
>>> eval('for i in range(3): print(i)')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    for i in range(3): print(i)
      ^
SyntaxError: invalid syntax

Both exec and eval accept 2 additional positional arguments - globals and locals - which are the global and local variable scopes that the code sees. These default to the globals() and locals() within the scope that called exec or eval, but any dictionary can be used for globals and any mapping for locals (including dict of course). These can be used not only to restrict/modify the variables that the code sees, but are often also used for capturing the variables that the executed code creates:

>>> g = dict()
>>> l = dict()
>>> exec('global a; a, b = 123, 42', g, l)
>>> g['a']
123
>>> l
{'b': 42}

(If you display the value of the entire g, it would be much longer, because exec and eval add the built-ins module as __builtins__ to the globals automatically if it is missing).

In Python 2, the official syntax for the exec statement is actually exec code in globals, locals, as in

>>> exec 'global a; a, b = 123, 42' in g, l

However the alternate syntax exec(code, globals, locals) has always been accepted too (see below).

compile

The compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1) built-in can be used to speed up repeated invocations of the same code with exec or eval by compiling the source into a code object beforehand. The mode parameter controls the kind of code fragment the compile function accepts and the kind of bytecode it produces. The choices are 'eval', 'exec' and 'single':

  • 'eval' mode expects a single expression, and will produce bytecode that when run will return the value of that expression:

    >>> dis.dis(compile('a + b', '<string>', 'eval'))
      1           0 LOAD_NAME                0 (a)
                  3 LOAD_NAME                1 (b)
                  6 BINARY_ADD
                  7 RETURN_VALUE
    
  • 'exec' accepts any kinds of python constructs from single expressions to whole modules of code, and executes them as if they were module top-level statements. The code object returns None:

    >>> dis.dis(compile('a + b', '<string>', 'exec'))
      1           0 LOAD_NAME                0 (a)
                  3 LOAD_NAME                1 (b)
                  6 BINARY_ADD
                  7 POP_TOP                             <- discard result
                  8 LOAD_CONST               0 (None)   <- load None on stack
                 11 RETURN_VALUE                        <- return top of stack
    
  • 'single' is a limited form of 'exec' which accepts a source code containing a single statement (or multiple statements separated by ;) if the last statement is an expression statement, the resulting bytecode also prints the repr of the value of that expression to the standard output(!).

    An if-elif-else chain, a loop with else, and try with its except, else and finally blocks is considered a single statement.

    A source fragment containing 2 top-level statements is an error for the 'single', except in Python 2 there is a bug that sometimes allows multiple toplevel statements in the code; only the first is compiled; the rest are ignored:

    In Python 2.7.8:

    >>> exec(compile('a = 5\na = 6', '<string>', 'single'))
    >>> a
    5
    

    And in Python 3.4.2:

    >>> exec(compile('a = 5\na = 6', '<string>', 'single'))
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<string>", line 1
        a = 5
            ^
    SyntaxError: multiple statements found while compiling a single statement
    

    This is very useful for making interactive Python shells. However, the value of the expression is not returned, even if you eval the resulting code.

Thus greatest distinction of exec and eval actually comes from the compile function and its modes.


In addition to compiling source code to bytecode, compile supports compiling abstract syntax trees (parse trees of Python code) into code objects; and source code into abstract syntax trees (the ast.parse is written in Python and just calls compile(source, filename, mode, PyCF_ONLY_AST)); these are used for example for modifying source code on the fly, and also for dynamic code creation, as it is often easier to handle the code as a tree of nodes instead of lines of text in complex cases.


While eval only allows you to evaluate a string that contains a single expression, you can eval a whole statement, or even a whole module that has been compiled into bytecode; that is, with Python 2, print is a statement, and cannot be evalled directly:

>>> eval('for i in range(3): print("Python is cool")')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    for i in range(3): print("Python is cool")
      ^
SyntaxError: invalid syntax

compile it with 'exec' mode into a code object and you can eval it; the eval function will return None.

>>> code = compile('for i in range(3): print("Python is cool")',
                   'foo.py', 'exec')
>>> eval(code)
Python is cool
Python is cool
Python is cool

If one looks into eval and exec source code in CPython 3, this is very evident; they both call PyEval_EvalCode with same arguments, the only difference being that exec explicitly returns None.

Syntax differences of exec between Python 2 and Python 3

One of the major differences in Python 2 is that exec is a statement and eval is a built-in function (both are built-in functions in Python 3). It is a well-known fact that the official syntax of exec in Python 2 is exec code [in globals[, locals]].

Unlike majority of the Python 2-to-3 porting guides seem to suggest, the exec statement in CPython 2 can be also used with syntax that looks exactly like the exec function invocation in Python 3. The reason is that Python 0.9.9 had the exec(code, globals, locals) built-in function! And that built-in function was replaced with exec statement somewhere before Python 1.0 release.

Since it was desirable to not break backwards compatibility with Python 0.9.9, Guido van Rossum added a compatibility hack in 1993: if the code was a tuple of length 2 or 3, and globals and locals were not passed into the exec statement otherwise, the code would be interpreted as if the 2nd and 3rd element of the tuple were the globals and locals respectively. The compatibility hack was not mentioned even in Python 1.4 documentation (the earliest available version online); and thus was not known to many writers of the porting guides and tools, until it was documented again in November 2012:

The first expression may also be a tuple of length 2 or 3. In this case, the optional parts must be omitted. The form exec(expr, globals) is equivalent to exec expr in globals, while the form exec(expr, globals, locals) is equivalent to exec expr in globals, locals. The tuple form of exec provides compatibility with Python 3, where exec is a function rather than a statement.

Yes, in CPython 2.7 that it is handily referred to as being a forward-compatibility option (why confuse people over that there is a backward compatibility option at all), when it actually had been there for backward-compatibility for two decades.

Thus while exec is a statement in Python 1 and Python 2, and a built-in function in Python 3 and Python 0.9.9,

>>> exec("print(a)", globals(), {'a': 42})
42

has had identical behaviour in possibly every widely released Python version ever; and works in Jython 2.5.2, PyPy 2.3.1 (Python 2.7.6) and IronPython 2.6.1 too (kudos to them following the undocumented behaviour of CPython closely).

What you cannot do in Pythons 1.0 - 2.7 with its compatibility hack, is to store the return value of exec into a variable:

Python 2.7.11+ (default, Apr 17 2016, 14:00:29) 
[GCC 5.3.1 20160413] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = exec('print(42)')
  File "<stdin>", line 1
    a = exec('print(42)')
           ^
SyntaxError: invalid syntax

(which wouldn't be useful in Python 3 either, as exec always returns None), or pass a reference to exec:

>>> call_later(exec, 'print(42)', delay=1000)
  File "<stdin>", line 1
    call_later(exec, 'print(42)', delay=1000)
                  ^
SyntaxError: invalid syntax

Which a pattern that someone might actually have used, though unlikely;

Or use it in a list comprehension:

>>> [exec(i) for i in ['print(42)', 'print(foo)']
  File "<stdin>", line 1
    [exec(i) for i in ['print(42)', 'print(foo)']
        ^
SyntaxError: invalid syntax

which is abuse of list comprehensions (use a for loop instead!).

Get the generated SQL statement from a SqlCommand object?

My Solution:

public static class DbHelper
{
    public static string ToString(this DbParameterCollection parameters, string sqlQuery)
    {
        return parameters.Cast<DbParameter>().Aggregate(sqlQuery, (current, p) => current.Replace(p.ParameterName, p.Value.ToString()));
    }
}

What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?

This question comes up ALL THE TIME on SO. It's one of the first things that new Swift developers struggle with.

Background:

Swift uses the concept of "Optionals" to deal with values that could contain a value, or not. In other languages like C, you might store a value of 0 in a variable to indicate that it contains no value. However, what if 0 is a valid value? Then you might use -1. What if -1 is a valid value? And so on.

Swift optionals let you set up a variable of any type to contain either a valid value, or no value.

You put a question mark after the type when you declare a variable to mean (type x, or no value).

An optional is actually a container than contains either a variable of a given type, or nothing.

An optional needs to be "unwrapped" in order to fetch the value inside.

The "!" operator is a "force unwrap" operator. It says "trust me. I know what I am doing. I guarantee that when this code runs, the variable will not contain nil." If you are wrong, you crash.

Unless you really do know what you are doing, avoid the "!" force unwrap operator. It is probably the largest source of crashes for beginning Swift programmers.

How to deal with optionals:

There are lots of other ways of dealing with optionals that are safer. Here are some (not an exhaustive list)

You can use "optional binding" or "if let" to say "if this optional contains a value, save that value into a new, non-optional variable. If the optional does not contain a value, skip the body of this if statement".

Here is an example of optional binding with our foo optional:

if let newFoo = foo //If let is called optional binding. {
  print("foo is not nil")
} else {
  print("foo is nil")
}

Note that the variable you define when you use optional biding only exists (is only "in scope") in the body of the if statement.

Alternately, you could use a guard statement, which lets you exit your function if the variable is nil:

func aFunc(foo: Int?) {
  guard let newFoo = input else { return }
  //For the rest of the function newFoo is a non-optional var
}

Guard statements were added in Swift 2. Guard lets you preserve the "golden path" through your code, and avoid ever-increasing levels of nested ifs that sometimes result from using "if let" optional binding.

There is also a construct called the "nil coalescing operator". It takes the form "optional_var ?? replacement_val". It returns a non-optional variable with the same type as the data contained in the optional. If the optional contains nil, it returns the value of the expression after the "??" symbol.

So you could use code like this:

let newFoo = foo ?? "nil" // "??" is the nil coalescing operator
print("foo = \(newFoo)")

You could also use try/catch or guard error handling, but generally one of the other techniques above is cleaner.

EDIT:

Another, slightly more subtle gotcha with optionals is "implicitly unwrapped optionals. When we declare foo, we could say:

var foo: String!

In that case foo is still an optional, but you don't have to unwrap it to reference it. That means any time you try to reference foo, you crash if it's nil.

So this code:

var foo: String!


let upperFoo = foo.capitalizedString

Will crash on reference to foo's capitalizedString property even though we're not force-unwrapping foo. the print looks fine, but it's not.

Thus you want to be really careful with implicitly unwrapped optionals. (and perhaps even avoid them completely until you have a solid understanding of optionals.)

Bottom line: When you are first learning Swift, pretend the "!" character is not part of the language. It's likely to get you into trouble.

How to change heatmap.2 color range in R?

You could try to create your own color palette using the RColorBrewer package

my_palette <- colorRampPalette(c("green", "black", "red"))(n = 1000)

and see how this looks like. But I assume in your case only scaling would help if you really want to keep the black in "the middle". You can simply use my_palette instead of the redgreen()

I recommend that you check out the RColorBrewer package, they have pretty nice in-built palettes, and see interactive website for colorbrewer.

Unable to use Intellij with a generated sources folder

Maybe you can add a step to the generate-sources phase that moves the folder?

How to rename files and folder in Amazon S3?

aws s3 cp s3://source_folder/ s3://destination_folder/ --recursive
aws s3 rm s3://source_folder --recursive

Adding ASP.NET MVC5 Identity Authentication to an existing project

I recommend IdentityServer.This is a .NET Foundation project and covers many issues about authentication and authorization.

Overview

IdentityServer is a .NET/Katana-based framework and hostable component that allows implementing single sign-on and access control for modern web applications and APIs using protocols like OpenID Connect and OAuth2. It supports a wide range of clients like mobile, web, SPAs and desktop applications and is extensible to allow integration in new and existing architectures.

For more information, e.g.

  • support for MembershipReboot and ASP.NET Identity based user stores
  • support for additional Katana authentication middleware (e.g. Google, Twitter, Facebook etc)
  • support for EntityFramework based persistence of configuration
  • support for WS-Federation
  • extensibility

check out the documentation and the demo.

What is a None value?

largest=none
smallest =none 
While True :
          num =raw_input ('enter a number ') 
          if num =="done ": break 
          try :
           inp =int (inp) 
          except:
              Print'Invalid input' 
           if largest is none :
               largest=inp
           elif inp>largest:
                largest =none 
           print 'maximum', largest

          if smallest is none:
               smallest =none
          elif inp<smallest :
               smallest =inp
          print 'minimum', smallest 

print 'maximum, minimum, largest, smallest 

Executing an EXE file using a PowerShell script

Not being a developer I found a solution in running multiple ps commands in one line. E.g:

powershell "& 'c:\path with spaces\to\executable.exe' -arguments ; second command ; etc

By placing a " (double quote) before the & (ampersand) it executes the executable. In none of the examples I have found this was mentioned. Without the double quotes the ps prompt opens and waits for input.

Multiple FROMs - what it means

The first answer is too complex, historic, and uninformative for my tastes.


It's actually rather simple. Docker provides for a functionality called multi-stage builds the basic idea here is to,

  • Free you from having to manually remove what you don't want, by forcing you to whitelist what you do want,
  • Free resources that would otherwise be taken up because of Docker's implementation.

Let's start with the first. Very often with something like Debian you'll see.

RUN apt-get update \ 
  && apt-get dist-upgrade \
  && apt-get install <whatever> \
  && apt-get clean

We can explain all of this in terms of the above. The above command is chained together so it represents a single change with no intermediate Images required. If it was written like this,

RUN apt-get update ;
RUN apt-get dist-upgrade;
RUN apt-get install <whatever>;
RUN apt-get clean;

It would result in 3 more temporary intermediate Images. Having it reduced to one image, there is one remaining problem: apt-get clean doesn't clean up artifacts used in the install. If a Debian maintainer includes in his install a script that modifies the system that modification will also be present in the final solution (see something like pepperflashplugin-nonfree for an example of that).

By using a multi-stage build you get all the benefits of a single changed action, but it will require you to manually whitelist and copy over files that were introduced in the temporary image using the COPY --from syntax documented here. Moreover, it's a great solution where there is no alternative (like an apt-get clean), and you would otherwise have lots of un-needed files in your final image.

See also

How to convert numbers to alphabet?

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

What is the difference between match_parent and fill_parent?

Just to give it a name closer to it's actual action. "fill_parent" does not fill the remaining space as the name would imply (for that you use the weight attribute). Instead, it takes up as much space as its layout parent. That's why the new name is "match_parent"

Is there a code obfuscator for PHP?

Thicket™ Obfuscator for PHP

The PHP Obfuscator tool scrambles PHP source code to make it very difficult to understand or reverse-engineer (example). This provides significant protection for source code intellectual property that must be hosted on a website or shipped to a customer. It is a member of SD's family of Source Code Obfuscators.

How to increase storage for Android Emulator? (INSTALL_FAILED_INSUFFICIENT_STORAGE)

The following approach worked for me

  1. Navigate to your android SDK/tools folder in the terminal window (in case you didn't added the path for it)

  2. Make sure the virtual device you're planning to clean is powered off.

  3. Run the command "./emulator -wipe-data -avd YourAvdName" where YourAvdName is the name of your virtual android device

An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode

If you still need to use the HTTP Module you need to configure it (.NET 4.0 framework) as follows:

<system.webServer>
   <modules runAllManagedModulesForAllRequests="true">
       <add name="MyModule" type="[Namespace].[Class], [assembly]"/>
   </modules>
   <validation validateIntegratedModeConfiguration="false"/>
</system.webServer>

Is it possible to modify a string of char in C?

It seems like your question has been answered but now you might wonder why char *a = "String" is stored in read-only memory. Well, it is actually left undefined by the c99 standard but most compilers choose to it this way for instances like:

printf("Hello, World\n");

c99 standard(pdf) [page 130, section 6.7.8]:

The declaration:

char s[] = "abc", t[3] = "abc";

defines "plain" char array objects s and t whose elements are initialized with character string literals. This declaration is identical to char

s[] = { 'a', 'b', 'c', '\0' }, t[] = { 'a', 'b', 'c' };

The contents of the arrays are modifiable. On the other hand, the declaration

char *p = "abc";

defines p with type "pointer to char" and initializes it to point to an object with type "array of char" with length 4 whose elements are initialized with a character string literal. If an attempt is made to use p to modify the contents of the array, the behavior is undefined.

How to create a property for a List<T>

T must be defined within the scope in which you are working. Therefore, what you have posted will work if your class is generic on T:

public class MyClass<T>
{
    private List<T> newList;

    public List<T> NewList
    {
        get{return newList;}
        set{newList = value;}
    }
}

Otherwise, you have to use a defined type.

EDIT: Per @lKashef's request, following is how to have a List property:

private List<int> newList;

public List<int> NewList
{
    get{return newList;}
    set{newList = value;}
}

This can go within a non-generic class.

Edit 2: In response to your second question (in your edit), I would not recommend using a list for this type of data handling (if I am understanding you correctly). I would put the user settings in their own class (or struct, if you wish) and have a property of this type on your original class:

public class UserSettings
{
 string FirstName { get; set; }
 string LastName { get; set; }
 // etc.
}

public class MyClass
{
 string MyClassProperty1 { get; set; }
 // etc.

 UserSettings MySettings { get; set; }
}

This way, you have named properties that you can reference instead of an arbitrary index in a list. For example, you can reference MySettings.FirstName as opposed to MySettingsList[0].

Let me know if you have any further questions.

EDIT 3: For the question in the comments, your property would be like this:

public class MyClass
{
    public List<KeyValuePair<string, string>> MySettings { get; set; } 
}

EDIT 4: Based on the question's edit 2, following is how I would use this:

public class MyClass
{
    // note that this type of property declaration is called an "Automatic Property" and
    // it means the same thing as you had written (the private backing variable is used behind the scenes, but you don't see it)
    public List<KeyValuePair<string, string> MySettings { get; set; } 
}

public class MyConsumingClass
{
    public void MyMethod
    {
        MyClass myClass = new MyClass();
        myClass.MySettings = new List<KeyValuePair<string, string>>();
        myClass.MySettings.Add(new KeyValuePair<string, string>("SomeKeyValue", "SomeValue"));

        // etc.
    }
}

You mentioned that "the property still won't appear in the object's instance," and I am not sure what you mean. Does this property not appear in IntelliSense? Are you sure that you have created an instance of MyClass (like myClass.MySettings above), or are you trying to access it like a static property (like MyClass.MySettings)?

How to create an Excel File with Nodejs?

install exceljs

npm i exceljs --save

import exceljs

var Excel = require('exceljs');
var workbook = new Excel.Workbook();

create workbook

var options = {
                filename: __dirname+'/Reports/'+reportName,
                useStyles: true,
                useSharedStrings: true
            };

            var workbook = new Excel.stream.xlsx.WorkbookWriter(options);

after create worksheet

var worksheet = workbook.addWorksheet('Rate Sheet',{properties:{tabColor:{argb:'FFC0000'}}});

in worksheet.column array you pass column name in header and array key pass in key

worksheet.columns = [
            { header: 'column name', key: 'array key', width: 35},
            { header: 'column name', key: 'array key', width: 35},
            { header: 'column name', key: 'array key', width: 20},

            ];

after using forEach loop append row one by one in exel file

array.forEach(function(row){ worksheet.addRow(row); })

you can also perfome loop on each exel row and cell

worksheet.eachRow(function(row, rowNumber) {
    console.log('Row ' + rowNumber + ' = ' + JSON.stringify(row.values));
});
row.eachCell(function(cell, colNumber) {
    console.log('Cell ' + colNumber + ' = ' + cell.value);
});

How to copy static files to build directory with Webpack?

The way I load static images and fonts:

module: {
    rules: [
      ....

      {
        test: /\.(jpe?g|png|gif|svg)$/i,
        /* Exclude fonts while working with images, e.g. .svg can be both image or font. */
        exclude: path.resolve(__dirname, '../src/assets/fonts'),
        use: [{
          loader: 'file-loader',
          options: {
            name: '[name].[ext]',
            outputPath: 'images/'
          }
        }]
      },
      {
        test: /\.(woff(2)?|ttf|eot|svg|otf)(\?v=\d+\.\d+\.\d+)?$/,
        /* Exclude images while working with fonts, e.g. .svg can be both image or font. */
        exclude: path.resolve(__dirname, '../src/assets/images'),
        use: [{
          loader: 'file-loader',
          options: {
            name: '[name].[ext]',
            outputPath: 'fonts/'
          },
        }
    ]
}

Don't forget to install file-loader to have that working.

JSON for List of int

JSON is perfectly capable of expressing lists of integers, and the JSON you have posted is valid. You can simply separate the integers by commas:

{
    "Id": "610",
    "Name": "15",
    "Description": "1.99",
    "ItemModList": [42, 47, 139]
}

How to add 20 minutes to a current date?

Add it in milliseconds:

var currentDate = new Date();
var twentyMinutesLater = new Date(currentDate.getTime() + (20 * 60 * 1000));

Error: The type exists in both directories

I had the same problem in one of my projects. Turns out the problem started from me coping a Master page.

The problem will also occur if two pages "Inherit" the same page.

I had the following line of code at the top of my "LoginMaster.Master" & "MasterPage.Master"

<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MainMaster.master.cs" Inherits="Master_Pages_Header" %>

I changed the Inherits on my "LoginMaster.Master to:

<%@ Master Language="C#" AutoEventWireup="true" CodeFile="LoginMaster.master.cs" Inherits="Master_Pages_LoginMaster" %>

I was immediately able to publish my project with out any problems. Hopefully this works for someone else. I apologize for not use the correct terms.

You will also need to change the class in the .cs to match the Inherits name. If you don't it will cause an error.

IE:

public partial class Master_Pages_LoginMaster : System.Web.UI.MasterPage

Consider defining a bean of type 'package' in your configuration [Spring-Boot]

I think, you are missing the @Bean annotation in your RequestController

Add the Bean in your file, this solved my issue
I got this solution while I was learning Spring Boot from tutorialspoint

private Applicant applicant;

@Bean 
public Applicant applicant() { 
    return new Applicant(); 
}

Specifing width of a flexbox flex item: width or basis?

The bottom statement is equivalent to:

.half {
   flex-grow: 0;
   flex-shrink: 0;
   flex-basis: 50%;
}

Which, in this case, would be equivalent as the box is not allowed to flex and therefore retains the initial width set by flex-basis.

Flex-basis defines the default size of an element before the remaining space is distributed so if the element were allowed to flex (grow/shrink) it may not be 50% of the width of the page.

I've found that I regularly return to https://css-tricks.com/snippets/css/a-guide-to-flexbox/ for help regarding flexbox :)

How to define custom sort function in javascript?

It could be that the plugin is case-sensitive. Try inputting Te instead of te. You can probably have your results setup to not be case-sensitive. This question might help.

For a custom sort function on an Array, you can use any JavaScript function and pass it as parameter to an Array's sort() method like this:

_x000D_
_x000D_
var array = ['White 023', 'White', 'White flower', 'Teatr'];_x000D_
_x000D_
array.sort(function(x, y) {_x000D_
  if (x < y) {_x000D_
    return -1;_x000D_
  }_x000D_
  if (x > y) {_x000D_
    return 1;_x000D_
  }_x000D_
  return 0;_x000D_
});_x000D_
_x000D_
// Teatr White White 023 White flower_x000D_
document.write(array);
_x000D_
_x000D_
_x000D_

More Info here on Array.sort.

Can we define min-margin and max-margin, max-padding and min-padding in css?

Try using the css properties min and max as a workaround

For example:

width: min(50vw, 200px);

means the width will be the smallest of the two values.

width: max(50vw, 200px);

means the width will be the larger of the two values.

More details here:

https://developer.mozilla.org/en-US/docs/Web/CSS/min

How can I dynamically set the position of view in Android?

There is a library called NineOldAndroids, which allows you to use the Honeycomb animation library all the way down to version one.

This means you can define left, right, translationX/Y with a slightly different interface.

Here is how it works:

ViewHelper.setTranslationX(view, 50f);

You just use the static methods from the ViewHelper class, pass the view and which ever value you want to set it to.

Permission denied (publickey,keyboard-interactive)

The server first tries to authenticate you by public key. That doesn't work (I guess you haven't set one up), so it then falls back to 'keyboard-interactive'. It should then ask you for a password, which presumably you're not getting right. Did you see a password prompt?

Range of values in C Int and Long 32 - 64 bits

In C and C++ you have these least requirements (i.e actual implementations can have larger magnitudes)

signed char: -2^07+1 to +2^07-1
short:       -2^15+1 to +2^15-1
int:         -2^15+1 to +2^15-1
long:        -2^31+1 to +2^31-1
long long:   -2^63+1 to +2^63-1

Now, on particular implementations, you have a variety of bit ranges. The wikipedia article describes this nicely.

How to check for null in a single statement in scala?

Option(getObject) foreach (QueueManager add)

COUNT DISTINCT with CONDITIONS

You can try this:

select
  count(distinct tag) as tag_count,
  count(distinct (case when entryId > 0 then tag end)) as positive_tag_count
from
  your_table_name;

The first count(distinct...) is easy. The second one, looks somewhat complex, is actually the same as the first one, except that you use case...when clause. In the case...when clause, you filter only positive values. Zeros or negative values would be evaluated as null and won't be included in count.

One thing to note here is that this can be done by reading the table once. When it seems that you have to read the same table twice or more, it can actually be done by reading once, in most of the time. As a result, it will finish the task a lot faster with less I/O.

What is the most efficient way to loop through dataframes with pandas?

Another suggestion would be to combine groupby with vectorized calculations if subsets of the rows shared characteristics which allowed you to do so.

ReactJS: Maximum update depth exceeded error

that because you calling toggle inside the render method which will cause to re-render and toggle will call again and re-rendering again and so on

this line at your code

{<td><span onClick={this.toggle()}>Details</span></td>}

you need to make onClick refer to this.toggle not calling it

to fix the issue do this

{<td><span onClick={this.toggle}>Details</span></td>}

Getting Access Denied when calling the PutObject operation with bucket-level permission

For me I was using expired auth keys. Generated new ones and boom.

Can't build create-react-app project with custom PUBLIC_URL

If the other answers aren't working for you, there's also a homepage field in package.json. After running npm run build you should get a message like the following:

The project was built assuming it is hosted at the server root.
To override this, specify the homepage in your package.json.
For example, add this to build it for GitHub Pages:

  "homepage" : "http://myname.github.io/myapp",

You would just add it as one of the root fields in package.json, e.g.

{
  // ...
  "scripts": {
    // ...
  },
  "homepage": "https://example.com"
}

When it's successfully set, either via homepage or PUBLIC_URL, you should instead get a message like this:

The project was built assuming it is hosted at https://example.com.
You can control this with the homepage field in your package.json.

AWS : The config profile (MyName) could not be found

Did you actually set up your specific user? The walkthrough setup guide in AWS explains how to set a default user, and then how to set up additional users. If you didn't complete the full setup, you'll just have a default block and your myName won't have been created..

Single quotes vs. double quotes in C or C++

Single quotes are denoting a char, double denote a string.

In Java, it is also the same.

Extract every nth element of a vector

a <- 1:120
b <- a[seq(1, length(a), 6)]

How do I correctly detect orientation change using Phonegap on iOS?

if (window.DeviceOrientationEvent) {
    // Listen for orientation changes
    window.addEventListener("orientationchange", orientationChangeHandler);
    function orientationChangeHandler(evt) {
        // Announce the new orientation number
        // alert(screen.orientation);
        // Find matches
        var mql = window.matchMedia("(orientation: portrait)");

        if (mql.matches)  //true
    }
}

"You have mail" message in terminal, os X

I was also having this issue of "You have mail" coming up every time I started Terminal.

What I discovered is this.

Something I'd installed (not entirely sure what, but possibly a script or something associated with an Alfred Workflow [at a guess]) made a change to the OS X system to start presenting Terminal bash notifications. Prior to that, it appears Wordpress had attempted to use the Local Mail system to send a message. The message bounced, due to it having an invalid Recipient address. The bounced message then ended up in the local system mail inbox. So Terminal (bash) was then notifying me that "You have mail".

You can access the mail by simply using the command

mail

This launches you into Mail, and it will right away show you a list of messages that are stored there. If you want to see the content of the first message, use

t

This will show you the content of the first message, in full. You'll need to scroll down through the message to view it all, by hitting the down-arrow key.

If you want to jump to the end of the message, use the

spacebar

If you want to abort viewing the message, use

q 

To view the next message in the queue use

n

... assuming there's more than one message.

NOTE: You need to use these commands at the mail ? command prompt. They won't work whilst you are in the process of viewing a message. Hitting n whilst viewing a message will just cause an error message related to regular expressions. So, if in the midst of viewing a message, hit q to quit from that, or hit spacebar to jump to the end of the message, and then at the ? prompt, hit n.

Viewing the content of the messages in this way may help you identify what attempted to send the message(s).

You can also view a specific message by just inputting its number at the ? prompt. 3, for instance, will show you the content of the third message (if there are that many in there).

DELETING MESSAGES

Use the d command (at the ? command prompt )

d [message number]

To delete each message when you are done looking at them. For example, d 2 will delete message number 2. Or you can delete a list of messages, such as d 1 2 5 7. Or you can delete a range of messages with (for example), d 3-10. You can find the message numbers in the list of messages mail shows you.

To delete all the messages, from the mail prompt (?) use the command d *.

As per a comment on this post, you will need to use q to quit mail, which also saves any changes.

If you'd like to see the mail all in one output, use this command at the bash prompt (i.e. not from within mail, but from your regular command prompt):

cat /var/mail/<username>

And, if you wish to delete the emails all in one hit, use this command

sudo rm /var/mail/<username>

In my particular case, there were a number of messages. It looks like the one was a returned message that bounced. It was sent by a local Wordpress installation. It was a notification for when user "Admin" (me) changed its password. Two additional messages where there. Both seemed to be to the same incident.

What I don't know, and can't answer for you either, is WHY I only recently started seeing this mail notification each time I open Terminal. The mails were generated a couple of months ago, and yet I only noticed this "you have mail" appearing in the last few weeks. I suspect it's the result of something a workflow I installed in Alfred, and that workflow using Terminal bash to provide notifications... or something along those lines.

Simply deleting the messages

If you have no interest in determining the source of the messages, and just wish to get rid of them, it may be easier to do so without using the mail command (which can be somewhat fiddly). As pointed out by a few other people, you can use this command instead:

sudo rm /var/mail/YOURUSERNAME

How to check if a symlink exists

How about using readlink?

# if symlink, readlink returns not empty string (the symlink target)
# if string is not empty, test exits w/ 0 (normal)
#
# if non symlink, readlink returns empty string
# if string is empty, test exits w/ 1 (error)
simlink? () {
  test "$(readlink "${1}")";
}

FILE=/usr/mda

if simlink? "${FILE}"; then
  echo $FILE is a symlink
else
  echo $FILE is not a symlink
fi

How to drop a unique constraint from table column?

This statement works for me

  ALTER TABLE table_name DROP UNIQUE (column_name);

How to upload files in asp.net core?

You can add a new property of type IFormFile to your view model

public class CreatePost
{
   public string ImageCaption { set;get; }
   public string ImageDescription { set;get; }
   public IFormFile MyImage { set; get; }
}

and in your GET action method, we will create an object of this view model and send to the view.

public IActionResult Create()
{
   return View(new CreatePost());
}

Now in your Create view which is strongly typed to our view model, have a form tag which has the enctype attribute set to "multipart/form-data"

@model CreatePost
<form asp-action="Create" enctype="multipart/form-data">   

    <input asp-for="ImageCaption"/>
    <input asp-for="ImageDescription"/>
    <input asp-for="MyImage"/>

    <input type="submit"/>
</form>

And your HttpPost action to handle the form posting

[HttpPost]
public IActionResult Create(CreatePost model)
{
   var img = model.MyImage;
   var imgCaption = model.ImageCaption;

   //Getting file meta data
   var fileName = Path.GetFileName(model.MyImage.FileName);
   var contentType = model.MyImage.ContentType;

   // do something with the above data
   // to do : return something
}

If you want to upload the file to some directory in your app, you should use IHostingEnvironment to get the webroot path. Here is a working sample.

public class HomeController : Controller
{
    private readonly IHostingEnvironment hostingEnvironment;
    public HomeController(IHostingEnvironment environment)
    {
        hostingEnvironment = environment;
    }
    [HttpPost]
    public IActionResult Create(CreatePost model)
    {
        // do other validations on your model as needed
        if (model.MyImage != null)
        {
            var uniqueFileName = GetUniqueFileName(model.MyImage.FileName);
            var uploads = Path.Combine(hostingEnvironment.WebRootPath, "uploads");
            var filePath = Path.Combine(uploads,uniqueFileName);
            model.MyImage.CopyTo(new FileStream(filePath, FileMode.Create)); 

            //to do : Save uniqueFileName  to your db table   
        }
        // to do  : Return something
        return RedirectToAction("Index","Home");
    }
    private string GetUniqueFileName(string fileName)
    {
        fileName = Path.GetFileName(fileName);
        return  Path.GetFileNameWithoutExtension(fileName)
                  + "_" 
                  + Guid.NewGuid().ToString().Substring(0, 4) 
                  + Path.GetExtension(fileName);
    }
}

This will save the file to uploads folder inside wwwwroot directory of your app with a random file name generated using Guids ( to prevent overwriting of files with same name)

Here we are using a very simple GetUniqueName method which will add 4 chars from a guid to the end of the file name to make it somewhat unique. You can update the method to make it more sophisticated as needed.

Should you be storing the full url to the uploaded image in the database ?

No. Do not store the full url to the image in the database. What if tomorrow your business decides to change your company/product name from www.thefacebook.com to www.facebook.com ? Now you have to fix all the urls in the table!

What should you store ?

You should store the unique filename which you generated above(the uniqueFileName varibale we used above) to store the file name. When you want to display the image back, you can use this value (the filename) and build the url to the image.

For example, you can do this in your view.

@{
    var imgFileName = "cats_46df.png";
}
<img src="~/uploads/@imgFileName"  alt="my img"/>

I just hardcoded an image name to imgFileName variable and used that. But you may read the stored file name from your database and set to your view model property and use that. Something like

<img src="~/uploads/@Model.FileName"  alt="my img"/>

Storing the image to table

If you want to save the file as bytearray/varbinary to your database, you may convert the IFormFile object to byte array like this

private byte[] GetByteArrayFromImage(IFormFile file)
{
    using (var target = new MemoryStream())
    {
        file.CopyTo(target);
        return target.ToArray();
    }
}

Now in your http post action method, you can call this method to generate the byte array from IFormFile and use that to save to your table. the below example is trying to save a Post entity object using entity framework.

[HttpPost]
public IActionResult Create(CreatePost model)
{
    //Create an object of your entity class and map property values
    var post=new Post() { ImageCaption = model.ImageCaption };

    if (model.MyImage != null)
    {
       post.Image =  GetByteArrayFromImage(model.MyImage);
    }
    _context.Posts.Add(post);
    _context.SaveChanges();
    return RedirectToAction("Index","Home");
}

Match everything except for specified strings

Matching any text but those matching a pattern is usually achieved with splitting the string with the regex pattern.

Examples:

  • - Regex.Split(text, @"red|green|blue") or, to get rid of empty values, Regex.Split(text, @"red|green|blue").Where(x => !string.IsNullOrEmpty(x)) (see demo)
  • - Regex.Split(text, "red|green|blue") or, to remove empty items, Regex.Split(text, "red|green|blue").Where(Function(s) Not String.IsNullOrWhitespace(s)) (see demo, or this demo where LINQ is supported)
  • - text.split(/red|green|blue/) (no need to use g modifier here!) (to get rid of empty values, use text.split(/red|green|blue/).filter(Boolean)), see demo
  • - text.split("red|green|blue"), or - to keep all trailing empty items - use text.split("red|green|blue", -1), or to remove all empty items use more code to remove them (see demo)
  • - Similar to Java, text.split(/red|green|blue/), to get all trailing items use text.split(/red|green|blue/, -1) and to remove all empty items use text.split(/red|green|blue/).findAll {it != ""}) (see demo)
  • - text.split(Regex("red|green|blue")) or, to remove blank items, use text.split(Regex("red|green|blue")).filter{ !it.isBlank() }, see demo
  • - text.split("red|green|blue"), or to keep all trailing empty items, use text.split("red|green|blue", -1) and to remove all empty items, use text.split("red|green|blue").filter(_.nonEmpty) (see demo)
  • - text.split(/red|green|blue/), to get rid of empty values use .split(/red|green|blue/).reject(&:empty?) (and to get both leading and trailing empty items, use -1 as the second argument, .split(/red|green|blue/, -1)) (see demo)
  • - my @result1 = split /red|green|blue/, $text;, or with all trailing empty items, my @result2 = split /red|green|blue/, $text, -1;, or without any empty items, my @result3 = grep { /\S/ } split /red|green|blue/, $text; (see demo)
  • - preg_split('~red|green|blue~', $text) or preg_split('~red|green|blue~', $text, -1, PREG_SPLIT_NO_EMPTY) to output no empty items (see demo)
  • - re.split(r'red|green|blue', text) or, to remove empty items, list(filter(None, re.split(r'red|green|blue', text))) (see demo)
  • - Use regexp.MustCompile("red|green|blue").Split(text, -1), and if you need to remove empty items, use this code. See Go demo.

NOTE: If you patterns contain capturing groups, regex split functions/methods may behave differently, also depending on additional options. Please refer to the appropriate split method documentation then.

GitLab remote: HTTP Basic: Access denied and fatal Authentication

I got the same error and I solved this by :

  1. Apply command from cmd (run as administrator)

    git config --system --unset credential.helper

  2. And then I removed gitconfig file from C:\Program Files\Git\mingw64/etc/ location (Note: this path will be different in MAC like "/Users/username")

  3. After that use git command like git pull or git push, it asked me for username and password. applying valid username and password and git command working.

hope this will help you...

How to return HTTP 500 from ASP.NET Core RC2 Web Api?

A better way to handle this as of now (1.1) is to do this in Startup.cs's Configure():

app.UseExceptionHandler("/Error");

This will execute the route for /Error. This will save you from adding try-catch blocks to every action you write.

Of course, you'll need to add an ErrorController similar to this:

[Route("[controller]")]
public class ErrorController : Controller
{
    [Route("")]
    [AllowAnonymous]
    public IActionResult Get()
    {
        return StatusCode(StatusCodes.Status500InternalServerError);
    }
}

More information here.


In case you want to get the actual exception data, you may add this to the above Get() right before the return statement.

// Get the details of the exception that occurred
var exceptionFeature = HttpContext.Features.Get<IExceptionHandlerPathFeature>();

if (exceptionFeature != null)
{
    // Get which route the exception occurred at
    string routeWhereExceptionOccurred = exceptionFeature.Path;

    // Get the exception that occurred
    Exception exceptionThatOccurred = exceptionFeature.Error;

    // TODO: Do something with the exception
    // Log it with Serilog?
    // Send an e-mail, text, fax, or carrier pidgeon?  Maybe all of the above?
    // Whatever you do, be careful to catch any exceptions, otherwise you'll end up with a blank page and throwing a 500
}

Above snippet taken from Scott Sauber's blog.

How to execute an oracle stored procedure?

I use oracle 12 and it tell me that if you need to invoke the procedure then use call keyword. In your case it should be:

begin
  call temp_proc;
end;

Errors: Data path ".builders['app-shell']" should have required property 'class'

I was also coming across this issue and for me when doing more updates more issues occurred.

What worked for me in the end was more or less to remove angular cli and re install it with these steps:

npm uninstall -g @angular/cli
npm cache clean --force
npm install -g @angular/cli

this helped me out source: how to uninstall angular/cli

Python; urllib error: AttributeError: 'bytes' object has no attribute 'read'

Try this:

jsonResponse = json.loads(response.decode('utf-8'))

Nesting queries in SQL

The way I see it, the only place for a nested query would be in the WHERE clause, so e.g.

SELECT country.name, country.headofstate
FROM country 
WHERE country.headofstate LIKE 'A%' AND 
country.id in (SELECT country_id FROM city WHERE population > 100000)

Apart from that, I have to agree with Adrian on: why the heck should you use nested queries?

Creating a border like this using :before And :after Pseudo-Elements In CSS?

See the following snippet, is this what you want?

_x000D_
_x000D_
body {
    background: silver;
    padding: 0 10px;
}

#content:after {
    height: 10px;
    display: block;
    width: 100px;
    background: #808080;
    border-right: 1px white;
    content: '';
}

#footer:before {
    display: block;
    content: '';
    background: silver;
    height: 10px;
    margin-top: -20px;
    margin-left: 101px;
}

#content {
    background: white;
}


#footer {
    padding-top: 10px;
    background: #404040;
}

p {
    padding: 100px;
    text-align: center;
}

#footer p {
    color: white;
}
_x000D_
<body>
    <div id="content"><p>#content</p></div>
    <div id="footer"><p>#footer</p></div>
</body>
_x000D_
_x000D_
_x000D_

JSFiddle

Error "Metadata file '...\Release\project.dll' could not be found in Visual Studio"

The ~30th answer :-)

In VS2015:

  • Right-click on Solution
  • Select Project Build Order
  • Look at the list of projects in Project Build Order
  • Build each of your projects in that order
  • Inspect the Output

In my case, doing it step-by-step helped discovered what my problem is without all those errors thrown left and right.

If you had to know, I added Entity Framework (EF) 6.1.3 via NuGet when the project was set for .NET 4.5.2. I later downgraded the .NET Framework down to 4, and then the error was more obvious. Via NuGet, I uninstalled EF and re-added it.

What is the best IDE for PHP?

I believe that PHP being what it is, doesn't really require an IDE. I use vi, it is fast, doesn't crash and with grep -r and Ctags, it can multiply productivity many times over.

Subversion is literally built-in in the console, so you won't run into problems with source control.

Finally, I used springloops.com as the repositories, so I don't have have to manually FTP files to any server. It has a FTP deployment option which also makes sure that only the altered file move to the staging server.

The best part is that you can go to a friends house, find a Linux machine, and just start developing because everything that you need is mostly available on most machines.

Convert integer into its character equivalent, where 0 => a, 1 => b, etc

Use String.fromCharCode. This returns a string from a Unicode value, which matches the first 128 characters of ASCII.

var a = String.fromCharCode(97);

How to uninstall Apache with command line

If Apache was installed using NSIS installer it should have left an uninstaller. You should search inside Apache installation directory for executable named unistaller.exe or something like that. NSIS uninstallers support /S flag by default for silent uninstall. So you can run something like "C:\Program Files\<Apache installation dir here>\uninstaller.exe" /S

From NSIS documentation:

3.2.1 Common Options

/NCRC disables the CRC check, unless CRCCheck force was used in the script. /S runs the installer or uninstaller silently. See section 4.12 for more information. /D sets the default installation directory ($INSTDIR), overriding InstallDir and InstallDirRegKey. It must be the last parameter used in the command line and must not contain any quotes, even if the path contains spaces. Only absolute paths are supported.

an htop-like tool to display disk activity in linux

It is not htop-like, but you could use atop. However, to display disk activity per process, it needs a kernel patch (available from the site). These kernel patches are now obsoleted, only to show per-process network activity an optional module is provided.

How to center the content inside a linear layout?

android:layout_gravity is used for the layout itself

Use android:gravity="center" for children of your LinearLayout

So your code should be:

<LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:layout_weight="1" >

SQL string value spanning multiple lines in query

What's the column "BIO" datatype? What database server (sql/oracle/mysql)? You should be able to span over multiple lines all you want as long as you adhere to the character limit in the column's datatype (ie: varchar(200) ). Try using single quotes, that might make a difference. This works for me:

update table set mycolumn = 'hello world,
my name is carlos.
goodbye.'
where id = 1;

Also, you might want to put in checks for single quotes if you are concatinating the sql string together in C#. If the variable contains single quotes that could escape the code out of the sql statement, therefore, not doing all the lines you were expecting to see.

BTW, you can delimit your SQL statements with a semi colon like you do in C#, just as FYI.

git commit error: pathspec 'commit' did not match any file(s) known to git

The order line contentions are isolated by space. On the off chance that you need furnish a contention with a space in it, you should cite it. So use git commit - m "Initial commit". must follow this syntax.

How can I loop through a List<T> and grab each item?

This is how I would write using more functional way. Here is the code:

new List<Money>()
{
     new Money() { Amount = 10, Type = "US"},
     new Money() { Amount = 20, Type = "US"}
}
.ForEach(money =>
{
    Console.WriteLine($"amount is {money.Amount}, and type is {money.Type}");
});

Android - R cannot be resolved to a variable

I've fixed the problem in my case very easy:
go to Build- Path->Configure Build Path->Order and Export and ensure that <project name>/gen folder is above <project name>/src
After fixing the order the error disappears.

Spring - @Transactional - What happens in background?

The simplest answer is:

On whichever method you declare @Transactional the boundary of transaction starts and boundary ends when method completes.

If you are using JPA call then all commits are with in this transaction boundary.

Lets say you are saving entity1, entity2 and entity3. Now while saving entity3 an exception occur, then as enitiy1 and entity2 comes in same transaction so entity1 and entity2 will be rollback with entity3.

Transaction :

  1. entity1.save
  2. entity2.save
  3. entity3.save

Any exception will result in rollback of all JPA transactions with DB.Internally JPA transaction are used by Spring.

Programmatically Creating UILabel

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 30, 300, 50)];
label.backgroundColor = [UIColor clearColor];
label.textAlignment = NSTextAlignmentCenter;
label.textColor = [UIColor whiteColor];
label.numberOfLines = 0;
label.lineBreakMode = UILineBreakModeWordWrap;
label.text = @"Your Text";
[self.view addSubview:label];

Pointtype command for gnuplot

You first have to tell Gnuplot to use a style that uses points, e.g. with points or with linespoints. Try for example:

plot sin(x) with points

Output:

Now try:

plot sin(x) with points pointtype 5

Output:

You may also want to look at the output from the test command which shows you the capabilities of the current terminal. Here are the capabilities for my pngairo terminal:

How to pass in parameters when use resource service?

I think I see your problem, you need to use the @ syntax to define parameters you will pass in this way, also I'm not sure what loginID or password are doing you don't seem to define them anywhere and they are not being used as URL parameters so are they being sent as query parameters?

This is what I can suggest based on what I see so far:

.factory('MagComments', function ($resource) {
    return $resource('http://localhost/dooleystand/ci/api/magCommenct/:id', {
      loginID : organEntity,
      password : organCommpassword,
      id : '@magId'
    });
  })

The @magId string will tell the resource to replace :id with the property magId on the object you pass it as parameters.

I'd suggest reading over the documentation here (I know it's a bit opaque) very carefully and looking at the examples towards the end, this should help a lot.

AngularJS ng-click to go to another page (with Ionic framework)

Based on comments, and due to the fact that @Thinkerer (the OP - original poster) created a plunker for this case, I decided to append another answer with more details.

The first and important change:

// instead of this
$urlRouterProvider.otherwise('/tab/post');

// we have to use this
$urlRouterProvider.otherwise('/tab/posts');

because the states definition is:

.state('tab', {
  url: "/tab",
  abstract: true,
  templateUrl: 'tabs.html'
})

.state('tab.posts', {
  url: '/posts',
  views: {
    'tab-posts': {
      templateUrl: 'tab-posts.html',
      controller: 'PostsCtrl'
    }
  }
})

and we need their concatenated url '/tab' + '/posts'. That's the url we want to use as a otherwise

The rest of the application is really close to the result we need...
E.g. we stil have to place the content into same view targetgood, just these were changed:

.state('tab.newpost', {
  url: '/newpost',
  views: {
    // 'tab-newpost': {
    'tab-posts': {
      templateUrl: 'tab-newpost.html',
      controller: 'NavCtrl'
    }
  }

because .state('tab.newpost' would be replacing the .state('tab.posts' we have to place it into the same anchor:

<ion-nav-view name="tab-posts"></ion-nav-view>  

Finally some adjustments in controllers:

$scope.create = function() {
    $state.go('tab.newpost');
};
$scope.close = function() { 
     $state.go('tab.posts'); 
};

As I already said in my previous answer and comments ... the $state.go() is the only right way how to use ionic or ui-router

Check that all here Final note - I made running just navigation between tab.posts... tab.newpost... the rest would be similar

Factory Pattern. When to use factory methods?

Factory classes are more heavyweight, but give you certain advantages. In cases when you need to build your objects from multiple, raw data sources they allow you to encapsulate only the building logic (and maybe the aggregation of the data) in one place. There it can be tested in abstract without being concerned with the object interface.

I have found this a useful pattern, particularly where I am unable to replace and inadequate ORM and want to efficiently instantiate many objects from DB table joins or stored procedures.

Best way to generate xml?

Use lxml.builder class, from: http://lxml.de/tutorial.html#the-e-factory

import lxml.builder as lb
from lxml import etree

nstext = "new story"
story = lb.E.Asset(
  lb.E.Attribute(nstext, name="Name", act="set"),
  lb.E.Relation(lb.E.Asset(idref="Scope:767"),
            name="Scope", act="set")
  )

print 'story:\n', etree.tostring(story, pretty_print=True)

Output:

story:
<Asset>
  <Attribute name="Name" act="set">new story</Attribute>
  <Relation name="Scope" act="set">
    <Asset idref="Scope:767"/>
  </Relation>
</Asset>

How to make overlay control above all other controls?

<Canvas Panel.ZIndex="1" HorizontalAlignment="Left" VerticalAlignment="Top" Width="570">
  <!-- YOUR XAML CODE -->
</Canvas>

How to change MySQL column definition?

Syntax to change column name in MySql:

alter table table_name change old_column_name new_column_name data_type(size);

Example:

alter table test change LowSal Low_Sal integer(4);

Dynamically create and submit form

Like Purmou, but removing the form when submit will done.

$(function() {
   $('<form action="form2.html"></form>').appendTo('body').submit().remove();
});

Correct way of using log4net (logger naming)

My Answer might be coming late, but I think it can help newbie. You shall not see logs executed unless the changes are made as below.

2 Files have to be changes when you implement Log4net.


  1. Add Reference of log4net.dll in the project.
  2. app.config
  3. Class file where you will implement Logs.

Inside [app.config] :

First, under 'configSections', you need to add below piece of code;

<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />

Then, under 'configuration' block, you need to write below piece of code.(This piece of code is customised as per my need , but it works like charm.)

<log4net debug="true">
    <logger name="log">
      <level value="All"></level>
      <appender-ref ref="RollingLogFileAppender" />
    </logger>

    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="log.txt" />
      <appendToFile value="true" />
      <rollingStyle value="Composite" />
      <maxSizeRollBackups value="1" />
      <maximumFileSize value="1MB" />
      <staticLogFileName value="true" />

      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date %C.%M [%line] %-5level - %message %newline %exception %newline" />
      </layout>
    </appender>
</log4net>

Inside Calling Class :

Inside the class where you are going to use this log4net, you need to declare below piece of code.

 ILog log = LogManager.GetLogger("log");

Now, you are ready call log wherever you want in that same class. Below is one of the method you can call while doing operations.

log.Error("message");

How to add anything in <head> through jquery/javascript?

jQuery

$('head').append( ... );

JavaScript:

document.getElementsByTagName('head')[0].appendChild( ... );

Background color in input and text fields

input[type="text"], textarea {

  background-color : #d1d1d1; 

}

Hope that helps :)

Edit: working example, http://jsfiddle.net/C5WxK/

Resizing an Image without losing any quality

See if you like the image resizing quality of this open source ASP.NET module. There's a live demo, so you can mess around with it yourself. It yields results that are (to me) impossible to distinguish from Photoshop output. It also has similar file sizes - MS did a good job on their JPEG encoder.

Reading and displaying data from a .txt file

public class PassdataintoFile {

    public static void main(String[] args) throws IOException  {
        try {
            PrintWriter pw = new PrintWriter("C:/new/hello.txt", "UTF-8");
            PrintWriter pw1 = new PrintWriter("C:/new/hello.txt");
             pw1.println("Hi chinni");
             pw1.print("your succesfully entered text into file");
             pw1.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        BufferedReader br = new BufferedReader(new FileReader("C:/new/hello.txt"));
           String line;
           while((line = br.readLine())!= null)
           {
               System.out.println(line);
           }
           br.close();
    }

}

Error sending json in POST to web API service

another tip...where to add "content-type: application/json"...to the textbox field on the Composer/Parsed tab. There are 3 lines already filled in there, so I added this Content-type as the 4th line. That made the Post work.

List of all unique characters in a string?

Use an OrderedDict. This will ensure that the order is preserved

>>> ''.join(OrderedDict.fromkeys( "aaabcabccd").keys())
'abcd'

PS: I just timed both the OrderedDict and Set solution, and the later is faster. If order does not matter, set should be the natural solution, if Order Matter;s this is how you should do.

>>> from timeit import Timer
>>> t1 = Timer(stmt=stmt1, setup="from __main__ import data, OrderedDict")
>>> t2 = Timer(stmt=stmt2, setup="from __main__ import data")
>>> t1.timeit(number=1000)
1.2893918431815337
>>> t2.timeit(number=1000)
0.0632140599081196

How do I find the authoritative name-server for a domain name?

You can use the whois service. On a UNIX like operating system you would execute the following command. Alternatively you can do it on the web at http://www.internic.net/whois.html.

whois stackoverflow.com

You would get the following response.

...text removed here...

Domain servers in listed order: NS51.DOMAINCONTROL.COM NS52.DOMAINCONTROL.COM

You can use nslookup or dig to find out more information about records for a given domain. This might help you resolve the conflicts you have described.

How to query a CLOB column in Oracle

To add to the answer.

declare
v_result clob;
begin
---- some operation on v_result
dbms_lob.substr( v_result, 4000 ,length(v_result) - 3999 );

end;
/

In dbms_lob.substr

first parameter is clob which you want to extract .

Second parameter is how much length of clob you want to extract.

Third parameter is from which word you want to extract .

In above example i know my clob size is more than 50000 , so i want last 4000 character .

Creating an empty file in C#

You can chain methods off the returned object, so you can immediately close the file you just opened in a single statement.

File.Open("filename", FileMode.Create).Close();

Spring application context external properties?

<context:property-placeholder location="file:/apps/tomcat/ath/ath_conf/pcr.application.properties" />

This works for me. Local development machine path is C:\apps\tomcat\ath\ath_conf and in server /apps/tomcat/ath/ath_conf

Both works for me

Remove characters from NSString?

If you want to support more than one space at a time, or support any whitespace, you can do this:

NSString* noSpaces =
    [[myString componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]
                           componentsJoinedByString:@""];

Default password of mysql in ubuntu server 16.04

Early versions allowed root password to be blank but, in Newer versions set the root password is the admin(main) user login password during the installation.

Refresh an asp.net page on button click

Add one unique session or cookie in button click event then redirect page on same URL using Request.RawUrl Now add code in Page_Load event to grab that session or coockie. If session/cookie matches then you can knows that page redirected using refresh button. So decrease hit counter by 1 to keep it on same number do hitcountr -= hitconter

Else increase the hit counter.

The calling thread must be STA, because many UI components require this

For me, this error occurred because of a null parameter being passed. Checking the variable values fixed my issue without having to change the code. I used BackgroundWorker.

How to get distinct values for non-key column fields in Laravel?

I found this method working quite well (for me) to produce a flat array of unique values:

$uniqueNames = User::select('name')->distinct()->pluck('name')->toArray();

If you ran ->toSql() on this query builder, you will see it generates a query like this:

select distinct `name` from `users`

The ->pluck() is handled by illuminate\collection lib (not via sql query).

How To have Dynamic SQL in MySQL Stored Procedure

I don't believe MySQL supports dynamic sql. You can do "prepared" statements which is similar, but different.

Here is an example:

mysql> PREPARE stmt FROM 
    -> 'select count(*) 
    -> from information_schema.schemata 
    -> where schema_name = ? or schema_name = ?'
;
Query OK, 0 rows affected (0.00 sec)
Statement prepared
mysql> EXECUTE stmt 
    -> USING @schema1,@schema2
+----------+
| count(*) |
+----------+
|        2 |
+----------+
1 row in set (0.00 sec)
mysql> DEALLOCATE PREPARE stmt;

The prepared statements are often used to see an execution plan for a given query. Since they are executed with the execute command and the sql can be assigned to a variable you can approximate the some of the same behavior as dynamic sql.

Here is a good link about this:

Don't forget to deallocate the stmt using the last line!

Good Luck!

How can I clear the Scanner buffer in Java?

This should fix it...

Scanner in=new Scanner(System.in);
    int rounds = 0;
    while (rounds < 1 || rounds > 3) {
        System.out.print("How many rounds? ");
        if (in.hasNextInt()) {
            rounds = in.nextInt();
        } else {
            System.out.println("Invalid input. Please try again.");
            in.next(); // -->important
            System.out.println();
        }
        // Clear buffer
    }
    System.out.print(rounds+" rounds.");

How to use Python's pip to download and keep the zipped files for a package?

The --download-cache option should do what you want:

pip install --download-cache="/pth/to/downloaded/files" package

However, when I tested this, the main package downloaded, saved and installed ok, but the the dependencies were saved with their full url path as the name - a bit annoying, but all the tar.gz files were there.

The --download option downloads the main package and its dependencies and does not install any of them. (Note that prior to version 1.1 the --download option did not download dependencies.)

pip install package --download="/pth/to/downloaded/files"

The pip documentation outlines using --download for fast & local installs.

Resource interpreted as stylesheet but transferred with MIME type text/html (seems not related with web server)

Try this <link rel="stylesheet" type="text/css" href="../##/yourcss.css">

where ## is your folder wherein is your .CSS - file

Don't forget about the: .. (double dots).

Error loading MySQLdb Module 'Did you install mysqlclient or MySQL-python?'

For pip

pip install pymysql

For pip3 you should use

python3 -m pip install PyMySQL

Then, edit the init.py file in your project origin directory (the same as settings.py). Add:

import pymysql

pymysql.install_as_MySQLdb()

Check if a string is a date value

Here's a minimalist version.

var isDate = function (date) {
    return!!(function(d){return(d!=='Invalid Date'&&!isNaN(d))})(new Date(date));
}

Command-line Tool to find Java Heap Size and Memory Used (Linux)?

If using jrockit try the jrcmd command line tool. For example:

$ jrcmd 5127 print_memusage
5127:
Total mapped                  1074596KB           (reserved=3728KB)
-              Java heap       786432KB           (reserved=0KB)
-              GC tables        26316KB          
-          Thread stacks        13452KB           (#threads=34)
-          Compiled code         9856KB           (used=9761KB)
-               Internal          840KB          
-                     OS        15036KB          
-                  Other       146632KB          
-        Java class data        75008KB           (malloced=74861KB #103221 in 18709 classes)
- Native memory tracking         1024KB           (malloced=102KB #8)

For more commands, like heap_diagnostics, use "jrcmd help" to list them.

https://blogs.oracle.com/jrockit/entry/why_is_my_jvm_process_larger_t

Creating for loop until list.length

You could learn about Python loops here: http://en.wikibooks.org/wiki/Python_Programming/Loops

You have to know that Python doesn't have { and } for start and end of loop, instead it depends on tab chars you enter in first of line, I mean line indents.

So you can do loop inside loop with double tab (indent)

An example of double loop is like this:

onetoten = range(1,11)
tentotwenty = range(10,21)
for count in onetoten:
    for count2 in tentotwenty
        print(count2)

Firefox 'Cross-Origin Request Blocked' despite headers

Try this, it should solve your issue

  1. In your config.php, add www pre in your domain.com. For example:

    HTTP define('HTTP_SERVER', 'http://domain name with www/');
    HTTPS define('HTTPS_SERVER', 'http://domain name with www/');
    
  2. Add this to your .htaccess file

    RewriteCond %{REQUEST_METHOD} OPTIONS RewriteRule ^(.*)$ $1 [R=200,L]
    

How do I set session timeout of greater than 30 minutes

If you want to never expire a session use 0 or negative value -1.

<session-config>
    <session-timeout>0</session-timeout>
</session-config>

or mention 1440 it indicates 1440 minutes [24hours * 60 minutes]

<session-config>
  <session-timeout>1440</session-timeout><!-- 24hours -->
</session-config>

Session will be expire after 24hours.

Remove empty strings from a list of strings

Reply from @Ib33X is awesome. If you want to remove every empty string, after stripped. you need to use the strip method too. Otherwise, it will return the empty string too if it has white spaces. Like, " " will be valid too for that answer. So, can be achieved by.

strings = ["first", "", "second ", " "]
[x.strip() for x in strings if x.strip()]

The answer for this will be ["first", "second"].
If you want to use filter method instead, you can do like
list(filter(lambda item: item.strip(), strings)). This is give the same result.

Python - How do you run a .py file?

use IDLE Editor {You may already have it} it has interactive shell for python and it will show you execution and result.

What is the easiest way to parse an INI File in C++?

Unless you plan on making the app cross-platform, using the Windows API calls would be the best way to go. Just ignore the note in the API documentation about being provided only for 16-bit app compatibility.

Description Box using "onmouseover"

The CSS Tooltip allows you to format the popup as you like as any div section! And no Javascript needed.

month name to month number and vice versa in python

Here's yet another way to do it.

monthToNum(shortMonth):

    return {
            'jan' : 1,
            'feb' : 2,
            'mar' : 3,
            'apr' : 4,
            'may' : 5,
            'jun' : 6,
            'jul' : 7,
            'aug' : 8,
            'sep' : 9, 
            'oct' : 10,
            'nov' : 11,
            'dec' : 12
    }[shortMonth]

Check if a time is between two times (time DataType)

I suspect you want to check that it's after 11pm or before 7am:

select *
from MyTable
where CAST(Created as time) >= '23:00:00' 
   or CAST(Created as time) < '07:00:00'

How to force a UIViewController to Portrait orientation in iOS 6

So I ran into the same problem when displaying portrait only modal views. Normally, I'd create a UINavigationController, set the viewController as the rootViewController, then display the UINavigationController as a modal view. But with iOS 6, the viewController will now ask the navigationController for its supported interface orientations (which, by default, is now all for iPad and everything but upside down for iPhone).

Solution: I had to subclass UINavigationController and override the autorotation methods. Kind of lame.

- (BOOL)shouldAutorotate {
    return NO;
}

- (NSUInteger)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskPortrait;
}
// pre-iOS 6 support 
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
    return (toInterfaceOrientation == UIInterfaceOrientationPortrait);
}

C++ Array of pointers: delete or delete []?

delete[] monsters;

Is incorrect because monsters isn't a pointer to a dynamically allocated array, it is an array of pointers. As a class member it will be destroyed automatically when the class instance is destroyed.

Your other implementation is the correct one as the pointers in the array do point to dynamically allocated Monster objects.

Note that with your current memory allocation strategy you probably want to declare your own copy constructor and copy-assignment operator so that unintentional copying doesn't cause double deletes. (If you you want to prevent copying you could declare them as private and not actually implement them.)

Duplicate line in Visual Studio Code

Ubuntu :

  • Duplicate Line Up : Ctrl + Alt + Shift + 8
  • Duplicate Line Down : Ctrl + Alt + Shift + 2

Process all arguments except the first one (in a bash script)

Use this:

echo "${@:2}"

The following syntax:

echo "${*:2}"

would work as well, but is not recommended, because as @Gordon already explained, that using *, it runs all of the arguments together as a single argument with spaces, while @ preserves the breaks between them (even if some of the arguments themselves contain spaces). It doesn't make the difference with echo, but it matters for many other commands.

Encoding URL query parameters in Java

String param="2019-07-18 19:29:37";
param="%27"+param.trim().replace(" ", "%20")+"%27";

I observed in case of Datetime (Timestamp) URLEncoder.encode(param,"UTF-8") does not work.

How to achieve pagination/table layout with Angular.js?

I use this solution:

It's a bit more concise since I use: ng-repeat="obj in objects | filter : paginate" to filter the rows. Also made it working with $resource:

http://plnkr.co/edit/79yrgwiwvan3bAG5SnKx?p=preview

Basic http file downloading and saving to disk in python?

I use wget.

Simple and good library if you want to example?

import wget

file_url = 'http://johndoe.com/download.zip'

file_name = wget.download(file_url)

wget module support python 2 and python 3 versions

Display date/time in user's locale format and time offset

You can use new Date().getTimezoneOffset()/60 for the timezone. There is also a toLocaleString() method for displaying a date using the user's locale.

Here's the whole list: Working with Dates

Selecting Folder Destination in Java?

try something like this

JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("."));
chooser.setDialogTitle("select folder");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);

How to use S_ISREG() and S_ISDIR() POSIX Macros?

You're using S_ISREG() and S_ISDIR() correctly, you're just using them on the wrong thing.

In your while((dit = readdir(dip)) != NULL) loop in main, you're calling stat on currentPath over and over again without changing currentPath:

if(stat(currentPath, &statbuf) == -1) {
    perror("stat");
    return errno;
}

Shouldn't you be appending a slash and dit->d_name to currentPath to get the full path to the file that you want to stat? Methinks that similar changes to your other stat calls are also needed.

Twitter bootstrap remote modal shows same content every time

Why not make it more general with BS 3? Just use "[something]modal" as the ID of the modal DIV.

$("div[id$='modal']").on('hidden.bs.modal',
    function () {
        $(this).removeData('bs.modal');
    }
);

Angular: How to download a file from HttpClient?

I ended up here when searching for ”rxjs download file using post”.

This was my final product. It uses the file name and type given in the server response.

import { ajax, AjaxResponse } from 'rxjs/ajax';
import { map } from 'rxjs/operators';

downloadPost(url: string, data: any) {
    return ajax({
        url: url,
        method: 'POST',
        responseType: 'blob',
        body: data,
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'text/plain, */*',
            'Cache-Control': 'no-cache',
        }
    }).pipe(
        map(handleDownloadSuccess),
    );
}


handleDownloadSuccess(response: AjaxResponse) {
    const downloadLink = document.createElement('a');
    downloadLink.href = window.URL.createObjectURL(response.response);

    const disposition = response.xhr.getResponseHeader('Content-Disposition');
    if (disposition) {
        const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
        const matches = filenameRegex.exec(disposition);
        if (matches != null && matches[1]) {
            const filename = matches[1].replace(/['"]/g, '');
            downloadLink.setAttribute('download', filename);
        }
    }

    document.body.appendChild(downloadLink);
    downloadLink.click();
    document.body.removeChild(downloadLink);
}

How to open a folder in Windows Explorer from VBA?

Here is what I did.

Dim strPath As String
strPath = "\\server\Instructions\"    
Shell "cmd.exe /c start """" """ & strPath & """", vbNormalFocus

Pros:

  • Avoids opening new explorer instances (only sets focus if window exists).
  • Relatively simple (does not need to reference win32 libraries).
  • Window maximization (or minimization) is not mandatory. Window will open with normal size.

Cons:

  • The cmd-window is visible for a short time.

This consistently opens a window to the folder if there is none open and switches to the open window if there is one open to that folder.

Thanks to PhilHibbs and AnorZaken for the basis for this. PhilHibbs comment didn't quite work for me, I needed to the command string to have a pair of double quotes before the folder name. And I preferred having a command prompt window appear for a bit rather than be forced to have the Explorer window maximized or minimized.

Form Submit jQuery does not work

Some time you have to give all the form element into a same div.

example:-

If you are using ajax submit with modal.

So all the elements are in modal body.

Some time we put submit button in modal footer.

fatal error: iostream.h no such file or directory

Using standard C++ calling (note that you should use namespace std for cout or add using namespace std;)

#include <iostream>

int main()
{
    std::cout<<"Hello World!\n";
    return 0;
}

How to access URL segment(s) in blade in Laravel 5?

BASED ON LARAVEL 5.7 & ABOVE

To get all segments of current URL:

$current_uri = request()->segments();

To get segment posts from http://example.com/users/posts/latest/

NOTE: Segments are an array that starts at index 0. The first element of array starts after the TLD part of the url. So in the above url, segment(0) will be users and segment(1) will be posts.

//get segment 0
$segment_users = request()->segment(0); //returns 'users'
//get segment 1
$segment_posts = request()->segment(1); //returns 'posts'

You may have noted that the segment method only works with the current URL ( url()->current() ). So I designed a method to work with previous URL too by cloning the segment() method:

public function index()
{
    $prev_uri_segments = $this->prev_segments(url()->previous());
}

 /**
 * Get all of the segments for the previous uri.
 *
 * @return array
 */
public function prev_segments($uri)
{
    $segments = explode('/', str_replace(''.url('').'', '', $uri));

    return array_values(array_filter($segments, function ($value) {
        return $value !== '';
    }));
}

The page cannot be displayed because an internal server error has occurred on server

In my case, setting httpErrors and the like in Web.config did not help to identify the issue.

Instead I did:

  1. Activate "Failed Request Tracing" for the website with the error.
  2. Configured a trace for HTTP errors 350-999 (just in case), although I suspected 500.
  3. Called the erroneous URL again.
  4. Watched in the log folder ("%SystemDrive%\inetpub\logs\FailedReqLogFiles" in my case).
  5. Opened one of the XML files in Internet Explorer.

I then saw an entry with a detailed exception information. In my case it was

\?\C:\Websites\example.com\www\web.config ( 592) :Cannot add duplicate collection entry of type 'mimeMap' with unique key attribute 'fileExtension' set to '.json'

I now was able to resolve it and fix the error. After that I deactivated "Failed Request Tracing" again.

FIND_IN_SET() vs IN()

SELECT o.*, GROUP_CONCAT(c.name) FROM Orders AS o , Company.c
    WHERE FIND_IN_SET(c.CompanyID , o.attachedCompanyIDs) GROUP BY o.attachedCompanyIDs

Convert UTC Epoch to local date

The Easiest Way

If you have the unix epoch in milliseconds, in my case - 1601209912824

  1. convert it into a Date Object as so
const dateObject = new Date(milliseconds)
const humanDateFormat = dateObject.toString() 

output -

Sun Sep 27 2020 18:01:52 GMT+0530 (India Standard Time)
  1. if you want the date in UTC -
const dateObject = new Date(milliseconds)
const humanDateFormat = dateObject.toUTCString() 
  1. Now you can format it as you please.

bitwise XOR of hex numbers in python

For performance purpose, here's a little code to benchmark these two alternatives:

#!/bin/python

def hexxorA(a, b):
    if len(a) > len(b):
        return "".join(["%x" % (int(x,16) ^ int(y,16)) for (x, y) in zip(a[:len(b)], b)])
    else:
        return "".join(["%x" % (int(x,16) ^ int(y,16)) for (x, y) in zip(a, b[:len(a)])])

def hexxorB(a, b):
    if len(a) > len(b):
        return '%x' % (int(a[:len(b)],16)^int(b,16))
    else:
        return '%x' % (int(a,16)^int(b[:len(a)],16))

def testA():
    strstr = hexxorA("b4affa21cbb744fa9d6e055a09b562b87205fe73cd502ee5b8677fcd17ad19fce0e0bba05b1315e03575fe2a783556063f07dcd0b9d15188cee8dd99660ee751", "5450ce618aae4547cadc4e42e7ed99438b2628ff15d47b20c5e968f086087d49ec04d6a1b175701a5e3f80c8831e6c627077f290c723f585af02e4c16122b7e2")
    if not int(strstr, 16) == int("e0ff3440411901bd57b24b18ee58fbfbf923d68cd88455c57d8e173d91a564b50ce46d01ea6665fa6b4a7ee2fb2b3a644f702e407ef2a40d61ea3958072c50b3", 16):
        raise KeyError
    return strstr

def testB():
    strstr = hexxorB("b4affa21cbb744fa9d6e055a09b562b87205fe73cd502ee5b8677fcd17ad19fce0e0bba05b1315e03575fe2a783556063f07dcd0b9d15188cee8dd99660ee751", "5450ce618aae4547cadc4e42e7ed99438b2628ff15d47b20c5e968f086087d49ec04d6a1b175701a5e3f80c8831e6c627077f290c723f585af02e4c16122b7e2")
    if not int(strstr, 16) == int("e0ff3440411901bd57b24b18ee58fbfbf923d68cd88455c57d8e173d91a564b50ce46d01ea6665fa6b4a7ee2fb2b3a644f702e407ef2a40d61ea3958072c50b3", 16):
        raise KeyError
    return strstr

if __name__ == '__main__':
    import timeit
    print("Time-it 100k iterations :")
    print("\thexxorA: ", end='')
    print(timeit.timeit("testA()", setup="from __main__ import testA", number=100000), end='s\n')
    print("\thexxorB: ", end='')
    print(timeit.timeit("testB()", setup="from __main__ import testB", number=100000), end='s\n')

Here are the results :

Time-it 100k iterations :
    hexxorA: 8.139988073991844s
    hexxorB: 0.240523161992314s

Seems like '%x' % (int(a,16)^int(b,16)) is faster then the zip version.

How to repeat a char using printf?

If you limit yourself to repeating either a 0 or a space you can do:

For spaces:

printf("%*s", count, "");

For zeros:

printf("%0*d", count, 0);

How to declare global variables in Android?

The approach of subclassing has also been used by the BARACUS framework. From my point of view subclassing Application was intended to work with the lifecycles of Android; this is what any Application Container does. Instead of having globals then, I register beans to this context an let them beeing injected into any class manageable by the context. Every injected bean instance actually is a singleton.

See this example for details

Why do manual work if you can have so much more?

C++ catching all exceptions

Let me just mention this here: the Java

try 
{
...
}
catch (Exception e)
{
...
}

may NOT catch all exceptions! I've actually had this sort of thing happen before, and it's insantiy-provoking; Exception derives from Throwable. So literally, to catch everything, you DON'T want to catch Exceptions; you want to catch Throwable.

I know it sounds nitpicky, but when you've spent several days trying to figure out where the "uncaught exception" came from in code that was surrounded by a try ... catch (Exception e)" block comes from, it sticks with you.

Route.get() requires callback functions but got a "object Undefined"

Some time you miss below line. add this router will understand this.

module.exports = router;

How to determine if a string is a number with C++?

Yet another answer, that uses stold (though you could also use stof/stod if you don't require the precision).

bool isNumeric(const std::string& string)
{
    std::size_t pos;
    long double value = 0.0;

    try
    {
        value = std::stold(string, &pos);
    }
    catch(std::invalid_argument&)
    {
        return false;
    }
    catch(std::out_of_range&)
    {
        return false;
    }

    return pos == string.size() && !std::isnan(value);
}

Angular bootstrap datepicker date format does not format ng-model value

I can fix this by adding below code in my JSP file. Now both model and UI values are same.

<div ng-show="false">
    {{dt = (dt | date:'dd-MMMM-yyyy') }}
</div>  

How can I delete all cookies with JavaScript?

There is no 100% solution to delete browser cookies.

The problem is that cookies are uniquely identified by not just by their key "name" but also their "domain" and "path".

Without knowing the "domain" and "path" of a cookie, you cannot reliably delete it. This information is not available through JavaScript's document.cookie. It's not available through the HTTP Cookie header either!

However, if you know the name, path and domain of a cookie, then you can clear it by setting an empty cookie with an expiry date in the past, for example:

function clearCookie(name, domain, path){
    var domain = domain || document.domain;
    var path = path || "/";
    document.cookie = name + "=; expires=" + +new Date + "; domain=" + domain + "; path=" + path;
};

How do I select between the 1st day of the current month and current day in MySQL?

I was looking for a similar query where I needed to use the first day of a month in my query. The last_day function didn't work for me but DAYOFMONTH came in handy.

So if anyone is looking for the same issue, the following code returns the date for first day of the current month.

SELECT DATE_SUB(CURRENT_DATE, INTERVAL DAYOFMONTH(CURRENT_DATE)-1 DAY);

Comparing a date column with the first day of the month :

select * from table_name where date between 
DATE_SUB(CURRENT_DATE, INTERVAL DAYOFMONTH(CURRENT_DATE)-1 DAY) and CURRENT_DATE

Adding a simple spacer to twitter bootstrap

My approach. Tricky, but works well for me

<p>&nbsp;</p>

Is it possible to style a select box?

As for CSS, Mozilla seems to be the most friendly, especially from FF 3.5+. Webkit browsers mostly just do their own thing, and ignore any style. IE is very limited, though IE8 lets you at least style border color/width.

The following actually looks fairly nice in FF 3.5+ (picking your color preference, of course):

select {
    -moz-border-radius: 4px;
    -moz-box-shadow: 1px 1px 5px #cfcfcf inset;
    border: 1px solid #cfcfcf;
    vertical-align: middle;
    background-color: transparent;
}
option {
    background-color: #fef5e6;
    border-bottom: 1px solid #ebdac0;
    border-right: 1px solid #d6bb86;
    border-left: 1px solid #d6bb86;
}
option:hover {
    cursor: pointer;
}

But when it comes to IE, you have to disable the background color on the option if you don't want it to display when the option menu isn't pulled down. And, as I said, webkit does its own thing.

window.location.href doesn't redirect

I'll give you one nice function for this problem:

function url_redirect(url){
    var X = setTimeout(function(){
        window.location.replace(url);
        return true;
    },300);

    if( window.location = url ){
        clearTimeout(X);
        return true;
    } else {
        if( window.location.href = url ){
            clearTimeout(X);
            return true;
        }else{
            clearTimeout(X);
            window.location.replace(url);
            return true;
        }
    }
    return false;
};

This is universal working solution for the window.location problem. Some browsers go into problem with window.location.href and also sometimes can happen that window.location fail. That's why we also use window.location.replace() for any case and timeout for the "last try".

If '<selector>' is an Angular component, then verify that it is part of this module

Check your selector in your filename.component.ts

Using the tag in various html files I would say

<my-first-component></my-first-component>

Should be

<app-my-first-component></app-my-first-component>

Example

@Component({
  selector: 'app-my-first-component',
  templateUrl: './my-first-component.component.html',
  styleUrls: ['./my-first-component.component.scss']
})

How do you use $sce.trustAsHtml(string) to replicate ng-bind-html-unsafe in Angular 1.2+

$scope.trustAsHtml=function(scope)
{
    return $sce.trustAsHtml(scope);
}
<p class="card-text w-100" ng-bind-html="trustAsHtml(note.redoq_csd_product_lead_note)"></p>

How to check if string contains Latin characters only?

No jQuery Needed

if (str.match(/[a-z]/i)) {
    // alphabet letters found
}

in iPhone App How to detect the screen resolution of the device

UIScreen class lets you find screen resolution in Points and Pixels.

Screen resolutions is measured in Points or Pixels. It should never be confused with screen size. A smaller screen size can have higher resolution.

UIScreen's 'bounds.width' return rectangular size in Points enter image description here

UIScreen's 'nativeBounds.width' return rectangular size in Pixels.This value is detected as PPI ( Point per inch ). Shows the sharpness & clarity of the Image on a device. enter image description here

You can use UIScreen class to detect all these values.

Swift3

// Normal Screen Bounds - Detect Screen size in Points.
let width = UIScreen.main.bounds.width
let height = UIScreen.main.bounds.height
print("\n width:\(width) \n height:\(height)")

// Native Bounds - Detect Screen size in Pixels.
let nWidth = UIScreen.main.nativeBounds.width
let nHeight = UIScreen.main.nativeBounds.height
print("\n Native Width:\(nWidth) \n Native Height:\(nHeight)")

Console

width:736.0 
height:414.0

Native Width:1080.0 
Native Height:1920.0

Swift 2.x

//Normal Bounds - Detect Screen size in Points.
    let width  = UIScreen.mainScreen.bounds.width
    let height = UIScreen.mainScreen.bounds.height

// Native Bounds - Detect Screen size in Pixels.
    let nWidth  = UIScreen.mainScreen.nativeBounds.width
    let nHeight = UIScreen.mainScreen.nativeBounds.height

ObjectiveC

// Normal Bounds - Detect Screen size in Points.
CGFloat *width  = [UIScreen mainScreen].bounds.size.width;
CGFloat *height = [UIScreen mainScreen].bounds.size.height;

// Native Bounds - Detect Screen size in Pixels.
CGFloat *width  = [UIScreen mainScreen].nativeBounds.size.width
CGFloat *height = [UIScreen mainScreen].nativeBounds.size.width

What's the best way to check if a file exists in C?

Yes. Use stat(). See the man page forstat(2).

stat() will fail if the file doesn't exist, otherwise most likely succeed. If it does exist, but you have no read access to the directory where it exists, it will also fail, but in that case any method will fail (how can you inspect the content of a directory you may not see according to access rights? Simply, you can't).

Oh, as someone else mentioned, you can also use access(). However I prefer stat(), as if the file exists it will immediately get me lots of useful information (when was it last updated, how big is it, owner and/or group that owns the file, access permissions, and so on).

How to open an elevated cmd using command line for Windows?

Can use a temporary environment variable to use with an elevated shortcut (

start.cmd

setx valueName_betterSpecificForEachCase %~dp0
"%~dp0ascladm.lnk"

ascladm.lnk (shortcut)

_ properties\advanced\"run as administrator"=yes

(to make path changes you'll need to temporarily create the env.Variable)

_ properties\target="%valueName_betterSpecificForEachCase%\ascladm.cmd"

_ properties\"start in"="%valueName_betterSpecificForEachCase%"

ascladm.cmd

setx valueName_betterSpecificForEachCase=
reg delete HKEY_CURRENT_USER\Environment /F /V valueName_betterSpecificForEachCase
"%~dp0fileName_targetedCmd.cmd"

) (targetedCmd gets executed in elevated cmd window)

Although it is 3 files ,you can place everything (including targetedCmd) in some subfolder (do not forget to add the folderName to the patches) and rename "start.cmd" to targeted's one name

For me it looks like most native way of doing this ,whilst cmd doesn't have the needed command

console.log showing contents of array object

Json stands for JavaScript Object Notation really all json is are javascript objects so your array is in json form already. To write it out in a div you could do a bunch of things one of the easiest I think would be:

 objectDiv.innerHTML = filter;

where objectDiv is the div you want selected from the DOM using jquery. If you wanted to list parts of the array out you could access them since it is a javascript object like so:

 objectDiv.innerHTML = filter.dvals.valueToDisplay; //brand or count depending.

edit: anything you want to be a string but is not currently (which is rare javascript treats almost everything as a string) just use the toString() function built in. so line above if you needed it would be filter.dvals.valueToDisplay.toString();

second edit to clarify: this answer is in response to the OP's comments and not completely to his original question.

How to create/make rounded corner buttons in WPF?

Although this question is long-since answered, I used an alternative approach that people might find simpler than any of these solutions (even Keith Stein's excellent answer). So I'm posting it in case it might help anyone.

You can achieve rounded corners on a button without having to write any XAML (other than a Style, once) and without having to replace the template or set/change any other properties. Just use an EventSetter in your style for the button's "Loaded" event and change it in code-behind.

(And if your style lives in a separate Resource Dictionary XAML file, then you can put the event code in a code-behind file for your resource dictionary.)

I do it like this:

Xaml Style:

<Style x:Key="ButtonStyle" TargetType="{x:Type Button}" BasedOn="{StaticResource {x:Type Button}}">
    <EventSetter Event="Loaded"                   Handler="ButtonLoaded"/>
</Style>

Code-Behind:

public partial class ButtonStyles
{
    private void ButtonLoaded(object sender, RoutedEventArgs e)
    {
        if (!(sender is Button b))
            return;

        // Find the first top-level border we can.

        Border border = default;
        for (var i = 0; null == border && i < VisualTreeHelper.GetChildrenCount(b); ++i)
            border = VisualTreeHelper.GetChild(b, i) as Border;

        // If we found it, set its corner radius how we want.  

        if (border != null)
            border.CornerRadius = new CornerRadius(3);
    }
}

If you had to add the code-behind file to an existing resource dictionary xaml file, you can even have the code-behind file automatically appear underneath that XAML file in the Visual Studio Solution if you want. In a .NET Core project, just give it appropriate corresponding name (e.g if the resource Dictionary is "MyDictionary.xaml", name the code-behind file "MyDictionary.xaml.cs"). In a .NET Framework project, you need to edit the .csproj file in XML mode

How to multiply a BigDecimal by an integer in Java

First off, BigDecimal.multiply() returns a BigDecimal and you're trying to store that in an int.

Second, it takes another BigDecimal as the argument, not an int.

If you just use the BigDecimal for all variables involved in these calculations, it should work fine.

How to use jQuery Plugin with Angular 4?

Yes you can use jquery with Angular 4

Steps:

1) In index.html put below line in tag.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

2) In component ts file below you have to declare var like this

import { Component } from '@angular/core';
declare var jquery:any;
declare var $ :any;

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'angular 4 with jquery';
  toggleTitle(){
    $('.title').slideToggle(); //
  }

}

And use this code for corresponding html file like this:

<h1 class="title" style="display:none">
  {{title}}
</h1>
<button (click)="toggleTitle()"> clickhere</button>

This will work for you. Thanks

send Content-Type: application/json post with node.js

Since the request module that other answers use has been deprecated, may I suggest switching to node-fetch:

const fetch = require("node-fetch")

const url = "https://www.googleapis.com/urlshortener/v1/url"
const payload = { longUrl: "http://www.google.com/" }

const res = await fetch(url, {
  method: "post",
  body: JSON.stringify(payload),
  headers: { "Content-Type": "application/json" },
})

const { id } = await res.json()

In Python how should I test if a variable is None, True or False

Don't fear the Exception! Having your program just log and continue is as easy as:

try:
    result = simulate(open("myfile"))
except SimulationException as sim_exc:
    print "error parsing stream", sim_exc
else:
    if result:
        print "result pass"
    else:
        print "result fail"

# execution continues from here, regardless of exception or not

And now you can have a much richer type of notification from the simulate method as to what exactly went wrong, in case you find error/no-error not to be informative enough.

Error resolving template "index", template might not exist or might not be accessible by any of the configured Template Resolvers

I am new to spring spent an hour trying to figure this out.

go to --- > application.properties

add these :

spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html

how to setup ssh keys for jenkins to publish via ssh

For Windows:

  1. Install the necessary plugins for the repository (ex: GitHub install GitHub and GitHub Authentication plugins) in Jenkins.
  2. You can generate a key with Putty key generator, or by running the following command in git bash: $ ssh-keygen -t rsa -b 4096 -C [email protected]
  3. Private key must be OpenSSH. You can convert your private key to OpenSSH in putty key generator
  4. SSH keys come in pairs, public and private. Public keys are inserted in the repository to be cloned. Private keys are saved as credentials in Jenkins
  5. You need to copy the SSH URL not the HTTPS to work with ssh keys.

How to debug external class library projects in visual studio?

[according to Martin Beckett, the guy who send me this answer ]

You can debug into an external library.

In the project settings tab look for 'visual studio directories' in the 'source code' field include the path to the openCV sources. Then make sure that the .pdb files for each of the debug dll are in the same directory as the dll.

sqlplus statement from command line

I'm able to execute your exact query by just making sure there is a semicolon at the end of my select statement. (Output is actual, connection params removed.)

echo "select 1 from dual;" | sqlplus -s username/password@host:1521/service 

Output:

         1
----------
         1

Note that is should matter but this is running on Mac OS X Snow Leopard and Oracle 11g.

Difference between jQuery .hide() and .css("display", "none")

no difference

With no parameters, the .hide() method is the simplest way to hide an element:

$('.target').hide(); The matched elements will be hidden immediately, with no animation. This is roughly equivalent to calling .css('display', 'none'), except that the value of the display property is saved in jQuery's data cache so that display can later be restored to its initial value. If an element has a display value of inline, then is hidden and shown, it will once again be displayed inline.

Same about show

How to remove not null constraint in sql server using query

Remove column constraint: not null to null

ALTER TABLE test ALTER COLUMN column_01 DROP NOT NULL;

Difference between ref and out parameters in .NET

out parameters are initialized by the method called, ref parameters are initialized before calling the method. Therefore, out parameters are used when you just need to get a secondary return value, ref parameters are used to get a value and potentially return a change to that value (secondarily to the main return value).

Sort ObservableCollection<string> through C#

I did a sort on a certain class field (distance).

public class RateInfo 
{
    public string begin { get; set; }
    public string end { get; set; }
    public string price { get; set; }
    public string comment { get; set; }
    public string phone { get; set; }
    public string ImagePath { get; set; }
    public string what { get; set; }
    public string distance { get; set; }
}    

public ObservableCollection<RateInfo> Phones { get; set; }

public List<RateInfo> LRate { get; set; }

public ObservableCollection<RateInfo> Phones { get; set; }

public List<RateInfo> LRate { get; set; }

......

foreach (var item in ph)
        {

            LRate.Add(new RateInfo { begin = item["begin"].ToString(), end = item["end"].ToString(), price = item["price"].ToString(), distance=kilom, ImagePath = "chel.png" });
        }

       LRate.Sort((x, y) => x.distance.CompareTo(y.distance));

        foreach (var item in LRate)
        {
            Phones.Add(item);
        }

WAMP/XAMPP is responding very slow over localhost

For my it was the xdebug. I disabled and it worked as it should be !

[XDebug]
zend_extension = C:\xampp\php\ext\php_xdebug-2.3.2-5.6-vc11.dll