Programs & Examples On #Ima4

How do I compare two strings in python?

If you just need to check if the two strings are exactly same,

text1 = 'apple'

text2 = 'apple'

text1 == text2

The result will be

True

If you need the matching percentage,

import difflib

text1 = 'Since 1958.'

text2 = 'Since 1958'

output = str(int(difflib.SequenceMatcher(None, text1, text2).ratio()*100))

Matching percentage output will be,

'95'

How to send emails from my Android application?

This function first direct intent gmail for sending email, if gmail is not found then promote intent chooser. I used this function in many commercial app and it's working fine. Hope it will help you:

public static void sentEmail(Context mContext, String[] addresses, String subject, String body) {

    try {
        Intent sendIntentGmail = new Intent(Intent.ACTION_VIEW);
        sendIntentGmail.setType("plain/text");
        sendIntentGmail.setData(Uri.parse(TextUtils.join(",", addresses)));
        sendIntentGmail.setClassName("com.google.android.gm", "com.google.android.gm.ComposeActivityGmail");
        sendIntentGmail.putExtra(Intent.EXTRA_EMAIL, addresses);
        if (subject != null) sendIntentGmail.putExtra(Intent.EXTRA_SUBJECT, subject);
        if (body != null) sendIntentGmail.putExtra(Intent.EXTRA_TEXT, body);
        mContext.startActivity(sendIntentGmail);
    } catch (Exception e) {
        //When Gmail App is not installed or disable
        Intent sendIntentIfGmailFail = new Intent(Intent.ACTION_SEND);
        sendIntentIfGmailFail.setType("*/*");
        sendIntentIfGmailFail.putExtra(Intent.EXTRA_EMAIL, addresses);
        if (subject != null) sendIntentIfGmailFail.putExtra(Intent.EXTRA_SUBJECT, subject);
        if (body != null) sendIntentIfGmailFail.putExtra(Intent.EXTRA_TEXT, body);
        if (sendIntentIfGmailFail.resolveActivity(mContext.getPackageManager()) != null) {
            mContext.startActivity(sendIntentIfGmailFail);
        }
    }
}

Objective-C ARC: strong vs retain and weak vs assign

nonatomic/atomic

  • nonatomic is much faster than atomic
  • always use nonatomic unless you have a very specific requirement for atomic, which should be rare (atomic doesn't guarantee thread safety - only stalls accessing the property when it's simultaneously being set by another thread)

strong/weak/assign

  • use strong to retain objects - although the keyword retain is synonymous, it's best to use strong instead
  • use weak if you only want a pointer to the object without retaining it - useful for avoid retain cycles (ie. delegates) - it will automatically nil out the pointer when the object is released
  • use assign for primatives - exactly like weak except it doesn't nil out the object when released (set by default)

(Optional)

copy

  • use it for creating a shallow copy of the object
  • good practice to always set immutable properties to copy - because mutable versions can be passed into immutable properties, copy will ensure that you'll always be dealing with an immutable object
  • if an immutable object is passed in, it will retain it - if a mutable object is passed in, it will copy it

readonly

  • use it to disable setting of the property (prevents code from compiling if there's an infraction)
  • you can change what's delivered by the getter by either changing the variable directly via its instance variable, or within the getter method itself

How to retrieve field names from temporary table (SQL Server 2008)

select * 
from tempdb.INFORMATION_SCHEMA.COLUMNS 
where TABLE_NAME=OBJECT_NAME(OBJECT_ID('#table'))

Password must have at least one non-alpha character

Run it through a fairly simple regex: [^a-zA-Z]

And then check it's length separately:

if(string.Length > 7)

Get the decimal part from a double

 string input = "0.55";
    var regex1 = new System.Text.RegularExpressions.Regex("(?<=[\\.])[0-9]+");
    if (regex1.IsMatch(input))
    {
        string dp= regex1.Match(input ).Value;
    }

Log4j output not displayed in Eclipse console

A simple log4j.properties file can look like this:

log4j.rootCategory=debug,console

log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.target=System.out
log4j.appender.console.immediateFlush=true
log4j.appender.console.encoding=UTF-8
log4j.appender.console.threshold=info

log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.conversionPattern=%d [%t] %-5p %c - %m%n

Place it in your class path (target/classes folder). Or you if you have a Maven project, place it under your src/main/resources and Eclipse will copy it to your class path.

Without a configuration file, you should see an Eclipse warning in the console like this:

log4j:WARN No appenders could be found for logger.
log4j:WARN Please initialize the log4j system properly.

Select multiple columns from a table, but group by one

I had a similar problem to the OP. Then I saw the answer from @Urs Marian which helped a lot. But additionally what I was looking for is, when there are multiple values in a column and they will be grouped, how I can get the last submitted value (e.g. ordered by a date/id column).

Example:

We have following table structure:

CREATE TABLE tablename(
    [msgid] [int] NOT NULL,
    [userid] [int] NOT NULL,
    [username] [varchar](70) NOT NULL,
    [message] [varchar](5000) NOT NULL
) 

Now there are at least two datasets in the table:

+-------+--------+----------+---------+
| msgid | userid | username | message |
+-------+--------+----------+---------+
|     1 |      1 | userA    | hello   |
|     2 |      1 | userB    | world   |
+-------+--------+----------+---------+

Therefore following SQL script does work (checked on MSSQL) to group it, also if the same userid has different username values. In the example below, the username with the highest msgid will be shown:

SELECT m.userid, 
(select top 1 username from table where userid = m.userid order by msgid desc) as username,
count(*) as messages
FROM tablename m
GROUP BY m.userid
ORDER BY count(*) DESC

How to describe table in SQL Server 2008?

The sp_help built-in procedure is the SQL Server's closest thing to Oracle's DESC function IMHO

sp_help MyTable

Use

sp_help "[SchemaName].[TableName]" 

or

sp_help "[InstanceName].[SchemaName].[TableName]"

in case you need to qualify the table name further

Deleting a file in VBA

You can set a reference to the Scripting.Runtime library and then use the FileSystemObject. It has a DeleteFile method and a FileExists method.

See the MSDN article here.

bitwise XOR of hex numbers in python

Whoa. You're really over-complicating it by a very long distance. Try:

>>> print hex(0x12ef ^ 0xabcd)
0xb922

You seem to be ignoring these handy facts, at least:

  • Python has native support for hexadecimal integer literals, with the 0x prefix.
  • "Hexadecimal" is just a presentation detail; the arithmetic is done in binary, and then the result is printed as hex.
  • There is no connection between the format of the inputs (the hexadecimal literals) and the output, there is no such thing as a "hexadecimal number" in a Python variable.
  • The hex() function can be used to convert any number into a hexadecimal string for display.

If you already have the numbers as strings, you can use the int() function to convert to numbers, by providing the expected base (16 for hexadecimal numbers):

>>> print int("12ef", 16)
4874

So you can do two conversions, perform the XOR, and then convert back to hex:

>>> print hex(int("12ef", 16) ^ int("abcd", 16))
0xb922

How to calculate number of days between two given dates?

from datetime import date
def d(s):
  [month, day, year] = map(int, s.split('/'))
  return date(year, month, day)
def days(start, end):
  return (d(end) - d(start)).days
print days('8/18/2008', '9/26/2008')

This assumes, of course, that you've already verified that your dates are in the format r'\d+/\d+/\d+'.

Should you commit .gitignore into the Git repos?

Normally yes, .gitignore is useful for everyone who wants to work with the repository. On occasion you'll want to ignore more private things (maybe you often create LOG or something. In those cases you probably don't want to force that on anyone else.

Cannot perform runtime binding on a null reference, But it is NOT a null reference

This error happens when you have a ViewBag Non-Existent in your razor code calling a method.

Controller

public ActionResult Accept(int id)
{
    return View();
}

razor:

<div class="form-group">
      @Html.LabelFor(model => model.ToId, "To", htmlAttributes: new { @class = "control-label col-md-2" })
     <div class="col-md-10">
           @Html.Flag(Model.from)
     </div>
</div>
<div class="form-group">
     <div class="col-md-10">
          <input value="@ViewBag.MaximounAmount.ToString()" />@* HERE is the error *@ 
     </div>
</div>

For some reason, the .net aren't able to show the error in the correct line.

Normally this causes a lot of wasted time.

Transposing a 1D NumPy array

You can only transpose a 2D array. You can use numpy.matrix to create a 2D array. This is three years late, but I am just adding to the possible set of solutions:

import numpy as np
m = np.matrix([2, 3])
m.T

How do I restart nginx only after the configuration test was successful on Ubuntu?

I use the following command to reload Nginx (version 1.5.9) only if a configuration test was successful:

/etc/init.d/nginx configtest && sudo /etc/init.d/nginx reload

If you need to do this often, you may want to use an alias. I use the following:

alias n='/etc/init.d/nginx configtest && sudo /etc/init.d/nginx reload'

The trick here is done by the "&&" which only executes the second command if the first was successful. You can see here a more detailed explanation of the use of the "&&" operator.

You can use "restart" instead of "reload" if you really want to restart the server.

Gradle - Could not target platform: 'Java SE 8' using tool chain: 'JDK 7 (1.7)'

I had a very related issue but for higher Java versions:

$ ./gradlew clean assemble

... <other normal Gradle output>

Could not target platform: 'Java SE 11' using tool chain: 'JDK 8 (1.8)'.

I noticed that the task succeeded when running using InteliJ. Adding a file (same level as build.gradle) called .java-version solved my issue:

 # .java-version
 11.0.3

UNC path to a folder on my local computer

I had to:

Can't find AVD or SDK manager in Eclipse

Well I feel silly, but my problem was that I was in the Debug perspective and they do not show up in that perspective. Switched back to the Java perspective and viola.

Delete duplicate records from a SQL table without a primary key

delete from employee where rowid in (select rowid from (select rowid, name_count from (select rowid, count(emp_name) as name_count from employee group by emp_id, emp_name) where name_count>1))

What does PHP keyword 'var' do?

So basically it is an old style and do not use it for newer version of PHP. Better to use Public keyword instead;if you are not in love with var keyword. So instead of using

class Test {
    var $name;
}

Use

class Test {
   public $name;
}

What is meant by the term "hook" in programming?

Simple said:

A hook is a means of executing custom code (function) either before, after, or instead of existing code. For example, a function may be written to "hook" into the login process in order to execute a Captcha function before continuing on to the normal login process.

Convert UIImage to NSData and convert back to UIImage in Swift?

For safe execution of code, use if-let block with Data to prevent app crash & , as function UIImagePNGRepresentation returns an optional value.

if let img = UIImage(named: "TestImage.png") {
    if let data:Data = UIImagePNGRepresentation(img) {
       // Handle operations with data here...         
    }
}

Note: Data is Swift 3+ class. Use Data instead of NSData with Swift 3+

Generic image operations (like png & jpg both):

if let img = UIImage(named: "TestImage.png") {  //UIImage(named: "TestImage.jpg")
        if let data:Data = UIImagePNGRepresentation(img) {
               handleOperationWithData(data: data)     
        } else if let data:Data = UIImageJPEGRepresentation(img, 1.0) {
               handleOperationWithData(data: data)     
        }
}

*******
func handleOperationWithData(data: Data) {
     // Handle operations with data here...
     if let image = UIImage(data: data) {
        // Use image...
     }
}

By using extension:

extension UIImage {

    var pngRepresentationData: Data? {
        return UIImagePNGRepresentation(self)
    }

    var jpegRepresentationData: Data? {
        return UIImageJPEGRepresentation(self, 1.0)
    }
}

*******
if let img = UIImage(named: "TestImage.png") {  //UIImage(named: "TestImage.jpg")
      if let data = img.pngRepresentationData {
              handleOperationWithData(data: data)     
      } else if let data = img.jpegRepresentationData {
              handleOperationWithData(data: data)     
     }
}

*******
func handleOperationWithData(data: Data) {
     // Handle operations with data here...
     if let image = UIImage(data: data) {
        // Use image...
     }
}

java.lang.UnsupportedClassVersionError

This class was compiled with a JDK more recent than the one used for execution.

The easiest is to install a more recent JRE on the computer where you execute the program. If you think you installed a recent one, check the JAVA_HOME and PATH environment variables.

Version 49 is java 1.5. That means the class was compiled with (or for) a JDK which is yet old. You probably tried to execute the class with JDK 1.4. You really should use one more recent (1.6 or 1.7, see java version history).

How to know Laravel version and where is it defined?

Run this command in your project folder location in cmd

php artisan --version

List file using ls command in Linux with full path

I have had this issue, and I use the following :

ls -dl $PWD/* | grep $PWD

It has always got me the listingI have wanted, but your mileage may vary.

How to access random item in list?

I'll suggest different approach, If the order of the items inside the list is not important at extraction (and each item should be selected only once), then instead of a List you can use a ConcurrentBag which is a thread-safe, unordered collection of objects:

var bag = new ConcurrentBag<string>();
bag.Add("Foo");
bag.Add("Boo");
bag.Add("Zoo");

The EventHandler:

string result;
if (bag.TryTake(out result))
{
    MessageBox.Show(result);
}

The TryTake will attempt to extract an "random" object from the unordered collection.

Syntax for async arrow function

Immediately Invoked Async Arrow Function:

(async () => {
    console.log(await asyncFunction());
})();

Immediately Invoked Async Function Expression:

(async function () {
    console.log(await asyncFunction());
})();

Form content type for a json HTTP POST?

It looks like people answered the first part of your question (use application/json).

For the second part: It is perfectly legal to send query parameters in a HTTP POST Request.

Example:

POST /members?id=1234 HTTP/1.1
Host: www.example.com
Content-Type: application/json

{"email":"[email protected]"}

Query parameters are commonly used in a POST request to refer to an existing resource. The above example would update the email address of an existing member with the id of 1234.

How to format x-axis time scale values in Chart.js v2

Just set all the selected time unit's displayFormat to MMM DD

options: {
  scales: {
    xAxes: [{
      type: 'time',
      time: {
        displayFormats: {
           'millisecond': 'MMM DD',
           'second': 'MMM DD',
           'minute': 'MMM DD',
           'hour': 'MMM DD',
           'day': 'MMM DD',
           'week': 'MMM DD',
           'month': 'MMM DD',
           'quarter': 'MMM DD',
           'year': 'MMM DD',
        }
        ...

Notice that I've set all the unit's display format to MMM DD. A better way, if you have control over the range of your data and the chart size, would be force a unit, like so

options: {
  scales: {
    xAxes: [{
      type: 'time',
      time: {
        unit: 'day',
        unitStepSize: 1,
        displayFormats: {
           'day': 'MMM DD'
        }
        ...

Fiddle - http://jsfiddle.net/prfd1m8q/

When to use AtomicReference in Java?

When do we use AtomicReference?

AtomicReference is flexible way to update the variable value atomically without use of synchronization.

AtomicReference support lock-free thread-safe programming on single variables.

There are multiple ways of achieving Thread safety with high level concurrent API. Atomic variables is one of the multiple options.

Lock objects support locking idioms that simplify many concurrent applications.

Executors define a high-level API for launching and managing threads. Executor implementations provided by java.util.concurrent provide thread pool management suitable for large-scale applications.

Concurrent collections make it easier to manage large collections of data, and can greatly reduce the need for synchronization.

Atomic variables have features that minimize synchronization and help avoid memory consistency errors.

Provide a simple example where AtomicReference should be used.

Sample code with AtomicReference:

String initialReference = "value 1";

AtomicReference<String> someRef =
    new AtomicReference<String>(initialReference);

String newReference = "value 2";
boolean exchanged = someRef.compareAndSet(initialReference, newReference);
System.out.println("exchanged: " + exchanged);

Is it needed to create objects in all multithreaded programs?

You don't have to use AtomicReference in all multi threaded programs.

If you want to guard a single variable, use AtomicReference. If you want to guard a code block, use other constructs like Lock /synchronized etc.

Batch File: ( was unexpected at this time

you need double quotes in all your three if statements, eg.:

IF "%a%"=="2" (

@echo OFF &SETLOCAL ENABLEDELAYEDEXPANSION
cls
title ~USB Wizard~
echo What do you want to do?
echo 1.Enable/Disable USB Storage Devices.
echo 2.Enable/Disable Writing Data onto USB Storage.
echo 3.~Yet to come~.


set "a=%globalparam1%"
goto :aCheck
:aPrompt
set /p "a=Enter Choice: "
:aCheck
if "%a%"=="" goto :aPrompt
echo %a%

IF "%a%"=="2" (
    title USB WRITE LOCK
    echo What do you want to do?
    echo 1.Apply USB Write Protection
    echo 2.Remove USB Write Protection
    ::param1
    set "param1=%globalparam2%"
    goto :param1Check
    :param1Prompt
    set /p "param1=Enter Choice: "
    :param1Check
    if "!param1!"=="" goto :param1Prompt

    if "!param1!"=="1" (
         REG ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\StorageDevicePolicies\ /v WriteProtect /t REG_DWORD /d 00000001
         USB Write is Locked!
    )
    if "!param1!"=="2" (
         REG ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\StorageDevicePolicies\ /v WriteProtect /t REG_DWORD /d 00000000
         USB Write is Unlocked!
    )
)
pause

UnsupportedClassVersionError: JVMCFRE003 bad major version in WebSphere AS 7

At first you should check major version of compiled problematic .class file, in your case map/CareMonths. See this answer how to do it.

WAS7 uses Java 6 (as said Jacek), and Java 6 uses major version 50, so you have to compile your project with Java 6. How to set proper version of Java compiler depends on your IDE (e.g. Eclipse, IntelliJ) or build tool (e.g. Maven, Ant).

Is there a way to get a <button> element to link to a location without wrapping it in an <a href ... tag?

<form action="portfolio.html">
 <button type="link" class="btn btn-primary btn-lg">View Work</button>
</form>

I just figured this out, and it links perfectly to another page without having my default link settings over ride my button classes! :)

Log4Net configuring log level

Use threshold.

For example:

   <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
        <threshold value="WARN"/>
        <param name="File" value="File.log" />
        <param name="AppendToFile" value="true" />
        <param name="RollingStyle" value="Size" />
        <param name="MaxSizeRollBackups" value="10" />
        <param name="MaximumFileSize" value="1024KB" />
        <param name="StaticLogFileName" value="true" />
        <layout type="log4net.Layout.PatternLayout">
            <param name="Header" value="[Server startup]&#13;&#10;" />
            <param name="Footer" value="[Server shutdown]&#13;&#10;" />
            <param name="ConversionPattern" value="%d %m%n" />
        </layout>
    </appender>
    <appender name="EventLogAppender" type="log4net.Appender.EventLogAppender" >
        <threshold value="ERROR"/>
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date [%thread]- %message%newline" />
        </layout>
    </appender>
    <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
        <threshold value="INFO"/>
        <layout type="log4net.Layout.PatternLayout">
            <param name="ConversionPattern" value="%d [%thread] %m%n" />
        </layout>
    </appender>

In this example all INFO and above are sent to Console, all WARN are sent to file and ERRORs are sent to the Event-Log.

What is the difference between persist() and merge() in JPA and Hibernate?

The most important difference is this:

  • In case of persist method, if the entity that is to be managed in the persistence context, already exists in persistence context, the new one is ignored. (NOTHING happened)

  • But in case of merge method, the entity that is already managed in persistence context will be replaced by the new entity (updated) and a copy of this updated entity will return back. (from now on any changes should be made on this returned entity if you want to reflect your changes in persistence context)

SQL Server - In clause with a declared variable

First, create a quick function that will split a delimited list of values into a table, like this:

CREATE FUNCTION dbo.udf_SplitVariable
(
    @List varchar(8000),
    @SplitOn varchar(5) = ','
)

RETURNS @RtnValue TABLE
(
    Id INT IDENTITY(1,1),
    Value VARCHAR(8000)
)

AS
BEGIN

--Account for ticks
SET @List = (REPLACE(@List, '''', ''))

--Account for 'emptynull'
IF LTRIM(RTRIM(@List)) = 'emptynull'
BEGIN
    SET @List = ''
END

--Loop through all of the items in the string and add records for each item
WHILE (CHARINDEX(@SplitOn,@List)>0)
BEGIN

    INSERT INTO @RtnValue (value)
    SELECT Value = LTRIM(RTRIM(SUBSTRING(@List, 1, CHARINDEX(@SplitOn, @List)-1)))  

    SET @List = SUBSTRING(@List, CHARINDEX(@SplitOn,@List) + LEN(@SplitOn), LEN(@List))

END

INSERT INTO @RtnValue (Value)
SELECT Value = LTRIM(RTRIM(@List))

RETURN

END 

Then call the function like this...

SELECT * 
FROM A
LEFT OUTER JOIN udf_SplitVariable(@ExcludedList, ',') f ON A.Id = f.Value
WHERE f.Id IS NULL

This has worked really well on our project...

Of course, the opposite could also be done, if that was the case (though not your question).

SELECT * 
FROM A
INNER JOIN udf_SplitVariable(@ExcludedList, ',') f ON A.Id = f.Value

And this really comes in handy when dealing with reports that have an optional multi-select parameter list. If the parameter is NULL you want all values selected, but if it has one or more values you want the report data filtered on those values. Then use SQL like this:

SELECT * 
FROM A
INNER JOIN udf_SplitVariable(@ExcludedList, ',') f ON A.Id = f.Value OR @ExcludeList IS NULL

This way, if @ExcludeList is a NULL value, the OR clause in the join becomes a switch that turns off filtering on this value. Very handy...

CSS getting text in one line rather than two

The best way to use is white-space: nowrap; This will align the text to one line.

JavaScript/JQuery: $(window).resize how to fire AFTER the resize is completed?

I prefer to create an event:

$(window).bind('resizeEnd', function() {
    //do something, window hasn't changed size in 500ms
});

Here is how you create it:

 $(window).resize(function() {
        if(this.resizeTO) clearTimeout(this.resizeTO);
        this.resizeTO = setTimeout(function() {
            $(this).trigger('resizeEnd');
        }, 500);
    });

You could have this in a global javascript file somewhere.

Eclipse: How do you change the highlight color of the currently selected method/expression?

If you're using eclipse with PHP package and want to change highlighted colour then there is slight difference to above answer.

  1. Right click on highlighted word
  2. Select 'Preferences'
  3. Go to General > Editors > Text Editors > Annotations. Now look for "PHP elements 'read' occurrences" and "PHP elements 'write' occurrences". You can select your desired colour there.

Change Highlighted text colour in Eclips with PHP

Pandas df.to_csv("file.csv" encode="utf-8") still gives trash characters for minus sign

Your "bad" output is UTF-8 displayed as CP1252.

On Windows, many editors assume the default ANSI encoding (CP1252 on US Windows) instead of UTF-8 if there is no byte order mark (BOM) character at the start of the file. While a BOM is meaningless to the UTF-8 encoding, its UTF-8-encoded presence serves as a signature for some programs. For example, Microsoft Office's Excel requires it even on non-Windows OSes. Try:

df.to_csv('file.csv',encoding='utf-8-sig')

That encoder will add the BOM.

Close/kill the session when the browser or tab is closed

It is not possible to kill the session variable, when the machine unexpectly shutdown due to power failure. It is only possible when the user is idle for a long time or it is properly logout.

CSS pseudo elements in React

Inline styling does not support pseudos or at-rules (e.g., @media). Recommendations range from reimplement CSS features in JavaScript for CSS states like :hover via onMouseEnter and onMouseLeave to using more elements to reproduce pseudo-elements like :after and :before to just use an external stylesheet.

Personally dislike all of those solutions. Reimplementing CSS features via JavaScript does not scale well -- neither does adding superfluous markup.

Imagine a large team wherein each developer is recreating CSS features like :hover. Each developer will do it differently, as teams grow in size, if it can be done, it will be done. Fact is with JavaScript there are about n ways to reimplement CSS features, and over time you can bet on every one of those ways being implemented with the end result being spaghetti code.

So what to do? Use CSS. Granted you asked about inline styling going to assume you're likely in the CSS-in-JS camp (me too!). Have found colocating HTML and CSS to be as valuable as colocating JS and HTML, lots of folks just don't realise it yet (JS-HTML colocation had lots of resistance too at first).

Made a solution in this space called Style It that simply lets your write plaintext CSS in your React components. No need to waste cycles reinventing CSS in JS. Right tool for the right job, here is an example using :after:

npm install style-it --save

Functional Syntax (JSFIDDLE)

import React from 'react';
import Style from 'style-it';

class Intro extends React.Component {
  render() {
    return Style.it(`
      #heart {
        position: relative;
        width: 100px;
        height: 90px;
      }
      #heart:before,
      #heart:after {
        position: absolute;
        content: "";
        left: 50px;
        top: 0;
        width: 50px;
        height: 80px;
        background: red;
        -moz-border-radius: 50px 50px 0 0;
        border-radius: 50px 50px 0 0;
        -webkit-transform: rotate(-45deg);
        -moz-transform: rotate(-45deg);
        -ms-transform: rotate(-45deg);
        -o-transform: rotate(-45deg);
        transform: rotate(-45deg);
        -webkit-transform-origin: 0 100%;
        -moz-transform-origin: 0 100%;
        -ms-transform-origin: 0 100%;
        -o-transform-origin: 0 100%;
        transform-origin: 0 100%;
      }
      #heart:after {
        left: 0;
        -webkit-transform: rotate(45deg);
        -moz-transform: rotate(45deg);
        -ms-transform: rotate(45deg);
        -o-transform: rotate(45deg);
        transform: rotate(45deg);
        -webkit-transform-origin: 100% 100%;
        -moz-transform-origin: 100% 100%;
        -ms-transform-origin: 100% 100%;
        -o-transform-origin: 100% 100%;
        transform-origin :100% 100%;
      }
    `,
      <div id="heart" />
    );
  }
}

export default Intro;

JSX Syntax (JSFIDDLE)

import React from 'react';
import Style from 'style-it';

class Intro extends React.Component {
  render() {
    return (
      <Style>
      {`
        #heart {
          position: relative;
          width: 100px;
          height: 90px;
        }
        #heart:before,
        #heart:after {
          position: absolute;
          content: "";
          left: 50px;
          top: 0;
          width: 50px;
          height: 80px;
          background: red;
          -moz-border-radius: 50px 50px 0 0;
          border-radius: 50px 50px 0 0;
          -webkit-transform: rotate(-45deg);
          -moz-transform: rotate(-45deg);
          -ms-transform: rotate(-45deg);
          -o-transform: rotate(-45deg);
          transform: rotate(-45deg);
          -webkit-transform-origin: 0 100%;
          -moz-transform-origin: 0 100%;
          -ms-transform-origin: 0 100%;
          -o-transform-origin: 0 100%;
          transform-origin: 0 100%;
        }
        #heart:after {
          left: 0;
          -webkit-transform: rotate(45deg);
          -moz-transform: rotate(45deg);
          -ms-transform: rotate(45deg);
          -o-transform: rotate(45deg);
          transform: rotate(45deg);
          -webkit-transform-origin: 100% 100%;
          -moz-transform-origin: 100% 100%;
          -ms-transform-origin: 100% 100%;
          -o-transform-origin: 100% 100%;
          transform-origin :100% 100%;
        }
     `}

      <div id="heart" />
    </Style>
  }
}

export default Intro;

Heart example pulled from CSS-Tricks

iPhone X / 8 / 8 Plus CSS media queries

I noticed that the answers here are using: device-width, device-height, min-device-width, min-device-height, max-device-width, max-device-height.

Please refrain from using them since they are deprecated. see MDN for reference. Instead use the regular min-width, max-width and so on. For extra assurance, you can set the min and max to the same px amount. For example:

iPhone X

@media only screen 
    and (width : 375px) 
    and (height : 635px)
    and (orientation : portrait)  
    and (-webkit-device-pixel-ratio : 3) { }

You may also notice that I am using 635px for height. Try it yourself the window height is actually 635px. run iOS simulator for iPhone X and in Safari Web inspector do window.innerHeight. Here are a few useful links on this subject:

Is there an easy way to convert Android Application to IPad, IPhone

In the box is working on being able to convert android projects to iOS

https://code.google.com/p/in-the-box/

RecyclerView and java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionViewHolder in Samsung devices

This is an example for refreshing data with completely new content. You can easily modify it to fit your needs. I solved this in my case by calling:

notifyItemRangeRemoved(0, previousContentSize);

before:

notifyItemRangeInserted(0, newContentSize);

This is the correct solution and is also mentioned in this post by an AOSP project member.

Visual Studio opens the default browser instead of Internet Explorer

In visual studio 2013, this can be done as follows:

1) Ensure you have selected a start up project from your solution explore window 2) This brings a drop down to the left of the debug drop down. You can choose browser from this new drop down.

Key is there should be a project selected as start up

How do I check that a Java String is not all whitespaces?

public static boolean isStringBlank(final CharSequence cs) {
        int strLen;
        if (cs == null || (strLen = cs.length()) == 0) {
            return true;
        }
        for (int i = 0; i < strLen; i++) {
            if (!Character.isWhitespace(cs.charAt(i))) {
                return false;
            }
        }
        return true;
    }

Why do access tokens expire?

This is very much implementation specific, but the general idea is to allow providers to issue short term access tokens with long term refresh tokens. Why?

  • Many providers support bearer tokens which are very weak security-wise. By making them short-lived and requiring refresh, they limit the time an attacker can abuse a stolen token.
  • Large scale deployment don't want to perform a database lookup every API call, so instead they issue self-encoded access token which can be verified by decryption. However, this also means there is no way to revoke these tokens so they are issued for a short time and must be refreshed.
  • The refresh token requires client authentication which makes it stronger. Unlike the above access tokens, it is usually implemented with a database lookup.

pass parameter by link_to ruby on rails

The above did not work for me but this did

<%= link_to "text_to_show_in_url", action_controller_path(:gender => "male", :param2=> "something_else") %>

Simplest SOAP example

The question is 'What is the simplest SOAP example using Javascript?'

This answer is of an example in the Node.js environment, rather than a browser. (Let's name the script soap-node.js) And we will use the public SOAP web service from Europe PMC as an example to get the reference list of an article.

const XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
const DOMParser = require('xmldom').DOMParser;

function parseXml(text) {
    let parser = new DOMParser();
    let xmlDoc = parser.parseFromString(text, "text/xml");
    Array.from(xmlDoc.getElementsByTagName("reference")).forEach(function (item) {
        console.log('Title: ', item.childNodes[3].childNodes[0].nodeValue);
    });

}

function soapRequest(url, payload) {
    let xmlhttp = new XMLHttpRequest();
    xmlhttp.open('POST', url, true);

    // build SOAP request
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4) {
            if (xmlhttp.status == 200) {
                parseXml(xmlhttp.responseText);
            }
        }
    }

    // Send the POST request
    xmlhttp.setRequestHeader('Content-Type', 'text/xml');
    xmlhttp.send(payload);
}

soapRequest('https://www.ebi.ac.uk/europepmc/webservices/soap', 
    `<?xml version="1.0" encoding="UTF-8"?>
    <S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
    <S:Header />
    <S:Body>
        <ns4:getReferences xmlns:ns4="http://webservice.cdb.ebi.ac.uk/"
            xmlns:ns2="http://www.scholix.org"
            xmlns:ns3="https://www.europepmc.org/data">
            <id>C7886</id>
            <source>CTX</source>
            <offSet>0</offSet>
            <pageSize>25</pageSize>
            <email>[email protected]</email>
        </ns4:getReferences>
    </S:Body>
    </S:Envelope>`);

Before running the code, you need to install two packages:

npm install xmlhttprequest
npm install xmldom

Now you can run the code:

node soap-node.js

And you'll see the output as below:

Title:  Perspective: Sustaining the big-data ecosystem.
Title:  Making proteomics data accessible and reusable: current state of proteomics databases and repositories.
Title:  ProteomeXchange provides globally coordinated proteomics data submission and dissemination.
Title:  Toward effective software solutions for big biology.
Title:  The NIH Big Data to Knowledge (BD2K) initiative.
Title:  Database resources of the National Center for Biotechnology Information.
Title:  Europe PMC: a full-text literature database for the life sciences and platform for innovation.
Title:  Bio-ontologies-fast and furious.
Title:  BioPortal: ontologies and integrated data resources at the click of a mouse.
Title:  PubMed related articles: a probabilistic topic-based model for content similarity.
Title:  High-Impact Articles-Citations, Downloads, and Altmetric Score.

What is the difference between \r and \n?

In addition to @Jon Skeet's answer:

Traditionally Windows has used \r\n, Unix \n and Mac \r, however newer Macs use \n as they're unix based.

Python list iterator behavior and next(iterator)

What is happening is that next(a) returns the next value of a, which is printed to the console because it is not affected.

What you can do is affect a variable with this value:

>>> a = iter(list(range(10)))
>>> for i in a:
...    print(i)
...    b=next(a)
...
0
2
4
6
8

Referring to the null object in Python

Use f string for getting this solved.

year=None
year_val= 'null' if year is None else  str(year)
print(f'{year_val}')

null

FtpWebRequest Download File

Easiest way

The most trivial way to download a binary file from an FTP server using .NET framework is using WebClient.DownloadFile:

WebClient client = new WebClient();
client.Credentials = new NetworkCredential("username", "password");
client.DownloadFile(
    "ftp://ftp.example.com/remote/path/file.zip", @"C:\local\path\file.zip");

Advanced options

Use FtpWebRequest, only if you need a greater control, that WebClient does not offer (like TLS/SSL encryption, progress monitoring, ascii/text transfer mode, resuming transfers, etc). Easy way is to just copy an FTP response stream to FileStream using Stream.CopyTo:

FtpWebRequest request =
    (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip");
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Ftp.DownloadFile;

using (Stream ftpStream = request.GetResponse().GetResponseStream())
using (Stream fileStream = File.Create(@"C:\local\path\file.zip"))
{
    ftpStream.CopyTo(fileStream);
}

Progress monitoring

If you need to monitor a download progress, you have to copy the contents by chunks yourself:

FtpWebRequest request =
    (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip");
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Ftp.DownloadFile;

using (Stream ftpStream = request.GetResponse().GetResponseStream())
using (Stream fileStream = File.Create(@"C:\local\path\file.zip"))
{
    byte[] buffer = new byte[10240];
    int read;
    while ((read = ftpStream.Read(buffer, 0, buffer.Length)) > 0)
    {
        fileStream.Write(buffer, 0, read);
        Console.WriteLine("Downloaded {0} bytes", fileStream.Position);
    }
}

For GUI progress (WinForms ProgressBar), see:
FtpWebRequest FTP download with ProgressBar


Downloading folder

If you want to download all files from a remote folder, see
C# Download all files and subdirectories through FTP.

Why Maven uses JDK 1.6 but my java -version is 1.7

For Eclipse Users. If you have a Run Configuration that does clean package for example.

In the Run Configuration panel there is a JRE tab where you can specify against which runtime it should run. Note that this configuration overrides whatever is in the pom.xml.

FirstOrDefault returns NullReferenceException if no match is found

You can use a combination of other LINQ methods to handle not matching condition:

var res = dictionary.Where(x => x.Value.ID == someID)
                    .Select(x => x.Value.DisplayName)
                    .DefaultIfEmpty("Unknown")
                    .First();

How to force Chrome's script debugger to reload javascript?

Here's a shortcut to DevTools:

  1. F12 to open Chrome DevTools
  2. F1 to open DevTools Settings
  3. Check Disable cache (while DevTools is open) as shown below:

enter image description here

Note: Updated per Dimi's comment. They tend to move it so let me know or update the post if you notice that it's changed.

SQL How to correctly set a date variable value and use it?

Your syntax is fine, it will return rows where LastAdDate lies within the last 6 months;

select cast('01-jan-1970' as datetime) as LastAdDate into #PubAdvTransData 
    union select GETDATE()
    union select NULL
    union select '01-feb-2010'

DECLARE @sp_Date DATETIME = DateAdd(m, -6, GETDATE())

SELECT * FROM #PubAdvTransData pat
     WHERE (pat.LastAdDate > @sp_Date)

>2010-02-01 00:00:00.000
>2010-04-29 21:12:29.920

Are you sure LastAdDate is of type DATETIME?

Converting byte array to string in javascript

Simply apply your byte array to String.fromCharCode. For example

String.fromCharCode.apply(null, [102, 111, 111]) equals 'foo'.

Caveat: works for arrays shorter than 65535. MDN docs here.

What's wrong with foreign keys?

In a project I worked on there was often implicit rather than explicit relationships so that numerous tables could be joined on the same column.

Take the following table

Address

  • AddressId (PK)
  • EntityId
  • EntityType
  • City
  • State
  • Country
  • Etc..

Possible values of EntityType may be Employee, Company, Customer, and the EntityId refers to the primarky key of whichever table you were interested in.

I don't really think this is the best way to do things, but it worked for this project.

android activity has leaked window com.android.internal.policy.impl.phonewindow$decorview Issue

 @Override
    protected void onPostExecute(final Boolean success) {
        mProgressDialog.dismiss();
        mProgressDialog = null;

setting the value null works for me

What is the maximum value for an int32?

Largest negative (32bit) value : -2147483648
(1 << 31)

Largest positive (32bit) value : 2147483647
~(1 << 31)

Mnemonic: "drunk AKA horny"

drunk ========= Drinking age is 21
AK ============ AK 47
A ============= 4 (A and 4 look the same)
horny ========= internet rule 34 (if it exists, there's 18+ material of it) 

21 47 4(years) 3(years) 4(years)
21 47 48       36       48

The requested URL /about was not found on this server

FWIW: I rebuilt a LAMP server from scratch and installed WordPress. I had the same issue after saving my Permalink setting to generate the .htaccess file. Turns out that mod_rewrite was not enabled. I ran across this post on Digital Ocean.
FTA:

First, we need to activate mod_rewrite. It’s available but not enabled with a clean Apache 2 installation.

$ sudo a2enmod rewrite

This will activate the module or alert you that the module is already enabled. To put these changes into effect, restart Apache.

$ sudo systemctl restart apache2

ExecutorService that interrupts tasks after a timeout

You can use this implementation that ExecutorService provides

invokeAll(Collection<? extends Callable<T>> tasks,long timeout, TimeUnit unit)
as

executor.invokeAll(Arrays.asList(task), 2 , TimeUnit.SECONDS);

However, in my case, I could not as Arrays.asList took extra 20ms.

How to convert an int to string in C?

EDIT: As pointed out in the comment, itoa() is not a standard, so better use sprintf() approach suggested in the rivaling answer!


You can use itoa() function to convert your integer value to a string.

Here is an example:

int num = 321;
char snum[5];

// convert 123 to string [buf]
itoa(num, snum, 10);

// print our string
printf("%s\n", snum);

If you want to output your structure into a file there is no need to convert any value beforehand. You can just use the printf format specification to indicate how to output your values and use any of the operators from printf family to output your data.

Do I need to close() both FileReader and BufferedReader?

Starting from Java 7 you can use try-with-resources Statement

try (BufferedReader br = new BufferedReader(new FileReader(path))) {
    return br.readLine();
}

Because the BufferedReader instance is declared in a try-with-resource statement, it will be closed regardless of whether the try statement completes normally or abruptly. So you don't need to close it yourself in the finally statement. (This is also the case with nested resource statements)

This is the recomanded way to work with resources, see the documentation for more detailed information

How to add one column into existing SQL Table

What about something like:

Alter Table Products
Add LastUpdate varchar(200) null

Do you need something more complex than this?

Converting Secret Key into a String and Vice Versa

You don't want to use .toString().

Notice that SecretKey inherits from java.security.Key, which itself inherits from Serializable. So the key here (no pun intended) is to serialize the key into a ByteArrayOutputStream, get the byte[] array and store it into the db. The reverse process would be to get the byte[] array off the db, create a ByteArrayInputStream offf the byte[] array, and deserialize the SecretKey off it...

... or even simpler, just use the .getEncoded() method inherited from java.security.Key (which is a parent interface of SecretKey). This method returns the encoded byte[] array off Key/SecretKey, which you can store or retrieve from the database.

This is all assuming your SecretKey implementation supports encoding. Otherwise, getEncoded() will return null.

edit:

You should look at the Key/SecretKey javadocs (available right at the start of a google page):

http://download.oracle.com/javase/6/docs/api/java/security/Key.html

Or this from CodeRanch (also found with the same google search):

http://www.coderanch.com/t/429127/java/java/Convertion-between-SecretKey-String-or

Java array reflection: isArray vs. instanceof

I recently ran into an issue upgrading a Groovy application from JDK 5 to JDK 6. Using isArray() failed in JDK6:

MissingMethodException:
No signature of sun.reflect.generics.reflectiveObjects.GenericArrayTypeImpl.isArray() ...

Changing to instanceof Object[] fixed this.

Handling the TAB character in Java

You can also use the tab character '\t' to represent a tab, instead of "\t".

char c ='t';
char c =(char)9;

How to iterate through a String

Using Guava (r07) you can do this:

for(char c : Lists.charactersOf(someString)) { ... }

This has the convenience of using foreach while not copying the string to a new array. Lists.charactersOf returns a view of the string as a List.

Python convert csv to xlsx

Here's an example using xlsxwriter:

import os
import glob
import csv
from xlsxwriter.workbook import Workbook


for csvfile in glob.glob(os.path.join('.', '*.csv')):
    workbook = Workbook(csvfile[:-4] + '.xlsx')
    worksheet = workbook.add_worksheet()
    with open(csvfile, 'rt', encoding='utf8') as f:
        reader = csv.reader(f)
        for r, row in enumerate(reader):
            for c, col in enumerate(row):
                worksheet.write(r, c, col)
    workbook.close()

FYI, there is also a package called openpyxl, that can read/write Excel 2007 xlsx/xlsm files.

Hope that helps.

How to execute a java .class from the command line

Try:

java -cp . Echo "hello"

Assuming that you compiled with:

javac Echo.java 

Then there is a chance that the "current" directory is not in your classpath ( where java looks for .class definitions )

If that's the case and listing the contents of your dir displays:

Echo.java
Echo.class

Then any of this may work:

java -cp . Echo "hello"

or

SET CLASSPATH=%CLASSPATH;.  

java Echo "hello"

And later as Fredrik points out you'll get another error message like.

Exception in thread "main" java.lang.NoSuchMethodError: main

When that happens, go and read his answer :)

What is DOM element?

Document Object Model (DOM), a programming interface specification being developed by the World Wide Web Consortium (W3C), lets a programmer create and modify HTML pages and XML documents as full-fledged program objects.

Restore the mysql database from .frm files

Copy all file and replace to /var/lib/mysql , after that you must change owner of files to mysql this is so important if mariadb.service restart has been faild

chown -R mysql:mysql /var/lib/mysql/*

and

chmod -R 700 /var/lib/mysql/*

AngularJS- Login and Authentication in each route and controller

app.js

'use strict';
// Declare app level module which depends on filters, and services
var app= angular.module('myApp', ['ngRoute','angularUtils.directives.dirPagination','ngLoadingSpinner']);
app.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/login', {templateUrl: 'partials/login.html', controller: 'loginCtrl'});
  $routeProvider.when('/home', {templateUrl: 'partials/home.html', controller: 'homeCtrl'});
  $routeProvider.when('/salesnew', {templateUrl: 'partials/salesnew.html', controller: 'salesnewCtrl'});
  $routeProvider.when('/salesview', {templateUrl: 'partials/salesview.html', controller: 'salesviewCtrl'});
  $routeProvider.when('/users', {templateUrl: 'partials/users.html', controller: 'usersCtrl'});
    $routeProvider.when('/forgot', {templateUrl: 'partials/forgot.html', controller: 'forgotCtrl'});


  $routeProvider.otherwise({redirectTo: '/login'});


}]);


app.run(function($rootScope, $location, loginService){
    var routespermission=['/home'];  //route that require login
    var salesnew=['/salesnew'];
    var salesview=['/salesview'];
    var users=['/users'];
    $rootScope.$on('$routeChangeStart', function(){
        if( routespermission.indexOf($location.path()) !=-1
        || salesview.indexOf($location.path()) !=-1
        || salesnew.indexOf($location.path()) !=-1
        || users.indexOf($location.path()) !=-1)
        {
            var connected=loginService.islogged();
            connected.then(function(msg){
                if(!msg.data)
                {
                    $location.path('/login');
                }

            });
        }
    });
});

loginServices.js

'use strict';
app.factory('loginService',function($http, $location, sessionService){
    return{
        login:function(data,scope){
            var $promise=$http.post('data/user.php',data); //send data to user.php
            $promise.then(function(msg){
                var uid=msg.data;
                if(uid){
                    scope.msgtxt='Correct information';
                    sessionService.set('uid',uid);
                    $location.path('/home');
                }          
                else  {
                    scope.msgtxt='incorrect information';
                    $location.path('/login');
                }                  
            });
        },
        logout:function(){
            sessionService.destroy('uid');
            $location.path('/login');
        },
        islogged:function(){
            var $checkSessionServer=$http.post('data/check_session.php');
            return $checkSessionServer;
            /*
            if(sessionService.get('user')) return true;
            else return false;
            */
        }
    }

});

sessionServices.js

'use strict';

app.factory('sessionService', ['$http', function($http){
    return{
        set:function(key,value){
            return sessionStorage.setItem(key,value);
        },
        get:function(key){
            return sessionStorage.getItem(key);
        },
        destroy:function(key){
            $http.post('data/destroy_session.php');
            return sessionStorage.removeItem(key);
        }
    };
}])

loginCtrl.js

'use strict';

app.controller('loginCtrl', ['$scope','loginService', function ($scope,loginService) {
    $scope.msgtxt='';
    $scope.login=function(data){
        loginService.login(data,$scope); //call login service
    };

}]);

How to give a user only select permission on a database

For the GUI minded people, you can:

  • Right click the Database in Management Studio.
  • Choose Properties
  • Select Permissions
  • If your user does not show up in the list, choose Search and type their name
  • Select the user in the Users or Roles list
  • In the lower window frame, Check the Select permission under the Grant column

What is SYSNAME data type in SQL Server?

sysname is a built in datatype limited to 128 Unicode characters that, IIRC, is used primarily to store object names when creating scripts. Its value cannot be NULL

It is basically the same as using nvarchar(128) NOT NULL

EDIT

As mentioned by @Jim in the comments, I don't think there is really a business case where you would use sysname to be honest. It is mainly used by Microsoft when building the internal sys tables and stored procedures etc within SQL Server.

For example, by executing Exec sp_help 'sys.tables' you will see that the column name is defined as sysname this is because the value of this is actually an object in itself (a table)

I would worry too much about it.

It's also worth noting that for those people still using SQL Server 6.5 and lower (are there still people using it?) the built in type of sysname is the equivalent of varchar(30)

Documentation

sysname is defined with the documentation for nchar and nvarchar, in the remarks section:

sysname is a system-supplied user-defined data type that is functionally equivalent to nvarchar(128), except that it is not nullable. sysname is used to reference database object names.

To clarify the above remarks, by default sysname is defined as NOT NULL it is certainly possible to define it as nullable. It is also important to note that the exact definition can vary between instances of SQL Server.

Using Special Data Types

The sysname data type is used for table columns, variables, and stored procedure parameters that store object names. The exact definition of sysname is related to the rules for identifiers. Therefore, it can vary between instances of SQL Server. sysname is functionally the same as nvarchar(128) except that, by default, sysname is NOT NULL. In earlier versions of SQL Server, sysname is defined as varchar(30).

Some further information about sysname allowing or disallowing NULL values can be found here https://stackoverflow.com/a/52290792/300863

Just because it is the default (to be NOT NULL) does not guarantee that it will be!

How do I indent multiple lines at once in Notepad++?

in Notepad++v6.1.8 (Unicode) it works after removing the QuickText plugin.

What is the size limit of a post request?

As David pointed out, I would go with KB in most cases.

php_value post_max_size 2K

Note: my form is simple, just a few text boxes, not long text.

(PHP shorthand for KB is K, as outlined here.)

JavaScript for detecting browser language preference

Dan Singerman's answer has an issue that the header fetched has to be used right away, due to the asynchronous nature of jQuery's ajax. However, with his google app server, I wrote the following, such that the header is set as part of the initial set up and can be used at later time.

<html>
<head>
<script>

    var bLocale='raw'; // can be used at any other place

    function processHeaders(headers){
        bLocale=headers['Accept-Language'];
        comma=bLocale.indexOf(',');
        if(comma>0) bLocale=bLocale.substring(0, comma);
    }

</script>

<script src="jquery-1.11.0.js"></script>

<script type="application/javascript" src="http://ajaxhttpheaders.appspot.com?callback=processHeaders"></script>

</head>
<body>

<h1 id="bLocale">Should be the browser locale here</h1>

</body>

<script>

    $("#bLocale").text(bLocale);

</script>
</html>

Excel: replace part of cell's string value

I know this is old but I had a similar need for this and I did not want to do the find and replace version. It turns out that you can nest the substitute method like so:

=SUBSTITUTE(SUBSTITUTE(F149, "a", " AM"), "p", " PM")

In my case, I am using excel to view a DBF file and however it was populated has times like this:

9:16a
2:22p

So I just made a new column and put that formula in it to convert it to the excel time format.

The entity type <type> is not part of the model for the current context

You may try removing the table from the model and adding it again. You can do this visually by opening the .edmx file from the Solution Explorer.

Steps:

  1. Double click the .edmx file from the Solution Explorer
  2. Right click on the table head you want to remove and select "Delete from Model"
  3. Now again right click on the work area and select "Update Model from Database.."
  4. Add the table again from the table list
  5. Clean and build the solution

Android: How can I validate EditText input?

In order to reduce the verbosity of the validation logic I have authored a library for Android. It takes care of most of the day to day validations using Annotations and built-in rules. There are constraints such as @TextRule, @NumberRule, @Required, @Regex, @Email, @IpAddress, @Password, etc.,

You can add these annotations to your UI widget references and perform validations. It also allows you to perform validations asynchronously which is ideal for situations such as checking for unique username from a remote server.

There is a example on the project home page on how to use annotations. You can also read the associated blog post where I have written sample codes on how to write custom rules for validations.

Here is a simple example that depicts the usage of the library.

@Required(order = 1)
@Email(order = 2)
private EditText emailEditText;

@Password(order = 3)
@TextRule(order = 4, minLength = 6, message = "Enter at least 6 characters.")
private EditText passwordEditText;

@ConfirmPassword(order = 5)
private EditText confirmPasswordEditText;

@Checked(order = 6, message = "You must agree to the terms.")
private CheckBox iAgreeCheckBox;

The library is extendable, you can write your own rules by extending the Rule class.

add new element in laravel collection object

If you want to add a product into the array you can use:

$item['product'] = $product;

git stash -> merge stashed change with current changes

What I want is a way to merge my stashed changes with the current changes

Here is another option to do it:

git stash show -p|git apply
git stash drop

git stash show -p will show the patch of last saved stash. git apply will apply it. After the merge is done, merged stash can be dropped with git stash drop.

Splitting a string into chunks of a certain size

This is based on @dove solution but implemented as an extension method.

Benefits:

  • Extension method
  • Covers corner cases
  • Splits string with any chars: numbers, letters, other symbols

Code

public static class EnumerableEx
{    
    public static IEnumerable<string> SplitBy(this string str, int chunkLength)
    {
        if (String.IsNullOrEmpty(str)) throw new ArgumentException();
        if (chunkLength < 1) throw new ArgumentException();

        for (int i = 0; i < str.Length; i += chunkLength)
        {
            if (chunkLength + i > str.Length)
                chunkLength = str.Length - i;

            yield return str.Substring(i, chunkLength);
        }
    }
}

Usage

var result = "bobjoecat".SplitBy(3); // bob, joe, cat

Unit tests removed for brevity (see previous revision)

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

All required parameters must be placed before any default arguments. Simply because they are mandatory, whereas default arguments are not. Syntactically, it would be impossible for the interpreter to decide which values match which arguments if mixed modes were allowed. A SyntaxError is raised if the arguments are not given in the correct order:

Let us take a look at keyword arguments, using your function.

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

Suppose its allowed to declare function as above, Then with the above declarations, we can make the following (regular) positional or keyword argument calls:

func1("ok a", "ok b", 1)  # Is 1 assigned to x or ?
func1(1)                  # Is 1 assigned to a or ?
func1(1, 2)               # ?

How you will suggest the assignment of variables in the function call, how default arguments are going to be used along with keyword arguments.

>>> def fun1(x, y, a="who is you", b="True"):
...     print a,b,x,y
... 

Reference O'Reilly - Core-Python
Where as this function make use of the default arguments syntactically correct for above function calls. Keyword arguments calling prove useful for being able to provide for out-of-order positional arguments, but, coupled with default arguments, they can also be used to "skip over" missing arguments as well.

How to change checkbox's border style in CSS?

If something happens in any browser I'd be surprised. This is one of those outstanding form elements that browsers tend not to let you style that much, and that people usually try to replace with javascript so they can style/code something to look and act like a checkbox.

Multiple file-extensions searchPattern for System.IO.Directory.GetFiles

I would try to specify something like

var searchPattern = "as?x";

it should work.

How to ignore the first line of data when processing CSV data?

just add [1:]

example below:

data = pd.read_csv("/Users/xyz/Desktop/xyxData/xyz.csv", sep=',', header=None)**[1:]**

that works for me in iPython

Does Django scale?

Check out this micro news aggregator called EveryBlock.

It's entirely written in Django. In fact they are the people who developed the Django framework itself.

Setting CSS pseudo-class rules from JavaScript

Just place the css in a template string.

const cssTemplateString = `.foo:[psuedoSelector]{prop: value}`;

Then create a style element and place the string in the style tag and attach it to the document.

const styleTag = document.createElement("style");
styleTag.innerHTML = cssTemplateString;
document.head.insertAdjacentElement('beforeend', styleTag);

Specificity will take care of the rest. Then you can remove and add style tags dynamically. This is a simple alternative to libraries and messing with the stylesheet array in the DOM. Happy Coding!

Get Environment Variable from Docker Container

None of the above answers show you how to extract a variable from a non-running container (if you use the echo approach with run, you won't get any output).

Simply run with printenv, like so:

docker run --rm <container> printenv <MY_VAR>

(Note that docker-compose instead of docker works too)

Return HTML content as a string, given URL. Javascript Function

Here's a version of the accepted answer that 1) returns a value from the function (bugfix), and 2) doesn't break when using "use strict";

I use this code to pre-load a .txt file into my <textarea> when the user loads the page.

function httpGet(theUrl)
{
    let xmlhttp;
    
    if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    } else { // code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            return xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET", theUrl, false);
    xmlhttp.send();
    
    return xmlhttp.response;
}

Print the data in ResultSet along with column names

Have a look at the documentation. You made the following mistakes. Firstly, ps.executeQuery() doesn't have any parameters. Instead you passed the SQL query into it.

Secondly, regarding the prepared statement, you have to use the ? symbol if want to pass any parameters. And later bind it using

setXXX(index, value) 

Here xxx stands for the data type.

Why is there no Constant feature in Java?

What does const mean
First, realize that the semantics of a "const" keyword means different things to different people:

  • read-only reference - Java final semantics - reference variable itself cannot be reassigned to point to another instance (memory location), but the instance itself is modifiable
  • readable-only reference - C const pointer/reference semantics - means this reference cannot be used to modify the instance (e.g. cannot assign to instance variables, cannot invoke mutable methods) - affects the reference variable only, so a non-const reference pointing to the same instance could modify the instance
  • immutable object - means the instance itself cannot be modified - applies to instance, so any non-const reference would not be allowed or could not be used to modify the instance
  • some combination of the the above?
  • others?

Why or Why Not const
Second, if you really want to dig into some of the "pro" vs "con" arguments, see the discussion under this request for enhancement (RFE) "bug". This RFE requests a "readable-only reference"-type "const" feature. Opened in 1999 and then closed/rejected by Sun in 2005, the "const" topic was vigorously debated:

http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4211070

While there are a lot of good arguments on both sides, some of the oft-cited (but not necessarily compelling or clear-cut) reasons against const include:

  • may have confusing semantics that may be misused and/or abused (see the What does const mean above)
  • may duplicate capability otherwise available (e.g. designing an immutable class, using an immutable interface)
  • may be feature creep, leading to a need for other semantic changes such as support for passing objects by value

Before anyone tries to debate me about whether these are good or bad reasons, note that these are not my reasons. They are simply the "gist" of some of the reasons I gleaned from skimming the RFE discussion. I don't necessarily agree with them myself - I'm simply trying to cite why some people (not me) may feel a const keyword may not be a good idea. Personally, I'd love more "const" semantics to be introduced to the language in an unambiguous manner.

Set position / size of UI element as percentage of screen size

For TextView and it's descendants (e.g., Button) you can get the display size from the WindowManager and then set the TextView height to be some fraction of it:

Button btn = new Button (this);
android.view.Display display = ((android.view.WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); 
btn.setHeight((int)(display.getHeight()*0.68));

Install windows service without InstallUtil.exe

Topshelf is an OSS project which was started after this question was answered and it makes Windows service much, MUCH easier.I highly recommend looking into it.

http://topshelf-project.com/

Iterate all files in a directory using a 'for' loop

Iterate through...

  • ...files in current dir: for %f in (.\*) do @echo %f
  • ...subdirs in current dir: for /D %s in (.\*) do @echo %s
  • ...files in current and all subdirs: for /R %f in (.\*) do @echo %f
  • ...subdirs in current and all subdirs: for /R /D %s in (.\*) do @echo %s

Unfortunately I did not find any way to iterate over files and subdirs at the same time.

Just use cygwin with its bash for much more functionality.

Apart from this: Did you notice, that the buildin help of MS Windows is a great resource for descriptions of cmd's command line syntax?

Also have a look here: http://technet.microsoft.com/en-us/library/bb490890.aspx

Count the Number of Tables in a SQL Server Database

You can use INFORMATION_SCHEMA.TABLES to retrieve information about your database tables.

As mentioned in the Microsoft Tables Documentation:

INFORMATION_SCHEMA.TABLES returns one row for each table in the current database for which the current user has permissions.

The following query, therefore, will return the number of tables in the specified database:

USE MyDatabase
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'

As of SQL Server 2008, you can also use sys.tables to count the the number of tables.

From the Microsoft sys.tables Documentation:

sys.tables returns a row for each user table in SQL Server.

The following query will also return the number of table in your database:

SELECT COUNT(*)
FROM sys.tables

Convert string to integer type in Go?

Converting Simple strings

The easiest way is to use the strconv.Atoi() function.

Note that there are many other ways. For example fmt.Sscan() and strconv.ParseInt() which give greater flexibility as you can specify the base and bitsize for example. Also as noted in the documentation of strconv.Atoi():

Atoi is equivalent to ParseInt(s, 10, 0), converted to type int.

Here's an example using the mentioned functions (try it on the Go Playground):

flag.Parse()
s := flag.Arg(0)

if i, err := strconv.Atoi(s); err == nil {
    fmt.Printf("i=%d, type: %T\n", i, i)
}

if i, err := strconv.ParseInt(s, 10, 64); err == nil {
    fmt.Printf("i=%d, type: %T\n", i, i)
}

var i int
if _, err := fmt.Sscan(s, &i); err == nil {
    fmt.Printf("i=%d, type: %T\n", i, i)
}

Output (if called with argument "123"):

i=123, type: int
i=123, type: int64
i=123, type: int

Parsing Custom strings

There is also a handy fmt.Sscanf() which gives even greater flexibility as with the format string you can specify the number format (like width, base etc.) along with additional extra characters in the input string.

This is great for parsing custom strings holding a number. For example if your input is provided in a form of "id:00123" where you have a prefix "id:" and the number is fixed 5 digits, padded with zeros if shorter, this is very easily parsable like this:

s := "id:00123"

var i int
if _, err := fmt.Sscanf(s, "id:%5d", &i); err == nil {
    fmt.Println(i) // Outputs 123
}

Can constructors throw exceptions in Java?

Yes, it can throw an exception and you can declare that in the signature of the constructor too as shown in the example below:

public class ConstructorTest
{
    public ConstructorTest() throws InterruptedException
    {
        System.out.println("Preparing object....");
        Thread.sleep(1000);
        System.out.println("Object ready");
    }

    public static void main(String ... args)
    {
        try
        {
            ConstructorTest test = new ConstructorTest();
        }
        catch (InterruptedException e)
        {
            System.out.println("Got interrupted...");
        }
    }
}

Missing Microsoft RDLC Report Designer in Visual Studio

I've had the same problem as you and I installed Microsoft rdlc designer to solve my problem.

And if you already installed this but still can't found rdlc designer try open visual studio > tools > Extension and Updates > then enable Miscrosoft Rdlc designer extensions.

Can't use SURF, SIFT in OpenCV

As per June 2020, I suppose this version (pip install -U opencv-contrib-python==3.4.2.16) is still working. so install it and enjoy.

What causing this "Invalid length for a Base-64 char array"

I've seen this error caused by the combination of good sized viewstate and over aggressive content-filtering devices/firewalls (especially when dealing with K-12 Educational institutions).

We worked around it by storing Viewstate in SQL Server. Before going that route, I would recommend trying to limit your use of viewstate by not storing anything large in it and turning it off for all controls which do not need it.

References for storing ViewState in SQL Server:
MSDN - Overview of PageStatePersister
ASP Alliance - Simple method to store viewstate in SQL Server
Code Project - ViewState Provider Model

how to remove empty strings from list, then remove duplicate values from a list

Amiram's answer is correct, but Distinct() as implemented is an N2 operation; for each item in the list, the algorithm compares it to all the already processed elements, and returns it if it's unique or ignores it if not. We can do better.

A sorted list can be deduped in linear time; if the current element equals the previous element, ignore it, otherwise return it. Sorting is NlogN, so even having to sort the collection, we get some benefit:

public static IEnumerable<T> SortAndDedupe<T>(this IEnumerable<T> input)
{
   var toDedupe = input.OrderBy(x=>x);

   T prev;
   foreach(var element in toDedupe)
   {
      if(element == prev) continue;

      yield return element;
      prev = element;      
   }
}

//Usage
dtList  = dtList.Where(s => !string.IsNullOrWhitespace(s)).SortAndDedupe().ToList();

This returns the same elements; they're just sorted.

Foreach with JSONArray and JSONObject

Make sure you are using this org.json: https://mvnrepository.com/artifact/org.json/json

if you are using Java 8 then you can use

import org.json.JSONArray;
import org.json.JSONObject;

JSONArray array = ...;

array.forEach(item -> {
    JSONObject obj = (JSONObject) item;
    parse(obj);
});

Just added a simple test to prove that it works:

Add the following dependency into your pom.xml file (To prove that it works, I have used the old jar which was there when I have posted this answer)

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

And the simple test code snippet will be:

import org.json.JSONArray;
import org.json.JSONObject;

public class Test {
    public static void main(String args[]) {
        JSONArray array = new JSONArray();

        JSONObject object = new JSONObject();
        object.put("key1", "value1");

        array.put(object);

        array.forEach(item -> {
            System.out.println(item.toString());
        });
    }
}

output:

{"key1":"value1"}

Can I get JSON to load into an OrderedDict?

Yes, you can. By specifying the object_pairs_hook argument to JSONDecoder. In fact, this is the exact example given in the documentation.

>>> json.JSONDecoder(object_pairs_hook=collections.OrderedDict).decode('{"foo":1, "bar": 2}')
OrderedDict([('foo', 1), ('bar', 2)])
>>> 

You can pass this parameter to json.loads (if you don't need a Decoder instance for other purposes) like so:

>>> import json
>>> from collections import OrderedDict
>>> data = json.loads('{"foo":1, "bar": 2}', object_pairs_hook=OrderedDict)
>>> print json.dumps(data, indent=4)
{
    "foo": 1,
    "bar": 2
}
>>> 

Using json.load is done in the same way:

>>> data = json.load(open('config.json'), object_pairs_hook=OrderedDict)

How to search in a List of Java object

I modifie this list and add a List to the samples try this

Pseudocode

Sample {
   List<String> values;
   List<String> getList() {
   return values}
}



for(Sample s : list) {
   if(s.getString.getList.contains("three") {
      return s;
   }
}

How to receive serial data using android bluetooth

Take a look at incredible Bluetooth Serial class that has onResume() ability that helped me so much. I hope this helps ;)

How can I change the user on Git Bash?

For any OS

This helped me so I'll put it here, just in case. Once you are done with adding the rsa keys for both the accounts, add a config file in your .ssh directory for both the accounts (.ssh/config)

# First account
Host github.com-<FIRST_ACCOUNT_USERNAME_HERE>
   HostName github.com
   User git
   IdentityFile ~/.ssh/id_rsa_user1
   
# Second account
Host github.com-<SECOND_ACCOUNT_USERNAME_HERE>   
   HostName github.com
   User git
   IdentityFile ~/.ssh/id_rsa_user2

Make sure you use the correct usernames and RSA files. Next, you can open the terminal/git bash on the repository root and check which account you would be pushing from

git config user.email

Suppose this returns the first user email and you want to push from the second user. Change the local user.name and user.email :

git config user.name "SECOND_USER"
git config user.email "[email protected]"

(This won't change the global config and you can have the first user set up as the global user). Once done, you can confirm with git config user.email and it should return the email of the second user. You're all set to push to GitHub with the second user. The rest is all the same old git add , git commit and git push. To push from the first user, change the local user.name again and follow the same steps. Hope it helps :)


If the above steps are still not working for you, check to see if you have uploaded the RSA keys within GitHub portal. Refer to GitHub documentation:

Then, clear your ssh cached keys Reference

ssh-add -D

Then add you 2 ssh keys

ssh-add ~/.ssh/id_rsa_user1
ssh-add ~/.ssh/id_rsa_user2

Then type in your terminal:

ssh -T [email protected]<SECOND_ACCOUNT_USERNAME_HERE>

You should see the following output:

Hi <SECOND_USERNAME>! You've successfully authenticated, but GitHub does not provide shell access.

Then, assign the correct remote to your local repository. Make sure you put the same username as the one you gave in your .ssh/config file next to Host. In the following case [email protected]<SECOND_ACCOUNT_USERNAME_HERE>.

git remote rm origin
git remote add origin [email protected]<SECOND_ACCOUNT_USERNAME_HERE>:/your_username/your_repository.git

Automatic vertical scroll bar in WPF TextBlock?

<ScrollViewer Height="239" VerticalScrollBarVisibility="Auto">
    <TextBox AcceptsReturn="True" TextWrapping="Wrap" LineHeight="10" />
</ScrollViewer>

This is way to use the scrolling TextBox in XAML and use it as a text area.

Run a string as a command within a Bash script

Here is my gradle build script that executes strings stored in heredocs:

current_directory=$( realpath "." )
GENERATED=${current_directory}/"GENERATED"
build_gradle=$( realpath build.gradle )

## touch because .gitignore ignores this folder:
touch $GENERATED

COPY_BUILD_FILE=$( cat <<COPY_BUILD_FILE_HEREDOC

    cp 
        $build_gradle 
        $GENERATED/build.gradle

COPY_BUILD_FILE_HEREDOC
)
$COPY_BUILD_FILE

GRADLE_COMMAND=$( cat <<GRADLE_COMMAND_HEREDOC

    gradle run

        --build-file       
            $GENERATED/build.gradle

        --gradle-user-home 
            $GENERATED  

        --no-daemon

GRADLE_COMMAND_HEREDOC
)
$GRADLE_COMMAND

The lone ")" are kind of ugly. But I have no clue how to fix that asthetic aspect.

Appending items to a list of lists in python

Python lists are mutable objects and here:

plot_data = [[]] * len(positions) 

you are repeating the same list len(positions) times.

>>> plot_data = [[]] * 3
>>> plot_data
[[], [], []]
>>> plot_data[0].append(1)
>>> plot_data
[[1], [1], [1]]
>>> 

Each list in your list is a reference to the same object. You modify one, you see the modification in all of them.

If you want different lists, you can do this way:

plot_data = [[] for _ in positions]

for example:

>>> pd = [[] for _ in range(3)]
>>> pd
[[], [], []]
>>> pd[0].append(1)
>>> pd
[[1], [], []]

Flask SQLAlchemy query, specify column names

As session.query(SomeModel.col1) returns an array of tuples like this [('value_1',),('value_2',)] if you want t cast the result to a plain array you can do it by using one of the following statements:

values = [value[0] for value in session.query(SomeModel.col1)]
values = [model.col1 for model in session.query(SomeModel).options(load_only('col1'))]

Result:

 ['value_1', 'value_2']

The easiest way to replace white spaces with (underscores) _ in bash

This is borderline programming, but look into using tr:

$ echo "this is just a test" | tr -s ' ' | tr ' ' '_'

Should do it. The first invocation squeezes the spaces down, the second replaces with underscore. You probably need to add TABs and other whitespace characters, this is for spaces only.

Case insensitive searching in Oracle

Since 10gR2, Oracle allows to fine-tune the behaviour of string comparisons by setting the NLS_COMP and NLS_SORT session parameters:

SQL> SET HEADING OFF
SQL> SELECT *
  2  FROM NLS_SESSION_PARAMETERS
  3  WHERE PARAMETER IN ('NLS_COMP', 'NLS_SORT');

NLS_SORT
BINARY

NLS_COMP
BINARY


SQL>
SQL> SELECT CASE WHEN 'abc'='ABC' THEN 1 ELSE 0 END AS GOT_MATCH
  2  FROM DUAL;

         0

SQL>
SQL> ALTER SESSION SET NLS_COMP=LINGUISTIC;

Session altered.

SQL> ALTER SESSION SET NLS_SORT=BINARY_CI;

Session altered.

SQL>
SQL> SELECT *
  2  FROM NLS_SESSION_PARAMETERS
  3  WHERE PARAMETER IN ('NLS_COMP', 'NLS_SORT');

NLS_SORT
BINARY_CI

NLS_COMP
LINGUISTIC


SQL>
SQL> SELECT CASE WHEN 'abc'='ABC' THEN 1 ELSE 0 END AS GOT_MATCH
  2  FROM DUAL;

         1

You can also create case insensitive indexes:

create index
   nlsci1_gen_person
on
   MY_PERSON
   (NLSSORT
      (PERSON_LAST_NAME, 'NLS_SORT=BINARY_CI')
   )
;

This information was taken from Oracle case insensitive searches. The article mentions REGEXP_LIKE but it seems to work with good old = as well.


In versions older than 10gR2 it can't really be done and the usual approach, if you don't need accent-insensitive search, is to just UPPER() both the column and the search expression.

How to import Swagger APIs into Postman?

You can do that: Postman -> Import -> Link -> {root_url}/v2/api-docs

Problems with a PHP shell script: "Could not open input file"

Due to windows encoding issue for me

I experienced this "Could not open input file" error. Then I obtained the file using wget from another linux system, and the error did not occur.

The error ws only occurring for me when the file transited through windows.

Can I set text box to readonly when using Html.TextBoxFor?

By setting readonly attribute to either true or false is not going to work in most browsers, I have done it as below, when the mode of the page is "reload", I've not included "readonly" attribute.

@if(Model.Mode.Equals("edit")){
@Html.TextAreaFor(model => Model.Content.Data, new { id = "modEditor", @readonly = moduleEditModel.Content.ReadOnly, @style = "width:99%; height:360px;" })
}
@if (Model.Mode.Equals("reload")){
@Html.TextAreaFor(model => Model.Content.Data, new { id = "modEditor", @style = "width:99%; height:360px;" })}

Example of Named Pipes

Linux dotnet core doesn't support namedpipes!

Try TcpListener if you deploy to Linux

This NamedPipe Client/Server code round trips a byte to a server.

  • Client writes byte
  • Server reads byte
  • Server writes byte
  • Client reads byte

DotNet Core 2.0 Server ConsoleApp

using System;
using System.IO.Pipes;
using System.Threading.Tasks;

namespace Server
{
    class Program
    {
        static void Main(string[] args)
        {
            var server = new NamedPipeServerStream("A", PipeDirection.InOut);
            server.WaitForConnection();

            for (int i =0; i < 10000; i++)
            {
                var b = new byte[1];
                server.Read(b, 0, 1); 
                Console.WriteLine("Read Byte:" + b[0]);
                server.Write(b, 0, 1);
            }
        }
    }
}

DotNet Core 2.0 Client ConsoleApp

using System;
using System.IO.Pipes;
using System.Threading.Tasks;

namespace Client
{
    class Program
    {
        public static int threadcounter = 1;
        public static NamedPipeClientStream client;

        static void Main(string[] args)
        {
            client = new NamedPipeClientStream(".", "A", PipeDirection.InOut, PipeOptions.Asynchronous);
            client.Connect();

            var t1 = new System.Threading.Thread(StartSend);
            var t2 = new System.Threading.Thread(StartSend);

            t1.Start();
            t2.Start(); 
        }

        public static void StartSend()
        {
            int thisThread = threadcounter;
            threadcounter++;

            StartReadingAsync(client);

            for (int i = 0; i < 10000; i++)
            {
                var buf = new byte[1];
                buf[0] = (byte)i;
                client.WriteAsync(buf, 0, 1);

                Console.WriteLine($@"Thread{thisThread} Wrote: {buf[0]}");
            }
        }

        public static async Task StartReadingAsync(NamedPipeClientStream pipe)
        {
            var bufferLength = 1; 
            byte[] pBuffer = new byte[bufferLength];

            await pipe.ReadAsync(pBuffer, 0, bufferLength).ContinueWith(async c =>
            {
                Console.WriteLine($@"read data {pBuffer[0]}");
                await StartReadingAsync(pipe); // read the next data <-- 
            });
        }
    }
}

Formatting Decimal places in R

Check functions prettyNum, format

to have trialling zeros (123.1240 for example) use sprintf(x, fmt='%#.4g')

Possible to perform cross-database queries with PostgreSQL?

Just to add a bit more information.

There is no way to query a database other than the current one. Because PostgreSQL loads database-specific system catalogs, it is uncertain how a cross-database query should even behave.

contrib/dblink allows cross-database queries using function calls. Of course, a client can also make simultaneous connections to different databases and merge the results on the client side.

PostgreSQL FAQ

No connection string named 'MyEntities' could be found in the application config file

are you using more than one project on your solution?

Because if you are, the web config you must check is the one on the same project as de .edmx file

Python in Xcode 4+?

This Technical Note TN2328 from Apple Developer Library helped me a lot about Changes To Embedding Python Using Xcode 5.0.

nodejs get file name from absolute path?

For those interested in removing extension from filename, you can use https://nodejs.org/api/path.html#path_path_basename_path_ext

path.basename('/foo/bar/baz/asdf/quux.html', '.html');

setting the id attribute of an input element dynamically in IE: alternative for setAttribute method

The documentation says:

When you need to set attributes that are also mapped to a JavaScript dot-property (such as href, style, src or event-handlers), favour that mapping instead.

So, just change id, value assignment and you should be done.

CSS table-cell equal width

this will work for everyone

_x000D_
_x000D_
<table border="your val" cellspacing="your val" cellpadding="your val" role="grid" style="width=100%; table-layout=fixed">_x000D_
<!-- set the table td element roll attr to gridcell -->_x000D_
<tr>_x000D_
<td roll="gridcell"></td>_x000D_
</tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

This will also work for table data created by iteration

Update query using Subquery in Sql Server

because you are just learning I suggest you practice converting a SELECT joins to UPDATE or DELETE joins. First I suggest you generate a SELECT statement joining these two tables:

SELECT *
FROM    tempDataView a
        INNER JOIN tempData b
            ON a.Name = b.Name

Then note that we have two table aliases a and b. Using these aliases you can easily generate UPDATE statement to update either table a or b. For table a you have an answer provided by JW. If you want to update b, the statement will be:

UPDATE  b
SET     b.marks = a.marks
FROM    tempDataView a
        INNER JOIN tempData b
            ON a.Name = b.Name

Now, to convert the statement to a DELETE statement use the same approach. The statement below will delete from a only (leaving b intact) for those records that match by name:

DELETE a
FROM    tempDataView a
        INNER JOIN tempData b
            ON a.Name = b.Name

You can use the SQL Fiddle created by JW as a playground

Add/remove class with jquery based on vertical scroll?

Its my code

jQuery(document).ready(function(e) {
    var WindowHeight = jQuery(window).height();

    var load_element = 0;

    //position of element
    var scroll_position = jQuery('.product-bottom').offset().top;

    var screen_height = jQuery(window).height();
    var activation_offset = 0;
    var max_scroll_height = jQuery('body').height() + screen_height;

    var scroll_activation_point = scroll_position - (screen_height * activation_offset);

    jQuery(window).on('scroll', function(e) {

        var y_scroll_pos = window.pageYOffset;
        var element_in_view = y_scroll_pos > scroll_activation_point;
        var has_reached_bottom_of_page = max_scroll_height <= y_scroll_pos && !element_in_view;

        if (element_in_view || has_reached_bottom_of_page) {
            jQuery('.product-bottom').addClass("change");
        } else {
            jQuery('.product-bottom').removeClass("change");
        }

    });

});

Its working Fine

How to find all links / pages on a website

function getalllinks($url) {
    $links = array();
    if ($fp = fopen($url, 'r')) {
        $content = '';
        while ($line = fread($fp, 1024)) {
            $content. = $line;
        }
    }
    $textLen = strlen($content);
    if ($textLen > 10) {
        $startPos = 0;
        $valid = true;
        while ($valid) {
            $spos = strpos($content, '<a ', $startPos);
            if ($spos < $startPos) $valid = false;
            $spos = strpos($content, 'href', $spos);
            $spos = strpos($content, '"', $spos) + 1;
            $epos = strpos($content, '"', $spos);
            $startPos = $epos;
            $link = substr($content, $spos, $epos - $spos);
            if (strpos($link, 'http://') !== false) $links[] = $link;
        }
    }
    return $links;
}

try this code....

Fastest way to compute entropy in Python

With the data as a pd.Series and scipy.stats, calculating the entropy of a given quantity is pretty straightforward:

import pandas as pd
import scipy.stats

def ent(data):
    """Calculates entropy of the passed `pd.Series`
    """
    p_data = data.value_counts()           # counts occurrence of each value
    entropy = scipy.stats.entropy(p_data)  # get entropy from counts
    return entropy

Note: scipy.stats will normalize the provided data, so this doesn't need to be done explicitly, i.e. passing an array of counts works fine.

How to see the values of a table variable at debug time in T-SQL?

This project https://github.com/FilipDeVos/sp_select has a stored procedure sp_select which allows for selecting from a temp table.

Usage:

exec sp_select 'tempDb..#myTempTable'

While debugging a stored procedure you can open a new tab and run this command to see the contents of the temp table.

javac: invalid target release: 1.8

Installing a newer release of IDEA Community (2018.3 instead of 2017.x) was solved my issue with same error but java version:11. Reimport hadn't worked for me. But it worth a try.

CSS background opacity with rgba not working in IE 8

the transparent png image will not work in IE 6-, alternatives are:

with CSS:

.transparent {

    /* works for IE 5+. */
    filter:alpha(opacity=30); 

    /* works for IE 8. */
    -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=30)";

    /* works for old school versions of the Mozilla browsers like Netscape Navigator. */
    -moz-opacity:0.3; 

    /* This is for old versions of Safari (1.x) with KHTML rendering engine */
    -khtml-opacity: 0.3; 

    /* This is the "most important" one because it's the current standard in CSS. This will work in most versions of Firefox, Safari, and Opera. */  
    opacity: 0.3; 
}

or just do it with jQuery:

// a crossbrowser solution
$(document).ready(function(){ 
    $(".transparent").css('opacity','.3');
});

Errno 13 Permission denied Python

For future searchers, if none of the above worked, for me, python was trying to open a folder as a file.

How do I get the MAX row with a GROUP BY in LINQ query?

I've checked DamienG's answer in LinqPad. Instead of

g.Group.Max(s => s.uid)

should be

g.Max(s => s.uid)

Thank you!

Unit testing void methods?

If a method doesn't return anything, it's either one of the following

  • imperative - You're either asking the object to do something to itself.. e.g change state (without expecting any confirmation.. its assumed that it will be done)
  • informational - just notifying someone that something happened (without expecting action or response) respectively.

Imperative methods - you can verify if the task was actually performed. Verify if state change actually took place. e.g.

void DeductFromBalance( dAmount ) 

can be tested by verifying if the balance post this message is indeed less than the initial value by dAmount

Informational methods - are rare as a member of the public interface of the object... hence not normally unit-tested. However if you must, You can verify if the handling to be done on a notification takes place. e.g.

void OnAccountDebit( dAmount )  // emails account holder with info

can be tested by verifying if the email is being sent

Post more details about your actual method and people will be able to answer better.
Update: Your method is doing 2 things. I'd actually split it into two methods that can now be independently tested.

string[] ExamineLogFileForX( string sFileName );
void InsertStringsIntoDatabase( string[] );

String[] can be easily verified by providing the first method with a dummy file and expected strings. The second one is slightly tricky.. you can either use a Mock (google or search stackoverflow on mocking frameworks) to mimic the DB or hit the actual DB and verify if the strings were inserted in the right location. Check this thread for some good books... I'd recomment Pragmatic Unit Testing if you're in a crunch.
In the code it would be used like

InsertStringsIntoDatabase( ExamineLogFileForX( "c:\OMG.log" ) );

Writing Unicode text to a text file?

In Python 2.6+, you could use io.open() that is default (builtin open()) on Python 3:

import io

with io.open(filename, 'w', encoding=character_encoding) as file:
    file.write(unicode_text)

It might be more convenient if you need to write the text incrementally (you don't need to call unicode_text.encode(character_encoding) multiple times). Unlike codecs module, io module has a proper universal newlines support.

ImportError: No module named tensorflow

Activate the virtualenv environment by issuing one of the following commands:

$ source ~/tensorflow/bin/activate # bash, sh, ksh, or zsh
$ source ~/tensorflow/bin/activate.csh # csh or tcsh

Hope this help

NSURLSession/NSURLConnection HTTP load failed on iOS 9

You should add App Transport Security Settings to info.plist and add Allow Arbitrary Loads to App Transport Security Settings

enter image description here

<key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
    </dict>

AWS S3 CLI - Could not connect to the endpoint URL

Everyone has different defaults, and interestingly it will change after time. As an example, first I was on global, and then after 15 minutes it shows Ohio (which is us-east-2).

The best approach is to check it during your work -- in console of your AWS working area, just set it on the right above side near your name on top bar check your region name and click on the down arrow to see your region.

In AWS CLI type aws configure or aws2 configure, give your access and secret id, then during default region, write your region and press Enter.

You will definitely get access to specific region set and it will work.

How do I create a datetime in Python from milliseconds?

Converting millis to datetime (UTC):

import datetime
time_in_millis = 1596542285000
dt = datetime.datetime.fromtimestamp(time_in_millis / 1000.0, tz=datetime.timezone.utc)

Converting datetime to string following the RFC3339 standard (used by Open API specification):

from rfc3339 import rfc3339
converted_to_str = rfc3339(dt, utc=True, use_system_timezone=False)
# 2020-08-04T11:58:05Z

Find and replace in file and overwrite file doesn't work, it empties the file

You can use Vim in Ex mode:

ex -sc '%s/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g|x' index.html
  1. % select all lines

  2. x save and close

In Bootstrap 3,How to change the distance between rows in vertical?

If it was me I would introduce new CSS class and use along with unmodified bootstrap row class.

HTML

<div class="row extra-bottom-padding" id="a">
   <img>...</img>
<div>
<div class="row" id="b">
   <button>..</button>
<div>

CSS

.row.extra-bottom-padding{
   margin-bottom: 20px;
}

RequestDispatcher.forward() vs HttpServletResponse.sendRedirect()

SendRedirect() will search the content between the servers. it is slow because it has to intimate the browser by sending the URL of the content. then browser will create a new request for the content within the same server or in another one.

RquestDispatcher is for searching the content within the server i think. its the server side process and it is faster compare to the SendRedirect() method. but the thing is that it will not intimate the browser in which server it is searching the required date or content, neither it will not ask the browser to change the URL in URL tab. so it causes little inconvenience to the user.

PHP: How do you determine every Nth iteration of a loop?

How about: if(($counter % $display) == 0)

Passing arguments to an interactive program non-interactively

For more complex tasks there is expect ( http://en.wikipedia.org/wiki/Expect ). It basically simulates a user, you can code a script how to react to specific program outputs and related stuff.

This also works in cases like ssh that prohibits piping passwords to it.

Forbidden You don't have permission to access /wp-login.php on this server

I had a similar error, which was fixed by adding:

Options FollowSymLinks

... in the apps/[app-name]/conf/httpd-app.conf file. This is because, in my case, an .htaccess file wants to use rewrite rules, that are not allowed with FollowSymLinks AND SymLinksIfOwnerMatch turned off.

If your conf file already has a line with Options ..., you can just add FollowSymLinks to the list of options. You could end up with something like this:

Options Indexes MultiViews FollowSymLinks

ASP.NET MVC passing an ID in an ActionLink to the controller

Don't put the @ before the id

new { id = "1" }

The framework "translate" it in ?Lenght when there is a mismatch in the parameter/route

What happens to a declared, uninitialized variable in C? Does it have a value?

Because computers have finite storage capacity, automatic variables will typically be held in storage elements (whether registers or RAM) that have previously been used for some other arbitrary purpose. If a such a variable is used before a value has been assigned to it, that storage may hold whatever it held previously, and so the contents of the variable will be unpredictable.

As an additional wrinkle, many compilers may keep variables in registers which are larger than the associated types. Although a compiler would be required to ensure that any value which is written to a variable and read back will be truncated and/or sign-extended to its proper size, many compilers will perform such truncation when variables are written and expect that it will have been performed before the variable is read. On such compilers, something like:

uint16_t hey(uint32_t x, uint32_t mode)
{ uint16_t q; 
  if (mode==1) q=2; 
  if (mode==3) q=4; 
  return q; }

 uint32_t wow(uint32_t mode) {
   return hey(1234567, mode);
 }

might very well result in wow() storing the values 1234567 into registers 0 and 1, respectively, and calling foo(). Since x isn't needed within "foo", and since functions are supposed to put their return value into register 0, the compiler may allocate register 0 to q. If mode is 1 or 3, register 0 will be loaded with 2 or 4, respectively, but if it is some other value, the function may return whatever was in register 0 (i.e. the value 1234567) even though that value is not within the range of uint16_t.

To avoid requiring compilers to do extra work to ensure that uninitialized variables never seem to hold values outside their domain, and avoid needing to specify indeterminate behaviors in excessive detail, the Standard says that use of uninitialized automatic variables is Undefined Behavior. In some cases, the consequences of this may be even more surprising than a value being outside the range of its type. For example, given:

void moo(int mode)
{
  if (mode < 5)
    launch_nukes();
  hey(0, mode);      
}

a compiler could infer that because invoking moo() with a mode which is greater than 3 will inevitably lead to the program invoking Undefined Behavior, the compiler may omit any code which would only be relevant if mode is 4 or greater, such as the code which would normally prevent the launch of nukes in such cases. Note that neither the Standard, nor modern compiler philosophy, would care about the fact that the return value from "hey" is ignored--the act of trying to return it gives a compiler unlimited license to generate arbitrary code.

LINQ to Entities how to update a record

In most cases @tster's answer will suffice. However, I had a scenario where I wanted to update a row without first retrieving it.

My situation is this: I've got a table where I want to "lock" a row so that only a single user at a time will be able to edit it in my app. I'm achieving this by saying

update items set status = 'in use', lastuser = @lastuser, lastupdate = @updatetime where ID = @rowtolock and @status = 'free'

The reason being, if I were to simply retrieve the row by ID, change the properties and then save, I could end up with two people accessing the same row simultaneously. This way, I simply send and update claiming this row as mine, then I try to retrieve the row which has the same properties I just updated with. If that row exists, great. If, for some reason it doesn't (someone else's "lock" command got there first), I simply return FALSE from my method.

I do this by using context.Database.ExecuteSqlCommand which accepts a string command and an array of parameters.

Just wanted to add this answer to point out that there will be scenarios in which retrieving a row, updating it, and saving it back to the DB won't suffice and that there are ways of running a straight update statement when necessary.

getElementById returns null?

There could be many reason why document.getElementById doesn't work

  • You have an invalid ID

    ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods ("."). (resource: What are valid values for the id attribute in HTML?)

  • you used some id that you already used as <meta> name in your header (e.g. copyright, author... ) it looks weird but happened to me: if your 're using IE take a look at (resource: http://www.phpied.com/getelementbyid-description-in-ie/)

  • you're targeting an element inside a frame or iframe. In this case if the iframe loads a page within the same domain of the parent you should target the contentdocument before looking for the element (resource: Calling a specific id inside a frame)

  • you're simply looking to an element when the node is not effectively loaded in the DOM, or maybe it's a simple misspelling

I doubt you used same ID twice or more: in that case document.getElementById should return at least the first element

How to reduce the space between <p> tags?

I have found this to work to give more book style paragraphs:

p.firstpar {
  margin-top: 0;
  text-indent: 2em;
  padding: 0 5px 0 5px;
}
p.nextpar {
  margin-top: -1em;
  text-indent: 2em;
  padding: 0 5px 0 5px;
}

using the em ("M") unit, rather than px unit, it makes the style independent of the font-size. Padding goes in that order: top, right, bottom, left.

`getchar()` gives the same output as the input string

getchar() reads a single character of input and returns that character as the value of the function. If there is an error reading the character, or if the end of input is reached, getchar() returns a special value, represented by EOF.

How do I get current scope dom-element in AngularJS controller?

The better and correct solution is to have a directive. The scope is the same, whether in the controller of the directive or the main controller. Use $element to do DOM operations. The method defined in the directive controller is accessible in the main controller.

Example, finding a child element:

var app = angular.module('myapp', []);
app.directive("testDir", function () {
    function link(scope, element) { 

    }
    return {
        restrict: "AE", 
        link: link, 
        controller:function($scope,$element){
            $scope.name2 = 'this is second name';
            var barGridSection = $element.find('#barGridSection'); //helps to find the child element.
    }
    };
})

app.controller('mainController', function ($scope) {
$scope.name='this is first name'
});

When is the finalize() method called in Java?

When is the finalize() method called in Java?

The finalize method will be called after the GC detects that the object is no longer reachable, and before it actually reclaims the memory used by the object.

  • If an object never becomes unreachable, finalize() will never be called on it.

  • If the GC doesn't run then finalize() may never be called. (Normally, the GC only runs when the JVM decides that there is likely to enough garbage to make it worthwhile.)

  • It may take more than one GC cycle before the GC determines that a specific object is unreachable. (Java GCs are typically "generational" collectors ...)

  • Once the GC detects an object is unreachable and finalizable, it is places on a finalization queue. Finalization typically occurs asynchronously with the normal GC.

(The JVM spec actually allows a JVM to never run finalizers ... provided that it doesn't reclaim the space used by the objects. A JVM that was implemented this way would be crippled / useless, but it this behavior is "allowed".)

The upshot is that it is unwise to rely on finalization to do things that have to be done in a definite time-frame. It is "best practice" not to use them at all. There should be a better (i.e. more reliable) way to do whatever it is you are trying to do in the finalize() method.

The only legitimate use for finalization is to clean up resources associated with objects that have been lost by application code. Even then, you should try to write the application code so that it doesn't lose the objects in the first place. (For example, use Java 7+ try-with-resources to ensure that close() is always called ...)


I created a test class which writes into a file when the finalize() method is called by overriding it. It is not executed. Can anybody tell me the reason why it is not executing?

It is hard to say, but there are a few possibilities:

  • The object is not garbage collected because it is still reachable.
  • The object is not garbage collected because the GC doesn't run before your test finishes.
  • The object is found by the GC and placed in the finalization queue by the GC, but finalization isn't completed before your test finishes.

Track a new remote branch created on GitHub

git fetch
git branch --track branch-name origin/branch-name

First command makes sure you have remote branch in local repository. Second command creates local branch which tracks remote branch. It assumes that your remote name is origin and branch name is branch-name.

--track option is enabled by default for remote branches and you can omit it.

Setting new value for an attribute using jQuery

It is working you have to check attr after assigning value

LiveDemo

$('#amount').attr( 'datamin','1000');

alert($('#amount').attr( 'datamin'));?

crudrepository findBy method signature with multiple in operators?

The following signature will do:

List<Email> findByEmailIdInAndPincodeIn(List<String> emails, List<String> pinCodes);

Spring Data JPA supports a large number of keywords to build a query. IN and AND are among them.

Starting with Zend Tutorial - Zend_DB_Adapter throws Exception: "SQLSTATE[HY000] [2002] No such file or directory"

Try setting host=127.0.0.1 on your db settings file, it worked for me! :)

Hope it helps!

Git: "Corrupt loose object"

To me this happened due to a power failure while doing a git push.

The messages looked like this:

$ git status
error: object file .git/objects/c2/38824eb3fb602edc2c49fccb535f9e53951c74 is empty
error: object file .git/objects/c2/38824eb3fb602edc2c49fccb535f9e53951c74 is empty
fatal: loose object c238824eb3fb602edc2c49fccb535f9e53951c74 (stored in .git/objects/c2/38824eb3fb602edc2c49fccb535f9e53951c74) is corrupt

I tried things like git fsck but that didn't help. Since the crash happened during a git push, it obviously happened during rewrite on the client side which happens after the server is updated. I looked around and figured that c2388 in my case was a commit object, because it was referred to by entries in .git/refs. So I knew that I would be able to find c2388 when I look at the history (through a web interface or second clone).

On the second clone I did a git log -n 2 c2388 to identify the predecessor of c2388. Then I manually modified .git/refs/heads/master and .git/refs/remotes/origin/master to be the predecessor of c2388 instead of c2388. Then I could do a git fetch. The git fetch failed a few times for conflicts on empty objects. I removed each of these empty objects until git fetch succeeded. That has healed the repository.

Make: how to continue after a command fails?

Change clean to

rm -f .lambda .lambda_t .activity .activity_t_lambda

I.e. don't prompt for remove; don't complain if file doesn't exist.

How can I cast int to enum?

Below is a nice utility class for Enums

public static class EnumHelper
{
    public static int[] ToIntArray<T>(T[] value)
    {
        int[] result = new int[value.Length];
        for (int i = 0; i < value.Length; i++)
            result[i] = Convert.ToInt32(value[i]);
        return result;
    }

    public static T[] FromIntArray<T>(int[] value) 
    {
        T[] result = new T[value.Length];
        for (int i = 0; i < value.Length; i++)
            result[i] = (T)Enum.ToObject(typeof(T),value[i]);
        return result;
    }


    internal static T Parse<T>(string value, T defaultValue)
    {
        if (Enum.IsDefined(typeof(T), value))
            return (T) Enum.Parse(typeof (T), value);

        int num;
        if(int.TryParse(value,out num))
        {
            if (Enum.IsDefined(typeof(T), num))
                return (T)Enum.ToObject(typeof(T), num);
        }

        return defaultValue;
    }
}

Multiple Java versions running concurrently under Windows

We can install multiple versions of Java Development kits on the same machine using SDKMan.

Some points about SDKMan are as following:

  1. SDKMan is free to use and it is developed by the open source community.
  2. SDKMan is written in bash and it only requires curl and zip/unzip programs to be present on your system.
  3. SDKMan can install around 29 Software Development Kits for the JVM such as Java, Groovy, Scala, Kotlin and Ceylon. Ant, Gradle, Grails, Maven, SBT, Spark, Spring Boot, Vert.x.
  4. We do not need to worry about setting the _HOME and PATH environment variables because SDKMan handles it automatically.

SDKMan can run on any UNIX based platforms such as Mac OSX, Linux, Cygwin, Solaris and FreeBSD and we can install it using following commands:

$ curl -s "https://get.sdkman.io" | bash  
$ source "$HOME/.sdkman/bin/sdkman-init.sh" 

Because SDKMan is written in bash and only requires curl and zip/unzip to be present on your system. You can install SDKMan on windows as well either by first installing Cygwin or Git Bash for Windows environment and then running above commands.

Command sdk list java will give us a list of java versions which we can install using SDKMan.

Installing Java 8

$ sdk install java 8.0.201-oracle

Installing Java 9

$ sdk install java 9.0.4-open 

Installing Java 11

$ sdk install java 11.0.2-open

Uninstalling a Java version

In case you want to uninstall any JDK version e.g., 11.0.2-open you can do that as follows:

$ sdk uninstall java 11.0.2-open

Switching current Java version

If you want to activate one version of JDK for all terminals and applications, you can use the command

sdk default java <your-java_version>

Above commands will also update the PATH and JAVA_HOME variables automatically. You can read more on my article How to Install Multiple Versions of Java on the Same Machine.

sql query to get earliest date

If you just want the date:

SELECT MIN(date) as EarliestDate
FROM YourTable
WHERE id = 2

If you want all of the information:

SELECT TOP 1 id, name, score, date
FROM YourTable
WHERE id = 2
ORDER BY Date

Prevent loops when you can. Loops often lead to cursors, and cursors are almost never necessary and very often really inefficient.

c++ array assignment of multiple values

You have to replace the values one by one such as in a for-loop or copying another array over another such as using memcpy(..) or std::copy

e.g.

for (int i = 0; i < arrayLength; i++) {
    array[i] = newValue[i];
}

Take care to ensure proper bounds-checking and any other checking that needs to occur to prevent an out of bounds problem.

How to change the height of a div dynamically based on another div using css?

#container-of-boxes {
    display: table;
    width: 1158px;
}
#box-1 {
    width: 578px;
}
#box-2 {
    width: 386px;
}
#box-3 {
    width: 194px;
}
#box-1, #box-2, #box-3 {
    min-height: 210px;
    padding-bottom: 20px;
    display: table-cell;
    height: auto;
    overflow: hidden;
}
  • The container must have display:table
  • The boxes inside container must be: display:table-cell
  • Don't put floats.

Why can't I define my workbook as an object?

It's actually a sensible question. Here's the answer from Excel 2010 help:

"The Workbook object is a member of the Workbooks collection. The Workbooks collection contains all the Workbook objects currently open in Microsoft Excel."

So, since that workbook isn't open - at least I assume it isn't - it can't be set as a workbook object. If it was open you'd just set it like:

Set wbk = workbooks("Master Benchmark Data Sheet.xlsx")

How to pass an ArrayList to a varargs method parameter?

Source article: Passing a list as an argument to a vararg method


Use the toArray(T[] arr) method.

.getMap(locations.toArray(new WorldLocation[locations.size()]))

(toArray(new WorldLocation[0]) also works, but you would allocate a zero-length array for no reason.)


Here's a complete example:

public static void method(String... strs) {
    for (String s : strs)
        System.out.println(s);
}

...
    List<String> strs = new ArrayList<String>();
    strs.add("hello");
    strs.add("world");
    
    method(strs.toArray(new String[strs.size()]));
    //     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
...

No module named 'openpyxl' - Python 3.4 - Ubuntu

I had the same problem solved using instead of pip install :

sudo apt-get install python-openpyxl
sudo apt-get install python3-openpyxl

The sudo command also works better for other packages.

Matplotlib 2 Subplots, 1 Colorbar

Shared colormap and colorbar

This is for the more complex case where the values are not just between 0 and 1; the cmap needs to be shared instead of just using the last one.

import numpy as np
from matplotlib.colors import Normalize
import matplotlib.pyplot as plt
import matplotlib.cm as cm
fig, axes = plt.subplots(nrows=2, ncols=2)
cmap=cm.get_cmap('viridis')
normalizer=Normalize(0,4)
im=cm.ScalarMappable(norm=normalizer)
for i,ax in enumerate(axes.flat):
    ax.imshow(i+np.random.random((10,10)),cmap=cmap,norm=normalizer)
    ax.set_title(str(i))
fig.colorbar(im, ax=axes.ravel().tolist())
plt.show()

AngularJS: ng-model not binding to ng-checked for checkboxes

You don't need ng-checked when you use ng-model. If you're performing CRUD on your HTML Form, just create a model for CREATE mode that is consistent with your EDIT mode during the data-binding:

CREATE Mode: Model with default values only

$scope.dataModel = {
   isItemSelected: true,
   isApproved: true,
   somethingElse: "Your default value"
}

EDIT Mode: Model from database

$scope.dataModel = getFromDatabaseWithSameStructure()

Then whether EDIT or CREATE mode, you can consistently make use of your ng-model to sync with your database.

Check if Variable is Empty - Angular 2

Ar you looking for that:

isEmptyObject(obj) {
  return (obj && (Object.keys(obj).length === 0));
}

(found here)

or that :

function isEmpty(obj) {
    for(var key in obj) {
        if(obj.hasOwnProperty(key))
            return false;
    }
    return true;
}

found here

How to edit binary file on Unix systems

There's lightweight binary editor, check hexedit. http://www.linux.org/apps/AppId_6968.html. I tried using it for editing ELF binaries in Linux at least.

How do I set hostname in docker-compose?

I needed to spin freeipa container to have a working kdc and had to give it a hostname otherwise it wouldn't run. What eventually did work for me is setting the HOSTNAME env variable in compose:

version: 2
services:
  freeipa:
    environment:
      - HOSTNAME=ipa.example.test

Now its working:

docker exec -it freeipa_freeipa_1 hostname
ipa.example.test

How to cast List<Object> to List<MyClass>

List<Object[]> testNovedads = crudService.createNativeQuery(
            "SELECT ID_NOVEDAD_PK, OBSERVACIONES, ID_SOLICITUD_PAGO_FK FROM DBSEGUIMIENTO.SC_NOVEDADES WHERE ID_NOVEDAD_PK < 2000");

Convertir<TestNovedad> convertir = new Convertir<TestNovedad>();
Collection<TestNovedad> novedads = convertir.toList(testNovedads, TestNovedad.class);
for (TestNovedad testNovedad : novedads) {
    System.out.println(testNovedad.toString());
}

public Collection<T> toList(List<Object[]> objects, Class<T> type) {
    Gson gson = new Gson();
    JSONObject jsonObject = new JSONObject();
    Collection<T> collection = new ArrayList<>();
    Field[] fields = TestNovedad.class.getDeclaredFields();
    for (Object[] object : objects) {
        int pos = 0;
        for (Field field : fields) {
            jsonObject.put(field.getName(), object[pos++]);
        }
        collection.add(gson.fromJson(jsonObject.toString(), type));
    }
    return collection;
}

Java SSL: how to disable hostname verification

In case you're using apache's http-client 4:

SSLConnectionSocketFactory sslConnectionSocketFactory = 
    new SSLConnectionSocketFactory(sslContext,
             new String[] { "TLSv1.2" }, null, new HostnameVerifier() {
                    public boolean verify(String arg0, SSLSession arg1) {
                            return true;
            }
      });

Template not provided using create-react-app

I fix this issue on Mac by uninstalling create-react-app from global npm lib, that's basically what said, just try to do, you need also do sudo:

sudo npm uninstall -g create-react-app

Then simply run:

npx create-react-app my-app-name

Now should be all good and get the folder structures as below:

template not provided using create react app

Using .htaccess to make all .html pages to run as .php files?

I'm using PHP7.1 running in my Raspberry Pi 3.

In the file /etc/apache2/mods-enabled/php7.1.conf I added at the end:

AddType application/x-httpd-php .html .htm .png .jpg .gif

Loop over html table and get checked checkboxes (JQuery)

The following code snippet enables/disables a button depending on whether at least one checkbox on the page has been checked.
$('input[type=checkbox]').change(function () {
    $('#test > tbody  tr').each(function () {
        if ($('input[type=checkbox]').is(':checked')) {
            $('#btnexcellSelect').removeAttr('disabled');
        } else {
            $('#btnexcellSelect').attr('disabled', 'disabled');
        }
        if ($(this).is(':checked')){
            console.log( $(this).attr('id'));
         }else{
             console.log($(this).attr('id'));
         }
     });
});

Here is demo in JSFiddle.

How can I count the number of characters in a Bash variable

Use the wc utility with the print the byte counts (-c) option:

$ SO="stackoverflow"
$ echo -n "$SO" | wc -c
    13

You'll have to use the do not output the trailing newline (-n) option for echo. Otherwise, the newline character will also be counted.

Select Last Row in the Table

Somehow all the above doesn't seem to work for me in laravel 5.3, so i solved my own problem using:

Model::where('user_id', '=', $user_id)->orderBy('created_at', 'desc')->get();

hope am able to bail someone out.

How to change a nullable column to not nullable in a Rails migration?

You can't use add_timestamps and null:false if you have existing records, so here is the solution :

def change
  add_timestamps(:buttons, null: true)

  Button.find_each { |b| b.update(created_at: Time.zone.now, updated_at: Time.zone.now) }

  change_column_null(:buttons, :created_at, false)
  change_column_null(:buttons, :updated_at, false)
end

How to get every first element in 2 dimensional list

You can get it like

[ x[0] for x in a]

which will return a list of the first element of each list in a

Check if array is empty or null

As long as your selector is actually working, I see nothing wrong with your code that checks the length of the array. That should do what you want. There are a lot of ways to clean up your code to be simpler and more readable. Here's a cleaned up version with notes about what I cleaned up.

var album_text = [];

$("input[name='album_text[]']").each(function() {
    var value = $(this).val();
    if (value) {
        album_text.push(value);
    }
});
if (album_text.length === 0) {
    $('#error_message').html("Error");
}

else {
  //send data
}

Some notes on what you were doing and what I changed.

  1. $(this) is always a valid jQuery object so there's no reason to ever check if ($(this)). It may not have any DOM objects inside it, but you can check that with $(this).length if you need to, but that is not necessary here because the .each() loop wouldn't run if there were no items so $(this) inside your .each() loop will always be something.
  2. It's inefficient to use $(this) multiple times in the same function. Much better to get it once into a local variable and then use it from that local variable.
  3. It's recommended to initialize arrays with [] rather than new Array().
  4. if (value) when value is expected to be a string will both protect from value == null, value == undefined and value == "" so you don't have to do if (value && (value != "")). You can just do: if (value) to check for all three empty conditions.
  5. if (album_text.length === 0) will tell you if the array is empty as long as it is a valid, initialized array (which it is here).

What are you trying to do with this selector $("input[name='album_text[]']")?

Convert regular Python string to raw string

For Python 3, the way to do this that doesn't add double backslashes and simply preserves \n, \t, etc. is:

a = 'hello\nbobby\nsally\n'
a.encode('unicode-escape').decode().replace('\\\\', '\\')
print(a)

Which gives a value that can be written as CSV:

hello\nbobby\nsally\n

There doesn't seem to be a solution for other special characters, however, that may get a single \ before them. It's a bummer. Solving that would be complex.

For example, to serialize a pandas.Series containing a list of strings with special characters in to a textfile in the format BERT expects with a CR between each sentence and a blank line between each document:

with open('sentences.csv', 'w') as f:

    current_idx = 0
    for idx, doc in sentences.items():
        # Insert a newline to separate documents
        if idx != current_idx:
            f.write('\n')
        # Write each sentence exactly as it appared to one line each
        for sentence in doc:
            f.write(sentence.encode('unicode-escape').decode().replace('\\\\', '\\') + '\n')

This outputs (for the Github CodeSearchNet docstrings for all languages tokenized into sentences):

Makes sure the fast-path emits in order.
@param value the value to emit or queue up\n@param delayError if true, errors are delayed until the source has terminated\n@param disposable the resource to dispose if the drain terminates

Mirrors the one ObservableSource in an Iterable of several ObservableSources that first either emits an item or sends\na termination notification.
Scheduler:\n{@code amb} does not operate by default on a particular {@link Scheduler}.
@param  the common element type\n@param sources\nan Iterable of ObservableSource sources competing to react first.
A subscription to each source will\noccur in the same order as in the Iterable.
@return an Observable that emits the same sequence as whichever of the source ObservableSources first\nemitted an item or sent a termination notification\n@see ReactiveX operators documentation: Amb


...

Difference between nVidia Quadro and Geforce cards?

Surfing the web, you will find many technical justifications for Quadro price. Real answer is in "demand for reliable and task specific graphic cards".

Imagine you have an architectural firm with many fat projects on deadline. Your computers are only used in working with one specific CAD software. If foundation of your business is supposed to rely on these computers, you would want to make sure this foundation is strong.

For such clients, Nvidia engineered cards like Quadro, providing what they call "Professional Solution". And if you are among the targeted clients, you would really appreciate reliability of these graphic cards.

Many believe Geforce have become powerful and reliable enough to take Quadro's place. But in the end, it depends on the software you are mostly going to use and importance of reliability in what you do.

How do you set a default value for a MySQL Datetime column?

For all who use the TIMESTAMP column as a solution i want to second the following limitation from the manual:

http://dev.mysql.com/doc/refman/5.0/en/datetime.html

"The TIMESTAMP data type has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC. It has varying properties, depending on the MySQL version and the SQL mode the server is running in. These properties are described later in this section. "

So this will obviously break your software in about 28 years.

I believe the only solution on the database side is to use triggers like mentioned in other answers.

Explanation on Integer.MAX_VALUE and Integer.MIN_VALUE to find min and max value in an array

but as for this method, I don't understand the purpose of Integer.MAX_VALUE and Integer.MIN_VALUE.

By starting out with smallest set to Integer.MAX_VALUE and largest set to Integer.MIN_VALUE, they don't have to worry later about the special case where smallest and largest don't have a value yet. If the data I'm looking through has a 10 as the first value, then numbers[i]<smallest will be true (because 10 is < Integer.MAX_VALUE) and we'll update smallest to be 10. Similarly, numbers[i]>largest will be true because 10 is > Integer.MIN_VALUE and we'll update largest. And so on.

Of course, when doing this, you must ensure that you have at least one value in the data you're looking at. Otherwise, you end up with apocryphal numbers in smallest and largest.


Note the point Onome Sotu makes in the comments:

...if the first item in the array is larger than the rest, then the largest item will always be Integer.MIN_VALUE because of the else-if statement.

Which is true; here's a simpler example demonstrating the problem (live copy):

public class Example
{
    public static void main(String[] args) throws Exception {
        int[] values = {5, 1, 2};
        int smallest = Integer.MAX_VALUE;
        int largest  = Integer.MIN_VALUE;
        for (int value : values) {
            if (value < smallest) {
                smallest = value;
            } else if (value > largest) {
                largest = value;
            }
        }
        System.out.println(smallest + ", " + largest); // 1, 2 -- WRONG
    }
}

To fix it, either:

  1. Don't use else, or

  2. Start with smallest and largest equal to the first element, and then loop the remaining elements, keeping the else if.

Here's an example of that second one (live copy):

public class Example
{
    public static void main(String[] args) throws Exception {
        int[] values = {5, 1, 2};
        int smallest = values[0];
        int largest  = values[0];
        for (int n = 1; n < values.length; ++n) {
            int value = values[n];
            if (value < smallest) {
                smallest = value;
            } else if (value > largest) {
                largest = value;
            }
        }
        System.out.println(smallest + ", " + largest); // 1, 5
    }
}

iPhone SDK on Windows (alternative solutions)

This really comes down to how much you value your time. As the other posters have mentioned, there are a couple of ways you can build iPhone apps without a Mac. However, you are jumping through serious hoops, and it'll be much more difficult and take longer than it would with the proper development chain.

You can buy a second-hand Mac Mini for a couple of hundred bucks on eBay. If you're serious about doing iPhone development you'll make this back in saved time very quickly.

How to add soap header in java

Maven dependency

    <dependency>
        <groupId>org.springframework.ws</groupId>
        <artifactId>spring-ws-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.apache.ws.security</groupId>
        <artifactId>wss4j</artifactId>
        <version>1.6.19</version>
    </dependency>    

Configuration class

import org.springframework.ws.soap.security.wss4j.Wss4jSecurityInterceptor;

@Configuration
public class ConfigurationClass{

@Bean
public Wss4jSecurityInterceptor securityInterceptor() {
    Wss4jSecurityInterceptor wss4jSecurityInterceptor = new Wss4jSecurityInterceptor();
    wss4jSecurityInterceptor.setSecurementActions("UsernameToken");
    wss4jSecurityInterceptor.setSecurementMustUnderstand(true);
    wss4jSecurityInterceptor.setSecurementPasswordType("PasswordText");
    wss4jSecurityInterceptor.setSecurementUsername("123456789011");
    wss4jSecurityInterceptor.setSecurementPassword("TestPass123");
    return wss4jSecurityInterceptor;
}

Result xml

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header>
    <wsse:Security
        xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
        xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" 
        SOAP-ENV:mustUnderstand="1">
        <wsse:UsernameToken wsu:Id="UsernameToken-F57F40DC89CD6998E214700450735811">
            <wsse:Username>123456789011</wsse:Username>
            <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">TestPass123</wsse:Password>
        </wsse:UsernameToken>
    </wsse:Security>
</SOAP-ENV:Header>
<SOAP-ENV:Body>
    ...
    something
    ...
</SOAP-ENV:Body>