Programs & Examples On #Collada

COLLADA is a royalty-free XML schema that enables digital asset exchange within the interactive 3D industry.

Using HTML5/JavaScript to generate and save a file

As previously mentioned the File API, along with the FileWriter and FileSystem APIs can be used to store files on a client's machine from the context of a browser tab/window.

However, there are several things pertaining to latter two APIs which you should be aware of:

  • Implementations of the APIs currently exist only in Chromium-based browsers (Chrome & Opera)
  • Both of the APIs were taken off of the W3C standards track on April 24, 2014, and as of now are proprietary
  • Removal of the (now proprietary) APIs from implementing browsers in the future is a possibility
  • A sandbox (a location on disk outside of which files can produce no effect) is used to store the files created with the APIs
  • A virtual file system (a directory structure which does not necessarily exist on disk in the same form that it does when accessed from within the browser) is used represent the files created with the APIs

Here are simple examples of how the APIs are used, directly and indirectly, in tandem to do this:

BakedGoods*

bakedGoods.get({
        data: ["testFile"],
        storageTypes: ["fileSystem"],
        options: {fileSystem:{storageType: Window.PERSISTENT}},
        complete: function(resultDataObj, byStorageTypeErrorObj){}
});

Using the raw File, FileWriter, and FileSystem APIs

function onQuotaRequestSuccess(grantedQuota)
{

    function saveFile(directoryEntry)
    {

        function createFileWriter(fileEntry)
        {

            function write(fileWriter)
            {
                var dataBlob = new Blob(["Hello world!"], {type: "text/plain"});
                fileWriter.write(dataBlob);              
            }

            fileEntry.createWriter(write);
        }

        directoryEntry.getFile(
            "testFile", 
            {create: true, exclusive: true},
            createFileWriter
        );
    }

    requestFileSystem(Window.PERSISTENT, grantedQuota, saveFile);
}

var desiredQuota = 1024 * 1024 * 1024;
var quotaManagementObj = navigator.webkitPersistentStorage;
quotaManagementObj.requestQuota(desiredQuota, onQuotaRequestSuccess);

Though the FileSystem and FileWriter APIs are no longer on the standards track, their use can be justified in some cases, in my opinion, because:

  • Renewed interest from the un-implementing browser vendors may place them right back on it
  • Market penetration of implementing (Chromium-based) browsers is high
  • Google (the main contributer to Chromium) has not given and end-of-life date to the APIs

Whether "some cases" encompasses your own, however, is for you to decide.

*BakedGoods is maintained by none other than this guy right here :)

How to Remove Array Element and Then Re-Index Array?

Try with:

$foo2 = array_slice($foo, 1);

Run all SQL files in a directory

Make sure you have SQLCMD enabled by clicking on the Query > SQLCMD mode option in the management studio.

  1. Suppose you have four .sql files (script1.sql,script2.sql,script3.sql,script4.sql) in a folder c:\scripts.

  2. Create a main script file (Main.sql) with the following:

    :r c:\Scripts\script1.sql
    :r c:\Scripts\script2.sql
    :r c:\Scripts\script3.sql
    :r c:\Scripts\script4.sql
    

    Save the Main.sql in c:\scripts itself.

  3. Create a batch file named ExecuteScripts.bat with the following:

    SQLCMD -E -d<YourDatabaseName> -ic:\Scripts\Main.sql
    PAUSE
    

    Remember to replace <YourDatabaseName> with the database you want to execute your scripts. For example, if the database is "Employee", the command would be the following:

    SQLCMD -E -dEmployee -ic:\Scripts\Main.sql
    PAUSE
    
  4. Execute the batch file by double clicking the same.

How to call a method with a separate thread in Java?

In Java 8 you can do this with one line of code.

If your method doesn't take any parameters, you can use a method reference:

new Thread(MyClass::doWork).start();

Otherwise, you can call the method in a lambda expression:

new Thread(() -> doWork(someParam)).start();

How can I color Python logging output?

Another minor remix of airmind's approach that keeps everything in one class:

class ColorFormatter(logging.Formatter):
  FORMAT = ("[$BOLD%(name)-20s$RESET][%(levelname)-18s]  "
            "%(message)s "
            "($BOLD%(filename)s$RESET:%(lineno)d)")

  BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)

  RESET_SEQ = "\033[0m"
  COLOR_SEQ = "\033[1;%dm"
  BOLD_SEQ = "\033[1m"

  COLORS = {
    'WARNING': YELLOW,
    'INFO': WHITE,
    'DEBUG': BLUE,
    'CRITICAL': YELLOW,
    'ERROR': RED
  }

  def formatter_msg(self, msg, use_color = True):
    if use_color:
      msg = msg.replace("$RESET", self.RESET_SEQ).replace("$BOLD", self.BOLD_SEQ)
    else:
      msg = msg.replace("$RESET", "").replace("$BOLD", "")
    return msg

  def __init__(self, use_color=True):
    msg = self.formatter_msg(self.FORMAT, use_color)
    logging.Formatter.__init__(self, msg)
    self.use_color = use_color

  def format(self, record):
    levelname = record.levelname
    if self.use_color and levelname in self.COLORS:
      fore_color = 30 + self.COLORS[levelname]
      levelname_color = self.COLOR_SEQ % fore_color + levelname + self.RESET_SEQ
      record.levelname = levelname_color
    return logging.Formatter.format(self, record)

To use attach the formatter to a handler, something like:

handler.setFormatter(ColorFormatter())
logger.addHandler(handler)

Adding days to a date in Python

In order to have have a less verbose code, and avoid name conflicts between datetime and datetime.datetime, you should rename the classes with CamelCase names.

from datetime import datetime as DateTime, timedelta as TimeDelta

So you can do the following, which I think it is clearer.

date_1 = DateTime.today() 
end_date = date_1 + TimeDelta(days=10)

Also, there would be no name conflict if you want to import datetime later on.

Java error: Comparison method violates its general contract

It also has something to do with the version of JDK. If it does well in JDK6, maybe it will have the problem in JDK 7 described by you, because the implementation method in jdk 7 has been changed.

Look at this:

Description: The sorting algorithm used by java.util.Arrays.sort and (indirectly) by java.util.Collections.sort has been replaced. The new sort implementation may throw an IllegalArgumentException if it detects a Comparable that violates the Comparable contract. The previous implementation silently ignored such a situation. If the previous behavior is desired, you can use the new system property, java.util.Arrays.useLegacyMergeSort, to restore previous mergesort behaviour.

I don't know the exact reason. However, if you add the code before you use sort. It will be OK.

System.setProperty("java.util.Arrays.useLegacyMergeSort", "true");

await is only valid in async function

The error is not refering to myfunction but to start.

async function start() {
   ....

   const result = await helper.myfunction('test', 'test');
}

_x000D_
_x000D_
// My function_x000D_
const myfunction = async function(x, y) {_x000D_
  return [_x000D_
    x,_x000D_
    y,_x000D_
  ];_x000D_
}_x000D_
_x000D_
// Start function_x000D_
const start = async function(a, b) {_x000D_
  const result = await myfunction('test', 'test');_x000D_
  _x000D_
  console.log(result);_x000D_
}_x000D_
_x000D_
// Call start_x000D_
start();
_x000D_
_x000D_
_x000D_



I use the opportunity of this question to advise you about an known anti pattern using await which is : return await.


WRONG

_x000D_
_x000D_
async function myfunction() {_x000D_
  console.log('Inside of myfunction');_x000D_
}_x000D_
_x000D_
// Here we wait for the myfunction to finish_x000D_
// and then returns a promise that'll be waited for aswell_x000D_
// It's useless to wait the myfunction to finish before to return_x000D_
// we can simply returns a promise that will be resolved later_x000D_
_x000D_
// useless async here_x000D_
async function start() {_x000D_
  // useless await here_x000D_
  return await myfunction();_x000D_
}_x000D_
_x000D_
// Call start_x000D_
(async() => {_x000D_
  console.log('before start');_x000D_
_x000D_
  await start();_x000D_
  _x000D_
  console.log('after start');_x000D_
})();
_x000D_
_x000D_
_x000D_


CORRECT

_x000D_
_x000D_
async function myfunction() {_x000D_
  console.log('Inside of myfunction');_x000D_
}_x000D_
_x000D_
// Here we wait for the myfunction to finish_x000D_
// and then returns a promise that'll be waited for aswell_x000D_
// It's useless to wait the myfunction to finish before to return_x000D_
// we can simply returns a promise that will be resolved later_x000D_
_x000D_
// Also point that we don't use async keyword on the function because_x000D_
// we can simply returns the promise returned by myfunction_x000D_
function start() {_x000D_
  return myfunction();_x000D_
}_x000D_
_x000D_
// Call start_x000D_
(async() => {_x000D_
  console.log('before start');_x000D_
_x000D_
  await start();_x000D_
  _x000D_
  console.log('after start');_x000D_
})();
_x000D_
_x000D_
_x000D_


Also, know that there is a special case where return await is correct and important : (using try/catch)

Are there performance concerns with `return await`?

Constructors in JavaScript objects

They do if you use Typescript - open source from MicroSoft :-)

class BankAccount {
 balance: number;
 constructor(initially: number) {
 this.balance = initially;
 }
 deposit(credit: number) {
 this.balance += credit;
 return this.balance;
 }
}

Typescript lets you 'fake' OO constructs that are compiled into javascript constructs. If you're starting a large project it may save you a lot of time and it just reached milestone 1.0 version.

http://www.typescriptlang.org/Content/TypeScript%20Language%20Specification.pdf

The above code gets 'compiled' to :

var BankAccount = (function () {
    function BankAccount(initially) {
        this.balance = initially;
    }
    BankAccount.prototype.deposit = function (credit) {
        this.balance += credit;
        return this.balance;
    };
    return BankAccount;
})();

Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>)

You define var scatterSeries = [];, and then try to parse it as a json string at console.info(JSON.parse(scatterSeries)); which obviously fails. The variable is converted to an empty string, which causes an "unexpected end of input" error when trying to parse it.

Search for "does-not-contain" on a DataFrame in pandas

You can use the invert (~) operator (which acts like a not for boolean data):

new_df = df[~df["col"].str.contains(word)]

, where new_df is the copy returned by RHS.

contains also accepts a regular expression...


If the above throws a ValueError, the reason is likely because you have mixed datatypes, so use na=False:

new_df = df[~df["col"].str.contains(word, na=False)]

Or,

new_df = df[df["col"].str.contains(word) == False]

How to install a specific version of a ruby gem?

For installing gem install gemname -v versionnumber

For uninstall gem uninstall gemname -v versionnumber

Best equivalent VisualStudio IDE for Mac to program .NET/C#

Whilst more of a workaround, if you're running an Intel Mac, you could go the virtualisation route - at least then you can run the same tools.

Erase the current printed console line

echo -e "hello\c" ;sleep 1 ; echo -e "\rbye  "

What the above command will do :

  1. It will print hello and the cursor will remain at "o" (using \c)

  2. Then it will wait for 1 sec (sleep 1)

  3. Then it will replace hello with bye.(using \r)

NOTE : Using ";", We can run multiple command in a single go.

Excel VBA Open a Folder

I use this to open a workbook and then copy that workbook's data to the template.

Private Sub CommandButton24_Click()
Set Template = ActiveWorkbook
 With Application.FileDialog(msoFileDialogOpen)
    .InitialFileName = "I:\Group - Finance" ' Yu can select any folder you want
    .Filters.Clear
    .Title = "Your Title"
    If Not .Show Then
        MsgBox "No file selected.": Exit Sub
    End If
    Workbooks.OpenText .SelectedItems(1)

'The below is to copy the file into a new sheet in the workbook and paste those values in sheet 1

    Set myfile = ActiveWorkbook
    ActiveWorkbook.Sheets(1).Copy after:=ThisWorkbook.Sheets(1)
    myfile.Close
    Template.Activate
    ActiveSheet.Cells.Select
    Selection.Copy
    Sheets("Sheet1").Select
    Cells.Select
    ActiveSheet.Paste

End With

How to change a dataframe column from String type to Double type in PySpark?

Given answers are enough to deal with the problem but I want to share another way which may be introduced the new version of Spark (I am not sure about it) so given answer didn't catch it.

We can reach the column in spark statement with col("colum_name") keyword:

from pyspark.sql.functions import col , column
changedTypedf = joindf.withColumn("show", col("show").cast("double"))

TensorFlow not found using pip

I have experienced the same error while I tried to install tensorflow in an anaconda package. After struggling a lot, I finally found an easy way to install any package without running into an error. First create an environment in your anaconda administrator using this command

conda create -n packages

Now activate that environment

activate packages 

and try running

pip install tensorflow 

After a successful installation, we need to make this environment accessible to jupyter notebook. For that, you need to install a package called ipykernel using this command

pip install ipykernel

After installing ipykernel enter the following command

python -m ipykernel install --user --name=packages

After running this command, this environment will be added to jupyter notebook and that's it. Just go to your jupyter notebook, click on new notebook, and you can see your environment. Select that environment and try importing tensorflow and in case if you want to install any other packages, just activate the environment and install those packages and use that environment in your jupyter

Why is "forEach not a function" for this object?

If you really need to use a secure foreach interface to iterate an object and make it reusable and clean with a npm module, then use this, https://www.npmjs.com/package/foreach-object

Ex:

import each from 'foreach-object';
   
const object = {
   firstName: 'Arosha',
   lastName: 'Sum',
   country: 'Australia'
};
   
each(object, (value, key, object) => {
   console.log(key + ': ' + value);
});
   
// Console log output will be:
//      firstName: Arosha
//      lastName: Sum
//      country: Australia

How can I convert string date to NSDate?

If you're going to need to parse the string into a date often, you may want to move the functionality into an extension. I created a sharedCode.swift file and put my extensions there:

extension String
{   
    func toDateTime() -> NSDate
    {
        //Create Date Formatter
        let dateFormatter = NSDateFormatter()

        //Specify Format of String to Parse
        dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss.SSSSxxx"

        //Parse into NSDate
        let dateFromString : NSDate = dateFormatter.dateFromString(self)!

        //Return Parsed Date
        return dateFromString
    }
}

Then if you want to convert your string into a NSDate you can just write something like:

var myDate = myDateString.toDateTime()

Maven 3 and JUnit 4 compilation problem: package org.junit does not exist

my problem was a line inside my pom.xml i had the line <sourceDirectory>${basedir}/src</sourceDirectory> removing this line made maven use regular structure folders which solves my issue

fastest way to export blobs from table into individual files

For me what worked by combining all the posts I have read is:

1.Enable OLE automation - if not enabled

sp_configure 'show advanced options', 1;  
GO  
RECONFIGURE;  
GO  
sp_configure 'Ole Automation Procedures', 1;  
GO  
RECONFIGURE;  
GO

2.Create a folder where the generated files will be stored:

C:\GREGTESTING

3.Create DocTable that will be used for file generation and store there the blobs in Doc_Content
enter image description here

CREATE TABLE [dbo].[Document](
    [Doc_Num] [numeric](18, 0) IDENTITY(1,1) NOT NULL,
    [Extension] [varchar](50) NULL,
    [FileName] [varchar](200) NULL,
    [Doc_Content] [varbinary](max) NULL   
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] 

INSERT [dbo].[Document] ([Extension] ,[FileName] , [Doc_Content] )
    SELECT 'pdf', 'SHTP Notional hire - January 2019.pdf', 0x....(varbinary blob)

Important note!

Don't forget to add in Doc_Content column the varbinary of file you want to generate!

4.Run the below script

DECLARE @outPutPath varchar(50) = 'C:\GREGTESTING'
, @i bigint
, @init int
, @data varbinary(max) 
, @fPath varchar(max)  
, @folderPath  varchar(max)

--Get Data into temp Table variable so that we can iterate over it 
DECLARE @Doctable TABLE (id int identity(1,1), [Doc_Num]  varchar(100) , [FileName]  varchar(100), [Doc_Content] varBinary(max) )



INSERT INTO @Doctable([Doc_Num] , [FileName],[Doc_Content])
Select [Doc_Num] , [FileName],[Doc_Content] FROM  [dbo].[Document]



SELECT @i = COUNT(1) FROM @Doctable   

WHILE @i >= 1   

BEGIN    

SELECT 
    @data = [Doc_Content],
    @fPath = @outPutPath + '\' + [Doc_Num] +'_' +[FileName],
    @folderPath = @outPutPath + '\'+ [Doc_Num]
FROM @Doctable WHERE id = @i

EXEC sp_OACreate 'ADODB.Stream', @init OUTPUT; -- An instace created
EXEC sp_OASetProperty @init, 'Type', 1;  
EXEC sp_OAMethod @init, 'Open'; -- Calling a method
EXEC sp_OAMethod @init, 'Write', NULL, @data; -- Calling a method
EXEC sp_OAMethod @init, 'SaveToFile', NULL, @fPath, 2; -- Calling a method
EXEC sp_OAMethod @init, 'Close'; -- Calling a method
EXEC sp_OADestroy @init; -- Closed the resources
print 'Document Generated at - '+  @fPath   

--Reset the variables for next use
SELECT @data = NULL  
, @init = NULL
, @fPath = NULL  
, @folderPath = NULL
SET @i -= 1
END   

5.The results is shown below: enter image description here

AngularJS - pass function to directive

@JorgeGRC Thanks for your answer. One thing though, the "maybe" part is very important. If you do have parameter(s), you must include it/them on your template as well and be sure to specify your locals e.g. updateFn({msg: "Directive Args"}.

Nested or Inner Class in PHP

You can, like this, in PHP 7:

class User{
  public $id;
  public $name;
  public $password;
  public $Profile;
  public $History;  /*  (optional declaration, if it isn't public)  */
  public function __construct($id,$name,$password){
    $this->id=$id;
    $this->name=$name;
    $this->name=$name;
    $this->Profile=(object)[
        'get'=>function(){
          return 'Name: '.$this->name.''.(($this->History->get)());
        }
      ];
    $this->History=(object)[
        'get'=>function(){
          return ' History: '.(($this->History->track)());
        }
        ,'track'=>function(){
          return (lcg_value()>0.5?'good':'bad');
        }
      ];
  }
}
echo ((new User(0,'Lior','nyh'))->Profile->get)();

How to bind a List to a ComboBox?

As you are referring to a combobox, I'm assuming you don't want to use 2-way databinding (if so, look at using a BindingList)

public class Country
{
    public string Name { get; set; }
    public IList<City> Cities { get; set; }
    public Country(string _name)
    {
        Cities = new List<City>();
        Name = _name;
    }
}



List<Country> countries = new List<Country> { new Country("UK"), 
                                     new Country("Australia"), 
                                     new Country("France") };

var bindingSource1 = new BindingSource();
bindingSource1.DataSource = countries;

comboBox1.DataSource = bindingSource1.DataSource;

comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "Name";

To find the country selected in the bound combobox, you would do something like: Country country = (Country)comboBox1.SelectedItem;.

If you want the ComboBox to dynamically update you'll need to make sure that the data structure that you have set as the DataSource implements IBindingList; one such structure is BindingList<T>.


Tip: make sure that you are binding the DisplayMember to a Property on the class and not a public field. If you class uses public string Name { get; set; } it will work but if it uses public string Name; it will not be able to access the value and instead will display the object type for each line in the combo box.

PowerShell on Windows 7: Set-ExecutionPolicy for regular users

This should solve your problem, you should try to run the following below:

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser 

Early exit from function?

I dislike answering things that aren't a real solution...

...but when I encountered this same problem, I made below workaround:

function doThis() {
  var err=0
  if (cond1) { alert('ret1'); err=1; }
  if (cond2) { alert('ret2'); err=1; }
  if (cond3) { alert('ret3'); err=1; }
  if (err < 1) {
    // do the rest (or have it skipped)
  }
}

Hope it can be useful for anyone.

How to add Web API to an existing ASP.NET MVC 4 Web Application project?

UPDATE 11/22/2013 - this is the latest WebApi package:

Install-Package Microsoft.AspNet.WebApi

Original answer (this is an older WebApi package)

Install-Package AspNetWebApi

More details.

How can I do SELECT UNIQUE with LINQ?

The Distinct() is going to mess up the ordering, so you'll have to the sorting after that.

var uniqueColors = 
               (from dbo in database.MainTable 
                 where dbo.Property == true 
                 select dbo.Color.Name).Distinct().OrderBy(name=>name);

Repository access denied. access via a deployment key is read-only

'Deployment Key' is only for Read Only access. Following is a good way to work through this.

  • Create and SSH key and add it to bitbucket (User Avatar -> Bitbucket Setting-> SSH keys)
  • ~/.ssh/known_hosts
  • ssh-add -D (Remove keys loaded to SSH agent)
  • ssh-add ~/.ssh/your_private_key_for_bitbucket
  • ssh [email protected] -Tv (Verify that your key is getting used to connect to bitbucket)
  • git push 'remote name' 'branch name'

How to resolve : Can not find the tag library descriptor for "http://java.sun.com/jsp/jstl/core"

I also use this

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

but I don't get any error.

Did you include the jstl.jar in your library? If not maybe this causing the problem. And also the 'tld' folder do you have it? And how about your web.xml did you map it?

Have a look on the info about jstl for other information.

How to 'insert if not exists' in MySQL?

Update or insert without known primary key

If you already have a unique or primary key, the other answers with either INSERT INTO ... ON DUPLICATE KEY UPDATE ... or REPLACE INTO ... should work fine (note that replace into deletes if exists and then inserts - thus does not partially update existing values).

But if you have the values for some_column_id and some_type, the combination of which are known to be unique. And you want to update some_value if exists, or insert if not exists. And you want to do it in just one query (to avoid using a transaction). This might be a solution:

INSERT INTO my_table (id, some_column_id, some_type, some_value)
SELECT t.id, t.some_column_id, t.some_type, t.some_value
FROM (
    SELECT id, some_column_id, some_type, some_value
    FROM my_table
    WHERE some_column_id = ? AND some_type = ?
    UNION ALL
    SELECT s.id, s.some_column_id, s.some_type, s.some_value
    FROM (SELECT NULL AS id, ? AS some_column_id, ? AS some_type, ? AS some_value) AS s
) AS t
LIMIT 1
ON DUPLICATE KEY UPDATE
some_value = ?

Basically, the query executes this way (less complicated than it may look):

  • Select an existing row via the WHERE clause match.
  • Union that result with a potential new row (table s), where the column values are explicitly given (s.id is NULL, so it will generate a new auto-increment identifier).
  • If an existing row is found, then the potential new row from table s is discarded (due to LIMIT 1 on table t), and it will always trigger an ON DUPLICATE KEY which will UPDATE the some_value column.
  • If an existing row is not found, then the potential new row is inserted (as given by table s).

Note: Every table in a relational database should have at least a primary auto-increment id column. If you don't have this, add it, even when you don't need it at first sight. It is definitely needed for this "trick".

Stop all active ajax requests in jQuery

Make a pool of all ajax request and abort them.....

var xhrQueue = []; 

$(document).ajaxSend(function(event,jqxhr,settings){
    xhrQueue.push(jqxhr); //alert(settings.url);
});

$(document).ajaxComplete(function(event,jqxhr,settings){
    var i;   
    if((i=$.inArray(jqxhr,xhrQueue)) > -1){
        xhrQueue.splice(i,1); //alert("C:"+settings.url);
    }
});

ajaxAbort = function (){  //alert("abortStart");
    var i=0;
    while(xhrQueue.length){ 
        xhrQueue[i++] .abort(); //alert(i+":"+xhrQueue[i++]);
    }
};

What's the difference between "app.render" and "res.render" in express.js?

Here are some differences:

  1. You can call app.render on root level and res.render only inside a route/middleware.

  2. app.render always returns the html in the callback function, whereas res.render does so only when you've specified the callback function as your third parameter. If you call res.render without the third parameter/callback function the rendered html is sent to the client with a status code of 200.

    Take a look at the following examples.

    • app.render

      app.render('index', {title: 'res vs app render'}, function(err, html) {
          console.log(html)
      });
      
      // logs the following string (from default index.jade)
      <!DOCTYPE html><html><head><title>res vs app render</title><link rel="stylesheet" href="/stylesheets/style.css"></head><body><h1>res vs app render</h1><p>Welcome to res vs app render</p></body></html>
      
    • res.render without third parameter

      app.get('/render', function(req, res) {
          res.render('index', {title: 'res vs app render'})
      })
      
      // also renders index.jade but sends it to the client 
      // with status 200 and content-type text/html on GET /render
      
    • res.render with third parameter

      app.get('/render', function(req, res) {
          res.render('index', {title: 'res vs app render'}, function(err, html) {
              console.log(html);
              res.send('done');
          })
      })
      
      // logs the same as app.render and sends "done" to the client instead 
      // of the content of index.jade
      
  3. res.render uses app.render internally to render template files.

  4. You can use the render functions to create html emails. Depending on your structure of your app, you might not always have acces to the app object.

    For example inside an external route:

    app.js

    var routes = require('routes');
    
    app.get('/mail', function(req, res) {
        // app object is available -> app.render
    })
    
    app.get('/sendmail', routes.sendmail);
    

    routes.js

    exports.sendmail = function(req, res) {
        // can't use app.render -> therefore res.render
    }
    

CS0120: An object reference is required for the nonstatic field, method, or property 'foo'

You start a thread which runs the static method SumData. However, SumData calls SetTextboxText which isn't static. Thus you need an instance of your form to call SetTextboxText.

What is the size of ActionBar in pixels?

From the de-compiled sources of Android 3.2's framework-res.apk, res/values/styles.xml contains:

<style name="Theme.Holo">
    <!-- ... -->
    <item name="actionBarSize">56.0dip</item>
    <!-- ... -->
</style>

3.0 and 3.1 seem to be the same (at least from AOSP)...

Is there a way to create and run javascript in Chrome?

You don't necessarily need to have an HTML page. Open Chrome, press Ctrl+Shift+j and it opens the JavaScript console where you can write and test your code.

- Chrome JavaScript Console

Writing a dictionary to a text file?

You can do as follow :

import json
exDict = {1:1, 2:2, 3:3}
file.write(json.dumps(exDict))

https://developer.rhino3d.com/guides/rhinopython/python-xml-json/

Maven fails to find local artifact

Even I faced this issue and solved it with 2 ways:

1) In your IDE select project and clean all projects then install all the maven dependencies by right clicking on project -> go to maven and Update project dependencies select all projects at once to install the same. Once this is done run the particular project

2) Else What you can do is check in the pom.xml for the dependencies for which you are getting error and "mvn clean install" those dependent project first and the install maven dependencies of the current project in which you facing issue. By this the dependencies of the local project will be build and jars will be created.

sed edit file in place

Like Moneypenny said in Skyfall: "Sometimes the old ways are best." Kincade said something similar later on.

$ printf ',s/false/true/g\nw\n' | ed {YourFileHere}

Happy editing in place. Added '\nw\n' to write the file. Apologies for delay answering request.

What are the git concepts of HEAD, master, origin?

I highly recommend the book "Pro Git" by Scott Chacon. Take time and really read it, while exploring an actual git repo as you do.

HEAD: the current commit your repo is on. Most of the time HEAD points to the latest commit in your current branch, but that doesn't have to be the case. HEAD really just means "what is my repo currently pointing at".

In the event that the commit HEAD refers to is not the tip of any branch, this is called a "detached head".

master: the name of the default branch that git creates for you when first creating a repo. In most cases, "master" means "the main branch". Most shops have everyone pushing to master, and master is considered the definitive view of the repo. But it's also common for release branches to be made off of master for releasing. Your local repo has its own master branch, that almost always follows the master of a remote repo.

origin: the default name that git gives to your main remote repo. Your box has its own repo, and you most likely push out to some remote repo that you and all your coworkers push to. That remote repo is almost always called origin, but it doesn't have to be.

HEAD is an official notion in git. HEAD always has a well-defined meaning. master and origin are common names usually used in git, but they don't have to be.

Failed to resolve version for org.apache.maven.archetypes

I had the same problem. I fixed it by adding the maven archetype catalog to eclipse. Steps are provided below:

  1. Open Window > Preferences
  2. Open Maven > Archetypes
  3. Click 'Add Remote Catalog' and add the following:

Windows equivalent to UNIX pwd

Open notepad as administrator and write:

@echo %cd%

Save it in c:\windows\system32\ with the name "pwd.cmd" (be careful not to save pwd.cmd.txt)

Then you have the pwd command.

Windows Application has stopped working :: Event Name CLR20r3

Make sure the client computer has the same or higher version of the .NET framework that you built your program to.

Java Process with Input/Output Stream

Firstly, I would recommend replacing the line

Process process = Runtime.getRuntime ().exec ("/bin/bash");

with the lines

ProcessBuilder builder = new ProcessBuilder("/bin/bash");
builder.redirectErrorStream(true);
Process process = builder.start();

ProcessBuilder is new in Java 5 and makes running external processes easier. In my opinion, its most significant improvement over Runtime.getRuntime().exec() is that it allows you to redirect the standard error of the child process into its standard output. This means you only have one InputStream to read from. Before this, you needed to have two separate Threads, one reading from stdout and one reading from stderr, to avoid the standard error buffer filling while the standard output buffer was empty (causing the child process to hang), or vice versa.

Next, the loops (of which you have two)

while ((line = reader.readLine ()) != null) {
    System.out.println ("Stdout: " + line);
}

only exit when the reader, which reads from the process's standard output, returns end-of-file. This only happens when the bash process exits. It will not return end-of-file if there happens at present to be no more output from the process. Instead, it will wait for the next line of output from the process and not return until it has this next line.

Since you're sending two lines of input to the process before reaching this loop, the first of these two loops will hang if the process hasn't exited after these two lines of input. It will sit there waiting for another line to be read, but there will never be another line for it to read.

I compiled your source code (I'm on Windows at the moment, so I replaced /bin/bash with cmd.exe, but the principles should be the same), and I found that:

  • after typing in two lines, the output from the first two commands appears, but then the program hangs,
  • if I type in, say, echo test, and then exit, the program makes it out of the first loop since the cmd.exe process has exited. The program then asks for another line of input (which gets ignored), skips straight over the second loop since the child process has already exited, and then exits itself.
  • if I type in exit and then echo test, I get an IOException complaining about a pipe being closed. This is to be expected - the first line of input caused the process to exit, and there's nowhere to send the second line.

I have seen a trick that does something similar to what you seem to want, in a program I used to work on. This program kept around a number of shells, ran commands in them and read the output from these commands. The trick used was to always write out a 'magic' line that marks the end of the shell command's output, and use that to determine when the output from the command sent to the shell had finished.

I took your code and I replaced everything after the line that assigns to writer with the following loop:

while (scan.hasNext()) {
    String input = scan.nextLine();
    if (input.trim().equals("exit")) {
        // Putting 'exit' amongst the echo --EOF--s below doesn't work.
        writer.write("exit\n");
    } else {
        writer.write("((" + input + ") && echo --EOF--) || echo --EOF--\n");
    }
    writer.flush();

    line = reader.readLine();
    while (line != null && ! line.trim().equals("--EOF--")) {
        System.out.println ("Stdout: " + line);
        line = reader.readLine();
    }
    if (line == null) {
        break;
    }
}

After doing this, I could reliably run a few commands and have the output from each come back to me individually.

The two echo --EOF-- commands in the line sent to the shell are there to ensure that output from the command is terminated with --EOF-- even in the result of an error from the command.

Of course, this approach has its limitations. These limitations include:

  • if I enter a command that waits for user input (e.g. another shell), the program appears to hang,
  • it assumes that each process run by the shell ends its output with a newline,
  • it gets a bit confused if the command being run by the shell happens to write out a line --EOF--.
  • bash reports a syntax error and exits if you enter some text with an unmatched ).

These points might not matter to you if whatever it is you're thinking of running as a scheduled task is going to be restricted to a command or a small set of commands which will never behave in such pathological ways.

EDIT: improve exit handling and other minor changes following running this on Linux.

Twitter Bootstrap vs jQuery UI?

I have on several projects.

The biggest difference in my opinion

  • jQuery UI is fallback safe, it works correctly and looks good in old browsers, where Bootstrap is based on CSS3 which basically means GREAT in new browsers, not so great in old

  • Update frequency: Bootstrap is getting some great big updates with awesome new features, but sadly they might break previous code, so you can't just install bootstrap and update when there is a new major release, it basically requires a lot of new coding

  • jQuery UI is based on good html structure with transformations from JavaScript, while Bootstrap is based on visually and customizable inline structure. (calling a widget in JQUERY UI, defining it in Bootstrap)

So what to choose?

That always depends on the type of project you are working on. Is cool and fast looking widgets better, or are your users often using old browsers?

I always end up using both, so I can use the best of both worlds.

Here are the links to both frameworks, if you decide to use them.

  1. jQuery UI
  2. Bootstrap

How to show the Project Explorer window in Eclipse

Try to close Eclipse IDE and reopen it and

click on window->show view->project explorer

Find length (size) of an array in jquery

var array=[];

array.push(array);  //insert the array value using push methods.

for (var i = 0; i < array.length; i++) {    
    nameList += "" + array[i] + "";          //display the array value.                                                             
}

$("id/class").html(array.length);   //find the array length.

Listing only directories using ls in Bash?

For all folders without subfolders:

find /home/alice/Documents -maxdepth 1 -type d

For all folders with subfolders:

find /home/alice/Documents -type d

justify-content property isn't working

justify-content only has an effect if there's space left over after your flex items have flexed to absorb the free space. In most/many cases, there won't be any free space left, and indeed justify-content will do nothing.

Some examples where it would have an effect:

  • if your flex items are all inflexible (flex: none or flex: 0 0 auto), and smaller than the container.

  • if your flex items are flexible, BUT can't grow to absorb all the free space, due to a max-width on each of the flexible items.

In both of those cases, justify-content would be in charge of distributing the excess space.

In your example, though, you have flex items that have flex: 1 or flex: 6 with no max-width limitation. Your flexible items will grow to absorb all of the free space, and there will be no space left for justify-content to do anything with.

Java integer list

Let's use some java 8 feature:

IntStream.iterate(10, x -> x + 10).limit(5)
  .forEach(System.out::println);

If you need to store the numbers you can collect them into a collection eg:

List numbers = IntStream.iterate(10, x -> x + 10).limit(5)
  .boxed()
  .collect(Collectors.toList());

And some delay added:

IntStream.iterate(10, x -> x + 10).limit(5)
  .forEach(x -> {
    System.out.println(x);
    try {
      Thread.sleep(2000);
    } catch (InterruptedException e) {
      // Do something with the exception
    }  
  });

Case insensitive comparison of strings in shell script

I came across this great blog/tutorial/whatever about dealing with case sensitive pattern. The following three methods are explained in details with examples:

1. Convert pattern to lowercase using tr command

opt=$( tr '[:upper:]' '[:lower:]' <<<"$1" )
case $opt in
        sql)
                echo "Running mysql backup using mysqldump tool..."
                ;;
        sync)
                echo "Running backup using rsync tool..."
                ;;
        tar)
                echo "Running tape backup using tar tool..."
                ;;
        *)
                echo "Other options"
                ;;
esac

2. Use careful globbing with case patterns

opt=$1
case $opt in
        [Ss][Qq][Ll])
                echo "Running mysql backup using mysqldump tool..."
                ;;
        [Ss][Yy][Nn][Cc])
                echo "Running backup using rsync tool..."
                ;;
        [Tt][Aa][Rr])
                echo "Running tape backup using tar tool..."
                ;;
        *)
                echo "Other option"
                ;;
esac

3. Turn on nocasematch

opt=$1
shopt -s nocasematch
case $opt in
        sql)
                echo "Running mysql backup using mysqldump tool..."
                ;;
        sync)
                echo "Running backup using rsync tool..."
                ;;
        tar)
                echo "Running tape backup using tar tool..."
                ;;
        *)
                echo "Other option"
                ;;
esac

shopt -u nocasematch

Python set to list

You've shadowed the builtin set by accidentally using it as a variable name, here is a simple way to replicate your error

>>> set=set()
>>> set=set()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'set' object is not callable

The first line rebinds set to an instance of set. The second line is trying to call the instance which of course fails.

Here is a less confusing version using different names for each variable. Using a fresh interpreter

>>> a=set()
>>> b=a()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'set' object is not callable

Hopefully it is obvious that calling a is an error

Apache VirtualHost and localhost

It may be because your web folder (as mentioned "/Applications/MAMP/htdocs/mysite/web") is empty.

My suggestion is first to make your project and then work on making the virtual host.

I went with a similar situation. I was using an empty folder in the DocumentRoot in httpd-vhosts.confiz and I couldn't access my shahg101.com site.

Blur the edges of an image or background image with CSS

<html>
<head>
<meta charset="utf-8">
<title>test</title>

<style>
#grad1 {
  height: 400px;
  width: 600px;
  background-image: url(t1.jpg);/* Select Image Hare */
}


#gradup {
  height: 100%;
  width: 100%;
  background: radial-gradient(transparent 20%, white 70%); /* Set radial-gradient to faded edges */

}
</style>

</head>

<body>
<h1>Fade Image Edge With Radial Gradient</h1>

<div id="grad1"><div id="gradup"></div></div>

</body>
</html>

Regex to Match Symbols: !$%^&*()_+|~-=`{}[]:";'<>?,./

Answer

/[\W\S_]/

Explanation

This creates a character class removing the word characters, space characters, and adding back the underscore character (as underscore is a "word" character). All that is left is the special characters. Capital letters represent the negation of their lowercase counterparts.

\W will select all non "word" characters equivalent to [^a-zA-Z0-9_]
\S will select all non "whitespace" characters equivalent to [ \t\n\r\f\v]
_ will select "_" because we negate it when using the \W and need to add it back in

Git Push ERROR: Repository not found

So for me, my password had a ` (tick) in it and PhpStorm was removing the character before sending the git push:

Lets say for this example my password is _pa``ssword_

Phpstorm would output the following:

https://_username_:[email protected]/_username_/repo.git

instead of

https://_username_:_pa``[email protected]/_username_/repo.git

Changed password to something not using the ` character. WORKS!!!

Java Reflection: How to get the name of a variable?

As of Java 8, some local variable name information is available through reflection. See the "Update" section below.

Complete information is often stored in class files. One compile-time optimization is to remove it, saving space (and providing some obsfuscation). However, when it is is present, each method has a local variable table attribute that lists the type and name of local variables, and the range of instructions where they are in scope.

Perhaps a byte-code engineering library like ASM would allow you to inspect this information at runtime. The only reasonable place I can think of for needing this information is in a development tool, and so byte-code engineering is likely to be useful for other purposes too.


Update: Limited support for this was added to Java 8. Parameter (a special class of local variable) names are now available via reflection. Among other purposes, this can help to replace @ParameterName annotations used by dependency injection containers.

Outline radius?

clip-path: circle(100px at center);

This will actually make clickable only circle, while border-radius still makes a square, but looks as circle.

Jquery change background color

The .css() function doesn't queue behind running animations, it's instantaneous.

To match the behaviour that you're after, you'd need to do the following:

$(document).ready(function() {
  $("button").mouseover(function() {
    var p = $("p#44.test").css("background-color", "yellow");
    p.hide(1500).show(1500);
    p.queue(function() {
      p.css("background-color", "red");
    });
  });
});

The .queue() function waits for running animations to run out and then fires whatever's in the supplied function.

how to install apk application from my pc to my mobile android

To install an APK on your mobile, you can either:

  1. Use ADB from the Android SDK, and do the following command: adb install filename.apk. Note, you'll need to enable USB debugging for this to work.
  2. Transfer the file to your device, then open it with a file manager, such as Linda File Manager.

Note, that you'll have to enable installing packages from Unknown Sources in your Applications settings.

As for getting USB to work, I suggest consulting the Android StackExchange for advice.

How to make a copy of an object in C#

Properties in your object are value types and you can use the shallow copy in such situation like that:

obj myobj2 = (obj)myobj.MemberwiseClone();

But in other situations, like if any members are reference types, then you need Deep Copy. You can get a deep copy of an object using Serialization and Deserialization techniques with the help of BinaryFormatter class:

public static T DeepCopy<T>(T other)
{
    using (MemoryStream ms = new MemoryStream())
    {
        BinaryFormatter formatter = new BinaryFormatter();
        formatter.Context = new StreamingContext(StreamingContextStates.Clone);
        formatter.Serialize(ms, other);
        ms.Position = 0;
        return (T)formatter.Deserialize(ms);
    }
}

The purpose of setting StreamingContext: We can introduce special serialization and deserialization logic to our code with the help of either implementing ISerializable interface or using built-in attributes like OnDeserialized, OnDeserializing, OnSerializing, OnSerialized. In all cases StreamingContext will be passed as an argument to the methods(and to the special constructor in case of ISerializable interface). With setting ContextState to Clone, we are just giving hint to that method about the purpose of the serialization.

Additional Info: (you can also read this article from MSDN)

Shallow copying is creating a new object and then copying the nonstatic fields of the current object to the new object. If a field is a value type, a bit-by-bit copy of the field is performed; for a reference type, the reference is copied but the referred object is not; therefore the original object and its clone refer to the same object.

Deep copy is creating a new object and then copying the nonstatic fields of the current object to the new object. If a field is a value type, a bit-by-bit copy of the field is performed. If a field is a reference type, a new copy of the referred object is performed.

ImportError: No module named psycopg2

Recently faced this issue on my production server. I had installed pyscopg2 using

sudo pip install psycopg2

It worked beautifully on my local, but had me for a run on my ec2 server.

sudo python -m pip install psycopg2

The above command worked for me there. Posting here just in case it would help someone in future.

Creating a Zoom Effect on an image on hover using CSS?

  <div class="item">
  <img src="yamahdi1.jpg" alt="pepsi" width="50" height="58">
  <img src="yamahdi.jpg" alt="pepsi" width="50" height="58">
  <div class="item-overlay top"></div>

css:

.item img {

  -moz-transition: all 0.3s;
  -webkit-transition: all 0.3s;
  transition: all 0.3s;
}
.item img:hover {
  -moz-transform: scale(1.1);
  -webkit-transform: scale(1.1);
  transform: scale(1.1);
}

Notepad++ Setting for Disabling Auto-open Previous Files

For versions 6.6+ you need to uncheck "Remember the current session for next launch" on Settings -> Preferences -> Backup.

this is it in 6.6+

For older versions you need to uncheck "Remember the current session for next launch" on Settings -> Preferences.

this is it

Float vs Decimal in ActiveRecord

In Rails 3.2.18, :decimal turns into :integer when using SQLServer, but it works fine in SQLite. Switching to :float solved this issue for us.

The lesson learned is "always use homogeneous development and deployment databases!"

Finding all possible permutations of a given string in python

This is a recursive solution with n! which accepts duplicate elements in the string

import math

def getFactors(root,num):
    sol = []
    # return condition
    if len(num) == 1:
            return [root+num]
    # looping in next iteration
    for i in range(len(num)):  
        # Creating a substring with all remaining char but the taken in this iteration
        if i > 0:
            rem = num[:i]+num[i+1:]
        else:
            rem = num[i+1:]
        # Concatenating existing solutions with the solution of this iteration
        sol = sol + getFactors(root + num[i], rem)
    return sol

I validated the solution taking into account two elements, the number of combinations is n! and the result can not contain duplicates. So:

inpt = "1234"
results = getFactors("",inpt)

if len(results) == math.factorial(len(inpt)) | len(results) != len(set(results)):
    print("Wrong approach")
else:
    print("Correct Approach")

How do I change the background color of the ActionBar of an ActionBarActivity using XML?

When you are Extending Activity use following Code

ActionBar actionbar = getActionBar();
actionbar.setBackgroundDrawable(new ColorDrawable("color"));

When you are Extending AppCompatActivity use following Code

ActionBar actionbar = getSupportActionBar();
actionbar.setBackgroundDrawable(new ColorDrawable("color"));

Is there a way to call a stored procedure with Dapper?

I think the answer depends on which features of stored procedures you need to use.

Stored procedures returning a result set can be run using Query; stored procedures which don't return a result set can be run using Execute - in both cases (using EXEC <procname>) as the SQL command (plus input parameters as necessary). See the documentation for more details.

As of revision 2d128ccdc9a2 there doesn't appear to be native support for OUTPUT parameters; you could add this, or alternatively construct a more complex Query command which declared TSQL variables, executed the SP collecting OUTPUT parameters into the local variables and finallyreturned them in a result set:

DECLARE @output int

EXEC <some stored proc> @i = @output OUTPUT

SELECT @output AS output1

How do I convert a number to a letter in Java?

if you define a/A as 0

char res;
if (i>25 || i<0){
    res = null;
}
    res = (i) + 65
}
return res;

65 for captitals; 97 for non captitals

TortoiseGit-git did not exit cleanly (exit code 1)

Right click -> TortoiseGit -> Settings -> Network
SSH client was pointing to C:\Program Files\TortoiseGit\bin\TortoisePlink.exe
Changed path to C:\Program Files (x86)\Git\bin\ssh.exe

Java Enum Methods - return opposite direction enum

For those lured here by title: yes, you can define your own methods in your enum. If you are wondering how to invoke such non-static method, you do it same way as with any other non-static method - you invoke it on instance of type which defines or inherits that method. In case of enums such instances are simply ENUM_CONSTANTs.

So all you need is EnumType.ENUM_CONSTANT.methodName(arguments).


Now lets go back to problem from question. One of solutions could be

public enum Direction {

    NORTH, SOUTH, EAST, WEST;

    private Direction opposite;

    static {
        NORTH.opposite = SOUTH;
        SOUTH.opposite = NORTH;
        EAST.opposite = WEST;
        WEST.opposite = EAST;
    }

    public Direction getOppositeDirection() {
        return opposite;
    }

}

Now Direction.NORTH.getOppositeDirection() will return Direction.SOUTH.


Here is little more "hacky" way to illustrate @jedwards comment but it doesn't feel as flexible as first approach since adding more fields or changing their order will break our code.

public enum Direction {
    NORTH, EAST, SOUTH, WEST;

    // cached values to avoid recreating such array each time method is called
    private static final Direction[] VALUES = values();

    public Direction getOppositeDirection() {
        return VALUES[(ordinal() + 2) % 4]; 
    }
}

How to change the size of the font of a JLabel to take the maximum size

 JLabel textLabel = new JLabel("<html><span style='font-size:20px'>"+Text+"</span></html>");

Should I use @EJB or @Inject

@Inject can inject any bean, while @EJB can only inject EJBs. You can use either to inject EJBs, but I'd prefer @Inject everywhere.

C# : assign data to properties via constructor vs. instantiating

Both approaches call a constructor, they just call different ones. This code:

var albumData = new Album 
                {
                     Name = "Albumius",
                     Artist = "Artistus",
                     Year = 2013
                };

is syntactic shorthand for this equivalent code:

var albumData = new Album();
albumData.Name = "Albumius";
albumData.Artist = "Artistus";
albumData.Year = 2013;

The two are almost identical after compilation (close enough for nearly all intents and purposes). So if the parameterless constructor wasn't public:

public Album() { }

then you wouldn't be able to use the object initializer at all anyway. So the main question isn't which to use when initializing the object, but which constructor(s) the object exposes in the first place. If the object exposes two constructors (like the one in your example), then one can assume that both ways are equally valid for constructing an object.

Sometimes objects don't expose parameterless constructors because they require certain values for construction. Though in cases like that you can still use the initializer syntax for other values. For example, suppose you have these constructors on your object:

private Album() { }
public Album(string name)
{
    this.Name = name;
}

Since the parameterless constructor is private, you can't use that. But you can use the other one and still make use of the initializer syntax:

var albumData = new Album("Albumius")
                {
                     Artist = "Artistus",
                     Year = 2013
                };

The post-compilation result would then be identical to:

var albumData = new Album("Albumius");
albumData.Artist = "Artistus";
albumData.Year = 2013;

What is the difference between Bower and npm?

Found this useful explanation from http://ng-learn.org/2013/11/Bower-vs-npm/

On one hand npm was created to install modules used in a node.js environment, or development tools built using node.js such Karma, lint, minifiers and so on. npm can install modules locally in a project ( by default in node_modules ) or globally to be used by multiple projects. In large projects the way to specify dependencies is by creating a file called package.json which contains a list of dependencies. That list is recognized by npm when you run npm install, which then downloads and installs them for you.

On the other hand bower was created to manage your frontend dependencies. Libraries like jQuery, AngularJS, underscore, etc. Similar to npm it has a file in which you can specify a list of dependencies called bower.json. In this case your frontend dependencies are installed by running bower install which by default installs them in a folder called bower_components.

As you can see, although they perform a similar task they are targeted to a very different set of libraries.

How can I sort a List alphabetically?

Better late than never! Here is how we can do it(for learning purpose only)-

import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

class SoftDrink {
    String name;
    String color;
    int volume; 

    SoftDrink (String name, String color, int volume) {
        this.name = name;
        this.color = color;
        this.volume = volume;
    }
}

public class ListItemComparision {
    public static void main (String...arg) {
        List<SoftDrink> softDrinkList = new ArrayList<SoftDrink>() ;
        softDrinkList .add(new SoftDrink("Faygo", "ColorOne", 4));
        softDrinkList .add(new SoftDrink("Fanta",  "ColorTwo", 3));
        softDrinkList .add(new SoftDrink("Frooti", "ColorThree", 2));       
        softDrinkList .add(new SoftDrink("Freshie", "ColorFour", 1));

        Collections.sort(softDrinkList, new Comparator() {
            @Override
            public int compare(Object softDrinkOne, Object softDrinkTwo) {
                //use instanceof to verify the references are indeed of the type in question
                return ((SoftDrink)softDrinkOne).name
                        .compareTo(((SoftDrink)softDrinkTwo).name);
            }
        }); 
        for (SoftDrink sd : softDrinkList) {
            System.out.println(sd.name + " - " + sd.color + " - " + sd.volume);
        }
        Collections.sort(softDrinkList, new Comparator() {
            @Override
            public int compare(Object softDrinkOne, Object softDrinkTwo) {
                //comparision for primitive int uses compareTo of the wrapper Integer
                return(new Integer(((SoftDrink)softDrinkOne).volume))
                        .compareTo(((SoftDrink)softDrinkTwo).volume);
            }
        });

        for (SoftDrink sd : softDrinkList) {
            System.out.println(sd.volume + " - " + sd.color + " - " + sd.name);
        }   
    }
}

Java - JPA - @Version annotation

But still I am not sure how it works?

Let's say an entity MyEntity has an annotated version property:

@Entity
public class MyEntity implements Serializable {    

    @Id
    @GeneratedValue
    private Long id;

    private String name;

    @Version
    private Long version;

    //...
}

On update, the field annotated with @Version will be incremented and added to the WHERE clause, something like this:

UPDATE MYENTITY SET ..., VERSION = VERSION + 1 WHERE ((ID = ?) AND (VERSION = ?))

If the WHERE clause fails to match a record (because the same entity has already been updated by another thread), then the persistence provider will throw an OptimisticLockException.

Does it mean that we should declare our version field as final

No but you could consider making the setter protected as you're not supposed to call it.

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

I just stumbled upon this and using @b_stil's snippet, I was able to figure the culprit column. And on futher investigation, I figured i needed to trim the column just like @Liji Chandran suggested but I was using IExcelDataReader and I couldn't figure out an easy way to validate and trim each of my 160 columns.

Then I stumbled upon this class, (ValidatingDataReader) class from CSVReader.

Interesting thing about this class is that it gives you the source and destination columns data length, the culprit row and even the column value that's causing the error.

All I did was just trim all (nvarchar, varchar, char and nchar) columns.

I just changed my GetValue method to this:

 object IDataRecord.GetValue(int i)
    {
        object columnValue = reader.GetValue(i);

        if (i > -1 && i < lookup.Length)
        {
            DataRow columnDef = lookup[i];
            if
            (
                (
                    (string)columnDef["DataTypeName"] == "varchar" ||
                    (string)columnDef["DataTypeName"] == "nvarchar" ||
                    (string)columnDef["DataTypeName"] == "char" ||
                    (string)columnDef["DataTypeName"] == "nchar"
                ) &&
                (
                    columnValue != null &&
                    columnValue != DBNull.Value
                )
            )
            {
                string stringValue = columnValue.ToString().Trim();

                columnValue = stringValue;


                if (stringValue.Length > (int)columnDef["ColumnSize"])
                {
                    string message =
                        "Column value \"" + stringValue.Replace("\"", "\\\"") + "\"" +
                        " with length " + stringValue.Length.ToString("###,##0") +
                        " from source column " + (this as IDataRecord).GetName(i) +
                        " in record " + currentRecord.ToString("###,##0") +
                        " does not fit in destination column " + columnDef["ColumnName"] +
                        " with length " + ((int)columnDef["ColumnSize"]).ToString("###,##0") +
                        " in table " + tableName +
                        " in database " + databaseName +
                        " on server " + serverName + ".";

                    if (ColumnException == null)
                    {
                        throw new Exception(message);
                    }
                    else
                    {
                        ColumnExceptionEventArgs args = new ColumnExceptionEventArgs();

                        args.DataTypeName = (string)columnDef["DataTypeName"];
                        args.DataType = Type.GetType((string)columnDef["DataType"]);
                        args.Value = columnValue;
                        args.SourceIndex = i;
                        args.SourceColumn = reader.GetName(i);
                        args.DestIndex = (int)columnDef["ColumnOrdinal"];
                        args.DestColumn = (string)columnDef["ColumnName"];
                        args.ColumnSize = (int)columnDef["ColumnSize"];
                        args.RecordIndex = currentRecord;
                        args.TableName = tableName;
                        args.DatabaseName = databaseName;
                        args.ServerName = serverName;
                        args.Message = message;

                        ColumnException(args);

                        columnValue = args.Value;
                    }
                }



            }
        }

        return columnValue;
    }

Hope this helps someone

How can I rename column in laravel using migration?

Renaming Columns (Laravel 5.x)

To rename a column, you may use the renameColumn method on the Schema builder. *Before renaming a column, be sure to add the doctrine/dbal dependency to your composer.json file.*

Or you can simply required the package using composer...

composer require doctrine/dbal

Source: https://laravel.com/docs/5.0/schema#renaming-columns

Note: Use make:migration and not migrate:make for Laravel 5.x

How to display a range input slider vertically

_x000D_
_x000D_
window.onload = function(){
var slider = document.getElementById("sss");
 var  result = document.getElementById("final");
slider.oninput = function(){
    result.innerHTML = slider.value ;
}
}
_x000D_
.slider{
    width: 100vw;
    height: 100vh;
   
    display: flex;
    justify-content: center;
    align-items: center;
}

.slider .container-slider{
    width: 600px;
    display: flex;
    justify-content: center;
    align-items: center;
    transform: rotate(90deg)
}

.slider .container-slider input[type="range"]{
    width: 60%;
    -webkit-appearance: none;
    background-color: blue;
    height: 7px;
    border-radius: 5px;;
    outline: none;
    margin: 0 20px
    
}

.slider .container-slider input[type="range"]::-webkit-slider-thumb{
    -webkit-appearance: none;
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background-color: red;
}



.slider .container-slider input[type="range"]::-webkit-slider-thumb:hover{

box-shadow: 0px 0px 10px rgba(255,255,255,.3),
            0px 0px 15px rgba(255,255,255,.4),
            0px 0px 20px rgba(255,255,255,.5),
            0px 0px 25px rgba(255,255,255,.6),
            0px 0px 30px rgba(255,255,255,.7)

}


.slider .container-slider .val {
    width: 60px;
    height: 40px;
    background-color: #ACB6E5;
    display: flex;
    justify-content: center;
    align-items: center;
    font-family: consolas;
    font-weight: 700;
    font-size: 20px;
    letter-spacing: 1.3px;
    transform: rotate(-90deg)
}

.slider .container-slider .val::before{
    content: "";
    position: absolute;
    width: 0;
    height: 0;
    display: block;
    border: 20px solid transparent;
    border-bottom-color: #ACB6E5;
    top: -30px;
}
_x000D_
<div class="slider">
  <div class="container-slider">
    <input type="range" min="0" max="100" step="1" value="" id="sss">
    <div class="val" id="final">0</div>
  </div>
</div>
_x000D_
_x000D_
_x000D_

How to empty/destroy a session in rails?

to delete a user's session

session.delete(:user_id)

How do I convert special UTF-8 chars to their iso-8859-1 equivalent using javascript?

Internally, Javascript strings are all Unicode (actually UCS-2, a subset of UTF-16).

If you're retrieving the JSON files separately via AJAX, then you only need to make sure that the JSON files are served with the correct Content-Type and charset: Content-Type: application/json; charset="utf-8"). If you do that, jQuery should already have interpreted them properly by the time you access the deserialized objects.

Could you post an example of the code you’re using to retrieve the JSON objects?

Changing Font Size For UITableView Section Headers

Swift 4 version of Leo Natan answer is

UILabel.appearance(whenContainedInInstancesOf: [UITableViewHeaderFooterView.self]).font = UIFont.boldSystemFont(ofSize: 28)

If you wanted to set a custom font you could use

if let font = UIFont(name: "font-name", size: 12) {
    UILabel.appearance(whenContainedInInstancesOf: [UITableViewHeaderFooterView.self]).font = font
}

How to create a HTML Cancel button that redirects to a URL

it defaults to submitting a form, easiest way is to add "return false"

<button type="cancel" onclick="window.location='http://stackoverflow.com';return false;">Cancel</button>

Reading and writing environment variables in Python?

If you want to pass global variables into new scripts, you can create a python file that is only meant for holding global variables (e.g. globals.py). When you import this file at the top of the child script, it should have access to all of those variables.

If you are writing to these variables, then that is a different story. That involves concurrency and locking the variables, which I'm not going to get into unless you want.

MySQL: ALTER TABLE if column not exists

hope this will help you

SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'tbl_name'
AND table_schema = 'db_name'
AND column_name = 'column_name'

or

delimiter '//'

CREATE PROCEDURE addcol() BEGIN
IF NOT EXISTS(
SELECT * FROM information_schema.COLUMNS
WHERE COLUMN_NAME='new_column' AND TABLE_NAME='tablename' AND TABLE_SCHEMA='the_schema'
)
THEN
    ALTER TABLE `the_schema`.`the_table`
    ADD COLUMN `new_column` TINYINT(1) NOT NULL DEFAULT 1;;

END IF;
END;
//

delimiter ';'

CALL addcol();

DROP PROCEDURE addcol;

Java Regex Capturing Groups

From the doc :

Capturing groups</a> are indexed from left
 * to right, starting at one.  Group zero denotes the entire pattern, so
 * the expression m.group(0) is equivalent to m.group().

So capture group 0 send the whole line.

The difference between "require(x)" and "import x"

Not an answer here and more like a comment, sorry but I can't comment.

In node V10, you can use the flag --experimental-modules to tell Nodejs you want to use import. But your entry script should end with .mjs.

Note this is still an experimental thing and should not be used in production.

// main.mjs
import utils from './utils.js'
utils.print();
// utils.js
module.exports={
    print:function(){console.log('print called')}
}

Ref 1 - Nodejs Doc

Ref 2 - github issue

Unknown SSL protocol error in connection

I had the same issue, tried all changing SSL settings that are provided here. If you are in the corporate network and ssh keys used in such tools like Gerrit. 1. Get your ssh key, 2. Visit Bitbucket and navigate to Profile >> Settings >> SSH Keys >> Add Key.

After ssh key addition, try to push again.

VBA Public Array : how to?

Declare array as global across subs in a application:

Public GlobalArray(10) as String
GlobalArray = Array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L')

Sub DisplayArray()
    Dim i As Integer

    For i = 0 to UBound(GlobalArray, 1)
        MsgBox GlobalArray(i)

    Next i
End Sub

Method 2: Pass an array to sub. Use ParamArray.

Sub DisplayArray(Name As String, ParamArray Arr() As Variant)
    Dim i As Integer

    For i = 0 To UBound(Arr())
        MsgBox Name & ": " & Arr(i)
    Next i
End Sub

ParamArray must be the last parameter.

How to print the values of slices

If you want to view the information in a slice in the same format that you'd use to type it in (something like ["one", "two", "three"]), here's a code example showing how to do that:

package main

import (
    "fmt"
    "strings"
)

func main() {
    test := []string{"one", "two", "three"}     // The slice of data
    semiformat := fmt.Sprintf("%q\n", test)     // Turn the slice into a string that looks like ["one" "two" "three"]
    tokens := strings.Split(semiformat, " ")    // Split this string by spaces
    fmt.Printf(strings.Join(tokens, ", "))      // Join the Slice together (that was split by spaces) with commas
}

Go Playground

Adding files to java classpath at runtime

You coud try java.net.URLClassloader with the url of the folder/jar where your updated class resides and use it instead of the default classloader when creating a new thread.

Hide separator line on one UITableViewCell

if the accepted answer doesn't work, you can try this:

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01f; }

It's great ;)

Changing every value in a hash in Ruby

In Ruby 2.1 and higher you can do

{ a: 'a', b: 'b' }.map { |k, str| [k, "%#{str}%"] }.to_h

How do I clone into a non-empty directory?

Maybe I misunderstood your question, but wouldn't it be simpler if you copy/move the files from A to the git repo B and add the needed ones with git add?

UPDATE: From the git doc:

Cloning into an existing directory is only allowed if the directory is empty.

SOURCE: http://git-scm.com/docs/git-clone

Best Java obfuscator?

We've had much better luck encrypting the jars rather than obfuscating. We use Classguard.

How to change the application launcher icon on Flutter?

Follow these steps:-

1. Add dependencies of flutter_luncher_icons in pubspec.yaml file.You can find this plugin from here.

2. Add your required images in asstes folder and pubspec.yaml file as below .

pubspec.yaml

name: NewsApi.org
description: A new Flutter application.

# The following line prevents the package from being accidentally published to
# pub.dev using `pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev

https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1

environment:
  sdk: ">=2.7.0 <3.0.0"

dependencies:
  flutter:
      sdk: flutter


  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.1
  fluttertoast: ^7.1.6
  toast: ^0.1.5
  flutter_launcher_icons: ^0.8.0




dev_dependencies:
  flutter_test:
    sdk: flutter

flutter_icons:
  image_path: "assets/icon/newsicon.png"
  android: true
  ios: false

# The following section is specific to Flutter.
flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true
  assets:
    - assets/images/dropbox.png



  fonts:
    - family: LangerReguler
      fonts:
        - asset: assets/langer_reguler.ttf




  # fonts:
  #   - family: Schyler
  #     fonts:
  #       - asset: fonts/Schyler-Regular.ttf
  #       - asset: fonts/Schyler-Italic.ttf
  #         style: italic
  #   - family: Trajan Pro
  #     fonts:
  #       - asset: fonts/TrajanPro.ttf
  #       - asset: fonts/TrajanPro_Bold.ttf
  #         weight: 700
  #
  # For details regarding fonts from package dependencies,
  # see https://flutter.dev/custom-fonts/#from-packages

3. Then run the command in terminal flutter pub get and then flutter_luncher_icon.This is what I get the result after the successfully run the command . And luncher icon is also generated successfully.

My Terminal

[E:\AndroidStudioProjects\FlutterProject\NewsFlutter\news_flutter>flutter pub get
Running "flutter pub get" in news_flutter...                       881ms

E:\AndroidStudioProjects\FlutterProject\NewsFlutter\news_flutter>flutter pub run flutter_launcher_icons:main
  --------------------------------------------
     FLUTTER LAUNCHER ICONS (v0.8.0)
  --------------------------------------------

• Creating default icons Android
• Overwriting the default Android launcher icon with a new icon

? Successfully generated launcher icons

How to extend an existing JavaScript array with another array, without creating a new array

Update 2018: A better answer is a newer one of mine: a.push(...b). Don't upvote this one anymore, as it never really answered the question, but it was a 2015 hack around first-hit-on-Google :)


For those that simply searched for "JavaScript array extend" and got here, you can very well use Array.concat.

var a = [1, 2, 3];
a = a.concat([5, 4, 3]);

Concat will return a copy the new array, as thread starter didn't want. But you might not care (certainly for most kind of uses this will be fine).


There's also some nice ECMAScript 6 sugar for this in the form of the spread operator:

const a = [1, 2, 3];
const b = [...a, 5, 4, 3];

(It also copies.)

How to get GET (query string) variables in Express.js on Node.js?

I learned from the other answers and decided to use this code throughout my site:

var query = require('url').parse(req.url,true).query;

Then you can just call

var id = query.id;
var option = query.option;

where the URL for get should be

/path/filename?id=123&option=456

ld cannot find an existing library

In Ubuntu, you can install libtool which resolves the libraries automatically.

$ sudo apt-get install libtool

This resolved a problem with ltdl for me, which had been installed as libltdl.so.7 and wasn't found as simply -lltdl in the make.

regex to remove all text before a character

no need to do a replacement. the regex will give you what u wanted directly:

"(?<=_)[^_]*\.jpg"

tested with grep:

 echo "3.04_somename.jpg"|grep -oP "(?<=_)[^_]*\.jpg"
somename.jpg

How do I convert seconds to hours, minutes and seconds?

I can hardly name that an easy way (at least I can't remember the syntax), but it is possible to use time.strftime, which gives more control over formatting:

from time import strftime
from time import gmtime

strftime("%H:%M:%S", gmtime(666))
'00:11:06'

strftime("%H:%M:%S", gmtime(60*60*24))
'00:00:00'

gmtime is used to convert seconds to special tuple format that strftime() requires.

Note: Truncates after 23:59:59

Convert Text to Date?

Solved the issue for me :

    Range(Cells(1, 1), Cells(100, 1)).Select

    For Each xCell In Selection

    xCell.Value = CDate(xCell.Value)

    Next xCell

WPF: simple TextBox data binding

Your Window is not implementing the necessary data binding notifications that the grid requires to use it as a data source, namely the INotifyPropertyChanged interface.

Your "Name2" string needs also to be a property and not a public variable, as data binding is for use with properties.

Implementing the necessary interfaces for using an object as a data source can be found here.

How to update a git clone --mirror?

Regarding commits, refs, branches and "et cetera", Magnus answer just works (git remote update).

But unfortunately there is no way to clone / mirror / update the hooks, as I wanted...

I have found this very interesting thread about cloning/mirroring the hooks:

http://kerneltrap.org/mailarchive/git/2007/8/28/256180/thread

I learned:

  • The hooks are not considered part of the repository contents.

  • There is more data, like the .git/description folder, which does not get cloned, just as the hooks.

  • The default hooks that appear in the hooks dir comes from the TEMPLATE_DIR

  • There is this interesting template feature on git.

So, I may either ignore this "clone the hooks thing", or go for a rsync strategy, given the purposes of my mirror (backup + source for other clones, only).

Well... I will just forget about hooks cloning, and stick to the git remote update way.

  • Sehe has just pointed out that not only "hooks" aren't managed by the clone / update process, but also stashes, rerere, etc... So, for a strict backup, rsync or equivalent would really be the way to go. As this is not really necessary in my case (I can afford not having hooks, stashes, and so on), like I said, I will stick to the remote update.

Thanks! Improved a bit of my own "git-fu"... :-)

Parse JSON from HttpURLConnection object

The JSON string will just be the body of the response you get back from the URL you have called. So add this code

...
BufferedReader in = new BufferedReader(new InputStreamReader(
                            conn.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) 
    System.out.println(inputLine);
in.close();

That will allow you to see the JSON being returned to the console. The only missing piece you then have is using a JSON library to read that data and provide you with a Java representation.

Here's an example using JSON-LIB

Merging two arrayLists into a new arrayList, with no duplicates and in order, in Java

Add elements in first arraylist

ArrayList<String> firstArrayList = new ArrayList<String>();

firstArrayList.add("A");
firstArrayList.add("B");
firstArrayList.add("C");
firstArrayList.add("D");
firstArrayList.add("E");

Add elements in second arraylist

ArrayList<String> secondArrayList = new ArrayList<String>();

secondArrayList.add("B");
secondArrayList.add("D");
secondArrayList.add("F");
secondArrayList.add("G");

Add first arraylist's elements in second arraylist

secondArrayList.addAll(firstArrayList);

Assign new combine arraylist and add all elements from both arraylists

ArrayList<String> comboArrayList = new ArrayList<String>(firstArrayList);
comboArrayList.addAll(secondArrayList);

Assign new Set for remove duplicate entries from arraylist

Set<String> setList = new LinkedHashSet<String>(comboArrayList);
comboArrayList.clear();
comboArrayList.addAll(setList);

Sorting arraylist

Collections.sort(comboArrayList);

Output

 A
 B
 C
 D
 E
 F
 G

Reportviewer tool missing in visual studio 2017 RC

Update: this answer works with both ,Visual Sudio 2017 and 2019

For me it worked by the following three steps:

  1. Updating Visual Studio to the latest build.
  2. Adding Report / Report Wizard to the Add/New Item menu by:
    • Going to Visual Studio menu Tools/Extensions and Updates
    • Choose Online from the left panel.
    • Search for Microsoft Rdlc Report Designer for Visual Studio
    • Download and install it.
  3. Adding Report viewer control by:

    • Going to NuGet Package Manager.

    • Installing Microsoft.ReportingServices.ReportViewerControl.Winforms

    • Go to the folder that contains Microsoft.ReportViewer.WinForms.dll: %USERPROFILE%\.nuget\packages\microsoft.reportingservices.reportviewercontrol.winforms\140.1000.523\lib\net40
    • Drag the Microsoft.ReportViewer.WinForms.dll file and drop it at Visual Studio Toolbox Window.

For WebForms applications:

  1. The same.
  2. The same.
  3. Adding Report viewer control by:

    • Going to NuGet Package Manager.

    • Installing Microsoft.ReportingServices.ReportViewerControl.WebForms

    • Go to the folder that contains Microsoft.ReportViewer.WebForms.dll file: %USERPROFILE%\.nuget\packages\microsoft.reportingservices.reportviewercontrol.webforms\140.1000.523\lib\net40
    • Drag the Microsoft.ReportViewer.WebForms.dll file and drop it at Visual Studio Toolbox Window.

That's all!

How to debug in Django, the good way?

As mentioned in other posts here - setting breakpoints in your code and walking thru the code to see if it behaves as you expected is a great way to learn something like Django until you have a good sense of how it all behaves - and what your code is doing.

To do this I would recommend using WingIde. Just like other mentioned IDEs nice and easy to use, nice layout and also easy to set breakpoints evaluate / modify the stack etc. Perfect for visualizing what your code is doing as you step through it. I'm a big fan of it.

Also I use PyCharm - it has excellent static code analysis and can help sometimes spot problems before you realize they are there.

As mentioned already django-debug-toolbar is essential - https://github.com/django-debug-toolbar/django-debug-toolbar

And while not explicitly a debug or analysis tool - one of my favorites is SQL Printing Middleware available from Django Snippets at https://djangosnippets.org/snippets/290/

This will display the SQL queries that your view has generated. This will give you a good sense of what the ORM is doing and if your queries are efficient or you need to rework your code (or add caching).

I find it invaluable for keeping an eye on query performance while developing and debugging my application.

Just one other tip - I modified it slightly for my own use to only show the summary and not the SQL statement.... So I always use it while developing and testing. I also added that if the len(connection.queries) is greater than a pre-defined threshold it displays an extra warning.

Then if I spot something bad (from a performance or number of queries perspective) is happening I turn back on the full display of the SQL statements to see exactly what is going on. Very handy when you are working on a large Django project with multiple developers.

How to do something before on submit?

You can use onclick to run some JavaScript or jQuery code before submitting the form like this:

<script type="text/javascript">
    beforeSubmit = function(){
        if (1 == 1){
            //your before submit logic
        }        
        $("#formid").submit();            
    }
</script>
<input type="button" value="Click" onclick="beforeSubmit();" />

What is the equivalent of Java's System.out.println() in Javascript?

I'm using Chrome and print() literally prints the text on paper. This is what works for me:

document.write("My message");

How to install Java SDK on CentOS?

enter image description here

This is what I did:

  1. First, I downloaded the .tar file for Java JDK and JRE from the Oracle site.

  2. Extract the .tar file into the opt folder.

  3. I faced an issue that despite setting my environment variables, JAVA_HOME and PATH for Java 9, it was still showing Java 8 as my runtime environment. Hence, I symlinked from the Java 9.0.4 directory to /user/bin using the ln command.

  4. I used java -version command to check which version of java is currently set as my default java runtime environment.

Android Pop-up message

sample code show custom dialog in kotlin:

fun showDlgFurtherDetails(context: Context,title: String?, details: String?) {

    val dialog = Dialog(context)
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
    dialog.setCancelable(false)
    dialog.setContentView(R.layout.dlg_further_details)
    dialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
    val lblService = dialog.findViewById(R.id.lblService) as TextView
    val lblDetails = dialog.findViewById(R.id.lblDetails) as TextView
    val imgCloseDlg = dialog.findViewById(R.id.imgCloseDlg) as ImageView

    lblService.text = title
    lblDetails.text = details
    lblDetails.movementMethod = ScrollingMovementMethod()
    lblDetails.isScrollbarFadingEnabled = false
    imgCloseDlg.setOnClickListener {
        dialog.dismiss()
    }
    dialog.show()
}

Rename multiple files based on pattern in Unix

Generic command would be

find /path/to/files -name '<search>*' -exec bash -c 'mv $0 ${0/<search>/<replace>}' {} \;

where <search> and <replace> should be replaced with your source and target respectively.

As a more specific example tailored to your problem (should be run from the same folder where your files are), the above command would look like:

find . -name 'gfh*' -exec bash -c 'mv $0 ${0/gfh/jkl}' {} \;

For a "dry run" add echo before mv, so that you'd see what commands are generated:

find . -name 'gfh*' -exec bash -c 'echo mv $0 ${0/gfh/jkl}' {} \;

Installing Apple's Network Link Conditioner Tool

For Xcode 8 you gotta download a package named Additional Tools for Xcode 8

For other versions (8.1, 8.2) get the package here

Double click and open the dmg and go to Hardware directory. Double click on Network Link Conditioner.prefPane.

enter image description here

Click on install

enter image description here

Now Network Link Conditioner will be available in System Preferences.

For versions older than Xcode 8, the package to be downloaded is called Hardware IO Tools for Xcode. Get it from this page

Git: how to reverse-merge a commit?

To revert a merge commit, you need to use: git revert -m <parent number>. So for example, to revert the recent most merge commit using the parent with number 1 you would use:

git revert -m 1 HEAD

To revert a merge commit before the last commit, you would do:

git revert -m 1 HEAD^

Use git show <merge commit SHA1> to see the parents, the numbering is the order they appear e.g. Merge: e4c54b3 4725ad2

git merge documentation: http://schacon.github.com/git/git-merge.html

git merge discussion (confusing but very detailed): http://schacon.github.com/git/howto/revert-a-faulty-merge.txt

Ctrl+click doesn't work in Eclipse Juno

I can confirm that Ctrl + click works fine with the following :

Eclipse Java EE IDE for Web Developers.
Version: Juno Release
Build id: 20120606-2254
Operating System : Windows 7, 64 Bit

What do you have for the following preference ?

On Window -> Preferences -> General -> Editors -> Text Editors -> Hyperlinking -> Open Declaration

Here is what I had for a new workspace in Juno :

enter image description here

Update

I have not experienced this in the recent past, but I vaguely remember encountering this problem in previous Eclipse releases (Galileo and earlier).

All of what follows is worth doing only if we are sure that it's a problem with the Eclipse workspace. A quick way of checking this is to restart eclipse with a new workspace (Do this by going to File -> Switch Workspace -> Other... and choosing the path to a folder which is preferably empty and different than the current workspace folder).

If things worked in the new workspace, my fix then was one of the following, in increasing order extremeness :

  1. Re-start eclipse (Yup, sometimes that is all it took)
  2. Re-start eclipse with the -clean parameter to clean out the workspace ( See this). This might specially be worth doing if you used a workspace from an older version of eclipse.
  3. When the above failed, and I just had to use my existing workspace, I backed up my workspace folder and restarted Eclipse after deleting WORKSPACE_FOLDER/.metadata/.plugins/org.eclipse.jdt.core

HTML Upload MAX_FILE_SIZE does not appear to work

MAX_FILE_SIZE is in KB not bytes. You were right, it is in bytes. So, for a limit of 4MB convert 4MB in bytes {1024 * (1024 * 4)} try:

<input type="hidden" name="MAX_FILE_SIZE" value="4194304" /> 

enter image description here

Update 1

As explained by others, you will never get a warning for this. It's there just to impose a soft limit on server side.

Update 2

To answer your sub-question. Yes, there is a difference, you NEVER trust the user input. If you want to always impose a limit, you always must check its size. Don't trust what MAX_FILE_SIZE does, because it can be changed by a user. So, yes, you should check to make sure it's always up to or above the size you want it to be.

The difference is that if you have imposed a MAX_FILE_SIZE of 2MB and the user tries to upload a 4MB file, once they reach roughly the first 2MB of upload, the transfer will terminate and the PHP will stop accepting more data for that file. It will report the error on the files array.

How to set Java classpath in Linux?

export CLASSPATH=/home/appnetix/LOG4J_HOME/log4j-1.2.16.jar

or, if you already have some classpath set

export CLASSPATH=$CLASSPATH:/home/appnetix/LOG4J_HOME/log4j-1.2.16.jar

and, if also you want to include current directory

export CLASSPATH=$CLASSPATH:/home/appnetix/LOG4J_HOME/log4j-1.2.16.jar:.

Writing BMP image in pure c/c++ without other libraries

Note that the lines are saved from down to up and not the other way around.

Additionally, the scanlines must have a byte-length of multiples of four, you should insert fill bytes at the end of the lines to ensure this.

Linker error: "linker input file unused because linking not done", undefined reference to a function in that file

I think you are confused about how the compiler puts things together. When you use -c flag, i.e. no linking is done, the input is C++ code, and the output is object code. The .o files thus don't mix with -c, and compiler warns you about that. Symbols from object file are not moved to other object files like that.

All object files should be on the final linker invocation, which is not the case here, so linker (called via g++ front-end) complains about missing symbols.

Here's a small example (calling g++ explicitly for clarity):

PROG ?= myprog
OBJS = worker.o main.o

all: $(PROG)

.cpp.o:
        g++ -Wall -pedantic -ggdb -O2 -c -o $@ $<

$(PROG): $(OBJS)
        g++ -Wall -pedantic -ggdb -O2 -o $@ $(OBJS)

There's also makedepend utility that comes with X11 - helps a lot with source code dependencies. You might also want to look at the -M gcc option for building make rules.

Prefer composition over inheritance?

Think of containment as a has a relationship. A car "has an" engine, a person "has a" name, etc.

Think of inheritance as an is a relationship. A car "is a" vehicle, a person "is a" mammal, etc.

I take no credit for this approach. I took it straight from the Second Edition of Code Complete by Steve McConnell, Section 6.3.

How to highlight a current menu item?

$scope.getClass = function (path) {
return String(($location.absUrl().split('?')[0]).indexOf(path)) > -1 ? 'active' : ''
}


<li class="listing-head" ng-class="getClass('/v/bookings')"><a href="/v/bookings">MY BOOKING</a></li>
<li class="listing-head" ng-class="getClass('/v/fleets')"><a href="/v/fleets">MY FLEET</a></li>
<li class="listing-head" ng-class="getClass('/v/adddriver')"><a href="/v/adddriver">ADD DRIVER</a></li>
<li class="listing-head" ng-class="getClass('/v/bookings')"><a href="/v/invoice">INVOICE</a></li>
<li class="listing-head" ng-class="getClass('/v/profile')"><a href="/v/profile">MY PROFILE</a></li>
<li class="listing-head"><a href="/v/logout">LOG OUT</a></li>

Getting value from appsettings.json in .net core

Just create An AnyName.cs file and paste following code.

using System;
using System.IO;
using Microsoft.Extensions.Configuration;

namespace Custom
{
    static class ConfigurationManager
    {
        public static IConfiguration AppSetting { get; }
        static ConfigurationManager()
        {
            AppSetting = new ConfigurationBuilder()
                    .SetBasePath(Directory.GetCurrentDirectory())
                    .AddJsonFile("YouAppSettingFile.json")
                    .Build();
        }
    }
}

Must replace YouAppSettingFile.json file name with your file name.
Your .json file should look like below.

{
    "GrandParent_Key" : {
        "Parent_Key" : {
            "Child_Key" : "value1"
        }
    },
    "Parent_Key" : {
        "Child_Key" : "value2"
    },
    "Child_Key" : "value3"
}

Now you can use it.
Don't forget to Add Reference in your class where you want to use.

using Custom;

Code to retrieve value.

string value1 = ConfigurationManager.AppSetting["GrandParent_Key:Parent_Key:Child_Key"];
string value2 = ConfigurationManager.AppSetting["Parent_Key:Child_Key"];
string value3 = ConfigurationManager.AppSetting["Child_Key"];

Design DFA accepting binary strings divisible by a number 'n'

Below, I have written an answer for n equals to 5, but you can apply same approach to draw DFAs for any value of n and 'any positional number system' e.g binary, ternary...

First lean the term 'Complete DFA', A DFA defined on complete domain in d:Q × S?Q is called 'Complete DFA'. In other words we can say; in transition diagram of complete DFA there is no missing edge (e.g. from each state in Q there is one outgoing edge present for every language symbol in S). Note: Sometime we define partial DFA as d ? Q × S?Q (Read: How does “d:Q × S?Q” read in the definition of a DFA).

Design DFA accepting Binary numbers divisible by number 'n':

Step-1: When you divide a number ? by n then reminder can be either 0, 1, ..., (n - 2) or (n - 1). If remainder is 0 that means ? is divisible by n otherwise not. So, in my DFA there will be a state qr that would be corresponding to a remainder value r, where 0 <= r <= (n - 1), and total number of states in DFA is n.
After processing a number string ? over S, the end state is qr implies that ? % n => r (% reminder operator).

In any automata, the purpose of a state is like memory element. A state in an atomata stores some information like fan's switch that can tell whether the fan is in 'off' or in 'on' state. For n = 5, five states in DFA corresponding to five reminder information as follows:

  1. State q0 reached if reminder is 0. State q0 is the final state(accepting state). It is also an initial state.
  2. State q1 reaches if reminder is 1, a non-final state.
  3. State q2 if reminder is 2, a non-final state.
  4. State q3 if reminder is 3, a non-final state.
  5. State q4 if reminder is 4, a non-final state.

Using above information, we can start drawing transition diagram TD of five states as follows:

fig-1
Figure-1

So, 5 states for 5 remainder values. After processing a string ? if end-state becomes q0 that means decimal equivalent of input string is divisible by 5. In above figure q0 is marked final state as two concentric circle.
Additionally, I have defined a transition rule d:(q0, 0)?q0 as a self loop for symbol '0' at state q0, this is because decimal equivalent of any string consist of only '0' is 0 and 0 is a divisible by n.

Step-2: TD above is incomplete; and can only process strings of '0's. Now add some more edges so that it can process subsequent number's strings. Check table below, shows new transition rules those can be added next step:

+-------------------------------------+
¦Number¦Binary¦Remainder(%5)¦End-state¦
+------+------+-------------+---------¦
¦One   ¦1     ¦1            ¦q1       ¦
+------+------+-------------+---------¦
¦Two   ¦10    ¦2            ¦q2       ¦
+------+------+-------------+---------¦
¦Three ¦11    ¦3            ¦q3       ¦
+------+------+-------------+---------¦
¦Four  ¦100   ¦4            ¦q4       ¦
+-------------------------------------+
  1. To process binary string '1' there should be a transition rule d:(q0, 1)?q1
  2. Two:- binary representation is '10', end-state should be q2, and to process '10', we just need to add one more transition rule d:(q1, 0)?q2
    Path: ?(q0)-1?(q1)-0?(q2)
  3. Three:- in binary it is '11', end-state is q3, and we need to add a transition rule d:(q1, 1)?q3
    Path: ?(q0)-1?(q1)-1?(q3)
  4. Four:- in binary '100', end-state is q4. TD already processes prefix string '10' and we just need to add a new transition rule d:(q2, 0)?q4
    Path: ?(q0)-1?(q1)-0?(q2)-0?(q4)

fig-2 Figure-2

Step-3: Five = 101
Above transition diagram in figure-2 is still incomplete and there are many missing edges, for an example no transition is defined for d:(q2, 1)-?. And the rule should be present to process strings like '101'.
Because '101' = 5 is divisible by 5, and to accept '101' I will add d:(q2, 1)?q0 in above figure-2.
Path: ?(q0)-1?(q1)-0?(q2)-1?(q0)
with this new rule, transition diagram becomes as follows:

fig-3 Figure-3

Below in each step I pick next subsequent binary number to add a missing edge until I get TD as a 'complete DFA'.

Step-4: Six = 110.

We can process '11' in present TD in figure-3 as: ?(q0)-11?(q3) -0?(?). Because 6 % 5 = 1 this means to add one rule d:(q3, 0)?q1.

fig-4 Figure-4

Step-5: Seven = 111

+--------------------------------------------------------------+
¦Number¦Binary¦Remainder(%5)¦End-state¦ Path       ¦ Add       ¦
+------+------+-------------+---------+------------+-----------¦
¦Seven ¦111   ¦7 % 5 = 2    ¦q2       ¦ q0-11?q3   ¦ q3-1?q2    ¦
+--------------------------------------------------------------+

fig-5 Figure-5

Step-6: Eight = 1000

+----------------------------------------------------------+
¦Number¦Binary¦Remainder(%5)¦End-state¦ Path     ¦ Add     ¦
+------+------+-------------+---------+----------+---------¦
¦Eight ¦1000  ¦8 % 5 = 3    ¦q3       ¦q0-100?q4 ¦ q4-0?q3  ¦
+----------------------------------------------------------+

fig-6 Figure-6

Step-7: Nine = 1001

+----------------------------------------------------------+
¦Number¦Binary¦Remainder(%5)¦End-state¦ Path     ¦ Add     ¦
+------+------+-------------+---------+----------+---------¦
¦Nine  ¦1001  ¦9 % 5 = 4    ¦q4       ¦q0-100?q4 ¦ q4-1?q4  ¦
+----------------------------------------------------------+

fig-7 Figure-7

In TD-7, total number of edges are 10 == Q × S = 5 × 2. And it is a complete DFA that can accept all possible binary strings those decimal equivalent is divisible by 5.

Design DFA accepting Ternary numbers divisible by number n:

Step-1 Exactly same as for binary, use figure-1.

Step-2 Add Zero, One, Two

+------------------------------------------------------+
¦Decimal¦Ternary¦Remainder(%5)¦End-state¦   Add        ¦
+-------+-------+-------------+---------+--------------¦
¦Zero   ¦0      ¦0            ¦q0       ¦ d:(q0,0)?q0  ¦
+-------+-------+-------------+---------+--------------¦
¦One    ¦1      ¦1            ¦q1       ¦ d:(q0,1)?q1  ¦
+-------+-------+-------------+---------+--------------¦
¦Two    ¦2      ¦2            ¦q2       ¦ d:(q0,2)?q3  ¦
+------------------------------------------------------+

fig-8
Figure-8

Step-3 Add Three, Four, Five

+-----------------------------------------------------+
¦Decimal¦Ternary¦Remainder(%5)¦End-state¦  Add        ¦
+-------+-------+-------------+---------+-------------¦
¦Three  ¦10     ¦3            ¦q3       ¦ d:(q1,0)?q3 ¦
+-------+-------+-------------+---------+-------------¦
¦Four   ¦11     ¦4            ¦q4       ¦ d:(q1,1)?q4 ¦
+-------+-------+-------------+---------+-------------¦
¦Five   ¦12     ¦0            ¦q0       ¦ d:(q1,2)?q0 ¦
+-----------------------------------------------------+

fig-9
Figure-9

Step-4 Add Six, Seven, Eight

+-----------------------------------------------------+
¦Decimal¦Ternary¦Remainder(%5)¦End-state¦  Add        ¦
+-------+-------+-------------+---------+-------------¦
¦Six    ¦20     ¦1            ¦q1       ¦ d:(q2,0)?q1 ¦
+-------+-------+-------------+---------+-------------¦
¦Seven  ¦21     ¦2            ¦q2       ¦ d:(q2,1)?q2 ¦
+-------+-------+-------------+---------+-------------¦
¦Eight  ¦22     ¦3            ¦q3       ¦ d:(q2,2)?q3 ¦
+-----------------------------------------------------+

fig-10
Figure-10

Step-5 Add Nine, Ten, Eleven

+-----------------------------------------------------+
¦Decimal¦Ternary¦Remainder(%5)¦End-state¦  Add        ¦
+-------+-------+-------------+---------+-------------¦
¦Nine   ¦100    ¦4            ¦q4       ¦ d:(q3,0)?q4 ¦
+-------+-------+-------------+---------+-------------¦
¦Ten    ¦101    ¦0            ¦q0       ¦ d:(q3,1)?q0 ¦
+-------+-------+-------------+---------+-------------¦
¦Eleven ¦102    ¦1            ¦q1       ¦ d:(q3,2)?q1 ¦
+-----------------------------------------------------+

fig-11
Figure-11

Step-6 Add Twelve, Thirteen, Fourteen

+------------------------------------------------------+
¦Decimal ¦Ternary¦Remainder(%5)¦End-state¦  Add        ¦
+--------+-------+-------------+---------+-------------¦
¦Twelve  ¦110    ¦2            ¦q2       ¦ d:(q4,0)?q2 ¦
+--------+-------+-------------+---------+-------------¦
¦Thirteen¦111    ¦3            ¦q3       ¦ d:(q4,1)?q3 ¦
+--------+-------+-------------+---------+-------------¦
¦Fourteen¦112    ¦4            ¦q4       ¦ d:(q4,2)?q4 ¦
+------------------------------------------------------+

fig-12
Figure-12

Total number of edges in transition diagram figure-12 are 15 = Q × S = 5 * 3 (a complete DFA). And this DFA can accept all strings consist over {0, 1, 2} those decimal equivalent is divisible by 5.
If you notice at each step, in table there are three entries because at each step I add all possible outgoing edge from a state to make a complete DFA (and I add an edge so that qr state gets for remainder is r)!

To add further, remember union of two regular languages are also a regular. If you need to design a DFA that accepts binary strings those decimal equivalent is either divisible by 3 or 5, then draw two separate DFAs for divisible by 3 and 5 then union both DFAs to construct target DFA (for 1 <= n <= 10 your have to union 10 DFAs).

If you are asked to draw DFA that accepts binary strings such that decimal equivalent is divisible by 5 and 3 both then you are looking for DFA of divisible by 15 ( but what about 6 and 8?).

Note: DFAs drawn with this technique will be minimized DFA only when there is no common factor between number n and base e.g. there is no between 5 and 2 in first example, or between 5 and 3 in second example, hence both DFAs constructed above are minimized DFAs. If you are interested to read further about possible mini states for number n and base b read paper: Divisibility and State Complexity.

below I have added a Python script, I written it for fun while learning Python library pygraphviz. I am adding it I hope it can be helpful for someone in someway.

Design DFA for base 'b' number strings divisible by number 'n':

So we can apply above trick to draw DFA to recognize number strings in any base 'b' those are divisible a given number 'n'. In that DFA total number of states will be n (for n remainders) and number of edges should be equal to 'b' * 'n' — that is complete DFA: 'b' = number of symbols in language of DFA and 'n' = number of states.

Using above trick, below I have written a Python Script to Draw DFA for input base and number. In script, function divided_by_N populates DFA's transition rules in base * number steps. In each step-num, I convert num into number string num_s using function baseN(). To avoid processing each number string, I have used a temporary data-structure lookup_table. In each step, end-state for number string num_s is evaluated and stored in lookup_table to use in next step.

For transition graph of DFA, I have written a function draw_transition_graph using Pygraphviz library (very easy to use). To use this script you need to install graphviz. To add colorful edges in transition diagram, I randomly generates color codes for each symbol get_color_dict function.

#!/usr/bin/env python
import pygraphviz as pgv
from pprint import pprint
from random import choice as rchoice

def baseN(n, b, syms="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"):
    """ converts a number `n` into base `b` string """
    return ((n == 0) and syms[0]) or (
        baseN(n//b, b, syms).lstrip(syms[0]) + syms[n % b])

def divided_by_N(number, base):
    """
    constructs DFA that accepts given `base` number strings
    those are divisible by a given `number`
    """
    ACCEPTING_STATE = START_STATE = '0'
    SYMBOL_0 = '0'
    dfa = {
        str(from_state): {
            str(symbol): 'to_state' for symbol in range(base)
        }
        for from_state in range(number)
    }
    dfa[START_STATE][SYMBOL_0] = ACCEPTING_STATE
    # `lookup_table` keeps track: 'number string' -->[dfa]--> 'end_state'
    lookup_table = { SYMBOL_0: ACCEPTING_STATE }.setdefault
    for num in range(number * base):
        end_state = str(num % number)
        num_s = baseN(num, base)
        before_end_state = lookup_table(num_s[:-1], START_STATE)
        dfa[before_end_state][num_s[-1]] = end_state
        lookup_table(num_s, end_state)
    return dfa

def symcolrhexcodes(symbols):
    """
    returns dict of color codes mapped with alphabets symbol in symbols
    """
    return {
        symbol: '#'+''.join([
            rchoice("8A6C2B590D1F4E37") for _ in "FFFFFF"
        ])
        for symbol in symbols
    }

def draw_transition_graph(dfa, filename="filename"):
    ACCEPTING_STATE = START_STATE = '0'
    colors = symcolrhexcodes(dfa[START_STATE].keys())
    # draw transition graph
    tg = pgv.AGraph(strict=False, directed=True, decorate=True)
    for from_state in dfa:
        for symbol, to_state in dfa[from_state].iteritems():
            tg.add_edge("Q%s"%from_state, "Q%s"%to_state,
                        label=symbol, color=colors[symbol],
                        fontcolor=colors[symbol])

    # add intial edge from an invisible node!
    tg.add_node('null', shape='plaintext', label='start')
    tg.add_edge('null', "Q%s"%START_STATE,)

    # make end acception state as 'doublecircle'
    tg.get_node("Q%s"%ACCEPTING_STATE).attr['shape'] = 'doublecircle'
    tg.draw(filename, prog='circo')
    tg.close()

def print_transition_table(dfa):
    print("DFA accepting number string in base '%(base)s' "
            "those are divisible by '%(number)s':" % {
                'base': len(dfa['0']),
                'number': len(dfa),})
    pprint(dfa)

if __name__ == "__main__":
    number = input ("Enter NUMBER: ")
    base = input ("Enter BASE of number system: ")
    dfa = divided_by_N(number, base)

    print_transition_table(dfa)
    draw_transition_graph(dfa)

Execute it:

~/study/divide-5/script$ python script.py 
Enter NUMBER: 5
Enter BASE of number system: 4
DFA accepting number string in base '4' those are divisible by '5':
{'0': {'0': '0', '1': '1', '2': '2', '3': '3'},
 '1': {'0': '4', '1': '0', '2': '1', '3': '2'},
 '2': {'0': '3', '1': '4', '2': '0', '3': '1'},
 '3': {'0': '2', '1': '3', '2': '4', '3': '0'},
 '4': {'0': '1', '1': '2', '2': '3', '3': '4'}}
~/study/divide-5/script$ ls
script.py filename.png
~/study/divide-5/script$ display filename

Output:

base_4_divided_5_best
DFA accepting number strings in base 4 those are divisible by 5

Similarly, enter base = 4 and number = 7 to generate - dfa accepting number string in base '4' those are divisible by '7'
Btw, try changing filename to .png or .jpeg.

References those I use to write this script:
➊ Function baseN from "convert integer to a string in a given numeric base in python"
➋ To install "pygraphviz": "Python does not see pygraphviz"
➌ To learn use of Pygraphviz: "Python-FSM"
➍ To generate random hex color codes for each language symbol: "How would I make a random hexdigit code generator using .join and for loops?"

window.onload vs <body onload=""/>

They both work the same. However, note that if both are defined, only one of them will be invoked. I generally avoid using either of them directly. Instead, you can attach an event handler to the load event. This way you can incorporate more easily other JS packages which might also need to attach a callback to the onload event.

Any JS framework will have cross-browser methods for event handlers.

turn typescript object into json string

TS gets compiled to JS which then executed. Therefore you have access to all of the objects in the JS runtime. One of those objects is the JSON object. This contains the following methods:

  • JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string.
  • JSON.stringify() method converts a JavaScript object or value to a JSON string.

Example:

_x000D_
_x000D_
const jsonString = '{"employee":{ "name":"John", "age":30, "city":"New York" }}';_x000D_
_x000D_
_x000D_
const JSobj = JSON.parse(jsonString);_x000D_
_x000D_
console.log(JSobj);_x000D_
console.log(typeof JSobj);_x000D_
_x000D_
const JSON_string = JSON.stringify(JSobj);_x000D_
_x000D_
console.log(JSON_string);_x000D_
console.log(typeof JSON_string);
_x000D_
_x000D_
_x000D_

Difference between Java SE/EE/ME?

As I come across this question, I found the information provided on the Oracle's tutorial very complete and worth to share:

The Java Programming Language Platforms

There are four platforms of the Java programming language:

  • Java Platform, Standard Edition (Java SE)

  • Java Platform, Enterprise Edition (Java EE)

  • Java Platform, Micro Edition (Java ME)

  • JavaFX

All Java platforms consist of a Java Virtual Machine (VM) and an application programming interface (API). The Java Virtual Machine is a program, for a particular hardware and software platform, that runs Java technology applications. An API is a collection of software components that you can use to create other software components or applications. Each Java platform provides a virtual machine and an API, and this allows applications written for that platform to run on any compatible system with all the advantages of the Java programming language: platform-independence, power, stability, ease-of-development, and security.

Java SE

When most people think of the Java programming language, they think of the Java SE API. Java SE's API provides the core functionality of the Java programming language. It defines everything from the basic types and objects of the Java programming language to high-level classes that are used for networking, security, database access, graphical user interface (GUI) development, and XML parsing.

In addition to the core API, the Java SE platform consists of a virtual machine, development tools, deployment technologies, and other class libraries and toolkits commonly used in Java technology applications.

Java EE

The Java EE platform is built on top of the Java SE platform. The Java EE platform provides an API and runtime environment for developing and running large-scale, multi-tiered, scalable, reliable, and secure network applications.

Java ME

The Java ME platform provides an API and a small-footprint virtual machine for running Java programming language applications on small devices, like mobile phones. The API is a subset of the Java SE API, along with special class libraries useful for small device application development. Java ME applications are often clients of Java EE platform services.

JavaFX

JavaFX is a platform for creating rich internet applications using a lightweight user-interface API. JavaFX applications use hardware-accelerated graphics and media engines to take advantage of higher-performance clients and a modern look-and-feel as well as high-level APIs for connecting to networked data sources. JavaFX applications may be clients of Java EE platform services.

What are .tpl files? PHP, web design

Templates. I think that is Smarty syntax.

Python threading. How do I lock a thread?

You can see that your locks are pretty much working as you are using them, if you slow down the process and make them block a bit more. You had the right idea, where you surround critical pieces of code with the lock. Here is a small adjustment to your example to show you how each waits on the other to release the lock.

import threading
import time
import inspect

class Thread(threading.Thread):
    def __init__(self, t, *args):
        threading.Thread.__init__(self, target=t, args=args)
        self.start()

count = 0
lock = threading.Lock()

def incre():
    global count
    caller = inspect.getouterframes(inspect.currentframe())[1][3]
    print "Inside %s()" % caller
    print "Acquiring lock"
    with lock:
        print "Lock Acquired"
        count += 1  
        time.sleep(2)  

def bye():
    while count < 5:
        incre()

def hello_there():
    while count < 5:
        incre()

def main():    
    hello = Thread(hello_there)
    goodbye = Thread(bye)


if __name__ == '__main__':
    main()

Sample output:

...
Inside hello_there()
Acquiring lock
Lock Acquired
Inside bye()
Acquiring lock
Lock Acquired
...

How to load up CSS files using Javascript?

If you use jquery:

$('head').append('<link rel="stylesheet" type="text/css" href="style.css">');

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

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

get current url in twig template?

{{ path(app.request.attributes.get('_route'),
     app.request.attributes.get('_route_params')) }}

If you want to read it into a view variable:

{% set currentPath = path(app.request.attributes.get('_route'),
                       app.request.attributes.get('_route_params')) %}

The app global view variable contains all sorts of useful shortcuts, such as app.session and app.security.token.user, that reference the services you might use in a controller.

JavaScript global event mechanism

sophisticated error handling

If your error handling is very sophisticated and therefore might throw an error itself, it is useful to add a flag indicating if you are already in "errorHandling-Mode". Like so:

var appIsHandlingError = false;

window.onerror = function() {
    if (!appIsHandlingError) {
        appIsHandlingError = true;
        handleError();
    }
};

function handleError() {
    // graceful error handling
    // if successful: appIsHandlingError = false;
}

Otherwise you could find yourself in an infinite loop.

Add string in a certain position in Python

If you want many inserts

from rope.base.codeanalyze import ChangeCollector

c = ChangeCollector(code)
c.add_change(5, 5, '<span style="background-color:#339999;">')
c.add_change(10, 10, '</span>')
rend_code = c.get_changed()

How to transform array to comma separated words string?

You're looking for implode()

$string = implode(",", $array);

Where is HttpContent.ReadAsAsync?

Just right click in your project go Manage NuGet Packages search for Microsoft.AspNet.WebApi.Client install it and you will have access to the extension method.

Executing a stored procedure within a stored procedure

Inline Stored procedure we using as per our need. Example like different Same parameter with different values we have to use in queries..

Create Proc SP1
(
 @ID int,
 @Name varchar(40)
 -- etc parameter list, If you don't have any parameter then no need to pass.
 )

  AS
  BEGIN

  -- Here we have some opereations

 -- If there is any Error Before Executing SP2 then SP will stop executing.

  Exec SP2 @ID,@Name,@SomeID OUTPUT 

 -- ,etc some other parameter also we can use OutPut parameters like 

 -- @SomeID is useful for some other operations for condition checking insertion etc.

 -- If you have any Error in you SP2 then also it will stop executing.

 -- If you want to do any other operation after executing SP2 that we can do here.

END

How do I create sql query for searching partial matches?

First of all, this approach won't scale in the large, you'll need a separate index from words to item (like an inverted index).

If your data is not large, you can do

SELECT DISTINCT(name) FROM mytable WHERE name LIKE '%mall%' OR description LIKE '%mall%'

using OR if you have multiple keywords.

PHP function to get the subdomain of a URL

PHP 7.0: Using the explode function and create a list of all the results.

list($subdomain,$host) = explode('.', $_SERVER["SERVER_NAME"]);

Example: sub.domain.com

echo $subdomain; 

Result: sub

echo $host;

Result: domain

JavaScript: How to pass object by value?

I needed to copy an object by value (not reference) and I found this page helpful:

What is the most efficient way to deep clone an object in JavaScript?. In particular, cloning an object with the following code by John Resig:

//Shallow copy
var newObject = jQuery.extend({}, oldObject);
// Deep copy
var newObject = jQuery.extend(true, {}, oldObject);

Commit only part of a file in Git

If you are using vim, you may want to try the excellent plugin called fugitive.

You can see the diff of a file between working copy and index with :Gdiff, and then add lines or hunks to the index using classic vim diff commands like dp. Save the modifications in the index and commit with :Gcommit, and you're done.

Very good introductory screencasts here (see esp. part 2).

C# Dictionary get item by index

you can easily access elements by index , by use System.Linq

Here is the sample

First add using in your class file

using System.Linq;

Then

yourDictionaryData.ElementAt(i).Key
yourDictionaryData.ElementAt(i).Value

Hope this helps.

adb not finding my device / phone (MacOS X)

This only worked for me after I've enabled developer usb debugging on the phone:

On your android phone, go to Settings > About, then tap repeatedly on Build Number until Developer Options is enabled.

javascript toISOString() ignores timezone offset

It will be very helpful to get current date and time.

var date=new Date();
  var today=new Date(date.getTime() - (date.getTimezoneOffset() * 60000)).toISOString().replace(/T/, ' ').replace(/\..+/, '');  

Remove duplicates in the list using linq

This is how I was able to group by with Linq. Hope it helps.

var query = collection.GroupBy(x => x.title).Select(y => y.FirstOrDefault());

How to use Class<T> in Java?

In java <T> means Generic class. A Generic Class is a class which can work on any type of data type or in other words we can say it is data type independent.

public class Shape<T> {
    // T stands for "Type"
    private T t;

    public void set(T t) { this.t = t; }
    public T get() { return t; }
}

Where T means type. Now when you create instance of this Shape class you will need to tell the compiler for what data type this will be working on.

Example:

Shape<Integer> s1 = new Shape();
Shape<String> s2 = new Shape();

Integer is a type and String is also a type.

<T> specifically stands for generic type. According to Java Docs - A generic type is a generic class or interface that is parameterized over types.

How to set cursor position in EditText?

How to resolve the cursor position issue which is automatically moving to the last position after formatting in US Mobile like (xxx) xxx-xxxx in Android.

private String oldText = "";
private int lastCursor;
private EditText mEtPhone;

@Override
    public void afterTextChanged(Editable s) {
String cleanString = AppUtil.cleanPhone(s.toString());

String format = cleanString.length() < 11 ? cleanString.replaceFirst("(\\d{3})(\\d{3})(\\d+)", "($1) $2-$3") :
                cleanString.substring(0, 10).replaceFirst("(\\d{3})(\\d{3})(\\d+)", "($1) $2-$3");


boolean isDeleted = format.length() < oldText.length();

        try {

            int cur = AppUtil.getPointer(lastCursor, isDeleted ? s.toString() : format, oldText, isDeleted);
            mEtPhone.setSelection(cur > 0 ? cur : format.length());

        }catch (Exception e){
            e.printStackTrace();
            mEtPhone.setSelection(format.length());
        }

        mEtPhone.addTextChangedListener(this);

    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        oldText = s.toString();
        lastCursor = start;
    }

Define the below method to any Activityclass in my case Activity name is AppUtil and access it globally

public static int getPointer(int index, String newString, String oldText, boolean isDeleted){

        int diff = Math.abs(newString.length() - oldText.length());

        return diff > 1 ? isDeleted ? index - diff : index  + diff : isDeleted ? index : index + 1;
    }

public static String cleanPhone(String phone){

        if(TextUtils.isEmpty(phone))
            return "";

        StringBuilder sb = new StringBuilder();
        for(char c : phone.toCharArray()){
            if(Character.isDigit(c))
                sb.append(c);
        }
        return sb.toString();
    }

And if you want to set any specific position

edittext.setSelection(position);

Set the layout weight of a TextView programmatically

After strugling for 4 hours. Finally, This code worked for me.

3 Columns are there in a row.

  TextView serialno = new TextView(UsersActivity.this);
  TextView userId = new TextView(UsersActivity.this);
  TextView name = new TextView(UsersActivity.this);

  serialno.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT, 1f));
  userId.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT, 1f));
  name.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT, 1f));

How to post raw body data with curl?

curl's --data will by default send Content-Type: application/x-www-form-urlencoded in the request header. However, when using Postman's raw body mode, Postman sends Content-Type: text/plain in the request header.

So to achieve the same thing as Postman, specify -H "Content-Type: text/plain" for curl:

curl -X POST -H "Content-Type: text/plain" --data "this is raw data" http://78.41.xx.xx:7778/

Note that if you want to watch the full request sent by Postman, you can enable debugging for packed app. Check this link for all instructions. Then you can inspect the app (right-click in Postman) and view all requests sent from Postman in the network tab :

enter image description here

Java java.sql.SQLException: Invalid column index on preparing statement

Everywhere inside the query string, the wildcard should be ? instead of '?'. That should solve the problem.

EDIT :

To add to that, you need to change date '?' to to_date(?, 'yyyy-mm-dd'). Please try that and let me know.

Uninstall mongoDB from ubuntu

In my case mongodb packages are named mongodb-org and mongodb-org-*

So when I type sudo apt purge mongo then tab (for auto-completion) I can see all installed packages that start with mongo.

Another option is to run the following command (which will list all packages that contain mongo in their names or their descriptions):

dpkg -l | grep mongo

In summary, I would do (to purge all packages that start with mongo):

sudo apt purge mongo*

and then (to make sure that no mongo packages are left):

dpkg -l | grep mongo

Of course, as mentioned by @alicanozkara, you will need to manually remove some directories like /var/log/mongodb and /var/lib/mongodb

Running the following find commands:

sudo find /etc/ -name "*mongo*" and sudo find /var/ -name "*mongo*"

may also show some files that you may want to remove, like:

/etc/systemd/system/mongodb.service
/etc/apt/sources.list.d/mongodb-org-3.2.list

and:

/var/lib/apt/lists/repo.mongodb.*

You may also want to remove user and group mongodb, to do so you need to run:

sudo userdel -r mongodb
sudo groupdel mongodb

To check whether mongodb user/group exists or not, try:

cut -d: -f1 /etc/passwd | grep mongo
cut -d: -f1 /etc/group | grep mongo

Converting date between DD/MM/YYYY and YYYY-MM-DD?

Your example code is wrong. This works:

import datetime

datetime.datetime.strptime("21/12/2008", "%d/%m/%Y").strftime("%Y-%m-%d")

The call to strptime() parses the first argument according to the format specified in the second, so those two need to match. Then you can call strftime() to format the result into the desired final format.

How to compare the contents of two string objects in PowerShell

You can do it in two different ways.

Option 1: The -eq operator

>$a = "is"
>$b = "fission"
>$c = "is"
>$a -eq $c
True
>$a -eq $b
False

Option 2: The .Equals() method of the string object. Because strings in PowerShell are .Net System.String objects, any method of that object can be called directly.

>$a.equals($b)
False
>$a.equals($c)
True
>$a|get-member -membertype method

List of System.String methods follows.

Angular 2 declaring an array of objects

type NumberArray = Array<{id: number, text: string}>;

const arr: NumberArray = [
    {id: 0, text: 'Number 0'},
    {id: 1, text: 'Number 1'},
    {id: 2, text: 'Number 2'},
    {id: 3, text: 'Number 3 '},
    {id: 4, text: 'Number 4 '},
    {id: 5, text: 'Number 5 '},
];

How to get sp_executesql result into a variable?

Here's something you can try

DECLARE  @SqlStatement  NVARCHAR(MAX) = ''
       ,@result     XML
       ,@DatabaseName  VARCHAR(100)
       ,@SchemaName    VARCHAR(10)
       ,@ObjectName    VARCHAR(200);

SELECT   @DatabaseName = 'some database'
       ,@SchemaName   = 'some schema'
       ,@ObjectName   = 'some object (Table/View)'

SET @SqlStatement = '
                    SELECT @result = CONVERT(XML,
                                            STUFF( ( SELECT *
                                                     FROM 
                                                       (
                                                          SELECT TOP(100) 
                                                          * 
                                                          FROM ' + QUOTENAME(@DatabaseName) +'.'+ QUOTENAME(@SchemaName) +'.' + QUOTENAME(@ObjectName) + '
                                                       ) AS A1 
                                                    FOR XML PATH(''row''), ELEMENTS, ROOT(''recordset'')
                                                 ), 1, 0, '''')
                                       )
                ';

EXEC sp_executesql @SqlStatement,N'@result XML OUTPUT', @result = @result OUTPUT;

SELECT DISTINCT
    QUOTENAME(r.value('fn:local-name(.)', 'VARCHAR(200)')) AS ColumnName
FROM @result.nodes('//recordset/*/*') AS records(r)
ORDER BY ColumnName

MS Access VBA: Sending an email through Outlook

Add a reference to the Outlook object model in the Visual Basic editor. Then you can use the code below to send an email using outlook.

Sub sendOutlookEmail()
Dim oApp As Outlook.Application
Dim oMail As MailItem
Set oApp = CreateObject("Outlook.application")

Set oMail = oApp.CreateItem(olMailItem)
oMail.Body = "Body of the email"
oMail.Subject = "Test Subject"
oMail.To = "[email protected]"
oMail.Send
Set oMail = Nothing
Set oApp = Nothing


End Sub

background-size in shorthand background property (CSS3)

try out like this

body {
   background: #fff url("!--MIZO-PRO--!") no-repeat center 15px top 15px/100px;
     }


/* 100px is the background size */

The source was not found, but some or all event logs could not be searched. Inaccessible logs: Security

Whenever you start Visual Studio run it as administrator. It works for me.

How to Solve the XAMPP 1.7.7 - PHPMyAdmin - MySQL Error #2002 in Ubuntu

It turns out that the solution is to stop all the related services and solve the “Another daemon is already running” issue.

The commands i used to solve the issue are as follows:

sudo /opt/lampp/lampp stop              
sudo /etc/init.d/apache2 stop    
sudo /etc/init.d/mysql stop

Or, you can also type instead:

sudo service apache2 stop
sudo service mysql stop

After that, we again start the lampp services:

sudo /opt/lampp/lampp start

Now, there must be no problems while opening:

http://localhost                  
http://localhost/phpmyadmin

How to Create a real one-to-one relationship in SQL Server

There is one way I know how to achieve a strictly* one-to-one relationship without using triggers, computed columns, additional tables, or other 'exotic' tricks (only foreign keys and unique constraints), with one small caveat.

I will borrow the chicken-and-the-egg concept from the accepted answer to help me explain the caveat.

It is a fact that either a chicken or an egg must come first (in current DBs anyway). Luckily this solution does not get political and does not prescribe which has to come first - it leaves it up to the implementer.

The caveat is that the table which allows a record to 'come first' technically can have a record created without the corresponding record in the other table; however, in this solution, only one such record is allowed. When only one record is created (only chicken or egg), no more records can be added to any of the two tables until either the 'lonely' record is deleted or a matching record is created in the other table.

Solution:

Add foreign keys to each table, referencing the other, add unique constraints to each foreign key, and make one foreign key nullable, the other not nullable and also a primary key. For this to work, the unique constrain on the nullable column must only allow one null (this is the case in SQL Server, not sure about other databases).

CREATE TABLE dbo.Egg (
    ID int identity(1,1) not null,
    Chicken int null,
    CONSTRAINT [PK_Egg] PRIMARY KEY CLUSTERED ([ID] ASC) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE TABLE dbo.Chicken (
    Egg int not null,
    CONSTRAINT [PK_Chicken] PRIMARY KEY CLUSTERED ([Egg] ASC) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE dbo.Egg  WITH NOCHECK ADD  CONSTRAINT [FK_Egg_Chicken] FOREIGN KEY([Chicken]) REFERENCES [dbo].[Chicken] ([Egg])
GO
ALTER TABLE dbo.Chicken  WITH NOCHECK ADD  CONSTRAINT [FK_Chicken_Egg] FOREIGN KEY([Egg]) REFERENCES [dbo].[Egg] ([ID])
GO
ALTER TABLE dbo.Egg WITH NOCHECK ADD CONSTRAINT [UQ_Egg_Chicken] UNIQUE([Chicken])
GO
ALTER TABLE dbo.Chicken WITH NOCHECK ADD CONSTRAINT [UQ_Chicken_Egg] UNIQUE([Egg])
GO

To insert, first an egg must be inserted (with null for Chicken). Now, only a chicken can be inserted and it must reference the 'unclaimed' egg. Finally, the added egg can be updated and it must reference the 'unclaimed' chicken. At no point can two chickens be made to reference the same egg or vice-versa.

To delete, the same logic can be followed: update egg's Chicken to null, delete the newly 'unclaimed' chicken, delete the egg.

This solution also allows swapping easily. Interestingly, swapping might be the strongest argument for using such a solution, because it has a potential practical use. Normally, in most cases, a one-to-one relationship of two tables is better implemented by simply refactoring the two tables into one; however, in a potential scenario, the two tables may represent truly distinct entities, which require a strict one-to-one relationship, but need to frequently swap 'partners' or be re-arranged in general, while still maintaining the one-to-one relationship after re-arrangement. If the more common solution were used, all data columns of one of the entities would have to be updated/overwritten for all pairs being re-arranged, as opposed to this solution, where only one column of foreign keys need to be re-arranged (the nullable foreign key column).

Well, this is the best I could do using standard constraints (don't judge :) Maybe someone will find it useful.

Android: keep Service running when app is killed

If your Service is started by your app then actually your service is running on main process. so when app is killed service will also be stopped. So what you can do is, send broadcast from onTaskRemoved method of your service as follows:

 Intent intent = new Intent("com.android.ServiceStopped");
 sendBroadcast(intent);

and have an broadcast receiver which will again start a service. I have tried it. service restarts from all type of kills.

What represents a double in sql server?

Also, here is a good answer for SQL-CLR Type Mapping with a useful chart.

From that post (by David): enter image description here

How to parse a text file with C#

One way that I've found really useful in situations like this is to go old-school and use the Jet OLEDB provider, together with a schema.ini file to read large tab-delimited files in using ADO.Net. Obviously, this method is really only useful if you know the format of the file to be imported.

public void ImportCsvFile(string filename)
{
    FileInfo file = new FileInfo(filename);

    using (OleDbConnection con = 
            new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"" +
            file.DirectoryName + "\";
            Extended Properties='text;HDR=Yes;FMT=TabDelimited';"))
    {
        using (OleDbCommand cmd = new OleDbCommand(string.Format
                                  ("SELECT * FROM [{0}]", file.Name), con))
        {
            con.Open();

            // Using a DataReader to process the data
            using (OleDbDataReader reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    // Process the current reader entry...
                }
            }

            // Using a DataTable to process the data
            using (OleDbDataAdapter adp = new OleDbDataAdapter(cmd))
            {
                DataTable tbl = new DataTable("MyTable");
                adp.Fill(tbl);

                foreach (DataRow row in tbl.Rows)
                {
                    // Process the current row...
                }
            }
        }
    }
} 

Once you have the data in a nice format like a datatable, filtering out the data you need becomes pretty trivial.

How to link to specific line number on github

a permalink to a code snippet is pasted into a pull request comment field

You can you use permalinks to include code snippets in issues, PRs, etc.

References:

https://help.github.com/en/articles/creating-a-permanent-link-to-a-code-snippet

How can I add raw data body to an axios request?

The key is to use "Content-Type": "text/plain" as mentioned by @MadhuBhat.

axios.post(path, code, { headers: { "Content-Type": "text/plain" } }).then(response => {
    console.log(response);
});

A thing to note if you use .NET is that a raw string to a controller will return 415 Unsupported Media Type. To get around this you need to encapsulate the raw string in hyphens like this and send it as "Content-Type": "application/json":

axios.post(path, "\"" + code + "\"", { headers: { "Content-Type": "application/json" } }).then(response => {
    console.log(response);
});

C# Controller:

[HttpPost]
public async Task<ActionResult<string>> Post([FromBody] string code)
{
    return Ok(code);
}

https://weblog.west-wind.com/posts/2017/sep/14/accepting-raw-request-body-content-in-aspnet-core-api-controllers

You can also make a POST with query params if that helps:

.post(`/mails/users/sendVerificationMail`, null, { params: {
  mail,
  firstname
}})
.then(response => response.status)
.catch(err => console.warn(err));

This will POST an empty body with the two query params:

POST http://localhost:8000/api/mails/users/sendVerificationMail?mail=lol%40lol.com&firstname=myFirstName

Source: https://stackoverflow.com/a/53501339/3850405

Refresh certain row of UITableView based on Int in Swift

How about:

self.tableView.reloadRowsAtIndexPaths([NSIndexPath(rowNumber)], withRowAnimation: UITableViewRowAnimation.Top)

What does jQuery.fn mean?

In jQuery, the fn property is just an alias to the prototype property.

The jQuery identifier (or $) is just a constructor function, and all instances created with it, inherit from the constructor's prototype.

A simple constructor function:

function Test() {
  this.a = 'a';
}
Test.prototype.b = 'b';

var test = new Test(); 
test.a; // "a", own property
test.b; // "b", inherited property

A simple structure that resembles the architecture of jQuery:

(function() {
  var foo = function(arg) { // core constructor
    // ensure to use the `new` operator
    if (!(this instanceof foo))
      return new foo(arg);
    // store an argument for this example
    this.myArg = arg;
    //..
  };

  // create `fn` alias to `prototype` property
  foo.fn = foo.prototype = {
    init: function () {/*...*/}
    //...
  };

  // expose the library
  window.foo = foo;
})();

// Extension:

foo.fn.myPlugin = function () {
  alert(this.myArg);
  return this; // return `this` for chainability
};

foo("bar").myPlugin(); // alerts "bar"

How to build a RESTful API?

That is pretty much the same as created a normal website.

Normal pattern for a php website is:

  1. The user enter a url
  2. The server get the url, parse it and execute a action
  3. In this action, you get/generate every information you need for the page
  4. You create the html/php page with the info from the action
  5. The server generate a fully html page and send it back to the user

With a api, you just add a new step between 3 and 4. After 3, create a array with all information you need. Encode this array in json and exit or return this value.

$info = array("info_1" => 1; "info_2" => "info_2" ... "info_n" => array(1,2,3));
exit(json_encode($info));

That all for the api. For the client side, you can call the api by the url. If the api work only with get call, I think it's possible to do a simply (To check, I normally use curl).

$info = file_get_contents(url);
$info = json_decode($info);

But it's more common to use the curl library to perform get and post call. You can ask me if you need help with curl.

Once the get the info from the api, you can do the 4 & 5 steps.

Look the php doc for json function and file_get_contents.

curl : http://fr.php.net/manual/fr/ref.curl.php


EDIT

No, wait, I don't get it. "php API page" what do you mean by that ?

The api is only the creation/recuperation of your project. You NEVER send directly the html result (if you're making a website) throw a api. You call the api with the url, the api return information, you use this information to create the final result.

ex: you want to write a html page who say hello xxx. But to get the name of the user, you have to get the info from the api.

So let's say your api have a function who have user_id as argument and return the name of this user (let's say getUserNameById(user_id)), and you call this function only on a url like your/api/ulr/getUser/id.

Function getUserNameById(user_id)
{
  $userName = // call in db to get the user
  exit(json_encode($userName)); // maybe return work as well.
}

From the client side you do

    $username = file_get_contents(your/api/url/getUser/15); // You should normally use curl, but it simpler for the example
// So this function to this specifique url will call the api, and trigger the getUserNameById(user_id), whom give you the user name.
    <html>
    <body>
    <p>hello <?php echo $username ?> </p>
    </body>
    </html>

So the client never access directly the databases, that the api's role.

Is that clearer ?

jquery ajax get responsetext from http url

Since jQuery AJAX requests fail if they are cross-domain, you can use cURL (in PHP) to set up a proxy server.

Suppose a PHP file responder.php has these contents:

$url = "https://www.google.com";
$ch      = curl_init( $url );
curl_set_opt($ch, CURLOPT_RETURNTRANSFER, "true")
$response= curl_exec( $ch );
curl_close( $ch );
return $response;

Your AJAX request should be to this responder.php file so that it executes the cross-domain request.

Check box size change with CSS

input fields can be styled as you wish. So instead of zoom, you could have

input[type="checkbox"]{
  width: 30px; /*Desired width*/
  height: 30px; /*Desired height*/
}

EDIT:

You would have to add extra rules like this:

input[type="checkbox"]{
  width: 30px; /*Desired width*/
  height: 30px; /*Desired height*/
  cursor: pointer;
  -webkit-appearance: none;
  appearance: none;
}

Check this fiddle http://jsfiddle.net/p36tqqyq/1/

java.lang.NoClassDefFoundError: org/json/JSONObject

Please add the following dependency http://mvnrepository.com/artifact/org.json/json/20080701

<dependency>
   <groupId>org.json</groupId>
   <artifactId>json</artifactId>
   <version>20080701</version>
</dependency>

PHP Change Array Keys

If you have an array of keys that you want to use then use array_combine

Given $keys = array('a', 'b', 'c', ...) and your array, $list, then do this:

$list = array_combine($keys, array_values($list));

List will now be array('a' => 'blabla 1', ...) etc.

You have to use array_values to extract just the values from the array and not the old, numeric, keys.

That's nice and simple looking but array_values makes an entire copy of the array so you could have space issues. All we're doing here is letting php do the looping for us, not eliminate the loop. I'd be tempted to do something more like:

foreach ($list as $k => $v) {
   unset ($list[$k]);

   $new_key =  *some logic here*

   $list[$new_key] = $v;
}

I don't think it's all that more efficient than the first code but it provides more control and won't have issues with the length of the arrays.

What is an uber jar?

The different names are just ways of packaging java apps.

Skinny – Contains ONLY the bits you literally type into your code editor, and NOTHING else.

Thin – Contains all of the above PLUS the app’s direct dependencies of your app (db drivers, utility libraries, etc).

Hollow – The inverse of Thin – Contains only the bits needed to run your app but does NOT contain the app itself. Basically a pre-packaged “app server” to which you can later deploy your app, in the same style as traditional Java EE app servers, but with important differences.

Fat/Uber – Contains the bit you literally write yourself PLUS the direct dependencies of your app PLUS the bits needed to run your app “on its own”.

Source: Article from Dzone

Visual representation of JAR types

Reposted from: https://stackoverflow.com/a/57592130/9470346

How to order results with findBy() in Doctrine

$ens = $em->getRepository('AcmeBinBundle:Marks')
              ->findBy(
                 array(), 
                 array('id' => 'ASC')
               );

How to set JAVA_HOME in Mac permanently?

to set JAVA_HOME permenantly in mac make sure you have JDK installed in your system, if jdk is not installed you can download it from here https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html

After installing jdk follow these steps :-

1) Open Terminal

2) Type "vim .bash_profile"

3) press "i" to edit or enter the path

4) Type your java instalation dir :- export JAVA_HOME=$(/usr/libexec/java_home)

5) Click ESC then type ":wq" (save and quit in vim)

6) Then type "source .bash_profile"

7) type "echo $JAVA_HOME" if you see the path you are all set.

THANK YOU

How does Python manage int and long?

On my machine:

>>> print type(1<<30)
<type 'int'>
>>> print type(1<<31)
<type 'long'>
>>> print type(0x7FFFFFFF)
<type 'int'>
>>> print type(0x7FFFFFFF+1)
<type 'long'>

Python uses ints (32 bit signed integers, I don't know if they are C ints under the hood or not) for values that fit into 32 bit, but automatically switches to longs (arbitrarily large number of bits - i.e. bignums) for anything larger. I'm guessing this speeds things up for smaller values while avoiding any overflows with a seamless transition to bignums.

Python: How to ignore an exception and proceed?

Try this:

try:
    blah()
except:
    pass

Upload Image using POST form data in Python-requests

From wechat api doc:

curl -F [email protected] "http://file.api.wechat.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE"

Translate the command above to python:

import requests
url = 'http://file.api.wechat.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE'
files = {'media': open('test.jpg', 'rb')}
requests.post(url, files=files)

calling another method from the main method in java

This is a fundamental understanding in Java, but can be a little tricky to new programmers. Do a little research on the difference between a static and instance method. The basic difference is the instance method do() is only accessible to a instance of the class foo.

You must instantiate (create an instance of) the class, creating an object, that you use to call the instance method.

I have included your example with a couple comments and example.

public class SomeName {

//this is a static method and cannot call an instance method without a object
public static void main(String[] args){

    // can't do this from this static method, no object reference
    // someMethod();

    //create instance of object
    SomeName thisObj = new SomeName();
    //call instance method using object
    thisObj.someMethod();
}

//instance method
public void someMethod(){
    System.out.print("some message...");
}

}// end class SomeName

jquery find class and get the value

Class selectors are prefixed with a dot. Your .find() is missing that so jQuery thinks you're looking for <myClass> elements.

var myVar = $("#start").find('.myClass').val();

Git vs Team Foundation Server

The whole Distributed thing of Git is really really great. it gives a few features Shelvesets don't have (in the current product) such as local rollback and commit options (such as Eclipse's localhistory feature). You could alleviate this using developer branches, but lets be honest, many developers don't like branching and merging one bit. I've been asked to turn on the old style "exclusive checkout" feature in TFS a few times too often (and denied it each and every time).

I think many large enterprises are quite scared to allow a dev to just bring the whole history into a local workspace and take it with them (to a new employer for example)... Stealing a snapshot is bad, but taking away a whole history is even more troublesome. (Not that you couldn't get a full history from TFS of you wanted it)...

It's mentioned that it's a great way to backup, which is great for open source again where the original maintainer might stop to care and removes his version, but for a enterprise plan this again falls short for many enterprises as there is no clear assignment of responsibility to keep backups. And it would be hard to figure out which version to use if the main 'project' vanishes somehow. Which would tend to appoint one repository as leading/central.

What I like most about Git is the Push/Pull option, where you can easily contribute code to a project without the need to have commit rights. I guess you could use very limited users and shelvesets in TFS to mimic this, but it isn't as powerful as the Git option. Branching across team projects might work as well, but from an administrative perspective it's not really feasible for many organisations as adding team projects adds a lot of administartive overhead.

I'd also like to add to the things mentioned in the non source control area. Features such as Work Item Tracking, Reporting and Build Automation (including lab management) greatly benefit from a central leading repository. These become a lot harder when you use a pure distributed model, unless you make one of the nodes leading (and thus go back to a less distributed model).

With TFS Basic coming with TFS 11, it might not be far off to expect a distributed TFS which allows you to sync your local TFS basic to a central TFS in the TFS 12+ era. I'll put my vote for that down in the uservoice!

Check if string contains only whitespace

for those who expect a behaviour like the apache StringUtils.isBlank or Guava Strings.isNullOrEmpty :

if mystring and mystring.strip():
    print "not blank string"
else:
    print "blank string"

java.nio.file.Path for a classpath resource

It turns out you can do this, with the help of the built-in Zip File System provider. However, passing a resource URI directly to Paths.get won't work; instead, one must first create a zip filesystem for the jar URI without the entry name, then refer to the entry in that filesystem:

static Path resourceToPath(URL resource)
throws IOException,
       URISyntaxException {

    Objects.requireNonNull(resource, "Resource URL cannot be null");
    URI uri = resource.toURI();

    String scheme = uri.getScheme();
    if (scheme.equals("file")) {
        return Paths.get(uri);
    }

    if (!scheme.equals("jar")) {
        throw new IllegalArgumentException("Cannot convert to Path: " + uri);
    }

    String s = uri.toString();
    int separator = s.indexOf("!/");
    String entryName = s.substring(separator + 2);
    URI fileURI = URI.create(s.substring(0, separator));

    FileSystem fs = FileSystems.newFileSystem(fileURI,
        Collections.<String, Object>emptyMap());
    return fs.getPath(entryName);
}

Update:

It’s been rightly pointed out that the above code contains a resource leak, since the code opens a new FileSystem object but never closes it. The best approach is to pass a Consumer-like worker object, much like how Holger’s answer does it. Open the ZipFS FileSystem just long enough for the worker to do whatever it needs to do with the Path (as long as the worker doesn’t try to store the Path object for later use), then close the FileSystem.

How can I remove the string "\n" from within a Ruby string?

use chomp or strip functions from Ruby:

"abcd\n".chomp => "abcd"
"abcd\n".strip => "abcd"

How to write an inline IF statement in JavaScript?

I often need to run more code per condition, by using: ( , , ) multiple code elements can execute:

var a = 2;
var b = 3;
var c = 0;

( a < b ?  ( alert('hi'), a=3, b=2, c=a*b ) : ( alert('by'), a=4, b=10, c=a/b ) );

ggplot2 legend to bottom and horizontal

Here is how to create the desired outcome:

library(reshape2); library(tidyverse)
melt(outer(1:4, 1:4), varnames = c("X1", "X2")) %>%
ggplot() + 
  geom_tile(aes(X1, X2, fill = value)) + 
  scale_fill_continuous(guide = guide_legend()) +
  theme(legend.position="bottom",
        legend.spacing.x = unit(0, 'cm'))+
  guides(fill = guide_legend(label.position = "bottom"))

Created on 2019-12-07 by the reprex package (v0.3.0)


Edit: no need for these imperfect options anymore, but I'm leaving them here for reference.

Two imperfect options that don't give you exactly what you were asking for, but pretty close (will at least put the colours together).

library(reshape2); library(tidyverse)
df <- melt(outer(1:4, 1:4), varnames = c("X1", "X2"))
p1 <- ggplot(df, aes(X1, X2)) + geom_tile(aes(fill = value))
p1 + scale_fill_continuous(guide = guide_legend()) +
 theme(legend.position="bottom", legend.direction="vertical")

p1 + scale_fill_continuous(guide = "colorbar") + theme(legend.position="bottom")

Created on 2019-02-28 by the reprex package (v0.2.1)

How do I run PHP code when a user clicks on a link?

I know this post is old but I just wanted to add my answer!

You said to log a user out WITHOUT directing... this method DOES redirect but it returns the user to the page they were on! here's my implementation:

// every page with logout button
<?php
        // get the full url of current page
        $page = $_SERVER['PHP_SELF'];
        // find position of the last '/'
        $file_name_begin_pos = strripos($page, "/");
        // get substring from position to end 
        $file_name = substr($page, ++$fileNamePos);
    }
?>

// the logout link in your html
<a href="logout.php?redirect_to=<?=$file_name?>">Log Out</a>

// logout.php page
<?php
    session_start();
    $_SESSION = array();
    session_destroy();
    $page = "index.php";
    if(isset($_GET["redirect_to"])){
        $file = $_GET["redirect_to"];
        if ($file == "user.php"){
            // if redirect to is a restricted page, redirect to index
            $file = "index.php";
        }
    }
    header("Location: $file");
?>

and there we go!

the code that gets the file name from the full url isn't bug proof. for example if query strings are involved with un-escaped '/' in them, it will fail.

However there are many scripts out there to get the filename from url!

Happy Coding!

Alex

How do you install GLUT and OpenGL in Visual Studio 2012?

the instructions for Vs2012

To Install FreeGLUT

  1. Download "freeglut 2.8.1 MSVC Package" from http://www.transmissionzero.co.uk/software/freeglut-devel/
  2. Extract the compressed file freeglut-MSVC.zip to a folder freeglut

  3. Inside freeglut folder:

On 32bit versions of windows

copy all files in include/GL folder to C:\Program Files\Windows Kits\8.0\Include\um\gl

copy all files in lib folder to C:\Program Files\Windows Kits\8.0\Lib\win8\um\ (note: Lib\freeglut.lib in a folder goes into x86)

copy freeglut.dll to C:\windows\system32

On 64bit versions of windows:(not 100% sure but try)

copy all files in include/GL folder to C:\Program Files(x86)\Windows Kits\8.0\Include\um\gl

copy all files in lib folder to C:\Program Files(x86)\Windows Kits\8.0\Lib\win8\um\ (note: Lib\freeglut.lib in a folder goes into x86)

copy freeglut.dll to C:\windows\SysWOW64

How to identify whether a grammar is LL(1), LR(0) or SLR(1)?

LL(1) grammar is Context free unambiguous grammar which can be parsed by LL(1) parsers.

In LL(1)

  • First L stands for scanning input from Left to Right. Second L stands for Left Most Derivation. 1 stands for using one input symbol at each step.

For Checking grammar is LL(1) you can draw predictive parsing table. And if you find any multiple entries in table then you can say grammar is not LL(1).

Their is also short cut to check if the grammar is LL(1) or not . Shortcut Technique

How can I calculate the number of lines changed between two commits in Git?

If you want to see the changes including the # of lines that changed between your branch and another branch,

git diff the_other_branch_name --stat

How to extract the decision rules from scikit-learn decision-tree?

Scikit learn introduced a delicious new method called export_text in version 0.21 (May 2019) to extract the rules from a tree. Documentation here. It's no longer necessary to create a custom function.

Once you've fit your model, you just need two lines of code. First, import export_text:

from sklearn.tree import export_text

Second, create an object that will contain your rules. To make the rules look more readable, use the feature_names argument and pass a list of your feature names. For example, if your model is called model and your features are named in a dataframe called X_train, you could create an object called tree_rules:

tree_rules = export_text(model, feature_names=list(X_train.columns))

Then just print or save tree_rules. Your output will look like this:

|--- Age <= 0.63
|   |--- EstimatedSalary <= 0.61
|   |   |--- Age <= -0.16
|   |   |   |--- class: 0
|   |   |--- Age >  -0.16
|   |   |   |--- EstimatedSalary <= -0.06
|   |   |   |   |--- class: 0
|   |   |   |--- EstimatedSalary >  -0.06
|   |   |   |   |--- EstimatedSalary <= 0.40
|   |   |   |   |   |--- EstimatedSalary <= 0.03
|   |   |   |   |   |   |--- class: 1

How to loop through elements of forms with JavaScript?

Es5 forEach:

Array.prototype.forEach.call(form.elements, function (inpt) {
       if(inpt.name === name) {
             inpt.parentNode.removeChild(inpt);
       }
});

Otherwise the lovely for:

var input;
for(var i = 0; i < form.elements.length; i++) {
     input = form.elements[i];

      // ok my nice work with input, also you have the index with i (in foreach too you can get the index as second parameter (foreach is a wrapper around for, that offer a function to be called at each iteration.
}

Rails ActiveRecord date between

Rails 5.1 introduced a new date helper method all_day, see: https://github.com/rails/rails/pull/24930

>> Date.today.all_day
=> Wed, 26 Jul 2017 00:00:00 UTC +00:00..Wed, 26 Jul 2017 23:59:59 UTC +00:00

If you are using Rails 5.1, the query would look like:

Comment.where(created_at: @selected_date.all_day)

How can one print a size_t variable portably using the printf family?

if you want to print the value of a size_t as a string you can do this:

char text[] = "Lets go fishing in stead of sitting on our but !!";
size_t line = 2337200120702199116;

/* on windows I64x or I64d others %lld or %llx if it works %zd or %zx */
printf("number: %I64d\n",*(size_t*)&text);
printf("text: %s\n",*(char(*)[])&line);

result is:

number: 2337200120702199116

text: Lets go fishing in stead of sitting on our but !!

Edit: rereading the question because of the down votes i noted his problem is not %llu or %I64d but the size_t type on different machines see this question https://stackoverflow.com/a/918909/1755797
http://www.cplusplus.com/reference/cstdio/printf/

size_t is unsigned int on a 32bit machine and unsigned long long int on 64bit
but %ll always expects a unsigned long long int.

size_t varies in length on different operating systems while %llu is the same

Javascript array declaration: new Array(), new Array(3), ['a', 'b', 'c'] create arrays that behave differently

Arrays in JS have two types of properties:

Regular elements and associative properties (which are nothing but objects)

When you define a = new Array(), you are defining an empty array. Note that there are no associative objects yet

When you define b = new Array(2), you are defining an array with two undefined locations.

In both your examples of 'a' and 'b', you are adding associative properties i.e. objects to these arrays.

console.log (a) or console.log(b) prints the array elements i.e. [] and [undefined, undefined] respectively. But since a1/a2 and b1/b2 are associative objects inside their arrays, they can be logged only by console.log(a.a1, a.a2) kind of syntax

Passing two command parameters using a WPF binding

About using Tuple in Converter, it would be better to use 'object' instead of 'string', so that it works for all types of objects without limitation of 'string' object.

public class YourConverter : IMultiValueConverter 
{      
    public object Convert(object[] values, ...)     
    {   
        Tuple<object, object> tuple = new Tuple<object, object>(values[0], values[1]);
        return tuple;
    }      
} 

Then execution logic in Command could be like this

public void OnExecute(object parameter) 
{
    var param = (Tuple<object, object>) parameter;

    // e.g. for two TextBox object
    var txtZip = (System.Windows.Controls.TextBox)param.Item1;
    var txtCity = (System.Windows.Controls.TextBox)param.Item2;
}

and multi-bind with converter to create the parameters (with two TextBox objects)

<Button Content="Zip/City paste" Command="{Binding PasteClick}" >
    <Button.CommandParameter>
        <MultiBinding Converter="{StaticResource YourConvert}">
            <Binding ElementName="txtZip"/>
            <Binding ElementName="txtCity"/>
        </MultiBinding>
    </Button.CommandParameter>
</Button>

An error occurred while executing the command definition. See the inner exception for details

I've just run into this issue and it was because I had updated a view in my DB and not refreshed the schema in my mapping.