Programs & Examples On #Grails plugin

A Grails plugin is a self-contained bundle of functionality that can be installed into a Grails application.

When should we call System.exit in Java

System.exit(0) terminates the JVM. In simple examples like this it is difficult to percieve the difference. The parameter is passed back to the OS and is normally used to indicate abnormal termination (eg some kind of fatal error), so if you called java from a batch file or shell script you'd be able to get this value and get an idea if the application was successful.

It would make a quite an impact if you called System.exit(0) on an application deployed to an application server (think about it before you try it).

Python: AttributeError: '_io.TextIOWrapper' object has no attribute 'split'

Try this:

 >>> f = open('goodlines.txt')
 >>> mylist = f.readlines()

open() function returns a file object. And for file object, there is no method like splitlines() or split(). You could use dir(f) to see all the methods of file object.

SQL Server query to find all permissions/access for all users in a database

Unfortunately I couldn't comment on the Sean Rose post due to insufficient reputation, however I had to amend the "public" role portion of the script as it didn't show SCHEMA-scoped permissions due to the (INNER) JOIN against sys.objects. After that was changed to a LEFT JOIN I further had to amend the WHERE-clause logic to omit system objects. My amended query for the public perms is below.

--3) List all access provisioned to the public role, which everyone gets by default
    SELECT
        @@servername ServerName
        , db_name() DatabaseName
        , [UserType]         = '{All Users}',
        [DatabaseUserName] = '{All Users}',
        [LoginName]        = '{All Users}',
        [Role]             = roleprinc.[name],
        [PermissionType]   = perm.[permission_name],
        [PermissionState]  = perm.[state_desc],
        [ObjectType] = CASE perm.[class]
                           WHEN 1 THEN obj.[type_desc]        -- Schema-contained objects
                           ELSE perm.[class_desc]             -- Higher-level objects
                       END,
        [Schema] = objschem.[name],
        [ObjectName] = CASE perm.[class]
                           WHEN 3 THEN permschem.[name]       -- Schemas
                           WHEN 4 THEN imp.[name]             -- Impersonations
                           ELSE OBJECT_NAME(perm.[major_id])  -- General objects
                       END,
        [ColumnName] = col.[name]
    FROM
        --Roles
        sys.database_principals            AS roleprinc
        --Role permissions
        LEFT JOIN sys.database_permissions AS perm      ON perm.[grantee_principal_id] = roleprinc.[principal_id]
        LEFT JOIN sys.schemas              AS permschem ON permschem.[schema_id] = perm.[major_id]
        --All objects
        LEFT JOIN sys.objects              AS obj       ON obj.[object_id] = perm.[major_id]
        LEFT JOIN sys.schemas              AS objschem  ON objschem.[schema_id] = obj.[schema_id]
        --Table columns
        LEFT JOIN sys.columns              AS col       ON col.[object_id] = perm.[major_id]
                                                           AND col.[column_id] = perm.[minor_id]
        --Impersonations
        LEFT JOIN sys.database_principals  AS imp       ON imp.[principal_id] = perm.[major_id]
    WHERE
        roleprinc.[type] = 'R'
        AND roleprinc.[name] = 'public'
        AND isnull(obj.[is_ms_shipped], 0) = 0
        AND isnull(object_schema_name(perm.[major_id]), '') <> 'sys'

ORDER BY
    [UserType],
    [DatabaseUserName],
    [LoginName],
    [Role],
    [Schema],
    [ObjectName],
    [ColumnName],
    [PermissionType],
    [PermissionState],
    [ObjectType]

Turn off warnings and errors on PHP and MySQL

Always show errors on a testing server. Never show errors on a production server.

Write a script to determine whether the page is on a local, testing, or live server, and set $state to "local", "testing", or "live". Then:

if( $state == "local" || $state == "testing" )
{
    ini_set( "display_errors", "1" );
    error_reporting( E_ALL & ~E_NOTICE );
}
else
{
    error_reporting( 0 );
}

How to show a dialog to confirm that the user wishes to exit an Android Activity?

If you are not sure if the call to "back" will exit the app, or will take the user to another activity, you can wrap the above answers in a check, isTaskRoot(). This can happen if your main activity can be added to the back stack multiple times, or if you are manipulating your back stack history.

if(isTaskRoot()) {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Are you sure you want to exit?")
       .setCancelable(false)
       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int id) {
                YourActivity.super.onBackPressed;
           }
       })
       .setNegativeButton("No", new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
           }
       });
    AlertDialog alert = builder.create();
    alert.show();

} else {
    super.onBackPressed();
}

Control flow in T-SQL SP using IF..ELSE IF - are there other ways?

Nope IF is the way to go, what is the problem you have with using it?

BTW your example won't ever get to the third block of code as it and the second block are exactly alike.

How to convert unsigned long to string

you can write a function which converts from unsigned long to str, similar to ltostr library function.

char *ultostr(unsigned long value, char *ptr, int base)
{
  unsigned long t = 0, res = 0;
  unsigned long tmp = value;
  int count = 0;

  if (NULL == ptr)
  {
    return NULL;
  }

  if (tmp == 0)
  {
    count++;
  }

  while(tmp > 0)
  {
    tmp = tmp/base;
    count++;
  }

  ptr += count;

  *ptr = '\0';

  do
  {
    res = value - base * (t = value / base);
    if (res < 10)
    {
      * -- ptr = '0' + res;
    }
    else if ((res >= 10) && (res < 16))
    {
        * --ptr = 'A' - 10 + res;
    }
  } while ((value = t) != 0);

  return(ptr);
}

you can refer to my blog here which explains implementation and usage with example.

ElasticSearch: Unassigned Shards, how to fix?

When dealing with corrupted shards you can set the replication factor to 0 and then set it back to the original value. This should clear up most if not all your corrupted shards and relocate the new replicas in the cluster.

Setting indexes with unassigned replicas to use a replication factor of 0:

curl -XGET http://localhost:9200/_cat/shards |\
  grep UNASSIGNED | grep ' r ' |\
  awk '{print $1}' |\
  xargs -I {} curl -XPUT http://localhost:9200/{}/_settings -H "Content-Type: application/json" \
  -d '{ "index":{ "number_of_replicas": 0}}'

Setting them back to 1:

curl -XGET http://localhost:9200/_cat/shards |\
  awk '{print $1}' |\
  xargs -I {} curl -XPUT http://localhost:9200/{}/_settings -H "Content-Type: application/json" \
  -d '{ "index":{ "number_of_replicas": 1}}'

Note: Do not run this if you have different replication factors for different indexes. This would hardcode the replication factor for all indexes to 1.

Does Python have an ordered set?

For many purposes simply calling sorted will suffice. For example

>>> s = set([0, 1, 2, 99, 4, 40, 3, 20, 24, 100, 60])
>>> sorted(s)
[0, 1, 2, 3, 4, 20, 24, 40, 60, 99, 100]

If you are going to use this repeatedly, there will be overhead incurred by calling the sorted function so you might want to save the resulting list, as long as you're done changing the set. If you need to maintain unique elements and sorted, I agree with the suggestion of using OrderedDict from collections with an arbitrary value such as None.

Passing Javascript variable to <a href >

You can also use an express framework

app.get("/:id",function(req,res)
{
  var id = req.params.id;
  res.render("home.ejs",{identity : id});
});

Express file, which receives a JS variable identity from node.js

<a href = "/any_route/<%=identity%> includes identity JS variable into your href without a trouble enter

How can I merge the columns from two tables into one output?

When your are three tables or more, just add union and left outer join:

select a.col1, b.col2, a.col3, b.col4, a.category_id 
from 
(
    select category_id from a
    union
    select category_id from b
) as c
left outer join a on a.category_id = c.category_id
left outer join b on b.category_id = c.category_id

SVN- How to commit multiple files in a single shot

You can use --targets ARG option where ARG is the name of textfile containing the targets for commit.

svn ci --targets myfiles.txt -m "another commit"

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 23: ordinal not in range(128)

I was getting this error when executing in python3,I got the same program working by simply executing in python2

How to get the size of a string in Python?

Do you want to find the length of the string in python language ? If you want to find the length of the word, you can use the len function.

string = input("Enter the string : ")

print("The string length is : ",len(string))

OUTPUT : -

Enter the string : viral

The string length is : 5

ImportError: No module named 'bottle' - PyCharm

In some cases no "No module ..." can appear even on local files. In such cases you just need to mark appropriate directories as "source directories":

Mark as source lib directory

How can bcrypt have built-in salts?

I believe that phrase should have been worded as follows:

bcrypt has salts built into the generated hashes to prevent rainbow table attacks.

The bcrypt utility itself does not appear to maintain a list of salts. Rather, salts are generated randomly and appended to the output of the function so that they are remembered later on (according to the Java implementation of bcrypt). Put another way, the "hash" generated by bcrypt is not just the hash. Rather, it is the hash and the salt concatenated.

What does the ??!??! operator do in C?

Well, why this exists in general is probably different than why it exists in your example.

It all started half a century ago with repurposing hardcopy communication terminals as computer user interfaces. In the initial Unix and C era that was the ASR-33 Teletype.

This device was slow (10 cps) and noisy and ugly and its view of the ASCII character set ended at 0x5f, so it had (look closely at the pic) none of the keys:

{ | } ~ 

The trigraphs were defined to fix a specific problem. The idea was that C programs could use the ASCII subset found on the ASR-33 and in other environments missing the high ASCII values.

Your example is actually two of ??!, each meaning |, so the result is ||.

However, people writing C code almost by definition had modern equipment,1 so my guess is: someone showing off or amusing themself, leaving a kind of Easter egg in the code for you to find.

It sure worked, it led to a wildly popular SO question.

ASR-33 Teletype

                                            ASR-33 Teletype


1. For that matter, the trigraphs were invented by the ANSI committee, which first met after C become a runaway success, so none of the original C code or coders would have used them.

How to use putExtra() and getExtra() for string data

Simple, In first Activity-

    EditText name= (EditText) findViewById(R.id.editTextName);
    Button button= (Button) findViewById(R.id.buttonGo);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(MainActivity.this,Main2Activity.class);
            i.putExtra("name",name.getText().toString());
           startActivity(i);
          }
    });

In second Activity-

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    TextView t = (TextView) findViewById(R.id.textView);
    Bundle bundle=getIntent().getExtras();
    String s=bundle.getString("name");
    t.setText(s);
}

You can add if/else conditions if you want.

SQL query to group by day

If you're using SQL Server, you could add three calculated fields to your table:

Sales (saleID INT, amount INT, created DATETIME)

ALTER TABLE dbo.Sales
  ADD SaleYear AS YEAR(Created) PERSISTED
ALTER TABLE dbo.Sales
  ADD SaleMonth AS MONTH(Created) PERSISTED
ALTER TABLE dbo.Sales
  ADD SaleDay AS DAY(Created) PERSISTED

and now you could easily group by, order by etc. by day, month or year of the sale:

SELECT SaleDay, SUM(Amount)
FROM dbo.Sales
GROUP BY SaleDay

Those calculated fields will always be kept up to date (when your "Created" date changes), they're part of your table, they can be used just like regular fields, and can even be indexed (if they're "PERSISTED") - great feature that's totally underused, IMHO.

Marc

How to make modal dialog in WPF?

Did you try showing your window using the ShowDialog method?

Don't forget to set the Owner property on the dialog window to the main window. This will avoid weird behavior when Alt+Tabbing, etc.

How to access a preexisting collection with Mongoose?

Mongoose added the ability to specify the collection name under the schema, or as the third argument when declaring the model. Otherwise it will use the pluralized version given by the name you map to the model.

Try something like the following, either schema-mapped:

new Schema({ url: String, text: String, id: Number}, 
           { collection : 'question' });   // collection name

or model mapped:

mongoose.model('Question', 
               new Schema({ url: String, text: String, id: Number}), 
               'question');     // collection name

Select 2 columns in one and combine them

Yes, you can combine columns easily enough such as concatenating character data:

select col1 | col 2 as bothcols from tbl ...

or adding (for example) numeric data:

select col1 + col2 as bothcols from tbl ...

In both those cases, you end up with a single column bothcols, which contains the combined data. You may have to coerce the data type if the columns are not compatible.

How can I easily switch between PHP versions on Mac OSX?

If you have both versions of PHP installed, you can switch between versions using the link and unlink brew commands.

For example, to switch between PHP 7.4 and PHP 7.3

brew unlink [email protected]
brew link [email protected]

PS: both versions of PHP have be installed for these commands to work.

How to find text in a column and saving the row number where it is first found - Excel VBA

Alternatively you could use a loop, keep the row number (counter should be the row number) and stop the loop when you find the first "ProjTemp".
Then it should look something like this:

Sub find()
    Dim i As Integer
    Dim firstTime As Integer
    Dim bNotFound As Boolean

    i = 1
    bNotFound = True

      Do While bNotFound
        If Cells(i, 2).Value = "ProjTemp" Then
            firstTime = i
            bNotFound = false
        End If
        i = i + 1
    Loop
End Sub

How to prevent background scrolling when Bootstrap 3 modal open on mobile browsers?

Had an issue with this as well, iPhone + Safari where needed to add:

position: fixed;

As mentioned elsewhere, this created a scroll-to-top issue. Fix that worked for me was to capture the position to top upon modal open, and then animate to that position on modal close

upon modal open:

scrollTo = $('body').scrollTop();
$('body').css("position", "fixed");

upon modal close

$('body').css("position", "static");
$('body').animate({scrollTop: scrollTo}, 0);

jQuery DIV click, with anchors

Using a custom url attribute makes the HTML invalid. Although that may not be a huge problem, the given examples are neither accessible. Not for keyboard navigation and not in cases when JavaScript is turned off (or blocked by some other script). Even Google will not find the page located at the specified url, not via this route at least.

It's quite easy to make this accessible though. Just make sure there's a regular link inside the div that points to the url. Using JavaScript/jQuery you add an onclick to the div that redirects to the location specified by the link's href attribute. Now, when JavaScript doesn't work, the link still does and it can even catch the focus when using the keyboard to navigate (and you don't need custom attributes, so your HTML can be valid).


I wrote a jQuery plugin some time ago that does this. It also adds classNames to the div (or any other element you want to make clickable) and the link so you can alter their looks with CSS when the div is indeed clickable. It even adds classNames that you can use to specify hover and focus styles.

All you need to do is specify the element(s) you want to make clickable and call their clickable() method: in your case that would be $("div.clickable).clickable();

For downloading + documentation see the plugin's page: jQuery: clickable — jLix

Force youtube embed to start in 720p

I've managed to get this working by the following fix:

//www.youtube.com/embed/_YOUR_VIDEO_CODE_/?vq=hd720

You video should have the hd720 resolution to do so.

I was using the embedding via iframe, BTW. Hope someone will find this helpful.

Date object to Calendar [Java]

something like

movie.setStopDate(movie.getStartDate() + movie.getDurationInMinutes()* 60000);

Way to insert text having ' (apostrophe) into a SQL table

try this

INSERT INTO exampleTbl VALUES('he doesn''t work for me')

add scroll bar to table body

This is because you are adding your <tbody> tag before <td> in table you cannot print any data without <td>.

So for that you have to make a <div> say #header with position: fixed;

 header
 {
      position: fixed;
 }

make another <div> which will act as <tbody>

tbody
{
    overflow:scroll;
}

Now your header is fixed and the body will scroll. And the header will remain there.

SQL Server: Query fast, but slow from procedure

This time you found your problem. If next time you are less lucky and cannot figure it out, you can use plan freezing and stop worrying about wrong execution plan.

Automated way to convert XML files to SQL database?

For Mysql please see the LOAD XML SyntaxDocs.

It should work without any additional XML transformation for the XML you've provided, just specify the format and define the table inside the database firsthand with matching column names:

LOAD XML LOCAL INFILE 'table1.xml'
    INTO TABLE table1
    ROWS IDENTIFIED BY '<table1>';

There is also a related question:

For Postgresql I do not know.

Passing arrays as parameters in bash

Requirement: Function to find a string in an array.
This is a slight simplification of DevSolar's solution in that it uses the arguments passed rather than copying them.

myarray=('foobar' 'foxbat')

function isInArray() {
  local item=$1
  shift
  for one in $@; do
    if [ $one = $item ]; then
      return 0   # found
    fi
  done
  return 1       # not found
}

var='foobar'
if isInArray $var ${myarray[@]}; then
  echo "$var found in array"
else
  echo "$var not found in array"
fi 

Print raw string from variable? (not getting the answers)

In general, to make a raw string out of a string variable, I use this:

string = "C:\\Windows\Users\alexb"

raw_string = r"{}".format(string)

output:

'C:\\\\Windows\\Users\\alexb'

SQL Server - Convert varchar to another collation (code page) to fix character encoding

Must be used convert, not cast:

SELECT
 CONVERT(varchar(50), N'æøåáälcçcédnoöruýtžš')
 COLLATE Cyrillic_General_CI_AI

(http://blog.sqlpositive.com/2010/03/using-convert-with-collate-to-strip-accents-from-unicode-strings/)

Android Closing Activity Programmatically

What about the Activity.finish() method (quoting) :

Call this when your activity is done and should be closed.

SQL variable to hold list of integers

You are right, there is no datatype in SQL-Server which can hold a list of integers. But what you can do is store a list of integers as a string.

DECLARE @listOfIDs varchar(8000);
SET @listOfIDs = '1,2,3,4';

You can then split the string into separate integer values and put them into a table. Your procedure might already do this.

You can also use a dynamic query to achieve the same outcome:

DECLARE @SQL nvarchar(8000);

SET @SQL = 'SELECT * FROM TabA WHERE TabA.ID IN (' + @listOfIDs + ')';
EXECUTE (@SQL);

AngularJs .$setPristine to reset form

Just for those who want to get $setPristine without having to upgrade to v1.1.x, here is the function I used to simulate the $setPristine function. I was reluctant to use the v1.1.5 because one of the AngularUI components I used is no compatible.

var setPristine = function(form) {
    if (form.$setPristine) {//only supported from v1.1.x
        form.$setPristine();
    } else {
        /*
         *Underscore looping form properties, you can use for loop too like:
         *for(var i in form){ 
         *  var input = form[i]; ...
         */
        _.each(form, function (input) {
            if (input.$dirty) {
                input.$dirty = false;
            }
        });
    }
};

Note that it ONLY makes $dirty fields clean and help changing the 'show error' condition like $scope.myForm.myField.$dirty && $scope.myForm.myField.$invalid.

Other parts of the form object (like the css classes) still need to consider, but this solve my problem: hide error messages.

Redirect pages in JSP?

Extending @oopbase's answer with return; statement.

Let's consider a use case of traditional authentication system where we store login information into the session. On each page we check for active session like,

/* Some Import Statements here. */

if(null == session || !session.getAttribute("is_login").equals("1")) {
    response.sendRedirect("http://domain.com/login");
}

// ....

session.getAttribute("user_id");

// ....
/* Some More JSP+Java+HTML code here */

It looks fine at first glance however; It has one issue. If your server has expired session due to time limit and user is trying to access the page he might get error if you have not written your code in try..catch block or handled if(null != session.getAttribute("attr_name")) everytime.

So by putting a return; statement I stopped further execution and forced to redirect page to certain location.

if(null == session || !session.getAttribute("is_login").equals("1")) {
    response.sendRedirect("http://domain.com/login");
    return;
}

Note that Use of redirection may vary based on the requirements. Nowadays people don't use such authentication system. (Modern approach - Token Based Authentication) It's just an simple example to understand where and how to place redirection(s).

Count if two criteria match - EXCEL formula

If youR data was in A1:C100 then:

Excel - all versions

=SUMPRODUCT(--(A1:A100="M"),--(C1:C100="Yes"))

Excel - 2007 onwards

=COUNTIFS(A1:A100,"M",C1:C100,"Yes")

SQL Server - copy stored procedures from one db to another

This code copies all stored procedures in the Master database to the target database, you can copy just the procedures you like by filtering the query on procedure name.

@sql is defined as nvarchar(max), @Name is the target database

DECLARE c CURSOR FOR 
   SELECT Definition
   FROM [ResiDazeMaster].[sys].[procedures] p
   INNER JOIN [ResiDazeMaster].sys.sql_modules m ON p.object_id = m.object_id

OPEN c

FETCH NEXT FROM c INTO @sql

WHILE @@FETCH_STATUS = 0 
BEGIN
   SET @sql = REPLACE(@sql,'''','''''')
   SET @sql = 'USE [' + @Name + ']; EXEC(''' + @sql + ''')'

   EXEC(@sql)

   FETCH NEXT FROM c INTO @sql
END             

CLOSE c
DEALLOCATE c

Python string.replace regular expression

str.replace() v2|v3 does not recognize regular expressions.

To perform a substitution using a regular expression, use re.sub() v2|v3.

For example:

import re

line = re.sub(
           r"(?i)^.*interfaceOpDataFile.*$", 
           "interfaceOpDataFile %s" % fileIn, 
           line
       )

In a loop, it would be better to compile the regular expression first:

import re

regex = re.compile(r"^.*interfaceOpDataFile.*$", re.IGNORECASE)
for line in some_file:
    line = regex.sub("interfaceOpDataFile %s" % fileIn, line)
    # do something with the updated line

How to properly use the "choices" field option in Django

I think no one actually has answered to the first question:

Why did they create those variables?

Those variables aren't strictly necessary. It's true. You can perfectly do something like this:

MONTH_CHOICES = (
    ("JANUARY", "January"),
    ("FEBRUARY", "February"),
    ("MARCH", "March"),
    # ....
    ("DECEMBER", "December"),
)

month = models.CharField(max_length=9,
                  choices=MONTH_CHOICES,
                  default="JANUARY")

Why using variables is better? Error prevention and logic separation.

JAN = "JANUARY"
FEB = "FEBRUARY"
MAR = "MAR"
# (...)

MONTH_CHOICES = (
    (JAN, "January"),
    (FEB, "February"),
    (MAR, "March"),
    # ....
    (DEC, "December"),
)

Now, imagine you have a view where you create a new Model instance. Instead of doing this:

new_instance = MyModel(month='JANUARY')

You'll do this:

new_instance = MyModel(month=MyModel.JAN)

In the first option you are hardcoding the value. If there is a set of values you can input, you should limit those options when coding. Also, if you eventually need to change the code at the Model layer, now you don't need to make any change in the Views layer.

Trigger Change event when the Input value changed programmatically?

Vanilla JS solution:

var el = document.getElementById('changeProgramatic');
el.value='New Value'
el.dispatchEvent(new Event('change'));

Note that dispatchEvent doesn't work in old IE (see: caniuse). So you should probably only use it on internal websites (not on websites having wide audience).

So as of 2019 you just might want to make sure your customers/audience don't use Windows XP (yes, some still do in 2019). You might want to use conditional comments to warn customers that you don't support old IE (pre IE 11 in this case), but note that conditional comments only work until IE9 (don't work in IE10). So you might want to use feature detection instead. E.g. you could do an early check for: typeof document.body.dispatchEvent === 'function'.

How to get last inserted id?

INSERT INTO aspnet_GameProfiles(UserId,GameId) VALUES(@UserId, @GameId)"; then you can just access to the last id by ordering the table in desc way.

SELECT TOP 1 UserId FROM aspnet_GameProfiles ORDER BY UserId DESC.

Listing information about all database files in SQL Server

The query will error if multiple data files (e.g. ".ndf" file types) are used in one of the databases.

Here's a version of your query using joins instead of the sub-queries.

Cheers!

SELECT
    db.name AS DBName,
    db.database_id,
    mfr.physical_name AS DataFile,
    mfl.physical_name AS LogFile
FROM sys.databases db
    JOIN sys.master_files mfr ON db.database_id=mfr.database_id AND mfr.type_desc='ROWS'
    JOIN sys.master_files mfl ON db.database_id=mfl.database_id AND mfl.type_desc='LOG'
ORDER BY db.database_id

Call a Vue.js component method from outside the component

This is a simple way to access a component's methods from other component

// This is external shared (reusable) component, so you can call its methods from other components

export default {
   name: 'SharedBase',
   methods: {
      fetchLocalData: function(module, page){
          // .....fetches some data
          return { jsonData }
      }
   }
}

// This is your component where you can call SharedBased component's method(s)
import SharedBase from '[your path to component]';
var sections = [];

export default {
   name: 'History',
   created: function(){
       this.sections = SharedBase.methods['fetchLocalData']('intro', 'history');
   }
}

WCF change endpoint address at runtime

app.config

<client>
    <endpoint address="" binding="basicHttpBinding" 
    bindingConfiguration="LisansSoap" 
    contract="Lisans.LisansSoap" 
    name="LisansSoap" />
</client>

program

 Lisans.LisansSoapClient test = new LisansSoapClient("LisansSoap",
                         "http://webservis.uzmanevi.com/Lisans/Lisans.asmx");

 MessageBox.Show(test.LisansKontrol("","",""));

Java and HTTPS url connection without downloading certificate

If you are using any Payment Gateway to hit any url just to send a message, then i used a webview by following it : How can load https url without use of ssl in android webview

and make a webview in your activity with visibility gone. What you need to do : just load that webview.. like this:

 webViewForSms.setWebViewClient(new SSLTolerentWebViewClient());
                webViewForSms.loadUrl(" https://bulksms.com/" +
                        "?username=test&password=test@123&messageType=text&mobile="+
                        mobileEditText.getText().toString()+"&senderId=ATZEHC&message=Your%20OTP%20for%20A2Z%20registration%20is%20124");

Easy.

You will get this: SSLTolerentWebViewClient from this link: How can load https url without use of ssl in android webview

How to select from subquery using Laravel Query Builder?

The solution of @JarekTkaczyk it is exactly what I was looking for. The only thing I miss is how to do it when you are using DB::table() queries. In this case, this is how I do it:

$other = DB::table( DB::raw("({$sub->toSql()}) as sub") )->select(
    'something', 
    DB::raw('sum( qty ) as qty'), 
    'foo', 
    'bar'
);
$other->mergeBindings( $sub );
$other->groupBy('something');
$other->groupBy('foo');
$other->groupBy('bar');
print $other->toSql();
$other->get();

Special atention how to make the mergeBindings without using the getQuery() method

How to restart Activity in Android

This is by far the easiest way to restart the current activity:

finish();
startActivity(getIntent());

Material Design not styling alert dialogs

AppCompat doesn't do that for dialogs (not yet at least)

EDIT: it does now. make sure to use android.support.v7.app.AlertDialog

Can't stop rails server

Following are steps to kill server process:

1. lsof -i tcp:3000

2. kill -9 1234

where 1234 is the PID of process: localhost:3000 display in step 1.

OR

Remove file(server.pid) under Rails.root/tmp/pids/ and restart server.

OR

open app in another port by using command:

rails s -p 3001

Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'

If you have this in your application.properties:

spring.datasource.driverClassName=com.mysql.jdbc.Driver,

you can get rid of the error by removing that line.

"Post Image data using POSTMAN"

Follow the below steps:

  1. No need to give any type of header.
  2. Select body > form-data and do same as shown in the image. 1

  3. Now in your Django view.py

def post(self, request, *args, **kwargs):
    image = request.FILES["image"]
    data = json.loads(request.data['data'])
    ...
    return Response(...)
  1. You can access all the keys (id, uid etc..) from the data variable.

Convert char array to single int?

There are mulitple ways of converting a string to an int.

Solution 1: Using Legacy C functionality

int main()
{
    //char hello[5];     
    //hello = "12345";   --->This wont compile

    char hello[] = "12345";

    Printf("My number is: %d", atoi(hello)); 

    return 0;
}

Solution 2: Using lexical_cast(Most Appropriate & simplest)

int x = boost::lexical_cast<int>("12345"); 

Solution 3: Using C++ Streams

std::string hello("123"); 
std::stringstream str(hello); 
int x;  
str >> x;  
if (!str) 
{      
   // The conversion failed.      
} 

matrix multiplication algorithm time complexity

Using linear algebra, there exist algorithms that achieve better complexity than the naive O(n3). Solvay Strassen algorithm achieves a complexity of O(n2.807) by reducing the number of multiplications required for each 2x2 sub-matrix from 8 to 7.

The fastest known matrix multiplication algorithm is Coppersmith-Winograd algorithm with a complexity of O(n2.3737). Unless the matrix is huge, these algorithms do not result in a vast difference in computation time. In practice, it is easier and faster to use parallel algorithms for matrix multiplication.

Change language for bootstrap DateTimePicker

all you are right! other way to getting !

https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/locales/bootstrap-datepicker.ru.min.js

You can find out all languages on there https://cdnjs.com/libraries/bootstrap-datepicker

https://labs.maarch.org/maarch/maarchRM/commit/3299d1e7ed25018b48715e16a42d52c288b4da3e

Epoch vs Iteration when training neural networks

In the neural network terminology:

  • one epoch = one forward pass and one backward pass of all the training examples
  • batch size = the number of training examples in one forward/backward pass. The higher the batch size, the more memory space you'll need.
  • number of iterations = number of passes, each pass using [batch size] number of examples. To be clear, one pass = one forward pass + one backward pass (we do not count the forward pass and backward pass as two different passes).

Example: if you have 1000 training examples, and your batch size is 500, then it will take 2 iterations to complete 1 epoch.

FYI: Tradeoff batch size vs. number of iterations to train a neural network


The term "batch" is ambiguous: some people use it to designate the entire training set, and some people use it to refer to the number of training examples in one forward/backward pass (as I did in this answer). To avoid that ambiguity and make clear that batch corresponds to the number of training examples in one forward/backward pass, one can use the term mini-batch.

How can I align all elements to the left in JPanel?

You should use setAlignmentX(..) on components you want to align, not on the container that has them..

JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(c1);
panel.add(c2);

c1.setAlignmentX(Component.LEFT_ALIGNMENT);
c2.setAlignmentX(Component.LEFT_ALIGNMENT);

HTML Drag And Drop On Mobile Devices

For vue 3, there is https://github.com/SortableJS/vue.draggable.next

For vue 2, it's https://github.com/SortableJS/Vue.Draggable

The latter you can use like this:

<draggable v-model="myArray" group="people" @start="drag=true" @end="drag=false">
   <div v-for="element in myArray" :key="element.id">{{element.name}}</div>
</draggable>

These are based on sortable.js

How different is Objective-C from C++?

As others have said, Objective-C is much more dynamic in terms of how it thinks of objects vs. C++'s fairly static realm.

Objective-C, being in the Smalltalk lineage of object-oriented languages, has a concept of objects that is very similar to that of Java, Python, and other "standard", non-C++ object-oriented languages. Lots of dynamic dispatch, no operator overloading, send messages around.

C++ is its own weird animal; it mostly skipped the Smalltalk portion of the family tree. In some ways, it has a good module system with support for inheritance that happens to be able to be used for object-oriented programming. Things are much more static (overridable methods are not the default, for example).

How can I pass a parameter to a setTimeout() callback?

I think you want:

setTimeout("postinsql(" + topicId + ")", 4000);

How can I add a string to the end of each line in Vim?

Even shorter than the :search command:

:%norm A*

This is what it means:

 %       = for every line
 norm    = type the following commands
 A*      = append '*' to the end of current line

Clearing a string buffer/builder after loop

The easiest way to reuse the StringBuffer is to use the method setLength()

public void setLength(int newLength)

You may have the case like

StringBuffer sb = new StringBuffer("HelloWorld");
// after many iterations and manipulations
sb.setLength(0);
// reuse sb

How to distinguish between left and right mouse click with jQuery

$("body").on({
    click: function(){alert("left click");},
    contextmenu: function(){alert("right click");}   
});

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

Use stat like this:

#include <sys/stat.h>   // stat
#include <stdbool.h>    // bool type

bool file_exists (char *filename) {
  struct stat   buffer;   
  return (stat (filename, &buffer) == 0);
}

and call it like this:

#include <stdio.h>      // printf

int main(int ac, char **av) {
    if (ac != 2)
        return 1;

    if (file_exists(av[1]))
        printf("%s exists\n", av[1]);
    else
        printf("%s does not exist\n", av[1]);

    return 0;
}

How can I return the difference between two lists?

With Stream API you can do something like this:

List<String> aWithoutB = a.stream()
    .filter(element -> !b.contains(element))
    .collect(Collectors.toList());

List<String> bWithoutA = b.stream()
    .filter(element -> !a.contains(element))
    .collect(Collectors.toList());

How to cancel/abort jQuery AJAX request?

You can use jquery-validate.js . The following is the code snippet from jquery-validate.js.

// ajax mode: abort
// usage: $.ajax({ mode: "abort"[, port: "uniqueport"]});
// if mode:"abort" is used, the previous request on that port (port can be undefined) is aborted via XMLHttpRequest.abort()

var pendingRequests = {},
    ajax;
// Use a prefilter if available (1.5+)
if ( $.ajaxPrefilter ) {
    $.ajaxPrefilter(function( settings, _, xhr ) {
        var port = settings.port;
        if ( settings.mode === "abort" ) {
            if ( pendingRequests[port] ) {
                pendingRequests[port].abort();
            }
            pendingRequests[port] = xhr;
        }
    });
} else {
    // Proxy ajax
    ajax = $.ajax;
    $.ajax = function( settings ) {
        var mode = ( "mode" in settings ? settings : $.ajaxSettings ).mode,
            port = ( "port" in settings ? settings : $.ajaxSettings ).port;
        if ( mode === "abort" ) {
            if ( pendingRequests[port] ) {
                pendingRequests[port].abort();
            }
            pendingRequests[port] = ajax.apply(this, arguments);
            return pendingRequests[port];
        }
        return ajax.apply(this, arguments);
    };
}

So that you just only need to set the parameter mode to abort when you are making ajax request.

Ref:https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.14.0/jquery.validate.js

How can I parse a YAML file in Python

Example:


defaults.yaml

url: https://www.google.com

environment.py

from ruamel import yaml

data = yaml.safe_load(open('defaults.yaml'))
data['url']

How to programmatically determine the current checked out Git branch

I found that calling git is rather slow (any of the subcommands), especially for updating the prompt. Time varies between .1 and .2 seconds within the root dir of a repo, and over .2 seconds outside a repo, on a top notch machine (raid 1, 8 gb ram, 8 hardware threads). It does run Cygwin, though.

Therefore I wrote this script for speed:

#!/usr/bin/perl

$cwd=$ENV{PWD}; #`pwd`;
chomp $cwd;

while (length $cwd)
{
        -d "$cwd/.git" and do {
                -f "$cwd/.git/HEAD" and do {
                        open IN, "<", "$cwd/.git/HEAD";
                        $_=<IN>;
                        close IN;
                        s@ref: refs/heads/@@;
                        print $_;
                };
                exit;
        };

        $cwd=~s@/[^/]*$@@;
}

May need some tweaking.

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

I've been trying to do something very similar but not using the nodes. However, my xml structure is a little different.

You have it like this:

<Metrics>
    <Metric id="TransactionCleanupThread.RefundOldTrans" type="timer" ...>

If it were like this instead:

<Metrics>
    <Metric>
        <id>TransactionCleanupThread.RefundOldTrans</id>
        <type>timer</type>
        .
        .
        .

Then you could simply use this SQL statement.

SELECT
    Sqm.SqmId,
    Data.value('(/Sqm/Metrics/Metric/id)[1]', 'varchar(max)') as id,
    Data.value('(/Sqm/Metrics/Metric/type)[1]', 'varchar(max)') AS type,
    Data.value('(/Sqm/Metrics/Metric/unit)[1]', 'varchar(max)') AS unit,
    Data.value('(/Sqm/Metrics/Metric/sum)[1]', 'varchar(max)') AS sum,
    Data.value('(/Sqm/Metrics/Metric/count)[1]', 'varchar(max)') AS count,
    Data.value('(/Sqm/Metrics/Metric/minValue)[1]', 'varchar(max)') AS minValue,
    Data.value('(/Sqm/Metrics/Metric/maxValue)[1]', 'varchar(max)') AS maxValue,
    Data.value('(/Sqm/Metrics/Metric/stdDeviation)[1]', 'varchar(max)') AS stdDeviation,
FROM Sqm

To me this is much less confusing than using the outer apply or cross apply.

I hope this helps someone else looking for a simpler solution!

How to append elements into a dictionary in Swift?

Given two dictionaries as below:

var dic1 = ["a": 1, "c": 2]
var dic2 = ["e": 3, "f": 4]

Here is how you can add all the items from dic2 to dic1:

dic2.forEach {
   dic1[$0.key] = $0.value
}

http to https through .htaccess

Try this RewriteCond %{HTTP_HOST} !^www. [NC] RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

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

I had the same issue, I had to convert my shared project into a portable class library.

How to clear a chart from a canvas so that hover events cannot be triggered?

This worked for me. Add a call to clearChart, at the top oF your updateChart()

`function clearChart() {
    event.preventDefault();
    var parent = document.getElementById('parent-canvas');
    var child = document.getElementById('myChart');          
    parent.removeChild(child);            
    parent.innerHTML ='<canvas id="myChart" width="350" height="99" ></canvas>';             
    return;
}`

How to extract duration time from ffmpeg output?

I recommend using json format, it's easier for parsing

ffprobe -i your-input-file.mp4 -v quiet -print_format json -show_format -show_streams -hide_banner

{
    "streams": [
        {
            "index": 0,
            "codec_name": "aac",
            "codec_long_name": "AAC (Advanced Audio Coding)",
            "profile": "HE-AACv2",
            "codec_type": "audio",
            "codec_time_base": "1/44100",
            "codec_tag_string": "[0][0][0][0]",
            "codec_tag": "0x0000",
            "sample_fmt": "fltp",
            "sample_rate": "44100",
            "channels": 2,
            "channel_layout": "stereo",
            "bits_per_sample": 0,
            "r_frame_rate": "0/0",
            "avg_frame_rate": "0/0",
            "time_base": "1/28224000",
            "duration_ts": 305349201,
            "duration": "10.818778",
            "bit_rate": "27734",
            "disposition": {
                "default": 0,
                "dub": 0,
                "original": 0,
                "comment": 0,
                "lyrics": 0,
                "karaoke": 0,
                "forced": 0,
                "hearing_impaired": 0,
                "visual_impaired": 0,
                "clean_effects": 0,
                "attached_pic": 0
            }
        }
    ],
    "format": {
        "filename": "your-input-file.mp4",
        "nb_streams": 1,
        "nb_programs": 0,
        "format_name": "aac",
        "format_long_name": "raw ADTS AAC (Advanced Audio Coding)",
        "duration": "10.818778",
        "size": "37506",
        "bit_rate": "27734",
        "probe_score": 51
    }
}

you can find the duration information in format section, works both for video and audio

ADB Android Device Unauthorized

After having spent over an hour going in rounds swearing at Samsung (mostly), Google, and who not, here are my findings, that finally helped me get the device recognized:

  • On Device:
    • Set developer mode
    • Allow USB debugging
    • Default USB configuration > Select USB tethering
    • Connect device to PC USB
  • On PC:
    • Elevated cmd/ps prompt (maybe not mandatory, but that was my drill)
    • adb kill-server (precede with .\ in ps)
    • adb start-server (while device connected) > watch for prompt on device
  • On device:
    • Always allow connections from this computer > Yes
  • On PC:
    • adb devices gets the following output:
List of devices attached
278c250cce217ece        device

Correctly Parsing JSON in Swift 3

Swift has a powerful type inference. Lets get rid of "if let" or "guard let" boilerplate and force unwraps using functional approach:

  1. Here is our JSON. We can use optional JSON or usual. I'm using optional in our example:
let json: Dictionary<String, Any>? = ["current": ["temperature": 10]]
  1. Helper functions. We need to write them only once and then reuse with any dictionary:
/// Curry
public func curry<A, B, C>(_ f: @escaping (A, B) -> C) -> (A) -> (B) -> C {
    return { a in
        { f(a, $0) }
    }
}

/// Function that takes key and optional dictionary and returns optional value
public func extract<Key, Value>(_ key: Key, _ json: Dictionary<Key, Any>?) -> Value? {
    return json.flatMap {
        cast($0[key])
    }
}

/// Function that takes key and return function that takes optional dictionary and returns optional value
public func extract<Key, Value>(_ key: Key) -> (Dictionary<Key, Any>?) -> Value? {
    return curry(extract)(key)
}

/// Precedence group for our operator
precedencegroup RightApplyPrecedence {
    associativity: right
    higherThan: AssignmentPrecedence
    lowerThan: TernaryPrecedence
}

/// Apply. g § f § a === g(f(a))
infix operator § : RightApplyPrecedence
public func §<A, B>(_ f: (A) -> B, _ a: A) -> B {
    return f(a)
}

/// Wrapper around operator "as".
public func cast<A, B>(_ a: A) -> B? {
    return a as? B
}
  1. And here is our magic - extract the value:
let temperature = (extract("temperature") § extract("current") § json) ?? NSNotFound

Just one line of code and no force unwraps or manual type casting. This code works in playground, so you can copy and check it. Here is an implementation on GitHub.

Hidden Columns in jqGrid

It is a bit old, this post. But this is my code to show/hide the columns. I use the built in function to display the columns and just mark them.

Function that displays columns shown/hidden columns. The #jqGrid is the name of my grid, and the columnChooser is the jqGrid column chooser.

  function showHideColumns() {
        $('#jqGrid').jqGrid('columnChooser', {
            width: 250,
            dialog_opts: {
                modal: true,
                minWidth: 250,
                height: 300,
                show: 'blind',
                hide: 'explode',
                dividerLocation: 0.5
            } });

Extract first and last row of a dataframe in pandas

You can also use head and tail:

In [29]: pd.concat([df.head(1), df.tail(1)])
Out[29]:
   a  b
0  1  a
3  4  d

RadioGroup: How to check programmatically

Watch out! checking the radiobutton with setChecked() is not changing the state inside the RadioGroup. For example this method from the radioGroup will return a wrong result: getCheckedRadioButtonId().

Check the radioGroup always with

mOption.check(R.id.option1);

you've been warned ;)

Converting a double to an int in C#

Casting will ignore anything after the decimal point, so 8.6 becomes 8.

Convert.ToInt32(8.6) is the safe way to ensure your double gets rounded to the nearest integer, in this case 9.

GIT vs. Perforce- Two VCS will enter... one will leave

I use Perforce at work. I also use Git because I would still like some form of version control when I'm working on code and can't connect to the server. No, reconcile offline work just is not the same. Here is where I've found git to be a great benefit:

  1. Branching speed - git takes a few seconds at most.
  2. Conflicts - P4Merge's auto resolve destroyed a week's worth of work once. Ever since then I would rather resolve by hand when merging. When Git prompts me about a conflict, it is actually a conflict. The rest of the time, git resolves stuff correctly and I save heaps of time.
  3. Keeping track of merges - If you have one branch that is continuously receiving merges from two other branches, you know what a headache this can be with perforce. With git, the headache is minimized because the result of a merge in git is actually a new commit which knows who its ancestors are.
  4. Permissions - I have lost track of the number of times I've tried to work on a file but couldn't because it was not checked out in Perforce. If you worked with XCode (or any editor that does not have a solid Perforce SCM plugin) offline, you know how irritating this can get. I don't have to worry about that with Git. I make my changes. Git does not stop me and tracks them in the background.
  5. Keeping the main tree tidy - With git, I can sort my commits and tidy the code up so that the history looks nice and tidy. None of that "checking in this file because it was supposed to be part of the previous checkin" rubbish. I squash commits like that, because they help nobody.
  6. Stashing - Your perforce server needs to be version 2010.1 or newer to use the p4 shelve command.
  7. Creating patches - Easy to do in git. Don't know if it is possible in Perforce without using the command line.
  8. Mailing patches from the GUI - again, git wins here.
  9. Disk space - With perforce, every branch is a copy. That means if your source tree is huge, your disk space gets eaten up fast. This is not even counting the additional space once you start building. Why even have a link between branches and disk space? With git, you can have 100 branches and only one branch at a time ever exists. If you specifically want to work on two versions simultaneously you can clone, do your work and then get rid of one clone if you want, without losing anything.
  10. If you're on XCode4, perforce support has been dropped and git support is now built in. If you do cross platform work like I do, this matters a lot. With Visual Studio, you can use git extensions. With perforce, it's equally yuck on both OSes. Well, maybe a little more on mac now with XCode4 on the scene.
  11. Finding the faulty checkin (or, git bisect rules) - Ever tried to do a binary search with perforce to figure out where a bug was introduced? Quite a hassle, yes? Even more of a hassle when there have been integrates from other branches in the middle. Why? Because there is no automation for such tasks. You need to write your own tool to talk to perforce and you usually don't have the time. With git, you give it the starting points (the "good" point and the "bad" point) and it automates the search for you. Even better, if you have a script that can automate the build and test process, you can hook git up to the script and the whole process of finding the checkin is automated. That is how it should be.
  12. Tracking changes across refactors - Try splitting BigClass into SmallClass1 and SmallClass2. To Perforce, BigClass has now ceased to exist and two new classes (SmallClass1 and SmallClass2 have joined the source tree). To Perforce, there is no relation between BigClass and SmallClass1 and SmallClass2. Git, on the other hand, is smart enough to know that x% of BigClass is now in SmallClass1 and y% of BigClass is in SmallClass2 and that BigClass has ceased to exist. Now, from the point of view of someone who is reviewing changes across multiple branches, you tell me which approach you'd find more useful - Git's or Perforce's. Personally, I prefer Git's approach because it more accurately reflects the actual change in the code. Git is able to do this because it tracks content within the file and not the file itself.
  13. Centralized or decentralized: Git is a DVCS system while perforce is centralized. A centralized VCS cannot be decentralized later, but a DVCS (especially git) can be centralized. There are several products that add very fine grained access control to git, if that is something the business needs. Personally, I would go with a system that gives me greater flexibility in the long term.
  14. Branch mappings: If you want to do branching right in Perforce, you need to create a branch mapping. There are reasons for this, but they are tied to how Perforce conceptualizes a branch. As a developer, or a team, this simply means one more step in the work flow, which I do not consider efficient at all.
  15. Sharing work between teams: With Perforce, you cannot break up a submission. Team A is working on feature A. Team B on feature B. Team C works on bug fixes. Now, Teams A & B have to fix a bunch of bugs in order to implement their features. The only thing is, they weren't so disciplined when committing their changes (probably because they're rushing to a deadline) and so their "bug fixes" are parts of larger submissions that also contain new stuff as far as version control on their branches are concerned. However, Team C is now doing a point release and would like to get the bug fixes from the other teams. If they were using Git, Team C could cherry pick the other teams' relevant changes, split them up and only take what they needed without worrying about introducing any partially implemented features. With Perforce, Team C can get the affected files, but would have to separate the relevant changes using a much more manual process.
  16. Changing platform - If, for whatever reason in the future, you decide to change your platform of choice, with Perforce, you're at the mercy of Perforce.com and the availability of the tools for the platform of your choosing.
  17. Changing to future amazing source control engine X - If you decide to change what you use for source control, extracting your source control history from Perforce and moving it to new system X is going to be a nightmare, because it is closed source and the best you can do is guess - just Google for Perforce to Git migration to get a sense of what I'm talking about. At least with Git, its open source, so it eliminates a lot of the guesswork involved.

Well, that's my 2 cents. In Perforce's defense, I gotta say their customer support rules and so does their Time Lapse View tool. I do not know how to get a time lapse view with git. But for the convenience and time saved, I'd go with git any day.

HTML image bottom alignment inside DIV container

<div> with some proportions

div {
  position: relative;
  width: 100%;
  height: 100%;
}

<img>'s with their own proportions

img {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  width: auto; /* to keep proportions */
  height: auto; /* to keep proportions */
  max-width: 100%; /* not to stand out from div */
  max-height: 100%; /* not to stand out from div */
  margin: auto auto 0; /* position to bottom and center */
}

How to convert a "dd/mm/yyyy" string to datetime in SQL Server?

You can convert a string to a date easily by:

CAST(YourDate AS DATE)

How do I perform a JAVA callback between classes?

Define an interface, and implement it in the class that will receive the callback.

Have attention to the multi-threading in your case.

Code example from http://cleancodedevelopment-qualityseal.blogspot.com.br/2012/10/understanding-callbacks-with-java.html

interface CallBack {                   //declare an interface with the callback methods, so you can use on more than one class and just refer to the interface
    void methodToCallBack();
}

class CallBackImpl implements CallBack {          //class that implements the method to callback defined in the interface
    public void methodToCallBack() {
        System.out.println("I've been called back");
    }
}

class Caller {

    public void register(CallBack callback) {
        callback.methodToCallBack();
    }

    public static void main(String[] args) {
        Caller caller = new Caller();
        CallBack callBack = new CallBackImpl();       //because of the interface, the type is Callback even thought the new instance is the CallBackImpl class. This alows to pass different types of classes that have the implementation of CallBack interface
        caller.register(callBack);
    }
} 

In your case, apart from multi-threading you could do like this:

interface ServerInterface {
    void newSeverConnection(Socket socket);
}

public class Server implements ServerInterface {

    public Server(int _address) {
        System.out.println("Starting Server...");
        serverConnectionHandler = new ServerConnections(_address, this);
        workers.execute(serverConnectionHandler);
        System.out.println("Do something else...");
    }

    void newServerConnection(Socket socket) {
        System.out.println("A function of my child class was called.");
    }

}

public class ServerConnections implements Runnable {

    private ServerInterface serverInterface;

    public ServerConnections(int _serverPort, ServerInterface _serverInterface) {
      serverPort = _serverPort;
      serverInterface = _serverInterface;
    }

    @Override
    public void run() {
        System.out.println("Starting Server Thread...");

        if (serverInterface == null) {
            System.out.println("Server Thread error: callback null");
        }

        try {
            mainSocket = new ServerSocket(serverPort);

            while (true) {
                serverInterface.newServerConnection(mainSocket.accept());
            }
        } catch (IOException ex) {
            Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

Multi-threading

Remember this does not handle multi-threading, this is another topic and can have various solutions depending on the project.

The observer-pattern

The observer-pattern does nearly this, the major difference is the use of an ArrayList for adding more than one listener. Where this is not needed, you get better performance with one reference.

Text overflow ellipsis on two lines

Css below should do the trick.

After the second line the, text will contain ...

line-height: 1em;
max-height: 2em;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;

How to get parameter value for date/time column from empty MaskedTextBox

You're storing the .Text properties of the textboxes directly into the database, this doesn't work. The .Text properties are Strings (i.e. simple text) and not typed as DateTime instances. Do the conversion first, then it will work.

Do this for each date parameter:

Dim bookIssueDate As DateTime = DateTime.ParseExact( txtBookDateIssue.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture ) cmd.Parameters.Add( New OleDbParameter("@Date_Issue", bookIssueDate ) ) 

Note that this code will crash/fail if a user enters an invalid date, e.g. "64/48/9999", I suggest using DateTime.TryParse or DateTime.TryParseExact, but implementing that is an exercise for the reader.

If else in stored procedure sql server

Thank you all for your answers but I figured out how to do it and the final procedure looks like that :

Create Procedure sp_ADD_RESPONSABLE_EXTRANET_CLIENT
(
@ParLngId int output
)
as
Begin
if not exists (Select ParLngId from T_Param where ParStrIndex = 'RES' and ParStrP2 = 'Web')
    Begin
            INSERT INTO T_Param values('RES','¤ExtranetClient', 'ECli', 'Web', 1, 1, Null, Null, 'non', 'ExtranetClient', 'ExtranetClient', 25032, Null, '[email protected]', 'Extranet-Client', Null, 27, Null, Null, Null, Null, Null, Null, Null, Null, 1, Null, Null, 0 )
            SET @ParLngId = @@IDENTITY
    End
Else
    Begin
            SET @ParLngId = (Select top 1 ParLngId from T_Param where ParStrNom = 'Extranet Client')
            Return @ParLngId
    End   
End

So the thing that I found out and which made it works is:

if not exists

It allows us to use a boolean instead of Null or 0 or a number resulted of count()

Set System.Drawing.Color values

using System;
using System.Drawing;
public struct MyColor
    {
        private byte a, r, g, b;        
        public byte A
        {
            get
            {
                return this.a;
            }
        }
        public byte R
        {
            get
            {
                return this.r;
            }
        }
        public byte G
        {
            get
            {
                return this.g;
            }
        }
        public byte B
        {
            get
            {
                return this.b;
            }
        }       
        public MyColor SetAlpha(byte value)
        {
            this.a = value;
            return this;
        }
        public MyColor SetRed(byte value)
        {
            this.r = value;
            return this;
        }
        public MyColor SetGreen(byte value)
        {
            this.g = value;
            return this;
        }
        public MyColor SetBlue(byte value)
        {
            this.b = value;
            return this;
        }
        public int ToArgb()
        {
            return (int)(A << 24) || (int)(R << 16) || (int)(G << 8) || (int)(B);
        }
        public override string ToString ()
        {
            return string.Format ("[MyColor: A={0}, R={1}, G={2}, B={3}]", A, R, G, B);
        }

        public static MyColor FromArgb(byte alpha, byte red, byte green, byte blue)
        {
            return new MyColor().SetAlpha(alpha).SetRed(red).SetGreen(green).SetBlue(blue);
        }
        public static MyColor FromArgb(byte red, byte green, byte blue)
        {
            return MyColor.FromArgb(255, red, green, blue);
        }
        public static MyColor FromArgb(byte alpha, MyColor baseColor)
        {
            return MyColor.FromArgb(alpha, baseColor.R, baseColor.G, baseColor.B);
        }
        public static MyColor FromArgb(int argb)
        {
            return MyColor.FromArgb(argb & 255, (argb >> 8) & 255, (argb >> 16) & 255, (argb >> 24) & 255);
        }   
        public static implicit operator Color(MyColor myColor)
        {           
            return Color.FromArgb(myColor.ToArgb());
        }
        public static implicit operator MyColor(Color color)
        {
            return MyColor.FromArgb(color.ToArgb());
        }
    }

Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

i had the same problem and it seems like i didn't initiate the button used with click listener, in other words id didn't te

Check string for palindrome

I worked on a solution for a question that was marked as duplicate of this one. Might as well throw it here...

The question requested a single line to solve this, and I took it more as the literary palindrome - so spaces, punctuation and upper/lower case can throw off the result.

Here's the ugly solution with a small test class:

public class Palindrome {
   public static boolean isPalendrome(String arg) {
         return arg.replaceAll("[^A-Za-z]", "").equalsIgnoreCase(new StringBuilder(arg).reverse().toString().replaceAll("[^A-Za-z]", ""));
   }
   public static void main(String[] args) {
      System.out.println(isPalendrome("hiya"));
      System.out.println(isPalendrome("star buttons not tub rats"));
      System.out.println(isPalendrome("stab nail at ill Italian bats!"));
      return;
   }
}

Sorry that it is kind of nasty - but the other question specified a one-liner.

How to change an element's title attribute using jQuery

In jquery ui modal dialogs you need to use this construct:

$( "#my_dialog" ).dialog( "option", "title", "my new title" );

When or Why to use a "SET DEFINE OFF" in Oracle Database

By default, SQL Plus treats '&' as a special character that begins a substitution string. This can cause problems when running scripts that happen to include '&' for other reasons:

SQL> insert into customers (customer_name) values ('Marks & Spencers Ltd');
Enter value for spencers: 
old   1: insert into customers (customer_name) values ('Marks & Spencers Ltd')
new   1: insert into customers (customer_name) values ('Marks  Ltd')

1 row created.

SQL> select customer_name from customers;

CUSTOMER_NAME
------------------------------
Marks  Ltd

If you know your script includes (or may include) data containing '&' characters, and you do not want the substitution behaviour as above, then use set define off to switch off the behaviour while running the script:

SQL> set define off
SQL> insert into customers (customer_name) values ('Marks & Spencers Ltd');

1 row created.

SQL> select customer_name from customers;

CUSTOMER_NAME
------------------------------
Marks & Spencers Ltd

You might want to add set define on at the end of the script to restore the default behaviour.

MySQL's now() +1 day

Try doing: INSERT INTO table(data, date) VALUES ('$data', now() + interval 1 day)

Mapping a JDBC ResultSet to an object

Let's assume you want to use core Java, w/o any strategic frameworks. If you can guarantee, that field name of an entity will be equal to the column in database, you can use Reflection API (otherwise create annotation and define mapping name there)

By FieldName

/**

Class<T> clazz - a list of object types you want to be fetched
ResultSet resultSet - pointer to your retrieved results 

*/

    List<Field> fields = Arrays.asList(clazz.getDeclaredFields());
    for(Field field: fields) {
        field.setAccessible(true);
    }

    List<T> list = new ArrayList<>(); 
    while(resultSet.next()) {

        T dto = clazz.getConstructor().newInstance();

        for(Field field: fields) {
            String name = field.getName();

            try{
                String value = resultSet.getString(name);
                field.set(dto, field.getType().getConstructor(String.class).newInstance(value));
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        list.add(dto);

    }

By annotation

@Retention(RetentionPolicy.RUNTIME)
public @interface Col {

    String name();
}

DTO:

class SomeClass {

   @Col(name = "column_in_db_name")
   private String columnInDbName;

   public SomeClass() {}

   // ..

}

Same, but

    while(resultSet.next()) {

        T dto = clazz.getConstructor().newInstance();

        for(Field field: fields) {
            Col col = field.getAnnotation(Col.class);
            if(col!=null) {
                String name = col.name();
                try{
                    String value = resultSet.getString(name);
                    field.set(dto, field.getType().getConstructor(String.class).newInstance(value));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        list.add(dto);

    }

Thoughts

In fact, iterating over all Fields might seem ineffective, so I would store mapping somewhere, rather than iterating each time. However, if our T is a DTO with only purpose of transferring data and won't contain loads of unnecessary fields, that's ok. In the end it's much better than using boilerplate methods all the way.

Hope this helps someone.

When is a C++ destructor called?

Remember that Constructor of an object is called immediately after the memory is allocated for that object and whereas the destructor is called just before deallocating the memory of that object.

How can I print out C++ map values?

Since C++17 you can use range-based for loops together with structured bindings for iterating over your map. This improves readability, as you reduce the amount of needed first and second members in your code:

std::map<std::string, std::pair<std::string, std::string>> myMap;
myMap["x"] = { "a", "b" };
myMap["y"] = { "c", "d" };

for (const auto &[k, v] : myMap)
    std::cout << "m[" << k << "] = (" << v.first << ", " << v.second << ") " << std::endl;

Output:

m[x] = (a, b)
m[y] = (c, d)

Code on Coliru

Optional args in MATLAB functions

A simple way of doing this is via nargin (N arguments in). The downside is you have to make sure that your argument list and the nargin checks match.

It is worth remembering that all inputs are optional, but the functions will exit with an error if it calls a variable which is not set. The following example sets defaults for b and c. Will exit if a is not present.

function [ output_args ] = input_example( a, b, c )
if nargin < 1
  error('input_example :  a is a required input')
end

if nargin < 2
  b = 20
end

if nargin < 3
  c = 30
end
end

Installing and Running MongoDB on OSX

Assuming you have created the data/db directory under bin after install.

  1. Start a terminal for your mongo server
  2. Go to <mongodb-install-directory>/bin directory
  3. Run the command

    ./mongod

  4. Start a terminal for your mongo shell

  5. Go to <mongodb-install-directory>/bin directory
  6. Run the command (make sure you put the name of the database)

    ./mongo test

Makefile, header dependencies

The following works for me:

DEPS := $(OBJS:.o=.d)

-include $(DEPS)

%.o: %.cpp
    $(CXX) $(CFLAGS) -MMD -c -o $@ $<

Stopping a windows service when the stop option is grayed out

sc queryex <service name>
taskkill /F /PID <Service PID>

eg

enter image description here

eg

jquery.ajax Access-Control-Allow-Origin

At my work we have our restful services on a different port number and the data resides in db2 on a pair of AS400s. We typically use the $.getJSON AJAX method because it easily returns JSONP using the ?callback=? without having any issues with CORS.

data ='USER=<?echo trim($USER)?>' +
         '&QRYTYPE=' + $("input[name=QRYTYPE]:checked").val();

        //Call the REST program/method returns: JSONP 
        $.getJSON( "http://www.stackoverflow.com/rest/resttest?callback=?",data)
        .done(function( json ) {        

              //  loading...
                if ($.trim(json.ERROR) != '') {
                    $("#error-msg").text(message).show();
                }
                else{
                    $(".error").hide();
                    $("#jsonp").text(json.whatever);

                }

        })  
        .fail(function( jqXHR, textStatus, error ) {
        var err = textStatus + ", " + error;
        alert('Unable to Connect to Server.\n Try again Later.\n Request Failed: ' + err);
        });     

Get IFrame's document, from JavaScript in main document

The problem is that in IE (which is what I presume you're testing in), the <iframe> element has a document property that refers to the document containing the iframe, and this is getting used before the contentDocument or contentWindow.document properties. What you need is:

function GetDoc(x) {
    return x.contentDocument || x.contentWindow.document;
}

Also, document.all is not available in all browsers and is non-standard. Use document.getElementById() instead.

Find and Replace string in all files recursive using grep and sed

sed expression needs to be quoted

sed -i "s/$oldstring/$newstring/g"

ListView item background via custom selector

It's enough,if you put in list_row_layout.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:background="@drawable/listitem_background">... </LinearLayout>

listitem_selector.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/dark" android:state_pressed="true" />
    <item android:drawable="@color/dark" android:state_focused="true" />
    <item android:drawable="@android:color/white" />
</selector>

How to add to the PYTHONPATH in Windows, so it finds my modules/packages?

Just append your installation path (ex. C:\Python27\) to the PATH variable in System variables. Then close and open your command line and type 'python'.

day of the week to day number (Monday = 1, Tuesday = 2)

$day_of_week = date('N', strtotime('Monday'));

Try-Catch-End Try in VBScript doesn't seem to work

Handling Errors

A sort of an "older style" of error handling is available to us in VBScript, that does make use of On Error Resume Next. First we enable that (often at the top of a file; but you may use it in place of the first Err.Clear below for their combined effect), then before running our possibly-error-generating code, clear any errors that have already occurred, run the possibly-error-generating code, and then explicitly check for errors:

On Error Resume Next
' ...
' Other Code Here (that may have raised an Error)
' ...
Err.Clear      ' Clear any possible Error that previous code raised
Set myObj = CreateObject("SomeKindOfClassThatDoesNotExist")
If Err.Number <> 0 Then
    WScript.Echo "Error: " & Err.Number
    WScript.Echo "Error (Hex): " & Hex(Err.Number)
    WScript.Echo "Source: " &  Err.Source
    WScript.Echo "Description: " &  Err.Description
    Err.Clear             ' Clear the Error
End If
On Error Goto 0           ' Don't resume on Error
WScript.Echo "This text will always print."

Above, we're just printing out the error if it occurred. If the error was fatal to the script, you could replace the second Err.clear with WScript.Quit(Err.Number).

Also note the On Error Goto 0 which turns off resuming execution at the next statement when an error occurs.

If you want to test behavior for when the Set succeeds, go ahead and comment that line out, or create an object that will succeed, such as vbscript.regexp.

The On Error directive only affects the current running scope (current Sub or Function) and does not affect calling or called scopes.


Raising Errors

If you want to check some sort of state and then raise an error to be handled by code that calls your function, you would use Err.Raise. Err.Raise takes up to five arguments, Number, Source, Description, HelpFile, and HelpContext. Using help files and contexts is beyond the scope of this text. Number is an error number you choose, Source is the name of your application/class/object/property that is raising the error, and Description is a short description of the error that occurred.

If MyValue <> 42 Then
    Err.Raise(42, "HitchhikerMatrix", "There is no spoon!")
End If

You could then handle the raised error as discussed above.


Change Log

  • Edit #1: Added an Err.Clear before the possibly error causing line to clear any previous errors that may have been ignored.
  • Edit #2: Clarified.
  • Edit #3: Added comments in code block. Clarified that there was expected to be more code between On Error Resume Next and Err.Clear. Fixed some grammar to be less awkward. Added info on Err.Raise. Formatting.
  • Java: How to convert String[] to List or Set

    String[] w = {"a", "b", "c", "d", "e"};  
    
    List<String> wL = Arrays.asList(w);  
    

    How can I search Git branches for a file or directory?

    git log + git branch will find it for you:

    % git log --all -- somefile
    
    commit 55d2069a092e07c56a6b4d321509ba7620664c63
    Author: Dustin Sallings <[email protected]>
    Date:   Tue Dec 16 14:16:22 2008 -0800
    
        added somefile
    
    
    % git branch -a --contains 55d2069
      otherbranch
    

    Supports globbing, too:

    % git log --all -- '**/my_file.png'
    

    The single quotes are necessary (at least if using the Bash shell) so the shell passes the glob pattern to git unchanged, instead of expanding it (just like with Unix find).

    How to force reloading php.ini file?

    You also can use graceful restart the apache server with service apache2 reload or apachectl -k graceful. As the apache doc says:

    The USR1 or graceful signal causes the parent process to advise the children to exit after their current request (or to exit immediately if they're not serving anything). The parent re-reads its configuration files and re-opens its log files. As each child dies off the parent replaces it with a child from the new generation of the configuration, which begins serving new requests immediately.

    HTML table with 100% width, with vertical scroll inside tbody

    CSS-only

    for Chrome, Firefox, Edge (and other evergreen browsers)

    Simply position: sticky; top: 0; your th elements:

    _x000D_
    _x000D_
    /* Fix table head */
    .tableFixHead    { overflow-y: auto; height: 100px; }
    .tableFixHead th { position: sticky; top: 0; }
    
    /* Just common table stuff. */
    table  { border-collapse: collapse; width: 100%; }
    th, td { padding: 8px 16px; }
    th     { background:#eee; }
    _x000D_
    <div class="tableFixHead">
      <table>
        <thead>
          <tr><th>TH 1</th><th>TH 2</th></tr>
        </thead>
        <tbody>
          <tr><td>A1</td><td>A2</td></tr>
          <tr><td>B1</td><td>B2</td></tr>
          <tr><td>C1</td><td>C2</td></tr>
          <tr><td>D1</td><td>D2</td></tr>
          <tr><td>E1</td><td>E2</td></tr>
        </tbody>
      </table>
    </div>
    _x000D_
    _x000D_
    _x000D_

    PS: if you need borders for TH elements th {box-shadow: 1px 1px 0 #000; border-top: 0;} will help (since the default borders are not painted correctly on scroll).

    For a variant of the above that uses just a bit of JS in order to accommodate for IE11 see this answer Table fixed header and scrollable body

    How do I calculate a point on a circle’s circumference?

    Implemented in JavaScript (ES6):

    /**
        * Calculate x and y in circle's circumference
        * @param {Object} input - The input parameters
        * @param {number} input.radius - The circle's radius
        * @param {number} input.angle - The angle in degrees
        * @param {number} input.cx - The circle's origin x
        * @param {number} input.cy - The circle's origin y
        * @returns {Array[number,number]} The calculated x and y
    */
    function pointsOnCircle({ radius, angle, cx, cy }){
    
        angle = angle * ( Math.PI / 180 ); // Convert from Degrees to Radians
        const x = cx + radius * Math.sin(angle);
        const y = cy + radius * Math.cos(angle);
        return [ x, y ];
    
    }
    

    Usage:

    const [ x, y ] = pointsOnCircle({ radius: 100, angle: 180, cx: 150, cy: 150 });
    console.log( x, y );
    

    Codepen

    _x000D_
    _x000D_
    /**
     * Calculate x and y in circle's circumference
     * @param {Object} input - The input parameters
     * @param {number} input.radius - The circle's radius
     * @param {number} input.angle - The angle in degrees
     * @param {number} input.cx - The circle's origin x
     * @param {number} input.cy - The circle's origin y
     * @returns {Array[number,number]} The calculated x and y
     */
    function pointsOnCircle({ radius, angle, cx, cy }){
      angle = angle * ( Math.PI / 180 ); // Convert from Degrees to Radians
      const x = cx + radius * Math.sin(angle);
      const y = cy + radius * Math.cos(angle);
      return [ x, y ];
    }
    
    const canvas = document.querySelector("canvas");
    const ctx = canvas.getContext("2d");
    
    function draw( x, y ){
    
      ctx.clearRect( 0, 0, canvas.width, canvas.height );
      ctx.beginPath();
      ctx.strokeStyle = "orange";
      ctx.arc( 100, 100, 80, 0, 2 * Math.PI);
      ctx.lineWidth = 3;
      ctx.stroke();
      ctx.closePath();
    
      ctx.beginPath();
      ctx.fillStyle = "indigo";
      ctx.arc( x, y, 6, 0, 2 * Math.PI);
      ctx.fill();
      ctx.closePath();
      
    }
    
    let angle = 0;  // In degrees
    setInterval(function(){
    
      const [ x, y ] = pointsOnCircle({ radius: 80, angle: angle++, cx: 100, cy: 100 });
      console.log( x, y );
      draw( x, y );
      document.querySelector("#degrees").innerHTML = angle + "&deg;";
      document.querySelector("#points").textContent = x.toFixed() + "," + y.toFixed();
    
    }, 100 );
    _x000D_
    <p>Degrees: <span id="degrees">0</span></p>
    <p>Points on Circle (x,y): <span id="points">0,0</span></p>
    <canvas width="200" height="200" style="border: 1px solid"></canvas>
    _x000D_
    _x000D_
    _x000D_

    How to use default Android drawables

    Java Usage example: myMenuItem.setIcon(android.R.drawable.ic_menu_save);

    Resource Usage example: android:icon="@android:drawable/ic_menu_save"

    how to set image from url for imageView

    You can also let Square's Picasso library do the heavy lifting:

    Picasso
        .get()
        .load("http://...")
        .into(imageView);
    

    As a bonus, you get caching, transformations, and more.

    How to set a single, main title above all the subplots with Pyplot?

    Use pyplot.suptitle or Figure.suptitle:

    import matplotlib.pyplot as plt
    import numpy as np
    
    fig=plt.figure()
    data=np.arange(900).reshape((30,30))
    for i in range(1,5):
        ax=fig.add_subplot(2,2,i)        
        ax.imshow(data)
    
    fig.suptitle('Main title') # or plt.suptitle('Main title')
    plt.show()
    

    enter image description here

    How can I create a self-signed cert for localhost?

    If you are trying to create a self signed certificate that lets you go http://localhost/mysite Then here is a way to create it

    makecert -r -n "CN=localhost" -b 01/01/2000 -e 01/01/2099 -eku 1.3.6.1.5.5.7.3.1 -sv localhost.pvk localhost.cer
    cert2spc localhost.cer localhost.spc
    pvk2pfx -pvk localhost.pvk -spc localhost.spc -pfx localhost.pfx
    

    From http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/32bc5a61-1f7b-4545-a514-a11652f11200

    Custom Input[type="submit"] style not working with jquerymobile button

    jQuery Mobile >= 1.4

    Create a custom class, e.g. .custom-btn. Note that to override jQM styles without using !important, CSS hierarchy should be respected. .ui-btn.custom-class or .ui-input-btn.custom-class.

    .ui-input-btn.custom-btn {
       border:1px solid red;
       text-decoration:none;
       font-family:helvetica;
       color:red;
       background:url(img.png) repeat-x;
    }
    

    Add a data-wrapper-class to input. The custom class will be added to input wrapping div.

    <input type="button" data-wrapper-class="custom-btn">
    

    Demo


    jQuery Mobile <= 1.3

    Input button is wrapped by a DIV with class ui-btn. You need to select that div and the input[type="submit"]. Using !important is essential to override Jquery Mobile styles.

    Demo

    div.ui-btn, input[type="submit"] {
     border:1px solid red !important;
     text-decoration:none !important;
     font-family:helvetica !important;
     color:red !important;
     background:url(../images/btn_hover.png) repeat-x !important;
    }
    

    REST API Best practice: How to accept list of parameter values as input

    A Step Back

    First and foremost, REST describes a URI as a universally unique ID. Far too many people get caught up on the structure of URIs and which URIs are more "restful" than others. This argument is as ludicrous as saying naming someone "Bob" is better than naming him "Joe" – both names get the job of "identifying a person" done. A URI is nothing more than a universally unique name.

    So in REST's eyes arguing about whether ?id=["101404","7267261"] is more restful than ?id=101404,7267261 or \Product\101404,7267261 is somewhat futile.

    Now, having said that, many times how URIs are constructed can usually serve as a good indicator for other issues in a RESTful service. There are a couple of red flags in your URIs and question in general.

    Suggestions

    1. Multiple URIs for the same resource and Content-Location

      We may want to accept both styles but does that flexibility actually cause more confusion and head aches (maintainability, documentation, etc.)?

      URIs identify resources. Each resource should have one canonical URI. This does not mean that you can't have two URIs point to the same resource but there are well defined ways to go about doing it. If you do decide to use both the JSON and list based formats (or any other format) you need to decide which of these formats is the main canonical URI. All responses to other URIs that point to the same "resource" should include the Content-Location header.

      Sticking with the name analogy, having multiple URIs is like having nicknames for people. It is perfectly acceptable and often times quite handy, however if I'm using a nickname I still probably want to know their full name – the "official" way to refer to that person. This way when someone mentions someone by their full name, "Nichloas Telsa", I know they are talking about the same person I refer to as "Nick".

    2. "Search" in your URI

      A more complex case is when we want to offer more complex inputs. For example, if we want to allow multiple filters on search...

      A general rule of thumb of mine is, if your URI contains a verb, it may be an indication that something is off. URI's identify a resource, however they should not indicate what we're doing to that resource. That's the job of HTTP or in restful terms, our "uniform interface".

      To beat the name analogy dead, using a verb in a URI is like changing someone's name when you want to interact with them. If I'm interacting with Bob, Bob's name doesn't become "BobHi" when I want to say Hi to him. Similarly, when we want to "search" Products, our URI structure shouldn't change from "/Product/..." to "/Search/...".

    Answering Your Initial Question

    1. Regarding ["101404","7267261"] vs 101404,7267261: My suggestion here is to avoid the JSON syntax for simplicity's sake (i.e. don't require your users do URL encoding when you don't really have to). It will make your API a tad more usable. Better yet, as others have recommended, go with the standard application/x-www-form-urlencoded format as it will probably be most familiar to your end users (e.g. ?id[]=101404&id[]=7267261). It may not be "pretty", but Pretty URIs does not necessary mean Usable URIs. However, to reiterate my initial point though, ultimately when speaking about REST, it doesn't matter. Don't dwell too heavily on it.

    2. Your complex search URI example can be solved in very much the same way as your product example. I would recommend going the application/x-www-form-urlencoded format again as it is already a standard that many are familiar with. Also, I would recommend merging the two.

    Your URI...

    /Search?term=pumas&filters={"productType":["Clothing","Bags"],"color":["Black","Red"]}    
    

    Your URI after being URI encoded...

    /Search?term=pumas&filters=%7B%22productType%22%3A%5B%22Clothing%22%2C%22Bags%22%5D%2C%22color%22%3A%5B%22Black%22%2C%22Red%22%5D%7D
    

    Can be transformed to...

    /Product?term=pumas&productType[]=Clothing&productType[]=Bags&color[]=Black&color[]=Red
    

    Aside from avoiding the requirement of URL encoding and making things look a bit more standard, it now homogenizes the API a bit. The user knows that if they want to retrieve a Product or List of Products (both are considered a single "resource" in RESTful terms), they are interested in /Product/... URIs.

    clearing a char array c

    I usually just do like this:

    memset(bufferar, '\0', sizeof(bufferar));
    

    Converting dd/mm/yyyy formatted string to Datetime

    use DateTime.ParseExact

    string strDate = "24/01/2013";
    DateTime date = DateTime.ParseExact(strDate, "dd/MM/YYYY", null)
    

    null will use the current culture, which is somewhat dangerous. Try to supply a specific culture

    DateTime date = DateTime.ParseExact(strDate, "dd/MM/YYYY", CultureInfo.InvariantCulture)
    

    What is the proper way to format a multi-line dict in Python?

    I use #3. Same for long lists, tuples, etc. It doesn't require adding any extra spaces beyond the indentations. As always, be consistent.

    mydict = {
        "key1": 1,
        "key2": 2,
        "key3": 3,
    }
    
    mylist = [
        (1, 'hello'),
        (2, 'world'),
    ]
    
    nested = {
        a: [
            (1, 'a'),
            (2, 'b'),
        ],
        b: [
            (3, 'c'),
            (4, 'd'),
        ],
    }
    

    Similarly, here's my preferred way of including large strings without introducing any whitespace (like you'd get if you used triple-quoted multi-line strings):

    data = (
        "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABG"
        "l0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAEN"
        "xBRpFYmctaKCfwrBSCrRLuL3iEW6+EEUG8XvIVjYWNgJdhFjIX"
        "rz6pKtPB5e5rmq7tmxk+hqO34e1or0yXTGrj9sXGs1Ib73efh1"
        "AAAABJRU5ErkJggg=="
    )
    

    Getting the screen resolution using PHP

    This is a very simple process. Yes, you cannot get the width and height in PHP. It is true that JQuery can provide the screen's width and height. First go to https://github.com/carhartl/jquery-cookie and get jquery.cookie.js. Here is example using php to get the screen width and height:

        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>Test</title>
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
            <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
            <script src="js/jquery.cookie.js"></script>
            <script type=text/javascript>
                function setScreenHWCookie() {
                    $.cookie('sw',screen.width);
                    $.cookie('sh',screen.height);
                    return true;
                }
                setScreenHWCookie();
            </script>
        </head>
        <body>
            <h1>Using jquery.cookie.js to store screen height and width</h1>
        <?php
             if(isset($_COOKIE['sw'])) { echo "Screen width: ".$_COOKIE['sw']."<br/>";}
             if(isset($_COOKIE['sh'])) { echo "Screen height: ".$_COOKIE['sh']."<br/>";}
        ?>
        </body>
        </html>
    

    I have a test that you can execute: http://rw-wrd.net/test.php

    destination path already exists and is not an empty directory

    Steps to get this error ;

    1. Clone a repo (for eg take name as xyz)in a folder
    2. Not try to clone again in the same folder . Even after deleting the folder manually this error will come since deleting folder doesn't delete git info .

    Solution : rm -rf "name of repo folder which in out case is xyz" . So

    rm -rf xyz
    

    Latex - Change margins of only a few pages

    I had the same problem in a beamer presentation. For me worked using the columns environment:

    \begin{frame}
      \begin{columns}
        \column{1.2\textwidth}
        \begin{figure}
          \subfigure{\includegraphics[width=.49\textwidth]{1.png}}
          \subfigure{\includegraphics[width=.49\textwidth]{2.png}}
        \end{figure}
       \end{columns}
    \end{frame}
    

    jQuery - disable selected options

    This seems to work:

    $("#theSelect").change(function(){          
        var value = $("#theSelect option:selected").val();
        var theDiv = $(".is" + value);
    
        theDiv.slideDown().removeClass("hidden");
        //Add this...
        $("#theSelect option:selected").attr('disabled', 'disabled');
    });
    
    
    $("div a.remove").click(function () {     
        $(this).parent().slideUp(function() { $(this).addClass("hidden"); });
        //...and this.
        $("#theSelect option:disabled").removeAttr('disabled');
    });
    

    How can I fix the Microsoft Visual Studio error: "package did not load correctly"?

    You need to find file devenv.exe.config in C:\Users\{user_name}\AppData\Local\Microsoft\VisualStudio\14.0\ and update it. (Or C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\, depending on the location of your devenv.exe file.)

    For this particular case, you should find rows that setup redirects for System.Collections.Immutable and change newVersion from 1.1.36.0 to 1.1.37.0.

    The original article is How to restore Visual Studio 2015 after the Update 1 (dependency dance).

    Add a string of text into an input field when user clicks a button

    Here it is: http://jsfiddle.net/tQyvp/

    Here's the code if you don't like going to jsfiddle:

    html

    <input id="myinputfield" value="This is some text" type="button">?
    

    Javascript:

    $('body').on('click', '#myinputfield', function(){
        var textField = $('#myinputfield');
        textField.val(textField.val()+' after clicking')       
    });?
    

    How do I turn a String into a InputStreamReader in java?

    Does it have to be specifically an InputStreamReader? How about using StringReader?

    Otherwise, you could use StringBufferInputStream, but it's deprecated because of character conversion issues (which is why you should prefer StringReader).

    Oracle "SQL Error: Missing IN or OUT parameter at index:: 1"

    I got the same error and found the cause to be a wrong or missing foreign key. (Using JDBC)

    WAMP Server doesn't load localhost

    Change the port 80 to port 8080 and restart all services and access like localhost:8080/

    It will work fine.

    Assign pandas dataframe column dtypes

    You're better off using typed np.arrays, and then pass the data and column names as a dictionary.

    import numpy as np
    import pandas as pd
    # Feature: np arrays are 1: efficient, 2: can be pre-sized
    x = np.array(['a', 'b'], dtype=object)
    y = np.array([ 1 ,  2 ], dtype=np.int32)
    df = pd.DataFrame({
       'x' : x,    # Feature: column name is near data array
       'y' : y,
       }
     )
    

    Cassandra port usage - how are the ports used?

    JMX now uses port 7199 instead of port 8080 (as of Cassandra 0.8.xx).

    This is configurable in your cassandra-env.sh file, but the default is 7199.

    UIView Hide/Show with animation

    You can do it VERY easily using Animatics library:

    //To hide button:
    AlphaAnimator(0) ~> button
    
    //to show button
    AlphaAnimator(1) ~> button
    

    Initializing a struct to 0

    The first is easiest(involves less typing), and it is guaranteed to work, all members will be set to 0[Ref 1].
    The second is more readable.

    The choice depends on user preference or the one which your coding standard mandates.

    [Ref 1] Reference C99 Standard 6.7.8.21:

    If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

    Good Read:
    C and C++ : Partial initialization of automatic structure

    Resize Cross Domain Iframe Height

    You need to have access as well on the site that you will be iframing. i found the best solution here: https://gist.github.com/MateuszFlisikowski/91ff99551dcd90971377

    yourotherdomain.html

    <script type='text/javascript' src="js/jquery.min.js"></script>
    <script type='text/javascript'>
      // Size the parent iFrame
      function iframeResize() {
        var height = $('body').outerHeight(); // IMPORTANT: If body's height is set to 100% with CSS this will not work.
        parent.postMessage("resize::"+height,"*");
      }
    
      $(document).ready(function() {
        // Resize iframe
        setInterval(iframeResize, 1000);
      });
    </script>
    

    your website with iframe

    <iframe src='example.html' id='edh-iframe'></iframe>
    <script type='text/javascript'>
      // Listen for messages sent from the iFrame
      var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
      var eventer = window[eventMethod];
      var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
    
      eventer(messageEvent,function(e) {
        // If the message is a resize frame request
        if (e.data.indexOf('resize::') != -1) {
          var height = e.data.replace('resize::', '');
          document.getElementById('edh-iframe').style.height = height+'px';
        }
      } ,false);
    </script>
    

    How does collections.defaultdict work?

    There is a great explanation of defaultdicts here: http://ludovf.net/blog/python-collections-defaultdict/

    Basically, the parameters int and list are functions that you pass. Remember that Python accepts function names as arguments. int returns 0 by default and list returns an empty list when called with parentheses.

    In normal dictionaries, if in your example I try calling d[a], I will get an error (KeyError), since only keys m, s, i and p exist and key a has not been initialized. But in a defaultdict, it takes a function name as an argument, when you try to use a key that has not been initialized, it simply calls the function you passed in and assigns its return value as the value of the new key.

    Does Arduino use C or C++?

    Both are supported. To quote the Arduino homepage,

    The core libraries are written in C and C++ and compiled using avr-gcc

    Note that C++ is a superset of C (well, almost), and thus can often look very similar. I am not an expert, but I guess that most of what you will program for the Arduino in your first year on that platform will not need anything but plain C.

    Scikit-learn train_test_split with indices

    If you are using pandas you can access the index by calling .index of whatever array you wish to mimic. The train_test_split carries over the pandas indices to the new dataframes.

    In your code you simply use x1.index and the returned array is the indexes relating to the original positions in x.

    How do I concatenate const/literal strings in C?

    int main()
    {
        char input[100];
        gets(input);
    
        char str[101];
        strcpy(str, " ");
        strcat(str, input);
    
        char *p = str;
    
        while(*p) {
           if(*p == ' ' && isalpha(*(p+1)) != 0)
               printf("%c",*(p+1));
           p++;
        }
    
        return 0;
    }
    

    Error Code: 1406. Data too long for column - MySQL

    I think that switching off the STRICT mode is not a good option because the app can start losing the data entered by users.

    If you receive values for the TESTcol from an app you could add model validation, like in Rails

    validates :TESTcol, length: { maximum: 45 }
    

    If you manipulate with values in SQL script you could truncate the string with the SUBSTRING command

    INSERT INTO TEST
    VALUES
    (
        1,
        SUBSTRING('Vikas Kumar Gupta Kratika Shukla Kritika Shukla', 0, 45)
    );
    

    How do I use PHP to get the current year?

    use a PHP date() function.

    and the format is just going to be Y. Capital Y is going to be a four digit year.

    <?php echo date("Y"); ?>
    

    dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac

    This is what finally worked for me.

    brew reinstall postgres

    After running the above command you might need to run

    brew postgresql-upgrade-database

    to access your previous data.

    How to position the form in the center screen?

    i hope this will be helpful.

    put this on the top of source code :

    import java.awt.Toolkit;
    

    and then write this code :

    private void formWindowOpened(java.awt.event.WindowEvent evt) {                                  
        int lebar = this.getWidth()/2;
        int tinggi = this.getHeight()/2;
        int x = (Toolkit.getDefaultToolkit().getScreenSize().width/2)-lebar;
        int y = (Toolkit.getDefaultToolkit().getScreenSize().height/2)-tinggi;
        this.setLocation(x, y);
    }
    

    good luck :)

    When should a class be Comparable and/or Comparator?

    Comparable is for providing a default ordering on data objects, for example if the data objects have a natural order.

    A Comparator represents the ordering itself for a specific use.

    unresolved external symbol __imp__fprintf and __imp____iob_func, SDL2

    To bring more confusion in this already rich thread, I happened to bump in the same unresolved external on fprintf

    main.obj : error LNK2019: unresolved external symbol __imp__fprintf referenced in function _GenerateInfoFile
    

    Even if in my case it was in a rather different context : under Visual Studio 2005 (Visual Studio 8.0) and the error was happening in my own code (the very same I was compiling), not a third party.

    It happened that this error was triggered by /MD option in my compiler flags. Switching to /MT removed the issue. This is weird because usually, linking statically (MT) raises more problem than dynamically (MD)... but just in case it serves other, I put it there.

    Reshaping data.frame from wide to long format

    You can also use the cdata package, which uses the concept of (transformation) control table:

    # data
    wide <- read.table(text="Code Country        1950    1951    1952    1953    1954
    AFG  Afghanistan    20,249  21,352  22,532  23,557  24,555
    ALB  Albania        8,097   8,986   10,058  11,123  12,246", header=TRUE, check.names=FALSE)
    
    library(cdata)
    # build control table
    drec <- data.frame(
        Year=as.character(1950:1954),
        Value=as.character(1950:1954),
        stringsAsFactors=FALSE
    )
    drec <- cdata::rowrecs_to_blocks_spec(drec, recordKeys=c("Code", "Country"))
    
    # apply control table
    cdata::layout_by(drec, wide)
    

    I am currently exploring that package and find it quite accessible. It is designed for much more complicated transformations and includes the backtransformation. There is a tutorial available.

    Error in Python script "Expected 2D array, got 1D array instead:"?

    I was facing the same issue earlier but I have somehow found the solution, You can try reg.predict([[3300]]).

    The API used to allow scalar value but now you need to give a 2D array.

    How do I get into a Docker container's shell?

    It is simple!

    List out all your Docker images:

    sudo docker images
    

    On my system it showed the following output:

    REPOSITORY          TAG                 IMAGE ID            CREATED             VIRTUAL SIZE
    bash                latest              922b9cc3ea5e        9 hours ago
    14.03 MB
    ubuntu              latest              7feff7652c69        5 weeks ago         81.15 MB
    

    I have two Docker images on my PC. Let's say I want to run the first one.

    sudo docker run -i -t ubuntu:latest /bin/bash
    

    This will give you terminal control of the container. Now you can do all type of shell operations inside the container. Like doing ls will output all folders in the root of the file system.

    bin  boot  dev  etc  home  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
    

    Fast query runs slow in SSRS

    I simply deselected 'Repeat header columns on each page' within the Tablix Properties.

    What does the arrow operator, '->', do in Java?

    I believe, this arrow exists because of your IDE. IntelliJ IDEA does such thing with some code. This is called code folding. You can click at the arrow to expand it.

    How can I set multiple CSS styles in JavaScript?

    Is the below innerHtml valid

    _x000D_
    _x000D_
    var styleElement = win.document.createElement("STYLE");_x000D_
    styleElement.innerHTML = "#notEditableVatDisplay {display:inline-flex} #editableVatInput,.print-section,i.fa.fa-sort.click-sortable{display : none !important}";
    _x000D_
    _x000D_
    _x000D_

    jQuery Ajax simple call

    You could also make the ajax call more generic, reusable, so you can call it from different CRUD(create, read, update, delete) tasks for example and treat the success cases from those calls.

    makePostCall = function (url, data) { // here the data and url are not hardcoded anymore
       var json_data = JSON.stringify(data);
    
        return $.ajax({
            type: "POST",
            url: url,
            data: json_data,
            dataType: "json",
            contentType: "application/json;charset=utf-8"
        });
    }
    
    // and here a call example
    makePostCall("index.php?action=READUSERS", {'city' : 'Tokio'})
        .success(function(data){
                   // treat the READUSERS data returned
       })
        .fail(function(sender, message, details){
               alert("Sorry, something went wrong!");
      });
    

    Get input value from TextField in iOS alert in Swift

    In Swift5 ans Xcode 10

    Add two textfields with Save and Cancel actions and read TextFields text data

    func alertWithTF() {
        //Step : 1
        let alert = UIAlertController(title: "Great Title", message: "Please input something", preferredStyle: UIAlertController.Style.alert )
        //Step : 2
        let save = UIAlertAction(title: "Save", style: .default) { (alertAction) in
            let textField = alert.textFields![0] as UITextField
            let textField2 = alert.textFields![1] as UITextField
            if textField.text != "" {
                //Read TextFields text data
                print(textField.text!)
                print("TF 1 : \(textField.text!)")
            } else {
                print("TF 1 is Empty...")
            }
    
            if textField2.text != "" {
                print(textField2.text!)
                print("TF 2 : \(textField2.text!)")
            } else {
                print("TF 2 is Empty...")
            }
        }
    
        //Step : 3
        //For first TF
        alert.addTextField { (textField) in
            textField.placeholder = "Enter your first name"
            textField.textColor = .red
        }
        //For second TF
        alert.addTextField { (textField) in
            textField.placeholder = "Enter your last name"
            textField.textColor = .blue
        }
    
        //Step : 4
        alert.addAction(save)
        //Cancel action
        let cancel = UIAlertAction(title: "Cancel", style: .default) { (alertAction) in }
        alert.addAction(cancel)
        //OR single line action
        //alert.addAction(UIAlertAction(title: "Cancel", style: .default) { (alertAction) in })
    
        self.present(alert, animated:true, completion: nil)
    
    }
    

    For more explanation https://medium.com/@chan.henryk/alert-controller-with-text-field-in-swift-3-bda7ac06026c

    Bootstrap: How do I identify the Bootstrap version?

    Method 1 - Very Simple

    In Package.json - you'll see bootstrap package installed with version mentioned.

    "dependencies": {
        // ...
       "bootstrap": "x.x.x"
        // ...
    }
    

    Method 2

    1. Open node_modules folder and under that
    2. Search and open bootstrap folder
    3. Now you'll be able to see version number in the following files
      • package.json
      • scss/bootstrap.scss or css/bootstrap.css
      • README.md

    Convert String value format of YYYYMMDDHHMMSS to C# DateTime

    class Program
    {
        static void Main(string[] args)
        {
    
            int transactionDate = 20201010;
            int? transactionTime = 210000;
    
            var agreementDate = DateTime.Today;
            var previousDate = agreementDate.AddDays(-1);
    
            var agreementHour = 22;
            var agreementMinute = 0;
            var agreementSecond = 0;
    
            var startDate = new DateTime(previousDate.Year, previousDate.Month, previousDate.Day, agreementHour, agreementMinute, agreementSecond);
            var endDate = new DateTime(agreementDate.Year, agreementDate.Month, agreementDate.Day, agreementHour, agreementMinute, agreementSecond);
    
            DateTime selectedDate = Convert.ToDateTime(transactionDate.ToString().Substring(6, 2) + "/" + transactionDate.ToString().Substring(4, 2) + "/" + transactionDate.ToString().Substring(0, 4) + " " + string.Format("{0:00:00:00}", transactionTime));
    
            Console.WriteLine("Selected Date : " + selectedDate.ToString());
            Console.WriteLine("Start Date : " + startDate.ToString());
            Console.WriteLine("End Date : " + endDate.ToString());
    
            if (selectedDate > startDate && selectedDate <= endDate)
                Console.WriteLine("Between two dates..");
            else if (selectedDate <= startDate)
                Console.WriteLine("Less than or equal to the start date!");
            else if (selectedDate > endDate)
                Console.WriteLine("Greater than end date!");
            else
                Console.WriteLine("Out of date ranges!");
        }
    }
    

    How to configure port for a Spring Boot application

    As explained in Spring documentation, there are several ways to do that:

    Either you set the port in the command line (for example 8888)

    -Dserver.port=8888 or --server.port=8888

    Example : java -jar -Dserver.port=8888 test.jar

    Or you set the port in the application.properties

    server.port=${port:4588}
    

    or (in application.yml with yaml syntax)

    server:
       port: ${port:4588}
    

    If the port passed by -Dport (or -Dserver.port) is set in command line then this port will be taken into account. If not, then the port will be 4588 by default.

    If you want to enforce the port in properties file whatever the environment variable, you just have to write:

    server.port=8888
    

    How to allow Cross domain request in apache2

    OS=GNU/Linux Debian
    Httpd=Apache/2.4.10
    

    Change in /etc/apache2/apache2.conf

    <Directory /var/www/html>
         Order Allow,Deny
         Allow from all
         AllowOverride all
         Header set Access-Control-Allow-Origin "*"
    </Directory>
    

    Add/activate module

     a2enmod headers 
    

    Restart service

    /etc/init.d/apache2 restart
    

    HTML iframe - disable scroll

    Unfortunately I do not believe it's possible in fully-conforming HTML5 with just HTML and CSS properties. Fortunately however, most browsers do still support the scrolling property (which was removed from the HTML5 specification).

    overflow isn't a solution for HTML5 as the only modern browser which wrongly supports this is Firefox.

    A current solution would be to combine the two:

    <iframe src="" scrolling="no"></iframe>
    
    iframe {
      overflow: hidden;
    }
    

    But this could be rendered obsolete as browsers update. You may want to check this for a JavaScript solution: http://www.christersvensson.com/html-tool/iframe.htm

    Edit: I've checked and scrolling="no" will work in IE10, Chrome 25 and Opera 12.12.

    When doing a MERGE in Oracle SQL, how can I update rows that aren't matched in the SOURCE?

    You can do it with a separate UPDATE statement

    UPDATE report.TEST target
    SET    is Deleted = 'Y'
    WHERE  NOT EXISTS (SELECT 1
                       FROM   main.TEST source
                       WHERE  source.ID = target.ID);
    

    I don't know of any way to integrate this into your MERGE statement.

    JQuery post JSON object to a server

    To send json to the server, you first have to create json

    function sendData() {
        $.ajax({
            url: '/helloworld',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({
                name:"Bob",
                ...
            }),
            dataType: 'json'
        });
    }
    

    This is how you would structure the ajax request to send the json as a post var.

    function sendData() {
        $.ajax({
            url: '/helloworld',
            type: 'POST',
            data: { json: JSON.stringify({
                name:"Bob",
                ...
            })},
            dataType: 'json'
        });
    }
    

    The json will now be in the json post var.

    Why does visual studio 2012 not find my tests?

    I had the same problem.. In my case it was caused by a private property TestContext.

    Changing it to the following helped:

    public TestContext TestContext
    {
        get;
        set;
    }
    

    After cleaning and building the solution (as described in @Ourjamie 's answer), the test methods in the affected test class were available in the Test Explorer.

    How to execute a function when page has fully loaded?

    2019 update: This is was the answer that worked for me. As I needed multiple ajax requests to fire and return data first to count the list items.

    $(document).ajaxComplete(function(){
           alert("Everything is ready now!");
    });
    

    How can I find out a file's MIME type (Content-Type)?

    Use file. Examples:

    > file --mime-type image.png
    image.png: image/png
    
    > file -b --mime-type image.png
    image/png
    
    > file -i FILE_NAME
    image.png: image/png; charset=binary
    

    How to print the number of characters in each line of a text file

    I've tried the other answers listed above, but they are very far from decent solutions when dealing with large files -- especially once a single line's size occupies more than ~1/4 of available RAM.

    Both bash and awk slurp the entire line, even though for this problem it's not needed. Bash will error out once a line is too long, even if you have enough memory.

    I've implemented an extremely simple, fairly unoptimized python script that when tested with large files (~4 GB per line) doesn't slurp, and is by far a better solution than those given.

    If this is time critical code for production, you can rewrite the ideas in C or perform better optimizations on the read call (instead of only reading a single byte at a time), after testing that this is indeed a bottleneck.

    Code assumes newline is a linefeed character, which is a good assumption for Unix, but YMMV on Mac OS/Windows. Be sure the file ends with a linefeed to ensure the last line character count isn't overlooked.

    from sys import stdin, exit
    
    counter = 0
    while True:
        byte = stdin.buffer.read(1)
        counter += 1
        if not byte:
            exit()
        if byte == b'\x0a':
            print(counter-1)
            counter = 0
    

    DateTime.TryParse issue with dates of yyyy-dd-MM format

    Try using safe TryParseExact method

    DateTime temp;
    string   date = "2011-29-01 12:00 am";
    
    DateTime.TryParseExact(date, "yyyy-dd-MM hh:mm tt", CultureInfo.InvariantCulture, DateTimeStyles.None, out temp);
    

    UnicodeEncodeError: 'charmap' codec can't encode - character maps to <undefined>, print function

    If you are using Windows command line to print the data, you should use

    chcp 65001
    

    This worked for me!

    Reset par to the default values at startup

    dev.off() is the best function, but it clears also all plots. If you want to keep plots in your window, at the beginning save default par settings:

    def.par = par()

    Then when you use your par functions you still have a backup of default par settings. Later on, after generating plots, finish with:

    par(def.par) #go back to default par settings

    With this, you keep generated plots and reset par settings.

    How to leave space in HTML

    Either use literal non-breaking space symbol (yes, you can copy/paste it), HTML entity, or, if you're dealing with big pre-formatted block, use white-space CSS property.

    How do ports work with IPv6?

    The protocols used in IPv6 are the same as the protocols in IPv4. The only thing that changed between the two versions is the addressing scheme, DHCP [DHCPv6] and ICMP [ICMPv6]. So basically, anything TCP/UDP related, including the port range (0-65535) remains unchanged.

    Edit: Port 0 is a reserved port in TCP but it does exist. See RFC793

    Swift - encode URL

    For Swift 5 to endcode string

    func escape(string: String) -> String {
        let allowedCharacters = string.addingPercentEncoding(withAllowedCharacters: CharacterSet(charactersIn: ":=\"#%/<>?@\\^`{|}").inverted) ?? ""
        return allowedCharacters
    }
    

    How to use ?

    let strEncoded = self.escape(string: "http://www.edamam.com/ontologies/edamam.owl#recipe_e2a1b9bf2d996cbd9875b80612ed9aa4")
    print("escapedString: \(strEncoded)")
    

    set height of imageview as matchparent programmatically

    imageView.setLayoutParams
        (new ViewGroup.MarginLayoutParams
            (width, ViewGroup.LayoutParams.MATCH_PARENT));
    

    The Type of layout params depends on the parent view group. If you put the wrong one it will cause exception.

    Converting a date string to a DateTime object using Joda Time library

    You need a DateTimeFormatter appropriate to the format you're using. Take a look at the docs for instructions on how to build one.

    Off the cuff, I think you need format = DateTimeFormat.forPattern("M/d/y H:m:s")

    int to string in MySQL

    If you have a column called "col1" which is int, you cast it to String like this:

    CONVERT(col1,char)
    

    e.g. this allows you to check an int value is containing another value (here 9) like this:

    CONVERT(col1,char) LIKE '%9%'
    

    Getting full URL of action in ASP.NET MVC

    This may be just me being really, really picky, but I like to only define constants once. If you use any of the approaches defined above, your action constant will be defines multiple times.

    To avoid this, you can do the following:

        public class Url
        {
            public string LocalUrl { get; }
    
            public Url(string localUrl)
            {
                LocalUrl = localUrl;
            }
    
            public override string ToString()
            {
                return LocalUrl;
            }
        }
    
        public abstract class Controller
        {
            public Url RootAction => new Url(GetUrl());
    
            protected abstract string Root { get; }
    
            public Url BuildAction(string actionName)
            {
                var localUrl = GetUrl() + "/" + actionName;
                return new Url(localUrl);
            }
    
            private string GetUrl()
            {
                if (Root == "")
                {
                    return "";
                }
    
                return "/" + Root;
            }
    
            public override string ToString()
            {
                return GetUrl();
            }
        }
    

    Then create your controllers, say for example the DataController:

        public static readonly DataController Data = new DataController();
        public class DataController : Controller
        {
            public const string DogAction = "dog";
            public const string CatAction = "cat";
            public const string TurtleAction = "turtle";
    
            protected override string Root => "data";
    
            public Url Dog => BuildAction(DogAction);
            public Url Cat => BuildAction(CatAction);
            public Url Turtle => BuildAction(TurtleAction);
        }
    

    Then just use it like:

        // GET: Data/Cat
        [ActionName(ControllerRoutes.DataController.CatAction)]
        public ActionResult Etisys()
        {
            return View();
        }
    

    And from your .cshtml (or any code)

    <ul>
        <li><a href="@ControllerRoutes.Data.Dog">Dog</a></li>
        <li><a href="@ControllerRoutes.Data.Cat">Cat</a></li>
    </ul>
    

    This is definitely a lot more work, but I rest easy knowing compile time validation is on my side.

    Capturing multiple line output into a Bash variable

    In case that you're interested in specific lines, use a result-array:

    declare RESULT=($(./myscript))  # (..) = array
    echo "First line: ${RESULT[0]}"
    echo "Second line: ${RESULT[1]}"
    echo "N-th line: ${RESULT[N]}"
    

    How to show all of columns name on pandas dataframe?

    I know it is a repetition but I always end up copy pasting and modifying YOLO's answer:

    pd.set_option('display.max_columns', 500)
    pd.set_option('display.max_rows', 500)
    

    How do I use FileSystemObject in VBA?

    In excel 2013 the object creation string is:

    Dim fso
    Set fso = CreateObject("Scripting.FileSystemObject")
    

    instead of the code in the answer above:

    Dim fs,fname
    Set fs=Server.CreateObject("Scripting.FileSystemObject")
    

    Get cookie by name

    If you use jQuery I recommend you to use this plugin:

    https://github.com/carhartl/jquery-cookie
    https://github.com/carhartl/jquery-cookie/blob/master/jquery.cookie.js

    <script type="text/javascript"
     src="//cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js">
    

    So you can read cookie like this:

    var value = $.cookie("obligations");
    

    Also you can write cookie:

    $.cookie('obligations', 'new_value');
    $.cookie('obligations', 'new_value', { expires: 14, path: '/' });
    

    Delete cookie:

    $.removeCookie('obligations');
    

    Android Studio - local path doesn't exist

    delete de out directory and .ide folder work for me

    Mismatch Detected for 'RuntimeLibrary'

    Issue can be solved by adding CRT of msvcrtd.lib in the linker library. Because cryptlib.lib used CRT version of debug.

    Restricting JTextField input to Integers

    Here's one approach that uses a keylistener,but uses the keyChar (instead of the keyCode):

    http://edenti.deis.unibo.it/utils/Java-tips/Validating%20numerical%20input%20in%20a%20JTextField.txt

     keyText.addKeyListener(new KeyAdapter() {
        public void keyTyped(KeyEvent e) {
          char c = e.getKeyChar();
          if (!((c >= '0') && (c <= '9') ||
             (c == KeyEvent.VK_BACK_SPACE) ||
             (c == KeyEvent.VK_DELETE))) {
            getToolkit().beep();
            e.consume();
          }
        }
      });
    

    Another approach (which personally I find almost as over-complicated as Swing's JTree model) is to use Formatted Text Fields:

    http://docs.oracle.com/javase/tutorial/uiswing/components/formattedtextfield.html

    How to convert an int value to string in Go?

    fmt.Sprintf("%v",value);
    

    If you know the specific type of value use the corresponding formatter for example %d for int

    More info - fmt

    JavaScript Extending Class

    ES6 gives you now the opportunity to use class & extends keywords :

    Then , your code will be :

    You have a base class:

    class Monster{
           constructor(){
                 this.health = 100;
            }
           growl() {
               console.log("Grr!");
           }
    
    }
    

    That You want to extend and create another class with:

    class Monkey extends Monster {
            constructor(){
                super(); //don't forget "super"
                this.bananaCount = 5;
            }
    
    
            eatBanana() {
               this.bananaCount--;
               this.health++; //Accessing variable from parent class monster
               this.growl(); //Accessing function from parent class monster
            }
    
    }
    

    PDF Editing in PHP?

    I really had high hopes for dompdf (it is a cool idea) but the positioning issue are a major factor in my using fpdf. Though it is tedious as every element has to be set; it is powerful as all get out.

    I lay an image underneath my workspace in the document to put my layout on top of to fit. Its always been sufficient even for columns (requires a tiny bit of php string calculation, but nothing too terribly heady).

    Good luck.

    How to prevent colliders from passing through each other?

    So I haven't been able to get the Mesh Colliders to work. I created a composite collider using simple box colliders and it worked exactly as expected.

    Other tests with simple Mesh Colliders have come out the same.

    It looks like the best answer is to build a composite collider out of simple box/sphere colliders.

    For my specific case I wrote a Wizard that creates a Pipe shaped compound collider.

    @script AddComponentMenu("Colliders/Pipe Collider");
    class WizardCreatePipeCollider extends ScriptableWizard
    {
        public var outterRadius : float = 200;
        public var innerRadius : float = 190;
        public var sections : int = 12;
        public var height : float = 20;
    
        @MenuItem("GameObject/Colliders/Create Pipe Collider")
        static function CreateWizard()
        {
            ScriptableWizard.DisplayWizard.<WizardCreatePipeCollider>("Create Pipe Collider");
        }
    
        public function OnWizardUpdate() {
            helpString = "Creates a Pipe Collider";
        }
    
        public function OnWizardCreate() {
            var theta : float = 360f / sections;
            var width : float = outterRadius - innerRadius;
    
            var sectionLength : float = 2 * outterRadius * Mathf.Sin((theta / 2) * Mathf.Deg2Rad);
    
            var container : GameObject = new GameObject("Pipe Collider");
            var section : GameObject;
            var sectionCollider : GameObject;
            var boxCollider : BoxCollider;
    
            for(var i = 0; i < sections; i++)
            {
                section = new GameObject("Section " + (i + 1));
    
                sectionCollider = new GameObject("SectionCollider " + (i + 1));
                section.transform.parent = container.transform;
                sectionCollider.transform.parent = section.transform;
    
                section.transform.localPosition = Vector3.zero;
                section.transform.localRotation.eulerAngles.y = i * theta;
    
                boxCollider = sectionCollider.AddComponent.<BoxCollider>();
                boxCollider.center = Vector3.zero;
                boxCollider.size = new Vector3(width, height, sectionLength);
    
                sectionCollider.transform.localPosition = new Vector3(innerRadius + (width / 2), 0, 0);
            }
        }
    }
    

    public static const in TypeScript

    Meanwhile this can be solved through a decorator in combination with Object.freeze or Object.defineProperty, I'm using this, it's a little bit prettier than using tons of getters. You can copy/paste this directly TS Playground to see it in action. - There are two options


    Make individual fields "final"

    The following decorator converts both, annotated static and non-static fields to "getter-only-properties".

    Note: If an instance-variable with no initial value is annotated @final, then the first assigned value (no matter when) will be the final one.

    // example
    class MyClass {
        @final
        public finalProp: string = "You shall not change me!";
    
        @final
        public static FINAL_FIELD: number = 75;
    
        public static NON_FINAL: string = "I am not final."
    }
    
    var myInstance: MyClass = new MyClass();
    myInstance.finalProp = "Was I changed?";
    MyClass.FINAL_FIELD = 123;
    MyClass.NON_FINAL = "I was changed.";
    
    console.log(myInstance.finalProp);  // => You shall not change me!
    console.log(MyClass.FINAL_FIELD);   // => 75
    console.log(MyClass.NON_FINAL);     // => I was changed.
    

    The Decorator: Make sure you include this in your code!

    /**
    * Turns static and non-static fields into getter-only, and therefor renders them "final".
    * To use simply annotate the static or non-static field with: @final
    */
    function final(target: any, propertyKey: string) {
        const value: any = target[propertyKey];
        // if it currently has no value, then wait for the first setter-call
        // usually the case with non-static fields
        if (!value) {
            Object.defineProperty(target, propertyKey, {
                set: function (value: any) {
                    Object.defineProperty(this, propertyKey, {
                        get: function () {
                            return value;
                        },
                        enumerable: true,
                        configurable: false
                    });
                },
                enumerable: true,
                configurable: true
            });
        } else { // else, set it immediatly
            Object.defineProperty(target, propertyKey, {
                get: function () {
                    return value;
                },
                enumerable: true
            });
        }
    }
    

    As an alternative to the decorator above, there would also be a strict version of this, which would even throw an Error when someone tried to assign some value to the field with "use strict"; being set. (This is only the static part though)

    /**
     * Turns static fields into getter-only, and therefor renders them "final".
     * Also throws an error in strict mode if the value is tried to be touched.
     * To use simply annotate the static field with: @strictFinal
     */
    function strictFinal(target: any, propertyKey: string) {
        Object.defineProperty(target, propertyKey, {
            value: target[propertyKey],
            writable: false,
            enumerable: true
        });
    }
    

    Make every static field "final"

    Possible Downside: This will only work for ALL statics of that class or for none, but cannot be applied to specific statics.

    /**
    * Freezes the annotated class, making every static 'final'.
    * Usage:
    * @StaticsFinal
    * class MyClass {
    *      public static SOME_STATIC: string = "SOME_STATIC";
    *      //...
    * }
    */
    function StaticsFinal(target: any) {
        Object.freeze(target);
    }
    
    // Usage here
    @StaticsFinal
    class FreezeMe {
        public static FROZEN_STATIC: string = "I am frozen";
    }
    
    class EditMyStuff {
        public static NON_FROZEN_STATIC: string = "I am frozen";
    }
    
    // Test here
    FreezeMe.FROZEN_STATIC = "I am not frozen.";
    EditMyStuff.NON_FROZEN_STATIC = "I am not frozen.";
    
    console.log(FreezeMe.FROZEN_STATIC); // => "I am frozen."
    console.log(EditMyStuff.NON_FROZEN_STATIC); // => "I am not frozen."
    

    How do I install Maven with Yum?

    Maven is packaged for Fedora since mid 2014, so it is now pretty easy. Just type

    sudo dnf install maven
    

    Now test the installation, just run maven in a random directory

    mvn
    

    And it will fail, because you did not specify a goal, e.g. mvn package

    [INFO] Scanning for projects...
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD FAILURE
    [INFO] ------------------------------------------------------------------------
    [INFO] Total time: 0.102 s
    [INFO] Finished at: 2017-11-14T13:45:00+01:00
    [INFO] Final Memory: 8M/176M
    [INFO] ------------------------------------------------------------------------
    [ERROR] No goals have been specified for this build
    
    [...]
    

    MAX() and MAX() OVER PARTITION BY produces error 3504 in Teradata Query

    Logically OLAP functions are calculated after GROUP BY/HAVING, so you can only access columns in GROUP BY or columns with an aggregate function. Following looks strange, but is Standard SQL:

    SELECT employee_number,
           MAX(MAX(course_completion_date)) 
               OVER (PARTITION BY course_code) AS max_course_date,
           MAX(course_completion_date) AS max_date
    FROM employee_course_completion
    WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
    GROUP BY employee_number, course_code
    

    And as Teradata allows re-using an alias this also works:

    SELECT employee_number,
           MAX(max_date) 
               OVER (PARTITION BY course_code) AS max_course_date,
           MAX(course_completion_date) AS max_date
    FROM employee_course_completion
    WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
    GROUP BY employee_number, course_code
    

    How do you share constants in NodeJS modules?

    As an alternative, you can group your "constant" values in a local object, and export a function that returns a shallow clone of this object.

    var constants = { FOO: "foo" }
    
    module.exports = function() {
      return Object.assign({}, constants)
    }
    

    Then it doesn't matter if someone re-assigns FOO because it will only affect their local copy.

    Handle ModelState Validation in ASP.NET Web API

    Here you can check to show the model state error one by one

     public HttpResponseMessage CertificateUpload(employeeModel emp)
        {
            if (!ModelState.IsValid)
            {
                string errordetails = "";
                var errors = new List<string>();
                foreach (var state in ModelState)
                {
                    foreach (var error in state.Value.Errors)
                    {
                        string p = error.ErrorMessage;
                        errordetails = errordetails + error.ErrorMessage;
    
                    }
                }
                Dictionary<string, object> dict = new Dictionary<string, object>();
    
    
    
                dict.Add("error", errordetails);
                return Request.CreateResponse(HttpStatusCode.BadRequest, dict);
    
    
            }
            else
            {
          //do something
            }
            }
    

    }

    Export to CSV using MVC, C# and jQuery

    I Think you have forgot to use

      Response.Flush();
    

    under

      Response.Write(sw);
    

    please check

    Parsing a CSV file using NodeJS

    I use this simple one: https://www.npmjs.com/package/csv-parser

    Very simple to use:

    const csv = require('csv-parser')
    const fs = require('fs')
    const results = [];
    
    fs.createReadStream('./CSVs/Update 20191103C.csv')
      .pipe(csv())
      .on('data', (data) => results.push(data))
      .on('end', () => {
        console.log(results);
        console.log(results[0]['Lowest Selling Price'])
      });
    

    Remove part of string in Java

    Kotlin Solution

    If you are removing a specific string from the end, use removeSuffix (Documentation)

    var text = "one(two"
    text = text.removeSuffix("(two") // "one"
    

    If the suffix does not exist in the string, it just returns the original

    var text = "one(three"
    text = text.removeSuffix("(two") // "one(three"
    

    If you want to remove after a character, use

    // Each results in "one"
    
    text = text.replaceAfter("(", "").dropLast(1) // You should check char is present before `dropLast`
    // or
    text = text.removeRange(text.indexOf("("), text.length)
    // or
    text = text.replaceRange(text.indexOf("("), text.length, "")
    

    You can also check out removePrefix, removeRange, removeSurrounding, and replaceAfterLast which are similar

    The Full List is here: (Documentation)

    pandas GroupBy columns with NaN (missing) values

    I answered this already, but some reason the answer was converted to a comment. Nevertheless, this is the most efficient solution:

    Not being able to include (and propagate) NaNs in groups is quite aggravating. Citing R is not convincing, as this behavior is not consistent with a lot of other things. Anyway, the dummy hack is also pretty bad. However, the size (includes NaNs) and the count (ignores NaNs) of a group will differ if there are NaNs.

    dfgrouped = df.groupby(['b']).a.agg(['sum','size','count'])
    
    dfgrouped['sum'][dfgrouped['size']!=dfgrouped['count']] = None
    

    When these differ, you can set the value back to None for the result of the aggregation function for that group.

    pandas read_csv index_col=None not working with delimiters at the end of each line

    Quick Answer

    Use index_col=False instead of index_col=None when you have delimiters at the end of each line to turn off index column inference and discard the last column.

    More Detail

    After looking at the data, there is a comma at the end of each line. And this quote (the documentation has been edited since the time this post was created):

    index_col: column number, column name, or list of column numbers/names, to use as the index (row labels) of the resulting DataFrame. By default, it will number the rows without using any column, unless there is one more data column than there are headers, in which case the first column is taken as the index.

    from the documentation shows that pandas believes you have n headers and n+1 data columns and is treating the first column as the index.


    EDIT 10/20/2014 - More information

    I found another valuable entry that is specifically about trailing limiters and how to simply ignore them:

    If a file has one more column of data than the number of column names, the first column will be used as the DataFrame’s row names: ...

    Ordinarily, you can achieve this behavior using the index_col option.

    There are some exception cases when a file has been prepared with delimiters at the end of each data line, confusing the parser. To explicitly disable the index column inference and discard the last column, pass index_col=False: ...

    creating Hashmap from a JSON String

    You can use Google's Gson library to convert json to Hashmap. Try below code

    String jsonString = "Your JSON string";
    HashMap<String,String> map = new Gson().fromJson(jsonString, new TypeToken<HashMap<String, String>>(){}.getType());