Programs & Examples On #Planerotation

Convert Date/Time for given Timezone - java

The solution is actually quite simple (pure, simple Java):

System.out.println(" NZ Local Time: 2011-10-06 03:35:05");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime localNZ = LocalDateTime.parse("2011-10-06 03:35:05",formatter);
ZonedDateTime zonedNZ = ZonedDateTime.of(localNZ,ZoneId.of("+13:00"));
LocalDateTime localUTC = zonedNZ.withZoneSameInstant(ZoneId.of("UTC")).toLocalDateTime();
System.out.println("UTC Local Time: "+localUTC.format(formatter));

OUTPUT IS:

 NZ Local Time: 2011-10-06 03:35:05
UTC Local Time: 2011-10-05 14:35:05

php foreach with multidimensional array

This would have been a comment under Brad's answer, but I don't have a high enough reputation.

Recently I found that I needed the key of the multidimensional array too, i.e., it wasn't just an index for the array, in the foreach loop.

In order to achieve that, you could use something very similar to the accepted answer, but instead split the key and value as follows

foreach ($mda as $mdaKey => $mdaData) {
    echo $mdaKey . ": " . $mdaData["value"];
}

Hope that helps someone.

Best data type to store money values in MySQL

It depends on your need.

Using DECIMAL(10,2) usually is enough but if you need a little bit more precise values you can set DECIMAL(10,4).

If you work with big values replace 10 with 19.

How to bind inverse boolean properties in WPF?

Add one more property in your view model, which will return reverse value. And bind that to button. Like;

in view model:

public bool IsNotReadOnly{get{return !IsReadOnly;}}

in xaml:

IsEnabled="{Binding IsNotReadOnly"}

How to get the cell value by column name not by index in GridView in asp.net

You can use the DataRowView to get the column index.

    void OnRequestsGridRowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            var data = e.Row.DataItem as DataRowView;

            // replace request name with a link
            if (data.DataView.Table.Columns["Request Name"] != null)
            {
                // get the request name
                string title = data["Request Name"].ToString();
                // get the column index
                int idx = data.Row.Table.Columns["Request Name"].Ordinal;

                // ...

                e.Row.Cells[idx].Controls.Clear();
                e.Row.Cells[idx].Controls.Add(link);
            }
        }
    }

Concatenating strings in C, which method is more efficient?

Don't worry about efficiency: make your code readable and maintainable. I doubt the difference between these methods is going to matter in your program.

Launching an application (.EXE) from C#?

Use System.Diagnostics.Process.Start() method.

Check out this article on how to use it.

Process.Start("notepad", "readme.txt");

string winpath = Environment.GetEnvironmentVariable("windir");
string path = System.IO.Path.GetDirectoryName(
              System.Windows.Forms.Application.ExecutablePath);

Process.Start(winpath + @"\Microsoft.NET\Framework\v1.0.3705\Installutil.exe",
path + "\\MyService.exe");

Optimal way to concatenate/aggregate strings

Although @serge answer is correct but i compared time consumption of his way against xmlpath and i found the xmlpath is so faster. I'll write the compare code and you can check it by yourself. This is @serge way:

DECLARE @startTime datetime2;
DECLARE @endTime datetime2;
DECLARE @counter INT;
SET @counter = 1;

set nocount on;

declare @YourTable table (ID int, Name nvarchar(50))

WHILE @counter < 1000
BEGIN
    insert into @YourTable VALUES (ROUND(@counter/10,0), CONVERT(NVARCHAR(50), @counter) + 'CC')
    SET @counter = @counter + 1;
END

SET @startTime = GETDATE()

;WITH Partitioned AS
(
    SELECT 
        ID,
        Name,
        ROW_NUMBER() OVER (PARTITION BY ID ORDER BY Name) AS NameNumber,
        COUNT(*) OVER (PARTITION BY ID) AS NameCount
    FROM @YourTable
),
Concatenated AS
(
    SELECT ID, CAST(Name AS nvarchar) AS FullName, Name, NameNumber, NameCount FROM Partitioned WHERE NameNumber = 1

    UNION ALL

    SELECT 
        P.ID, CAST(C.FullName + ', ' + P.Name AS nvarchar), P.Name, P.NameNumber, P.NameCount
    FROM Partitioned AS P
        INNER JOIN Concatenated AS C ON P.ID = C.ID AND P.NameNumber = C.NameNumber + 1
)
SELECT 
    ID,
    FullName
FROM Concatenated
WHERE NameNumber = NameCount

SET @endTime = GETDATE();

SELECT DATEDIFF(millisecond,@startTime, @endTime)
--Take about 54 milliseconds

And this is xmlpath way:

DECLARE @startTime datetime2;
DECLARE @endTime datetime2;
DECLARE @counter INT;
SET @counter = 1;

set nocount on;

declare @YourTable table (RowID int, HeaderValue int, ChildValue varchar(5))

WHILE @counter < 1000
BEGIN
    insert into @YourTable VALUES (@counter, ROUND(@counter/10,0), CONVERT(NVARCHAR(50), @counter) + 'CC')
    SET @counter = @counter + 1;
END

SET @startTime = GETDATE();

set nocount off
SELECT
    t1.HeaderValue
        ,STUFF(
                   (SELECT
                        ', ' + t2.ChildValue
                        FROM @YourTable t2
                        WHERE t1.HeaderValue=t2.HeaderValue
                        ORDER BY t2.ChildValue
                        FOR XML PATH(''), TYPE
                   ).value('.','varchar(max)')
                   ,1,2, ''
              ) AS ChildValues
    FROM @YourTable t1
    GROUP BY t1.HeaderValue

SET @endTime = GETDATE();

SELECT DATEDIFF(millisecond,@startTime, @endTime)
--Take about 4 milliseconds

How to resize images proportionally / keeping the aspect ratio?

After some trial and error I came to this solution:

function center(img) {
    var div = img.parentNode;
    var divW = parseInt(div.style.width);
    var divH = parseInt(div.style.height);
    var srcW = img.width;
    var srcH = img.height;
    var ratio = Math.min(divW/srcW, divH/srcH);
    var newW = img.width * ratio;
    var newH = img.height * ratio;
    img.style.width  = newW + "px";
    img.style.height = newH + "px";
    img.style.marginTop = (divH-newH)/2 + "px";
    img.style.marginLeft = (divW-newW)/2 + "px";
}

How should I use try-with-resources with JDBC?

I realize this was long ago answered but want to suggest an additional approach that avoids the nested try-with-resources double block.

public List<User> getUser(int userId) {
    try (Connection con = DriverManager.getConnection(myConnectionURL);
         PreparedStatement ps = createPreparedStatement(con, userId); 
         ResultSet rs = ps.executeQuery()) {

         // process the resultset here, all resources will be cleaned up

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

private PreparedStatement createPreparedStatement(Connection con, int userId) throws SQLException {
    String sql = "SELECT id, username FROM users WHERE id = ?";
    PreparedStatement ps = con.prepareStatement(sql);
    ps.setInt(1, userId);
    return ps;
}

Vertically centering Bootstrap modal window

e(document).on('show.bs.modal', function () {
        if($winWidth < $(window).width()){
            $('body.modal-open,.navbar-fixed-top,.navbar-fixed-bottom').css('marginRight',$(window).width()-$winWidth)
        }
    });
    e(document).on('hidden.bs.modal', function () {
        $('body,.navbar-fixed-top,.navbar-fixed-bottom').css('marginRight',0)
    });

How to use .htaccess in WAMP Server?

Click on Wamp icon and open Apache/httpd.conf and search "#LoadModule rewrite_module modules/mod_rewrite.so". Remove # as below and save it

LoadModule rewrite_module modules/mod_rewrite.so

and restart all service.

How to parse XML using jQuery?

you can use .parseXML

var xml='<Pages>
          <Page Name="test">
           <controls>
              <test>this is a test.</test>
           </controls>  
          </Page>
          <page Name = "User">
           <controls>
             <name>Sunil</name>
           </controls>
          </page>
        </Pages>';

jquery

    xmlDoc = $.parseXML( xml ),
    $xml = $( xmlDoc );
    $($xml).each(function(){
       alert($(this).find("Page[Name]>controls>name").text());
     });

here is the fiddle http://jsfiddle.net/R37mC/1/

Passing multiple argument through CommandArgument of Button in Asp.net

You can pass semicolon separated values as command argument and then split the string and use it.

<asp:TemplateField ShowHeader="false">
    <ItemTemplate>
       <asp:LinkButton ID="lnkCustomize" Text="Customize"  CommandName="Customize"  CommandArgument='<%#Eval("IdTemplate") + ";" +Eval("EntityId")%>'  runat="server"> 
       </asp:LinkButton>   
    </ItemTemplate>   
</asp:TemplateField>

at server side

protected void gridview_RowCommand(object sender, GridViewCommandEventArgs e)
{
      string[] arg = new string[2];
      arg = e.CommandArgument.ToString().Split(';');
      Session["IdTemplate"] = arg[0];
      Session["IdEntity"] = arg[1];
      Response.Redirect("Samplepage.aspx");
}

Hope it helps!!!!

What’s the best way to load a JSONObject from a json text file?

With java 8 you can try this:

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class JSONUtil {

    public static JSONObject parseJSONFile(String filename) throws JSONException, IOException {
        String content = new String(Files.readAllBytes(Paths.get(filename)));
        return new JSONObject(content);
    }

    public static void main(String[] args) throws IOException, JSONException {
        String filename = "path/to/file/abc.json";
        JSONObject jsonObject = parseJSONFile(filename);

        //do anything you want with jsonObject
    }
}

Multiline input form field using Bootstrap

The answer by Nick Mitchinson is for Bootstrap version 2.

If you are using Bootstrap version 3, then forms have changed a bit. For bootstrap 3, use the following instead:

<div class="form-horizontal">
    <div class="form-group">
        <div class="col-md-6">
            <textarea class="form-control" rows="3" placeholder="What's up?" required></textarea>
        </div>
    </div>
</div>

Where, col-md-6 will target medium sized devices. You can add col-xs-6 etc to target smaller devices.

Rename multiple files in a folder, add a prefix (Windows)

Based on @ofer.sheffer answer, this is the CMD variant for adding an affix (this is not the question, but this page is still the #1 google result if you search affix). It is a bit different because of the extension.

for %a in (*.*) do ren "%~a" "%~na-affix%~xa"

You can change the "-affix" part.

How do I add space between two variables after a print in Python

A simple way to add the tab would be to use the \t tag.

print '{0} \t {1}'.format(count, conv)

How do I retrieve my MySQL username and password?

Stop the MySQL process.

Start the MySQL process with the --skip-grant-tables option.

Start the MySQL console client with the -u root option.

List all the users;

SELECT * FROM mysql.user;

Reset password;

UPDATE mysql.user SET Password=PASSWORD('[password]') WHERE User='[username]';

But DO NOT FORGET to

Stop the MySQL process

Start the MySQL Process normally (i.e. without the --skip-grant-tables option)

when you are finished. Otherwise, your database's security could be compromised.

How to read and write to a text file in C++?

To read you should create an instance of ifsteam and not ofstream.

ifstream iusrfile;

You should open the file in read mode.

iusrfile.open("usrfile.txt", ifstream::in);

Also this statement is not correct.

cout<<iusrfile;

If you are trying to print the data you read from the file you should do:

cout<<usr;

You can read more about ifstream and its API here

How to copy a java.util.List into another java.util.List

originalArrayList.addAll(copyArrayofList);

Please keep on mind whenever using the addAll() method for copy, the contents of both the array lists (originalArrayList and copyArrayofList) references to the same objects will be added to the list so if you modify any one of them then copyArrayofList also will also reflect the same change.

If you don't want side effect then you need to copy each of element from the originalArrayList to the copyArrayofList, like using a for or while loop. for deep copy you can use below code snippet.

but one more thing you need to do, implement the Cloneable interface and override the clone() method for SomeBean class.

public static List<SomeBean> cloneList(List<SomeBean> originalArrayList) {
    List<SomeBean> copyArrayofList = new ArrayList<SomeBean>(list.size());
    for (SomeBean item : list) copyArrayofList.add(item.clone());
    return clone;
}

How to convert an enum type variable to a string?

Thanks James for your suggestion. It was very useful so I implemented the other way around to contribute in some way.

#include <iostream>
#include <boost/preprocessor.hpp>

using namespace std;

#define X_DEFINE_ENUM_WITH_STRING_CONVERSIONS_TOSTRING_CASE(r, data,  elem) \
    case data::elem : return BOOST_PP_STRINGIZE(elem);

#define X_DEFINE_ENUM_WITH_STRING_CONVERSIONS_TOENUM_IF(r, data, elem) \
    if (BOOST_PP_SEQ_TAIL(data) ==                                     \
            BOOST_PP_STRINGIZE(elem)) return                           \
            static_cast<int>(BOOST_PP_SEQ_HEAD(data)::elem); else

#define DEFINE_ENUM_WITH_STRING_CONVERSIONS(name, enumerators)         \
    enum class name {                                                  \
        BOOST_PP_SEQ_ENUM(enumerators)                                 \
    };                                                                 \
                                                                       \
    inline const char* ToString(name v)                                \
    {                                                                  \
        switch (v)                                                     \
        {                                                              \
            BOOST_PP_SEQ_FOR_EACH(                                     \
                X_DEFINE_ENUM_WITH_STRING_CONVERSIONS_TOSTRING_CASE,   \
                name,                                                  \
                enumerators                                            \
            )                                                          \
            default: return "[Unknown " BOOST_PP_STRINGIZE(name) "]";  \
        }                                                              \
    }                                                                  \
                                                                       \
    inline int ToEnum(std::string s)                                   \
    {                                                                  \
        BOOST_PP_SEQ_FOR_EACH(                                         \
                X_DEFINE_ENUM_WITH_STRING_CONVERSIONS_TOENUM_IF,       \
                (name)(s),                                             \
                enumerators                                            \
            )                                                          \
        return -1;                                                     \
    }


DEFINE_ENUM_WITH_STRING_CONVERSIONS(OS_type, (Linux)(Apple)(Windows));

int main(void)
{
    OS_type t = OS_type::Windows;

    cout << ToString(t) << " " << ToString(OS_type::Apple) << " " << ToString(OS_type::Linux) << endl;

    cout << ToEnum("Windows") << " " << ToEnum("Apple") << " " << ToEnum("Linux") << endl;

    return 0;
}

Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class'

I have to say, if you don't want to change anything in package.json file, try to update your Node.js version to latest. (currently 12.13.1 LTS)

How to pass values arguments to modal.show() function in Bootstrap

Use

$(document).ready(function() {
    $('#createFormId').on('show.bs.modal', function(event) {
        $("#cafeId").val($(event.relatedTarget).data('id'));
    });
});

Use PPK file in Mac Terminal to connect to remote connection over SSH

You can ssh directly from the Terminal on Mac, but you need to use a .PEM key rather than the putty .PPK key. You can use PuttyGen on Windows to convert from .PEM to .PPK, I'm not sure about the other way around though.

You can also convert the key using putty for Mac via port or brew:

sudo port install putty

or

brew install putty

This will also install puttygen. To get puttygen to output a .PEM file:

puttygen privatekey.ppk -O private-openssh -o privatekey.pem

Once you have the key, open a terminal window and:

ssh -i privatekey.pem [email protected]

The private key must have tight security settings otherwise SSH complains. Make sure only the user can read the key.

chmod go-rw privatekey.pem

center image in div with overflow hidden

You should make the container relative and give it a height as well and you're done.

http://jsfiddle.net/jaap/wjw83/4/

_x000D_
_x000D_
.main {_x000D_
  width: 300px;_x000D_
  margin: 0 auto;_x000D_
  overflow: hidden;_x000D_
  position: relative;_x000D_
  height: 200px;_x000D_
}_x000D_
_x000D_
img.absolute {_x000D_
  left: 50%;_x000D_
  margin-left: -200px;_x000D_
  position: absolute;_x000D_
}
_x000D_
<div class="main">_x000D_
  <img class="absolute" src="http://via.placeholder.com/400x200/A44/EED?text=Hello" alt="" />_x000D_
</div>_x000D_
<br />_x000D_
<img src="http://via.placeholder.com/400x200/A44/EED?text=Hello" alt="" />
_x000D_
_x000D_
_x000D_

If you want to you can also center the image vertically by adding a negative margin and top position: http://jsfiddle.net/jaap/wjw83/5/

Object array initialization without default constructor

You can always create an array of pointers , pointing to car objects and then create objects, in a for loop, as you want and save their address in the array , for example :

#include <iostream>
class Car
{
private:
  Car(){};
  int _no;
public:
  Car(int no)
  {
    _no=no;
  }
  void printNo()
  {
    std::cout<<_no<<std::endl;
  }
};
void printCarNumbers(Car *cars, int length)
{
    for(int i = 0; i<length;i++)
         std::cout<<cars[i].printNo();
}

int main()
{
  int userInput = 10;
  Car **mycars = new Car*[userInput];
  int i;
  for(i=0;i<userInput;i++)
      mycars[i] = new Car(i+1);

note new method !!!

  printCarNumbers_new(mycars,userInput);


  return 0;
}    

All you have to change in new method is handling cars as pointers than static objects in parameter and when calling method printNo() for example :

void printCarNumbers_new(Car **cars, int length)
{
    for(int i = 0; i<length;i++)
         std::cout<<cars[i]->printNo();
}

at the end of main is good to delete all dynamicly allocated memory like this

for(i=0;i<userInput;i++)
  delete mycars[i];      //deleting one obgject
delete[] mycars;         //deleting array of objects

Hope I helped, cheers!

How to set shadows in React Native for android?

for an android screen you can use this property elevation.

for example :

 HeaderView:{
    backgroundColor:'#F8F8F8',
    justifyContent:'center',
    alignItems:'center',
    height:60,
    paddingTop:15,

    //Its for IOS
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.2,

    // its for android 
    elevation: 5,
    position:'relative',

},

Array versus List<T>: When to use which?

Arrays should be used in preference to List when the immutability of the collection itself is part of the contract between the client & provider code (not necessarily immutability of the items within the collection) AND when IEnumerable is not suitable.

For example,

var str = "This is a string";
var strChars = str.ToCharArray();  // returns array

It is clear that modification of "strChars" will not mutate the original "str" object, irrespective implementation-level knowledge of "str"'s underlying type.

But suppose that

var str = "This is a string";
var strChars = str.ToCharList();  // returns List<char>
strChars.Insert(0, 'X');

In this case, it's not clear from that code-snippet alone if the insert method will or will not mutate the original "str" object. It requires implementation level knowledge of String to make that determination, which breaks Design by Contract approach. In the case of String, it's not a big deal, but it can be a big deal in almost every other case. Setting the List to read-only does help but results in run-time errors, not compile-time.

Unresolved external symbol in object files

See Linker Tools Error LNK2019 at MSDN, it has a detailed list of common problems that cause LNK2019.

Display Two <div>s Side-by-Side

Try this : (http://jsfiddle.net/TpqVx/)

.left-div {
    float: left;
    width: 100px;
    /*height: 20px;*/
    margin-right: 8px;
    background-color: linen;
}
.right-div {

    margin-left: 108px;
    background-color: lime;
}??

<div class="left-div">
    &nbsp;
</div>
<div class="right-div">
    My requirements are <b>[A]</b> Content in the two divs should line up at the top, <b>[B]</b> Long text in right-div should not wrap underneath left-div, and <b>[C]</b> I do not want to specify a width of right-div. I don't want to set the width of right-div because this markup needs to work within different widths.
</div>
<div style='clear:both;'>&nbsp;</div>

Hints :

  • Just use float:left in your left-most div only.
  • No real reason to use height, but anyway...
  • Good practice to use <div 'clear:both'>&nbsp;</div> after your last div.

How to make a flat list out of list of lists?

If you are willing to give up a tiny amount of speed for a cleaner look, then you could use numpy.concatenate().tolist() or numpy.concatenate().ravel().tolist():

import numpy

l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]] * 99

%timeit numpy.concatenate(l).ravel().tolist()
1000 loops, best of 3: 313 µs per loop

%timeit numpy.concatenate(l).tolist()
1000 loops, best of 3: 312 µs per loop

%timeit [item for sublist in l for item in sublist]
1000 loops, best of 3: 31.5 µs per loop

You can find out more here in the docs numpy.concatenate and numpy.ravel

Enter key press in C#

You must try this in keydown event

here is the code for that :

private void textBox1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Enter)
        {
            MessageBox.Show("Enter pressed");
        }
    }

Update :

Also you can do this with keypress event.

Try This :

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar == Convert.ToChar(Keys.Return))
        {
            MessageBox.Show("Key pressed");
        }
    }

Ruby on Rails generates model field:type - what are the options for field:type?

:primary_key, :string, :text, :integer, :float, :decimal, :datetime, :timestamp,
:time, :date, :binary, :boolean, :references

See the table definitions section.

Make an Installation program for C# applications and include .NET Framework installer into the setup

You need to create installer, which will check if user has required .NET Framework 4.0. You can use WiX to create installer. It's very powerfull and customizable. Also you can use ClickOnce to create installer - it's very simple to use. It will allow you with one click add requirement to install .NET Framework 4.0.

Determine if $.ajax error is a timeout

If your error event handler takes the three arguments (xmlhttprequest, textstatus, and message) when a timeout happens, the status arg will be 'timeout'.

Per the jQuery documentation:

Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror".

You can handle your error accordingly then.

I created this fiddle that demonstrates this.

$.ajax({
    url: "/ajax_json_echo/",
    type: "GET",
    dataType: "json",
    timeout: 1000,
    success: function(response) { alert(response); },
    error: function(xmlhttprequest, textstatus, message) {
        if(textstatus==="timeout") {
            alert("got timeout");
        } else {
            alert(textstatus);
        }
    }
});?

With jsFiddle, you can test ajax calls -- it will wait 2 seconds before responding. I put the timeout setting at 1 second, so it should error out and pass back a textstatus of 'timeout' to the error handler.

Hope this helps!

Git with SSH on Windows

If Git for windows is installed, run Git Bash shell:

  bash

You can run ssh from within Bash shell (Bash is aware of the path of ssh)

To know the exact path of ssh, run "where" command in Bash shell:

  $ where ssh

you get:

  c:\Program Files\Git\usr\bin\ssh.exe

Setting width of spreadsheet cell using PHPExcel

Tha is because getColumnDimensionByColumn receives the column index (an integer starting from 0), not a string.

The same goes for setCellValueByColumnAndRow

Open multiple Eclipse workspaces on the Mac

This seems to be the supported native method in OS X:

cd /Applications/eclipse/

open -n Eclipse.app

Be sure to specify the ".app" version (directory); in OS X Mountain Lion erroneously using the symbolic link such as open -n eclipse, might get one GateKeeper stopping access:

"eclipse" can't be opened because it is from an unidentified developer.

Your security preferences allow installation of only apps from the Mac App Store and identified developers.

Even removing the extended attribute com.apple.quarantine does not fix that. Instead, simply using the ".app" version will rely on your previous consent, or prompt you once:

"Eclipse" is an application downloaded from the Internet. Are you sure you want to open it?

Dots in URL causes 404 with ASP.NET mvc and IIS

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace WebApplication1.Controllers
{
    [RoutePrefix("File")]
    [Route("{action=index}")]
    public class FileController : Controller
    {
        // GET: File
        public ActionResult Index()
        {
            return View();
        }

        [AllowAnonymous]
        [Route("Image/{extension?}/{filename}")]
        public ActionResult Image(string extension, string filename)
        {
            var dir = Server.MapPath("/app_data/images");

            var path = Path.Combine(dir, filename+"."+ (extension!=null?    extension:"jpg"));
           // var extension = filename.Substring(0,filename.LastIndexOf("."));

            return base.File(path, "image/jpeg");
        }
    }
}

How To Create Table with Identity Column

[id] [int] IDENTITY(1,1) NOT NULL,

of course since you're creating the table in SQL Server Management Studio you could use the table designer to set the Identity Specification.

enter image description here

Insert 2 million rows into SQL Server quickly

You can try with SqlBulkCopy class.

Lets you efficiently bulk load a SQL Server table with data from another source.

There is a cool blog post about how you can use it.

Django CharField vs TextField

For eg.,. 2 fields are added in a model like below..

description = models.TextField(blank=True, null=True)
title = models.CharField(max_length=64, blank=True, null=True)

Below are the mysql queries executed when migrations are applied.


for TextField(description) the field is defined as a longtext

ALTER TABLE `sometable_sometable` ADD COLUMN `description` longtext NULL;

The maximum length of TextField of MySQL is 4GB according to string-type-overview.


for CharField(title) the max_length(required) is defined as varchar(64)

ALTER TABLE `sometable_sometable` ADD COLUMN `title` varchar(64) NULL;
ALTER TABLE `sometable_sometable` ALTER COLUMN `title` DROP DEFAULT;

Could not load file or assembly 'Microsoft.Web.Infrastructure,

I had a similar problem. NuGet showed the package successfully installed, but the reference was not added to my project.

Running <PM> Install-Package Microsoft.Web.InfraStructure also didn't help as the package manager kept saying it's already installed

I finally added it manually by editing the csproj file and adding these lines:

 <Reference Include="Microsoft.Web.Infrastructure">
  <HintPath>..\packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40\Microsoft.Web.Infrastructure.dll</HintPath>
  <Private>True</Private>
</Reference>

That solved the problem.

Java - Including variables within strings?

This is called string interpolation; it doesn't exist as such in Java.

One approach is to use String.format:

String string = String.format("A string %s", aVariable);

Another approach is to use a templating library such as Velocity or FreeMarker.

How do I disable text selection with CSS or JavaScript?

<div 
 style="-moz-user-select: none; -webkit-user-select: none; -ms-user-select:none; user-select:none;-o-user-select:none;" 
 unselectable="on"
 onselectstart="return false;" 
 onmousedown="return false;">
    Blabla
</div>

React Native version mismatch

Just go to your android/app/build.gradle and then add to the dependencies section:

dependencies{
compile ("com.facebook.react:react-native:0.50.3") { force = true } 
}

/// the react native version can be found in package.json

How to get the timezone offset in GMT(Like GMT+7:00) from android device?

You can do like this:

    TimeZone tz = TimeZone.getDefault();
    int offset = tz.getRawOffset();

    String timeZone = String.format("%s%02d%02d", offset >= 0 ? "+" : "-", offset / 3600000, (offset / 60000) % 60);

Why is setState in reactjs Async instead of Sync?

I know this question is old, but it has been causing a lot of confusion for many reactjs users for a long time, including me. Recently Dan Abramov (from the react team) just wrote up a great explanation as to why the nature of setState is async:

https://github.com/facebook/react/issues/11527#issuecomment-360199710

setState is meant to be asynchronous, and there are a few really good reasons for that in the linked explanation by Dan Abramov. This doesn't mean it will always be asynchronous - it mainly means that you just can't depend on it being synchronous. ReactJS takes into consideration many variables in the scenario that you're changing the state in, to decide when the state should actually be updated and your component rerendered.
A simple example to demonstrate this, is that if you call setState as a reaction to a user action, then the state will probably be updated immediately (although, again, you can't count on it), so the user won't feel any delay, but if you call setState in reaction to an ajax call response or some other event that isn't triggered by the user, then the state might be updated with a slight delay, since the user won't really feel this delay, and it will improve performance by waiting to batch multiple state updates together and rerender the DOM fewer times.

Where to put a textfile I want to use in eclipse?

Ask first yourself: Is your file an internal component of your application? (That usually implies that it's packed inside your JAR, or WAR if it is a web-app; typically, it's some configuration file or static resource, read-only).

If the answer is yes, you don't want to specify an absolute path for the file. But you neither want to access it with a relative path (as your example), because Java assumes that path is relative to the "current directory". Usually the preferred way for this scenario is to load it relatively from the classpath.

Java provides you the classLoader.getResource() method for doing this. And Eclipse (in the normal setup) assumes src/ is to be in the root of your classpath, so that, after compiling, it copies everything to your output directory ( bin/ ), the java files in compiled form ( .class ), the rest as is.

So, for example, if you place your file in src/Files/myfile.txt, it will be copied at compile time to bin/Files/myfile.txt ; and, at runtime, bin/ will be in (the root of) your classpath. So, by calling getResource("/Files/myfile.txt") (in some of its variants) you will be able to read it.

Edited: Further, if your file is conceptually tied to a java class (eg, some com.example.MyClass has a MyClass.cfg associated configuration file), you can use the getResource() method from the class and use a (resource) relative path: MyClass.getResource("MyClass.cfg"). The file then will be searched in the classpath, but with the class package pre-appended. So that, in this scenario, you'll typically place your MyClass.cfg and MyClass.java files in the same directory.

html select option separator

You could use the em dash "—". It has no visible spaces between each character.
(In some fonts!)

In HTML:

<option value="—————————————" disabled>—————————————</option>

Or in XHTML:

<option value="—————————————" disabled="disabled">—————————————</option>

Check whether a string is not null and not empty

Simple solution :

private boolean stringNotEmptyOrNull(String st) {
    return st != null && !st.isEmpty();
}

break/exit script

You can use the pskill function in the R "tools" package to interrupt the current process and return to the console. Concretely, I have the following function defined in a startup file that I source at the beginning of each script. You can also copy it directly at the start of your code, however. Then insert halt() at any point in your code to stop script execution on the fly. This function works well on GNU/Linux and judging from the R documentation, it should also work on Windows (but I didn't check).

# halt: interrupts the current R process; a short iddle time prevents R from
# outputting further results before the SIGINT (= Ctrl-C) signal is received 
halt <- function(hint = "Process stopped.\n") {
    writeLines(hint)
    require(tools, quietly = TRUE)
    processId <- Sys.getpid() 
    pskill(processId, SIGINT)
    iddleTime <- 1.00
    Sys.sleep(iddleTime)
}

Entry point for Java applications: main(), init(), or run()?

The main() method is the entry point for a Java application. run() is typically used for new threads or tasks.

Where have you been writing a run() method, what kind of application are you writing (e.g. Swing, AWT, console etc) and what's your development environment?

Is it possible to access an SQLite database from JavaScript?

Up to date answer

My fork of sql.js has now be merged into the original version, on kriken's repo.

The good documentation is also available on the original repo.

Original answer (outdated)

You should use the newer version of sql.js. It is a port of sqlite 3.8, has a good documentation and is actively maintained (by me). It supports prepared statements, and BLOB data type.

What is the difference between aggregation, composition and dependency?

One object may contain another as a part of its attribute.

  1. document contains sentences which contain words.
  2. Computer system has a hard disk, ram, processor etc.

So containment need not be physical. e.g., computer system has a warranty.

Is Java a Compiled or an Interpreted programming language ?

Java implementations typically use a two-step compilation process. Java source code is compiled down to bytecode by the Java compiler. The bytecode is executed by a Java Virtual Machine (JVM). Modern JVMs use a technique called Just-in-Time (JIT) compilation to compile the bytecode to native instructions understood by hardware CPU on the fly at runtime.

Some implementations of JVM may choose to interpret the bytecode instead of JIT compiling it to machine code, and running it directly. While this is still considered an "interpreter," It's quite different from interpreters that read and execute the high level source code (i.e. in this case, Java source code is not interpreted directly, the bytecode, output of Java compiler, is.)

It is technically possible to compile Java down to native code ahead-of-time and run the resulting binary. It is also possible to interpret the Java code directly.

To summarize, depending on the execution environment, bytecode can be:

  • compiled ahead of time and executed as native code (similar to most C++ compilers)
  • compiled just-in-time and executed
  • interpreted
  • directly executed by a supported processor (bytecode is the native instruction set of some CPUs)

Git fetch remote branch

git checkout -b branch_name
git pull remote_name branch_name

How to change color of Toolbar back button in Android?

I am using <style name="BaseTheme" parent="Theme.AppCompat.Light.NoActionBar> theme in my android application and in NoActionBar theme, colorControlNormal property is used to change the color of navigation icon default Back button arrow in my toolbar

styles.xml

<style name="BaseTheme" parent="Theme.AppCompat.Light.NoActionBar">
  <item name="colorControlNormal">@color/your_color</item> 
</style>

Undo working copy modifications of one file in Git?

I have Done through git bash:

(use "git checkout -- <file>..." to discard changes in working directory)

  1. Git status. [So we have seen one file wad modified.]
  2. git checkout -- index.html [i have changed in index.html file :
  3. git status [now those changes was removed]

enter image description here

JavaScript - populate drop down list with array

["1","2","3","4"].forEach( function(item) { 
   const optionObj = document.createElement("option");
   optionObj.textContent = item;
   document.getElementById("myselect").appendChild(optionObj);
});

Getting rid of all the rounded corners in Twitter Bootstrap

The code posted above by @BrunoS did not work for me,

* {
  .border-radius(0) !important;
}

what i used was

* {
  border-radius: 0 !important;
}

I hope this helps someone

What is the way of declaring an array in JavaScript?

If you are creating an array whose main feature is it's length, rather than the value of each index, defining an array as var a=Array(length); is appropriate.

eg-

String.prototype.repeat= function(n){
    n= n || 1;
    return Array(n+1).join(this);
}

Simple dynamic breadcrumb

Here is my solution based on Skeptic answer. It gets page title from WordPress DB, not from URL because there is a problem with latin characters (slug doesn't has a latin characters). You can also choose to display "home" item or not.

/**
 * Show Breadcrumbs
 * 
 * @param string|bool $home
 * @param string $class
 * @return string
 * 
 * Using: echo breadcrumbs();
 */
function breadcrumbs($home = 'Home', $class = 'items') {
    $breadcrumb  = '<ul class="'. $class .'">';
    $breadcrumbs = array_filter(explode('/', parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)));

    if ($home) {
        $breadcrumb .= '<li><a href="' . get_site_url() . '">' . $home . '</a></li>';
    }

    $path = '';
    foreach ($breadcrumbs as $crumb) {
        $path .=  $crumb . '/';
        $page = get_page_by_path($path);

        if ($home && ($page->ID == get_option('page_on_front'))) {
            continue;
        }

        $breadcrumb .= '<li><a href="'. get_permalink($page) .'">' . $page->post_title . '</a></li>';
    }

    $breadcrumb .= '</ul>';
    return $breadcrumb;
}

Using:

<div class="breadcrumb">
    <div class="container">
        <h3 class="breadcrumb__title">Jazda na maxa!</h3>
        <?php echo breadcrumbs('Start', 'breadcrumb__items'); ?>
    </div>
</div>

MVC If statement in View

You only need to prefix an if statement with @ if you're not already inside a razor code block.

Edit: You have a couple of things wrong with your code right now.

You're declaring nmb, but never actually doing anything with the value. So you need figure out what that's supposed to actually be doing. In order to fix your code, you need to make a couple of tiny changes:

@if (ViewBag.Articles != null)
{
    int nmb = 0;
    foreach (var item in ViewBag.Articles)
    {
        if (nmb % 3 == 0)
        {
            @:<div class="row"> 
        }

        <a href="@Url.Action("Article", "Programming", new { id = item.id })">
            <div class="tasks">
                <div class="col-md-4">
                    <div class="task important">
                        <h4>@item.Title</h4>
                        <div class="tmeta">
                            <i class="icon-calendar"></i>
                                @item.DateAdded - Pregleda:@item.Click
                            <i class="icon-pushpin"></i> Authorrr
                        </div>
                    </div>
                </div>
            </div>
        </a>
        if (nmb % 3 == 0)
        {
            @:</div>
        }
    }
}

The important part here is the @:. It's a short-hand of <text></text>, which is used to force the razor engine to render text.

One other thing, the HTML standard specifies that a tags can only contain inline elements, and right now, you're putting a div, which is a block-level element, inside an a.

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

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

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

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

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

Getting current unixtimestamp using Moment.js

To find the Unix Timestamp in seconds:

moment().unix()

The documentation is your friend. :)

Java 11 package javax.xml.bind does not exist

According to the release-notes, Java 11 removed the Java EE modules:

java.xml.bind (JAXB) - REMOVED
  • Java 8 - OK
  • Java 9 - DEPRECATED
  • Java 10 - DEPRECATED
  • Java 11 - REMOVED

See JEP 320 for more info.

You can fix the issue by using alternate versions of the Java EE technologies. Simply add Maven dependencies that contain the classes you need:

<dependency>
  <groupId>javax.xml.bind</groupId>
  <artifactId>jaxb-api</artifactId>
  <version>2.3.0</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-core</artifactId>
  <version>2.3.0</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-impl</artifactId>
  <version>2.3.0</version>
</dependency>

Jakarta EE 8 update (Mar 2020)

Instead of using old JAXB modules you can fix the issue by using Jakarta XML Binding from Jakarta EE 8:

<dependency>
  <groupId>jakarta.xml.bind</groupId>
  <artifactId>jakarta.xml.bind-api</artifactId>
  <version>2.3.3</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-impl</artifactId>
  <version>2.3.3</version>
  <scope>runtime</scope>
</dependency>

Jakarta EE 9 update (Nov 2020)

Use latest release of Eclipse Implementation of JAXB 3.0.0:

<dependency>
  <groupId>jakarta.xml.bind</groupId>
  <artifactId>jakarta.xml.bind-api</artifactId>
  <version>3.0.0</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-impl</artifactId>
  <version>3.0.0</version>
  <scope>runtime</scope>
</dependency>

Note: Jakarta EE 9 adopts new API package namespace jakarta.xml.bind.*, so update import statements:

javax.xml.bind -> jakarta.xml.bind

How do you clear a stringstream variable?

I am always scoping it:

{
    std::stringstream ss;
    ss << "what";
}

{
    std::stringstream ss;
    ss << "the";
}

{
    std::stringstream ss;
    ss << "heck";
}

How do I get the current username in Windows PowerShell?

Just building on the work of others here:

[String] ${stUserDomain},[String]  ${stUserAccount} = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name.split("\")

How to scale images to screen size in Pygame

You can scale the image with pygame.transform.scale:

import pygame
picture = pygame.image.load(filename)
picture = pygame.transform.scale(picture, (1280, 720))

You can then get the bounding rectangle of picture with

rect = picture.get_rect()

and move the picture with

rect = rect.move((x, y))
screen.blit(picture, rect)

where screen was set with something like

screen = pygame.display.set_mode((1600, 900))

To allow your widgets to adjust to various screen sizes, you could make the display resizable:

import os
import pygame
from pygame.locals import *

pygame.init()
screen = pygame.display.set_mode((500, 500), HWSURFACE | DOUBLEBUF | RESIZABLE)
pic = pygame.image.load("image.png")
screen.blit(pygame.transform.scale(pic, (500, 500)), (0, 0))
pygame.display.flip()
while True:
    pygame.event.pump()
    event = pygame.event.wait()
    if event.type == QUIT:
        pygame.display.quit()
    elif event.type == VIDEORESIZE:
        screen = pygame.display.set_mode(
            event.dict['size'], HWSURFACE | DOUBLEBUF | RESIZABLE)
        screen.blit(pygame.transform.scale(pic, event.dict['size']), (0, 0))
        pygame.display.flip()

Draw on HTML5 Canvas using a mouse

Here is my very simple working canvas draw and erase.

https://jsfiddle.net/richardcwc/d2gxjdva/

_x000D_
_x000D_
//Canvas_x000D_
var canvas = document.getElementById('canvas');_x000D_
var ctx = canvas.getContext('2d');_x000D_
//Variables_x000D_
var canvasx = $(canvas).offset().left;_x000D_
var canvasy = $(canvas).offset().top;_x000D_
var last_mousex = last_mousey = 0;_x000D_
var mousex = mousey = 0;_x000D_
var mousedown = false;_x000D_
var tooltype = 'draw';_x000D_
_x000D_
//Mousedown_x000D_
$(canvas).on('mousedown', function(e) {_x000D_
    last_mousex = mousex = parseInt(e.clientX-canvasx);_x000D_
 last_mousey = mousey = parseInt(e.clientY-canvasy);_x000D_
    mousedown = true;_x000D_
});_x000D_
_x000D_
//Mouseup_x000D_
$(canvas).on('mouseup', function(e) {_x000D_
    mousedown = false;_x000D_
});_x000D_
_x000D_
//Mousemove_x000D_
$(canvas).on('mousemove', function(e) {_x000D_
    mousex = parseInt(e.clientX-canvasx);_x000D_
    mousey = parseInt(e.clientY-canvasy);_x000D_
    if(mousedown) {_x000D_
        ctx.beginPath();_x000D_
        if(tooltype=='draw') {_x000D_
            ctx.globalCompositeOperation = 'source-over';_x000D_
            ctx.strokeStyle = 'black';_x000D_
            ctx.lineWidth = 3;_x000D_
        } else {_x000D_
            ctx.globalCompositeOperation = 'destination-out';_x000D_
            ctx.lineWidth = 10;_x000D_
        }_x000D_
        ctx.moveTo(last_mousex,last_mousey);_x000D_
        ctx.lineTo(mousex,mousey);_x000D_
        ctx.lineJoin = ctx.lineCap = 'round';_x000D_
        ctx.stroke();_x000D_
    }_x000D_
    last_mousex = mousex;_x000D_
    last_mousey = mousey;_x000D_
    //Output_x000D_
    $('#output').html('current: '+mousex+', '+mousey+'<br/>last: '+last_mousex+', '+last_mousey+'<br/>mousedown: '+mousedown);_x000D_
});_x000D_
_x000D_
//Use draw|erase_x000D_
use_tool = function(tool) {_x000D_
    tooltype = tool; //update_x000D_
}
_x000D_
canvas {_x000D_
    cursor: crosshair;_x000D_
    border: 1px solid #000000;_x000D_
}
_x000D_
<canvas id="canvas" width="800" height="500"></canvas>_x000D_
<input type="button" value="draw" onclick="use_tool('draw');" />_x000D_
<input type="button" value="erase" onclick="use_tool('erase');" />_x000D_
<div id="output"></div>
_x000D_
_x000D_
_x000D_

What is the common header format of Python files?

Also see PEP 263 if you are using a non-ascii characterset

Abstract

This PEP proposes to introduce a syntax to declare the encoding of a Python source file. The encoding information is then used by the Python parser to interpret the file using the given encoding. Most notably this enhances the interpretation of Unicode literals in the source code and makes it possible to write Unicode literals using e.g. UTF-8 directly in an Unicode aware editor.

Problem

In Python 2.1, Unicode literals can only be written using the Latin-1 based encoding "unicode-escape". This makes the programming environment rather unfriendly to Python users who live and work in non-Latin-1 locales such as many of the Asian countries. Programmers can write their 8-bit strings using the favorite encoding, but are bound to the "unicode-escape" encoding for Unicode literals.

Proposed Solution

I propose to make the Python source code encoding both visible and changeable on a per-source file basis by using a special comment at the top of the file to declare the encoding.

To make Python aware of this encoding declaration a number of concept changes are necessary with respect to the handling of Python source code data.

Defining the Encoding

Python will default to ASCII as standard encoding if no other encoding hints are given.

To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as:

      # coding=<encoding name>

or (using formats recognized by popular editors)

      #!/usr/bin/python
      # -*- coding: <encoding name> -*-

or

      #!/usr/bin/python
      # vim: set fileencoding=<encoding name> :

...

jquery draggable: how to limit the draggable area?

Use the "containment" option:

jQuery UI API - Draggable Widget - containment

The documentation says it only accepts the values: 'parent', 'document', 'window', [x1, y1, x2, y2] but I seem to remember it will accept a selector such as '#container' too.

Execute and get the output of a shell command in node.js

If you're using node later than 7.6 and you don't like the callback style, you can also use node-util's promisify function with async / await to get shell commands which read cleanly. Here's an example of the accepted answer, using this technique:

const { promisify } = require('util');
const exec = promisify(require('child_process').exec)

module.exports.getGitUser = async function getGitUser () {
  const name = await exec('git config --global user.name')
  const email = await exec('git config --global user.email')
  return { name, email }
};

This also has the added benefit of returning a rejected promise on failed commands, which can be handled with try / catch inside the async code.

history.replaceState() example?

history.pushState pushes the current page state onto the history stack, and changes the URL in the address bar. So, when you go back, that state (the object you passed) are returned to you.

Currently, that is all it does. Any other page action, such as displaying the new page or changing the page title, must be done by you.

The W3C spec you link is just a draft, and browser may implement it differently. Firefox, for example, ignores the title parameter completely.

Here is a simple example of pushState that I use on my website.

(function($){
    // Use AJAX to load the page, and change the title
    function loadPage(sel, p){
        $(sel).load(p + ' #content', function(){
            document.title = $('#pageData').data('title');
        });
    }

    // When a link is clicked, use AJAX to load that page
    // but use pushState to change the URL bar
    $(document).on('click', 'a', function(e){
        e.preventDefault();
        history.pushState({page: this.href}, '', this.href);
        loadPage('#frontPage', this.href);
    });

    // This event is triggered when you visit a page in the history
    // like when yu push the "back" button
    $(window).on('popstate', function(e){
        loadPage('#frontPage', location.pathname);
        console.log(e.originalEvent.state);
    });
}(jQuery));

Installing J2EE into existing eclipse IDE

Go to Help -> Install new softwares-> add -> paste this link in location box http://download.eclipse.org/webtools/repository/luna/ install all new versions..

How can I copy the content of a branch to a new local branch?

git branch copyOfMyBranch MyBranch

This avoids the potentially time-consuming and unnecessary act of checking out a branch. Recall that a checkout modifies the "working tree", which could take a long time if it is large or contains large files (images or videos, for example).

Verify ImageMagick installation

Remember that after installing Imagick (or indeed any PHP module) you need to restart your web server and/or php-fpm if you're using it, for the module to appear in phpinfo().

Finding CN of users in Active Directory

CN refers to class name, so put in your LDAP query CN=Users. Should work.

How to use pagination on HTML tables?

With Reference to Anusree answer above and with respect,I am tweeking the code little bit to make sure it works in most of the cases.

  1. Created a reusable function paginate('#myTableId') which can be called any number times for any table.
  2. Adding code inside ajaxComplete function to make sure paging is called once table using jquery is completely loaded. We use paging mostly for ajax based tables.
  3. Remove Pagination div and rebind on every pagination call
  4. Configuring Number of rows per page

Code:

$(document).ready(function () {
    $(document).ajaxComplete(function () {
        paginate('#myTableId',10);
        function paginate(tableName,RecordsPerPage) {
            $('#nav').remove();
            $(tableName).after('<div id="nav"></div>');
            var rowsShown = RecordsPerPage;
            var rowsTotal = $(tableName + ' tbody tr').length;
            var numPages = rowsTotal / rowsShown;
            for (i = 0; i < numPages; i++) {
                var pageNum = i + 1;
                $('#nav').append('<a href="#" rel="' + i + '">' + pageNum + '</a> ');
            }
            $(tableName + ' tbody tr').hide();
            $(tableName + ' tbody tr').slice(0, rowsShown).show();
            $('#nav a:first').addClass('active');
            $('#nav a').bind('click', function () {

                $('#nav a').removeClass('active');
                $(this).addClass('active');
                var currPage = $(this).attr('rel');
                var startItem = currPage * rowsShown;
                var endItem = startItem + rowsShown;
                $(tableName + ' tbody tr').css('opacity', '0.0').hide().slice(startItem, endItem).
                    css('display', 'table-row').animate({ opacity: 1 }, 300);
            });
        }
    });
});

How to detect the swipe left or Right in Android?

I like the code from @user2999943. But just some minor changes for my own purposes.

@Override
public boolean onTouchEvent(MotionEvent event)
{     
    switch(event.getAction())
    {
      case MotionEvent.ACTION_DOWN:
          x1 = event.getX();                         
      break;         
      case MotionEvent.ACTION_UP:
          x2 = event.getX();
          float deltaX = x2 - x1;

          if (Math.abs(deltaX) > MIN_DISTANCE)
          {
              // Left to Right swipe action
              if (x2 > x1)
              {
                  Toast.makeText(this, "Left to Right swipe [Next]", Toast.LENGTH_SHORT).show ();                     
              }

              // Right to left swipe action               
              else 
              {
                  Toast.makeText(this, "Right to Left swipe [Previous]", Toast.LENGTH_SHORT).show ();                    
              }

          }
          else
          {
              // consider as something else - a screen tap for example
          }                          
      break;   
    }           
    return super.onTouchEvent(event);       
}

Get the second highest value in a MySQL table

for 2nd heightest salary

 select max(salary) from salary where salary not in (select top 1 salary from salary order by salary desc)

for 3rd heightest salary

 select max(salary) from salary where salary not in (select top 2 salary from salary order by salary desc)

and so on......

How do I include a pipe | in my linux find -exec command?

If you are looking for a simple alternative, this can be done using a loop:

for i in $(find -name 'file_*' -follow -type f); do
  zcat $i | agrep -dEOE 'grep'
done

or, more general and easy to understand form:

for i in $(YOUR_FIND_COMMAND); do
  YOUR_EXEC_COMMAND_AND_PIPES
done

and replace any {} by $i in YOUR_EXEC_COMMAND_AND_PIPES

How to group dataframe rows into list in pandas groupby

A handy way to achieve this would be:

df.groupby('a').agg({'b':lambda x: list(x)})

Look into writing Custom Aggregations: https://www.kaggle.com/akshaysehgal/how-to-group-by-aggregate-using-py

How to use Global Variables in C#?

In C# you cannot define true global variables (in the sense that they don't belong to any class).

This being said, the simplest approach that I know to mimic this feature consists in using a static class, as follows:

public static class Globals
{
    public const Int32 BUFFER_SIZE = 512; // Unmodifiable
    public static String FILE_NAME = "Output.txt"; // Modifiable
    public static readonly String CODE_PREFIX = "US-"; // Unmodifiable
}

You can then retrieve the defined values anywhere in your code (provided it's part of the same namespace):

String code = Globals.CODE_PREFIX + value.ToString();

In order to deal with different namespaces, you can either:

  • declare the Globals class without including it into a specific namespace (so that it will be placed in the global application namespace);
  • insert the proper using directive for retrieving the variables from another namespace.

Adding a default value in dropdownlist after binding with database

The solution provided by Justin should work. To be sure making use of SelectedIndex property will also help.

ddlColor.DataSource = from p in db.ProductTypes
                      where p.ProductID == pID
                      orderby p.Color
                      select new { p.Color };

ddlColor.DataTextField = "Color";
ddlColor.DataBind();

ddlColor.Items.Insert(0, new ListItem("Select Color", ""); 
ddlColor.SelectedIndex = 0;

Adding a parameter to the URL with JavaScript

var MyApp = new Class();

MyApp.extend({
    utility: {
        queryStringHelper: function (url) {
            var originalUrl = url;
            var newUrl = url;
            var finalUrl;
            var insertParam = function (key, value) {
                key = escape(key);
                value = escape(value);

                //The previous post had the substr strat from 1 in stead of 0!!!
                var kvp = newUrl.substr(0).split('&');

                var i = kvp.length;
                var x;
                while (i--) {
                    x = kvp[i].split('=');

                    if (x[0] == key) {
                        x[1] = value;
                        kvp[i] = x.join('=');
                        break;
                    }
                }

                if (i < 0) {
                    kvp[kvp.length] = [key, value].join('=');
                }

                finalUrl = kvp.join('&');

                return finalUrl;
            };

            this.insertParameterToQueryString = insertParam;

            this.insertParams = function (keyValues) {
                for (var keyValue in keyValues[0]) {
                    var key = keyValue;
                    var value = keyValues[0][keyValue];
                    newUrl = insertParam(key, value);
                }
                return newUrl;
            };

            return this;
        }
    }
});

How do I do logging in C# without using 3rd party libraries?

If you want to stay close to .NET check out Enterprise Library Logging Application Block. Look here. Or for a quickstart tutorial check this. I have used the Validation application Block from the Enterprise Library and it really suits my needs and is very easy to "inherit" (install it and refrence it!) in your project.

How to validate IP address in Python?

I hope it's simple and pythonic enough:

def is_valid_ip(ip):
    m = re.match(r"^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$", ip)
    return bool(m) and all(map(lambda n: 0 <= int(n) <= 255, m.groups()))

CSS values using HTML5 data attribute

There is, indeed, prevision for such feature, look http://www.w3.org/TR/css3-values/#attr-notation

This fiddle should work like what you need, but will not for now.

Unfortunately, it's still a draft, and isn't fully implemented on major browsers.

It does work for content on pseudo-elements, though.

Getting the difference between two sets

Try this

test2.removeAll(test1);

Set#removeAll

Removes from this set all of its elements that are contained in the specified collection (optional operation). If the specified collection is also a set, this operation effectively modifies this set so that its value is the asymmetric set difference of the two sets.

Spark Kill Running Application

This might not be an ethical and preferred solution but it helps in environments where you can't access the console to kill the job using yarn application command.

Steps are

Go to application master page of spark job. Click on the jobs section. Click on the active job's active stage. You will see "kill" button right next to the active stage.

This works if the succeeding stages are dependent on the currently running stage. Though it marks job as " Killed By User"

python-dev installation error: ImportError: No module named apt_pkg

Please try to fix this by setting the locale variables:

export LC_ALL="en_US.UTF-8"

export LC_CTYPE="en_US.UTF-8"

How can I find the current OS in Python?

I usually use sys.platform (docs) to get the platform. sys.platform will distinguish between linux, other unixes, and OS X, while os.name is "posix" for all of them.

For much more detailed information, use the platform module. This has cross-platform functions that will give you information on the machine architecture, OS and OS version, version of Python, etc. Also it has os-specific functions to get things like the particular linux distribution.

How can INSERT INTO a table 300 times within a loop in SQL?

I would prevent loops in general if i can, set approaches are much more efficient:

INSERT INTO tblFoo
  SELECT TOP (300) n = ROW_NUMBER()OVER (ORDER BY [object_id]) 
  FROM sys.all_objects ORDER BY n;

Demo

Generate a set or sequence without loops

Convert string with commas to array

_x000D_
_x000D_
var i = "[{a:1,b:2}]",_x000D_
    j = i.replace(/([a-zA-Z0-9]+?):/g, '"$1":').replace(/'/g,'"'),_x000D_
    k = JSON.parse(j);_x000D_
_x000D_
console.log(k)
_x000D_
_x000D_
_x000D_

// => declaring regular expression

[a-zA-Z0-9] => match all a-z, A-Z, 0-9

(): => group all matched elements

$1 => replacement string refers to the first match group in the regex.

g => global flag

Pointers in C: when to use the ampersand and the asterisk?

I was looking through all the wordy explanations so instead turned to a video from University of New South Wales for rescue.Here is the simple explanation: if we have a cell that has address x and value 7, the indirect way to ask for address of value 7 is &7 and the indirect way to ask for value at address x is *x.So (cell: x , value: 7) == (cell: &7 , value: *x) .Another way to look into it: John sits at 7th seat.The *7th seat will point to John and &John will give address/location of the 7th seat. This simple explanation helped me and hope it will help others as well. Here is the link for the excellent video: click here.

Here is another example:

#include <stdio.h>

int main()
{ 
    int x;            /* A normal integer*/
    int *p;           /* A pointer to an integer ("*p" is an integer, so p
                       must be a pointer to an integer) */

    p = &x;           /* Read it, "assign the address of x to p" */
    scanf( "%d", &x );          /* Put a value in x, we could also use p here */
    printf( "%d\n", *p ); /* Note the use of the * to get the value */
    getchar();
}

Add-on: Always initialize pointer before using them.If not, the pointer will point to anything, which might result in crashing the program because the operating system will prevent you from accessing the memory it knows you don't own.But simply putting p = &x;, we are assigning the pointer a specific location.

Add text to Existing PDF using Python

Leveraging David Dehghan's answer above, the following works in Python 2.7.13:

from PyPDF2 import PdfFileWriter, PdfFileReader, PdfFileMerger

import StringIO

from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter

packet = StringIO.StringIO()
# create a new PDF with Reportlab
can = canvas.Canvas(packet, pagesize=letter)
can.drawString(290, 720, "Hello world")
can.save()

#move to the beginning of the StringIO buffer
packet.seek(0)
new_pdf = PdfFileReader(packet)
# read your existing PDF
existing_pdf = PdfFileReader("original.pdf")
output = PdfFileWriter()
# add the "watermark" (which is the new pdf) on the existing page
page = existing_pdf.getPage(0)
page.mergePage(new_pdf.getPage(0))
output.addPage(page)
# finally, write "output" to a real file
outputStream = open("destination.pdf", "wb")
output.write(outputStream)
outputStream.close()

What is the difference between signed and unsigned variables?

unsigned is used when ur value must be positive, no negative value here, if signed for int range -32768 to +32767 if unsigned for int range 0 to 65535

Current timestamp as filename in Java

Use SimpleDateFormat as aix suggested to format the current time into a string. You should use a format that does not include / characters etc. I would suggest something like yyyyMMddhhmm

How to use ADB Shell when Multiple Devices are connected? Fails with "error: more than one device and emulator"

Create a Bash (tools.sh) to select a serial from devices (or emulator):

clear;
echo "====================================================================================================";
echo " ADB DEVICES";
echo "====================================================================================================";
echo "";

adb_devices=( $(adb devices | grep -v devices | grep device | cut -f 1)#$(adb devices | grep -v devices | grep device | cut -f 2) );

if [ $((${#adb_devices[@]})) -eq "1" ] && [ "${adb_devices[0]}" == "#" ]
then
    echo "No device found";
    echo ""; 
    echo "====================================================================================================";
    device=""
    // Call Main Menu function fxMenu;
else
    read -p "$(
        f=0
        for dev in "${adb_devices[@]}"; do
            nm="$(echo ${dev} | cut -f1 -d#)";
            tp="$(echo ${dev} | cut -f2 -d#)";
            echo " $((++f)). ${nm} [${tp}]";
        done

        echo "";
        echo " 0. Quit"
        echo "";

        echo "====================================================================================================";
        echo "";
        echo ' Please select a device: '
    )" selection

    error="You think it's over just because I am dead. It's not over. The games have just begun.";
    // Call Validation Numbers fxValidationNumberMenu ${#adb_devices[@]} ${selection} "${error}" 
    case "${selection}" in
        0)
            // Call Main Menu function fxMenu;
        *)  
            device="$(echo ${adb_devices[$((selection-1))]} | cut -f1 -d#)";
            // Call Main Menu function fxMenu;
    esac
fi

Then in another option can use adb -s (global option -s use device with given serial number that overrides $ANDROID_SERIAL):

adb -s ${device} <command>

I tested this code on MacOS terminal, but I think it can be used on windows across Git Bash Terminal.

Also remember configure environmental variables and Android SDK paths on .bash_profile file:

export ANDROID_HOME="/usr/local/opt/android-sdk/"
export PATH="$ANDROID_HOME/platform-tools:$PATH"
export PATH="$ANDROID_HOME/tools:$PATH"

Mockito matcher and array of primitives

I agree with Mutanos and Alecio. Further, one can check as many identical method calls as possible (verifying the subsequent calls in the production code, the order of the verify's does not matter). Here is the code:

import static org.mockito.AdditionalMatchers.*;

    verify(mockObject).myMethod(aryEq(new byte[] { 0 }));
    verify(mockObject).myMethod(aryEq(new byte[] { 1, 2 }));

Android ListView Text Color

if you didnot set your activity style it shows you black background .if you want to make changes such as white background, black text of listview then it is difficult process.

ADD android:theme="@style/AppTheme" in Android Manifest.

The meaning of NoInitialContextException error

Is a JNDI problem. You will see that exception if the InitialContext class has neither default properties for the JNDI service provider nor explicitly configured server properties.

Set the Context.INITIAL_CONTEXT_FACTORY environment property to the class name of the initial context implementation that you are using. This class must be available to your program in the classpath.

Check:

Favicon not showing up in Google Chrome

Cache

Clear your cache. http://support.google.com/chrome/bin/answer.py?hl=en&answer=95582 And test another browser.

Some where able to get an updated favicon by adding an URL parameter: ?v=1 after the link href which changes the resource link and therefore loads the favicon without cache (thanks @Stanislav).

<link rel="icon" type="image/x-icon" href="favicon.ico?v=2"  />

Favicon Usage

How did you import the favicon? How you should add it.

Normal favicon:

<link rel="icon" href="favicon.ico" type="image/x-icon" />
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />

PNG/GIF favicon:

<link rel="icon" type="image/gif" href="favicon.gif" />
<link rel="icon" type="image/png" href="favicon.png" />

in the <head> Tag.

Chrome local problem

Another thing could be the problem that chrome can't display favicons, if it's local (not uploaded to a webserver). Only if the file/icon would be in the downloads directory chrome is allowed to load this data - more information about this can be found here: local (file://) website favicon works in Firefox, not in Chrome or Safari- why?

Renaming

Try to rename it from favicon.{whatever} to {yourfaviconname}.{whatever} but I would suggest you to still have the normal favicon. This has solved my issue on IE.

Base64 approach

Found another solution for this which works great! I simply added my favicon as Base64 Encoded Image directly inside the tag like this:

<link href="data:image/x-icon;base64,AAABAAIAEBAAAAEAIABoBAAAJgAAACAgAAABACAAqBAAAI4EAAAoAAAAEAAAACAAAAABACAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAA////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AIaDgv+Gg4L/hoOC/4aDgv+Gg4L/hoOC/4aDgv+Gg4L/hoOC/4aDgv////8A////AP///wD///8A////AP///wCGg4L/////AP///wD///8A////AP///wD///8A////AP///wCGg4L/////AP///wD///8A////AP///wD///8AhoOC/////wCGg4L/hoOC/4aDgv+Gg4L/hoOC/4aDgv////8AhoOC/////wD///8A////AP///wD///8A////AIaDgv////8A////AP///wD///8A////AP///wD///8A////AIaDgv////8A////AP///wD///8A////AP///wCGg4L/////AHCMqP9wjKj/cIyo/3CMqP9wjKj/cIyo/////wCGg4L/////AP///wD///8A////AP///wD///8AhoOC/////wBTlsIAU5bCAFOWwgBTlsIAU5bCM1OWwnP///8AhoOC/////wD///8A////AP///wD///8A////AP///wD///8AU5bCBlOWwndTlsLHU5bC+FOWwv1TlsLR////AP///wD///8A////AP///wD///8A////AP///wD///8A////AFOWwvtTlsLuU5bCu1OWwlc2k9cANpPXqjaT19H///8A////AP///wD///8A////AP///wD///8A////AP///wBTlsIGNpPXADaT1wA2k9dINpPX8TaT1+40ktpDH4r2tB+K9hL///8A////AP///wD///8A////AP///wD///8A////ADaT1wY2k9e7NpPX/TaT16AfivYGH4r23R+K9u4tg/WQLoL1mP///wD///8A////AP///wD///8A////AP///wA2k9fuNpPX5zaT1zMfivYGH4r23R+K9uwjiPYXLoL1+S6C9W7///8A////AP///wD///8A////AP///wD///8ANpPXLjaT1wAfivYGH4r22x+K9usfivYSLoL1oC6C9esugvUA////AP///wD///8A////AP///wD///8A////AP///wD///8AH4r2zx+K9usfivYSLoL1DC6C9fwugvVXLoL1AP///wD///8A////AP///wD///8A////AP///wD///8A////AB+K9kgfivYMH4r2AC6C9bEugvXhLoL1AC6C9QD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAugvXyLoL1SC6C9QAugvUA////AP//AADgBwAA7/cAAOgXAADv9wAA6BcAAO+XAAD4HwAA+E8AAPsDAAD8AQAA/AEAAP0DAAD/AwAA/ycAAP/nAAAoAAAAIAAAAEAAAAABACAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAA////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AhISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/////wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wCEhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AISEhP+EhIT/////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AhISE/4SEhP////8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AhISE/4SEhP////8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wCEhIT/hISE/////wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wCEhIT/hISE/////wD///8AhISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP8AAAAA////AISEhP+EhIT/////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AISEhP+EhIT/////AP///wCEhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/wAAAAD///8AhISE/4SEhP////8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AhISE/4SEhP/4+vsA4ujuAOLo7gDi6O4A4ujuAN3k6wDZ4OgA2eDoANng6ADZ4OgA2eDoANng6ADW3uYAJS84APj6+wCEhIT/hISE/////wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wCEhIT/hISE/9Xd5QBwjKgAcIyoRnCMqGRwjKhxcIyogHCMqI9wjKidcIyoq3CMqLlwjKjHcIyo1HCMqLhogpwA/f7+AISEhP+EhIT/////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AISEhP+EhIT/xtHcAHCMqABwjKjAcIyo/3CMqP9wjKj/cIyo/3CMqP9wjKj/cIyo/3CMqP9wjKj/cIyo4EdZawD///8AhISE/4SEhP////8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AhISE/4SEhP+2xNMAcIyoAHCMqJhwjKjPcIyowHCMqLFwjKijcoymlXSMpIh0jKR6co2mbG+OqGFqj61zXZO4AeXv9gCEhIT/hISE/////wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wCEhIT/hISE/6i5ygDF0dwAIiozACQyPQAoP1AALlBmADhlggBblLkGVJbBPFOWwnxTlsK5U5bC9FOWwv9TlsIp3erzAISEhP+EhIT/////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAAAAAAALztHAAAAAAAuU2sAU5bCClOWwkNTlsKAU5bCwFOWwvhTlsL/U5bC/1OWwv9TlsL/U5bC/ViVvVcXOFAAAAAAAAAAAAD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AAAAAAAAAAAALDhEALVFoAFOWwjpTlsL6U5bC/1OWwv9TlsL/U5bC/1OWwvxTlsLIV5W+i2CRs0xHi71TKYzUnyuM0gIJHi4AAAAAAAAAAAAAAAAA////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAAAAAAAAAAACtNZABTlsIAU5bCD1OWwv1TlsL6U5bCxFOWwoRVlsBHZJKwDCNObAA8icJAKYzUwimM1P8pjNT/KYzUWCaCxgALLUsAAAAAAAAAAAD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAApS2EAU5bCAFOWwgBTlsIAU5bCNVOWwgg+cJEAIT1QABU/XQA1isg4KYzUuymM1P8pjNT/KYzU/ymM1LAti9E0JYvmDhdouAAAAAAAAAAAAP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AFyk1AE+PuQBTlsIAU5bCAER7nwAmRVoADBojABRFaQAwi80xKYzUsymM1P8pjNT/KYzU/ymM1LgsjNE2MovXFB+K9MUfivbBH4r2BgcdNAARQH8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAAAAAAAQIDABIgKgAPGiIABRMcABdQeQAti9AqKYzUrCmM1P8pjNT/KYzU/ymM1MAqjNM9HmqmACWK7SIfivbZH4r2/x+K9vsuiudAFE2YACB69AD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAAAAAAABhQfABtejgAoitEAKYzUACmM1JQpjNT/KYzU/ymM1MgpjNREH2mgABlosQAfivY0H4r26R+K9v8fivbyKIrtR0CB1SggevTQIHr0Nv///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AAAAAAAAAAAACBwsAJX2+ACmM1AApjNQAKYzUGSmM1MYpjNRMInWxABNHdQAcfuEAH4r2Sx+K9vUfivb/H4r25iGK9DE2gt4EIHr0yyB69P8gevTQ////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAAAAAAAAAAAAAAAAAOMUsAKYzUACmM1AApjNQAJX6/ABE7WgAUWJwAH4r2AB+K9mYfivb9H4r2/x+K9tYfivYfG27RACB69HsgevT/IHr0+yB69DL///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAAAAAAAAAAAAAAAAAAfaJ4AJ4XKABVGagAKKkoAG3raAB+K9gEfivaEH4r2/x+K9v8fivbCH4r2EB133wAgevQsIHr0+SB69P8gevSAIHr0AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AAAAAAAAAAAAAAAAAAAAAAAUSGwAFERwAElCOAB+J9QAfivYAH4r2lx+K9v8fivb/H4r2qR+K9gYefuoAIHr0BSB69M4gevT/IHr00CB69AUgevQA////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAkqSgAfivYAH4r2AB+K9gAfivZLH4r2/R+K9osfivYBH4PwACB69AAgevSAIHr0/yB69PkgevQwIHr0ACB69AD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAAAAAAAAAAAAAAAAAAAAAAAEEiAAB+K9gAfivYAH4r2AB+K9gAfivYsH4r2AB+G8wAge/QAIHr0MCB69PsgevT/IHr0eyB69AAgevQAIHr0AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AAAAAAAAAAAAAAAAAAAAAAAAAAAAXZrYAH4r2AB+K9gAfivYAH4r2AB+K9gAfifUAIHz0ACB69AcgevTQIHr0/yB69MwgevQEIHr0ACB69AAgevQA////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAAAAAAAAAAAAAAAAAAAAAAAAIDAB6E6gAfivYAH4r2AB+K9gAfivYAH4r2ACB+9QAgevQAIHr0fCB69P8gevT5IHr0LCB69AAgevQAIHr0ACB69AD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAAAAAAAAAAAAAAAAAABBAcAEUqDAB6E6wAfivYAH4r2AB+K9gAggPUAIHr0ACB69AAgevQTIHr0qCB69HYgevQAIHr0ACB69AAgevQAIHr0AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP////////////////wAAH/8AAB//P/+f/z//n/8wAZ//MAGf/z//n/8wAZ//MAGf/zAAn/8/gJ//+AD///AAf//wEH//+cA///8AH//8BB///BgH//xwB///4If//4EP//+CD///hh///9w////4P///+H////j////////////" rel="icon" type="image/x-icon" />

Used this page here for this: http://www.motobit.com/util/base64-decoder-encoder.asp

Generate favicons

I can really suggest you this page: http://www.favicon-generator.org/ to create all types of favicons you need.

Enable tcp\ip remote connections to sql server express already installed database with code or script(query)

I recommend to use SMO (Enable TCP/IP Network Protocol for SQL Server). However, it was not available in my case.

I rewrote the WMI commands from Krzysztof Kozielczyk to PowerShell.

# Enable TCP/IP

Get-CimInstance -Namespace root/Microsoft/SqlServer/ComputerManagement10 -ClassName ServerNetworkProtocol -Filter "InstanceName = 'SQLEXPRESS' and ProtocolName = 'Tcp'" |
Invoke-CimMethod -Name SetEnable

# Open the right ports in the firewall
New-NetFirewallRule -DisplayName 'MSSQL$SQLEXPRESS' -Direction Inbound -Action Allow -Protocol TCP -LocalPort 1433

# Modify TCP/IP properties to enable an IP address

$properties = Get-CimInstance -Namespace root/Microsoft/SqlServer/ComputerManagement10 -ClassName ServerNetworkProtocolProperty -Filter "InstanceName='SQLEXPRESS' and ProtocolName = 'Tcp' and IPAddressName='IPAll'"
$properties | ? { $_.PropertyName -eq 'TcpPort' } | Invoke-CimMethod -Name SetStringValue -Arguments @{ StrValue = '1433' }
$properties | ? { $_.PropertyName -eq 'TcpPortDynamic' } | Invoke-CimMethod -Name SetStringValue -Arguments @{ StrValue = '' }

# Restart SQL Server

Restart-Service 'MSSQL$SQLEXPRESS'

How to revert multiple git commits?

In my opinion a very easy and clean way could be:

go back to A

git checkout -f A

point master's head to the current state

git symbolic-ref HEAD refs/heads/master

save

git commit

Android: Create a toggle button with image and no text

  1. Can I replace the toggle text with an image

    No, we can not, although we can hide the text by overiding the default style of the toggle button, but still that won't give us a toggle button you want as we can't replace the text with an image.

  2. How can I make a normal toggle button

    Create a file ic_toggle in your res/drawable folder

    <selector xmlns:android="http://schemas.android.com/apk/res/android">
    
        <item android:state_checked="false"
              android:drawable="@drawable/ic_slide_switch_off" />
    
        <item android:state_checked="true"
              android:drawable="@drawable/ic_slide_switch_on" />
    
    </selector>
    

    Here @drawable/ic_slide_switch_on & @drawable/ic_slide_switch_off are images you create.

    Then create another file in the same folder, name it ic_toggle_bg

    <?xml version="1.0" encoding="utf-8"?>
    <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    
        <item android:id="@+android:id/background"  
              android:drawable="@android:color/transparent" />
    
        <item android:id="@+android:id/toggle"
              android:drawable="@drawable/ic_toggle" />
    
    </layer-list>
    

    Now add to your custom theme, (if you do not have one create a styles.xml file in your res/values/folder)

    <style name="Widget.Button.Toggle" parent="android:Widget">
       <item name="android:background">@drawable/ic_toggle_bg</item>
       <item name="android:disabledAlpha">?android:attr/disabledAlpha</item>
    </style>
    
    <style name="toggleButton"  parent="@android:Theme.Black">
       <item name="android:buttonStyleToggle">@style/Widget.Button.Toggle</item>
       <item name="android:textOn"></item>
       <item name="android:textOff"></item>
    </style>
    

    This creates a custom toggle button for you.

  3. How to use it

    Use the custom style and background in your view.

      <ToggleButton
            android:id="@+id/toggleButton"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="right"
            style="@style/toggleButton"
            android:background="@drawable/ic_toggle_bg"/>
    

JavaScript - XMLHttpRequest, Access-Control-Allow-Origin errors

I've gotten same problem. The servers logs showed:

DEBUG: <-- origin: null

I've investigated that and it occurred that this is not populated when I've been calling from file from local drive. When I've copied file to the server and used it from server - the request worked perfectly fine

How to Compare two Arrays are Equal using Javascript?

You could try this simple approach

_x000D_
_x000D_
var array1 = [4,8,9,10];_x000D_
var array2 = [4,8,9,10];_x000D_
_x000D_
console.log(array1.join('|'));_x000D_
console.log(array2.join('|'));_x000D_
_x000D_
if (array1.join('|') === array2.join('|')) {_x000D_
 console.log('The arrays are equal.');_x000D_
} else {_x000D_
 console.log('The arrays are NOT equal.');_x000D_
}_x000D_
_x000D_
array1 = [[1,2],[3,4],[5,6],[7,8]];_x000D_
array2 = [[1,2],[3,4],[5,6],[7,8]];_x000D_
_x000D_
console.log(array1.join('|'));_x000D_
console.log(array2.join('|'));_x000D_
_x000D_
if (array1.join('|') === array2.join('|')) {_x000D_
 console.log('The arrays are equal.');_x000D_
} else {_x000D_
 console.log('The arrays are NOT equal.');_x000D_
}
_x000D_
_x000D_
_x000D_

If the position of the values are not important you could sort the arrays first.

if (array1.sort().join('|') === array2.sort().join('|')) {
    console.log('The arrays are equal.');
} else {
    console.log('The arrays are NOT equal.');
}

How to copy a file to multiple directories using the gnu cp command

This will copy to the immediate sub-directories, if you want to go deeper, adjust the -maxdepth parameter.

find . -mindepth 1 -maxdepth 1 -type d| xargs -n 1 cp -i index.html

If you don't want to copy to all directories, hopefully you can filter the directories you are not interested in. Example copying to all folders starting with a

find . -mindepth 1 -maxdepth 1 -type d| grep \/a |xargs -n 1 cp -i index.html

If copying to a arbitrary/disjoint set of directories you'll need Robert Gamble's suggestion.

Bootstrap datepicker hide after selection

You can change source code, bootstrap-datepicker.js. Add this.hide(); like ne

  if (this.viewMode !== 0) {
    this.date = new Date(this.viewDate);
    this.element.trigger({
        type: 'changeDate',
        date: this.date,
        viewMode: DPGlobal.modes[this.viewMode].clsName
    });
    this.hide();//here
 }

Using an if statement to check if a div is empty

if (typeof($('#container .prateleira')[0]) === 'undefined') {
    $('#ctl00_Conteudo_ctrPaginaSistemaAreaWrapper').css('display','none');
}

Div show/hide media query

 Small devices (landscape phones, 576px and up)
@media (min-width: 576px) { 
  #my-content{
   width:100%;
 }

// Medium devices (tablets, 768px and up)
@media (min-width: 768px) { 
  #my-content{
   width:100%;
 }
 }

// Large devices (desktops, 992px and up)
@media (min-width: 992px) { 
display: none;
 }

// Extra large devices (large desktops, 1200px and up)
@media (min-width: 1200px) {
// Havent code only get for more informations 
 } 

Send data from javascript to a mysql database

The other posters are correct you cannot connect to MySQL directly from javascript. This is because JavaScript is at client side & mysql is server side.

So your best bet is to use ajax to call a handler as quoted above if you can let us know what language your project is in we can better help you ie php/java/.net

If you project is using php then the example from Merlyn is a good place to start, I would personally use jquery.ajax() to cut down you code and have a better chance of less cross browser issues.

http://api.jquery.com/jQuery.ajax/

replace String with another in java

Replacing one string with another can be done in the below methods

Method 1: Using String replaceAll

 String myInput = "HelloBrother";
 String myOutput = myInput.replaceAll("HelloBrother", "Brother"); // Replace hellobrother with brother
 ---OR---
 String myOutput = myInput.replaceAll("Hello", ""); // Replace hello with empty
 System.out.println("My Output is : " +myOutput);       

Method 2: Using Pattern.compile

 import java.util.regex.Pattern;
 String myInput = "JAVAISBEST";
 String myOutputWithRegEX = Pattern.compile("JAVAISBEST").matcher(myInput).replaceAll("BEST");
 ---OR -----
 String myOutputWithRegEX = Pattern.compile("JAVAIS").matcher(myInput).replaceAll("");
 System.out.println("My Output is : " +myOutputWithRegEX);           

Method 3: Using Apache Commons as defined in the link below:

http://commons.apache.org/proper/commons-lang/javadocs/api-z.1/org/apache/commons/lang3/StringUtils.html#replace(java.lang.String, java.lang.String, java.lang.String)

REFERENCE

How to include clean target in Makefile?

In makefile language $@ means "name of the target", so rm -f $@ translates to rm -f clean.

You need to specify to rm what exactly you want to delete, like rm -f *.o code1 code2

How do I create a user account for basic authentication?

If you create a user with the advanced user management (from command line: netplwiz), then modify the group, remove users, and add iis_users. They will be able to authenticate to your web page, but not the computer.

Twitter bootstrap 3 two columns full height

I thought about a subtle change, which doesn't change the default bootstrap behavior. And I can use it only when I needed it:

.table-container {
  display: table;
}

.table-container .table-row {
  height: 100%;
  display: table-row;
}

.table-container .table-row .table-col {
  display: table-cell;
  float: none;
  vertical-align: top;
}

so I can have use it like this:

<div class="container table-container">
  <div class="row table-row">
    <div class="col-lg-4 table-col"> ... </div>
    <div class="col-lg-4 table-col"> ... </div>
    <div class="col-lg-4 table-col"> ... </div>
  </div>
</div>

How to refer environment variable in POM.xml?

It might be safer to directly pass environment variables to maven system properties. For example, say on Linux you want to access environment variable MY_VARIABLE. You can use a system property in your pom file.

<properties>
    ...
    <!-- Default value for my.variable can be defined here -->
    <my.variable>foo</my.variable>
    ...
</properties>
...
<!-- Use my.variable -->
... ${my.variable} ...

Set the property value on the maven command line:

mvn clean package -Dmy.variable=$MY_VARIABLE

Play sound on button click android

  • The audio must be placed in the raw folder, if it doesn't exists, create one.
  • The raw folder must be inside the res folder
  • The name mustn't have any - or special characters in it.

On your activity, you need to have a object MediaPlayer, inside the onCreate method or the onclick method, you have to initialize the MediaPlayer, like MediaPlayer.create(this, R.raw.name_of_your_audio_file), then your audio file ir ready to be played with the call for start(), in your case, since you want it to be placed in a button, you'll have to put it inside the onClick method.

Example:

private Button myButton;
private MediaPlayer mp;
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.myactivity);
        mp = MediaPlayer.create(this, R.raw.gunshot);

        myButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mp.start();
            }
        });
}
}

PostgreSQL: insert from another table

Just supply literal values in the SELECT:

INSERT INTO TABLE1 (id, col_1, col_2, col_3)
SELECT id, 'data1', 'data2', 'data3'
FROM TABLE2
WHERE col_a = 'something';

A select list can contain any value expression:

But the expressions in the select list do not have to reference any columns in the table expression of the FROM clause; they can be constant arithmetic expressions, for instance.

And a string literal is certainly a value expression.

Replace line break characters with <br /> in ASP.NET MVC Razor view

I prefer this method as it doesn't require manually emitting markup. I use this because I'm rendering Razor Pages to strings and sending them out via email, which is an environment where the white-space styling won't always work.

public static IHtmlContent RenderNewlines<TModel>(this IHtmlHelper<TModel> html, string content)
{
    if (string.IsNullOrEmpty(content) || html is null)
    {
        return null;
    }

    TagBuilder brTag = new TagBuilder("br");
    IHtmlContent br = brTag.RenderSelfClosingTag();
    HtmlContentBuilder htmlContent = new HtmlContentBuilder();

    // JAS: On the off chance a browser is using LF instead of CRLF we strip out CR before splitting on LF.
    string lfContent = content.Replace("\r", string.Empty, StringComparison.InvariantCulture);
    string[] lines = lfContent.Split('\n', StringSplitOptions.None);
    foreach(string line in lines)
    {
        _ = htmlContent.Append(line);
        _ = htmlContent.AppendHtml(br);
    }

    return htmlContent;
}

Javascript receipt printing using POS Printer

If you are talking about a browser based POS app then it basically can't be done out of the box. There are a number of alternatives.

  1. Use an applet like Scott Selby says
  2. Print from the server. If this is a cloud server, ie not connectable to the receipt printer then what you can do is
    • From the server generate it as a pdf which can be made to popup a print dialog in the browser
    • Use something like Google Cloud Print which will allow connecting printers to a cloud service

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.

How to specify the port an ASP.NET Core application is hosted on?

Alternative solution is to use a hosting.json in the root of the project.

{
  "urls": "http://localhost:60000"
}

And then in Program.cs

public static void Main(string[] args)
{
    var config = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("hosting.json", true)
        .Build();

    var host = new WebHostBuilder()
        .UseKestrel(options => options.AddServerHeader = false)
        .UseConfiguration(config)
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseIISIntegration()
        .UseStartup<Startup>()
        .Build();

    host.Run();
}

warning about too many open figures

This is also useful if you only want to temporarily suppress the warning:

import matplotlib.pyplot as plt
       
with plt.rc_context(rc={'figure.max_open_warning': 0}):
    lots_of_plots()

Output of git branch in tree like fashion

You can use a tool called gitk.

Executing "SELECT ... WHERE ... IN ..." using MySQLdb

Have been trying every variation on João's solution to get an IN List query to work with Tornado's mysql wrapper, and was still getting the accursed "TypeError: not enough arguments for format string" error. Turns out adding "*" to the list var "*args" did the trick.

args=['A', 'C']
sql='SELECT fooid FROM foo WHERE bar IN (%s)'
in_p=', '.join(list(map(lambda x: '%s', args)))
sql = sql % in_p
db.query(sql, *args)

SQL Query - Change date format in query to DD/MM/YYYY

If you have a Date (or Datetime) column, look at http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format

 SELECT DATE_FORMAT(datecolumn,'%d/%m/%Y') FROM ...

Should do the job for MySQL, for SqlServer I'm sure there is an analog function. If you have a VARCHAR column, you might have at first to convert it to a date, see STR_TO_DATE for MySQL.

'Linker command failed with exit code 1' when using Google Analytics via CocoaPods

This usually happens when using Cocoapods and you are building from the xcproject which doesn't know about the cocoapod libraries.

What's the difference between next() and nextLine() methods from Scanner class?

From the documentation for Scanner:

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.

From the documentation for next():

A complete token is preceded and followed by input that matches the delimiter pattern.

Case-Insensitive List Search

Based on Adam Sills answer above - here's a nice clean extensions method for Contains... :)

///----------------------------------------------------------------------
/// <summary>
/// Determines whether the specified list contains the matching string value
/// </summary>
/// <param name="list">The list.</param>
/// <param name="value">The value to match.</param>
/// <param name="ignoreCase">if set to <c>true</c> the case is ignored.</param>
/// <returns>
///   <c>true</c> if the specified list contais the matching string; otherwise, <c>false</c>.
/// </returns>
///----------------------------------------------------------------------
public static bool Contains(this List<string> list, string value, bool ignoreCase = false)
{
    return ignoreCase ?
        list.Any(s => s.Equals(value, StringComparison.OrdinalIgnoreCase)) :
        list.Contains(value);
}

What are bitwise shift (bit-shift) operators and how do they work?

The bitwise shift operators move the bit values of a binary object. The left operand specifies the value to be shifted. The right operand specifies the number of positions that the bits in the value are to be shifted. The result is not an lvalue. Both operands have the same precedence and are left-to-right associative.

Operator     Usage

 <<           Indicates the bits are to be shifted to the left.

 >>           Indicates the bits are to be shifted to the right.

Each operand must have an integral or enumeration type. The compiler performs integral promotions on the operands, and then the right operand is converted to type int. The result has the same type as the left operand (after the arithmetic conversions).

The right operand should not have a negative value or a value that is greater than or equal to the width in bits of the expression being shifted. The result of bitwise shifts on such values is unpredictable.

If the right operand has the value 0, the result is the value of the left operand (after the usual arithmetic conversions).

The << operator fills vacated bits with zeros. For example, if left_op has the value 4019, the bit pattern (in 16-bit format) of left_op is:

0000111110110011

The expression left_op << 3 yields:

0111110110011000

The expression left_op >> 3 yields:

0000000111110110

Create JPA EntityManager without persistence.xml configuration file

Yes you can without using any xml file using spring like this inside a @Configuration class (or its equivalent spring config xml):

@Bean
public LocalContainerEntityManagerFactoryBean emf(){
    properties.put("javax.persistence.jdbc.driver", dbDriverClassName);
    properties.put("javax.persistence.jdbc.url", dbConnectionURL);
    properties.put("javax.persistence.jdbc.user", dbUser); //if needed

    LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
    emf.setPersistenceProviderClass(org.eclipse.persistence.jpa.PersistenceProvider.class); //If your using eclipse or change it to whatever you're using
    emf.setPackagesToScan("com.yourpkg"); //The packages to search for Entities, line required to avoid looking into the persistence.xml
    emf.setPersistenceUnitName(SysConstants.SysConfigPU);
    emf.setJpaPropertyMap(properties);
    emf.setLoadTimeWeaver(new ReflectiveLoadTimeWeaver()); //required unless you know what your doing
    return emf;
}

How to select option in drop down using Capybara

Here's the most concise way I've found (using capybara 3.3.0 and chromium driver):

all('#id-of-select option')[1].select_option

will select the 2nd option. Increment the index as needed.

Extract data from XML Clob using SQL from Oracle Database

Try

SELECT EXTRACTVALUE(xmltype(testclob), '/DCResponse/ContextData/Field[@key="Decision"]') 
FROM traptabclob;

Here is a sqlfiddle demo

Java reverse an int value without using array

It's good that you wrote out your original code. I have another way to code this concept of reversing an integer. I'm only going to allow up to 10 digits. However, I am going to make the assumption that the user will not enter a zero.

if((inputNum <= 999999999)&&(inputNum > 0 ))
{
   System.out.print("Your number reversed is: ");

   do
   {
      endInt = inputNum % 10; //to get the last digit of the number
      inputNum /= 10;
      system.out.print(endInt);
   }
   While(inputNum != 0);
 System.out.println("");

}
 else
   System.out.println("You used an incorrect number of integers.\n");

System.out.println("Program end");

Php artisan make:auth command is not defined

In the Laravel 6 application the make:auth command no longer exists.

Laravel UI is a new first-party package that extracts the UI portion of a Laravel project into a separate laravel/ui package. The separate package enables the Laravel team to iterate on the UI package separately from the main Laravel codebase.

You can install the laravel/ui package via composer:

composer require laravel/ui

The ui:auth Command

Besides the new ui command, the laravel/ui package comes with another command for generating the auth scaffolding:

php artisan ui:auth

If you run the ui:auth command, it will generate the auth routes, a HomeController, auth views, and a app.blade.php layout file.


If you want to generate the views alone, type the following command instead:

php artisan ui:auth --views

If you want to generate the auth scaffolding at the same time:

php artisan ui vue --auth
php artisan ui react --auth

php artisan ui vue --auth command will create all of the views you need for authentication and place them in the resources/views/auth directory

The ui command will also create a resources/views/layouts directory containing a base layout for your application. All of these views use the Bootstrap CSS framework, but you are free to customize them however you wish.

More detail follow. laravel-news & documentation

Simply you've to follow this two-step.

composer require laravel/ui
php artisan ui:auth

Simple way to sort strings in the (case sensitive) alphabetical order

I recently answered a similar question here. Applying the same approach to your problem would yield following solution:

list.sort(
  p2Ord(stringOrd, stringOrd).comap(new F<String, P2<String, String>>() {
    public P2<String, String> f(String s) {
      return p(s.toLowerCase(), s);
    }
  })
);

jQuery UI DatePicker - Change Date Format

getDate function returns a JavaScript date. Use the following code to format this date:

var dateObject = $("#datepicker").datepicker("getDate");
var dateString = $.datepicker.formatDate("dd-mm-yy", dateObject);

It uses a utility function which is built into datepicker:

$.datepicker.formatDate( format, date, settings ) - Format a date into a string value with a specified format.

The full list of format specifiers is available here.

How to delete all instances of a character in a string in python?

I suggest split (not saying that the other answers are invalid, this is just another way to do it):

def findreplace(char, string):
   return ''.join(string.split(char))

Splitting by a character removes all the characters and turns it into a list. Then we join the list with the join function. You can see the ipython console test below

In[112]: findreplace('i', 'it is icy')
Out[112]: 't s cy'

And the speed...

In[114]: timeit("findreplace('it is icy','i')", "from __main__ import findreplace")
Out[114]: 0.9927914671134204

Not as fast as replace or translate, but ok.

How to Calculate Jump Target Address and Branch Target Address?

(In the diagrams and text below, PC is the address of the branch instruction itself. PC+4 is the end of the branch instruction itself, and the start of the branch delay slot. Except in the absolute jump diagram.)

1. Branch Address Calculation

In MIPS branch instruction has only 16 bits offset to determine next instruction. We need a register added to this 16 bit value to determine next instruction and this register is actually implied by architecture. It is PC register since PC gets updated (PC+4) during the fetch cycle so that it holds the address of the next instruction.

We also limit the branch distance to -2^15 to +2^15 - 1 instruction from the (instruction after the) branch instruction. However, this is not real issue since most branches are local anyway.

So step by step :

  • Sign extend the 16 bit offset value to preserve its value.
  • Multiply resulting value with 4. The reason behind this is that If we are going to branch some address, and PC is already word aligned, then the immediate value has to be word-aligned as well. However, it makes no sense to make the immediate word-aligned because we would be wasting low two bits by forcing them to be 00.
  • Now we have a 32 bit relative offset. Add this value to PC + 4 and that is your branch address.

Branch address calculation


2. Jump Address Calculation

For Jump instruction MIPS has only 26 bits to determine Jump location. Jumps are relative to PC in MIPS. Like branch, immediate jump value needs to be word-aligned; therefore, we need to multiply 26 bit address with four.

Again step by step:

  • Multiply 26 bit value with 4.
  • Since we are jumping relative to PC+4 value, concatenate first four bits of PC+4 value to left of our jump address.
  • Resulting address is the jump value.

In other words, replace the lower 28 bits of the PC + 4 with the lower 26 bits of the fetched instruction shifted left by 2 bits.

enter image description here

Jumps are region-relative to the branch-delay slot, not necessarily the branch itself. In the diagram above, PC has already advanced to the branch delay slot before the jump calculation. (In a classic-RISC 5 stage pipeline, the BD was fetched in the same cycle the jump is decoded, so that PC+4 next instruction address is already available for jumps as well as branches, and calculating relative to the jump's own address would have required extra work to save that address.)

Source: Bilkent University CS 224 Course Slides

Why does ASP.NET webforms need the Runat="Server" attribute?

It's there because all controls in ASP .NET inherit from System.Web.UI.Control which has the "runat" attribute.

in the class System.Web.UI.HTMLControl, the attribute is not required, however, in the class System.Web.UI.WebControl the attribute is required.

edit: let me be more specific. since asp.net is pretty much an abstract of HTML, the compiler needs some sort of directive so that it knows that specific tag needs to run server-side. if that attribute wasn't there then is wouldn't know to process it on the server first. if it isn't there it assumes it is regular markup and passes it to the client.

Create listview in fragment android

Please use ListFragment. Otherwise, it won't work.

EDIT 1: Then you'll only need setListAdapter() and getListView().

How to add a delay for a 2 or 3 seconds

You could use Thread.Sleep() function, e.g.

int milliseconds = 2000;
Thread.Sleep(milliseconds);

that completely stops the execution of the current thread for 2 seconds.

Probably the most appropriate scenario for Thread.Sleep is when you want to delay the operations in another thread, different from the main e.g. :

 MAIN THREAD        --------------------------------------------------------->
 (UI, CONSOLE ETC.)      |                                      |
                         |                                      |
 OTHER THREAD            ----- ADD A DELAY (Thread.Sleep) ------>

For other scenarios (e.g. starting operations after some time etc.) check Cody's answer.

OSError - Errno 13 Permission denied

supplementing @falsetru's answer : run id in the terminal to get your user_id and group_id

Go the directory/partition where you are facing the challenge. Open terminal, type id then press enter. This will show you your user_id and group_id

then type

chown -R user-id:group-id .

Replace user-id and group-id

. at the end indicates current partition / repository

// chown -R 1001:1001 . (that was my case)

Reduce git repository size

This should not affect everyone, but one of the semi-hidden reasons of the repository size being large could be Git submodules.

You might have added one or more submodules, but stopped using it at some time, and some files remained in .git/modules directory. To make redundant submodule files gone away, see this question.

However, just like the main repository, the other way is to navigate to the submodule directory in .git/modules, and do a, for example, git gc --aggressive --prune.

These should have a good impact in the repository size, but as long as you use Git submodules, e.g. especially with large libraries, your repository size should not change drastically.

How do I delete from multiple tables using INNER JOIN in SQL server

Example for delete some records from master table and corresponding records from two detail tables:

BEGIN TRAN

  -- create temporary table for deleted IDs
  CREATE TABLE #DeleteIds (
    Id INT NOT NULL PRIMARY KEY
  )

  -- save IDs of master table records (you want to delete) to temporary table    
  INSERT INTO #DeleteIds(Id)
  SELECT DISTINCT mt.MasterTableId
  FROM MasterTable mt 
  INNER JOIN ... 
  WHERE ...  

  -- delete from first detail table using join syntax
  DELETE d
  FROM DetailTable_1 D
  INNER JOIN #DeleteIds X
    ON D.MasterTableId = X.Id


  -- delete from second detail table using IN clause  
  DELETE FROM DetailTable_2
  WHERE MasterTableId IN (
    SELECT X.Id
    FROM #DeleteIds X
  )


  -- and finally delete from master table
  DELETE d
  FROM MasterTable D
  INNER JOIN #DeleteIds X
    ON D.MasterTableId = X.Id

  -- do not forget to drop the temp table
  DROP TABLE #DeleteIds

COMMIT

Excel plot time series frequency with continuous xaxis

You can get good Time Series graphs in Excel, the way you want, but you have to work with a few quirks.

  1. Be sure to select "Scatter Graph" (with a line option). This is needed if you have non-uniform time stamps, and will scale the X-axis accordingly.

  2. In your data, you need to add a column with the mid-point. Here's what I did with your sample data. (This trick ensures that the data gets plotted at the mid-point, like you desire.) enter image description here

  3. You can format the x-axis options with this menu. (Chart->Design->Layout) enter image description here

  4. Select "Axes" and go to Primary Horizontal Axis, and then select "More Primary Horizontal Axis Options"

  5. Set up the options you wish. (Fix the starting and ending points.) enter image description here

  6. And you will get a graph such as the one below. enter image description here

You can then tweak many of the options, label the axes better etc, but this should get you started.

Hope this helps you move forward.

MySQL TEXT vs BLOB vs CLOB

It's worth to mention that CLOB / BLOB data types and their sizes are supported by MySQL 5.0+, so you can choose the proper data type for your need.

http://dev.mysql.com/doc/refman/5.7/en/storage-requirements.html

Data Type   Date Type   Storage Required
(CLOB)      (BLOB)

TINYTEXT    TINYBLOB    L + 1 bytes, where L < 2**8  (255)
TEXT        BLOB        L + 2 bytes, where L < 2**16 (64 K)
MEDIUMTEXT  MEDIUMBLOB  L + 3 bytes, where L < 2**24 (16 MB)
LONGTEXT    LONGBLOB    L + 4 bytes, where L < 2**32 (4 GB)

where L stands for the byte length of a string

printf not printing on console

Output is buffered.

stdout is line-buffered by default, which means that '\n' is supposed to flush the buffer. Why is it not happening in your case? I don't know. I need more info about your application/environment.

However, you can control buffering with setvbuf():

setvbuf(stdout, NULL, _IOLBF, 0);

This will force stdout to be line-buffered.

setvbuf(stdout, NULL, _IONBF, 0);

This will force stdout to be unbuffered, so you won't need to use fflush(). Note that it will severely affect application performance if you have lots of prints.

How do I base64 encode a string efficiently using Excel VBA?

This code works very fast. It comes from here

Option Explicit

Private Const clOneMask = 16515072          '000000 111111 111111 111111
Private Const clTwoMask = 258048            '111111 000000 111111 111111
Private Const clThreeMask = 4032            '111111 111111 000000 111111
Private Const clFourMask = 63               '111111 111111 111111 000000

Private Const clHighMask = 16711680         '11111111 00000000 00000000
Private Const clMidMask = 65280             '00000000 11111111 00000000
Private Const clLowMask = 255               '00000000 00000000 11111111

Private Const cl2Exp18 = 262144             '2 to the 18th power
Private Const cl2Exp12 = 4096               '2 to the 12th
Private Const cl2Exp6 = 64                  '2 to the 6th
Private Const cl2Exp8 = 256                 '2 to the 8th
Private Const cl2Exp16 = 65536              '2 to the 16th

Public Function Encode64(sString As String) As String

    Dim bTrans(63) As Byte, lPowers8(255) As Long, lPowers16(255) As Long, bOut() As Byte, bIn() As Byte
    Dim lChar As Long, lTrip As Long, iPad As Integer, lLen As Long, lTemp As Long, lPos As Long, lOutSize As Long

    For lTemp = 0 To 63                                 'Fill the translation table.
        Select Case lTemp
            Case 0 To 25
                bTrans(lTemp) = 65 + lTemp              'A - Z
            Case 26 To 51
                bTrans(lTemp) = 71 + lTemp              'a - z
            Case 52 To 61
                bTrans(lTemp) = lTemp - 4               '1 - 0
            Case 62
                bTrans(lTemp) = 43                      'Chr(43) = "+"
            Case 63
                bTrans(lTemp) = 47                      'Chr(47) = "/"
        End Select
    Next lTemp

    For lTemp = 0 To 255                                'Fill the 2^8 and 2^16 lookup tables.
        lPowers8(lTemp) = lTemp * cl2Exp8
        lPowers16(lTemp) = lTemp * cl2Exp16
    Next lTemp

    iPad = Len(sString) Mod 3                           'See if the length is divisible by 3
    If iPad Then                                        'If not, figure out the end pad and resize the input.
        iPad = 3 - iPad
        sString = sString & String(iPad, Chr(0))
    End If

    bIn = StrConv(sString, vbFromUnicode)               'Load the input string.
    lLen = ((UBound(bIn) + 1) \ 3) * 4                  'Length of resulting string.
    lTemp = lLen \ 72                                   'Added space for vbCrLfs.
    lOutSize = ((lTemp * 2) + lLen) - 1                 'Calculate the size of the output buffer.
    ReDim bOut(lOutSize)                                'Make the output buffer.

    lLen = 0                                            'Reusing this one, so reset it.

    For lChar = LBound(bIn) To UBound(bIn) Step 3
        lTrip = lPowers16(bIn(lChar)) + lPowers8(bIn(lChar + 1)) + bIn(lChar + 2)    'Combine the 3 bytes
        lTemp = lTrip And clOneMask                     'Mask for the first 6 bits
        bOut(lPos) = bTrans(lTemp \ cl2Exp18)           'Shift it down to the low 6 bits and get the value
        lTemp = lTrip And clTwoMask                     'Mask for the second set.
        bOut(lPos + 1) = bTrans(lTemp \ cl2Exp12)       'Shift it down and translate.
        lTemp = lTrip And clThreeMask                   'Mask for the third set.
        bOut(lPos + 2) = bTrans(lTemp \ cl2Exp6)        'Shift it down and translate.
        bOut(lPos + 3) = bTrans(lTrip And clFourMask)   'Mask for the low set.
        If lLen = 68 Then                               'Ready for a newline
            bOut(lPos + 4) = 13                         'Chr(13) = vbCr
            bOut(lPos + 5) = 10                         'Chr(10) = vbLf
            lLen = 0                                    'Reset the counter
            lPos = lPos + 6
        Else
            lLen = lLen + 4
            lPos = lPos + 4
        End If
    Next lChar

    If bOut(lOutSize) = 10 Then lOutSize = lOutSize - 2 'Shift the padding chars down if it ends with CrLf.

    If iPad = 1 Then                                    'Add the padding chars if any.
        bOut(lOutSize) = 61                             'Chr(61) = "="
    ElseIf iPad = 2 Then
        bOut(lOutSize) = 61
        bOut(lOutSize - 1) = 61
    End If

    Encode64 = StrConv(bOut, vbUnicode)                 'Convert back to a string and return it.

End Function

Public Function Decode64(sString As String) As String

    Dim bOut() As Byte, bIn() As Byte, bTrans(255) As Byte, lPowers6(63) As Long, lPowers12(63) As Long
    Dim lPowers18(63) As Long, lQuad As Long, iPad As Integer, lChar As Long, lPos As Long, sOut As String
    Dim lTemp As Long

    sString = Replace(sString, vbCr, vbNullString)      'Get rid of the vbCrLfs.  These could be in...
    sString = Replace(sString, vbLf, vbNullString)      'either order.

    lTemp = Len(sString) Mod 4                          'Test for valid input.
    If lTemp Then
        Call Err.Raise(vbObjectError, "MyDecode", "Input string is not valid Base64.")
    End If

    If InStrRev(sString, "==") Then                     'InStrRev is faster when you know it's at the end.
        iPad = 2                                        'Note:  These translate to 0, so you can leave them...
    ElseIf InStrRev(sString, "=") Then                  'in the string and just resize the output.
        iPad = 1
    End If

    For lTemp = 0 To 255                                'Fill the translation table.
        Select Case lTemp
            Case 65 To 90
                bTrans(lTemp) = lTemp - 65              'A - Z
            Case 97 To 122
                bTrans(lTemp) = lTemp - 71              'a - z
            Case 48 To 57
                bTrans(lTemp) = lTemp + 4               '1 - 0
            Case 43
                bTrans(lTemp) = 62                      'Chr(43) = "+"
            Case 47
                bTrans(lTemp) = 63                      'Chr(47) = "/"
        End Select
    Next lTemp

    For lTemp = 0 To 63                                 'Fill the 2^6, 2^12, and 2^18 lookup tables.
        lPowers6(lTemp) = lTemp * cl2Exp6
        lPowers12(lTemp) = lTemp * cl2Exp12
        lPowers18(lTemp) = lTemp * cl2Exp18
    Next lTemp

    bIn = StrConv(sString, vbFromUnicode)               'Load the input byte array.
    ReDim bOut((((UBound(bIn) + 1) \ 4) * 3) - 1)       'Prepare the output buffer.

    For lChar = 0 To UBound(bIn) Step 4
        lQuad = lPowers18(bTrans(bIn(lChar))) + lPowers12(bTrans(bIn(lChar + 1))) + _
                lPowers6(bTrans(bIn(lChar + 2))) + bTrans(bIn(lChar + 3))           'Rebuild the bits.
        lTemp = lQuad And clHighMask                    'Mask for the first byte
        bOut(lPos) = lTemp \ cl2Exp16                   'Shift it down
        lTemp = lQuad And clMidMask                     'Mask for the second byte
        bOut(lPos + 1) = lTemp \ cl2Exp8                'Shift it down
        bOut(lPos + 2) = lQuad And clLowMask            'Mask for the third byte
        lPos = lPos + 3
    Next lChar

    sOut = StrConv(bOut, vbUnicode)                     'Convert back to a string.
    If iPad Then sOut = Left$(sOut, Len(sOut) - iPad)   'Chop off any extra bytes.
    Decode64 = sOut

End Function

How to execute my SQL query in CodeIgniter

    $sql="Select * from my_table where 1";    
    $query = $this->db->query($SQL);
    return $query->result_array();

Work on a remote project with Eclipse via SSH

For this case you can use ptp eclipse https://eclipse.org/ptp/ for source browsing and building.

You can use this pluging to debug your application

http://marketplace.eclipse.org/content/direct-remote-c-debugging

Trim string in JavaScript?

Although there are a bunch of correct answers above, it should be noted that the String object in JavaScript has a native .trim() method as of ECMAScript 5. Thus ideally any attempt to prototype the trim method should really check to see if it already exists first.

if(!String.prototype.trim){  
  String.prototype.trim = function(){  
    return this.replace(/^\s+|\s+$/g,'');  
  };  
}

Added natively in: JavaScript 1.8.1 / ECMAScript 5

Thus supported in:

Firefox: 3.5+

Safari: 5+

Internet Explorer: IE9+ (in Standards mode only!) http://blogs.msdn.com/b/ie/archive/2010/06/25/enhanced-scripting-in-ie9-ecmascript-5-support-and-more.aspx

Chrome: 5+

Opera: 10.5+

ECMAScript 5 Support Table: http://kangax.github.com/es5-compat-table/

Capturing browser logs with Selenium WebDriver using Java

In a more concise way, you can do:

LogEntries logs = driver.manage().logs().get(LogType.BROWSER);

For me it worked wonderfully for catching JS errors in console. Then you can add some verification for its size. For example, if it is > 0, add some error output.

Checkout remote branch using git svn

Standard Subversion layout

Create a git clone of that includes your Subversion trunk, tags, and branches with

git svn clone http://svn.example.com/project -T trunk -b branches -t tags

The --stdlayout option is a nice shortcut if your Subversion repository uses the typical structure:

git svn clone http://svn.example.com/project --stdlayout

Make your git repository ignore everything the subversion repo does:

git svn show-ignore >> .git/info/exclude

You should now be able to see all the Subversion branches on the git side:

git branch -r

Say the name of the branch in Subversion is waldo. On the git side, you'd run

git checkout -b waldo-svn remotes/waldo

The -svn suffix is to avoid warnings of the form

warning: refname 'waldo' is ambiguous.

To update the git branch waldo-svn, run

git checkout waldo-svn
git svn rebase

Starting from a trunk-only checkout

To add a Subversion branch to a trunk-only clone, modify your git repository's .git/config to contain

[svn-remote "svn-mybranch"]
        url = http://svn.example.com/project/branches/mybranch
        fetch = :refs/remotes/mybranch

You'll need to develop the habit of running

git svn fetch --fetch-all

to update all of what git svn thinks are separate remotes. At this point, you can create and track branches as above. For example, to create a git branch that corresponds to mybranch, run

git checkout -b mybranch-svn remotes/mybranch

For the branches from which you intend to git svn dcommit, keep their histories linear!


Further information

You may also be interested in reading an answer to a related question.

Postgres: How to convert a json string to text?

There is no way in PostgreSQL to deconstruct a scalar JSON object. Thus, as you point out,

select  length(to_json('Some "text"'::TEXT) ::TEXT);

is 15,

The trick is to convert the JSON into an array of one JSON element, then extract that element using ->>.

select length( array_to_json(array[to_json('Some "text"'::TEXT)])->>0 );

will return 11.

Resize external website content to fit iFrame width

Tip for 1 website resizing the height. But you can change to 2 websites.

Here is my code to resize an iframe with an external website. You need insert a code into the parent (with iframe code) page and in the external website as well, so, this won't work with you don't have access to edit the external website.

  • local (iframe) page: just insert a code snippet
  • remote (external) page: you need a "body onload" and a "div" that holds all contents. And body needs to be styled to "margin:0"

Local:

<IFRAME STYLE="width:100%;height:1px" SRC="http://www.remote-site.com/" FRAMEBORDER="no" BORDER="0" SCROLLING="no" ID="estframe"></IFRAME>

<SCRIPT>
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
eventer(messageEvent,function(e) {
  if (e.data.substring(0,3)=='frm') document.getElementById('estframe').style.height = e.data.substring(3) + 'px';
},false);
</SCRIPT>

You need this "frm" prefix to avoid problems with other embeded codes like Twitter or Facebook plugins. If you have a plain page, you can remove the "if" and the "frm" prefix on both pages (script and onload).

Remote:

You need jQuery to accomplish about "real" page height. I cannot realize how to do with pure JavaScript since you'll have problem when resize the height down (higher to lower height) using body.scrollHeight or related. For some reason, it will return always the biggest height (pre-redimensioned).

<BODY onload="parent.postMessage('frm'+$('#master').height(),'*')" STYLE="margin:0">
<SCRIPT SRC="path-to-jquery/jquery.min.js"></SCRIPT>
<DIV ID="master">
your content
</DIV>

So, parent page (iframe) has a 1px default height. The script inserts a "wait for message/event" from the iframe. When a message (post message) is received and the first 3 chars are "frm" (to avoid the mentioned problem), will get the number from 4th position and set the iframe height (style), including 'px' unit.

The external site (loaded in the iframe) will "send a message" to the parent (opener) with the "frm" and the height of the main div (in this case id "master"). The "*" in postmessage means "any source".

Hope this helps. Sorry for my english.

How to deal with "data of class uneval" error from ggplot2?

This could also occur if you refer to a variable in the data.frame that doesn't exist. For example, recently I forgot to tell ddply to summarize by one of my variables that I used in geom_line to specify line color. Then, ggplot didn't know where to find the variable I hadn't created in the summary table, and I got this error.

Fork() function in C

First a link to some documentation of fork()

http://pubs.opengroup.org/onlinepubs/009695399/functions/fork.html

The pid is provided by the kernel. Every time the kernel create a new process it will increase the internal pid counter and assign the new process this new unique pid and also make sure there are no duplicates. Once the pid reaches some high number it will wrap and start over again.

So you never know what pid you will get from fork(), only that the parent will keep it's unique pid and that fork will make sure that the child process will have a new unique pid. This is stated in the documentation provided above.

If you continue reading the documentation you will see that fork() return 0 for the child process and the new unique pid of the child will be returned to the parent. If the child want to know it's own new pid you will have to query for it using getpid().

pid_t pid = fork()
if(pid == 0) {
    printf("this is a child: my new unique pid is %d\n", getpid());
} else {
    printf("this is the parent: my pid is %d and I have a child with pid %d \n", getpid(), pid);
}

and below is some inline comments on your code

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main() {
    pid_t pid1, pid2, pid3;
    pid1=0, pid2=0, pid3=0;
    pid1= fork(); /* A */
    if(pid1 == 0){
        /* This is child A */
        pid2=fork(); /* B */
        pid3=fork(); /* C */
    } else {
        /* This is parent A */
        /* Child B and C will never reach this code */
        pid3=fork(); /* D */
        if(pid3==0) {
            /* This is child D fork'ed from parent A */
            pid2=fork(); /* E */
        }
        if((pid1 == 0)&&(pid2 == 0)) {
            /* pid1 will never be 0 here so this is dead code */
            printf("Level 1\n");
        }
        if(pid1 !=0) {
            /* This is always true for both parent and child E */
            printf("Level 2\n");
        }
        if(pid2 !=0) {
           /* This is parent E (same as parent A) */
           printf("Level 3\n");
        }
        if(pid3 !=0) {
           /* This is parent D (same as parent A) */
           printf("Level 4\n");
        }
    }
    return 0;
}

Angular + Material - How to refresh a data source (mat-table)

import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs/Observable';

export class LanguageComponent implemnts OnInit {
  displayedColumns = ['name', 'native', 'code', 'leavel'];
  user: any;
  private update = new Subject<void>();
  update$ = this.update.asObservable();

  constructor(private authService: AuthService, private dialog: MatDialog) {}

   ngOnInit() {
     this.update$.subscribe(() => { this.refresh()});
   }

   setUpdate() {
     this.update.next();
   }

   add() {
     this.dialog.open(LanguageAddComponent, {
     data: { user: this.user },
   }).afterClosed().subscribe(result => {
     this.setUpdate();
   });
 }

 refresh() {
   this.authService.getAuthenticatedUser().subscribe((res) => {
     this.user = res;
     this.teachDS = new LanguageDataSource(this.user.profile.languages.teach);   
    });
  }
}

Save child objects automatically using JPA Hibernate

Following program describe how bidirectional relation work in hibernate.

When parent will save its list of child object will be auto save.

On Parent side:

    @Entity
    @Table(name="clients")
    public class Clients implements Serializable  {

         @Id
         @GeneratedValue(strategy = GenerationType.IDENTITY)     
         @OneToMany(mappedBy="clients", cascade=CascadeType.ALL)
          List<SmsNumbers> smsNumbers;
    }

And put the following annotation on the child side:

  @Entity
  @Table(name="smsnumbers")
  public class SmsNumbers implements Serializable {

     @Id
     @GeneratedValue(strategy = GenerationType.IDENTITY)
     int id;
     String number;
     String status;
     Date reg_date;
     @ManyToOne
     @JoinColumn(name = "client_id")
     private Clients clients;

    // and getter setter.

 }

Main class:

 public static void main(String arr[])
 {
    Session session = HibernateUtil.openSession();
      //getting transaction object from session object
    session.beginTransaction();

    Clients cl=new Clients("Murali", "1010101010");
    SmsNumbers sms1=new SmsNumbers("99999", "Active", cl);
    SmsNumbers sms2=new SmsNumbers("88888", "InActive", cl);
    SmsNumbers sms3=new SmsNumbers("77777", "Active", cl);
    List<SmsNumbers> lstSmsNumbers=new ArrayList<SmsNumbers>();
    lstSmsNumbers.add(sms1);
    lstSmsNumbers.add(sms2);
    lstSmsNumbers.add(sms3);
    cl.setSmsNumbers(lstSmsNumbers);
    session.saveOrUpdate(cl);
    session.getTransaction().commit(); 
    session.close();    

 }

Swift Set to Array

I created a simple extension that gives you an unsorted Array as a property of Set in Swift 4.0.

extension Set {
    var array: [Element] {
        return Array(self)
    }
}

If you want a sorted array, you can either add an additional computed property, or modify the existing one to suit your needs.

To use this, just call

let array = set.array

Updating the value of data attribute using jQuery

$('.toggle img').data('block', 'something');
$('.toggle img').attr('src', 'something.jpg');

Use jQuery.data and jQuery.attr.

I'm showing them to you separately for the sake of understanding.

How to empty a char array?

You can use the following instruction:

strcpy_s(members, "");

Laravel Eloquent inner join with multiple conditions

return $query->join('kg_shops', function($join)
 {
   $join->on('kg_shops.id', '=', 'kg_feeds.shop_id');

 })
 ->select('required column names') 
 ->where('kg_shops.active', 1)
 ->get();

How ViewBag in ASP.NET MVC works

ViewBag is a dynamic type that allow you to dynamically set or get values and allow you to add any number of additional fields without a strongly-typed class They allow you to pass data from controller to view. In controller......

public ActionResult Index()
{
    ViewBag.victor = "My name is Victor";
    return View();
}

In view

@foreach(string a in ViewBag.victor)
{
     .........
}

What I have learnt is that both should have the save dynamic name property ie ViewBag.victor

Alter user defined type in SQL Server

The simplest way to do this is through Visual Studio's object explorer, which is also supported in the Community edition.

Once you have made a connection to SQL server, browse to the type, right click and select View Code, make your changes to the schema of the user defined type and click update. Visual Studio should show you all of the dependencies for that object and generate scripts to update the type and recompile dependencies.

Storing Python dictionaries

Also see the speeded-up package ujson:

import ujson

with open('data.json', 'wb') as fp:
    ujson.dump(data, fp)

How to make return key on iPhone make keyboard disappear?

After quite a bit of time hunting down something that makes sense, this is what I put together and it worked like a charm.

.h

//
//  ViewController.h
//  demoKeyboardScrolling
//
//  Created by Chris Cantley on 11/14/13.
//  Copyright (c) 2013 Chris Cantley. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UITextFieldDelegate>

// Connect your text field to this the below property.
@property (weak, nonatomic) IBOutlet UITextField *theTextField;

@end

.m

//
//  ViewController.m
//  demoKeyboardScrolling
//
//  Created by Chris Cantley on 11/14/13.
//  Copyright (c) 2013 Chris Cantley. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController



- (void)viewDidLoad
{
    [super viewDidLoad];
    // _theTextField is the name of the parameter designated in the .h file. 
    _theTextField.returnKeyType = UIReturnKeyDone;
    [_theTextField setDelegate:self];

}

// This part is more dynamic as it closes the keyboard regardless of what text field 
// is being used when pressing return.  
// You might want to control every single text field separately but that isn't 
// what this code do.
-(void)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
}


@end

Hope this helps!

Is there a printf converter to print in binary format?

The combination of functions + macro at the end of this answer can help you.

Use it like that:

float float_var = 9.4;
SHOW_BITS(float_var);

Which will output: Variable 'float_var': 01000001 00010110 01100110 01100110

Note that it is very general and can work with pretty much any type. For instance:

struct {int a; float b; double c;} struct_var = {1,1.1,1.2};
SHOW_BITS(struct_var);

Which will output:

Variable `struct_var`: 00111111 11110011 00110011 00110011 00110011 00110011 00110011 00110011 00111111 10001100 11001100 11001101 00000000 00000000 00000000 00000001

Here's the code:

#define SHOW_BITS(a) ({ \
    printf("Variable `%s`: ", #a);\
    show_bits(&a, sizeof(a));\
})

void show_uchar(unsigned char a)
{
    for(int i = 7; i >= 0; i-= 1) 
        printf("%d", ((a >> i) & 1));
}

void show_bits(void* a, size_t s)
{
    unsigned char* p = (unsigned char*) a;
    for(int i = s-1; i >= 0 ; i -= 1) {
        show_uchar(p[i]);
        printf(" ");
    }
    printf("\n");
}

Why do we have to normalize the input for an artificial neural network?

In neural networks, it is good idea not just to normalize data but also to scale them. This is intended for faster approaching to global minima at error surface. See the following pictures: error surface before and after normalization

error surface before and after scaling

Pictures are taken from the coursera course about neural networks. Author of the course is Geoffrey Hinton.

How to get diff between all files inside 2 folders that are on the web?

You urls are not in the same repository, so you can't do it with the svn diff command.

svn: 'http://svn.boost.org/svn/boost/sandbox/boost/extension' isn't in the same repository as 'http://cloudobserver.googlecode.com/svn'

Another way you could do it, is export each repos using svn export, and then use the diff command to compare the 2 directories you exported.

// Export repositories
svn export http://svn.boost.org/svn/boost/sandbox/boost/extension/ repos1
svn export http://cloudobserver.googlecode.com/svn/branches/v0.4/Boost.Extension.Tutorial/libs/boost/extension/ repos2

// Compare exported directories
diff repos1 repos2 > file.diff

Pass data to layout that are common to all pages

Presumably, the primary use case for this is to get a base model to the view for all (or the majority of) controller actions.

Given that, I've used a combination of several of these answers, primary piggy backing on Colin Bacon's answer.

It is correct that this is still controller logic because we are populating a viewmodel to return to a view. Thus the correct place to put this is in the controller.

We want this to happen on all controllers because we use this for the layout page. I am using it for partial views that are rendered in the layout page.

We also still want the added benefit of a strongly typed ViewModel

Thus, I have created a BaseViewModel and BaseController. All ViewModels Controllers will inherit from BaseViewModel and BaseController respectively.

The code:

BaseController

public class BaseController : Controller
{
    protected override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        base.OnActionExecuted(filterContext);

        var model = filterContext.Controller.ViewData.Model as BaseViewModel;

        model.AwesomeModelProperty = "Awesome Property Value";
        model.FooterModel = this.getFooterModel();
    }

    protected FooterModel getFooterModel()
    {
        FooterModel model = new FooterModel();
        model.FooterModelProperty = "OMG Becky!!! Another Awesome Property!";
    }
}

Note the use of OnActionExecuted as taken from this SO post

HomeController

public class HomeController : BaseController
{
    public ActionResult Index(string id)
    {
        HomeIndexModel model = new HomeIndexModel();

        // populate HomeIndexModel ...

        return View(model);
    }
}

BaseViewModel

public class BaseViewModel
{
    public string AwesomeModelProperty { get; set; }
    public FooterModel FooterModel { get; set; }
}

HomeViewModel

public class HomeIndexModel : BaseViewModel
{

    public string FirstName { get; set; }

    // other awesome properties
}

FooterModel

public class FooterModel
{
    public string FooterModelProperty { get; set; }
}

Layout.cshtml

@model WebSite.Models.BaseViewModel
<!DOCTYPE html>
<html>
<head>
    < ... meta tags and styles and whatnot ... >
</head>
<body>
    <header>
        @{ Html.RenderPartial("_Nav", Model.FooterModel.FooterModelProperty);}
    </header>

    <main>
        <div class="container">
            @RenderBody()
        </div>

        @{ Html.RenderPartial("_AnotherPartial", Model); }
        @{ Html.RenderPartial("_Contact"); }
    </main>

    <footer>
        @{ Html.RenderPartial("_Footer", Model.FooterModel); }
    </footer>

    < ... render scripts ... >

    @RenderSection("scripts", required: false)
</body>
</html>

_Nav.cshtml

@model string
<nav>
    <ul>
        <li>
            <a href="@Model" target="_blank">Mind Blown!</a>
        </li>
    </ul>
</nav>

Hopefully this helps.

Remove CSS from a Div using JQuery

jQuery.fn.extend
({
    removeCss: function(cssName) {
        return this.each(function() {
            var curDom = $(this);
            jQuery.grep(cssName.split(","),
                    function(cssToBeRemoved) {
                        curDom.css(cssToBeRemoved, '');
                    });
            return curDom;
        });
    }
});

/*example code: I prefer JQuery extend so I can use it anywhere I want to use.

$('#searchJqueryObject').removeCss('background-color');
$('#searchJqueryObject').removeCss('background-color,height,width'); //supports comma separated css names.

*/

OR

//this parse style & remove style & rebuild style. I like the first one.. but anyway exploring..
jQuery.fn.extend
({
    removeCSS: function(cssName) {
        return this.each(function() {

            return $(this).attr('style',

            jQuery.grep($(this).attr('style').split(";"),
                    function(curCssName) {
                        if (curCssName.toUpperCase().indexOf(cssName.toUpperCase() + ':') <= 0)
                            return curCssName;
                    }).join(";"));
        });
    }
});

How do I create a readable diff of two spreadsheets using git diff?

I got the problem like you so I decide to write small tool to help me out. Please check ExcelDiff_Tools. It comes with several key points:

  • Support xls, xlsx, xlsm.
  • With formula cell. It will compare both formula and value.
  • I try to make UI look like standard diff text viewer with : modified, deleted, added, unchanged status. Please take a look with image below for example: enter image description here

Set background image in CSS using jquery

Try this:

<div class="rmz-srchbg">
    <input type="text" id="globalsearchstr" name="search" value="" class="rmz-txtbox">
    <input type="submit" value="&nbsp;" id="srchbtn" class="rmz-srchico">
    <br style="clear:both;">
</div>
<script>
$(function(){
   $('#globalsearchstr').on('focus mouseenter', function(){
    $(this).parent().css("background", "url(/images/r-srchbg_white.png) no-repeat");
   });
});
</script>

Bitwise and in place of modulus operator

Modulo "7" without "%" operator

int a = x % 7;

int a = (x + x / 7) & 7;

How to find index of list item in Swift?

As swift is in some regards more functional than object-oriented (and Arrays are structs, not objects), use the function "find" to operate on the array, which returns an optional value, so be prepared to handle a nil value:

let arr:Array = ["a","b","c"]
find(arr, "c")!              // 2
find(arr, "d")               // nil

Update for Swift 2.0:

The old find function is not supported any more with Swift 2.0!

With Swift 2.0, Array gains the ability to find the index of an element using a function defined in an extension of CollectionType (which Array implements):

let arr = ["a","b","c"]

let indexOfA = arr.indexOf("a") // 0
let indexOfB = arr.indexOf("b") // 1
let indexOfD = arr.indexOf("d") // nil

Additionally, finding the first element in an array fulfilling a predicate is supported by another extension of CollectionType:

let arr2 = [1,2,3,4,5,6,7,8,9,10]
let indexOfFirstGreaterThanFive = arr2.indexOf({$0 > 5}) // 5
let indexOfFirstGreaterThanOneHundred = arr2.indexOf({$0 > 100}) // nil

Note that these two functions return optional values, as find did before.

Update for Swift 3.0:

Note the syntax of indexOf has changed. For items conforming to Equatable you can use:

let indexOfA = arr.index(of: "a")

A detailed documentation of the method can be found at https://developer.apple.com/reference/swift/array/1689674-index

For array items that don't conform to Equatable you'll need to use index(where:):

let index = cells.index(where: { (item) -> Bool in
  item.foo == 42 // test if this is the item you're looking for
})

Update for Swift 4.2:

With Swift 4.2, index is no longer used but is separated into firstIndex and lastIndex for better clarification. So depending on whether you are looking for the first or last index of the item:

let arr = ["a","b","c","a"]

let indexOfA = arr.firstIndex(of: "a") // 0
let indexOfB = arr.lastIndex(of: "a") // 3

git repo says it's up-to-date after pull but files are not updated

For me my forked branch was not in sync with the master branch. So I went to bitbucket and synced and merged my forked branch and then tried to take the pull. Then it worked fine.

Vertical align in bootstrap table

For me <td class="align-middle" >${element.imie}</td> works. I'm using Bootstrap v4.0.0-beta .

How do I fix MSB3073 error in my post-build event?

The Post-Build Event (under Build Events, in the properties dialog) of an imported project, had an environment variable which was not defined.
Navigated to Control Panel\All Control Panel Items\System\Advanced system settings to add the appropriate environment variable, and doing no more than restarting VS2017 resolved the error.
Also, following on from @Seans and other answers regarding multiple project races/contentions, create a temp folder in the output folder like so,

like so

and select the project producing the preferred output:

enter image description here

and build (no rebuild/clean) is a speedy solution.

What's the easiest way to install a missing Perl module?

Also see Yes, even you can use CPAN. It shows how you can use CPAN without having root or sudo access.

Pythonic way to check if a list is sorted or not

I use this one-liner based on numpy.diff():

def issorted(x):
    """Check if x is sorted"""
    return (numpy.diff(x) >= 0).all() # is diff between all consecutive entries >= 0?

I haven't really timed it against any other method, but I assume it's faster than any pure Python method, especially for large n, since the loop in numpy.diff (probably) runs directly in C (n-1 subtractions followed by n-1 comparisons).

However, you need to be careful if x is an unsigned int, which might cause silent integer underflow in numpy.diff(), resulting in a false positive. Here's a modified version:

def issorted(x):
    """Check if x is sorted"""
    try:
        if x.dtype.kind == 'u':
            # x is unsigned int array, risk of int underflow in np.diff
            x = numpy.int64(x)
    except AttributeError:
        pass # no dtype, not an array
    return (numpy.diff(x) >= 0).all()

how to use html2canvas and jspdf to export to pdf in a proper and simple way

I have made a jsfiddle for you.

 <canvas id="canvas" width="480" height="320"></canvas> 
      <button id="download">Download Pdf</button>

'

        html2canvas($("#canvas"), {
            onrendered: function(canvas) {         
                var imgData = canvas.toDataURL(
                    'image/png');              
                var doc = new jsPDF('p', 'mm');
                doc.addImage(imgData, 'PNG', 10, 10);
                doc.save('sample-file.pdf');
            }
        });

jsfiddle: http://jsfiddle.net/rpaul/p4s5k59s/5/

Tested in Chrome38, IE11 and Firefox 33. Seems to have issues with Safari. However, Andrew got it working in Safari 8 on Mac OSx by switching to JPEG from PNG. For details, see his comment below.

Of Countries and their Cities

I was comparing worldcitiesdatabae.info with www.worldcitiesdatabase.com and it appears the latter one to be more resourceful. However, maxmind has a free database so then why buy a cities database. Just get the free one and there is lot of help available on internet about maxmind db. If you put in extra efforts then you can save those few bucks :)

Optimal number of threads per core

The ideal is 1 thread per core, as long as none of the threads will block.

One case where this may not be true: there are other threads running on the core, in which case more threads may give your program a bigger slice of the execution time.

How do I use the ternary operator ( ? : ) in PHP as a shorthand for "if / else"?


I dont think i found the answer in all the above solutions. Some are also wrong.

To tests if a variable (or an element of an array, or a property of an object) exists (and is not null) use: echo isset($address['street2']) ? $address['street2'] : 'Empty';

To tests if a variable (...) contains some non-empty data use:
echo !empty($address['street2']) ? $address['street2'] : 'Empty';

Replace last occurrence of character in string

This is a recursive way that removes multiple occurrences of "endchar":

_x000D_
_x000D_
function TrimEnd(str, endchar) {_x000D_
  while (str.endsWith(endchar) && str !== "" && endchar !== "") {_x000D_
    str = str.slice(0, -1);_x000D_
  }_x000D_
  return str;_x000D_
}_x000D_
_x000D_
var res = TrimEnd("Look at me. I'm a string without dots at the end...", ".");_x000D_
console.log(res)
_x000D_
_x000D_
_x000D_

Library not loaded: libmysqlclient.16.dylib error when trying to run 'rails server' on OS X 10.6 with mysql2 gem

I still found that with the solutions above, it didn't work (for example) with the Rails plugin for TextMate. I got a similar error (when retrieving the database schema).

So what did is, open terminal:

cd /usr/local/lib
sudo ln -s ../mysql-5.5.8-osx10.6-x86_64/lib/libmysqlclient.16.dylib .

Replace mysql-5.5.8-osx10.6-x86_64 with your own path (or mysql).

This makes a symbol link to the lib, now rails runs from the command line, as-well as TextMate plugin(s) like ruby-on-rails-tmbundle.

To be clear: this also fixes the error you get when starting rails server.

Make code in LaTeX look *nice*

It turns out that lstlisting is able to format code nicely, but requires a lot of tweaking.

Wikibooks has a good example for the parameters you can tweak.

std::string to char*

Alternatively , you can use vectors to get a writable char* as demonstrated below;

//this handles memory manipulations and is more convenient
string str;
vector <char> writable (str.begin (), str.end) ;
writable .push_back ('\0'); 
char* cstring = &writable[0] //or &*writable.begin () 

//Goodluck  

how to pass parameters to query in SQL (Excel)

It depends on the database to which you're trying to connect, the method by which you created the connection, and the version of Excel that you're using. (Also, most probably, the version of the relevant ODBC driver on your computer.)

The following examples are using SQL Server 2008 and Excel 2007, both on my local machine.

When I used the Data Connection Wizard (on the Data tab of the ribbon, in the Get External Data section, under From Other Sources), I saw the same thing that you did: the Parameters button was disabled, and adding a parameter to the query, something like select field from table where field2 = ?, caused Excel to complain that the value for the parameter had not been specified, and the changes were not saved.

When I used Microsoft Query (same place as the Data Connection Wizard), I was able to create parameters, specify a display name for them, and enter values each time the query was run. Bringing up the Connection Properties for that connection, the Parameters... button is enabled, and the parameters can be modified and used as I think you want.

I was also able to do this with an Access database. It seems reasonable that Microsoft Query could be used to create parameterized queries hitting other types of databases, but I can't easily test that right now.

How to get POSTed JSON in Flask?

Assuming that you have posted valid JSON,

@app.route('/api/add_message/<uuid>', methods=['GET', 'POST'])
def add_message(uuid):
    content = request.json
    print content['uuid']
    # Return data as JSON
    return jsonify(content)

Quicksort: Choosing the pivot

On the average, Median of 3 is good for small n. Median of 5 is a bit better for larger n. The ninther, which is the "median of three medians of three" is even better for very large n.

The higher you go with sampling the better you get as n increases, but the improvement dramatically slows down as you increase the samples. And you incur the overhead of sampling and sorting samples.

How to get JSON data from the URL (REST API) to UI using jQuery or plain JavaScript?

You can use us jquery function getJson :

$(function(){
    $.getJSON('/api/rest/abc', function(data) {
        console.log(data);
    });
});