Programs & Examples On #Codecave

How to create a thread?

Your example fails because Thread methods take either one or zero arguments. To create a thread without passing arguments, your code looks like this:

void Start()
{
    // do stuff
}

void Test()
{
    new Thread(new ThreadStart(Start)).Start();
}

If you want to pass data to the thread, you need to encapsulate your data into a single object, whether that is a custom class of your own design, or a dictionary object or something else. You then need to use the ParameterizedThreadStart delegate, like so:

void Start(object data)
{
    MyClass myData = (MyClass)myData;
    // do stuff
}

void Test(MyClass data)
{
    new Thread(new ParameterizedThreadStart(Start)).Start(data);
}

How to approach a "Got minus one from a read call" error when connecting to an Amazon RDS Oracle instance

in my case, I got the same exception because the user that I configured in the app did not existed in the DB, creating the user and granting needed permissions solved the problem.

Using R to list all files with a specified extension

Gives you the list of files with full path:

  Sys.glob(file.path(file_dir, "*.dbf")) ## file_dir = file containing directory

How to implement a SQL like 'LIKE' operator in java?

Regular expressions are the most versatile. However, some LIKE functions can be formed without regular expressions. e.g.

String text = "digital";
text.startsWith("dig"); // like "dig%"
text.endsWith("tal"); // like "%tal"
text.contains("gita"); // like "%gita%"

What's the difference between UTF-8 and UTF-8 without BOM?

One practical difference is that if you write a shell script for Mac OS X and save it as plain UTF-8, you will get the response:

#!/bin/bash: No such file or directory

in response to the shebang line specifying which shell you wish to use:

#!/bin/bash

If you save as UTF-8, no BOM (say in BBEdit) all will be well.

Including JavaScript class definition from another file in Node.js

I just want to point out that most of the answers here don't work, I am new to NodeJS and IDK if throughout time the "module.exports.yourClass" method changed, or if people just entered the wrong answer.

// MyClass

module.exports.Ninja = class Ninja{
    test(){
        console.log('TESTING 1... 2... 3...');
    };
}
//Using MyClass in seprate File


const ninjaFw = require('./NinjaFw');

let ninja = new ninjaFw.Ninja();
ninja.test();

  • This is the method I am currently using. I like this syntax, becuase module.exports sits on the same line as the class declaration and that cleans the code up a little imo. The other way you can do it is like this:
//  Ninja Framework File


class Ninja{
    test(){
        console.log('TESTING 1... 2... 3...');
    };
}


module.exports.Ninja = Ninja;

  • Two different syntax but, in the end, the same result. Just a matter of syntax anesthetics.

Error on line 2 at column 1: Extra content at the end of the document

I think you are creating a document that looks like this:

<mycatch>
    ....
</mycatch>
<mycatch>
    ....
</mycatch>

This is not a valid XML document as it has more than one root element. You must have a single top-level element, as in

<mydocument>      
  <mycatch>
      ....
  </mycatch>
  <mycatch>
      ....
  </mycatch>
  ....
</mydocument>

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

To view database roles assigned to users, you can use sys.database_role_members

The following query returns the members of the database roles.

SELECT DP1.name AS DatabaseRoleName,   
    isnull (DP2.name, 'No members') AS DatabaseUserName   
FROM sys.database_role_members AS DRM  
RIGHT OUTER JOIN sys.database_principals AS DP1  
    ON DRM.role_principal_id = DP1.principal_id  
LEFT OUTER JOIN sys.database_principals AS DP2  
    ON DRM.member_principal_id = DP2.principal_id  
WHERE DP1.type = 'R'
ORDER BY DP1.name;  

How can I fix WebStorm warning "Unresolved function or method" for "require" (Firefox Add-on SDK)

On WebStorm 2016.3

  1. Press ALT+F12 (open terminal)

  2. Run this command:

    npm install require.js
    

Converting a UNIX Timestamp to Formatted Date String

$unixtime_to_date = date('jS F Y h:i:s A (T)', $unixtime);

This should work to.

How to hide axes and gridlines in Matplotlib (python)

Turn the axes off with:

plt.axis('off')

And gridlines with:

plt.grid(b=None)

Removing duplicates from a SQL query (not just "use distinct")

If I understand you correctly, you want to list to exclude duplicates on one column only, inner join to a sub-select

select u.* [whatever joined values]
from users u
inner join
(select name from users group by name having count(*)=1) uniquenames
on uniquenames.name = u.name

How can I edit a view using phpMyAdmin 3.2.4?

try running SHOW CREATE VIEW my_view_name in the sql portion of phpmyadmin and you will have a better idea of what is inside the view

How do I use a char as the case in a switch-case?

Like that. Except char hi=hello; should be char hi=hello.charAt(0). (Don't forget your break; statements).

What are major differences between C# and Java?

Please go through the link given below msdn.microsoft.com/en-us/library/ms836794.aspx It covers both the similarity and difference between C# and java

I am getting "java.lang.ClassNotFoundException: com.google.gson.Gson" error even though it is defined in my classpath

I was just having the same issue...

To resolve the problem (at least in my case) ensure you have included the lib folder in your bundle classpath:

Manifest-Version: 1.0
... 
Bundle-ClassPath: lib/gson-1.6.jar,
 .
...

Or if you want to include all jar's in the folder:

Bundle-ClassPath: lib/

You will still need to place the jar files on the java build path as shown above. Then your imported jar's should appear in the folder "Referenced Libraries"

add new row in gridview after binding C#, ASP.net

try using the cloning technique.

{
    DataGridViewRow row = (DataGridViewRow)yourdatagrid.Rows[0].Clone();
    // then for each of the values use a loop like below.
    int cc = yourdatagrid.Columns.Count;
    for (int i2 = 0; i < cc; i2++)
    {
        row.Cells[i].Value = yourdatagrid.Rows[0].Cells[i].Value;
    }
    yourdatagrid.Rows.Add(row);
    i++;
    }
}

This should work. I'm not sure about how the binding works though. Hopefully it won't prevent this from working.

relative path in require_once doesn't work

for php version 5.2.17 __DIR__ will not work it will only works with php 5.3

But for older version of php dirname(__FILE__) perfectly

For example write like this

require_once dirname(__FILE__) . '/db_config.php';

split string only on first instance of specified character

This should be quite fast

function splitOnFirst (str, sep) {
  const index = str.indexOf(sep);
  return index < 0 ? [str] : [str.slice(0, index), str.slice(index + sep.length)];
}

Add vertical scroll bar to panel

Below is the code that implements custom vertical scrollbar. The important detail here is to know when scrollbar is needed by calculating how much space is consumed by the controls that you add to the panel.

panelUserInput.SuspendLayout();
panelUserInput.Controls.Clear();
panelUserInput.AutoScroll = false;
panelUserInput.VerticalScroll.Visible = false;

// here you'd be adding controls

int x = 20, y = 20, height = 0;
for (int inx = 0; inx < numControls; inx++ )
{
    // this example uses textbox control
    TextBox txt = new TextBox();
    txt.Location = new System.Drawing.Point(x, y);
    // add whatever details you need for this control
    // before adding it to the panel
    panelUserInput.Controls.Add(txt);
    height = y + txt.Height;
    y += 25;
}
if (height > panelUserInput.Height)
{
    VScrollBar bar = new VScrollBar();
    bar.Dock = DockStyle.Right;
    bar.Scroll += (sender, e) => { panelUserInput.VerticalScroll.Value =  bar.Value; };
    bar.Top = 0;
    bar.Left = panelUserInput.Width - bar.Width;
    bar.Height = panelUserInput.Height;
    bar.Visible = true;
    panelUserInput.Controls.Add(bar);
}
panelUserInput.ResumeLayout();

// then update the form
this.PerformLayout();

Using DISTINCT along with GROUP BY in SQL Server

Use DISTINCT to remove duplicate GROUPING SETS from the GROUP BY clause

In a completely silly example using GROUPING SETS() in general (or the special grouping sets ROLLUP() or CUBE() in particular), you could use DISTINCT in order to remove the duplicate values produced by the grouping sets again:

SELECT DISTINCT actors
FROM (VALUES('a'), ('a'), ('b'), ('b')) t(actors)
GROUP BY CUBE(actors, actors)

With DISTINCT:

actors
------
NULL
a
b

Without DISTINCT:

actors
------
a
b
NULL
a
b
a
b

But why, apart from making an academic point, would you do that?

Use DISTINCT to find unique aggregate function values

In a less far-fetched example, you might be interested in the DISTINCT aggregated values, such as, how many different duplicate numbers of actors are there?

SELECT DISTINCT COUNT(*)
FROM (VALUES('a'), ('a'), ('b'), ('b')) t(actors)
GROUP BY actors

Answer:

count
-----
2

Use DISTINCT to remove duplicates with more than one GROUP BY column

Another case, of course, is this one:

SELECT DISTINCT actors, COUNT(*)
FROM (VALUES('a', 1), ('a', 1), ('b', 1), ('b', 2)) t(actors, id)
GROUP BY actors, id

With DISTINCT:

actors  count
-------------
a       2
b       1

Without DISTINCT:

actors  count
-------------
a       2
b       1
b       1

For more details, I've written some blog posts, e.g. about GROUPING SETS and how they influence the GROUP BY operation, or about the logical order of SQL operations (as opposed to the lexical order of operations).

jQuery - Add active class and remove active from other element on click

Try this one:

$(document).ready(function() {
    $(".tab").click(function () {
        $("this").addClass("active").siblings().removeClass("active");   
    });
});

What is a bus error?

A typical buffer overflow which results in Bus error is,

{
    char buf[255];
    sprintf(buf,"%s:%s\n", ifname, message);
}

Here if size of the string in double quotes ("") is more than buf size it gives bus error.

How to use template module with different set of variables?

- name: copy vhosts
  template: src=site-vhost.conf dest=/etc/apache2/sites-enabled/{{ item }}.conf
  with_items:
    - somehost.local
    - otherhost.local
  notify: restart apache

IMPORTANT: Note that an item does not have to be just a string, it can be an object with as many properties as you like, so that way you can pass any number of variables.

In the template I have:

<VirtualHost *:80>
    ServerAdmin [email protected]
    ServerName {{ item }}
    DocumentRoot /vagrant/public


    ErrorLog ${APACHE_LOG_DIR}/error-{{ item }}.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

</VirtualHost>

Delete all data rows from an Excel table (apart from the first)

I wanted to keep the formulas in place, which the above code did not do.

Here's what I've been doing, note that this leaves one empty row in the table.

Sub DeleteTableRows(ByRef Table As ListObject, KeepFormulas as boolean)

On Error Resume Next

if not KeepFormulas then
    Table.DataBodyRange.clearcontents
end if

Table.DataBodyRange.Rows.Delete

On Error GoTo 0

End Sub

(PS don't ask me why!)

Why does the arrow (->) operator in C exist?

Beyond historical (good and already reported) reasons, there's is also a little problem with operators precedence: dot operator has higher priority than star operator, so if you have struct containing pointer to struct containing pointer to struct... These two are equivalent:

(*(*(*a).b).c).d

a->b->c->d

But the second is clearly more readable. Arrow operator has the highest priority (just as dot) and associates left to right. I think this is clearer than use dot operator both for pointers to struct and struct, because we know the type from the expression without have to look at the declaration, that could even be in another file.

Can a local variable's memory be accessed outside its scope?

In typical compiler implementations, you can think of the code as "print out the value of the memory block with adress that used to be occupied by a". Also, if you add a new function invocation to a function that constains a local int it's a good chance that the value of a (or the memory address that a used to point to) changes. This happens because the stack will be overwritten with a new frame containing different data.

However, this is undefined behaviour and you should not rely on it to work!

How do you handle multiple submit buttons in ASP.NET MVC Framework?

Index.cshtml

@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { id = "submitForm" }))

{

button type="submit" id="btnApprove" name="Command" value="Approve"> Approve

button type="submit" id="btnReject" name="Command" value="Reject"> Reject

}

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Index(FormCollection frm, string Command)
    {
        if (Command == "Approve")
        {

        }
        else if (Command == "Reject")
        {

        }

        return View();
    }

}

New to MongoDB Can not run command mongo

Create the data/db directory in your main (windows) partition:

C:\> mkdir \data
C:\> mkdir \data\db

and then go to your mongo_directory/bin and run mongod.exe:

C:\> cd \my_mongo_dir\bin

C:\my_mongo_dir\bin> mongod

DON't CLOSE THIS WINDOW

Now in a different command prompt window run Mongo:

C:\> cd \my_mongo_dir\bin
C:\my_mongo_dir\bin> mongo

(REMEMBER YOU HAVE TO KEEP THAT OTHER WINDOW OPEN)

This solved the problem for me.

Onclick event to remove default value in a text input field

HTML5 Placeholder Attribute

You are likely wanting placeholder functionality:

<input name="Name" placeholder="Enter Your Name" />

Polyfill for Older Browsers

This will not work in some older browsers, but polyfills exist (some require jQuery, others don't) to patch that functionality.

"Screw it, I'll do it myself."

If you wanted to roll your own solution, you could use the onfocus and onblur events of your element to determine what its value should be:

<input name="Name" value="Enter Your Name"
       onfocus="(this.value == 'Enter Your Name') && (this.value = '')"
       onblur="(this.value == '') && (this.value = 'Enter Your Name')" />

Avoid Mixing HTML with JavaScript

You'll find that most of us aren't big fans of evaluating JavaScript from attributes like onblur and onfocus. Instead, it's more commonly encouraged to bind this logic up purely with JavaScript. Granted, it's a bit more verbose, but it keeps a nice separation between your logic and your markup:

var nameElement = document.forms.myForm.Name;

function nameFocus( e ) {
  var element = e.target || window.event.srcElement;
  if (element.value == "Enter Your Name") element.value = "";
}

function nameBlur( e ) {
  var element = e.target || window.event.srcElement;
  if (element.value == "") element.value = "Enter Your Name";
}

if ( nameElement.addEventListener ) {
  nameElement.addEventListener("focus", nameFocus, false);
  nameElement.addEventListener("blur", nameBlur, false);
} else if ( nameElement.attachEvent ) {
  nameElement.attachEvent("onfocus", nameFocus);
  nameElement.attachEvent("onblur", nameBlur);
}

Demo: http://jsbin.com/azehum/2/edit

SET versus SELECT when assigning variables?

Aside from the one being ANSI and speed etc., there is a very important difference that always matters to me; more than ANSI and speed. The number of bugs I have fixed due to this important overlook is large. I look for this during code reviews all the time.

-- Arrange
create table Employee (EmployeeId int);
insert into dbo.Employee values (1);
insert into dbo.Employee values (2);
insert into dbo.Employee values (3);

-- Act
declare @employeeId int;
select @employeeId = e.EmployeeId from dbo.Employee e;

-- Assert
-- This will print 3, the last EmployeeId from the query (an arbitrary value)
-- Almost always, this is not what the developer was intending. 
print @employeeId; 

Almost always, that is not what the developer is intending. In the above, the query is straight forward but I have seen queries that are quite complex and figuring out whether it will return a single value or not, is not trivial. The query is often more complex than this and by chance it has been returning single value. During developer testing all is fine. But this is like a ticking bomb and will cause issues when the query returns multiple results. Why? Because it will simply assign the last value to the variable.

Now let's try the same thing with SET:

 -- Act
 set @employeeId = (select e.EmployeeId from dbo.Employee e);

You will receive an error:

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

That is amazing and very important because why would you want to assign some trivial "last item in result" to the @employeeId. With select you will never get any error and you will spend minutes, hours debugging.

Perhaps, you are looking for a single Id and SET will force you to fix your query. Thus you may do something like:

-- Act
-- Notice the where clause
set @employeeId = (select e.EmployeeId from dbo.Employee e where e.EmployeeId = 1);
print @employeeId;

Cleanup

drop table Employee;

In conclusion, use:

  • SET: When you want to assign a single value to a variable and your variable is for a single value.
  • SELECT: When you want to assign multiple values to a variable. The variable may be a table, temp table or table variable etc.

MVC Razor Radio Button

I done this in a way like:

  @Html.RadioButtonFor(model => model.Gender, "M", false)@Html.Label("Male")
  @Html.RadioButtonFor(model => model.Gender, "F", false)@Html.Label("Female")

How to create the pom.xml for a Java project with Eclipse

Right click on Project -> Add FrameWork Support -> Maven

INSERT SELECT statement in Oracle 11G

for inserting data into table you can write

insert into tablename values(column_name1,column_name2,column_name3);

but write the column_name in the sequence as per sequence in table ...

Ignoring a class property in Entity Framework 4.1 Code First

As of EF 5.0, you need to include the System.ComponentModel.DataAnnotations.Schema namespace.

Angular.js: set element height on page load

Combining matty-j suggestion with the snippet of the question, I ended up with this code focusing on resizing the grid after the data was loaded.

The HTML:

<div ng-grid="gridOptions" class="gridStyle"></div>

The directive:

angular.module('myApp.directives', [])
    .directive('resize', function ($window) {
        return function (scope, element) {

            var w = angular.element($window);
            scope.getWindowDimensions = function () {
                return { 'h': w.height(), 'w': w.width() };
            };
            scope.$watch(scope.getWindowDimensions, function (newValue, oldValue) {

                // resize Grid to optimize height
                $('.gridStyle').height(newValue.h - 250);
            }, true);

            w.bind('resize', function () {
                scope.$apply();
            });
        }
    });

The controller:

angular.module('myApp').controller('Admin/SurveyCtrl', function ($scope, $routeParams, $location, $window, $timeout, Survey) {

    // Retrieve data from the server
    $scope.surveys = Survey.query(function(data) {

        // Trigger resize event informing elements to resize according to the height of the window.
        $timeout(function () {
            angular.element($window).resize();
        }, 0)
    });

    // Configure ng-grid.
    $scope.gridOptions = {
        data: 'surveys',
        ...
    };
}

Slide div left/right using jQuery

The easiest way to do so is using jQuery and animate.css animation library.

Javascript

/* --- Show DIV --- */
$( '.example' ).removeClass( 'fadeOutRight' ).show().addClass( 'fadeInRight' );

/* --- Hide DIV --- */
$( '.example' ).removeClass( 'fadeInRight' ).addClass( 'fadeOutRight' );


HTML

<div class="example">Some text over here.</div>


Easy enough to implement. Just don't forget to include the animate.css file in the header :)

SQL Query - how do filter by null or not null

How about statusid = statusid. Null is never equal to null.

JPA mapping: "QuerySyntaxException: foobar is not mapped..."

JPQL mostly is case-insensitive. One of the things that is case-sensitive is Java entity names. Change your query to:

"SELECT r FROM FooBar r"

how to upload file using curl with php

Use:

if (function_exists('curl_file_create')) { // php 5.5+
  $cFile = curl_file_create($file_name_with_full_path);
} else { // 
  $cFile = '@' . realpath($file_name_with_full_path);
}
$post = array('extra_info' => '123456','file_contents'=> $cFile);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result=curl_exec ($ch);
curl_close ($ch);

You can also refer:

http://blog.derakkilgo.com/2009/06/07/send-a-file-via-post-with-curl-and-php/

Important hint for PHP 5.5+:

Now we should use https://wiki.php.net/rfc/curl-file-upload but if you still want to use this deprecated approach then you need to set curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);

How to format a URL to get a file from Amazon S3?

Its actually formulated more like:

https://<bucket-name>.s3.amazonaws.com/<key>

See here

How to echo (or print) to the js console with php

https://github.com/bkdotcom/PHPDebugConsole

Support for all the javascript console methods:
assert, clear, count, error, group, groupCollapsed, groupEnd, info, log, table, trace, time, timeEnd, warn
plus a few more:
alert, groupSummary, groupUncollapse, timeGet

$debug = new \bdk\Debug(array(
    'collect' => true,
    'output' => true,
    'outputAs' => 'script',
));

$debug->log('hello world');
$debug->info('all of the javascript console methods are supported');
\bdk\Debug::_log('can use static methods');
$debug->trace();
$list = array(
    array('userId'=>1, 'name'=>'Bob', 'sex'=>'M', 'naughty'=>false),
    array('userId'=>10, 'naughty'=>true, 'name'=>'Sally', 'extracol' => 'yes', 'sex'=>'F'),
    array('userId'=>2, 'name'=>'Fred', 'sex'=>'M', 'naughty'=>false),
);
$debug->table('people', $list);

this will output the appropriate <script> tag upon script shutdown

alternatively, you can output as html, chromeLogger, FirePHP, file, plaintext, websockets, etc

upcomming release includes a psr-3 (logger) implementation

Disable Laravel's Eloquent timestamps

You either have to declare public $timestamps = false; in every model, or create a BaseModel, define it there, and have all your models extend it instead of eloquent. Just bare in mind pivot tables MUST have timestamps if you're using Eloquent.

Update: Note that timestamps are no longer REQUIRED in pivot tables after Laravel v3.

Update: You can also disable timestamps by removing $table->timestamps() from your migration.

Github: Can I see the number of downloads for a repo?

To check the number of times a release file/package was downloaded you can go to https://githubstats0.firebaseapp.com

It gives you a total download count and a break up of of total downloads per release tag.

connecting to MySQL from the command line

Best practice would be to mysql -u root -p. Then MySQL will prompt for password after you hit enter.

Is it possible to get element from HashMap by its position?

HashMaps don't allow access by position, it only knows about the hash code and and it can retrieve the value if it can calculate the hash code of the key. TreeMaps have a notion of ordering. Linkedhas maps preserve the order in which they entered the map.

Getting Database connection in pure JPA setup

Where you want to get that connection is unclear. One possibility would be to get it from the underlying Hibernate Session used by the EntityManager. With JPA 1.0, you'll have to do something like this:

Session session = (Session)em.getDelegate();
Connection conn = session.connection();

Note that the getDelegate() is not portable, the result of this method is implementation specific: the above code works in JBoss, for GlassFish you'd have to adapt it - have a look at Be careful while using EntityManager.getDelegate().

In JPA 2.0, things are a bit better and you can do the following:

Connection conn = em.unwrap(Session.class).connection();

If you are running inside a container, you could also perform a lookup on the configured DataSource.

Find all special characters in a column in SQL Server 2008

Select * from TableName Where ColumnName LIKE '%[^A-Za-z0-9, ]%'

This will give you all the row which contains any special character.

HTML5 and frameborder

As per the other posting here, the best solution is to use the CSS entry of

style="border:0;"

100% height minus header?

If your browser supports CSS3, try using the CSS element Calc()

height: calc(100% - 65px);

you might also want to adding browser compatibility options:

height: -o-calc(100% - 65px); /* opera */
height: -webkit-calc(100% - 65px); /* google, safari */
height: -moz-calc(100% - 65px); /* firefox */

also make sure you have spaces between values, see: https://stackoverflow.com/a/16291105/427622

Configure DataSource programmatically in Spring Boot

for springboot 2.1.7 working with url seems not to work. change with jdbcUrl instead.

In properties:

security:
      datasource:
        jdbcUrl: jdbc:mysql://ip:3306/security
        username: user
        password: pass

In java:

@ConfigurationProperties(prefix = "security.datasource")
@Bean("dataSource")
@Primary
public DataSource dataSource(){

    return DataSourceBuilder
            .create()
            .build();
}

How to use ImageBackground to set background image for screen in react-native

.hero-image {
  background-image: url("photographer.jpg"); /* The image used */
  background-color: #cccccc; /* Used if the image is unavailable */
  height: 500px; /* You must set a specified height */
  background-position: center; /* Center the image */
  background-repeat: no-repeat; /* Do not repeat the image */
  background-size: cover; /* Resize the background image to cover the entire container */
}

look result

How to put a new line into a wpf TextBlock control?

Using System.Environment.NewLine is the only solution that worked for me. When I tried \r\n, it just repeated the actual \r\n in the text box.

Ternary operator in PowerShell

If you're just looking for a syntactically simple way to assign/return a string or numeric based on a boolean condition, you can use the multiplication operator like this:

"Condition is "+("true"*$condition)+("false"*!$condition)
(12.34*$condition)+(56.78*!$condition)

If you're only ever interested in the result when something is true, you can just omit the false part entirely (or vice versa), e.g. a simple scoring system:

$isTall = $true
$isDark = $false
$isHandsome = $true

$score = (2*$isTall)+(4*$isDark)+(10*$isHandsome)
"Score = $score"
# or
# "Score = $((2*$isTall)+(4*$isDark)+(10*$isHandsome))"

Note that the boolean value should not be the leading term in the multiplication, i.e. $condition*"true" etc. won't work.

Failed to run sdkmanager --list with Java 9

I was able to solve the issue by using an edited sdkmanager.bat file by forcing to use the Java embedded inside the Android Studio Itself, which i presume uses the OpenJDK 8. Here is the edited sdkmanager I Used :

@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem  sdkmanager startup script for Windows
@rem
@rem ##########################################################################

@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal

set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%..

@rem Add default JVM options here. You can also use JAVA_OPTS and SDKMANAGER_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Dcom.android.sdklib.toolsdir=%~dp0\.."

@rem find Java from Android Studio
@rem Find java.exe
if defined ANDROID_STUDIO_JAVA_HOME goto findJavaFromAndroidStudioJavaHome

set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init

goto findJavaNormally

:findJavaFromAndroidStudioJavaHome
set JAVA_HOME=%ANDROID_STUDIO_JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe

if exist "%JAVA_EXE%" goto init

goto findJavaNormally




@rem java from java home
@rem Find java.exe
:findJavaNormally
if defined JAVA_HOME goto findJavaFromJavaHome

set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init

goto javaError

:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe

if exist "%JAVA_EXE%" goto init

goto javaDirectoryError



:javaError
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.

goto fail

:javaDirectoryError
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.

goto fail


:init
@rem Get command-line arguments, handling Windows variants

if not "%OS%" == "Windows_NT" goto win9xME_args

:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2

:win9xME_args_slurp
if "x%~1" == "x" goto execute

set CMD_LINE_ARGS=%*

:execute
@rem Setup the command line

set CLASSPATH=%APP_HOME%\lib\dvlib-26.0.0-dev.jar;%APP_HOME%\lib\jimfs-1.1.jar;%APP_HOME%\lib\jsr305-1.3.9.jar;%APP_HOME%\lib\repository-26.0.0-dev.jar;%APP_HOME%\lib\j2objc-annotations-1.1.jar;%APP_HOME%\lib\layoutlib-api-26.0.0-dev.jar;%APP_HOME%\lib\gson-2.3.jar;%APP_HOME%\lib\httpcore-4.2.5.jar;%APP_HOME%\lib\commons-logging-1.1.1.jar;%APP_HOME%\lib\commons-compress-1.12.jar;%APP_HOME%\lib\annotations-26.0.0-dev.jar;%APP_HOME%\lib\error_prone_annotations-2.0.18.jar;%APP_HOME%\lib\animal-sniffer-annotations-1.14.jar;%APP_HOME%\lib\httpclient-4.2.6.jar;%APP_HOME%\lib\commons-codec-1.6.jar;%APP_HOME%\lib\common-26.0.0-dev.jar;%APP_HOME%\lib\kxml2-2.3.0.jar;%APP_HOME%\lib\httpmime-4.1.jar;%APP_HOME%\lib\annotations-12.0.jar;%APP_HOME%\lib\sdklib-26.0.0-dev.jar;%APP_HOME%\lib\guava-22.0.jar

@rem Execute sdkmanager
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %SDKMANAGER_OPTS%  -classpath "%CLASSPATH%" com.android.sdklib.tool.sdkmanager.SdkManagerCli %CMD_LINE_ARGS%

:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd

:fail
rem Set variable SDKMANAGER_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if  not "" == "%SDKMANAGER_EXIT_CONSOLE%" exit 1
exit /b 1

:mainEnd
if "%OS%"=="Windows_NT" endlocal

:omega

Here i used an environmental variable ANDROID_STUDIO_JAVA_HOME which actually points to the JRE embedded in the android studio eg: ../android_studio/jre

This also has a fallback to JAVA_HOME if ANDROID_STUDIO_JAVA_HOME is not set.

Permanently add a directory to PYTHONPATH?

The script below works on all platforms as it's pure Python. It makes use of the pathlib Path, documented here https://docs.python.org/3/library/pathlib.html, to make it work cross-platform. You run it once, restart the kernel and that's it. Inspired by https://medium.com/@arnaud.bertrand/modifying-python-s-search-path-with-pth-files-2a41a4143574. In order to run it it requires administrator privileges since you modify some system files.

from pathlib import Path
to_add=Path(path_of_directory_to_add)
from sys import path

if str(to_add) not in path:
    minLen=999999
    for index,directory in enumerate(path):
        if 'site-packages' in directory and len(directory)<=minLen:
            minLen=len(directory)
            stpi=index
            
    pathSitePckgs=Path(path[stpi])
    with open(str(pathSitePckgs/'current_machine_paths.pth'),'w') as pth_file:
        pth_file.write(str(to_add))

How to send control+c from a bash script?

You can get the PID of a particular process like MySQL by using following commands: ps -e | pgrep mysql

This command will give you the PID of MySQL rocess. e.g, 13954 Now, type following command on terminal. kill -9 13954 This will kill the process of MySQL.

Cheap way to search a large text file for a string

5000 lines isn't big (well, depends on how long the lines are...)

Anyway: assuming the string will be a word and will be seperated by whitespace...

lines=open(file_path,'r').readlines()
str_wanted="whatever_youre_looking_for"


    for i in range(len(lines)):
        l1=lines.split()
        for p in range(len(l1)):
            if l1[p]==str_wanted:
                #found
                # i is the file line, lines[i] is the full line, etc.

How can I keep a container running on Kubernetes?

Use this command inside you Dockerfile to keep the container running in your K8s cluster:

  • CMD tail -f /dev/null

How to convert an address to a latitude/longitude?

Yahoo! Maps Web Services - Geocoding API accurately geocodes UK postcodes, unlike Google's API.

Unfortunately yahoo has deprecated this service, you could visit http://developer.yahoo.com/geo/placefinder/ for yahoo's service

Git on Mac OS X v10.7 (Lion)

There are a couple of points to this answer.

Firstly, you don't need to install Xcode. The Git installer works perfectly well. However, if you want to use Git from within Xcode - it expects to find an installation under /usr/local/bin. If you have your own Git installed elsewhere - I've got a script that fixes this.

Second is to do with the path. My Git path used to be kept under /etc/paths.d/ However, a Mac OS X v10.7 (Lion) install overwrites the contents of this folder and the /etc/paths file as well. That's what happened to me and I got the same error. Recreating the path file fixed the problem.

Read a variable in bash with a default value

name=Ricardo
echo "Please enter your name: $name \c"
read newname
[ -n "$newname" ] && name=$newname

Set the default; print it; read a new value; if there is a new value, use it in place of the default. There is (or was) some variations between shells and systems on how to suppress a newline at the end of a prompt. The '\c' notation seems to work on MacOS X 10.6.3 with a 3.x bash, and works on most variants of Unix derived from System V, using Bourne or Korn shells.

Also note that the user would probably not realize what is going on behind the scenes; their new data would be entered after the name already on the screen. It might be better to format it:

echo "Please enter your name ($name): \c"

How do I get Fiddler to stop ignoring traffic to localhost?

For Fiddler to capture traffic from localhost on local IIS, there are 3 steps (It worked on my computer):

  1. Click Tools > Fiddler Options. Ensure Allow remote clients to connect is checked. Close Fiddler.

enter image description here

  1. Create a new DWORD named ReverseProxyForPort inside KEY_CURRENT_USER\SOFTWARE\Microsoft\Fiddler2. Set the DWORD to port 80 (choose decimal here). Restart Fiddler.

enter image description here

  1. Add port 8888 to the addresses defined in your client. For example localhost:8888/MyService/WebAPI/v1/

How to access Winform textbox control from another class?

You will need to have some access to the Form's Instance to access its Controls collection and thereby changing the Text Box's Text.

One of ways could be that You can have a Your Form's Instance Available as Public or More better Create a new Constructor For your Second Form and have it receive the Form1's instance during initialization.

jQuery multiselect drop down menu

Update (2017): The following two libraries have now become the most common drop-down libraries used with Javascript. While they are jQuery-native, they have been customized to work with everything from AngularJS 1.x to having custom CSS for Bootstrap. (Chosen JS, the original answer here, seems to have dropped to #3 in popularity.)

Obligatory screenshots below.

Select2: Select2

Selectize: Selectize


Original answer (2012): I think that the Chosen library might also be useful. Its available in jQuery, Prototype and MooTools versions.

Attached is a screenshot of how the multi-select functionality looks in Chosen.

Chosen library

How to git clone a specific tag

git clone --depth 1 --branch <tag_name> <repo_url>

--depth 1 is optional but if you only need the state at that one revision, you probably want to skip downloading all the history up to that revision.

Dataset - Vehicle make/model/year (free)

How about Freebase? I think they have an API available, too.

http://www.freebase.com/

Why can't non-default arguments follow default arguments?

SyntaxError: non-default argument follows default argument

If you were to allow this, the default arguments would be rendered useless because you would never be able to use their default values, since the non-default arguments come after.

In Python 3 however, you may do the following:

def fun1(a="who is you", b="True", *, x, y):
    pass

which makes x and y keyword only so you can do this:

fun1(x=2, y=2)

This works because there is no longer any ambiguity. Note you still can't do fun1(2, 2) (that would set the default arguments).

asp.net Button OnClick event not firing

Try to go into Design mode in Visual Studio, locate the button and double click the button that should setup the event. Otherwise once the button is selected in Design more, go to the properties and try setting it from there.

Java Wait and Notify: IllegalMonitorStateException

You're calling both wait and notifyAll without using a synchronized block. In both cases the calling thread must own the lock on the monitor you call the method on.

From the docs for notify (wait and notifyAll have similar documentation but refer to notify for the fullest description):

This method should only be called by a thread that is the owner of this object's monitor. A thread becomes the owner of the object's monitor in one of three ways:

  • By executing a synchronized instance method of that object.
  • By executing the body of a synchronized statement that synchronizes on the object.
  • For objects of type Class, by executing a synchronized static method of that class.

Only one thread at a time can own an object's monitor.

Only one thread will be able to actually exit wait at a time after notifyAll as they'll all have to acquire the same monitor again - but all will have been notified, so as soon as the first one then exits the synchronized block, the next will acquire the lock etc.

get the data of uploaded file in javascript

The example below shows the basic usage of the FileReader to read the contents of an uploaded file. Here is a working Plunker of this example.

<!DOCTYPE html>
<html>
  <head>
    <script src="script.js"></script>
  </head>

  <body onload="init()">
    <input id="fileInput" type="file" name="file" />
    <pre id="fileContent"></pre>
  </body>
</html>

script.js

function init(){
  document.getElementById('fileInput').addEventListener('change', handleFileSelect, false);
}

function handleFileSelect(event){
  const reader = new FileReader()
  reader.onload = handleFileLoad;
  reader.readAsText(event.target.files[0])
}

function handleFileLoad(event){
  console.log(event);
  document.getElementById('fileContent').textContent = event.target.result;
}

Using HTTPS with REST in Java

Check this out: http://code.google.com/p/resting/. I could use resting to consume HTTPS REST services.

Converting a pointer into an integer

I came across this question while studying the source code of SQLite.

In the sqliteInt.h, there is a paragraph of code defined a macro convert between integer and pointer. The author made a very good statement first pointing out it should be a compiler dependent problem and then implemented the solution to account for most of the popular compilers out there.

#if defined(__PTRDIFF_TYPE__)  /* This case should work for GCC */
# define SQLITE_INT_TO_PTR(X)  ((void*)(__PTRDIFF_TYPE__)(X))
# define SQLITE_PTR_TO_INT(X)  ((int)(__PTRDIFF_TYPE__)(X))
#elif !defined(__GNUC__)       /* Works for compilers other than LLVM */
# define SQLITE_INT_TO_PTR(X)  ((void*)&((char*)0)[X])
# define SQLITE_PTR_TO_INT(X)  ((int)(((char*)X)-(char*)0))
#elif defined(HAVE_STDINT_H)   /* Use this case if we have ANSI headers */
# define SQLITE_INT_TO_PTR(X)  ((void*)(intptr_t)(X))
# define SQLITE_PTR_TO_INT(X)  ((int)(intptr_t)(X))
#else                          /* Generates a warning - but it always works     */
# define SQLITE_INT_TO_PTR(X)  ((void*)(X))
# define SQLITE_PTR_TO_INT(X)  ((int)(X))
#endif

And here is a quote of the comment for more details:

/*
** The following macros are used to cast pointers to integers and
** integers to pointers.  The way you do this varies from one compiler
** to the next, so we have developed the following set of #if statements
** to generate appropriate macros for a wide range of compilers.
**
** The correct "ANSI" way to do this is to use the intptr_t type.
** Unfortunately, that typedef is not available on all compilers, or
** if it is available, it requires an #include of specific headers
** that vary from one machine to the next.
**
** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on
** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).
** So we have to define the macros in different ways depending on the
** compiler.
*/

Credit goes to the committers.

find vs find_by vs where

where returns ActiveRecord::Relation

Now take a look at find_by implementation:

def find_by
  where(*args).take
end

As you can see find_by is the same as where but it returns only one record. This method should be used for getting 1 record and where should be used for getting all records with some conditions.

bootstrap popover not showing on top of all elements

When you have some styles on a parent element that interfere with a popover, you’ll want to specify a custom container so that the popover’s HTML appears within that element instead.

For instance say the parent for a popover is body then you can use.

    <a href="#" data-toggle="tooltip" data-container="body"> Popover One </a>

Other case might be when popover is placed inside some other element and you want to show popover over that element, then you'll need to specify that element in data-container. ex: Suppose, we have popover inside a bootstrap modal with id as 'modal-two', then you'll need to set 'data-container' to 'modal-two'.

    <a href="#" data-toggle="tooltip" data-container="#modal-two"> Popover Two </a>

Executing Javascript from Python

Using PyV8, I can do this. However, I have to replace document.write with return because there's no DOM and therefore no document.

import PyV8
ctx = PyV8.JSContext()
ctx.enter()

js = """
function escramble_758(){
var a,b,c
a='+1 '
b='84-'
a+='425-'
b+='7450'
c='9'
document.write(a+c+b)
}
escramble_758()
"""

print ctx.eval(js.replace("document.write", "return "))

Or you could create a mock document object

class MockDocument(object):

    def __init__(self):
        self.value = ''

    def write(self, *args):
        self.value += ''.join(str(i) for i in args)


class Global(PyV8.JSClass):
    def __init__(self):
        self.document = MockDocument()

scope = Global()
ctx = PyV8.JSContext(scope)
ctx.enter()
ctx.eval(js)
print scope.document.value

How can I add a .npmrc file?

This issue is because of you having some local or private packages. For accessing those packages you have to create .npmrc file for this issue. Just refer the following link for your solution. https://nodesource.com/blog/configuring-your-npmrc-for-an-optimal-node-js-environment

Passing multiple variables in @RequestBody to a Spring MVC controller using Ajax

I have adapted the solution of Biju:

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.IOUtils;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;


public class JsonPathArgumentResolver implements HandlerMethodArgumentResolver{

    private static final String JSONBODYATTRIBUTE = "JSON_REQUEST_BODY";

    private ObjectMapper om = new ObjectMapper();

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(JsonArg.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        String jsonBody = getRequestBody(webRequest);

        JsonNode rootNode = om.readTree(jsonBody);
        JsonNode node = rootNode.path(parameter.getParameterName());    

        return om.readValue(node.toString(), parameter.getParameterType());
    }


    private String getRequestBody(NativeWebRequest webRequest){
        HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class);

        String jsonBody = (String) webRequest.getAttribute(JSONBODYATTRIBUTE, NativeWebRequest.SCOPE_REQUEST);
        if (jsonBody==null){
            try {
                jsonBody = IOUtils.toString(servletRequest.getInputStream());
                webRequest.setAttribute(JSONBODYATTRIBUTE, jsonBody, NativeWebRequest.SCOPE_REQUEST);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return jsonBody;

    }

}

What's the different:

  • I'm using Jackson to convert json
  • I don't need a value in the annotation, you can read the name of the parameter out of the MethodParameter
  • I also read the type of the parameter out of the Methodparameter => so the solution should be generic (i tested it with string and DTOs)

BR

Can't install laravel installer via composer

For macOs users you can use Homebrew instead :

# For php v7.0
brew install [email protected]

# For php v7.1
brew install [email protected]

# For php v7.2
brew install [email protected]

# For php v7.3
brew install [email protected]

# For php v7.4
brew install [email protected]

Is String.Contains() faster than String.IndexOf()?

Contains(s2) is many times (in my computer 10 times) faster than IndexOf(s2) because Contains uses StringComparison.Ordinal that is faster than the culture sensitive search that IndexOf does by default (but that may change in .net 4.0 http://davesbox.com/archive/2008/11/12/breaking-changes-to-the-string-class.aspx).

Contains has exactly the same performance as IndexOf(s2,StringComparison.Ordinal) >= 0 in my tests but it's shorter and makes your intent clear.

JSON.Parse,'Uncaught SyntaxError: Unexpected token o

Without single quotes around it, you are creating an array with two objects inside of it. This is JavaScript's own syntax. When you add the quotes, that object (array+2 objects) is now a string. You can use JSON.parse to convert a string into a JavaScript object. You cannot use JSON.parse to convert a JavaScript object into a JavaScript object.

//String - you can use JSON.parse on it
var jsonStringNoQuotes = '[{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}]';

//Already a javascript object - you cannot use JSON.parse on it
var jsonStringNoQuotes = [{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}];

Furthermore, your last example fails because you are adding literal single quote characters to the JSON string. This is illegal. JSON specification states that only double quotes are allowed. If you were to console.log the following...

console.log("'"+[{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}]+"'");
//Logs:
'[object Object],[object Object]'

You would see that it returns the string representation of the array, which gets converted to a comma separated list, and each list item would be the string representation of an object, which is [object Object]. Remember, associative arrays in javascript are simply objects with each key/value pair being a property/value.

Why does this happen? Because you are starting with a string "'", then you are trying to append the array to it, which requests the string representation of it, then you are appending another string "'".

Please do not confuse JSON with Javascript, as they are entirely different things. JSON is a data format that is humanly readable, and was intended to match the syntax used when creating javascript objects. JSON is a string. Javascript objects are not, and therefor when declared in code are not surrounded in quotes.

See this fiddle: http://jsfiddle.net/NrnK5/

Error while installing json gem 'mkmf.rb can't find header files for ruby'

You need to install the entire ruby and not just the minimum package. The correct command to use is:

sudo apt install ruby-full

The following command will also not install a complete ruby:

sudo apt-get install ruby2.3-dev

How to use HTTP.GET in AngularJS correctly? In specific, for an external API call?

So you need to use what we call promise. Read how angular handles it here, https://docs.angularjs.org/api/ng/service/$q. Turns our $http support promises inherently so in your case we'll do something like this,

(function() {
  "use strict";
  var serviceCallJson = function($http) {

      this.getCustomers = function() {
        // http method anyways returns promise so you can catch it in calling function
        return $http({
            method : 'get',
            url : '../viewersData/userPwdPair.json'
          });
      }

  }

  var validateIn = function (serviceCallJson, $q) {

      this.called = function(username, password) {
          var deferred = $q.defer(); 
          serviceCallJson.getCustomers().then( 
            function( returnedData ) {
              console.log(returnedData); // you should get output here this is a success handler
              var i = 0;
              angular.forEach(returnedData, function(value, key){
                while (i < 10) {
                  if(value[i].username == username) {
                    if(value[i].password == password) {
                     alert("Logged In");
                    }
                  }
                  i = i + 1;
                }
              });
            }, 
            function() {

              // this is error handler
            } 
          );
          return deferred.promise;  
      }

  }

  angular.module('assignment1App')
    .service ('serviceCallJson', serviceCallJson)

  angular.module('assignment1App')
  .service ('validateIn', ['serviceCallJson', validateIn])

}())

nginx 502 bad gateway

change

fastcgi_pass    unix:/var/run/php-fpm.sock;

to

fastcgi_pass    unix:/var/run/php5-fpm.sock;

How to loop through a plain JavaScript object with the objects as members?

p is the value

for (var key in p) {
  alert(key + ' => ' + p[key]);
}

OR

Object.keys(p).forEach(key => { console.log(key, p[key]) })

Iterate through <select> options

$("#selectId > option").each(function() {
    alert(this.text + ' ' + this.value);
});

Boolean Field in Oracle

Either 1/0 or Y/N with a check constraint on it. ether way is fine. I personally prefer 1/0 as I do alot of work in perl, and it makes it really easy to do perl Boolean operations on database fields.

If you want a really in depth discussion of this question with one of Oracles head honchos, check out what Tom Kyte has to say about this Here

Show a PDF files in users browser via PHP/Perl

I assume you want the PDF to display in the browser, rather than forcing a download. If that is the case, try setting the Content-Disposition header with a value of inline.

Also remember that this will also be affected by browser settings - some browsers may be configured to always download PDF files or open them in a different application (e.g. Adobe Reader)

HTTP 404 when accessing .svc file in IIS

There are 2 .net framework version are given under the features in add role/ features in server 2012

a. 3.5

b. 4.5

Depending up on used framework you can enable HTTP-Activation under WCF services. :)

Volatile Vs Atomic

The volatile keyword is used:

  • to make non atomic 64-bit operations atomic: long and double. (all other, primitive accesses are already guaranteed to be atomic!)
  • to make variable updates guaranteed to be seen by other threads + visibility effects: after writing to a volatile variable, all the variables that where visible before writing that variable become visible to another thread after reading the same volatile variable (happen-before ordering).

The java.util.concurrent.atomic.* classes are, according to the java docs:

A small toolkit of classes that support lock-free thread-safe programming on single variables. In essence, the classes in this package extend the notion of volatile values, fields, and array elements to those that also provide an atomic conditional update operation of the form:

boolean compareAndSet(expectedValue, updateValue);

The atomic classes are built around the atomic compareAndSet(...) function that maps to an atomic CPU instruction. The atomic classes introduce the happen-before ordering as the volatile variables do. (with one exception: weakCompareAndSet(...)).

From the java docs:

When a thread sees an update to an atomic variable caused by a weakCompareAndSet, it does not necessarily see updates to any other variables that occurred before the weakCompareAndSet.

To your question:

Does this mean that whosoever takes lock on it, that will be setting its value first. And in if meantime, some other thread comes up and read old value while first thread was changing its value, then doesn't new thread will read its old value?

You don't lock anything, what you are describing is a typical race condition that will happen eventually if threads access shared data without proper synchronization. As already mentioned declaring a variable volatile in this case will only ensure that other threads will see the change of the variable (the value will not be cached in a register of some cache that is only seen by one thread).

What is the difference between AtomicInteger and volatile int?

AtomicInteger provides atomic operations on an int with proper synchronization (eg. incrementAndGet(), getAndAdd(...), ...), volatile int will just ensure the visibility of the int to other threads.

How do I find the length of an array?

Instead of using the built in array function aka:

 int x[3] = {0, 1, 2};

you should use the array class and the array template. Try:

#include <array>
array<type_of_the_array, number_of_elements_in_the_array> Name_of_Array = {};

So now if you want to find the length of the array, all you have to do is using the size function in the array class.

Name_of_Array.size();

and that should return the length of elements in the array.

Exception : javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated

This can also happen if you are attempting to connect over HTTPS and the server is not configured to handle SSL connections correctly.

I would check your application servers SSL settings and make sure that the certification is configured correctly.

Is it possible to access to google translate api for free?

Yes, you can use GT for free. See the post with explanation. And look at repo on GitHub.

UPD 19.03.2019 Here is a version for browser on GitHub.

Python - TypeError: 'int' object is not iterable

This is very simple you are trying to convert an integer to a list object !!! of course it will fail and it should ...

To demonstrate/prove this to you by using the example you provided ...just use type function for each case as below and the results will speak for itself !

>>> type(cow)
<class 'range'>
>>> 
>>> type(cow[0])
<class 'int'>
>>> 
>>> type(0)
<class 'int'>
>>> 
>>> >>> list(0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>> 

How to read if a checkbox is checked in PHP?

A minimalistic boolean check with switch position retaining

<?php

$checked = ($_POST['foo'] == ' checked');

?>

<input type="checkbox" name="foo" value=" checked"<?=$_POST['foo']?>>

Python function attributes - uses and abuses

I've used them as static variables for a function. For example, given the following C code:

int fn(int i)
{
    static f = 1;
    f += i;
    return f;
}

I can implement the function similarly in Python:

def fn(i):
    fn.f += i
    return fn.f
fn.f = 1

This would definitely fall into the "abuses" end of the spectrum.

Increment counter with loop

what led me to this page is that I set within a page then the inside of an included page I did the increment

and here is the problem

so to solve such a problem, simply use scope="request" when you declare the variable or the increment

//when you set the variale add scope="request"
<c:set var="nFilters" value="${0}" scope="request"/>
//the increment, it can be happened inside an included page
<c:set var="nFilters" value="${nFilters + 1}"  scope="request" />

hope this saves your time

Set Culture in an ASP.Net MVC app

I would do it in the Initialize event of the controller like this...

    protected override void Initialize(System.Web.Routing.RequestContext requestContext)
    {
        base.Initialize(requestContext);

        const string culture = "en-US";
        CultureInfo ci = CultureInfo.GetCultureInfo(culture);

        Thread.CurrentThread.CurrentCulture = ci;
        Thread.CurrentThread.CurrentUICulture = ci;
    }

Why there is no ConcurrentHashSet against ConcurrentHashMap

As pointed by this the best way to obtain a concurrency-able HashSet is by means of Collections.synchronizedSet()

Set s = Collections.synchronizedSet(new HashSet(...));

This worked for me and I haven't seen anybody really pointing to it.

EDIT This is less efficient than the currently aproved solution, as Eugene points out, since it just wraps your set into a synchronized decorator, while a ConcurrentHashMap actually implements low-level concurrency and it can back your Set just as fine. So thanks to Mr. Stepanenkov for making that clear.

http://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#synchronizedSet-java.util.Set-

In Java, what is the best way to determine the size of an object?

Firstly "the size of an object" isn't a well-defined concept in Java. You could mean the object itself, with just its members, the Object and all objects it refers to (the reference graph). You could mean the size in memory or the size on disk. And the JVM is allowed to optimise things like Strings.

So the only correct way is to ask the JVM, with a good profiler (I use YourKit), which probably isn't what you want.

However, from the description above it sounds like each row will be self-contained, and not have a big dependency tree, so the serialization method will probably be a good approximation on most JVMs. The easiest way to do this is as follows:

 Serializable ser;
 ByteArrayOutputStream baos = new ByteArrayOutputStream();
 ObjectOutputStream oos = new ObjectOutputStream(baos);
 oos.writeObject(ser);
 oos.close();
 return baos.size();

Remember that if you have objects with common references this will not give the correct result, and size of serialization will not always match size in memory, but it is a good approximation. The code will be a bit more efficient if you initialise the ByteArrayOutputStream size to a sensible value.

Import existing source code to GitHub

As JB quite rightly points out, it's made incredibly easy on GitHub by simply following the instructions.

Here's an example of the instructions displayed after setting up a new repository on GitHub using http://github.com/new when you're logged in.

Global setup:

 Set up Git:
  git config --global user.name "Name"
  git config --global user.email [email protected]


Next steps:

  mkdir audioscripts
  cd audioscripts
  git init
  touch README
  git add README
  git commit -m 'first commit'
  git remote add origin [email protected]:ktec/audioscripts.git
  git push -u origin master


Existing Git repository?

  cd existing_git_repo
  git remote add origin [email protected]:ktec/audioscripts.git
  git push -u origin master


Importing a Subversion repository?

  Check out the guide for step-by-step instructions.

It couldn't be easier!!

How to get JSON object from Razor Model object in javascript

If You want make json object from yor model do like this :

  foreach (var item in Persons)
   {
    var jsonObj=["FirstName":"@item.FirstName"]
   }

Or Use Json.Net to make json from your model :

string json = JsonConvert.SerializeObject(person);

Javascript Iframe innerHTML

Conroy's answer was right. In the case you need only stuff from body tag, just use:

$('#my_iframe').contents().find('body').html();

ES6 Map in Typescript

With the lib config option your are able to cherry pick Map into your project. Just add es2015.collection to your lib section. When you have no lib config add one with the defaults and add es2015.collection.

So when you have target: es5, change tsconfig.json to:

"target": "es5",
"lib": [ "dom", "es5", "scripthost", "es2015.collection" ],

MemoryStream - Cannot access a closed Stream

Since .net45 you can use the LeaveOpen constructor argument of StreamWriter and still use the using statement. Example:

using (var ms = new MemoryStream())
{
    using (var sw = new StreamWriter(ms, Encoding.UTF8, 1024, true))
    {
        sw.WriteLine("data");
        sw.WriteLine("data 2");    
    }

    ms.Position = 0;
    using (var sr = new StreamReader(ms))
    {
        Console.WriteLine(sr.ReadToEnd());
    }
}

Python: tf-idf-cosine: to find document similarity

I know its an old post. but I tried the http://scikit-learn.sourceforge.net/stable/ package. here is my code to find the cosine similarity. The question was how will you calculate the cosine similarity with this package and here is my code for that

from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.feature_extraction.text import TfidfVectorizer

f = open("/root/Myfolder/scoringDocuments/doc1")
doc1 = str.decode(f.read(), "UTF-8", "ignore")
f = open("/root/Myfolder/scoringDocuments/doc2")
doc2 = str.decode(f.read(), "UTF-8", "ignore")
f = open("/root/Myfolder/scoringDocuments/doc3")
doc3 = str.decode(f.read(), "UTF-8", "ignore")

train_set = ["president of India",doc1, doc2, doc3]

tfidf_vectorizer = TfidfVectorizer()
tfidf_matrix_train = tfidf_vectorizer.fit_transform(train_set)  #finds the tfidf score with normalization
print "cosine scores ==> ",cosine_similarity(tfidf_matrix_train[0:1], tfidf_matrix_train)  #here the first element of tfidf_matrix_train is matched with other three elements

Here suppose the query is the first element of train_set and doc1,doc2 and doc3 are the documents which I want to rank with the help of cosine similarity. then I can use this code.

Also the tutorials provided in the question was very useful. Here are all the parts for it part-I,part-II,part-III

the output will be as follows :

[[ 1.          0.07102631  0.02731343  0.06348799]]

here 1 represents that query is matched with itself and the other three are the scores for matching the query with the respective documents.

dyld: Library not loaded: /usr/local/lib/libpng16.16.dylib with anything php related

I had very hard time with this error :

Reason: Incompatible library version: php requires version 44.0.0 or later, but libpng16.16.dylib provides version 42.0.0 Trace/BPT trap: 6

I did all the above things with brew and much more ... but it wasn't this !

Check where your library is :

sudo find / -name libpng16.16.dylib

In my case here was the relevant result :

  • /usr/local/lib/libpng16.16.dylib
  • /usr/local/Cellar/libpng/1.6.34/lib/libpng16.16.dylib
  • /Applications/MAMP/Library/lib/libpng16.16.dylib
  • /opt/X11/lib/libpng16.16.dylib

So as I'm a MAMP user it turn out that the error appeared while I was trying to update from PHP 7.1.0 to 7.1.8 (last MAMP php available) as Symfony4 require at least 7.1.3

At the end I instaled the new version of MAMP and it worked (4.1 to 4.2). However be carreful when you're doing this, you need to backup first everything in your MAMP/htdoc folder. Also keep a backup of your custom compiled php version than can live in MAMP/bin/php. (In my case I had a special PHP version with Oracle drivers).

Also if you configured the MAMP php version to be your CLI php interpreter, you'll need to update the PATH in your .bash_profile

It should look something like this :

export PATH=/Applications/MAMP/bin/php/php7.1.8/bin:$PATH

I hope this can help.

Find the most frequent number in a NumPy array

You may use

values, counts = np.unique(a, return_counts=True)

ind = np.argmax(counts)
print(values[ind])  # prints the most frequent element

ind = np.argpartition(-counts, kth=10)[:10]
print(values[ind])  # prints the 10 most frequent elements

If some element is as frequent as another one, this code will return only the first element.

Changing file permission in Python

All the current answers clobber the non-writing permissions: they make the file readable-but-not-executable for everybody. Granted, this is because the initial question asked for 444 permissions -- but we can do better!

Here's a solution that leaves all the individual "read" and "execute" bits untouched. I wrote verbose code to make it easy to understand; you can make it more terse if you like.

import os
import stat

def remove_write_permissions(path):
    """Remove write permissions from this path, while keeping all other permissions intact.

    Params:
        path:  The path whose permissions to alter.
    """
    NO_USER_WRITING = ~stat.S_IWUSR
    NO_GROUP_WRITING = ~stat.S_IWGRP
    NO_OTHER_WRITING = ~stat.S_IWOTH
    NO_WRITING = NO_USER_WRITING & NO_GROUP_WRITING & NO_OTHER_WRITING

    current_permissions = stat.S_IMODE(os.lstat(path).st_mode)
    os.chmod(path, current_permissions & NO_WRITING)

Why does this work?

As John La Rooy pointed out,stat.S_IWUSR basically means "the bitmask for the user's write permissions". We want to set the corresponding permission bit to 0. To do that, we need the exact opposite bitmask (i.e., one with a 0 in that location, and 1's everywhere else). The ~ operator, which flips all the bits, gives us exactly that. If we apply this to any variable via the "bitwise and" operator (&), it will zero out the corresponding bit.

We need to repeat this logic with the "group" and "other" permission bits, too. Here we can save some time by just &'ing them all together (forming the NO_WRITING bit constant).

The last step is to get the current file's permissions, and actually perform the bitwise-and operation.

What are static factory methods?

Readability can be improved by static factory methods:

Compare

public class Foo{
  public Foo(boolean withBar){
    //...
  }
}

//...

// What exactly does this mean?
Foo foo = new Foo(true);
// You have to lookup the documentation to be sure.
// Even if you remember that the boolean has something to do with a Bar
// you might not remember whether it specified withBar or withoutBar.

to

public class Foo{
  public static Foo createWithBar(){
    //...
  }

  public static Foo createWithoutBar(){
    //...
  }
}

// ...

// This is much easier to read!
Foo foo = Foo.createWithBar();

How to downgrade Node version

For windows 10,

  • Uninstalling the node from the "Add or remove programs"
  • Installing the required version from https://nodejs.org/en/

worked for me.

How to get the entire document HTML as a string?

The correct way is actually:

webBrowser1.DocumentText

Click through div to underlying elements

An easier way would be to inline the transparent background image using Data URIs as follows:

.click-through {
    pointer-events: none;
    background: url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7);
}

How to retrieve SQL result column value using column name in Python?

selecting values from particular column:

import pymysql
db = pymysql.connect("localhost","root","root","school")
cursor=db.cursor()
sql="""select Total from student"""
l=[]
try:
    #query execution
    cursor.execute(sql)
    #fetch all rows 
    rs = cursor.fetchall()
    #iterate through rows
    for i in rs:
        #converting set to list
        k=list(i)
        #taking the first element from the list and append it to the list
        l.append(k[0])
    db.commit()
except:
    db.rollback()
db.close()
print(l)

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

another fun way to do this:

from functools import reduce
from operator import add

li=[[1,2],[3,4]]
x= reduce(add, li)

How to present UIAlertController when not in a view controller?

You can send the current view or controller as a parameter:

+ (void)myUtilityMethod:(id)controller {
    // do stuff
    // something bad happened, display an alert.
}

How to repeat a char using printf?

i think doing some like this.

void printchar(char c, int n){
     int i;
     for(i=0;i<n;i++)
         print("%c",c);
}

printchar("*",10);

JavaScript chop/slice/trim off last character in string

debris = string.split("_") //explode string into array of strings indexed by "_"

debris.pop(); //pop last element off the array (which you didn't want)

result = debris.join("_"); //fuse the remainng items together like the sun

String.Format like functionality in T-SQL?

take a look at xp_sprintf. example below.

DECLARE @ret_string varchar (255)
EXEC xp_sprintf @ret_string OUTPUT, 
    'INSERT INTO %s VALUES (%s, %s)', 'table1', '1', '2'
PRINT @ret_string

Result looks like this:

INSERT INTO table1 VALUES (1, 2)

Just found an issue with the max size (255 char limit) of the string with this so there is an alternative function you can use:

create function dbo.fnSprintf (@s varchar(MAX), 
                @params varchar(MAX), @separator char(1) = ',')
returns varchar(MAX)
as
begin
declare @p varchar(MAX)
declare @paramlen int

set @params = @params + @separator
set @paramlen = len(@params)
while not @params = ''
begin
    set @p = left(@params+@separator, charindex(@separator, @params)-1)
    set @s = STUFF(@s, charindex('%s', @s), 2, @p)
    set @params = substring(@params, len(@p)+2, @paramlen)
end
return @s
end

To get the same result as above you call the function as follows:

print dbo.fnSprintf('INSERT INTO %s VALUES (%s, %s)', 'table1,1,2', default)

return query based on date

If you are using Mongoose,

try {
  const data = await GPSDatas.aggregate([
    {
      $match: { createdAt : { $gt: new Date() }
    },
    {
      $sort: { createdAt: 1 }
    }
  ])
  console.log(data)

} catch(error) {
    console.log(error)
}

How to add a class to body tag?

Well, you're going to want document.location. Do some sort of string manipulation on it (unless jQuery has a way to avoid that work for you) and then

$(body).addClass(foo);

I know this isn't the complete answer, but I assume you can work the rest out :)

How to open .dll files to see what is written inside?

I think you have downloaded the .NET Reflector & this FileGenerator plugin http://filegenreflector.codeplex.com/ , If you do,

  1. Open up the Reflector.exe,

  2. Go to View and click Add-Ins,

  3. In the Add-Ins window click Add...,

  4. Then find the dll you have downloaded

  5. FileGenerator.dll (witch came wth the FileGenerator plugin),

  6. Then close the Add-Ins window.

  7. Go to File and click Open and choose the dll that you want to decompile,

  8. After you have opend it, it will appear in the tree view,

  9. Go to Tools and click Generate Files(Crtl+Shift+G),

  10. select the output directory and select appropriate settings as your wish, Click generate files.

OR

use http://ilspy.net/

ASP.NET MVC - Getting QueryString values

I think what you are looking for is

Request.QueryString["QueryStringName"]

and you can access it on views by adding @

now look at my example,,, I generated a Url with QueryString

 var listURL = '@Url.RouteUrl(new { controller = "Sector", action = "List" , name = Request.QueryString["name"]})';

the listURL value is /Sector/List?name=value'

and when queryString is empty

listURL value is /Sector/List

C# cannot convert method to non delegate type

You can simplify your class code to this below and it will work as is but if you want to make your example work, add parenthesis at the end : string x = getTitle();

public class Pin
{
   public string Title { get; set;}
}

How to get the total number of rows of a GROUP BY query?

That's yet another question, which, being wrongly put, spawns A LOT of terrible solutions, all making things awfully complicated to solve a non-existent problem.

The extremely simple and obvious rule for any database interaction is

Always select the only data you need.

From this point of view, the question is wrong and the accepted answer is right. But other proposed solutions are just terrible.

The question is "how to get the count wrong way". One should never answer it straightforward, but instead, the only proper answer is "One should never select the rows to count them. Instead, ALWAYS ask the database to count the rows for you." This rule is so obvious, that it's just improbable to see so many tries to break it.

After learning this rule, we would see that this is an SQL question, not even PDO related. And, were it asked properly, from SQL perspective, the answer would appeared in an instant - DISTINCT.

$num = $db->query('SELECT count(distinct boele) FROM tbl WHERE oele = 2')->fetchColumn();

is the right answer to this particular question.

The opening poster's own solution is also acceptable from the perspective of the aforementioned rule, but would be less efficient in general terms.

Remove a fixed prefix/suffix from a string in Bash

Using @Adrian Frühwirth answer:

function strip {
    local STRING=${1#$"$2"}
    echo ${STRING%$"$2"}
}

use it like this

HELLO=":hello:"
HELLO=$(strip "$HELLO" ":")
echo $HELLO # hello

MSSQL Error 'The underlying provider failed on Open'

I found the problem was that I had the server path within the connection string in one of these variants:

SERVER\SQLEXPRESS
SERVER

When really I should have:

.\SQLEXPRESS

For some reason I got the error whenever it had difficulty locating the instance of SQL.

How to concatenate two MP4 files using FFmpeg?

based on rogerdpack's and Ed999's responses, I've created my .sh version

#!/bin/bash

[ -e list.txt ] && rm list.txt
for f in *.mp4
do
   echo "file $f" >> list.txt
done

ffmpeg -f concat -i list.txt -c copy joined-out.mp4 && rm list.txt

it joins all the *.mp4 files in current folder into joined-out.mp4

tested on mac.

resulting filesize is exact sum of my 60 tested files. Should not be any loss. Just what I needed

How to access the first property of a Javascript object?

No. An object literal, as defined by MDC is:

a list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({}).

Therefore an object literal is not an array, and you can only access the properties using their explicit name or a for loop using the in keyword.

ASP.NET MVC View Engine Comparison

ASP.NET MVC View Engines (Community Wiki)

Since a comprehensive list does not appear to exist, let's start one here on SO. This can be of great value to the ASP.NET MVC community if people add their experience (esp. anyone who contributed to one of these). Anything implementing IViewEngine (e.g. VirtualPathProviderViewEngine) is fair game here. Just alphabetize new View Engines (leaving WebFormViewEngine and Razor at the top), and try to be objective in comparisons.


System.Web.Mvc.WebFormViewEngine

Design Goals:

A view engine that is used to render a Web Forms page to the response.

Pros:

  • ubiquitous since it ships with ASP.NET MVC
  • familiar experience for ASP.NET developers
  • IntelliSense
  • can choose any language with a CodeDom provider (e.g. C#, VB.NET, F#, Boo, Nemerle)
  • on-demand compilation or precompiled views

Cons:

  • usage is confused by existence of "classic ASP.NET" patterns which no longer apply in MVC (e.g. ViewState PostBack)
  • can contribute to anti-pattern of "tag soup"
  • code-block syntax and strong-typing can get in the way
  • IntelliSense enforces style not always appropriate for inline code blocks
  • can be noisy when designing simple templates

Example:

<%@ Control Inherits="System.Web.Mvc.ViewPage<IEnumerable<Product>>" %>
<% if(model.Any()) { %>
<ul>
    <% foreach(var p in model){%>
    <li><%=p.Name%></li>
    <%}%>
</ul>
<%}else{%>
    <p>No products available</p>
<%}%>

System.Web.Razor

Design Goals:

Pros:

  • Compact, Expressive, and Fluid
  • Easy to Learn
  • Is not a new language
  • Has great Intellisense
  • Unit Testable
  • Ubiquitous, ships with ASP.NET MVC

Cons:

  • Creates a slightly different problem from "tag soup" referenced above. Where the server tags actually provide structure around server and non-server code, Razor confuses HTML and server code, making pure HTML or JS development challenging (see Con Example #1) as you end up having to "escape" HTML and / or JavaScript tags under certain very common conditions.
  • Poor encapsulation+reuseability: It's impractical to call a razor template as if it were a normal method - in practice razor can call code but not vice versa, which can encourage mixing of code and presentation.
  • Syntax is very html-oriented; generating non-html content can be tricky. Despite this, razor's data model is essentially just string-concatenation, so syntax and nesting errors are neither statically nor dynamically detected, though VS.NET design-time help mitigates this somewhat. Maintainability and refactorability can suffer due to this.
  • No documented API, http://msdn.microsoft.com/en-us/library/system.web.razor.aspx

Con Example #1 (notice the placement of "string[]..."):

@{
    <h3>Team Members</h3> string[] teamMembers = {"Matt", "Joanne", "Robert"};
    foreach (var person in teamMembers)
    {
        <p>@person</p>
    }
}

Bellevue

Design goals:

  • Respect HTML as first-class language as opposed to treating it as "just text".
  • Don't mess with my HTML! The data binding code (Bellevue code) should be separate from HTML.
  • Enforce strict Model-View separation

Brail

Design Goals:

The Brail view engine has been ported from MonoRail to work with the Microsoft ASP.NET MVC Framework. For an introduction to Brail, see the documentation on the Castle project website.

Pros:

  • modeled after "wrist-friendly python syntax"
  • On-demand compiled views (but no precompilation available)

Cons:

  • designed to be written in the language Boo

Example:

<html>    
<head>        
<title>${title}</title>
</head>    
<body>        
     <p>The following items are in the list:</p>  
     <ul><%for element in list:    output "<li>${element}</li>"%></ul>
     <p>I hope that you would like Brail</p>    
</body>
</html>

Hasic

Hasic uses VB.NET's XML literals instead of strings like most other view engines.

Pros:

  • Compile-time checking of valid XML
  • Syntax colouring
  • Full intellisense
  • Compiled views
  • Extensibility using regular CLR classes, functions, etc
  • Seamless composability and manipulation since it's regular VB.NET code
  • Unit testable

Cons:

  • Performance: Builds the whole DOM before sending it to client.

Example:

Protected Overrides Function Body() As XElement
    Return _
    <body>
        <h1>Hello, World</h1>
    </body>
End Function

NDjango

Design Goals:

NDjango is an implementation of the Django Template Language on the .NET platform, using the F# language.

Pros:


NHaml

Design Goals:

.NET port of Rails Haml view engine. From the Haml website:

Haml is a markup language that's used to cleanly and simply describe the XHTML of any web document, without the use of inline code... Haml avoids the need for explicitly coding XHTML into the template, because it is actually an abstract description of the XHTML, with some code to generate dynamic content.

Pros:

  • terse structure (i.e. D.R.Y.)
  • well indented
  • clear structure
  • C# Intellisense (for VS2008 without ReSharper)

Cons:

  • an abstraction from XHTML rather than leveraging familiarity of the markup
  • No Intellisense for VS2010

Example:

@type=IEnumerable<Product>
- if(model.Any())
  %ul
    - foreach (var p in model)
      %li= p.Name
- else
  %p No products available

NVelocityViewEngine (MvcContrib)

Design Goals:

A view engine based upon NVelocity which is a .NET port of the popular Java project Velocity.

Pros:

  • easy to read/write
  • concise view code

Cons:

  • limited number of helper methods available on the view
  • does not automatically have Visual Studio integration (IntelliSense, compile-time checking of views, or refactoring)

Example:

#foreach ($p in $viewdata.Model)
#beforeall
    <ul>
#each
    <li>$p.Name</li>
#afterall
    </ul>
#nodata 
    <p>No products available</p>
#end

SharpTiles

Design Goals:

SharpTiles is a partial port of JSTL combined with concept behind the Tiles framework (as of Mile stone 1).

Pros:

  • familiar to Java developers
  • XML-style code blocks

Cons:

  • ...

Example:

<c:if test="${not fn:empty(Page.Tiles)}">
  <p class="note">
    <fmt:message key="page.tilesSupport"/>
  </p>
</c:if>

Spark View Engine

Design Goals:

The idea is to allow the html to dominate the flow and the code to fit seamlessly.

Pros:

  • Produces more readable templates
  • C# Intellisense (for VS2008 without ReSharper)
  • SparkSense plug-in for VS2010 (works with ReSharper)
  • Provides a powerful Bindings feature to get rid of all code in your views and allows you to easily invent your own HTML tags

Cons:

  • No clear separation of template logic from literal markup (this can be mitigated by namespace prefixes)

Example:

<viewdata products="IEnumerable[[Product]]"/>
<ul if="products.Any()">
    <li each="var p in products">${p.Name}</li>
</ul>
<else>
    <p>No products available</p>
</else>

<Form style="background-color:olive;">
    <Label For="username" />
    <TextBox For="username" />
    <ValidationMessage For="username" Message="Please type a valid username." />
</Form>

StringTemplate View Engine MVC

Design Goals:

  • Lightweight. No page classes are created.
  • Fast. Templates are written to the Response Output stream.
  • Cached. Templates are cached, but utilize a FileSystemWatcher to detect file changes.
  • Dynamic. Templates can be generated on the fly in code.
  • Flexible. Templates can be nested to any level.
  • In line with MVC principles. Promotes separation of UI and Business Logic. All data is created ahead of time, and passed down to the template.

Pros:

  • familiar to StringTemplate Java developers

Cons:

  • simplistic template syntax can interfere with intended output (e.g. jQuery conflict)

Wing Beats

Wing Beats is an internal DSL for creating XHTML. It is based on F# and includes an ASP.NET MVC view engine, but can also be used solely for its capability of creating XHTML.

Pros:

  • Compile-time checking of valid XML
  • Syntax colouring
  • Full intellisense
  • Compiled views
  • Extensibility using regular CLR classes, functions, etc
  • Seamless composability and manipulation since it's regular F# code
  • Unit testable

Cons:

  • You don't really write HTML but code that represents HTML in a DSL.

XsltViewEngine (MvcContrib)

Design Goals:

Builds views from familiar XSLT

Pros:

  • widely ubiquitous
  • familiar template language for XML developers
  • XML-based
  • time-tested
  • Syntax and element nesting errors can be statically detected.

Cons:

  • functional language style makes flow control difficult
  • XSLT 2.0 is (probably?) not supported. (XSLT 1.0 is much less practical).

Copy all files with a certain extension from all subdirectories

From all of the above, I came up with this version. This version also works for me in the mac recovery terminal.

find ./ -name '*.xsl' -exec cp -prv '{}' '/path/to/targetDir/' ';'

It will look in the current directory and recursively in all of the sub directories for files with the xsl extension. It will copy them all to the target directory.

cp flags are:

  • p - preserve attributes of the file
  • r - recursive
  • v - verbose (shows you whats being copied)

Chrome blocks different origin requests

This is a security update. If an attacker can modify some file in the web server (the JS one, for example), he can make every loaded pages to download another script (for example to keylog your password or steal your SessionID and send it to his own server).

To avoid it, the browser check the Same-origin policy

Your problem is that the browser is trying to load something with your script (with an Ajax request) that is on another domain (or subdomain). To avoid it (if it is on your own website) you can:

How to specify the current directory as path in VBA?

I thought I had misunderstood but I was right. In this scenario, it will be ActiveWorkbook.Path

But the main issue was not here. The problem was with these 2 lines of code

strFile = Dir(strPath & "*.csv")

Which should have written as

strFile = Dir(strPath & "\*.csv")

and

With .QueryTables.Add(Connection:="TEXT;" & strPath & strFile, _

Which should have written as

With .QueryTables.Add(Connection:="TEXT;" & strPath & "\" & strFile, _

How to use activity indicator view on iPhone?

Take a look at the open source WordPress application. They have a very re-usable window they have created for displaying an "activity in progress" type display over top of whatever view your application is currently displaying.

http://iphone.trac.wordpress.org/browser/trunk

The files you want are:

  • WPActivityIndicator.xib
  • RoundedRectBlack.png
  • WPActivityIndicator.h
  • WPActivityIndicator.m

Then to show it use something like:

[[WPActivityIndicator sharedActivityIndicator] show];

And hide with:

[[WPActivityIndicator sharedActivityIndicator] hide];

How to get a variable value if variable name is stored as string?

X=foo
Y=X
eval "Z=\$$Y"

sets Z to "foo"

Take care using eval since this may allow accidential excution of code through values in ${Y}. This may cause harm through code injection.

For example

Y="\`touch /tmp/eval-is-evil\`"

would create /tmp/eval-is-evil. This could also be some rm -rf /, of course.

How to highlight a current menu item?

For those using ui-router, my answer is somewhat similar to Ender2050's, but I prefer doing this via state name testing:

$scope.isActive = function (stateName) {
  var active = (stateName === $state.current.name);
  return active;
};

corresponding HTML:

<ul class="nav nav-sidebar">
    <li ng-class="{ active: isActive('app.home') }"><a ui-sref="app.home">Dashboard</a></li>
    <li ng-class="{ active: isActive('app.tiles') }"><a ui-sref="app.tiles">Tiles</a></li>
</ul>

Unable to set variables in bash script

Assignment in bash scripts cannot have spaces around the = and you probably want your date commands enclosed in backticks $():

#!/bin/bash
folder="ABC"
useracct='test'
day=$(date "+%d")
month=$(date "+%B")
year=$(date "+%Y")
folderToBeMoved="/users/$useracct/Documents/Archive/Primetime.eyetv"
newfoldername="/Volumes/Media/Network/$folder/$month$day$year"
ECHO "Network is $network" $network
ECHO "day is $day"
ECHO "Month is $month"
ECHO "YEAR is $year"
ECHO "source is $folderToBeMoved"
ECHO "dest is $newfoldername"
mkdir $newfoldername
cp -R $folderToBeMoved $newfoldername
if [-f $newfoldername/Primetime.eyetv]; then rm $folderToBeMoved; fi

With the last three lines commented out, for me this outputs:

Network is 
day is 16
Month is March
YEAR is 2010
source is /users/test/Documents/Archive/Primetime.eyetv
dest is /Volumes/Media/Network/ABC/March162010

Converting a Uniform Distribution to a Normal Distribution

Where R1, R2 are random uniform numbers:

NORMAL DISTRIBUTION, with SD of 1:

sqrt(-2*log(R1))*cos(2*pi*R2)

This is exact... no need to do all those slow loops!

Reference: dspguide.com/ch2/6.htm

Remote desktop connection protocol error 0x112f

Might not be a solution for all but I found that if I reduced the screen resolution of the RDP session, I was able to get in. The server was at 95% capacity I went from 3 high res monitors to 1 800x600 window.

Hidden Features of Xcode

Switch to Header/Source File

  • Option ? Command ? Up Arrow ?

  • View > Switch to Header/Source File

Switches between the .m and .h files.

  • In Xcode 4 this is ctrl Command ? Up Arrow ?

Npm install cannot find module 'semver'

I got same error and I solved it.

delete package-lock.json file and node_modules folder then npm install

Git merge is not possible because I have unmerged files

The error message:

merge: remote/master - not something we can merge

is saying that Git doesn't recognize remote/master. This is probably because you don't have a "remote" named "remote". You have a "remote" named "origin".

Think of "remotes" as an alias for the url to your Git server. master is your locally checked-out version of the branch. origin/master is the latest version of master from your Git server that you have fetched (downloaded). A fetch is always safe because it will only update the "origin/x" version of your branches.

So, to get your master branch back in sync, first download the latest content from the git server:

git fetch

Then, perform the merge:

git merge origin/master

...But, perhaps the better approach would be:

git pull origin master

The pull command will do the fetch and merge for you in one step.

Use jQuery to change value of a label

val() is more like a shortcut for attr('value'). For your usage use text() or html() instead

Search for executable files using find command

This worked for me & thought of sharing...

find ./ -type f -name "*" -not -name "*.o" -exec sh -c '
    case "$(head -n 1 "$1")" in
      ?ELF*) exit 0;;
      MZ*) exit 0;;
      #!*/ocamlrun*)exit0;;
    esac
exit 1
' sh {} \; -print

Create a view with ORDER BY clause

I've had success forcing the view to be ordered using

SELECT TOP 9999999 ... ORDER BY something

Unfortunately using SELECT TOP 100 PERCENT does not work due the issue here.

How can Print Preview be called from Javascript?

It can be done using javascript. Say your html/aspx code goes this way:

<span>Main heading</span>
<asp:Label ID="lbl1" runat="server" Text="Contents"></asp:Label>
<asp:Label Text="Contractor Name" ID="lblCont" runat="server"></asp:Label>
<div id="forPrintPreview">
  <asp:Label Text="Company Name" runat="server"></asp:Label>
  <asp:GridView runat="server">

      //GridView Content goes here

  </asp:GridView
</div>

<input type="button" onclick="PrintPreview();" value="Print Preview" />

Here on click of "Print Preview" button we will open a window with data for print. Observe that 'forPrintPreview' is the id of a div. The function for Print preview goes this way:

function PrintPreview() {
 var Contractor= $('span[id*="lblCont"]').html();
 printWindow = window.open("", "", "location=1,status=1,scrollbars=1,width=650,height=600");
 printWindow.document.write('<html><head>');
 printWindow.document.write('<style type="text/css">@media print{.no-print, .no-print *{display: none !important;}</style>');
 printWindow.document.write('</head><body>');
 printWindow.document.write('<div style="width:100%;text-align:right">');

  //Print and cancel button
 printWindow.document.write('<input type="button" id="btnPrint" value="Print" class="no-print" style="width:100px" onclick="window.print()" />');
 printWindow.document.write('<input type="button" id="btnCancel" value="Cancel" class="no-print"  style="width:100px" onclick="window.close()" />');

 printWindow.document.write('</div>');

 //You can include any data this way.
 printWindow.document.write('<table><tr><td>Contractor name:'+ Contractor +'</td></tr>you can include any info here</table');

 printWindow.document.write(document.getElementById('forPrintPreview').innerHTML);
 //here 'forPrintPreview' is the id of the 'div' in current page(aspx).
 printWindow.document.write('</body></html>');
 printWindow.document.close();
 printWindow.focus();
}

Observe that buttons 'print' and 'cancel' has the css class 'no-print', So these buttons will not appear in the print.

In Node.js, how do I "include" functions from my other files?

Like you are having a file abc.txt and many more?

Create 2 files: fileread.js and fetchingfile.js, then in fileread.js write this code:

function fileread(filename) {
    var contents= fs.readFileSync(filename);
        return contents;
    }

    var fs = require("fs");  // file system

    //var data = fileread("abc.txt");
    module.exports.fileread = fileread;
    //data.say();
    //console.log(data.toString());
}

In fetchingfile.js write this code:

function myerror(){
    console.log("Hey need some help");
    console.log("type file=abc.txt");
}

var ags = require("minimist")(process.argv.slice(2), { string: "file" });
if(ags.help || !ags.file) {
    myerror();
    process.exit(1);
}
var hello = require("./fileread.js");
var data = hello.fileread(ags.file);  // importing module here 
console.log(data.toString());

Now, in a terminal: $ node fetchingfile.js --file=abc.txt

You are passing the file name as an argument, moreover include all files in readfile.js instead of passing it.

Thanks

jQuery: Count number of list elements?

Try:

$("#mylist li").length

Just curious: why do you need to know the size? Can't you just use:

$("#mylist").append("<li>New list item</li>");

?

How can I export a GridView.DataSource to a datatable or dataset?

You should convert first DataSource in BindingSource, look example

BindingSource bs = (BindingSource)dgrid.DataSource; // Se convierte el DataSource 
DataTable tCxC = (DataTable) bs.DataSource;

With the data of tCxC you can do anything.

Gunicorn worker timeout error

On Google Cloud Just add --timeout 90 to entrypoint in app.yaml

entrypoint: gunicorn -b :$PORT main:app --timeout 90

textarea character limit

This is entirely untested but it should do what you need.

Update : here's a jsfiddle to look at. Seems to be working. link

You would past it into a js file and reference it after your jquery reference. You would then call it like this..

$("textarea").characterCounter(200);

A brief explanation of what is going on..

On every keyup event the function is checking what type of key is pressed. If it is acceptable the the counter will check the count, trim any excess and prevent any further input once the limit is reached.

The plugin should handle pasting into the target too.

  ; (function ($) {
        $.fn.characterCounter = function (limit) {
            return this.filter("textarea, input:text").each(function () {
                var $this = $(this),
                  checkCharacters = function (event) {

                      if ($this.val().length > limit) {

                          // Trim the string as paste would allow you to make it 
                          // more than the limit.
                          $this.val($this.val().substring(0, limit))
                          // Cancel the original event
                          event.preventDefault();
                          event.stopPropagation();

                      }
                  };

                $this.keyup(function (event) {

                    // Keys "enumeration"
                    var keys = {
                        BACKSPACE: 8,
                        TAB: 9,
                        LEFT: 37,
                        UP: 38,
                        RIGHT: 39,
                        DOWN: 40
                    };

                    // which normalizes keycode and charcode.
                    switch (event.which) {

                        case keys.UP:
                        case keys.DOWN:
                        case keys.LEFT:
                        case keys.RIGHT:
                        case keys.TAB:
                            break;
                        default:
                            checkCharacters(event);
                            break;
                    }   

                });

                // Handle cut/paste.
                $this.bind("paste cut", function (event) {
                    // Delay so that paste value is captured.
                    setTimeout(function () { checkCharacters(event); event = null; }, 150);
                });
            });
        };
    } (jQuery));

UICollectionView spacing margins

Setting up insets in Interface Builder like shown in the screenshot below

Setting section insets for UICollectionView

Will result in something like this:

A collection view cell with section insets

Correct way to pass multiple values for same parameter name in GET request

Solutions above didn't work. It simply displayed the last key/value pairs, but this did:

http://localhost/?key[]=1&key[]=2

Returns:

Array
(
[key] => Array
    (
        [0] => 1
        [1] => 2
    )

Regex - how to match everything except a particular pattern

pattern - re

str.split(/re/g) 

will return everything except the pattern.

Test here

CSS /JS to prevent dragging of ghost image?

I found that for IE, you must add the draggable="false" attribute to images and anchors to prevent dragging. the CSS options work for all other browsers. I did this in jQuery:

$("a").attr('draggable', false); 
$("img").attr('draggable', false);

Difference between ${} and $() in Bash

  1. $() means: "first evaluate this, and then evaluate the rest of the line".

    Ex :

    echo $(pwd)/myFile.txt
    

    will be interpreted as

    echo /my/path/myFile.txt
    

    On the other hand ${} expands a variable.

    Ex:

    MY_VAR=toto
    echo ${MY_VAR}/myFile.txt
    

    will be interpreted as

    echo toto/myFile.txt
    
  2. Why can't I use it as bash$ while ((i=0;i<10;i++)); do echo $i; done

    I'm afraid the answer is just that the bash syntax for while just isn't the same as the syntax for for.

How do C++ class members get initialized if I don't do it explicitly?

Uninitialized non-static members will contain random data. Actually, they will just have the value of the memory location they are assigned to.

Of course for object parameters (like string) the object's constructor could do a default initialization.

In your example:

int *ptr; // will point to a random memory location
string name; // empty string (due to string's default costructor)
string *pname; // will point to a random memory location
string &rname; // it would't compile
const string &crname; // it would't compile
int age; // random value

Should a RESTful 'PUT' operation return something

I think it is possible for the server to return content in response to a PUT. If you are using a response envelop format that allows for sideloaded data (such as the format consumed by ember-data), then you can also include other objects that may have been modified via database triggers, etc. (Sideloaded data is explicitly to reduce # of requests, and this seems like a fine place to optimize.)

If I just accept the PUT and have nothing to report back, I use status code 204 with no body. If I have something to report, I use status code 200, and include a body.

How to pass model attributes from one Spring MVC controller to another controller?

Maybe you could do it like this:

Don't use the model in first controller. Store data in some other shared object which could be then retrieved by second controller.

Look at this and this post. It's about the similar issue.

P.S.

You could probabbly use session scoped bean for that shared data...

How to Detect cause of 503 Service Temporarily Unavailable error and handle it?

There is of course some apache log files. Search in your apache configuration files for 'Log' keyword, you'll certainly find plenty of them. Depending on your OS and installation places may vary (in a Typical Linux server it would be /var/log/apache2/[access|error].log).

Having a 503 error in Apache usually means the proxied page/service is not available. I assume you're using tomcat and that means tomcat is either not responding to apache (timeout?) or not even available (down? crashed?). So chances are that it's a configuration error in the way to connect apache and tomcat or an application inside tomcat that is not even sending a response for apache.

Sometimes, in production servers, it can as well be that you get too much traffic for the tomcat server, apache handle more request than the proxyied service (tomcat) can accept so the backend became unavailable.

Moq, SetupGet, Mocking a property

But while mocking read-only properties means properties with getter method only you should declare it as virtual otherwise System.NotSupportedException will be thrown because it is only supported in VB as moq internally override and create proxy when we mock anything.

What is this CSS selector? [class*="span"]

.show-grid [class*="span"]

It's a CSS selector that selects all elements with the class show-grid that has a child element whose class contains the name span.

How to order by with union in SQL?

Just write

Select id,name,age
From Student
Where age < 15
Union
Select id,name,age
From Student
Where Name like "%a%"
Order by name

the order by is applied to the complete resultset

Git error when trying to push -- pre-receive hook declined

Bitbucket: Check for Branch permissions in Settings (it may be on 'Deny all'). If that doesn't work, simply clone your branch to a new local branch, push the changes to the remote (a new remote branch will be created), and create a PR.

How to display special characters in PHP

Try This

Input:

<!DOCTYPE html>
<html>
<body>

<?php
$str = "This is some <b>bold</b> text.";
echo htmlspecialchars($str);
?>

<p>Converting &lt; and &gt; into entities are often used to prevent browsers from using it as an HTML element. <br />This can be especially useful to prevent code from running when users have access to display input on your homepage.</p>

</body>
</html>

Output:

This is some <b>bold</b> text.

Converting < and > into entities are often used to prevent browsers from using it as an HTML element. This can be especially useful to prevent code from running when users have access to display input on your homepage.

How to create two columns on a web page?

i recommend to look this article

http://www.456bereastreet.com/lab/developing_with_web_standards/csslayout/2-col/

see 4. Place the columns side by side special

To make the two columns (#main and #sidebar) display side by side we float them, one to the left and the other to the right. We also specify the widths of the columns.

    #main {
    float:left;
    width:500px;
    background:#9c9;
    }
    #sidebar {
    float:right;
    width:250px;
   background:#c9c;
   }

Note that the sum of the widths should be equal to the width given to #wrap in Step 3.

Convert Pandas column containing NaNs to dtype `int`

If you want to use it when you chain methods, you can use assign:

df = (
     df.assign(col = lambda x: x['col'].astype('Int64'))
)

how to include glyphicons in bootstrap 3

I think your particular problem isn't how to use Glyphicons but understanding how Bootstrap files work together.

Bootstrap requires a specific file structure to work. I see from your code you have this:

<link href="bootstrap.css" rel="stylesheet" media="screen">

Your Bootstrap.css is being loaded from the same location as your page, this would create a problem if you didn't adjust your file structure.

But first, let me recommend you setup your folder structure like so:

/css      <-- Bootstrap.css here
/fonts    <-- Bootstrap fonts here
/img
/js       <-- Bootstrap JavaScript here
index.html

If you notice, this is also how Bootstrap structures its files in its download ZIP.

You then include your Bootstrap file like so:

<link href="css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="./css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="/css/bootstrap.css" rel="stylesheet" media="screen">

Depending on your server structure or what you're going for.

The first and second are relative to your file's current directory. The second one is just more explicit by saying "here" (./) first then css folder (/css).

The third is good if you're running a web server, and you can just use relative to root notation as the leading "/" will be always start at the root folder.

So, why do this?

Bootstrap.css has this specific line for Glyphfonts:

@font-face {
    font-family: 'Glyphicons Halflings';
    src: url('../fonts/glyphicons-halflings-regular.eot');
    src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');
}

What you can see is that that Glyphfonts are loaded by going up one directory ../ and then looking for a folder called /fonts and THEN loading the font file.

The URL address is relative to the location of the CSS file. So, if your CSS file is at the same location like this:

/fonts
Bootstrap.css
index.html

The CSS file is going one level deeper than looking for a /fonts folder.

So, let's say the actual location of these files are:

C:\www\fonts
C:\www\Boostrap.css
C:\www\index.html

The CSS file would technically be looking for a folder at:

C:\fonts

but your folder is actually in:

C:\www\fonts

So see if that helps. You don't have to do anything 'special' to load Bootstrap Glyphicons, except make sure your folder structure is set up appropriately.

When you get that fixed, your HTML should simply be:

<span class="glyphicon glyphicon-comment"></span>

Note, you need both classes. The first class glyphicon sets up the basic styles while glyphicon-comment sets the specific image.

Questions every good PHP Developer should be able to answer

Admittedly, I stole this question from somewhere else (can't remember where I read it any more) but thought it was funny:

Q: What is T_PAAMAYIM_NEKUDOTAYIM?
A: Its the scope resolution operator (double colon)

An experienced PHP'er immediately knows what it means. Less experienced (and not Hebrew) developers may want to read this.

But more serious questions now:


Q: What is the cause of this warning: 'Warning: Cannot modify header information - headers already sent', and what is a good practice to prevent it?
A: Cause: body data was sent, causing headers to be sent too.
Prevention: Be sure to execute header specific code first before you output any body data. Be sure you haven't accidentally sent out whitespace or any other characters.


Q: What is wrong with this query: "SELECT * FROM table WHERE id = $_POST[ 'id' ]"?
A: 1. It is vulnarable to SQL injection. Never use user input directly in queries. Sanitize it first. Preferebly use prepared statements (PDO) 2. Don't select all columns (*), but specify every single column. This is predominantly ment to prevent queries hogging up memory when for instance a BLOB column is added at some point in the future.


Q: What is wrong with this if statement: if( !strpos( $haystack, $needle ) ...?
A: strpos returns the index position of where it first found the $needle, which could be 0. Since 0 also resolves to false the solution is to use strict comparison: if( false !== strpos( $haystack, $needle )...


Q: What is the preferred way to write this if statement, and why?
if( 5 == $someVar ) or if( $someVar == 5 )
A: The former, as it prevents accidental assignment of 5 to $someVar when you forget to use 2 equalsigns ($someVar = 5), and will cause an error, the latter won't.


Q: Given this code:

function doSomething( &$arg )
{
    $return = $arg;
    $arg += 1;
    return $return;
}

$a = 3;
$b = doSomething( $a );

...what is the value of $a and $b after the function call and why?
A: $a is 4 and $b is 3. The former because $arg is passed by reference, the latter because the return value of the function is a copy of (not a reference to) the initial value of the argument.


OOP specific

Q: What is the difference between public, protected and private in a class definition?
A: public makes a class member available to "everyone", protected makes the class member available to only itself and derived classes, private makes the class member only available to the class itself.


Q: What is wrong with this code:

class SomeClass
{
    protected $_someMember;

    public function __construct()
    {
        $this->_someMember = 1;
    }

    public static function getSomethingStatic()
    {
        return $this->_someMember * 5; // here's the catch
    }
}

A: Static methods don't have access to $this, because static methods can be executed without instantiating a class.


Q: What is the difference between an interface and an abstract class?
A: An interface defines a contract between an implementing class is and an object that calls the interface. An abstract class pre-defines certain behaviour for classes that will extend it. To a certain degree this can also be considered a contract, since it garantuees certain methods to exist.


Q: What is wrong with classes that predominantly define getters and setters, that map straight to it's internal members, without actually having methods that execute behaviour?
A: This might be a code smell since the object acts as an ennobled array, without much other use.


Q: Why is PHP's implementation of the use of interfaces sub-optimal?
A: PHP doesn't allow you to define the expected return type of the method's, which essentially renders interfaces pretty useless. :-P

how to put image in a bundle and pass it to another activity

So you can do it like this, but the limitation with the Parcelables is that the payload between activities has to be less than 1MB total. It's usually better to save the Bitmap to a file and pass the URI to the image to the next activity.

 protected void onCreate(Bundle savedInstanceState) {     setContentView(R.layout.my_layout);     Bitmap bitmap = getIntent().getParcelableExtra("image");     ImageView imageView = (ImageView) findViewById(R.id.imageview);     imageView.setImageBitmap(bitmap);  } 

How do I call ::CreateProcess in c++ to launch a Windows executable?

Something like this:

STARTUPINFO info={sizeof(info)};
PROCESS_INFORMATION processInfo;
if (CreateProcess(path, cmd, NULL, NULL, TRUE, 0, NULL, NULL, &info, &processInfo))
{
    WaitForSingleObject(processInfo.hProcess, INFINITE);
    CloseHandle(processInfo.hProcess);
    CloseHandle(processInfo.hThread);
}

Writing to CSV with Python adds blank lines

The way you use the csv module changed in Python 3 in several respects (docs), at least with respect to how you need to open the file. Anyway, something like

import csv
with open('test.csv', 'w', newline='') as fp:
    a = csv.writer(fp, delimiter=',')
    data = [['Me', 'You'],
            ['293', '219'],
            ['54', '13']]
    a.writerows(data)

should work.

How do I show running processes in Oracle DB?

After looking at sp_who, Oracle does not have that ability per se. Oracle has at least 8 processes running which run the db. Like RMON etc.

You can ask the DB which queries are running as that just a table query. Look at the V$ tables.

Quick Example:

SELECT sid,
       opname,
       sofar,
       totalwork,
       units,
       elapsed_seconds,
       time_remaining
FROM v$session_longops
WHERE sofar != totalwork;

No signing certificate "iOS Distribution" found

Double click and install the production certificate in your key chain. This might resolve the issue.

Is it possible to make Font Awesome icons larger than 'fa-5x'?

Alternatively you can edit the source and create your own incrementations

FontAwesome 5

https://github.com/FortAwesome/Font-Awesome/blob/master/web-fonts-with-css/less/_larger.less

// Icon Sizes
// -------------------------

.larger(@factor) when (@factor > 0) {
  .larger((@factor - 1));

  .@{fa-css-prefix}-@{factor}x {
    font-size: (@factor * 1em);
  }
}

/* makes the font 33% larger relative to the icon container */
.@{fa-css-prefix}-lg {
  font-size: (4em / 3);
  line-height: (3em / 4);
  vertical-align: -.0667em;
}

.@{fa-css-prefix}-xs {
  font-size: .75em;
}

.@{fa-css-prefix}-sm {
  font-size: .875em;
}

// Change the number below to create your own incrementations
// This currently creates classes .fa-1x - .fa-10x
.larger(10);

FontAwesome 4

https://github.com/FortAwesome/Font-Awesome/blob/v4.7.0/less/larger.less

// Icon Sizes
// -------------------------

/* makes the font 33% larger relative to the icon container */
.@{fa-css-prefix}-lg {
    font-size: (4em / 3);
    line-height: (3em / 4);
    vertical-align: -15%;
}

.@{fa-css-prefix}-2x { font-size: 2em; }
.@{fa-css-prefix}-3x { font-size: 3em; }
.@{fa-css-prefix}-4x { font-size: 4em; }
.@{fa-css-prefix}-5x { font-size: 5em; }

// Your custom sizes
.@{fa-css-prefix}-6x { font-size: 6em; }
.@{fa-css-prefix}-7x { font-size: 7em; }
.@{fa-css-prefix}-8x { font-size: 8em; }

Eclipse 3.5 Unable to install plugins

I had a similar problem setting up eclipse in the office. I had set up the for HTTP, HTTPS and SOCKS in:

Window>pref>general>network connections

Clearing the proxy settings for SOCKS fixed the problem for me.

Add string in a certain position in Python

I think the above answers are fine, but I would explain that there are some unexpected-but-good side effects to them...

def insert(string_s, insert_s, pos_i=0):
    return string_s[:pos_i] + insert_s + string_s[pos_i:]

If the index pos_i is very small (too negative), the insert string gets prepended. If too long, the insert string gets appended. If pos_i is between -len(string_s) and +len(string_s) - 1, the insert string gets inserted into the correct place.

Fatal error: Maximum execution time of 30 seconds exceeded

Your loop might be endless. If it is not, you could extend the maximum execution time like this:

ini_set('max_execution_time', '300'); //300 seconds = 5 minutes

and

set_time_limit(300);

can be used to temporarily extend the time limit.

How do I generate a SALT in Java for Salted-Hash?

Another version using SHA-3, I am using bouncycastle:

The interface:

public interface IPasswords {

    /**
     * Generates a random salt.
     *
     * @return a byte array with a 64 byte length salt.
     */
    byte[] getSalt64();

    /**
     * Generates a random salt
     *
     * @return a byte array with a 32 byte length salt.
     */
    byte[] getSalt32();

    /**
     * Generates a new salt, minimum must be 32 bytes long, 64 bytes even better.
     *
     * @param size the size of the salt
     * @return a random salt.
     */
    byte[] getSalt(final int size);

    /**
     * Generates a new hashed password
     *
     * @param password to be hashed
     * @param salt the randomly generated salt
     * @return a hashed password
     */
    byte[] hash(final String password, final byte[] salt);

    /**
     * Expected password
     *
     * @param password to be verified
     * @param salt the generated salt (coming from database)
     * @param hash the generated hash (coming from database)
     * @return true if password matches, false otherwise
     */
    boolean isExpectedPassword(final String password, final byte[] salt, final byte[] hash);

    /**
     * Generates a random password
     *
     * @param length desired password length
     * @return a random password
     */
    String generateRandomPassword(final int length);
}

The implementation:

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.Validate;
import org.apache.log4j.Logger;
import org.bouncycastle.jcajce.provider.digest.SHA3;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

public final class Passwords implements IPasswords, Serializable {

    /*serialVersionUID*/
    private static final long serialVersionUID = 8036397974428641579L;
    private static final Logger LOGGER = Logger.getLogger(Passwords.class);
    private static final Random RANDOM = new SecureRandom();
    private static final int DEFAULT_SIZE = 64;
    private static final char[] symbols;

    static {
            final StringBuilder tmp = new StringBuilder();
            for (char ch = '0'; ch <= '9'; ++ch) {
                    tmp.append(ch);
            }
            for (char ch = 'a'; ch <= 'z'; ++ch) {
                    tmp.append(ch);
            }
            symbols = tmp.toString().toCharArray();
    }

    @Override public byte[] getSalt64() {
            return getSalt(DEFAULT_SIZE);
    }

    @Override public byte[] getSalt32() {
            return getSalt(32);
    }

    @Override public byte[] getSalt(int size) {
            final byte[] salt;
            if (size < 32) {
                    final String message = String.format("Size < 32, using default of: %d", DEFAULT_SIZE);
                    LOGGER.warn(message);
                    salt = new byte[DEFAULT_SIZE];
            } else {
                    salt = new byte[size];
            }
            RANDOM.nextBytes(salt);
            return salt;
    }

    @Override public byte[] hash(String password, byte[] salt) {

            Validate.notNull(password, "Password must not be null");
            Validate.notNull(salt, "Salt must not be null");

            try {
                    final byte[] passwordBytes = password.getBytes("UTF-8");
                    final byte[] all = ArrayUtils.addAll(passwordBytes, salt);
                    SHA3.DigestSHA3 md = new SHA3.Digest512();
                    md.update(all);
                    return md.digest();
            } catch (UnsupportedEncodingException e) {
                    final String message = String
                            .format("Caught UnsupportedEncodingException e: <%s>", e.getMessage());
                    LOGGER.error(message);
            }
            return new byte[0];
    }

    @Override public boolean isExpectedPassword(final String password, final byte[] salt, final byte[] hash) {

            Validate.notNull(password, "Password must not be null");
            Validate.notNull(salt, "Salt must not be null");
            Validate.notNull(hash, "Hash must not be null");

            try {
                    final byte[] passwordBytes = password.getBytes("UTF-8");
                    final byte[] all = ArrayUtils.addAll(passwordBytes, salt);

                    SHA3.DigestSHA3 md = new SHA3.Digest512();
                    md.update(all);
                    final byte[] digest = md.digest();
                    return Arrays.equals(digest, hash);
            }catch(UnsupportedEncodingException e){
                    final String message =
                            String.format("Caught UnsupportedEncodingException e: <%s>", e.getMessage());
                    LOGGER.error(message);
            }
            return false;


    }

    @Override public String generateRandomPassword(final int length) {

            if (length < 1) {
                    throw new IllegalArgumentException("length must be greater than 0");
            }

            final char[] buf = new char[length];
            for (int idx = 0; idx < buf.length; ++idx) {
                    buf[idx] = symbols[RANDOM.nextInt(symbols.length)];
            }
            return shuffle(new String(buf));
    }


    private String shuffle(final String input){
            final List<Character> characters = new ArrayList<Character>();
            for(char c:input.toCharArray()){
                    characters.add(c);
            }
            final StringBuilder output = new StringBuilder(input.length());
            while(characters.size()!=0){
                    int randPicker = (int)(Math.random()*characters.size());
                    output.append(characters.remove(randPicker));
            }
            return output.toString();
    }
}

The test cases:

public class PasswordsTest {

    private static final Logger LOGGER = Logger.getLogger(PasswordsTest.class);

    @Before
    public void setup(){
            BasicConfigurator.configure();
    }

    @Test
    public void testGeSalt() throws Exception {

            IPasswords passwords = new Passwords();
            final byte[] bytes = passwords.getSalt(0);
            int arrayLength = bytes.length;

            assertThat("Expected length is", arrayLength, is(64));
    }

    @Test
    public void testGeSalt32() throws Exception {
            IPasswords passwords = new Passwords();
            final byte[] bytes = passwords.getSalt32();
            int arrayLength = bytes.length;
            assertThat("Expected length is", arrayLength, is(32));
    }

    @Test
    public void testGeSalt64() throws Exception {
            IPasswords passwords = new Passwords();
            final byte[] bytes = passwords.getSalt64();
            int arrayLength = bytes.length;
            assertThat("Expected length is", arrayLength, is(64));
    }

    @Test
    public void testHash() throws Exception {
            IPasswords passwords = new Passwords();
            final byte[] hash = passwords.hash("holacomoestas", passwords.getSalt64());
            assertThat("Array is not null", hash, Matchers.notNullValue());
    }


    @Test
    public void testSHA3() throws UnsupportedEncodingException {
            SHA3.DigestSHA3 md = new SHA3.Digest256();
            md.update("holasa".getBytes("UTF-8"));
            final byte[] digest = md.digest();
             assertThat("expected digest is:",digest,Matchers.notNullValue());
    }

    @Test
    public void testIsExpectedPasswordIncorrect() throws Exception {

            String password = "givemebeer";
            IPasswords passwords = new Passwords();

            final byte[] salt64 = passwords.getSalt64();
            final byte[] hash = passwords.hash(password, salt64);
            //The salt and the hash go to database.

            final boolean isPasswordCorrect = passwords.isExpectedPassword("jfjdsjfsd", salt64, hash);

            assertThat("Password is not correct", isPasswordCorrect, is(false));

    }

    @Test
    public void testIsExpectedPasswordCorrect() throws Exception {
            String password = "givemebeer";
            IPasswords passwords = new Passwords();
            final byte[] salt64 = passwords.getSalt64();
            final byte[] hash = passwords.hash(password, salt64);
            //The salt and the hash go to database.
            final boolean isPasswordCorrect = passwords.isExpectedPassword("givemebeer", salt64, hash);
            assertThat("Password is correct", isPasswordCorrect, is(true));
    }

    @Test
    public void testGenerateRandomPassword() throws Exception {
            IPasswords passwords = new Passwords();
            final String randomPassword = passwords.generateRandomPassword(10);
            LOGGER.info(randomPassword);
            assertThat("Random password is not null", randomPassword, Matchers.notNullValue());
    }
}

pom.xml (only dependencies):

<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.testng</groupId>
        <artifactId>testng</artifactId>
        <version>6.1.1</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.hamcrest</groupId>
        <artifactId>hamcrest-all</artifactId>
        <version>1.3</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>

    <dependency>
        <groupId>org.bouncycastle</groupId>
        <artifactId>bcprov-jdk15on</artifactId>
        <version>1.51</version>
        <type>jar</type>
    </dependency>


    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
        <version>3.3.2</version>
    </dependency>


</dependencies>

javascript - Create Simple Dynamic Array

This answer is about "how to dynamically create an array without loop".

Literal operator [] doesn't allow us to create dynamically, so let's look into Array, it's constructor and it's methods.

In ES2015 Array has method .from(), which easily allows us to create dynamic Array:

Array.from({length: 10}) // -> [undefined, undefined, undefined, ... ]

When Array's constructor receives number as first parameter, it creates an Array with size of that number, but it is not iterable, so we cannot use .map(), .filter() etc. :

new Array(10) // -> [empty × 10]

But if we'll pass more than one parameter we will receive array from all parameters:

new Array(1,2,3) // -> [1,2,3]

If we would use ES2015 we can use spread operator which will spread empty Array inside another Array, so we will get iterable Array :

[...new Array(10)]  // -> [undefined, undefined, undefined, ...]

But if we don't use ES2015 and don't have polyfills, there is also a way to create dynamic Array without loop in ES5. If we'll think about .apply() method: it spreads second argument array to params. So calling apply on Array's constructor will do the thing:

Array.apply(null, new Array(10))  // -> [undefined, undefined, undefined, ...]

After we have dynamic iterable Array, we can use map to assign dynamic values:

Array.apply(null, new Array(10)).map(function(el, i) {return ++i + ""})

// ["1","2","3", ...]

$.ajax - dataType

(ps: the answer given by Nick Craver is incorrect)

contentType specifies the format of data being sent to the server as part of request(it can be sent as part of response too, more on that later).

dataType specifies the expected format of data to be received by the client(browser).

Both are not interchangable.

  • contentType is the header sent to the server, specifying the format of data(i.e the content of message body) being being to the server. This is used with POST and PUT requests. Usually when u send POST request, the message body comprises of passed in parameters like:

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

Sample request:

POST /search HTTP/1.1 
Content-Type: application/x-www-form-urlencoded 
<<other header>>

name=sam&age=35

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

The last line above "name=sam&age=35" is the message body and contentType specifies it as application/x-www-form-urlencoded since we are passing the form parameters in the message body. However we aren't limited to just sending the parameters, we can send json, xml,... like this(sending different types of data is especially useful with RESTful web services):

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

Sample request:

POST /orders HTTP/1.1
Content-Type: application/xml
<<other header>>

<order>
   <total>$199.02</total>
   <date>December 22, 2008 06:56</date>
...
</order>

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

So the ContentType this time is: application/xml, cause that's what we are sending. The above examples showed sample request, similarly the response send from the server can also have the Content-Type header specifying what the server is sending like this:

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

sample response:

HTTP/1.1 201 Created
Content-Type: application/xml
<<other headers>>

<order id="233">
   <link rel="self" href="http://example.com/orders/133"/>
   <total>$199.02</total>
   <date>December 22, 2008 06:56</date>
...
</order>

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

  • dataType specifies the format of response to expect. Its related to Accept header. JQuery will try to infer it based on the Content-Type of the response.

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

Sample request:

GET /someFolder/index.html HTTP/1.1
Host: mysite.org
Accept: application/xml
<<other headers>>

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

Above request is expecting XML from the server.

Regarding your question,

contentType: "application/json; charset=utf-8",
dataType: "json",

Here you are sending json data using UTF8 character set, and you expect back json data from the server. As per the JQuery docs for dataType,

The json type parses the fetched data file as a JavaScript object and returns the constructed object as the result data.

So what you get in success handler is proper javascript object(JQuery converts the json object for you)

whereas

contentType: "application/json",
dataType: "text",

Here you are sending json data, since you haven't mentioned the encoding, as per the JQuery docs,

If no charset is specified, data will be transmitted to the server using the server's default charset; you must decode this appropriately on the server side.

and since dataType is specified as text, what you get in success handler is plain text, as per the docs for dataType,

The text and xml types return the data with no processing. The data is simply passed on to the success handler

Using MySQL with Entity Framework

If you interested in running Entity Framework with MySql on mono/linux/macos, this might be helpful https://iyalovoi.wordpress.com/2015/04/06/entity-framework-with-mysql-on-mac-os/

How do I find out what keystore my JVM is using?

For me using the official OpenJDK 12 Docker image, the location of the Java keystore was:

/usr/java/openjdk-12/lib/security/cacerts

Convert byte to string in Java

If it's a single byte, just cast the byte to a char and it should work out to be fine i.e. give a char entity corresponding to the codepoint value of the given byte. If not, use the String constructor as mentioned elsewhere.

char ch = (char)0x63;
System.out.println(ch);

Google Maps API 3 - Custom marker color for default (dot) marker

Well the closest thing I've been able to get with the StyledMarker is this.

The bullet in the middle isn't quite a big as the default one though. The StyledMarker class simply builds this url and asks the google api to create the marker.

From the class use example use "%E2%80%A2" as your text, as in:

var styleMaker2 = new StyledMarker({styleIcon:new StyledIcon(StyledIconTypes.MARKER,{text:"%E2%80%A2"},styleIconClass),position:new google.maps.LatLng(37.263477473067, -121.880502070713),map:map});

You will need to modifiy StyledMarker.js to comment out the lines:

  if (text_) {
    text_ = text_.substr(0,2);
  }

as this will trim the text string to 2 characters.

Alternatively you could create custom marker images based on the default one with the colors you desire and override the default marker with code such as this:

marker = new google.maps.Marker({
  map:map,
  position: latlng,
  icon: new google.maps.MarkerImage(
    'http://www.gettyicons.com/free-icons/108/gis-gps/png/24/needle_left_yellow_2_24.png',
    new google.maps.Size(24, 24),
    new google.maps.Point(0, 0),
    new google.maps.Point(0, 24)
  )
});

Missing Microsoft RDLC Report Designer in Visual Studio

If you did a custom installation you need to add Microsoft Sql Server Data Tools. After that you can add Reportviwer to your webform.

scrollIntoView Scrolls just too far

Assuming you want to scroll to the divs that are all at the same level in DOM and have class name "scroll-with-offset", then this CSS will solve the issue:

.scroll-with-offset {    
  padding-top: 100px;
  margin-bottom: -100px;
}

The offset from the top of the page is 100px. It will only work as intended with block: 'start':

element.scrollIntoView({ behavior: 'smooth', block: 'start' });

What's happening is that the divs' top point is at the normal location but their inner contents start 100px below the normal location. That's what padding-top:100px is for. margin-bottom: -100px is to offset the below div's extra margin. To make the solution complete also add this CSS to offset the margins/paddings for the top-most and bottom-most divs:

.top-div {
  padding-top: 0;
}
.bottom-div {
  margin-bottom: 0;
}

ERROR 2003 (HY000): Can't connect to MySQL server (111)

errno 111 is ECONNREFUSED, I suppose something is wrong with the router's DNAT.

It is also possible that your ISP is filtering that port.

How do I limit the number of results returned from grep?

Another option is just using head:

grep ...parameters... yourfile | head

This won't require searching the entire file - it will stop when the first ten matching lines are found. Another advantage with this approach is that will return no more than 10 lines even if you are using grep with the -o option.

For example if the file contains the following lines:

112233
223344
123123

Then this is the difference in the output:

$ grep -o '1.' yourfile | head -n2
11
12

$ grep -m2 -o '1.'
11
12
12

Using head returns only 2 results as desired, whereas -m2 returns 3.

How to get ID of button user just clicked?

$("button").click(function() {
    alert(this.id);
});

Drop primary key using script in SQL Server database

The answer I got is that variables and subqueries will not work and we have to user dynamic SQL script. The following works:

DECLARE @SQL VARCHAR(4000)
SET @SQL = 'ALTER TABLE dbo.Student DROP CONSTRAINT |ConstraintName| '

SET @SQL = REPLACE(@SQL, '|ConstraintName|', ( SELECT   name
                                               FROM     sysobjects
                                               WHERE    xtype = 'PK'
                                                        AND parent_obj =        OBJECT_ID('Student')))

EXEC (@SQL)

How do I partially update an object in MongoDB so the new object will overlay / merge with the existing one

If I understand the question correctly, you want to update a document with the contents of another document, but only the fields that are not already present, and completely ignore the fields that are already set (even if to another value).

There is no way to do that in a single command.

You have to query the document first, figure out what you want to $set and then update it (using the old values as a matching filter to make sure you don't get concurrent updates in between).


Another reading of your question would be that you are happy with $set, but do not want to explicitly set all fields. How would you pass in the data then?

You know you can do the following:

db.collection.update(  { _id:...} , { $set: someObjectWithNewData } 

Only on Firefox "Loading failed for the <script> with source"

I ran in the same situation and the script was correctly loading in safe mode. However, disabling all the Add-ons and other Firefox security features didn't help. One thing I tried, and this was the solution in my case, was to temporary disable the cache from the developer window for this particular request. After I saw this was the cause, I wiped out the cache for that site and everything started word normally.

How to turn on/off MySQL strict mode in localhost (xampp)?

For ubuntu :

  • Once you are connected to your VPS via SSH, please try connecting to your mysql with "root"

user: mysql -u root -p

  • Enter "root" user password and you will be in the mysql environment (mysql>), then simply check what is sql_mode, with the following command:

    SHOW VARIABLES LIKE 'sql_mode';

Basically, you will see the table as your result, if the table has a value of STRICT_TRANS_TABLES, it means that this option is enabled, so you need to remove the value from this table with the following command:

set global sql_mode='';

This will set your table's value to empty and disable this setting. Like this:

 +---------------+-------+
 | Variable_name | Value |
 +---------------+-------+
 | sql_mode      |       |
 +---------------+-------+

Please make sure to perform these commands within the MySQL environment and not simply via SSH. I think this moment was missed in the article provided below and the author assumes that the reader understands it intuitively.