Programs & Examples On #Mss

PYODBC--Data source name not found and no default driver specified

Do not put a space after the Driver keyword in the connection string.

This fails on Windows ...

conn_str = (
    r'DRIVER = {SQL Server};'
    r'SERVER=(local)\SQLEXPRESS;'
    r'DATABASE=myDb;'
    r'Trusted_Connection=yes;'
)
cnxn = pyodbc.connect(conn_str)

... but this works:

conn_str = (
    r'DRIVER={SQL Server};'
    r'SERVER=(local)\SQLEXPRESS;'
    r'DATABASE=myDb;'
    r'Trusted_Connection=yes;'
)
cnxn = pyodbc.connect(conn_str)

Unable to create migrations after upgrading to ASP.NET Core 2.0

Previously, you configured the seed data in the Configure method in Startup.cs. It is now recommended that you use the Configure method only to set up the request pipeline. Application startup code belongs in the Main method.

The refactored Main method. Add the following references to the Program.cs:

using Microsoft.Extensions.DependencyInjection;

using MyProject.MyDbContextFolder;

_x000D_
_x000D_
public static void Main(string[] args)_x000D_
{_x000D_
    var host = BuildWebHost(args);_x000D_
_x000D_
    using (var scope = host.Services.CreateScope())_x000D_
    {_x000D_
        var services = scope.ServiceProvider;_x000D_
        try_x000D_
        {_x000D_
            var context = services.GetRequiredService<MyDbConext>();_x000D_
            DbInitializer.Initialize(context);_x000D_
        }_x000D_
        catch (Exception ex)_x000D_
        {_x000D_
            var logger = services.GetRequiredService<ILogger<Program>>();_x000D_
            logger.LogError(ex, "An error occurred while seeding the database.");_x000D_
        }_x000D_
    }_x000D_
_x000D_
    host.Run();_x000D_
}
_x000D_
_x000D_
_x000D_

iOS 11, 12, and 13 installed certificates not trusted automatically (self signed)

I've been struggling with this for 3 days now while attempting to connect to a local API running Laravel valet. I finally figured it out. In my case I had to drag and drop over the LaravelValetCASelfSigned.pem file from ~/.config/valet/CA/LaravelValetCASelfSigned.pem

After verifying the installing within the simulator I had to go to Settings > About > Certificate Trust Settings > and Enable the Laravel Valet VA Self Signed CN

Finally working!!!

Error: the entity type requires a primary key

Yet another reason may be that your entity class has several properties named somhow /.*id/i - so ending with ID case insensitive AND elementary type AND there is no [Key] attribute.

EF will namely try to figure out the PK by itself by looking for elementary typed properties ending in ID.

See my case:

public class MyTest, IMustHaveTenant
{
  public long Id { get; set; }
  public int TenantId { get; set; }
  [MaxLength(32)]
  public virtual string Signum{ get; set; }
  public virtual string ID { get; set; }
  public virtual string ID_Other { get; set; }
}

don't ask - lecacy code. The Id was even inherited, so I could not use [Key] (just simplifying the code here)

But here EF is totally confused.

What helped was using modelbuilder this in DBContext class.

            modelBuilder.Entity<MyTest>(f =>
            {
                f.HasKey(e => e.Id);
                f.HasIndex(e => new { e.TenantId });
                f.HasIndex(e => new { e.TenantId, e.ID_Other });
            });

the index on PK is implicit.

Specifying Font and Size in HTML table

This worked for me and also worked with bootstrap tables

<style>
    .table td, .table th {
        font-size: 10px;
    }
</style>

ASP.NET Core Dependency Injection error: Unable to resolve service for type while attempting to activate

In my case I was trying to do dependency injection for an object which required constructor arguments. In this case, during Startup I just provided the arguments from the configuration file, for example:

var config = Configuration.GetSection("subservice").Get<SubServiceConfig>();
services.AddScoped<ISubService>(provider => new SubService(config.value1, config.value2));

Reactive forms - disabled attribute

this.form.disable()
this.form.enable()

For one formcontrol makes disable

this.form.get('first').disable()
this.form.get('first').enable()

Or initial set method.

first: new FormControl({disabled: true}, Validators.required)

'Microsoft.ACE.OLEDB.16.0' provider is not registered on the local machine. (System.Data)

If you have OS(64bit) and SSMS(64bit) and already install the AccessDatabaseEngine(64bit) and you still received an error, try this following solutions:

1: direct opening the sql server import and export wizard.

if you able to connect using direct sql server import and export wizard, then importing from SSMS is the issue, it's like activating 32bit if you import data from SSMS.

Instead of installing AccessDatabaseEngine(64bit) , try to use the AccessDatabaseEngine(32bit) , upon installation, windows will stop you for continuing the installation if you already have another app installed , if so , then use the following steps. This is from the MICROSOFT. The Quiet Installation.

If Office 365 is already installed, side by side detection will prevent the installation from proceeding. Instead perform a /quiet install of these components from command line. To do so, download the desired AccessDatabaseEngine.exe or AccessDatabaeEngine_x64.exe to your PC, open an administrative command prompt, and provide the installation path and switch Ex: C:\Files\AccessDatabaseEngine.exe /quiet

or check in the Addition Information content from the link below,

https://www.microsoft.com/en-us/download/details.aspx?id=54920

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

C++ programs are translated to assembly programs during the generation of machine code from the source code. It would be virtually wrong to say assembly is slower than C++. Moreover, the binary code generated differs from compiler to compiler. So a smart C++ compiler may produce binary code more optimal and efficient than a dumb assembler's code.

However I believe your profiling methodology has certain flaws. The following are general guidelines for profiling:

  1. Make sure your system is in its normal/idle state. Stop all running processes (applications) that you started or that use CPU intensively (or poll over the network).
  2. Your datasize must be greater in size.
  3. Your test must run for something more than 5-10 seconds.
  4. Do not rely on just one sample. Perform your test N times. Collect results and calculate the mean or median of the result.

How to read connection string in .NET Core?

The posted answer is fine but didn't directly answer the same question I had about reading in a connection string. Through much searching I found a slightly simpler way of doing this.

In Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    ...
    // Add the whole configuration object here.
    services.AddSingleton<IConfiguration>(Configuration);
}

In your controller add a field for the configuration and a parameter for it on a constructor

private readonly IConfiguration configuration;

public HomeController(IConfiguration config) 
{
    configuration = config;
}

Now later in your view code you can access it like:

connectionString = configuration.GetConnectionString("DefaultConnection");

Get current index from foreach loop

You have two options here, 1. Use for instead for foreach for iteration.But in your case the collection is IEnumerable and the upper limit of the collection is unknown so foreach will be the best option. so i prefer to use another integer variable to hold the iteration count: here is the code for that:

int i = 0; // for index
foreach (var row in list)
{
    bool IsChecked;// assign value to this variable
    if (IsChecked)
    {    
       // use i value here                
    }
    i++; // will increment i in each iteration
}

Map<String, String>, how to print both the "key string" and "value string" together

There are various ways to achieve this. Here are three.

    Map<String, String> map = new HashMap<String, String>();
    map.put("key1", "value1");
    map.put("key2", "value2");
    map.put("key3", "value3");

    System.out.println("using entrySet and toString");
    for (Entry<String, String> entry : map.entrySet()) {
        System.out.println(entry);
    }
    System.out.println();

    System.out.println("using entrySet and manual string creation");
    for (Entry<String, String> entry : map.entrySet()) {
        System.out.println(entry.getKey() + "=" + entry.getValue());
    }
    System.out.println();

    System.out.println("using keySet");
    for (String key : map.keySet()) {
        System.out.println(key + "=" + map.get(key));
    }
    System.out.println();

Output

using entrySet and toString
key1=value1
key2=value2
key3=value3

using entrySet and manual string creation
key1=value1
key2=value2
key3=value3

using keySet
key1=value1
key2=value2
key3=value3

java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient

In my case, I stopped my docker hive container and run it again and finally, it worked. Hope it will be useful for someone.

Note: This might be caused because there might be an instance running in the background so stopping the container will stop all background instances.

A connection was successfully established with the server, but then an error occurred during the login process. (Error Number: 233)

I had to do 2 things: Do what Joseph Wu said and change the authentication to be SQL and Windows. But I also had to go to Server Properties > Advanced and change "Enable Contained Databases" to True.

There is no argument given that corresponds to the required formal parameter - .NET Error

I got the same error but it was due to me not creating a default constructor. If you haven't already tried that, create the default constructor like this:

public TestClass() {

}

How to add LocalDB to Visual Studio 2015 Community's SQL Server Object Explorer?

To check if LocalDb is installed or not:

  • run cmd and type in sqllocaldb i this should give you the installed sqllocaldb instances if found.
  • Run SSMS (SQL Server Management Studio).
  • Try to connect to this instance (localdb)\V11.0 using windows authentication.

If an error is raised Cannot connect to (localdb)\V11.0. change the instance name to (localdb)\MSSQLLocalDB and try again to connect, if you still get the same error.

Follow these steps to install LocalDb:

  • Close SSMS.
  • Close VS (Visual Studio) if it's running.
  • Go to Start Menu and type in search sqlLocalDb.
  • From the results that appears choose sqlLocalDb.msi and click it.
  • SQL setup will start to install LocalDB

after finishing the installation re-run SSMS and try connecting to either of the instances (localdb)\V11.0 or (localdb)\MSSQLLocalDB, one of it should work depending on what Visual Studio version you have.

You can also verify that localdb is installed using Visual Studio by simply creating new sql file and go to the connect icon on the top header of the file which by default lists all the servers you can connect to including localdb if installed.

In addition to the above mentioned ways of finding if localdb is installed, you can also use the MS windows power shell or windows command processor CMD or even NuGet package manager console on your server machine and run these commands sqllocaldb i and sqllocaldb v that will show you the localdb name if it is installed and the MSSQL server version installed and running on your machine.

The target principal name is incorrect. Cannot generate SSPI context

In my case, the problem was setting up DNS on the wifi. I removed the settings, and left them empty, and worked.

Como ficou minha configuração do DNS

Slack URL to open a channel from browser

The URI to open a specific channel in Slack app is:

slack://channel?id=<CHANNEL-ID>&team=<TEAM-ID>

You will probably need these resources of the Slack API to get IDs of your team and channel:

Here's the full documentation from Slack

How to view the roles and permissions granted to any database user in Azure SQL server instance?

Per the MSDN documentation for sys.database_permissions, this query lists all permissions explicitly granted or denied to principals in the database you're connected to:

SELECT DISTINCT pr.principal_id, pr.name, pr.type_desc, 
    pr.authentication_type_desc, pe.state_desc, pe.permission_name
FROM sys.database_principals AS pr
JOIN sys.database_permissions AS pe
    ON pe.grantee_principal_id = pr.principal_id;

Per Managing Databases and Logins in Azure SQL Database, the loginmanager and dbmanager roles are the two server-level security roles available in Azure SQL Database. The loginmanager role has permission to create logins, and the dbmanager role has permission to create databases. You can view which users belong to these roles by using the query you have above against the master database. You can also determine the role memberships of users on each of your user databases by using the same query (minus the filter predicate) while connected to them.

MSSQL Regular expression

As above the question was originally about MySQL

Use REGEXP, not LIKE:

SELECT * FROM `table` WHERE ([url] NOT REGEXP '^[-A-Za-z0-9/.]+$')

No process is on the other end of the pipe (SQL Server 2012)

make sure that you have specified user in Security-> Logins, if no - add it and try again.

The OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)"

This is for my reference, as I encountered a variety of SQL error messages while trying to connect with provider. Other answers prescribe "try this, then this, then this". I appreciate the other answers, but I like to pair specific solutions with specific problems


Error

...provider did not give information...Cannot initialize data source object...

Error Numbers

7399, 7303

Error Detail

Msg 7399, Level 16, State 1, Line 2 The OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" reported an error. 
  The provider did not give any information about the error. 
Msg 7303, Level 16, State 1, Line 2 Cannot initialize the data source object
  of OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)".

Solution

File was open. Close it.

Credit


Error

Access denied...Cannot get the column information...

Error Numbers

7399, 7350

Error Detail

Msg 7399, Level 16, State 1, Line 2 The OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" reported an error. 
  Access denied.
Msg 7350, Level 16, State 2, Line 2 Cannot get the column information 
  from OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)".

Solution

Give access

Credit


Error

No value given for one or more required parameters....Cannot execute the query ...

Error Numbers

???, 7320

Error Detail

OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" returned message "No value given for one or more required parameters.".
Msg 7320, Level 16, State 2, Line 2
Cannot execute the query "select [Col A], [Col A] FROM $Sheet" against OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)". 

Solution

Column names might be wrong. Do [Col A] and [Col B] actually exist in your spreadsheet?


Error

"Unspecified error"...Cannot initialize data source object...

Error Numbers

???, 7303

Error Detail

OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" returned message "Unspecified error".
Msg 7303, Level 16, State 1, Line 2 Cannot initialize the data source object of OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)".

Solution

Run SSMS as admin. See this question.


Other References

Other answers which suggest modifying properties. Not sure how modifying these two properties (checking them or unchecking them) would help.

Laravel: Error [PDOException]: Could not Find Driver in PostgreSQL

In Windows 8 PC with Laragon 3.4.0 180809, I faced the same issue. It happened in my case because I updated Laragon and it added a new version of PHP. So in laragon/bin/php/ I actually had two directories:

  • php-7.1.20-Win32-VC14-x64
  • php-7.1.7-Win32-VC14-x64

I added 7.1.20 into my PATH variable. But in my Command Console, running php --ini was showing that the path actually was fetching from the older one: php-7.1.7-Win32-VC14-x64. So I deleted the old one (for safety, I put it in Recycle Bin). But Laragon failed to start after that.

So, in laragaon/etc/apache2/mod_php.conf, I changed the path to the latest PHP version. Then restarted Laragon and the issue is resolved.

Reference: How to add another PHP version - Laragon Forum

SQL Server Service not available in service list after installation of SQL Server Management Studio

downloaded Sql server management 2008 r2 and got it installed. Its getting installed but when I try to connect it via .\SQLEXPRESS it shows error. DO I need to install any SQL service on my system?

You installed management studio which is just a management interface to SQL Server. If you didn't (which is what it seems like) already have SQL Server installed, you'll need to install it in order to have it on your system and use it.

http://www.microsoft.com/en-us/download/details.aspx?id=1695

How to Convert datetime value to yyyymmddhhmmss in SQL server?

also this works too

SELECT replace(replace(replace(convert(varchar, getdate(), 120),':',''),'-',''),' ','')

Call asynchronous method in constructor?

I'd like to share a pattern that I've been using to solve these kinds of problems. It works rather well I think. Of course, it only works if you have control over what calls the constructor. Example below

public class MyClass
{
    public static async Task<MyClass> Create()
    {
        var myClass = new MyClass();
        await myClass.Initialize();
        return myClass;
    }

    private MyClass()
    {

    }

    private async Task Initialize()
    {
        await Task.Delay(1000); // Do whatever asynchronous work you need to do
    }
}

Basicly what we do is we make the constructor private and make our own public static async method that is responsible for creating an instance of MyClass. By making the constructor private and keeping the static method within the same class we have made sure that noone could "accidently" create an instance of this class without calling the proper initialization methods. All the logic around the creation of the object is still contained within the class (just within a static method).

var myClass1 = new MyClass() // Cannot be done, the constructor is private
var myClass2 = MyClass.Create() // Returns a Task that promises an instance of MyClass once it's finished
var myClass3 = await MyClass.Create() // asynchronously creates and initializes an instance of MyClass

Implemented on the current scenario it would look something like:

public partial class Page2 : PhoneApplicationPage
{
    public static async Task<Page2> Create()
    {
        var page = new Page2();
        await page.getWritings();
        return page;
    }

    List<Writing> writings;

    private Page2()
    {
        InitializeComponent();
    }

    private async Task getWritings()
    {
        string jsonData = await JsonDataManager.GetJsonAsync("1");
        JObject obj = JObject.Parse(jsonData);
        JArray array = (JArray)obj["posts"];

        for (int i = 0; i < array.Count; i++)
        {
            Writing writing = new Writing();
            writing.content = JsonDataManager.JsonParse(array, i, "content");
            writing.date = JsonDataManager.JsonParse(array, i, "date");
            writing.image = JsonDataManager.JsonParse(array, i, "url");
            writing.summary = JsonDataManager.JsonParse(array, i, "excerpt");
            writing.title = JsonDataManager.JsonParse(array, i, "title");

            writings.Add(writing);
        }

        myLongList.ItemsSource = writings;
    }
}

And instead of doing

var page = new Page2();

You would be doing

var page = await Page2.Create();

Android difference between Two Dates

I arranged a little. This works great.

@SuppressLint("SimpleDateFormat") SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd MM yyyy");
    Date date = new Date();
    String dateOfDay = simpleDateFormat.format(date);

    String timeofday = android.text.format.DateFormat.format("HH:mm:ss", new Date().getTime()).toString();

    @SuppressLint("SimpleDateFormat") SimpleDateFormat dateFormat = new SimpleDateFormat("dd MM yyyy hh:mm:ss");
    try {
        Date date1 = dateFormat.parse(06 09 2018 + " " + 10:12:56);
        Date date2 = dateFormat.parse(dateOfDay + " " + timeofday);

        printDifference(date1, date2);

    } catch (ParseException e) {
        e.printStackTrace();
    }

@SuppressLint("SetTextI18n")
private void printDifference(Date startDate, Date endDate) {
    //milliseconds
    long different = endDate.getTime() - startDate.getTime();

    long secondsInMilli = 1000;
    long minutesInMilli = secondsInMilli * 60;
    long hoursInMilli = minutesInMilli * 60;
    long daysInMilli = hoursInMilli * 24;

    long elapsedDays = different / daysInMilli;
    different = different % daysInMilli;

    long elapsedHours = different / hoursInMilli;
    different = different % hoursInMilli;

    long elapsedMinutes = different / minutesInMilli;
    different = different % minutesInMilli;

    long elapsedSeconds = different / secondsInMilli;

Toast.makeText(context, elapsedDays + " " + elapsedHours + " " + elapsedMinutes + " " + elapsedSeconds, Toast.LENGTH_SHORT).show();
}

How to get correct timestamp in C#

internal static string UnixToDate(int Timestamp, string ConvertFormat)
{
    DateTime ConvertedUnixTime = DateTimeOffset.FromUnixTimeSeconds(Timestamp).DateTime;
    return ConvertedUnixTime.ToString(ConvertFormat);
}

int Timestamp = (int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;

Usage:

UnixToDate(1607013172, "HH:mm:ss"); // Output 16:32:52
Timestamp; // Output 1607013172

How to bind DataTable to Datagrid

In cs file:

    private DataTable _dataTable;

    public DataTable DataTable
    {
        get { return _dataTable; }
        set { _dataTable = value; }
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        this._dataTable = new DataTable("table");

        this._dataTable.Columns.Add("col0");
        this._dataTable.Columns.Add("col1");
        this._dataTable.Columns.Add("col2");

        this._dataTable.Rows.Add("data00", "data01", "data02");
        this._dataTable.Rows.Add("data10", "data11", "data22");
        this._dataTable.Rows.Add("data20", "data21", "data22");

        this.grid1.DataContext = this;

    }

In Xaml file:

<DataGrid x:Name="grid1"
          Margin="10"
          AutoGenerateColumns="True"
          ItemsSource="{Binding Path=DataTable, Mode=TwoWay}" />

Display current date and time without punctuation

A simple example in shell script

#!/bin/bash

current_date_time="`date +%Y%m%d%H%M%S`";
echo $current_date_time;

With out punctuation format :- +%Y%m%d%H%M%S
With punctuation :- +%Y-%m-%d %H:%M:%S

How to format current time using a yyyyMMddHHmmss format?

This question comes in top of Google search when you find "golang current time format" so, for all the people that want to use another format, remember that you can always call to:

t := time.Now()

t.Year()

t.Month()

t.Day()

t.Hour()

t.Minute()

t.Second()

For example, to get current date time as "YYYY-MM-DDTHH:MM:SS" (for example 2019-01-22T12:40:55) you can use these methods with fmt.Sprintf:

t := time.Now()
formatted := fmt.Sprintf("%d-%02d-%02dT%02d:%02d:%02d",
        t.Year(), t.Month(), t.Day(),
        t.Hour(), t.Minute(), t.Second())

As always, remember that docs are the best source of learning: https://golang.org/pkg/time/

Binding ComboBox SelectedItem using MVVM

<!-- xaml code-->
    <Grid>
        <ComboBox Name="cmbData"    SelectedItem="{Binding SelectedstudentInfo, Mode=OneWayToSource}" HorizontalAlignment="Left" Margin="225,150,0,0" VerticalAlignment="Top" Width="120" DisplayMemberPath="name" SelectedValuePath="id" SelectedIndex="0" />
        <Button VerticalAlignment="Center" Margin="0,0,150,0" Height="40" Width="70" Click="Button_Click">OK</Button>
    </Grid>



        //student Class
        public class Student
        {
            public  int Id { set; get; }
            public string name { set; get; }
        }

        //set 2 properties in MainWindow.xaml.cs Class
        public ObservableCollection<Student> studentInfo { set; get; }
        public Student SelectedstudentInfo { set; get; }

        //MainWindow.xaml.cs Constructor
        public MainWindow()
        {
            InitializeComponent();
            bindCombo();
            this.DataContext = this;
            cmbData.ItemsSource = studentInfo;

        }

        //method to bind cobobox or you can fetch data from database in MainWindow.xaml.cs
        public void bindCombo()
        {
            ObservableCollection<Student> studentList = new ObservableCollection<Student>();
            studentList.Add(new Student { Id=0 ,name="==Select=="});
            studentList.Add(new Student { Id = 1, name = "zoyeb" });
            studentList.Add(new Student { Id = 2, name = "siddiq" });
            studentList.Add(new Student { Id = 3, name = "James" });

              studentInfo=studentList;

        }

        //button click to get selected student MainWindow.xaml.cs
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Student student = SelectedstudentInfo;
            if(student.Id ==0)
            {
                MessageBox.Show("select name from dropdown");
            }
            else
            {
                MessageBox.Show("Name :"+student.name + "Id :"+student.Id);
            }
        }

Wait on the Database Engine recovery handle failed. Check the SQL server error log for potential causes

Root cause: Corrupted user profile of user account used to start database

The main thread here seems to be a corrupted user account profile for the account that is used to start the DB engine. This is the account that was specified for the "SQL Server Database" engine during installation. In the setup event log, it's also indicated by the following entry:

SQLSVCACCOUNT:                 NT AUTHORITY\SYSTEM

According to the link provided by @royki:

The root cause of this issue, in most cases, is that the profile of the user being used for the service account (in my case it was local system) is corrupted.

This would explain why other respondents had success after changing to different accounts:

  • bmjjr suggests changing to "NT AUTHORITY\NETWORK SERVICE"
  • comments to @bmjjr indicate different accounts "I used NT AUTHORITY\LOCAL SERVICE. That helped too"
  • @Julio Nobre had success with "NT Authority\System "

Fix: reset the corrupt user profile

To fix the user profile that's causing the error, follow the steps listed KB947215.

The main steps from KB947215 are summarized as follows:-

  1. Open regedit
  2. Navigate to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList
  3. Navigate to the SID for the corrupted profile

    To find the SID, click on each SID GUID, review the value for the ProfileImagePath value, and see if it's the correct account. For system accounts, there's a different way to know the SID for the account that failed:

The main system account SIDs of interest are:

SID          Name               Also Known As
S-1-5-18     Local System       NT AUTHORITY\SYSTEM
S-1-5-19     LocalService       NT AUTHORITY\LOCAL SERVICE
S-1-5-20     NetworkService     NT AUTHORITY\NETWORK SERVICE

For information on additional SIDs, see Well-known security identifiers in Windows operating systems.

  1. If there are two entries (e.g. with a .bak) at the end for the SID in question, or the SID in question ends in .bak, ensure to follow carefully the steps in the KB947215 article.
  2. Reset the values for RefCount and State to be 0.
  3. Reboot.
  4. Retry the SQL Server installation.

Why is HttpContext.Current null?

Clearly HttpContext.Current is not null only if you access it in a thread that handles incoming requests. That's why it works "when i use this code in another class of a page".

It won't work in the scheduling related class because relevant code is not executed on a valid thread, but a background thread, which has no HTTP context associated with.

Overall, don't use Application["Setting"] to store global stuffs, as they are not global as you discovered.

If you need to pass certain information down to business logic layer, pass as arguments to the related methods. Don't let your business logic layer access things like HttpContext or Application["Settings"], as that violates the principles of isolation and decoupling.

Update: Due to the introduction of async/await it is more often that such issues happen, so you might consider the following tip,

In general, you should only call HttpContext.Current in only a few scenarios (within an HTTP module for example). In all other cases, you should use

instead of HttpContext.Current.

Windows Task Scheduler doesn't start batch file task

Configuration that worked for me:

  • In General tab: mark radio button - "Run only when user is logged on" <= important !
  • Program/script: just the path to script without quotes or nothing: C:/tools/script.bat
  • Add arguments: kept it empty
  • Start in: kept it empty

In settings, only 2 checkboxes marked:

  • Allow task to be run on demand
  • if the running task does not end when requested, force it to stop

How to query for Xml values and attributes from table in SQL Server?

use value instead of query (must specify index of node to return in the XQuery as well as passing the sql data type to return as the second parameter):

select
    xt.Id
    , x.m.value( '@id[1]', 'varchar(max)' ) MetricId
from
    XmlTest xt
    cross apply xt.XmlData.nodes( '/Sqm/Metrics/Metric' ) x(m)

How to use PHP to connect to sql server

for further investigation: print out the mssql error message:

$dbhandle = mssql_connect($myServer, $myUser, $myPass) or die("Could not connect to database: ".mssql_get_last_message()); 

It is also important to specify the port: On MS SQL Server 2000, separate it with a comma:

$myServer = "10.85.80.229:1443";

or

$myServer = "10.85.80.229,1443";

How to iterate through XML in Powershell?

You can also do it without the [xml] cast. (Although xpath is a world unto itself. https://www.w3schools.com/xml/xml_xpath.asp)

$xml = (select-xml -xpath / -path stack.xml).node
$xml.objects.object.property

Or just this, xpath is case sensitive. Both have the same output:

$xml = (select-xml -xpath /Objects/Object/Property -path stack.xml).node
$xml


Name         Type                                                #text
----         ----                                                -----
DisplayName  System.String                                       SQL Server (MSSQLSERVER)
ServiceState Microsoft.SqlServer.Management.Smo.Wmi.ServiceState Running
DisplayName  System.String                                       SQL Server Agent (MSSQLSERVER)
ServiceState Microsoft.SqlServer.Management.Smo.Wmi.ServiceState Stopped

PKIX path building failed in Java application

In my case the issue was resolved by installing Oracle's official JDK 10 as opposed to using the default OpenJDK that came with my Ubuntu. This is the guide I followed: https://www.linuxuprising.com/2018/04/install-oracle-java-10-in-ubuntu-or.html

Restoring database from .mdf and .ldf files of SQL Server 2008

From a script (one that works):

CREATE DATABASE Northwind
ON ( FILENAME = 'C:\Program Files\Microsoft SQL Server\MSSQL11.SQLEXPRESS\MSSQL\DATA\Northwind.mdf' )
LOG ON ( FILENAME = 'C:\Program Files\Microsoft SQL Server\MSSQL11.SQLEXPRESS\MSSQL\DATA\Northwind_log.ldf')
GO

obviously update the path:

C:\Program Files\Microsoft SQL Server\MSSQL11.SQLEXPRESS\MSSQL\DATA

To where your .mdf and .ldf reside.

How to set DataGrid's row Background, based on a property value using data bindings

The same can be done without DataTrigger too:

 <DataGrid.RowStyle>
     <Style TargetType="DataGridRow">
         <Setter Property="Background" >
             <Setter.Value>
                 <Binding Path="State" Converter="{StaticResource BooleanToBrushConverter}">
                     <Binding.ConverterParameter>
                         <x:Array Type="SolidColorBrush">
                             <SolidColorBrush Color="{StaticResource RedColor}"/>
                             <SolidColorBrush Color="{StaticResource TransparentColor}"/>
                         </x:Array>
                     </Binding.ConverterParameter>
                 </Binding>
             </Setter.Value>
         </Setter>
     </Style>
 </DataGrid.RowStyle>

Where BooleanToBrushConverter is the following class:

public class BooleanToBrushConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null)
            return Brushes.Transparent;

        Brush[] brushes = parameter as Brush[];
        if (brushes == null)
            return Brushes.Transparent;

        bool isTrue;
        bool.TryParse(value.ToString(), out isTrue);

        if (isTrue)
        {
            var brush =  (SolidColorBrush)brushes[0];
            return brush ?? Brushes.Transparent;
        }
        else
        {
            var brush = (SolidColorBrush)brushes[1];
            return brush ?? Brushes.Transparent;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Select SQL Server database size

SELECT
    DB_NAME (database_id) as [Database Name],
    name as [Database File Name],
    [Type] = CASE WHEN Type_Desc = 'ROWS' THEN 'Data File(s)'
            WHEN Type_Desc = 'LOG'  THEN 'Log File(s)'
            ELSE Type_Desc END,
    size*8/1024 as 'Size (MB)',
    physical_name as [Database_File_Location]
FROM sys.master_files
ORDER BY 1,3

Output

Database Name               Database File Name              Type                Size (MB)   Database_File_Location
--------------------------- ------------------------------- ------------------- ----------- ---------------------------------------------------------------
AdventureWorksDW2017        AdventureWorksDW2017            Data File(s)        136         E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\AdventureWorksDW2017.mdf
AdventureWorksDW2017        AdventureWorksDW2017_log        Log File(s)         72          E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\AdventureWorksDW2017_log.ldf
DBA_Admin                   DBA_Admin                       Data File(s)        8           E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\DBA_Admin.mdf
DBA_Admin                   DBA_Admin_log                   Log File(s)         8           E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\DBA_Admin_log.ldf
EventNotifications          EventNotifications              Data File(s)        8           E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\EventNotifications.mdf
EventNotifications          EventNotifications_log          Log File(s)         8           E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\EventNotifications_log.ldf
master                      master                          Data File(s)        4           E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\master.mdf
master                      mastlog                         Log File(s)         2           E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\mastlog.ldf
model                       modeldev                        Data File(s)        8           E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\model.mdf
model                       modellog                        Log File(s)         8           E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\modellog.ldf
msdb                        MSDBData                        Data File(s)        19          E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\MSDBData.mdf
msdb                        MSDBLog                         Log File(s)         13          E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\MSDBLog.ldf
tempdb                      temp2                           Data File(s)        8           E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\tempdb_mssql_2.ndf
tempdb                      temp3                           Data File(s)        8           E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\tempdb_mssql_3.ndf
tempdb                      temp4                           Data File(s)        8           E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\tempdb_mssql_4.ndf
tempdb                      tempdev                         Data File(s)        8           E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\tempdb.mdf
tempdb                      templog                         Log File(s)         8           E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\templog.ldf

mssql convert varchar to float

DECLARE @INPUT VARCHAR(5) = '0.12',@INPUT_1 VARCHAR(5)='0.12x';
select CONVERT(float, @INPUT) YOUR_QUERY ,
case when isnumeric(@INPUT_1)=1 THEN CONVERT(float, @INPUT_1) ELSE 0 END AS YOUR_QUERY_ANSWERED

above will return values

however below query wont work

DECLARE @INPUT VARCHAR(5) = '0.12',@INPUT_1 VARCHAR(5)='0.12x';
select CONVERT(float, @INPUT) YOUR_QUERY ,
case when isnumeric(@INPUT_1)=1 THEN CONVERT(float, @INPUT_1) ELSE **@INPUT_1** END AS YOUR_QUERY_ANSWERED

as @INPUT_1 actually has varchar in it.

So your output column must have a varchar in it.

Php - Your PHP installation appears to be missing the MySQL extension which is required by WordPress

The php mysql api is deprecated. It's kaput --- going away -- not to be used, finito.

If you have a modern version of PHP (> 5.6) then Wordpress should automatically switch to make use of mysqli. That should be your first attempt.

If you can not update your php, rather than attempting to resurrect something that php no longer supports, just patch your wordpress: http://wordpress.org/plugins/mysqli/

Windows could not start the SQL Server (MSSQLSERVER) on Local Computer... (error code 3417)

A few times now, I've experienced various instances MS SQL Server to fail with this error after a Windows update. Most of the quick fixes above did not work for me.

What did:

  • copy all production databases over to some safe place
  • remove everything SQL Server via add/remove programs
  • get the latest SQL Server Express or Dev & install it
  • move the databases over to their home and reattach them.

For me, this was the fastest solution. Trying to find the cause of the error and fixing it is an afternoon of googling misty error messages. But YMMV.

How to parse JSON and access results

Try:

$result = curl_exec($cURL);
$result = json_decode($result,true);

Now you can access MessageID from $result['MessageID'].

As for the database, it's simply using a query like so:

INSERT INTO `tableName`(`Cancelled`,`Queued`,`SMSError`,`SMSIncommingMessage`,`Sent`,`SentDateTime`) VALUES('?','?','?','?','?');

Prepared.

select into in mysql

Use the CREATE TABLE SELECT syntax.

http://dev.mysql.com/doc/refman/5.0/en/create-table-select.html

CREATE TABLE new_tbl SELECT * FROM orig_tbl;

How to select data from 30 days?

You should be using DATEADD is Sql server so if try this simple select you will see the affect

Select DATEADD(Month, -1, getdate())

Result

2013-04-20 14:08:07.177

in your case try this query

SELECT name
FROM (
SELECT name FROM 
Hist_answer
WHERE id_city='34324' AND datetime >= DATEADD(month,-1,GETDATE())
UNION ALL
SELECT name FROM 
Hist_internet
WHERE id_city='34324' AND datetime >= DATEADD(month,-1,GETDATE())
) x
GROUP BY name ORDER BY name

JDBC connection to MSSQL server in windows authentication mode

i was getting error as "This driver is not configured for integrated authentication" while authenticating windows users by following jdbc string

jdbc:sqlserver://host:1433;integratedSecurity=true;domain=myDomain

So the updated connection string to make it work is as below.

jdbc:sqlserver://host:1433;authenticationScheme=NTLM;integratedSecurity=true;domain=myDomain

note: username entered was without domain.

Wpf DataGrid Add new row

Just simply use this Style of DataGridRow:

<DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
            <Setter Property="IsEnabled" Value="{Binding RelativeSource={RelativeSource Self},Path=IsNewItem,Mode=OneWay}" />
        </Style>
</DataGrid.RowStyle>

How can I bold the fonts of a specific row or cell in an Excel worksheet with C#?

Your question is a little unclear...as the part that you indicate you want to bold in Excel is a DataGridView in the import from word method. Do you maybe want to bold the first row in the excel document?

using xl = Microsoft.Office.Interop.Excel;

xl.Range rng = (xl.Range)xlWorkSheet.Rows[0];
rng.Font.Bold = true;

Simple as that!

HTH, Z

how to re-format datetime string in php?

You can use date_parse_from_format() function ...

Check this link..you will get clear idea

How to Write text file Java

I think your expectations and reality don't match (but when do they ever ;))

Basically, where you think the file is written and where the file is actually written are not equal (hmmm, perhaps I should write an if statement ;))

public class TestWriteFile {

    public static void main(String[] args) {
        BufferedWriter writer = null;
        try {
            //create a temporary file
            String timeLog = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
            File logFile = new File(timeLog);

            // This will output the full path where the file will be written to...
            System.out.println(logFile.getCanonicalPath());

            writer = new BufferedWriter(new FileWriter(logFile));
            writer.write("Hello world!");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // Close the writer regardless of what happens...
                writer.close();
            } catch (Exception e) {
            }
        }
    }
}

Also note that your example will overwrite any existing files. If you want to append the text to the file you should do the following instead:

writer = new BufferedWriter(new FileWriter(logFile, true));

How to show form input fields based on select value?

Demo on JSFiddle

$(document).ready(function () {
    toggleFields(); // call this first so we start out with the correct visibility depending on the selected form values
    // this will call our toggleFields function every time the selection value of our other field changes
    $("#dbType").change(function () {
        toggleFields();
    });

});
// this toggles the visibility of other server
function toggleFields() {
    if ($("#dbType").val() === "other")
        $("#otherServer").show();
    else
        $("#otherServer").hide();
}

HTML:

    <p>Choose type</p>
    <p>Server:
        <select id="dbType" name="dbType">
          <option>Choose Database Type</option>
          <option value="oracle">Oracle</option>
          <option value="mssql">MS SQL</option>
          <option value="mysql">MySQL</option>
          <option value="other">Other</option>
        </select>
    </p>
    <div id="otherServer">
        <p>Server:
            <input type="text" name="server_name" />
        </p>
        <p>Port:
            <input type="text" name="port_no" />
        </p>
    </div>
    <p align="center">
        <input type="submit" value="Submit!" />
    </p>

Pandas count(distinct) equivalent

Here is another method, much simple, lets say your dataframe name is daat and column name is YEARMONTH

daat.YEARMONTH.value_counts()

SQL Server stored procedure parameters

SQL Server doesn't allow you to pass parameters to a procedure that you haven't defined. I think the closest you can get to this sort of design is to use optional parameters like so:

CREATE PROCEDURE GetTaskEvents
    @TaskName varchar(50),
    @ID int = NULL
AS
BEGIN
-- SP Logic
END;

You would need to include every possible parameter that you might use in the definition. Then you'd be free to call the procedure either way:

EXEC GetTaskEvents @TaskName = 'TESTTASK', @ID = 2;
EXEC GetTaskEvents @TaskName = 'TESTTASK'; -- @ID gets NULL here

What is the reason and how to avoid the [FIN, ACK] , [RST] and [RST, ACK]

Here is a rough explanation of the concepts.

[ACK] is the acknowledgement that the previously sent data packet was received.

[FIN] is sent by a host when it wants to terminate the connection; the TCP protocol requires both endpoints to send the termination request (i.e. FIN).

So, suppose

  • host A sends a data packet to host B
  • and then host B wants to close the connection.
  • Host B (depending on timing) can respond with [FIN,ACK] indicating that it received the sent packet and wants to close the session.
  • Host A should then respond with a [FIN,ACK] indicating that it received the termination request (the ACK part) and that it too will close the connection (the FIN part).

However, if host A wants to close the session after sending the packet, it would only send a [FIN] packet (nothing to acknowledge) but host B would respond with [FIN,ACK] (acknowledges the request and responds with FIN).

Finally, some TCP stacks perform half-duplex termination, meaning that they can send [RST] instead of the usual [FIN,ACK]. This happens when the host actively closes the session without processing all the data that was sent to it. Linux is one operating system which does just this.

You can find a more detailed and comprehensive explanation here.

Is the LIKE operator case-sensitive with MSSQL Server?

You can easy change collation in Microsoft SQL Server Management studio.

  • right click table -> design.
  • choose your column, scroll down i column properties to Collation.
  • Set your sort preference by check "Case Sensitive"

How to use HTTP GET in PowerShell?

Downloading Wget is not necessary; the .NET Framework has web client classes built in.

$wc = New-Object system.Net.WebClient;
$sms = Read-Host "Enter SMS text";
$sms = [System.Web.HttpUtility]::UrlEncode($sms);
$smsResult = $wc.downloadString("http://smsserver/SNSManager/msgSend.jsp?uid&to=smartsms:*+001XXXXXX&msg=$sms&encoding=windows-1255")

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

The answer is in the error message itself:

Error Locating Server/Instance Specified

Basically, you've got the wrong server\instance in the connection string, i.e. this bit:

Data Source=MSSQL2008-1

is wrong and not pointing to the server, or the servername doesn't resolve to an IP address. Two other posibilities: (1) the SQL Browser Service on the box running SQL Server isn't running or (2) Windows Firewall (or some other firewall) on the SQL box is denying incoming connections.

Ultimately, if the servername is correct, then it turns into a networking problem, and you need to find out why the client cannot connect to the server (and this will be more likely to be a basic networking problem than a SQL Server configuration problem).

SQL Server database restore error: specified cast is not valid. (SqlManagerUI)

Could be because of restoring SQL Server 2012 version backup file into SQL Server 2008 R2 or even less.

Linq where clause compare only date value without time value

There is also EntityFunctions.TruncateTime or DbFunctions.TruncateTime in EF 6.0

JSON.Net Self referencing loop detected

This may help you.

public MyContext() : base("name=MyContext") 
{ 
    Database.SetInitializer(new MyContextDataInitializer()); 
    this.Configuration.LazyLoadingEnabled = false; 
    this.Configuration.ProxyCreationEnabled = false; 
} 

http://code.msdn.microsoft.com/Loop-Reference-handling-in-caaffaf7

select data up to a space?

An alternative if you sometimes do not have spaces do not want to use the CASE statement

select REVERSE(RIGHT(REVERSE(YourColumn), LEN(YourColumn) - CHARINDEX(' ', REVERSE(YourColumn))))

This works in SQL Server, and according to my searching MySQL has the same functions

Viewing root access files/folders of android on windows

If you have android, you can install free app on phone (Wifi file Transfer) and enable ssl, port and other options for access and send data in both directions just start application and write in pc browser phone ip and port. enjoy!

Connect to SQL Server through PDO using SQL Server Driver

$servername = "";
$username = "";
$password = "";
$database = "";
$port = "1433";
try {
    $conn = new PDO("sqlsrv:server=$servername,$port;Database=$database;ConnectionPooling=0", $username, $password,
        array(
            PDO::ATTR_PERSISTENT => true,
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
        )
    );
} catch (PDOException $e) {
    echo ("Error connecting to SQL Server: " . $e->getMessage());
}

Connecting to SQL Server Express - What is my server name?

by default -

you can also log in to sql express using server name as:

./SQLEXPRESS

or log in to sql server simply as

.

SQL Server 2012 can't start because of a login failure

I had a similar issue that was resolved with the following:

  1. In Services.MSC click on the Log On tab and add the user with minimum privileges and password (on the service that is throwing the login error)
  2. By Starting Sql Server to run as Administrator

If the user is a domain user use Domain username and password

CREATE FILE encountered operating system error 5(failed to retrieve text for this error. Reason: 15105)

In my case, Run as Administrator does not help. I solved the problem by changing the Build-in Account to Local System in Configuration Manager.

MySQL - Meaning of "PRIMARY KEY", "UNIQUE KEY" and "KEY" when used together while creating a table

Just to add to the other answers, the documentation gives this explanation:

  • KEY is normally a synonym for INDEX. The key attribute PRIMARY KEY can also be specified as just KEY when given in a column definition. This was implemented for compatibility with other database systems.

  • A UNIQUE index creates a constraint such that all values in the index must be distinct. An error occurs if you try to add a new row with a key value that matches an existing row. For all engines, a UNIQUE index permits multiple NULL values for columns that can contain NULL.

  • A PRIMARY KEY is a unique index where all key columns must be defined as NOT NULL. If they are not explicitly declared as NOT NULL, MySQL declares them so implicitly (and silently). A table can have only one PRIMARY KEY. The name of a PRIMARY KEY is always PRIMARY, which thus cannot be used as the name for any other kind of index.

WPF ListView - detect when selected item is clicked

This worked for me.

Single-clicking a row triggers the code-behind.

XAML:

<ListView x:Name="MyListView" MouseLeftButtonUp="MyListView_MouseLeftButtonUp">
    <GridView>
        <!-- Declare GridViewColumns. -->
    </GridView>
</ListView.View>

Code-behind:

private void MyListView_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
    System.Windows.Controls.ListView list = (System.Windows.Controls.ListView)sender;
    MyClass selectedObject = (MyClass)list.SelectedItem;
    // Do stuff with the selectedObject.
}

PHP Fatal error: Call to undefined function mssql_connect()

I have just tried to install that extension on my dev server.

First, make sure that the extension is correctly enabled. Your phpinfo() output doesn't seem complete.

If it is indeed installed properly, your phpinfo() should have a section that looks like this: enter image description here

If you do not get that section in your phpinfo(). Make sure that you are using the right version. There are both non-thread-safe and thread-safe versions of the extension.

Finally, check your extension_dir setting. By default it's this: extension_dir = "ext", for most of the time it works fine, but if it doesn't try: extension_dir = "C:\PHP\ext".

===========================================================================

EDIT given new info:

You are using the wrong function. mssql_connect() is part of the Mssql extension. You are using microsoft's extension, so use sqlsrv_connect(), for the API for the microsoft driver, look at SQLSRV_Help.chm which should be extracted to your ext directory when you extracted the extension.

The calling thread cannot access this object because a different thread owns it

To add my 2 cents, the exception can occur even if you call your code through System.Windows.Threading.Dispatcher.CurrentDispatcher.Invoke().
The point is that you have to call Invoke() of the Dispatcher of the control that you're trying to access, which in some cases may not be the same as System.Windows.Threading.Dispatcher.CurrentDispatcher. So instead you should use YourControl.Dispatcher.Invoke() to be safe. I was banging my head for a couple of hours before I realized this.

Update

For future readers, it looks like this has changed in the newer versions of .NET (4.0 and above). Now you no longer have to worry about the correct dispatcher when updating UI-backing properties in your VM. WPF engine will marshal cross-thread calls on the correct UI thread. See more details here. Thanks to @aaronburro for the info and link. You may also want to read our conversation below in comments.

ExecuteReader requires an open and available Connection. The connection's current state is Connecting

Sorry for only commenting in the first place, but i'm posting almost every day a similar comment since many people think that it would be smart to encapsulate ADO.NET functionality into a DB-Class(me too 10 years ago). Mostly they decide to use static/shared objects since it seems to be faster than to create a new object for any action.

That is neither a good idea in terms of peformance nor in terms of fail-safety.

Don't poach on the Connection-Pool's territory

There's a good reason why ADO.NET internally manages the underlying Connections to the DBMS in the ADO-NET Connection-Pool:

In practice, most applications use only one or a few different configurations for connections. This means that during application execution, many identical connections will be repeatedly opened and closed. To minimize the cost of opening connections, ADO.NET uses an optimization technique called connection pooling.

Connection pooling reduces the number of times that new connections must be opened. The pooler maintains ownership of the physical connection. It manages connections by keeping alive a set of active connections for each given connection configuration. Whenever a user calls Open on a connection, the pooler looks for an available connection in the pool. If a pooled connection is available, it returns it to the caller instead of opening a new connection. When the application calls Close on the connection, the pooler returns it to the pooled set of active connections instead of closing it. Once the connection is returned to the pool, it is ready to be reused on the next Open call.

So obviously there's no reason to avoid creating,opening or closing connections since actually they aren't created,opened and closed at all. This is "only" a flag for the connection pool to know when a connection can be reused or not. But it's a very important flag, because if a connection is "in use"(the connection pool assumes), a new physical connection must be openend to the DBMS what is very expensive.

So you're gaining no performance improvement but the opposite. If the maximum pool size specified (100 is the default) is reached, you would even get exceptions(too many open connections ...). So this will not only impact the performance tremendously but also be a source for nasty errors and (without using Transactions) a data-dumping-area.

If you're even using static connections you're creating a lock for every thread trying to access this object. ASP.NET is a multithreading environment by nature. So theres a great chance for these locks which causes performance issues at best. Actually sooner or later you'll get many different exceptions(like your ExecuteReader requires an open and available Connection).

Conclusion:

  • Don't reuse connections or any ADO.NET objects at all.
  • Don't make them static/shared(in VB.NET)
  • Always create, open(in case of Connections), use, close and dispose them where you need them(f.e. in a method)
  • use the using-statement to dispose and close(in case of Connections) implicitely

That's true not only for Connections(although most noticable). Every object implementing IDisposable should be disposed(simplest by using-statement), all the more in the System.Data.SqlClient namespace.

All the above speaks against a custom DB-Class which encapsulates and reuse all objects. That's the reason why i commented to trash it. That's only a problem source.


Edit: Here's a possible implementation of your retrievePromotion-method:

public Promotion retrievePromotion(int promotionID)
{
    Promotion promo = null;
    var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MainConnStr"].ConnectionString;
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        var queryString = "SELECT PromotionID, PromotionTitle, PromotionURL FROM Promotion WHERE PromotionID=@PromotionID";
        using (var da = new SqlDataAdapter(queryString, connection))
        {
            // you could also use a SqlDataReader instead
            // note that a DataTable does not need to be disposed since it does not implement IDisposable
            var tblPromotion = new DataTable();
            // avoid SQL-Injection
            da.SelectCommand.Parameters.Add("@PromotionID", SqlDbType.Int);
            da.SelectCommand.Parameters["@PromotionID"].Value = promotionID;
            try
            {
                connection.Open(); // not necessarily needed in this case because DataAdapter.Fill does it otherwise 
                da.Fill(tblPromotion);
                if (tblPromotion.Rows.Count != 0)
                {
                    var promoRow = tblPromotion.Rows[0];
                    promo = new Promotion()
                    {
                        promotionID    = promotionID,
                        promotionTitle = promoRow.Field<String>("PromotionTitle"),
                        promotionUrl   = promoRow.Field<String>("PromotionURL")
                    };
                }
            }
            catch (Exception ex)
            {
                // log this exception or throw it up the StackTrace
                // we do not need a finally-block to close the connection since it will be closed implicitely in an using-statement
                throw;
            }
        }
    }
    return promo;
}

Convert HH:MM:SS string to seconds only in javascript

This function handels "HH:MM:SS" as well as "MM:SS" or "SS".

function hmsToSecondsOnly(str) {
    var p = str.split(':'),
        s = 0, m = 1;

    while (p.length > 0) {
        s += m * parseInt(p.pop(), 10);
        m *= 60;
    }

    return s;
}

Recommended date format for REST GET API

REST doesn't have a recommended date format. Really it boils down to what works best for your end user and your system. Personally, I would want to stick to a standard like you have for ISO 8601 (url encoded).

If not having ugly URI is a concern (e.g. not including the url encoded version of :, -, in you URI) and (human) addressability is not as important, you could also consider epoch time (e.g. http://example.com/start/1331162374). The URL looks a little cleaner, but you certainly lose readability.

The /2012/03/07 is another format you see a lot. You could expand upon that I suppose. If you go this route, just make sure you're either always in GMT time (and make that clear in your documentation) or you might also want to include some sort of timezone indicator.

Ultimately it boils down to what works for your API and your end user. Your API should work for you, not you for it ;-).

select the TOP N rows from a table

In MySql, you can get 10 rows starting from row 20 using:

SELECT * FROM Reflow  
WHERE ReflowProcessID = somenumber
ORDER BY ID DESC
LIMIT 10 OFFSET 20 --Equivalent to LIMIT 20, 10

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.

Opening a SQL Server .bak file (Not restoring!)

Just to add my TSQL-scripted solution:

First of all; add a new database named backup_lookup. Then just run this script, inserting your own databases' root path and backup filepath

USE [master]
GO
RESTORE DATABASE backup_lookup
 FROM DISK = 'C:\backup.bak'
WITH REPLACE,
 MOVE 'Old Database Name' TO 'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\backup_lookup.mdf',
 MOVE 'Old Database Name_log' TO 'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\backup_lookup_log.ldf'
GO

Notify ObservableCollection when Item changes

I know it's late, but maybe this helps others. I have created a class NotifyObservableCollection, that solves the problem of missing notification to item itself, when a property of the item changes. The usage is as simple as ObservableCollection.

public class NotifyObservableCollection<T> : ObservableCollection<T> where T : INotifyPropertyChanged
{
    private void Handle(object sender, PropertyChangedEventArgs args)
    {
        OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset, null));
    }

    protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
    {
        if (e.NewItems != null) {
            foreach (object t in e.NewItems) {
                ((T) t).PropertyChanged += Handle;
            }
        }
        if (e.OldItems != null) {
            foreach (object t in e.OldItems) {
                ((T) t).PropertyChanged -= Handle;
            }
        }
        base.OnCollectionChanged(e);
    }

While Items are added or removed the class forwards the items PropertyChanged event to the collections PropertyChanged event.

usage:

public abstract class ParameterBase : INotifyPropertyChanged
{
    protected readonly CultureInfo Ci = new CultureInfo("en-US");
    private string _value;

    public string Value {
        get { return _value; }
        set {
            if (value == _value) return;
            _value = value;
            OnPropertyChanged();
        }
    }
}

public class AItem {
    public NotifyObservableCollection<ParameterBase> Parameters {
        get { return _parameters; }
        set {
            NotifyCollectionChangedEventHandler cceh = (sender, args) => OnPropertyChanged();
            if (_parameters != null) _parameters.CollectionChanged -= cceh;
            _parameters = value;
            //needed for Binding to AItem at xaml directly
            _parameters.CollectionChanged += cceh; 
        }
    }

    public NotifyObservableCollection<ParameterBase> DefaultParameters {
        get { return _defaultParameters; }
        set {
            NotifyCollectionChangedEventHandler cceh = (sender, args) => OnPropertyChanged();
            if (_defaultParameters != null) _defaultParameters.CollectionChanged -= cceh;
            _defaultParameters = value;
            //needed for Binding to AItem at xaml directly
            _defaultParameters.CollectionChanged += cceh;
        }
    }


public class MyViewModel {
    public NotifyObservableCollection<AItem> DataItems { get; set; }
}

If now a property of an item in DataItems changes, the following xaml will get a notification, though it binds to Parameters[0] or to the item itself except to the changing property Value of the item (Converters at Triggers are called reliable on every change).

<DataGrid CanUserAddRows="False" AutoGenerateColumns="False" ItemsSource="{Binding DataItems}">
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding Parameters[0].Value}" Header="P1">
            <DataGridTextColumn.CellStyle>
                <Style TargetType="DataGridCell">
                    <Setter Property="Background" Value="Aqua" />
                    <Style.Triggers>
                        <DataTrigger Value="False">
                            <!-- Bind to Items with changing properties -->
                            <DataTrigger.Binding>
                                <MultiBinding Converter="{StaticResource ParameterCompareConverter}">
                                    <Binding Path="DefaultParameters[0]" />
                                    <Binding Path="Parameters[0]" />
                                </MultiBinding>
                            </DataTrigger.Binding>
                            <Setter Property="Background" Value="DeepPink" />
                        </DataTrigger>
                        <!-- Binds to AItem directly -->
                        <DataTrigger Value="True" Binding="{Binding Converter={StaticResource CheckParametersConverter}}">
                            <Setter Property="FontWeight" Value="ExtraBold" />
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </DataGridTextColumn.CellStyle>
        </DataGridTextColumn>

Best practices for SQL varchar column length

In a sense you're right, although anything lower than 2^8 characters will still register as a byte of data.

If you account for the base character that leaves anything with a VARCHAR < 255 as consuming the same amount of space.

255 is a good baseline definition unless you particularly wish to curtail excessive input.

Computed / calculated / virtual / derived columns in PostgreSQL

Up to Postgres 11 generated columns are not supported - as defined in the SQL standard and implemented by some RDBMS including DB2, MySQL and Oracle. Nor the similar "computed columns" of SQL Server.

STORED generated columns are introduced with Postgres 12. Trivial example:

CREATE TABLE tbl (
  int1    int
, int2    int
, product bigint GENERATED ALWAYS AS (int1 * int2) STORED
);

db<>fiddle here

VIRTUAL generated columns may come with one of the next iterations. (Not in Postgres 13, yet) .

Related:


Until then, you can emulate VIRTUAL generated columns with a function using attribute notation (tbl.col) that looks and works much like a virtual generated column. That's a bit of a syntax oddity which exists in Postgres for historic reasons and happens to fit the case. This related answer has code examples:

The expression (looking like a column) is not included in a SELECT * FROM tbl, though. You always have to list it explicitly.

Can also be supported with a matching expression index - provided the function is IMMUTABLE. Like:

CREATE FUNCTION col(tbl) ... AS ...  -- your computed expression here
CREATE INDEX ON tbl(col(tbl));

Alternatives

Alternatively, you can implement similar functionality with a VIEW, optionally coupled with expression indexes. Then SELECT * can include the generated column.

"Persisted" (STORED) computed columns can be implemented with triggers in a functionally identical way.

Materialized views are a closely related concept, implemented since Postgres 9.3.
In earlier versions one can manage MVs manually.

how to change listen port from default 7001 to something different?

The following lines are used to control the listen-port of a server, both are necessary:

    <listen-port>7002</listen-port>
    <listen-port-enabled>true</listen-port-enabled>

Date formatting in WPF datagrid

Don`t forget to use DataGrid.Columns, all columns must be inside that collection. In my project I format date a little bit differently:

<tk:DataGrid>
    <tk:DataGrid.Columns>
        <tk:DataGridTextColumn Binding="{Binding StartDate, StringFormat=\{0:dd.MM.yy HH:mm:ss\}}" />
    </tk:DataGrid.Columns>
</tk:DataGrid>

With AutoGenerateColumns you won`t be able to contol formatting as DataGird will add its own columns.

jQuery show/hide options from one select drop down, when option on other select dropdown is slected

How about:

(Updated)

$("#column_select").change(function () {
    $("#layout_select")
        .find("option")
        .show()
        .not("option[value*='" + this.value + "']").hide();

    $("#layout_select").val(
        $("#layout_select").find("option:visible:first").val());

}).change();

(assuming the third option should have a value col3)

Example: http://jsfiddle.net/cL2tt/

Notes:

  • Use the .change() event to define an event handler that executes when the value of select#column_select changes.
  • .show() all options in the second select.
  • .hide() all options in the second select whose value does not contain the value of the selected option in select#column_select, using the attribute contains selector.

Unable to begin a distributed transaction

Apart from the security settings, I had to open some ports on both servers for the transaction to run. I had to open port 59640 but according to the following suggestion, port 135 has to be open. http://support.microsoft.com/kb/839279

How to sort alphabetically while ignoring case sensitive?

I can't believe no one made a reference to the Collator. Almost all of these answers will only work for the English language.

You should almost always use a Collator for dictionary based sorting.

For case insensitive collator searching for the English language you do the following:

Collator usCollator = Collator.getInstance(Locale.US);
usCollator.setStrength(Collator.PRIMARY);
Collections.sort(listToSort, usCollator);

How do I get the SQLSRV extension to work with PHP, since MSSQL is deprecated?

Quoting http://php.net/manual/en/intro.mssql.php:

The MSSQL extension is not available anymore on Windows with PHP 5.3 or later. SQLSRV, an alternative driver for MS SQL is available from Microsoft: » http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx.

Once you downloaded that, follow the instructions at this page:

In a nutshell:

Put the driver file in your PHP extension directory.
Modify the php.ini file to include the driver. For example:

extension=php_sqlsrv_53_nts_vc9.dll  

Restart the Web server.

See Also (copied from that page)

The PHP Manual for the SQLSRV extension is located at http://php.net/manual/en/sqlsrv.installation.php and offers the following for Installation:

The SQLSRV extension is enabled by adding appropriate DLL file to your PHP extension directory and the corresponding entry to the php.ini file. The SQLSRV download comes with several driver files. Which driver file you use will depend on 3 factors: the PHP version you are using, whether you are using thread-safe or non-thread-safe PHP, and whether your PHP installation was compiled with the VC6 or VC9 compiler. For example, if you are running PHP 5.3, you are using non-thread-safe PHP, and your PHP installation was compiled with the VC9 compiler, you should use the php_sqlsrv_53_nts_vc9.dll file. (You should use a non-thread-safe version compiled with the VC9 compiler if you are using IIS as your web server). If you are running PHP 5.2, you are using thread-safe PHP, and your PHP installation was compiled with the VC6 compiler, you should use the php_sqlsrv_52_ts_vc6.dll file.

The drivers can also be used with PDO.

Explicitly set column value to null SQL Developer

You'll have to write the SQL DML yourself explicitly. i.e.

UPDATE <table>
   SET <column> = NULL;

Once it has completed you'll need to commit your updates

commit;

If you only want to set certain records to NULL use a WHERE clause in your UPDATE statement.

As your original question is pretty vague I hope this covers what you want.

SQL Server: SELECT only the rows with MAX(DATE)

The best way is Mikael Eriksson, if ROW_NUMBER() is available to you.

The next best is to join on a query, as per Cularis' answer.

Alternatively, the most simple and straight forward way is a correlated-sub-query in the WHERE clause.

SELECT
  *
FROM
  yourTable AS [data]
WHERE
  DateEntered = (SELECT MAX(DateEntered) FROM yourTable WHERE orderNo = [data].orderNo)

Or...

WHERE
  ID = (SELECT TOP 1 ID FROM yourTable WHERE orderNo = [data].orderNo ORDER BY DateEntered DESC)

SQL Server Restore Error - Access is Denied

Got problem like this. Error caused by enabled compression on SQL Server folders.

Move SQL Server 2008 database files to a new folder location

Some notes to complement the ALTER DATABASE process:

1) You can obtain a full list of databases with logical names and full paths of MDF and LDF files:

   USE master SELECT name, physical_name FROM sys.master_files

2) You can move manually the files with CMD move command:

Move "Source" "Destination"

Example:

md "D:\MSSQLData"
Move "C:\test\SYSADMIT-DB.mdf" "D:\MSSQLData\SYSADMIT-DB_Data.mdf"
Move "C:\test\SYSADMIT-DB_log.ldf" "D:\MSSQLData\SYSADMIT-DB_log.ldf"

3) You should change the default database path for new databases creation. The default path is obtained from the Windows registry.

You can also change with T-SQL, for example, to set default destination to: D:\MSSQLData

USE [master]

GO

EXEC xp_instance_regwrite N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'DefaultData', REG_SZ, N'D:\MSSQLData'

GO

EXEC xp_instance_regwrite N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'DefaultLog', REG_SZ, N'D:\MSSQLData'

GO

Extracted from: http://www.sysadmit.com/2016/08/mover-base-de-datos-sql-server-a-otro-disco.html

Why doesn't GCC optimize a*a*a*a*a*a to (a*a*a)*(a*a*a)?

I would not have expected this case to be optimized at all. It can't be very often where an expression contains subexpressions that can be regrouped to remove entire operations. I would expect compiler writers to invest their time in areas which would be more likely to result in noticeable improvements, rather than covering a rarely encountered edge case.

I was surprised to learn from the other answers that this expression could indeed be optimized with the proper compiler switches. Either the optimization is trivial, or it is an edge case of a much more common optimization, or the compiler writers were extremely thorough.

There's nothing wrong with providing hints to the compiler as you've done here. It's a normal and expected part of the micro-optimization process to rearrange statements and expressions to see what differences they will bring.

While the compiler may be justified in considering the two expressions to deliver inconsistent results (without the proper switches), there's no need for you to be bound by that restriction. The difference will be incredibly tiny - so much so that if the difference matters to you, you should not be using standard floating point arithmetic in the first place.

InvalidKeyException : Illegal Key Size - Java code throwing exception for encryption class - how to fix?

Add below code in your client code :

static {
    Security.insertProviderAt(new BouncyCastleProvider(),1);
 }

with this there is no need to add any entry in java.security file.

Count all duplicates of each value

SELECT number, COUNT(*)
    FROM YourTable
    GROUP BY number
    ORDER BY number

How to bind an enum to a combobox control in WPF?

You can do it from code by placing the following code in Window Loaded event handler, for example:

yourComboBox.ItemsSource = Enum.GetValues(typeof(EffectStyle)).Cast<EffectStyle>();

If you need to bind it in XAML you need to use ObjectDataProvider to create object available as binding source:

<Window x:Class="YourNamespace.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:System="clr-namespace:System;assembly=mscorlib"
        xmlns:StyleAlias="clr-namespace:Motion.VideoEffects">
    <Window.Resources>
        <ObjectDataProvider x:Key="dataFromEnum" MethodName="GetValues"
                            ObjectType="{x:Type System:Enum}">
            <ObjectDataProvider.MethodParameters>
                <x:Type TypeName="StyleAlias:EffectStyle"/>
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>
    </Window.Resources>
    <Grid>
        <ComboBox ItemsSource="{Binding Source={StaticResource dataFromEnum}}"
                  SelectedItem="{Binding Path=CurrentEffectStyle}" />
    </Grid>
</Window>

Draw attention on the next code:

xmlns:System="clr-namespace:System;assembly=mscorlib"
xmlns:StyleAlias="clr-namespace:Motion.VideoEffects"

Guide how to map namespace and assembly you can read on MSDN.

javascript date to string

A little bit simpler using regex and toJSON().

var now = new Date();
var timeRegex = /^.*T(\d{2}):(\d{2}):(\d{2}).*$/
var dateRegex = /^(\d{4})-(\d{2})-(\d{2})T.*$/
var dateData = dateRegex.exec(now.toJSON());
var timeData = timeRegex.exec(now.toJSON());
var myFormat = dateData[1]+dateData[2]+dateData[3]+timeData[1]+timeData[2]+timeData[3]

Which at the time of writing gives you "20151111180924".

The good thing of using toJSON() is that everything comes already padded.

Get current time as formatted string in Go?

Use the time.Now() and time.Format() functions (as time.LocalTime() doesn't exist anymore as of Go 1.0.3)

t := time.Now()
fmt.Println(t.Format("20060102150405"))

Online demo (with date fixed in the past in the playground, never mind)

How can I convert an MDB (Access) file to MySQL (or plain SQL file)?

You want to convert mdb to mysql (direct transfer to mysql or mysql dump)?

Try a software called Access to MySQL.

Access to MySQL is a small program that will convert Microsoft Access Databases to MySQL.

  • Wizard interface.
  • Transfer data directly from one server to another.
  • Create a dump file.
  • Select tables to transfer.
  • Select fields to transfer.
  • Transfer password protected databases.
  • Supports both shared security and user-level security.
  • Optional transfer of indexes.
  • Optional transfer of records.
  • Optional transfer of default values in field definitions.
  • Identifies and transfers auto number field types.
  • Command line interface.
  • Easy install, uninstall and upgrade.

See the aforementioned link for a step-by-step tutorial with screenshots.

error, string or binary data would be truncated when trying to insert

A 2016/2017 update will show you the bad value and column.

enter image description here

A new trace flag will swap the old error for a new 2628 error and will print out the column and offending value. Traceflag 460 is available in the latest cumulative update for 2016 and 2017:

https://support.microsoft.com/en-sg/help/4468101/optional-replacement-for-string-or-binary-data-would-be-truncated

Just make sure that after you've installed the CU that you enable the trace flag, either globally/permanently on the server: enter image description here

...or with DBCC TRACEON:

https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-traceon-trace-flags-transact-sql?view=sql-server-ver15

Binding ItemsSource of a ComboBoxColumn in WPF DataGrid

The correct solution seems to be:

<Window.Resources>
    <CollectionViewSource x:Key="ItemsCVS" Source="{Binding MyItems}" />
</Window.Resources>
<!-- ... -->
<DataGrid ItemsSource="{Binding MyRecords}">
    <DataGridComboBoxColumn Header="Column With Predefined Values"
                            ItemsSource="{Binding Source={StaticResource ItemsCVS}}"
                            SelectedValueBinding="{Binding MyItemId}"
                            SelectedValuePath="Id"
                            DisplayMemberPath="StatusCode" />
</DataGrid>

The layout above works perfectly fine for me, and should work for others. This design choice also makes sense, though it isn't very well explained anywhere. But if you have a data column with predefined values, those values typically don't change during run-time. So creating a CollectionViewSource and initializing the data once makes sense. It also gets rid of the longer bindings to find an ancestor and bind on it's data context (which always felt wrong to me).

I am leaving this here for anyone else who struggled with this binding, and wondered if there was a better way (As this page is obviously still coming up in search results, that's how I got here).

How to use a table type in a SELECT FROM statement?

In package specs you can do all you mentioned but not sure about INDEX BY BINARY_INTEGER;

In package body:

initialize the table in declarations:

exch_rt exch_tbl := exch_tbl();

in order to add record to the local collection, in begin - end block you can do:

exch_rt.extend;
                                one_row.exch_rt_usd := 2;
                                one_row.exch_rt_eur := 1;
                                one_row.currency_cd := 'dollar';
                                exch_rt(1) := one_row; -- 1 - number of row in the table - you can put a variable which will be incremented inside a loop 

in order to get data from this table , inside package body you can use:

select exch_rt_usd, exch_rt_eur, currency_cd from table(exch_rt)

enjoy!

P.S. sorry for a late answer :D

Mapping many-to-many association table with extra column(s)

Since the SERVICE_USER table is not a pure join table, but has additional functional fields (blocked), you must map it as an entity, and decompose the many to many association between User and Service into two OneToMany associations : One User has many UserServices, and one Service has many UserServices.

You haven't shown us the most important part : the mapping and initialization of the relationships between your entities (i.e. the part you have problems with). So I'll show you how it should look like.

If you make the relationships bidirectional, you should thus have

class User {
    @OneToMany(mappedBy = "user")
    private Set<UserService> userServices = new HashSet<UserService>();
}

class UserService {
    @ManyToOne
    @JoinColumn(name = "user_id")
    private User user;

    @ManyToOne
    @JoinColumn(name = "service_code")
    private Service service;

    @Column(name = "blocked")
    private boolean blocked;
}

class Service {
    @OneToMany(mappedBy = "service")
    private Set<UserService> userServices = new HashSet<UserService>();
}

If you don't put any cascade on your relationships, then you must persist/save all the entities. Although only the owning side of the relationship (here, the UserService side) must be initialized, it's also a good practice to make sure both sides are in coherence.

User user = new User();
Service service = new Service();
UserService userService = new UserService();

user.addUserService(userService);
userService.setUser(user);

service.addUserService(userService);
userService.setService(service);

session.save(user);
session.save(service);
session.save(userService);

What does 'COLLATE SQL_Latin1_General_CP1_CI_AS' do?

It sets how the database server sorts (compares pieces of text). in this case:

SQL_Latin1_General_CP1_CI_AS

breaks up into interesting parts:

  1. latin1 makes the server treat strings using charset latin 1, basically ascii
  2. CP1 stands for Code Page 1252
  3. CI case insensitive comparisons so 'ABC' would equal 'abc'
  4. AS accent sensitive, so 'ü' does not equal 'u'

P.S. For more detailed information be sure to read @solomon-rutzky's answer.

How do I get just the date when using MSSQL GetDate()?

It's database specific. You haven't specified what database engine you are using.

e.g. in PostgreSQL you do cast(myvalue as date).

Where is database .bak file saved from SQL Server Management Studio?

have you tried:

C:\Program Files\Microsoft SQL Server\MSSQL10.SQL2008\MSSQL\Backup

Script to get all backups in the last week can be found at:

http://wraithnath.blogspot.com/2010/12/how-to-find-all-database-backups-in.html

I have plenty more backup SQL scripts there also at

http://wraithnath.blogspot.com/search/label/SQL

Finding blocking/locking queries in MS SQL (mssql)

Use the script: sp_blocker_pss08 or SQL Trace/Profiler and the Blocked Process Report event class.

ImportError: No module named pythoncom

If you're on windows you probably want the pywin32 library, which includes pythoncom and a whole lot of other stuff that is pretty standard.

What are the options for storing hierarchical data in a relational database?

I am using PostgreSQL with closure tables for my hierarchies. I have one universal stored procedure for the whole database:

CREATE FUNCTION nomen_tree() RETURNS trigger
    LANGUAGE plpgsql
    AS $_$
DECLARE
  old_parent INTEGER;
  new_parent INTEGER;
  id_nom INTEGER;
  txt_name TEXT;
BEGIN
-- TG_ARGV[0] = name of table with entities with PARENT-CHILD relationships (TBL_ORIG)
-- TG_ARGV[1] = name of helper table with ANCESTOR, CHILD, DEPTH information (TBL_TREE)
-- TG_ARGV[2] = name of the field in TBL_ORIG which is used for the PARENT-CHILD relationship (FLD_PARENT)
    IF TG_OP = 'INSERT' THEN
    EXECUTE 'INSERT INTO ' || TG_ARGV[1] || ' (child_id,ancestor_id,depth) 
        SELECT $1.id,$1.id,0 UNION ALL
      SELECT $1.id,ancestor_id,depth+1 FROM ' || TG_ARGV[1] || ' WHERE child_id=$1.' || TG_ARGV[2] USING NEW;
    ELSE                                                           
    -- EXECUTE does not support conditional statements inside
    EXECUTE 'SELECT $1.' || TG_ARGV[2] || ',$2.' || TG_ARGV[2] INTO old_parent,new_parent USING OLD,NEW;
    IF COALESCE(old_parent,0) <> COALESCE(new_parent,0) THEN
      EXECUTE '
      -- prevent cycles in the tree
      UPDATE ' || TG_ARGV[0] || ' SET ' || TG_ARGV[2] || ' = $1.' || TG_ARGV[2]
        || ' WHERE id=$2.' || TG_ARGV[2] || ' AND EXISTS(SELECT 1 FROM '
        || TG_ARGV[1] || ' WHERE child_id=$2.' || TG_ARGV[2] || ' AND ancestor_id=$2.id);
      -- first remove edges between all old parents of node and its descendants
      DELETE FROM ' || TG_ARGV[1] || ' WHERE child_id IN
        (SELECT child_id FROM ' || TG_ARGV[1] || ' WHERE ancestor_id = $1.id)
        AND ancestor_id IN
        (SELECT ancestor_id FROM ' || TG_ARGV[1] || ' WHERE child_id = $1.id AND ancestor_id <> $1.id);
      -- then add edges for all new parents ...
      INSERT INTO ' || TG_ARGV[1] || ' (child_id,ancestor_id,depth) 
        SELECT child_id,ancestor_id,d_c+d_a FROM
        (SELECT child_id,depth AS d_c FROM ' || TG_ARGV[1] || ' WHERE ancestor_id=$2.id) AS child
        CROSS JOIN
        (SELECT ancestor_id,depth+1 AS d_a FROM ' || TG_ARGV[1] || ' WHERE child_id=$2.' 
        || TG_ARGV[2] || ') AS parent;' USING OLD, NEW;
    END IF;
  END IF;
  RETURN NULL;
END;
$_$;

Then for each table where I have a hierarchy, I create a trigger

CREATE TRIGGER nomenclature_tree_tr AFTER INSERT OR UPDATE ON nomenclature FOR EACH ROW EXECUTE PROCEDURE nomen_tree('my_db.nomenclature', 'my_db.nom_helper', 'parent_id');

For populating a closure table from existing hierarchy I use this stored procedure:

CREATE FUNCTION rebuild_tree(tbl_base text, tbl_closure text, fld_parent text) RETURNS void
    LANGUAGE plpgsql
    AS $$
BEGIN
    EXECUTE 'TRUNCATE ' || tbl_closure || ';
    INSERT INTO ' || tbl_closure || ' (child_id,ancestor_id,depth) 
        WITH RECURSIVE tree AS
      (
        SELECT id AS child_id,id AS ancestor_id,0 AS depth FROM ' || tbl_base || '
        UNION ALL 
        SELECT t.id,ancestor_id,depth+1 FROM ' || tbl_base || ' AS t
        JOIN tree ON child_id = ' || fld_parent || '
      )
      SELECT * FROM tree;';
END;
$$;

Closure tables are defined with 3 columns - ANCESTOR_ID, DESCENDANT_ID, DEPTH. It is possible (and I even advice) to store records with same value for ANCESTOR and DESCENDANT, and a value of zero for DEPTH. This will simplify the queries for retrieval of the hierarchy. And they are very simple indeed:

-- get all descendants
SELECT tbl_orig.*,depth FROM tbl_closure LEFT JOIN tbl_orig ON descendant_id = tbl_orig.id WHERE ancestor_id = XXX AND depth <> 0;
-- get only direct descendants
SELECT tbl_orig.* FROM tbl_closure LEFT JOIN tbl_orig ON descendant_id = tbl_orig.id WHERE ancestor_id = XXX AND depth = 1;
-- get all ancestors
SELECT tbl_orig.* FROM tbl_closure LEFT JOIN tbl_orig ON ancestor_id = tbl_orig.id WHERE descendant_id = XXX AND depth <> 0;
-- find the deepest level of children
SELECT MAX(depth) FROM tbl_closure WHERE ancestor_id = XXX;

Service Reference Error: Failed to generate code for the service reference

I also encountered a similar error when trying to generate the client for a web service from an ASP .Net MVC 4.0 project using Visual Studio 2012.

The root of the problem seems to be that fact that the project from where I was trying to generate the client was referencing an assembly which in turn was dependent on another assembly that was not being referenced as well.

When "Reuse types in referenced assemblies" is enabled in the service configuration, the service generator is probably inspecting all the referenced assemblies to get a list of types that can be reused. The fact that one of the referenced assemblies is referencing another assembly which is not available is probably causing the generator to fail.

Unchecking "Reuse types in referenced assemblies" from the service configurations will solve the above problem, but there is a side effect to it. The reuse types option is there for a reason and in some cases it avoids unnecessary casting in the code consuming the service.

For example, if the service itself is built using WCF and some methods parameters inside it are of type System.Guid, they will be translated to strings in the generated client if the reuse types option is disabled.

An alternative that I prefer to disabling reusing types is to add the service reference from Class Library project specifically created for that purpose. The one thing to keep in mind is to copy all the service related configurations from the class library's app.config to the configuration file of the startup project.

If there are types defined in local assemblies that need to be reused in the service client, those assemblies simply need to be referenced from the above mentioned class library project, along with all their dependencies.

How to export non-exportable private key from store

Gentil Kiwi's answer is correct. He developed this mimikatz tool that is able to retrieve non-exportable private keys.

However, his instructions are outdated. You need:

  1. Download the lastest release from https://github.com/gentilkiwi/mimikatz/releases

  2. Run the cmd with admin rights in the same machine where the certificate was requested

  3. Change to the mimikatz bin directory (Win32 or x64 version)

  4. Run mimikatz

  5. Follow the wiki instructions and the .pfx file (protected with password mimikatz) will be placed in the same folder of the mimikatz bin

mimikatz # crypto::capi
Local CryptoAPI patched

mimikatz # privilege::debug
Privilege '20' OK

mimikatz # crypto::cng
"KeyIso" service patched

mimikatz # crypto::certificates /systemstore:local_machine /store:my /export
* System Store : 'local_machine' (0x00020000)
* Store : 'my'

  1. example.domain.local
         Key Container : example.domain.local
         Provider : Microsoft Software Key Storage Provider
         Type : CNG Key (0xffffffff)
         Exportable key : NO
         Key size : 2048
         Public export : OK - 'local_machine_my_0_example.domain.local.der'
         Private export : OK - 'local_machine_my_0_example.domain.local.pfx'

Is there a free GUI management tool for Oracle Database Express?

Yes, there is Oracle SQL Developer, which is maintained by Oracle.

Oracle SQL Developer is a free graphical tool for database development. With SQL Developer, you can browse database objects, run SQL statements and SQL scripts, and edit and debug PL/SQL statements. You can also run any number of provided reports, as well as create and save your own. SQL Developer enhances productivity and simplifies your database development tasks.

SQL Developer can connect to any Oracle Database version 10g and later and runs on Windows, Linux and Mac OSX.

mssql '5 (Access is denied.)' error during restoring database

I found this, and it worked for me:

CREATE LOGIN BackupRestoreAdmin WITH PASSWORD='$tr0ngP@$$w0rd'
GO
CREATE USER BackupRestoreAdmin FOR LOGIN BackupRestoreAdmin
GO
EXEC sp_addsrvrolemember 'BackupRestoreAdmin', 'dbcreator'
GO
EXEC sp_addrolemember 'db_owner','BackupRestoreAdmin'
GO

Using LINQ to find item in a List but get "Value cannot be null. Parameter name: source"

Ok - my case was not strictly related to this question, but I ended up on this page when Googling for the same exception; I queried an SQL database with LINQ when I got this exception.

private Table<SubscriptionModel> m_subscriptionsSql;
var query = from SubscriptionModel subscription in m_subscriptionsSql ...

Turned out I forgot to initialize my Table instance variable, that I used in the LINQ query.

m_subscriptionsSql = GetTable<SubscriptionModel>();

PHP Warning: PHP Startup: ????????: Unable to initialize module

try to upgrade each of those modules using pecl command

# pecl upgrade fileinfo
# pecl upgrade memcache
# pecl upgrade mhash
# pecl upgrade readline

etc...

Restore DB — Error RESTORE HEADERONLY is terminating abnormally.

Cannot open backup device 'c:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\Backup\ C:\HostingSpaces\dbname_jun14_2010_new.bak'

The error is quite self-explanatory. The file C:\program files\...\Backup \c:\Hosting...\ is incorrectly formatted. This is quite obvious if you inspect the file name. Perhaps ommit the extra space in your backup statement?

BACKUP DATABASE go4sharepoint_1384_8481 
TO DISK='C:\HostingSpaces\dbname_jun14_2010_new.bak' with FORMAT

Note there is no space between ' and C:

Convert String value format of YYYYMMDDHHMMSS to C# DateTime

Define your own parse format string to use.

string formatString = "yyyyMMddHHmmss";
string sample = "20100611221912";
DateTime dt = DateTime.ParseExact(sample,formatString,null);

In case you got a datetime having milliseconds, use the following formatString

string format = "yyyyMMddHHmmssfff"
string dateTime = "20140123205803252";
DateTime.ParseExact(dateTime ,format,CultureInfo.InvariantCulture);

Thanks

C# DateTime to "YYYYMMDDHHMMSS" format

You can use a custom format string:

DateTime d = DateTime.Now;
string dateString = d.ToString("yyyyMMddHHmmss");

Substitute "hh" for "HH" if you do not want 24-hour clock time.

Constructor in an Interface?

Dependencies that are not referenced in an interfaces methods should be regarded as implementation details, not something that the interface enforces. Of course there can be exceptions, but as a rule, you should define your interface as what the behavior is expected to be. Internal state of a given implementation shouldn't be a design concern of the interface.

Why does Google prepend while(1); to their JSON responses?

It prevents disclosure of the response through JSON hijacking.

In theory, the content of HTTP responses are protected by the Same Origin Policy: pages from one domain cannot get any pieces of information from pages on the other domain (unless explicitly allowed).

An attacker can request pages on other domains on your behalf, e.g. by using a <script src=...> or <img> tag, but it can't get any information about the result (headers, contents).

Thus, if you visit an attacker's page, it couldn't read your email from gmail.com.

Except that when using a script tag to request JSON content, the JSON is executed as JavaScript in an attacker's controlled environment. If the attacker can replace the Array or Object constructor or some other method used during object construction, anything in the JSON would pass through the attacker's code, and be disclosed.

Note that this happens at the time the JSON is executed as JavaScript, not at the time it's parsed.

There are multiple countermeasures:

Making sure the JSON never executes

By placing a while(1); statement before the JSON data, Google makes sure that the JSON data is never executed as JavaScript.

Only a legitimate page could actually get the whole content, strip the while(1);, and parse the remainder as JSON.

Things like for(;;); have been seen at Facebook for instance, with the same results.

Making sure the JSON is not valid JavaScript

Similarly, adding invalid tokens before the JSON, like &&&START&&&, makes sure that it is never executed.

Always return JSON with an Object on the outside

This is OWASP recommended way to protect from JSON hijacking and is the less intrusive one.

Similarly to the previous counter-measures, it makes sure that the JSON is never executed as JavaScript.

A valid JSON object, when not enclosed by anything, is not valid in JavaScript:

eval('{"foo":"bar"}')
// SyntaxError: Unexpected token :

This is however valid JSON:

JSON.parse('{"foo":"bar"}')
// Object {foo: "bar"}

So, making sure you always return an Object at the top level of the response makes sure that the JSON is not valid JavaScript, while still being valid JSON.

As noted by @hvd in the comments, the empty object {} is valid JavaScript, and knowing the object is empty may itself be valuable information.

Comparison of above methods

The OWASP way is less intrusive, as it needs no client library changes, and transfers valid JSON. It is unsure whether past or future browser bugs could defeat this, however. As noted by @oriadam, it is unclear whether data could be leaked in a parse error through an error handling or not (e.g. window.onerror).

Google's way requires a client library in order for it to support automatic de-serialization and can be considered to be safer with regard to browser bugs.

Both methods require server side changes in order to avoid developers accidentally sending vulnerable JSON.

Efficient way to update all rows in a table

update Hotels set Discount=30 where Hotelid >= 1 and Hotelid <= 5504

how to use "tab space" while writing in text file

use \t instead of space.

bw.write("\t"); 

How do I output an ISO 8601 formatted string in JavaScript?

The problem with toISOString is that it gives datetime only as "Z".

ISO-8601 also defines datetime with timezone difference in hours and minutes, in the forms like 2016-07-16T19:20:30+5:30 (when timezone is ahead UTC) and 2016-07-16T19:20:30-01:00 (when timezone is behind UTC).

I don't think it is a good idea to use another plugin, moment.js for such a small task, especially when you can get it with a few lines of code.



    var timezone_offset_min = new Date().getTimezoneOffset(),
        offset_hrs = parseInt(Math.abs(timezone_offset_min/60)),
        offset_min = Math.abs(timezone_offset_min%60),
        timezone_standard;

    if(offset_hrs < 10)
        offset_hrs = '0' + offset_hrs;

    if(offset_min > 10)
        offset_min = '0' + offset_min;

    // getTimezoneOffset returns an offset which is positive if the local timezone is behind UTC and vice-versa.
    // So add an opposite sign to the offset
    // If offset is 0, it means timezone is UTC
    if(timezone_offset_min < 0)
        timezone_standard = '+' + offset_hrs + ':' + offset_min;
    else if(timezone_offset_min > 0)
        timezone_standard = '-' + offset_hrs + ':' + offset_min;
    else if(timezone_offset_min == 0)
        timezone_standard = 'Z';

    // Timezone difference in hours and minutes
    // String such as +5:30 or -6:00 or Z
    console.log(timezone_standard); 


Once you have the timezone offset in hours and minutes, you can append to a datetime string.

I wrote a blog post on it : http://usefulangle.com/post/30/javascript-get-date-time-with-offset-hours-minutes

How do I install soap extension?

Please follow the below steps :

 1) Locate php.ini in your apache bin folder, I.e Apache/bin/php.ini
 2) Remove the ; from the beginning of extension=php_soap.dll
 3) Restart your Apache server (by using : 
    # /etc/init.d/apache2 restart OR 
    $ sudo /etc/init.d/apache2 restart OR 
    $ sudo service apache2 restart)
 4) Look up your phpinfo();

 you may check here as well,if this does not solve your issue:  
 https://www.php.net/manual/en/soap.requirements.php

MSSQL Error 'The underlying provider failed on Open'

I had this error and found a few solutions:

Looking at your connection string, it looks valid. I found this blog post, the problem here is that they were using Integrated Security. If you are running on IIS, your IIS user needs access to the database.

If you are using Entity Framework with Transactions, Entity Framework automatically opens and closes a connection with each database call. So when using transactions, you are attempting to spread a transaction out over multiple connections. This elevates to MSDTC.

(See this reference for more information.)

Changing my code to the following fixed it:

using (DatabaseEntities context = new DatabaseEntities())
{
    context.Connection.Open();
    // the rest
}

How do I connect to a SQL Server 2008 database using JDBC?

If your having trouble connecting, most likely the problem is that you haven't yet enabled the TCP/IP listener on port 1433. A quick "netstat -an" command will tell you if its listening. By default, SQL server doesn't enable this after installation.

Also, you need to set a password on the "sa" account and also ENABLE the "sa" account (if you plan to use that account to connect with).

Obviously, this also means you need to enable "mixed mode authentication" on your MSSQL node.

DateTime to javascript date

This should do the trick:

date.Subtract(new DateTime(1970, 1,1)).TotalMilliseconds

Java SimpleDateFormat for time zone with a colon separator?

Here's a snippet I used - with plain SimpleDateFormat. Hope somebody else may benefit from it:

public static void main(String[] args) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ") {
        public StringBuffer format(Date date, StringBuffer toAppendTo, java.text.FieldPosition pos) {
            StringBuffer toFix = super.format(date, toAppendTo, pos);
            return toFix.insert(toFix.length()-2, ':');
        };
    };
    // Usage:
    System.out.println(dateFormat.format(new Date()));
}

Output:

- Usual Output.........: 2013-06-14T10:54:07-0200
- This snippet's Output: 2013-06-14T10:54:07-02:00

Or... better, use a simpler, different, pattern:

SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
// Usage:
System.out.println(dateFormat2.format(new Date()));

Output:

- This pattern's output: 2013-06-14T10:54:07-02:00

See the docs for that.

Change background color for selected ListBox item

<UserControl.Resources>
    <Style x:Key="myLBStyle" TargetType="{x:Type ListBoxItem}">
        <Style.Resources>
            <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}"
                             Color="Transparent"/>
        </Style.Resources>
    </Style>
</UserControl.Resources> 

and

<ListBox ItemsSource="{Binding Path=FirstNames}"
         ItemContainerStyle="{StaticResource myLBStyle}">  

You just override the style of the listboxitem (see the: TargetType is ListBoxItem)

Getting execute permission to xp_cmdshell

I want to complete the answer from tchester.

(1) Enable the xp_cmdshell procedure:

-- To allow advanced options to be changed.
EXEC sp_configure 'show advanced options', 1
RECONFIGURE
GO

-- Enable the xp_cmdshell procedure
EXEC sp_configure 'xp_cmdshell', 1
RECONFIGURE
GO

(2) Create a login 'Domain\TestUser' (windows user) for the non-sysadmin user that has public access to the master database

(3) Grant EXEC permission on the xp_cmdshell stored procedure:

GRANT EXECUTE ON xp_cmdshell TO [Domain\TestUser]

(4) Create a proxy account that xp_cmdshell will be run under using sp_xp_cmdshell_proxy_account

EXEC sp_xp_cmdshell_proxy_account 'Domain\TestUser', 'pwd'
-- Note: pwd means windows password for [Domain\TestUser] account id on the box.
--       Don't include square brackets around Domain\TestUser.

(5) Grant control server permission to user

USE master;
GRANT CONTROL SERVER TO [Domain\TestUser]
GO

WPF binding to Listbox selectedItem

For me, I usually use DataContext together in order to bind two-depth property such as this question.

<TextBlock DataContext="{Binding SelectedRule}" Text="{Binding Name}" />

Or, I prefer to use ElementName because it achieves bindings only with view controls.

<TextBlock DataContext="{Binding ElementName=lbRules, Path=SelectedItem}" Text="{Binding Name}" />

How to alter SQL in "Edit Top 200 Rows" in SSMS 2008

Ctrl+3 in SQL Server 2012. Might work in 2008 too

Understanding REST: Verbs, error codes, and authentication

Simply put, you are doing this completely backward.

You should not be approaching this from what URLs you should be using. The URLs will effectively come "for free" once you've decided upon what resources are necessary for your system AND how you will represent those resources, and the interactions between the resources and application state.

To quote Roy Fielding

A REST API should spend almost all of its descriptive effort in defining the media type(s) used for representing resources and driving application state, or in defining extended relation names and/or hypertext-enabled mark-up for existing standard media types. Any effort spent describing what methods to use on what URIs of interest should be entirely defined within the scope of the processing rules for a media type (and, in most cases, already defined by existing media types). [Failure here implies that out-of-band information is driving interaction instead of hypertext.]

Folks always start with the URIs and think this is the solution, and then they tend to miss a key concept in REST architecture, notably, as quoted above, "Failure here implies that out-of-band information is driving interaction instead of hypertext."

To be honest, many see a bunch of URIs and some GETs and PUTs and POSTs and think REST is easy. REST is not easy. RPC over HTTP is easy, moving blobs of data back and forth proxied through HTTP payloads is easy. REST, however, goes beyond that. REST is protocol agnostic. HTTP is just very popular and apt for REST systems.

REST lives in the media types, their definitions, and how the application drives the actions available to those resources via hypertext (links, effectively).

There are different view about media types in REST systems. Some favor application specific payloads, while others like uplifting existing media types in to roles that are appropriate for the application. For example, on the one hand you have specific XML schemas designed suited to your application versus using something like XHTML as your representation, perhaps through microformats and other mechanisms.

Both approaches have their place, I think, the XHTML working very well in scenarios that overlap both the human driven and machine driven web, whereas the former, more specific data types I feel better facilitate machine to machine interactions. I find the uplifting of commodity formats can make content negotiation potentially difficult. "application/xml+yourresource" is much more specific as a media type than "application/xhtml+xml", as the latter can apply to many payloads which may or may not be something a machine client is actually interested in, nor can it determine without introspection.

However, XHTML works very well (obviously) in the human web where web browsers and rendering is very important.

You application will guide you in those kinds of decisions.

Part of the process of designing a REST system is discovering the first class resources in your system, along with the derivative, support resources necessary to support the operations on the primary resources. Once the resources are discovered, then the representation of those resources, as well as the state diagrams showing resource flow via hypertext within the representations because the next challenge.

Recall that each representation of a resource, in a hypertext system, combines both the actual resource representation along with the state transitions available to the resource. Consider each resource a node in a graph, with the links being the lines leaving that node to other states. These links inform clients not only what can be done, but what is required for them to be done (as a good link combines the URI and the media type required).

For example, you may have:

<link href="http://example.com/users" rel="users" type="application/xml+usercollection"/>
<link href="http://example.com/users?search" rel="search" type="application/xml+usersearchcriteria"/>

Your documentation will talk about the rel field named "users", and the media type of "application/xml+youruser".

These links may seem redundant, they're all talking to the same URI, pretty much. But they're not.

This is because for the "users" relation, that link is talking about the collection of users, and you can use the uniform interface to work with the collection (GET to retrieve all of them, DELETE to delete all of them, etc.)

If you POST to this URL, you will need to pass a "application/xml+usercollection" document, which will probably only contain a single user instance within the document so you can add the user, or not, perhaps, to add several at once. Perhaps your documentation will suggest that you can simply pass a single user type, instead of the collection.

You can see what the application requires in order to perform a search, as defined by the "search" link and it's mediatype. The documentation for the search media type will tell you how this behaves, and what to expect as results.

The takeaway here, though, is the URIs themselves are basically unimportant. The application is in control of the URIs, not the clients. Beyond a few 'entry points', your clients should rely on the URIs provided by the application for its work.

The client needs to know how to manipulate and interpret the media types, but doesn't much need to care where it goes.

These two links are semantically identical in a clients eyes:

<link href="http://example.com/users?search" rel="search" type="application/xml+usersearchcriteria"/>
<link href="http://example.com/AW163FH87SGV" rel="search" type="application/xml+usersearchcriteria"/>

So, focus on your resources. Focus on their state transitions in the application and how that's best achieved.

How to get a List<string> collection of values from app.config in WPF?

In App.config:

<add key="YOURKEY" value="a,b,c"/>

In C#:

string[] InFormOfStringArray = ConfigurationManager.AppSettings["YOURKEY"].Split(',').Select(s => s.Trim()).ToArray();
List<string> list = new List<string>(InFormOfStringArray);

how to select first N rows from a table in T-SQL?

You can use Microsoft's row_number() function to decide which rows to return. That means that you aren't limited to just the top X results, you can take pages.

SELECT * 
FROM (SELECT row_number() over (order by UserID) AS line_no, * 
      FROM dbo.User) as users
WHERE users.line_no < 10
OR users.line_no BETWEEN 34 and 67

You have to nest the original query though, because otherwise you'll get an error message telling you that you can't do what you want to in the way you probably should be able to in an ideal world.

Msg 4108, Level 15, State 1, Line 3
Windowed functions can only appear in the SELECT or ORDER BY clauses.

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

I had the same error and SOLVED by removing the DB roles db_denydatawriter and db_denydatreader of the DB user. For that, select the appropriate DB user on logins >> properties >> user mappings >> find out DB and select it >> uncheck the mentioned Db user roles. Thats it !!

Can you recommend a free light-weight MySQL GUI for Linux?

i suggest using phpmyadmin

it’s definitely the best free tool out there and it works on every system with php+mysql

How to make Java work with SQL Server?

If you are use sqljdbc4.jar, use the following code

ResultSet objResultSet = objPreparedStatement.getResultSet();
if (objResultSet == null) {
  boolean bResult = false;
  while (!bResult){
    if (objPreparedStatement.getMoreResults()){
      objResultSet = objPreparedStatement.getResultSet();
      bResult = true;
    }
  } 
}
objCachedRowSet = new CachedRowSetImpl();
objCachedRowSet.populate(objResultSet);
if (CommonUtility.isValidObject(objResultSet)) objResultSet.close();
objResultSet = null;

SQL JOIN vs IN performance?

A interesting writeup on the logical differences: SQL Server: JOIN vs IN vs EXISTS - the logical difference

I am pretty sure that assuming that the relations and indexes are maintained a Join will perform better overall (more effort goes into working with that operation then others). If you think about it conceptually then its the difference between 2 queries and 1 query.

You need to hook it up to the Query Analyzer and try it and see the difference. Also look at the Query Execution Plan and try to minimize steps.

SQL Server convert string to datetime

UPDATE MyTable SET MyDate = CONVERT(datetime, '2009/07/16 08:28:01', 120)

For a full discussion of CAST and CONVERT, including the different date formatting options, see the MSDN Library Link below:

https://docs.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql

WPF Databinding: How do I access the "parent" data context?

You could try something like this:

...Binding="{Binding RelativeSource={RelativeSource FindAncestor, 
AncestorType={x:Type Window}}, Path=DataContext.AllowItemCommand}" ...

How Do I Insert a Byte[] Into an SQL Server VARBINARY Column

check this image link for all steps https://drive.google.com/open?id=0B0-Ll2y6vo_sQ29hYndnbGZVZms

STEP1: I created a field of type varbinary in table

STEP2: I created a stored procedure to accept a parameter of type sql_variant

STEP3: In my front end asp.net page, I created a sql data source parameter of object type

        <tr>
        <td>
            UPLOAD DOCUMENT</td>
        <td>
            <asp:FileUpload ID="FileUpload1" runat="server" />
            <asp:Button ID="btnUpload" runat="server" Text="Upload" />
            <asp:SqlDataSource ID="sqldsFileUploadConn" runat="server" 
                ConnectionString="<%$ ConnectionStrings: %>" 
                InsertCommand="ph_SaveDocument"     
               InsertCommandType="StoredProcedure">
                <InsertParameters>
                    <asp:Parameter Name="DocBinaryForm" Type="Object" />
                </InsertParameters>

             </asp:SqlDataSource>
        </td>
        <td>
            &nbsp;</td>
    </tr>

STEP 4: In my code behind, I try to upload the FileBytes from FileUpload Control via this stored procedure call using a sql data source control

      Dim filebytes As Object
      filebytes = FileUpload1.FileBytes()
      sqldsFileUploadConn.InsertParameters("DocBinaryForm").DefaultValue = filebytes.ToString
      Dim uploadstatus As Int16 = sqldsFileUploadConn.Insert()

               ' ... code continues ... '

C# generic list <T> how to get the type of T?

Given an object which I suspect to be some kind of IList<>, how can I determine of what it's an IList<>?

Here's a reliable solution. My apologies for length - C#'s introspection API makes this suprisingly difficult.

/// <summary>
/// Test if a type implements IList of T, and if so, determine T.
/// </summary>
public static bool TryListOfWhat(Type type, out Type innerType)
{
    Contract.Requires(type != null);

    var interfaceTest = new Func<Type, Type>(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IList<>) ? i.GetGenericArguments().Single() : null);

    innerType = interfaceTest(type);
    if (innerType != null)
    {
        return true;
    }

    foreach (var i in type.GetInterfaces())
    {
        innerType = interfaceTest(i);
        if (innerType != null)
        {
            return true;
        }
    }

    return false;
}

Example usage:

    object value = new ObservableCollection<int>();
Type innerType;
TryListOfWhat(value.GetType(), out innerType).Dump();
innerType.Dump();

Returns

True
typeof(Int32)

MySQL: @variable vs. variable. What's the difference?

In MySQL, @variable indicates a user-defined variable. You can define your own.

SET @a = 'test';
SELECT @a;

Outside of stored programs, a variable, without @, is a system variable, which you cannot define yourself.

The scope of this variable is the entire session. That means that while your connection with the database exists, the variable can still be used.

This is in contrast with MSSQL, where the variable will only be available in the current batch of queries (stored procedure, script, or otherwise). It will not be available in a different batch in the same session.

What is the best free SQL GUI for Linux for various DBMS systems

For Oracle, I highly recommend the free Oracle SQL Developer

http://www.oracle.com/technology/products/database/sql_developer/index.html

The doucmentation states it also works with non-oracle databases - i've never tried that feature myself, but I do know that it works really well with Oracle

Data binding to SelectedItem in a WPF Treeview

After studying the Internet for a day I found my own solution for selecting an item after create a normal treeview in a normal WPF/C# environment

private void BuildSortTree(int sel)
        {
            MergeSort.Items.Clear();
            TreeViewItem itTemp = new TreeViewItem();
            itTemp.Header = SortList[0];
            MergeSort.Items.Add(itTemp);
            TreeViewItem prev;
            itTemp.IsExpanded = true;
            if (0 == sel) itTemp.IsSelected= true;
            prev = itTemp;
            for(int i = 1; i<SortList.Count; i++)
            {

                TreeViewItem itTempNEW = new TreeViewItem();
                itTempNEW.Header = SortList[i];
                prev.Items.Add(itTempNEW);
                itTempNEW.IsExpanded = true;
                if (i == sel) itTempNEW.IsSelected = true;
                prev = itTempNEW ;
            }
        }

Is it possible to have a default parameter for a mysql stored procedure?

We worked around this limitation by adding a simple IF statement in the stored procedure. Practically we pass an empty string whenever we want to save the default value in the DB.

CREATE DEFINER=`test`@`%` PROCEDURE `myProc`(IN myVarParam VARCHAR(40))
BEGIN
  IF myVarParam = '' THEN SET myVarParam = 'default-value'; END IF;

  ...your code here...
END

How to COUNT rows within EntityFramework without loading contents?

I think this should work...

var query = from m in context.MyTable
            where m.MyContainerId == '1' // or what ever the foreign key name is...
            select m;

var count = query.Count();

Temporary tables in stored procedures

For all those recommending using table variables, be cautious in doing so. Table variable cannot be indexed whereas a temp table can be. A table variable is best when working with small amounts of data but if you are working on larger sets of data (e.g. 50k records) a temp table will be much faster than a table variable.

Also keep in mind that you can't rely on a try/catch to force a cleanup within the stored procedure. certain types of failures cannot be caught within a try/catch (e.g. compile failures due to delayed name resolution) if you want to be really certain you may need to create a wrapper stored procedure that can do a try/catch of the worker stored procedure and do the cleanup there.

e.g. create proc worker AS BEGIN -- do something here END

create proc wrapper AS
BEGIN
    Create table #...
    BEGIN TRY
       exec worker
       exec worker2 -- using same temp table
       -- etc
    END TRY
    END CATCH
       -- handle transaction cleanup here
       drop table #...
    END CATCH 
END

One place where table variables are always useful is they do not get rolled back when a transaction is rolled back. This can be useful for capturing debug data that you want to commit outside the primary transaction.

How to get a ListBox ItemTemplate to stretch horizontally the full width of the ListBox?

I'm sure this is a duplicate, but I can't find a question with the same answer.

Add HorizontalContentAlignment="Stretch" to your ListBox. That should do the trick. Just be careful with auto-complete because it is so easy to get HorizontalAlignment by mistake.

Large WCF web service request failing with (400) HTTP Bad Request

For what it is worth, an additional consideration when using .NET 4.0 is that if a valid endpoint is not found in your configuration, a default endpoint will be automatically created and used.

The default endpoint will use all default values so if you think you have a valid service configuration with a large value for maxReceivedMessageSize etc., but there is something wrong with the configuration, you would still get the 400 Bad Request since a default endpoint would be created and used.

This is done silently so it is hard to detect. You will see messages to this effect (e.g. 'No Endpoint found for Service, creating Default Endpoint' or similar) if you turn on tracing on the server but there is no other indication (to my knowledge).

"Items collection must be empty before using ItemsSource."

I encountered this error in another situation. I tried to defined a style for TreeViewItems directly within the <TreeView>, but instead should have embedded that within <TreeView.ItemContainerStyle>.

Wrong:

<TreeView ItemsSource="{Binding ExampleListView}">
    <Style TargetType="{x:Type TreeViewItem}">
        <Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}"/>
        <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}"/>
    </Style>
    <TreeView.ItemTemplate>
        <HierarchicalDataTemplate ItemsSource="{Binding SubItemListList}">
        ...
        </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>
</TreeView>

Correct:

<TreeView ItemsSource="{Binding ExampleListView}">
    <TreeView.ItemContainerStyle>
        <Style TargetType="TreeViewItem">
            <Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}"/>
            <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}"/>
        </Style>
    </TreeView.ItemContainerStyle>
    <TreeView.ItemTemplate>
        <HierarchicalDataTemplate ItemsSource="{Binding SubItemListList}">
        ...
        </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>
</TreeView>

how can I enable scrollbars on the WPF Datagrid?

Put the DataGrid in a Grid, DockPanel, ContentControl or directly in the Window. A vertically-oriented StackPanel will give its children whatever vertical space they ask for - even if that means it is rendered out of view.

WPF MVVM ComboBox SelectedItem or SelectedValue not working

I solved the problem by adding dispatcher in UserControl_Loaded event

 Dispatcher.BeginInvoke(DispatcherPriority.Loaded, new Action(() =>
 {
     combobox.SelectedIndex = 0;
 }));

How to randomly select rows in SQL?

SELECT TOP 5 Id, Name FROM customerNames
ORDER BY NEWID()

That said, everybody seems to come to this page for the more general answer to your question:

Selecting a random row in SQL

Select a random row with MySQL:

SELECT column FROM table
ORDER BY RAND()
LIMIT 1

Select a random row with PostgreSQL:

SELECT column FROM table
ORDER BY RANDOM()
LIMIT 1

Select a random row with Microsoft SQL Server:

SELECT TOP 1 column FROM table
ORDER BY NEWID()

Select a random row with IBM DB2

SELECT column, RAND() as IDX 
FROM table 
ORDER BY IDX FETCH FIRST 1 ROWS ONLY

Select a random record with Oracle:

SELECT column FROM
( SELECT column FROM table
ORDER BY dbms_random.value )
WHERE rownum = 1

Select a random row with sqlite:

SELECT column FROM table 
ORDER BY RANDOM() LIMIT 1

Get only the Date part of DateTime in mssql

Another nifty way is:

DATEADD(dd, 0, DATEDIFF(dd, 0, [YourDate]))

Which gets the number of days from DAY 0 to YourDate and the adds it to DAY 0 to set the baseline again. This method (or "derivatives" hereof) can be used for a bunch of other date manipulation.

Edit - other date calculations:

First Day of Month:

DATEADD(mm, DATEDIFF(mm, 0, getdate()), 0)

First Day of the Year:

DATEADD(yy, DATEDIFF(yy, 0, getdate()), 0)

First Day of the Quarter:

DATEADD(qq, DATEDIFF(qq, 0, getdate()), 0)

Last Day of Prior Month:

DATEADD(ms, -3, DATEADD(mm, DATEDIFF(mm, 0, getdate()), 0))

Last Day of Current Month:

DATEADD(ms, -3, DATEADD(mm, DATEDIFF(m, 0, getdate()) + 1, 0))

Last Day of Current Year:

DATEADD(ms, -3, DATEADD(yy, DATEDIFF(yy, 0, getdate()) + 1, 0))

First Monday of the Month:

DATEADD(wk, DATEDIFF(wk, 0, DATEADD(dd, 6 - DATEPART(day, getdate()), getdate())), 0)        

Edit: True, Joe, it does not add it to DAY 0, it adds 0 (days) to the number of days which basically just converts it back to a datetime.

Binding a WPF ComboBox to a custom list

You set the DisplayMemberPath and the SelectedValuePath to "Name", so I assume that you have a class PhoneBookEntry with a public property Name.

Have you set the DataContext to your ConnectionViewModel object?

I copied you code and made some minor modifications, and it seems to work fine. I can set the viewmodels PhoneBookEnty property and the selected item in the combobox changes, and I can change the selected item in the combobox and the view models PhoneBookEntry property is set correctly.

Here is my XAML content:

<Window x:Class="WpfApplication6.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window1" Height="300" Width="300">
<Grid>
    <StackPanel>
        <Button Click="Button_Click">asdf</Button>
        <ComboBox ItemsSource="{Binding Path=PhonebookEntries}"
                  DisplayMemberPath="Name"
                  SelectedValuePath="Name"
                  SelectedValue="{Binding Path=PhonebookEntry}" />
    </StackPanel>
</Grid>
</Window>

And here is my code-behind:

namespace WpfApplication6
{

    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
            ConnectionViewModel vm = new ConnectionViewModel();
            DataContext = vm;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            ((ConnectionViewModel)DataContext).PhonebookEntry = "test";
        }
    }

    public class PhoneBookEntry
    {
        public string Name { get; set; }

        public PhoneBookEntry(string name)
        {
            Name = name;
        }

        public override string ToString()
        {
            return Name;
        }
    }

    public class ConnectionViewModel : INotifyPropertyChanged
    {
        public ConnectionViewModel()
        {
            IList<PhoneBookEntry> list = new List<PhoneBookEntry>();
            list.Add(new PhoneBookEntry("test"));
            list.Add(new PhoneBookEntry("test2"));
            _phonebookEntries = new CollectionView(list);
        }

        private readonly CollectionView _phonebookEntries;
        private string _phonebookEntry;

        public CollectionView PhonebookEntries
        {
            get { return _phonebookEntries; }
        }

        public string PhonebookEntry
        {
            get { return _phonebookEntry; }
            set
            {
                if (_phonebookEntry == value) return;
                _phonebookEntry = value;
                OnPropertyChanged("PhonebookEntry");
            }
        }

        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
        public event PropertyChangedEventHandler PropertyChanged;
    }
}

Edit: Geoffs second example does not seem to work, which seems a bit odd to me. If I change the PhonebookEntries property on the ConnectionViewModel to be of type ReadOnlyCollection, the TwoWay binding of the SelectedValue property on the combobox works fine.

Maybe there is an issue with the CollectionView? I noticed a warning in the output console:

System.Windows.Data Warning: 50 : Using CollectionView directly is not fully supported. The basic features work, although with some inefficiencies, but advanced features may encounter known bugs. Consider using a derived class to avoid these problems.

Edit2 (.NET 4.5): The content of the DropDownList can be based on ToString() and not of DisplayMemberPath, while DisplayMemberPath specifies the member for the selected and displayed item only.

How to autosize and right-align GridViewColumn data in WPF?

I liked user1333423's solution except that it always re-sized every column; i needed to allow some columns to be fixed width. So in this version columns with a width set to "Auto" will be auto-sized and those set to a fixed amount will not be auto-sized.

public class AutoSizedGridView : GridView
{
    HashSet<int> _autoWidthColumns;

    protected override void PrepareItem(ListViewItem item)
    {
        if (_autoWidthColumns == null)
        {
            _autoWidthColumns = new HashSet<int>();

            foreach (var column in Columns)
            {
                if(double.IsNaN(column.Width))
                    _autoWidthColumns.Add(column.GetHashCode());
            }                
        }

        foreach (GridViewColumn column in Columns)
        {
            if (_autoWidthColumns.Contains(column.GetHashCode()))
            {
                if (double.IsNaN(column.Width))
                    column.Width = column.ActualWidth;

                column.Width = double.NaN;                    
            }          
        }

        base.PrepareItem(item);
    }        
}

MSSQL Select statement with incremental integer column... not from a table

You can start with a custom number and increment from there, for example you want to add a cheque number for each payment you can do:

select @StartChequeNumber = 3446;
SELECT 
((ROW_NUMBER() OVER(ORDER BY AnyColumn)) + @StartChequeNumber ) AS 'ChequeNumber'
,* FROM YourTable

will give the correct cheque number for each row.

SQL Server: Database stuck in "Restoring" state

I had a similar incident with stopping a log shipping secondary server. After the command to remove the server from log shipping and stopped the log shipping from primary server the database on secondary server got stuck in restoring status after the command

RESTORE DATABASE <database name> WITH RECOVERY

The database messages:

RESTORE DATABASE successfully processed 0 pages in 18.530 seconds (0.000 MB/sec).

The database was usable again after those 18 seconds.

How can I get a vertical scrollbar in my ListBox?

I was having the same problem, I had a ComboBox followed by a ListBox in a StackPanel and the scroll bar for the ListBox was not showing up. I solved this by putting the two in a DockPanel instead. I set the ComboBox DockPanel.Dock="Top" and let the ListBox fill the remaining space.

How do I shrink my SQL Server Database?

"Therefore it's reasonable to assume much space should now be retrievable."

Apologies if I misunderstood the question, but are you sure it's the database and not the log files that are using up the space? Check to see what recovery model the database is in. Chances are it's in Full, which means the log file is never truncated. If you don't need a complete record of every transaction, you should be able to change to Simple, which will truncate the logs. You can shrink the database during the process. Assuming things go right, the process looks like:

  1. Backup the database!
  2. Change to Simple Recovery
  3. Shrink db (right-click db, choose all tasks > shrink db -> set to 10% free space)
  4. Verify that the space has been reclaimed, if not you might have to do a full backup

If that doesn't work (or you get a message saying "log file is full" when you try to switch recovery modes), try this:

  1. Backup
  2. Kill all connections to the db
  3. Detach db (right-click > Detach or right-click > All Tasks > Detach)
  4. Delete the log (ldf) file
  5. Reattach the db
  6. Change the recovery mode

etc.

Using variable in SQL LIKE statement

This works for me on the Northwind sample DB, note that SearchLetter has 2 characters to it and SearchLetter also has to be declared for this to run:

declare @SearchLetter2 char(2)
declare @SearchLetter char(1)
Set @SearchLetter = 'A'
Set @SearchLetter2 = @SearchLetter+'%'
select * from Customers where ContactName like @SearchLetter2 and Region='WY'

How to connect to local instance of SQL Server 2008 Express

var.connectionstring = "server=localhost; database=dbname; integrated security=yes"

or

var.connectionstring = "server=localhost; database=dbname; login=yourlogin; pwd=yourpass"

How do I calculate tables size in Oracle

IIRC the tables you need are DBA_TABLES, DBA_EXTENTS or DBA_SEGMENTS and DBA_DATA_FILES. There are also USER_ and ALL_ versions of these for tables you can see if you don't have administration permissions on the machine.

Cannot truncate table because it is being referenced by a FOREIGN KEY constraint?

I write the following ways and tried to parameterized them, so you can Run them in a Query document Or Make a useful SP with them easily.

A) Delete

If your table has not millions of records this works good and hasn't any Alter commands:

---------------------------------------------------------------
------------------- Just Fill Parameters Value ----------------
---------------------------------------------------------------
DECLARE @DbName AS NVARCHAR(30) = 'MyDb'         --< Db Name
DECLARE @Schema AS NVARCHAR(30) = 'dbo'          --< Schema
DECLARE @TableName AS NVARCHAR(30) = 'Book'      --< Table Name
------------------ /Just Fill Parameters Value ----------------

DECLARE @Query AS NVARCHAR(500) = 'Delete FROM ' + @TableName

EXECUTE sp_executesql @Query
SET @Query=@DbName+'.'+@Schema+'.'+@TableName
DBCC CHECKIDENT (@Query,RESEED, 0)
  • In above answer of mine the method of resolve the mentioned problem in the question is based on @s15199d answer.

B) Truncate

If your table has millions of records or you hasn't any problem with Alter command in your codes, then use this one:

--   Book                               Student
--
--   |  BookId  | Field1 |              | StudentId |  BookId  |
--   ---------------------              ------------------------ 
--   |    1     |    A   |              |     2     |    1     |  
--   |    2     |    B   |              |     1     |    1     |
--   |    3     |    C   |              |     2     |    3     |  

---------------------------------------------------------------
------------------- Just Fill Parameters Value ----------------
---------------------------------------------------------------
DECLARE @DbName AS NVARCHAR(30) = 'MyDb'
DECLARE @Schema AS NVARCHAR(30) = 'dbo'
DECLARE @TableName_ToTruncate AS NVARCHAR(30) = 'Book'

DECLARE @TableName_OfOwnerOfConstraint AS NVARCHAR(30) = 'Student' --< Decelations About FK_Book_Constraint
DECLARE @Ref_ColumnName_In_TableName_ToTruncate AS NVARCHAR(30) = 'BookId' --< Decelations About FK_Book_Constraint
DECLARE @FK_ColumnName_In_TableOfOwnerOfConstraint AS NVARCHAR(30) = 'Fk_BookId' --< Decelations About FK_Book_Constraint
DECLARE @FK_ConstraintName AS NVARCHAR(30) = 'FK_Book_Constraint'                --< Decelations About FK_Book_Constraint
------------------ /Just Fill Parameters Value ----------------

DECLARE @Query AS NVARCHAR(2000)

SET @Query= 'ALTER TABLE '+@TableName_OfOwnerOfConstraint+' DROP CONSTRAINT '+@FK_ConstraintName
EXECUTE sp_executesql @Query

SET @Query= 'Truncate Table '+ @TableName_ToTruncate
EXECUTE sp_executesql @Query

SET @Query= 'ALTER TABLE '+@TableName_OfOwnerOfConstraint+' ADD CONSTRAINT '+@FK_ConstraintName+' FOREIGN KEY('+@FK_ColumnName_In_TableOfOwnerOfConstraint+') REFERENCES '+@TableName_ToTruncate+'('+@Ref_ColumnName_In_TableName_ToTruncate+')'
EXECUTE sp_executesql @Query
  • In above answer of mine the method of resolve the mentioned problem in the question is based on @LauroWolffValenteSobrinho answer.

  • If you have more than one CONSTRAINT then you should append its codes like me to the above query

  • Also you can change the above code base @SerjSagan answer to disable an enable the constraint

SQL Server equivalent to Oracle's CREATE OR REPLACE VIEW

For reference from SQL Server 2016 SP1+ you could use CREATE OR ALTER VIEW syntax.

MSDN CREATE VIEW:

CREATE [ OR ALTER ] VIEW [ schema_name . ] view_name [ (column [ ,...n ] ) ]   
[ WITH <view_attribute> [ ,...n ] ]   
AS select_statement   
[ WITH CHECK OPTION ]   
[ ; ]

OR ALTER

Conditionally alters the view only if it already exists.

db<>fiddle demo

How to list only top level directories in Python?

being a newbie here i can't yet directly comment but here is a small correction i'd like to add to the following part of ??O?????'s answer :

If you prefer full pathnames, then use this function:

def listdirs(folder):  
  return [
    d for d in (os.path.join(folder, d1) for d1 in os.listdir(folder))
    if os.path.isdir(d)
]

for those still on python < 2.4: the inner construct needs to be a list instead of a tuple and therefore should read like this:

def listdirs(folder):  
  return [
    d for d in [os.path.join(folder, d1) for d1 in os.listdir(folder)]
    if os.path.isdir(d)
  ]

otherwise one gets a syntax error.

How do I do a simple 'Find and Replace" in MsSQL?

If you are working with SQL Server 2005 or later there is also a CLR library available at http://www.sqlsharp.com/ that provides .NET implementations of string and RegEx functions which, depending on your volume and type of data may be easier to use and in some cases the .NET string manipulation functions can be more efficient than T-SQL ones.

Databinding an enum property to a ComboBox in WPF

you can consider something like that:

  1. define a style for textblock, or any other control you want to use to display your enum:

    <Style x:Key="enumStyle" TargetType="{x:Type TextBlock}">
        <Setter Property="Text" Value="&lt;NULL&gt;"/>
        <Style.Triggers>
            <Trigger Property="Tag">
                <Trigger.Value>
                    <proj:YourEnum>Value1<proj:YourEnum>
                </Trigger.Value>
                <Setter Property="Text" Value="{DynamicResource yourFriendlyValue1}"/>
            </Trigger>
            <!-- add more triggers here to reflect your enum -->
        </Style.Triggers>
    </Style>
    
  2. define your style for ComboBoxItem

    <Style TargetType="{x:Type ComboBoxItem}">
        <Setter Property="ContentTemplate">
            <Setter.Value>
                <DataTemplate>
                    <TextBlock Tag="{Binding}" Style="{StaticResource enumStyle}"/>
                </DataTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    
  3. add a combobox and load it with your enum values:

    <ComboBox SelectedValue="{Binding Path=your property goes here}" SelectedValuePath="Content">
        <ComboBox.Items>
            <ComboBoxItem>
                <proj:YourEnum>Value1</proj:YourEnum>
            </ComboBoxItem>
        </ComboBox.Items>
    </ComboBox>
    

if your enum is large, you can of course do the same in code, sparing a lot of typing. i like that approach, since it makes localization easy - you define all the templates once, and then, you only update your string resource files.

SQL Query for Logins

EXEC sp_helplogins

You can also pass an "@LoginNamePattern" parameter to get information about a specific login:

EXEC sp_helplogins @LoginNamePattern='fred'

Compare a date string to datetime in SQL Server?

Just compare the year, month and day values.

Declare @DateToSearch DateTime
Set @DateToSearch = '14 AUG 2008'

SELECT * 
FROM table1
WHERE Year(column_datetime) = Year(@DateToSearch)
      AND Month(column_datetime) = Month(@DateToSearch)
      AND Day(column_datetime) = Day(@DateToSearch)

Storing a file in a database as opposed to the file system?

If you can move to SQL Server 2008, you can take advantage of the FILESTREAM support which gives you the best of both - the files are stored in the filesystem, but the database integration is much better than just storing a filepath in a varchar field. Your query can return a standard .NET file stream, which makes the integration a lot simpler.

Getting Started with FILESTREAM Storage

set pythonpath before import statements

As also noted in the docs here.
Go to Python X.X/Lib and add these lines to the site.py there,

import sys
sys.path.append("yourpathstring")

This changes your sys.path so that on every load, it will have that value in it..

As stated here about site.py,

This module is automatically imported during initialization. Importing this module will append site-specific paths to the module search path and add a few builtins.

For other possible methods of adding some path to sys.path see these docs

commons httpclient - Adding query string parameters to GET/POST request

If you want to add a query parameter after you have created the request, try casting the HttpRequest to a HttpBaseRequest. Then you can change the URI of the casted request:

HttpGet someHttpGet = new HttpGet("http://google.de");

URI uri = new URIBuilder(someHttpGet.getURI()).addParameter("q",
        "That was easy!").build();

((HttpRequestBase) someHttpGet).setURI(uri);

How to create a generic array?

Problem is that while runtime generic type is erased so new E[10] would be equivalent to new Object[10].

This would be dangerous because it would be possible to put in array other data than of E type. That is why you need to explicitly say that type you want by either

Twitter bootstrap collapse: change display of toggle button

Easier with inline coding

<button type="button" ng-click="showmore = (showmore !=null && showmore) ? false : true;" class="btn float-right" data-toggle="collapse" data-target="#moreoptions">
            <span class="glyphicon" ng-class="showmore ? 'glyphicon-collapse-up': 'glyphicon-collapse-down'"></span>
            {{ showmore !=null && showmore ? "Hide More Options" : "Show More Options" }}
        </button>


<div id="moreoptions" class="collapse">Your Panel</div>

Run PHP function on html button click

It depends on what function you want to run. If you need something done on server side, like querying a database or setting something in the session or anything that can not be done on client side, you need AJAX, else you can do it on client-side with JavaScript. Don't make the server work when you can do what you need to do on client side.

jQuery provides an easy way to do ajax : http://api.jquery.com/jQuery.ajax/

What charset does Microsoft Excel use when saving files?

I had a similar problem last week. I received a number of CSV files with varying encodings. Before importing into the database I then used the chardet libary to automatically sniff out the correct encoding.

Chardet is a port from Mozillas character detection engine and if the sample size is large enough (one accentuated character will not do) works really well.

MacOS Xcode CoreSimulator folder very big. Is it ok to delete content?

That directory is part of your user data and you can delete any user data without affecting Xcode seriously. You can delete the whole CoreSimulator/ directory. Xcode will recreate fresh instances there for you when you do your next simulator run. If you can afford losing any previous simulator data of your apps this is the easy way to get space.

Update: A related useful app is "DevCleaner for Xcode" https://apps.apple.com/app/devcleaner-for-xcode/id1388020431

A select query selecting a select statement

I was over-complicating myself. After taking a long break and coming back, the desired output could be accomplished by this simple query:

SELECT Sandwiches.[Sandwich Type], Sandwich.Bread, Count(Sandwiches.[SandwichID]) AS [Total Sandwiches]
FROM Sandwiches
GROUP BY Sandwiches.[Sandwiches Type], Sandwiches.Bread;

Thanks for answering, it helped my train of thought.

Change collations of all columns of all tables in SQL Server

I made a little change on the script.

DECLARE @collate nvarchar(100);
DECLARE @table sysname;
DECLARE @schema sysname;
DECLARE @objectId int;
DECLARE @column_name nvarchar(255);
DECLARE @column_id int;
DECLARE @data_type nvarchar(255);
DECLARE @max_length int;
DECLARE @row_id int;
DECLARE @sql nvarchar(max);
DECLARE @sql_column nvarchar(max);
DECLARE @is_Nullable bit;
DECLARE @null nvarchar(25);

SET @collate = 'Latin1_General_CI_AS';

DECLARE local_table_cursor CURSOR FOR

SELECT tbl.TABLE_SCHEMA,[name],obj.id
FROM sysobjects as obj
inner join INFORMATION_SCHEMA.TABLES as tbl
on obj.name = tbl.TABLE_NAME
WHERE OBJECTPROPERTY(obj.id, N'IsUserTable') = 1

OPEN local_table_cursor
FETCH NEXT FROM local_table_cursor
INTO @schema, @table, @objectId;

WHILE @@FETCH_STATUS = 0
BEGIN
    DECLARE local_change_cursor CURSOR FOR
    SELECT ROW_NUMBER() OVER (ORDER BY c.column_id) AS row_id
        , c.name column_name
        , t.Name data_type
        , c.max_length
        , c.column_id
        , c.is_nullable
    FROM sys.columns c
    JOIN sys.types t ON c.system_type_id = t.system_type_id
    LEFT OUTER JOIN sys.index_columns ic ON ic.object_id = c.object_id AND ic.column_id = c.column_id
    LEFT OUTER JOIN sys.indexes i ON ic.object_id = i.object_id AND ic.index_id = i.index_id
    WHERE c.object_id = @objectId
    ORDER BY c.column_id

    OPEN local_change_cursor
    FETCH NEXT FROM local_change_cursor
    INTO @row_id, @column_name, @data_type, @max_length, @column_id, @is_nullable

    WHILE @@FETCH_STATUS = 0
    BEGIN
        IF (@max_length = -1) SET @max_length = 4000;
        set @null=' NOT NULL'
        if (@is_nullable = 1) Set @null=' NULL'
        if (@Data_type='nvarchar') set @max_length=cast(@max_length/2 as bigint)
        IF (@data_type LIKE '%char%')
        BEGIN TRY
            SET @sql = 'ALTER TABLE ' + @schema + '.' + @table + ' ALTER COLUMN [' + rtrim(@column_name) + '] ' + @data_type + '(' + CAST(@max_length AS nvarchar(100)) +  ') COLLATE ' + @collate + @null
            PRINT @sql
            EXEC sp_executesql @sql
        END TRY
        BEGIN CATCH
          PRINT 'ERROR: Some index or contraint rely on the column ' + @column_name + '. No conversion possible.'
          PRINT @sql
        END CATCH

        FETCH NEXT FROM local_change_cursor
        INTO @row_id, @column_name, @data_type, @max_length, @column_id, @is_Nullable

    END

    CLOSE local_change_cursor
    DEALLOCATE local_change_cursor

    FETCH NEXT FROM local_table_cursor
    INTO @schema,@table,@objectId

END

CLOSE local_table_cursor
DEALLOCATE local_table_cursor

GO

Display a decimal in scientific notation

To convert a Decimal to scientific notation without needing to specify the precision in the format string, and without including trailing zeros, I'm currently using

def sci_str(dec):
    return ('{:.' + str(len(dec.normalize().as_tuple().digits) - 1) + 'E}').format(dec)

print( sci_str( Decimal('123.456000') ) )    # 1.23456E+2

To keep any trailing zeros, just remove the normalize().

Hosting ASP.NET in IIS7 gives Access is denied?

If the IUSR user is already specified in Authentication and you're still getting this issue, it could be that your Directory Listing isn't enabled. Be sure to check that. That was the case for me.

How to bring back "Browser mode" in IE11?

In IE11 we can change user agent to IE10, IE9 and even as windows phone. It is really good

Difference between System.DateTime.Now and System.DateTime.Today

The DateTime.Now property returns the current date and time, for example 2011-07-01 10:09.45310.

The DateTime.Today property returns the current date with the time compnents set to zero, for example 2011-07-01 00:00.00000.

The DateTime.Today property actually is implemented to return DateTime.Now.Date:

public static DateTime Today {
  get {
    DateTime now = DateTime.Now;
    return now.Date;
  }
}

What is the difference between SQL Server 2012 Express versions?

Scroll down on that page and you'll see:

Express with Tools (with LocalDB) Includes the database engine and SQL Server Management Studio Express)
This package contains everything needed to install and configure SQL Server as a database server. Choose either LocalDB or Express depending on your needs above.

That's the SQLEXPRWT_x64_ENU.exe download.... (WT = with tools)


Express with Advanced Services (contains the database engine, Express Tools, Reporting Services, and Full Text Search)
This package contains all the components of SQL Express. This is a larger download than “with Tools,” as it also includes both Full Text Search and Reporting Services.

That's the SQLEXPRADV_x64_ENU.exe download ... (ADV = Advanced Services)


The SQLEXPR_x64_ENU.exe file is just the database engine - no tools, no Reporting Services, no fulltext-search - just barebones engine.

matrix multiplication algorithm time complexity

In matrix multiplication there are 3 for loop, we are using since execution of each for loop requires time complexity O(n). So for three loops it becomes O(n^3)

android download pdf from url then open it with a pdf reader

Download source code from here (Open Pdf from url in Android Programmatically)

MainActivity.java

package com.deepshikha.openpdf;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

public class MainActivity extends AppCompatActivity {
    WebView webview;
    ProgressBar progressbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        webview = (WebView)findViewById(R.id.webview);
        progressbar = (ProgressBar) findViewById(R.id.progressbar);
        webview.getSettings().setJavaScriptEnabled(true);
        String filename ="http://www3.nd.edu/~cpoellab/teaching/cse40816/android_tutorial.pdf";
        webview.loadUrl("http://docs.google.com/gview?embedded=true&url=" + filename);

        webview.setWebViewClient(new WebViewClient() {

            public void onPageFinished(WebView view, String url) {
                // do your stuff here
                progressbar.setVisibility(View.GONE);
            }
        });

    }
}

Thanks!

UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block

I resolve the problem. It's very simple . if do you checking care the problem may be because the auxiliar variable has whitespace. Why ? I don't know but yus must use the trim() method and will resolve the problem

Make scrollbars only visible when a Div is hovered over?

Give the div a fixed height and srcoll:hidden; and on hover change the scroll to auto;

#test_scroll{ height:300px; overflow:hidden;}
#test_scroll:hover{overflow-y:auto;}

Here is an example. http://jsfiddle.net/Lywpk/

Apache - MySQL Service detected with wrong path. / Ports already in use

  • Ok it's very easy actually to solve this...most of you who are presented with this problem probably don't even realize you don't have the full software yet installed :) I tried looking online with little success except some1 mentioned you need to look for those services running already. Forexample problem with filezilla you look in task manager for filezilla and you stop the process then you click the X in the xampp control pannel to install filezilla and then click run and it should start the service normally showing you a green lite with a check mark.

  • Same goes for mysql issues.

  • As for the apache problem, it usualy is a problem with the port being overtaken by skype or some other program, but you can find info how to solve that on the net easily :)

Python "SyntaxError: Non-ASCII character '\xe2' in file"

I had the same error while copying and pasting a comment from the web

For me it was a single quote (') in the word

I just erased it and re-typed it.

CSS3 Transition not working

HTML:

<div class="foo">
    /* whatever is required */
</div>

CSS:

.foo {
    top: 0;
    transition: top ease 0.5s;
}

.foo:hover{
    top: -10px;
}

This is just a basic transition to ease the div tag up by 10px when it is hovered on. The transition property's values can be edited along with the class.hover properties to determine how the transition works.

c++ compile error: ISO C++ forbids comparison between pointer and integer

You need the change those double quotation marks into singles. ie. if (answer == 'y') returns true;

Here is some info on String Literals in C++: http://msdn.microsoft.com/en-us/library/69ze775t%28VS.80%29.aspx

What does !important mean in CSS?

The !important rule is a way to make your CSS cascade but also have the rules you feel are most crucial always be applied. A rule that has the !important property will always be applied no matter where that rule appears in the CSS document.

So, if you have the following:

.class {
   color: red !important;
}
.outerClass .class {
   color: blue;
}

the rule with the important will be the one applied (not counting specificity)

I believe !important appeared in CSS1 so every browser supports it (IE4 to IE6 with a partial implementation, IE7+ full)

Also, it's something that you don't want to use pretty often, because if you're working with other people you can override other properties.

How do I center an SVG in a div?

None of these answers worked for me. This is how I did it.

position: relative;
left: 50%;
-webkit-transform: translateX(-50%);
-ms-transform: translateX(-50%);
transform: translateX(-50%);

Accessing private member variables from prototype-defined functions

see Doug Crockford's page on this. You have to do it indirectly with something that can access the scope of the private variable.

another example:

Incrementer = function(init) {
  var counter = init || 0;  // "counter" is a private variable
  this._increment = function() { return counter++; }
  this._set = function(x) { counter = x; }
}
Incrementer.prototype.increment = function() { return this._increment(); }
Incrementer.prototype.set = function(x) { return this._set(x); }

use case:

js>i = new Incrementer(100);
[object Object]
js>i.increment()
100
js>i.increment()
101
js>i.increment()
102
js>i.increment()
103
js>i.set(-44)
js>i.increment()
-44
js>i.increment()
-43
js>i.increment()
-42

How to make a div 100% height of the browser window

You don't mention a few important details like:

  • Is the layout fixed width?
  • Are either or both of the columns fixed width?

Here's one possibility:

_x000D_
_x000D_
body,_x000D_
div {_x000D_
  margin: 0;_x000D_
  border: 0 none;_x000D_
  padding: 0;_x000D_
}_x000D_
_x000D_
html,_x000D_
body,_x000D_
#wrapper,_x000D_
#left,_x000D_
#right {_x000D_
  height: 100%;_x000D_
  min-height: 100%;_x000D_
}_x000D_
_x000D_
#wrapper {_x000D_
  margin: 0 auto;_x000D_
  overflow: hidden;_x000D_
  width: 960px; // width optional_x000D_
}_x000D_
_x000D_
#left {_x000D_
  background: yellow;_x000D_
  float: left;_x000D_
  width: 360px; // width optional but recommended _x000D_
}_x000D_
_x000D_
#right {_x000D_
  background: grey;_x000D_
  margin-left: 360px; // must agree with previous width _x000D_
}
_x000D_
<html>_x000D_
<head>_x000D_
  <title>Example</title>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <div id="wrapper">_x000D_
    <div id="left">_x000D_
      Left_x000D_
    </div>_x000D_
_x000D_
    <div id="right"></div>_x000D_
  </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

There are many variations on this depending on which columns need to be fixed and which are liquid. You can do this with absolute positioning too but I've generally found better results (particularly in terms of cross-browser) using floats instead.

Convert integer to string Jinja

I found the answer.

Cast integer to string:

myOldIntValue|string

Cast string to integer:

myOldStrValue|int

ES6 exporting/importing in index file

Also, bear in mind that if you need to export multiple functions at once, like actions you can use

export * from './XThingActions';

View contents of database file in Android Studio

New Database Inspector introduced in Android 4.1 Canary 5 Preview where you can now Inspect, query, modify, and debug SQLite databases in your running app directly from the IDE - https://developer.android.com/studio/preview/features?linkId=86173020#database-inspector

Supports database live query as well - https://developer.android.com/studio/preview/features?linkId=86173020#query

enter image description here

What's the difference between passing by reference vs. passing by value?

If you don't want to change the value of the original variable after passing it into a function, the function should be constructed with a "pass by value" parameter.

Then the function will have ONLY the value but not the address of the passed in variable. Without the variable's address, the code inside the function cannot change the variable value as seen from the outside of the function.

But if you want to give the function the ability to change the value of the variable as seen from the outside, you need to use pass by reference. As both the value and the address (reference) are passed in and available inside the function.

How to concatenate two MP4 files using FFmpeg?

for MP4 files:

If they are not exactly same (100% same codec, same resolution, same type) MP4 files, then you have to trans-code them into intermediate streams at first:

ffmpeg -i myfile1.mp4 -c copy -bsf:v h264_mp4toannexb -f mpegts temp1.ts
ffmpeg -i myfile2.mp4 -c copy -bsf:v h264_mp4toannexb -f mpegts temp2.ts
// now join
ffmpeg -i "concat:temp1.ts|temp2.ts" -c copy -bsf:a aac_adtstoasc output.mp4

NOTE!: Output will be like first file ( and not a second one)

How do I schedule a task to run at periodic intervals?

Use timer.scheduleAtFixedRate

public void scheduleAtFixedRate(TimerTask task,
                                long delay,
                                long period)

Schedules the specified task for repeated fixed-rate execution, beginning after the specified delay. Subsequent executions take place at approximately regular intervals, separated by the specified period.
In fixed-rate execution, each execution is scheduled relative to the scheduled execution time of the initial execution. If an execution is delayed for any reason (such as garbage collection or other background activity), two or more executions will occur in rapid succession to "catch up." In the long run, the frequency of execution will be exactly the reciprocal of the specified period (assuming the system clock underlying Object.wait(long) is accurate).

Fixed-rate execution is appropriate for recurring activities that are sensitive to absolute time, such as ringing a chime every hour on the hour, or running scheduled maintenance every day at a particular time. It is also appropriate for recurring activities where the total time to perform a fixed number of executions is important, such as a countdown timer that ticks once every second for ten seconds. Finally, fixed-rate execution is appropriate for scheduling multiple repeating timer tasks that must remain synchronized with respect to one another.

Parameters:

  • task - task to be scheduled.
  • delay - delay in milliseconds before task is to be executed.
  • period - time in milliseconds between successive task executions.

Throws:

  • IllegalArgumentException - if delay is negative, or delay + System.currentTimeMillis() is negative.
  • IllegalStateException - if task was already scheduled or cancelled, timer was cancelled, or timer thread terminated.

Removing duplicate rows from table in Oracle

create or replace procedure delete_duplicate_enq as
    cursor c1 is
    select *
    from enquiry;
begin
    for z in c1 loop
        delete enquiry
        where enquiry.enquiryno = z.enquiryno
        and rowid > any
        (select rowid
        from enquiry
        where enquiry.enquiryno = z.enquiryno);
    end loop;
 end delete_duplicate_enq;

How to check if mysql database exists

Another php solution, but with PDO:

<?php
try {
   $pdo = new PDO('mysql:host=localhost;dbname=dbname', 'root', 'password');
   echo 'table dbname exists...';
}
catch (PDOException $e) {
   die('dbname not found...');
}

Prevent a webpage from navigating away using JavaScript

I ended up with this slightly different version:

var dirty = false;
window.onbeforeunload = function() {
    return dirty ? "If you leave this page you will lose your unsaved changes." : null;
}

Elsewhere I set the dirty flag to true when the form gets dirtied (or I otherwise want to prevent navigating away). This allows me to easily control whether or not the user gets the Confirm Navigation prompt.

With the text in the selected answer you see redundant prompts:

enter image description here

Python - Get Yesterday's date as a string in YYYY-MM-DD format

>>> import datetime
>>> datetime.date.fromordinal(datetime.date.today().toordinal()-1).strftime("%F")
'2015-05-26'

How can I get npm start at a different directory?

I came here from google so it might be relevant to others: for yarn you could use:

yarn --cwd /path/to/your/app run start 

getElementById in React

You may have to perform a diff and put document.getElementById('name') code inside a condition, in case your component is something like this:

// using the new hooks API
function Comp(props) {
  const { isLoading, data } = props;
  useEffect(() => {
    if (data) {
      var name = document.getElementById('name').value;
    }
  }, [data]) // this diff is necessary

  if (isLoading) return <div>isLoading</div>
  return (
    <div id='name'>Comp</div>
  );
}

If diff is not performed then, you will get null.

Overlapping Views in Android

If you want to add you custom Overlay screen on Layout, you can create a Custom Linear Layout and get control of drawing and key events. You can my tutorial- Overlay on Android Layout- http://prasanta-paul.blogspot.com/2010/08/overlay-on-android-layout.html

Problems with installation of Google App Engine SDK for php in OS X

It's likely that the download was corrupted if you are getting an error with the disk image. Go back to the downloads page at https://developers.google.com/appengine/downloads and look at the SHA1 checksum. Then, go to your Terminal app on your mac and run the following:

openssl sha1 [put the full path to the file here without brackets] 

For example:

openssl sha1 /Users/me/Desktop/myFile.dmg 

If you get a different value than the one on the Downloads page, you know your file is not properly downloaded and you should try again.

Angularjs autocomplete from $http

I made an autocomplete directive and uploaded it to GitHub. It should also be able to handle data from an HTTP-Request.

Here's the demo: http://justgoscha.github.io/allmighty-autocomplete/ And here the documentation and repository: https://github.com/JustGoscha/allmighty-autocomplete

So basically you have to return a promise when you want to get data from an HTTP request, that gets resolved when the data is loaded. Therefore you have to inject the $qservice/directive/controller where you issue your HTTP Request.

Example:

function getMyHttpData(){
  var deferred = $q.defer();
  $http.jsonp(request).success(function(data){
    // the promise gets resolved with the data from HTTP
    deferred.resolve(data);
  });
  // return the promise
  return deferred.promise;
}

I hope this helps.

How to keep footer at bottom of screen

set its position:fixed and bottom:0 so that it will always reside at bottom of your browser windows

How to index characters in a Golang string?

Interpreted string literals are character sequences between double quotes "" using the (possibly multi-byte) UTF-8 encoding of individual characters. In UTF-8, ASCII characters are single-byte corresponding to the first 128 Unicode characters. Strings behave like slices of bytes. A rune is an integer value identifying a Unicode code point. Therefore,

package main

import "fmt"

func main() {
    fmt.Println(string("Hello"[1]))              // ASCII only
    fmt.Println(string([]rune("Hello, ??")[1])) // UTF-8
    fmt.Println(string([]rune("Hello, ??")[8])) // UTF-8
}

Output:

e
e
?

Read:

Go Programming Language Specification section on Conversions.

The Go Blog: Strings, bytes, runes and characters in Go

How to Bulk Insert from XLSX file extension?

Create a linked server to your document

http://www.excel-sql-server.com/excel-import-to-sql-server-using-linked-servers.htm

Then use ordinary INSERT or SELECT INTO. If you want to get fancy, you can use ADO.NET's SqlBulkCopy, which takes just about any data source that you can get a DataReader from and is pretty quick on insert, although the reading of the data won't be esp fast.

You could also take the time to transform an excel spreadsheet into a text delimited file or other bcp supported format and then use BCP.

How to check if a line has one of the strings in a list?

strings = ("string1", "string2", "string3")
for line in file:
    if any(s in line for s in strings):
        print "yay!"

Rails 4 - passing variable to partial

From the Rails api on PartialRender:

Rendering the default case

If you're not going to be using any of the options like collections or layouts, you can also use the short-hand defaults of render to render partials.

Examples:

# Instead of <%= render partial: "account" %>
<%= render "account" %>

# Instead of <%= render partial: "account", locals: { account: @buyer } %>
<%= render "account", account: @buyer %>

# @account.to_partial_path returns 'accounts/account', so it can be used to replace:
# <%= render partial: "accounts/account", locals: { account: @account} %>
<%= render @account %>

# @posts is an array of Post instances, so every post record returns 'posts/post' on `to_partial_path`,
# that's why we can replace:
# <%= render partial: "posts/post", collection: @posts %>
<%= render @posts %>

So, you can use pass a local variable size to render as follows:

<%= render @users, size: 50 %>

and then use it in the _user.html.erb partial:

<li>
    <%= gravatar_for user, size: size %>
    <%= link_to user.name, user %>
</li>

Note that size: size is equivalent to :size => size.

Redirecting to a page after submitting form in HTML

What you could do is, a validation of the values, for example:

if the value of the input of fullanme is greater than some value length and if the value of the input of address is greater than some value length then redirect to a new page, otherwise shows an error for the input.

_x000D_
_x000D_
// We access to the inputs by their id's
let fullname = document.getElementById("fullname");
let address = document.getElementById("address");

// Error messages
let errorElement = document.getElementById("name_error");
let errorElementAddress = document.getElementById("address_error");

// Form
let contactForm = document.getElementById("form");

// Event listener
contactForm.addEventListener("submit", function (e) {
  let messageName = [];
  let messageAddress = [];
  
    if (fullname.value === "" || fullname.value === null) {
    messageName.push("* This field is required");
  }

  if (address.value === "" || address.value === null) {
    messageAddress.push("* This field is required");
  }

  // Statement to shows the errors
  if (messageName.length || messageAddress.length > 0) {
    e.preventDefault();
    errorElement.innerText = messageName;
    errorElementAddress.innerText = messageAddress;
  }
  
   // if the values length is filled and it's greater than 2 then redirect to this page
    if (
    (fullname.value.length > 2,
    address.value.length > 2)
  ) {
    e.preventDefault();
    window.location.assign("https://www.google.com");
  }

});
_x000D_
.error {
  color: #000;
}

.input-container {
  display: flex;
  flex-direction: column;
  margin: 1rem auto;
}
_x000D_
<html>
  <body>
    <form id="form" method="POST">
    <div class="input-container">
    <label>Full name:</label>
      <input type="text" id="fullname" name="fullname">
      <div class="error" id="name_error"></div>
      </div>
      
      <div class="input-container">
      <label>Address:</label>
      <input type="text" id="address" name="address">
      <div class="error" id="address_error"></div>
      </div>
      <button type="submit" id="submit_button" value="Submit request" >Submit</button>
    </form>
  </body>
</html>
_x000D_
_x000D_
_x000D_

JavaScript load a page on button click

The answers here work to open the page in the same browser window/tab.

However, I wanted the page to open in a new window/tab when they click a button. (tab/window decision depends on the user's browser setting)

So here is how it worked to open the page in new tab/window:

<button type="button" onclick="window.open('http://www.example.com/', '_blank');">View Example Page</button>

It doesn't have to be a button, you can use anywhere. Notice the _blank that is used to open in new tab/window.

How to Clone Objects

It couldn't be simpler than this:

    public SomeClass Clone () {

        var clonedJson = JsonConvert.SerializeObject (this);

        return JsonConvert.DeserializeObject<SomeClass> (clonedJson);
    }

Just serialize any object to a JSON string and then deserialize it. This will do a deep copy...

Get URL of ASP.Net Page in code-behind

I'm facing same problem and so far I found:

new Uri(Request.Url,Request.ApplicationPath)

or

Request.Url.GetLeftPart(UriPartial.Authority)+Request.ApplicationPath

html cellpadding the left side of a cell

I would suggest using inline CSS styling.

<table border="1" style="padding-right: 10px;">
<tr>
<td>Content</td>
</tr>
</table>

or

<table border="1">
<tr style="padding-right: 10px;">
<td>Content</td>
</tr>
</table>

or

<table border="1">
<tr>
<td style="padding-right: 10px;">Content</td>
</tr>
</table>

I don't quite follow what you need, but this is what I would do, assuming I understand you needs.

UIImageView - How to get the file name of the image assigned?

Nope. No way to do that natively. You're going to have to subclass UIImageView, and add an imageFileName property (which you set when you set the image).

How to auto generate migrations with Sequelize CLI from Sequelize models?

As of 16/9/2020 most of these answers are not too much consistent any way! Try this new npm package

Sequelize-mig

It completed most known problems in sequelize-auto-migrations and its forks and its maintained and documented!

Its used in a way similar to the known one

Install:

npm install sequelize-mig -g / yarn global add sequelize-mig

then use it like this

sequelize-mig migration:make -n <migration name>

Regex for password must contain at least eight characters, at least one number and both lower and uppercase letters and special characters

I had some difficulty following the most popular answer for my circumstances. For example, my validation was failing with characters such as ; or [. I was not interested in white-listing my special characters, so I instead leveraged [^\w\s] as a test - simply put - match non word characters (including numeric) and non white space characters. To summarize, here is what worked for me...

  • at least 8 characters
  • at least 1 numeric character
  • at least 1 lowercase letter
  • at least 1 uppercase letter
  • at least 1 special character

/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[^\w\s]).{8,}$/

JSFiddle Link - simple demo covering various cases

What does $ mean before a string?

The following example highlights various advantages of using interpolated strings over string.Format() as far as cleanliness and readability goes. It also shows that code within {} gets evaluated like any other function argument, just as it would if string.Format() we're being called.

using System;

public class Example
{
   public static void Main()
   {
      var name = "Horace";
      var age = 34;
      // replaces {name} with the value of name, "Horace"
      var s1 = $"He asked, \"Is your name {name}?\", but didn't wait for a reply.";
      Console.WriteLine(s1);

      // as age is an integer, we can use ":D3" to denote that
      // it should have leading zeroes and be 3 characters long
      // see https://docs.microsoft.com/en-us/dotnet/standard/base-types/how-to-pad-a-number-with-leading-zeros
      //
      // (age == 1 ? "" : "s") uses the ternary operator to 
      // decide the value used in the placeholder, the same 
      // as if it had been placed as an argument of string.Format
      //
      // finally, it shows that you can actually have quoted strings within strings
      // e.g. $"outer { "inner" } string"
      var s2 = $"{name} is {age:D3} year{(age == 1 ? "" : "s")} old.";
      Console.WriteLine(s2); 
   }
}
// The example displays the following output:
//       He asked, "Is your name Horace?", but didn't wait for a reply.
//       Horace is 034 years old.

Incompatible implicit declaration of built-in function ‘malloc’

You need to #include <stdlib.h>. Otherwise it's defined as int malloc() which is incompatible with the built-in type void *malloc(size_t).

Constants in Objective-C

// Prefs.h
extern NSString * const RAHUL;

// Prefs.m
NSString * const RAHUL = @"rahul";

Using VBA to get extended file attributes

'vb.net
'Extended file stributes
'visual basic .net sample 

Dim sFile As Object
        Dim oShell = CreateObject("Shell.Application")
        Dim oDir = oShell.Namespace("c:\temp")

        For i = 0 To 34
            TextBox1.Text = TextBox1.Text & oDir.GetDetailsOf(oDir, i) & vbCrLf
            For Each sFile In oDir.Items
                TextBox1.Text = TextBox1.Text & oDir.GetDetailsOf(sFile, i) & vbCrLf
            Next
            TextBox1.Text = TextBox1.Text & vbCrLf
        Next

Getting index value on razor foreach

Or you could simply do this:

@foreach(var myItem in Model.Members)
{    
    <span>@Model.Members.IndexOf(myItem)</span>
}

What is the difference between a deep copy and a shallow copy?

char * Source = "Hello, world.";

char * ShallowCopy = Source;    

char * DeepCopy = new char(strlen(Source)+1);
strcpy(DeepCopy,Source);        

'ShallowCopy' points to the same location in memory as 'Source' does. 'DeepCopy' points to a different location in memory, but the contents are the same.

Extract XML Value in bash script

I agree with Charles Duffy that a proper XML parser is the right way to go.

But as to what's wrong with your sed command (or did you do it on purpose?).

  • $data was not quoted, so $data is subject to shell's word splitting, filename expansion among other things. One of the consequences being that the spacing in the XML snippet is not preserved.

So given your specific XML structure, this modified sed command should work

title=$(sed -ne '/title/{s/.*<title>\(.*\)<\/title>.*/\1/p;q;}' <<< "$data")

Basically for the line that contains title, extract the text between the tags, then quit (so you don't extract the 2nd <title>)

Go to next item in ForEach-Object

You just have to replace the break with a return statement.

Think of the code inside the Foreach-Object as an anonymous function. If you have loops inside the function, just use the control keywords applying to the construction (continue, break, ...).

Setting JDK in Eclipse

Configuring JDKs

  1. Windows -> Preferences -> Installed JREs, to configured the installed JDKs
  2. Project Properties, Java Compiler, Enable project specific settings (or configure Workspace settings), JDK Compliance
  3. Project Properties, Java Build Path, Libraries, Add Library, JRE system library, Workspace default or Alternate JRE (one of the JREs configured in

Maven

BUT IF you are using maven, provided that you have your latest JRE (Windows/Preferences/Installed JREs) -for example JDK 1.8

You can select the level 1.6, 1.7, 1.8 by configuring the maven-compiler-plugin source and target attributes, like this

            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.3</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>

And ideally, if you have a parent pom, you can do it for all the modules (Eclipse projects) in the parent pom, in one single place.

Source and Target If we want to use the Java 8 language features the –source should be set to 1.8. Also, for the compiled classes to be compatible with JVM 1.8, the –target value should be 1.8.

Updating JRE library that is broken in many projects at once (with Maven)

Rather than updating one by one the JRE library, let Maven do it for you.

Selecting the projects and right-clicking for Maven -> Update Project, will set the system library to the path of the installed JDK, in case the paths are broken (because you installed a new JDK or imported from another computer, etc.) and set the JDK compliance according to the maven source and target setting in the pom.

Bitbucket fails to authenticate on git pull

You can update your Bitbucket credentials from the OSX Keychain.

Updating your cached credentials via the command line:

$ git credential-osxkeychain erase
host=bitbucket.org
protocol=https
[press return]

If it's successful, nothing will print out. To test that it works, try and clone a repository from Bitbucket. If you are prompted for a password, the keychain entry was deleted.

C++ template typedef

C++11 added alias declarations, which are generalization of typedef, allowing templates:

template <size_t N>
using Vector = Matrix<N, 1>;

The type Vector<3> is equivalent to Matrix<3, 1>.


In C++03, the closest approximation was:

template <size_t N>
struct Vector
{
    typedef Matrix<N, 1> type;
};

Here, the type Vector<3>::type is equivalent to Matrix<3, 1>.

Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time

As ping works, but telnetto port 80 does not, the HTTP port 80 is closed on your machine. I assume that your browser's HTTP connection goes through a proxy (as browsing works, how else would you read stackoverflow?). You need to add some code to your python program, that handles the proxy, like described here:

Using an HTTP PROXY - Python

How to programmatically close a JFrame

setVisible(false); //you can't see me!
dispose(); //Destroy the JFrame object

Not too tricky.

How to change fontFamily of TextView in Android

To set the font by program, write...

     TextView tv7 = new TextView(this);
     tv7.setText(" TIME ");    
     tv7.setTypeface(Typeface.create("sans-serif-condensed",Typeface.BOLD));
     tv7.setTextSize(12);
     tbrow.addView(tv7);

The name "sans-serif-condensed" is referenced from fonts.xml file which should be created in app--> res--> values folder and it holds the fonts in it.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="font_family_light">sans-serif-light</string>
    <string name="font_family_medium">sans-serif-medium</string>
    <string name="font_family_regular">sans-serif</string>
    <string name="font_family_condensed">sans-serif-condensed</string>
    <string name="font_family_black">sans-serif-black</string>
    <string name="font_family_thin">sans-serif-thin</string>
</resources>

Hope this is clear!

To show error message without alert box in Java Script

I m agree with @ReNjITh.R answer but If you want to display error message just beside textbox. Just like below

enter image description here

<html>
<head>
<script type="text/javascript">
    function validate() 
    {
        if(myform.fname.value.length==0)
        {
           document.getElementById('errfn').innerHTML="this is invalid name";
        }
    }
</script>
</head>
<body>
    <form name="myform">
         First_Name
         <input type=text id=fname name=fname onblur="validate()" /><span id="errfn"></span>
        <br> <br>
         Last_Name
         <input type=text id=lname name=lname onblur="validate()"/><br>
         <input type=button value=check /> 
    </form>
</body>

How to reverse apply a stash?

git stash show -p | git apply --reverse

Warning, that would not in every case: "git apply -R"(man) did not handle patches that touch the same path twice correctly, which has been corrected with Git 2.30 (Q1 2021).

This is most relevant in a patch that changes a path from a regular file to a symbolic link (and vice versa).

See commit b0f266d (20 Oct 2020) by Jonathan Tan (jhowtan).
(Merged by Junio C Hamano -- gitster -- in commit c23cd78, 02 Nov 2020)

apply: when -R, also reverse list of sections

Helped-by: Junio C Hamano
Signed-off-by: Jonathan Tan

A patch changing a symlink into a file is written with 2 sections (in the code, represented as "struct patch"): firstly, the deletion of the symlink, and secondly, the creation of the file.

When applying that patch with -R, the sections are reversed, so we get: (1) creation of a symlink, then (2) deletion of a file.

This causes an issue when the "deletion of a file" section is checked, because Git observes that the so-called file is not a file but a symlink, resulting in a "wrong type" error message.

What we want is: (1) deletion of a file, then (2) creation of a symlink.

In the code, this is reflected in the behavior of previous_patch() when invoked from check_preimage() when the deletion is checked.
Creation then deletion means that when the deletion is checked, previous_patch() returns the creation section, triggering a mode conflict resulting in the "wrong type" error message.

But deletion then creation means that when the deletion is checked, previous_patch() returns NULL, so the deletion mode is checked against lstat, which is what we want.

There are also other ways a patch can contain 2 sections referencing the same file, for example, in 7a07841c0b ("git-apply: handle a patch that touches the same path more than once better", 2008-06-27, Git v1.6.0-rc0 -- merge). "git apply -R"(man) fails in the same way, and this commit makes this case succeed.

Therefore, when building the list of sections, build them in reverse order (by adding to the front of the list instead of the back) when -R is passed.

The located assembly's manifest definition does not match the assembly reference

I am going to blow everyone's mind right now . . .

Delete all the <assemblyBinding> references from your .config file, and then run this command from the NuGet Package Manager console:

Get-Project -All | Add-BindingRedirect

What is the proper way to URL encode Unicode characters?

IRIs do not replace URIs, because only URIs (effectively, ASCII) are permissible in some contexts -- including HTTP.

Instead, you specify an IRI and it gets transformed into a URI when going out on the wire.

org.postgresql.util.PSQLException: FATAL: sorry, too many clients already

You need to close all your connexions for example: If you make an INSERT INTO statement you need to close the statement and your connexion in this way:

statement.close();
Connexion.close():

And if you make a SELECT statement you need to close the statement, the connexion and the resultset in this way:

resultset.close();
statement.close();
Connexion.close();

I did this and it worked

Return date as ddmmyyyy in SQL Server

I found a way to do it without replacing the slashes

select CONVERT(VARCHAR(10), GETDATE(), 112)

This would return: "YYYYMMDD"

Spring Bean Scopes

About prototype bean(s) :

The client code must clean up prototype-scoped objects and release expensive resources that the prototype bean(s) are holding. To get the Spring container to release resources held by prototype-scoped beans, try using a custom bean post-processor, which holds a reference to beans that need to be cleaned up.

ref : https://docs.spring.io/spring/docs/3.0.0.M3/reference/html/ch04s04.html#beans-factory-scopes-prototype

Simple way to measure cell execution time in ipython notebook

When in trouble what means what:

?%timeit or ??timeit

To get the details:

Usage, in line mode:
  %timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement
or in cell mode:
  %%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] setup_code
  code
  code...

Time execution of a Python statement or expression using the timeit
module.  This function can be used both as a line and cell magic:

- In line mode you can time a single-line statement (though multiple
  ones can be chained with using semicolons).

- In cell mode, the statement in the first line is used as setup code
  (executed but not timed) and the body of the cell is timed.  The cell
  body has access to any variables created in the setup code.

Mac install and open mysql using terminal

  1. install homebrew via terminal

  2. brew install mysql

Maximum on http header values?

I also found that in some cases the reason for 502/400 in case of many headers could be because of a large number of headers without regard to size. from the docs

tune.http.maxhdr Sets the maximum number of headers in a request. When a request comes with a number of headers greater than this value (including the first line), it is rejected with a "400 Bad Request" status code. Similarly, too large responses are blocked with "502 Bad Gateway". The default value is 101, which is enough for all usages, considering that the widely deployed Apache server uses the same limit. It can be useful to push this limit further to temporarily allow a buggy application to work by the time it gets fixed. Keep in mind that each new header consumes 32bits of memory for each session, so don't push this limit too high.

https://cbonte.github.io/haproxy-dconv/configuration-1.5.html#3.2-tune.http.maxhdr

How should I set the default proxy to use default credentials?

From .NET 2.0 you shouldn't need to do this. If you do not explicitly set the Proxy property on a web request it uses the value of the static WebRequest.DefaultWebProxy. If you wanted to change the proxy being used by all subsequent WebRequests, you can set this static DefaultWebProxy property.

The default behaviour of WebRequest.DefaultWebProxy is to use the same underlying settings as used by Internet Explorer.

If you wanted to use different proxy settings to the current user then you would need to code

WebRequest webRequest = WebRequest.Create("http://stackoverflow.com/");
webRequest.Proxy = new WebProxy("http://proxyserver:80/",true);

or

WebRequest.DefaultWebProxy = new WebProxy("http://proxyserver:80/",true);

You should also remember the object model for proxies includes the concept that the proxy can be different depending on the destination hostname. This can make things a bit confusing when debugging and checking the property of webRequest.Proxy. Call

webRequest.Proxy.GetProxy(new Uri("http://google.com.au")) to see the actual details of the proxy server that would be used.

There seems to be some debate about whether you can set webRequest.Proxy or WebRequest.DefaultWebProxy = null to prevent the use of any proxy. This seems to work OK for me but you could set it to new DefaultProxy() with no parameters to get the required behaviour. Another thing to check is that if a proxy element exists in your applications config file, the .NET Framework will NOT use the proxy settings in Internet Explorer.

The MSDN Magazine article Take the Burden Off Users with Automatic Configuration in .NET gives further details of what is happening under the hood.

How can I programmatically freeze the top row of an Excel worksheet in Excel 2007 VBA?

Just hit the same problem... For some reason, the freezepanes command just caused crosshairs to appear in the centre of the screen. It turns oout I had switched ScreenUpdating off! Solved with the following code:

Application.ScreenUpdating = True
Cells(2, 1).Select
ActiveWindow.FreezePanes = True

Now it works fine.

Linux command-line call not returning what it should from os.system?

Your code returns 0 if the execution of the commands passed is successful and non zero if it fails. The following program works on python2.7, haven checked 3 and versions above. Try this code.

>>> import commands
>>> ret = commands.getoutput("ps -p 2993 -o time --no-headers")
>>> print ret

Passing parameters from jsp to Spring Controller method

Use the @RequestParam to pass a parameter to the controller handler method. In the jsp your form should have an input field with name = "id" like the following:

<input type="text" name="id" />
<input type="submit" />

Then in your controller, your handler method should be like the following:

@RequestMapping("listNotes")
public String listNotes(@RequestParam("id") int id) {
    Person person = personService.getCurrentlyAuthenticatedUser();
    model.addAttribute("person", new Person());
    model.addAttribute("listPersons", this.personService.listPersons());
    model.addAttribute("listNotes", this.notesService.listNotesBySectionId(id, person));
    return "note";
}

Please also refer to these answers and tutorial:

Access Form - Syntax error (missing operator) in query expression

I was able to quickly fix it by going into Design View of the Form and putting [] around any field names that had spaces. I am now able to use the built in filters without the annoying popup about syntax problems.

jQuery - Getting the text value of a table cell in the same row as a clicked element

it should work fine:

var Something = $(this).children("td:nth-child(n)").text();

Remove values from select list based on condition

Removing an option

$("#val option[value='A']").remove();

MySQL, create a simple function

this is a mysql function example. I hope it helps. (I have not tested it yet, but should work)

DROP FUNCTION IF EXISTS F_TEST //
CREATE FUNCTION F_TEST(PID INT) RETURNS VARCHAR
BEGIN
/*DECLARE VALUES YOU MAY NEED, EXAMPLE:
  DECLARE NOM_VAR1 DATATYPE [DEFAULT] VALUE;
  */
  DECLARE NAME_FOUND VARCHAR DEFAULT "";

    SELECT EMPLOYEE_NAME INTO NAME_FOUND FROM TABLE_NAME WHERE ID = PID;
  RETURN NAME_FOUND;
END;//

How to increase timeout for a single test case in mocha

If you wish to use es6 arrow functions you can add a .timeout(ms) to the end of your it definition:

it('should not timeout', (done) => {
    doLongThing().then(() => {
        done();
    });
}).timeout(5000);

At least this works in Typescript.

SqlDataAdapter vs SqlDataReader

The Fill function uses a DataReader internally. If your consideration is "Which one is more efficient?", then using a DataReader in a tight loop that populates a collection record-by-record, is likely to be the same load on the system as using DataAdapter.Fill.

(System.Data.dll, System.Data.Common.DbDataAdapter, FillInternal.)

C# - Fill a combo box with a DataTable

A few points:

1) "DataBind()" is only for web apps (not windows apps).

2) Your code looks very 'JAVAish' (not a bad thing, just an observation).

Try this:

mnuActionLanguage.ComboBox.DataSource = languages;

If that doesn't work... then I'm assuming that your datasource is being stepped on somewhere else in the code.

SQL: Insert all records from one table to another table without specific the columns

Use this

SELECT *
INTO new_table_name
FROM current_table_name

How to create a library project in Android Studio and an application project that uses the library project

There are two simplest ways if one does not work please try the other one.

  1. Add dependency of the library inside dependency inside build.gradle file of the library u r using, and paste ur library in External Libraries.

OR

  1. Just Go to your libs folder inside app folder and paste all your .jar e.g Library files there Now the trick here is that now go inside settings.gradle file now add this line "include ':app:libs'" after "include ':app'" It will definitely work...........:)

How do I copy to the clipboard in JavaScript?

I was going to use clipboard.js, but it doesn't have any mobile solution in place (yet) ... so I wrote a super small library:

Cheval

This will either copy the text (desktop, Android, and Safari 10+), or at the very least, select the text (older versions of iOS). Minified it is just over 1 kB. In desktop Safari (before version 10) it tells the user to "Press Command + C to copy". You also don't need to write any JavaScript to use it.

How to encode a string in JavaScript for displaying in HTML?

The only character that needs escaping is <. (> is meaningless outside of a tag).

Therefore, your "magic" code is:

safestring = unsafestring.replace(/</g,'&lt;');

How can I listen for a click-and-hold in jQuery?

Aircoded (but tested on this fiddle)

(function($) {
    function startTrigger(e) {
        var $elem = $(this);
        $elem.data('mouseheld_timeout', setTimeout(function() {
            $elem.trigger('mouseheld');
        }, e.data));
    }

    function stopTrigger() {
        var $elem = $(this);
        clearTimeout($elem.data('mouseheld_timeout'));
    }


    var mouseheld = $.event.special.mouseheld = {
        setup: function(data) {
            // the first binding of a mouseheld event on an element will trigger this
            // lets bind our event handlers
            var $this = $(this);
            $this.bind('mousedown', +data || mouseheld.time, startTrigger);
            $this.bind('mouseleave mouseup', stopTrigger);
        },
        teardown: function() {
            var $this = $(this);
            $this.unbind('mousedown', startTrigger);
            $this.unbind('mouseleave mouseup', stopTrigger);
        },
        time: 750 // default to 750ms
    };
})(jQuery);

// usage
$("div").bind('mouseheld', function(e) {
    console.log('Held', e);
})

nvarchar(max) still being truncated

I have encountered the same problem today and found that beyond that 4000 character limit, I had to split the dynamic query into two strings and concatenate them when executing the query.

DECLARE @Query NVARCHAR(max);
DECLARE @Query2 NVARCHAR(max);
SET @Query = 'SELECT...' -- some of the query gets set here
SET @Query2 = '...' -- more query gets added on, etc.

EXEC (@Query + @Query2)

Relative path in HTML

The easiest way to solve this in pure HTML is to use the <base href="…"> element like so:

<base href="http://localhost/mywebsite/" />

Then all of the URLs in your HTML can just be this:

<a href="images/example.png">Link To Image</a>

Just change the <base href="…"> to match your server. The rest of the HTML paths will just fall in line and will be appended to that.

How to create a SQL Server function to "join" multiple rows from a subquery into a single delimited field?

Mun's answer didn't work for me so I made some changes to that answer to get it to work. Hope this helps someone. Using SQL Server 2012:

SELECT [VehicleID]
     , [Name]
     , STUFF((SELECT DISTINCT ',' + CONVERT(VARCHAR,City) 
         FROM [Location] 
         WHERE (VehicleID = Vehicle.VehicleID) 
         FOR XML PATH ('')), 1, 2, '') AS Locations
FROM [Vehicle]

changing iframe source with jquery

Should work.

Here's a working example:

http://jsfiddle.net/rhpNc/

Excerpt:

function loadIframe(iframeName, url) {
    var $iframe = $('#' + iframeName);
    if ($iframe.length) {
        $iframe.attr('src',url);
        return false;
    }
    return true;
}

Validate decimal numbers in JavaScript - IsNumeric()

return (input - 0) == input && input.length > 0;

didn't work for me. When I put in an alert and tested, input.length was undefined. I think there is no property to check integer length. So what I did was

var temp = '' + input;
return (input - 0) == input && temp.length > 0;

It worked fine.

changing source on html5 video tag

Using JavaScript and jQuery:

<script src="js/jquery.js"></script>
...
<video id="vid" width="1280" height="720" src="v/myvideo01.mp4" controls autoplay></video>
...
function chVid(vid) {
    $("#vid").attr("src",vid);
}
...
<div onclick="chVid('v/myvideo02.mp4')">See my video #2!</div>

How to create empty folder in java?

Looks file you use the .mkdirs() method on a File object: http://www.roseindia.net/java/beginners/java-create-directory.shtml

// Create a directory; all non-existent ancestor directories are
// automatically created
success = (new File("../potentially/long/pathname/without/all/dirs")).mkdirs();
if (!success) {
    // Directory creation failed
}

How to return a dictionary | Python

def prepare_table_row(row):
    lst = [i.text for i in row if i != u'\n']
    return dict(rank = int(lst[0]),
                grade = str(lst[1]),
                channel=str(lst[2])),
                videos = float(lst[3].replace(",", " ")),
                subscribers = float(lst[4].replace(",", "")),
                views = float(lst[5].replace(",", "")))

iOS - UIImageView - how to handle UIImage image orientation

here is a workable sample cod, considering the image orientation:

#define rad(angle) ((angle) / 180.0 * M_PI)
- (CGAffineTransform)orientationTransformedRectOfImage:(UIImage *)img
{
    CGAffineTransform rectTransform;
    switch (img.imageOrientation)
    {
        case UIImageOrientationLeft:
            rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(90)), 0, -img.size.height);
            break;
        case UIImageOrientationRight:
            rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(-90)), -img.size.width, 0);
            break;
        case UIImageOrientationDown:
            rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(-180)), -img.size.width, -img.size.height);
            break;
        default:
            rectTransform = CGAffineTransformIdentity;
    };

    return CGAffineTransformScale(rectTransform, img.scale, img.scale);
}


- (UIImage *)croppedImage:(UIImage*)orignialImage InRect:(CGRect)visibleRect{
    //transform visible rect to image orientation
    CGAffineTransform rectTransform = [self orientationTransformedRectOfImage:orignialImage];
    visibleRect = CGRectApplyAffineTransform(visibleRect, rectTransform);

    //crop image
    CGImageRef imageRef = CGImageCreateWithImageInRect([orignialImage CGImage], visibleRect);
    UIImage *result = [UIImage imageWithCGImage:imageRef scale:orignialImage.scale orientation:orignialImage.imageOrientation];
    CGImageRelease(imageRef);
    return result;
}

When should you use a class vs a struct in C++?

they're the same thing with different defaults (private by default for class, and public by default for struct), so in theory they're totally interchangeable.

so, if I just want to package some info to move around, I use a struct, even if i put a few methods there (but not many). If it's a mostly-opaque thing, where the main use would be via methods, and not directly to the data members, i use a full class.

Android dex gives a BufferOverflowException when building

Add the Library file in project.. Project->right click->Properties->android->Library-> click Add and select the Library Project and give apply and ok.. then, clean the project and run again.. if you want restart the eclipse..

And also, sometimes, need to update Android SDK build tools..

How to run bootRun with spring profile via gradle task

For someone from internet, there was a similar question https://stackoverflow.com/a/35848666/906265 I do provide the modified answer from it here as well:

// build.gradle
<...>

bootRun {}

// make sure bootRun is executed when this task runs
task runDev(dependsOn:bootRun) {
    // TaskExecutionGraph is populated only after 
    // all the projects in the build have been evaulated https://docs.gradle.org/current/javadoc/org/gradle/api/execution/TaskExecutionGraph.html#whenReady-groovy.lang.Closure-
    gradle.taskGraph.whenReady { graph ->
        logger.lifecycle('>>> Setting spring.profiles.active to dev')
        if (graph.hasTask(runDev)) {
            // configure task before it is executed
            bootRun {
                args = ["--spring.profiles.active=dev"]
            }
        }
    }
}

<...>

then in terminal:

gradle runDev

Have used gradle 3.4.1 and spring boot 1.5.10.RELEASE

Twitter Bootstrap modal on mobile devices

Found a very hacky solution to this problem, but it works. I added a class to the link that is used to open the modal (With the data-target), then using Jquery, added a click event to that class that gets the data-target, finds the modal it is supposed to open, and then opens it via Javascript. Works just fine for me. I also added a mobile check on mine so that it only runs on mobile, but that's not required.

$('.forceOpen').click(function() {
  var id = $(this).attr('data-target');
  $('.modal').modal('hide');
  $(id).modal('show');
});

How to build & install GLFW 3 and use it in a Linux project

The well-described answer is already there, but I went through this SHORTER recipe:

  1. Install Linuxbrew
  2. $ brew install glfw
  3. cd /home/linuxbrew/.linuxbrew/Cellar/glfw/X.X/include
  4. sudo cp -R GLFW /usr/include

Explanation: We manage to build GLFW by CMAKE which is done by Linuxbrew (Linux port of beloved Homebrew). Then copy the header files to where Linux reads from (/usr/include).

How to set ChartJS Y axis title?

For me it works like this:

    options : {
      scales: {
        yAxes: [{
          scaleLabel: {
            display: true,
            labelString: 'probability'
          }
        }]
      }
    }

How to backup a local Git repository?

The way I do this is to create a remote (bare) repository (on a separate drive, USB Key, backup server or even github) and then use push --mirror to make that remote repo look exactly like my local one (except the remote is a bare repository).

This will push all refs (branches and tags) including non-fast-forward updates. I use this for creating backups of my local repository.

The man page describes it like this:

Instead of naming each ref to push, specifies that all refs under $GIT_DIR/refs/ (which includes but is not limited to refs/heads/, refs/remotes/, and refs/tags/) be mirrored to the remote repository. Newly created local refs will be pushed to the remote end, locally updated refs will be force updated on the remote end, and deleted refs will be removed from the remote end. This is the default if the configuration option remote.<remote>.mirror is set.

I made an alias to do the push:

git config --add alias.bak "push --mirror github"

Then, I just run git bak whenever I want to do a backup.

Drop-down box dependent on the option selected in another drop-down box

for this, I have noticed that it far better to show and hide the tags instead of adding and removing them for the DOM. It performs better that way.

IntelliJ can't recognize JavaFX 11 with OpenJDK 11

Quick summary, you can do either:

  1. Include the JavaFX modules via --module-path and --add-modules like in José's answer.

    OR

  2. Once you have JavaFX libraries added to your project (either manually or via maven/gradle import), add the module-info.java file similar to the one specified in this answer. (Note that this solution makes your app modular, so if you use other libraries, you will also need to add statements to require their modules inside the module-info.java file).


This answer is a supplement to Jose's answer.

The situation is this:

  1. You are using a recent Java version, e.g. 13.
  2. You have a JavaFX application as a Maven project.
  3. In your Maven project you have the JavaFX plugin configured and JavaFX dependencies setup as per Jose's answer.
  4. You go to the source code of your main class which extends Application, you right-click on it and try to run it.
  5. You get an IllegalAccessError involving an "unnamed module" when trying to launch the app.

Excerpt for a stack trace generating an IllegalAccessError when trying to run a JavaFX app from Intellij Idea:

Exception in Application start method
java.lang.reflect.InvocationTargetException
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:464)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:363)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1051)
Caused by: java.lang.RuntimeException: Exception in Application start method
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:900)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:195)
    at java.base/java.lang.Thread.run(Thread.java:830)
Caused by: java.lang.IllegalAccessError: class com.sun.javafx.fxml.FXMLLoaderHelper (in unnamed module @0x45069d0e) cannot access class com.sun.javafx.util.Utils (in module javafx.graphics) because module javafx.graphics does not export com.sun.javafx.util to unnamed module @0x45069d0e
    at com.sun.javafx.fxml.FXMLLoaderHelper.<clinit>(FXMLLoaderHelper.java:38)
    at javafx.fxml.FXMLLoader.<clinit>(FXMLLoader.java:2056)
    at org.jewelsea.demo.javafx.springboot.Main.start(Main.java:13)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:846)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:455)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:428)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:427)
    at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
Exception running application org.jewelsea.demo.javafx.springboot.Main

OK, now you are kind of stuck and have no clue what is going on.

What has actually happened is this:

  1. Maven has successfully downloaded the JavaFX dependencies for your application, so you don't need to separately download the dependencies or install a JavaFX SDK or module distribution or anything like that.
  2. Idea has successfully imported the modules as dependencies to your project, so everything compiles OK and all of the code completion and everything works fine.

So it seems everything should be OK. BUT, when you run your application, the code in the JavaFX modules is failing when trying to use reflection to instantiate instances of your application class (when you invoke launch) and your FXML controller classes (when you load FXML). Without some help, this use of reflection can fail in some cases, generating the obscure IllegalAccessError. This is due to a Java module system security feature which does not allow code from other modules to use reflection on your classes unless you explicitly allow it (and the JavaFX application launcher and FXMLLoader both require reflection in their current implementation in order for them to function correctly).

This is where some of the other answers to this question, which reference module-info.java, come into the picture.

So let's take a crash course in Java modules:

The key part is this:

4.9. Opens

If we need to allow reflection of private types, but we don't want all of our code exposed, we can use the opens directive to expose specific packages.

But remember, this will open the package up to the entire world, so make sure that is what you want:

module my.module { opens com.my.package; }

So, perhaps you don't want to open your package to the entire world, then you can do:

4.10. Opens … To

Okay, so reflection is great sometimes, but we still want as much security as we can get from encapsulation. We can selectively open our packages to a pre-approved list of modules, in this case, using the opens…to directive:

module my.module { opens com.my.package to moduleOne, moduleTwo, etc.; }

So, you end up creating a src/main/java/module-info.java class which looks like this:

module org.jewelsea.demo.javafx.springboot {
    requires javafx.fxml;
    requires javafx.controls;
    requires javafx.graphics;
    opens org.jewelsea.demo.javafx.springboot to javafx.graphics,javafx.fxml;
}

Where, org.jewelsea.demo.javafx.springboot is the name of the package which contains the JavaFX Application class and JavaFX Controller classes (replace this with the appropriate package name for your application). This tells the Java runtime that it is OK for classes in the javafx.graphics and javafx.fxml to invoke reflection on the classes in your org.jewelsea.demo.javafx.springboot package. Once this is done, and the application is compiled and re-run things will work fine and the IllegalAccessError generated by JavaFX's use of reflection will no longer occur.

But what if you don't want to create a module-info.java file

If instead of using the the Run button in the top toolbar of IDE to run your application class directly, you instead:

  1. Went to the Maven window in the side of the IDE.
  2. Chose the javafx maven plugin target javafx.run.
  3. Right-clicked on that and chose either Run Maven Build or Debug....

Then the app will run without the module-info.java file. I guess this is because the maven plugin is smart enough to dynamically include some kind of settings which allows the app to be reflected on by the JavaFX classes even without a module-info.java file, though I don't know how this is accomplished.

To get that setting transferred to the Run button in the top toolbar, right-click on the javafx.run Maven target and choose the option to Create Run/Debug Configuration for the target. Then you can just choose Run from the top toolbar to execute the Maven target.

Set selected radio from radio group with a value

$('input[name="mygroup"]').val([5])

Entity Framework 6 Code first Default value

I admit that my approach escapes the whole "Code First" concept. But if you have the ability to just change the default value in the table itself... it's much simpler than the lengths that you have to go through above... I'm just too lazy to do all that work!

It almost seems as if the posters original idea would work:

[DefaultValue(true)]
public bool IsAdmin { get; set; }

I thought they just made the mistake of adding quotes... but alas no such intuitiveness. The other suggestions were just too much for me (granted I have the privileges needed to go into the table and make the changes... where not every developer will in every situation). In the end I just did it the old fashioned way. I set the default value in the SQL Server table... I mean really, enough already! NOTE: I further tested doing an add-migration and update-database and the changes stuck. enter image description here

What's the purpose of SQL keyword "AS"?

Everyone who answered before me is correct. You use it kind of as an alias shortcut name for a table when you have long queries or queries that have joins. Here's a couple examples.

Example 1

SELECT P.ProductName,
       P.ProductGroup,
       P.ProductRetailPrice
FROM   Products AS P

Example 2

SELECT P.ProductName,
       P.ProductRetailPrice,
       O.Quantity
FROM   Products AS P
LEFT OUTER JOIN Orders AS O ON O.ProductID = P.ProductID
WHERE  O.OrderID = 123456

Example 3 It's a good practice to use the AS keyword, and very recommended, but it is possible to perform the same query without one (and I do often).

SELECT P.ProductName,
       P.ProductRetailPrice,
       O.Quantity
FROM   Products P
LEFT OUTER JOIN Orders O ON O.ProductID = P.ProductID
WHERE  O.OrderID = 123456

As you can tell, I left out the AS keyword in the last example. And it can be used as an alias.

Example 4

SELECT P.ProductName AS "Product",
       P.ProductRetailPrice AS "Retail Price",
       O.Quantity AS "Quantity Ordered"
FROM   Products P
LEFT OUTER JOIN Orders O ON O.ProductID = P.ProductID
WHERE  O.OrderID = 123456

Output of Example 4

Product             Retail Price     Quantity Ordered
Blue Raspberry Gum  $10 pk/$50 Case  2 Cases
Twizzler            $5 pk/$25 Case   10 Cases

How to perform mouseover function in Selenium WebDriver using Java?

Its not really possible to perform a 'mouse hover' action, instead you need to chain all of the actions that you want to achieve in one go. So move to the element that reveals the others, then during the same chain, move to the now revealed element and click on it.

When using Action Chains you have to remember to 'do it like a user would'.

Actions action = new Actions(webdriver);
WebElement we = webdriver.findElement(By.xpath("html/body/div[13]/ul/li[4]/a"));
action.moveToElement(we).moveToElement(webdriver.findElement(By.xpath("/expression-here"))).click().build().perform();

403 Access Denied on Tomcat 8 Manager App without prompting for user/password

I follwed the same tutorial but after some months I strangely got the error "403 Access Denied" while tryed to use Manager App. In this case I was using the ipaddress:8080 in the address bar and Tomcat Manager App didin't prompting for user/password. In case of localhost:8080 the error was "401", the dialogbox asking for username and password was displayed but the user not recognized.

I tried all the previous suggestions / solutions without lucky. The only way I found is been to repeat again the entire tutorial overwriting also the files. When finished, I found again the old deployed project into the webapps directory. Now Apache Tomcat/8.5.16 Manager App are working again. I do not know what happened I didn't understand also because I'm a newbie in Tomcat user

Does GPS require Internet?

I've found out that GPS does not need Internet, BUT of course if you need to download maps, you will need a data connection or wifi.

http://androidforums.com/samsung-fascinate/288871-gps-independent-3g-wi-fi.html http://www.droidforums.net/forum/droid-applications/63145-does-google-navigation-gps-requires-3g-work.html

How do I create JavaScript array (JSON format) dynamically?

var student = [];
var obj = {
    'first_name': name,
    'last_name': name,
    'age': age,
}
student.push(obj);

Does overflow:hidden applied to <body> work on iPhone Safari?

Yes, this is related to new updates in safari that are breaking your layout now if you use overflow: hidden to take care of clearing divs.

Change the "From:" address in Unix "mail"

I don't know if it's the same with other OS, but in OpenBSD, the mail command has this syntax:

mail to-addr ... -sendmail-options ...

sendmail has -f option where you indicate the email address for the FROM: field. The following command works for me.

mail [email protected] -f [email protected]

How to hide axes and gridlines in Matplotlib (python)

# Hide grid lines
ax.grid(False)

# Hide axes ticks
ax.set_xticks([])
ax.set_yticks([])
ax.set_zticks([])

Note, you need matplotlib>=1.2 for set_zticks() to work.

FragmentActivity to Fragment

first of all;

a Fragment must be inside a FragmentActivity, that's the first rule,

a FragmentActivity is quite similar to a standart Activity that you already know, besides having some Fragment oriented methods

second thing about Fragments, is that there is one important method you MUST call, wich is onCreateView, where you inflate your layout, think of it as the setContentLayout

here is an example:

    @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {     mView       = inflater.inflate(R.layout.fragment_layout, container, false);       return mView; } 

and continu your work based on that mView, so to find a View by id, call mView.findViewById(..);


for the FragmentActivity part:

the xml part "must" have a FrameLayout in order to inflate a fragment in it

        <FrameLayout             android:id="@+id/content_frame"             android:layout_width="match_parent"             android:layout_height="match_parent"  >         </FrameLayout> 

as for the inflation part

getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new YOUR_FRAGMENT, "TAG").commit();


begin with these, as there is tons of other stuf you must know about fragments and fragment activities, start of by reading something about it (like life cycle) at the android developer site

What is meant by Ems? (Android TextView)

Ems is a typography term, it controls text size, etc. Check here

Index of duplicates items in a python list

string_list = ['A', 'B', 'C', 'B', 'D', 'B']
pos_list = []
for i in range(len(string_list)):
    if string_list[i] = ='B':
        pos_list.append(i)
print pos_list

Attach the Java Source Code

What worked for me (with JDK7) was the following:

  1. Download the openjdk-xy-sources.jar from GrepCode,
  2. rename the file to src.zip,
  3. copy src.zip to the root folder of the JRE/JDK added to eclipse (the one with bin and lib folders in it)
  4. restart eclipse

Alternatively, if you don't want to write to your JDK folder, you could also attach src.zip to (at least) rt.jar in eclipse in the Window | Preferences menu in Java | Installed JREs.

If you're not comfortable with downloading the sources from GrepCode, you could also get them from openJDK directly. This requires requires a bit more effort, though. Replace step one above by the following steps:

  1. Download the JDK sources from here,
  2. extract all folders from the zip file's *openjdk\jdk\src\share\classes* folder,
  3. create a file src.zip and add these folders to it,
  4. copy src.zip to the root folder of the JRE/JDK added to eclipse (the one with bin and lib folders in it)
  5. restart eclipse

A third alternative to acquire src.zip is to download the unofficial OpenJDK builds from here. The src.zip is contained within the downloaded zip.

prevent iphone default keyboard when focusing an <input>

Best way to solve this as per my opinion is Using "ignoreReadonly".

First make the input field readonly then add ignoreReadonly:true. This will make sure that even if the text field is readonly , popup will show.

$('#txtStartDate').datetimepicker({
            locale: "da",
            format: "DD/MM/YYYY",
            ignoreReadonly: true
        });
        $('#txtEndDate').datetimepicker({
            locale: "da",
            useCurrent: false,
            format: "DD/MM/YYYY",
            ignoreReadonly: true
        });
});

MySQL - Replace Character in Columns

maybe I'd go by this.

 SQL = SELECT REPLACE(myColumn, '""', '\'') FROM myTable

I used singlequotes because that's the one that registers string expressions in MySQL, or so I believe.

Hope that helps.

How to enter quotes in a Java string?

suppose ROM is string variable which equals "strval" you can simply do

String value= " \" "+ROM+" \" ";

it will be stored as

value= " "strval" ";    

"Error 1067: The process terminated unexpectedly" when trying to start MySQL

I just went throught same issue and I solved it the following way. 1 - found the .err file which logs all mysql issues, in win7, located under programData\MySQL\MySQL Server 5.6\data\ 2 - Check the last entries from the file and, in my case, I found the error was coming from a flag (audit-log) that I set to "true" from the workbench interface the day before! 3 - went into the my.ini file, and removed audit-log=ON. 4 - launched mysql service and it worked!!

Xcode stuck on Indexing

This happened to me. If you are using cocoapods do this:

  1. Delete project.xcworkspace
  2. Reinstall pods using 'pod install' on the terminal
  3. It will create a new project.xcworkspace
  4. Open the new project.xcworkspace -> Clean -> Build

SQL Query Multiple Columns Using Distinct on One Column Only

You must use an aggregate function on the columns against which you are not grouping. In this example, I arbitrarily picked the Min function. You are combining the rows with the same FruitType value. If I have two rows with the same FruitType value but different Fruit_Id values for example, what should the system do?

Select Min(tblFruit_id) As tblFruit_id
    , tblFruit_FruitType
From tblFruit
Group By tblFruit_FruitType

SQL Fiddle example

Hashmap with Streams in Java 8 Streams to collect value of Map

Using keySet-

id1.keySet().stream()
        .filter(x -> x == 1)
        .map(x -> id1.get(x))
        .collect(Collectors.toList())

Twitter Bootstrap alert message close and open again

Data-dismiss completely removes the element. Use jQuery's .hide() method instead.

The fix-it-quick method:

Using inline javascript to hide the element onclick like this:

<div class="alert" style="display: none"> 
    <a class="close" onclick="$('.alert').hide()">×</a>  
    <strong>Warning!</strong> Best check yo self, you're not looking too good.  
</div>

<a href="#" onclick="$('alert').show()">show</a>

http://jsfiddle.net/cQNFL/

This should however only be used if you are lazy (which is no good thing if you want an maintainable app).

The do-it-right method:

Create a new data attribute for hiding an element.

Javascript:

$(function(){
    $("[data-hide]").on("click", function(){
        $("." + $(this).attr("data-hide")).hide()
        // -or-, see below
        // $(this).closest("." + $(this).attr("data-hide")).hide()
    })
})

and then change data-dismiss to data-hide in the markup. Example at jsfiddle.

$("." + $(this).attr("data-hide")).hide()

This will hide all elements with the class specified in data-hide, i.e: data-hide="alert" will hide all elements with the alert class.

Xeon06 provided an alternative solution:

$(this).closest("." + $(this).attr("data-hide")).hide()

This will only hide the closest parent element. This is very useful if you don't want to give each alert a unique class. Please note that, however, you need to place the close button within the alert.

Definition of .closest from jquery doc:

For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

Difference between getContext() , getApplicationContext() , getBaseContext() and "this"

A Context is:

  • an abstract class whose implementation is provided by the Android system.
  • It allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities, broadcasting and receiving intents, etc.

Curl : connection refused

Try curl -v http://localhost:8080/ instead of 127.0.0.1

invalid use of incomplete type

Not exactly what you were asking, but you can make action a template member function:

template<typename Subclass>
class A {
    public:
        //Why doesn't it like this?
        template<class V> void action(V var) {
                (static_cast<Subclass*>(this))->do_action();
        }
};

class B : public A<B> {
    public:
        typedef int mytype;

        B() {}

        void do_action(mytype var) {
                // Do stuff
        }
};

int main(int argc, char** argv) {
    B myInstance;
    return 0;
}

what is numeric(18, 0) in sql server 2008 r2

The first value is the precision and the second is the scale, so 18,0 is essentially 18 digits with 0 digits after the decimal place. If you had 18,2 for example, you would have 18 digits, two of which would come after the decimal...

example of 18,2: 1234567890123456.12

There is no functional difference between numeric and decimal, other that the name and I think I recall that numeric came first, as in an earlier version.

And to answer, "can I add (-10) in that column?" - Yes, you can.

What is the maximum length of a String in PHP?

http://php.net/manual/en/language.types.string.php says:

Note: As of PHP 7.0.0, there are no particular restrictions regarding the length of a string on 64-bit builds. On 32-bit builds and in earlier versions, a string can be as large as up to 2GB (2147483647 bytes maximum)

In PHP 5.x, strings were limited to 231-1 bytes, because internal code recorded the length in a signed 32-bit integer.


You can slurp in the contents of an entire file, for instance using file_get_contents()

However, a PHP script has a limit on the total memory it can allocate for all variables in a given script execution, so this effectively places a limit on the length of a single string variable too.

This limit is the memory_limit directive in the php.ini configuration file. The memory limit defaults to 128MB in PHP 5.2, and 8MB in earlier releases.

If you don't specify a memory limit in your php.ini file, it uses the default, which is compiled into the PHP binary. In theory you can modify the source and rebuild PHP to change this default value.

If you specify -1 as the memory limit in your php.ini file, it stop checking and permits your script to use as much memory as the operating system will allocate. This is still a practical limit, but depends on system resources and architecture.


Re comment from @c2:

Here's a test:

<?php

// limit memory usage to 1MB 
ini_set('memory_limit', 1024*1024);

// initially, PHP seems to allocate 768KB for basic operation
printf("memory: %d\n",  memory_get_usage(true));

$str = str_repeat('a',  255*1024);
echo "Allocated string of 255KB\n";

// now we have allocated all of the 1MB of memory allowed
printf("memory: %d\n",  memory_get_usage(true));

// going over the limit causes a fatal error, so no output follows
$str = str_repeat('a',  256*1024);
echo "Allocated string of 256KB\n";
printf("memory: %d\n",  memory_get_usage(true));

Excel formula to get cell color

Anticipating that I already had the answer, which is that there is no built-in worksheet function that returns the background color of a cell, I decided to review this article, in case I was wrong. I was amused to notice a citation to the very same MVP article that I used in the course of my ongoing research into colors in Microsoft Excel.

While I agree that, in the purest sense, color is not data, it is meta-data, and it has uses as such. To that end, I shall attempt to develop a function that returns the color of a cell. If I succeed, I plan to put it into an add-in, so that I can use it in any workbook, where it will join a growing legion of other functions that I think Microsoft left out of the product.

Regardless, IMO, the ColorIndex property is virtually useless, since there is essentially no connection between color indexes and the colors that can be selected in the standard foreground and background color pickers. See Color Combinations: Working with Colors in Microsoft Office and the associated binary workbook, Color_Combinations Workbook.

html <input type="text" /> onchange event not working

I encountered issues where Safari wasn't firing "onchange" events on a text input field. I used a jQuery 1.7.2 "change" event and it didn't work either. I ended up using ZURB's textchange event. It works with mouseevents and can fire without leaving the field:
http://www.zurb.com/playground/jquery-text-change-custom-event

$('.inputClassToBind').bind('textchange', function (event, previousText) {
    alert($(this).attr('id'));
});

How do I format currencies in a Vue component?

There is issues with the precision of the accepted answer.

the round(value, decimals) function in this test works. unlike the simple toFixed example.

this is a test of the toFixed vs round method.

http://www.jacklmoore.com/notes/rounding-in-javascript/

_x000D_
_x000D_
  Number.prototype.format = function(n) {_x000D_
      return this.toFixed(Math.max(0, ~~n));_x000D_
  };_x000D_
  function round(value, decimals) {_x000D_
    return Number(Math.round(value+'e'+decimals)+'e-'+decimals);_x000D_
  }_x000D_
_x000D_
  // can anyone tell me why these are equivalent for  50.005, and 1050.005 through 8150.005 (increments of 50)_x000D_
_x000D_
  var round_to = 2;_x000D_
  var maxInt = 1500000;_x000D_
  var equalRound = '<h1>BEGIN HERE</h1><div class="matches">';_x000D_
  var increment = 50;_x000D_
  var round_from = 0.005;_x000D_
  var expected = 0.01;_x000D_
  var lastWasMatch = true;_x000D_
_x000D_
  for( var n = 0; n < maxInt; n=n+increment){_x000D_
    var data = {};_x000D_
    var numberCheck = parseFloat(n + round_from);_x000D_
    data.original = numberCheck * 1;_x000D_
    data.expected =  Number(n + expected) * 1;_x000D_
    data.formatIt = Number(numberCheck).format(round_to) * 1;_x000D_
    data.roundIt = round(numberCheck, round_to).toFixed(round_to) * 1;_x000D_
    data.numberIt = Number(numberCheck).toFixed(round_to) * 1;_x000D_
    //console.log(data);_x000D_
_x000D_
    if( data.roundIt !== data.formatIt || data.formatIt !== data.numberIt ||_x000D_
       data.roundIt !== data.numberIt || data.roundIt != data.expected_x000D_
      ){_x000D_
        if(lastWasMatch){_x000D_
          equalRound = equalRound + '</div><div class="errors"> <hr/> Did Not Round UP <hr/>' ;_x000D_
            document.write(' <h3>EXAMPLE: Did Not Round UP: ' + numberCheck + '</h3><br /><hr/> ');_x000D_
            document.write('expected: '+data.expected + ' :: ' + (typeof data.expected)  + '<br />');_x000D_
            document.write('format: '+data.formatIt + ' :: ' + (typeof data.formatIt)  + '<br />');_x000D_
            document.write('round : '+data.roundIt + ' :: ' + (typeof data.roundIt)  + '<br />');_x000D_
            document.write('number: '+data.numberIt + ' :: ' + (typeof data.numberIt)  + '<br />');_x000D_
            lastWasMatch=false;_x000D_
        }_x000D_
        equalRound = equalRound + ', ' + numberCheck;_x000D_
    } else {_x000D_
        if(!lastWasMatch){_x000D_
          equalRound = equalRound + '</div><div class="matches"> <hr/> All Rounded UP! <hr/>' ;_x000D_
        } {_x000D_
            lastWasMatch=true;_x000D_
        }_x000D_
        equalRound = equalRound + ', ' + numberCheck;_x000D_
    }_x000D_
  }_x000D_
  document.write('equalRound: '+equalRound + '</div><br />');
_x000D_
_x000D_
_x000D_

mixin example

_x000D_
_x000D_
  export default {_x000D_
    methods: {_x000D_
      roundFormat: function (value, decimals) {_x000D_
        return Number(Math.round(value+'e'+decimals)+'e-'+decimals).toFixed(decimals);_x000D_
      },_x000D_
      currencyFormat: function (value, decimals, symbol='$') {_x000D_
        return symbol + this.roundFormat(value,2);_x000D_
      }_x000D_
    }_x000D_
  }
_x000D_
_x000D_
_x000D_

Reading a text file with SQL Server

BULK INSERT dbo.temp 

FROM 'c:\temp\file.txt' --- path file in db server 

WITH 

  (
     ROWTERMINATOR ='\n'
  )

it work for me but save as by editplus to ansi encoding for multilanguage

How do I remove repeated elements from ArrayList?

If you don't want duplicates in a Collection, you should consider why you're using a Collection that allows duplicates. The easiest way to remove repeated elements is to add the contents to a Set (which will not allow duplicates) and then add the Set back to the ArrayList:

Set<String> set = new HashSet<>(yourList);
yourList.clear();
yourList.addAll(set);

Of course, this destroys the ordering of the elements in the ArrayList.

How do I change the default location for Git Bash on Windows?

I tried the following; it helped me. I hope it help you also.

cd /c/xampp/your-project

What is object slicing?

"Slicing" is where you assign an object of a derived class to an instance of a base class, thereby losing part of the information - some of it is "sliced" away.

For example,

class A {
   int foo;
};

class B : public A {
   int bar;
};

So an object of type B has two data members, foo and bar.

Then if you were to write this:

B b;

A a = b;

Then the information in b about member bar is lost in a.

How to reload or re-render the entire page using AngularJS

For the record, to force angular to re-render the current page, you can use:

$route.reload();

According to AngularJS documentation:

Causes $route service to reload the current route even if $location hasn't changed.

As a result of that, ngView creates new scope, reinstantiates the controller.

ReactJS - .JS vs .JSX

As other mentioned JSX is not a standard Javascript extension. It's better to name your entry point of Application based on .js and for the rest components, you can use .jsx.

I have an important reason for why I'm using .JSX for all component's file names. Actually, In a large scale project with huge bunch of code, if we set all React's component with .jsx extension, It'll be easier while navigating to different javascript files across the project(like helpers, middleware, etc.) and you know this is a React Component and not other types of the javascript file.

How to change a string into uppercase

To get upper case version of a string you can use str.upper:

s = 'sdsd'
s.upper()
#=> 'SDSD'

On the other hand string.ascii_uppercase is a string containing all ASCII letters in upper case:

import string
string.ascii_uppercase
#=> 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

JavaScript object: access variable property by name as string

You don't need a function for it - simply use the bracket notation:

var side = columns['right'];

This is equal to dot notation, var side = columns.right;, except the fact that right could also come from a variable, function return value, etc., when using bracket notation.

If you NEED a function for it, here it is:

function read_prop(obj, prop) {
    return obj[prop];
}

To answer some of the comments below that aren't directly related to the original question, nested objects can be referenced through multiple brackets. If you have a nested object like so:

var foo = { a: 1, b: 2, c: {x: 999, y:998, z: 997}};

you can access property x of c as follows:

var cx = foo['c']['x']

If a property is undefined, an attempt to reference it will return undefined (not null or false):

foo['c']['q'] === null
// returns false

foo['c']['q'] === false
// returns false

foo['c']['q'] === undefined
// returns true

How do I make an input field accept only letters in javaScript?

Try this:

var alphaExp = /^[a-zA-Z]+$/;
            if(document.myForm.name.match(alphaExp))
            {
                //Your logice will be here.
            }
            else{
                alert("Please enter only alphabets");
            }

Thanks.

How to select data where a field has a min value in MySQL?

To make it simpler

SELECT *,MIN(price) FROM prod LIMIT 1

  • Put * so it will display the all record of the minimum value

Error in Swift class: Property not initialized at super.init call

You are just initing in the wrong order.

     class Shape2 {
        var numberOfSides = 0
        var name: String
        init(name:String) {
            self.name = name
        }
        func simpleDescription() -> String {
            return "A shape with \(numberOfSides) sides."
        }
    }

    class Square2: Shape2 {
        var sideLength: Double

        init(sideLength:Double, name:String) {

            self.sideLength = sideLength
            super.init(name:name) // It should be behind "self.sideLength = sideLength"
            numberOfSides = 4
        }
        func area () -> Double {
            return sideLength * sideLength
        }
    }

iOS: Compare two dates

According to Apple documentation of NSDate compare:

Returns an NSComparisonResult value that indicates the temporal ordering of the receiver and another given date.

- (NSComparisonResult)compare:(NSDate *)anotherDate

Parameters anotherDate

The date with which to compare the receiver. This value must not be nil. If the value is nil, the behavior is undefined and may change in future versions of Mac OS X.

Return Value

If:

The receiver and anotherDate are exactly equal to each other, NSOrderedSame

The receiver is later in time than anotherDate, NSOrderedDescending

The receiver is earlier in time than anotherDate, NSOrderedAscending

In other words:

if ([date1 compare:date2] == NSOrderedSame) ...

Note that it might be easier in your particular case to read and write this :

if ([date2 isEqualToDate:date2]) ...

See Apple Documentation about this one.

Angular 2 Show and Hide an element

Depending on your needs, *ngIf or [ngClass]="{hide_element: item.hidden}" where CSS class hide_element is { display: none; }

*ngIf can cause issues if you're changing state variables *ngIf is removing, in those cases using CSS display: none; is required.

How to write lists inside a markdown table?

another solution , you can add <br> tag to your table

    |Method name| Behavior |
    |--|--|
    | OnAwakeLogicController(); | Its called when MainLogicController is loaded into the memory , its also hold the following actions :- <br> 1. Checking Audio Settings <br>2. Initializing Level Controller|

enter image description here

Find object by id in an array of JavaScript objects

We can use Jquery methods $.each()/$.grep()

var data= [];
$.each(array,function(i){if(n !== 5 && i > 4){data.push(item)}}

or

var data = $.grep(array, function( n, i ) {
  return ( n !== 5 && i > 4 );
});

use ES6 syntax:

Array.find, Array.filter, Array.forEach, Array.map

Or use Lodash https://lodash.com/docs/4.17.10#filter, Underscore https://underscorejs.org/#filter

Maximum value for long integer

Python long can be arbitrarily large. If you need a value that's greater than any other value, you can use float('inf'), since Python has no trouble comparing numeric values of different types. Similarly, for a value lesser than any other value, you can use float('-inf').

Convert string to buffer Node

You can use Buffer.from() to convert a string to buffer. More information on this can be found here

var buf = Buffer.from('some string', 'encoding');

for example

var buf = Buffer.from(bStr, 'utf-8');

Cannot download Docker images behind a proxy

In my network, Ubuntu works behind a corporate ISA proxy server. And it requires authentication. I tried all the solutions mentioned above and nothing helped. What really helped was to write a proxy line in file /etc/systemd/system/docker.service.d/https-proxy.conf without a domain name.

Instead of

Environment="HTTP_PROXY=http://user@domain:password@proxy:8080"

or

Environment="HTTP_PROXY=http://domain\user:password@proxy:8080"

and some other replacement such as @ -> %40 or \ -> \\ I tried to use

Environment="HTTP_PROXY=http://user:password@proxy:8080"

And it works now.

Difference between $.ajax() and $.get() and $.load()

The methods provide different layers of abstraction.

  • $.ajax() gives you full control over the Ajax request. You should use it if the other methods don't fullfil your needs.

  • $.get() executes an Ajax GET request. The returned data (which can be any data) will be passed to your callback handler.

  • $(selector).load() will execute an Ajax GET request and will set the content of the selected returned data (which should be either text or HTML).

It depends on the situation which method you should use. If you want to do simple stuff, there is no need to bother with $.ajax().

E.g. you won't use $.load(), if the returned data will be JSON which needs to be processed further. Here you would either use $.ajax() or $.get().

send bold & italic text on telegram bot with html

If you are using PHP you can use this, and I'm sure it's almost similar in other languages as well

$WebsiteURL = "https://api.telegram.org/bot".$BotToken;
$text = "<b>This</b> <i>is some Text</i>";
$Update = file_get_contents($WebsiteURL."/sendMessage?chat_id=$chat_id&text=$text&parse_mode=html);

echo $Update;

Here is the list of all tags that you can use

<b>bold</b>, <strong>bold</strong>
<i>italic</i>, <em>italic</em>
<a href="http://www.example.com/">inline URL</a>
<code>inline fixed-width code</code>
<pre>pre-formatted fixed-width code block</pre>

Chrome dev tools fails to show response even the content returned has header Content-Type:text/html; charset=UTF-8

As described by Gideon, this is a known issue.
For use window.onunload = function() { debugger; } instead.
But you can add a breakpoint in Source tab, then can solve your problem. like this: enter image description here

How to get access token from FB.login method in javascript SDK

You can get access token using FB.getAuthResponse()['accessToken']:

FB.login(function(response) {
   if (response.authResponse) {
     var access_token =   FB.getAuthResponse()['accessToken'];
     console.log('Access Token = '+ access_token);
     FB.api('/me', function(response) {
     console.log('Good to see you, ' + response.name + '.');
     });
   } else {
     console.log('User cancelled login or did not fully authorize.');
   }
 }, {scope: ''});

Edit: Updated to use Oauth 2.0, required since December 2011. Now uses FB.getAuthResponse(); If you are using a browser that does not have a console, (I'm talking to you, Internet Explorer) be sure to comment out the console.log lines or use a log-failsafe script such as:

if (typeof(console) == "undefined") { console = {}; } 
if (typeof(console.log) == "undefined") { console.log = function() { return 0; } }

How do I Sort a Multidimensional Array in PHP

Here is a php4/php5 class that will sort one or more fields:

// a sorter class
//  php4 and php5 compatible
class Sorter {

  var $sort_fields;
  var $backwards = false;
  var $numeric = false;

  function sort() {
    $args = func_get_args();
    $array = $args[0];
    if (!$array) return array();
    $this->sort_fields = array_slice($args, 1);
    if (!$this->sort_fields) return $array();

    if ($this->numeric) {
      usort($array, array($this, 'numericCompare'));
    } else {
      usort($array, array($this, 'stringCompare'));
    }
    return $array;
  }

  function numericCompare($a, $b) {
    foreach($this->sort_fields as $sort_field) {
      if ($a[$sort_field] == $b[$sort_field]) {
        continue;
      }
      return ($a[$sort_field] < $b[$sort_field]) ? ($this->backwards ? 1 : -1) : ($this->backwards ? -1 : 1);
    }
    return 0;
  }

  function stringCompare($a, $b) {
    foreach($this->sort_fields as $sort_field) {
      $cmp_result = strcasecmp($a[$sort_field], $b[$sort_field]);
      if ($cmp_result == 0) continue;

      return ($this->backwards ? -$cmp_result : $cmp_result);
    }
    return 0;
  }
}

/////////////////////
// usage examples

// some starting data
$start_data = array(
  array('first_name' => 'John', 'last_name' => 'Smith', 'age' => 10),
  array('first_name' => 'Joe', 'last_name' => 'Smith', 'age' => 11),
  array('first_name' => 'Jake', 'last_name' => 'Xample', 'age' => 9),
);

// sort by last_name, then first_name
$sorter = new Sorter();
print_r($sorter->sort($start_data, 'last_name', 'first_name'));

// sort by first_name, then last_name
$sorter = new Sorter();
print_r($sorter->sort($start_data, 'first_name', 'last_name'));

// sort by last_name, then first_name (backwards)
$sorter = new Sorter();
$sorter->backwards = true;
print_r($sorter->sort($start_data, 'last_name', 'first_name'));

// sort numerically by age
$sorter = new Sorter();
$sorter->numeric = true;
print_r($sorter->sort($start_data, 'age'));

How can I undo a mysql statement that I just executed?

in case you do not only need to undo your last query (although your question actually only points on that, I know) and therefore if a transaction might not help you out, you need to implement a workaround for this:

copy the original data before commiting your query and write it back on demand based on the unique id that must be the same in both tables; your rollback-table (with the copies of the unchanged data) and your actual table (containing the data that should be "undone" than). for databases having many tables, one single "rollback-table" containing structured dumps/copies of the original data would be better to use then one for each actual table. it would contain the name of the actual table, the unique id of the row, and in a third field the content in any desired format that represents the data structure and values clearly (e.g. XML). based on the first two fields this third one would be parsed and written back to the actual table. a fourth field with a timestamp would help cleaning up this rollback-table.

since there is no real undo in SQL-dialects despite "rollback" in a transaction (please correct me if I'm wrong - maybe there now is one), this is the only way, I guess, and you have to write the code for it on your own.

Convert Json String to C# Object List

Try to change type of ScoreIfNoMatch, like this:

   public class MatrixModel
        {
            public string S1 { get; set; }
            public string S2 { get; set; }
            public string S3 { get; set; }
            public string S4 { get; set; }
            public string S5 { get; set; }
            public string S6 { get; set; }
            public string S7 { get; set; }
            public string S8 { get; set; }
            public string S9 { get; set; }
            public string S10 { get; set; }
            // the type should be string
            public string ScoreIfNoMatch { get; set; }
        }

How to set the default value of an attribute on a Laravel model

The other answers are not working for me - they may be outdated. This is what I used as my solution for auto setting an attribute:

/**
 * The "booting" method of the model.
 *
 * @return void
 */
protected static function boot()
{
    parent::boot();

    // auto-sets values on creation
    static::creating(function ($query) {
        $query->is_voicemail = $query->is_voicemail ?? true;
    });
}

How to "properly" print a list?

Using only print:

>>> l = ['x', 3, 'b']
>>> print(*l, sep='\n')
x
3
b
>>> print(*l, sep=', ')
x, 3, b

Convert DataFrame column type from string to datetime, dd/mm/yyyy format

If your date column is a string of the format '2017-01-01' you can use pandas astype to convert it to datetime.

df['date'] = df['date'].astype('datetime64[ns]')

or use datetime64[D] if you want Day precision and not nanoseconds

print(type(df_launath['date'].iloc[0]))

yields

<class 'pandas._libs.tslib.Timestamp'> the same as when you use pandas.to_datetime

You can try it with other formats then '%Y-%m-%d' but at least this works.

How to check if a service is running via batch file and start it, if it is not running?

@echo off

color 1F


@sc query >%COMPUTERNAME%_START.TXT


find /I "AcPrfMgrSvc" %COMPUTERNAME%_START.TXT >nul

IF ERRORLEVEL 0 EXIT

IF ERRORLEVEL 1 NET START "AcPrfMgrSvc"

Remove the last chars of the Java String variable

Another way:

if (s.size > 5) s.reverse.substring(5).reverse

BTW, this is Scala code. May need brackets to work in Java.

Html.Textbox VS Html.TextboxFor

IMO the main difference is that Textbox is not strongly typed. TextboxFor take a lambda as a parameter that tell the helper the with element of the model to use in a typed view.

You can do the same things with both, but you should use typed views and TextboxFor when possible.

Set custom HTML5 required field validation message

Code snippet

Since this answer got very much attention, here is a nice configurable snippet I came up with:

/**
  * @author ComFreek <https://stackoverflow.com/users/603003/comfreek>
  * @link https://stackoverflow.com/a/16069817/603003
  * @license MIT 2013-2015 ComFreek
  * @license[dual licensed] CC BY-SA 3.0 2013-2015 ComFreek
  * You MUST retain this license header!
  */
(function (exports) {
    function valOrFunction(val, ctx, args) {
        if (typeof val == "function") {
            return val.apply(ctx, args);
        } else {
            return val;
        }
    }

    function InvalidInputHelper(input, options) {
        input.setCustomValidity(valOrFunction(options.defaultText, window, [input]));

        function changeOrInput() {
            if (input.value == "") {
                input.setCustomValidity(valOrFunction(options.emptyText, window, [input]));
            } else {
                input.setCustomValidity("");
            }
        }

        function invalid() {
            if (input.value == "") {
                input.setCustomValidity(valOrFunction(options.emptyText, window, [input]));
            } else {
               input.setCustomValidity(valOrFunction(options.invalidText, window, [input]));
            }
        }

        input.addEventListener("change", changeOrInput);
        input.addEventListener("input", changeOrInput);
        input.addEventListener("invalid", invalid);
    }
    exports.InvalidInputHelper = InvalidInputHelper;
})(window);

Usage

jsFiddle

<input id="email" type="email" required="required" />
InvalidInputHelper(document.getElementById("email"), {
  defaultText: "Please enter an email address!",

  emptyText: "Please enter an email address!",

  invalidText: function (input) {
    return 'The email address "' + input.value + '" is invalid!';
  }
});

More details

  • defaultText is displayed initially
  • emptyText is displayed when the input is empty (was cleared)
  • invalidText is displayed when the input is marked as invalid by the browser (for example when it's not a valid email address)

You can either assign a string or a function to each of the three properties.
If you assign a function, it can accept a reference to the input element (DOM node) and it must return a string which is then displayed as the error message.

Compatibility

Tested in:

  • Chrome Canary 47.0.2
  • IE 11
  • Microsoft Edge (using the up-to-date version as of 28/08/2015)
  • Firefox 40.0.3
  • Opera 31.0

Old answer

You can see the old revision here: https://stackoverflow.com/revisions/16069817/6

How to change text color of cmd with windows batch script every 1 second

This should fit the bill. Sounds like a super-annoying thing to have going on, but there you have it:

@echo off
set NUM=0 1 2 3 4 5 6 7 8 9 A B C D E F
for %%x in (%NUM%) do ( 
    for %%y in (%NUM%) do (
        color %%x%%y
        timeout 1 >nul
    )
)

SQL Server 100% CPU Utilization - One database shows high CPU usage than others

According to this article on sqlserverstudymaterial;

Remember that "%Privileged time" is not based on 100%.It is based on number of processors.If you see 200 for sqlserver.exe and the system has 8 CPU then CPU consumed by sqlserver.exe is 200 out of 800 (only 25%).

If "% Privileged Time" value is more than 30% then it's generally caused by faulty drivers or anti-virus software. In such situations make sure the BIOS and filter drives are up to date and then try disabling the anti-virus software temporarily to see the change.

If "% User Time" is high then there is something consuming of SQL Server. There are several known patterns which can be caused high CPU for processes running in SQL Server including

Android ImageView Fixing Image Size

In your case you need to

  1. Fix the ImageView's size. You need to use dp unit so that it will look the same in all devices.
  2. Set android:scaleType to fitXY

Below is an example:

<ImageView
    android:id="@+id/photo"
    android:layout_width="200dp"
    android:layout_height="100dp"
    android:src="@drawable/iclauncher" 
    android:scaleType="fitXY"/>

For more information regarding ImageView scaleType please refer to the developer website.

Spring Boot REST service exception handling

With Spring Boot 1.4+ new cool classes for easier exception handling were added that helps in removing the boilerplate code.

A new @RestControllerAdvice is provided for exception handling, it is combination of @ControllerAdvice and @ResponseBody. You can remove the @ResponseBody on the @ExceptionHandler method when use this new annotation.

i.e.

@RestControllerAdvice
public class GlobalControllerExceptionHandler {

    @ExceptionHandler(value = { Exception.class })
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ApiErrorResponse unknownException(Exception ex, WebRequest req) {
        return new ApiErrorResponse(...);
    }
}

For handling 404 errors adding @EnableWebMvc annotation and the following to application.properties was enough:
spring.mvc.throw-exception-if-no-handler-found=true

You can find and play with the sources here:
https://github.com/magiccrafter/spring-boot-exception-handling

How to do tag wrapping in VS code?

Embedded Emmet could do the trick:

  1. Select text (optional)
  2. Open command palette (usually Ctrl+Shift+P)
  3. Execute Emmet: Wrap with Abbreviation
  4. Enter a tag div (or an abbreviation .wrapper>p)
  5. Hit Enter

Command can be assigned to a keybinding.

enter image description here


This thing even supports passing arguments:

{
    "key": "ctrl+shift+9",
    "command": "editor.emmet.action.wrapWithAbbreviation",
    "when": "editorHasSelection",
    "args": {
        "abbreviation": "span"
    }
},

Use it like this:

  • span.myCssClass
  • span#myCssId
  • b
  • b.myCssClass

Get first element from a dictionary

Though you can use First(), Dictionaries do not have order per se. Please use OrderedDictionary instead. And then you can do FirstOrDefault. This way it will be meaningful.

What is the backslash character (\\)?

If double backslash looks weird to you, C# also allows verbatim string literals where the escaping is not required.

Console.WriteLine(@"Mango \ Nightangle");

Don't you just wish Java had something like this ;-)

Bootstrap: Position of dropdown menu relative to navbar item

If you want to display the menu up, just add the class "dropup"
and remove the class "dropdown" if exists from the same div.

<div class="btn-group dropup">

enter image description here

Show loading screen when navigating between routes in Angular 2

You could also use this existing solution. The demo is here. It looks like youtube loading bar. I just found it and added it to my own project.

Android fade in and fade out with ImageView

you can do it by two simple point and change in your code

1.In your xml in anim folder of your project, Set the fade in and fade out duration time not equal

2.In you java class before the start of fade out animation, set second imageView visibility Gone then after fade out animation started set second imageView visibility which you want to fade in visible

fadeout.xml

<alpha
    android:duration="4000"
    android:fromAlpha="1.0"
    android:interpolator="@android:anim/accelerate_interpolator"
    android:toAlpha="0.0" />

fadein.xml

<alpha
    android:duration="6000"
    android:fromAlpha="0.0"
    android:interpolator="@android:anim/accelerate_interpolator"
    android:toAlpha="1.0" />

In you java class

Animation animFadeOut = AnimationUtils.loadAnimation(this, R.anim.fade_out);
    ImageView iv = (ImageView) findViewById(R.id.imageView1);
    ImageView iv2 = (ImageView) findViewById(R.id.imageView2);
    iv.setVisibility(View.VISIBLE);
    iv2.setVisibility(View.GONE);
    animFadeOut.reset();
    iv.clearAnimation();
    iv.startAnimation(animFadeOut);

    Animation animFadeIn = AnimationUtils.loadAnimation(this, R.anim.fade_in);
    iv2.setVisibility(View.VISIBLE);
    animFadeIn.reset();
    iv2.clearAnimation();
    iv2.startAnimation(animFadeIn);

How to center body on a page?

    body
    {
        width:80%;
        margin-left:auto;
        margin-right:auto;
    }

This will work on most browsers, including IE.

Getting DOM node from React child element

I found an easy way using the new callback refs. You can just pass a callback as a prop to the child component. Like this:

class Container extends React.Component {
  constructor(props) {
    super(props)
    this.setRef = this.setRef.bind(this)
  }

  setRef(node) {
    this.childRef = node
  }

  render() {
    return <Child setRef={ this.setRef }/>
  }
}

const Child = ({ setRef }) => (
    <div ref={ setRef }>
    </div>
)

Here's an example of doing this with a modal:

class Container extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      modalOpen: false
    }
    this.open = this.open.bind(this)
    this.close = this.close.bind(this)
    this.setModal = this.setModal.bind(this)
  }

  open() {
    this.setState({ open: true })
  }

  close(event) {
    if (!this.modal.contains(event.target)) {
      this.setState({ open: false })
    }
  }

  setModal(node) {
    this.modal = node
  }

  render() {
    let { modalOpen } = this.state
    return (
      <div>
        <button onClick={ this.open }>Open</button>
        {
          modalOpen ? <Modal close={ this.close } setModal={ this.setModal }/> : null
        }
      </div>
    )
  }
}

const Modal = ({ close, setModal }) => (
  <div className='modal' onClick={ close }>
    <div className='modal-window' ref={ setModal }>
    </div>
  </div>
)

CSS overflow-x: visible; and overflow-y: hidden; causing scrollbar issue

After some serious searching it seems i've found the answer to my question:

from: http://www.brunildo.org/test/Overflowxy2.html

In Gecko, Safari, Opera, ‘visible’ becomes ‘auto’ also when combined with ‘hidden’ (in other words: ‘visible’ becomes ‘auto’ when combined with anything else different from ‘visible’). Gecko 1.8, Safari 3, Opera 9.5 are pretty consistent among them.

also the W3C spec says:

The computed values of ‘overflow-x’ and ‘overflow-y’ are the same as their specified values, except that some combinations with ‘visible’ are not possible: if one is specified as ‘visible’ and the other is ‘scroll’ or ‘auto’, then ‘visible’ is set to ‘auto’. The computed value of ‘overflow’ is equal to the computed value of ‘overflow-x’ if ‘overflow-y’ is the same; otherwise it is the pair of computed values of ‘overflow-x’ and ‘overflow-y’.

Short Version:

If you are using visible for either overflow-x or overflow-y and something other than visible for the other, the visible value is interpreted as auto.

How to extract text from the PDF document?

Download the class.pdf2text.php @ https://pastebin.com/dvwySU1a or http://www.phpclasses.org/browse/file/31030.html (Registration required)

Code:

include('class.pdf2text.php');
$a = new PDF2Text();
$a->setFilename('filename.pdf'); 
$a->decodePDF();
echo $a->output(); 

  • class.pdf2text.php Project Home

  • pdf2textclass doesn't work with all the PDF's I've tested, If it doesn't work for you, try PDF Parser


Best practice to validate null and empty collection in Java

When you use spring then you can use

boolean isNullOrEmpty = org.springframework.util.ObjectUtils.isEmpty(obj);

where obj is any [map,collection,array,aything...]

otherwise: the code is:

public static boolean isEmpty(Object[] array) {
    return (array == null || array.length == 0);
}

public static boolean isEmpty(Object obj) {
    if (obj == null) {
        return true;
    }

    if (obj.getClass().isArray()) {
        return Array.getLength(obj) == 0;
    }
    if (obj instanceof CharSequence) {
        return ((CharSequence) obj).length() == 0;
    }
    if (obj instanceof Collection) {
        return ((Collection) obj).isEmpty();
    }
    if (obj instanceof Map) {
        return ((Map) obj).isEmpty();
    }

    // else
    return false;
}

for String best is:

boolean isNullOrEmpty = (str==null || str.trim().isEmpty());

java - iterating a linked list

I found 5 main ways to iterate over a Linked List in Java (including the Java 8 way):

  1. For Loop
  2. Enhanced For Loop
  3. While Loop
  4. Iterator
  5. Collections’s stream() util (Java8)

For loop

LinkedList<String> linkedList = new LinkedList<>();
System.out.println("==> For Loop Example.");
for (int i = 0; i < linkedList.size(); i++) {
    System.out.println(linkedList.get(i));
}

Enhanced for loop

for (String temp : linkedList) {
    System.out.println(temp);
}

While loop

int i = 0;
while (i < linkedList.size()) {
    System.out.println(linkedList.get(i));
    i++;
}

Iterator

Iterator<String> iterator = linkedList.iterator();
while (iterator.hasNext()) {
    System.out.println(iterator.next()); 
}

collection stream() util (Java 8)

linkedList.forEach((temp) -> {
    System.out.println(temp);
});

One thing should be pointed out is that the running time of For Loop or While Loop is O(n square) because get(i) operation takes O(n) time(see this for details). The other 3 ways take linear time and performs better.

Comparing two dataframes and getting the differences

Updating and placing, somewhere it will be easier for others to find, ling's comment upon jur's response above.

df_diff = pd.concat([df1,df2]).drop_duplicates(keep=False)

Testing with these DataFrames:

# with import pandas as pd

df1 = pd.DataFrame({
    'Date':['2013-11-24','2013-11-24','2013-11-24','2013-11-24'],
    'Fruit':['Banana','Orange','Apple','Celery'],
    'Num':[22.1,8.6,7.6,10.2],
    'Color':['Yellow','Orange','Green','Green'],
    })

df2 = pd.DataFrame({
    'Date':['2013-11-24','2013-11-24','2013-11-24','2013-11-24','2013-11-25','2013-11-25'],
    'Fruit':['Banana','Orange','Apple','Celery','Apple','Orange'],
    'Num':[22.1,8.6,7.6,10.2,22.1,8.6],
    'Color':['Yellow','Orange','Green','Green','Red','Orange'],
    })

Results in this:

# for df1

         Date   Fruit   Num   Color
0  2013-11-24  Banana  22.1  Yellow
1  2013-11-24  Orange   8.6  Orange
2  2013-11-24   Apple   7.6   Green
3  2013-11-24  Celery  10.2   Green


# for df2

         Date   Fruit   Num   Color
0  2013-11-24  Banana  22.1  Yellow
1  2013-11-24  Orange   8.6  Orange
2  2013-11-24   Apple   7.6   Green
3  2013-11-24  Celery  10.2   Green
4  2013-11-25   Apple  22.1     Red
5  2013-11-25  Orange   8.6  Orange


# for df_diff

         Date   Fruit   Num   Color
4  2013-11-25   Apple  22.1     Red
5  2013-11-25  Orange   8.6  Orange

How to implement onBackPressed() in Fragments?

Just add addToBackStack while you are transitioning between your fragments like below:

fragmentManager.beginTransaction().replace(R.id.content_frame,fragment).addToBackStack("tag").commit();

if you write addToBackStack(null) , it will handle it by itself but if you give a tag , you should handle it manually.

LINQ select in C# dictionary

One way would be to first flatten the list with a SelectMany:

subList.SelectMany(m => m).Where(k => k.Key.Equals("valueTitle"));

error: request for member '..' in '..' which is of non-class type

I was having a similar error, it seems that the compiler misunderstand the call to the constructor without arguments. I made it work by removing the parenthesis from the variable declaration, in your code something like this:

class Foo
{
  public:
    Foo() {};
    Foo(int a) {};
    void bar() {};
};

int main()
{
  // this works...
  Foo foo1(1);
  foo1.bar();

  // this does not...
  Foo foo2; // Without "()" 
  foo2.bar();

  return 0;
}

XPath: select text node

your xpath should work . i have tested your xpath and mine in both MarkLogic and Zorba Xquery/ Xpath implementation.

Both should work.

/node/child::text()[1] - should return Text1
/node/child::text()[2] - should return text2


/node/text()[1] - should return Text1
/node/text()[2] - should return text2

Command to get latest Git commit hash from a branch

In a comment you wrote

i want to show that there is a difference in local and github repo

As already mentioned in another answer, you should do a git fetch origin first. Then, if the remote is ahead of your current branch, you can list all commits between your local branch and the remote with

git log master..origin/master --stat

If your local branch is ahead:

git log origin/master..master --stat

--stat shows a list of changed files as well.

If you want to explicitly list the additions and deletions, use git diff:

git diff master origin/master

How to execute 16-bit installer on 64-bit Win7?

You can't run 16-bit applications (or components) on 64-bit versions of Windows. That emulation layer no longer exists. The 64-bit versions already have to provide a compatibility layer for 32-bit applications.

Support for 16-bit had to be dropped eventually, even in a culture where backwards-compatibility is of sacred import. The transition to 64-bit seemed like as good a time as any. It's hard to imagine anyone out there in the wild that is still using 16-bit applications and seeking to upgrade to 64-bit OSes.

What would be the best way to get round this problem?

If the component itself is 16-bit, then using a virtual machine running a 32-bit version of Windows is your only real choice. Oracle's VirtualBox is free, and a perennial favorite.

If only the installer is 16-bit (and it installs a 32-bit component), then you might be able to use a program like 7-Zip to extract the contents of the installer and install them manually. Let's just say this "solution" is high-risk and you should have few, if any, expectations.

It's high time to upgrade away from 16-bit stuff, like Turbo C++ and Sheridan controls. I've yet to come across anything that the Sheridan controls can do that the built-in controls can't do and haven't been able to do since Windows 95.

Validating parameters to a Bash script

You can validate point a and b compactly by doing something like the following:

#!/bin/sh
MYVAL=$(echo ${1} | awk '/^[0-9]+$/')
MYVAL=${MYVAL:?"Usage - testparms <number>"}
echo ${MYVAL}

Which gives us ...

$ ./testparams.sh 
Usage - testparms <number>

$ ./testparams.sh 1234
1234

$ ./testparams.sh abcd
Usage - testparms <number>

This method should work fine in sh.

Sending email with PHP from an SMTP server

For Unix users, mail() is actually using Sendmail command to send email. Instead of modifying the application, you can change the environment. msmtp is an SMTP client with Sendmail compatible CLI syntax which means it can be used in place of Sendmail. It only requires a small change to your php.ini.

sendmail_path = "/usr/bin/msmtp -C /path/to/your/config -t"

Then even the lowly mail() function can work with SMTP goodness. It is super useful if you're trying to connect an existing application to mail services like sendgrid or mandrill without modifying the application.