Programs & Examples On #Flyout

jQuery position DIV fixed at top on scroll

instead of doing it like that, why not just make the flyout position:fixed, top:0; left:0; once your window has scrolled pass a certain height:

jQuery

  $(window).scroll(function(){
      if ($(this).scrollTop() > 135) {
          $('#task_flyout').addClass('fixed');
      } else {
          $('#task_flyout').removeClass('fixed');
      }
  });

css

.fixed {position:fixed; top:0; left:0;}

Example

show/hide a div on hover and hover out

May be there no need for JS. You can achieve this with css also. Write like this:

.flyout {
    position: absolute;
    width: 1000px;
    height: 450px;
    background: red;
    overflow: hidden;
    z-index: 10000;
    display: none;
}
#menu:hover + .flyout {
    display: block;
}

React Hook Warnings for async function in useEffect: useEffect function must return a cleanup function or nothing

Please try this

 useEffect(() => {
        (async () => {
          const products = await api.index()
          setFilteredProducts(products)
          setProducts(products)
        })()
      }, [])

What does ':' (colon) do in JavaScript?

var o = {
    r: 'some value',
    t: 'some other value'
};

is functionally equivalent to

var o = new Object();
o.r = 'some value';
o.t = 'some other value';

When you use 'badidea' or 'thisisunsafe' to bypass a Chrome certificate/HSTS error, does it only apply for the current site?

I'm a PHP developer and to be able to work on my development environment with a certificate, I was able to do the same by finding the real SSL HTTPS/HTTP Certificate and deleting it.

The steps are :

  1. In the address bar, type "chrome://net-internals/#hsts".
  2. Type the domain name in the text field below "Delete domain".
  3. Click the "Delete" button.
  4. Type the domain name in the text field below "Query domain".
  5. Click the "Query" button.
  6. Your response should be "Not found".

You can find more information at : http://classically.me/blogs/how-clear-hsts-settings-major-browsers

Although this solution is not the best, Chrome currently does not have any good solution for the moment. I have escalated this situation with their support team to help improve user experience.

Edit : you have to repeat the steps every time you will go on the production site.

Call one constructor from another

I am improving upon supercat's answer. I guess the following can also be done:

class Sample
{
    private readonly int _intField;
    public int IntProperty
    {
        get { return _intField; }
    }

    void setupStuff(ref int intField, int newValue)
    {
        //Do some stuff here based upon the necessary initialized variables.
        intField = newValue;
    }

    public Sample(string theIntAsString, bool? doStuff = true)
    {
        //Initialization of some necessary variables.
        //==========================================
        int i = int.Parse(theIntAsString);
        // ................
        // .......................
        //==========================================

        if (!doStuff.HasValue || doStuff.Value == true)
           setupStuff(ref _intField,i);
    }

    public Sample(int theInt): this(theInt, false) //"false" param to avoid setupStuff() being called two times
    {
        setupStuff(ref _intField, theInt);
    }
}

React Checkbox not sending onChange

To get the checked state of your checkbox the path would be:

this.refs.complete.state.checked

The alternative is to get it from the event passed into the handleChange method:

event.target.checked

How to access a value defined in the application.properties file in Spring Boot

The best thing is to use @Value annotation it will automatically assign value to your object private Environment en. This will reduce your code and it will be easy to filter your files.

UnsatisfiedDependencyException: Error creating bean with name

Considering that your package scanning is correctly set either through XML configuration or annotation based configuration.

You will need a @Repository on your ClientRepository implementation as well to allow Spring to use it in an @Autowired. Since it's not here we can only suppose that's what's missing.

As a side note, it would be cleaner to put your @Autowired/@Qualifier directly on your member if the setter method is only used for the @Autowired.

@Autowired
@Qualifier("clientRepository")
private ClientRepository clientRepository;

Lastly, you don't need the @Qualifier is there is only one class implementing the bean definition so unless you have several implementation of ClientService and ClientRepository you can remove the @Qualifier

Getting IP address of client

I use the following static helper method to retrieve the IP of a client:

public static String getClientIpAddr(HttpServletRequest request) {  
    String ip = request.getHeader("X-Forwarded-For");  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("Proxy-Client-IP");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("WL-Proxy-Client-IP");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("HTTP_X_FORWARDED_FOR");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("HTTP_X_FORWARDED");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("HTTP_X_CLUSTER_CLIENT_IP");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("HTTP_CLIENT_IP");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("HTTP_FORWARDED_FOR");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("HTTP_FORWARDED");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("HTTP_VIA");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("REMOTE_ADDR");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getRemoteAddr();  
    }  
    return ip;  
}

How can I override the OnBeforeUnload dialog and replace it with my own?

1) Use onbeforeunload, not onunload.

2) The important thing is to avoid executing a return statement. I don't mean, by this, to avoid returning from your handler. You return all right, but you do it by ensuring that you reach the end of the function and DO NOT execute a return statement. Under these conditions the built-in standard dialog does not occur.

3) You can, if you use onbeforeunload, run an ajax call in your unbeforeunload handler to tidy up on the server, but it must be a synchronous one, and you have to wait for and handle the reply in your onbeforeunload handler (still respecting condition (2) above). I do this and it works fine. If you do a synchronous ajax call, everything is held up until the response comes back. If you do an asynchronous one, thinking that you don't care about the reply from the server, the page unload continues and your ajax call is aborted by this process - including a remote script if it's running.

Char array declaration and initialization in C

That's because your first code snippet is not performing initialization, but assignment:

char myarray[4] = "abc";  // Initialization.

myarray = "abc";          // Assignment.

And arrays are not directly assignable in C.

The name myarray actually resolves to the address of its first element (&myarray[0]), which is not an lvalue, and as such cannot be the target of an assignment.

PHP Redirect to another page after form submit

If your redirect is in PHP, nothing should be echoed to the user before the redirect instruction.

See header for more info.

Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP

Otherwise, you can use Javascript to redirect the user.

Just use

window.location = "http://www.google.com/"

How to use multiple conditions (With AND) in IIF expressions in ssrs

Here is an example that should give you some idea..

=IIF(First(Fields!Gender.Value,"vw_BrgyClearanceNew")="Female" and 
(First(Fields!CivilStatus.Value,"vw_BrgyClearanceNew")="Married"),false,true)

I think you have to identify the datasource name or the table name where your data is coming from.

How do I add an existing directory tree to a project in Visual Studio?

You can also drag and drop the folder from Windows Explorer onto your Visual Studio solution window.

MySQL select where column is not empty

If there are spaces in the phone2 field from inadvertant data entry, you can ignore those records with the IFNULL and TRIM functions:

SELECT phone, phone2
FROM jewishyellow.users
WHERE phone LIKE '813%'
    AND TRIM(IFNULL(phone2,'')) <> '';

Android: Unable to add window. Permission denied for this window type

I tried my best to try all the examples available for this issue. Finally I got the answer for this I don know how much is it reliable but my app is not crashing now.

windowManager = (WindowManager)getSystemService(WINDOW_SERVICE);
    //here is all the science of params
    final LayoutParams myParams = new LayoutParams(
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.WRAP_CONTENT,
            LayoutParams.TYPE_SYSTEM_ERROR,
            WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                    | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
                    | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
            PixelFormat.TRANSLUCENT
    );

In your manifest file just give the permission

 <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>

Addition to this you can also check for the API level if its >=23 then

 if(Build.VERSION.SDK_INT >= 23) {
    if (!Settings.canDrawOverlays(Activity.this)) {
        Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                Uri.parse("package:" + getPackageName()));
        startActivityForResult(intent, 1234);
    }
}
            else
{
    Intent intent = new Intent(Activity.this, Service.class);
    startService(intent);
}

I hope it helps someone somewhere. Full example https://anam-android-codes.blogspot.in/?m=1

How to get row count in sqlite using Android?

c.getCount() returns 1 because the cursor contains a single row (the one with the real COUNT(*)). The count you need is the int value of first row in cursor.

public int getTaskCount(long tasklist_Id) {

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor= db.rawQuery(
        "SELECT COUNT (*) FROM " + TABLE_TODOTASK + " WHERE " + KEY_TASK_TASKLISTID + "=?",
         new String[] { String.valueOf(tasklist_Id) }
    );
    int count = 0;
    if(null != cursor)
        if(cursor.getCount() > 0){
          cursor.moveToFirst();    
          count = cursor.getInt(0);
        }
        cursor.close();
    }

    db.close();
    return count;
}   

Check date between two other dates spring data jpa

I did use following solution to this:

findAllByStartDateLessThanEqualAndEndDateGreaterThanEqual(OffsetDateTime endDate, OffsetDateTime startDate);

Odd behavior when Java converts int to byte?

 N is input number
case 1: 0<=N<=127  answer=N;
case 2: 128<=N<=256 answer=N-256 
case 3: N>256   
        temp1=N/256;
        temp2=N-temp*256;
        if temp2<=127   then answer=temp2;
        else if temp2>=128  then answer=temp2-256;
case 4: negative  number input
        do same procedure.just change the sign of the solution           

How to change the sender's name or e-mail address in mutt?

before you send the email you can press <ESC> f (Escape followed by f) to change the From: Address.

Constraint: This only works if you use mutt in curses mode and do not wan't to script it or if you want to change the address permanent. Then the other solutions are way better!

Dialog to pick image from gallery or from camera

This library makes it simple.

Just Call:

PickImageDialog.on(MainActivity.this, new PickSetup(BuildConfig.APPLICATION_ID));

Then make your Activity implement IPickResult and override this below method.

@Override
public void onPickResult(PickResult r) {
    if (r.getError() == null) {
        imageView.setImageBitmap(r.getBitmap());

        //or

        imageView.setImageURI(r.getUri());
    } else {
        //Handle possible errors
        //TODO: do what you have to do with r.getError();
    }
}

Converting a double to an int in C#

In the provided example your decimal is 8.6. Had it been 8.5 or 9.5, the statement i1 == i2 might have been true. Infact it would have been true for 8.5, and false for 9.5.

Explanation:

Regardless of the decimal part, the second statement, int i2 = (int)score will discard the decimal part and simply return you the integer part. Quite dangerous thing to do, as data loss might occur.

Now, for the first statement, two things can happen. If the decimal part is 5, that is, it is half way through, a decision is to be made. Do we round up or down? In C#, the Convert class implements banker's rounding. See this answer for deeper explanation. Simply put, if the number is even, round down, if the number is odd, round up.

E.g. Consider:

        double score = 8.5;
        int i1 = Convert.ToInt32(score); // 8
        int i2 = (int)score;             // 8

        score += 1;
        i1 = Convert.ToInt32(score);     // 10
        i2 = (int)score;                 // 9

Cmake doesn't find Boost

You can also specify the version of Boost that you would like CMake to use by passing -DBOOST_INCLUDEDIR or -DBOOST_ROOT pointing to the location of correct version boost headers

Example:

cmake -DBOOST_ROOT=/opt/latestboost

This will also be useful when multiple boost versions are on the same system.

How does one target IE7 and IE8 with valid CSS?

For a more complete list as of 2015:

IE 6

* html .ie6 {property:value;}

or

.ie6 { _property:value;}

IE 7

*+html .ie7 {property:value;}

or

*:first-child+html .ie7 {property:value;}

IE 6 and 7

@media screen\9 {
    .ie67 {property:value;}
}

or

.ie67 { *property:value;}

or

.ie67 { #property:value;}

IE 6, 7 and 8

@media \0screen\,screen\9 {
    .ie678 {property:value;}
}

IE 8

html>/**/body .ie8 {property:value;}

or

@media \0screen {
    .ie8 {property:value;}
}

IE 8 Standards Mode Only

.ie8 { property /*\**/: value\9 }

IE 8,9 and 10

@media screen\0 {
    .ie8910 {property:value;}
}

IE 9 only

@media screen and (min-width:0) and (min-resolution: .001dpcm) { 
 // IE9 CSS
 .ie9{property:value;}
}

IE 9 and above

@media screen and (min-width:0) and (min-resolution: +72dpi) {
  // IE9+ CSS
  .ie9up{property:value;}
}

IE 9 and 10

@media screen and (min-width:0) {
    .ie910{property:value;}
}

IE 10 only

_:-ms-lang(x), .ie10 { property:value\9; }

IE 10 and above

_:-ms-lang(x), .ie10up { property:value; }

or

@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
   .ie10up{property:value;}
}

IE 11 (and above..)

_:-ms-fullscreen, :root .ie11up { property:value; }

Javascript alternatives

Modernizr

Modernizr runs quickly on page load to detect features; it then creates a JavaScript object with the results, and adds classes to the html element

User agent selection

The Javascript:

var b = document.documentElement;
        b.setAttribute('data-useragent',  navigator.userAgent);
        b.setAttribute('data-platform', navigator.platform );
        b.className += ((!!('ontouchstart' in window) || !!('onmsgesturechange' in window))?' touch':'');

Adds (e.g) the below to the html element:

data-useragent='Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C)'
data-platform='Win32'

Allowing very targetted CSS selectors, e.g.:

html[data-useragent*='Chrome/13.0'] .nav{
    background:url(img/radial_grad.png) center bottom no-repeat;
}

Footnote

If possible, avoid browser targeting. Identify and fix any issue(s) you identify. Support progressive enhancement and graceful degradation. With that in mind, this is an 'ideal world' scenario not always obtainable in a production environment, as such- the above should help provide some good options.


Attribution / Essential Reading

Remove scroll bar track from ScrollView in Android

By using below, solved the problem

android:scrollbarThumbVertical="@null"

Total number of items defined in an enum

You can use Enum.GetNames to return an IEnumerable of values in your enum and then .Count the resulting IEnumerable.

GetNames produces much the same result as GetValues but is faster.

Select info from table where row has max date

SELECT group, date, checks
  FROM table 
  WHERE checks > 0
  GROUP BY group HAVING date = max(date) 

should work.

How do you produce a .d.ts "typings" definition file from an existing JavaScript library?

I would look for an existing mapping of your 3rd party JS libraries that support Script# or SharpKit. Users of these C# to .js cross compilers will have faced the problem you now face and might have published an open source program to scan your 3rd party lib and convert into skeleton C# classes. If so hack the scanner program to generate TypeScript in place of C#.

Failing that, translating a C# public interface for your 3rd party lib into TypeScript definitions might be simpler than doing the same by reading the source JavaScript.

My special interest is Sencha's ExtJS RIA framework and I know there have been projects published to generate a C# interpretation for Script# or SharpKit

OS X: equivalent of Linux's wget

You can either build wget on the mac machine or use MacPorts to install it directly.

sudo port install wget 

This would work like a charm, also you can update to the latest version as soon as it's available. Port is much more stable than brew, although has a lot less number of formula and ports.

You can install MacPorts from https://www.macports.org/install.php you can download the .pkg file and install it.

Is quitting an application frowned upon?

You can use Process.killProcess(Process.myPid()); to kill your app, but maybe it is not safe? I didn't encounter any problem or crash after I used this method and after I used this, the process of my app in the DDMS list disappeared.

java.io.StreamCorruptedException: invalid stream header: 7371007E

This exception may also occur if you are using Sockets on one side and SSLSockets on the other. Consistency is important.

How to add data validation to a cell using VBA

Use this one:

Dim ws As Worksheet
Dim range1 As Range, rng As Range
'change Sheet1 to suit
Set ws = ThisWorkbook.Worksheets("Sheet1")

Set range1 = ws.Range("A1:A5")
Set rng = ws.Range("B1")

With rng.Validation
    .Delete 'delete previous validation
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
        Formula1:="='" & ws.Name & "'!" & range1.Address
End With

Note that when you're using Dim range1, rng As range, only rng has type of Range, but range1 is Variant. That's why I'm using Dim range1 As Range, rng As Range.
About meaning of parameters you can read is MSDN, but in short:

  • Type:=xlValidateList means validation type, in that case you should select value from list
  • AlertStyle:=xlValidAlertStop specifies the icon used in message boxes displayed during validation. If user enters any value out of list, he/she would get error message.
  • in your original code, Operator:= xlBetween is odd. It can be used only if two formulas are provided for validation.
  • Formula1:="='" & ws.Name & "'!" & range1.Address for list data validation provides address of list with values (in format =Sheet!A1:A5)

How do I pass an object from one activity to another on Android?

This answer is specific to situations where the objects to be passed has nested class structure. With nested class structure, making it Parcelable or Serializeable is a bit tedious. And, the process of serialising an object is not efficient on Android. Consider the example below,

class Myclass    {
  int a;
  class SubClass    {
       int b;
  }
}

With Google's GSON library, you can directly parse an object into a JSON formatted String and convert it back to the object format after usage. For example,

MyClass src = new MyClass();
Gson gS = new Gson();
String target = gS.toJson(src); // Converts the object to a JSON String

Now you can pass this String across activities as a StringExtra with the activity intent.

Intent i = new Intent(FromActivity.this, ToActivity.class);
i.putExtra("MyObjectAsString", target);

Then in the receiving activity, create the original object from the string representation.

String target = getIntent().getStringExtra("MyObjectAsString");
MyClass src = gS.fromJson(target, MyClass.class); // Converts the JSON String to an Object

It keeps the original classes clean and reusable. Above of all, if these class objects are created from the web as JSON objects, then this solution is very efficient and time saving.

UPDATE


While the above explained method works for most situations, for obvious performance reasons, do not rely on Android's bundled-extra system to pass objects around. There are a number of solutions makes this process flexible and efficient, here are a few. Each has its own pros and cons.

  1. Eventbus
  2. Otto

Get connection status on Socket.io client

You can check the socket.connected property:

var socket = io.connect();
console.log('check 1', socket.connected);
socket.on('connect', function() {
  console.log('check 2', socket.connected);
});

It's updated dynamically, if the connection is lost it'll be set to false until the client picks up the connection again. So easy to check for with setInterval or something like that.

Another solution would be to catch disconnect events and track the status yourself.

How do you redirect HTTPS to HTTP?

If you are looking for an answer where you can redirect specific url/s to http then please update your htaccess like below

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteCond %{THE_REQUEST} !/(home/panel/videos|user/profile) [NC] # Multiple urls
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

RewriteCond %{HTTPS} on
RewriteCond %{THE_REQUEST} /(home/panel/videos|user/profile) [NC] # Multiple urls
RewriteRule ^ http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

It worked for me :)

Why is exception.printStackTrace() considered bad practice?

In server applications the stacktrace blows up your stdout/stderr file. It may become larger and larger and is filled with useless data because usually you have no context and no timestamp and so on.

e.g. catalina.out when using tomcat as container

How do you import a large MS SQL .sql file?

I am using MSSQL Express 2014 and none of the solutions worked for me. They all just crashed SQL. As I only needed to run a one off script with many simple insert statements I got around it by writing a little console app as a very last resort:

class Program
{
    static void Main(string[] args)
    {
        RunScript();
    }

    private static void RunScript()
    {
        My_DataEntities db = new My_DataEntities();

        string line;

        System.IO.StreamReader file =
           new System.IO.StreamReader("c:\\ukpostcodesmssql.sql");
        while ((line = file.ReadLine()) != null)
        {
            db.Database.ExecuteSqlCommand(line);
        }

        file.Close();
    }
}

Print a list of space-separated elements in Python 3

list = [1, 2, 3, 4, 5]
for i in list[0:-1]:
    print(i, end=', ')
print(list[-1])

do for loops really take that much longer to run?

was trying to make something that printed all str values in a list separated by commas, inserting "and" before the last entry and came up with this:

spam = ['apples', 'bananas', 'tofu', 'cats']
for i in spam[0:-1]:
    print(i, end=', ')
print('and ' + spam[-1])

Regex to accept alphanumeric and some special character in Javascript?

I forgot to mention. This should also accept whitespace.

You could use:

/^[-@.\/#&+\w\s]*$/

Note how this makes use of the character classes \w and \s.

EDIT:- Added \ to escape /

How to test if a list contains another list?

a=[[1,2] , [3,4] , [0,5,4]]
print(a.__contains__([0,5,4]))

It provides true output.

a=[[1,2] , [3,4] , [0,5,4]]
print(a.__contains__([1,3]))

It provides false output.

Page redirect after certain time PHP

header( "refresh:5;url=wherever.php" );

this is the php way to set header which will redirect you to wherever.php in 5 seconds


Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file. (source php.net)

What is the best way to create and populate a numbers table?

I know this thread is old and answered, but there is a way to squeeze a little extra performance out of Method 7:

Instead of this (essentially method 7 but with some ease of use polish):

DECLARE @BIT AS BIT = 0
IF OBJECT_ID('tempdb..#TALLY') IS NOT NULL
  DROP TABLE #TALLY
DECLARE @RunDate datetime
SET @RunDate=GETDATE()
SELECT TOP 10000 IDENTITY(int,1,1) AS Number
    INTO #TALLY
    FROM sys.objects s1       --use sys.columns if you don't get enough rows returned to generate all the numbers you need
    CROSS JOIN sys.objects s2 --use sys.co
ALTER TABLE #TALLY ADD PRIMARY KEY(Number)
PRINT CONVERT(varchar(20),datediff(ms,@RunDate,GETDATE()))+' milliseconds'

Try this:

DECLARE @BIT AS BIT = 0
IF OBJECT_ID('tempdb..#TALLY') IS NOT NULL
  DROP TABLE #TALLY
DECLARE @RunDate datetime
SET @RunDate=GETDATE()
SELECT TOP 10000 IDENTITY(int,1,1) AS Number
    INTO #TALLY
    FROM        (SELECT @BIT [X] UNION ALL SELECT @BIT) [T2]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T4]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T8]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T16]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T32]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T64]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T128]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T256]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T512]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T1024]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T2048]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T4096]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T8192]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T16384]
ALTER TABLE #TALLY ADD PRIMARY KEY(Number)
PRINT CONVERT(varchar(20),datediff(ms,@RunDate,GETDATE()))+' milliseconds'

On my server this takes ~10 ms as opposed to the ~16-20 ms when selecting from sys.objects. It also has the added benefit of not being dependent on how many objects are in sys.objects. While it's pretty safe, it's technically a dependency and the other one goes faster anyway. I think the speed boost is down to using BITs if you change:

DECLARE @BIT AS BIT = 0

to:

DECLARE @BIT AS BIGINT = 0

It adds ~8-10 ms to the total time on my server. That said, when you scale up to 1,000,000 records BIT vs BIGINT doesn't appreciably affect my query anymore, but it still runs around ~680ms vs ~730ms from sys.objects.

SQL where datetime column equals today's date?

There might be another way, but this should work:

SELECT [Title], [Firstname], [Surname], [Company_name], [Interest] 
FROM [dbo].[EXTRANET] 
WHERE day(Submission_date)=day(now) and 
     month(Submission_date)=month(now)
     and year(Submission_date)=year(now)

Return the most recent record from ElasticSearch index

You can use sort on date field and size=1 parameter. Does it help?

'method' object is not subscriptable. Don't know what's wrong

You need to use parentheses: myList.insert([1, 2, 3]). When you leave out the parentheses, python thinks you are trying to access myList.insert at position 1, 2, 3, because that's what brackets are used for when they are right next to a variable.

Query error with ambiguous column name in SQL

if you join 2 or more tables and they have similar names for their columns sql server wants you to qualify columns which they belong.

SELECT  ev.[ID]
    ,[Description]
    FROM   [Events] as ev 
    LEFT JOIN  [Units] as un ON ev.UnitID = un.UnitId  

if Events and Units tables has same column name (ID) SQL server wants you to use aliases.

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

Once you have the source trees, e.g.

diff -ENwbur repos1/ repos2/ 

Even better

diff -ENwbur repos1/ repos2/  | kompare -o -

and have a crack at it in a good gui tool :)

  • -Ewb ignore the bulk of whitespace changes
  • -N detect new files
  • -u unified
  • -r recurse

How can I use onItemSelected in Android?

spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

               //check if spinner2 has a selected item and show the value in edittext

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

               // sometimes you need nothing here
            }
        });

spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

               //check if spinner1 has a selected item and show the value in edittext


            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

               // sometimes you need nothing here
            }
        });

How can I calculate the number of years between two dates?

if someone needs for interest calculation year in float format

function floatYearDiff(olddate, newdate) {
  var new_y = newdate.getFullYear();
  var old_y = olddate.getFullYear();
  var diff_y = new_y - old_y;
  var start_year = new Date(olddate);
  var end_year = new Date(olddate);
  start_year.setFullYear(new_y);
  end_year.setFullYear(new_y+1);
  if (start_year > newdate) {
    start_year.setFullYear(new_y-1);
    end_year.setFullYear(new_y);
    diff_y--;
  }
  var diff = diff_y + (newdate - start_year)/(end_year - start_year);
  return diff;
}

Doing a join across two databases with different collations on SQL Server and getting an error

You can use the collate clause in a query (I can't find my example right now, so my syntax is probably wrong - I hope it points you in the right direction)

select sone_field collate SQL_Latin1_General_CP850_CI_AI
  from table_1
    inner join table_2
      on (table_1.field collate SQL_Latin1_General_CP850_CI_AI = table_2.field)
  where whatever

Statistics: combinations in Python

This function is very optimized.

def nCk(n,k):
    m=0
    if k==0:
        m=1
    if k==1:
        m=n
    if k>=2:
        num,dem,op1,op2=1,1,k,n
        while(op1>=1):
            num*=op2
            dem*=op1
            op1-=1
            op2-=1
        m=num//dem
    return m

Python JSON dump / append to .txt with each variable on new line

To avoid confusion, paraphrasing both question and answer. I am assuming that user who posted this question wanted to save dictionary type object in JSON file format but when the user used json.dump, this method dumped all its content in one line. Instead, he wanted to record each dictionary entry on a new line. To achieve this use:

with g as outfile:
  json.dump(hostDict, outfile,indent=2)

Using indent = 2 helped me to dump each dictionary entry on a new line. Thank you @agf. Rewriting this answer to avoid confusion.

How to save and load numpy.array() data properly?

np.fromfile() has a sep= keyword argument:

Separator between items if file is a text file. Empty (“”) separator means the file should be treated as binary. Spaces (” ”) in the separator match zero or more whitespace characters. A separator consisting only of spaces must match at least one whitespace.

The default value of sep="" means that np.fromfile() tries to read it as a binary file rather than a space-separated text file, so you get nonsense values back. If you use np.fromfile('markers.txt', sep=" ") you will get the result you are looking for.

However, as others have pointed out, np.loadtxt() is the preferred way to convert text files to numpy arrays, and unless the file needs to be human-readable it is usually better to use binary formats instead (e.g. np.load()/np.save()).

Resetting remote to a certain commit

I solved problem like yours by this commands:

git reset --hard <commit-hash> 
git push -f <remote> <local branch>:<remote branch> 

How to replace substrings in windows batch file

To avoid problems with the batch parser (e.g. exclamation point), look at Problem with search and replace batch file.

Following modification of aflat's script will include special characters like exclamation points.

@echo off
setlocal DisableDelayedExpansion
set INTEXTFILE=test.txt
set OUTTEXTFILE=test_out.txt
set SEARCHTEXT=bath
set REPLACETEXT=hello
set OUTPUTLINE=

for /f "tokens=1,* delims=¶" %%A in ( '"type %INTEXTFILE%"') do (
    SET string=%%A
    setlocal EnableDelayedExpansion
    SET modified=!string:%SEARCHTEXT%=%REPLACETEXT%!

    >> %OUTTEXTFILE% echo(!modified!
    endlocal
)
del %INTEXTFILE%
rename %OUTTEXTFILE% %INTEXTFILE%

How to select the rows with maximum values in each group with dplyr?

df %>% group_by(A,B) %>% slice(which.max(value))

"R cannot be resolved to a variable"?

I know this is an old question but I just solved my own version of it and perhaps this might help someone.

After two days of tearing my hair out with this, I finally got around it by deleting the raw folder, then recreating it and dropping the file(s) back in.

After that, another Project > Clean and it at last compiled.

Cannot read property 'map' of undefined

The error occur mainly becuase the array isnt found. Just check if you have mapped to the correct array. Check the array name or declaration.

Return value from a VBScript function

To return a value from a VBScript function, assign the value to the name of the function, like this:

Function getNumber
    getNumber = "423"
End Function

Getting a machine's external IP address with Python

If you don't want to use external services (IP websites, etc.) You can use the UPnP Protocol.

Do to that we use a simple UPnP client library (https://github.com/flyte/upnpclient)

Install:

pip install upnpclient

Simple Code:

import upnpclient

devices = upnpclient.discover()

if(len(devices) > 0):
    externalIP = devices[0].WANIPConn1.GetExternalIPAddress()
    print(externalIP)
else:
    print('No Connected network interface detected')

Full Code (to get more information as mentioned in the github readme)

In [1]: import upnpclient

In [2]: devices = upnpclient.discover()

In [3]: devices
Out[3]: 
[<Device 'OpenWRT router'>,
 <Device 'Harmony Hub'>,
 <Device 'walternate: root'>]

In [4]: d = devices[0]

In [5]: d.WANIPConn1.GetStatusInfo()
Out[5]: 
{'NewConnectionStatus': 'Connected',
 'NewLastConnectionError': 'ERROR_NONE',
 'NewUptime': 14851479}

In [6]: d.WANIPConn1.GetNATRSIPStatus()
Out[6]: {'NewNATEnabled': True, 'NewRSIPAvailable': False}

In [7]: d.WANIPConn1.GetExternalIPAddress()
Out[7]: {'NewExternalIPAddress': '123.123.123.123'}

Multipart File upload Spring Boot

You can simply use a controller method like this:

@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> uploadFile(
    @RequestParam("file") MultipartFile file) {

  try {
    // Handle the received file here
    // ...
  }
  catch (Exception e) {
    return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
  }

  return new ResponseEntity<>(HttpStatus.OK);
} // method uploadFile

Without any additional configurations for Spring Boot.

Using the following html form client side:

<html>
<body>
  <form action="/uploadFile" method="POST" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" value="Upload"> 
  </form>
</body>
</html>

If you want to set limits on files size you can do it in the application.properties:

# File size limit
multipart.maxFileSize = 3Mb

# Total request size for a multipart/form-data
multipart.maxRequestSize = 20Mb

Moreover to send the file with Ajax take a look here: http://blog.netgloo.com/2015/02/08/spring-boot-file-upload-with-ajax/

How to find which version of Oracle is installed on a Linux server (In terminal)

A bit manual searching but its an alternative way...
Find the Oracle home or where the installation files for Oracle is installed on your linux server.

cd / <-- Goto root directory
find . -print| grep -i dbm*.sql

Result varies on how you installed Oracle but mine displays this

/db/oracle

Goto the folder

less /db/oracle/db1/sqlplus/doc/README.htm

scroll down and you should see something like this

SQL*Plus Release Notes - Release 11.2.0.2

What is the definition of "interface" in object oriented programming

Technically, I would describe an interface as a set of ways (methods, properties, accessors... the vocabulary depends on the language you are using) to interact with an object. If an object supports/implements an interface, then you can use all of the ways specified in the interface to interact with this object.

Semantically, an interface could also contain conventions about what you may or may not do (e.g., the order in which you may call the methods) and about what, in return, you may assume about the state of the object given how you interacted so far.

Violation of PRIMARY KEY constraint. Cannot insert duplicate key in object

Make sure if your table doesn't already have rows whose Primary Key values are same as the the Primary Key Id in your Query.

What's the difference between an id and a class?

CSS is object oriented. ID says instance, class says class.

How do you compare two version Strings in Java?

Here's an optimized implementation:

public static final Comparator<CharSequence> VERSION_ORDER = new Comparator<CharSequence>() {

  @Override
  public int compare (CharSequence lhs, CharSequence rhs) {
    int ll = lhs.length(), rl = rhs.length(), lv = 0, rv = 0, li = 0, ri = 0;
    char c;
    do {
      lv = rv = 0;
      while (--ll >= 0) {
        c = lhs.charAt(li++);
        if (c < '0' || c > '9')
          break;
        lv = lv*10 + c - '0';
      }
      while (--rl >= 0) {
        c = rhs.charAt(ri++);
        if (c < '0' || c > '9')
          break;
        rv = rv*10 + c - '0';
      }
    } while (lv == rv && (ll >= 0 || rl >= 0));
    return lv - rv;
  }

};

Result:

"0.1" - "1.0" = -1
"1.0" - "1.0" = 0
"1.0" - "1.0.0" = 0
"10" - "1.0" = 9
"3.7.6" - "3.7.11" = -5
"foobar" - "1.0" = -1

Batch - If, ElseIf, Else

@echo off
title Test

echo Select a language. (de/en)
set /p language=

IF /i "%language%"=="de" goto languageDE
IF /i "%language%"=="en" goto languageEN

echo Not found.
goto commonexit

:languageDE
echo German
goto commonexit

:languageEN
echo English
goto commonexit

:commonexit
pause

The point is that batch simply continues through instructions, line by line until it reaches a goto, exit or end-of-file. It has no concept of sections to control flow.

Hence, entering de would jump to :languagede then simply continue executing instructions until the file ends, showing de then en then not found.

PHP UML Generator

If you are looking to generate UML easily from your existing PHP Classes you might want to consider PHPStorm 3.0 IDE. It does a good job of replicating existing code into UML.

Have a look at the PHP Storm feature list.

LoDash: Get an array of values from an array of object properties

Simple and even faster way to get it via ES6

let newArray = users.flatMap(i => i.ID) // -> [ 12, 13, 14, 15 ]

Turning off eslint rule for a specific file

Based on the number of rules you want to ignore (All, or Some), and the scope of disabling it (Line(s), File(s), Everywhere), we have 2 × 3 = 6 cases.


1) Disabling "All rules"


Case 1.1: You want to disable "All Rules" for "One or more Lines"

Two ways you can do this:

  1. Put /* eslint-disable-line */ at the end of the line(s),
  2. or /* eslint-disable-next-line */ right before the line.

Case 1.2: You want to disable "All Rules" for "One File"

  • Put the comment of /* eslint-disable */ at the top of the file.

Case 1.3: You want to disable "All rules" for "Some Files"

There are 3 ways you can do this:

  1. You can go with 1.2 and add /* eslint-disable */ on top of the files, one by one.
  2. You can put the file name(s) in .eslintignore. This works well especially if you have a path that you want to be ignored. (e.g. apidoc/**)
  3. Alternatively, if you don't want to have a separate .eslintignore file, you can add "eslintIgnore": ["file1.js", "file2.js"] in package.json as instructed here.

2) Disabling "Some Rules"


Case 2.1: You want to disable "Some Rules" for "One or more Lines"

Two ways you can do this:

  1. You can put /* eslint-disable-line quotes */ (replace quotes with your rules) at the end of the line(s),

  2. or /* eslint-disable-next-line no-alert, quotes, semi */ before the line.


Case 2.2: You want to disable "Some Rules" for "One File"

  • Put the /* eslint-disable no-use-before-define */ comment at the top of the file.

More examples here.


Case 2.3: You want to disable "Some Rules" for "Some files"

  • This is less straight-forward. You should put them in "excludedFiles" object of "overrides" section of your .eslintrc as instructed here.

Add element to a JSON file?

alternatively you can do

iter(data).next()['f'] = var

Test a string for a substring

if "ABCD" in "xxxxABCDyyyy":
    # whatever

Is there a way to get a list of column names in sqlite?

Quick, interactive way to see column names

If you're working interactively in Python and just want to quickly 'see' the column names, I found cursor.description to work.

import sqlite3
conn = sqlite3.connect('test-db.db')
cursor = conn.execute('select * from mytable')
cursor.description

Outputs something like this:

(('Date', None, None, None, None, None, None),
 ('Object-Name', None, None, None, None, None, None),
 ('Object-Count', None, None, None, None, None, None))

Or, quick way to access and print them out.

colnames = cursor.description
for row in colnames:
    print row[0]

Outputs something like this:

Date
Object-Name
Object-Count

The infamous java.sql.SQLException: No suitable driver found

In my case I was working on a Java project with Maven and encountered this error. In your pom.xml file make sure you have this dependencies

<dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.11</version>
    </dependency>
  </dependencies>

and where you create connection have something like this

public Connection createConnection() {
        try {
            String url = "jdbc:mysql://localhost:3306/yourDatabaseName";
            String username = "root"; //your my sql username here
            String password = "1234"; //your mysql password here

            Class.forName("com.mysql.cj.jdbc.Driver");
            return DriverManager.getConnection(url, username, password);
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        }

        return null;
    }

How to insert newline in string literal?

One more way of convenient placement of Environment.NewLine in format string. The idea is to create string extension method that formats string as usual but also replaces {nl} in text with Environment.NewLine

Usage

   " X={0} {nl} Y={1}{nl} X+Y={2}".FormatIt(1, 2, 1+2);
   gives:
    X=1
    Y=2
    X+Y=3

Code

    ///<summary>
    /// Use "string".FormatIt(...) instead of string.Format("string, ...)
    /// Use {nl} in text to insert Environment.NewLine 
    ///</summary>
    ///<exception cref="ArgumentNullException">If format is null</exception>
    [StringFormatMethod("format")]
    public static string FormatIt(this string format, params object[] args)
    {
        if (format == null) throw new ArgumentNullException("format");

        return string.Format(format.Replace("{nl}", Environment.NewLine), args);
    }

Note

  1. If you want ReSharper to highlight your parameters, add attribute to the method above

    [StringFormatMethod("format")]

  2. This implementation is obviously less efficient than just String.Format

  3. Maybe one, who interested in this question would be interested in the next question too: Named string formatting in C#

How can I remove the top and right axis in matplotlib?

[edit] matplotlib in now (2013-10) on version 1.3.0 which includes this

That ability was actually just added, and you need the Subversion version for it. You can see the example code here.

I am just updating to say that there's a better example online now. Still need the Subversion version though, there hasn't been a release with this yet.

[edit] Matplotlib 0.99.0 RC1 was just released, and includes this capability.

Using Bootstrap Modal window as PartialView

I have achieved this by using one nice example i have found here. I have replaced the jquery dialog used in that example with the Twitter Bootstrap Modal windows.

How to add a linked source folder in Android Studio?

in your build.gradle add the following to the end of the android node

android {
    ....
    ....

    sourceSets {
        main.java.srcDirs += 'src/main/<YOUR DIRECTORY>'
    }

}

How to create a file with a given size in Linux?

You can do it programmatically:

#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>

int main() {
    int fd = creat("/tmp/foo.txt", 0644);
    ftruncate(fd, SIZE_IN_BYTES);
    close(fd);
    return 0;
}

This approach is especially useful to subsequently mmap the file into memory.

use the following command to check that the file has the correct size:

# du -B1 --apparent-size /tmp/foo.txt

Be careful:

# du /tmp/foo.txt

will probably print 0 because it is allocated as Sparse file if supported by your filesystem.

see also: man 2 open and man 2 truncate

Auto increment primary key in SQL Server Management Studio 2012

Make sure that the Key column's datatype is int and then setting identity manually, as image shows

enter image description here

Or just run this code

-- ID is the name of the  [to be] identity column
ALTER TABLE [yourTable] DROP COLUMN ID 
ALTER TABLE [yourTable] ADD ID INT IDENTITY(1,1)

the code will run, if ID is not the only column in the table

image reference fifo's

How to write an inline IF statement in JavaScript?

To add to this you can also use inline if condition with && and || operators. Like this

var a = 2;
var b = 0;

var c = (a > b || b == 0)? "do something" : "do something else";

OpenCV - Apply mask to a color image

Answer given by Abid Rahman K is not completely correct. I also tried it and found very helpful but got stuck.

This is how I copy image with a given mask.

x, y = np.where(mask!=0)
pts = zip(x, y)
# Assuming dst and src are of same sizes
for pt in pts:
   dst[pt] = src[pt]

This is a bit slow but gives correct results.

EDIT:

Pythonic way.

idx = (mask!=0)
dst[idx] = src[idx]

Passing HTML to template using Flask/Jinja2

From the jinja docs section HTML Escaping:

When automatic escaping is enabled everything is escaped by default except for values explicitly marked as safe. Those can either be marked by the application or in the template by using the |safe filter.

Example:

 <div class="info">
   {{data.email_content|safe}}
 </div>

When is the init() function run?

mutil init function in one package execute order:

  1. const and variable defined file init() function execute

  2. init function execute order by the filename asc

Declare a dictionary inside a static class

The problem with your initial example was primarily due to the use of const rather than static; you can't create a non-null const reference in C#.

I believe this would also have worked:

public static class ErrorCode
{
    public static IDictionary<string, string> ErrorCodeDic
        = new Dictionary<string, string>()
            { {"1", "User name or password problem"} };
}

Also, as Y Low points out, adding readonly is a good idea as well, and none of the modifiers discussed here will prevent the dictionary itself from being modified.

How to set image for bar button with swift?

I am using latest swift (2.1) and the answer (Dharmesh Kheni and jungledev) does not work for me. The image color was off (when setting in IB, it was blue and when setting directly in UIButton, it was black). It turns out I could create the same bar item with the following code:

let barButton = UIBarButtonItem(image: UIImage(named: "menu"), landscapeImagePhone: nil, style: .Done, target: self, action: #selector(revealBackClicked))
self.navigationItem.leftBarButtonItem = barButton

Get only part of an Array in Java?

You can try:

System.arraycopy(sourceArray, 0, targetArray, 0, targetArray.length);// copies whole array

// copies elements 1 and 2 from sourceArray to targetArray
System.arraycopy(sourceArray, 1, targetArray, 0, 2); 

See javadoc for System.

What's the best way to send a signal to all members of a process group?

Kill all the processes belonging to the same process tree using the Process Group ID (PGID)

  • kill -- -$PGID     Use default signal (TERM = 15)
  • kill -9 -$PGID     Use the signal KILL (9)

You can retrieve the PGID from any Process-ID (PID) of the same process tree

  • kill -- -$(ps -o pgid= $PID | grep -o '[0-9]*')   (signal TERM)
  • kill -9 -$(ps -o pgid= $PID | grep -o '[0-9]*')   (signal KILL)

Special thanks to tanager and Speakus for contributions on $PID remaining spaces and OSX compatibility.

Explanation

  • kill -9 -"$PGID" => Send signal 9 (KILL) to all child and grandchild...
  • PGID=$(ps opgid= "$PID") => Retrieve the Process-Group-ID from any Process-ID of the tree, not only the Process-Parent-ID. A variation of ps opgid= $PID is ps -o pgid --no-headers $PID where pgid can be replaced by pgrp.
    But:
    • ps inserts leading spaces when PID is less than five digits and right aligned as noticed by tanager. You can use:
      PGID=$(ps opgid= "$PID" | tr -d ' ')
    • ps from OSX always print the header, therefore Speakus proposes:
      PGID="$( ps -o pgid "$PID" | grep [0-9] | tr -d ' ' )"
  • grep -o [0-9]* prints successive digits only (does not print spaces or alphabetical headers).

Further command lines

PGID=$(ps -o pgid= $PID | grep -o [0-9]*)
kill -TERM -"$PGID"  # kill -15
kill -INT  -"$PGID"  # correspond to [CRTL+C] from keyboard
kill -QUIT -"$PGID"  # correspond to [CRTL+\] from keyboard
kill -CONT -"$PGID"  # restart a stopped process (above signals do not kill it)
sleep 2              # wait terminate process (more time if required)
kill -KILL -"$PGID"  # kill -9 if it does not intercept signals (or buggy)

Limitation

  • As noticed by davide and Hubert Kario, when kill is invoked by a process belonging to the same tree, kill risks to kill itself before terminating the whole tree killing.
  • Therefore, be sure to run the command using a process having a different Process-Group-ID.

Long story

> cat run-many-processes.sh
#!/bin/sh
echo "ProcessID=$$ begins ($0)"
./child.sh background &
./child.sh foreground
echo "ProcessID=$$ ends ($0)"

> cat child.sh
#!/bin/sh
echo "ProcessID=$$ begins ($0)"
./grandchild.sh background &
./grandchild.sh foreground
echo "ProcessID=$$ ends ($0)"

> cat grandchild.sh
#!/bin/sh
echo "ProcessID=$$ begins ($0)"
sleep 9999
echo "ProcessID=$$ ends ($0)"

Run the process tree in background using '&'

> ./run-many-processes.sh &    
ProcessID=28957 begins (./run-many-processes.sh)
ProcessID=28959 begins (./child.sh)
ProcessID=28958 begins (./child.sh)
ProcessID=28960 begins (./grandchild.sh)
ProcessID=28961 begins (./grandchild.sh)
ProcessID=28962 begins (./grandchild.sh)
ProcessID=28963 begins (./grandchild.sh)

> PID=$!                    # get the Parent Process ID
> PGID=$(ps opgid= "$PID")  # get the Process Group ID

> ps fj
 PPID   PID  PGID   SID TTY      TPGID STAT   UID   TIME COMMAND
28348 28349 28349 28349 pts/3    28969 Ss   33021   0:00 -bash
28349 28957 28957 28349 pts/3    28969 S    33021   0:00  \_ /bin/sh ./run-many-processes.sh
28957 28958 28957 28349 pts/3    28969 S    33021   0:00  |   \_ /bin/sh ./child.sh background
28958 28961 28957 28349 pts/3    28969 S    33021   0:00  |   |   \_ /bin/sh ./grandchild.sh background
28961 28965 28957 28349 pts/3    28969 S    33021   0:00  |   |   |   \_ sleep 9999
28958 28963 28957 28349 pts/3    28969 S    33021   0:00  |   |   \_ /bin/sh ./grandchild.sh foreground
28963 28967 28957 28349 pts/3    28969 S    33021   0:00  |   |       \_ sleep 9999
28957 28959 28957 28349 pts/3    28969 S    33021   0:00  |   \_ /bin/sh ./child.sh foreground
28959 28960 28957 28349 pts/3    28969 S    33021   0:00  |       \_ /bin/sh ./grandchild.sh background
28960 28964 28957 28349 pts/3    28969 S    33021   0:00  |       |   \_ sleep 9999
28959 28962 28957 28349 pts/3    28969 S    33021   0:00  |       \_ /bin/sh ./grandchild.sh foreground
28962 28966 28957 28349 pts/3    28969 S    33021   0:00  |           \_ sleep 9999
28349 28969 28969 28349 pts/3    28969 R+   33021   0:00  \_ ps fj

The command pkill -P $PID does not kill the grandchild:

> pkill -P "$PID"
./run-many-processes.sh: line 4: 28958 Terminated              ./child.sh background
./run-many-processes.sh: line 4: 28959 Terminated              ./child.sh foreground
ProcessID=28957 ends (./run-many-processes.sh)
[1]+  Done                    ./run-many-processes.sh

> ps fj
 PPID   PID  PGID   SID TTY      TPGID STAT   UID   TIME COMMAND
28348 28349 28349 28349 pts/3    28987 Ss   33021   0:00 -bash
28349 28987 28987 28349 pts/3    28987 R+   33021   0:00  \_ ps fj
    1 28963 28957 28349 pts/3    28987 S    33021   0:00 /bin/sh ./grandchild.sh foreground
28963 28967 28957 28349 pts/3    28987 S    33021   0:00  \_ sleep 9999
    1 28962 28957 28349 pts/3    28987 S    33021   0:00 /bin/sh ./grandchild.sh foreground
28962 28966 28957 28349 pts/3    28987 S    33021   0:00  \_ sleep 9999
    1 28961 28957 28349 pts/3    28987 S    33021   0:00 /bin/sh ./grandchild.sh background
28961 28965 28957 28349 pts/3    28987 S    33021   0:00  \_ sleep 9999
    1 28960 28957 28349 pts/3    28987 S    33021   0:00 /bin/sh ./grandchild.sh background
28960 28964 28957 28349 pts/3    28987 S    33021   0:00  \_ sleep 9999

The command kill -- -$PGID kills all processes including the grandchild.

> kill --    -"$PGID"  # default signal is TERM (kill -15)
> kill -CONT -"$PGID"  # awake stopped processes
> kill -KILL -"$PGID"  # kill -9 to be sure

> ps fj
 PPID   PID  PGID   SID TTY      TPGID STAT   UID   TIME COMMAND
28348 28349 28349 28349 pts/3    29039 Ss   33021   0:00 -bash
28349 29039 29039 28349 pts/3    29039 R+   33021   0:00  \_ ps fj

Conclusion

I notice in this example PID and PGID are equal (28957).
This is why I originally thought kill -- -$PID was enough. But in the case the process is spawn within a Makefile the Process ID is different from the Group ID.

I think kill -- -$(ps -o pgid= $PID | grep -o [0-9]*) is the best simple trick to kill a whole process tree when called from a different Group ID (another process tree).

react native get TextInput value

This piece of code worked for me. What I was missing was I was not passing 'this' in button action:

 onPress={this._handlePress.bind(this)}>
--------------

  _handlePress(event) {
console.log('Pressed!');

 var username = this.state.username;
 var password = this.state.password;

 console.log(username);
 console.log(password);
}

  render() {
    return (
      <View style={styles.container}>

      <TextInput
      ref="usr"
      style={{height: 40, borderColor: 'gray', borderWidth: 1 , marginTop: 10 , padding : 10 , marginLeft : 5 , marginRight : 5 }}
      placeHolder= "Enter username "
      placeholderTextColor = '#a52a2a'

      returnKeyType = {"next"}
      autoFocus = {true}
      autoCapitalize = "none"
      autoCorrect = {false}
      clearButtonMode = 'while-editing'
      onChangeText={(text) => {
          this.setState({username:text});
        }}
      onSubmitEditing={(event) => {
     this.refs.psw.focus();

      }}
      />

      <TextInput
      ref="psw"
      style={{height: 40, borderColor: 'gray', borderWidth: 1 , marginTop: 10,marginLeft : 5 , marginRight : 5}}
      placeholder= "Enter password"
      placeholderTextColor = '#a52a2a'
      autoCapitalize = "none"
      autoCorrect = {false}
      returnKeyType = {'done'}
      secureTextEntry = {true}
      clearButtonMode = 'while-editing'
      onChangeText={(text) => {
          this.setState({password:text});
        }}
      />

      <Button
        style={{borderWidth: 1, borderColor: 'blue'}}
        onPress={this._handlePress.bind(this)}>
        Login
      </Button>

      </View>
    );``
  }
}

Interview question: Check if one string is a rotation of other string

It's very easy to write in PHP using strlen and strpos functions:

function isRotation($string1, $string2) {
    return strlen($string1) == strlen($string2) && (($string1.$string1).strpos($string2) != -1);
}

I don't know what strpos uses internally, but if it uses KMP this will be linear in time.

What does "opt" mean (as in the "opt" directory)? Is it an abbreviation?

Add-on software packages.

See http://www.pathname.com/fhs/2.2/fhs-3.12.html for details.

Also described at Wikipedia.

Its use dates back at least to the late 1980s, when it was a standard part of System V UNIX. These days, it's also seen in Linux, Solaris (which is SysV), OSX Cygwin, etc. Other BSD unixes (FreeBSD, NetBSD, etc) tend to follow other rules, so you don't usually see BSD systems with an /opt unless they're administered by someone who is more comfortable in other environments.

How to remove a web site from google analytics

Update 26/03/2016:

Instead of a link in the bottom right corner of the Settings form, the delete button is moved to the top right corner, saying:

Move To Trash Can

When you click on it, it will ask you for confirmation and move it to Trash Can.

What is difference between Lightsail and EC2?

Check official website https://aws.amazon.com/free/compute/lightsail-vs-ec2/

enter image description here

Amazon Lightsail – The Power of AWS, the Simplicity of a VPS https://aws.amazon.com/blogs/aws/amazon-lightsail-the-power-of-aws-the-simplicity-of-a-vps/

Amazon EC2 vs Amazon Lightsail (comparison on point )

  • Web Performances
  • Plans
  • Features and Usability enter image description here

Source : https://www.vpsbenchmarks.com/compare/features/ec2_vs_lightsail

Getting a File's MD5 Checksum in Java

If you're using ANT to build, this is dead-simple. Add the following to your build.xml:

<checksum file="${jarFile}" todir="${toDir}"/>

Where jarFile is the JAR you want to generate the MD5 against, and toDir is the directory you want to place the MD5 file.

More info here.

Getting last month's date in php

Oh I figured this out, please ignore unless you have the same problem i did in which case:

$prevmonth = date("M Y",mktime(0,0,0,date("m")-1,1,date("Y")));

Validate Dynamically Added Input fields

Reset form validation after adding new fields.

function resetFormValidator(formId) {
    $(formId).removeData('validator');
    $(formId).removeData('unobtrusiveValidation');
    $.validator.unobtrusive.parse(formId);
}

Change the Bootstrap Modal effect

 body{
  text-align:center;
  padding:50px;
}
.modal.fade{
  opacity:1;
}
.modal.fade .modal-dialog {
   -webkit-transform: translate(0);
   -moz-transform: translate(0);
   transform: translate(0);
}
.btn-black{
  position:absolute;
  bottom:50px;
  transform:translateX(-50%);
  background:#222;
  padding:10px 20px;
  text-transform:uppercase;
  letter-spacing:1px;
  font-size:14px;
  font-weight:bold;
}

    <div class="container">
    <form class="form-inline" style="position:absolute; top:40%; left:50%; transform:translateX(-50%);">
        <div class="form-group">
        <label>Entrances</label>
          <select class="form-control" id="entrance">
            <optgroup label="Attention Seekers">
              <option value="bounce">bounce</option>
              <option value="flash">flash</option>
              <option value="pulse">pulse</option>
              <option value="rubberBand">rubberBand</option>
              <option value="shake">shake</option>
              <option value="swing">swing</option>
              <option value="tada">tada</option>
              <option value="wobble">wobble</option>
              <option value="jello">jello</option>
            </optgroup>
            <optgroup label="Bouncing Entrances">
              <option value="bounceIn" selected>bounceIn</option>
              <option value="bounceInDown">bounceInDown</option>
              <option value="bounceInLeft">bounceInLeft</option>
              <option value="bounceInRight">bounceInRight</option>
              <option value="bounceInUp">bounceInUp</option>
            </optgroup>
            <optgroup label="Fading Entrances">
              <option value="fadeIn">fadeIn</option>
              <option value="fadeInDown">fadeInDown</option>
              <option value="fadeInDownBig">fadeInDownBig</option>
              <option value="fadeInLeft">fadeInLeft</option>
              <option value="fadeInLeftBig">fadeInLeftBig</option>
              <option value="fadeInRight">fadeInRight</option>
              <option value="fadeInRightBig">fadeInRightBig</option>
              <option value="fadeInUp">fadeInUp</option>
              <option value="fadeInUpBig">fadeInUpBig</option>
            </optgroup>
            <optgroup label="Flippers">
              <option value="flipInX">flipInX</option>
              <option value="flipInY">flipInY</option>
            </optgroup>
            <optgroup label="Lightspeed">
              <option value="lightSpeedIn">lightSpeedIn</option>
            </optgroup>
            <optgroup label="Rotating Entrances">
              <option value="rotateIn">rotateIn</option>
              <option value="rotateInDownLeft">rotateInDownLeft</option>
              <option value="rotateInDownRight">rotateInDownRight</option>
              <option value="rotateInUpLeft">rotateInUpLeft</option>
              <option value="rotateInUpRight">rotateInUpRight</option>
            </optgroup>
            <optgroup label="Sliding Entrances">
              <option value="slideInUp">slideInUp</option>
              <option value="slideInDown">slideInDown</option>
              <option value="slideInLeft">slideInLeft</option>
              <option value="slideInRight">slideInRight</option>
            </optgroup>
            <optgroup label="Zoom Entrances">
              <option value="zoomIn">zoomIn</option>
              <option value="zoomInDown">zoomInDown</option>
              <option value="zoomInLeft">zoomInLeft</option>
              <option value="zoomInRight">zoomInRight</option>
              <option value="zoomInUp">zoomInUp</option>
            </optgroup>

            <optgroup label="Specials">
              <option value="rollIn">rollIn</option>
            </optgroup>
          </select>
       </div>
        <div class="form-group">
        <label>Exits</label>
          <select class="form-control" id="exit">
            <optgroup label="Attention Seekers">
              <option value="bounce">bounce</option>
              <option value="flash">flash</option>
              <option value="pulse">pulse</option>
              <option value="rubberBand">rubberBand</option>
              <option value="shake">shake</option>
              <option value="swing">swing</option>
              <option value="tada">tada</option>
              <option value="wobble">wobble</option>
              <option value="jello">jello</option>
            </optgroup>
            <optgroup label="Bouncing Exits">
              <option value="bounceOut">bounceOut</option>
              <option value="bounceOutDown">bounceOutDown</option>
              <option value="bounceOutLeft">bounceOutLeft</option>
              <option value="bounceOutRight">bounceOutRight</option>
              <option value="bounceOutUp">bounceOutUp</option>
            </optgroup>
            <optgroup label="Fading Exits">
              <option value="fadeOut">fadeOut</option>
              <option value="fadeOutDown">fadeOutDown</option>
              <option value="fadeOutDownBig">fadeOutDownBig</option>
              <option value="fadeOutLeft">fadeOutLeft</option>
              <option value="fadeOutLeftBig">fadeOutLeftBig</option>
              <option value="fadeOutRight">fadeOutRight</option>
              <option value="fadeOutRightBig">fadeOutRightBig</option>
              <option value="fadeOutUp">fadeOutUp</option>
              <option value="fadeOutUpBig">fadeOutUpBig</option>
            </optgroup>
            <optgroup label="Flippers">
              <option value="flipOutX" selected>flipOutX</option>
              <option value="flipOutY">flipOutY</option>
            </optgroup>
            <optgroup label="Lightspeed">
              <option value="lightSpeedOut">lightSpeedOut</option>
            </optgroup>
            <optgroup label="Rotating Exits">
              <option value="rotateOut">rotateOut</option>
              <option value="rotateOutDownLeft">rotateOutDownLeft</option>
              <option value="rotateOutDownRight">rotateOutDownRight</option>
              <option value="rotateOutUpLeft">rotateOutUpLeft</option>
              <option value="rotateOutUpRight">rotateOutUpRight</option>
            </optgroup>
            <optgroup label="Sliding Exits">
              <option value="slideOutUp">slideOutUp</option>
              <option value="slideOutDown">slideOutDown</option>
              <option value="slideOutLeft">slideOutLeft</option>
              <option value="slideOutRight">slideOutRight</option>
            </optgroup>        
            <optgroup label="Zoom Exits">
              <option value="zoomOut">zoomOut</option>
              <option value="zoomOutDown">zoomOutDown</option>
              <option value="zoomOutLeft">zoomOutLeft</option>
              <option value="zoomOutRight">zoomOutRight</option>
              <option value="zoomOutUp">zoomOutUp</option>
            </optgroup>
            <optgroup label="Specials">
              <option value="rollOut">rollOut</option>
            </optgroup>

          </select>
       </div>
    <!-- Button trigger modal -->
    <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
      Launch demo modal
    </button>
    </form>

      <a class="btn btn-black " href="http://demo.nhembram.com/bootstrap-modal-animation-with-animate-css/index.html" target="_blank">View FullPage</a>
    </div>
    <!-- Modal -->
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title" id="myModalLabel">Modal title</h4>
          </div>
          <div class="modal-body">
            ...
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary">Save changes</button>
          </div>
        </div>
      </div>
    </div>

    <script>
    function testAnim(x) {
        $('.modal .modal-dialog').attr('class', 'modal-dialog  ' + x + '  animated');
    };
    $('#myModal').on('show.bs.modal', function (e) {
      var anim = $('#entrance').val();
          testAnim(anim);
    });
    $('#myModal').on('hide.bs.modal', function (e) {
      var anim = $('#exit').val();
          testAnim(anim);
    });
    </script>

<style>
body{
  text-align:center;
  padding:50px;
}
.modal.fade{
  opacity:1;
}
.modal.fade .modal-dialog {
   -webkit-transform: translate(0);
   -moz-transform: translate(0);
   transform: translate(0);
}
.btn-black{
  position:absolute;
  bottom:50px;
  transform:translateX(-50%);
  background:#222;
  padding:10px 20px;
  text-transform:uppercase;
  letter-spacing:1px;
  font-size:14px;
  font-weight:bold;
}
</style>

jQuery, checkboxes and .is(":checked")

$('#myCheckbox').change(function () {
    if ($(this).prop("checked")) {
        // checked
        return;
    }
    // not checked
});

Note: In older versions of jquery it was OK to use attr. Now it's suggested to use prop to read the state.

:after and :before pseudo-element selectors in Sass

Use ampersand to specify the parent selector.

SCSS syntax:

p {
    margin: 2em auto;

    > a {
        color: red;
    }

    &:before {
        content: "";
    }

    &:after {
        content: "* * *";
    }
}

Use string in switch case in java

    String name,lname;
 name= JOptionPane.showInputDialog(null,"Enter your name");
   lname= JOptionPane.showInputDialog(null,"Enter your father name");
    if(name.equals("Ahmad")){
       JOptionPane.showMessageDialog(null,"welcome "+name);
    }
    if(lname.equals("Khan"))
   JOptionPane.showMessageDialog(null,"Name : "+name +"\nLast name :"+lname ); 

    else {
       JOptionPane.showMessageDialog(null,"try again " );
    } 
  }}

How do I find the index of a character in a string in Ruby?

You can use this

"abcdefg".index('c')   #=> 2

How to return a string value from a Bash function

All answers above ignore what has been stated in the man page of bash.

  • All variables declared inside a function will be shared with the calling environment.
  • All variables declared local will not be shared.

Example code

#!/bin/bash

f()
{
    echo function starts
    local WillNotExists="It still does!"
    DoesNotExists="It still does!"
    echo function ends
}

echo $DoesNotExists #Should print empty line
echo $WillNotExists #Should print empty line
f                   #Call the function
echo $DoesNotExists #Should print It still does!
echo $WillNotExists #Should print empty line

And output

$ sh -x ./x.sh
+ echo

+ echo

+ f
+ echo function starts 
function starts
+ local 'WillNotExists=It still does!'
+ DoesNotExists='It still does!'
+ echo function ends 
function ends
+ echo It still 'does!' 
It still does!
+ echo

Also under pdksh and ksh this script does the same!

How to merge a specific commit in Git

If you have committed changes to master branch. Now you want to move that same commit to release-branch. Check the commit id(Eg:xyzabc123) for the commit.

Now try following commands

git checkout release-branch
git cherry-pick xyzabc123
git push origin release-branch

Getting All Variables In Scope

I made a fiddle implementing (essentially) above ideas outlined by iman. Here is how it looks when you mouse over the second ipsum in return ipsum*ipsum - ...

enter image description here

The variables which are in scope are highlighted where they are declared (with different colors for different scopes). The lorem with red border is a shadowed variable (not in scope, but be in scope if the other lorem further down the tree wouldn't be there.)

I'm using esprima library to parse the JavaScript, and estraverse, escodegen, escope (utility libraries on top of esprima.) The 'heavy lifting' is done all by those libraries (the most complex being esprima itself, of course.)

How it works

ast = esprima.parse(sourceString, {range: true, sourceType: 'script'});

makes the abstract syntax tree. Then,

analysis = escope.analyze(ast);

generates a complex data structure encapsulating information about all the scopes in the program. The rest is gathering together the information encoded in that analysis object (and the abstract syntax tree itself), and making an interactive coloring scheme out of it.

So the correct answer is actually not "no", but "yes, but". The "but" being a big one: you basically have to rewrite significant parts of the chrome browser (and it's devtools) in JavaScript. JavaScript is a Turing complete language, so of course that is possible, in principle. What is impossible is doing the whole thing without using the entirety of your source code (as a string) and then doing highly complex stuff with that.

finding and replacing elements in a list

You can simply use list comprehension in python:

def replace_element(YOUR_LIST, set_to=NEW_VALUE):
    return [i
            if SOME_CONDITION
            else NEW_VALUE
            for i in YOUR_LIST]

for your case, where you want to replace all occurrences of 1 with 10, the code snippet will be like this:

def replace_element(YOUR_LIST, set_to=10):
    return [i
            if i != 1  # keeps all elements not equal to one
            else set_to  # replaces 1 with 10
            for i in YOUR_LIST]

Carriage return and Line feed... Are both required in C#?

It depends on where you're displaying the text. On the console or a textbox for example, \n will suffice. On a RichTextBox I think you need both.

HTML set image on browser tab

It's called a Favicon, have a read.

<link rel="shortcut icon" href="http://www.example.com/myicon.ico"/>

You can use this neat tool to generate cross-browser compatible Favicons.

JAXB: how to marshall map into <key>value</key>

I'm still working on a better solution but using MOXy JAXB, I've been able to handle the following XML:

<?xml version="1.0" encoding="UTF-8"?>
<root>
   <mapProperty>
      <map>
         <key>value</key>
         <key2>value2</key2>
      </map>
   </mapProperty>
</root>

You need to use an @XmlJavaTypeAdapter on your Map property:

import java.util.HashMap;
import java.util.Map;

import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

@XmlRootElement
public class Root {

    private Map<String, String> mapProperty;

    public Root() {
        mapProperty = new HashMap<String, String>();
    }

    @XmlJavaTypeAdapter(MapAdapter.class)
    public Map<String, String> getMapProperty() {
        return mapProperty;
    }

    public void setMapProperty(Map<String, String> map) {
        this.mapProperty = map;
    }

}

The implementation of the XmlAdapter is as follows:

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.xml.bind.annotation.adapters.XmlAdapter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class MapAdapter extends XmlAdapter<AdaptedMap, Map<String, String>> {

    @Override
    public AdaptedMap marshal(Map<String, String> map) throws Exception {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document document = db.newDocument();
        Element rootElement = document.createElement("map");
        document.appendChild(rootElement);

        for(Entry<String,String> entry : map.entrySet()) {
            Element mapElement = document.createElement(entry.getKey());
            mapElement.setTextContent(entry.getValue());
            rootElement.appendChild(mapElement);
        }

        AdaptedMap adaptedMap = new AdaptedMap();
        adaptedMap.setValue(document);
        return adaptedMap;
    }

    @Override
    public Map<String, String> unmarshal(AdaptedMap adaptedMap) throws Exception {
        Map<String, String> map = new HashMap<String, String>();
        Element rootElement = (Element) adaptedMap.getValue();
        NodeList childNodes = rootElement.getChildNodes();
        for(int x=0,size=childNodes.getLength(); x<size; x++) {
            Node childNode = childNodes.item(x);
            if(childNode.getNodeType() == Node.ELEMENT_NODE) {
                map.put(childNode.getLocalName(), childNode.getTextContent());
            }
        }
        return map;
    }

}

The AdpatedMap class is where all the magic happens, we will use a DOM to represent the content. We will trick JAXB intro dealing with a DOM through the combination of @XmlAnyElement and a property of type Object:

import javax.xml.bind.annotation.XmlAnyElement;

public class AdaptedMap {

    private Object value;

    @XmlAnyElement
    public Object getValue() {
        return value;
    }

    public void setValue(Object value) {
        this.value = value;
    }

}

This solution requires the MOXy JAXB implementation. You can configure the JAXB runtime to use the MOXy implementation by adding a file named jaxb.properties in with your model classes with the following entry:

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

The following demo code can be used to verify the code:

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Root.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        Root root = (Root) unmarshaller.unmarshal(new File("src/forum74/input.xml"));

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(root, System.out);
    }
}

How do you dismiss the keyboard when editing a UITextField

Swift 3, iOS 9+

@IBAction private func noteFieldDidEndOnExit(_ sender: UITextField) {}

UPD: It still works fine for me. I think guy that devoted this answer just didn't understand that he needs to bind this action to the UITextField at the storyboard.

Associating existing Eclipse project with existing SVN repository

I came across the same issue. I checked out using Tortoise client and then tried to import the projects in Eclipse using import wizard. Eclipse did not recognize the svn location. I tried share option as mentioned in the above posts and it tried to commit these projects into SVN. But my issue was a version mismatch. I selected svn 1.8 version in eclipse (I was using 1.7 in eclipse and 1.8.8 in tortoise) and then re imported the projects. It resolved with no issues.

no module named zlib

The easiest solution I found, is given on python.org devguide:

sudo apt-get build-dep python3.6

If that package is not available for your system, try reducing the minor version until you find a package that is available in your system’s package manager.

I tried explaining details, on my blog.

HTML&CSS + Twitter Bootstrap: full page layout or height 100% - Npx

I know it's late in the day but might help someone else!

body,html {
  height: 100%;
}

.contentarea {

 /* 
  * replace 160px with the sum of height of all other divs 
  * inc padding, margins etc 
  */
  min-height: calc(100% - 160px); 
}

How do I get a YouTube video thumbnail from the YouTube API?

You can use YouTube Data API to retrieve video thumbnails, caption, description, rating, statistics and more. API version 3 requires a key*. Obtain the key and create a videos: list request:

https://www.googleapis.com/youtube/v3/videos?key=YOUR_API_KEY&part=snippet&id=VIDEO_ID

Example PHP Code

$data = file_get_contents("https://www.googleapis.com/youtube/v3/videos?key=YOUR_API_KEY&part=snippet&id=T0Jqdjbed40");
$json = json_decode($data);
var_dump($json->items[0]->snippet->thumbnails);

Output

object(stdClass)#5 (5) {
  ["default"]=>
  object(stdClass)#6 (3) {
    ["url"]=>
    string(46) "https://i.ytimg.com/vi/T0Jqdjbed40/default.jpg"
    ["width"]=>
    int(120)
    ["height"]=>
    int(90)
  }
  ["medium"]=>
  object(stdClass)#7 (3) {
    ["url"]=>
    string(48) "https://i.ytimg.com/vi/T0Jqdjbed40/mqdefault.jpg"
    ["width"]=>
    int(320)
    ["height"]=>
    int(180)
  }
  ["high"]=>
  object(stdClass)#8 (3) {
    ["url"]=>
    string(48) "https://i.ytimg.com/vi/T0Jqdjbed40/hqdefault.jpg"
    ["width"]=>
    int(480)
    ["height"]=>
    int(360)
  }
  ["standard"]=>
  object(stdClass)#9 (3) {
    ["url"]=>
    string(48) "https://i.ytimg.com/vi/T0Jqdjbed40/sddefault.jpg"
    ["width"]=>
    int(640)
    ["height"]=>
    int(480)
  }
  ["maxres"]=>
  object(stdClass)#10 (3) {
    ["url"]=>
    string(52) "https://i.ytimg.com/vi/T0Jqdjbed40/maxresdefault.jpg"
    ["width"]=>
    int(1280)
    ["height"]=>
    int(720)
  }
}

* Not only that you need a key, you might be asked for billing information depending on the number of API requests you plan to make. However, few million requests per day are free.

Source article.

Reading From A Text File - Batch

Your code "for /f "tokens=* delims=" %%x in (a.txt) do echo %%x" will work on most Windows Operating Systems unless you have modified commands.

So you could instead "cd" into the directory to read from before executing the "for /f" command to follow out the string. For instance if the file "a.txt" is located at C:\documents and settings\%USERNAME%\desktop\a.txt then you'd use the following.

cd "C:\documents and settings\%USERNAME%\desktop"
for /f "tokens=* delims=" %%x in (a.txt) do echo %%x
echo.
echo.
echo.
pause >nul
exit

But since this doesn't work on your computer for x reason there is an easier and more efficient way of doing this. Using the "type" command.

@echo off
color a
cls
cd "C:\documents and settings\%USERNAME%\desktop"
type a.txt
echo.
echo.
pause >nul
exit

Or if you'd like them to select the file from which to write in the batch you could do the following.

@echo off
:A
color a
cls
echo Choose the file that you want to read.
echo.
echo.
tree
echo.
echo.
echo.
set file=
set /p file=File:
cls
echo Reading from %file%
echo.
type %file%
echo.
echo.
echo.
set re=
set /p re=Y/N?:
if %re%==Y goto :A
if %re%==y goto :A
exit

JavaScript sleep/wait before continuing

JS does not have a sleep function, it has setTimeout() or setInterval() functions.

If you can move the code that you need to run after the pause into the setTimeout() callback, you can do something like this:

//code before the pause
setTimeout(function(){
    //do what you need here
}, 2000);

see example here : http://jsfiddle.net/9LZQp/

This won't halt the execution of your script, but due to the fact that setTimeout() is an asynchronous function, this code

console.log("HELLO");
setTimeout(function(){
    console.log("THIS IS");
}, 2000);
console.log("DOG");

will print this in the console:

HELLO
DOG
THIS IS

(note that DOG is printed before THIS IS)


You can use the following code to simulate a sleep for short periods of time:

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

now, if you want to sleep for 1 second, just use:

sleep(1000);

example: http://jsfiddle.net/HrJku/1/

please note that this code will keep your script busy for n milliseconds. This will not only stop execution of Javascript on your page, but depending on the browser implementation, may possibly make the page completely unresponsive, and possibly make the entire browser unresponsive. In other words this is almost always the wrong thing to do.

Converting String to Int with Swift

I recently got the same issue. Below solution is work for me:

        let strValue = "123"
        let result = (strValue as NSString).integerValue

SQL query for finding records where count > 1

Try this query:

SELECT column_name
  FROM table_name
 GROUP BY column_name
HAVING COUNT(column_name) = 1;

Checking cin input stream produces an integer

You could use :

int a = 12;
if (a>0 || a<0){
cout << "Your text"<<endl;
}

I'm pretty sure it works.

How to overwrite files with Copy-Item in PowerShell

How about calling the .NET Framework methods?

You can do ANYTHING with them... :

[System.IO.File]::Copy($src, $dest, $true);

The $true argument makes it overwrite.

Temporarily switch working copy to a specific Git commit

If you are at a certain branch mybranch, just go ahead and git checkout commit_hash. Then you can return to your branch by git checkout mybranch. I had the same game bisecting a bug today :) Also, you should know about git bisect.

Failed to install Python Cryptography package with PIP and setup.py

I tried many solutions above, but only after the installation of the following lib I could install cryptography:

sudo apt install libssl1.0

I'm using Ubuntu 18.04, but it will work on Ubuntu 18.10 as well.

UPD: To solve this error on Ubuntu 20 I had to replace cryptography==1.9 with cryptography==2.1.1

What is the purpose of Node.js module.exports and how do you use it?

What is the purpose of a module system?

It accomplishes the following things:

  1. Keeps our files from bloating to really big sizes. Having files with e.g. 5000 lines of code in it are usually real hard to deal with during development.
  2. Enforces separation of concerns. Having our code split up into multiple files allows us to have appropriate file names for every file. This way we can easily identify what every module does and where to find it (assuming we made a logical directory structure which is still your responsibility).

Having modules makes it easier to find certain parts of code which makes our code more maintainable.

How does it work?

NodejS uses the CommomJS module system which works in the following manner:

  1. If a file wants to export something it has to declare it using module.export syntax
  2. If a file wants to import something it has to declare it using require('file') syntax

Example:

test1.js

const test2 = require('./test2');    // returns the module.exports object of a file

test2.Func1(); // logs func1
test2.Func2(); // logs func2

test2.js

module.exports.Func1 = () => {console.log('func1')};

exports.Func2 = () => {console.log('func2')};

Other useful things to know:

  1. Modules are getting cached. When you are loading the same module in 2 different files the module only has to be loaded once. The second time a require() is called on the same module the is pulled from the cache.
  2. Modules are loaded in synchronous. This behavior is required, if it was asynchronous we couldn't access the object retrieved from require() right away.

Phone Number Validation MVC

To display a phone number with (###) ###-#### format, you can create a new HtmlHelper.

Usage

@Html.DisplayForPhone(item.Phone)

HtmlHelper Extension

public static class HtmlHelperExtensions
{
    public static HtmlString DisplayForPhone(this HtmlHelper helper, string phone)
    {
        if (phone == null)
        {
            return new HtmlString(string.Empty);
        }
        string formatted = phone;
        if (phone.Length == 10)
        {
            formatted = $"({phone.Substring(0,3)}) {phone.Substring(3,3)}-{phone.Substring(6,4)}";
        }
        else if (phone.Length == 7)
        {
            formatted = $"{phone.Substring(0,3)}-{phone.Substring(3,4)}";
        }
        string s = $"<a href='tel:{phone}'>{formatted}</a>";
        return new HtmlString(s);
    }
}

How can I return to a parent activity correctly?

Although an old question, here is another (imho the cleanest and best) solution as all the previous answeres didn't work for me since I deeplinked Activity B from a Widget.

public void navigateUp() {
final Intent upIntent = NavUtils.getParentActivityIntent(this);
if (NavUtils.shouldUpRecreateTask(this, upIntent) || isTaskRoot()) {
    Log.v(logTag, "Recreate back stack");
        TaskStackBuilder.create(this).addNextIntentWithParentStack(upIntent).startActivities();
  } else {
    NavUtils.navigateUpTo(this, upIntent);
  }
}

[https://stackoverflow.com/a/31350642/570168 ]

But also see: https://speakerdeck.com/jgilfelt/this-way-up-implementing-effective-navigation-on-android

Show message box in case of exception

        try
        {
           // your code
        }
        catch (Exception w)
        {
            MessageDialog msgDialog = new MessageDialog(w.ToString());
        }

LINQ to SQL using GROUP BY and COUNT(DISTINCT)

There isn't direct support for COUNT(DISTINCT {x})), but you can simulate it from an IGrouping<,> (i.e. what group by returns); I'm afraid I only "do" C#, so you'll have to translate to VB...

 select new
 {
     Foo= grp.Key,
     Bar= grp.Select(x => x.SomeField).Distinct().Count()
 };

Here's a Northwind example:

    using(var ctx = new DataClasses1DataContext())
    {
        ctx.Log = Console.Out; // log TSQL to console
        var qry = from cust in ctx.Customers
                  where cust.CustomerID != ""
                  group cust by cust.Country
                  into grp
                  select new
                  {
                      Country = grp.Key,
                      Count = grp.Select(x => x.City).Distinct().Count()
                  };

        foreach(var row in qry.OrderBy(x=>x.Country))
        {
            Console.WriteLine("{0}: {1}", row.Country, row.Count);
        }
    }

The TSQL isn't quite what we'd like, but it does the job:

SELECT [t1].[Country], (
    SELECT COUNT(*)
    FROM (
        SELECT DISTINCT [t2].[City]
        FROM [dbo].[Customers] AS [t2]
        WHERE ((([t1].[Country] IS NULL) AND ([t2].[Country] IS NULL)) OR (([t1]
.[Country] IS NOT NULL) AND ([t2].[Country] IS NOT NULL) AND ([t1].[Country] = [
t2].[Country]))) AND ([t2].[CustomerID] <> @p0)
        ) AS [t3]
    ) AS [Count]
FROM (
    SELECT [t0].[Country]
    FROM [dbo].[Customers] AS [t0]
    WHERE [t0].[CustomerID] <> @p0
    GROUP BY [t0].[Country]
    ) AS [t1]
-- @p0: Input NVarChar (Size = 0; Prec = 0; Scale = 0) []
-- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 3.5.30729.1

The results, however, are correct- verifyable by running it manually:

        const string sql = @"
SELECT c.Country, COUNT(DISTINCT c.City) AS [Count]
FROM Customers c
WHERE c.CustomerID != ''
GROUP BY c.Country
ORDER BY c.Country";
        var qry2 = ctx.ExecuteQuery<QueryResult>(sql);
        foreach(var row in qry2)
        {
            Console.WriteLine("{0}: {1}", row.Country, row.Count);
        }

With definition:

class QueryResult
{
    public string Country { get; set; }
    public int Count { get; set; }
}

java.lang.NoClassDefFoundError: org/hamcrest/SelfDescribing

If this problem arise in a RCP project it can be because JUnit has been explicitly imported.

Check the editor for your plugin.xml under Dependencies tab, remove the org.junit from the Imported Packages and add org.junit to the Required Plug-ins.

Specifying onClick event type with Typescript and React.Konva

React.MouseEvent works for me:

private onClick = (e: React.MouseEvent<HTMLInputElement>) => {
  let button = e.target as HTMLInputElement;
}

Listing only directories using ls in Bash?

file * | grep directory

Output (on my machine) --

[root@rhel6 ~]# file * | grep directory
mongo-example-master:    directory
nostarch:                directory
scriptzz:                directory
splunk:                  directory
testdir:                 directory

The above output can be refined more by using cut:

file * | grep directory | cut -d':' -f1
mongo-example-master
nostarch
scriptzz
splunk
testdir

* could be replaced with any path that's permitted
 file - determine file type
 grep - searches for string named directory
 -d - to specify a field delimiter
 -f1 - denotes field 1

How to add an extra language input to Android?

Sliding the space bar only works if you gave more then one input language selected.

In that case the space bar will also indicate the selected language and show arrows to indicate Sliding will change selection.

This is easy fast and changes the dictionary at the same time.

First response seems the mist accurate.

Regards

Install shows error in console: INSTALL FAILED CONFLICTING PROVIDER

Encountered this issue.

Resolved it by:

1 - open AndroidManifest.xml

2 - ctrl+f find "provider"

3 - find provider and update your root directory name there.

run project. hopefully issue will be fixed!

I need to convert an int variable to double

Either use casting as others have already said, or multiply one of the int variables by 1.0:

double firstSolution = ((1.0* b1 * a22 - b2 * a12) / (a11 * a22 - a12 * a21));

What does '--set-upstream' do?

When you push to a remote and you use the --set-upstream flag git sets the branch you are pushing to as the remote tracking branch of the branch you are pushing.

Adding a remote tracking branch means that git then knows what you want to do when you git fetch, git pull or git push in future. It assumes that you want to keep the local branch and the remote branch it is tracking in sync and does the appropriate thing to achieve this.

You could achieve the same thing with git branch --set-upstream-to or git checkout --track. See the git help pages on tracking branches for more information.

Collision Detection between two images in Java

Here's the main class from my collision detection program.
You can see it run at: http://www.youtube.com/watch?v=JIXhCvXgjsQ

/**
 *
 * @author Tyler Griffin
 */
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.GraphicsDevice.*;
import java.util.ArrayList;
import java.awt.Graphics;
import java.awt.geom.Line2D;


public class collision extends JFrame implements KeyListener, MouseMotionListener, MouseListener
{
    ArrayList everything=new ArrayList<tile>();

    int time=0, x, y, width, height, up=0, down=0, left=0, right=0, mouse1=0, mouse2=0;
    int mouseX, mouseY;

    GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment();
    GraphicsDevice screen = environment.getDefaultScreenDevice();
    DisplayMode displayMode = screen.getDisplayMode();

    //private BufferStrategy strategy;

    JLayeredPane pane = new JLayeredPane();

     tile Tile;
     circle Circle;
     rectangle Rectangle;

         textPane text;

    public collision()
    {
        setUndecorated(screen.isFullScreenSupported());
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
        setLayout(null);
        setResizable(false);
        screen.setFullScreenWindow(this);


        width=displayMode.getWidth();
        height=displayMode.getHeight();


          Circle=new circle(-(int)Math.round((double)height/7*2),-(int)Math.round((double)height/7*2),(int)Math.round((double)height/7*.85),this);
          Rectangle=new rectangle(-(int)Math.round((double)height/7*1.5),-(int)Math.round((double)height/7*1.5),(int)Math.round((double)height/7*1.5),(int)Math.round((double)height/7*1.5),this);
          Tile=Circle;
          Tile.move(mouseX-Tile.width/2, mouseY-Tile.height/2);
                  text=new textPane(0,0,width,height,this);

          everything.add(new circle((int)Math.round((double)width/100*75),(int)Math.round((double)height/100*15),(int)Math.round((double)width/100*10),this));
                  everything.add(new rectangle((int)Math.round((double)width/100*70),(int)Math.round((double)height/100*60),(int)Math.round((double)width/100*20),(int)Math.round((double)height/100*20),this));
                  //everything.add(new line(750,250,750,750,this));
                  /*everything.add(new line(width/700*419,height/700*68,width/700*495,height/700*345,this));
                  everything.add(new line(width/700*495,height/700*345,width/700*749,height/700*350,this));
                  everything.add(new line(width/700*749,height/700*350,width/700*549,height/700*519,this));
                  everything.add(new line(width/700*549,height/700*519,width/700*624,height/700*800,this));
                  everything.add(new line(width/700*624,height/700*800,width/700*419,height/700*638,this));
                  everything.add(new line(width/700*419,height/700*638,width/700*203,height/700*800,this));
                  everything.add(new line(width/700*203,height/700*800,width/700*279,height/700*519,this));
                  everything.add(new line(width/700*279,height/700*519,width/700*76,height/700*350,this));
                  everything.add(new line(width/700*76,height/700*350,width/700*333,height/700*345,this));
                  everything.add(new line(width/700*333,height/700*345,width/700*419,height/700*68,this));

                  everything.add(new line(width/950*419,height/700*68,width/950*624,height/700*800,this));
                  everything.add(new line(width/950*419,height/700*68,width/950*203,height/700*800,this));
                  everything.add(new line(width/950*76,height/700*350,width/950*624,height/700*800,this));
                  everything.add(new line(width/950*203,height/700*800,width/950*749,height/700*350,this));
                  everything.add(new rectangle(width/950*76,height/700*350,width/950*673,1,this));*/

                  everything.add(new line((int)Math.round((double)width/1350*419),(int)Math.round((double)height/1000*68),(int)Math.round((double)width/1350*624),(int)Math.round((double)height/1000*800),this));
                  everything.add(new line((int)Math.round((double)width/1350*419),(int)Math.round((double)height/1000*68),(int)Math.round((double)width/1350*203),(int)Math.round((double)height/1000*800),this));
                  everything.add(new line((int)Math.round((double)width/1350*76),(int)Math.round((double)height/1000*350),(int)Math.round((double)width/1350*624),(int)Math.round((double)height/1000*800),this));
                  everything.add(new line((int)Math.round((double)width/1350*203),(int)Math.round((double)height/1000*800),(int)Math.round((double)width/1350*749),(int)Math.round((double)height/1000*350),this));
                  everything.add(new rectangle((int)Math.round((double)width/1350*76),(int)Math.round((double)height/1000*350),(int)Math.round((double)width/1350*673),1,this));


        addKeyListener(this);
        addMouseMotionListener(this);
        addMouseListener(this);
    }

    public void keyReleased(KeyEvent e)
    {
        Object source=e.getSource();

        int released=e.getKeyCode();

        if (released==KeyEvent.VK_A){left=0;}
        if (released==KeyEvent.VK_W){up=0;}
        if (released==KeyEvent.VK_D){right=0;}
        if (released==KeyEvent.VK_S){down=0;}
    }//end keyReleased


    public void keyPressed(KeyEvent e)
    {
        Object source=e.getSource();

        int pressed=e.getKeyCode();

        if (pressed==KeyEvent.VK_A){left=1;}
        if (pressed==KeyEvent.VK_W){up=1;}
        if (pressed==KeyEvent.VK_D){right=1;}
        if (pressed==KeyEvent.VK_S){down=1;}

        if (pressed==KeyEvent.VK_PAUSE&&pressed==KeyEvent.VK_P)
        {
            //if (paused==0){paused=1;}
            //else paused=0;
        }
    }//end keyPressed

    public void keyTyped(KeyEvent e){}

//***********************************************************************************************

    public void mouseDragged(MouseEvent e)
    {
        mouseX=(e.getX());
        mouseY=(e.getY());

          //run();
    }

    public void mouseMoved(MouseEvent e)
    {
        mouseX=(e.getX());
        mouseY=(e.getY());

          //run();
    }

//***********************************************************************************************

    public void mousePressed(MouseEvent e)
    {
        if(e.getX()==0 && e.getY()==0){System.exit(0);}

    mouseX=(e.getX()+x);
        mouseY=(e.getY()+y);

        if(Tile instanceof circle)
        {
                Circle.move(0-Circle.width, 0-Circle.height);
                Circle.setBounds(Circle.x, Circle.y, Circle.width, Circle.height);
                Tile=Rectangle;
        }
        else
        {
                Rectangle.move(0-Rectangle.width, 0-Rectangle.height);
                Rectangle.setBounds(Rectangle.x, Rectangle.y, Rectangle.width, Rectangle.height);
                Tile=Circle;
        }

        Tile.move(mouseX-Tile.width/2, mouseY-Tile.height/2);
    }

    public void mouseReleased(MouseEvent e)
    {
         //run();
    }

    public void mouseEntered(MouseEvent e){}
    public void mouseExited(MouseEvent e){}

    public void mouseClicked(MouseEvent e){}

//***********************************************************************************************

    public void run()//run collision detection
    {
        while (this == this)
        {
            Tile.move(Tile.x + ((mouseX - (Tile.x + (Tile.width / 2))) / 10), Tile.y + ((mouseY - (Tile.y + (Tile.height / 2))) / 10));
            //Tile.move((mouseX - Tile.width / 2), mouseY - (Tile.height / 2));

            for (int i = 0; i < everything.size(); i++)
            {
                tile Temp = (tile) everything.get(i);

                if (Temp.x < (Tile.x + Tile.width) && (Temp.x + Temp.width) > Tile.x && Temp.y < (Tile.y + Tile.height) && (Temp.y + Temp.height) > Tile.y)//rectangles collided
                {
                    if (Temp instanceof rectangle)
                    {
                        if (Tile instanceof rectangle){rectangleRectangle(Temp);}
                        else {circleRectangle(Temp);}//Tile instanceof circle
                    }
                    else
                    {
                        if (Temp instanceof circle)
                        {
                            if (Tile instanceof rectangle) {rectangleCircle(Temp);}
                            else {circleCircle(Temp);}
                        }
                        else//line
                        {
                            if (Tile instanceof rectangle){rectangleLine(Temp);}
                            else{circleLine(Temp);}
                        }
                    }
                }//end if
            }//end for

            try {Thread.sleep(16L);}
            catch (Exception e) {}

            Tile.setBounds(Tile.x, Tile.y, Tile.width, Tile.height);
            //Rectangle.setBounds(x, y, width, height);
            //Circle.setBounds(x, y, width, height);
            repaint();

            text.out=" ";
        }//end while loop
    }//end run

//***************************************special collision detection/handling functions************************************************

    void rectangleRectangle(tile Temp)
    {
        int lapTop, lapBot, lapLeft, lapRight, small, scootX=0, scootY=0;

        lapTop=(Temp.y+Temp.height)-Tile.y;
        lapBot=(Tile.y+Tile.height)-Temp.y;
        lapLeft=(Temp.x+Temp.width)-Tile.x;
        lapRight=(Tile.x+Tile.width)-Temp.x;

        small=999999999;

        if (lapTop<small){small=lapTop; scootX=0; scootY=lapTop;}
        if (lapBot<small){small=lapBot; scootX=0; scootY=lapBot*-1;}
                if (lapLeft<small){small=lapLeft; scootX=lapLeft; scootY=0;}
                if (lapRight<small){small=lapRight; scootX=lapRight*-1; scootY=0;}

        Tile.move(Tile.x+scootX, Tile.y+scootY);text.out="collision detected!";
    }



    void circleRectangle(tile Temp)
    {
        if((Tile.x+Tile.width/2<=Temp.x+Temp.width && Tile.x+Tile.width/2>=Temp.x)||(Tile.y+Tile.height/2>=Temp.y && Tile.y+Tile.height/2<=Temp.y+Temp.height))
        {
            rectangleRectangle(Temp);
        }
        else//push from nearest corner
        {
            int x,y;
            if(Tile.x+Tile.width/2>Temp.x+Temp.width && Tile.y+Tile.height/2<Temp.y){x=Temp.x+Temp.width; y=Temp.y;}
            else if(Tile.x+Tile.width/2<Temp.x && Tile.y+Tile.height/2<Temp.y){x=Temp.x; y=Temp.y;}
            else if(Tile.x+Tile.width/2>Temp.x+Temp.width && Tile.y+Tile.height/2>Temp.y+Temp.height){x=Temp.x+Temp.width; y=Temp.y+Temp.height;}
            else {x=Temp.x; y=Temp.y+Temp.height;}

            double distance = Math.sqrt(Math.pow(Tile.x+(Tile.width/2) - x, 2) + Math.pow(Tile.y+(Tile.height/2) - y, 2));

            if((int)Math.round(distance)<Tile.height/2)
            {
                             double normY = ((Tile.y+(Tile.height/2) - y) / distance);
                             double normX = ((Tile.x+(Tile.width/2) - x) / distance);

                            Tile.move(x-Tile.width/2+(int)Math.round(normX*((Tile.width/2))) , y-Tile.height/2+(int)Math.round(normY*((Tile.height/2))));text.out="collision detected!";
            }
        }
    }



    void rectangleCircle(tile Temp)
    {
        if((Temp.x+Temp.width/2<=Tile.x+Tile.width && Temp.x+Temp.width/2>=Tile.x)||(Temp.y+Temp.height/2>=Tile.y && Temp.y+Temp.height/2<=Tile.y+Tile.height))
        {
            rectangleRectangle(Temp);
        }
        else//push from nearest corner
        {
            int x,y;
            if(Temp.x+Temp.width/2>Tile.x+Tile.width && Temp.y+Temp.height/2<Tile.y){x=Tile.x+Tile.width; y=Tile.y;}
            else if(Temp.x+Temp.width/2<Tile.x && Temp.y+Temp.height/2<Tile.y){x=Tile.x; y=Tile.y;}
            else if(Temp.x+Temp.width/2>Tile.x+Tile.width && Temp.y+Temp.height/2>Tile.y+Tile.height){x=Tile.x+Tile.width; y=Tile.y+Tile.height;}
            else {x=Tile.x; y=Tile.y+Tile.height;}

            double distance = Math.sqrt(Math.pow(Temp.x+(Temp.width/2) - x, 2) + Math.pow(Temp.y+(Temp.height/2) - y, 2));

            if((int)Math.round(distance)<Temp.height/2)
            {
             double normY = ((Temp.y+(Temp.height/2) - y) / distance);
             double normX = ((Temp.x+(Temp.width/2) - x) / distance);

             if(Temp.x+Temp.width/2>Tile.x+Tile.width && Temp.y+Temp.height/2<Tile.y){Tile.move((Temp.x+Temp.width/2)-(int)Math.round(normX*((Temp.width/2)))-Tile.width,(Temp.y+Temp.height/2)-(int)Math.round(normY*((Temp.height/2))));text.out="collision detected!";}
                else if(Temp.x+Temp.width/2<Tile.x && Temp.y+Temp.height/2<Tile.y){Tile.move((Temp.x+Temp.width/2)-(int)Math.round(normX*((Temp.width/2))),(Temp.y+Temp.height/2)-(int)Math.round(normY*((Temp.height/2))));text.out="collision detected!";}
                else if(Temp.x+Temp.width/2>Tile.x+Tile.width && Temp.y+Temp.height/2>Tile.y+Tile.height){Tile.move((Temp.x+Temp.width/2)-(int)Math.round(normX*((Temp.width/2)))-Tile.width,(Temp.y+Temp.height/2)-(int)Math.round(normY*((Temp.height/2)))-Tile.height);text.out="collision detected!";}
                else {Tile.move((Temp.x+Temp.width/2)-(int)Math.round(normX*((Temp.width/2))),(Temp.y+Temp.height/2)-(int)Math.round(normY*((Temp.height/2)))-Tile.height);text.out="collision detected!";}
            }
        }
    }




    void circleCircle(tile Temp)
    {
        double distance = Math.sqrt(Math.pow((Tile.x+(Tile.width/2)) - (Temp.x+(Temp.width/2)),2) + Math.pow((Tile.y+(Tile.height/2)) - (Temp.y+(Temp.height/2)), 2));

        if((int)distance<(Tile.width/2+Temp.width/2))
        {
                        double normX = ((Tile.x+(Tile.width/2)) - (Temp.x+(Temp.width/2))) / distance;
                        double normY = ((Tile.y+(Tile.height/2)) - (Temp.y+(Temp.height/2))) / distance;

            Tile.move((Temp.x+(Temp.width/2))+(int)Math.round(normX*(Tile.width/2+Temp.width/2))-(Tile.width/2) , (Temp.y+(Temp.height/2))+(int)Math.round(normY*(Tile.height/2+Temp.height/2))-(Tile.height/2));text.out="collision detected!";
        }
    }



    void circleLine(tile Temp)
    {
            line Line=(line)Temp;

            if (Line.x1 < (Tile.x + Tile.width) && (Line.x1) > Tile.x && Line.y1 < (Tile.y + Tile.height) && Line.y1 > Tile.y)//circle may be hitting one of the end points
            {
                rectangle rec=new rectangle(Line.x1, Line.y1, 1, 1, this);
                circleRectangle(rec);
                remove(rec);
            }

            if (Line.x2 < (Tile.x + Tile.width) && (Line.x2) > Tile.x && Line.y2 < (Tile.y + Tile.height) && Line.y2 > Tile.y)//circle may be hitting one of the end points
            {
                rectangle rec=new rectangle(Line.x2, Line.y2, 1, 1, this);
                circleRectangle(rec);
                remove(rec);
            }


            int x1=0, y1=0, x2=Tile.x+(Tile.width/2), y2=Tile.y+(Tile.height/2);

            x1=Tile.x+(Tile.width/2)-Line.height;//(int)Math.round(Line.xNorm*1000);
            x2=Tile.x+(Tile.width/2)+Line.height;
            if(Line.posSlope)
            {
                y1=Tile.y+(Tile.height/2)-Line.width;
                y2=Tile.y+(Tile.height/2)+Line.width;
            }
            else
            {
                y1=Tile.y+(Tile.height/2)+Line.width;
                y2=Tile.y+(Tile.height/2)-Line.width;
            }

            Point point=intersection((double)x1,(double)y1,(double)x2,(double)y2,(double)Line.x1,(double)Line.y1,(double)Line.x2,(double)Line.y2);//find intersection

            if (point.x < (Line.x + Line.width) && point.x > Line.x && point.y < (Line.y + Line.height) && point.y > Line.y)//line intersects within line segment
            {
                //if(point!=null){System.out.println(point.x+","+point.y);}
                double distance = Math.sqrt(Math.pow((Tile.x+(Tile.width/2)) - point.x,2) + Math.pow((Tile.y+(Tile.width/2)) - point.y, 2));

                if((int)distance<Tile.width/2)
                {
                    //System.out.println("hit");
                    double normX = ((Tile.x+(Tile.width/2)) - point.x) / distance;
                    double normY = ((Tile.y+(Tile.height/2)) - point.y) / distance;

                    Tile.move((point.x)+(int)Math.round(normX*(Tile.width/2))-(Tile.width/2) , (point.y)+(int)Math.round(normY*(Tile.height/2))-(Tile.height/2));text.out="collision detected!";
                    //System.out.println(point.x+","+point.y);
                }
            }

            //new bullet(this, (int)Math.round(tryX), (int)Math.round(tryY));
    }

        void rectangleLine(tile Temp)
    {
            line Line=(line)Temp;
            if(new Line2D.Double(Line.x1,Line.y1,Line.x2,Line.y2).intersects(new Rectangle(Tile.x,Tile.y,Tile.width,Tile.height)))
            {
                if (Line.x1 < (Tile.x + Tile.width) && (Line.x1) > Tile.x && Line.y1 < (Tile.y + Tile.height) && Line.y1 > Tile.y)//circle may be hitting one of the end points
                {
                    rectangle rec=new rectangle(Line.x1, Line.y1, 1, 1, this);
                    rectangleRectangle(rec);
                    remove(rec);
                }

                if (Line.x2 < (Tile.x + Tile.width) && (Line.x2) > Tile.x && Line.y2 < (Tile.y + Tile.height) && Line.y2 > Tile.y)//circle may be hitting one of the end points
                {
                    rectangle rec=new rectangle(Line.x2, Line.y2, 1, 1, this);
                    rectangleRectangle(rec);
                    remove(rec);
                }

                if(Line.posSlope)//positive sloped line
                {
                    //first we'll do the top left corner
                    int x1=Tile.x-Line.height;
                    int x2=Tile.x+Line.height;
                    int y1=Tile.y-Line.width;
                    int y2=Tile.y+Line.width;
                    Point topPoint=new Point(-99,-99), botPoint=new Point(-99,-99);
                    double topDistance=0, botDistance=0;

                    topPoint=intersection((double)x1,(double)y1,(double)x2,(double)y2,(double)Line.x1,(double)Line.y1,(double)Line.x2,(double)Line.y2);//find intersection

                    topDistance = Math.sqrt(Math.pow(Tile.x - topPoint.x,2) + Math.pow(Tile.y - topPoint.y, 2));

                    //new let's do the bottom right corner
                    x1=Tile.x+Tile.width-Line.height;
                    x2=Tile.x+Tile.width+Line.height;
                    y1=Tile.y+Tile.height-Line.width;
                    y2=Tile.y+Tile.height+Line.width;

                    botPoint=intersection((double)x1,(double)y1,(double)x2,(double)y2,(double)Line.x1,(double)Line.y1,(double)Line.x2,(double)Line.y2);//find intersection

                    botDistance = Math.sqrt(Math.pow((Tile.x+Tile.width) - botPoint.x,2) + Math.pow((Tile.y+Tile.height) - botPoint.y, 2));


                    if(topDistance<botDistance)
                    {
                        if(new Rectangle(Tile.x,Tile.y,Tile.width,Tile.height).contains(topPoint) && new Rectangle(Line.x,Line.y,Line.width,Line.height).contains(topPoint))
                        {
                            Tile.move(topPoint.x,topPoint.y);text.out="collision detected!";
                        }
                    }
                    else
                    {
                        if(new Rectangle(Tile.x,Tile.y,Tile.width,Tile.height).contains(botPoint) && new Rectangle(Line.x,Line.y,Line.width,Line.height).contains(botPoint))
                        {
                            Tile.move(botPoint.x-Tile.width,botPoint.y-Tile.height);text.out="collision detected!";
                        }
                    }
                }
                else//negative sloped lne
                {
                    //first we'll do the top right corner
                    int x1=Tile.x+Tile.width-Line.height;
                    int x2=Tile.x+Tile.width+Line.height;
                    int y1=Tile.y+Line.width;
                    int y2=Tile.y-Line.width;
                    Point topPoint=new Point(-99,-99), botPoint=new Point(-99,-99);
                    double topDistance=0, botDistance=0;

                    topPoint=intersection((double)x1,(double)y1,(double)x2,(double)y2,(double)Line.x1,(double)Line.y1,(double)Line.x2,(double)Line.y2);//find intersection

                    topDistance = Math.sqrt(Math.pow(Tile.x + Tile.width - topPoint.x,2) + Math.pow(Tile.y - topPoint.y, 2));

                    //new let's do the bottom left corner
                    x1=Tile.x-Line.height;
                    x2=Tile.x+Line.height;
                    y1=Tile.y+Tile.height+Line.width;
                    y2=Tile.y+Tile.height-Line.width;

                    botPoint=intersection((double)x1,(double)y1,(double)x2,(double)y2,(double)Line.x1,(double)Line.y1,(double)Line.x2,(double)Line.y2);//find intersection

                    botDistance = Math.sqrt(Math.pow(Tile.x - botPoint.x,2) + Math.pow((Tile.y+Tile.height) - botPoint.y, 2));


                    if(topDistance<botDistance)
                    {
                        if(new Rectangle(Tile.x,Tile.y,Tile.width,Tile.height).contains(topPoint) && new Rectangle(Line.x,Line.y,Line.width,Line.height).contains(topPoint))
                        {
                            Tile.move(topPoint.x-Tile.width,topPoint.y);text.out="collision detected!";
                        }
                    }
                    else
                    {
                        if(new Rectangle(Tile.x,Tile.y,Tile.width,Tile.height).contains(botPoint) && new Rectangle(Line.x,Line.y,Line.width,Line.height).contains(botPoint))
                        {
                            Tile.move(botPoint.x,botPoint.y-Tile.height);text.out="collision detected!";
                        }
                    }
                }
            }
    }

       public Point intersection(double x1, double y1, double x2, double y2,double x3, double y3, double x4, double y4)//I didn't write this. got it from http://www.ahristov.com/tutorial/geometry-games/intersection-lines.html (I altered it)
       {
            double d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);

            double xi = ((x3 - x4) * (x1 * y2 - y1 * x2) - (x1 - x2) * (x3 * y4 - y3 * x4)) / d;
            double yi = ((y3 - y4) * (x1 * y2 - y1 * x2) - (y1 - y2) * (x3 * y4 - y3 * x4)) / d;

            int x=(int)Math.round(xi);
            int y=(int)Math.round(yi);

            return new Point(x, y);
        }

//***************************************************************************************

    public static void main(String[] args)
    {
        final collision Collision=new collision();
          Collision.run();
    }//end main
}//end class

Internal vs. Private Access Modifiers

internal is for assembly scope (i.e. only accessible from code in the same .exe or .dll)

private is for class scope (i.e. accessible only from code in the same class).

using stored procedure in entity framework

After importing stored procedure, you can create object of stored procedure pass the parameter like function

using (var entity = new FunctionsContext())
{
   var DBdata = entity.GetFunctionByID(5).ToList<Functions>();
}

or you can also use SqlQuery

using (var entity = new FunctionsContext())
{
    var Parameter = new SqlParameter {
                     ParameterName = "FunctionId",
                     Value = 5
            };

    var DBdata = entity.Database.SqlQuery<Course>("exec GetFunctionByID @FunctionId ", Parameter).ToList<Functions>();
}

set date in input type date

Update: I'm doing this with date.toISOString().substr(0, 10). Gives the same result as the accepted answer and has good support.

What is an unhandled promise rejection?

"DeprecationWarning: Unhandled promise rejections are deprecated"

TLDR: A promise has resolve and reject, doing a reject without a catch to handle it is deprecated, so you will have to at least have a catch at top level.

jQuery if statement, syntax

You can wrap jQuery calls inside normal JavaScript code. So, for example:

$(document).ready(function() {
    if (someCondition && someOtherCondition) {
        // Make some jQuery call.
    }
});

mailto link multiple body lines

This is what I do, just add \n and use encodeURIComponent

Example

var emailBody = "1st line.\n 2nd line \n 3rd line";

emailBody = encodeURIComponent(emailBody);

href = "mailto:[email protected]?body=" + emailBody;

Check encodeURIComponent docs

How to git ignore subfolders / subdirectories?

All the above answers are valid, but something that I don't think is mentioned is that once you add a file from that directory into the repo, you can't ignore that directory/subdirectory that contains that file (git will ignore that directive).

To ignore already added files run

$ git rm --cached

Otherwise you'll have to remove all files from the repo's target directory first - and then you can ignore that folder.

using BETWEEN in WHERE condition

I think we can write like this : $this->db->where('accommodation >=', minvalue); $this->db->where('accommodation <=', maxvalue);

//without dollar($) sign It's work for me :)

Site does not exist error for a2ensite

I have just upgraded the Ubuntu Server version from 12.04 LTS to 14.04 LTS.

Indeed, as said above, the .conf extension to Apache 2.4.x is needed to the websites vhost files that resides on sites-available directory.

Before read this question I did not have a clue what was going on with the server.

Pretty nice solution.

Just summarizing I did the following steps on Terminal:

1) Access sites-enabled folder

$ cd /etc/apache2/sites-enabled

2) Because the command a2dissite will not work with deprecated files (without .conf) remove the old website files that was published

$ sudo rm <my-old-website-without-.conf>

3) Rename the website vhost files changing its extension adding .conf to the end

$ sudo mv /etc/apache2/sites-available/mywebsite /etc/apache2/sites-available/mywebsite.conf

4) Republish the new and correct vhost file

$ sudo a2ensite mywebsite.conf

5) Check the website on browser and have fun! :)

Error: TypeError: $(...).dialog is not a function

if some reason two versions of jQuery are loaded (which is not recommended), calling $.noConflict(true) from the second version will return the globally scoped jQuery variables to those of the first version.

Some times it could be issue with older version (or not stable version) of JQuery files

Solution use $.noConflict();

<script src="other_lib.js"></script>
<script src="jquery.js"></script>
<script>
$.noConflict();
jQuery( document ).ready(function( $ ) {
   $("#opener").click(function() {
            $("#dialog1").dialog('open');
    });
});
// Code that uses other library's $ can follow here.
</script>

Variable declaration in a header file

The key is to keep the declarations of the variable in the header file and source file the same.

I use this trick

------sample.c------
#define sample_c
#include sample.h

(rest of sample .c)

------sample.h------
#ifdef sample_c
#define EXTERN
#else
#define EXTERN extern
#endif

EXTERN int x;

Sample.c is only compiled once and it defines the variables. Any file that includes sample.h is only given the "extern" of the variable; it does allocate space for that variable.

When you change the type of x, it will change for everybody. You won't need to remember to change it in the source file and the header file.

Video format or MIME type is not supported

FIXED IT!

I was losing my mind over this one. Reset firefox, tried safe mode, removed plugins, debugged using developers tools. All were to no avail and didn't get me any further with getting my online videos back to normal viewing condition. This however did the trick perfectly.

Within Firefox or whatever flavor of Firefox you have(CyberFox being my favorite choice here), simply browse to https://get.adobe.com/flashplayer/

VERIFY FIRST that the website detected you're using FireFox and has set your download for the flash player to be for Firefox.

Don't just click download. PLEASE PLEASE PLEASE SAVE YOURSELF the migraine and ALWAYS make sure that the middle section labeled "Optional offer:" is absolutely NOT CHECKED, it will be checked by default so always UNCHECK it before proceeding to download.

After it's finished downloading, close out of Firefox. Run the downloaded setup file As Administrator. It takes only a few seconds or so to complete, so after it's done, open up Firefox again and try viewing anything that was previously throwing this error. Should be back to normal now.

Enjoy!

How to achieve ripple animation using support library?

Basic ripple setup

  • Ripples contained within the view.
    android:background="?selectableItemBackground"

  • Ripples that extend beyond the view's bounds:
    android:background="?selectableItemBackgroundBorderless"

    Have a look here for resolving ?(attr) xml references in Java code.

Support Library

  • Using ?attr: (or the ? shorthand) instead of ?android:attr references the support library, so is available back to API 7.

Ripples with images/backgrounds

  • To have a image or background and overlaying ripple the easiest solution is to wrap the View in a FrameLayout with the ripple set with setForeground() or setBackground().

Honestly there is no clean way of doing this otherwise.

How to check if a user is logged in (how to properly use user.is_authenticated)?

In your view:

{% if user.is_authenticated %}
<p>{{ user }}</p>
{% endif %}

In you controller functions add decorator:

from django.contrib.auth.decorators import login_required
@login_required
def privateFunction(request):

Controlling execution order of unit tests in Visual Studio

As you should know by now, purists say it's forbiden to run ordered tests. That might be true for unit tests. MSTest and other Unit Test frameworks are used to run pure unit test but also UI tests, full integration tests, you name it. Maybe we shouldn't call them Unit Test frameworks, or maybe we should and use them according to our needs. That's what most people do anyway.

I'm running VS2015 and I MUST run tests in a given order because I'm running UI tests (Selenium).

Priority - Doesn't do anything at all This attribute is not used by the test system. It is provided to the user for custom purposes.

orderedtest - it works but I don't recommend it because:

  1. An orderedtest a text file that lists your tests in the order they should be executed. If you change a method name, you must fix the file.
  2. The test execution order is respected inside a class. You can't order which class executes its tests first.
  3. An orderedtest file is bound to a configuration, either Debug or Release
  4. You can have several orderedtest files but a given method can not be repeated in different orderedtest files. So you can't have one orderedtest file for Debug and another for Release.

Other suggestions in this thread are interesting but you loose the ability to follow the test progress on Test Explorer.

You are left with the solution that purist will advise against, but in fact is the solution that works: sort by declaration order.

The MSTest executor uses an interop that manages to get the declaration order and this trick will work until Microsoft changes the test executor code.

This means the test method that is declared in the first place executes before the one that is declared in second place, etc.

To make your life easier, the declaration order should match the alphabetical order that is is shown in the Test Explorer.

  • A010_FirstTest
  • A020_SecondTest
  • etc
  • A100_TenthTest

I strongly suggest some old and tested rules:

  • use a step of 10 because you will need to insert a test method later on
  • avoid the need to renumber your tests by using a generous step between test numbers
  • use 3 digits to number your tests if you are running more than 10 tests
  • use 4 digits to number your tests if you are running more than 100 tests

VERY IMPORTANT

In order to execute the tests by the declaration order, you must use Run All in the Test Explorer.

Say you have 3 test classes (in my case tests for Chrome, Firefox and Edge). If you select a given class and right click Run Selected Tests it usually starts by executing the method declared in the last place.

Again, as I said before, declared order and listed order should match or else you'll in big trouble in no time.

How to print out more than 20 items (documents) in MongoDB's shell?

You can use it inside of the shell to iterate over the next 20 results. Just type it if you see "has more" and you will see the next 20 items.

How to give environmental variable path for file appender in configuration file in log4j

This syntax is documented only in log4j 2.X so make sure you are using the correct version.

    <Appenders>
    <File name="file" fileName="${env:LOG_PATH}">
        <PatternLayout>
            <Pattern>%d %p %c{1.} [%t] %m %ex%n</Pattern>
        </PatternLayout>
    </File>
</Appenders>

http://logging.apache.org/log4j/2.x/manual/lookups.html#EnvironmentLookup

Why do we assign a parent reference to the child object in Java?

It's simple.

Parent parent = new Child();

In this case the type of the object is Parent. Ant Parent has only one properties. It's name.

Child child = new Child();

And in this case the type of the object is Child. Ant Child has two properties. They're name and salary.

The fact is that there's no need to initialize non-final field immediately at the declaration. Usually this’s done at run-time because often you cannot know exactly what exactly implementation will you need. For example imagine that you have a class hierarchy with class Transport at the head. And three subclasses: Car, Helicopter and Boat. And there's another class Tour which has field Transport. That is:

class Tour {
   Transport transport;
}  

As long as an user hasn't booked a trip and hasn't chosen a particular type of transport you can't initialize this field. It's first.

Second, assume that all of these classes must have a method go() but with a different implementation. You can define a basic implementation by default in the superclass Transport and own unique implementations in each subclass. With this initialization Transport tran; tran = new Car(); you can call the method tran.go() and get result without worrying about specific implementation. It’ll call overrided method from particular subclass.

Moreover you can use instance of subclass everywhere where instance of superclass is used. For example you want provide opportunity to rent your transport. If you don't use polymorphism, you have to write a lot of methods for each case: rentCar(Car car), rentBoat(Boat boat) and so forth. At the same time polymorphism allows you to create one universal method rent(Transport transport). You can pass in it object of any subclass of Transport. In addition, if over time your logic will increase up and you'll need to create another class in the hierarchy? When using polymorphism you don't need to change anything. Just extend class Transport and pass your new class into the method:

public class Airplane extends Transport {
    //implementation
}

and rent(new Airplane()). And new Airplane().go() in second case.

IIS7 deployment - duplicate 'system.web.extensions/scripting/scriptResourceHandler' section

In my case it happened after I converted the whole solution (using an extension called Target Framework Migrator) to 4.6.2 but ended up undoing the changes and going back to 3.5 (solution is versioned by TFS). To solve this, I converted just the problematic project (which was using IIS Express to run) to 4.6.2 and then back to 3.5.

Get attribute name value of <input>

You need to write a selector which selects the correct <input> first. Ideally you use the element's ID $('#element_id'), failing that the ID of it's container $('#container_id input'), or the element's class $('input.class_name').

Your element has none of these and no context, so it's hard to tell you how to select it.

Once you have figured out the proper selector, you'd use the attr method to access the element's attributes. To get the name, you'd use $(selector).attr('name') which would return (in your example) 'xxxxx'.

How to check visibility of software keyboard in Android?

99% of solutions here are based on probability of IME WINDOW SIZE and each such solution is a sh... worth!

because:

  1. OVERLAYS - from User apps or System apps
  2. IME have no MINIMUM SIZE it can take 100% of window size and can be so thin as imagination of developer implementation :)
  3. MODAL windows / MULTI windows
  4. and many many more like no knowledge of IPC (eg: foreign window or its content detection)

so guessing it's IME is always wrong - don't guess be sure !!!

@kevin-du is best solution wright now as its query IMM for IME height - but as it said the method is hidden API so using it could be dangerous in the way of getting wrong "false negative results" - by wrong dev usage.

Read data from a text file using Java

In Java 8 you could easily turn your text file into a List of Strings with streams by using Files.lines and collect:

private List<String> loadFile() {
    URI uri = null;
    try {
        uri = ClassLoader.getSystemResource("example.txt").toURI();
    } catch (URISyntaxException e) {
        LOGGER.error("Failed to load file.", e);
    }
    List<String> list = null;
    try (Stream<String> lines = Files.lines(Paths.get(uri))) {
        list = lines.collect(Collectors.toList());
    } catch (IOException e) {
        LOGGER.error("Failed to load file.", e);
    }
    return list;
}

Entitlements file do not match those specified in your provisioning profile.(0xE8008016)

Had this issue with a cordova / ionic3 app, was caused by forking a main app and not selected again the legacy system in project settings. I selected legacy and the entitlements bs went away.

Expand a div to fill the remaining width

A slightly different implementation,

Two div panels(content+extra), side by side, content panel expands if extra panel is not present.

jsfiddle: http://jsfiddle.net/qLTMf/1722/

How to find the port for MS SQL Server 2008?

Here are 5 methodes i found:

  • Method 1: SQL Server Configuration Manager
  • Method 2: Windows Event Viewer
  • Method 3: SQL Server Error Logs
  • Method 4: sys.dm_exec_connections DMV
  • Method 5: Reading registry using xp_instance_regread

Method 4: sys.dm_exec_connections DMV
I think this is almost the easiest way...
DMVs return server state that can be used to monitor SQL Server Instance. We can use sys.dm_exec_connections DMV to identify the port number SQL Server Instance is listening on using below T-SQL code:

SELECT local_tcp_port
FROM   sys.dm_exec_connections
WHERE  session_id = @@SPID
GO

Result Set:
local_tcp_port
61499

(1 row(s) affected)

Method 1: SQL Server Configuration Manager

Step 1. Click Start > All Programs > Microsoft SQL Server 2012 > Configuration Tools > SQL Server Configuration Manager

Step 2. Go to SQL Server Configuration Manager > SQL Server Network Configuration > Protocols for

Step 3. Right Click on TCP/IP and select Properties

enter image description here

Step 4. In TCP/IP Properties dialog box, go to IP Addresses tab and scroll down to IPAll group.

enter image description here

If SQL Server if configured to run on a static port it will be available in TCP Port textbox, and if it is configured on dynamic port then current port will be available in TCP Dynamic Ports textbox. Here my instance is listening on port number 61499.

The other methods you can find here: http://sqlandme.com/2013/05/01/sql-server-finding-tcp-port-number-sql-instance-is-listening-on/

How to hide column of DataGridView when using custom DataSource?

Just set DataGridView.AutoGenerateColumns = false;

You need click on the arrow on top right corner (in datagridview) to add columns, and in DataPropertyName you need to put a name of your property in your class.

Then, after you defined your columns in datagridview, you can set datagridview.datasource = myClassViewModel.

Android simple alert dialog

You can easily make your own 'AlertView' and use it everywhere.

alertView("You really want this?");

Implement it once:

private void alertView( String message ) {
 AlertDialog.Builder dialog = new AlertDialog.Builder(context);
 dialog.setTitle( "Hello" )
       .setIcon(R.drawable.ic_launcher)
       .setMessage(message)
//     .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
//      public void onClick(DialogInterface dialoginterface, int i) {
//          dialoginterface.cancel();   
//          }})
      .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialoginterface, int i) {   
        }               
        }).show();
 }

SQL Server Error : String or binary data would be truncated

This error is usually encountered when inserting a record in a table where one of the columns is a VARCHAR or CHAR data type and the length of the value being inserted is longer than the length of the column.

I am not satisfied how Microsoft decided to inform with this "dry" response message, without any point of where to look for the answer.

System.Net.Http: missing from namespace? (using .net 4.5)

just go to add reference then add

system.net.http

enter image description here

Converting Hexadecimal String to Decimal Integer

Well, Mr.ajb has resolved and pointed out the error in your code.

Coming to the second part of the code, that is, converting a string with letters to decimal integer below is code for that,

import java.util.Scanner;

public class HexaToDecimal
{
   int number;

   void getValue()
   {
      Scanner sc = new Scanner(System.in);
      System.out.println("Please enter hexadecimal to convert: ");
      number = Integer.parseInt(sc.nextLine(), 16);
      sc.close();
   }

   void toConvert()
   {
      String decimal = Integer.toString(number);
      System.out.println("The Decimal value is : " + decimal);
   }

   public static void main(String[] args)
   {
      HexaToDecimal htd = new HexaToDecimal();
      htd.getValue();
      htd.toConvert();
   }
}

You can refer example on hexadecimal to decimal for more information.

Why do Sublime Text 3 Themes not affect the sidebar?

The most recent version of Sublime has fixed this issue, click on Preferences, click on Theme select Adaptive.sublime-theme. This will change the sidebar to a dark colored background.

Python timedelta in years

Get the number of days, then divide by 365.2425 (the mean Gregorian year) for years. Divide by 30.436875 (the mean Gregorian month) for months.

Saving a high resolution image in R

A simpler way is

ggplot(data=df, aes(x=xvar, y=yvar)) + 
geom_point()

ggsave(path = path, width = width, height = height, device='tiff', dpi=700)

Android: Scale a Drawable or background image?

Kotlin:

If you needed to draw a bitmap in a View, scaled to FIT.

You can do the proper calculations to set bm the height equal to the container and adjust width, in the case bm width to height ratio is less than container width to height ratio, or the inverse in the opposite scenario.

Images:

Example Image 1

Example Image 2

// binding.fragPhotoEditDrawCont is the RelativeLayout where is your view
// bm is the Bitmap
val ch = binding.fragPhotoEditDrawCont.height
val cw = binding.fragPhotoEditDrawCont.width
val bh = bm.height
val bw = bm.width
val rc = cw.toFloat() / ch.toFloat()
val rb = bw.toFloat() / bh.toFloat()

if (rb < rc) {
    // Bitmap Width to Height ratio is less than Container ratio
    // Means, bitmap should pin top and bottom, and have some space on sides.
    //              _____          ___
    // container = |_____|   bm = |___| 
    val bmHeight = ch - 4 //4 for container border
    val bmWidth = rb * bmHeight //new width is bm_ratio * bm_height
    binding.fragPhotoEditDraw.layoutParams = RelativeLayout.LayoutParams(bmWidth.toInt(), bmHeight)
}
else {
    val bmWidth = cw - 4 //4 for container border
    val bmHeight = 1f/rb * cw
    binding.fragPhotoEditDraw.layoutParams = RelativeLayout.LayoutParams(bmWidth, bmHeight.toInt())
}

Download old version of package with NuGet

In NuGet 3.x (Visual Studio 2015) you can just select the version from the UI

NuGet 3 package manager UI

Environment variables in Mac OS X

There's no need for duplication. You can set environment variables used by launchd (and child processes, i.e. anything you start from Spotlight) using launchctl setenv.

For example, if you want to mirror your current path in launchd after setting it up in .bashrc or wherever:

PATH=whatever:you:want
launchctl setenv PATH $PATH

Environment variables are not automatically updated in running applications. You will need to relaunch applications to get the updated environment variables (although you can just set variables in your shell, e.g. PATH=whatever:you:want; there's no need to relaunch the terminal).

Download a file from HTTPS using download.file()

I've succeed with the following code:

url = "http://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Fss06hid.csv"
x = read.csv(file=url)

Note that I've changed the protocol from https to http, since the first one doesn't seem to be supported in R.

CURL ERROR: Recv failure: Connection reset by peer - PHP Curl

I faced same error but in a different way.

When you curl a page with a specific SSL protocol.

curl --sslv3 https://example.com

If --sslv3 is not supported by the target server then the error will be

curl: (35) TCP connection reset by peer

With the supported protocol, error will be gone.

curl --tlsv1.2 https://example.com

Today`s date in an excel macro

Try the Date function. It will give you today's date in a MM/DD/YYYY format. If you're looking for today's date in the MM-DD-YYYY format try Date$. Now() also includes the current time (which you might not need). It all depends on what you need. :)

Anyway to prevent the Blue highlighting of elements in Chrome when clicking quickly?

I had similar issue with <input type="range" /> and I solved it with

-webkit-tap-highlight-color: transparent;

_x000D_
_x000D_
input[type="range"]{
  -webkit-tap-highlight-color: transparent;
}
_x000D_
 <input type="range" id="volume" name="demo"
         min="0" max="11">
  <label for="volume">Demo</label>
_x000D_
_x000D_
_x000D_

Right click to select a row in a Datagridview and show a menu to delete it

private void MyDataGridView_MouseDown(object sender, MouseEventArgs e)
{
    if(e.Button == MouseButtons.Right)
    {
        MyDataGridView.ClearSelection();
        MyDataGridView.Rows[e.RowIndex].Selected = true;
    }
}

private void DeleteRow_Click(object sender, EventArgs e)
{
    Int32 rowToDelete = MyrDataGridView.Rows.GetFirstRow(DataGridViewElementStates.Selected);
    MyDataGridView.Rows.RemoveAt(rowToDelete);
    MyDataGridView.ClearSelection();
}

Current time in microseconds in java

If you intend to use it for realtime system, perhaps java isnt the best choice to get the timestamp. But if youre going to use if for unique key, then Jason Smith's answer will do enough. But just in case, to anticipate 2 item end up getting the same timestamp (its possible if those 2 were processed almost simultaneously), you can loop until the last timestamp not equals with the current timestamp.

String timestamp = new String();
do {
    timestamp = String.valueOf(MicroTimestamp.INSTANCE.get());
    item.setTimestamp(timestamp);
} while(lasttimestamp.equals(timestamp));
lasttimestamp = item.getTimestamp();

How to get the latest record in each group using GROUP BY?

Try this

SELECT * FROM messages where id in (SELECT max(id) FROM messages GROUP BY from_id ) order by id desc

Range with step of type float

This is what I would use:

numbers = [float(x)/10 for x in range(10)]

rather than:

numbers = [x*0.1 for x in range(10)]
that would return :
[0.0, 0.1, 0.2, 0.30000000000000004, 0.4, 0.5, 0.6000000000000001, 0.7000000000000001, 0.8, 0.9]

hope it helps.

Issue in installing php7.2-mcrypt

Mcrypt PECL extenstion

 sudo apt-get -y install gcc make autoconf libc-dev pkg-config
 sudo apt-get -y install libmcrypt-dev
 sudo pecl install mcrypt-1.0.1

When you are shown the prompt

 libmcrypt prefix? [autodetect] :

Press [Enter] to autodetect.

After success installing mcrypt trought pecl, you should add mcrypt.so extension to php.ini.

The output will look like this:

...
Build process completed successfully
Installing '/usr/lib/php/20170718/mcrypt.so'    ---->   this is our path to mcrypt extension lib
install ok: channel://pecl.php.net/mcrypt-1.0.1
configuration option "php_ini" is not set to php.ini location
You should add "extension=mcrypt.so" to php.ini

Grab installing path and add to cli and apache2 php.ini configuration.

sudo bash -c "echo extension=/usr/lib/php/20170718/mcrypt.so > /etc/php/7.2/cli/conf.d/mcrypt.ini"
sudo bash -c "echo extension=/usr/lib/php/20170718/mcrypt.so > /etc/php/7.2/apache2/conf.d/mcrypt.ini"

Verify that the extension was installed

Run command:

php -i | grep "mcrypt"

The output will look like this:

/etc/php/7.2/cli/conf.d/mcrypt.ini
Registered Stream Filters => zlib.*, string.rot13, string.toupper, string.tolower, string.strip_tags, convert.*, consumed, dechunk, convert.iconv.*, mcrypt.*, mdecrypt.*
mcrypt
mcrypt support => enabled
mcrypt_filter support => enabled
mcrypt.algorithms_dir => no value => no value
mcrypt.modes_dir => no value => no value

How to get year/month/day from a date object?

Here is a cleaner way getting Year/Month/Day with template literals:

_x000D_
_x000D_
var date = new Date();_x000D_
var formattedDate = `${date.getFullYear()}/${(date.getMonth() + 1)}/${date.getDate()}`;_x000D_
console.log(formattedDate);
_x000D_
_x000D_
_x000D_

oracle sql: update if exists else insert

MERGE doesn't need "multiple tables", but it does need a query as the source. Something like this should work:

MERGE INTO mytable d
USING (SELECT 1 id, 'x' name from dual) s
ON (d.id = s.id)
WHEN MATCHED THEN UPDATE SET d.name = s.name
WHEN NOT MATCHED THEN INSERT (id, name) VALUES (s.id, s.name);

Alternatively you can do this in PL/SQL:

BEGIN
  INSERT INTO mytable (id, name) VALUES (1, 'x');
EXCEPTION
  WHEN DUP_VAL_ON_INDEX THEN
    UPDATE mytable
    SET    name = 'x'
    WHERE id = 1;
END;

How do I check if an index exists on a table field in MySQL?

Use the following statement: SHOW INDEX FROM your_table

And then check the result for the fields: row["Table"], row["Key_name"]

Make sure you write "Key_name" correctly

error: (-215) !empty() in function detectMultiScale

You may find such kind of errors when you did not define the complete path of your XML file. Try this one if you are using opencv3.1.0 in raspberrypi 3: "faceCascade = cv2.CascadeClassifier('/home/pi/opencv-3.1.0/data/haarcascades/haarcascade_frontalface_default.xml')"

How to generate Javadoc HTML files in Eclipse?

To quickly add a Javadoc use following shortcut:

Windows: alt + shift + J

Mac: ? + Alt + J

Depending on selected context, a Javadoc will be printed. To create Javadoc written by OP, select corresponding method and hit the shotcut keys.

How to copy to clipboard using Access/VBA?

User Leigh Webber on the social.msdn.microsoft.com site posted VBA code implementing an easy-to-use clipboard interface that uses the Windows API:

http://social.msdn.microsoft.com/Forums/en/worddev/thread/ee9e0d28-0f1e-467f-8d1d-1a86b2db2878

You can get Leigh Webber's source code here

If this link doesn't go through, search for "A clipboard object for VBA" in the Office Dev Center > Microsoft Office for Developers Forums > Word for Developers section.

I created the two classes, ran his test cases, and it worked perfectly inside Outlook 2007 SP3 32-bit VBA under Windows 7 64-bit. It will most likely work for Access. Tip: To rename classes, select the class in the VBA 'Project' window, then click 'View' on the menu bar and click 'Properties Window' (or just hit F4).

With his classes, this is what it takes to copy to/from the clipboard:

Dim myClipboard As New vbaClipboard  ' Create clipboard

' Copy text to clipboard as ClipboardFormat TEXT (CF_TEXT)    
myClipboard.SetClipboardText "Text to put in clipboard", "CF_TEXT"    

' Retrieve clipboard text in CF_TEXT format (CF_TEXT = 1)
mytxt = myClipboard.GetClipboardText(1)

He also provides other functions for manipulating the clipboard.

It also overcomes 32KB MSForms_DataObject.SetText limitation - the main reason why SetText often fails. However, bear in mind that, unfortunatelly, I haven't found a reference on Microsoft recognizing this limitation.

-Jim

Declare a constant array

An array isn't immutable by nature; you can't make it constant.

The nearest you can get is:

var letter_goodness = [...]float32 {.0817, .0149, .0278, .0425, .1270, .0223, .0202, .0609, .0697, .0015, .0077, .0402, .0241, .0675, .0751, .0193, .0009, .0599, .0633, .0906, .0276, .0098, .0236, .0015, .0197, .0007 }

Note the [...] instead of []: it ensures you get a (fixed size) array instead of a slice. So the values aren't fixed but the size is.

CASE IN statement with multiple values

The question is specific to SQL Server, but I would like to extend Martin Smith's answer.

SQL:2003 standard allows to define multiple values for simple case expression:

SELECT CASE c.Number
          WHEN '1121231','31242323' THEN 1
          WHEN '234523','2342423' THEN 2
       END AS Test
FROM tblClient c;

It is optional feature: Comma-separated predicates in simple CASE expression“ (F263).

Syntax:

CASE <common operand>
     WHEN <expression>[, <expression> ...] THEN <result>
    [WHEN <expression>[, <expression> ...] THEN <result>
     ...]
    [ELSE <result>]
END

As for know I am not aware of any RDBMS that actually supports that syntax.

Postgres "psql not recognized as an internal or external command"

I had your issue and got it working again (on windows 7).

My setup had actually worked at first. I installed postgres and then set up the system PATH variables with C:\Program Files\PostgreSQL\9.6\bin; C:\Program Files\PostgreSQL\9.6\lib. The psql keyword in the command line gave no errors.

I deleted the PATH variables above one at a time to test if they were both really needed. Psql continued to work after I deleted the lib path, but stopped working after I deleted the bin path. When I returned bin, it still didn't work, and the same with lib. I closed and reopened the command line between tries, and checked the path. The problem lingered even though the path was identical to how it had been when working. I re-pasted it.

I uninstalled and reinstalled postgres. The problem lingered. It finally worked after I deleted the spaces between the "; C:..." in the paths and re-saved.

Not sure if it was really the spaces that were the culprit. Maybe the environment variables just needed to be altered and refreshed after the install.

I'm also still not sure if both lib and bin paths are needed since there seems to be some kind of lingering memory for old path configurations. I don't want to test it again though.

Change icon-bar (?) color in bootstrap

Just one line of coding is enough.. just try this out. and you can adjust even thicknes of icon-bar with this by adding pixels.

HTML

<div class="navbar-header">
  <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#defaultNavbar1" aria-expanded="false"><span class="sr-only">Toggle navigation</span>

  <span class="icon-bar"></span>
  <span class="icon-bar"></span>
  <span class="icon-bar"></span>

  </button>
  <a class="navbar-brand" href="#" <span class="icon-bar"></span><img class="img-responsive brand" src="img/brand.png">
  </a></div>

CSS

    .navbar-toggle, .icon-bar {
    border:1px solid orange;
}

BOOM...

SyntaxError: multiple statements found while compiling a single statement

A (partial) practical work-around is to put things into a throw-away function.

Pasting

x = 1
x += 1
print(x)

results in

>>> x = 1
x += 1
print(x)
  File "<stdin>", line 1
    x += 1
print(x)

    ^
SyntaxError: multiple statements found while compiling a single statement
>>>

However, pasting

def abc():
  x = 1
  x += 1
  print(x)

works:

>>> def abc():
  x = 1
  x += 1
  print(x)
>>> abc()
2
>>>

Of course, this is OK for a quick one-off, won't work for everything you might want to do, etc. But then, going to ipython / jupyter qtconsole is probably the next simplest option.

T-SQL query to show table definition?

I know it's an old question, but exactly what I was looking for. Because I want to batch script some tables, I rewrote the C# code from Anthony Faull for PowerShell.

This one is uses Integrated Security:

Import-Module sqlps

$serverInstance = "<server>"
$database = "<database>"
$table = "<table>"
$schema = "<schema>"

$options = New-Object -TypeName Microsoft.SqlServer.Management.Smo.ScriptingOptions
$options.DriAll = $true
$options.SchemaQualify = $true

$connection = New-Object -TypeName Microsoft.SqlServer.Management.Common.ServerConnection `
    -ArgumentList $serverInstance
$server = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server `
    -ArgumentList $connection

$server.Databases.Item($database).Tables.Item($table, $schema).Script($options) `
    | ForEach-Object -Process { $_ + "`nGO"}

And here with username and password:

Import-Module sqlps

$serverInstance = "<server>"
$user = "<user>"
$password = "<pasword>"
$database = "<database>"
$table = "<table>"
$schema = "<schema>"

$options = New-Object -TypeName Microsoft.SqlServer.Management.Smo.ScriptingOptions
$options.DriAll = $true
$options.SchemaQualify = $true

$connection = New-Object -TypeName Microsoft.SqlServer.Management.Common.ServerConnection `
    -ArgumentList $serverInstance
$connection.LoginSecure = $false
$connection.Login = $user
$connection.Password = $password
$server = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server `
    -ArgumentList $connection

$server.Databases.Item($database).Tables.Item($table, $schema).Script($options) `
    | ForEach-Object -Process { $_ + "`nGO"}

CSS: how do I create a gap between rows in a table?

You could also just modify the height for each row using CSS.

<head>
 <style>
 tr {
   height:40px;
 }
</style>
</head>

<body>
<table>

<tr> <td>One</td> <td>Two</td> </tr>
<tr> <td>Three</td> <td>Four</td> </tr>
<tr> <td>Five</td> <td>Six</td> </tr>

</table>
</body>

You could also modify the height of the <td> element, it should give you the same result.

What is the difference between a generative and a discriminative algorithm?

Generally, there is a practice in machine learning community not to learn something that you don’t want to. For example, consider a classification problem where one's goal is to assign y labels to a given x input. If we use generative model

p(x,y)=p(y|x).p(x)

we have to model p(x) which is irrelevant for the task in hand. Practical limitations like data sparseness will force us to model p(x) with some weak independence assumptions. Therefore, we intuitively use discriminative models for classification.

PostgreSQL: Drop PostgreSQL database through command line

When it says users are connected, what does the query "select * from pg_stat_activity;" say? Are the other users besides yourself now connected? If so, you might have to edit your pg_hba.conf file to reject connections from other users, or shut down whatever app is accessing the pg database to be able to drop it. I have this problem on occasion in production. Set pg_hba.conf to have a two lines like this:

local   all         all                               ident
host    all         all         127.0.0.1/32          reject

and tell pgsql to reload or restart (i.e. either sudo /etc/init.d/postgresql reload or pg_ctl reload) and now the only way to connect to your machine is via local sockets. I'm assuming you're on linux. If not this may need to be tweaked to something other than local / ident on that first line, to something like host ... yourusername.

Now you should be able to do:

psql postgres
drop database mydatabase;