Programs & Examples On #Catalog

Error ITMS-90717: "Invalid App Store Icon"

Use Alpha Channel Remover. It lets you drag icons into the app and it'll remove transparency.

Download it from here: http://alphachannelremover.blogspot.com

Update: this is not my site

Using app.config in .Net Core

It is possible to use your usual System.Configuration even in .NET Core 2.0 on Linux. Try this test example:

  1. Created a .NET Standard 2.0 Library (say MyLib.dll)
  2. Added the NuGet package System.Configuration.ConfigurationManager v4.4.0. This is needed since this package isn't covered by the meta-package NetStandard.Library v2.0.0 (I hope that changes)
  3. All your C# classes derived from ConfigurationSection or ConfigurationElement go into MyLib.dll. For example MyClass.cs derives from ConfigurationSection and MyAccount.cs derives from ConfigurationElement. Implementation details are out of scope here but Google is your friend.
  4. Create a .NET Core 2.0 app (e.g. a console app, MyApp.dll). .NET Core apps end with .dll rather than .exe in Framework.
  5. Create an app.config in MyApp with your custom configuration sections. This should obviously match your class designs in #3 above. For example:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="myCustomConfig" type="MyNamespace.MyClass, MyLib" />
  </configSections>
  <myCustomConfig>
    <myAccount id="007" />
  </myCustomConfig>
</configuration>

That's it - you'll find that the app.config is parsed properly within MyApp and your existing code within MyLib works just fine. Don't forget to run dotnet restore if you switch platforms from Windows (dev) to Linux (test).

Additional workaround for test projects

If you're finding that your App.config is not working in your test projects, you might need this snippet in your test project's .csproj (e.g. just before the ending </Project>). It basically copies App.config into your output folder as testhost.dll.config so dotnet test picks it up.

  <!-- START: This is a buildtime work around for https://github.com/dotnet/corefx/issues/22101 -->
  <Target Name="CopyCustomContent" AfterTargets="AfterBuild">
    <Copy SourceFiles="App.config" DestinationFiles="$(OutDir)\testhost.dll.config" />
  </Target>
  <!-- END: This is a buildtime work around for https://github.com/dotnet/corefx/issues/22101 -->

how can get index & count in vuejs

Using Vue 1.x, use the special variable $index like so:

<li v-for="catalog in catalogs">this index : {{$index + 1}}</li>

alternatively, you can specify an alias as a first argument for v-for directive like so:

<li v-for="(itemObjKey, catalog) in catalogs">
    this index : {{itemObjKey + 1}}
</li>

See : Vue 1.x guide

Using Vue 2.x, v-for provides a second optional argument referencing the index of the current item, you can add 1 to it in your mustache template as seen before:

<li v-for="(catalog, itemObjKey) in catalogs">
    this index : {{itemObjKey + 1}}
</li>

See: Vue 2.x guide

Eliminating the parentheses in the v-for syntax also works fine hence:

<li v-for="catalog, itemObjKey in catalogs">
    this index : {{itemObjKey + 1}}
</li>

Hope that helps.

Angular2 equivalent of $document.ready()

I went with this solution so I didn't have to include my custom js code within the component other than the jQuery $.getScript function.

Note: Has a dependency on jQuery. So you will need jQuery and jQuery typings.

I have found this is a good way to get around custom or vendor js files that do not have typings available that way TypeScript doesn't scream at you when you go to start your app.

import { Component,AfterViewInit} from '@angular/core'

@Component({
  selector: 'ssContent',
  templateUrl: 'app/content/content.html',
})
export class ContentComponent implements AfterViewInit  {

  ngAfterViewInit(){
    $.getScript('../js/myjsfile.js');
  }
}

Update Actually in my scenario the OnInit lifecycle event worked better because it prevented the script from loading after the views were loaded, which was the case with ngAfterViewInit, and that cause the view to show incorrect element positions prior to the script loading.

ngOnInit() {
    $.getScript('../js/mimity.js');
  }

HikariCP - connection is not available

From stack trace:

HikariPool: Timeout failure pool HikariPool-0 stats (total=20, active=20, idle=0, waiting=0) Means pool reached maximum connections limit set in configuration.

The next line: HikariPool-0 - Connection is not available, request timed out after 30000ms. Means pool waited 30000ms for free connection but your application not returned any connection meanwhile.

Mostly it is connection leak (connection is not closed after borrowing from pool), set leakDetectionThreshold to the maximum value that you expect SQL query would take to execute.

otherwise, your maximum connections 'at a time' requirement is higher than 20 !

How to update RecyclerView Adapter Data?

I strongly recommend you to use [DiffUtil.ItemCallback][1] to handle the change in RecyclerView.Adapter


 fun setData(data: List<T>) {
        val calculateDiff = DiffUtil.calculateDiff(DiffUtilCallback(items, data))
        items.clear()
        items += data
        calculateDiff.dispatchUpdatesTo(this)
    }

under the hood it handles most of the things with AdapterListUpdateCallback:

/**
 * ListUpdateCallback that dispatches update events to the given adapter.
 *
 * @see DiffUtil.DiffResult#dispatchUpdatesTo(RecyclerView.Adapter)
 */
public final class AdapterListUpdateCallback implements ListUpdateCallback {
    @NonNull
    private final RecyclerView.Adapter mAdapter;

    /**
     * Creates an AdapterListUpdateCallback that will dispatch update events to the given adapter.
     *
     * @param adapter The Adapter to send updates to.
     */
    public AdapterListUpdateCallback(@NonNull RecyclerView.Adapter adapter) {
        mAdapter = adapter;
    }

    /** {@inheritDoc} */
    @Override
    public void onInserted(int position, int count) {
        mAdapter.notifyItemRangeInserted(position, count);
    }

    /** {@inheritDoc} */
    @Override
    public void onRemoved(int position, int count) {
        mAdapter.notifyItemRangeRemoved(position, count);
    }

    /** {@inheritDoc} */
    @Override
    public void onMoved(int fromPosition, int toPosition) {
        mAdapter.notifyItemMoved(fromPosition, toPosition);
    }

    /** {@inheritDoc} */
    @Override
    public void onChanged(int position, int count, Object payload) {
        mAdapter.notifyItemRangeChanged(position, count, payload);
    }
}

python save image from url

import random
import urllib.request

def download_image(url):
    name = random.randrange(1,100)
    fullname = str(name)+".jpg"
    urllib.request.urlretrieve(url,fullname)     
download_image("http://site.meishij.net/r/58/25/3568808/a3568808_142682562777944.jpg")

Spring boot - Not a managed type

Try adding All the following, In my application it is working fine with tomcat

 @EnableJpaRepositories("my.package.base.*")
 @ComponentScan(basePackages = { "my.package.base.*" })
 @EntityScan("my.package.base.*")   

I am using spring boot, and when i am using embedded tomcat it was working fine with out @EntityScan("my.package.base.*") but when I tried to deploy the app to an external tomcat I got not a managed type error for my entity.

Using Excel VBA to run SQL query

Below is code that I currently use to pull data from a MS SQL Server 2008 into VBA. You need to make sure you have the proper ADODB reference [VBA Editor->Tools->References] and make sure you have Microsoft ActiveX Data Objects 2.8 Library checked, which is the second from the bottom row that is checked (I'm using Excel 2010 on Windows 7; you might have a slightly different ActiveX version, but it will still begin with Microsoft ActiveX):

References required for SQL

Sub Module for Connecting to MS SQL with Remote Host & Username/Password

Sub Download_Standard_BOM()
'Initializes variables
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim ConnectionString As String
Dim StrQuery As String

'Setup the connection string for accessing MS SQL database
   'Make sure to change:
       '1: PASSWORD
       '2: USERNAME
       '3: REMOTE_IP_ADDRESS
       '4: DATABASE
    ConnectionString = "Provider=SQLOLEDB.1;Password=PASSWORD;Persist Security Info=True;User ID=USERNAME;Data Source=REMOTE_IP_ADDRESS;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;Tag with column collation when possible=False;Initial Catalog=DATABASE"

    'Opens connection to the database
    cnn.Open ConnectionString
    'Timeout error in seconds for executing the entire query; this will run for 15 minutes before VBA timesout, but your database might timeout before this value
    cnn.CommandTimeout = 900

    'This is your actual MS SQL query that you need to run; you should check this query first using a more robust SQL editor (such as HeidiSQL) to ensure your query is valid
    StrQuery = "SELECT TOP 10 * FROM tbl_table"

    'Performs the actual query
    rst.Open StrQuery, cnn
    'Dumps all the results from the StrQuery into cell A2 of the first sheet in the active workbook
    Sheets(1).Range("A2").CopyFromRecordset rst
End Sub

How to detect query which holds the lock in Postgres?

From this excellent article on query locks in Postgres, one can get blocked query and blocker query and their information from the following query.

CREATE VIEW lock_monitor AS(
SELECT
  COALESCE(blockingl.relation::regclass::text,blockingl.locktype) as locked_item,
  now() - blockeda.query_start AS waiting_duration, blockeda.pid AS blocked_pid,
  blockeda.query as blocked_query, blockedl.mode as blocked_mode,
  blockinga.pid AS blocking_pid, blockinga.query as blocking_query,
  blockingl.mode as blocking_mode
FROM pg_catalog.pg_locks blockedl
JOIN pg_stat_activity blockeda ON blockedl.pid = blockeda.pid
JOIN pg_catalog.pg_locks blockingl ON(
  ( (blockingl.transactionid=blockedl.transactionid) OR
  (blockingl.relation=blockedl.relation AND blockingl.locktype=blockedl.locktype)
  ) AND blockedl.pid != blockingl.pid)
JOIN pg_stat_activity blockinga ON blockingl.pid = blockinga.pid
  AND blockinga.datid = blockeda.datid
WHERE NOT blockedl.granted
AND blockinga.datname = current_database()
);

SELECT * from lock_monitor;

As the query is long but useful, the article author has created a view for it to simplify it's usage.

Read specific columns with pandas or other python module

Above answers are in python2. So for python 3 users I am giving this answer. You can use the bellow code:

import pandas as pd
fields = ['star_name', 'ra']

df = pd.read_csv('data.csv', skipinitialspace=True, usecols=fields)
# See the keys
print(df.keys())
# See content in 'star_name'
print(df.star_name)

Cannot create Maven Project in eclipse

Just delete the ${user.home}/.m2/repository/org/apache/maven/archetypes to refresh all files needed, it worked fine to me!

Select query to get data from SQL Server

That is by design.

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery(v=vs.110).aspx

For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. When a trigger exists on a table being inserted or updated, the return value includes the number of rows affected by both the insert or update operation and the number of rows affected by the trigger or triggers. For all other types of statements, the return value is -1. If a rollback occurs, the return value is also -1.

Ignore fields from Java object dynamically while sending as JSON from Spring MVC

If I were you and wanted to do so, I wouldn't use my User entity in Controller layer.Instead I create and use UserDto (Data transfer object) to communicate with business(Service) layer and Controller. You can use Apache BeanUtils(copyProperties method) to copy data from User entity to UserDto.

How to prevent 'query timeout expired'? (SQLNCLI11 error '80040e31')

Turns out that the post (or rather the whole table) was locked by the very same connection that I tried to update the post with.

I had a opened record set of the post that was created by:

Set RecSet = Conn.Execute()

This type of recordset is supposed to be read-only and when I was using MS Access as database it did not lock anything. But apparently this type of record set did lock something on MS SQL Server 2012 because when I added these lines of code before executing the UPDATE SQL statement...

RecSet.Close
Set RecSet = Nothing

...everything worked just fine.

So bottom line is to be careful with opened record sets - even if they are read-only they could lock your table from updates.

System.Data.SqlClient.SqlException: Login failed for user

I faced the same situation. Create your connection string as follows.

Replace

"connectionString": "Data Source=server name;Initial Catalog=DB name;User id=user id;Password=password;Integrated Security=True;MultipleActiveResultSets=True"

by

"connectionString": "Server=server name; Database=Treat; User Id=user id; Password=password; Trusted_Connection=False; MultipleActiveResultSets=true"

How to solve the system.data.sqlclient.sqlexception (0x80131904) error

The datasource is by default .\SQLEXPRESS (its the instance where databases are placed by default) or if u changed the name of the instance during installation of sql server so i advise you to do this :

connectionString="Data Source=.\\yourInstance(defaulT Data source is SQLEXPRESS);
       Initial Catalog=databaseName;
       User ID=theuser if u use it;
       Password=thepassword if u use it;
       integrated security=true(if u don t use user and pass; else change it false)"

Without to knowing your instance, I could help with this one. Hope it helped

Summernote image upload

I tested this code and Works

Javascript

<script>
$(document).ready(function() {
  $('#summernote').summernote({
    height: 200,
    onImageUpload: function(files, editor, welEditable) {
      sendFile(files[0], editor, welEditable);
    }
  });

  function sendFile(file, editor, welEditable) {
    data = new FormData();
    data.append("file", file);
    $.ajax({
      data: data,
      type: "POST",
      url: "Your URL POST (php)",
      cache: false,
      contentType: false,
      processData: false,
      success: function(url) {
        editor.insertImage(welEditable, url);
      }
    });
  }
});
</script>

PHP

if ($_FILES['file']['name']) {
  if (!$_FILES['file']['error']) {
    $name = md5(rand(100, 200));
    $ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
    $filename = $name.
    '.'.$ext;
    $destination = '/assets/images/'.$filename; //change this directory
    $location = $_FILES["file"]["tmp_name"];
    move_uploaded_file($location, $destination);
    echo 'http://test.yourdomain.al/images/'.$filename; //change this URL
  } else {
    echo $message = 'Ooops!  Your upload triggered the following error:  '.$_FILES['file']['error'];
  }
}

Update:

After 0.7.0 onImageUpload should be inside callbacks option as mentioned by @tugberk

$('#summernote').summernote({
    height: 200,
    callbacks: {
        onImageUpload: function(files, editor, welEditable) {
            sendFile(files[0], editor, welEditable);
        }
    }
});

Sql connection-string for localhost server

Do You have Internal Connection or External Connection. If you did Internal Connection then try this:

"Data Source=.\SQLEXPRESS;AttachDbFilename="Your PAth .mdf";Integrated Security=True;User Instance=True";

How to get first item from a java.util.Set?

From the Oracle docs:

As implied by its name, this interface models the mathematical set abstraction.

In Set Theory, "a "set" is a collection of distinct objects, considered as an object in its own right." - [Wikipedia - Set].

Mathematically, elements in sets are not individualised. Their only identity is derived from their presence in the set. Therefore, there is no point in getting the "first" element in a set, as conceptually such a task is illogical.

There may be no point to getting the "first" element from a set, but if all you need is to get one single object from a set (with no guarantees as to which object that is) you can do the following:

for(String aSiteId: siteIdSet) {
    siteId = aSiteId;
    break;
}

This is a slightly shorter way (than the method you posted) to get the "first" object of a Set, however since an Iterator is still being created (under the hood) it does not grant any performance benefit.

str.startswith with a list of strings to test for

You can also use any(), map() like so:

if any(map(l.startswith, x)):
    pass # Do something

Or alternatively, using a generator expression:

if any(l.startswith(s) for s in x)
    pass # Do something

Selenium WebDriver can't find element by link text

find_elements_by_xpath("//*[@class='class name']")

is a great solution

Entity Framework change connection at runtime

The created class is 'partial'!

public partial class Database1Entities1 : DbContext
{
    public Database1Entities1()
        : base("name=Database1Entities1")
    {
    }

... and you call it like this:

using (var ctx = new Database1Entities1())
      {
        #if DEBUG
        ctx.Database.Log = Console.Write;
        #endif

so, you need only create a partial own class file for original auto-generated class (with same class name!) and add a new constructor with connection string parameter, like Moho's answer before.

After it you able to use parametrized constructor against original. :-)

example:

using (var ctx = new Database1Entities1(myOwnConnectionString))
      {
        #if DEBUG
        ctx.Database.Log = Console.Write;
        #endif

How to save SELECT sql query results in an array in C# Asp.net

Instead of any Array you can load your data in DataTable like:

using System.Data;

DataTable dt = new DataTable();
using (var con = new SqlConnection("Data Source=local;Initial Catalog=Test;Integrated Security=True"))
{
    using (var command = new SqlCommand("SELECT col1,col2" +
    {
        con.Open();
        using (SqlDataReader dr = command.ExecuteReader())
        {
            dt.Load(dr);
        }
    }
}

You can also use SqlDataAdapater to fill your DataTable like

SqlDataAdapter da = new SqlDataAdapter(command);
da.Fill(dt);

Later you can iterate each row and compare like:

foreach (DataRow dr in dt.Rows)
{
    if (dr.Field<string>("col1") == "yourvalue") //your condition
    {
    }
}

could not extract ResultSet in hibernate

For MySql take in mind that it's not a good idea to write camelcase. For example if the schema is like that:

CREATE TABLE IF NOT EXISTS `task`(
    `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
    `teaching_hours` DECIMAL(5,2) DEFAULT NULL,
    `isActive` BOOLEAN DEFAULT FALSE,
    `is_validated` BOOLEAN DEFAULT FALSE,
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

You must be very careful cause isActive column will translate to isactive. So in your Entity class is should be like this:

 @Basic
 @Column(name = "isactive", nullable = true)
 public boolean isActive() {
     return isActive;
 }
 public void setActive(boolean active) {
     isActive = active;
 }

That was my problem at least that got me your error

This has nothing to do with MySql which is case insensitive, but rather is a naming strategy that spring will use to translate your tables. For more refer to this post

Understanding Spring @Autowired usage

Yes, you can configure the Spring servlet context xml file to define your beans (i.e., classes), so that it can do the automatic injection for you. However, do note, that you have to do other configurations to have Spring up and running and the best way to do that, is to follow a tutorial ground up.

Once you have your Spring configured probably, you can do the following in your Spring servlet context xml file for Example 1 above to work (please replace the package name of com.movies to what the true package name is and if this is a 3rd party class, then be sure that the appropriate jar file is on the classpath) :

<beans:bean id="movieFinder" class="com.movies.MovieFinder" />

or if the MovieFinder class has a constructor with a primitive value, then you could something like this,

<beans:bean id="movieFinder" class="com.movies.MovieFinder" >
    <beans:constructor-arg value="100" />
</beans:bean>

or if the MovieFinder class has a constructor expecting another class, then you could do something like this,

<beans:bean id="movieFinder" class="com.movies.MovieFinder" >
    <beans:constructor-arg ref="otherBeanRef" />
</beans:bean>

...where 'otherBeanRef' is another bean that has a reference to the expected class.

"int cannot be dereferenced" in Java

Change

id.equals(list[pos].getItemNumber())

to

id == list[pos].getItemNumber()

For more details, you should learn the difference between the primitive types like int, char, and double and reference types.

iOS 7 App Icons, Launch images And Naming Convention While Keeping iOS 6 Icons

You should use Asset Catalog:

I have investigated, how we can use Asset Catalog; Now it seems to be easy for me. I want to show you steps to add icons and splash in asset catalog.

Note: No need to make any entry in info.plist file :) And no any other configuration.

In below image, at right side, you will see highlighted area, where you can mention which icons you need. In case of mine, i have selected first four checkboxes; As its for my app requirements. You can select choices according to your requirements.

enter image description here

Now, see below image. As you will select any App icon then you will see its detail at right side selected area. It will help you to upload correct resolution icon. enter image description here

If Correct resolution image will not be added then following warning will come. Just upload the image with correct resolution. enter image description here

After uploading all required dimensions, you shouldn't get any warning. enter image description here

Responsive image align center bootstrap 3

Try this:

_x000D_
_x000D_
.img-responsive{_x000D_
    display: block;_x000D_
    height: auto;_x000D_
    max-width: 100%;_x000D_
   margin:0 auto;_x000D_
}_x000D_
.Image{_x000D_
  background:#ccc;_x000D_
  padding:30px;_x000D_
}
_x000D_
<div class="Image">_x000D_
  <img src="http://minisoft.com.bd/uploads/ourteam/rafiq.jpg" class="img-responsive" title="Rafique" alt="Rafique">_x000D_
</div>
_x000D_
_x000D_
_x000D_

Entity Framework The underlying provider failed on Open

Seems like a connection issue. You can use the Data link properties to find if the connection is fine. Do the following:

  1. Create a blank notepad and rename it to "X.UDL"
  2. Double click to open it
  3. Under connections tab choose the server name/enter the name use the correct credentials and DB
  4. Click OK to save it.

Now open the file in Notepad and compare the connection string properties.

The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception

I solved this problem removing DbproviderFactory in the section system.data of the file machine.config, there was some dirty data when I installed fbclient.dll.

C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\machine.config C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\machine.config

  <system.data>
    <!-- <DbProviderFactories><add name="FirebirdClient Data Provider" invariant="FirebirdSql.Data.FirebirdClient" description=".NET Framework Data Provider for Firebird" type="FirebirdSql.Data.FirebirdClient.FirebirdClientFactory, FirebirdSql.Data.FirebirdClient, Version=4.10.0.0, Culture=neutral, PublicKeyToken=3750abcc3150b00c"/><add name="FirebirdClient Data Provider" invariant="FirebirdSql.Data.FirebirdClient" description=".NET Framework Data Provider for Firebird" type="FirebirdSql.Data.FirebirdClient.FirebirdClientFactory, FirebirdSql.Data.FirebirdClient, Version=6.4.0.0, Culture=neutral, PublicKeyToken=3750abcc3150b00c"/> -->
  </system.data>

Cannot attach the file *.mdf as database

You already have an old copy of that database installed in Server Explorer. So its a simple naming collision in the Server Object Explorer / SQL server. You likely created the same database Catalog Name already before you decided to move it to the Apps_Data folder. So that Database name already exists and just needs to be deleted.

Just go into Visual Studio > View > SQL Server Object Explorer and delete the old database name and its connection. Retry your app again and it should install the .mdf file in App_Data and create the same exact database again in the Server Explorer.

How do I get values from a SQL database into textboxes using C#?

The line reader.Read() is missing in your code. You should add it. It is the function which actually reads data from the database:

string conString = "Data Source=localhost;Initial Catalog=LoginScreen;Integrated Security=True";
SqlConnection con = new SqlConnection(conString);

string selectSql = "select * from Pending_Tasks";
SqlCommand com = new SqlCommand(selectSql, con);

try
{
    con.Open();

    using (SqlDataReader read = cmd.ExecuteReader())
    {
        while(reader.Read())
        {
            CustID.Text = (read["Customer_ID"].ToString());
            CustName.Text = (read["Customer_Name"].ToString());
            Add1.Text = (read["Address_1"].ToString());
            Add2.Text = (read["Address_2"].ToString());
            PostBox.Text = (read["Postcode"].ToString());
            PassBox.Text = (read["Password"].ToString());
            DatBox.Text = (read["Data_Important"].ToString());
            LanNumb.Text = (read["Landline"].ToString());
            MobNumber.Text = (read["Mobile"].ToString());
            FaultRep.Text = (read["Fault_Report"].ToString());
        }
    }
}
finally
{
    con.Close();
}

EDIT : This code works supposing you want to write the last record to your textboxes. If you want to apply a different scenario, like for example to read all the records from database and to change data in the texboxes when you click the Next button, you should create and use your own Model, or you can store data in the DataTable and refer to them later if you wish.

Get product id and product type in magento?

Try below code to get currently loaded product id:

$product_id = $this->getProduct()->getId();

When you don’t have access to $this, you can use Magento registry:

$product_id = Mage::registry('current_product')->getId();

Also for product type i think

$product = Mage::getModel('catalog/product')->load($product_id); 

$productType = $product->getTypeId();

how to insert a new line character in a string to PrintStream then use a scanner to re-read the file

The linefeed character \n is not the line separator in certain operating systems (such as windows, where it's "\r\n") - my suggestion is that you use \r\n instead, then it'll both see the line-break with only \n and \r\n, I've never had any problems using it.

Also, you should look into using a StringBuilder instead of concatenating the String in the while-loop at BookCatalog.toString(), it is a lot more effective. For instance:

public String toString() {
        BookNode current = front;
        StringBuilder sb = new StringBuilder();
        while (current!=null){
            sb.append(current.getData().toString()+"\r\n ");
            current = current.getNext();
        }
        return sb.toString();
}

VB.NET Connection string (Web.Config, App.Config)

Public Function connectDB() As OleDbConnection

        Dim Con As New OleDbConnection
        'Con.ConnectionString = "Provider=SQLOLEDB.1;Persist Security Info=False;User ID=sa;Initial Catalog=" & DBNAME & ";Data Source=" & DBSERVER & ";Pwd=" & DBPWD & ""
        Con.ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=DBNAME;Data Source=DBSERVER-TOSH;User ID=Sa;Pwd= & DBPWD"
        Try
            Con.Open()
        Catch ex As Exception
            showMessage(ex)
        End Try
        Return Con
    End Function

Can't access Eclipse marketplace

And also check with your antivirus, in case of me its avast, its blocking me from accessing market place, so i disabled it for few mins and tried accessing market place from eclipse , it worked!!!

Magento: Set LIMIT on collection

Order Collection Limit :

$orderCollection = Mage::getResourceModel('sales/order_collection'); 
$orderCollection->getSelect()->limit(10);

foreach ($orderCollection->getItems() as $order) :
   $orderModel = Mage::getModel('sales/order');
   $order =   $orderModel->load($order['entity_id']);
   echo $order->getId().'<br>'; 
endforeach; 

Connection string using Windows Authentication

This is shorter and works

<connectionStrings>      
<add name="DBConnection"
             connectionString="data source=SERVER\INSTANCE;
       Initial Catalog=MyDB;Integrated Security=SSPI;"
             providerName="System.Data.SqlClient" />
</connectionStrings> 

Persist Security Info not needed

How to retrieve data from a SQL Server database in C#?

create a class called DbManager:

Class DbManager
{
 SqlConnection connection;
 SqlCommand command;

       public DbManager()
      {
        connection = new SqlConnection();
        connection.ConnectionString = @"Data Source=.     \SQLEXPRESS;AttachDbFilename=|DataDirectory|DatabaseName.mdf;Integrated Security=True;User Instance=True";
        command = new SqlCommand();
        command.Connection = connection;
        command.CommandType = CommandType.Text;
     } // constructor

 public bool GetUsersData(ref string lastname, ref string firstname, ref string age)
     {
        bool returnvalue = false;
        try
        {
            command.CommandText = "select * from TableName where firstname=@firstname and lastname=@lastname";
            command.Parameters.Add("firstname",SqlDbType.VarChar).Value = firstname;
 command.Parameters.Add("lastname",SqlDbType.VarChar).Value = lastname; 
            connection.Open();
            SqlDataReader reader= command.ExecuteReader();
            if (reader.HasRows)
            {
                while (reader.Read())
                {

                    lastname = reader.GetString(1);
                    firstname = reader.GetString(2);

                    age = reader.GetString(3);


                }
            }
            returnvalue = true;
        }
        catch
        { }
        finally
        {
            connection.Close();
        }
        return returnvalue;

    }

then double click the retrieve button(e.g btnretrieve) on your form and insert the following code:

 private void btnretrieve_Click(object sender, EventArgs e)
    {
        try
        {
            string lastname = null;
            string firstname = null;
            string age = null;

            DbManager db = new DbManager();

            bool status = db.GetUsersData(ref surname, ref firstname, ref age);
                if (status)
                {
                txtlastname.Text = surname;
                txtfirstname.Text = firstname;
                txtAge.Text = age;       
               }
          }
       catch
          {

          }
   }

How to display data from database into textbox, and update it

protected void Page_Load(object sender, EventArgs e)

    {

        DropDownTitle();
    }


protected void DropDownTitle()
{
    if (!Page.IsPostBack)
    {

        string connection = System.Configuration.ConfigurationManager.ConnectionStrings["AuzineConnection"].ConnectionString;

        string selectSQL = "select DISTINCT ForumTitlesID,ForumTitles from ForumTtitle";
        SqlConnection con = new SqlConnection(connection);
        SqlCommand cmd = new SqlCommand(selectSQL, con);
        SqlDataReader reader;
        try
        {

            ListItem newItem = new ListItem();
            newItem.Text = "Select";
            newItem.Value = "0";
            ForumTitleList.Items.Add(newItem);
            con.Open();
            reader = cmd.ExecuteReader();



            while (reader.Read())
            {
                ListItem newItem1 = new ListItem();
                newItem1.Text = reader["ForumTitles"].ToString();
                newItem1.Value = reader["ForumTitlesID"].ToString();
                ForumTitleList.Items.Add(newItem1);



            }
            reader.Close();
            reader.Dispose();
            con.Close();
            con.Dispose();
            cmd.Dispose();


        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }

    }
}

SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified

We got the same issue recently. We found out that the code is looking for the connection string named "LocalSqlServer" in the machine.confg file. We added this line and it is working fine.

Inserting values into a SQL Server database using ado.net via C#

private void button1_Click(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection();
    con.ConnectionString = "data source=CHANCHAL\SQLEXPRESS;initial catalog=AssetManager;user id=GIPL-PC\GIPL;password=";
    con.Open();
    SqlDataAdapter ad = new SqlDataAdapter("select * from detail1", con);
    SqlCommandBuilder cmdbl = new SqlCommandBuilder(ad);
    DataSet ds = new DataSet("detail1");
    ad.Fill(ds, "detail1");
    DataRow row = ds.Tables["detail1"].NewRow();
    row["Name"] = textBox1.Text;
    row["address"] =textBox2.Text;
    ds.Tables["detail1"].Rows.Add(row);
    ad.Update(ds, "detail1");
    con.Close();
    MessageBox.Show("insert secussfully"); 
}

How to solve privileges issues when restore PostgreSQL Database

Some of the answers have already provided various approaches related to getting rid of the create extension and comment on extensions. For me, the following command line seemed to work and be the simplest approach to solve the problem:

cat /tmp/backup.sql.gz | gunzip - | \
  grep -v -E '(CREATE\ EXTENSION|COMMENT\ ON)' |  \
    psql --set ON_ERROR_STOP=on -U db_user -h localhost my_db

Some notes

  • The first line is just uncompressing my backup and you may need to adjust accordingly.
  • The second line is using grep to get rid of offending lines.
  • the third line is my psql command; you may need to adjust as you normally would use psql for restore.

Fill Combobox from database

void Fillcombobox()
{

    con.Open();
    cmd = new SqlCommand("select ID From Employees",con);
    Sdr = cmd.ExecuteReader();
    while (Sdr.Read())
    {
        for (int i = 0; i < Sdr.FieldCount; i++)
        {
           comboID.Items.Add( Sdr.GetString(i));

        }
    }
    Sdr.Close();
    con.Close();

}

How to insert Records in Database using C# language?

Use a parameterized query to prevent Sql injections (secutity problem)

Use the using statement so the connection will be closed and resources will be disposed.

using(var connection = new SqlConnection("connectionString"))
{
    connection.Open();
    var sql = "INSERT INTO Main(FirstName, SecondName) VALUES(@FirstName, @SecondName)";
    using(var cmd = new SqlCommand(sql, connection))
    {
        cmd.Parameters.AddWithValue("@FirstName", txFirstName.Text);
        cmd.Parameters.AddWithValue("@SecondName", txSecondName.Text);

        cmd.ExecuteNonQuery();
    }
}

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". error

Had similar error with the same result with Gradle and was able to solve it by following:

//compile 'org.slf4j:slf4j-api:1.7.1'
compile group: 'org.apache.logging.log4j', name: 'log4j-api', version: '2.1'
compile group: 'org.apache.logging.log4j', name: 'log4j-core', version: '2.1'
compile group: 'org.apache.logging.log4j', name: 'log4j-slf4j-impl', version: '2.1'

Out-commented line is the one which caused the error output. I believe you can transfer this to Maven.

CREATE DATABASE permission denied in database 'master' (EF code-first)

I have resolved this problem in my way. Try connection string in this way:

<add name="MFCConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\MFC.mdf;Initial Catalog=MFC;Integrated Security=false;User ID=sa;Password=123"
  providerName="System.Data.SqlClient" />

remember to set default db from master to MFC (in your case, aspnet-test-2012615153521).

The type or namespace name does not exist in the namespace 'System.Web.Mvc'

I had the same problem, but in my case was originated by other factor. I write this to help other people with the same problem. I have a solutions with multiple projects. two of them work with the System.Web.Mvc, Normally our reference was pointing to external packages where we controlled the used version. For some reason one of the project reference goes to GAC and point to the GAC dll (version 4.0.0.1) and the program got the error. To correct it:

Simple check if the references to System.Web.Mvc point to the same dll in the same directory path.

I hope that help.

Error Message: Type or namespace definition, or end-of-file expected

You have extra brackets in Hours property;

public  object Hours { get; set; }}

error: the details of the application error from being viewed remotely

In my case I got this message because there's a special char (&) in my connectionstring, remove it then everything's good.

Cheers

Best way to compare dates in Android

You can use compareTo()

CompareTo method must return negative number if current object is less than other object, positive number if current object is greater than other object and zero if both objects are equal to each other.

// Get Current Date Time
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm aa");
String getCurrentDateTime = sdf.format(c.getTime());
String getMyTime="05/19/2016 09:45 PM ";
Log.d("getCurrentDateTime",getCurrentDateTime); 
// getCurrentDateTime: 05/23/2016 18:49 PM

if (getCurrentDateTime.compareTo(getMyTime) < 0)
{

}
else
{
 Log.d("Return","getMyTime older than getCurrentDateTime "); 
}

Troubleshooting "Warning: session_start(): Cannot send session cache limiter - headers already sent"

I had a website transferring from one host to another, it seemed to work fine on the old host but a few pages on the new host threw the error

Warning: session_start(): Cannot send session cache limiter - headers already sent
while I always kept the

 <?php
session_start(); 

at the top of the page no spaces and nothing inserted before

it really bugged me that I stared every page with the session opening, and it worked on some pages and run through a bug on others I picked the pages that had the problems, backed them up, created new blank pages and simply copied and pasted the code as is, saved and uploaded and boom, problem gone!

this is something you guys may need to consider, it may have been the encoding of the page, or something, not sure the exact source of the problem, but here is a fix to look at in case you guys run into a similar problem

cheers!

ExecuteNonQuery: Connection property has not been initialized.

double click on your form to create form_load event.Then inside that event write command.connection = "your connection name";

Get the Selected value from the Drop down box in PHP

You have to give a name attribute on your <select /> element, and then use it from the $_POST or $_GET (depending on how you transmit data) arrays in PHP. Be sure to sanitize user input, though.

HTTP 404 Page Not Found in Web Api hosted in IIS 7.5

i do nothing, just add this tag in web.config, its working this issue come up one of the following points

  1. Use Web Api in the same project using MVC or asp.net forms

  2. Use RouteConfig and WebApiConfig in Global.asax as GlobalConfiguration.Configure(WebApiConfig.Register); RouteConfig.RegisterRoutes(RouteTable.Routes);

  3. Use RouteConfig for 2 purposes, asp.net forms using with friendlyurl and mvc routing for MVC routing

we just use this tag in web.config, it will work.

<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
   .........................
</modules>
</system.webServer>

Byte array to image conversion

try (UPDATE)

MemoryStream ms = new MemoryStream(byteArrayIn,0,byteArrayIn.Length);
ms.Position = 0; // this is important
returnImage = Image.FromStream(ms,true);

Broadcast Receiver within a Service

The better pattern is to create a standalone BroadcastReceiver. This insures that your app can respond to the broadcast, whether or not the Service is running. In fact, using this pattern may remove the need for a constant-running Service altogether.

Register the BroadcastReceiver in your Manifest, and create a separate class/file for it.

Eg:

<receiver android:name=".FooReceiver" >
    <intent-filter >
        <action android:name="android.provider.Telephony.SMS_RECEIVED" />
    </intent-filter>
</receiver>

When the receiver runs, you simply pass an Intent (Bundle) to the Service, and respond to it in onStartCommand().

Eg:

public class FooReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        // do your work quickly!
        // then call context.startService();
    }   
}

How to fix error ::Format of the initialization string does not conform to specification starting at index 0::

In my Case, it is because of having more than one connection string in your Solution. one for your current project and the other one for a startup project in your Solution. for more information please refer to Telerik report not working

here we have the same situation.

How To Change DataType of a DataColumn in a DataTable?

You cannot change the DataType after the Datatable is filled with data. However, you can clone the Data table, change the column type and load data from previous data table to the cloned table as shown below.

DataTable dtCloned = dt.Clone();
dtCloned.Columns[0].DataType = typeof(Int32);
foreach (DataRow row in dt.Rows) 
{
    dtCloned.ImportRow(row);
}

Invalid column name sql error

Change this line:

cmd.CommandText = "INSERT INTO Data (Name,PhoneNo,Address) VALUES (" + txtName.Text + "," + txtPhone.Text + "," + txtAddress.Text + ");";

to this:

cmd.CommandText = "INSERT INTO Data (Name,PhoneNo,Address) VALUES ('" + txtName.Text + "','" + txtPhone.Text + "','" + txtAddress.Text + "');";

Your insert command is expecting text, and you need single quotes (') between the actual value so SQL can understand it as text.

EDIT: For those of you who aren't happy with this answer, I would like to point out that there is an issue with this code in regards to SQL Injection. When I answered this question I only considered the question in point which was the missing single-quote on his code and I pointed out how to fix it. A much better answer has been posted by Adam (and I voted for it), where he explains the issues with injection and shows a way to prevent. Now relax and be happy guys.

Java FileWriter how to write to next Line

You can call the method newLine() provided by java, to insert the new line in to a file.

For more refernce -http://download.oracle.com/javase/1.4.2/docs/api/java/io/BufferedWriter.html#newLine()

Strange Characters in database text: Ã, Ã, ¢, â‚ €,

This is surely an encoding problem. You have a different encoding in your database and in your website and this fact is the cause of the problem. Also if you ran that command you have to change the records that are already in your tables to convert those character in UTF-8.

Update: Based on your last comment, the core of the problem is that you have a database and a data source (the CSV file) which use different encoding. Hence you can convert your database in UTF-8 or, at least, when you get the data that are in the CSV, you have to convert them from UTF-8 to latin1.

You can do the convertion following this articles:

How to retrieve images from MySQL database and display in an html tag

Technically, you can too put image data in an img tag, using data URIs.

<img src="data:image/jpeg;base64,<?php echo base64_encode( $image_data ); ?>" />

There are some special circumstances where this could even be useful, although in most cases you're better off serving the image through a separate script like daiscog suggests.

The 'packages' element is not declared

You can also find a copy of the nuspec.xsd here as it seems to no longer be available:

https://gist.github.com/sharwell/6131243

Reading int values from SqlDataReader

based on Sam Holder's answer, you could make an extension method for that

namespace adonet.extensions
{
  public static class AdonetExt
  {
    public static int GetInt32(this SqlDataReader reader, string columnName)
    {
      return reader.GetInt32(reader.GetOrdinal(columnName));
    }
  }
}

and use it like this

using adonet.extensions;

//...

int farmsize = reader.GetInt32("farmsize");

assuming there is no GetInt32(string) already in SqlDataReader - if there is any, just use some other method name instead

Get connection string from App.config

string sTemp = System.Configuration.ConfigurationManager.ConnectionStrings["myDB In app.config"].ConnectionString;

Entity Framework Timeouts

For Entity framework 6 I use this annotation and works fine.

  public partial class MyDbContext : DbContext
  {
      private const int TimeoutDuration = 300;

      public MyDbContext ()
          : base("name=Model1")
      {
          this.Database.CommandTimeout = TimeoutDuration;
      }
       // Some other codes
    }

The CommandTimeout parameter is a nullable integer that set timeout values as seconds, if you set null or don't set it will use default value of provider you use.

How to install ADB driver for any android device?

If no other driver package worked for your obscure device go read how to make a truly universal abd and fastboot driver out of Google's USB driver. The trick is to use CompatibleID instead of HardwareID in the driver's INF Models section

ExecuteReader: Connection property has not been initialized

I like to place all my sql connections in using statements. I think they look cleaner, and they clean up after themselves when your done with them. I also recommend parameterizing every query, not only is it much safer but it is easier to maintain if you need to come back and make changes.

// create/open connection
using (SqlConnection conn = new SqlConnection("Data Source=Si-6\\SQLSERVER2005;Initial Catalog=rags;Integrated Security=SSPI")
{
    try
    {
        conn.Open();

        // initialize command
        using (SqlCommand cmd = conn.CreateCommand())
        {

            // generate query with parameters
            with cmd
            {
                .CommandType = CommandType.Text;
                .CommandText = "insert into time(project,iteration) values(@name, @iteration)";
                .Parameters.Add(new SqlParameter("@name", this.name1.SelectedValue));
                .Parameters.Add(new SqlParameter("@iteration", this.iteration.SelectedValue));
                .ExecuteNonQuery();
            }
        }
    }
    catch (Exception)
    {
        //throw;
    }
    finally
    {
        if (conn != null && conn.State == ConnectionState.Open)
        {
            conn.Close;
        }
    }
}

convert htaccess to nginx

Rewrite rules are pretty much written the same way with nginx: http://wiki.nginx.org/HttpRewriteModule#rewrite

Which rules are causing you trouble? I could help you translate those!

Web.Config Debug/Release

To make the transform work in development (using F5 or CTRL + F5) I drop ctt.exe (https://ctt.codeplex.com/) in the packages folder (packages\ConfigTransform\ctt.exe).

Then I register a pre- or post-build event in Visual Studio...

$(SolutionDir)packages\ConfigTransform\ctt.exe source:"$(ProjectDir)connectionStrings.config" transform:"$(ProjectDir)connectionStrings.$(ConfigurationName).config" destination:"$(ProjectDir)connectionStrings.config"
$(SolutionDir)packages\ConfigTransform\ctt.exe source:"$(ProjectDir)web.config" transform:"$(ProjectDir)web.$(ConfigurationName).config" destination:"$(ProjectDir)web.config"

For the transforms I use SlowCheeta VS extension (https://visualstudiogallery.msdn.microsoft.com/69023d00-a4f9-4a34-a6cd-7e854ba318b5).

Connection Strings for Entity Framework

Silverlight applications do not have direct access to machine.config.

java.sql.SQLException: No suitable driver found for jdbc:microsoft:sqlserver

I was having the same error, but had a proper connection string. My problem was that the driver was not being used, therefore was optimized out of the compiled war.

Be sure to import the driver:

import com.microsoft.sqlserver.jdbc.SQLServerDriver;

And then to force it to be included in the final war, you can do something like this:

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

That line is in the original question. This will also work:

SQLServerDriver driver = new SQLServerDriver();

rmagick gem install "Can't find Magick-config"

On Mac OS X sudo port install ImageMagick turned out to work fine to fix the gem install rmagick problem . I just didn't know that it worked fine because rvm during installation blew away my .bash_profile contents which included MacPort's addition of /opt/local/bin to PATH. I put back /opt/local/bin into PATH in my .bash_profile and then my gem install rmagick then succeeded.

Retrieving a random item from ArrayList

You must remove the system.out.println message from below the return, like this:

public Item anyItem()
{
    randomGenerator = new Random();
    int index = randomGenerator.nextInt(catalogue.size());
    Item it = catalogue.get(index);
    System.out.println("Managers choice this week" + it + "our recommendation to you");
    return it;
}

the return statement basically says the function will now end. anything included beyond the return statement that is also in scope of it will result in the behavior you experienced

XMLHttpRequest status 0 (responseText is empty)

I just had this issue because I used 0.0.0.0 as my server, changed it to localhost and it works.

Python error: AttributeError: 'module' object has no attribute

My solution is put those imports in __init__.py of lib:

in file: __init__.py
import mod1

Then,

import lib
lib.mod1

would work fine.

Cannot connect to local SQL Server with Management Studio

Check the sql log in the LOG directory of your instance - see if anything is going on there. You'll need to stop the service to open the log - or restart and you can read the old one - named with .1 on the end.

With the error you're getting, you need to enable TCP/IP or Named pipes for named connections. Shared memory connection should work, but you seem to not be using that. Are you trying to connect through SSMS?

In my log I see entries like this...

Server local connection provider is ready to accept connection on [\\.\pipe\mssql$sqlexpress\sql\query ]

As the comments said, .\SQLEXPRESS should work. Also worstationName\SQLEXPRESS will work.

Is there a way to retrieve the view definition from a SQL Server using plain ADO?

This example:Views Collection, CommandText Property Example (VB) Shows how to use ADOX to maintain VIEWS by changing COMMAND related to VIEW. But instead using it like this:

 Set cmd = cat.Views("AllCustomers").Command  

' Update the CommandText of the command.  
cmd.CommandText = _  
"Select CustomerId, CompanyName, ContactName From Customers"  

just try to use this way:

Set CommandText = cat.Views("AllCustomers").Command.CommandText

Force to open "Save As..." popup open at text link click for PDF in HTML

Add a response header Content-Disposition:attachment; followed by the file name. Remove the Meta Content-Disposition;Inline; which will open the document in the same window

In java it is set as

response.setHeader("Content-Disposition", "attachment;filename=test.jpg");

The model backing the <Database> context has changed since the database was created

Just in case someone has the same scenario as mine.

I have database first EF and at the same time using the asp.net identity

so I have two connectionStrings in my webconfig, and there is no problem with that. It happened that I created/run the scripts to generate manually the asp.net identity tables which I should not.

so DROP first all the asp.net identity tables created by you manually/from scripts.

DROP TABLE __MigrationHistory
DROP TABLE AspNetRoles
DROP TABLE AspNetUserClaims
DROP TABLE AspNetUserLogins
DROP TABLE AspNetUserRoles
DROP TABLE AspNetUsers

How to merge two PDF files into one in Java?

A quick Google search returned this bug: "Bad file descriptor while saving a document w. imported PDFs".

It looks like you need to keep the PDFs to be merged open, until after you have saved and closed the combined PDF.

When 1 px border is added to div, Div size increases, Don't want to do that

The border css property will increase all elements "outer" size, excepts tds in tables. You can get a visual idea of how this works in Firebug (discontinued), under the html->layout tab.

Just as an example, a div with a width and height of 10px and a border of 1px, will have an outer width and height of 12px.

For your case, to make it appear like the border is on the "inside" of the div, in your selected CSS class, you can reduce the width and height of the element by double your border size, or you can do the same for the elements padding.

Eg:

div.navitem
{
    width: 15px;
    height: 15px;
    /* padding: 5px; */
}

div.navitem .selected
{
    border: 1px solid;
    width: 13px;
    height: 13px;
    /* padding: 4px */
}

Why use pip over easy_install?

Another—as of yet unmentioned—reason for favoring pip is because it is the new hotness and will continue to be used in the future.

The infographic below—from the Current State of Packaging section in the The Hitchhiker's Guide to Packaging v1.0—shows that setuptools/easy_install will go away in the future.

enter image description here

Here's another infographic from distribute's documentation showing that Setuptools and easy_install will be replaced by the new hotness—distribute and pip. While pip is still the new hotness, Distribute merged with Setuptools in 2013 with the release of Setuptools v0.7.

enter image description here

How to define a connection string to a SQL Server 2008 database?

Standard Security
Data Source=serverName\instanceName;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;

Trusted Connection
Data Source=serverName\instanceName;Initial Catalog=myDataBase;Integrated Security=SSPI;

Here's a good reference on connection strings that I keep handy: ConnectionStrings.com

case-insensitive matching in xpath?

XPath 2 has a lower-case (and upper-case) string function. That's not quite the same as case-insensitive, but hopefully it will be close enough:

//CD[lower-case(@title)='empire burlesque']

If you are using XPath 1, there is a hack using translate.

How do I turn off PHP Notices?

Use phpinfo() and search for Configuration File (php.ini) Path to see which config file path for php is used. PHP can have multiple config files depending on environment it's running. Usually, for console it's:

/etc/php5/cli/php.ini

and for php run by apache it's:

/etc/php5/apache2/php.ini

And then set error_reporting the way you need it:

http://www.phpknowhow.com/configuration/php-ini-error-settings/ http://www.zootemplate.com/news-updates/how-to-disable-notice-and-warning-in-phpini-file

Login failed for user 'DOMAIN\MACHINENAME$'

I ran across this problem when a client renamed a SQL Server. The SQL Reporting Service was configured to connect to the old server name, which they had also created an alias for that redirected to the IP of the new server name.

All of their old IIS apps were working, redirecting to the new server name via the alias. On a hunch, I checked if they were running SSRS. Attempting to connect to the SSRS site Yielded the error:

"The service is not available.Contact your system administrator to resolve the issue. System administrators: The report server can’t connect to its database. Make sure the database is running and accessible. You can also check the report server trace log for details. "

It was running on the server, but failing to connect because it was using the alias for the old server name. Re-configuring SSRS to use the new server name instead of the old/alias fixed it.

How to get all table names from a database?

@Transactional
@RequestMapping(value = { "/getDatabaseTables" }, method = RequestMethod.GET)
public @ResponseBody String getDatabaseTables() throws Exception{ 

    Connection con = ((SessionImpl) sessionFactory.getCurrentSession()).connection();
    DatabaseMetaData md = con.getMetaData();
    ResultSet rs = md.getTables(null, null, "%", null);
    HashMap<String,List<String>> databaseTables = new HashMap<String,List<String>>();
    List<String> tables = new ArrayList<String>();
    String db = "";
    while (rs.next()) {
        tables.add(rs.getString(3));
        db = rs.getString(1);
    }
    List<String> database = new ArrayList<String>();
    database.add(db);
    databaseTables.put("database", database);
    Collections.reverse(tables);
    databaseTables.put("tables", tables);
    return new ObjectMapper().writeValueAsString(databaseTables);
}

@Transactional
@RequestMapping(value = { "/getTableDetails" }, method = RequestMethod.GET)
public @ResponseBody String getTableDetails(@RequestParam(value="tablename")String tablename) throws Exception{ 
    System.out.println("...tablename......"+tablename);
    Connection con = ((SessionImpl) sessionFactory.getCurrentSession()).connection();       
     Statement st = con.createStatement();
     String sql = "select * from "+tablename;
     ResultSet rs = st.executeQuery(sql);
     ResultSetMetaData metaData = rs.getMetaData();
     int rowCount = metaData.getColumnCount();    
     List<HashMap<String,String>> databaseColumns = new ArrayList<HashMap<String,String>>();
     HashMap<String,String> columnDetails = new HashMap<String,String>();
     for (int i = 0; i < rowCount; i++) {
         columnDetails = new HashMap<String,String>();
         Method method = com.mysql.jdbc.ResultSetMetaData.class.getDeclaredMethod("getField", int.class);
         method.setAccessible(true);
         com.mysql.jdbc.Field field = (com.mysql.jdbc.Field) method.invoke(metaData, i+1);
         columnDetails.put("columnName", field.getName());//metaData.getColumnName(i + 1));
         columnDetails.put("columnType", metaData.getColumnTypeName(i + 1));
         columnDetails.put("columnSize", field.getLength()+"");//metaData.getColumnDisplaySize(i + 1)+"");
         columnDetails.put("columnColl", field.getCollation());
         columnDetails.put("columnNull", ((metaData.isNullable(i + 1)==0)?"NO":"YES"));
         if (field.isPrimaryKey()) {
             columnDetails.put("columnKEY", "PRI");
         } else if(field.isMultipleKey()) {
             columnDetails.put("columnKEY", "MUL");
         } else if(field.isUniqueKey()) {
             columnDetails.put("columnKEY", "UNI");
         } else {
             columnDetails.put("columnKEY", "");
         }
         columnDetails.put("columnAINC", (field.isAutoIncrement()?"AUTO_INC":""));
         databaseColumns.add(columnDetails);
     }
    HashMap<String,List<HashMap<String,String>>> tableColumns = new HashMap<String,List<HashMap<String,String>>>();
    Collections.reverse(databaseColumns);
    tableColumns.put("columns", databaseColumns);
    return new ObjectMapper().writeValueAsString(tableColumns);
}

Getting an odd error, SQL Server query using `WITH` clause

;WITH 
    CteProductLookup(ProductId, oid) 
    AS 
...

Cannot open database "test" requested by the login. The login failed. Login failed for user 'xyz\ASPNET'

This Works for me.

  1. Go to SQL Server >> Security >> Logins and right click on NT AUTHORITY\NETWORK SERVICE and select Properties
  2. In newly opened screen of Login Properties, go to the “User Mapping” tab.
  3. Then, on the “User Mapping” tab, select the desired database – especially the database for which this error message is displayed.
  4. Click OK.

Read this blog.

http://blog.sqlauthority.com/2009/08/20/sql-server-fix-error-cannot-open-database-requested-by-the-login-the-login-failed-login-failed-for-user-nt-authoritynetwork-service/

MSSQL Error 'The underlying provider failed on Open'

I had the same problem but what worked for me was removing this from the Connection String:

persist security info=True

How to get a product's image in Magento?

You need set image type :small_image or image

echo $this->helper('catalog/image')->init($_product, 'small_image')->resize(163, 100);

MySQL: Invalid use of group function

You need to use HAVING, not WHERE.

The difference is: the WHERE clause filters which rows MySQL selects. Then MySQL groups the rows together and aggregates the numbers for your COUNT function.

HAVING is like WHERE, only it happens after the COUNT value has been computed, so it'll work as you expect. Rewrite your subquery as:

(                  -- where that pid is in the set:
SELECT c2.pid                  -- of pids
FROM Catalog AS c2             -- from catalog
WHERE c2.pid = c1.pid
HAVING COUNT(c2.sid) >= 2)

Login failed for user 'NT AUTHORITY\NETWORK SERVICE'

I was experiencing a similar error message that I noticed in the Windows Event Viewer that read:

Login failed for user 'NT AUTHORITY\NETWORK SERVICE'. Reason: Failed to open the explicitly specified database. [CLIENT: local machine]

The solution that resolved my problem was:

  1. Login to SqlExpress via SQL Server Management Studio
  2. Go to the "Security" directory of the database
  3. Right-click the Users directory
  4. Select "New User..."
  5. Add 'NT AUTHORITY\NETWORK SERVICE' as a new user
  6. In the Data Role Membership area, select db_owner
  7. Click OK

Here's a screenshot of the above: Screenshot of adding new user Network Service as db_owner to SqlExpress

Eclipse "this compilation unit is not on the build path of a java project"

Had the same problem. Solution: Context menu -> Maven -> Enable dependency management

Do not know why that was lost, when checking out.

List columns with indexes in PostgreSQL

How about a simple solution:

SELECT 
  t.relname table_name,
  ix.relname index_name,
  indisunique,
  indisprimary, 
  regexp_replace(pg_get_indexdef(indexrelid), '.*\((.*)\)', '\1') columns
FROM pg_index i
JOIN pg_class t ON t.oid = i.indrelid
JOIN pg_class ix ON ix.oid = i.indexrelid
WHERE t.relname LIKE 'test%'

`

What is the point of "Initial Catalog" in a SQL Server connection string?

Setting an Initial Catalog allows you to set the database that queries run on that connection will use by default. If you do not set this for a connection to a server in which multiple databases are present, in many cases you will be required to have a USE statement in every query in order to explicitly declare which database you are trying to run the query on. The Initial Catalog setting is a good way of explicitly declaring a default database.

Naming Classes - How to avoid calling everything a "<WhatEver>Manager"?

I asked a similar question, but where possible I try to copy the names already in the .NET framework, and I look for ideas in the Java and Android frameworks.

It seems Helper, Manager, and Util are the unavoidable nouns you attach for coordinating classes that contain no state and are generally procedural and static. An alternative is Coordinator.

You could get particularly purple prosey with the names and go for things like Minder, Overseer, Supervisor, Administrator, and Master, but as I said I prefer keeping it like the framework names you're used to.


Some other common suffixes (if that is the correct term) you also find in the .NET framework are:

  • Builder
  • Writer
  • Reader
  • Handler
  • Container

keyword not supported data source

What you have is a valid ADO.NET connection string - but it's NOT a valid Entity Framework connection string.

The EF connection string would look something like this:

<connectionStrings> 
  <add name="NorthwindEntities" connectionString=
     "metadata=.\Northwind.csdl|.\Northwind.ssdl|.\Northwind.msl;
      provider=System.Data.SqlClient;
      provider connection string=&quot;Data Source=SERVER\SQL2000;Initial Catalog=Northwind;Integrated Security=True;MultipleActiveResultSets=False&quot;" 
      providerName="System.Data.EntityClient" /> 
</connectionStrings>

You're missing all the metadata= and providerName= elements in your EF connection string...... you basically only have what's contained in the provider connection string part.

Using the EDMX designer should create a valid EF connection string for you, in your web.config or app.config.

Marc

UPDATE: OK, I understand what you're trying to do: you need a second "ADO.NET" connection string just for ASP.NET user / membership database. Your string is OK, but the providerName is wrong - it would have to be "System.Data.SqlClient" - this connection doesn't use ENtity Framework - don't specify the "EntityClient" for it then!

<add name="ASPNETMembership" 
     connectionString="Data Source=MONTGOMERY-DEV\SQLEXPRESS;Initial Catalog=ASPNETDB;Integrated Security=True;" 
     providerName="System.Data.SqlClient" />

If you specify providerName=System.Data.EntityClient ==> Entity Framework connection string (with the metadata= and everything).

If you need and specify providerName=System.Data.SqlClient ==> straight ADO.NET SQL Server connection string without all the EF additions

How can I get a list of all functions stored in the database of a particular schema in PostgreSQL?

Is a good idea named the functions with commun alias on the first words for filtre the name with LIKE Example with public schema in Postgresql 9.4, be sure to replace with his scheme

SELECT routine_name 
FROM information_schema.routines 
WHERE routine_type='FUNCTION' 
  AND specific_schema='public'
  AND routine_name LIKE 'aliasmyfunctions%';

The name 'ConfigurationManager' does not exist in the current context

Add the configuration manager file to connect to the database web.config

MetadataException when using Entity Framework Entity Connection

Found the problem.

The standard metadata string looks like this:

metadata=res://*/Model.csdl|res://*/Model.ssdl|res://*/Model.msl

And this works fine in most cases. However, in some (including mine) Entity Framework get confused and does not know which dll to look in. Therefore, change the metadata string to:

metadata=res://nameOfDll/Model.csdl|res://nameOfDll/Model.ssdl|res://nameOfDll/Model.msl

And it will work. It was this link that got me on the right track:

http://itstu.blogspot.com/2008/07/to-load-specified-metadata-resource.html

Although I had the oposite problem, did not work in unit test, but worked in service.

How to fix "The ConnectionString property has not been initialized"

Simply in Code Behind Page use:-

SqlConnection con = new SqlConnection("Data Source = DellPC; Initial Catalog = Account; user = sa; password = admin");

It Should Work Just Fine

Uncaught SoapFault exception: [HTTP] Error Fetching http headers

I am not about your PHP configuration but until PHP 5.2.6 , PHP does have some problem with SOAP client :

Bug #41983 - Error Fetching http headers

Bug #41983

Using varchar(MAX) vs TEXT on SQL Server

The VARCHAR(MAX) type is a replacement for TEXT. The basic difference is that a TEXT type will always store the data in a blob whereas the VARCHAR(MAX) type will attempt to store the data directly in the row unless it exceeds the 8k limitation and at that point it stores it in a blob.

Using the LIKE statement is identical between the two datatypes. The additional functionality VARCHAR(MAX) gives you is that it is also can be used with = and GROUP BY as any other VARCHAR column can be. However, if you do have a lot of data you will have a huge performance issue using these methods.

In regard to if you should use LIKE to search, or if you should use Full Text Indexing and CONTAINS. This question is the same regardless of VARCHAR(MAX) or TEXT.

If you are searching large amounts of text and performance is key then you should use a Full Text Index.

LIKE is simpler to implement and is often suitable for small amounts of data, but it has extremely poor performance with large data due to its inability to use an index.

Having a UITextField in a UITableViewCell

Here is how I have achieved this:

TextFormCell.h

#import <UIKit/UIKit.h>

#define CellTextFieldWidth 90.0
#define MarginBetweenControls 20.0

@interface TextFormCell : UITableViewCell {
 UITextField *textField;
}

@property (nonatomic, retain) UITextField *textField;

@end

TextFormCell.m

#import "TextFormCell.h"

@implementation TextFormCell

@synthesize textField;

- (id)initWithReuseIdentifier:(NSString *)reuseIdentifier {
    if (self = [super initWithReuseIdentifier:reuseIdentifier]) {
  // Adding the text field
  textField = [[UITextField alloc] initWithFrame:CGRectZero];
  textField.clearsOnBeginEditing = NO;
  textField.textAlignment = UITextAlignmentRight;
  textField.returnKeyType = UIReturnKeyDone;
  [self.contentView addSubview:textField];
    }
    return self;
}

- (void)dealloc {
 [textField release];
    [super dealloc];
}

#pragma mark -
#pragma mark Laying out subviews

- (void)layoutSubviews {
 CGRect rect = CGRectMake(self.contentView.bounds.size.width - 5.0, 
        12.0, 
        -CellTextFieldWidth, 
        25.0);
 [textField setFrame:rect];
 CGRect rect2 = CGRectMake(MarginBetweenControls,
       12.0,
         self.contentView.bounds.size.width - CellTextFieldWidth - MarginBetweenControls,
         25.0);
 UILabel *theTextLabel = (UILabel *)[self textLabel];
 [theTextLabel setFrame:rect2];
}

It may seems a bit verbose, but it works!

Don't forget to set the delegate!

Questions every good .NET developer should be able to answer?

A few more:

What are the limitations of garbage collection.

Know about finalizers and IDisposable.

Be aware of the thread pool and when to use it.

If you're doing GUI applications - be aware that Windows GUI is single threaded.

Use foreach (I see a lot of people doing MoveNext etc.)

Best practices to test protected methods with PHPUnit

If you're using PHP5 (>= 5.3.2) with PHPUnit, you can test your private and protected methods by using reflection to set them to be public prior to running your tests:

protected static function getMethod($name) {
  $class = new ReflectionClass('MyClass');
  $method = $class->getMethod($name);
  $method->setAccessible(true);
  return $method;
}

public function testFoo() {
  $foo = self::getMethod('foo');
  $obj = new MyClass();
  $foo->invokeArgs($obj, array(...));
  ...
}

How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?

All of these answers miss the point that doing an Ajax call with async:false will cause the browser to hang until the Ajax request completes. Using a flow control library will solve this problem without hanging up the browser. Here is an example with Frame.js:

beforecreate: function(node,targetNode,type,to) {

    Frame(function(next)){

        jQuery.get('http://example.com/catalog/create/', next);
    });

    Frame(function(next, response)){

        alert(response);
        next();
    });

    Frame.init();
}

Language Books/Tutorials for popular languages

I'd add Bruce Eckel's programming books:

In general, his "Books" page (http://mindview.net/Books/) is a good resource. The freely availabe books can also be found at http://www.ibiblio.org/pub/docs/books/eckel/

What does {0} mean when found in a string in C#?

It's a placeholder in the string.

For example,

string b = "world.";

Console.WriteLine("Hello {0}", b);

would produce this output:

Hello world.

Also, you can have as many placeholders as you wish. This also works on String.Format:

string b = "world.";
string a = String.Format("Hello {0}", b);

Console.WriteLine(a);

And you would still get the very same output.

How to replace text of a cell based on condition in excel

You can use the IF statement in a new cell to replace text, such as:

=IF(A4="C", "Other", A4)

This will check and see if cell value A4 is "C", and if it is, it replaces it with the text "Other"; otherwise, it uses the contents of cell A4.

EDIT

Assuming that the Employee_Count values are in B1-B10, you can use this:

=IF(B1=LARGE($B$1:$B$10, 10), "Other", B1)

This function doesn't even require the data to be sorted; the LARGE function will find the 10th largest number in the series, and then the rest of the formula will compare against that.

git push rejected: error: failed to push some refs

git push -f if you have permission, but that will screw up anyone else who pulls from that repo, so be careful.

If that is denied, and you have access to the server, as canzar says below, you can allow this on the server with

git config receive.denyNonFastForwards false

What to use now Google News API is deprecated?

Depending on your needs, you want to use their section feeds, their search feeds

http://news.google.com/news?q=apple&output=rss

or Bing News Search.

http://www.bing.com/toolbox/bingdeveloper/

Numpy - add row to array

I use numpy.insert(arr, i, the_object_to_be_added, axis) in order to insert object_to_be_added at the i'th row(axis=0) or column(axis=1)

import numpy as np

a = np.array([[1, 2, 3], [5, 4, 6]])
# array([[1, 2, 3],
#        [5, 4, 6]])

np.insert(a, 1, [55, 66], axis=1)
# array([[ 1, 55,  2,  3],
#        [ 5, 66,  4,  6]])

np.insert(a, 2, [50, 60, 70], axis=0)
# array([[ 1,  2,  3],
#        [ 5,  4,  6],
#        [50, 60, 70]])

Too old discussion, but I hope it helps someone.

Validate Dynamically Added Input fields

$('#form-btn').click(function () {
//set global rules & messages array to use in validator
   var rules = {};
   var messages = {};
//get input, select, textarea of form
   $('#formId').find('input, select, textarea').each(function () {
      var name = $(this).attr('name');
      rules[name] = {};
      messages[name] = {};

      rules[name] = {required: true}; // set required true against every name
//apply more rules, you can also apply custom rules & messages
      if (name === "email") {
         rules[name].email = true;
         //messages[name].email = "Please provide valid email";
      }
      else if(name==='url'){
        rules[name].required = false; // url filed is not required
//add other rules & messages
      }
   });
//submit form and use above created global rules & messages array
   $('#formId').submit(function (e) {
            e.preventDefault();
        }).validate({
            rules: rules,
            messages: messages,
            submitHandler: function (form) {
            console.log("validation success");
            }
        });
});

How to check if user input is not an int value

This is to keep requesting inputs while this input is integer and find whether it is odd or even else it will end.

int counter = 1;
    System.out.println("Enter a number:");
    Scanner OddInput = new Scanner(System.in);
        while(OddInput.hasNextInt()){
            int Num = OddInput.nextInt();
            if (Num %2==0){
                System.out.println("Number " + Num + " is Even");
                System.out.println("Enter a number:");
            }
            else {
                System.out.println("Number " + Num + " is Odd");
                System.out.println("Enter a number:");
                }
            }
        System.out.println("Program Ended");
    }

Index all *except* one item in python

Note that if variable is list of lists, some approaches would fail. For example:

v1 = [[range(3)] for x in range(4)]
v2 = v1[:3]+v1[4:] # this fails
v2

For the general case, use

removed_index = 1
v1 = [[range(3)] for x in range(4)]
v2 = [x for i,x in enumerate(v1) if x!=removed_index]
v2

Can Flask have optional URL parameters?

I think you can use Blueprint and that's will make ur code look better and neatly.

example:

from flask import Blueprint

bp = Blueprint(__name__, "example")

@bp.route("/example", methods=["POST"])
def example(self):
   print("example")

Should I use alias or alias_method?

A year after asking the question comes a new article on the subject:

http://erniemiller.org/2014/10/23/in-defense-of-alias/

It seems that "so many men, so many minds." From the former article author encourages to use alias_method, while the latter suggests using alias.

However there's a common overview of these methods in both blogposts and answers above:

  • use alias when you want to limit aliasing to the scope where it's defined
  • use alias_method to allow inherited classes to access it

Is there an easy way to reload css without reloading the page?

Possibly not applicable for your situation, but here's the jQuery function I use for reloading external stylesheets:

/**
 * Forces a reload of all stylesheets by appending a unique query string
 * to each stylesheet URL.
 */
function reloadStylesheets() {
    var queryString = '?reload=' + new Date().getTime();
    $('link[rel="stylesheet"]').each(function () {
        this.href = this.href.replace(/\?.*|$/, queryString);
    });
}

Maximum packet size for a TCP connection

The absolute limitation on TCP packet size is 64K (65535 bytes), but in practicality this is far larger than the size of any packet you will see, because the lower layers (e.g. ethernet) have lower packet sizes.

The MTU (Maximum Transmission Unit) for Ethernet, for instance, is 1500 bytes. Some types of networks (like Token Ring) have larger MTUs, and some types have smaller MTUs, but the values are fixed for each physical technology.

Disabled form inputs do not appear in the request

To post values from disabled inputs in addition to enabled inputs, you can simply re-enable all of the form's inputs as it is being submitted.

<form onsubmit="this.querySelectorAll('input').forEach(i => i.disabled = false)">
    <!-- Re-enable all input elements on submit so they are all posted, 
         even if currently disabled. -->

    <!-- form content with input elements -->
</form>

If you prefer jQuery:

<form onsubmit="$(this).find('input').prop('disabled', false)">
    <!-- Re-enable all input elements on submit so they are all posted, 
         even if currently disabled. -->

    <!-- form content with input elements -->
</form>

For ASP.NET MVC C# Razor, you add the submit handler like this:

using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post,
    // Re-enable all input elements on submit so they are all posted, even if currently disabled.
    new { onsubmit = "this.querySelectorAll('input').forEach(i => i.disabled = false)" } ))
{
    <!-- form content with input elements -->
}

How to execute a file within the python interpreter?

Just do,

from my_file import *

Make sure not to add .py extension. If your .py file in subdirectory use,

from my_dir.my_file import *

Trouble Connecting to sql server Login failed. "The login is from an untrusted domain and cannot be used with Windows authentication"

Following was working for me. hope this helps you

<add name="getconn" connectionString="Data Source=servername;Initial Catalog=DBName;Persist Security Info=True;User ID=sa;Password=***" />

maxReceivedMessageSize and maxBufferSize in app.config

If you are using a custom binding, you can set the values like this:

<customBinding>
    <binding name="x">
        <httpsTransport maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" />
    </binding>
</customBinding>

How to generate a Makefile with source in sub-directories using just one makefile

This will do it without painful manipulation or multiple command sequences:

build/%.o: src/%.cpp
src/%.o: src/%.cpp
%.o:
    $(CC) -c $< -o $@

build/test.exe: build/widgets/apple.o build/widgets/knob.o build/tests/blend.o src/ui/flash.o
    $(LD) $^ -o $@

JasperE has explained why "%.o: %.cpp" won't work; this version has one pattern rule (%.o:) with commands and no prereqs, and two pattern rules (build/%.o: and src/%.o:) with prereqs and no commands. (Note that I put in the src/%.o rule to deal with src/ui/flash.o, assuming that wasn't a typo for build/ui/flash.o, so if you don't need it you can leave it out.)

build/test.exe needs build/widgets/apple.o,
build/widgets/apple.o looks like build/%.o, so it needs src/%.cpp (in this case src/widgets/apple.cpp),
build/widgets/apple.o also looks like %.o, so it executes the CC command and uses the prereqs it just found (namely src/widgets/apple.cpp) to build the target (build/widgets/apple.o)

How to calculate the running time of my program?

At the beginning of your main method, add this line of code :

final long startTime = System.nanoTime();

And then, at the last line of your main method, you can add :

final long duration = System.nanoTime() - startTime;

duration now contains the time in nanoseconds that your program ran. You can for example print this value like this:

System.out.println(duration);

If you want to show duration time in seconds, you must divide the value by 1'000'000'000. Or if you want a Date object: Date myTime = new Date(duration / 1000); You can then access the various methods of Date to print number of minutes, hours, etc.

My Application Could not open ServletContext resource

If you are getting this error with a Java configuration, it is usually because you forget to pass in the application context to the DispatcherServlet constructor:

AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(WebConfig.class);

ServletRegistration.Dynamic dispatcher = sc.addServlet("dispatcher", 
    new DispatcherServlet()); // <-- no constructor args!
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/*");

Fix it by adding the context as the constructor arg:

AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(WebConfig.class);

ServletRegistration.Dynamic dispatcher = sc.addServlet("dispatcher", 
    new DispatcherServlet(ctx)); // <-- hooray! Spring doesn't look for XML files!
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/*");

ImportError: No module named MySQLdb

If you're having issues compiling the binary extension, or on a platform where you cant, you can try using the pure python PyMySQL bindings.

Simply pip install pymysql and switch your SQLAlchemy URI to start like this:

SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://.....'

There are some other drivers you could also try.

C++ obtaining milliseconds time on Linux -- clock() doesn't seem to work properly

I like the Hola Soy method of not using gettimeofday(). It happened to me on a running server the admin changed the timezone. The clock was updated to show the same (correct) local value. This caused the function time() and gettimeofday() to shift 2 hours and all timestamps in some services got stuck.

jQuery deferreds and promises - .then() vs .done()

There is a very simple mental mapping in response that was a bit hard to find in the other answers:

Check if an apt-get package is installed and then install it if it's not on Linux

dpkg-query --showformat='${db:Status-Status}'

This produces a small output string which is unlikely to change and is easy to compare deterministically without grep:

pkg=hello
status="$(dpkg-query -W --showformat='${db:Status-Status}' "$pkg" 2>&1)"
if [ ! $? = 0 ] || [ ! "$status" = installed ]; then
  sudo apt install $pkg
fi

The $? = 0 check is needed because if you've never installed a package before, and after you remove certain packages such as hello, dpkg-query exits with status 1 and outputs to stderr:

dpkg-query: no packages found matching hello

instead of outputting not-installed. The 2>&1 captures that error message too when it comes preventing it from going to the terminal.

For multiple packages:

pkgs='hello certbot'
install=false
for pkg in $pkgs; do
  status="$(dpkg-query -W --showformat='${db:Status-Status}' "$pkg" 2>&1)"
  if [ ! $? = 0 ] || [ ! "$status" = installed ]; then
    install=true
    break
  fi
done
if "$install"; then
  sudo apt install $pkgs
fi

The possible statuses are documented in man dpkg-query as:

   n = Not-installed
   c = Config-files
   H = Half-installed
   U = Unpacked
   F = Half-configured
   W = Triggers-awaiting
   t = Triggers-pending
   i = Installed

The single letter versions are obtainable with db:Status-Abbrev, but they come together with the action and error status, so you get 3 characters and would need to cut it.

So I think it is reliable enough to rely on the uncapitalized statuses (Config-files vs config-files) not changing instead.

dpkg -s exit status

This unfortunately doesn't do what most users want:

pkgs='qemu-user pandoc'
if ! dpkg -s $pkgs >/dev/null 2>&1; then
  sudo apt-get install $pkgs
fi

because for some packages, e.g. certbot, doing:

sudo apt install certbot
sudo apt remove certbot

leaves certbot in state config-files, which means that config files were left in the machine. And in that state, dpkg -s still returns 0, because the package metadata is still kept around so that those config files can be handled more nicely.

To actually make dpkg -s return 1 as desired, --purge would be needed:

sudo apt remove --purge certbot

which actually moves it into not-installed/dpkg-query: no packages found matching.

Note that only certain packages leave config files behind. A simpler package like hello goes directly from installed to not-installed without --purge.

Tested on Ubuntu 20.10.

Python apt package

There is a pre-installed Python 3 package called apt in Ubuntu 18.04 which exposes an Python apt interface!

A script that checks if a package is installed and installs it if not can be seen at: How to install a package using the python-apt API

Here is a copy for reference:

#!/usr/bin/env python
# aptinstall.py

import apt
import sys

pkg_name = "libjs-yui-doc"

cache = apt.cache.Cache()
cache.update()
cache.open()

pkg = cache[pkg_name]
if pkg.is_installed:
    print "{pkg_name} already installed".format(pkg_name=pkg_name)
else:
    pkg.mark_install()

    try:
        cache.commit()
    except Exception, arg:
        print >> sys.stderr, "Sorry, package installation failed [{err}]".format(err=str(arg))

Check if an executable is in PATH instead

See: How can I check if a program exists from a Bash script?

See also

Fill remaining vertical space - only CSS

If you can add an extra couple of divs so your html looks like this:

<div id="wrapper">
    <div id="first" class="row">
        <div class="cell"></div>
    </div>
    <div id="second" class="row">
        <div class="cell"></div>
    </div>
</div>

You can make use of the display:table properties:

#wrapper
{
   width:300px;
   height:100%;
   display:table;
}

.row 
{
   display:table-row;
}

.cell 
{
   display:table-cell;
}

#first .cell
{
   height:200px;
   background-color:#F5DEB3;
}

#second .cell
{
   background-color:#9ACD32;
}

Example

JSON character encoding

If you're using StringEntity try this, using your choice of character encoding. It handles foreign characters as well.

ssl_error_rx_record_too_long and Apache SSL

The link mentioned by Subimage was right on the money for me. It suggested changing the virtual host tag, ie, from <VirtualHost myserver.example.com:443> to <VirtualHost _default_:443>

Error code: ssl_error_rx_record_too_long

This usually means the implementation of SSL on your server is not correct. The error is usually caused by a server side problem which the server administrator will need to investigate.

Below are some things we recommend trying.

  • Ensure that port 443 is open and enabled on your server. This is the standard port for https communications.

  • If SSL is using a non-standard port then FireFox 3 can sometimes give this error. Ensure SSL is running on port 443.

  • If using Apache2 check that you are using port 443 for SSL. This can be done by setting the ports.conf file as follows

    Listen 80
    Listen 443 https
    
  • Make sure you do not have more than one SSL certificate sharing the same IP. Please ensure that all SSL certificates utilise their own dedicated IP.

  • If using Apache2 check your vhost config. Some users have reported changing <VirtualHost> to _default_ resolved the error.

That fixed my problem. It's rare that I google an error message and get the first hit with the right answer! :-)

In addition to the above, these are some other solutions that other folks have found were causing the issue:

  • Make sure that your SSL certificate is not expired

  • Try to specify the Cipher:

    SSLCipherSuite ALL:!aNULL:!ADH:!eNULL:!LOW:!EXP:RC4+RSA:+HIGH:+MEDIUM:+SSLv3

laravel foreach loop in controller

Actually your $product has no data because the Eloquent model returns NULL. It's probably because you have used whereOwnerAndStatus which seems wrong and if there were data in $product then it would not work in your first example because get() returns a collection of multiple models but that is not the case. The second example throws error because foreach didn't get any data. So I think it should be something like this:

$owner = Input::get('owner');
$count = Input::get('count');
$products = Product::whereOwner($owner, 0)->take($count)->get();

Further you may also make sure if $products has data:

if($product) {
    return View:make('viewname')->with('products', $products);
}

Then in the view:

foreach ($products as $product) {
    // If Product has sku (collection object, probably related models)
    foreach ($product->sku as $sku) {
        // Code Here        
    }
}

How can I get a Dialog style activity window to fill the screen?

For Dialog This may helpful for someone. I want a dialog to take full width of screen. searched a lot but nothing found useful. Finally this worked for me:

mDialog.setContentView(R.layout.my_custom_dialog);
mDialog.getWindow().setBackgroundDrawable(null);

after adding this, my dialog appears in full width of screen.

Adding placeholder text to textbox

This is not my code, but I use it a lot and it works perfect... XAML ONLY

<TextBox x:Name="Textbox" Height="23" Margin="0,17,18.8,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" HorizontalAlignment="Right" ></TextBox>

<TextBlock x:Name="Placeholder" IsHitTestVisible="False" TextWrapping="Wrap" Text="Placeholder Text" VerticalAlignment="Top" Margin="0,20,298.8,0" Foreground="DarkGray" HorizontalAlignment="Right" Width="214">
  <TextBlock.Style>
    <Style TargetType="{x:Type TextBlock}">
      <Setter Property="Visibility" Value="Collapsed"/>
      <Style.Triggers>
        <DataTrigger Binding="{Binding Text, ElementName=Textbox}" Value="">
          <Setter Property="Visibility" Value="Visible"/>
        </DataTrigger>
      </Style.Triggers>
    </Style>
  </TextBlock.Style>
</TextBlock>

Python JSON serialize a Decimal object

For Django users:

Recently came across TypeError: Decimal('2337.00') is not JSON serializable while JSON encoding i.e. json.dumps(data)

Solution:

# converts Decimal, Datetime, UUIDs to str for Encoding
from django.core.serializers.json import DjangoJSONEncoder  

json.dumps(response.data, cls=DjangoJSONEncoder)

But, now the Decimal value will be a string, now we can explicitly set the decimal/float value parser when decoding data, using parse_float option in json.loads:

import decimal 

data = json.loads(data, parse_float=decimal.Decimal) # default is float(num_str)

How do you get assembler output from C/C++ source in gcc?

Use "-S" as an option. It displays the assembly output in the terminal.

jQuery selector first td of each row

try

var children = null;
$('tr').each(function(){
    var td = $(this).children('td:first');
    if(children == null)
        children = td;
    else
        children.add(td);
});

// children should now hold all the first td elements

How do you open an SDF file (SQL Server Compact Edition)?

Download and install LINQPad, it works for SQL Server, MySQL, SQLite and also SDF (SQL CE 4.0).

Steps for open SDF Files:

  1. Click Add Connection

  2. Select Build data context automatically and Default (LINQ to SQL), then Next.

  3. Under Provider choose SQL CE 4.0.

  4. Under Database with Attach database file selected, choose Browse to select your .sdf file.

  5. Click OK.

How to get unique values in an array

I have tried this problem in pure JS. I have followed following steps 1. Sort the given array, 2. loop through the sorted array, 3. Verify previous value and next value with current value

// JS
var inpArr = [1, 5, 5, 4, 3, 3, 2, 2, 2,2, 100, 100, -1];

//sort the given array
inpArr.sort(function(a, b){
    return a-b;
});

var finalArr = [];
//loop through the inpArr
for(var i=0; i<inpArr.length; i++){
    //check previous and next value 
  if(inpArr[i-1]!=inpArr[i] && inpArr[i] != inpArr[i+1]){
        finalArr.push(inpArr[i]);
  }
}
console.log(finalArr);

Demo

Remove Identity from a column in a table

I just had this same problem. 4 statements in SSMS instead of using the GUI and it was very fast.

  • Make a new column

    alter table users add newusernum int;

  • Copy values over

    update users set newusernum=usernum;

  • Drop the old column

    alter table users drop column usernum;

  • Rename the new column to the old column name

    EXEC sp_RENAME 'users.newusernum' , 'usernum', 'COLUMN';

How to check if variable is array?... or something array-like

PHP 7.1.0 has introduced the iterable pseudo-type and the is_iterable() function, which is specially designed for such a purpose:

This […] proposes a new iterable pseudo-type. This type is analogous to callable, accepting multiple types instead of one single type.

iterable accepts any array or object implementing Traversable. Both of these types are iterable using foreach and can be used with yield from within a generator.

function foo(iterable $iterable) {
    foreach ($iterable as $value) {
        // ...
    }
}

This […] also adds a function is_iterable() that returns a boolean: true if a value is iterable and will be accepted by the iterable pseudo-type, false for other values.

var_dump(is_iterable([1, 2, 3])); // bool(true)
var_dump(is_iterable(new ArrayIterator([1, 2, 3]))); // bool(true)
var_dump(is_iterable((function () { yield 1; })())); // bool(true)
var_dump(is_iterable(1)); // bool(false)
var_dump(is_iterable(new stdClass())); // bool(false)

You can also use the function is_array($var) to check if the passed variable is an array:

<?php
    var_dump( is_array(array()) ); // true
    var_dump( is_array(array(1, 2, 3)) ); // true
    var_dump( is_array($_SERVER) ); // true
?>

Read more in How to check if a variable is an array in PHP?

Convert list to dictionary using linq and not worrying about duplicates

In case we want all the Person (instead of only one Person) in the returning dictionary, we could:

var _people = personList
.GroupBy(p => p.FirstandLastName)
.ToDictionary(g => g.Key, g => g.Select(x=>x));

When to create variables (memory management)

It's really a matter of opinion. In your example, System.out.println(5) would be slightly more efficient, as you only refer to the number once and never change it. As was said in a comment, int is a primitive type and not a reference - thus it doesn't take up much space. However, you might want to set actual reference variables to null only if they are used in a very complicated method. All local reference variables are garbage collected when the method they are declared in returns.

What does 'Unsupported major.minor version 52.0' mean, and how do I fix it?

Your code was compiled with Java 8.

Either compile your code with an older JDK (compliance level) or run it on a Java 8 JRE.

Hope this helps...

How to sum a variable by group

Another solution that returns sums by groups in a matrix or a data frame and is short and fast:

rowsum(x$Frequency, x$Category)

Best way to store passwords in MYSQL database

You should use one way encryption (which is a way to encrypt a value so that is very hard to revers it). I'm not familiar with MySQL, but a quick search shows that it has a password() function that does exactly this kind of encryption. In the DB you will store the encrypted value and when the user wants to authenticate you take the password he provided, you encrypt it using the same algorithm/function and then you check that the value is the same with the password stored in the database for that user. This assumes that the communication between the browser and your server is secure, namely that you use https.

Read a javascript cookie by name

The point of Stack Overflow is to provide a database of good quality answers, so I am going to reference some standard source code and an article that gives examples:

http://www.codelib.net/javascript/cookies.html

Note: The code is regular-expression free for greatly enhanced efficiency.

Using the source code provided, you would use cookies like this:

makeCookie('color', 'silver');

This saves a cookie indicating that the color is silver. The cookie would expire after the current session (as soon as the user quits the browser).

makeCookie('color', 'green', { domain: 'gardens.home.com' });

This saves the color green for gardens.home.com.

makeCookie('color', 'white', { domain: '.home.com', path: '/invoices' });
makeCookie('invoiceno', '0259876', { path: '/invoices', secure: true });

saves the color white for invoices viewed anywhere at home.com. The second cookie is a secure cookie, and records an invoice number. This cookie will be sent only to pages that are viewed through secure HTTPS connections, and scripts within secure pages are the only scripts allowed to access the cookie.

One HTTP host is not allowed to store or read cookies for another HTTP host. Thus, a cookie domain must be stored with at least two periods. By default, the domain is the same as the domain of the web address which created the cookie.

The path of an HTTP cookie restricts it to certain files on the HTTP host. Some browsers use a default path of /, so the cookie will be available on the whole host. Other browsers use the whole filename. In this case, if /invoices/overdue.cgi creates a cookie, only /invoices/overdue.cgi is going to get the cookie back.

When setting paths and other parameters, they are usually based on data obtained from variables like location.href, etc. These strings are already escaped, so when the cookie is created, the cookie function does not escape these values again. Only the name and value of the cookie are escaped, so we can conveniently use arbitrary names or values. Some browsers limit the total size of a cookie, or the total number of cookies which one domain is allowed to keep.

makeCookie('rememberemail', 'yes', { expires: 7 });
makeCookie('rememberlogin', 'yes', { expires: 1 });
makeCookie('allowentergrades', 'yes', { expires: 1/24 });

these cookies would remember the user's email for 7 days, the user's login for 1 day, and allow the user to enter grades without a password for 1 hour (a twenty-fourth of a day). These time limits are obeyed even if they quit the browser, and even if they don't quit the browser. Users are free to use a different browser program, or to delete cookies. If they do this, the cookies will have no effect, regardless of the expiration date.

makeCookie('rememberlogin', 'yes', { expires: -1 });

deletes the cookie. The cookie value is superfluous, and the return value false means that deletion was successful. (A expiration of -1 is used instead of 0. If we had used 0, the cookie might be undeleted until one second past the current time. In this case we would think that deletion was unsuccessful.)

Obviously, since a cookie can be deleted in this way, a new cookie will also overwrite any value of an old cookie which has the same name, including the expiration date, etc. However, cookies for completely non-overlapping paths or domains are stored separately, and the same names do not interfere with each other. But in general, any path or domain which has access to a cookie can overwrite the cookie, no matter whether or not it changes the path or domain of the new cookie.

rmCookie('rememberlogin');

also deletes the cookie, by doing makeCookie('rememberlogin', '', { expires: -1 }). This makes the cookie code longer, but saves code for people who use it, which one might think saves more code in the long run.

How to solve ADB device unauthorized in Android ADB host device?

If anyone has similar issue of having a phone with a cracked screen and has a need to access adb:

  1. Root your phone (mine was already rooted, so I was blessed at least with that).

If you forgot to enable developers mode and your adb isn't running, then do the following:

  1. Reboot your phone into recovery.
  2. Connect the phone with a cable.
  3. Open terminal.
  4. If you type adb devices you should see the device in the list.
  5. If so, type:

    adb shell mount /system
    abd shell
    
    echo "persist.service.adb.enable=1" >> default.prop 
    echo "persist.service.debuggable=1" >> default.prop
    echo "persist.sys.usb.config=mtp,adb" >> default.prop
    echo "persist.service.adb.enable=1" >> /system/build.prop 
    echo "persist.service.debuggable=1" >> /system/build.prop
    echo "persist.sys.usb.config=mtp,adb" >> /system/build.prop
    

Now if you are going to reboot into your phone android will tell you "oh your adb is working but please tap on this OK button, so we can trust your PC". And obviously if we can't tap on the phone stay in the recovery mode and do the following (assuming you are not in the adb shell mode, if so first type exit):

cd ~/.android
adb push adbkey.pub /data/misc/adb/adb_keys
  1. Hurray, it all should be hunky-dory now! Just reboot the phone and you should be able to access adb when the phone is running:

    adb shell reboot

P.S. Was using OS X and Moto X Style that's with the cracked screen.

Python: Generate random number between x and y which is a multiple of 5

Create an integer random between e.g. 1-11 and multiply it by 5. Simple math.

import random
for x in range(20):
  print random.randint(1,11)*5,
print

produces e.g.

5 40 50 55 5 15 40 45 15 20 25 40 15 50 25 40 20 15 50 10

How to set MouseOver event/trigger for border in XAML?

Yes, this is confusing...

According to this blog post, it looks like this is an omission from WPF.

To make it work you need to use a style:

    <Border Name="ClearButtonBorder" Grid.Column="1" CornerRadius="0,3,3,0">
        <Border.Style>
            <Style>
                <Setter Property="Border.Background" Value="Blue"/>
                <Style.Triggers>
                    <Trigger Property="Border.IsMouseOver" Value="True">
                        <Setter Property="Border.Background" Value="Green" />
                    </Trigger>
                </Style.Triggers>
            </Style>
        </Border.Style>
        <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="X" />
    </Border>

I guess this problem isn't that common as most people tend to factor out this sort of thing into a style, so it can be used on multiple controls.

How to get current screen width in CSS?

Based on your requirement i think you are wanted to put dynamic fields in CSS file, however that is not possible as CSS is a static language. However you can simulate the behaviour by using Angular.

Please refer to the below example. I'm here showing only one component.

login.component.html

import { Component, OnInit } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

    @Component({
      selector: 'app-login',
      templateUrl: './login.component.html',
      styleUrls: ['./login.component.css']
    })
    export class LoginComponent implements OnInit {

      cssProperty:any;
      constructor(private sanitizer: DomSanitizer) { 
        console.log(window.innerWidth);
        console.log(window.innerHeight);
        this.cssProperty = 'position:fixed;top:' + Math.floor(window.innerHeight/3.5) + 'px;left:' + Math.floor(window.innerWidth/3) + 'px;';
        this.cssProperty = this.sanitizer.bypassSecurityTrustStyle(this.cssProperty);
      }

    ngOnInit() {

      }

    }

login.component.ts

<div class="home">
    <div class="container" [style]="cssProperty">
        <div class="card">
            <div class="card-header">Login</div>
            <div class="card-body">Please login</div>
            <div class="card-footer">Login</div>
        </div>
    </div>
</div>

login.component.css

.card {
    max-width: 400px;
}
.card .card-body {
    min-height: 150px;
}
.home {
    background-color: rgba(171, 172, 173, 0.575);
}

I keep getting this error for my simple python program: "TypeError: 'float' object cannot be interpreted as an integer"

In:

for i in range(c/10):

You're creating a float as a result - to fix this use the int division operator:

for i in range(c // 10):

Boto3 Error: botocore.exceptions.NoCredentialsError: Unable to locate credentials

If you have multiple aws profiles in ~/.aws/credentials like...

[Profile 1]
aws_access_key_id = *******************
aws_secret_access_key = ******************************************
[Profile 2]
aws_access_key_id = *******************
aws_secret_access_key = ******************************************

Follow two steps:

  1. Make one you want to use as a default using export AWS_DEFAULT_PROFILE=Profile 1 command in terminal.

  2. Make sure to run above command in the same terminal from where you use boto3 or you open an editor.[Understand the following scenario]

Scenario:

  • If you have two terminal open called t1 and t2.
  • And you run the export command in t1 and you open JupyterLab or any other from t2, you will get NoCredentialsError: Unable to locate credentials error.

Solution:

  • Run the export command in t1 and then open JupyterLab or any other from the same terminal t1.

Could not find or load main class with a Jar File

If you use package names, it won't work with folders containing dots (Error: Could not find or load main class). Even though it compiles and creates the jar file successfully.

Instead it requires a complete folder hierarchy.

Fails:

com.example.mypackage/
    Main.java

Works:

com/
    example/
        mypackage/
            Main.java

To compile in Linux:

javac `find com/ -name '*.java'` \ && jar cfe app.jar com.example.mypackage.Main `find com/ -name '*.class'`

Javascript decoding html entities

There is a jQuery solution in this thread. Try something like this:

var decoded = $("<div/>").html('your string').text();

This sets the innerHTML of a new <div> element (not appended to the page), causing jQuery to decode it into HTML, which is then pulled back out with .text().

break statement in "if else" - java

Because your else isn't attached to anything. The if without braces only encompasses the single statement that immediately follows it.

if (choice==5)
{
    System.out.println("End of Game\n Thank you for playing with us!");
    break;
}
else
{
   System.out.println("Not a valid choice!\n Please try again...\n");
}

Not using braces is generally viewed as a bad practice because it can lead to the exact problems you encountered.

In addition, using a switch here would make more sense.

int choice;
boolean keepGoing = true;
while(keepGoing)
{
    System.out.println("---> Your choice: ");
    choice = input.nextInt();
    switch(choice)
    {
        case 1: 
            playGame();
            break;
        case 2: 
            loadGame();
            break;
        // your other cases
        // ...
        case 5: 
            System.out.println("End of Game\n Thank you for playing with us!");
            keepGoing = false;
            break;
        default:
            System.out.println("Not a valid choice!\n Please try again...\n");
     }
 }         

Note that instead of an infinite for loop I used a while(boolean), making it easy to exit the loop. Another approach would be using break with labels.

Error: Execution failed for task ':app:clean'. Unable to delete file

I had this problem in Android Studio 2.3.

I simply restarted Android Studio and after that I could clean without complaints.

How do I redirect to another webpage?

You can redirect the page by using the below methods:

  1. By using a meta tag in the head - <meta http-equiv="refresh" content="0;url=http://your-page-url.com" />. Note that content="0;... is used for after how many seconds you need to redirect the page

  2. By using JavaScript: window.location.href = "http://your-page-url.com";

  3. By using jQuery: $(location).attr('href', 'http://yourPage.com/');

Get specific ArrayList item

As many have already told you:

mainList.get(3);

Be sure to check the ArrayList Javadoc.

Also, be careful with the arrays indices: in Java, the first element is at index 0. So if you are trying to get the third element, your solution would be mainList.get(2);

Only local connections are allowed Chrome and Selenium webdriver

I was able to resolve the problem by following steps: a. upgrade to the latest chrome version, clear the cache and close the chrome browser b. Download latest Selenium 3.0

How to extend / inherit components?

If anyone is looking for an updated solution, Fernando's answer is pretty much perfect. Except that ComponentMetadata has been deprecated. Using Component instead worked for me.

The full Custom Decorator CustomDecorator.ts file looks like this:

import 'zone.js';
import 'reflect-metadata';
import { Component } from '@angular/core';
import { isPresent } from "@angular/platform-browser/src/facade/lang";

export function CustomComponent(annotation: any) {
  return function (target: Function) {
    var parentTarget = Object.getPrototypeOf(target.prototype).constructor;
    var parentAnnotations = Reflect.getMetadata('annotations', parentTarget);

    var parentAnnotation = parentAnnotations[0];
    Object.keys(parentAnnotation).forEach(key => {
      if (isPresent(parentAnnotation[key])) {
        // verify is annotation typeof function
        if(typeof annotation[key] === 'function'){
          annotation[key] = annotation[key].call(this, parentAnnotation[key]);
        }else if(
          // force override in annotation base
          !isPresent(annotation[key])
        ){
          annotation[key] = parentAnnotation[key];
        }
      }
    });

    var metadata = new Component(annotation);

    Reflect.defineMetadata('annotations', [ metadata ], target);
  }
}

Then import it in to your new component sub-component.component.ts file and use @CustomComponent instead of @Component like this:

import { CustomComponent } from './CustomDecorator';
import { AbstractComponent } from 'path/to/file';

...

@CustomComponent({
  selector: 'subcomponent'
})
export class SubComponent extends AbstractComponent {

  constructor() {
    super();
  }

  // Add new logic here!
}

ssh connection refused on Raspberry Pi

I think pi has ssh server enabled by default. Mine have always worked out of the box. Depends which operating system version maybe.

Most of the time when it fails for me it is because the ip address has been changed. Perhaps you are pinging something else now? Also sometimes they just refuse to connect and need a restart.

How to reference a .css file on a razor view?

I prefer to use the razor html helper from Client Dependency dll

Html.RequireCss("yourfile", 9999); // 9999 is loading priority 

Open an html page in default browser with VBA?

You can use the Windows API function ShellExecute to do so:

Option Explicit

Private Declare Function ShellExecute _
  Lib "shell32.dll" Alias "ShellExecuteA" ( _
  ByVal hWnd As Long, _
  ByVal Operation As String, _
  ByVal Filename As String, _
  Optional ByVal Parameters As String, _
  Optional ByVal Directory As String, _
  Optional ByVal WindowStyle As Long = vbMinimizedFocus _
  ) As Long

Public Sub OpenUrl()

    Dim lSuccess As Long
    lSuccess = ShellExecute(0, "Open", "www.google.com")

End Sub

Just a short remark concerning security: If the URL comes from user input make sure to strictly validate that input as ShellExecute would execute any command with the user's permissions, also a format c: would be executed if the user is an administrator.

Is there more to an interface than having the correct methods

If you have CardboardBox and HtmlBox (both of which implement IBox), you can pass both of them to any method that accepts a IBox. Even though they are both very different and not completely interchangable, methods that don't care about "open" or "resize" can still use your classes (perhaps because they care about how many pixels are needed to display something on a screen).

browser sessionStorage. share between tabs?

You can use localStorage and its "storage" eventListener to transfer sessionStorage data from one tab to another.

This code would need to exist on ALL tabs. It should execute before your other scripts.

// transfers sessionStorage from one tab to another
var sessionStorage_transfer = function(event) {
  if(!event) { event = window.event; } // ie suq
  if(!event.newValue) return;          // do nothing if no value to work with
  if (event.key == 'getSessionStorage') {
    // another tab asked for the sessionStorage -> send it
    localStorage.setItem('sessionStorage', JSON.stringify(sessionStorage));
    // the other tab should now have it, so we're done with it.
    localStorage.removeItem('sessionStorage'); // <- could do short timeout as well.
  } else if (event.key == 'sessionStorage' && !sessionStorage.length) {
    // another tab sent data <- get it
    var data = JSON.parse(event.newValue);
    for (var key in data) {
      sessionStorage.setItem(key, data[key]);
    }
  }
};

// listen for changes to localStorage
if(window.addEventListener) {
  window.addEventListener("storage", sessionStorage_transfer, false);
} else {
  window.attachEvent("onstorage", sessionStorage_transfer);
};


// Ask other tabs for session storage (this is ONLY to trigger event)
if (!sessionStorage.length) {
  localStorage.setItem('getSessionStorage', 'foobar');
  localStorage.removeItem('getSessionStorage', 'foobar');
};

I tested this in chrome, ff, safari, ie 11, ie 10, ie9

This method "should work in IE8" but i could not test it as my IE was crashing every time i opened a tab.... any tab... on any website. (good ol IE) PS: you'll obviously need to include a JSON shim if you want IE8 support as well. :)

Credit goes to this full article: http://blog.guya.net/2015/06/12/sharing-sessionstorage-between-tabs-for-secure-multi-tab-authentication/

Split String into an array of String

String[] result = "hi i'm paul".split("\\s+"); to split across one or more cases.

Or you could take a look at Apache Common StringUtils. It has StringUtils.split(String str) method that splits string using white space as delimiter. It also has other useful utility methods

Drawing Circle with OpenGL

Here is a code to draw a fill elipse, you can use the same method but replacing de xcenter and y center with radius

void drawFilledelipse(GLfloat x, GLfloat y, GLfloat xcenter,GLfloat ycenter) {
    int i;
    int triangleAmount = 20; //# of triangles used to draw circle

    //GLfloat radius = 0.8f; //radius
    GLfloat twicePi = 2.0f * PI;

    glBegin(GL_TRIANGLE_FAN);
    glVertex2f(x, y); // center of circle
    for (i = 0; i <= triangleAmount; i++) {
        glVertex2f(
            x + ((xcenter+1)* cos(i * twicePi / triangleAmount)),
            y + ((ycenter-1)* sin(i * twicePi / triangleAmount))
        );
    }
    glEnd();
}

SQL update from one Table to another based on a ID match

If above answers not working for you try this

Update Sales_Import A left join RetrieveAccountNumber B on A.LeadID = B.LeadID
Set A.AccountNumber = B.AccountNumber
where A.LeadID = B.LeadID 

Get parent of current directory from Python script

import os
current_file = os.path.abspath(os.path.dirname(__file__))
parent_of_parent_dir = os.path.join(current_file, '../../')

What is WEB-INF used for in a Java EE web application?

There is a convention (not necessary) of placing jsp pages under WEB-INF directory so that they cannot be deep linked or bookmarked to. This way all requests to jsp page must be directed through our application, so that user experience is guaranteed.

Changing text color onclick

A rewrite of the answer by Sarfraz would be something like this, I think:

<script>

    document.getElementById('change').onclick = changeColor;   

    function changeColor() {
        document.body.style.color = "purple";
        return false;
    }   

</script>

You'd either have to put this script at the bottom of your page, right before the closing body tag, or put the handler assignment in a function called onload - or if you're using jQuery there's the very elegant $(document).ready(function() { ... } );

Note that when you assign event handlers this way, it takes the functionality out of your HTML. Also note you set it equal to the function name -- no (). If you did onclick = myFunc(); the function would actually execute when the handler is being set.

And I'm curious -- you knew enough to script changing the background color, but not the text color? strange:)

Docker: Multiple Dockerfiles in project

In newer versions(>=1.8.0) of docker, you can do this

docker build -f Dockerfile.db .
docker build -f Dockerfile.web .

A big save.

EDIT: update versions per raksja's comment

EDIT: comment from @vsevolod: it's possible to get syntax highlighting in VS code by giving files .Dockerfile extension(instead of name) e.g. Prod.Dockerfile, Test.Dockerfile etc.

Padding or margin value in pixels as integer using jQuery

PLEASE don't go loading another library just to do something that's already natively available!

jQuery's .css() converts %'s and em's to their pixel equivalent to begin with, and parseInt() will remove the 'px' from the end of the returned string and convert it to an integer:

http://jsfiddle.net/BXnXJ/

$(document).ready(function () {
    var $h1 = $('h1');
    console.log($h1);
    $h1.after($('<div>Padding-top: ' + parseInt($h1.css('padding-top')) + '</div>'));
    $h1.after($('<div>Margin-top: ' + parseInt($h1.css('margin-top')) + '</div>'));
});

How do I start an activity from within a Fragment?

The difference between starting an Activity from a Fragment and an Activity is how you get the context, because in both cases it has to be an activity.

From an activity: The context is the current activity (this)

Intent intent = new Intent(this, NewActivity.class);
startActivity(intent);

From a fragment: The context is the parent activity (getActivity()). Notice, that the fragment itself can start the activity via startActivity(), this is not necessary to be done from the activity.

Intent intent = new Intent(getActivity(), NewActivity.class);
startActivity(intent);

Mean filter for smoothing images in Matlab

f=imread(...);

h=fspecial('average', [3 3]);
g= imfilter(f, h);
imshow(g);

Remove Server Response Header IIS7

This web.config setup works to remove all unnecessary headers from the ASP.NET response (at least starting from IIS 10):

<system.web>
    <!-- Removes version headers from response -->
    <httpRuntime enableVersionHeader="false" />
</system.web>

<system.webServer>
    <httpProtocol>
        <customHeaders>
            <!--Removes X-Powered-By header from response -->
            <clear />
        </customHeaders>
    </httpProtocol>

    <security>
        <!--Removes Server header from response-->
        <requestFiltering removeServerHeader ="true" />
    </security>
</system.webServer>

Please note that this hides all the headers for the "application", as do all the other approaches. If you e.g. reach some default page or an error page generated by the IIS itself or ASP.NET outside your application these rules won't apply. So ideally they should be on the root level in IIS and that sill may leave some error responses to the IIS itself.

P.S. There is a bug in IIS 10 that makes it sometimes show the server header even with correct config. It should be fixed by now, but IIS/Windows has to be updated.

What is an .axd file?

An AXD file is a file used by ASP.NET applications for handling embedded resource requests. It contains instructions for retrieving embedded resources, such as images, JavaScript (.JS) files, and.CSS files. AXD files are used for injecting resources into the client-side webpage and access them on the server in a standard way.

How do I check particular attributes exist or not in XML?

Another way to handle the situation is exception handling.

Every time a non-existent value is called, your code will recover from the exception and just continue with the loop. In the catch-block you can handle the error the same way you write it down in your else-statement when the expression (... != null) returns false. Of course throwing and handling exceptions is a relatively costly operation which might not be ideal depending on the performance requirements.

Cygwin - Makefile-error: recipe for target `main.o' failed

You see the two empty -D entries in the g++ command line? They're causing the problem. You must have values in the -D items e.g. -DWIN32

if you're insistent on using something like -D$(SYSTEM) -D$(ENVIRONMENT) then you can use something like:

SYSTEM ?= generic
ENVIRONMENT ?= generic

in the makefile which gives them default values.

Your output looks to be missing the all important output:

<command-line>:0:1: error: macro names must be identifiers
<command-line>:0:1: error: macro names must be identifiers

just to clarify, what actually got sent to g++ was -D -DWindows_NT, i.e. define a preprocessor macro called -DWindows_NT; which is of course not a valid identifier (similarly for -D -I.)

Android Studio suddenly cannot resolve symbols

Be aware that the name of files and specially folders can result in this error. For instance, if you have a folder "Helpers" and the package for files in this folder is "com.whatever.helpers" it won't result in any compilation error but will cause the Android studio fail to load the symbols in that folder. One typical reason for that is when you name a folder with first capital letter, commit it on Git and later change the folder name to all lower case. The Git system won't recognize the change resulting in a discrepancy between the local and remote repositories that only the new repository clones will be affect by.

Python Pandas: How to read only first n rows of CSV files in?

If you only want to read the first 999,999 (non-header) rows:

read_csv(..., nrows=999999)

If you only want to read rows 1,000,000 ... 1,999,999

read_csv(..., skiprows=1000000, nrows=999999)

nrows : int, default None Number of rows of file to read. Useful for reading pieces of large files*

skiprows : list-like or integer Row numbers to skip (0-indexed) or number of rows to skip (int) at the start of the file

and for large files, you'll probably also want to use chunksize:

chunksize : int, default None Return TextFileReader object for iteration

pandas.io.parsers.read_csv documentation

What is the advantage of using heredoc in PHP?

Heredoc's are a great alternative to quoted strings because of increased readability and maintainability. You don't have to escape quotes and (good) IDEs or text editors will use the proper syntax highlighting.

A very common example: echoing out HTML from within PHP:

$html = <<<HTML
  <div class='something'>
    <ul class='mylist'>
      <li>$something</li>
      <li>$whatever</li>
      <li>$testing123</li>
    </ul>
  </div>
HTML;

// Sometime later
echo $html;

It is easy to read and easy to maintain.

The alternative is echoing quoted strings, which end up containing escaped quotes and IDEs aren't going to highlight the syntax for that language, which leads to poor readability and more difficulty in maintenance.

Updated answer for Your Common Sense

Of course you wouldn't want to see an SQL query highlighted as HTML. To use other languages, simply change the language in the syntax:

$sql = <<<SQL
       SELECT * FROM table
SQL;

Fatal error: Class 'ZipArchive' not found in

I faced this issue on GCP while deploying wordpress in the App Engine Standard environment. This solved it :

sudo apt-get install php7.2-zip

AES vs Blowfish for file encryption

The algorithm choice probably doesn't matter that much. I'd use AES since it's been better researched. What's much more important is choosing the right operation mode and key derivation function.

You might want to take a look at the TrueCrypt format specification for inspiration if you want fast random access. If you don't need random access than XTS isn't the optimal mode, since it has weaknesses other modes don't. And you might want to add some kind of integrity check(or message authentication code) too.

Difference in System. exit(0) , System.exit(-1), System.exit(1 ) in Java

The parameter of exit should qualify if the execution of the program went good or bad. It's a sort of heredity from older programming languages where it's useful to know if something went wrong and what went wrong.

Exit code is

  • 0 when execution went fine;
  • 1, -1, whatever != 0 when some error occurred, you can use different values for different kind of errors.

If I'm correct exit codes used to be just positive numbers (I mean in UNIX) and according to range:

  • 1-127 are user defined codes (so generated by calling exit(n))
  • 128-255 are codes generated by termination due to different unix signals like SIGSEGV or SIGTERM

But I don't think you should care while coding on Java, it's just a bit of information. It's useful if you plan to make your programs interact with standard tools.

How to read a large file line by line?

Two memory efficient ways in ranked order (first is best) -

  1. use of with - supported from python 2.5 and above
  2. use of yield if you really want to have control over how much to read

1. use of with

with is the nice and efficient pythonic way to read large files. advantages - 1) file object is automatically closed after exiting from with execution block. 2) exception handling inside the with block. 3) memory for loop iterates through the f file object line by line. internally it does buffered IO (to optimized on costly IO operations) and memory management.

with open("x.txt") as f:
    for line in f:
        do something with data

2. use of yield

Sometimes one might want more fine-grained control over how much to read in each iteration. In that case use iter & yield. Note with this method one explicitly needs close the file at the end.

def readInChunks(fileObj, chunkSize=2048):
    """
    Lazy function to read a file piece by piece.
    Default chunk size: 2kB.

    """
    while True:
        data = fileObj.read(chunkSize)
        if not data:
            break
        yield data

f = open('bigFile')
for chunk in readInChunks(f):
    do_something(chunk)
f.close()

Pitfalls and for the sake of completeness - below methods are not as good or not as elegant for reading large files but please read to get rounded understanding.

In Python, the most common way to read lines from a file is to do the following:

for line in open('myfile','r').readlines():
    do_something(line)

When this is done, however, the readlines() function (same applies for read() function) loads the entire file into memory, then iterates over it. A slightly better approach (the first mentioned two methods above are the best) for large files is to use the fileinput module, as follows:

import fileinput

for line in fileinput.input(['myfile']):
    do_something(line)

the fileinput.input() call reads lines sequentially, but doesn't keep them in memory after they've been read or even simply so this, since file in python is iterable.

References

  1. Python with statement

Vertical Align Center in Bootstrap 4

I've tried all the answers herefrom, but found out here is the difference between h-100 and vh-100 Here is my solution:

      <div className='container vh-100 d-flex align-items-center col justify-content-center'>
        <div className="">
             ...
        </div>
      </div >

How to use Visual Studio C++ Compiler?

In Visual Studio, you can't just open a .cpp file and expect it to run. You must create a project first, or open the .cpp in some existing project.

In your case, there is no project, so there is no project to build.

Go to File --> New --> Project --> Visual C++ --> Win32 Console Application. You can uncheck "create a directory for solution". On the next page, be sure to check "Empty project".

Then, You can add .cpp files you created outside the Visual Studio by right clicking in the Solution explorer on folder icon "Source" and Add->Existing Item.

Obviously You can create new .cpp this way too (Add --> New). The .cpp file will be created in your project directory.

Then you can press ctrl+F5 to compile without debugging and can see output on console window.

add column to mysql table if it does not exist

Below are the Stored procedure in MySQL To Add Column(s) in different Table(s) in different Database(s) if column does not exists in a Database(s) Table(s) with following advantages

  • multiple columns can be added use at once to alter multiple Table in different Databases
  • three mysql commands run, i.e. DROP, CREATE, CALL For Procedure
  • DATABASE Name should be changes as per USE otherwise problem may occur for multiple datas

_x000D_
_x000D_
DROP PROCEDURE  IF EXISTS `AlterTables`;_x000D_
DELIMITER $$_x000D_
CREATE PROCEDURE `AlterTables`() _x000D_
BEGIN_x000D_
    DECLARE table1_column1_count INT;_x000D_
    DECLARE table2_column2_count INT;_x000D_
    SET table1_column1_count = (  SELECT COUNT(*) _x000D_
                    FROM INFORMATION_SCHEMA.COLUMNS_x000D_
                    WHERE   TABLE_SCHEMA = 'DATABASE_NAME' AND_x000D_
       TABLE_NAME = 'TABLE_NAME1' AND _x000D_
                            COLUMN_NAME = 'TABLE_NAME1_COLUMN1');_x000D_
    SET table2_column2_count = (  SELECT COUNT(*) _x000D_
                    FROM INFORMATION_SCHEMA.COLUMNS_x000D_
                    WHERE   TABLE_SCHEMA = 'DATABASE_NAME' AND_x000D_
       TABLE_NAME = 'TABLE_NAME2' AND _x000D_
                            COLUMN_NAME = 'TABLE_NAME2_COLUMN2');_x000D_
    IF table1_column1_count = 0 THEN_x000D_
        ALTER TABLE `TABLE_NAME1`ADD `TABLE_NAME1_COLUMN1` text COLLATE 'latin1_swedish_ci' NULL AFTER `TABLE_NAME1_COLUMN3`,COMMENT='COMMENT HERE';_x000D_
    END IF;_x000D_
    IF table2_column2_count = 0 THEN_x000D_
        ALTER TABLE `TABLE_NAME2` ADD `TABLE_NAME2_COLUMN2` VARCHAR( 100 ) NULL DEFAULT NULL COMMENT 'COMMENT HERE';_x000D_
    END IF;_x000D_
END $$_x000D_
DELIMITER ;_x000D_
call AlterTables();
_x000D_
_x000D_
_x000D_

Getting the .Text value from a TextBox

if(sender is TextBox) {
 var text = (sender as TextBox).Text;
}

How Can I Override Style Info from a CSS Class in the Body of a Page?

You can put CSS in the head of the HTML file, and it will take precedent over a class in an included style sheet.

<style>
.thing{
    color: #f00;
}
</style>

Get the second highest value in a MySQL table

FOR SECOND LAST:

SELECT name, salary
    FROM employee 
    ORDER BY salary DESC
    LIMIT 1 , 1

FOR THIRD LAST:

SELECT name, salary
    FROM employee 
    ORDER BY salary DESC
    LIMIT 2 , 1

Excel function to get first word from sentence in other cell

If you want to cater to 1-word cell, use this... based upon astander's

=IFERROR(LEFT(A1,SEARCH(" ",A1)-1),A1)

Is there a performance difference between CTE , Sub-Query, Temporary Table or Table Variable?

Just 2 things I think make it ALWAYS preferable to use a # Temp Table rather then a CTE are:

  1. You can not put a primary key on a CTE so the data being accessed by the CTE will have to traverse each one of the indexes in the CTE's tables rather then just accessing the PK or Index on the temp table.

  2. Because you can not add constraints, indexes and primary keys to a CTE they are more prone to bugs creeping in and bad data.


-onedaywhen yesterday

Here is an example where #table constraints can prevent bad data which is not the case in CTE's

DECLARE @BadData TABLE ( 
                       ThisID int
                     , ThatID int );
INSERT INTO @BadData
       ( ThisID
       , ThatID
       ) 
VALUES
       ( 1, 1 ),
       ( 1, 2 ),
       ( 2, 2 ),
       ( 1, 1 );

IF OBJECT_ID('tempdb..#This') IS NOT NULL
    DROP TABLE #This;
CREATE TABLE #This ( 
             ThisID int NOT NULL
           , ThatID int NOT NULL
                        UNIQUE(ThisID, ThatID) );
INSERT INTO #This
SELECT * FROM @BadData;
WITH This_CTE
     AS (SELECT *
           FROM @BadData)
     SELECT *
       FROM This_CTE;

Real world use of JMS/message queues?

Apache Camel used in conjunction with ActiveMQ is great way to do Enterprise Integration Patterns

Create a new cmd.exe window from within another cmd.exe prompt

Here is the code you need:

start cmd.exe @cmd /k "Command"

Java, Simplified check if int array contains int

1.one-off uses

List<T> list=Arrays.asList(...)
list.contains(...)

2.use HashSet for performance consideration if you use more than once.

Set <T>set =new HashSet<T>(Arrays.asList(...));
set.contains(...)

How do I implement a progress bar in C#?

When you perform operations on Background thread and you want to update UI, you can not call or set anything from background thread. In case of WPF you need Dispatcher.BeginInvoke and in case of WinForms you need Invoke method.

WPF:

// assuming "this" is the window containing your progress bar..
// following code runs in background worker thread...
for(int i=0;i<count;i++)
{
    DoSomething();
    this.Dispatcher.BeginInvoke((Action)delegate(){
         this.progressBar.Value = (int)((100*i)/count);
    });
}

WinForms:

// assuming "this" is the window containing your progress bar..
// following code runs in background worker thread...
for(int i=0;i<count;i++)
{
    DoSomething();
    this.Invoke(delegate(){
         this.progressBar.Value = (int)((100*i)/count);
    });
}

for WinForms delegate may require some casting or you may need little help there, dont remember the exact syntax now.

How do I read CSV data into a record array in NumPy?

You can use this code to send CSV file data into an array:

import numpy as np
csv = np.genfromtxt('test.csv', delimiter=",")
print(csv)

How to declare and initialize a static const array as a class member?

You are mixing pointers and arrays. If what you want is an array, then use an array:

struct test {
   static int data[10];        // array, not pointer!
};
int test::data[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

If on the other hand you want a pointer, the simplest solution is to write a helper function in the translation unit that defines the member:

struct test {
   static int *data;
};
// cpp
static int* generate_data() {            // static here is "internal linkage"
   int * p = new int[10];
   for ( int i = 0; i < 10; ++i ) p[i] = 10*i;
   return p;
}
int *test::data = generate_data();

Multiple INSERT statements vs. single INSERT with multiple VALUES

It is not too surprising: the execution plan for the tiny insert is computed once, and then reused 1000 times. Parsing and preparing the plan is quick, because it has only four values to del with. A 1000-row plan, on the other hand, needs to deal with 4000 values (or 4000 parameters if you parameterized your C# tests). This could easily eat up the time savings you gain by eliminating 999 roundtrips to SQL Server, especially if your network is not overly slow.

How to install an apk on the emulator in Android Studio?

Run simulator -> drag and drop yourApp.apk into simulator screen. Thats all. No commands.

How can JavaScript save to a local file?

It is not possible to save file locally without involving the local client (browser machine) as I could be a great threat to client machine. You can use link to download that file. If you want to store something like Json data on local machine you can use LocalStorage provided by the browsers, Web Storage

Get commit list between tags in git

To compare between latest commit of current branch and a tag:

git log --pretty=oneline HEAD...tag

Set Response Status Code

Why not using Cakes Response Class? You can set the status code of the response simply by this:

$this->response->statusCode(200);

Then just render a file with the error message, which suits best with JSON.

java.lang.NoSuchMethodError: org.apache.commons.codec.binary.Base64.encodeBase64String() in Java EE application

Simply create an object of Base64 and use it to encode or decode, when using org.apache.commons.codec.binary.Base64 library

To Encode

Base64 ed=new Base64();

String encoded=new String(ed.encode("Hello".getBytes()));

Replace "Hello" with the text to be encoded in String Format.

To Decode

Base64 ed=new Base64();

String decoded=new String(ed.decode(encoded.getBytes()));

Here encoded is the String variable to be decoded

document.getElementById().value and document.getElementById().checked not working for IE

Have a look at jQuery, a cross-browser library that will make your life a lot easier.

var msg = 'abc';
$('#msg').val(msg);
$('#sp_100').attr('checked', 'checked');

Received an invalid column length from the bcp client for colid 6

Great piece of code, thanks for sharing!

I ended up using reflection to get the actual DataMemberName to throw back to a client on an error (I'm using bulk save in a WCF service). Hopefully someone else will find how I did it useful.

_x000D_
_x000D_
static string GetDataMemberName(string colName, object t) {_x000D_
  foreach(PropertyInfo propertyInfo in t.GetType().GetProperties()) {_x000D_
    if (propertyInfo.CanRead) {_x000D_
      if (propertyInfo.Name == colName) {_x000D_
        var attributes = propertyInfo.GetCustomAttributes(typeof(DataMemberAttribute), false).FirstOrDefault() as DataMemberAttribute;_x000D_
        if (attributes != null && !string.IsNullOrEmpty(attributes.Name))_x000D_
          return attributes.Name;_x000D_
        return colName;_x000D_
      }_x000D_
    }_x000D_
  }_x000D_
  return colName;_x000D_
}
_x000D_
_x000D_
_x000D_

xml.LoadData - Data at the root level is invalid. Line 1, position 1

I have found out one of the solutions. For your code this could be as follows -

XmlDocument xml = new XmlDocument();
try
{
    // assuming the location of the file is in the current directory 
    // assuming the file name be loadData.xml
    string myString = "./loadData.xml";
    xml.Load(myString);
}
catch (Exception ex)
{
    System.IO.File.WriteAllText(@"C:\text.txt", myString + "\r\n\r\n" + ex.Message);
    throw ex;
}

How can I get phone serial number (IMEI)

public String getIMEI(Context context){

    TelephonyManager mngr = (TelephonyManager) context.getSystemService(context.TELEPHONY_SERVICE); 
    String imei = mngr.getDeviceId();
    return imei;

}

PHP string "contains"

PHP 8 or newer:

Use the str_contains function.

if (str_contains($str, "."))
{
    echo 'Found it';
}

else
{
    echo 'Not found.';
}

PHP 7 or older:

if (strpos($str, '.') !== FALSE)
{
    echo 'Found it';
}

else
{
    echo 'Not found.';
}

Note that you need to use the !== operator. If you use != or <> and the '.' is found at position 0, the comparison will evaluate to true because 0 is loosely equal to false.

Please explain about insertable=false and updatable=false in reference to the JPA @Column annotation

Defining insertable=false, updatable=false is useful when you need to map a field more than once in an entity, typically:

This is IMO not a semantical thing, but definitely a technical one.

How to set value in @Html.TextBoxFor in Razor syntax?

I tried replacing value with Value and it worked out. It has set the value in input tag now.

VB.NET Connection string (Web.Config, App.Config)

If it's a .mdf database and the connection string was saved when it was created, you should be able to access it via:

    Dim cn As SqlConnection = New SqlConnection(My.Settings.DatabaseNameConnectionString)

Hope that helps someone.

How can I get Docker Linux container information from within the container itself?

A comment by madeddie looks most elegant to me:

CID=$(basename $(cat /proc/1/cpuset))

LINQ: "contains" and a Lambda query

I'm not sure precisely what you're looking for, but this program:

    public class Building
    {
        public enum StatusType
        {
            open,
            closed,
            weird,
        };

        public string Name { get; set; }
        public StatusType Status { get; set; }
    }

    public static List <Building> buildingList = new List<Building> ()
    {
        new Building () { Name = "one", Status = Building.StatusType.open },
        new Building () { Name = "two", Status = Building.StatusType.closed },
        new Building () { Name = "three", Status = Building.StatusType.weird },

        new Building () { Name = "four", Status = Building.StatusType.open },
        new Building () { Name = "five", Status = Building.StatusType.closed },
        new Building () { Name = "six", Status = Building.StatusType.weird },
    };

    static void Main (string [] args)
    {
        var statusList = new List<Building.StatusType> () { Building.StatusType.open, Building.StatusType.closed };

        var q = from building in buildingList
                where statusList.Contains (building.Status)
                select building;

        foreach ( var b in q )
            Console.WriteLine ("{0}: {1}", b.Name, b.Status);
    }

produces the expected output:

one: open
two: closed
four: open
five: closed

This program compares a string representation of the enum and produces the same output:

    public class Building
    {
        public enum StatusType
        {
            open,
            closed,
            weird,
        };

        public string Name { get; set; }
        public string Status { get; set; }
    }

    public static List <Building> buildingList = new List<Building> ()
    {
        new Building () { Name = "one", Status = "open" },
        new Building () { Name = "two", Status = "closed" },
        new Building () { Name = "three", Status = "weird" },

        new Building () { Name = "four", Status = "open" },
        new Building () { Name = "five", Status = "closed" },
        new Building () { Name = "six", Status = "weird" },
    };

    static void Main (string [] args)
    {
        var statusList = new List<Building.StatusType> () { Building.StatusType.open, Building.StatusType.closed };
        var statusStringList = statusList.ConvertAll <string> (st => st.ToString ());

        var q = from building in buildingList
                where statusStringList.Contains (building.Status)
                select building;

        foreach ( var b in q )
            Console.WriteLine ("{0}: {1}", b.Name, b.Status);

        Console.ReadKey ();
    }

I created this extension method to convert one IEnumerable to another, but I'm not sure how efficient it is; it may just create a list behind the scenes.

public static IEnumerable <TResult> ConvertEach (IEnumerable <TSource> sources, Func <TSource,TResult> convert)
{
    foreach ( TSource source in sources )
        yield return convert (source);
}

Then you can change the where clause to:

where statusList.ConvertEach <string> (status => status.GetCharValue()).
    Contains (v.Status)

and skip creating the List<string> with ConvertAll () at the beginning.

command/usr/bin/codesign failed with exit code 1- code sign error

I had this error in Xcode 8 and Mac OS Sierra. Tried all the above solutions and none worked. This was the only one that worked for me. Open terminal, and type this in:

cd ~/Library/Developer/Xcode/DerivedData
xattr -c *

VBA collection: list of keys

An alternative solution is to store the keys in a separate Collection:

'Initialise these somewhere.
Dim Keys As Collection, Values As Collection

'Add types for K and V as necessary.
Sub Add(K, V) 
Keys.Add K
Values.Add V, K
End Sub

You can maintain a separate sort order for the keys and the values, which can be useful sometimes.

Git pull till a particular commit

I've found the updated answer from this video, the accepted answer didn't work for me.

First clone the latest repo from git (if haven't) using git clone <HTTPs link of the project> (or using SSH) then go to the desire branch using git checkout <branch name> .

Use the command

git log

to check the latest commits. Copy the shal of the particular commit. Then use the command

git fetch origin <Copy paste the shal here>

After pressing enter key. Now use the command

git checkout FETCH_HEAD

Now the particular commit will be available to your local. Change anything and push the code using git push origin <branch name> . That's all. Check the video for reference.

How to set the JSTL variable value in javascript?

This variable can be set using value="${val1}" inside c:set if you have used jquery in your system.

Mocking python function based on input arguments

I've ended up here looking for "how to mock a function based on input arguments" and I finally solved this creating a simple aux function:

def mock_responses(responses, default_response=None):
  return lambda input: responses[input] if input in responses else default_response

Now:

my_mock.foo.side_effect = mock_responses(
  {
    'x': 42, 
    'y': [1,2,3]
  })
my_mock.goo.side_effect = mock_responses(
  {
    'hello': 'world'
  }, 
  default_response='hi')
...

my_mock.foo('x') # => 42
my_mock.foo('y') # => [1,2,3]
my_mock.foo('unknown') # => None

my_mock.goo('hello') # => 'world'
my_mock.goo('ey') # => 'hi'

Hope this will help someone!

Identifying Exception Type in a handler Catch Block

Alternative Solution

Instead halting a debug session to add some throw-away statements to then recompile and restart, why not just use the debugger to answer that question immediately when a breakpoint is hit?

That can be done by opening up the Immediate Window of the debugger and typing a GetType off of the exception and hitting Enter. The immediate window also allows one to interrogate variables as needed.

See VS Docs: Immediate Window


For example I needed to know what the exception was and just extracted the Name property of GetType as such without having to recompile:

enter image description here

Is there a free GUI management tool for Oracle Database Express?

Try odbTools at http://odbtools.software.informer.com - it is free.

odbTools is set of integrated GUI tools to manage, administer, monitor and tune the Oracle database.

Casting a variable using a Type variable

Putting boxing and unboxing aside for simplicity, there's no specific runtime action involved in casting along the inheritance hierarchy. It's mostly a compile time thing. Essentially, a cast tells the compiler to treat the value of the variable as another type.

What you could do after the cast? You don't know the type, so you wouldn't be able to call any methods on it. There wouldn't be any special thing you could do. Specifically, it can be useful only if you know the possible types at compile time, cast it manually and handle each case separately with if statements:

if (type == typeof(int)) {
    int x = (int)obj;
    DoSomethingWithInt(x);
} else if (type == typeof(string)) {
    string s = (string)obj;
    DoSomethingWithString(s);
} // ...

The given key was not present in the dictionary. Which key?

You can try this code

Dictionary<string,string> AllFields = new Dictionary<string,string>();  
string value = (AllFields.TryGetValue(key, out index) ? AllFields[key] : null);

If the key is not present, it simply returns a null value.

Unable to install Maven on Windows: "JAVA_HOME is set to an invalid directory"

Sometimes in Windows whitespaces in paths are not recognized correctly

If you have a path problem and path seems like

c:\Program Files\....

try changing it in an old DOS format like

"C:\Progra~1\...

You can use dir /x to check correct syntax (third column)

C:\>dir /x ... 11.01.2008 15:47 <DIR> DOCUME~1 Documents and Settings 01.12.2006 09:10 <DIR> MYPROJ~1 My Projects 21.01.2011 14:08 <DIR> PROGRA~1 Program Files ...

In my pc JAVA_HOME is (and it works)

"C:\Progra~1\Java\jdk1.8.0_121"

Tested in Windows 10

SelectSingleNode returning null for known good xml node path using XPath

The rule to keep in mind is: if your document specifies a namespace, you MUST use an XmlNamespaceManager in your call to SelectNodes() or SelectSingleNode(). That's a good thing.

See the article Advantages of namespaces . Jon Skeet does a great job in his answer showing how to use XmlNamespaceManager. (This answer should really just be a comment on that answer, but I don't quite have enough Rep Points to comment.)

What is logits, softmax and softmax_cross_entropy_with_logits?

Above answers have enough description for the asked question.

Adding to that, Tensorflow has optimised the operation of applying the activation function then calculating cost using its own activation followed by cost functions. Hence it is a good practice to use: tf.nn.softmax_cross_entropy() over tf.nn.softmax(); tf.nn.cross_entropy()

You can find prominent difference between them in a resource intensive model.

Typescript: Type 'string | undefined' is not assignable to type 'string'

Had the same issue.

I find out that react-scrips add "strict": true to tsconfig.json.

After I removed it everything works great.

Edit

Need to warn that changing this property means that you:

not being warned about potential run-time errors anymore.

as been pointed out by PaulG in comments! Thank you :)

Use "strict": false only if you fully understand what it affects!

MySQL Select Multiple VALUES

Try or:

WHERE id = 3 or id = 4

Or the equivalent in:

WHERE id in (3,4)

convert base64 to image in javascript/jquery

This is not exactly the OP's scenario but an answer to those of some of the commenters. It is a solution based on Cordova and Angular 1, which should be adaptable to other frameworks like jQuery. It gives you a Blob from Base64 data which you can store somewhere and reference it from client side javascript / html.

It also answers the original question on how to get an image (file) from the Base 64 data:

The important part is the Base 64 - Binary conversion:

function base64toBlob(base64Data, contentType) {
    contentType = contentType || '';
    var sliceSize = 1024;
    var byteCharacters = atob(base64Data);
    var bytesLength = byteCharacters.length;
    var slicesCount = Math.ceil(bytesLength / sliceSize);
    var byteArrays = new Array(slicesCount);

    for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
        var begin = sliceIndex * sliceSize;
        var end = Math.min(begin + sliceSize, bytesLength);

        var bytes = new Array(end - begin);
        for (var offset = begin, i = 0; offset < end; ++i, ++offset) {
            bytes[i] = byteCharacters[offset].charCodeAt(0);
        }
        byteArrays[sliceIndex] = new Uint8Array(bytes);
    }
    return new Blob(byteArrays, { type: contentType });
}

Slicing is required to avoid out of memory errors.

Works with jpg and pdf files (at least that's what I tested). Should work with other mimetypes/contenttypes too. Check the browsers and their versions you aim for, they need to support Uint8Array, Blob and atob.

Here's the code to write the file to the device's local storage with Cordova / Android:

...
window.resolveLocalFileSystemURL(cordova.file.externalDataDirectory, function(dirEntry) {

                    // Setup filename and assume a jpg file
                    var filename = attachment.id + "-" + (attachment.fileName ? attachment.fileName : 'image') + "." + (attachment.fileType ? attachment.fileType : "jpg");
                    dirEntry.getFile(filename, { create: true, exclusive: false }, function(fileEntry) {
                        // attachment.document holds the base 64 data at this moment
                        var binary = base64toBlob(attachment.document, attachment.mimetype);
                        writeFile(fileEntry, binary).then(function() {
                            // Store file url for later reference, base 64 data is no longer required
                            attachment.document = fileEntry.nativeURL;

                        }, function(error) {
                            WL.Logger.error("Error writing local file: " + error);
                            reject(error.code);
                        });

                    }, function(errorCreateFile) {
                        WL.Logger.error("Error creating local file: " + JSON.stringify(errorCreateFile));
                        reject(errorCreateFile.code);
                    });

                }, function(errorCreateFS) {
                    WL.Logger.error("Error getting filesystem: " + errorCreateFS);
                    reject(errorCreateFS.code);
                });
...

Writing the file itself:

function writeFile(fileEntry, dataObj) {
    return $q(function(resolve, reject) {
        // Create a FileWriter object for our FileEntry (log.txt).
        fileEntry.createWriter(function(fileWriter) {

            fileWriter.onwriteend = function() {
                WL.Logger.debug(LOG_PREFIX + "Successful file write...");
                resolve();
            };

            fileWriter.onerror = function(e) {
                WL.Logger.error(LOG_PREFIX + "Failed file write: " + e.toString());
                reject(e);
            };

            // If data object is not passed in,
            // create a new Blob instead.
            if (!dataObj) {
                dataObj = new Blob(['missing data'], { type: 'text/plain' });
            }

            fileWriter.write(dataObj);
        });
    })
}

I am using the latest Cordova (6.5.0) and Plugins versions:

I hope this sets everyone here in the right direction.

How do I parse JSON in Android?

I've coded up a simple example for you and annotated the source. The example shows how to grab live json and parse into a JSONObject for detail extraction:

try{
    // Create a new HTTP Client
    DefaultHttpClient defaultClient = new DefaultHttpClient();
    // Setup the get request
    HttpGet httpGetRequest = new HttpGet("http://example.json");

    // Execute the request in the client
    HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
    // Grab the response
    BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
    String json = reader.readLine();

    // Instantiate a JSON object from the request response
    JSONObject jsonObject = new JSONObject(json);

} catch(Exception e){
    // In your production code handle any errors and catch the individual exceptions
    e.printStackTrace();
}

Once you have your JSONObject refer to the SDK for details on how to extract the data you require.

Using RegEx in SQL Server

SELECT * from SOME_TABLE where NAME like '%[^A-Z]%'

Or some other expression instead of A-Z

Select multiple columns by labels in pandas

Name- or Label-Based (using regular expression syntax)

df.filter(regex='[A-CEG-I]')   # does NOT depend on the column order

Note that any regular expression is allowed here, so this approach can be very general. E.g. if you wanted all columns starting with a capital or lowercase "A" you could use: df.filter(regex='^[Aa]')

Location-Based (depends on column order)

df[ list(df.loc[:,'A':'C']) + ['E'] + list(df.loc[:,'G':'I']) ]

Note that unlike the label-based method, this only works if your columns are alphabetically sorted. This is not necessarily a problem, however. For example, if your columns go ['A','C','B'], then you could replace 'A':'C' above with 'A':'B'.

The Long Way

And for completeness, you always have the option shown by @Magdalena of simply listing each column individually, although it could be much more verbose as the number of columns increases:

df[['A','B','C','E','G','H','I']]   # does NOT depend on the column order

Results for any of the above methods

          A         B         C         E         G         H         I
0 -0.814688 -1.060864 -0.008088  2.697203 -0.763874  1.793213 -0.019520
1  0.549824  0.269340  0.405570 -0.406695 -0.536304 -1.231051  0.058018
2  0.879230 -0.666814  1.305835  0.167621 -1.100355  0.391133  0.317467

How can I add new item to the String array?

Simple answer: You can't. An array is fixed size in Java. You'll want to use a List<String>.

Alternatively, you could create an array of fixed size and put things in it:

String[] array = new String[2];
array[0] = "Hello";
array[1] = "World!";

Column name or number of supplied values does not match table definition

Beware of triggers. Maybe the issue is with some operation in the trigger for inserted rows.

How to check the version before installing a package using apt-get?

Also, the apt-show-versions package (installed separately) parses dpkg information about what is installed and tells you if packages are up to date.

Example..

$ sudo apt-show-versions --regex chrome
google-chrome-stable/stable upgradeable from 32.0.1700.102-1 to 35.0.1916.114-1
xserver-xorg-video-openchrome/quantal-security uptodate 1:0.3.1-0ubuntu1.12.10.1
$

What are the advantages of Sublime Text over Notepad++ and vice-versa?

One thing that should be considered is licensing.

Notepad++ is free (as in speech and as in beer) for perpetual use, released under the GPL license, whereas Sublime Text 2 requires a license.

To quote the Sublime Text 2 website:

..a license must be purchased for continued use. There is currently no enforced time limit for the evaluation.

The same is now true of Sublime Text 3, and a paid upgrade will be needed for future versions.

Upgrade Policy A license is valid for Sublime Text 3, and includes all point updates, as well as access to prior versions (e.g., Sublime Text 2). Future major versions, such as Sublime Text 4, will be a paid upgrade.

This licensing requirement is still correct as of Dec 2019.

Error - replacement has [x] rows, data has [y]

You could use cut

 df$valueBin <- cut(df$value, c(-Inf, 250, 500, 1000, 2000, Inf), 
    labels=c('<=250', '250-500', '500-1,000', '1,000-2,000', '>2,000'))

data

 set.seed(24)
 df <- data.frame(value= sample(0:2500, 100, replace=TRUE))

How to do paging in AngularJS?

For anyone who find it difficult like me to create a paginator for a table I post this. So, in your view :

          <pagination total-items="total" items-per-page="itemPerPage"    ng-model="currentPage" ng-change="pageChanged()"></pagination>    
        <!-- To specify your choice of items Per Pages-->
     <div class="btn-group">
                <label class="btn btn-primary" ng-model="radioModel"  btn-radio="'Left'" data-ng-click="setItems(5)">5</label>
                <label class="btn btn-primary" ng-model="radioModel" btn-radio="'Middle'" data-ng-click="setItems(10)">10</label>
                <label class="btn btn-primary" ng-model="radioModel" btn-radio="'Right'" data-ng-click="setItems(15)">15</label>
            </div>
     //And don't forget in your table:
      <tr data-ng-repeat="p in profiles | offset: (currentPage-1)*itemPerPage | limitTo: itemPerPage" >

In your angularJs:

  var module = angular.module('myapp',['ui.bootstrap','dialogs']);
  module.controller('myController',function($scope,$http){
   $scope.total = $scope.mylist.length;     
   $scope.currentPage = 1;
   $scope.itemPerPage = 2;
   $scope.start = 0;

   $scope.setItems = function(n){
         $scope.itemPerPage = n;
   };
   // In case you can replace ($scope.currentPage - 1) * $scope.itemPerPage in <tr> by "start"
   $scope.pageChanged = function() {
        $scope.start = ($scope.currentPage - 1) * $scope.itemPerPage;
            };  
});
   //and our filter
     module.filter('offset', function() {
              return function(input, start) {
                start = parseInt(start, 10);
                return input.slice(start);
              };
            });     

Javascript - Track mouse position

What I think that he only wants to know the X/Y positions of cursor than why answer is that complicated.

_x000D_
_x000D_
// Getting 'Info' div in js hands_x000D_
var info = document.getElementById('info');_x000D_
_x000D_
// Creating function that will tell the position of cursor_x000D_
// PageX and PageY will getting position values and show them in P_x000D_
function tellPos(p){_x000D_
  info.innerHTML = 'Position X : ' + p.pageX + '<br />Position Y : ' + p.pageY;_x000D_
}_x000D_
addEventListener('mousemove', tellPos, false);
_x000D_
* {_x000D_
  padding: 0:_x000D_
  margin: 0;_x000D_
  /*transition: 0.2s all ease;*/_x000D_
  }_x000D_
#info {_x000D_
  position: absolute;_x000D_
  top: 10px;_x000D_
  right: 10px;_x000D_
  background-color: black;_x000D_
  color: white;_x000D_
  padding: 25px 50px;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
  _x000D_
  <body>_x000D_
    <div id='info'></div>_x000D_
        </body>_x000D_
  </html>
_x000D_
_x000D_
_x000D_

How to printf "unsigned long" in C?

For int %d

For long int %ld

For long long int %lld

For unsigned long long int %llu

How to do a HTTP HEAD request from the windows command line?

I'd download PuTTY and run a telnet session on port 80 to the webserver you want

HEAD /resource HTTP/1.1
Host: www.example.com

You could alternatively download Perl and try LWP's HEAD command. Or write your own script.

What does HTTP/1.1 302 mean exactly?

  • The code 302 indicates a temporary redirection.
  • One of the most notable features that differentiate it from a 301 redirect is that, in the case of 302 redirects, the strength of the SEO is not transferred to a new URL.
  • This is because this redirection has been designed to be used when there is a need to redirect content to a page that will not be the definitive one. Thus, once the redirection is eliminated, the original page will not have lost its positioning in the Google search engine.

EXAMPLE:- Although it is not very common that we find ourselves in need of a 302 redirect, this option can be very useful in some cases. These are the most frequent cases:

  • When we realize that there is some inappropriate content on a page. While we solve the problem, we can redirect the user to another page that may be of interest.
  • In the event that an attack on our website requires the restoration of any of the pages, this redirect can help us minimize the incidence.

A redirect 302 is a code that tells visitors of a specific URL that the page has been moved temporarily, directing them directly to the new location.

  • In other words, redirect 302 is activated when Google robots or other search engines request to load a specific page. At that moment, thanks to this redirection, the server returns an automatic response indicating a new URL.

  • In this way errors and annoyances are avoided both to search engines and users, guaranteeing smooth navigation.

For More details Refer this Article.

In Maven how to exclude resources from the generated jar?

Do you mean to property files located in src/main/resources? Then you should exclude them using the maven-resource-plugin. See the following page for details:

http://maven.apache.org/plugins/maven-resources-plugin/examples/include-exclude.html

from list of integers, get number closest to a given value

If we are not sure that the list is sorted, we could use the built-in min() function, to find the element which has the minimum distance from the specified number.

>>> min(myList, key=lambda x:abs(x-myNumber))
4

Note that it also works with dicts with int keys, like {1: "a", 2: "b"}. This method takes O(n) time.


If the list is already sorted, or you could pay the price of sorting the array once only, use the bisection method illustrated in @Lauritz's answer which only takes O(log n) time (note however checking if a list is already sorted is O(n) and sorting is O(n log n).)

Unable to connect to any of the specified mysql hosts. C# MySQL

Sometimes spacing and Order of parameters in connection string matters (based on personal experience and a long night :S)

So stick to the standard format here

Server=myServerAddress; Port=1234; Database=myDataBase; Uid=myUsername; Pwd=myPassword;

How to run multiple SQL commands in a single SQL connection?

I have not tested , but what the main idea is: put semicolon on each query.

SqlConnection connection = new SqlConnection();
SqlCommand command = new SqlCommand();
connection.ConnectionString = connectionString; // put your connection string
command.CommandText = @"
     update table
     set somecol = somevalue;
     insert into someTable values(1,'test');";
command.CommandType = CommandType.Text;
command.Connection = connection;

try
{
    connection.Open();
}
finally
{
    command.Dispose();
    connection.Dispose();
}

Update: you can follow Is it possible to have multiple SQL instructions in a ADO.NET Command.CommandText property? too

Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop

I suspect that the problem lies in the fact that you are calling your state setter immediately inside the function component body, which forces React to re-invoke your function again, with the same props, which ends up calling the state setter again, which triggers React to call your function again.... and so on.

const SingInContainer = ({ message, variant}) => {
    const [open, setSnackBarState] = useState(false);
    const handleClose = (reason) => {
        if (reason === 'clickaway') {
          return;
        }
        setSnackBarState(false)

      };

    if (variant) {
        setSnackBarState(true); // HERE BE DRAGONS
    }
    return (
        <div>
        <SnackBar
            open={open}
            handleClose={handleClose}
            variant={variant}
            message={message}
            />
        <SignInForm/>
        </div>
    )
}

Instead, I recommend you just conditionally set the default value for the state property using a ternary, so you end up with:

const SingInContainer = ({ message, variant}) => {
    const [open, setSnackBarState] = useState(variant ? true : false); 
                                  // or useState(!!variant); 
                                  // or useState(Boolean(variant));
    const handleClose = (reason) => {
        if (reason === 'clickaway') {
          return;
        }
        setSnackBarState(false)

      };

    return (
        <div>
        <SnackBar
            open={open}
            handleClose={handleClose}
            variant={variant}
            message={message}
            />
        <SignInForm/>
        </div>
    )
}

Comprehensive Demo

See this CodeSandbox.io demo for a comprehensive demo of it working, plus the broken component you had, and you can toggle between the two.

Converting Java file:// URL to File(...) path, platform independent, including UNC paths

For Java 8 the following method works:

  1. Form an URI from file URI string
  2. Create a file from the URI (not directly from URI string, absolute URI string are not paths)

Refer, below code snippet

    String fileURiString="file:///D:/etc/MySQL.txt";
    URI fileURI=new URI(fileURiString);
    File file=new File(fileURI);//File file=new File(fileURiString) - will generate exception

    FileInputStream fis=new FileInputStream(file);
    fis.close();

Output array to CSV in Ruby

Struggling with this myself. This is my take:

https://gist.github.com/2639448:

require 'csv'

class CSV
  def CSV.unparse array
    CSV.generate do |csv|
      array.each { |i| csv << i }
    end
  end
end

CSV.unparse [ %w(your array), %w(goes here) ]

How to add `style=display:"block"` to an element using jQuery?

$("#YourElementID").css("display","block");

Edit: or as dave thieben points out in his comment below, you can do this as well:

$("#YourElementID").css({ display: "block" });

Vagrant shared and synced folders

shared folders VS synced folders

Basically shared folders are renamed to synced folder from v1 to v2 (docs), under the bonnet it is still using vboxsf between host and guest (there is known performance issues if there are large numbers of files/directories).

Vagrantfile directory mounted as /vagrant in guest

Vagrant is mounting the current working directory (where Vagrantfile resides) as /vagrant in the guest, this is the default behaviour.

See docs

NOTE: By default, Vagrant will share your project directory (the directory with the Vagrantfile) to /vagrant.

You can disable this behaviour by adding cfg.vm.synced_folder ".", "/vagrant", disabled: true in your Vagrantfile.

Why synced folder is not working

Based on the output /tmp on host was NOT mounted during up time.

Use VAGRANT_INFO=debug vagrant up or VAGRANT_INFO=debug vagrant reload to start the VM for more output regarding why the synced folder is not mounted. Could be a permission issue (mode bits of /tmp on host should be drwxrwxrwt).

I did a test quick test using the following and it worked (I used opscode bento raring vagrant base box)

config.vm.synced_folder "/tmp", "/tmp/src"

output

$ vagrant reload
[default] Attempting graceful shutdown of VM...
[default] Setting the name of the VM...
[default] Clearing any previously set forwarded ports...
[default] Creating shared folders metadata...
[default] Clearing any previously set network interfaces...
[default] Available bridged network interfaces:
1) eth0
2) vmnet8
3) lxcbr0
4) vmnet1
What interface should the network bridge to? 1
[default] Preparing network interfaces based on configuration...
[default] Forwarding ports...
[default] -- 22 => 2222 (adapter 1)
[default] Running 'pre-boot' VM customizations...
[default] Booting VM...
[default] Waiting for VM to boot. This can take a few minutes.
[default] VM booted and ready for use!
[default] Configuring and enabling network interfaces...
[default] Mounting shared folders...
[default] -- /vagrant
[default] -- /tmp/src

Within the VM, you can see the mount info /tmp/src on /tmp/src type vboxsf (uid=900,gid=900,rw).

Java switch statement multiple cases

public class SwitchTest {
    public static void main(String[] args){
        for(int i = 0;i<10;i++){
            switch(i){
                case 1: case 2: case 3: case 4: //First case
                    System.out.println("First case");
                    break;
                case 8: case 9: //Second case
                    System.out.println("Second case");
                    break;
                default: //Default case
                    System.out.println("Default case");
                    break;
            }
        }
    }
}

Out:

Default case
First case
First case
First case
First case
Default case
Default case
Default case
Second case
Second case

Src: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html

Install a Nuget package in Visual Studio Code

You can do it easily using "vscode-nuget-package-manager". Go to the marketplace and install this. After That

1) Press Ctrl+P or Ctrl+Shift+P (and skip 2)

2) Type ">"

3) Then select "Nuget Package Manager:Add Package"

4) Enter package name Ex: Dapper

5) select package name and version

6) Done.

How can I declare dynamic String array in Java

no, there is no way to make array length dynamic in java. you can use ArrayList or other List implementations instead.

What is the difference between UTF-8 and ISO-8859-1?

UTF

UTF is a family of multi-byte encoding schemes that can represent Unicode code points which can be representative of up to 2^31 [roughly 2 billion] characters. UTF-8 is a flexible encoding system that uses between 1 and 4 bytes to represent the first 2^21 [roughly 2 million] code points.

Long story short: any character with a code point/ordinal representation below 127, aka 7-bit-safe ASCII is represented by the same 1-byte sequence as most other single-byte encodings. Any character with a code point above 127 is represented by a sequence of two or more bytes, with the particulars of the encoding best explained here.

ISO-8859

ISO-8859 is a family of single-byte encoding schemes used to represent alphabets that can be represented within the range of 127 to 255. These various alphabets are defined as "parts" in the format ISO-8859-n, the most familiar of these likely being ISO-8859-1 aka 'Latin-1'. As with UTF-8, 7-bit-safe ASCII remains unaffected regardless of the encoding family used.

The drawback to this encoding scheme is its inability to accommodate languages comprised of more than 128 symbols, or to safely display more than one family of symbols at one time. As well, ISO-8859 encodings have fallen out of favor with the rise of UTF. The ISO "Working Group" in charge of it having disbanded in 2004, leaving maintenance up to its parent subcommittee.

How to reference static assets within vue javascript

In order for Webpack to return the correct asset paths, you need to use require('./relative/path/to/file.jpg'), which will get processed by file-loader and returns the resolved URL.

computed: {
  iconUrl () {
    return require('./assets/img.png')
    // The path could be '../assets/img.png', etc., which depends on where your vue file is
  }
}

See VueJS templates - Handling Static Assets

HTML code for an apostrophe

If you are looking for single quote, it is

&#39;

why windows 7 task scheduler task fails with error 2147942667

This can happen for more than one reason. In my case this happened due to a permissions issue. The user that the task was running as didn't have permission to write to the logs directory so it failed with this error.

How do I conditionally apply CSS styles in AngularJS?

well i would suggest you to check condition in your controller with a function returning true or false .

<div class="week-wrap" ng-class="{today: getTodayForHighLight(todayDate, day.date)}">{{day.date}}</div>

and in your controller check the condition

$scope.getTodayForHighLight = function(today, date){
    return (today == date);
}

How can I get the line number which threw exception?

Check this one

StackTrace st = new StackTrace(ex, true);
//Get the first stack frame
StackFrame frame = st.GetFrame(0);

//Get the file name
string fileName = frame.GetFileName();

//Get the method name
string methodName = frame.GetMethod().Name;

//Get the line number from the stack frame
int line = frame.GetFileLineNumber();

//Get the column number
int col = frame.GetFileColumnNumber();

Command to close an application of console?

return; will exit a method in C#.

See code snippet below

using System;

namespace Exercise_strings
{
    class Program
    {
        static void Main(string[] args)
        {
           Console.WriteLine("Input string separated by -");

            var stringInput = Console.ReadLine();

            if (string.IsNullOrWhiteSpace(stringInput))
            {
                Console.WriteLine("Nothing entered");
                return;
            }
}

So in this case if a user enters a null string or whitespace, the use of the return method terminates the Main method elegantly.

A network-related or instance-specific error occurred while establishing a connection to SQL Server

Sql Server fire this error when your application don't have enough rights to access the database. there are several reason about this error . To fix this error you should follow the following instruction.

  1. Try to connect sql server from your server using management studio . if you use windows authentication to connect sql server then set your application pool identity to server administrator .

  2. if you use sql server authentication then check you connection string in web.config of your web application and set user id and password of sql server which allows you to log in .

  3. if your database in other server(access remote database) then first of enable remote access of sql server form sql server property from sql server management studio and enable TCP/IP form sql server configuration manager .

  4. after doing all these stuff and you still can't access the database then check firewall of server form where you are trying to access the database and add one rule in firewall to enable port of sql server(by default sql server use 1433 , to check port of sql server you need to check sql server configuration manager network protocol TCP/IP port).

  5. if your sql server is running on named instance then you need to write port number with sql serer name for example 117.312.21.21/nameofsqlserver,1433.

  6. If you are using cloud hosting like amazon aws or microsoft azure then server or instance will running behind cloud firewall so you need to enable 1433 port in cloud firewall if you have default instance or specific port for sql server for named instance.

  7. If you are using amazon RDS or SQL azure then you need to enable port from security group of that instance.

  8. If you are accessing sql server through sql server authentication mode them make sure you enabled "SQL Server and Windows Authentication Mode" sql server instance property. enter image description here

    1. Restart your sql server instance after making any changes in property as some changes will require restart.

if you further face any difficulty then you need to provide more information about your web site and sql server .

Anaconda vs. miniconda

The difference is that miniconda is just shipping the repository management system. So when you install it there is just the management system without packages. Whereas with Anaconda, it is like a distribution with some built in packages.

Like with any Linux distribution, there are some releases which bundles lots of updates for the included packages. That is why there is a difference in version numbering. If you only decide to upgrade Anaconda, you are updating a whole system.

Writing an input integer into a cell

You can use the Range object in VBA to set the value of a named cell, just like any other cell.

Range("C1").Value = Inputbox("Which job number would you like to add to the list?)

Where "C1" is the name of the cell you want to update.

My Excel VBA is a little bit old and crusty, so there may be a better way to do this in newer versions of Excel.

Python csv string to array

You can convert a string to a file object using io.StringIO and then pass that to the csv module:

from io import StringIO
import csv

scsv = """text,with,Polish,non-Latin,letters
1,2,3,4,5,6
a,b,c,d,e,f
ges,zólty,waz,idzie,waska,drózka,
"""

f = StringIO(scsv)
reader = csv.reader(f, delimiter=',')
for row in reader:
    print('\t'.join(row))

simpler version with split() on newlines:

reader = csv.reader(scsv.split('\n'), delimiter=',')
for row in reader:
    print('\t'.join(row))

Or you can simply split() this string into lines using \n as separator, and then split() each line into values, but this way you must be aware of quoting, so using csv module is preferred.

On Python 2 you have to import StringIO as

from StringIO import StringIO

instead.

CSS hexadecimal RGBA?

I found the answer after posting the enhancement to the question. Sorry!

MS Excel helped!

simply add the Hex prefix to the hex colour value to add an alpha that has the equivalent opacity as the % value.

(in rbga the percentage opacity is expressed as a decimal as mentioned above)

Opacity %   255 Step        2 digit HEX prefix
0%          0.00            00
5%          12.75           0C
10%         25.50           19
15%         38.25           26
20%         51.00           33
25%         63.75           3F
30%         76.50           4C
35%         89.25           59
40%         102.00          66
45%         114.75          72
50%         127.50          7F
55%         140.25          8C
60%         153.00          99
65%         165.75          A5
70%         178.50          B2
75%         191.25          BF
80%         204.00          CC
85%         216.75          D8
90%         229.50          E5
95%         242.25          F2
100%        255.00          FF

Android studio doesn't list my phone under "Choose Device"

I face Same problem. In my case i solved this by following some steps.

  1. click attached debugger to android process (It located In android tools inside run button)

  2. if see adb not responding error dialog. then click restart of dialogue button.

  3. Now you can see which device is connected. now close this window.

  4. again press run button. Now you find your targeted device or emulator which is connected.

Hopefully it helps you.

java.sql.SQLException: Exhausted Resultset

This occurs typically when the stmt is reused butexpecting a different ResultSet, try creting a new stmt and executeQuery. It fixed it for me!

Selecting the last value of a column

The answer

$ =INDEX(G2:G; COUNT(G2:G))

doesn't work correctly in LibreOffice. However, with a small change, it works perfectly.

$ =INDEX(G2:G100000; COUNT(G2:G100000))

It always works only if the true range is smaller than (G2:G10000)

Replace missing values with column mean

# Lets say I have a dataframe , df as following -
df <- data.frame(a=c(2,3,4,NA,5,NA),b=c(1,2,3,4,NA,NA))

# create a custom function
fillNAwithMean <- function(x){
    na_index <- which(is.na(x))        
    mean_x <- mean(x, na.rm=T)
    x[na_index] <- mean_x
    return(x)
}

(df <- apply(df,2,fillNAwithMean))
   a   b
2.0 1.0
3.0 2.0
4.0 3.0
3.5 4.0
5.0 2.5
3.5 2.5

Extending the User model with custom fields in Django

This is what i do and it's in my opinion simplest way to do this. define an object manager for your new customized model then define your model.

from django.db import models
from django.contrib.auth.models import PermissionsMixin, AbstractBaseUser, BaseUserManager

class User_manager(BaseUserManager):
    def create_user(self, username, email, gender, nickname, password):
        email = self.normalize_email(email)
        user = self.model(username=username, email=email, gender=gender, nickname=nickname)
        user.set_password(password)
        user.save(using=self.db)
        return user

    def create_superuser(self, username, email, gender, password, nickname=None):
        user = self.create_user(username=username, email=email, gender=gender, nickname=nickname, password=password)
        user.is_superuser = True
        user.is_staff = True
        user.save()
        return user



  class User(PermissionsMixin, AbstractBaseUser):
    username = models.CharField(max_length=32, unique=True, )
    email = models.EmailField(max_length=32)
    gender_choices = [("M", "Male"), ("F", "Female"), ("O", "Others")]
    gender = models.CharField(choices=gender_choices, default="M", max_length=1)
    nickname = models.CharField(max_length=32, blank=True, null=True)

    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    REQUIRED_FIELDS = ["email", "gender"]
    USERNAME_FIELD = "username"
    objects = User_manager()

    def __str__(self):
        return self.username

Dont forget to add this line of code in your settings.py:

AUTH_USER_MODEL = 'YourApp.User'

This is what i do and it always works.

How do I check for a network connection?

You can check for a network connection in .NET 2.0 using GetIsNetworkAvailable():

System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()

To monitor changes in IP address or changes in network availability use the events from the NetworkChange class:

System.Net.NetworkInformation.NetworkChange.NetworkAvailabilityChanged
System.Net.NetworkInformation.NetworkChange.NetworkAddressChanged

Remove CSS class from element with JavaScript (no jQuery)

The right and standard way to do it is using classList. It is now widely supported in the latest version of most modern browsers:

ELEMENT.classList.remove("CLASS_NAME");

_x000D_
_x000D_
remove.onclick = () => {_x000D_
  const el = document.querySelector('#el');_x000D_
  if (el.classList.contains("red")) {_x000D_
    el.classList.remove("red");_x000D_
_x000D_
  }_x000D_
}
_x000D_
.red {_x000D_
  background: red_x000D_
}
_x000D_
<div id='el' class="red"> Test</div>_x000D_
<button id='remove'>Remove Class</button>
_x000D_
_x000D_
_x000D_

Documentation: https://developer.mozilla.org/en/DOM/element.classList

Get loop counter/index using for…of syntax in JavaScript

Solution for small array collections:

for (var obj in arr) {
    var i = Object.keys(arr).indexOf(obj);
}

arr - ARRAY, obj - KEY of current element, i - COUNTER/INDEX

Notice: Method keys() is not available for IE version <9, you should use Polyfill code. https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

How to send data in request body with a GET when using jQuery $.ajax()

In general, that's not how systems use GET requests. So, it will be hard to get your libraries to play along. In fact, the spec says that "If the request method is a case-sensitive match for GET or HEAD act as if data is null." So, I think you are out of luck unless the browser you are using doesn't respect that part of the spec.

You can probably setup an endpoint on your own server for a POST ajax request, then redirect that in your server code to a GET request with a body.

If you aren't absolutely tied to GET requests with the body being the data, you have two options.

POST with data: This is probably what you want. If you are passing data along, that probably means you are modifying some model or performing some action on the server. These types of actions are typically done with POST requests.

GET with query string data: You can convert your data to query string parameters and pass them along to the server that way.

url: 'somesite.com/models/thing?ids=1,2,3'

Get the current cell in Excel VB

The keyword "Selection" is already a vba Range object so you can use it directly, and you don't have to select cells to copy, for example you can be on Sheet1 and issue these commands:

ThisWorkbook.worksheets("sheet2").Range("namedRange_or_address").Copy
ThisWorkbook.worksheets("sheet1").Range("namedRange_or_address").Paste

If it is a multiple selection you should use the Area object in a for loop:

Dim a as Range
For Each a in ActiveSheet.Selection.Areas
    a.Copy
    ThisWorkbook.worksheets("sheet2").Range("A1").Paste
Next

Regards

Thomas

Refreshing page on click of a button

I'd suggest <a href='page1.jsp'>Refresh</a>.

Is there a date format to display the day of the week in java?

tl;dr

LocalDate.of( 2018 , Month.JANUARY , 23 )
         .format( DateTimeFormatter.ofPattern( “uuuu-MM-EEE” , Locale.US )  )

java.time

The modern approach uses the java.time classes.

LocalDate ld = LocalDate.of( 2018 , Month.JANUARY , 23 ) ;

Note how we specify a Locale such as Locale.CANADA_FRENCH to determine the human language used to translate the name of the day.

DateTimeFormatter f = DateTimeFormatter.ofPattern( “uuuu-MM-EEE” , Locale.US ) ;
String output = ld.format( f ) ;

ISO 8601

By the way, you may be interested in the standard ISO 8601 week numbering scheme: yyyy-Www-d.

2018-W01-2

Week # 1 has the first Thursday of the calendar-year. Week starts on a Monday. A year has either 52 or 53 weeks. The last/first few days of a calendar-year may land in the next/previous week-based-year.

The single digit on the end is day-of-week, 1-7 for Monday-Sunday.

Add the ThreeTen-Extra library class to your project for the YearWeek class.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

How to force R to use a specified factor level as reference in a regression?

You can also manually tag the column with a contrasts attribute, which seems to be respected by the regression functions:

contrasts(df$factorcol) <- contr.treatment(levels(df$factorcol),
   base=which(levels(df$factorcol) == 'RefLevel'))

How to randomly pick an element from an array

Take a look at this question:

How do I generate random integers within a specific range in Java?

You will want to generate a random number from 0 to your integers length - 1. Then simply get your int from your array:

myArray[myRandomNumber];

Error: Could not find or load main class in intelliJ IDE

Check your class module : I have encountered this problem with intellij : I have a maven multi-module project, the problem is that i runing a class which not exist the module within the configuration, so my problem is fixed by setting the right module ("edit configuration" -> "use class of module")

may this help you

Difference between array_map, array_walk and array_filter

From the documentation,

bool array_walk ( array &$array , callback $funcname [, mixed $userdata ] ) <-return bool

array_walk takes an array and a function F and modifies it by replacing every element x with F(x).

array array_map ( callback $callback , array $arr1 [, array $... ] )<-return array

array_map does the exact same thing except that instead of modifying in-place it will return a new array with the transformed elements.

array array_filter ( array $input [, callback $callback ] )<-return array

array_filter with function F, instead of transforming the elements, will remove any elements for which F(x) is not true

Read .doc file with python

The answer from Shivam Kotwalia works perfectly. However, the object is imported as a byte type. Sometimes you may need it as a string for performing REGEX or something like that.

I recommend the following code (two lines from Shivam Kotwalia's answer) :

import textract

text = textract.process("path/to/file.extension")
text = text.decode("utf-8") 

The last line will convert the object text to a string.

Android Stop Emulator from Command Line

To stop all running emulators we use this command:

adb devices | grep emulator | cut -f1 | while read line; do adb -s $line emu kill; done

How to force a WPF binding to refresh?

I was fetching data from backend and updated the screen with just one line of code. It worked. Not sure, why we need to implement Interface. (windows 10, UWP)

    private void populateInCurrentScreen()
    {
        (this.FindName("Dets") as Grid).Visibility = Visibility.Visible;
        this.Bindings.Update();
    }

Simple search MySQL database using php

You need to use $_POST not $_post.

Fatal error: Class 'Illuminate\Foundation\Application' not found

I can't imagine that anyone else reading this is a stupid as I was but just in case... I had accidentally removed "laravel/framework": "^5.6" from my composer.json when resolving merge conflicts.

How, in general, does Node.js handle 10,000 concurrent requests?

Single Threaded Event Loop Model Processing Steps:

  • Clients Send request to Web Server.

  • Node JS Web Server internally maintains a Limited Thread pool to provide services to the Client Requests.

  • Node JS Web Server receives those requests and places them into a Queue. It is known as “Event Queue”.

  • Node JS Web Server internally has a Component, known as “Event Loop”. Why it got this name is that it uses indefinite loop to receive requests and process them.

  • Event Loop uses Single Thread only. It is main heart of Node JS Platform Processing Model.

  • Event Loop checks any Client Request is placed in Event Queue. If not then wait for incoming requests for indefinitely.

  • If yes, then pick up one Client Request from Event Queue

    1. Starts process that Client Request
    2. If that Client Request Does Not requires any Blocking IO Operations, then process everything, prepare response and send it back to client.
    3. If that Client Request requires some Blocking IO Operations like interacting with Database, File System, External Services then it will follow different approach
  • Checks Threads availability from Internal Thread Pool
  • Picks up one Thread and assign this Client Request to that thread.
  • That Thread is responsible for taking that request, process it, perform Blocking IO operations, prepare response and send it back to the Event Loop

    very nicely explained by @Rambabu Posa for more explanation go throw this Link

Laravel 5 How to switch from Production mode

Laravel 5 uses .env file to configure your app. .env should not be committed on your repository, like github or bitbucket. On your local environment your .env will look like the following:

# .env
APP_ENV=local

For your production server, you might have the following config:

# .env
APP_ENV=production

error C2220: warning treated as error - no 'object' file generated

The error says that a warning was treated as an error, therefore your problem is a warning message! The object file is then not created because there was an error. So you need to check your warnings and fix them.

In case you don't know how to find them: Open the Error List (View > Error List) and click on Warning.

Stop embedded youtube iframe?

How we Pause/stop YouTube iframe to when we use embed videos in modalpopup

 $('#close_one').click(function (e) {
         
         
         let link = document.querySelector('.divclass');// get iframe class 
         let link = document.querySelector('#divid');// get iframe id
         let video_src = link.getAttribute('src');

         $('.youtube-video').children('iframe').attr('src', ''); // set iframe parent div value null 
         $('.youtube-video').children('iframe').attr('src', video_src);// set iframe src again it works perfect

     });

Init method in Spring Controller (annotation version)

You can use

@PostConstruct
public void init() {
   // ...
}

What is the best way to remove a table row with jQuery?

$('#myTable tr').click(function(){
    $(this).remove();
    return false;
});

Even a better one

$("#MyTable").on("click", "#DeleteButton", function() {
   $(this).closest("tr").remove();
});

How do I handle a click anywhere in the page, even when a certain element stops the propagation?

You could use jQuery to add an event listener on the document DOM.

_x000D_
_x000D_
    $(document).on("click", function () {_x000D_
        console.log('clicked');_x000D_
    });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

How to log as much information as possible for a Java Exception?

You can also use Apache's ExceptionUtils.

Example:

import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.log4j.Logger;


public class Test {

    static Logger logger = Logger.getLogger(Test.class);

    public static void main(String[] args) {

        try{
            String[] avengers = null;
            System.out.println("Size: "+avengers.length);
        } catch (NullPointerException e){
            logger.info(ExceptionUtils.getFullStackTrace(e));
        }
    }

}

Console output:

java.lang.NullPointerException
    at com.aimlessfist.avengers.ironman.Test.main(Test.java:11)

Multiline editing in Visual Studio Code

Solved using just two steps!

  1. Ctrl + F

  2. Alt + Enter

It's equal to Sublime Text's Alt + F3.

Enter image description here

Refresh a page using PHP

You can do it with PHP:

header("Refresh:0");

It refreshes your current page, and if you need to redirect it to another page, use following:

header("Refresh:0; url=page2.php");

Tkinter example code for multiple windows, why won't buttons load correctly?

What you could do is copy the code from tkinter.py into a file called mytkinter.py, then do this code:

import tkinter, mytkinter
root = tkinter.Tk()
window = mytkinter.Tk()
button = mytkinter.Button(window, text="Search", width = 7,
                               command=cmd)
button2 = tkinter.Button(root, text="Search", width = 7,
                               command=cmdtwo)

And you have two windows which don't collide!