Programs & Examples On #Identity

An inherent property of an entity that distinguishes that entity from all others. Frequently used to refer to user identity and authentication.

How to get the unique ID of an object which overrides hashCode()?

hashCode() method is not for providing a unique identifier for an object. It rather digests the object's state (i.e. values of member fields) to a single integer. This value is mostly used by some hash based data structures like maps and sets to effectively store and retrieve objects.

If you need an identifier for your objects, I recommend you to add your own method instead of overriding hashCode. For this purpose, you can create a base interface (or an abstract class) like below.

public interface IdentifiedObject<I> {
    I getId();
}

Example usage:

public class User implements IdentifiedObject<Integer> {
    private Integer studentId;

    public User(Integer studentId) {
        this.studentId = studentId;
    }

    @Override
    public Integer getId() {
        return studentId;
    }
}

Firebase: how to generate a unique numeric ID for key?

As the docs say, this can be achieved just by using set instead if push.

As the docs say, it is not recommended (due to possible overwrite by other user at the "same" time).

But in some cases it's helpful to have control over the feed's content including keys.

As an example of webapp in js, 193 being your id generated elsewhere, simply:

 firebase.initializeApp(firebaseConfig);
  var data={
      "name":"Prague"
  };
  firebase.database().ref().child('areas').child("193").set(data);

This will overwrite any area labeled 193 or create one if it's not existing yet.

Auto increment primary key in SQL Server Management Studio 2012

CREATE TABLE Persons (
    Personid int IDENTITY(1,1) PRIMARY KEY,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Age int
);

The MS SQL Server uses the IDENTITY keyword to perform an auto-increment feature.

In the example above, the starting value for IDENTITY is 1, and it will increment by 1 for each new record.

Tip: To specify that the "Personid" column should start at value 10 and increment by 5, change it to IDENTITY(10,5).

To insert a new record into the "Persons" table, we will NOT have to specify a value for the "Personid" column (a unique value will be added automatically):

What is the difference between == and equals() in Java?

 String w1 ="Sarat";
 String w2 ="Sarat";
 String w3 = new String("Sarat");

 System.out.println(w1.hashCode());   //3254818
 System.out.println(w2.hashCode());   //3254818
 System.out.println(w3.hashCode());   //3254818

 System.out.println(System.identityHashCode(w1)); //prints 705927765
 System.out.println(System.identityHashCode(w2)); //prints 705927765
 System.out.println(System.identityHashCode(w3)); //prints 366712642


 if(w1==w2)   //  (705927765==705927765)
 {
   System.out.println("true");
 }
 else
 {
   System.out.println("false");
 }
 //prints true

 if(w2==w3)   //  (705927765==366712642)
 {
   System.out.println("true");
 }
 else
 {
   System.out.println("false");
 }
 //prints false


 if(w2.equals(w3))   //  (Content of 705927765== Content of 366712642)
 {
   System.out.println("true");
 }
 else
 {
   System.out.println("false");
 }
 //prints true

ASP.NET MVC 5 - Identity. How to get current ApplicationUser

You should not need to query the database directly for the current ApplicationUser.

That introduces a new dependency of having an extra context for starters, but going forward the user database tables change (3 times in the past 2 years) but the API is consistent. For example the users table is now called AspNetUsers in Identity Framework, and the names of several primary key fields kept changing, so the code in several answers will no longer work as-is.

Another problem is that the underlying OWIN access to the database will use a separate context, so changes from separate SQL access can produce invalid results (e.g. not seeing changes made to the database). Again the solution is to work with the supplied API and not try to work-around it.

The correct way to access the current user object in ASP.Net identity (as at this date) is:

var user = UserManager.FindById(User.Identity.GetUserId());

or, if you have an async action, something like:

var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());

FindById requires you have the following using statement so that the non-async UserManager methods are available (they are extension methods for UserManager, so if you do not include this you will only see FindByIdAsync):

using Microsoft.AspNet.Identity;

If you are not in a controller at all (e.g. you are using IOC injection), then the user id is retrieved in full from:

System.Web.HttpContext.Current.User.Identity.GetUserId();

If you are not in the standard Account controller you will need to add the following (as an example) to your controller:

1. Add these two properties:

    /// <summary>
    /// Application DB context
    /// </summary>
    protected ApplicationDbContext ApplicationDbContext { get; set; }

    /// <summary>
    /// User manager - attached to application DB context
    /// </summary>
    protected UserManager<ApplicationUser> UserManager { get; set; }

2. Add this in the Controller's constructor:

    this.ApplicationDbContext = new ApplicationDbContext();
    this.UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(this.ApplicationDbContext));

Update March 2015

Note: The most recent update to Identity framework changes one of the underlying classes used for authentication. You can now access it from the Owin Context of the current HttpContent.

ApplicationUser user = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(System.Web.HttpContext.Current.User.Identity.GetUserId());

Addendum:

When using EF and Identity Framework with Azure, over a remote database connection (e.g. local host testing to Azure database), you can randomly hit the dreaded “error: 19 - Physical connection is not usable”. As the cause is buried away inside Identity Framework, where you cannot add retries (or what appears to be a missing .Include(x->someTable)), you need to implement a custom SqlAzureExecutionStrategy in your project.

What is the difference between Scope_Identity(), Identity(), @@Identity, and Ident_Current()?

Scope Identity: Identity of last record added within the stored procedure being executed.

@@Identity: Identity of last record added within the query batch, or as a result of the query e.g. a procedure that performs an insert, the then fires a trigger that then inserts a record will return the identity of the inserted record from the trigger.

IdentCurrent: The last identity allocated for the table.

Handling identity columns in an "Insert Into TABLE Values()" statement?

You have 2 choices:

1) Either specify the column name list (without the identity column).

2) SET IDENTITY_INSERT tablename ON, followed by insert statements that provide explicit values for the identity column, followed by SET IDENTITY_INSERT tablename OFF.

If you are avoiding a column name list, perhaps this 'trick' might help?:

-- Get a comma separated list of a table's column names
SELECT STUFF(
(SELECT 
',' + COLUMN_NAME AS [text()]
FROM 
INFORMATION_SCHEMA.COLUMNS
WHERE 
TABLE_NAME = 'TableName'
Order By Ordinal_position
FOR XML PATH('')
), 1,1, '')

SQL Server, How to set auto increment after creating a table without data loss?

Below script can be a good solution.Worked in large data as well.

ALTER DATABASE WMlive SET RECOVERY SIMPLE WITH NO_WAIT

ALTER TABLE WMBOMTABLE DROP CONSTRAINT PK_WMBomTable

ALTER TABLE WMBOMTABLE drop column BOMID

ALTER TABLE WMBOMTABLE ADD BomID int IDENTITY(1, 1) NOT NULL;

ALTER TABLE WMBOMTABLE ADD CONSTRAINT PK_WMBomTable PRIMARY KEY CLUSTERED (BomID);

ALTER DATABASE WMlive SET RECOVERY FULL WITH NO_WAIT

SQL Server 2012 column identity increment jumping from 6 to 1000+ on 7th entry

While trace flag 272 may work for many, it definitely won't work for hosted Sql Server Express installations. So, I created an identity table, and use this through an INSTEAD OF trigger. I'm hoping this helps someone else, and/or gives others an opportunity to improve my solution. The last line allows returning the last identity column added. Since I typically use this to add a single row, this works to return the identity of a single inserted row.

The identity table:

CREATE TABLE [dbo].[tblsysIdentities](
[intTableId] [int] NOT NULL,
[intIdentityLast] [int] NOT NULL,
[strTable] [varchar](100) NOT NULL,
[tsConcurrency] [timestamp] NULL,
CONSTRAINT [PK_tblsysIdentities] PRIMARY KEY CLUSTERED 
(
    [intTableId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,  ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

and the insert trigger:

-- INSERT --
IF OBJECT_ID ('dbo.trgtblsysTrackerMessagesIdentity', 'TR') IS NOT NULL
   DROP TRIGGER dbo.trgtblsysTrackerMessagesIdentity;
GO
CREATE TRIGGER trgtblsysTrackerMessagesIdentity
ON dbo.tblsysTrackerMessages
INSTEAD OF INSERT AS 
BEGIN
    DECLARE @intTrackerMessageId INT
    DECLARE @intRowCount INT

    SET @intRowCount = (SELECT COUNT(*) FROM INSERTED)

    SET @intTrackerMessageId = (SELECT intIdentityLast FROM tblsysIdentities WHERE intTableId=1)
    UPDATE tblsysIdentities SET intIdentityLast = @intTrackerMessageId + @intRowCount WHERE intTableId=1

    INSERT INTO tblsysTrackerMessages( 
    [intTrackerMessageId],
    [intTrackerId],
    [strMessage],
    [intTrackerMessageTypeId],
    [datCreated],
    [strCreatedBy])
    SELECT @intTrackerMessageId + ROW_NUMBER() OVER (ORDER BY [datCreated]) AS [intTrackerMessageId], 
    [intTrackerId],
   [strMessage],
   [intTrackerMessageTypeId],
   [datCreated],
   [strCreatedBy] FROM INSERTED;

   SELECT TOP 1 @intTrackerMessageId + @intRowCount FROM INSERTED;
END

Why does comparing strings using either '==' or 'is' sometimes produce a different result?

is is identity testing and == is equality testing. This means is is a way to check whether two things are the same things, or just equivalent.

Say you've got a simple person object. If it is named 'Jack' and is '23' years old, it's equivalent to another 23-year-old Jack, but it's not the same person.

class Person(object):
   def __init__(self, name, age):
       self.name = name
       self.age = age

   def __eq__(self, other):
       return self.name == other.name and self.age == other.age

jack1 = Person('Jack', 23)
jack2 = Person('Jack', 23)

jack1 == jack2 # True
jack1 is jack2 # False

They're the same age, but they're not the same instance of person. A string might be equivalent to another, but it's not the same object.

How to change identity column values programmatically?

Firstly the setting of IDENTITY_INSERT on or off for that matter will not work for what you require (it is used for inserting new values, such as plugging gaps).

Doing the operation through the GUI just creates a temporary table, copies all the data across to a new table without an identity field, and renames the table.

Where is the Microsoft.IdentityModel dll

In Windows 8.1 64bit, look under C:\Windows\ADFS

Python Matplotlib figure title overlaps axes label when using twiny

Forget using plt.title and place the text directly with plt.text. An over-exaggerated example is given below:

import pylab as plt

fig = plt.figure(figsize=(5,10))

figure_title = "Normal title"
ax1  = plt.subplot(1,2,1)

plt.title(figure_title, fontsize = 20)
plt.plot([1,2,3],[1,4,9])

figure_title = "Raised title"
ax2  = plt.subplot(1,2,2)

plt.text(0.5, 1.08, figure_title,
         horizontalalignment='center',
         fontsize=20,
         transform = ax2.transAxes)
plt.plot([1,2,3],[1,4,9])

plt.show()

enter image description here

How to execute IN() SQL queries with Spring's JDBCTemplate effectively?

If you get an exception for : Invalid column type

Please use getNamedParameterJdbcTemplate() instead of getJdbcTemplate()

 List<Foo> foo = getNamedParameterJdbcTemplate().query("SELECT * FROM foo WHERE a IN (:ids)",parameters,
 getRowMapper());

Note that the second two arguments are swapped around.

JavaScript - get the first day of the week from current date

Using the getDay method of Date objects, you can know the number of day of the week (being 0=Sunday, 1=Monday, etc).

You can then subtract that number of days plus one, for example:

function getMonday(d) {
  d = new Date(d);
  var day = d.getDay(),
      diff = d.getDate() - day + (day == 0 ? -6:1); // adjust when day is sunday
  return new Date(d.setDate(diff));
}

getMonday(new Date()); // Mon Nov 08 2010

Pylint "unresolved import" error in Visual Studio Code

If you have this code in your settings.json file, delete it:

{
    "python.jediEnabled": false
}

How can I check if char* variable points to empty string?

Give it a chance:

Try getting string via function gets(string) then check condition as if(string[0] == '\0')

how to remove multiple columns in r dataframe?

If you only want to remove columns 5 and 7 but not 6 try:

album2 <- album2[,-c(5,7)] #deletes columns 5 and 7

SQL where datetime column equals today's date?

There might be another way, but this should work:

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

What's the difference between INNER JOIN, LEFT JOIN, RIGHT JOIN and FULL JOIN?

INNER JOIN gets all records that are common between both tables based on the supplied ON clause.

LEFT JOIN gets all records from the LEFT linked and the related record from the right table ,but if you have selected some columns from the RIGHT table, if there is no related records, these columns will contain NULL.

RIGHT JOIN is like the above but gets all records in the RIGHT table.

FULL JOIN gets all records from both tables and puts NULL in the columns where related records do not exist in the opposite table.

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

Add all model attributes to the redirecting URL as query string.

Filter an array using a formula (without VBA)

Today, in Office 365, Excel has so called 'array functions'. The filter function does exactly what you want. No need to use CTRL+SHIFT+ENTER anymore, a simple enter will suffice.

In Office 365, your problem would be simply solved by using:

=VLOOKUP(A3, FILTER(A2:C6, B2:B6="B"), 3, FALSE)

Best way to add Gradle support to IntelliJ Project

In IntelliJ 2017.2.4 I just closed the project and reopened it and I got a dialog asking me if I wanted to link with build.gradle which opened up the import dialog for Gradle projects.

No need to delete any files or add the idea plugin to build.gradle.

Get Multiple Values in SQL Server Cursor

This should work:

DECLARE db_cursor CURSOR FOR SELECT name, age, color FROM table; 
DECLARE @myName VARCHAR(256);
DECLARE @myAge INT;
DECLARE @myFavoriteColor VARCHAR(40);
OPEN db_cursor;
FETCH NEXT FROM db_cursor INTO @myName, @myAge, @myFavoriteColor;
WHILE @@FETCH_STATUS = 0  
BEGIN  

       --Do stuff with scalar values

       FETCH NEXT FROM db_cursor INTO @myName, @myAge, @myFavoriteColor;
END;
CLOSE db_cursor;
DEALLOCATE db_cursor;

Downcasting in Java

Consider the below example

public class ClastingDemo {

/**
 * @param args
 */
public static void main(String[] args) {
    AOne obj = new Bone();
    ((Bone) obj).method2();
}
}

class AOne {
public void method1() {
    System.out.println("this is superclass");
}
}


 class Bone extends AOne {

public void method2() {
    System.out.println("this is subclass");
}
}

here we create the object of subclass Bone and assigned it to super class AOne reference and now superclass reference does not know about the method method2 in the subclass i.e Bone during compile time.therefore we need to downcast this reference of superclass to subclass reference so as the resultant reference can know about the presence of methods in the subclass i.e Bone

OracleCommand SQL Parameters Binding

string strConn = "Data Source=ORCL134; User ID=user; Password=psd;";

System.Data.OracleClient.OracleConnection con = newSystem.Data.OracleClient.OracleConnection(strConn);
    con.Open();

    System.Data.OracleClient.OracleCommand Cmd = 
        new System.Data.OracleClient.OracleCommand(
            "SELECT * FROM TBLE_Name WHERE ColumnName_year= :year", con);

//for oracle..it is :object_name and for sql it s @object_name
    Cmd.Parameters.Add(new System.Data.OracleClient.OracleParameter("year", (txtFinYear.Text).ToString()));

    System.Data.OracleClient.OracleDataAdapter da = new System.Data.OracleClient.OracleDataAdapter(Cmd);
    DataSet myDS = new DataSet();
    da.Fill(myDS);
    try
    {
        lblBatch.Text = "Batch Number is : " + Convert.ToString(myDS.Tables[0].Rows[0][19]);
        lblBatch.ForeColor = System.Drawing.Color.Green;
        lblBatch.Visible = true;
    }
    catch 
    {
        lblBatch.Text = "No Data Found for the Year : " + txtFinYear.Text;
        lblBatch.ForeColor = System.Drawing.Color.Red;
        lblBatch.Visible = true;   
    }
    da.Dispose();
    con.Close();

PHP - iterate on string characters

Most of the answers forgot about non English characters !!!

strlen counts BYTES, not characters, that is why it is and it's sibling functions works fine with English characters, because English characters are stored in 1 byte in both UTF-8 and ASCII encodings, you need to use the multibyte string functions mb_*

This will work with any character encoded in UTF-8

// 8 characters in 12 bytes
$string = "abcd????";

$charsCount = mb_strlen($string, 'UTF-8');
for($i = 0; $i < $charsCount; $i++){
    $char = mb_substr($string, $i, 1, 'UTF-8');
    var_dump($char);
}

This outputs

string(1) "a"
string(1) "b"
string(1) "c"
string(1) "d"
string(2) "?"
string(2) "?"
string(2) "?"
string(2) "?"

What are the performance characteristics of sqlite with very large database files?

We are using DBS of 50 GB+ on our platform. no complains works great. Make sure you are doing everything right! Are you using predefined statements ? *SQLITE 3.7.3

  1. Transactions
  2. Pre made statements
  3. Apply these settings (right after you create the DB)

    PRAGMA main.page_size = 4096;
    PRAGMA main.cache_size=10000;
    PRAGMA main.locking_mode=EXCLUSIVE;
    PRAGMA main.synchronous=NORMAL;
    PRAGMA main.journal_mode=WAL;
    PRAGMA main.cache_size=5000;
    

Hope this will help others, works great here

Java, "Variable name" cannot be resolved to a variable

public void setHoursWorked(){
    hoursWorked = hours;
}

You haven't defined hours inside that method. hours is not passed in as a parameter, it's not declared as a variable, and it's not being used as a class member, so you get that error.

Two submit buttons in one form

Use the formaction HTML attribute (5th line):

<form action="/action_page.php" method="get">
    First name: <input type="text" name="fname"><br>
    Last name: <input type="text" name="lname"><br>
    <button type="submit">Submit</button><br>
    <button type="submit" formaction="/action_page2.php">Submit to another page</button>
</form>

.htaccess deny from all

You can edit it. The content of the file is literally "Deny from all" which is an Apache directive: http://httpd.apache.org/docs/2.2/mod/mod_authz_host.html#deny

The breakpoint will not currently be hit. No symbols have been loaded for this document in a Silverlight application

I had a similar issue except my problem was silly - I had 2 instances of the built-in web server running under 2 different ports AND I had my project -> properties -> web -> "Start URL" pointing to a fixed port but the web app was not actually running under that port. So my browser was being redirected to the "Start URL" which referred to 1539 but the code/debug instance was running under port 50803.

I changed the builtin web server to run under a fixed port and adjusted my "Start URL" to use that port as well. project -> properties -> web -> "Servers" section -> "Use Visual Studio Development Server" -> specific port

python: urllib2 how to send cookie with urlopen request

This answer is not working since the urllib2 module has been split across several modules in Python 3. You need to do

from urllib import request
opener = request.build_opener()
opener.addheaders.append(('Cookie', 'cookiename=cookievalue'))
f = opener.open("http://example.com/")

How to trim a file extension from a String in JavaScript?

x.length-4 only accounts for extensions of 3 characters. What if you have filename.jpegor filename.pl?

EDIT:

To answer... sure, if you always have an extension of .jpg, x.length-4 would work just fine.

However, if you don't know the length of your extension, any of a number of solutions are better/more robust.

x = x.replace(/\..+$/, '');

OR

x = x.substring(0, x.lastIndexOf('.'));

OR

x = x.replace(/(.*)\.(.*?)$/, "$1");

OR (with the assumption filename only has one dot)

parts = x.match(/[^\.]+/);
x = parts[0];

OR (also with only one dot)

parts = x.split(".");
x = parts[0];

What is the point of "Initial Catalog" in a SQL Server connection string?

If the user name that is in the connection string has access to more then one database you have to specify the database you want the connection string to connect to. If your user has only one database available then you are correct that it doesn't matter. But it is good practice to put this in your connection string.

Write / add data in JSON file using Node.js

I agree with above answers, Here is a complete read and write sample for anyone who needs it.

     router.post('/', function(req, res, next) {

        console.log(req.body);
        var id = Math.floor((Math.random()*100)+1);

        var tital = req.body.title;
        var description = req.body.description;
        var mynotes = {"Id": id, "Title":tital, "Description": description};
        
        fs.readFile('db.json','utf8', function(err,data){
            var obj = JSON.parse(data);
            obj.push(mynotes);
            var strNotes = JSON.stringify(obj);
            fs.writeFile('db.json',strNotes, function(err){
                if(err) return console.log(err);
                console.log('Note added');
            });

        })
        
        
    });


  

How to pass extra variables in URL with WordPress

There are quite few solutions to tackle this issue. First you can go for a plugin if you want:

Or code manually, check out this post:

Also check out:

Generating random integer from a range

Here is an unbiased version that generates numbers in [low, high]:

int r;
do {
  r = rand();
} while (r < ((unsigned int)(RAND_MAX) + 1) % (high + 1 - low));
return r % (high + 1 - low) + low;

If your range is reasonably small, there is no reason to cache the right-hand side of the comparison in the do loop.

How to show Snackbar when Activity starts?

A utils function for show snack bar

fun showSnackBar(activity: Activity, message: String, action: String? = null,
    actionListener: View.OnClickListener? = null, duration: Int = Snackbar.LENGTH_SHORT) {
    val snackBar = Snackbar.make(activity.findViewById(android.R.id.content), message, duration)
        .setBackgroundColor(Color.parseColor("#CC000000")) // todo update your color
        .setTextColor(Color.WHITE)
    if (action != null && actionListener!=null) {
        snackBar.setAction(action, actionListener)
    }
    snackBar.show()
}

Example using in Activity

  showSnackBar(this, "No internet")
  showSnackBar(this, "No internet", duration = Snackbar.LENGTH_LONG)
  showSnackBar(activity, "No internet", "OK", View.OnClickListener { 
       // handle click 
  })

Example using in Fragment

  showSnackBar(getActivity(), "No internet")

Hope it help

Filename timestamp in Windows CMD batch script getting truncated

Here's a batch script I made to return a timestamp. An optional first argument may be provided to be used as a field delimiter. For example:

c:\sys\tmp>timestamp.bat
20160404_144741
c:\sys\tmp>timestamp.bat -
2016-04-04_14-45-25
c:\sys\tmp>timestamp.bat :
2016:04:04_14:45:29

@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
:: put your desired field delimiter here.
:: for example, setting DELIMITER to a hyphen will separate fields like so:
:: yyyy-MM-dd_hh-mm-ss
::
:: setting DELIMITER to nothing will output like so:
:: yyyyMMdd_hhmmss
::
SET DELIMITER=%1

SET DATESTRING=%date:~-4,4%%DELIMITER%%date:~-7,2%%DELIMITER%%date:~-10,2%
SET TIMESTRING=%TIME%
::TRIM OFF the LAST 3 characters of TIMESTRING, which is the decimal point and hundredths of a second
set TIMESTRING=%TIMESTRING:~0,-3%

:: Replace colons from TIMESTRING with DELIMITER
SET TIMESTRING=%TIMESTRING::=!DELIMITER!%

:: if there is a preceeding space substitute with a zero
echo %DATESTRING%_%TIMESTRING: =0%

Remove pattern from string with gsub

The following code works on your example :

gsub(".*_", "", a)

jQuery: using a variable as a selector

You're thinking too complicated. It's actually just $('#'+openaddress).

How can I process each letter of text using Javascript?

If the order of alerts matters, use this:

for (var i = 0; i < str.length; i++) {
  alert(str.charAt(i));
}

Or this: (see also this answer)

 for (var i = 0; i < str.length; i++) {
   alert(str[i]);
 }

If the order of alerts doesn't matter, use this:

var i = str.length;
while (i--) {
  alert(str.charAt(i));
}

Or this: (see also this answer)

 var i = str.length;
while (i--) {
  alert(str[i]);
}

_x000D_
_x000D_
var str = 'This is my string';

function matters() {
  for (var i = 0; i < str.length; i++) {
    alert(str.charAt(i));
  }
}

function dontmatter() {
  var i = str.length;
  while (i--) {
    alert(str.charAt(i));
  }
}
_x000D_
<p>If the order of alerts matters, use <a href="#" onclick="matters()">this</a>.</p>

<p>If the order of alerts doesn't matter, use <a href="#" onclick="dontmatter()">this</a>.</p>
_x000D_
_x000D_
_x000D_

Dropdown using javascript onchange

Something like this should do the trick

<select id="leave" onchange="leaveChange()">
  <option value="5">Get Married</option>
  <option value="100">Have a Baby</option>
  <option value="90">Adopt a Child</option>
  <option value="15">Retire</option>
  <option value="15">Military Leave</option>
  <option value="15">Medical Leave</option>
</select>

<div id="message"></div>

Javascript

function leaveChange() {
    if (document.getElementById("leave").value != "100"){
        document.getElementById("message").innerHTML = "Common message";
    }     
    else{
        document.getElementById("message").innerHTML = "Having a Baby!!";
    }        
}

jsFiddle Demo

A shorter version and more general could be

HTML

<select id="leave" onchange="leaveChange(this)">
  <option value="5">Get Married</option>
  <option value="100">Have a Baby</option>
  <option value="90">Adopt a Child</option>
  <option value="15">Retire</option>
  <option value="15">Military Leave</option>
  <option value="15">Medical Leave</option>
</select>

Javascript

function leaveChange(control) {
    var msg = control.value == "100" ? "Having a Baby!!" : "Common message";
    document.getElementById("message").innerHTML = msg;
}

Set background image in CSS using jquery

Try this:

<div class="rmz-srchbg">
    <input type="text" id="globalsearchstr" name="search" value="" class="rmz-txtbox">
    <input type="submit" value="&nbsp;" id="srchbtn" class="rmz-srchico">
    <br style="clear:both;">
</div>
<script>
$(function(){
   $('#globalsearchstr').on('focus mouseenter', function(){
    $(this).parent().css("background", "url(/images/r-srchbg_white.png) no-repeat");
   });
});
</script>

How can I ask the Selenium-WebDriver to wait for few seconds in Java?

This thread is a bit older, but thought I'd post what I currently do (work in progress).

Though I'm still hitting situations where the system is under heavy load and when I click a submit button (e.g., login.jsp), all three conditions (see below) return true but the next page (e.g., home.jsp) hasn't started loading yet.

This is a generic wait method that takes a list of ExpectedConditions.

public boolean waitForPageLoad(int waitTimeInSec, ExpectedCondition<Boolean>... conditions) {
    boolean isLoaded = false;
    Wait<WebDriver> wait = new FluentWait<>(driver)
            .withTimeout(waitTimeInSec, TimeUnit.SECONDS)
            .ignoring(StaleElementReferenceException.class)
            .pollingEvery(2, TimeUnit.SECONDS);
    for (ExpectedCondition<Boolean> condition : conditions) {
        isLoaded = wait.until(condition);
        if (isLoaded == false) {
            //Stop checking on first condition returning false.
            break;
        }
    }
    return isLoaded;
}

I have defined various reusable ExpectedConditions (three are below). In this example, the three expected conditions include document.readyState = 'complete', no "wait_dialog" present, and no 'spinners' (elements indicating async data is being requested).

Only the first one can be generically applied to all web pages.

/**
 * Returns 'true' if the value of the 'window.document.readyState' via
 * JavaScript is 'complete'
 */
public static final ExpectedCondition<Boolean> EXPECT_DOC_READY_STATE = new ExpectedCondition<Boolean>() {
    @Override
    public Boolean apply(WebDriver driver) {
        String script = "if (typeof window != 'undefined' && window.document) { return window.document.readyState; } else { return 'notready'; }";
        Boolean result;
        try {
            result = ((JavascriptExecutor) driver).executeScript(script).equals("complete");
        } catch (Exception ex) {
            result = Boolean.FALSE;
        }
        return result;
    }
};
/**
 * Returns 'true' if there is no 'wait_dialog' element present on the page.
 */
public static final ExpectedCondition<Boolean> EXPECT_NOT_WAITING = new ExpectedCondition<Boolean>() {
    @Override
    public Boolean apply(WebDriver driver) {
        Boolean loaded = true;
        try {
            WebElement wait = driver.findElement(By.id("F"));
            if (wait.isDisplayed()) {
                loaded = false;
            }
        } catch (StaleElementReferenceException serex) {
            loaded = false;
        } catch (NoSuchElementException nseex) {
            loaded = true;
        } catch (Exception ex) {
            loaded = false;
            System.out.println("EXPECTED_NOT_WAITING: UNEXPECTED EXCEPTION: " + ex.getMessage());
        }
        return loaded;
    }
};
/**
 * Returns true if there are no elements with the 'spinner' class name.
 */
public static final ExpectedCondition<Boolean> EXPECT_NO_SPINNERS = new ExpectedCondition<Boolean>() {
    @Override
    public Boolean apply(WebDriver driver) {
        Boolean loaded = true;
        try {
        List<WebElement> spinners = driver.findElements(By.className("spinner"));
        for (WebElement spinner : spinners) {
            if (spinner.isDisplayed()) {
                loaded = false;
                break;
            }
        }
        }catch (Exception ex) {
            loaded = false;
        }
        return loaded;
    }
};

Depending on the page, I may use one or all of them:

waitForPageLoad(timeoutInSec,
            EXPECT_DOC_READY_STATE,
            EXPECT_NOT_WAITING,
            EXPECT_NO_SPINNERS
    );

There are also predefined ExpectedConditions in the following class: org.openqa.selenium.support.ui.ExpectedConditions

java.sql.SQLException: Fail to convert to internal representation

Your data types are mismatched when you are retrieving the field values.

Also check how you store your enums, default is ORDINAL (numeric value stored in database), but STRING (name of enum stored in database) is also an option. Make sure the Entity in your code and the Model in your database are exactly the same.

I had an enum mismatch. It was set to default (ORDINAL) but the database model was expecting a string VARCHAR2(100char). Solution: @Enumerated(EnumType.STRING)

Setting the JVM via the command line on Windows

You should be able to do this via the command line arguments, assuming these are Sun VMs installed using the usual Windows InstallShield mechanisms with the JVM finder EXE in system32.

Type java -help for the options. In particular, see:

-version:<value>
              require the specified version to run
-jre-restrict-search | -jre-no-restrict-search
              include/exclude user private JREs in the version search

Total Number of Row Resultset getRow Method

The getRow() method will always yield 0 after a query:

ResultSet.getRow()

Retrieves the current row number.

Second, you output totalrec but never assign anything to it.

HTML5 input type range show range value

If you're using multiple slides, and you can use jQuery, you can do the follow to deal with multiple sliders easily:

_x000D_
_x000D_
function updateRangeInput(elem) {_x000D_
  $(elem).next().val($(elem).val());_x000D_
}
_x000D_
input { padding: 8px; border: 1px solid #ddd; color: #555; display: block; }_x000D_
input[type=text] { width: 100px; }_x000D_
input[type=range] { width: 400px; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<input type="range" min="0" max="100" oninput="updateRangeInput(this)" value="0">_x000D_
<input type="text" value="0">_x000D_
_x000D_
<input type="range" min="0" max="100" oninput="updateRangeInput(this)" value="50">_x000D_
<input type="text" value="50">
_x000D_
_x000D_
_x000D_

Also, by using oninput on the <input type='range'> you'll receive events while dragging the range.

Case-Insensitive List Search

Based on Lance Larsen answer - here's an extension method with the recommended string.Compare instead of string.Equals

It is highly recommended that you use an overload of String.Compare that takes a StringComparison parameter. Not only do these overloads allow you to define the exact comparison behavior you intended, using them will also make your code more readable for other developers. [Josh Free @ BCL Team Blog]

public static bool Contains(this List<string> source, string toCheck, StringComparison comp)
{
    return
       source != null &&
       !string.IsNullOrEmpty(toCheck) &&
       source.Any(x => string.Compare(x, toCheck, comp) == 0);
}

Event system in Python

I've been doing it this way:

class Event(list):
    """Event subscription.

    A list of callable objects. Calling an instance of this will cause a
    call to each item in the list in ascending order by index.

    Example Usage:
    >>> def f(x):
    ...     print 'f(%s)' % x
    >>> def g(x):
    ...     print 'g(%s)' % x
    >>> e = Event()
    >>> e()
    >>> e.append(f)
    >>> e(123)
    f(123)
    >>> e.remove(f)
    >>> e()
    >>> e += (f, g)
    >>> e(10)
    f(10)
    g(10)
    >>> del e[0]
    >>> e(2)
    g(2)

    """
    def __call__(self, *args, **kwargs):
        for f in self:
            f(*args, **kwargs)

    def __repr__(self):
        return "Event(%s)" % list.__repr__(self)

However, like with everything else I've seen, there is no auto generated pydoc for this, and no signatures, which really sucks.

Eclipse CDT: Symbol 'cout' could not be resolved

Thanks loads for the answers above. I'm adding an answer for a specific use-case...

On a project with two target architectures each with its own build configuration (the main target is an embedded AVR platform; the second target is my local Linux PC for running unit tests) I found it necessary to set Preferences -> C/C++ -> Indexer -> Use active build configuration as well as to add /usr/include/c++/4.7, /usr/include and /usr/include/c++/4.7/x86_64-linux-gnu to Project Properties -> C/C++ General -> Paths and Symbols and then to rebuild the index.

Run react-native on android emulator

You probably haven't run the Android SDK in forever. So you probably just have to update it. If you open the Android Studio Software it'll probably let you know that and ask to update it for you. Otherwise refer to following link: Update Android SDK

All com.android.support libraries must use the exact same version specification

Had the same issue after updating to Android Studio 2.3, the fix was to add the following package in the build.gradle:

compile 'com.android.support:support-v13:25.3.1'

Note: Change the version to match other support library packages used in your project

How to define two angular apps / modules in one page?

Why do you want to use multiple [ng-app] ? Since Angular is resumed by using modules, you can use an app that use multiple dependencies.

Javascript:

// setter syntax -> initializing other module for demonstration
angular.module('otherModule', []);

angular.module('app', ['otherModule'])
.controller('AppController', function () {
    // ...do something
});

// getter syntax
angular.module('otherModule')
.controller('OtherController', function () {
    // ...do something
});

HTML:

<div ng-app="app">
    <div ng-controller="AppController">...</div>
    <div ng-controller="OtherController">...</div>
</div>

EDIT

Keep in mind that if you want to use controller inside controller you have to use the controllerAs syntax, like so:

<div ng-app="app">
    <div ng-controller="AppController as app">
        <div ng-controller="OtherController as other">...</div>
    </div>
</div>

How to rename a single column in a data.frame?

This can also be done using Hadley's plyr package, and the rename function.

library(plyr) 
df <- data.frame(foo=rnorm(1000)) 
df <- rename(df,c('foo'='samples'))

You can rename by the name (without knowing the position) and perform multiple renames at once. After doing a merge, for example, you might end up with:

  letterid id.x id.y
1       70    2    1
2      116    6    5
3      116    6    4
4      116    6    3
5      766   14    9
6      766   14   13

Which you can then rename in one step using:

letters <- rename(letters,c("id.x" = "source", "id.y" = "target"))

  letterid source target
1       70      2      1
2      116      6      5
3      116      6      4
4      116      6      3
5      766     14      9
6      766     14     13

MySQL pivot table query with dynamic columns

Here's stored procedure, which will generate the table based on data from one table and column and data from other table and column.

The function 'sum(if(col = value, 1,0)) as value ' is used. You can choose from different functions like MAX(if()) etc.

delimiter //

  create procedure myPivot(
    in tableA varchar(255),
    in columnA varchar(255),
    in tableB varchar(255),
    in columnB varchar(255)
)
begin
  set @sql = NULL;
    set @sql = CONCAT('select group_concat(distinct concat(
            \'SUM(IF(', 
        columnA, 
        ' = \'\'\',',
        columnA,
        ',\'\'\', 1, 0)) AS \'\'\',',
        columnA, 
            ',\'\'\'\') separator \', \') from ',
        tableA, ' into @sql');
    -- select @sql;

    PREPARE stmt FROM @sql;
    EXECUTE stmt;

    DEALLOCATE PREPARE stmt;
    -- select @sql;

    SET @sql = CONCAT('SELECT p.', 
        columnB, 
        ', ', 
        @sql, 
        ' FROM ', tableB, ' p GROUP BY p.',
        columnB,'');

    -- select @sql;

    /* */
    PREPARE stmt FROM @sql;
    EXECUTE stmt;
    /* */
    DEALLOCATE PREPARE stmt;
end//

delimiter ;

Check if a path represents a file or a folder

   private static boolean isValidFolderPath(String path) {
    File file = new File(path);
    if (!file.exists()) {
      return file.mkdirs();
    }
    return true;
  }

Basic text editor in command prompt?

There is also a port of nano for windows, which is more more akin to notepad.exe than vim is

https://www.nano-editor.org/dist/win32-support/

Get the WINNT zip. Tested in Windows 7 works as expected

correct PHP headers for pdf file download

$name = 'file.pdf';
//file_get_contents is standard function
$content = file_get_contents($name);
header('Content-Type: application/pdf');
header('Content-Length: '.strlen( $content ));
header('Content-disposition: inline; filename="' . $name . '"');
header('Cache-Control: public, must-revalidate, max-age=0');
header('Pragma: public');
header('Expires: Sat, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
echo $content;

Setting table row height

If you are using Bootstrap, look at padding of your tds.

DBCC CHECKIDENT Sets Identity to 0

USE AdventureWorks2012;  
GO  
DBCC CHECKIDENT ('Person.AddressType', RESEED, 0);  
GO 



AdventureWorks2012=Your databasename
Person.AddressType=Your tablename

What "wmic bios get serialnumber" actually retrieves?

wmic bios get serialnumber     

if run from a command line (start-run should also do the trick) prints out on screen the Serial Number of the product,
(for example in a toshiba laptop it would print out the serial number of the laptop.
with this serial number you can then identify your laptop model if you need ,from the makers service website-usually..:):)

I had to do exactly that.:):)

Unable to find valid certification path to requested target - error even after cert imported

I had the same problem with sbt.
It tried to fetch dependencies from repo1.maven.org over ssl
but said it was "unable to find valid certification path to requested target url".
so I followed this post and still failed to verify a connection.
So I read about it and found that the root cert is not enough, as was suggested by the post,so -
the thing that worked for me was importing the intermediate CA certificates into the keystore.
I actually added all the certificates in the chain and it worked like a charm.

How to replace local branch with remote branch entirely in Git?

It can be done multiple ways, continuing to edit this answer for spreading better knowledge perspective.

1) Reset hard

If you are working from remote develop branch, you can reset HEAD to the last commit on remote branch as below:

git reset --hard origin/develop

2) Delete current branch, and checkout again from the remote repository

Considering, you are working on develop branch in local repo, that syncs with remote/develop branch, you can do as below:

git branch -D develop
git checkout -b develop origin/develop

3) Abort Merge

If you are in-between a bad merge (mistakenly done with wrong branch), and wanted to avoid the merge to go back to the branch latest as below:

git merge --abort

4) Abort Rebase

If you are in-between a bad rebase, you can abort the rebase request as below:

git rebase --abort

Why should I use core.autocrlf=true in Git?

For me.

Edit .gitattributes file.

add

*.dll binary

Then everything goes well.

Remove everything after a certain character

var href = "/Controller/Action?id=11112&value=4444";
href = href.replace(/\?.*/,'');
href ; //# => /Controller/Action

This will work if it finds a '?' and if it doesn't

Android Fatal signal 11 (SIGSEGV) at 0x636f7d89 (code=1). How can it be tracked down?

I was getting this error when using a bitmap like this:

bmp = BitmapFactory.decodeResource(this.getResources(), R.drawable.myBitMap);

What fixed the problem for me was to reduce the size of the bitmap (>1000px high to 700px).

Invalid argument supplied for foreach()

How about this one? lot cleaner and all in single line.

foreach ((array) $items as $item) {
 // ...
 }

Difference between "char" and "String" in Java

In string we can store multiple char. e.g. char ch='a';

String s="a";

String s1="aaaa";

What is the iBeacon Bluetooth Profile

Just to reconcile the difference between sandeepmistry's answer and davidgyoung's answer:

02 01 1a 1a ff 4C 00

Is part of the advertising data format specification [1]

  02 # length of following AD structure
  01 # <<Flags>> AD Structure [2]
  1a # read as b00011010. 
     # In this case, LE General Discoverable,
     # and simultaneous BR/EDR but this may vary by device!

  1a # length of following AD structure
  FF # Manufacturer specific data [3]
4C00 # Apple Inc [4]
0215 # ?? some 2-byte header

Missing from the AD is a Service [5] definition. I think the iBeacon protocol itself has no relationship to the GATT and standard service discovery. If you download RedBearLab's iBeacon program, you'll see that they happen to use the GATT for configuring the advertisement parameters, but this seems to be specific to their implementation, and not part of the spec. The AirLocate program doesn't seem to use the GATT for configuration, for instance, according to LightBlue and or other similar programs I tried.

References:

  1. Core Bluetooth Spec v4, Vol 3, Part C, 11
  2. Vol 3, Part C, 18.1
  3. Vol 3, Part C, 18.11
  4. https://www.bluetooth.org/en-us/specification/assigned-numbers/company-identifiers
  5. Vol 3, Part C, 18.2

Check if a string has a certain piece of text

Here you go: ES5

var test = 'Hello World';
if( test.indexOf('World') >= 0){
  // Found world
}

With ES6 best way would be to use includes function to test if the string contains the looking work.

const test = 'Hello World';
if (test.includes('World')) { 
  // Found world
}

How to split a line into words separated by one or more spaces in bash?

The -a option of read will allow you to split a line read in by the characters contained in $IFS.

Using an image caption in Markdown Jekyll

You can try to use pandoc as your converter. Here's a jekyll plugin to implement this. Pandoc will be able to add a figure caption the same as your alt attribute automatically.

But you have to push the compiled site because github doesn't allow plugins in Github pages for security.

JSON.parse vs. eval()

There is a difference between what JSON.parse() and eval() will accept. Try eval on this:

var x = "{\"shoppingCartName\":\"shopping_cart:2000\"}"

eval(x)         //won't work
JSON.parse(x)   //does work

See this example.

Object variable or With block variable not set (Error 91)

As I wrote in my comment, the solution to your problem is to write the following:

Set hyperLinkText = hprlink.Range

Set is needed because TextRange is a class, so hyperLinkText is an object; as such, if you want to assign it, you need to make it point to the actual object that you need.

How to delete a cookie using jQuery?

To delete a cookie with JQuery, set the value to null:

$.cookie("name", null, { path: '/' });

Edit: The final solution was to explicitly specify the path property whenever accessing the cookie, because the OP accesses the cookie from multiple pages in different directories, and thus the default paths were different (this was not described in the original question). The solution was discovered in discussion below, which explains why this answer was accepted - despite not being correct.

For some versions jQ cookie the solution above will set the cookie to string null. Thus not removing the cookie. Use the code as suggested below instead.

$.removeCookie('the_cookie', { path: '/' });

How to compress an image via Javascript in the browser?

I find that there's simpler solution compared to the accepted answer.

  • Read the files using the HTML5 FileReader API with .readAsArrayBuffer
  • Create a Blob with the file data and get its url with window.URL.createObjectURL(blob)
  • Create new Image element and set it's src to the file blob url
  • Send the image to the canvas. The canvas size is set to desired output size
  • Get the scaled-down data back from canvas via canvas.toDataURL("image/jpeg",0.7) (set your own output format and quality)
  • Attach new hidden inputs to the original form and transfer the dataURI images basically as normal text
  • On backend, read the dataURI, decode from Base64, and save it

As per your question:

Is there a way to compress an image (mostly jpeg, png and gif) directly browser-side, before uploading it

My solution:

  1. Create a blob with the file directly with URL.createObjectURL(inputFileElement.files[0]).

  2. Same as accepted answer.

  3. Same as accepted answer. Worth mentioning that, canvas size is necessary and use img.width and img.height to set canvas.width and canvas.height. Not img.clientWidth.

  4. Get the scale-down image by canvas.toBlob(callbackfunction(blob){}, 'image/jpeg', 0.5). Setting 'image/jpg' has no effect. image/png is also supported. Make a new File object inside the callbackfunction body with let compressedImageBlob = new File([blob]).

  5. Add new hidden inputs or send via javascript . Server doesn't have to decode anything.

Check https://javascript.info/binary for all information. I came up the solution after reading this chapter.


Code:

    <!DOCTYPE html>
    <html>
    <body>
    <form action="upload.php" method="post" enctype="multipart/form-data">
      Select image to upload:
      <input type="file" name="fileToUpload" id="fileToUpload" multiple>
      <input type="submit" value="Upload Image" name="submit">
    </form>
    </body>
    </html>

This code looks far less scary than the other answers..

Update:

One has to put everything inside img.onload. Otherwise canvas will not be able to get the image's width and height correctly as the time canvas is assigned.

    function upload(){
        var f = fileToUpload.files[0];
        var fileName = f.name.split('.')[0];
        var img = new Image();
        img.src = URL.createObjectURL(f);
        img.onload = function(){
            var canvas = document.createElement('canvas');
            canvas.width = img.width;
            canvas.height = img.height;
            var ctx = canvas.getContext('2d');
            ctx.drawImage(img, 0, 0);
            canvas.toBlob(function(blob){
                    console.info(blob.size);
                    var f2 = new File([blob], fileName + ".jpeg");
                    var xhr = new XMLHttpRequest();
                    var form = new FormData();
                    form.append("fileToUpload", f2);
                    xhr.open("POST", "upload.php");
                    xhr.send(form);
            }, 'image/jpeg', 0.5);
        }
    }

3.4MB .png file compression test with image/jpeg argument set.

    |0.9| 777KB |
    |0.8| 383KB |
    |0.7| 301KB |
    |0.6| 251KB |
    |0.5| 219kB |

What's an easy way to read random line from a file in Unix command line?

Here's a simple Python script that will do the job:

import random, sys
lines = open(sys.argv[1]).readlines()
print(lines[random.randrange(len(lines))])

Usage:

python randline.py file_to_get_random_line_from

WebDriver - wait for element using Java

We're having a lot of race conditions with elementToBeClickable. See https://github.com/angular/protractor/issues/2313. Something along these lines worked reasonably well even if a little brute force

Awaitility.await()
        .atMost(timeout)
        .ignoreException(NoSuchElementException.class)
        .ignoreExceptionsMatching(
            Matchers.allOf(
                Matchers.instanceOf(WebDriverException.class),
                Matchers.hasProperty(
                    "message",
                    Matchers.containsString("is not clickable at point")
                )
            )
        ).until(
            () -> {
                this.driver.findElement(locator).click();
                return true;
            },
            Matchers.is(true)
        );

maximum value of int

What about (1 << (8*sizeof(int)-2)) - 1 + (1 << (8*sizeof(int)-2)). This is the same as 2^(8*sizeof(int)-2) - 1 + 2^(8*sizeof(int)-2).

If sizeof(int) = 4 => 2^(8*4-2) - 1 + 2^(8*4-2) = 2^30 - 1 + 20^30 = (2^32)/2 - 1 [max signed int of 4 bytes].

You can't use 2*(1 << (8*sizeof(int)-2)) - 1 because it will overflow, but (1 << (8*sizeof(int)-2)) - 1 + (1 << (8*sizeof(int)-2)) works.

How to find the Number of CPU Cores via .NET/C#?

From .NET Framework source

You can also get it with PInvoke on Kernel32.dll

The following code is coming more or less from SystemInfo.cs from System.Web source located here:

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct SYSTEM_INFO
{
  public ushort wProcessorArchitecture;
  public ushort wReserved;
  public uint dwPageSize;
  public IntPtr lpMinimumApplicationAddress;
  public IntPtr lpMaximumApplicationAddress;
  public IntPtr dwActiveProcessorMask;
  public uint dwNumberOfProcessors;
  public uint dwProcessorType;
  public uint dwAllocationGranularity;
  public ushort wProcessorLevel;
  public ushort wProcessorRevision;
}

internal static class SystemInfo 
{
    static int _trueNumberOfProcessors;
    internal static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);    

    [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
    internal static extern void GetSystemInfo(out SYSTEM_INFO si);

    [DllImport("kernel32.dll")]
    internal static extern int GetProcessAffinityMask(IntPtr handle, out IntPtr processAffinityMask, out IntPtr systemAffinityMask);

    internal static int GetNumProcessCPUs()
    {
      if (SystemInfo._trueNumberOfProcessors == 0)
      {
        SYSTEM_INFO si;
        GetSystemInfo(out si);
        if ((int) si.dwNumberOfProcessors == 1)
        {
          SystemInfo._trueNumberOfProcessors = 1;
        }
        else
        {
          IntPtr processAffinityMask;
          IntPtr systemAffinityMask;
          if (GetProcessAffinityMask(INVALID_HANDLE_VALUE, out processAffinityMask, out systemAffinityMask) == 0)
          {
            SystemInfo._trueNumberOfProcessors = 1;
          }
          else
          {
            int num1 = 0;
            if (IntPtr.Size == 4)
            {
              uint num2 = (uint) (int) processAffinityMask;
              while ((int) num2 != 0)
              {
                if (((int) num2 & 1) == 1)
                  ++num1;
                num2 >>= 1;
              }
            }
            else
            {
              ulong num2 = (ulong) (long) processAffinityMask;
              while ((long) num2 != 0L)
              {
                if (((long) num2 & 1L) == 1L)
                  ++num1;
                num2 >>= 1;
              }
            }
            SystemInfo._trueNumberOfProcessors = num1;
          }
        }
      }
      return SystemInfo._trueNumberOfProcessors;
    }
}

Restart android machine

I think the only way to do this is to run another machine in parallel and use that machine to issue commands to your android box similar to how you would with a phone. If you have issues with the IP changing you can reserve an ip on your router and have the machine grab that one instead of asking the routers DHCP for one. This way you can ping the machine and figure out if it's done rebooting to continue the script.

Best programming based games

I think the original game was called Core Wars (this Wikipedia article contains a lot of interesting links); there still seem to be programs and competitions around, for example at corewars.org. I never had the time to look into these games, but they seem like great fun.

Is there a way to create xxhdpi, xhdpi, hdpi, mdpi and ldpi drawables from a large scale image?

Use an online service like Image Baker.

image baker

It's simple. Upload the images and download processed assets for both Android and iOS.

Downloaded images

Note: Image Baker is a free service created by my friend and myself.

Summarizing multiple columns with dplyr?

We can summarize by using summarize_at, summarize_all and summarize_if on dplyr 0.7.4. We can set the multiple columns and functions by using vars and funs argument as below code. The left-hand side of funs formula is assigned to suffix of summarized vars. In the dplyr 0.7.4, summarise_each(and mutate_each) is already deprecated, so we cannot use these functions.

options(scipen = 100, dplyr.width = Inf, dplyr.print_max = Inf)

library(dplyr)
packageVersion("dplyr")
# [1] ‘0.7.4’

set.seed(123)
df <- data_frame(
  a = sample(1:5, 10, replace=T), 
  b = sample(1:5, 10, replace=T), 
  c = sample(1:5, 10, replace=T), 
  d = sample(1:5, 10, replace=T), 
  grp = as.character(sample(1:3, 10, replace=T)) # For convenience, specify character type
)

df %>% group_by(grp) %>% 
  summarise_each(.vars = letters[1:4],
                 .funs = c(mean="mean"))
# `summarise_each()` is deprecated.
# Use `summarise_all()`, `summarise_at()` or `summarise_if()` instead.
# To map `funs` over a selection of variables, use `summarise_at()`
# Error: Strings must match column names. Unknown columns: mean

You should change to the following code. The following codes all have the same result.

# summarise_at
df %>% group_by(grp) %>% 
  summarise_at(.vars = letters[1:4],
               .funs = c(mean="mean"))

df %>% group_by(grp) %>% 
  summarise_at(.vars = names(.)[1:4],
               .funs = c(mean="mean"))

df %>% group_by(grp) %>% 
  summarise_at(.vars = vars(a,b,c,d),
               .funs = c(mean="mean"))

# summarise_all
df %>% group_by(grp) %>% 
  summarise_all(.funs = c(mean="mean"))

# summarise_if
df %>% group_by(grp) %>% 
  summarise_if(.predicate = function(x) is.numeric(x),
               .funs = funs(mean="mean"))
# A tibble: 3 x 5
# grp a_mean b_mean c_mean d_mean
# <chr>  <dbl>  <dbl>  <dbl>  <dbl>
# 1     1   2.80   3.00    3.6   3.00
# 2     2   4.25   2.75    4.0   3.75
# 3     3   3.00   5.00    1.0   2.00

You can also have multiple functions.

df %>% group_by(grp) %>% 
  summarise_at(.vars = letters[1:2],
               .funs = c(Mean="mean", Sd="sd"))
# A tibble: 3 x 5
# grp a_Mean b_Mean      a_Sd     b_Sd
# <chr>  <dbl>  <dbl>     <dbl>    <dbl>
# 1     1   2.80   3.00 1.4832397 1.870829
# 2     2   4.25   2.75 0.9574271 1.258306
# 3     3   3.00   5.00        NA       NA

Mismatched anonymous define() module

In getting started with require.js I ran into the issue and as a beginner the docs may as well been written in greek.

The issue I ran into was that most of the beginner examples use "anonymous defines" when you should be using a "string id".

anonymous defines

define(function() {
        return { helloWorld: function() { console.log('hello world!') } };
 })
    
  
define(function() {
        return { helloWorld2: function() { console.log('hello world again!') } };
 })

define with string id

define('moduleOne',function() {
    return { helloWorld: function() { console.log('hello world!') } };
})

 define('moduleTwo', function() {
      return { helloWorld2: function() { console.log('hello world again!') } };
})

When you use define with a string id then you will avoid this error when you try to use the modules like so:

require([ "moduleOne", "moduleTwo" ], function(moduleOne, moduleTwo) {
    moduleOne.helloWorld();
    moduleTwo.helloWorld2();
});

Precision String Format Specifier In Swift

A more elegant and generic solution is to rewrite ruby / python % operator:

// Updated for beta 5
func %(format:String, args:[CVarArgType]) -> String {
    return NSString(format:format, arguments:getVaList(args))
}

"Hello %@, This is pi : %.2f" % ["World", M_PI]

How do I convert hex to decimal in Python?

>>> int("0xff", 16)
255

or

>>> int("FFFF", 16)
65535

Read the docs.

What is the difference between res.end() and res.send()?

res.send() implements res.write, res.setHeaders and res.end:

  1. It checks the data you send and sets the correct response headers.
  2. Then it streams the data with res.write.
  3. Finally, it uses res.end to set the end of the request.

There are some cases in which you will want to do this manually, for example, if you want to stream a file or a large data set. In these cases, you will want to set the headers yourself and use res.write to keep the stream flow.

How to make an executable JAR file?

It's too late to answer for this question. But if someone is searching for this answer now I've made it to run with no errors.

First of all make sure to download and add maven to path. [ mvn --version ] will give you version specifications of it if you have added to the path correctly.

Now , add following code to the maven project [ pom.xml ] , in the following code replace with your own main file entry point for eg [ com.example.test.Test ].

      <plugin>
            <!-- Build an executable JAR -->
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <version>2.4</version>
            <configuration>
                <archive>
                    <manifest>
                    <mainClass>
            your_package_to_class_that_contains_main_file .MainFileName</mainClass>
                    </manifest>
                </archive>
            </configuration>
        </plugin>

Now go to the command line [CMD] in your project and type mvn package and it will generate a jar file as something like ProjectName-0.0.1-SNAPSHOT.jar under target directory.

Now navigate to the target directory by cd target.

Finally type java -jar jar-file-name.jar and yes this should work successfully if you don't have any errors in your program.

ModelState.IsValid == false, why?

bool hasErrors =  ViewData.ModelState.Values.Any(x => x.Errors.Count > 1);

or iterate with

    foreach (ModelState state in ViewData.ModelState.Values.Where(x => x.Errors.Count > 0))
    {

    }

How to print a dictionary's key?

I looked up this question, because I wanted to know how to retrieve the name of "the key" if my dictionary only had one entry. In my case, the key was unknown to me and could be any number of things. Here is what I came up with:

dict1 = {'random_word': [1,2,3]}
key_name = str([key for key in dict1]).strip("'[]'")        
print(key_name)  # equal to 'random_word', type: string.

Shell script not running, command not found

Try chmod u+x MigrateNshell.sh

When and where to use GetType() or typeof()?

typeof is applied to a name of a type or generic type parameter known at compile time (given as identifier, not as string). GetType is called on an object at runtime. In both cases the result is an object of the type System.Type containing meta-information on a type.

Example where compile-time and run-time types are equal

string s = "hello";

Type t1 = typeof(string);
Type t2 = s.GetType();

t1 == t2 ==> true

Example where compile-time and run-time types are different

object obj = "hello";

Type t1 = typeof(object); // ==> object
Type t2 = obj.GetType();  // ==> string!

t1 == t2 ==> false

i.e., the compile time type (static type) of the variable obj is not the same as the runtime type of the object referenced by obj.


Testing types

If, however, you only want to know whether mycontrol is a TextBox then you can simply test

if (mycontrol is TextBox)

Note that this is not completely equivalent to

if (mycontrol.GetType() == typeof(TextBox))    

because mycontrol could have a type that is derived from TextBox. In that case the first comparison yields true and the second false! The first and easier variant is OK in most cases, since a control derived from TextBox inherits everything that TextBox has, probably adds more to it and is therefore assignment compatible to TextBox.

public class MySpecializedTextBox : TextBox
{
}

MySpecializedTextBox specialized = new MySpecializedTextBox();
if (specialized is TextBox)       ==> true

if (specialized.GetType() == typeof(TextBox))        ==> false

Casting

If you have the following test followed by a cast and T is nullable ...

if (obj is T) {
    T x = (T)obj; // The casting tests, whether obj is T again!
    ...
}

... you can change it to ...

T x = obj as T;
if (x != null) {
    ...
}

Testing whether a value is of a given type and casting (which involves this same test again) can both be time consuming for long inheritance chains. Using the as operator followed by a test for null is more performing.

Starting with C# 7.0 you can simplify the code by using pattern matching:

if (obj is T t) {
    // t is a variable of type T having a non-null value.
    ...
}

Btw.: this works for value types as well. Very handy for testing and unboxing. Note that you cannot test for nullable value types:

if (o is int? ni) ===> does NOT compile!

This is because either the value is null or it is an int. This works for int? o as well as for object o = new Nullable<int>(x);:

if (o is int i) ===> OK!

I like it, because it eliminates the need to access the Nullable<T>.Value property.

How to set a border for an HTML div tag

In bootstrap 4, you can use border utilities like so.

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>_x000D_
_x000D_
<style>_x000D_
  .border-5 {_x000D_
    border-width: 5px !important;_x000D_
  }_x000D_
</style>_x000D_
_x000D_
<textarea class="border border-dark border-5">some content</textarea>
_x000D_
_x000D_
_x000D_

How to set up googleTest as a shared library on Linux

The following method avoids manually messing with the /usr/lib directory while also requiring minimal change in your CMakeLists.txt file. It also lets your package manager cleanly uninstall libgtest-dev.

The idea is that when you get the libgtest-dev package via

sudo apt install libgtest-dev

The source is stored in location /usr/src/googletest

You can simply point your CMakeLists.txt to that directory so that it can find the necessary dependencies

Simply replace FindGTest with add_subdirectory(/usr/src/googletest gtest)

At the end, it should look like this

add_subdirectory(/usr/src/googletest gtest)
target_link_libraries(your_executable gtest)

How can I create 2 separate log files with one log4j config file?

Try the following configuration:

log4j.rootLogger=TRACE, stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n

log4j.appender.debugLog=org.apache.log4j.FileAppender
log4j.appender.debugLog.File=logs/debug.log
log4j.appender.debugLog.layout=org.apache.log4j.PatternLayout
log4j.appender.debugLog.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n

log4j.appender.reportsLog=org.apache.log4j.FileAppender
log4j.appender.reportsLog.File=logs/reports.log
log4j.appender.reportsLog.layout=org.apache.log4j.PatternLayout
log4j.appender.reportsLog.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n

log4j.category.debugLogger=TRACE, debugLog
log4j.additivity.debugLogger=false

log4j.category.reportsLogger=DEBUG, reportsLog
log4j.additivity.reportsLogger=false

Then configure the loggers in the Java code accordingly:

static final Logger debugLog = Logger.getLogger("debugLogger");
static final Logger resultLog = Logger.getLogger("reportsLogger");

Do you want output to go to stdout? If not, change the first line of log4j.properties to:

log4j.rootLogger=OFF

and get rid of the stdout lines.

How to restart service using command prompt?

PowerShell features a Restart-Service cmdlet, which either starts or restarts the service as appropriate.

The Restart-Service cmdlet sends a stop message and then a start message to the Windows Service Controller for a specified service. If a service was already stopped, it is started without notifying you of an error.

You can specify the services by their service names or display names, or you can use the InputObject parameter to pass an object that represents each service that you want to restart.

It is a little more foolproof than running two separate commands.

The easiest way to use it just pass either the service name or the display name directly:

Restart-Service 'Service Name'

It can be used directly from the standard cmd prompt with a command like:

powershell -command "Restart-Service 'Service Name'"

Accessing JSON elements

Just for more one option...You can do it this way too:

MYJSON = {
    'username': 'gula_gut',
    'pics': '/0/myfavourite.jpeg',
    'id': '1'
}

#changing username
MYJSON['username'] = 'calixto'
print(MYJSON['username'])

I hope this can help.

POST request with JSON body

You need to use the cURL library to send this request.

<?php
// Your ID and token
$blogID = '8070105920543249955';
$authToken = 'OAuth 2.0 token here';

// The data to send to the API
$postData = array(
    'kind' => 'blogger#post',
    'blog' => array('id' => $blogID),
    'title' => 'A new post',
    'content' => 'With <b>exciting</b> content...'
);

// Setup cURL
$ch = curl_init('https://www.googleapis.com/blogger/v3/blogs/'.$blogID.'/posts/');
curl_setopt_array($ch, array(
    CURLOPT_POST => TRUE,
    CURLOPT_RETURNTRANSFER => TRUE,
    CURLOPT_HTTPHEADER => array(
        'Authorization: '.$authToken,
        'Content-Type: application/json'
    ),
    CURLOPT_POSTFIELDS => json_encode($postData)
));

// Send the request
$response = curl_exec($ch);

// Check for errors
if($response === FALSE){
    die(curl_error($ch));
}

// Decode the response
$responseData = json_decode($response, TRUE);

// Close the cURL handler
curl_close($ch);

// Print the date from the response
echo $responseData['published'];

If, for some reason, you can't/don't want to use cURL, you can do this:

<?php
// Your ID and token
$blogID = '8070105920543249955';
$authToken = 'OAuth 2.0 token here';

// The data to send to the API
$postData = array(
    'kind' => 'blogger#post',
    'blog' => array('id' => $blogID),
    'title' => 'A new post',
    'content' => 'With <b>exciting</b> content...'
);

// Create the context for the request
$context = stream_context_create(array(
    'http' => array(
        // http://www.php.net/manual/en/context.http.php
        'method' => 'POST',
        'header' => "Authorization: {$authToken}\r\n".
            "Content-Type: application/json\r\n",
        'content' => json_encode($postData)
    )
));

// Send the request
$response = file_get_contents('https://www.googleapis.com/blogger/v3/blogs/'.$blogID.'/posts/', FALSE, $context);

// Check for errors
if($response === FALSE){
    die('Error');
}

// Decode the response
$responseData = json_decode($response, TRUE);

// Print the date from the response
echo $responseData['published'];

Switch statement equivalent in Windows batch file

It might be a bit late, but this does it:

set "case1=operation1"
set "case2=operation2"
set "case3=operation3"

setlocal EnableDelayedExpansion
!%switch%!
endlocal

%switch% gets replaced before line execution. Serious downsides:

  • You override the case variables
  • It needs DelayedExpansion

Might eventually be usefull in some cases.

jQuery click event not working in mobile browsers

I know this is a resolved old topic, but I just answered a similar question, and though my answer could help someone else as it covers other solution options:

Click events work a little differently on touch enabled devices. There is no mouse, so technically there is no click. According to this article - http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html - due to memory limitations, click events are only emulated and dispatched from anchor and input elements. Any other element could use touch events, or have click events manually initialized by adding a handler to the raw html element, for example, to force click events on list items:

$('li').each(function(){
    this.onclick = function() {}
});

Now click will be triggered by li, therefore can be listened by jQuery.


On your case, you could just change the listener to the anchor element as very well put by @mason81, or use a touch event on the li:

$('.menu').on('touchstart', '.publications', function(){
    $('#filter_wrapper').show();
});

Here is a fiddle with a few experiments - http://jsbin.com/ukalah/9/edit

Python equivalent to 'hold on' in Matlab

You can use the following:

plt.hold(True)

What is a deadlock?

A deadlock occurs when there is a circular chain of threads or processes which each hold a locked resource and are trying to lock a resource held by the next element in the chain. For example, two threads that hold respectively lock A and lock B, and are both trying to acquire the other lock.

Sql select rows containing part of string

you can use CHARINDEX in t-sql.

select * from table where CHARINDEX(url, 'http://url.com/url?url...') > 0

Code not running in IE 11, works fine in Chrome

As others have said startsWith and endsWith are part of ES6 and not available in IE11. Our company always uses lodash library as a polyfill solution for IE11. https://lodash.com/docs/4.17.4

_.startsWith([string=''], [target], [position=0])

How to change heatmap.2 color range in R?

Here's another option for those not using heatmap.2 (aheatmap is good!)

Make a sequential vector of 100 values from min to max of your input matrix, find value closest to 0 in that, make two vector of colours to and from desired midpoint, combine and use them:

breaks <- seq(from=min(range(inputMatrix)), to=max(range(inputMatrix)), length.out=100)
midpoint <- which.min(abs(breaks - 0))
rampCol1 <- colorRampPalette(c("forestgreen", "darkgreen", "black"))(midpoint)
rampCol2 <- colorRampPalette(c("black", "darkred", "red"))(100-(midpoint+1))
rampCols <- c(rampCol1,rampCol2)

How do I trigger a macro to run after a new mail is received in Outlook?

This code will add an event listener to the default local Inbox, then take some action on incoming emails. You need to add that action in the code below.

Private WithEvents Items As Outlook.Items 
Private Sub Application_Startup() 
  Dim olApp As Outlook.Application 
  Dim objNS As Outlook.NameSpace 
  Set olApp = Outlook.Application 
  Set objNS = olApp.GetNamespace("MAPI") 
  ' default local Inbox
  Set Items = objNS.GetDefaultFolder(olFolderInbox).Items 
End Sub
Private Sub Items_ItemAdd(ByVal item As Object) 

  On Error Goto ErrorHandler 
  Dim Msg As Outlook.MailItem 
  If TypeName(item) = "MailItem" Then
    Set Msg = item 
    ' ******************
    ' do something here
    ' ******************
  End If
ProgramExit: 
  Exit Sub
ErrorHandler: 
  MsgBox Err.Number & " - " & Err.Description 
  Resume ProgramExit 
End Sub

After pasting the code in ThisOutlookSession module, you must restart Outlook.

Dynamically creating keys in a JavaScript associative array

Use the first example. If the key doesn't exist it will be added.

var a = new Array();
a['name'] = 'oscar';
alert(a['name']);

Will pop up a message box containing 'oscar'.

Try:

var text = 'name = oscar'
var dict = new Array()
var keyValuePair = text.replace(/ /g,'').split('=');
dict[ keyValuePair[0] ] = keyValuePair[1];
alert( dict[keyValuePair[0]] );

Python: OSError: [Errno 2] No such file or directory: ''

Use os.path.abspath():

os.chdir(os.path.dirname(os.path.abspath(sys.argv[0])))

sys.argv[0] in your case is just a script name, no directory, so os.path.dirname() returns an empty string.

os.path.abspath() turns that into a proper absolute path with directory name.

How to insert a newline in front of a pattern?

This works in MAC for me

sed -i.bak -e 's/regex/xregex/g' input.txt sed -i.bak -e 's/qregex/\'$'\nregex/g' input.txt

Dono whether its perfect one...

Subversion stuck due to "previous operation has not finished"?

I have also stuck with the same issue I have tried blow:

1.Try kill the process related to svn i.e. TSVNCache.exe and TortoiseProc 2.Reverting the unversioned files and deletion of same, which I have in svn . 3.cleanup using command prompt "svn cleanup"

and finally when restarted the desktop it worked for me , So for restart of system worked for me

NSDictionary to NSArray?

You can create an array of all the objects inside the dictionary and then use it as a datasource for the TableView.

NSArray *aValuesArray = [yourDict allValues];

How to enable native resolution for apps on iPhone 6 and 6 Plus?

You can add a launch screen file that appears to work for multiple screen sizes. I just added the MainStoryboard as a launch screen file and that stopped the app from scaling. I think I will need to add a permanent launch screen later, but that got the native resolution up and working quickly. In Xcode, go to your target, general and add the launch screen file there.

Launch Screen File

Angular 2 change event - model changes

Use the (ngModelChange) event to detect changes on the model

React: "this" is undefined inside a component function

There are a couple of ways.

One is to add this.onToggleLoop = this.onToggleLoop.bind(this); in the constructor.

Another is arrow functions onToggleLoop = (event) => {...}.

And then there is onClick={this.onToggleLoop.bind(this)}.

Convert PEM to PPK file format

I'm rather shocked that this has not been answered since the solution is very simple.

As mentioned in previous posts, you would not want to convert it using C#, but just once. This is easy to do with PuTTYGen.

  1. Download your .pem from AWS
  2. Open PuTTYgen
  3. Click "Load" on the right side about 3/4 down
  4. Set the file type to *.*
  5. Browse to, and Open your .pem file
  6. PuTTY will auto-detect everything it needs, and you just need to click "Save private key" and you can save your ppk key for use with PuTTY

Enjoy!

java.net.SocketException: Software caused connection abort: recv failed

This will happen from time to time either when a connection times out or when a remote host terminates their connection (closed application, computer shutdown, etc). You can avoid this by managing sockets yourself and handling disconnections in your application via its communications protocol and then calling shutdownInput and shutdownOutput to clear up the session.

set up device for development (???????????? no permissions)

Only for Ubuntu/ Debian users: There are some specific things to do for ubuntu to make USB debugging work: described here: https://developer.android.com/studio/run/device Here are the two steps mentioned. Run this two command in terminal:

sudo usermod -aG plugdev $LOGNAME
sudo apt-get install android-sdk-platform-tools-common

C# How to change font of a label

Font.Name, Font.XYZProperty, etc are readonly as Font is an immutable object, so you need to specify a new Font object to replace it:

mainForm.lblName.Font = new Font("Arial", mainForm.lblName.Font.Size);

Check the constructor of the Font class for further options.

mysql update multiple columns with same now()

You can put the following code on the default value of the timestamp column: CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, so on update the two columns take the same value.

How can I do SELECT UNIQUE with LINQ?

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

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

Disable a textbox using CSS

&tl;dr: No, you can't disable a textbox using CSS.

pointer-events: none works but on IE the CSS property only works with IE 11 or higher, so it doesn't work everywhere on every browser. Except for that you cannot disable a textbox using CSS.

However you could disable a textbox in HTML like this:

<input value="...." readonly />

But if the textbox is in a form and you want the value of the textbox to be not submitted, instead do this:

<input value="...." disabled />

So the difference between these two options for disabling a textbox is that disabled cannot allow you to submit the value of the input textbox but readonly does allow.

For more information on the difference between these two, see "What is the difference between disabled="disabled" and readonly="readonly".

Is there a null-coalescing (Elvis) operator or safe navigation operator in javascript?

For the former, you can use ||. The Javascript "logical or" operator, rather than simply returning canned true and false values, follows the rule of returning its left argument if it is true, and otherwise evaluating and returning its right argument. When you're only interested in the truth value it works out the same, but it also means that foo || bar || baz returns the leftmost one of foo, bar, or baz that contains a true value.

You won't find one that can distinguish false from null, though, and 0 and empty string are false values, so avoid using the value || default construct where value can legitimately be 0 or "".

If/else else if in Jquery for a condition

If statement for images in jquery:
#html

<button id="chain">Chain</button>
<img src="bulb_on.jpg" alt="img" id="img"/>

#script
    <script>
        $(document).ready(function(){
            $("#chain").click(function(){
            if($("#img").attr('src')!='bulb_on.jpg'){
                $("#img").attr('src', 'bulb_on.jpg');
            }
            else
            {
                $("#img").attr('src', 'bulb_onn.jpg');
            }
            });
        });
    </script>

(change) vs (ngModelChange) in angular

In Angular 7, the (ngModelChange)="eventHandler()" will fire before the value bound to [(ngModel)]="value" is changed while the (change)="eventHandler()" will fire after the value bound to [(ngModel)]="value" is changed.

javaw.exe cannot find path

Just update your eclipse.ini file (you can find it in the root-directory of eclipse) by this:

-vm
path/javaw.exe

for example:

-vm 
C:/Program Files/Java/jdk1.7.0_09/jre/bin/javaw.exe

json.net has key method?

Just use x["error_msg"]. If the property doesn't exist, it returns null.

SVN change username

I believe you could create you own branch (using your own credential) from the same trunk as your workmate's branch, merge from your workmate's branch to your working copy and then merge from your branch. All future commit should be marked as coming from you.

how to make UITextView height dynamic according to text length?

Declaration here

    fileprivate weak var textView: UITextView!

Call your setupview here

    override func viewDidLoad() {
        super.viewDidLoad()

         setupViews()
    }

Setup here

    fileprivate func setupViews() {

    let textView = UITextView()
    textView.translatesAutoresizingMaskIntoConstraints = false
    textView.text = "your text here"
    textView.font = UIFont.poppinsMedium(size: 14)
    textView.textColor = UIColor.brownishGrey
    textView.textAlignment = .left
    textView.isEditable = false
    textView.isScrollEnabled = false
    textView.textContainerInset = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)

   self.view.addSubview(textView)

   self.textView = textView

   setupConstraints()

   }

Setup constraints here

   fileprivate func setupConstraints() {

    NSLayoutConstraint.activate([

        textView.topAnchor.constraint(equalTo: view.topAnchor, constant: 20),
        textView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 20),
        textView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -20),
        textView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -20),
        textView.heightAnchor.constraint(greaterThanOrEqualToConstant: 150),
        ])
  }

Doctrine 2: Update query with query builder

I think you need to use Expr with ->set() (However THIS IS NOT SAFE and you shouldn't do it):

$qb = $this->em->createQueryBuilder();
$q = $qb->update('models\User', 'u')
        ->set('u.username', $qb->expr()->literal($username))
        ->set('u.email', $qb->expr()->literal($email))
        ->where('u.id = ?1')
        ->setParameter(1, $editId)
        ->getQuery();
$p = $q->execute();

It's much safer to make all your values parameters instead:

$qb = $this->em->createQueryBuilder();
$q = $qb->update('models\User', 'u')
        ->set('u.username', '?1')
        ->set('u.email', '?2')
        ->where('u.id = ?3')
        ->setParameter(1, $username)
        ->setParameter(2, $email)
        ->setParameter(3, $editId)
        ->getQuery();
$p = $q->execute();

SELECT *, COUNT(*) in SQLite

count(*) is an aggregate function. Aggregate functions need to be grouped for a meaningful results. You can read: count columns group by

MySQL: how to get the difference between two timestamps in seconds

You could use the TIMEDIFF() and the TIME_TO_SEC() functions as follows:

SELECT TIME_TO_SEC(TIMEDIFF('2010-08-20 12:01:00', '2010-08-20 12:00:00')) diff;
+------+
| diff |
+------+
|   60 |
+------+
1 row in set (0.00 sec)

You could also use the UNIX_TIMESTAMP() function as @Amber suggested in an other answer:

SELECT UNIX_TIMESTAMP('2010-08-20 12:01:00') - 
       UNIX_TIMESTAMP('2010-08-20 12:00:00') diff;
+------+
| diff |
+------+
|   60 |
+------+
1 row in set (0.00 sec)

If you are using the TIMESTAMP data type, I guess that the UNIX_TIMESTAMP() solution would be slightly faster, since TIMESTAMP values are already stored as an integer representing the number of seconds since the epoch (Source). Quoting the docs:

When UNIX_TIMESTAMP() is used on a TIMESTAMP column, the function returns the internal timestamp value directly, with no implicit “string-to-Unix-timestamp” conversion.

Keep in mind that TIMEDIFF() return data type of TIME. TIME values may range from '-838:59:59' to '838:59:59' (roughly 34.96 days)

pip install fails with "connection error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:598)"

Short answer

If running into this at home on a corporate machine, try again at work.

Details

I ran into this over the weekend. Pip and conda both broken, unable to install or update. SO was helpful, but many answers were problematic on a corporate machine - the solutions require the ability to pip install (already does not work) or require downloading an installer (the ones I wanted to download were prohibited by firewall settings).

What worked for me was to try again when I was on prem. This worked. It turned out the corporate firewall settings were different when using the machine at home vs at work.

How (and why) to use display: table-cell (CSS)

How (and why) to use display: table-cell (CSS)

I just wanted to mention, since I don't think any of the other answers did directly, that the answer to "why" is: there is no good reason, and you should probably never do this.

In my over a decade of experience in web development, I can't think of a single time I would have been better served to have a bunch of <div>s with display styles than to just have table elements.

The only hypothetical I could come up with is if you have tabular data stored in some sort of non-HTML-table format (eg. a CSV file). In a very specific version of this case it might be easier to just add <div> tags around everything and then add descendent-based styles, instead of adding actual table tags.

But that's an extremely contrived example, and in all real cases I know of simply using table tags would be better.

python plot normal distribution

import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as stats
import math

mu = 0
variance = 1
sigma = math.sqrt(variance)
x = np.linspace(mu - 3*sigma, mu + 3*sigma, 100)
plt.plot(x, stats.norm.pdf(x, mu, sigma))
plt.show()

gass distro, mean is 0 variance 1

Adding Only Untracked Files

Not exactly what you're looking for, but I've found this quite helpful:

git add -AN

Will add all files to the index, but without their content. Files that were untracked now behave as if they were tracked. Their content will be displayed in git diff, and you can add then interactively with git add -p.

Remove scrollbars from textarea

style="overflow: hidden" and style="resize: none" were the ones that did the trick.

Appending a byte[] to the end of another byte[]

First you need to allocate an array of the combined length, then use arraycopy to fill it from both sources.

byte[] ciphertext = blah;
byte[] mac = blah;
byte[] out = new byte[ciphertext.length + mac.length];


System.arraycopy(ciphertext, 0, out, 0, ciphertext.length);
System.arraycopy(mac, 0, out, ciphertext.length, mac.length);

Javascript - Regex to validate date format

Try this:

^\d\d[./-]\d\d[./-]\d\d\d\d$

GoogleTest: How to skip a test?

If more than one test are needed be skipped

--gtest_filter=-TestName.*:TestName.*TestCase

What is the default Precision and Scale for a Number in Oracle?

Oracle stores numbers in the following way: 1 byte for power, 1 byte for the first significand digit (that is one before the separator), the rest for the other digits.

By digits here Oracle means centesimal digits (i. e. base 100)

SQL> INSERT INTO t_numtest VALUES (LPAD('9', 125, '9'))
  2  /

1 row inserted

SQL> INSERT INTO t_numtest VALUES (LPAD('7', 125, '7'))
  2  /

1 row inserted

SQL> INSERT INTO t_numtest VALUES (LPAD('9', 126, '9'))
  2  /

INSERT INTO t_numtest VALUES (LPAD('9', 126, '9'))

ORA-01426: numeric overflow

SQL> SELECT DUMP(num) FROM t_numtest;

DUMP(NUM)
--------------------------------------------------------------------------------
Typ=2 Len=2: 255,11
Typ=2 Len=21: 255,8,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,79

As we can see, the maximal number here is 7.(7) * 10^124, and he have 19 centesimal digits for precision, or 38 decimal digits.

Extract substring from a string

You can use subSequence , it's same as substr in C

 Str.subSequence(int Start , int End)

How do I hide a menu item in the actionbar?

Create you menu options the normal way see code below and add a global reference within the class to the menu

Menu mMenu;  // global reference within the class
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_tcktdetails, menu);
    mMenu=menu;  // assign the menu to the new menu item you just created 
    return true;
}


@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.action_cancelticket) {
        cancelTicket();

        return true;
    }

    return super.onOptionsItemSelected(item);
}

Now you can toggle your menu by running this code with a button or within a function

if(mMenu != null) {
                mMenu.findItem(R.id.action_cancelticket).setVisible(false);
            }

Is there any difference between "!=" and "<>" in Oracle Sql?

No there is no difference at all in functionality.
(The same is true for all other DBMS - most of them support both styles):

Here is the current SQL reference: https://docs.oracle.com/database/121/SQLRF/conditions002.htm#CJAGAABC

The SQL standard only defines a single operator for "not equals" and that is <>

How to make image hover in css?

Exact solution to your problem

You can change the image on hover by using content:url("YOUR-IMAGE-PATH");

For image hover use below line in your css:

img:hover

and to change the image on hover using the below config inside img:hover:

img:hover{
content:url("https://www.planwallpaper.com/static/images/9-credit-1.jpg");
}

Single line if statement with 2 actions

userType = (user.Type == 0) ? "Admin" : (user.type == 1) ? "User" : "Admin";

should do the trick.

Java: Unresolved compilation problem

I got this error multiple times and struggled to work out. Finally, I removed the run configuration and re-added the default entries. It worked beautifully.

How to use a WSDL file to create a WCF service (not make a call)

Using svcutil, you can create interfaces and classes (data contracts) from the WSDL.

svcutil your.wsdl (or svcutil your.wsdl /l:vb if you want Visual Basic)

This will create a file called "your.cs" in C# (or "your.vb" in VB.NET) which contains all the necessary items.

Now, you need to create a class "MyService" which will implement the service interface (IServiceInterface) - or the several service interfaces - and this is your server instance.

Now a class by itself doesn't really help yet - you'll need to host the service somewhere. You need to either create your own ServiceHost instance which hosts the service, configure endpoints and so forth - or you can host your service inside IIS.

Warning: #1265 Data truncated for column 'pdd' at row 1

You are most likely pushing a string 'NULL' to the table, rather then an actual NULL, but other things may be going on as well, an illustration:

mysql> CREATE TABLE date_test (pdd DATE NOT NULL);
Query OK, 0 rows affected (0.11 sec)

mysql> INSERT INTO date_test VALUES (NULL);
ERROR 1048 (23000): Column 'pdd' cannot be null
mysql> INSERT INTO date_test VALUES ('NULL');
Query OK, 1 row affected, 1 warning (0.05 sec)

mysql> show warnings;
+---------+------+------------------------------------------+
| Level   | Code | Message                                  |
+---------+------+------------------------------------------+
| Warning | 1265 | Data truncated for column 'pdd' at row 1 |
+---------+------+------------------------------------------+
1 row in set (0.00 sec)

mysql> SELECT * FROM date_test;
+------------+
| pdd        |
+------------+
| 0000-00-00 |
+------------+
1 row in set (0.00 sec)

mysql> ALTER TABLE date_test MODIFY COLUMN pdd DATE NULL;
Query OK, 1 row affected (0.15 sec)
Records: 1  Duplicates: 0  Warnings: 0

mysql> INSERT INTO date_test VALUES (NULL);
Query OK, 1 row affected (0.06 sec)

mysql> SELECT * FROM date_test;
+------------+
| pdd        |
+------------+
| 0000-00-00 |
| NULL       |
+------------+
2 rows in set (0.00 sec)

Extract first and last row of a dataframe in pandas

The accepted answer duplicates the first row if the frame only contains a single row. If that's a concern

df[0::len(df)-1 if len(df) > 1 else 1]

works even for single row-dataframes.

Example: For the following dataframe this will not create a duplicate:

df = pd.DataFrame({'a': [1], 'b':['a']})
df2 = df[0::len(df)-1 if len(df) > 1  else 1]

print df2

   a  b
0  1  a

whereas this does:

df3 = df.iloc[[0, -1]]

print df3 

   a  b
0  1  a
0  1  a

because the single row is the first AND last row at the same time.

How to change the port of Tomcat from 8080 to 80?

On modern linux the best approach (for me) is to use xinetd :

1) create /etc/xinet.d/tomcat-http

service http
{
        disable = no
        socket_type = stream
        user = root
        wait = no
        redirect = 127.0.0.1 8080
}

2) create /etc/xinet.d/tomcat-https

service https
{
        disable = no
        socket_type = stream
        user = root
        wait = no
        redirect = 127.0.0.1 8443
}

3) chkconfig xinetd on

4) /etc/init.d/xinetd start

How to set the maximum memory usage for JVM?

The answer above is kind of correct, you can't gracefully control how much native memory a java process allocates. It depends on what your application is doing.

That said, depending on platform, you may be able to do use some mechanism, ulimit for example, to limit the size of a java or any other process.

Just don't expect it to fail gracefully if it hits that limit. Native memory allocation failures are much harder to handle than allocation failures on the java heap. There's a fairly good chance the application will crash but depending on how critical it is to the system to keep the process size down that might still suit you.

Asynchronously wait for Task<T> to complete with timeout

Definitely don't do this, but it is an option if ... I can't think of a valid reason.

((CancellationTokenSource)cancellationToken.GetType().GetField("m_source",
    System.Reflection.BindingFlags.NonPublic |
    System.Reflection.BindingFlags.Instance
).GetValue(cancellationToken)).Cancel();

How to beautify JSON in Python?

Use the python tool library

Command line: python -mjson.tool

In code: http://docs.python.org/library/json.html

Insert HTML from CSS

No you cannot. The only thing you can do is to insert content. Like so:

p:after {
    content: "yo";
}

Android-Studio upgraded from 0.1.9 to 0.2.0 causing gradle build errors now

Gradle should be updated already, you just need to let your previous projects know gradle has been updated.

Source

Edit your build.gradle file to show this:

dependencies {
classpath 'com.android.tools.build:gradle:0.5.+'
}

This should only be required for projects created with the previous version of Android Studio. New projects you create will have that by default.

How can I replace newlines using PowerShell?

You can use "\\r\\n" also for the new line in powershell. I have used this in servicenow tool.

In my case "\r\n" s not working so i tried "\\r\\n" as "\" this symbol work as escape character in powershell.

Random state (Pseudo-random number) in Scikit learn

random_state number splits the test and training datasets with a random manner. In addition to what is explained here, it is important to remember that random_state value can have significant effect on the quality of your model (by quality I essentially mean accuracy to predict). For instance, If you take a certain dataset and train a regression model with it, without specifying the random_state value, there is the potential that everytime, you will get a different accuracy result for your trained model on the test data. So it is important to find the best random_state value to provide you with the most accurate model. And then, that number will be used to reproduce your model in another occasion such as another research experiment. To do so, it is possible to split and train the model in a for-loop by assigning random numbers to random_state parameter:

for j in range(1000):

            X_train, X_test, y_train, y_test = train_test_split(X, y , random_state =j,     test_size=0.35)
            lr = LarsCV().fit(X_train, y_train)

            tr_score.append(lr.score(X_train, y_train))
            ts_score.append(lr.score(X_test, y_test))

        J = ts_score.index(np.max(ts_score))

        X_train, X_test, y_train, y_test = train_test_split(X, y , random_state =J, test_size=0.35)
        M = LarsCV().fit(X_train, y_train)
        y_pred = M.predict(X_test)`

How to check if all elements of a list matches a condition?

this way is a bit more flexible than using all():

my_list = [[1, 2, 0], [1, 2, 0], [1, 2, 0]]
all_zeros = False if False in [x[2] == 0 for x in my_list] else True
any_zeros = True if True in [x[2] == 0 for x in my_list] else False

or more succinctly:

all_zeros = not False in [x[2] == 0 for x in my_list]
any_zeros = 0 in [x[2] for x in my_list]

Brew install docker does not include docker engine?

To install Docker for Mac with homebrew:

brew cask install docker

To install the command line completion:

brew install bash-completion
brew install docker-completion
brew install docker-compose-completion
brew install docker-machine-completion

Case vs If Else If: Which is more efficient?

it can do this for case statements as the values are compiler constants. An explanation in more detail is here http://sequence-points.blogspot.com/2007/10/why-is-switch-statement-faster-than-if.html

"Port 4200 is already in use" when running the ng serve command

As first step after any changes, I use ng build, then ng serve. It works without any problems.

Convert timestamp to date in Oracle SQL

Try using TRUNC and TO_DATE instead

WHERE
    TRUNC(start_ts) = TO_DATE('2016-05-13', 'YYYY-MM-DD')

Alternatively, you can use >= and < instead to avoid use of function in the start_ts column:

WHERE
   start_ts >= TO_DATE('2016-05-13', 'YYYY-MM-DD')
   AND start_ts < TO_DATE('2016-05-14', 'YYYY-MM-DD')

Can a PDF file's print dialog be opened with Javascript?

Embed code example:

<object type="application/pdf" data="example.pdf" width="100%" height="100%" id="examplePDF" name="examplePDF"><param name='src' value='example.pdf'/></object>

<script>
   examplePDF.printWithDialog();
</script>

May have to fool around with the ids/names. Using adobe reader...

Convert nullable bool? to bool

The complete way would be:

bool b1;
bool? b2 = ???;
if (b2.HasValue)
   b1 = b2.Value;

Or you can test for specific values using

bool b3 = (b2 == true); // b2 is true, not false or null

hardcoded string "row three", should use @string resource

It is not good practice to hard code strings into your layout files/ code. You should add them to a string resource file and then reference them from your layout.

  1. This allows you to update every occurrence of the same word in all
    layouts at the same time by just editing your strings.xml file.
  2. It is also extremely useful for supporting multiple languages as a separate strings.xml file can be used for each supported language
  3. the actual point of having the @string system please read over the localization documentation. It allows you to easily locate text in your app and later have it translated.
  4. Strings can be internationalized easily, allowing your application to support multiple languages with a single application package file (APK).

Benefits

  • Lets say you used same string in 10 different locations in the code. What if you decide to alter it? Instead of searching for where all it has been used in the project you just change it once and changes are reflected everywhere in the project.
  • Strings don’t clutter up your application code, leaving it clear and easy to maintain.

Understanding Linux /proc/id/maps

Please check: http://man7.org/linux/man-pages/man5/proc.5.html

address           perms offset  dev   inode       pathname
00400000-00452000 r-xp 00000000 08:02 173521      /usr/bin/dbus-daemon

The address field is the address space in the process that the mapping occupies.

The perms field is a set of permissions:

 r = read
 w = write
 x = execute
 s = shared
 p = private (copy on write)

The offset field is the offset into the file/whatever;

dev is the device (major:minor);

inode is the inode on that device.0 indicates that no inode is associated with the memoryregion, as would be the case with BSS (uninitialized data).

The pathname field will usually be the file that is backing the mapping. For ELF files, you can easily coordinate with the offset field by looking at the Offset field in the ELF program headers (readelf -l).

Under Linux 2.0, there is no field giving pathname.

React: trigger onChange if input value is changing by state?

The other answers talked about direct binding in render hence I want to add few points regarding that.

You are not recommended to bind the function directly in render or anywhere else in the component except in constructor. Because for every function binding a new function/object will be created in webpack bundle js file hence the bundle size will grow. Your component will re-render for many reasons like when you do setState, new props received, when you do this.forceUpdate() etc. So if you directly bind your function in render it will always create a new function. Instead do function binding always in constructor and call the reference wherever required. In this way it creates new function only once because constructor gets called only once per component.

How you should do is something like below

constructor(props){
  super(props);
  this.state = {
    value: 'random text'
  }
  this.handleChange = this.handleChange.bind(this);
}

handleChange (e) {
  console.log('handle change called');
  this.setState({value: e.target.value});
}

<input value={this.state.value} onChange={this.handleChange}/>

You can also use arrow functions but arrow functions also does create new function every time the component re-renders in certain cases. You should know about when to use arrow function and when are not suppose to. For detailed explation about when to use arrow functions check the accepted answer here

How do CSS triangles work?

If you want to apply border to the triangle read this: Create a triangle with CSS?

Almost all the answers focus on the triangle built using border so I am going to elaborate the linear-gradient method (as started in the answer of @lima_fil).

Using a degree value like 45° will force us to respect a specific ratio of height/width in order to obtain the triangle we want and this won't be responsive:

_x000D_
_x000D_
.tri {_x000D_
  width:100px;_x000D_
  height:100px;_x000D_
  background:linear-gradient(45deg, transparent 49.5%,red 50%);_x000D_
  _x000D_
  /*To illustrate*/_x000D_
  border:1px solid;_x000D_
}
_x000D_
Good one_x000D_
<div class="tri"></div>_x000D_
bad one_x000D_
<div class="tri" style="width:150px"></div>_x000D_
bad one_x000D_
<div class="tri" style="height:30px"></div>
_x000D_
_x000D_
_x000D_

Instead of doing this we should consider predefined values of direction like to bottom, to top, etc. In this case we can obtain any kind of triangle shape while keeping it responsive.

1) Rectangle triangle

To obtain such triangle we need one linear-gradient and a diagonal direction like to bottom right, to top left, to bottom left, etc

_x000D_
_x000D_
.tri-1,.tri-2 {_x000D_
  display:inline-block;_x000D_
  width:100px;_x000D_
  height:100px;_x000D_
  background:linear-gradient(to bottom left, transparent 49.5%,red 50%);_x000D_
  border:1px solid;_x000D_
  animation:change 2s linear infinite alternate;_x000D_
}_x000D_
.tri-2 {_x000D_
  background:linear-gradient(to top right, transparent 49.5%,red 50%);_x000D_
  border:none;_x000D_
}_x000D_
_x000D_
@keyframes change {_x000D_
  from {_x000D_
    width:100px;_x000D_
    height:100px;_x000D_
  }_x000D_
  to {_x000D_
    height:50px;_x000D_
    width:180px;_x000D_
  }_x000D_
}
_x000D_
<div class="tri-1"></div>_x000D_
<div class="tri-2"></div>
_x000D_
_x000D_
_x000D_

2) isosceles triangle

For this one we will need 2 linear-gradient like above and each one will take half the width (or the height). It's like we create a mirror image of the first triangle.

_x000D_
_x000D_
.tri {_x000D_
  display:inline-block;_x000D_
  width:100px;_x000D_
  height:100px;_x000D_
  background-image:_x000D_
  linear-gradient(to bottom right, transparent 49.5%,red 50%),_x000D_
  linear-gradient(to bottom left,  transparent 49.5%,red 50%);_x000D_
  background-size:50.3% 100%; /* I use a value slightly bigger than 50% to avoid having a small gap between both gradient*/_x000D_
  background-position:left,right;_x000D_
  background-repeat:no-repeat;_x000D_
  _x000D_
  animation:change 2s linear infinite alternate;_x000D_
}_x000D_
_x000D_
_x000D_
@keyframes change {_x000D_
  from {_x000D_
    width:100px;_x000D_
    height:100px;_x000D_
  }_x000D_
  to {_x000D_
    height:50px;_x000D_
    width:180px;_x000D_
  }_x000D_
}
_x000D_
<div class="tri"></div>
_x000D_
_x000D_
_x000D_

3) equilateral triangle

This one is a bit tricky to handle as we need to keep a relation between the height and width of the gradient. We will have the same triangle as above but we will make the calculation more complex in order to transform the isosceles triangle to an equilateral one.

To make it easy, we will consider that the width of our div is known and the height is big enough to be able to draw our triangle inside (height >= width).

CSS triangle with gradient

We have our two gradient g1 and g2, the blue line is the width of the div w and each gradient will have 50% of it (w/2) and each side of the triangle sould be equal to w. The green line is the height of both gradient hg and we can easily obtain the formula below:

(w/2)² + hg² = w² ---> hg = (sqrt(3)/2) * w ---> hg = 0.866 * w

We can rely on calc() in order to do our calculation and to obtain the needed result:

_x000D_
_x000D_
.tri {_x000D_
  --w:100px;_x000D_
  width:var(--w);_x000D_
  height:100px;_x000D_
  display:inline-block;_x000D_
  background-image:_x000D_
  linear-gradient(to bottom right, transparent 49.5%,red 50%),_x000D_
  linear-gradient(to bottom left,  transparent 49.5%,red 50%);_x000D_
  background-size:calc(var(--w)/2 + 0.5px)  calc(0.866 * var(--w));_x000D_
  background-position:_x000D_
    left bottom,right bottom;_x000D_
  background-repeat:no-repeat;_x000D_
  _x000D_
}
_x000D_
<div class="tri"></div>_x000D_
<div class="tri" style="--w:80px"></div>_x000D_
<div class="tri" style="--w:50px"></div>
_x000D_
_x000D_
_x000D_

Another way is to control the height of div and keep the syntax of gradient easy:

_x000D_
_x000D_
.tri {_x000D_
  --w:100px;_x000D_
  width:var(--w);_x000D_
  height:calc(0.866 * var(--w));_x000D_
  display:inline-block;_x000D_
  background:_x000D_
   linear-gradient(to bottom right, transparent 49.8%,red 50%) left,_x000D_
   linear-gradient(to bottom left,  transparent 49.8%,red 50%) right;_x000D_
  background-size:50.2% 100%;_x000D_
  background-repeat:no-repeat;_x000D_
  _x000D_
}
_x000D_
<div class="tri"></div>_x000D_
<div class="tri" style="--w:80px"></div>_x000D_
<div class="tri" style="--w:50px"></div>
_x000D_
_x000D_
_x000D_

4) Random triangle

To obtain a random triangle, it's easy as we simply need to remove the condition of 50% of each one BUT we should keep two condition (both should have the same height and the sum of both width should be 100%).

_x000D_
_x000D_
.tri-1 {_x000D_
  width:100px;_x000D_
  height:100px;_x000D_
  display:inline-block;_x000D_
  background-image:_x000D_
  linear-gradient(to bottom right, transparent 50%,red 0),_x000D_
  linear-gradient(to bottom left, transparent 50%,red 0);_x000D_
  background-size:20% 60%,80% 60%;_x000D_
  background-position:_x000D_
    left bottom,right bottom;_x000D_
  background-repeat:no-repeat;_x000D_
  _x000D_
 _x000D_
}
_x000D_
<div class="tri-1"></div>
_x000D_
_x000D_
_x000D_

But what if we want to define a value for each side? We simply need to do calculation again!

CSS triangle with gradient

Let's define hg1 and hg2 as the height of our gradient (both are equal to the red line) then wg1 and wg2 as the width of our gradient (wg1 + wg2 = a). I will not going to detail the calculation but at then end we will have:

wg2 = (a²+c²-b²)/(2a)
wg1 = a - wg2
hg1 = hg2 = sqrt(b² - wg1²) = sqrt(c² - wg2²)

Now we have reached the limit of CSS as even with calc() we won't be able to implement this so we simply need to gather the final result manually and use them as fixed size:

_x000D_
_x000D_
.tri {_x000D_
  --wg1: 20px; _x000D_
  --wg2: 60px;_x000D_
  --hg:30px; _x000D_
  width:calc(var(--wg1) + var(--wg2));_x000D_
  height:100px;_x000D_
  display:inline-block;_x000D_
  background-image:_x000D_
  linear-gradient(to bottom right, transparent 49.5%,red 50%),_x000D_
  linear-gradient(to bottom left,  transparent 49.5%,red 50%);_x000D_
_x000D_
  background-size:var(--wg1) var(--hg),var(--wg2) var(--hg);_x000D_
  background-position:_x000D_
    left bottom,right bottom;_x000D_
  background-repeat:no-repeat;_x000D_
  _x000D_
}
_x000D_
<div class="tri" ></div>_x000D_
_x000D_
<div class="tri" style="--wg1:80px;--wg2:60px;--hg:100px;" ></div>
_x000D_
_x000D_
_x000D_

Bonus

We should not forget that we can also apply rotation and/or skew and we have more option to obtain more triangle:

_x000D_
_x000D_
.tri {_x000D_
  --wg1: 20px; _x000D_
  --wg2: 60px;_x000D_
  --hg:30px; _x000D_
  width:calc(var(--wg1) + var(--wg2) - 0.5px);_x000D_
  height:100px;_x000D_
  display:inline-block;_x000D_
  background-image:_x000D_
  linear-gradient(to bottom right, transparent 49%,red 50%),_x000D_
  linear-gradient(to bottom left,  transparent 49%,red 50%);_x000D_
_x000D_
  background-size:var(--wg1) var(--hg),var(--wg2) var(--hg);_x000D_
  background-position:_x000D_
    left bottom,right bottom;_x000D_
  background-repeat:no-repeat;_x000D_
  _x000D_
}
_x000D_
<div class="tri" ></div>_x000D_
_x000D_
<div class="tri" style="transform:skewY(25deg)"></div>_x000D_
_x000D_
<div class="tri" style="--wg1:80px;--wg2:60px;--hg:100px;" ></div>_x000D_
_x000D_
_x000D_
<div class="tri" style="--wg1:80px;--wg2:60px;--hg:100px;transform:rotate(20deg)" ></div>
_x000D_
_x000D_
_x000D_

And of course we should keep in mind the SVG solution which can be more suitable in some situation:

_x000D_
_x000D_
svg {_x000D_
 width:100px;_x000D_
 height:100px;_x000D_
}_x000D_
_x000D_
polygon {_x000D_
  fill:red;_x000D_
}
_x000D_
<svg viewBox="0 0 100 100"><polygon points="0,100 0,0 100,100" /></svg>_x000D_
<svg viewBox="0 0 100 100"><polygon points="0,100 50,0 100,100" /></svg>_x000D_
<svg viewBox="0 0 100 100"><polygon points="0,100 50,23 100,100" /></svg>_x000D_
<svg viewBox="0 0 100 100"><polygon points="20,60 50,43 80,100" /></svg>
_x000D_
_x000D_
_x000D_

Correct way to delete cookies server-side

At the time of my writing this answer, the accepted answer to this question appears to state that browsers are not required to delete a cookie when receiving a replacement cookie whose Expires value is in the past. That claim is false. Setting Expires to be in the past is the standard, spec-compliant way of deleting a cookie, and user agents are required by spec to respect it.

Using an Expires attribute in the past to delete a cookie is correct and is the way to remove cookies dictated by the spec. The examples section of RFC 6255 states:

Finally, to remove a cookie, the server returns a Set-Cookie header with an expiration date in the past. The server will be successful in removing the cookie only if the Path and the Domain attribute in the Set-Cookie header match the values used when the cookie was created.

The User Agent Requirements section includes the following requirements, which together have the effect that a cookie must be immediately expunged if the user agent receives a new cookie with the same name whose expiry date is in the past

  1. If [when receiving a new cookie] the cookie store contains a cookie with the same name, domain, and path as the newly created cookie:

    1. ...
    2. ...
    3. Update the creation-time of the newly created cookie to match the creation-time of the old-cookie.
    4. Remove the old-cookie from the cookie store.
  2. Insert the newly created cookie into the cookie store.

A cookie is "expired" if the cookie has an expiry date in the past.

The user agent MUST evict all expired cookies from the cookie store if, at any time, an expired cookie exists in the cookie store.

Points 11-3, 11-4, and 12 above together mean that when a new cookie is received with the same name, domain, and path, the old cookie must be expunged and replaced with the new cookie. Finally, the point below about expired cookies further dictates that after that is done, the new cookie must also be immediately evicted. The spec offers no wiggle room to browsers on this point; if a browser were to offer the user the option to disable cookie expiration, as the accepted answer suggests some browsers do, then it would be in violation of the spec. (Such a feature would also have little use, and as far as I know it does not exist in any browser.)

Why, then, did the OP of this question observe this approach failing? Though I have not dusted off a copy of Internet Explorer to check its behaviour, I suspect it was because the OP's Expires value was malformed! They used this value:

expires=Thu, Jan 01 1970 00:00:00 UTC;

However, this is syntactically invalid in two ways.

The syntax section of the spec dictates that the value of the Expires attribute must be a

rfc1123-date, defined in [RFC2616], Section 3.3.1

Following the second link above, we find this given as an example of the format:

Sun, 06 Nov 1994 08:49:37 GMT

and find that the syntax definition...

  1. requires that dates be written in day month year format, not month day year format as used by the question asker.

    Specifically, it defines rfc1123-date as follows:

    rfc1123-date = wkday "," SP date1 SP time SP "GMT"
    

    and defines date1 like this:

    date1        = 2DIGIT SP month SP 4DIGIT
                 ; day month year (e.g., 02 Jun 1982)
    

and

  1. doesn't permit UTC as a timezone.

    The spec contains the following statement about what timezone offsets are acceptable in this format:

    All HTTP date/time stamps MUST be represented in Greenwich Mean Time (GMT), without exception.

    What's more if we dig deeper into the original spec of this datetime format, we find that in its initial spec in https://tools.ietf.org/html/rfc822, the Syntax section lists "UT" (meaning "universal time") as a possible value, but does not list not UTC (Coordinated Universal Time) as valid. As far as I know, using "UTC" in this date format has never been valid; it wasn't a valid value when the format was first specified in 1982, and the HTTP spec has adopted a strictly more restrictive version of the format by banning the use of all "zone" values other than "GMT".

If the question asker here had instead used an Expires attribute like this, then:

expires=Thu, 01 Jan 1970 00:00:00 GMT;

then it would presumably have worked.

How does String substring work in Swift

enter image description here

All of the following examples use

var str = "Hello, playground"

Swift 4

Strings got a pretty big overhaul in Swift 4. When you get some substring from a String now, you get a Substring type back rather than a String. Why is this? Strings are value types in Swift. That means if you use one String to make a new one, then it has to be copied over. This is good for stability (no one else is going to change it without your knowledge) but bad for efficiency.

A Substring, on the other hand, is a reference back to the original String from which it came. Here is an image from the documentation illustrating that.

No copying is needed so it is much more efficient to use. However, imagine you got a ten character Substring from a million character String. Because the Substring is referencing the String, the system would have to hold on to the entire String for as long as the Substring is around. Thus, whenever you are done manipulating your Substring, convert it to a String.

let myString = String(mySubstring)

This will copy just the substring over and the memory holding old String can be reclaimed. Substrings (as a type) are meant to be short lived.

Another big improvement in Swift 4 is that Strings are Collections (again). That means that whatever you can do to a Collection, you can do to a String (use subscripts, iterate over the characters, filter, etc).

The following examples show how to get a substring in Swift.

Getting substrings

You can get a substring from a string by using subscripts or a number of other methods (for example, prefix, suffix, split). You still need to use String.Index and not an Int index for the range, though. (See my other answer if you need help with that.)

Beginning of a string

You can use a subscript (note the Swift 4 one-sided range):

let index = str.index(str.startIndex, offsetBy: 5)
let mySubstring = str[..<index] // Hello

or prefix:

let index = str.index(str.startIndex, offsetBy: 5)
let mySubstring = str.prefix(upTo: index) // Hello

or even easier:

let mySubstring = str.prefix(5) // Hello

End of a string

Using subscripts:

let index = str.index(str.endIndex, offsetBy: -10)
let mySubstring = str[index...] // playground

or suffix:

let index = str.index(str.endIndex, offsetBy: -10)
let mySubstring = str.suffix(from: index) // playground

or even easier:

let mySubstring = str.suffix(10) // playground

Note that when using the suffix(from: index) I had to count back from the end by using -10. That is not necessary when just using suffix(x), which just takes the last x characters of a String.

Range in a string

Again we simply use subscripts here.

let start = str.index(str.startIndex, offsetBy: 7)
let end = str.index(str.endIndex, offsetBy: -6)
let range = start..<end

let mySubstring = str[range]  // play

Converting Substring to String

Don't forget, when you are ready to save your substring, you should convert it to a String so that the old string's memory can be cleaned up.

let myString = String(mySubstring)

Using an Int index extension?

I'm hesitant to use an Int based index extension after reading the article Strings in Swift 3 by Airspeed Velocity and Ole Begemann. Although in Swift 4, Strings are collections, the Swift team purposely hasn't used Int indexes. It is still String.Index. This has to do with Swift Characters being composed of varying numbers of Unicode codepoints. The actual index has to be uniquely calculated for every string.

I have to say, I hope the Swift team finds a way to abstract away String.Index in the future. But until them I am choosing to use their API. It helps me to remember that String manipulations are not just simple Int index lookups.

How to get list of all installed packages along with version in composer?

You can run composer show -i (short for --installed).

In the latest version just use composer show.

The -i options has been deprecated.

You can also use the global instalation of composer: composer global show

HttpListener Access Denied

If you use http://localhost:80/ as a prefix, you can listen to http requests with no need for Administrative privileges.

MySQL Error 1093 - Can't specify target table for update in FROM clause

try this

DELETE FROM story_category 
WHERE category_id NOT IN (
SELECT DISTINCT category.id 
FROM (SELECT * FROM STORY_CATEGORY) sc;

Passing dynamic javascript values using Url.action()

In my case it worked great just by doing the following:

The Controller:

[HttpPost]
public ActionResult DoSomething(int custNum)
{
    // Some magic code here...
}

Create the form with no action:

<form id="frmSomething" method="post">
    <div>
        <!-- Some magic html here... -->
    </div>
    <button id="btnSubmit" type="submit">Submit</button>
</form>

Set button click event to trigger submit after adding the action to the form:

var frmSomething= $("#frmSomething");
var btnSubmit= $("#btnSubmit");
var custNum = 100;

btnSubmit.click(function()
    {
        frmSomething.attr("action", "/Home/DoSomething?custNum=" + custNum);

        btnSubmit.submit();
    });

Hope this helps vatos!

HTTP Get with 204 No Content: Is that normal

I use GET/204 with a RESTful collection that is a positional array of known fixed length but with holes.

GET /items
    200: ["a", "b", null]

GET /items/0
    200: "a"

GET /items/1
    200: "b"

GET /items/2
    204:

GET /items/3
    404: Not Found

Define a struct inside a class in C++

#include<iostream>
using namespace std;

class A
{
    public:
        struct Assign
        {
            public:
                int a=10;
                float b=20.5;
            private:
                double c=30.0;
                long int d=40;
         };
         struct Assign ALT;
};

class B: public A
{
public:
    int x = 10;
private:
    float y = 20.8;
};

int main()
{
   B myobj;
   A obj;
   //cout<<myobj.a<<endl;
   //cout<<myobj.b<<endl;
   //cout<<obj.a<<endl;
   //cout<<obj.b<<endl;
   cout<<myobj.ALT.a<<endl;

    return 0;
}

    enter code here

Change x axes scale in matplotlib

Try using matplotlib.pyplot.ticklabel_format:

import matplotlib.pyplot as plt
...
plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0))

This applies scientific notation (i.e. a x 10^b) to your x-axis tickmarks

Python convert tuple to string

here is an easy way to use join.

''.join(('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e'))

How to fix the Eclipse executable launcher was unable to locate its companion shared library for windows 7?

The reason to that might be the 2 lines in eclipse.ini

--launcher.library
C:\Users\UserName\.p2\pool\plugins\org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.400.v20160518-1444

for my case the reason was admin privilages so I had to move the folder from the path specified in ini to my eclipse plugins and change path in ini to :

plugins\org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.400.v20160518-1444

Is Eclipse the best IDE for Java?

Eclipse was the first IDE to move me off of XEmacs. However, when my employer offered to buy me a Intellij IDEA license if I wanted one it only took 3 days with an evaluation copy to convince me to go for it.

It seems like so many small things are just nicer.

How to transform array to comma separated words string?

You're looking for implode()

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

Formatting a number with exactly two decimals in JavaScript

I don't know why can't I add a comment to a previous answer (maybe I'm hopelessly blind, I don't know), but I came up with a solution using @Miguel's answer:

function precise_round(num,decimals) {
   return Math.round(num*Math.pow(10, decimals)) / Math.pow(10, decimals);
}

And its two comments (from @bighostkim and @Imre):

  • Problem with precise_round(1.275,2) not returning 1.28
  • Problem with precise_round(6,2) not returning 6.00 (as he wanted).

My final solution is as follows:

function precise_round(num,decimals) {
    var sign = num >= 0 ? 1 : -1;
    return (Math.round((num*Math.pow(10,decimals)) + (sign*0.001)) / Math.pow(10,decimals)).toFixed(decimals);
}

As you can see I had to add a little bit of "correction" (it's not what it is, but since Math.round is lossy - you can check it on jsfiddle.net - this is the only way I knew how to "fix" it). It adds 0.001 to the already padded number, so it is adding a 1 three 0s to the right of the decimal value. So it should be safe to use.

After that I added .toFixed(decimal) to always output the number in the correct format (with the right amount of decimals).

So that's pretty much it. Use it well ;)

EDIT: added functionality to the "correction" of negative numbers.

Spring 3 RequestMapping: Get path value

I have a similar problem and I resolved in this way:

@RequestMapping(value = "{siteCode}/**/{fileName}.{fileExtension}")
public HttpEntity<byte[]> getResource(@PathVariable String siteCode,
        @PathVariable String fileName, @PathVariable String fileExtension,
        HttpServletRequest req, HttpServletResponse response ) throws IOException {
    String fullPath = req.getPathInfo();
    // Calling http://localhost:8080/SiteXX/images/argentine/flag.jpg
    // fullPath conentent: /SiteXX/images/argentine/flag.jpg
}

Note that req.getPathInfo() will return the complete path (with {siteCode} and {fileName}.{fileExtension}) so you will have to process conveniently.

Run a command over SSH with JSch

The gritty terminal was written to use Jsch, but with better handling and vt102 emulation. You can take a look at the code there. We use it and it works just fine.

How do I get the current location of an iframe?

I use this.

var iframe = parent.document.getElementById("theiframe");
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;

var currentFrame = innerDoc.location.href;

kubectl apply vs kubectl create?

Those are two different approaches:

Imperative Management

kubectl create is what we call Imperative Management. On this approach you tell the Kubernetes API what you want to create, replace or delete, not how you want your K8s cluster world to look like.

Declarative Management

kubectl apply is part of the Declarative Management approach, where changes that you may have applied to a live object (i.e. through scale) are "maintained" even if you apply other changes to the object.

You can read more about imperative and declarative management in the Kubernetes Object Management documentation.

Getting list of pixel values from PIL

If you have numpy installed you can try:

data = numpy.asarray(im)

(I say "try" here, because it's unclear why getdata() isn't working for you, and I don't know whether asarray uses getdata, but it's worth a test.)

How to install a specific version of package using Composer?

In your composer.json, you can put:

{
    "require": {
        "vendor/package": "version"
    }
}

then run composer install or composer update from the directory containing composer.json. Sometimes, for me, composer is hinky, so I'll start with composer clear-cache; rm -rf vendor; rm composer.lock before composer install to make sure it's getting fresh stuff.


Of course, as the other answers point out you can run the following from the terminal:

composer require vendor/package:version

And on versioning:
- Composer's official versions article
- Ecosia Search

Run Button is Disabled in Android Studio

for flutter project, if the run button is disabled then you have to

tools>> flutter>> flutter packages get >>enter your flutter sdk path >>finish

This should solve your problem...

Highlight the difference between two strings in PHP

I came across this PHP diff class by Chris Boulton based on Python difflib which could be a good solution:

PHP Diff Lib

How to create a laravel hashed password

The Laravel Hash facade provides secure Bcrypt hashing for storing user passwords.

Basic usage required two things:

First include the Facade in your file

use Illuminate\Support\Facades\Hash;

and use Make Method to generate password.

$hashedPassword = Hash::make($request->newPassword);

and when you want to match the Hashed string you can use the below code:

Hash::check($request->newPasswordAtLogin, $hashedPassword)

You can learn more with the Laravel document link below for Hashing: https://laravel.com/docs/5.5/hashing

Export and Import all MySQL databases at one time

Be careful when exporting from and importing to different MySQL versions as the mysql tables may have different columns. Grant privileges may fail to work if you're out of luck. I created this script (mysql_export_grants.sql ) to dump the grants for importing into the new database, just in case:

#!/bin/sh
stty -echo
printf 'Password: ' >&2
read PASSWORD
stty echo
printf "\n"
if [ -z "$PASSWORD" ]; then
        echo 'No password given!'
        exit 1
fi
MYSQL_CONN="-uroot -p$PASSWORD"
mysql ${MYSQL_CONN} --skip-column-names -A -e"SELECT CONCAT('SHOW GRANTS FOR ''',user,'''@''',host,''';') FROM mysql.user WHERE user<>''" | mysql ${MYSQL_CONN} --skip-column-names -A | sed 's/$/;/g'

Cross-browser bookmark/add to favorites JavaScript

function bookmark(title, url) {
  if (window.sidebar) { 
    // Firefox
    window.sidebar.addPanel(title, url, '');
  } 
  else if (window.opera && window.print) 
  { 
    // Opera
    var elem = document.createElement('a');
    elem.setAttribute('href', url);
    elem.setAttribute('title', title);
    elem.setAttribute('rel', 'sidebar');
    elem.click(); //this.title=document.title;
  } 
  else if (document.all) 
  { 
    // ie
    window.external.AddFavorite(url, title);
  }
}

I used this & works great in IE, FF, Netscape. Chrome, Opera and safari do not support it!

Remove Item from ArrayList

Try it this way,

ArrayList<String> List_Of_Array = new ArrayList<String>();
List_Of_Array.add("A");
List_Of_Array.add("B");
List_Of_Array.add("C");
List_Of_Array.add("D");
List_Of_Array.add("E");
List_Of_Array.add("F");
List_Of_Array.add("G");
List_Of_Array.add("H");

int i[] = {5,3,1};

for (int j = 0; j < i.length; j++) {
    List_Of_Array.remove(i[j]);
}

Check if an array item is set in JS

The most effective way:

if (array.indexOf(element) > -1) {
   alert('Bingooo')
}

W3Schools

How to load GIF image in Swift?

it would be great if somebody told to put gif into any folder instead of assets folder

Angular2 RC5: Can't bind to 'Property X' since it isn't a known property of 'Child Component'

If you use the Angular CLI to create your components, let's say CarComponent, it attaches app to the selector name (i.e app-car) and this throws the above error when you reference the component in the parent view. Therefore you either have to change the selector name in the parent view to let's say <app-car></app-car> or change the selector in the CarComponent to selector: 'car'

What's the difference between the atomic and nonatomic attributes?

After reading so many articles, Stack Overflow posts and making demo applications to check variable property attributes, I decided to put all the attributes information together:

  1. atomic // Default
  2. nonatomic
  3. strong = retain // Default
  4. weak = unsafe_unretained
  5. retain
  6. assign // Default
  7. unsafe_unretained
  8. copy
  9. readonly
  10. readwrite // Default

In the article Variable property attributes or modifiers in iOS you can find all the above-mentioned attributes, and that will definitely help you.

  1. atomic

    • atomic means only one thread access the variable (static type).
    • atomic is thread safe.
    • But it is slow in performance
    • atomic is the default behavior
    • Atomic accessors in a non garbage collected environment (i.e. when using retain/release/autorelease) will use a lock to ensure that another thread doesn't interfere with the correct setting/getting of the value.
    • It is not actually a keyword.

    Example:

        @property (retain) NSString *name;
    
        @synthesize name;
    
  2. nonatomic

    • nonatomic means multiple thread access the variable (dynamic type).
    • nonatomic is thread-unsafe.
    • But it is fast in performance
    • nonatomic is NOT default behavior. We need to add the nonatomic keyword in the property attribute.
    • It may result in unexpected behavior, when two different process (threads) access the same variable at the same time.

    Example:

        @property (nonatomic, retain) NSString *name;
    
        @synthesize name;
    

How to sort a list of strings numerically?

The most recent solution is right. You are reading solutions as a string, in which case the order is 1, then 100, then 104 followed by 2 then 21, then 2001001010, 3 and so forth.

You have to CAST your input as an int instead:

sorted strings:

stringList = (1, 10, 2, 21, 3)

sorted ints:

intList = (1, 2, 3, 10, 21)

To cast, just put the stringList inside int ( blahblah ).

Again:

stringList = (1, 10, 2, 21, 3)

newList = int (stringList)

print newList

=> returns (1, 2, 3, 10, 21) 

Configure Log4net to write to multiple files

I wanted to log all messages to root logger, and to have a separate log with errors, here is how it can be done:

<log4net>
    <appender name="FileAppender" type="log4net.Appender.FileAppender">
        <file value="allMessages.log" />
        <appendToFile value="true" />
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date  %-5level %logger  - %message%newline" />
        </layout>
    </appender>

    <appender name="ErrorsFileAppender" type="log4net.Appender.FileAppender">
        <file value="errorsLog.log" />
        <appendToFile value="true" />
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date  %-5level %logger  - %message%newline" />
        </layout>
        <filter type="log4net.Filter.LevelRangeFilter">
            <levelMin value="ERROR" />
            <levelMax value="FATAL" />
        </filter>
    </appender>

    <root>
        <level value="ALL" />
        <appender-ref ref="FileAppender" />
        <appender-ref ref="ErrorsFileAppender" />
    </root>
</log4net>

Notice the use of filter element.

PHP max_input_vars

Just to complement. On a shared server using mod_suphp I was having the same issue.

Declaring 4 max_input_vars (suhosin included), didn't solved it, it just kept truncating on 1000 vars (default), and declaring "php_value max_input_vars 6000" on .htaccess threw error 500.

What solved it was to add the following on .htaccess, which applies the php.ini file recursively to that path

suPHP_ConfigPath /home/myuser/public_html

Check if a file exists with wildcard in shell script

Update: For bash scripts, the most direct and performant approach is:

if compgen -G "${PROJECT_DIR}/*.png" > /dev/null; then
    echo "pattern exists!"
fi

This will work very speedily even in directories with millions of files and does not involve a new subshell.

Source


The simplest should be to rely on ls return value (it returns non-zero when the files do not exist):

if ls /path/to/your/files* 1> /dev/null 2>&1; then
    echo "files do exist"
else
    echo "files do not exist"
fi

I redirected the ls output to make it completely silent.


EDIT: Since this answer has got a bit of attention (and very useful critic remarks as comments), here is an optimization that also relies on glob expansion, but avoids the use of ls:

for f in /path/to/your/files*; do

    ## Check if the glob gets expanded to existing files.
    ## If not, f here will be exactly the pattern above
    ## and the exists test will evaluate to false.
    [ -e "$f" ] && echo "files do exist" || echo "files do not exist"

    ## This is all we needed to know, so we can break after the first iteration
    break
done

This is very similar to @grok12's answer, but it avoids the unnecessary iteration through the whole list.

How to write some data to excel file(.xlsx)

It is possible to write to an excel file without opening it using the Microsoft.Jet.OLEDB.4.0 and OleDb. Using OleDb, it behaves as if you were writing to a table using sql.

Here is the code I used to create and write to an new excel file. No extra references are needed

var connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\SomePath\ExcelWorkBook.xls;Extended Properties=Excel 8.0";
using (var excelConnection = new OleDbConnection(connectionString))
{
    // The excel file does not need to exist, opening the connection will create the
    // excel file for you
    if (excelConnection.State != ConnectionState.Open) { excelConnection.Open(); }

    // data is an object so it works with DBNull.Value
    object propertyOneValue = "cool!";
    object propertyTwoValue = "testing";

    var sqlText = "CREATE TABLE YourTableNameHere ([PropertyOne] VARCHAR(100), [PropertyTwo] INT)";

    // Executing this command will create the worksheet inside of the workbook
    // the table name will be the new worksheet name
    using (var command = new OleDbCommand(sqlText, excelConnection)) { command.ExecuteNonQuery(); }

    // Add (insert) data to the worksheet
    var commandText = $"Insert Into YourTableNameHere ([PropertyOne], [PropertyTwo]) Values (@PropertyOne, @PropertyTwo)";

    using (var command = new OleDbCommand(commandText, excelConnection))
    {
        // We need to allow for nulls just like we would with
        // sql, if your data is null a DBNull.Value should be used
        // instead of null 
        command.Parameters.AddWithValue("@PropertyOne", propertyOneValue ?? DBNull.Value);
        command.Parameters.AddWithValue("@PropertyTwo", propertyTwoValue ?? DBNull.Value);

        command.ExecuteNonQuery();
    }
}