Programs & Examples On #Model inheritance

Angular: date filter adds timezone, how to output UTC?

Since version 1.3.0 AngularJS introduced extra filter parameter timezone, like following:

{{ date_expression | date : format : timezone}}

But in versions 1.3.x only supported timezone is UTC, which can be used as following:

{{ someDate | date: 'MMM d, y H:mm:ss' : 'UTC' }}

Since version 1.4.0-rc.0 AngularJS supports other timezones too. I was not testing all possible timezones, but here's for example how you can get date in Japan Standard Time (JSP, GMT +9):

{{ clock | date: 'MMM d, y H:mm:ss' : '+0900' }}

Here you can find documentation of AngularJS date filters.

NOTE: this is working only with Angular 1.x

Here's working example

Enabling SSL with XAMPP

For XAMPP, do the following steps:

  1. G:\xampp\apache\conf\extra\httpd-ssl.conf"

  2. Search 'DocumentRoot' text.

  3. Change DocumentRoot DocumentRoot "G:/xampp/htdocs" to DocumentRoot "G:/xampp/htdocs/project name".

How to make <label> and <input> appear on the same line on an HTML form?

Wrap the label and the input within a bootstraps div

<div class ="row">
  <div class="col-md-4">Name:</div>
  <div class="col-md-8"><input type="text"></div>
</div>

javascript date to string

Relying on JQuery Datepicker, but it could be done easily:

var mydate = new Date();
$.datepicker.formatDate('yy-mm-dd', mydate);

Is Laravel really this slow?

From my Hello World contest, Which one is Laravel? I think you can guess. I used docker container for the test and here is the results

To make http-response "Hello World":

  • Golang with log handler stdout : 6000 rps
  • SpringBoot with Log Handler stdout: 3600 rps
  • Laravel 5 with off log :230 rps

How to make the corners of a button round?

if you are using vector drawables, then you simply need to specify a <corners> element in your drawable definition. I have covered this in a blog post.

If you are using bitmap / 9-patch drawables then you'll need to create the corners with transparency in the bitmap image.

What is the difference between buffer and cache memory in Linux?

Buffer is an area of memory used to temporarily store data while it's being moved from one place to another.

Cache is a temporary storage area used to store frequently accessed data for rapid access. Once the data is stored in the cache, future use can be done by accessing the cached copy rather than re-fetching the original data, so that the average access time is shorter.

Note: buffer and cache can be allocated on disk as well

Getting file names without extensions

using System;

using System.IO;

public class GetwithoutExtension
{

    public static void Main()
    {
        //D:Dir dhould exists in ur system
        DirectoryInfo dir1 = new DirectoryInfo(@"D:Dir");
        FileInfo [] files = dir1.GetFiles("*xls", SearchOption.AllDirectories);
        foreach (FileInfo f in files)
        {
            string filename = f.Name.ToString();
            filename= filename.Replace(".xls", "");
            Console.WriteLine(filename);
        }
        Console.ReadKey();

    }

}

Why do you need to invoke an anonymous function on the same line?

This answer is not strictly related to the question, but you might be interested to find out that this kind of syntax feature is not particular to functions. For example, we can always do something like this:

alert(
    {foo: "I am foo", bar: "I am bar"}.foo
); // alerts "I am foo"

Related to functions. As they are objects, which inherit from Function.prototype, we can do things like:

Function.prototype.foo = function () {
    return function () {
        alert("foo");
    };
};

var bar = (function () {}).foo();

bar(); // alerts foo

And you know, we don't even have to surround functions with parenthesis in order to execute them. Anyway, as long as we try to assign the result to a variable.

var x = function () {} (); // this function is executed but does nothing

function () {} (); // syntax error

One other thing you may do with functions, as soon as you declare them, is to invoke the new operator over them and obtain an object. The following are equivalent:

var obj = new function () {
    this.foo = "bar";
};

var obj = {
    foo : "bar"
};

Transaction marked as rollback only: How do I find the cause

disable the transactionmanager in your Bean.xml

<tx:annotation-driven proxy-target-class="true" transaction-manager="transactionManager"/>
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

comment out these lines, and you'll see the exception causing the rollback ;)

How to re-render flatlist?

after lots of searching and looking for real answer finally i got the answer which i think it is the best :

       <FlatList
      data={this.state.data}
      renderItem={this.renderItem}
      ListHeaderComponent={this.renderHeader}
      ListFooterComponent={this.renderFooter}
      ItemSeparatorComponent={this.renderSeparator}
      refreshing={this.state.refreshing}
      onRefresh={this.handleRefresh}
      onEndReached={this.handleLoadMore}
      onEndReachedThreshold={1}
      extraData={this.state.data}
      removeClippedSubviews={true}
      **keyExtractor={ (item, index) => index }**
              />
    .....

my main problem was (KeyExtractor) i was not using it like this . not working : keyExtractor={ (item) => item.ID} after i changed to this it worked like charm i hope this helps someone.

How to catch integer(0)?

That is R's way of printing a zero length vector (an integer one), so you could test for a being of length 0:

R> length(a)
[1] 0

It might be worth rethinking the strategy you are using to identify which elements you want, but without further specific details it is difficult to suggest an alternative strategy.

How do I do top 1 in Oracle?

To select the first row from a table and to select one row from a table are two different tasks and need a different query. There are many possible ways to do so. Four of them are:

First

select  max(Fname) from MyTbl;

Second

select  min(Fname) from MyTbl;

Third

select  Fname from MyTbl  where rownum = 1;

Fourth

select  max(Fname) from MyTbl where rowid=(select  max(rowid) from MyTbl)

how to set start value as "0" in chartjs?

If you need use it as a default configuration, just place min: 0 inside the node defaults.scale.ticks, as follows:

defaults: {
  global: {...},
  scale: {
    ...
    ticks: { min: 0 },
  }
},

Reference: https://www.chartjs.org/docs/latest/axes/

How can I set the request header for curl?

To pass multiple headers in a curl request you simply add additional -H or --header to your curl command.

Example

//Simplified
$ curl -v -H 'header1:val' -H 'header2:val' URL

//Explanatory
$ curl -v -H 'Connection: keep-alive' -H 'Content-Type: application/json'  https://www.example.com

Going Further

For standard HTTP header fields such as User-Agent, Cookie, Host, there is actually another way to setting them. The curl command offers designated options for setting these header fields:

  • -A (or --user-agent): set "User-Agent" field.
  • -b (or --cookie): set "Cookie" field.
  • -e (or --referer): set "Referer" field.
  • -H (or --header): set "Header" field

For example, the following two commands are equivalent. Both of them change "User-Agent" string in the HTTP header.

    $ curl -v -H "Content-Type: application/json" -H "User-Agent: UserAgentString" https://www.example.com
    $ curl -v -H "Content-Type: application/json" -A "UserAgentString" https://www.example.com

Replace characters from a column of a data frame R

You can use the stringr library:

library('stringr')

a <- runif(10)
b <- letters[1:10]
c <- c(rep('A-B', 4), rep('A_B', 6))
data <- data.frame(a, b, c)

data

#             a b   c
# 1  0.19426707 a A-B
# 2  0.12902673 b A-B
# 3  0.78324955 c A-B
# 4  0.06469028 d A-B
# 5  0.34752264 e A_C
# 6  0.55313288 f A_C
# 7  0.31264280 g A_C
# 8  0.33759921 h A_C
# 9  0.72322599 i A_C
# 10 0.25223075 j A_C

data$c <- str_replace_all(data$c, '_', '-')

data

#             a b   c
# 1  0.19426707 a A-B
# 2  0.12902673 b A-B
# 3  0.78324955 c A-B
# 4  0.06469028 d A-B
# 5  0.34752264 e A-C
# 6  0.55313288 f A-C
# 7  0.31264280 g A-C
# 8  0.33759921 h A-C
# 9  0.72322599 i A-C
# 10 0.25223075 j A-C

Note that this does change factored variables into character.

How to convert Set to Array?

The code below creates a set from an array and then, using the ... operator.

var arr=[1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9,];
var set=new Set(arr);
let setarr=[...set];
console.log(setarr);

QComboBox - set selected item based on the item's data

If you know the text in the combo box that you want to select, just use the setCurrentText() method to select that item.

ui->comboBox->setCurrentText("choice 2");

From the Qt 5.7 documentation

The setter setCurrentText() simply calls setEditText() if the combo box is editable. Otherwise, if there is a matching text in the list, currentIndex is set to the corresponding index.

So as long as the combo box is not editable, the text specified in the function call will be selected in the combo box.

Reference: http://doc.qt.io/qt-5/qcombobox.html#currentText-prop

How do I disable a Pylint warning?

As per Pylint documentation, the easiest is to use this chart:

  • C convention-related checks
  • R refactoring-related checks
  • W various warnings
  • E errors, for probable bugs in the code
  • F fatal, if an error occurred which prevented Pylint from doing further processing.

So one can use:

pylint -j 0 --disable=I,E,R,W,C,F YOUR_FILES_LOC

Basic CSS - how to overlay a DIV with semi-transparent DIV on top

.foo {
   position : relative;
}
.foo .wrapper {
    background-image : url('semi-trans.png');
    z-index : 10;
    position : absolute;
    top : 0;
    left : 0;
}

<div class="foo">
   <img src="example.png" />
   <div class="wrapper">&nbsp;</div>
</div>

List View Filter Android

In case anyone are still interested in this subject, I find that the best approach for filtering lists is to create a generic Filter class and use it with some base reflection/generics techniques contained in the Java old school SDK package. Here's what I did:

public class GenericListFilter<T> extends Filter {

    /**
     * Copycat constructor
     * @param list  the original list to be used
     */
    public GenericListFilter (List<T> list, String reflectMethodName, ArrayAdapter<T> adapter) {
        super ();

        mInternalList = new ArrayList<>(list);
        mAdapterUsed  = adapter;

        try {
            ParameterizedType stringListType = (ParameterizedType)
                    getClass().getField("mInternalList").getGenericType();
            mCompairMethod =
                    stringListType.getActualTypeArguments()[0].getClass().getMethod(reflectMethodName);
        }
        catch (Exception ex) {
            Log.w("GenericListFilter", ex.getMessage(), ex);

            try {
                if (mInternalList.size() > 0) {
                    T type = mInternalList.get(0);
                    mCompairMethod = type.getClass().getMethod(reflectMethodName);
                }
            }
            catch (Exception e) {
                Log.e("GenericListFilter", e.getMessage(), e);
            }

        }
    }

    /**
     * Let's filter the data with the given constraint
     * @param constraint
     * @return
     */
    @Override protected FilterResults performFiltering(CharSequence constraint) {
        FilterResults results = new FilterResults();
        List<T> filteredContents = new ArrayList<>();

        if ( constraint.length() > 0 ) {
            try {
                for (T obj : mInternalList) {
                    String result = (String) mCompairMethod.invoke(obj);
                    if (result.toLowerCase().startsWith(constraint.toString().toLowerCase())) {
                        filteredContents.add(obj);
                    }
                }
            }
            catch (Exception ex) {
                Log.e("GenericListFilter", ex.getMessage(), ex);
            }
        }
        else {
            filteredContents.addAll(mInternalList);
        }

        results.values = filteredContents;
        results.count  = filteredContents.size();
        return results;
    }

    /**
     * Publish the filtering adapter list
     * @param constraint
     * @param results
     */
    @Override protected void publishResults(CharSequence constraint, FilterResults results) {
        mAdapterUsed.clear();
        mAdapterUsed.addAll((List<T>) results.values);

        if ( results.count == 0 ) {
            mAdapterUsed.notifyDataSetInvalidated();
        }
        else {
            mAdapterUsed.notifyDataSetChanged();
        }
    }

    // class properties
    private ArrayAdapter<T> mAdapterUsed;
    private List<T> mInternalList;
    private Method  mCompairMethod;
}

And afterwards, the only thing you need to do is to create the filter as a member class (possibly within the View's "onCreate") passing your adapter reference, your list, and the method to be called for filtering:

this.mFilter = new GenericFilter<MyObjectBean> (list, "getName", adapter);

The only thing missing now, is to override the "getFilter" method in the adapter class:

@Override public Filter getFilter () {
     return MyViewClass.this.mFilter;
}

All done! You should successfully filter your list - Of course, you should also implement your filter algorithm the best way that describes your need, the code bellow is just an example.. Hope it helped, take care.

"Comparison method violates its general contract!"

In my case, it was an infinite sort. That is, at first the line moved up according to the condition, and then the same line moved down to the same place. I added one more condition at the end that unambiguously established the order of the lines.

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

In addition to the excellent answers, I would like to emphasize here when to use res.end() and when to use res.send() this was why I originally landed here and I didn't found a solution.

The answer is really simple

res.end() is used to quickly end the response without sending any data.

An example for this would be starting a process on a server

app.get(/start-service, (req, res) => {
   // Some logic here
   exec('./application'); // dummy code
   res.end();
});

If you would like to send data in your response then you should use res.send() instead

app.get(/start-service, (req, res) => {
   res.send('{"age":22}');
});

Here you can read more

Get local href value from anchor (a) tag

document.getElementById("aaa").href; //for example: http://example.com/sec/IF00.html

How to "EXPIRE" the "HSET" child key in redis?

If your use-case is that you're caching values in Redis and are tolerant of stale values but would like to refresh them occasionally so that they don't get too stale, a hacky workaround is to just include a timestamp in the field value and handle expirations in whatever place you're accessing the value.

This allows you to keep using Redis hashes normally without needing to worry about any complications that might arise from the other approaches. The only cost is a bit of extra logic and parsing on the client end. Not a perfect solution, but it's what I typically do as I haven't needed TTL for any other reason and I'm usually needing to do extra parsing on the cached value anyways.

So basically it'll be something like this:

In Redis:

hash_name
- field_1: "2021-01-15;123"
- field_2: "2021-01-20;125"
- field_2: "2021-02-01;127"

Your (pseudo)code:

val = redis.hget(hash_name, field_1)
timestamp = val.substring(0, val.index_of(";"))

if now() > timestamp:
  new_val = get_updated_value()
  new_timestamp = now() + EXPIRY_LENGTH
  redis.hset(hash_name, field_1, new_timestamp + ";" + new_val)
  val = new_val
else:
  val = val.substring(val.index_of(";"))

// proceed to use val

The biggest caveat imo is that you don't ever remove fields so the hash can grow quite large. Not sure there's an elegant solution for that - I usually just delete the hash every once in a while if it feels too big. Maybe you could keep track of everything you've stored somewhere and remove them periodically (though at that point, you might as well just be using that mechanism to expire the fields manually...).

X-Frame-Options Allow-From multiple domains

The RFC for the HTTP Header Field X-Frame-Options states that the "ALLOW-FROM" field in the X-Frame-Options header value can only contain one domain. Multiple domains are not allowed.

The RFC suggests a work around for this problem. The solution is to specify the domain name as a url parameter in the iframe src url. The server that hosts the iframe src url can then check the domain name given in the url parameters. If the domain name matches a list of valid domain names, then the server can send the X-Frame-Options header with the value: "ALLOW-FROM domain-name", where domain name is the name of the domain that is trying to embed the remote content. If the domain name is not given or is not valid, then the X-Frame-Options header can be sent with the value: "deny".

String concatenation with Groovy

Reproducing tim_yates answer on current hardware and adding leftShift() and concat() method to check the finding:

  'String leftShift' {
    foo << bar << baz
  }
  'String concat' {
    foo.concat(bar)
       .concat(baz)
       .toString()
  }

The outcome shows concat() to be the faster solution for a pure String, but if you can handle GString somewhere else, GString template is still ahead, while honorable mention should go to leftShift() (bitwise operator) and StringBuffer() with initial allocation:

Environment
===========
* Groovy: 2.4.8
* JVM: OpenJDK 64-Bit Server VM (25.191-b12, Oracle Corporation)
    * JRE: 1.8.0_191
    * Total Memory: 238 MB
    * Maximum Memory: 3504 MB
* OS: Linux (4.19.13-300.fc29.x86_64, amd64)

Options
=======
* Warm Up: Auto (- 60 sec)
* CPU Time Measurement: On

                                    user  system  cpu  real

String adder                         453       7  460   469
String leftShift                     287       2  289   295
String concat                        169       1  170   173
GString template                      24       0   24    24
Readable GString template             32       0   32    32
GString template toString            400       0  400   406
Readable GString template toString   412       0  412   419
StringBuilder                        325       3  328   334
StringBuffer                         390       1  391   398
StringBuffer with Allocation         259       1  260   265

Access the css ":after" selector with jQuery

You can add style for :after a like html code.
For example:

var value = 22;
body.append('<style>.wrapper:after{border-top-width: ' + value + 'px;}</style>');

How to downgrade to older version of Gradle

got it resolved:

uninstall the entire android studio

uninstalling android with the following commands

rm -Rf /Applications/Android\ Studio.app  
rm -Rf ~/Library/Preferences/AndroidStudio*  
rm -Rf ~/Library/Preferences/com.google.android.*  
rm -Rf ~/Library/Preferences/com.android.*  
rm -Rf ~/Library/Application\ Support/AndroidStudio*  
rm -Rf ~/Library/Logs/AndroidStudio*  
rm -Rf ~/Library/Caches/AndroidStudio*  
rm -Rf ~/.AndroidStudio*  
rm -Rf ~/.gradle  
rm -Rf ~/.android  
rm -Rf ~/Library/Android*  
rm -Rf /usr/local/var/lib/android-sdk/  
rm -Rf /Users/<username>/.tooling/gradle

Remove your project and clone it again and then goto Gradle Scripts and open gradle-wrapper.properties and change the below url which ever version you need

distributionUrl=https\://services.gradle.org/distributions/gradle-4.2-all.zip

Total Number of Row Resultset getRow Method

The best way to get number of rows from resultset is using count function query for database access and then rs.getInt(1) method to get number of rows. from my code look it:

    String query = "SELECT COUNT() FROM table";
ResultSet rs = new DatabaseConnection().selectData(query);
rs.getInt(1);

this will return int value number of rows fetched from database. Here DatabaseConnection().selectData() is my code for accessing database. I was also stuck here but then solved...

Change the color of a bullet in a html list?

<ul>
<li style="color:#ddd;"><span style="color:#000;">List Item</span></li>
</ul>

How to save a data.frame in R?

If you are only saving a single object (your data frame), you could also use saveRDS.
To save:

saveRDS(foo, file="data.Rda")

Then read it with:

bar <- readRDS(file="data.Rda")

The difference between saveRDS and save is that in the former only one object can be saved and the name of the object is not forced to be the same after you load it.

<modules runAllManagedModulesForAllRequests="true" /> Meaning

Modules Preconditions:

The IIS core engine uses preconditions to determine when to enable a particular module. Performance reasons, for example, might determine that you only want to execute managed modules for requests that also go to a managed handler. The precondition in the following example (precondition="managedHandler") only enables the forms authentication module for requests that are also handled by a managed handler, such as requests to .aspx or .asmx files:

<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" preCondition="managedHandler" />

If you remove the attribute precondition="managedHandler", Forms Authentication also applies to content that is not served by managed handlers, such as .html, .jpg, .doc, but also for classic ASP (.asp) or PHP (.php) extensions. See "How to Take Advantage of IIS Integrated Pipeline" for an example of enabling ASP.NET modules to run for all content.

You can also use a shortcut to enable all managed (ASP.NET) modules to run for all requests in your application, regardless of the "managedHandler" precondition.

To enable all managed modules to run for all requests without configuring each module entry to remove the "managedHandler" precondition, use the runAllManagedModulesForAllRequests property in the <modules> section:

<modules runAllManagedModulesForAllRequests="true" />    

When you use this property, the "managedHandler" precondition has no effect and all managed modules run for all requests.

Copied from IIS Modules Overview: Preconditions

jQuery Call to WebService returns "No Transport" error

i solve it by using dataType='jsonp' at the place of dataType='json'

Assign one struct to another in C

Yes, you can assign one instance of a struct to another using a simple assignment statement.

  • In the case of non-pointer or non pointer containing struct members, assignment means copy.

  • In the case of pointer struct members, assignment means pointer will point to the same address of the other pointer.

Let us see this first hand:

#include <stdio.h>

struct Test{
    int foo;
    char *bar;
};

int main(){
    struct Test t1;
    struct Test t2;
    t1.foo = 1;
    t1.bar = malloc(100 * sizeof(char));
    strcpy(t1.bar, "t1 bar value");
    t2.foo = 2;
    t2.bar = malloc(100 * sizeof(char));
    strcpy(t2.bar, "t2 bar value");
    printf("t2 foo and bar before copy: %d %s\n", t2.foo, t2.bar);
    t2 = t1;// <---- ASSIGNMENT
    printf("t2 foo and bar after copy: %d %s\n", t2.foo, t2.bar);
    //The following 3 lines of code demonstrate that foo is deep copied and bar is shallow copied
    strcpy(t1.bar, "t1 bar value changed");
    t1.foo = 3;
    printf("t2 foo and bar after t1 is altered: %d %s\n", t2.foo, t2.bar);
    return 0;
}

How to create a Calendar table for 100 years in Sql

 declare @date int
 WITH CTE_DatesTable
AS
(
  SELECT CAST('20000101' as date) AS [date]
  UNION ALL
  SELECT   DATEADD(dd, 1, [date])
  FROM CTE_DatesTable
  WHERE DATEADD(dd, 1, [date]) <= '21001231'
)
SELECT [DWDateKey]=[date],[DayDate]=datepart(dd,[date]),[DayOfWeekName]=datename(dw,[date]),[WeekNumber]=DATEPART( WEEK , [date]),[MonthNumber]=DATEPART( MONTH , [date]),[MonthName]=DATENAME( MONTH , [date]),[MonthShortName]=substring(LTRIM( DATENAME(MONTH,[date])),0, 4),[Year]=DATEPART(YY,[date]),[QuarterNumber]=DATENAME(quarter, [date]),[QuarterName]=DATENAME(quarter, [date]) into DimDate   FROM CTE_DatesTable

OPTION (MAXRECURSION 0);

Encrypting & Decrypting a String in C#

You may be looking for the ProtectedData class, which encrypts data using the user's logon credentials.

Can table columns with a Foreign Key be NULL?

Another way around this would be to insert a DEFAULT element in the other table. For example, any reference to uuid=00000000-0000-0000-0000-000000000000 on the other table would indicate no action. You also need to set all the values for that id to be "neutral", e.g. 0, empty string, null in order to not affect your code logic.

How to launch an Activity from another Application in Android

// in onCreate method
String appName = "Gmail";
String packageName = "com.google.android.gm";
openApp(context, appName, packageName);

public static void openApp(Context context, String appName, String packageName) {
    if (isAppInstalled(context, packageName))
        if (isAppEnabled(context, packageName))
            context.startActivity(context.getPackageManager().getLaunchIntentForPackage(packageName));
        else Toast.makeText(context, appName + " app is not enabled.", Toast.LENGTH_SHORT).show();
    else Toast.makeText(context, appName + " app is not installed.", Toast.LENGTH_SHORT).show();
}

private static boolean isAppInstalled(Context context, String packageName) {
    PackageManager pm = context.getPackageManager();
    try {
        pm.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES);
        return true;
    } catch (PackageManager.NameNotFoundException ignored) {
    }
    return false;
}

private static boolean isAppEnabled(Context context, String packageName) {
    boolean appStatus = false;
    try {
        ApplicationInfo ai = context.getPackageManager().getApplicationInfo(packageName, 0);
        if (ai != null) {
            appStatus = ai.enabled;
        }
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    return appStatus;
}

Get current controller in view

Other way to get current Controller name in View

@ViewContext.Controller.ValueProvider.GetValue("controller").RawValue

How do I create a comma-separated list from an array in PHP?

$fruit = array('apple', 'banana', 'pear', 'grape');    
$commasaprated = implode(',' , $fruit);

ASP MVC in IIS 7 results in: HTTP Error 403.14 - Forbidden

I read through every answer here looking for something that worked before I realized that I'm using IIS 10 (on Windows 10 version 2004) and this question is about IIS 7 and almost a decade old.

With that said, run this from an elevated command prompt:

dism /online /enable-feature /all /featurename:IIS-ASPNET45

The /all will automatically enable the dependent parent features: IIS-ISAPIFilter, IIS-ISAPIExtensions, and IIS-NetFxExtensibility45.

After this, you'll notice two new (in my environment at least) application pool names mentioned .NET v4.5. ASP.NET web apps that were previously using the DefaultAppPool will just work.

enter image description here

How to convert String to long in Java?

Long.valueOf(String s) - obviously due care must be taken to protect against non-numbers if that is possible in your code.

How to make a jquery function call after "X" seconds

try This

setTimeout( function(){ 
    // call after 5 second 
  }  , 5000 );

How to stop console from closing on exit?

Add a Console.ReadKey call to your program to force it to wait for you to press a key before exiting.

Call to a member function on a non-object

I realized that I wasn't passing $objPage into page_properties(). It works fine now.

What does "commercial use" exactly mean?

"Commercial use" in cases like this is actually just a shorthand to indicate that the product is dual-licensed under both an open source and a traditional paid-for commercial license.

Any "true" open source license will not discriminate against commercial use. (See clause 6 of the Open Source Definition.) However, open source licenses like the GPL contain clauses that are incompatible with most companies' approach to commercial software (since the GPL requires that you make your source code available if you incorporate GPL'ed code into your product).

Duel-licensing is a way to accommodate this and also provides a revenue stream for the company providing the software. For users that don't mind the restrictions of the GPL and don't need support, the product is available under an open source license. For users for whom the GPL's restrictions would be incompatible with their business model, and for users that do need support, a commercial license is available.

You gave the specific example of the Screwturn wiki, which is dual-licensed under the GPL and a commercial license. Under the terms of the GPL (i.e., without getting a "commercial" license), you can do the following:

  • Use it internally as much as you want (see here)
  • Run it on your internal servers for external users / clients / customers, or run it on your internal servers for paying clients if you're an ISP / hosting provider. (If Screwturn were licensed under the AGPL instead of the GPL, that might restrict this.)
  • Distribute it to others, either free of charge or for a payment that covers the shipping, as long as you're willing to also distribute the source code
  • Incorporate it into your product, as long as you're willing to also distribute the source code, and as long as either (a) it remains a separate program that you merely aggregate with your product or (b) you release the source code to your product under an open source license compatible with the GPL

In other words, there's a lot that you can do without getting a commercial license. This is especially true for web-based software, since people can use web-based software without it being distributed to them. Screwturn's web site even acknowledges this: they state that the commercial license is for "either integrating it in a commercial application, or using it in an enterprise environment where free software is not allowed," not for any use related to commerce.

All of the preceding is merely my understanding and is not intended to be legal advice. Consult your lawyer to be certain.

How do I get HTTP Request body content in Laravel?

Inside controller inject Request object. So if you want to access request body inside controller method 'foo' do the following:

public function foo(Request $request){
    $bodyContent = $request->getContent();
}

Set transparent background of an imageview on Android

In xml

@android:color/transparent

In code

mComponentName.setBackgroundResource(android.R.color.transparent);

Storing JSON in database vs. having a new column for each key

the drawback of the approach is exactly what you mentioned :

it makes it VERY slow to find things, since each time you need to perform a text-search on it.

value per column instead matches the whole string.

Your approach (JSON based data) is fine for data you don't need to search by, and just need to display along with your normal data.

Edit: Just to clarify, the above goes for classic relational databases. NoSQL use JSON internally, and are probably a better option if that is the desired behavior.

'Found the synthetic property @panelState. Please include either "BrowserAnimationsModule" or "NoopAnimationsModule" in your application.'

Simply add .. import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

imports: [ .. BrowserAnimationsModule

],

in app.module.ts file.

make sure you have installed .. npm install @angular/animations@latest --save

jQuery call function after load

In regards to the question in your comment:

Assuming that you've previously bound your function to the click event of the radio button, add this to your $(document).ready function:

$('#[radioButtonOptionID]').click()

Without a parameter, that simulates the click event.

Retrieve a Fragment from a ViewPager

in TabLayout there are multiple tab for Fragment. you can find the fragment by Tag using the index of the fragment.

For ex. the index for Fragment1 is 0, so in findFragmentByTag() method, pass the tag for the Viewpager.after using fragmentTransaction you can add,replace the fragment.

String tag = "android:switcher:" + R.id.viewPager + ":" + 0; Fragment1 f = (Fragment1) getSupportFragmentManager().findFragmentByTag(tag);

Attach the Java Source Code

Normally, if you have installed the JDK6u14, eclipse should detect it and declare it automatically in its "installed JRE" list.

If not, you can add that JDK through "Windows/Preferences": Java > Installed JREs:

Just point to the root directory of your JDK installation: it should include the sources of the JDK (src.zip), automatically detected and attached to rt.jar by eclipse.

Add JRE VM, from pic.dhe.ibm.com/infocenter/iadthelp/v8r0/topic/org.eclipse.jdt.doc.user/tasks/images/task-add_jre_std_vm.PNG

MySQL equivalent of DECODE function in Oracle

You can use a CASE statement...however why don't you just create a table with an integer for ages between 0 and 150, a varchar for the written out age and then you can just join on that

jQuery - how to check if an element exists?

if ($("#MyId").length) { ... write some code here ...}

This from will automatically check for the presence of the element and will return true if an element exists.

How to empty a list in C#?

you can do that

var list = new List<string>();
list.Clear();

location.host vs location.hostname and cross-browser compatibility?

interactive link anatomy

As a little memo: the interactive link anatomy

--

In short (assuming a location of http://example.org:8888/foo/bar#bang):

  • hostname gives you example.org
  • host gives you example.org:8888

Jquery how to find an Object by attribute in an Array

Best, Fastest way is

function arrayLookup(array, prop, val) {
    for (var i = 0, len = array.length; i < len; i++) {
        if (array[i].hasOwnProperty(prop) && array[i][prop] === val) {
            return array[i];
        }
    }
    return null;
}

Save internal file in my own internal folder in Android

The answer of Mintir4 is fine, I would also do the following to load the file.

FileInputStream fis = myContext.openFileInput(fn);
BufferedReader r = new BufferedReader(new InputStreamReader(fis));
String s = "";

while ((s = r.readLine()) != null) {
    txt += s;
}

r.close();

python to arduino serial read & write

I found it is better to use the command Serial.readString() to replace the Serial.read() to obtain the continuous I/O for Arduino.

Automated way to convert XML files to SQL database?

There is a project on CodeProject that makes it simple to convert an XML file to SQL Script. It uses XSLT. You could probably modify it to generate the DDL too.

And See this question too : Generating SQL using XML and XSLT

How can I calculate the difference between two dates?

Swift 4
Try this and see (date range with String):

// Start & End date string
let startingAt = "01/01/2018"
let endingAt = "08/03/2018"

// Sample date formatter
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"

// start and end date object from string dates
var startDate = dateFormatter.date(from: startingAt) ?? Date()
let endDate = dateFormatter.date(from: endingAt) ?? Date()


// Actual operational logic
var dateRange: [String] = []
while startDate <= endDate {
    let stringDate = dateFormatter.string(from: startDate)
    startDate = Calendar.current.date(byAdding: .day, value: 1, to: startDate) ?? Date()
    dateRange.append(stringDate)
}

print("Resulting Array - \(dateRange)")

Swift 3

var date1 = Date(string: "2010-01-01 00:00:00 +0000")
var date2 = Date(string: "2010-02-03 00:00:00 +0000")
var secondsBetween: TimeInterval = date2.timeIntervalSince(date1)
var numberOfDays: Int = secondsBetween / 86400
print(numberOfDays)

How to dismiss a Twitter Bootstrap popover by clicking outside?

Ok this is my first attempt at actually answering something on stackoverflow so here goes nothing :P

It appears that it isn't quite clear that this functionality actually works out of the box on the latest bootstrap (well, if you're willing to compromise where the user can click. I'm not sure if you have to put 'click hover' per-se but on an iPad, click works as a toggle.

The end result is, on a desktop you can hover or click (most users will hover). On a touch device, touching the element will bring it up, and touching it again will take it down. Of course, this is a slight compromise from your original requirement but at least your code is now cleaner :)

$(".my-popover").popover({ trigger: 'click hover' });

what is Ljava.lang.String;@

I also met this problem when I've made ListView for android app:

Map<String, Object> m;

for(int i=0; i < dates.length; i++){
    m = new HashMap<String, Object>();
    m.put(ATTR_DATES, dates[i]);
    m.put(ATTR_SQUATS, squats[i]);
    m.put(ATTR_BP, benchpress[i]);
    m.put(ATTR_ROW, row[i]);
    data.add(m);
}

The problem was that I've forgotten to use the [i] index inside the loop

How to load a resource from WEB-INF directory of a web archive

Here is how it works for me with no Servlet use.

Let's say I am trying to access web.xml in project/WebContent/WEB-INF/web.xml

  1. In project property Source-tab add source folder by pointing to the parent container for WEB-INF folder (in my case WebContent )

  2. Now let's use class loader:

    InputStream inStream = class.getClass().getClassLoader().getResourceAsStream("Web-INF/web.xml")
    

Adding a regression line on a ggplot

As I just figured, in case you have a model fitted on multiple linear regression, the above mentioned solution won't work.

You have to create your line manually as a dataframe that contains predicted values for your original dataframe (in your case data).

It would look like this:

# read dataset
df = mtcars

# create multiple linear model
lm_fit <- lm(mpg ~ cyl + hp, data=df)
summary(lm_fit)

# save predictions of the model in the new data frame 
# together with variable you want to plot against
predicted_df <- data.frame(mpg_pred = predict(lm_fit, df), hp=df$hp)

# this is the predicted line of multiple linear regression
ggplot(data = df, aes(x = mpg, y = hp)) + 
  geom_point(color='blue') +
  geom_line(color='red',data = predicted_df, aes(x=mpg_pred, y=hp))

Multiple LR

# this is predicted line comparing only chosen variables
ggplot(data = df, aes(x = mpg, y = hp)) + 
  geom_point(color='blue') +
  geom_smooth(method = "lm", se = FALSE)

Single LR

What characters can be used for up/down triangle (arrow without stem) for display in HTML?

OPTION 1: UNICODE COLUMN SORT ARROWS

I found this one very handy for a single character column sorter. (Looks good upscaled).

&#x21D5; = ?

Unicode table column sort arrows

IMPORTANT NOTE (When using Unicode symbols)

Unicode support varies dependant on the symbol of choice, browser and the font family. If you find your chosen symbol does not work in some browsers then try using a different font-family. Microsoft recommends "Segoe UI Symbol" however it would be wise to include the font with your website as not many people have it on their computers.

Open this page in other browsers to see which symbols render with the default font.


Some more Unicode arrows.

You can copy them right off the page below or you can use the code.

Each row of arrows is numbered from left to right:

0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F

Simply insert the corresponding number/letter before the closing semi-colon as above.


&#x219;

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?


&#x21A;

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?


&#x21B;

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?


&#x21C;

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?


&#x21D;

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?


&#x21E;

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?


&#x21F;

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?


Additional HTML unicode symbols

A selected list of other helpful Unicode icons/symbols.

U+2302  ¦   HOUSE
U+2303  ^   UP ARROWHEAD
U+2304  ?   DOWN ARROWHEAD
U+2305  ?   PROJECTIVE
U+2306  ?   PERSPECTIVE
U+2307  ?   WAVY LINE
U+2315  ?   TELEPHONE RECORDER
U+2316  ?   POSITION INDICATOR
U+2317  ?   VIEWDATA SQUARE
U+2318  ?   PLACE OF INTEREST SIGN
U+231A  ?   WATCH
U+231B  ?   HOURGLASS
U+2326  ?   ERASE TO THE RIGHT
U+2327  ?   X IN A RECTANGLE BOX
U+2328  ?   KEYBOARD
U+2329  <   LEFT-POINTING ANGLE BRACKET
U+232A  >   RIGHT-POINTING ANGLE BRACKET
U+232B  ?   ERASE TO THE LEFT
U+23E9  ?   BLACK RIGHT-POINTING DOUBLE TRIANGLE
U+23EA  ?   BLACK LEFT-POINTING DOUBLE TRIANGLE
U+23EB  ?   BLACK UP-POINTING DOUBLE TRIANGLE
U+23EC  ?   BLACK DOWN-POINTING DOUBLE TRIANGLE
U+23ED  ?   BLACK RIGHT-POINTING DOUBLE TRIANGLE WITH VERTICAL BAR
U+23EE  ?   BLACK LEFT-POINTING DOUBLE TRIANGLE WITH VERTICAL BAR
U+23EF  ?   BLACK RIGHT-POINTING TRIANGLE WITH DOUBLE VERTICAL BAR
U+23F0  ?   ALARM CLOCK
U+23F1  ?   STOPWATCH
U+23F2  ?   TIMER CLOCK
U+23F3  ?   HOURGLASS WITH FLOWING SAND
U+2600  ?   BLACK SUN WITH RAYS
U+2601  ?   CLOUD
U+2602  ?   UMBRELLA
U+2603  ?   SNOWMAN
U+2604  ?   COMET
U+2605  ?   BLACK STAR
U+2606  ?   WHITE STAR
U+2607  ?   LIGHTNING
U+2608  ?   THUNDERSTORM
U+2609  ?   SUN
U+260A  ?   ASCENDING NODE
U+260B  ?   DESCENDING NODE
U+260C  ?   CONJUNCTION
U+260D  ?   OPPOSITION
U+260E  ?   BLACK TELEPHONE
U+260F  ?   WHITE TELEPHONE
U+2610  ?   BALLOT BOX
U+2611  ?   BALLOT BOX WITH CHECK
U+2612  ?   BALLOT BOX WITH X
U+2613  ?   SALTIRE
U+2614  ?   UMBRELLA WITH RAINDROPS
U+2615  ?   HOT BEVERAGE
U+2616  ?   WHITE SHOGI PIECE
U+2617  ?   BLACK SHOGI PIECE
U+2618  ?   SHAMROCK
U+2619  ?   REVERSED ROTATED FLORAL HEART BULLET
U+261A  ?   BLACK LEFT-POINTING INDEX
U+261B  ?   BLACK RIGHT-POINTING INDEX
U+261C  ?   WHITE LEFT POINTING INDEX
U+261D  ?   WHITE UP POINTING INDEX
U+261E  ?   WHITE RIGHT POINTING INDEX
U+261F  ?   WHITE DOWN POINTING INDEX
U+2620  ?   SKULL AND CROSSBONES
U+2621  ?   CAUTION SIGN
U+2622  ?   RADIOACTIVE SIGN
U+2623  ?   BIOHAZARD SIGN
U+262A  ?   STAR AND CRESCENT
U+262B  ?   FARSI SYMBOL
U+262C  ?   ADI SHAKTI
U+262D  ?   HAMMER AND SICKLE
U+262E  ?   PEACE SYMBOL
U+262F  ?   YIN YANG
U+2638  ?   WHEEL OF DHARMA
U+2639  ?   WHITE FROWNING FACE
U+263A  ?   WHITE SMILING FACE
U+263B  ?   BLACK SMILING FACE
U+263C  ¤   WHITE SUN WITH RAYS
U+263D  ?   FIRST QUARTER MOON
U+263E  ?   LAST QUARTER MOON
U+263F  ?   MERCURY
U+2640  ?   FEMALE SIGN
U+2641  ?   EARTH
U+2642  ?   MALE SIGN
U+2643  ?   JUPITER
U+2644  ?   SATURN
U+2645  ?   URANUS
U+2646  ?   NEPTUNE
U+2647  ?   PLUTO
U+2648  ?   ARIES
U+2649  ?   TAURUS
U+264A  ?   GEMINI
U+264B  ?   CANCER
U+264C  ?   LEO
U+264D  ?   VIRGO
U+264E  ?   LIBRA
U+264F  ?   SCORPIUS
U+2650  ?   SAGITTARIUS
U+2651  ?   CAPRICORN
U+2652  ?   AQUARIUS
U+2653  ?   PISCES
U+2654  ?   WHITE CHESS KING
U+2655  ?   WHITE CHESS QUEEN
U+2656  ?   WHITE CHESS ROOK
U+2657  ?   WHITE CHESS BISHOP
U+2658  ?   WHITE CHESS KNIGHT
U+2659  ?   WHITE CHESS PAWN
U+265A  ?   BLACK CHESS KING
U+265B  ?   BLACK CHESS QUEEN
U+265C  ?   BLACK CHESS ROOK
U+265D  ?   BLACK CHESS BISHOP
U+265E  ?   BLACK CHESS KNIGHT
U+265F  ?   BLACK CHESS PAWN
U+2660  ?   BLACK SPADE SUIT
U+2661  ?   WHITE HEART SUIT
U+2662  ?   WHITE DIAMOND SUIT
U+2663  ?   BLACK CLUB SUITE
U+2664  ?   WHITE SPADE SUIT
U+2665  ?   BLACK HEART SUIT
U+2666  ?   BLACK DIAMOND SUIT
U+2667  ?   WHITE CLUB SUITE
U+2668  ?   HOT SPRINGS
U+2669  ?   QUARTER NOTE
U+266A  ?   EIGHTH NOTE
U+266B  ?   BEAMED EIGHTH NOTES
U+266C  ?   BEAMED SIXTEENTH NOTES
U+266D  ?   MUSIC FLAT SIGN
U+266E  ?   MUSIC NATURAL SIGN
U+266F  ?   MUSIC SHARP SIGN
U+267A  ?   RECYCLING SYMBOL FOR GENERIC MATERIALS
U+267B  ?   BLACK UNIVERSAL RECYCLING SYMBOL
U+267C  ?   RECYCLED PAPER SYMBOL
U+267D  ?   PARTIALLY-RECYCLED PAPER SYMBOL
U+267E  ?   PERMANENT PAPER SIGN
U+267F  ?   WHEELCHAIR SYMBOL
U+2680  ?   DIE FACE-1
U+2681  ?   DIE FACE-2
U+2682  ?   DIE FACE-3
U+2683  ?   DIE FACE-4
U+2684  ?   DIE FACE-5
U+2685  ?   DIE FACE-6
U+2686  ?   WHITE CIRCLE WITH DOT RIGHT
U+2687  ?   WHITE CIRCLE WITH TWO DOTS
U+2688  ?   BLACK CIRCLE WITH WHITE DOT RIGHT
U+2689  ?   BLACK CIRCLE WITH TWO WHITE DOTS
U+268A  ?   MONOGRAM FOR YANG
U+268B  ?   MONOGRAM FOR YIN
U+268C  ?   DIGRAM FOR GREATER YANG
U+268D  ?   DIGRAM FOR LESSER YIN
U+268E  ?   DIGRAM FOR LESSER YANG
U+268F  ?   DIGRAM FOR GREATER YIN
U+2690  ?   WHITE FLAG
U+2691  ?   BLACK FLAG
U+2692  ?   HAMMER AND PICK
U+2693  ?   ANCHOR
U+2694  ?   CROSSED SWORDS
U+2695  ?   STAFF OF AESCULAPIUS
U+2696  ?   SCALES
U+2697  ?   ALEMBIC
U+2698  ?   FLOWER
U+2699  ?   GEAR
U+269A  ?   STAFF OF HERMES
U+269B  ?   ATOM SYMBOL
U+269C  ?   FLEUR-DE-LIS
U+269D  ?   OUTLINED WHITE STAR
U+269E  ?   THREE LINES CONVERGING RIGHT
U+269F  ?   THREE LINES CONVERGING LEFT
U+26A0  ?   WARNING SIGN
U+26A1  ?   HIGH VOLTAGE SIGN
U+26A2  ?   DOUBLED FEMALE SIGN
U+26A3  ?   DOUBLED MALE SIGN
U+26A4  ?   INTERLOCKED FEMALE AND MALE SIGN
U+26A5  ?   MALE AND FEMALE SIGN
U+26A6  ?   MALE WITH STROKE SIGN
U+26A7  ?   MALE WITH STROKE AND MALE AND FEMALE SIGN
U+26A8  ?   VERTICAL MALE WITH STROKE SIGN
U+26A9  ?   HORIZONTAL MALE WITH STROKE SIGN
U+26AA  ?   MEDIUM WHITE CIRCLE
U+26AB  ?   MEDIUM BLACK CIRCLE
U+26BD  ?   SOCCER BALL
U+26BE  ?   BASEBALL
U+26BF  ?   SQUARED KEY
U+26C0  ?   WHITE DRAUGHTSMAN
U+26C1  ?   WHITE DRAUGHTS KING
U+26C2  ?   BLACK DRAUGHTSMAN
U+26C3  ?   BLACK DRAUGHTS KING
U+26C4  ?   SNOWMAN WITHOUT SNOW
U+26C5  ?   SUN BEHIND CLOUD
U+26C6  ?   RAIN
U+26C7  ?   BLACK SNOWMAN
U+26C8  ?   THUNDER CLOUD AND RAIN
U+26C9  ?   TURNED WHITE SHOGI PIECE
U+26CA  ?   TURNED BLACK SHOGI PIECE
U+26CB  ?   WHITE DIAMOND IN SQUARE
U+26CC  ?   CROSSING LANES
U+26CD  ?   DISABLED CAR
U+26CE  ?   OPHIUCHUS
U+26CF  ?   PICK
U+26D0  ?   CAR SLIDING
U+26D1  ?   HELMET WITH WHITE CROSS
U+26D2  ?   CIRCLED CROSSING LANES
U+26D3  ?   CHAINS
U+26D4  ?   NO ENTRY
U+26D5  ?   ALTERNATE ONE-WAY LEFT WAY TRAFFIC
U+26D6  ?   BLACK TWO-WAY LEFT WAY TRAFFIC
U+26D7  ?   WHITE TWO-WAY LEFT WAY TRAFFIC
U+26D8  ?   BLACK LEFT LANE MERGE
U+26D9  ?   WHITE LEFT LANE MERGE
U+26DA  ?   DRIVE SLOW SIGN
U+26DB  ?   HEAVY WHITE DOWN-POINTING TRIANGLE
U+26DC  ?   LEFT CLOSED ENTRY
U+26DD  ?   SQUARED SALTIRE
U+26DE  ?   FALLING DIAGONAL IN WHITE CIRCLE IN BLACK SQUARE
U+26DF  ?   BLACK TRUCK
U+26E0  ?   RESTRICTED LEFT ENTRY-1
U+26E1  ?   RESTRICTED LEFT ENTRY-2
U+26E2  ?   ASTRONOMICAL SYMBOL FOR URANUS
U+26E3  ?   HEAVY CIRCLE WITH STROKE AND TWO DOTS ABOVE
U+26E4  ?   PENTAGRAM
U+26E5  ?   RIGHT-HANDED INTERLACED PENTAGRAM
U+26E6  ?   LEFT-HANDED INTERLACED PENTAGRAM
U+26E7  ?   INVERTED PENTAGRAM
U+26E8  ?   BLACK CROSS ON SHIELD
U+26E9  ?   SHINTO SHRINE
U+26EA  ?   CHURCH
U+26EB  ?   CASTLE
U+26EC  ?   HISTORIC SITE
U+26ED  ?   GEAR WITHOUT HUB
U+26EE  ?   GEAR WITH HANDLES
U+26EF  ?   MAP SYMBOL FOR LIGHTHOUSE
U+26F0  ?   MOUNTAIN
U+26F1  ?   UMBRELLA ON GROUND
U+26F2  ?   FOUNTAIN
U+26F3  ?   FLAG IN HOLE
U+26F4  ?   FERRY
U+26F5  ?   SAILBOAT
U+26F6  ?   SQUARE FOUR CORNERS
U+26F7  ?   SKIER
U+26F8  ?   ICE SKATE
U+26F9  ?   PERSON WITH BALL
U+26FA  ?   TENT
U+26FD  ?   FUEL PUMP
U+26FE  ?   CUP ON BLACK SQUARE
U+26FF  ?   WHITE FLAG WITH HORIZONTAL MIDDLE BLACK STRIPE
U+2701  ?   UPPER BLADE SCISSORS
U+2702  ?   BLACK SCISSORS
U+2703  ?   LOWER BLADE SCISSORS
U+2704  ?   WHITE SCISSORS
U+2705  ?   WHITE HEAVY CHECK MARK
U+2706  ?   TELEPHONE LOCATION SIGN
U+2707  ?   TAPE DRIVE
U+2708  ?   AIRPLANE
U+2709  ?   ENVELOPE
U+270A  ?   RAISED FIST
U+270B  ?   RAISED HAND
U+270C  ?   VICTORY HAND
U+270D  ?   WRITING HAND
U+270E  ?   LOWER RIGHT PENCIL
U+270F  ?   PENCIL
U+2710  ?   UPPER RIGHT PENCIL
U+2711  ?   WHITE NIB
U+2712  ?   BLACK NIB
U+2713  ?   CHECK MARK
U+2714  ?   HEAVY CHECK MARK
U+2715  ?   MULTIPLICATION X
U+2716  ?   HEAVY MULTIPLICATION X
U+2717  ?   BALLOT X
U+2718  ?   HEAVY BALLOT X
U+2719  ?   OUTLINED GREEK CROSS
U+271A  ?   HEAVY GREEK CROSS
U+271B  ?   OPEN CENTRE CROSS
U+271C  ?   HEAVY OPEN CENTRE CROSS
U+271D  ?   LATIN CROSS
U+271E  ?   SHADOWED WHITE LATIN CROSS
U+271F  ?   OUTLINED LATIN CROSS
U+2720  ?   MALTESE CROSS
U+2721  ?   STAR OF DAVID
U+2722  ?   FOUR TEARDROP-SPOKED ASTERISK
U+2723  ?   FOUR BALLOON-SPOKED ASTERISK
U+2724  ?   HEAVY FOUR BALLOON-SPOKED ASTERISK
U+2725  ?   FOUR CLUB-SPOKED ASTERISK
U+2726  ?   BLACK FOUR POINTED STAR
U+2727  ?   WHITE FOUR POINTED STAR
U+2728  ?   SPARKLES
U+2729  ?   STRESS OUTLINED WHITE STAR
U+272A  ?   CIRCLED WHITE STAR
U+272B  ?   OPEN CENTRE BLACK STAR
U+272C  ?   BLACK CENTRE WHITE STAR
U+272D  ?   OUTLINED BLACK STAR
U+272E  ?   HEAVY OUTLINED BLACK STAR
U+272F  ?   PINWHEEL STAR
U+2730  ?   SHADOWED WHITE STAR
U+2731  ?   HEAVY ASTERISK
U+2732  ?   OPEN CENTRE ASTERISK
U+2733  ?   EIGHT SPOKED ASTERISK
U+2734  ?   EIGHT POINTED BLACK STAR
U+2735  ?   EIGHT POINTED PINWHEEL STAR
U+2736  ?   SIX POINTED BLACK STAR
U+2737  ?   EIGHT POINTED RECTILINEAR BLACK STAR
U+2738  ?   HEAVY EIGHT POINTED RECTILINEAR BLACK STAR
U+2739  ?   TWELVE POINTED BLACK STAR
U+273A  ?   SIXTEEN POINTED ASTERISK
U+273B  ?   TEARDROP-SPOKED ASTERISK
U+273C  ?   OPEN CENTRE TEARDROP-SPOKED ASTERISK
U+273D  ?   HEAVY TEARDROP-SPOKED ASTERISK
U+273E  ?   SIX PETALLED BLACK AND WHITE FLORETTE
U+273F  ?   BLACK FLORETTE
U+2740  ?   WHITE FLORETTE
U+2741  ?   EIGHT PETALLED OUTLINED BLACK FLORETTE
U+2742  ?   CIRCLED OPEN CENTRE EIGHT POINTED STAR
U+2743  ?   HEAVY TEARDROP-SPOKED PINWHEEL ASTERISK
U+2744  ?   SNOWFLAKE
U+2745  ?   TIGHT TRIFOLIATE SNOWFLAKE
U+2746  ?   HEAVY CHEVRON SNOWFLAKE
U+2747  ?   SPARKLE
U+2748  ?   HEAVY SPARKLE
U+2749  ?   BALLOON-SPOKED ASTERISK
U+274A  ?   EIGHT TEARDROP-SPOKED PROPELLER ASTERISK
U+274B  ?   HEAVY EIGHT TEARDROP-SPOKED PROPELLER ASTERISK
U+274C  ?   CROSS MARK
U+274D  ?   SHADOWED WHITE CIRCLE
U+274E  ?   NEGATIVE SQUARED CROSS MARK
U+2753  ?   BLACK QUESTION MARK ORNAMENT
U+2754  ?   WHITE QUESTION MARK ORNAMENT
U+2755  ?   WHITE EXCLAMATION MARK ORNAMENT
U+2756  ?   BLACK DIAMOND MINUS WHITE X
U+2757  ?   HEAVY EXCLAMATION MARK SYMBOL
U+275B  ?   HEAVY SINGLE TURNED COMMA QUOTATION MARK ORNAMENT
U+275C  ?   HEAVY SINGLE COMMA QUOTATION MARK ORNAMENT
U+275D  ?   HEAVY DOUBLE TURNED COMMA QUOTATION MARK ORNAMENT
U+275E  ?   HEAVY DOUBLE COMMA QUOTATION MARK ORNAMENT
U+275F  ?   HEAVY LOW SINGLE COMMA QUOTATION MARK ORNAMENT
U+2760  ?   HEAVY LOW DOUBLE COMMA QUOTATION MARK ORNAMENT
U+2761  ?   CURVED STEM PARAGRAPH SIGN ORNAMENT
U+2762  ?   HEAVY EXCLAMATION MARK ORNAMENT
U+2763  ?   HEAVY HEART EXCLAMATION MARK ORNAMENT
U+2764  ?   HEAVY BLACK HEART
U+2765  ?   ROTATED HEAVY BLACK HEART BULLET
U+2766  ?   FLORAL HEART
U+2767  ?   ROTATED FLORAL HEART BULLET
U+276C  ?   MEDIUM LEFT-POINTING ANGLE BRACKET ORNAMENT
U+276D  ?   MEDIUM RIGHT-POINTING ANGLE BRACKET ORNAMENT
U+276E  ?   HEAVY LEFT-POINTING ANGLE QUOTATION MARK ORNAMENT
U+276F  ?   HEAVY RIGHT-POINTING ANGLE QUOTATION MARK ORNAMENT
U+2770  ?   HEAVY LEFT-POINTING ANGLE BRACKET ORNAMENT
U+2771  ?   HEAVY RIGHT-POINTING ANGLE BRACKET ORNAMENT
U+2794  ?   HEAVY WIDE-HEADED RIGHTWARDS ARROW
U+2795  ?   HEAVY PLUS SIGN
U+2796  ?   HEAVY MINUS SIGN
U+2797  ?   HEAVY DIVISION SIGN
U+2798  ?   HEAVY SOUTH EAST ARROW
U+2799  ?   HEAVY RIGHTWARDS ARROW
U+279A  ?   HEAVY NORTH EAST ARROW
U+279B  ?   DRAFTING POINT RIGHTWARDS ARROW
U+279C  ?   HEAVY ROUND-TIPPED RIGHTWARDS ARROW
U+279D  ?   TRIANGLE-HEADED RIGHTWARDS ARROW
U+279E  ?   HEAVY TRIANGLE-HEADED RIGHTWARDS ARROW
U+279F  ?   DASHED TRIANGLE-HEADED RIGHTWARDS ARROW
U+27A0  ?   HEAVY DASHED TRIANGLE-HEADED RIGHTWARDS ARROW
U+27A1  ?   BLACK RIGHTWARDS ARROW
U+27A2  ?   THREE-D TOP-LIGHTED RIGHTWARDS ARROWHEAD
U+27A3  ?   THREE-D BOTTOM-LIGHTED RIGHTWARDS ARROWHEAD
U+27A4  ?   BLACK RIGHTWARDS ARROWHEAD
U+27A5  ?   HEAVY BLACK CURVED DOWNWARDS AND RIGHTWARDS ARROW
U+27A6  ?   HEAVY BLACK CURVED UPWARDS AND RIGHTWARDS ARROW
U+27A7  ?   SQUAT BLACK RIGHTWARDS ARROW
U+27A8  ?   HEAVY CONCAVE-POINTED BLACK RIGHTWARDS ARROW
U+27A9  ?   RIGHT-SHADED WHITE RIGHTWARDS ARROW
U+27AA  ?   LEFT-SHADED WHITE RIGHTWARDS ARROW
U+27AB  ?   BACK-TILTED SHADOWED WHITE RIGHTWARDS ARROW
U+27AC  ?   FRONT-TILTED SHADOWED WHITE RIGHTWARDS ARROW
U+27AD  ?   HEAVY LOWER RIGHT-SHADOWED WHITE RIGHTWARDS ARROW
U+27AE  ?   HEAVY UPPER RIGHT-SHADOWED WHITE RIGHTWARDS ARROW
U+27AF  ?   NOTCHED LOWER RIGHT-SHADOWED WHITE RIGHTWARDS ARROW
U+27B0  ?   CURLY LOOP
U+27B1  ?   NOTCHED UPPER RIGHT-SHADOWED WHITE RIGHTWARDS ARROW
U+27B2  ?   CIRCLED HEAVY WHITE RIGHTWARDS ARROW
U+27B3  ?   WHITE-FEATHERED RIGHTWARDS ARROW
U+27B4  ?   BLACK-FEATHERED SOUTH EAST ARROW
U+27B5  ?   BLACK-FEATHERED RIGHTWARDS ARROW
U+27B6  ?   BLACK-FEATHERED NORTH EAST ARROW
U+27B7  ?   HEAVY BLACK-FEATHERED SOUTH EAST ARROW
U+27B8  ?   HEAVY BLACK-FEATHERED RIGHTWARDS ARROW
U+27B9  ?   HEAVY BLACK-FEATHERED NORTH EAST ARROW
U+27BA  ?   TEARDROP-BARBED RIGHTWARDS ARROW
U+27BB  ?   HEAVY TEARDROP-SHANKED RIGHTWARDS ARROW
U+27BC  ?   WEDGE-TAILED RIGHTWARDS ARROW
U+27BD  ?   HEAVY WEDGE-TAILED RIGHTWARDS ARROW
U+27BE  ?   OPEN-OUTLINED RIGHTWARDS ARROW
U+27C0  ?   THREE DIMENSIONAL ANGLE
U+27E8  ?   MATHEMATICAL LEFT ANGLE BRACKET
U+27E9  ?   MATHEMATICAL RIGHT ANGLE BRACKET
U+27EA  ?   MATHEMATICAL LEFT DOUBLE ANGLE BRACKET
U+27EB  ?   MATHEMATICAL RIGHT DOUBLE ANGLE BRACKET
U+27F0  ?   UPWARDS QUADRUPLE ARROW
U+27F1  ?   DOWNWARDS QUADRUPLE ARROW
U+27F2  ?   ANTICLOCKWISE GAPPED CIRCLE ARROW
U+27F3  ?   CLOCKWISE GAPPED CIRCLE ARROW
U+27F4  ?   RIGHT ARROW WITH CIRCLED PLUS
U+27F5  ?   LONG LEFTWARDS ARROW
U+27F6  ?   LONG RIGHTWARDS ARROW
U+27F7  ?   LONG LEFT RIGHT ARROW
U+27F8  ?   LONG LEFTWARDS DOUBLE ARROW
U+27F9  ?   LONG RIGHTWARDS DOUBLE ARROW
U+27FA  ?   LONG LEFT RIGHT DOUBLE ARROW
U+27FB  ?   LONG LEFTWARDS ARROW FROM BAR
U+27FC  ?   LONG RIGHTWARDS ARROW FROM BAR
U+27FD  ?   LONG LEFTWARDS DOUBLE ARROW FROM BAR
U+27FE  ?   LONG RIGHTWARDS DOUBLE ARROW FROM BAR
U+27FF  ?   LONG RIGHTWARDS SQUIGGLE ARROW
U+2900  ?   RIGHTWARDS TWO-HEADED ARROW WITH VERTICAL STROKE
U+2901  ?   RIGHTWARDS TWO-HEADED ARROW WITH DOUBLE VERTICAL STROKE
U+2902  ?   LEFTWARDS DOUBLE ARROW WITH VERTICAL STROKE
U+2903  ?   RIGHTWARDS DOUBLE ARROW WITH VERTICAL STROKE
U+2904  ?   LEFT RIGHT DOUBLE ARROW WITH VERTICAL STROKE
U+2905  ?   RIGHTWARDS TWO-HEADED ARROW FROM BAR
U+2906  ?   LEFTWARDS DOUBLE ARROW FROM BAR
U+2907  ?   RIGHTWARDS DOUBLE ARROW FROM BAR
U+2908  ?   DOWNWARDS ARROW WITH HORIZONTAL STROKE
U+2909  ?   UPWARDS ARROW WITH HORIZONTAL STROKE
U+290A  ?   UPWARDS TRIPLE ARROW
U+290B  ?   DOWNWARDS TRIPLE ARROW
U+290C  ?   LEFTWARDS DOUBLE DASH ARROW
U+290D  ?   RIGHTWARDS DOUBLE DASH ARROW
U+290E  ?   LEFTWARDS TRIPLE DASH ARROW
U+290F  ?   RIGHTWARDS TRIPLE DASH ARROW
U+2910  ?   RIGHTWARDS TWO-HEADED TRIPLE DASH ARROW
U+2911  ?   RIGHTWARDS ARROW WITH DOTTED STEM
U+2912  ?   UPWARDS ARROW TO BAR
U+2913  ?   DOWNWARDS ARROW TO BAR
U+2914  ?   RIGHTWARDS ARROW WITH TAIL WITH VERTICAL STROKE
U+2915  ?   RIGHTWARDS ARROW WITH TAIL WITH DOUBLE VERTICAL STROKE
U+2916  ?   RIGHTWARDS TWO-HEADED ARROW WITH TAIL
U+2917  ?   RIGHTWARDS TWO-HEADED ARROW WITH TAIL WITH VERTICAL STROKE
U+2918  ?   RIGHTWARDS TWO-HEADED ARROW WITH TAIL WITH DOUBLE VERTICAL STROKE
U+2919  ?   LEFTWARDS ARROW-TAIL
U+291A  ?   RIGHTWARDS ARROW-TAIL
U+291B  ?   LEFTWARDS DOUBLE ARROW-TAIL
U+291C  ?   RIGHTWARDS DOUBLE ARROW-TAIL
U+291D  ?   LEFTWARDS ARROW TO BLACK DIAMOND
U+291E  ?   RIGHTWARDS ARROW TO BLACK DIAMOND
U+291F  ?   LEFTWARDS ARROW FROM BAR TO BLACK DIAMOND
U+2920  ?   RIGHTWARDS ARROW FROM BAR TO BLACK DIAMOND
U+2921  ?   NORTHWEST AND SOUTH EAST ARROW
U+2922  ?   NORTHEAST AND SOUTH WEST ARROW
U+2923  ?   NORTH WEST ARROW WITH HOOK
U+2924  ?   NORTH EAST ARROW WITH HOOK
U+2925  ?   SOUTH EAST ARROW WITH HOOK
U+2926  ?   SOUTH WEST ARROW WITH HOOK
U+2927  ?   NORTH WEST ARROW AND NORTH EAST ARROW
U+2928  ?   NORTH EAST ARROW AND SOUTH EAST ARROW
U+2929  ?   SOUTH EAST ARROW AND SOUTH WEST ARROW
U+292A  ?   SOUTH WEST ARROW AND NORTH WEST ARROW
U+292B  ?   RISING DIAGONAL CROSSING FALLING DIAGONAL
U+292C  ?   FALLING DIAGONAL CROSSING RISING DIAGONAL
U+292D  ?   SOUTH EAST ARROW CROSSING NORTH EAST ARROW
U+292E  ?   NORTH EAST ARROW CROSSING SOUTH EAST ARROW
U+292F  ?   FALLING DIAGONAL CROSSING NORTH EAST ARROW
U+2930  ?   RISING DIAGONAL CROSSING SOUTH EAST ARROW
U+2931  ?   NORTH EAST ARROW CROSSING NORTH WEST ARROW
U+2932  ?   NORTH WEST ARROW CROSSING NORTH EAST ARROW
U+2933  ?   WAVE ARROW POINTING DIRECTLY RIGHT
U+2934  ?   ARROW POINTING RIGHTWARDS THEN CURVING UPWARDS
U+2935  ?   ARROW POINTING RIGHTWARDS THEN CURVING DOWNWARDS
U+2936  ?   ARROW POINTING DOWNWARDS THEN CURVING LEFTWARDS
U+2937  ?   ARROW POINTING DOWNWARDS THEN CURVING RIGHTWARDS
U+2938  ?   RIGHT-SIDE ARC CLOCKWISE ARROW
U+2939  ?   LEFT-SIDE ARC ANTICLOCKWISE ARROW
U+293A  ?   TOP ARC ANTICLOCKWISE ARROW
U+293B  ?   BOTTOM ARC ANTICLOCKWISE ARROW
U+293C  ?   TOP ARC CLOCKWISE ARROW WITH MINUS
U+293D  ?   TOP ARC ANTICLOCKWISE ARROW WITH PLUS
U+293E  ?   LOWER RIGHT SEMICIRCULAR CLOCKWISE ARROW
U+293F  ?   LOWER LEFT SEMICIRCULAR ANTICLOCKWISE ARROW
U+2940  ?   ANTICLOCKWISE CLOSED CIRCLE ARROW
U+2941  ?   CLOCKWISE CLOSED CIRCLE ARROW
U+2942  ?   RIGHTWARDS ARROW ABOVE SHORT LEFTWARDS ARROW
U+2943  ?   LEFTWARDS ARROW ABOVE SHORT RIGHTWARDS ARROW
U+2944  ?   SHORT RIGHTWARDS ARROW ABOVE LEFTWARDS ARROW
U+2945  ?   RIGHTWARDS ARROW WITH PLUS BELOW
U+2946  ?   LEFTWARDS ARROW WITH PLUS BELOW
U+2962  ?   LEFTWARDS HARPOON WITH BARB UP ABOVE LEFTWARDS HARPOON WITH BARB DOWN
U+2963  ?   UPWARDS HARPOON WITH BARB LEFT BESIDE UPWARDS HARPOON WITH BARB RIGHT
U+2964  ?   RIGHTWARDS HARPOON WITH BARB UP ABOVE RIGHTWARDS HARPOON WITH BARB DOWN
U+2965  ?   DOWNWARDS HARPOON WITH BARB LEFT BESIDE DOWNWARDS HARPOON WITH BARB RIGHT
U+2966  ?   LEFTWARDS HARPOON WITH BARB UP ABOVE RIGHTWARDS HARPOON WITH BARB UP
U+2967  ?   LEFTWARDS HARPOON WITH BARB DOWN ABOVE RIGHTWARDS HARPOON WITH BARB DOWN
U+2968  ?   RIGHTWARDS HARPOON WITH BARB UP ABOVE LEFTWARDS HARPOON WITH BARB UP
U+2969  ?   RIGHTWARDS HARPOON WITH BARB DOWN ABOVE LEFTWARDS HARPOON WITH BARB DOWN
U+296A  ?   LEFTWARDS HARPOON WITH BARB UP ABOVE LONG DASH
U+296B  ?   LEFTWARDS HARPOON WITH BARB DOWN BELOW LONG DASH
U+296C  ?   RIGHTWARDS HARPOON WITH BARB UP ABOVE LONG DASH
U+296D  ?   RIGHTWARDS HARPOON WITH BARB DOWN BELOW LONG DASH
U+296E  ?   UPWARDS HARPOON WITH BARB LEFT BESIDE DOWNWARDS HARPOON WITH BARB RIGHT
U+296F  ?   DOWNWARDS HARPOON WITH BARB LEFT BESIDE UPWARDS HARPOON WITH BARB RIGHT
U+2989  ?   Z NOTATION LEFT BINDING BRACKET
U+298A  ?   Z NOTATION RIGHT BINDING BRACKET
U+2991  ?   LEFT ANGLE BRACKET WITH DOT
U+2992  ?   RIGHT ANGLE BRACKET WITH DOT
U+2993  ?   LEFT ARC LESS-THAN BRACKET
U+2994  ?   RIGHT ARC GREATER-THAN BRACKET
U+2995  ?   DOUBLE LEFT ARC GREATER-THAN BRACKET
U+2996  ?   DOUBLE RIGHT ARC LESS-THAN BRACKET
U+29A8  ?   MEASURED ANGLE WITH OPEN ARM ENDING IN ARROW POINTING UP AND RIGHT
U+29A9  ?   MEASURED ANGLE WITH OPEN ARM ENDING IN ARROW POINTING UP AND LEFT
U+29AA  ?   MEASURED ANGLE WITH OPEN ARM ENDING IN ARROW POINTING DOWN AND RIGHT
U+29AB  ?   MEASURED ANGLE WITH OPEN ARM ENDING IN ARROW POINTING DOWN AND LEFT
U+29AC  ?   MEASURED ANGLE WITH OPEN ARM ENDING IN ARROW POINTING RIGHT AND UP
U+29AD  ?   MEASURED ANGLE WITH OPEN ARM ENDING IN ARROW POINTING LEFT AND UP
U+29AE  ?   MEASURED ANGLE WITH OPEN ARM ENDING IN ARROW POINTING RIGHT AND DOWN
U+29AF  ?   MEASURED ANGLE WITH OPEN ARM ENDING IN ARROW POINTING LEFT AND DOWN
U+29BE  ?   CIRCLED WHITE BULLET
U+29BF  ?   CIRCLED BULLET
U+29C9  ?   TWO JOINED SQUARES
U+29CE  ?   RIGHT TRIANGLE ABOVE LEFT TRIANGLE
U+29CF  ?   LEFT TRIANGLE BESIDE VERTICAL BAR
U+29D0  ?   VERTICAL BAR BESIDE RIGHT TRIANGLE
U+29D1  ?   BOWTIE WITH LEFT HALF BLACK
U+29D2  ?   BOWTIE WITH RIGHT HALF BLACK
U+29D3  ?   BLACK BOWTIE
U+29D4  ?   TIMES WITH LEFT HALF BLACK
U+29D5  ?   TIMES WITH RIGHT HALF BLACK
U+29D6  ?   WHITE HOURGLASS
U+29D7  ?   BLACK HOURGLASS
U+29E8  ?   DOWN-POINTING TRIANGLE WITH LEFT HALF BLACK
U+29E9  ?   DOWN-POINTING TRIANGLE WITH RIGHT HALF BLACK
U+29EA  ?   BLACK DIAMOND WITH DOWN ARROW
U+29EB  ?   BLACK LOZENGE
U+29EC  ?   WHITE CIRCLE WITH DOWN ARROW
U+29ED  ?   BLACK CIRCLE WITH DOWN ARROW
U+29F4  ?   RULE-DELAYED
U+29FC  ?   LEFT-POINTING CURVED ANGLE BRACKET
U+29FD  ?   RIGHT-POINTING CURVED ANGLE BRACKET
U+29FE  ?   TINY
U+29FF  ?   MINY
U+2B00  ?   NORTH EAST WHITE ARROW
U+2B01  ?   NORTH WEST WHITE ARROW
U+2B02  ?   SOUTH EAST WHITE ARROW
U+2B03  ?   SOUTH WEST WHITE ARROW
U+2B04  ?   LEFT RIGHT WHITE ARROW
U+2B05  ?   LEFTWARDS BLACK ARROW
U+2B06  ?   UPWARDS BLACK ARROW
U+2B07  ?   DOWNWARDS BLACK ARROW
U+2B08  ?   NORTH EAST BLACK ARROW
U+2B09  ?   NORTH WEST BLACK ARROW
U+2B0A  ?   SOUTH EAST BLACK ARROW
U+2B0B  ?   SOUTHWEST BLACK ARROW
U+2B0C  ?   LEFT RIGHT BLACK ARROW
U+2B0D  ?   UP DOWN BLACK ARROW
U+2B0E  ?   RIGHTWARDS ARROW WITH TIP DOWNWARDS
U+2B0F  ?   RIGHTWARDS ARROW WITH TIP UPWARDS
U+2B10  ?   LEFTWARDS ARROW WITH TIP DOWNWARDS
U+2B11  ?   LEFTWARDS ARROW WITH TIP UPWARDS
U+2B12  ?   SQUARE WITH TOP HALF BLACK
U+2B13  ?   SQUARE WITH BOTTOM HALF BLACK
U+2B14  ?   SQUARE WITH UPPER RIGHT DIAGONAL HALF BLACK
U+2B15  ?   SQUARE WITH LOWER LEFT DIAGONAL HALF BLACK
U+2B16  ?   DIAMOND WITH LEFT HALF BLACK
U+2B17  ?   DIAMOND WITH RIGHT HALF BLACK
U+2B18  ?   DIAMOND WITH TOP HALF BLACK
U+2B19  ?   DIAMOND WITH BOTTOM HALF BLACK
U+2B1A  ?   DOTTED SQUARE
U+2B1B  ?   BLACK LARGE SQUARE
U+2B1C  ?   WHITE LARGE SQUARE
U+2B1D  ?   BLACK VERY SMALL SQUARE
U+2B1E  ?   WHITE VERY SMALL SQUARE
U+2B1F  ?   BLACK PENTAGON
U+2B20  ?   WHITE PENTAGON
U+2B21  ?   WHITE HEXAGON
U+2B22  ?   BLACK HEXAGON
U+2B23  ?   HORIZONTAL BLACK HEXAGON
U+2B24  ?   BLACK LARGE CIRCLE
U+2B25  ?   BLACK MEDIUM DIAMOND
U+2B26  ?   WHITE MEDIUM DIAMOND
U+2B27  ?   BLACK MEDIUM LOZENGE
U+2B28  ?   WHITE MEDIUM LOZENGE
U+2B29  ?   BLACK SMALL DIAMOND
U+2B2A  ?   BLACK SMALL LOZENGE
U+2B2B  ?   WHITE SMALL LOZENGE
U+2B30  ?   LEFT ARROW WITH SMALL CIRCLE
U+2B31  ?   THREE LEFTWARDS ARROWS
U+2B32  ?   LEFT ARROW WITH CIRCLED PLUS
U+2B33  ?   LONG LEFTWARDS SQUIGGLE ARROW
U+2B34  ?   LEFTWARDS TWO-HEADED ARROW WITH VERTICAL STROKE
U+2B35  ?   LEFTWARDS TWO-HEADED ARROW WITH DOUBLE VERTICAL STROKE
U+2B36  ?   LEFTWARDS TWO-HEADED ARROW FROM BAR
U+2B37  ?   LEFTWARDS TWO-HEADED TRIPLE DASH ARROW
U+2B38  ?   LEFTWARDS ARROW WITH DOTTED STEM
U+2B39  ?   LEFTWARDS ARROW WITH TAIL WITH VERTICAL STROKE
U+2B3A  ?   LEFTWARDS ARROW WITH TAIL WITH DOUBLE VERTICAL STROKE
U+2B3B  ?   LEFTWARDS TWO-HEADED ARROW WITH TAIL
U+2B3C  ?   LEFTWARDS TWO-HEADED ARROW WITH TAIL WITH VERTICAL STROKE
U+2B3D  ?   LEFTWARDS TWO-HEADED ARROW WITH TAIL WITH DOUBLE VERTICAL STROKE
U+2B3E  ?   LEFTWARDS ARROW THROUGH X
U+2B3F  ?   WAVE ARROW POINTING DIRECTLY LEFT
U+2B40  ?   EQUALS SIGN ABOVE LEFTWARDS ARROW
U+2B41  ?   REVERSE TILDE OPERATOR ABOVE LEFTWARDS ARROW
U+2B42  ?   LEFTWARDS ARROW ABOVE REVERSE ALMOST EQUAL TO
U+2B43  ?   RIGHTWARDS ARROW THROUGH GREATER-THAN
U+2B44  ?   RIGHTWARDS ARROW THROUGH SUPERSET
U+2B45  ?   LEFTWARDS QUADRUPLE ARROW
U+2B46  ?   RIGHTWARDS QUADRUPLE ARROW
U+2B47  ?   REVERSE TILDE OPERATOR ABOVE RIGHTWARDS ARROW
U+2B48  ?   RIGHTWARDS ARROW ABOVE REVERSE ALMOST EQUAL TO
U+2B49  ?   TILDE OPERATOR ABOVE LEFTWARDS ARROW
U+2B4A  ?   LEFTWARDS ARROW ABOVE ALMOST EQUAL TO
U+2B4B  ?   LEFTWARDS ARROW ABOVE REVERSE TILDE OPERATOR
U+2B4C  ?   RIGHTWARDS ARROW ABOVE REVERSE TILDE OPERATOR
U+2B50  ?   WHITE MEDIUM STAR
U+2B51  ?   BLACK SMALL STAR
U+2B52  ?   WHITE SMALL STAR
U+2B53  ?   BLACK RIGHT-POINTING PENTAGON
U+2B54  ?   WHITE RIGHT-POINTING PENTAGON
U+2B55  ?   HEAVY LARGE CIRCLE
U+2B56  ?   HEAVY OVAL WITH OVAL INSIDE
U+2B57  ?   HEAVY CIRCLE WITH CIRCLE INSIDE
U+2B58  ?   HEAVY CIRCLE
U+2B59  ?   HEAVY CIRCLED SALTIRE

OPTION 2: PURE CSS CHEVRONS

I recently made an article about creating chevrons efficiently using only CSS (No images required).

How to simply alter:

  • ROTATION
  • THICKNESS
  • COLOR
  • SIZE

CLICK FOR DEMO ON JSFIDDLE


enter image description here


CSS (Efficient with cross browser support)

_x000D_
_x000D_
.Chevron{_x000D_
    position:relative;_x000D_
    display:block;_x000D_
    height:50px;/*height should be double border*/_x000D_
}_x000D_
.Chevron:before,_x000D_
.Chevron:after{_x000D_
    position:absolute;_x000D_
    display:block;_x000D_
    content:"";_x000D_
    border:25px solid transparent;/*adjust size*/_x000D_
}_x000D_
/* Replace all text `top` below with left/right/bottom to rotate the chevron */_x000D_
.Chevron:before{_x000D_
    top:0;_x000D_
    border-top-color:#b00;/*Chevron Color*/_x000D_
}_x000D_
.Chevron:after{_x000D_
    top:-10px;/*adjust thickness*/_x000D_
    border-top-color:#fff;/*Match background colour*/_x000D_
}
_x000D_
<i class="Chevron"></i>
_x000D_
_x000D_
_x000D_


OPTION 3: CSS BASE64 IMAGE ICONS

UP/DOWN UP/DOWN

DOWN DOWN

UP UP

Using only a few lines of CSS we can encode our images into base64.


CLICK FOR DEMO ON JSFIDDLE


PROS

  • No need to include additional resources in the form of images or fonts.
  • Supports full alpha transparency.
  • Full cross-browser support.
  • Small images/icons can be stored in a database.

CONS

  • Updating/editing can become a hassle.
  • Not suitable for large images due to excessive code markup that's generated.

CSS

.sorting,
.sorting_asc,
.sorting_desc{
    padding:4px 21px 4px 4px;
    cursor:pointer;
}
.sorting{
    background:url(data:image/gif;base64,R0lGODlhCwALAJEAAAAAAP///xUVFf///yH5BAEAAAMALAAAAAALAAsAAAIUnC2nKLnT4or00PvyrQwrPzUZshQAOw==) no-repeat center right;
}
.sorting_asc{
    background:url(data:image/gif;base64,R0lGODlhCwALAJEAAAAAAP///xUVFf///yH5BAEAAAMALAAAAAALAAsAAAIRnC2nKLnT4or00Puy3rx7VQAAOw==) no-repeat center right;
}
.sorting_desc{
    background:url(data:image/gif;base64,R0lGODlhCwALAJEAAAAAAP///xUVFf///yH5BAEAAAMALAAAAAALAAsAAAIPnI+py+0/hJzz0IruwjsVADs=) no-repeat center right;
}

The value violated the integrity constraints for the column

As a slight alternative to @FazianMubasher's answer, instead of allowing NULL for the specified column (which may for many reasons not be possible), you could also add a Conditional Split Task to branch NULL values to an error file, or just to ignore them:

enter image description here

enter image description here

using sql count in a case statement

SELECT 
    COUNT(CASE WHEN rsp_ind = 0 then 1 ELSE NULL END) as "New",
    COUNT(CASE WHEN rsp_ind = 1 then 1 ELSE NULL END) as "Accepted"
from tb_a

You can see the output for this request HERE

C# Sort and OrderBy comparison

In a nutshell :

List/Array Sort() :

  • Unstable sort.
  • Done in-place.
  • Use Introsort/Quicksort.
  • Custom comparison is done by providing a comparer. If comparison is expensive, it might be slower than OrderBy() (which allow to use keys, see below).

OrderBy/ThenBy() :

  • Stable sort.
  • Not in-place.
  • Use Quicksort. Quicksort is not a stable sort. Here is the trick : when sorting, if two elements have equal key, it compares their initial order (which has been stored before sorting).
  • Allows to use keys (using lambdas) to sort elements on their values (eg : x => x.Id). All keys are extracted first before sorting. This might result in better performance than using Sort() and a custom comparer.

Sources: MDSN, reference source and dotnet/coreclr repository (GitHub).

Some of the statements listed above are based on current .NET framework implementation (4.7.2). It might change in the future.

Delete the last two characters of the String

You can use substring function:

s.substring(0,s.length() - 2));

With the first 0, you say to substring that it has to start in the first character of your string and with the s.length() - 2 that it has to finish 2 characters before the String ends.

For more information about substring function you can see here:

http://docs.oracle.com/javase/7/docs/api/java/lang/String.html

org.glassfish.jersey.servlet.ServletContainer ClassNotFoundException

I had the same problem with eclipse, the WA solution was to copy the libs to WEB-INF/lib

C++ IDE for Linux?

I use Eclipse CDT and Qt Creator (for Qt applications).

That's my preferences. It's a very suggestive question and there is as many answers as there is developers. :)

Checking whether a string starts with XXXX

In case you want to match multiple words to your magic word, you can pass the words to match as a tuple:

>>> magicWord = 'zzzTest'
>>> magicWord.startswith(('zzz', 'yyy', 'rrr'))
True

startswith takes a string or a tuple of strings.

Convert Rows to columns using 'Pivot' in SQL Server

I've achieved the same thing before by using subqueries. So if your original table was called StoreCountsByWeek, and you had a separate table that listed the Store IDs, then it would look like this:

SELECT StoreID, 
    Week1=(SELECT ISNULL(SUM(xCount),0) FROM StoreCountsByWeek WHERE StoreCountsByWeek.StoreID=Store.StoreID AND Week=1),
    Week2=(SELECT ISNULL(SUM(xCount),0) FROM StoreCountsByWeek WHERE StoreCountsByWeek.StoreID=Store.StoreID AND Week=2),
    Week3=(SELECT ISNULL(SUM(xCount),0) FROM StoreCountsByWeek WHERE StoreCountsByWeek.StoreID=Store.StoreID AND Week=3)
FROM Store
ORDER BY StoreID

One advantage to this method is that the syntax is more clear and it makes it easier to join to other tables to pull other fields into the results too.

My anecdotal results are that running this query over a couple of thousand rows completed in less than one second, and I actually had 7 subqueries. But as noted in the comments, it is more computationally expensive to do it this way, so be careful about using this method if you expect it to run on large amounts of data .

How do you redirect to a page using the POST verb?

try this one

return Content("<form action='actionname' id='frmTest' method='post'><input type='hidden' name='someValue' value='" + someValue + "' /><input type='hidden' name='anotherValue' value='" + anotherValue + "' /></form><script>document.getElementById('frmTest').submit();</script>");

Add onClick event to document.createElement("th")

var newTH = document.createElement('th');
newTH.addEventListener( 'click', function(){
  // delete the column here
} );

Style input type file?

Same solution via Jquery. Works if you have more than one file input in the page.

$j(".filebutton").click(function() {
    var input = $j(this).next().find('input');
    input.click();
});

$j(".fileinput").change(function(){

    var file = $j(this).val();
    var fileName = file.split("\\");
    var pai =$j(this).parent().parent().prev();
    pai.html(fileName[fileName.length-1]);
    event.preventDefault();
});

How can I generate an HTML report for Junit results?

If you could use Ant then you would just use the JUnitReport task as detailed here: http://ant.apache.org/manual/Tasks/junitreport.html, but you mentioned in your question that you're not supposed to use Ant. I believe that task merely transforms the XML report into HTML so it would be feasible to use any XSLT processor to generate a similar report.

Alternatively, you could switch to using TestNG ( http://testng.org/doc/index.html ) which is very similar to JUnit but has a default HTML report as well as several other cool features.

Purge or recreate a Ruby on Rails database

To drop a particular database, you can do this on rails console:

$rails console
Loading development environment
1.9.3 > ActiveRecord::Migration.drop_table(:<table_name>)
1.9.3 > exit

And then migrate DB again

$bundle exec rake db:migrate 

Is there a way to iterate over a dictionary?

This is iteration using block approach:

    NSDictionary *dict = @{@"key1":@1, @"key2":@2, @"key3":@3};

    [dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        NSLog(@"%@->%@",key,obj);
        // Set stop to YES when you wanted to break the iteration.
    }];

With autocompletion is very fast to set, and you do not have to worry about writing iteration envelope.

How to print current date on python3?

This function allows you to get the date and time in lots of formats (see the bottom of this post).

# Get the current date or time
def getdatetime(timedateformat='complete'):
    from datetime import datetime
    timedateformat = timedateformat.lower()
    if timedateformat == 'day':
        return ((str(datetime.now())).split(' ')[0]).split('-')[2]
    elif timedateformat == 'month':
        return ((str(datetime.now())).split(' ')[0]).split('-')[1]
    elif timedateformat == 'year':
        return ((str(datetime.now())).split(' ')[0]).split('-')[0]
    elif timedateformat == 'hour':
        return (((str(datetime.now())).split(' ')[1]).split('.')[0]).split(':')[0]
    elif timedateformat == 'minute':
        return (((str(datetime.now())).split(' ')[1]).split('.')[0]).split(':')[1]
    elif timedateformat == 'second':
        return (((str(datetime.now())).split(' ')[1]).split('.')[0]).split(':')[2]
    elif timedateformat == 'millisecond':
        return (str(datetime.now())).split('.')[1]
    elif timedateformat == 'yearmonthday':
        return (str(datetime.now())).split(' ')[0]
    elif timedateformat == 'daymonthyear':
        return ((str(datetime.now())).split(' ')[0]).split('-')[2] + '-' + ((str(datetime.now())).split(' ')[0]).split('-')[1] + '-' + ((str(datetime.now())).split(' ')[0]).split('-')[0]
    elif timedateformat == 'hourminutesecond':
        return ((str(datetime.now())).split(' ')[1]).split('.')[0]
    elif timedateformat == 'secondminutehour':
        return (((str(datetime.now())).split(' ')[1]).split('.')[0]).split(':')[2] + ':' + (((str(datetime.now())).split(' ')[1]).split('.')[0]).split(':')[1] + ':' + (((str(datetime.now())).split(' ')[1]).split('.')[0]).split(':')[0]
    elif timedateformat == 'complete':
        return str(datetime.now())
    elif timedateformat == 'datetime':
        return (str(datetime.now())).split('.')[0]
    elif timedateformat == 'timedate':
        return ((str(datetime.now())).split('.')[0]).split(' ')[1] + ' ' + ((str(datetime.now())).split('.')[0]).split(' ')[0]

To obtain the time or date, just use getdatetime("<TYPE>"), replacing <TYPE> with one of the following arguments:

All example outputs use this model information: 25-11-2017 03:23:56.477017

Argument Meaning Example output
day Get the current day 25
month Get the current month 11
year Get the current year 2017
hour Get the current hour 03
minute Get the current minute 23
second Get the current second 56
millisecond Get the current millisecond 477017
yearmonthday Get the year, month and day 2017-11-25
daymonthyear Get the day, month and year 25-11-2017
hourminutesecond Get the hour, minute and second 03:23:56
secondminutehour Get the second, minute and hour 56:23:03
complete Get the complete date and time 2017-11-25 03:23:56.477017
datetime Get the date and time 2017-11-25 03:23:56
timedate Get the time and date 03:23:56 2017-11-25

How to locate the Path of the current project directory in Java (IDE)?

I've just used this :

System.out.println(System.getenv().get("PWD"));

Using OpenJDK 11

jQuery override default validation error message display (Css) Popup/Tooltip like

Unfortunately I can't comment with my newbie reputation, but I have a solution for the issue of the screen going blank, or at least this is what worked for me. Instead of setting the wrapper class inside of the errorPlacement function, set it immediately when you're setting the wrapper type.

$('#myForm').validate({
    errorElement: "div",
    wrapper: "div class=\"message\"",
    errorPlacement: function(error, element) {
        offset = element.offset();
        error.insertBefore(element);
        //error.addClass('message');  // add a class to the wrapper
        error.css('position', 'absolute');
        error.css('left', offset.left + element.outerWidth() + 5);
        error.css('top', offset.top - 3);
    }

});

I'm assuming doing it this way allows the validator to know which div elements to remove, instead of all of them. Worked for me but I'm not entirely sure why, so if someone could elaborate that might help others out a ton.

Should Gemfile.lock be included in .gitignore?

Agreeing with r-dub, keep it in source control, but to me, the real benefit is this:

collaboration in identical environments (disregarding the windohs and linux/mac stuff). Before Gemfile.lock, the next dude to install the project might see all kinds of confusing errors, blaming himself, but he was just that lucky guy getting the next version of super gem, breaking existing dependencies.

Worse, this happened on the servers, getting untested version unless being disciplined and install exact version. Gemfile.lock makes this explicit, and it will explicitly tell you that your versions are different.

Note: remember to group stuff, as :development and :test

Turn off enclosing <p> tags in CKEditor 3.0

MAKE THIS YOUR config.js file code

CKEDITOR.editorConfig = function( config ) {

   //   config.enterMode = 2; //disabled <p> completely
        config.enterMode = CKEDITOR.ENTER_BR; // pressing the ENTER KEY input <br/>
        config.shiftEnterMode = CKEDITOR.ENTER_P; //pressing the SHIFT + ENTER KEYS input <p>
        config.autoParagraph = false; // stops automatic insertion of <p> on focus
    };

How to get correct timestamp in C#

Your mistake is using new DateTime(), which returns January 1, 0001 at 00:00:00.000 instead of current date and time. The correct syntax to get current date and time is DateTime.Now, so change this:

String timeStamp = GetTimestamp(new DateTime());

to this:

String timeStamp = GetTimestamp(DateTime.Now);

Load jQuery with Javascript and use jQuery

There's a working JSFiddle with a small example here, that demonstrates exactly what you are looking for (unless I've misunderstood your request): http://jsfiddle.net/9N7Z2/188/

There are a few issues with that method of loading javascript dynamically. When it comes to the very basal frameworks, like jQuery, you actually probably want to load them statically, because otherwise, you would have to write a whole JavaScript loading framework...

You could use some of the existing JavaScript loaders, or write your own by watching for window.jQuery to get defined.

// Immediately-invoked function expression
(function() {
    // Load the script
    var script = document.createElement("SCRIPT");
    script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';
    script.type = 'text/javascript';
    script.onload = function() {
        var $ = window.jQuery;
        // Use $ here...
    };
    document.getElementsByTagName("head")[0].appendChild(script);
})();

Just remember that if you need to support really old browsers, like IE8, load event handlers do not execute. In that case, you would need to poll for the existance of window.jQuery using repeated window.setTimeout. There is a working JSFiddle with that method here: http://jsfiddle.net/9N7Z2/3/

There are lots of people who have already done what you need to do. Check out some of the existing JavaScript Loader frameworks, like:

Android ListView selected item stay highlighted

*please be sure there is no Ripple at your root layout of list view container

add this line to your list view

android:listSelector="@drawable/background_listview"

here is the "background_listview.xml" file

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/white_background" android:state_pressed="true" />
<item android:drawable="@color/primary_color" android:state_focused="false" /></selector>

the colors that used in the background_listview.xml file :

<color name="primary_color">#cc7e00</color>
<color name="white_background">#ffffffff</color>

after these

(clicked item contain orange color until you click another item)

How do you see recent SVN log entries?

limit option, e.g.:

svn log --limit 4

svn log -l 4

Only the last 4 entries

To show a new Form on click of a button in C#

private void ButtonClick(object sender, System.EventArgs e)
{
    MyForm form = new MyForm();
    form.Show(); // or form.ShowDialog(this);
}

Selenium -- How to wait until page is completely loaded

3 answers, which you can combine:

  1. Set implicit wait immediately after creating the web driver instance:

    _ = driver.Manage().Timeouts().ImplicitWait;

    This will try to wait until the page is fully loaded on every page navigation or page reload.

  2. After page navigation, call JavaScript return document.readyState until "complete" is returned. The web driver instance can serve as JavaScript executor. Sample code:

    C#

    new WebDriverWait(driver, MyDefaultTimeout).Until(
    d => ((IJavaScriptExecutor) d).ExecuteScript("return document.readyState").Equals("complete"));
    

    Java

    new WebDriverWait(firefoxDriver, pageLoadTimeout).until(
          webDriver -> ((JavascriptExecutor) webDriver).executeScript("return document.readyState").equals("complete"));
    
  3. Check if the URL matches the pattern you expect.

How to set back button text in Swift

I do not know where you have used your methods that you put on your question but I could get the desired result if I use, on my ViewController class (in which I want to change the back button), on viewDidLoad() function, the following line:

self.navigationController?.navigationBar.backItem?.title = "Anything Else"

The result will be:

Before

enter image description here

After

enter image description here

How to set default Checked in checkbox ReactJS?

In the React rendering lifecycle, the value attribute on form elements will override the value in the DOM. With an uncontrolled component, you often want React to specify the initial value, but leave subsequent updates uncontrolled. To handle this case, you can specify a defaultValue or defaultChecked attribute instead of value.

        <input
          type="checkbox"
          defaultChecked={true}
        />

Or

React.createElement('input',{type: 'checkbox', defaultChecked: true});

Please checkout more details regarding defaultChecked for checkbox below: https://reactjs.org/docs/uncontrolled-components.html#default-values

A non well formed numeric value encountered

Because you are passing a string as the second argument to the date function, which should be an integer.

string date ( string $format [, int $timestamp = time() ] )

Try strtotime which will Parse about any English textual datetime description into a Unix timestamp (integer):

date("d", strtotime($_GET['start_date']));

Netbeans - class does not have a main method

My situation was different I believe because non of the above solutions di work for me. Let me share my situation.

  1. I am importing an existing project (NewProject->Java->Import Existing Projects)
  2. I name the project to xyz. The 'main' function exists in Main.class.
  3. I try to run the code I modified in the main function but the error pops out. I tried the shift_f6, specifically rebuild. Nothing works.

    Solution: I took the project properties and saw the 'Source Package Folder' mappings in the Sources branch was blank. I mapped it and voila it worked.

Now anyone might think that was very silly of me. Although I am new to Java and Netbeans this is not the first time I am importing sample projects and I saw all of them had the properties similar. The only difference I saw was that the main class was not having the name as the project which I believe is a java convention. I am using JDK7u51 (latest till date), is it causing the issue? I have no idea. But I am happy the project is running fine now.

Serializing PHP object to JSON

Since your object type is custom, I would tend to agree with your solution - break it down into smaller segments using an encoding method (like JSON or serializing the content), and on the other end have corresponding code to re-construct the object.

AWK: Access captured group from line pattern

This is something I need all the time so I created a bash function for it. It's based on glenn jackman's answer.

Definition

Add this to your .bash_profile etc.

function regex { gawk 'match($0,/'$1'/, ary) {print ary['${2:-'0'}']}'; }

Usage

Capture regex for each line in file

$ cat filename | regex '.*'

Capture 1st regex capture group for each line in file

$ cat filename | regex '(.*)' 1

How to get all possible combinations of a list’s elements?

This is an approach that can be easily transfered to all programming languages supporting recursion (no itertools, no yield, no list comprehension):

def combs(a):
    if len(a) == 0:
        return [[]]
    cs = []
    for c in combs(a[1:]):
        cs += [c, c+[a[0]]]
    return cs

>>> combs([1,2,3,4,5])
[[], [1], [2], [2, 1], [3], [3, 1], [3, 2], ..., [5, 4, 3, 2, 1]]

Rendering HTML in a WebView with custom CSS

Is it possible to have all the content rendered in-page, in a given div? You could then reset the css based on the id, and work on from there.

Say you give your div id="ocon"

In your css, have a definition like:

#ocon *{background:none;padding:0;etc,etc,}

and you can set values to clear all css from applying to the content. After that, you can just use

#ocon ul{}

or whatever, further down the stylesheet, to apply new styles to the content.

How to turn off magic quotes on shared hosting?

As per the manual you can often install a custom php.ini on shared hosting, where mod_php isn't used and the php_value directive thus leads to an error. For suexec/FastCGI setups it is quite common to have a per-webspace php.ini in any case.

--

I don't think O (uppercase letter o) is a valid value to set an ini flag. You need to use a true/false, 1/0, or "on"/"off" value.

ini_set( 'magic_quotes_gpc', 0 );   // doesn't work

EDIT

After checking the list of ini settings, I see that magic_quotes_gpc is a PHP_INI_PERDIR setting (after 4.2.3), which means you can't change it with ini_set() (only PHP_INI_ALL settings can be changed with ini_set())

What this means is you have to use an .htaccess file to do this - OR - implement a script to reverse the effects of magic quotes. Something like this

if ( in_array( strtolower( ini_get( 'magic_quotes_gpc' ) ), array( '1', 'on' ) ) )
{
    $_POST = array_map( 'stripslashes', $_POST );
    $_GET = array_map( 'stripslashes', $_GET );
    $_COOKIE = array_map( 'stripslashes', $_COOKIE );
}

Adding elements to a collection during iteration

public static void main(String[] args)
{
    // This array list simulates source of your candidates for processing
    ArrayList<String> source = new ArrayList<String>();
    // This is the list where you actually keep all unprocessed candidates
    LinkedList<String> list = new LinkedList<String>();

    // Here we add few elements into our simulated source of candidates
    // just to have something to work with
    source.add("first element");
    source.add("second element");
    source.add("third element");
    source.add("fourth element");
    source.add("The Fifth Element"); // aka Milla Jovovich

    // Add first candidate for processing into our main list
    list.addLast(source.get(0));

    // This is just here so we don't have to have helper index variable
    // to go through source elements
    source.remove(0);

    // We will do this until there are no more candidates for processing
    while(!list.isEmpty())
    {
        // This is how we get next element for processing from our list
        // of candidates. Here our candidate is String, in your case it
        // will be whatever you work with.
        String element = list.pollFirst();
        // This is where we process the element, just print it out in this case
        System.out.println(element);

        // This is simulation of process of adding new candidates for processing
        // into our list during this iteration.
        if(source.size() > 0) // When simulated source of candidates dries out, we stop
        {
            // Here you will somehow get your new candidate for processing
            // In this case we just get it from our simulation source of candidates.
            String newCandidate = source.get(0);
            // This is the way to add new elements to your list of candidates for processing
            list.addLast(newCandidate);
            // In this example we add one candidate per while loop iteration and 
            // zero candidates when source list dries out. In real life you may happen
            // to add more than one candidate here:
            // list.addLast(newCandidate2);
            // list.addLast(newCandidate3);
            // etc.

            // This is here so we don't have to use helper index variable for iteration
            // through source.
            source.remove(0);
        }
    }
}

Best font for coding

Funny, I was just researching this yesterday!

I personally use Monaco 10 or 11 for the Mac, but a good cross platform font would have to be Droid Sans Mono: http://damieng.com/blog/2007/11/14/droid-sans-mono-great-coding-font Or DejaVu sans mono is another great one (goes under a lot of different names, will be Menlo on SNow leopard and is really just a repackaged Prima/Vera) check it out here: Prima/Vera... Check it out here: http://dejavu-fonts.org/wiki/index.php?title=Download

Adding CSRFToken to Ajax request

The answer above didn't work for me.

I added the following code before my ajax request:

function getCookie(name) {
                var cookieValue = null;
                if (document.cookie && document.cookie != '') {
                    var cookies = document.cookie.split(';');
                    for (var i = 0; i < cookies.length; i++) {
                        var cookie = jQuery.trim(cookies[i]);
                        // Does this cookie string begin with the name we want?
                        if (cookie.substring(0, name.length + 1) == (name + '=')) {
                            cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                            break;
                        }
                    }
                }
                return cookieValue;
            }
            var csrftoken = getCookie('csrftoken');

            function csrfSafeMethod(method) {
                // these HTTP methods do not require CSRF protection
                return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
            }

            $.ajaxSetup({
                beforeSend: function(xhr, settings) {
                    if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                        xhr.setRequestHeader("X-CSRFToken", csrftoken);
                    }
                }
            });

            $.ajax({
                     type: 'POST',
                     url: '/url/',
            });

Allow scroll but hide scrollbar

Try this:

HTML:

<div id="container">
    <div id="content">
        // Content here
    </div>
</div>

CSS:

#container{
    height: 100%;
    width: 100%;
    overflow: hidden;
}

#content{
    width: 100%;
    height: 99%;
    overflow: auto;
    padding-right: 15px;
}

html, body{
    height: 99%;
    overflow:hidden;
}

JSFiddle Demo

Tested on FF and Safari.

Unable to ping vmware guest from another vmware guest

On both Operation Systems, must turnoff firewall. I using MS SERVER 2012 R2 & MS WIN-7 as a client. First of all call "RUN BOX" window logo button+ R, once RUN box appeared type "firewall.cpl" at Window Firewall setting you will see "Turn Window Firewall On or Off" like this you click it & chose "turn off window firewall" on both Private and Public Setting then OK. Ping again on guests OS. GOOD-LUCK Aungkokokhant

Docker error : no space left on device

In my case installation of ubuntu-server 18.04.1 [for some weird reason] created an LVM logical volume with just 4GBs in size instead of 750GBs. Therefore when pulling images i would get this "no space left on device" error. The fix is simple:

lvextend -l 100%FREE /dev/mapper/ubuntu--vg-ubuntu--lv
resize2fs /dev/mapper/ubuntu--vg-ubuntu--lv

Embedding DLLs in a compiled executable

The excerpt by Jeffrey Richter is very good. In short, add the library's as embedded resources and add a callback before anything else. Here is a version of the code (found in the comments of his page) that I put at the start of Main method for a console app (just make sure that any calls that use the library's are in a different method to Main).

AppDomain.CurrentDomain.AssemblyResolve += (sender, bargs) =>
        {
            String dllName = new AssemblyName(bargs.Name).Name + ".dll";
            var assem = Assembly.GetExecutingAssembly();
            String resourceName = assem.GetManifestResourceNames().FirstOrDefault(rn => rn.EndsWith(dllName));
            if (resourceName == null) return null; // Not found, maybe another handler will find it
            using (var stream = assem.GetManifestResourceStream(resourceName))
            {
                Byte[] assemblyData = new Byte[stream.Length];
                stream.Read(assemblyData, 0, assemblyData.Length);
                return Assembly.Load(assemblyData);
            }
        };

Connect over ssh using a .pem file

You can connect to a AWS ec-2 instance using the following commands.

chmod 400 mykey.pem

ssh -i mykey.pem username@your-ip

by default the machine name usually be like ubuntu since usually ubuntu machine is used as a server so the following command will work in that case.

ssh -i mykey.pem ubuntu@your-ip

Java string replace and the NUL (NULL, ASCII 0) character?

Should be probably changed to

firstName = firstName.trim().replaceAll("\\.", "");

Comment out HTML and PHP together

You can also use this as a comment:

<?php
    /* get_sidebar(); */

?>

How to get the size of the current screen in WPF?

As far as I know there is no native WPF function to get dimensions of the current monitor. Instead you could PInvoke native multiple display monitors functions, wrap them in managed class and expose all properties you need to consume them from XAML.

Test a weekly cron job

None of these answers fit my specific situation, which was that I wanted to run one specific cron job, just once, and run it immediately.

I'm on a Ubuntu server, and I use cPanel to setup my cron jobs.

I simply wrote down my current settings, and then edited them to be one minute from now. When I fixed another bug, I just edited it again to one minute from now. And when I was all done, I just reset the settings back to how they were before.

Example: It's 4:34pm right now, so I put 35 16 * * *, for it to run at 16:35.

It worked like a charm, and the most I ever had to wait was a little less than one minute.

I thought this was a better option than some of the other answers because I didn't want to run all of my weekly crons, and I didn't want the job to run every minute. It takes me a few minutes to fix whatever the issues were before I'm ready to test it again. Hopefully this helps someone.

How do I change the text of a span element using JavaScript?

For this span

<span id="name">sdfsdf</span>

You can go like this :-

$("name").firstChild.nodeValue = "Hello" + "World";

How to run a script as root on Mac OS X?

Or you can access root terminal by typing sudo -s

MySQL WHERE: how to write "!=" or "not equals"?

You may be using old version of Mysql but surely you can use

 DELETE FROM konta WHERE taken <> ''

But there are many other options available. You can try the following ones

DELETE * from konta WHERE strcmp(taken, '') <> 0;

DELETE * from konta where NOT (taken = '');

Convert Java string to Time, NOT Date

You might consider Joda Time or Java 8, which has a type called LocalTime specifically for a time of day without a date component.

Example code in Joda-Time 2.7/Java 8.

LocalTime t = LocalTime.parse( "17:40" ) ;

Why am I getting AttributeError: Object has no attribute

I got this error for multi-threading scenario (specifically when dealing with ZMQ). It turned out that socket was still being connected on one thread while another thread already started sending data. The events that occured due to another thread tried to access variables that weren't created yet. If your scenario involves multi-threading and if things work if you add bit of delay then you might have similar issue.

Local storage in Angular 2

You can also consider using library maintained by me: ngx-store (npm i ngx-store)

It makes working with localStorage, sessionStorage and cookies incredibly easy. There are a few supported methods to manipulate the data:

1) Decorator:

export class SomeComponent {
  @LocalStorage() items: Array<string> = [];

  addItem(item: string) {
    this.items.push(item);
    console.log('current items:', this.items);
    // and that's all: parsing and saving is made by the lib in the background 
  }
}

Variables stored by decorators can be also shared across different classes - there is also @TempStorage() (with an alias of @SharedStorage())) decorator designed for it.

2) Simple service methods:

export class SomeComponent {
  constructor(localStorageService: LocalStorageService) {}

  public saveSettings(settings: SettingsInterface) {
    this.localStorageService.set('settings', settings);
  }

  public clearStorage() {
    this.localStorageService.utility
      .forEach((value, key) => console.log('clearing ', key));
    this.localStorageService.clear();
  }
}

3) Builder pattern:

interface ModuleSettings {
    viewType?: string;
    notificationsCount: number;
    displayName: string;
}

class ModuleService {
    constructor(public localStorageService: LocalStorageService) {}

    public get settings(): NgxResource<ModuleSettings> {
        return this.localStorageService
            .load(`userSettings`)
            .setPath(`modules`)
            .setDefaultValue({}) // we have to set {} as default value, because numeric `moduleId` would create an array 
            .appendPath(this.moduleId)
            .setDefaultValue({});
    }

    public saveModuleSettings(settings: ModuleSettings) {
        this.settings.save(settings);
    }

    public updateModuleSettings(settings: Partial<ModuleSettings>) {
        this.settings.update(settings);
    }
}

Another important thing is you can listen for (every) storage changes, e.g. (the code below uses RxJS v5 syntax):

this.localStorageService.observe()
  .filter(event => !event.isInternal)
  .subscribe((event) => {
    // events here are equal like would be in:
    // window.addEventListener('storage', (event) => {});
    // excluding sessionStorage events
    // and event.type will be set to 'localStorage' (instead of 'storage')
  });

WebStorageService.observe() returns a regular Observable, so you can zip, filter, bounce them etc.

I'm always open to hearing suggestions and questions helping me to improve this library and its documentation.

Undo a Git merge that hasn't been pushed yet

Assuming your local master was not ahead of origin/master, you should be able to do

git reset --hard origin/master

Then your local master branch should look identical to origin/master.

Pandas groupby month and year

You can also do it by creating a string column with the year and month as follows:

df['date'] = df.index
df['year-month'] = df['date'].apply(lambda x: str(x.year) + ' ' + str(x.month))
grouped = df.groupby('year-month')

However this doesn't preserve the order when you loop over the groups, e.g.

for name, group in grouped:
    print(name)

Will give:

2007 11
2007 12
2008 1
2008 10
2008 11
2008 12
2008 2
2008 3
2008 4
2008 5
2008 6
2008 7
2008 8
2008 9
2009 1
2009 10

So then, if you want to preserve the order, you must do as suggested by @Q-man above:

grouped = df.groupby([df.index.year, df.index.month])

This will preserve the order in the above loop:

(2007, 11)
(2007, 12)
(2008, 1)
(2008, 2)
(2008, 3)
(2008, 4)
(2008, 5)
(2008, 6)
(2008, 7)
(2008, 8)
(2008, 9)
(2008, 10)

Creating a dynamic choice field

You can declare the field as a first-class attribute of your form and just set choices dynamically:

class WaypointForm(forms.Form):
    waypoints = forms.ChoiceField(choices=[])

    def __init__(self, user, *args, **kwargs):
        super().__init__(*args, **kwargs)
        waypoint_choices = [(o.id, str(o)) for o in Waypoint.objects.filter(user=user)]
        self.fields['waypoints'].choices = waypoint_choices

You can also use a ModelChoiceField and set the queryset on init in a similar manner.

How to make a char string from a C macro's value?

#include <stdio.h>

#define QUOTEME(x) #x

#ifndef TEST_FUN
#  define TEST_FUN func_name
#  define TEST_FUN_NAME QUOTEME(TEST_FUN)
#endif

int main(void)
{
    puts(TEST_FUN_NAME);
    return 0;
}

Reference: Wikipedia's C preprocessor page

NGINX to reverse proxy websockets AND enable SSL (wss://)?

Using nginx/1.14.0

i have a websocket-server running on port 8097 and users connect from to wss on port 8098, nginx just decrypts the content and forwards it to the websocket server

So i have this config file (in my case /etc/nginx/conf.d/default.conf)

server {
    listen   8098;
        ssl on;
        ssl_certificate      /etc/ssl/certs/domain.crt;
        ssl_certificate_key  /root/domain.key;
    location / {

        proxy_pass http://hostname:8097;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_read_timeout 86400;

    }
}

C non-blocking keyboard input

If you are happy just catching Control-C, it's a done deal. If you really want non-blocking I/O but you don't want the curses library, another alternative is to move lock, stock, and barrel to the AT&T sfio library. It's nice library patterned on C stdio but more flexible, thread-safe, and performs better. (sfio stands for safe, fast I/O.)

How to use Class<T> in Java?

Just use the beef class:

public <T> T beefmarshal( Class<beef> beefClass, InputBeef inputBeef )
     throws JAXBException {
     String packageName = docClass.getPackage().getBeef();
     JAXBContext beef = JAXBContext.newInstance( packageName );
     Unmarshaller u = beef.createBeef();
     JAXBElement<T> doc = (JAXBElement<T>)u.beefmarshal( inputBeef );
     return doc.getBeef();
}

How to add RSA key to authorized_keys file?

>ssh user@serverip -p portnumber 
>sudo bash (if user does not have bash shell else skip this line)
>cd /home/user/.ssh
>echo ssh_rsa...this is the key >> authorized_keys

center a row using Bootstrap 3

I use text-align-center in a row like this

<div class="row tac">
    <h1>Centered content</h1>
</div>

<style>
 .tac { text-align: center}
</style>

How do you add an image?

In order to add attributes, XSL wants

<xsl:element name="img">
     (attributes)
</xsl:element>

instead of just

<img>
     (attributes)
</img>

Although, yes, if you're just copying the element as-is, you don't need any of that.

Get selected key/value of a combo box using jQuery

This works:

<select name="foo" id="foo">
<option value="1">a</option>
<option value="2">b</option>
<option value="3">c</option>
</select>
<input type="button" id="button" value="Button" />

$('#button').click(function() {
    alert($('#foo option:selected').text());
    alert($('#foo option:selected').val());
});

Python NoneType object is not callable (beginner)

Why does it give me that error?

Because your first parameter you pass to the loop function is None but your function is expecting an callable object, which None object isn't.

Therefore you have to pass the callable-object which is in your case the hi function object.

def hi():     
  print 'hi'

def loop(f, n):         #f repeats n times
  if n<=0:
    return
  else:
    f()             
    loop(f, n-1)    

loop(hi, 5)

Get week day name from a given month, day and year individually in SQL Server

select to_char(sysdate,'DAY') from dual; It's work try it

Service has zero application (non-infrastructure) endpoints

I ran Visual Studio in Administrator mode and it worked for me :) Also, ensure that the app.config file which you are using for writing WCF configuration must be in the project where "ServiceHost" class is used, and not in actual WCF service project.

Safely limiting Ansible playbooks to a single machine?

To expand on joemailer's answer, if you want to have the pattern-matching ability to match any subset of remote machines (just as the ansible command does), but still want to make it very difficult to accidentally run the playbook on all machines, this is what I've come up with:

Same playbook as the in other answer:

# file: user.yml  (playbook)
---
- hosts: '{{ target }}'
  user: ...

Let's have the following hosts:

imac-10.local
imac-11.local
imac-22.local

Now, to run the command on all devices, you have to explicty set the target variable to "all"

ansible-playbook user.yml --extra-vars "target=all"

And to limit it down to a specific pattern, you can set target=pattern_here

or, alternatively, you can leave target=all and append the --limit argument, eg:

--limit imac-1*

ie. ansible-playbook user.yml --extra-vars "target=all" --limit imac-1* --list-hosts

which results in:

playbook: user.yml

  play #1 (office): host count=2
    imac-10.local
    imac-11.local

Error: Can't set headers after they are sent to the client

In my case it happens due to multiple callbacks. I have called next() method multiple time during the code

.trim() in JavaScript not working in IE

Add the following code to add trim functionality to the string.

if(typeof String.prototype.trim !== 'function') {
  String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, ''); 
  }
}

Add a column to existing table and uniquely number them on MS SQL Server

for UNIQUEIDENTIFIER datatype in sql server try this

Alter table table_name
add ID UNIQUEIDENTIFIER not null unique default(newid())

If you want to create primary key out of that column use this

ALTER TABLE table_name
ADD CONSTRAINT PK_name PRIMARY KEY (ID);

How to write a UTF-8 file with Java?

we can write the UTF-8 encoded file with java using use PrintWriter to write UTF-8 encoded xml

Or Click here

PrintWriter out1 = new PrintWriter(new File("C:\\abc.xml"), "UTF-8");

How to echo or print an array in PHP?

foreach($results['data'] as $result) {
    echo $result['type'], '<br />';
}

or echo $results['data'][1]['type'];

Python - PIP install trouble shooting - PermissionError: [WinError 5] Access is denied

For those who run into this issue and running the command prompt as administrator does not work this worked for me:

Since I had already tried a first time without running the cmd prompt as admin, in my c:\Users\"USER"\AppData\Local\Temp folder I found it was trying to run files from the same pip-u2e7e0ad-uninstall folder. Deleting this folder from the Temp folder and retrying the installation fixed the issue for me.

Passing an Array as Arguments, not an Array, in PHP

For sake of completeness, as of PHP 5.1 this works, too:

<?php
function title($title, $name) {
    return sprintf("%s. %s\r\n", $title, $name);
}
$function = new ReflectionFunction('title');
$myArray = array('Dr', 'Phil');
echo $function->invokeArgs($myArray);  // prints "Dr. Phil"
?>

See: http://php.net/reflectionfunction.invokeargs

For methods you use ReflectionMethod::invokeArgs instead and pass the object as first parameter.

Getting a random value from a JavaScript array

This is similar to, but more general than, @Jacob Relkin's solution:

This is ES2015:

const randomChoice = arr => {
    const randIndex = Math.floor(Math.random() * arr.length);
    return arr[randIndex];
};

The code works by selecting a random number between 0 and the length of the array, then returning the item at that index.

Winforms TableLayoutPanel adding rows programmatically

I just did this last week. Set the GrowStyle on the TableLayoutPanel to AddRows or AddColumns, then your code should work:

// Adds "myControl" to the first column of each row
myTableLayoutPanel.Controls.Add(myControl1, 0 /* Column Index */, 0 /* Row index */);
myTableLayoutPanel.Controls.Add(myControl2, 0 /* Column Index */, 1 /* Row index */);
myTableLayoutPanel.Controls.Add(myControl3, 0 /* Column Index */, 2 /* Row index */);

Here is some working code that seems similar to what you are doing:

    private Int32 tlpRowCount = 0;

    private void BindAddress()
    {
        Addlabel(Addresses.Street);
        if (!String.IsNullOrEmpty(Addresses.Street2))
        {
            Addlabel(Addresses.Street2);
        }
        Addlabel(Addresses.CityStateZip);
        if (!String.IsNullOrEmpty(Account.Country))
        {
            Addlabel(Address.Country);
        }
        Addlabel(String.Empty); // Notice the empty label...
    }

    private void Addlabel(String text)
    {            
        label = new Label();
        label.Dock = DockStyle.Fill;
        label.Text = text;
        label.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
        tlpAddress.Controls.Add(label, 1, tlpRowCount);
        tlpRowCount++;
    }

The TableLayoutPanel always gives me fits with size. In my example above, I'm filing an address card that might grow or shrink depending on the account having an address line two, or a country. Because the last row, or column, of the table layout panel will stretch, I throw the empty label in there to force a new empty row, then everything lines up nicely.

Here is the designer code so you can see the table I start with:

        //
        // tlpAddress
        // 
        this.tlpAddress.AutoSize = true;
        this.tlpAddress.BackColor = System.Drawing.Color.Transparent;
        this.tlpAddress.ColumnCount = 2;
        this.tlpAddress.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 25F));
        this.tlpAddress.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
        this.tlpAddress.Controls.Add(this.pictureBox1, 0, 0);
        this.tlpAddress.Dock = System.Windows.Forms.DockStyle.Fill;
        this.tlpAddress.Location = new System.Drawing.Point(0, 0);
        this.tlpAddress.Name = "tlpAddress";
        this.tlpAddress.Padding = new System.Windows.Forms.Padding(3);
        this.tlpAddress.RowCount = 2;
        this.tlpAddress.RowStyles.Add(new System.Windows.Forms.RowStyle());
        this.tlpAddress.RowStyles.Add(new System.Windows.Forms.RowStyle());
        this.tlpAddress.Size = new System.Drawing.Size(220, 95);
        this.tlpAddress.TabIndex = 0;

The requested operation cannot be performed on a file with a user-mapped section open

I fixed the issue as below:

  1. Restart machine
  2. Delete bin and obj folders from respective project path.
  3. Open visual studio
  4. Clean and build the solution.

There you go issue resolved:)

Reflection generic get field value

You are calling get with the wrong argument.

It should be:

Object value = field.get(object);

How do I know if jQuery has an Ajax request pending?

The $.ajax() function returns a XMLHttpRequest object. Store that in a variable that's accessible from the Submit button's "OnClick" event. When a submit click is processed check to see if the XMLHttpRequest variable is:

1) null, meaning that no request has been sent yet

2) that the readyState value is 4 (Loaded). This means that the request has been sent and returned successfully.

In either of those cases, return true and allow the submit to continue. Otherwise return false to block the submit and give the user some indication of why their submit didn't work. :)

Oracle: SQL query that returns rows with only numeric values

What about 1.1E10, +1, -0, etc? Parsing all possible numbers is trickier than many people think. If you want to include as many numbers are possible you should use the to_number function in a PL/SQL function. From http://www.oracle-developer.net/content/utilities/is_number.sql:

CREATE OR REPLACE FUNCTION is_number (str_in IN VARCHAR2) RETURN NUMBER IS
   n NUMBER;
BEGIN
   n := TO_NUMBER(str_in);
   RETURN 1;
EXCEPTION
   WHEN VALUE_ERROR THEN
      RETURN 0;
END;
/

How to install mod_ssl for Apache httpd?

I used:

sudo yum install mod24_ssl

and it worked in my Amazon Linux AMI.

Build project into a JAR automatically in Eclipse

This is possible by defining a custom Builder in eclipse (see the link in Peter's answer). However, unless your project is very small, it may slow down your workspace unacceptably. Autobuild for class files happens incrementally, i.e. only those classes affected by a change are recompiled, but the JAR file will have to be rebuilt and copied completely, every time you save a change.

How can I solve a connection pool problem between ASP.NET and SQL Server?

This is mainly due to the connection not been closed in the application. Use "MinPoolSize" and "MaxPoolSize" in the connection string.

Is there a better way to refresh WebView?

Refreshing current webview's URL is not a common usage.
I used this in such a scenario: When user goes to another activity and user come back to webview's activity I reload current URL like this:

public class MyWebviewActivity extends Activity {
    WebView mWebView;
    ....
    ....
    ....
    @Override
    public void onRestart() {
            String url = mWebView.getUrl();
            String postData = MyUtility.getOptionsDataForPOSTURL(mContext);
            mWebView.postUrl(url, EncodingUtils.getBytes(postData, "BASE64"));
    }
}

You can also use WebView's reload() function. But note that if you loaded the webview with postUrl(), then mWebView.reload(); doesn't work. This also works

String webUrl = webView.getUrl();
mWebView.loadUrl(webUrl);

How to comment multiple lines in Visual Studio Code?

All the key board shorcuts for VS code can be found in the link : Link

  • Add a Line comment Ctrl+K Ctrl+C
  • Remove a line comment Ctrl+K Ctrl+U
  • More shortcut Ctrl+/

Regex to validate password strength

For PHP, this works fine!

 if(preg_match("/^(?=(?:[^A-Z]*[A-Z]){2})(?=(?:[^0-9]*[0-9]){2}).{8,}$/", 
 'CaSu4Li8')){
    return true;
 }else{
    return fasle;
 }

in this case the result is true

Thsks for @ridgerunner

Detecting when the 'back' button is pressed on a navbar

7ynk3r's answer was really close to what I did use in the end but it needed some tweaks:

- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item {

    UIViewController *topViewController = self.topViewController;
    BOOL wasBackButtonClicked = topViewController.navigationItem == item;

    if (wasBackButtonClicked) {
        if ([topViewController respondsToSelector:@selector(navBackButtonPressed)]) {
            // if user did press back on the view controller where you handle the navBackButtonPressed
            [topViewController performSelector:@selector(navBackButtonPressed)];
            return NO;
        } else {
            // if user did press back but you are not on the view controller that can handle the navBackButtonPressed
            [self popViewControllerAnimated:YES];
            return YES;
        }
    } else {
        // when you call popViewController programmatically you do not want to pop it twice
        return YES;
    }
}

Find all files with name containing string

An alternative to the many solutions already provided is making use of the glob **. When you use bash with the option globstar (shopt -s globstar) or you make use of zsh, you can just use the glob ** for this.

**/bar

does a recursive directory search for files named bar (potentially including the file bar in the current directory). Remark that this cannot be combined with other forms of globbing within the same path segment; in that case, the * operators revert to their usual effect.

Note that there is a subtle difference between zsh and bash here. While bash will traverse soft-links to directories, zsh will not. For this you have to use the glob ***/ in zsh.

Angular 2 / 4 / 5 not working in IE11

In polyfills.ts

import 'core-js/es6/symbol';
import 'core-js/es6/object';
import 'core-js/es6/function';
import 'core-js/es6/parse-int';
import 'core-js/es6/parse-float';
import 'core-js/es6/number';
import 'core-js/es6/math';
import 'core-js/es6/string';
import 'core-js/es6/date';

import 'core-js/es6/array';
import 'core-js/es7/array';

import 'core-js/es6/regexp';
import 'core-js/es6/map';
import 'core-js/es6/weak-map';
import 'core-js/es6/weak-set';
import 'core-js/es6/set';

/** IE10 and IE11 requires the following for NgClass support on SVG elements */
 import 'classlist.js';  // Run `npm install --save classlist.js`.

/** Evergreen browsers require these. **/
import 'core-js/es6/reflect';
import 'core-js/es7/reflect';

/**
 * Required to support Web Animations `@angular/animation`.
 * Needed for: All but Chrome, Firefox and Opera. http://caniuse.com/#feat=web-animation
 **/
import 'web-animations-js';  // Run `npm install --save web-animations-js`.

Pass multiple parameters to rest API - Spring

Multiple parameters can be given like below,

    @RequestMapping(value = "/mno/{objectKey}", method = RequestMethod.GET, produces = "application/json")
    public List<String> getBook(HttpServletRequest httpServletRequest, @PathVariable(name = "objectKey") String objectKey
      , @RequestParam(value = "id", defaultValue = "false")String id,@RequestParam(value = "name", defaultValue = "false") String name) throws Exception {
               //logic
}

Why am I seeing "TypeError: string indices must be integers"?

TypeError for Slice Notation str[a:b]

tl;dr: use a colon : instead of a comma in between the two indices a and b in str[a:b]


When working with strings and slice notation (a common sequence operation), it can happen that a TypeError is raised, pointing out that the indices must be integers, even if they obviously are.

Example

>>> my_string = "hello world"
>>> my_string[0,5]
TypeError: string indices must be integers

We obviously passed two integers for the indices to the slice notation, right? So what is the problem here?

This error can be very frustrating - especially at the beginning of learning Python - because the error message is a little bit misleading.

Explanation

We implicitly passed a tuple of two integers (0 and 5) to the slice notation when we called my_string[0,5] because 0,5 (even without the parentheses) evaluates to the same tuple as (0,5) would do.

A comma , is actually enough for Python to evaluate something as a tuple:

>>> my_variable = 0,
>>> type(my_variable)
<class 'tuple'>

So what we did there, this time explicitly:

>>> my_string = "hello world"
>>> my_tuple = 0, 5
>>> my_string[my_tuple]
TypeError: string indices must be integers

Now, at least, the error message makes sense.

Solution

We need to replace the comma , with a colon : to separate the two integers correctly:

>>> my_string = "hello world"
>>> my_string[0:5]
'hello'

A clearer and more helpful error message could have been something like:

TypeError: string indices must be integers (not tuple)

A good error message shows the user directly what they did wrong and it would have been more obvious how to solve the problem.

[So the next time when you find yourself responsible for writing an error description message, think of this example and add the reason or other useful information to error message to let you and maybe other people understand what went wrong.]

Lessons learned

  • slice notation uses colons : to separate its indices (and step range, e.g. str[from:to:step])
  • tuples are defined by commas , (e.g. t = 1,)
  • add some information to error messages for users to understand what went wrong

Cheers and happy programming
winklerrr


[I know this question was already answered and this wasn't exactly the question the thread starter asked, but I came here because of the above problem which leads to the same error message. At least it took me quite some time to find that little typo.

So I hope that this will help someone else who stumbled upon the same error and saves them some time finding that tiny mistake.]

Updates were rejected because the tip of your current branch is behind hint: its remote counterpart. Integrate the remote changes (e.g

You need to merge the remote branch into your current branch by running git pull.

If your local branch is already up-to-date, you may also need to run git pull --rebase.

A quick google search also turned up this same question asked by another SO user: Cannot push to GitHub - keeps saying need merge. More details there.

Deprecated Java HttpClient - How hard can it be?

It got deprecated in version 4.3-alpha1 which you use because of the LATEST version specification. If you take a look at the javadoc of the class, it tells you what to use instead: HttpClientBuilder.

In the latest stable version (4.2.3) the DefaultHttpClient is not deprecated yet.

Pylint, PyChecker or PyFlakes?

Well, I am a bit curious, so I just tested the three myself right after asking the question ;-)

Ok, this is not a very serious review, but here is what I can say:

I tried the tools with the default settings (it's important because you can pretty much choose your check rules) on the following script:

#!/usr/local/bin/python
# by Daniel Rosengren modified by e-satis

import sys, time
stdout = sys.stdout

BAILOUT = 16
MAX_ITERATIONS = 1000

class Iterator(object) :

    def __init__(self):

        print 'Rendering...'
        for y in xrange(-39, 39):
            stdout.write('\n')
            for x in xrange(-39, 39):
                if self.mandelbrot(x/40.0, y/40.0) :
                    stdout.write(' ')
                else:
                    stdout.write('*')


    def mandelbrot(self, x, y):
        cr = y - 0.5
        ci = x
        zi = 0.0
        zr = 0.0

        for i in xrange(MAX_ITERATIONS) :
            temp = zr * zi
            zr2 = zr * zr
            zi2 = zi * zi
            zr = zr2 - zi2 + cr
            zi = temp + temp + ci

            if zi2 + zr2 > BAILOUT:
                return i

        return 0

t = time.time()
Iterator()
print '\nPython Elapsed %.02f' % (time.time() - t)

As a result:

  • PyChecker is troublesome because it compiles the module to analyze it. If you don't want your code to run (e.g, it performs a SQL query), that's bad.
  • PyFlakes is supposed to be light. Indeed, it decided that the code was perfect. I am looking for something quite severe so I don't think I'll go for it.
  • PyLint has been very talkative and rated the code 3/10 (OMG, I'm a dirty coder !).

Strong points of PyLint:

  • Very descriptive and accurate report.
  • Detect some code smells. Here it told me to drop my class to write something with functions because the OO approach was useless in this specific case. Something I knew, but never expected a computer to tell me :-p
  • The fully corrected code run faster (no class, no reference binding...).
  • Made by a French team. OK, it's not a plus for everybody, but I like it ;-)

Cons of Pylint:

  • Some rules are really strict. I know that you can change it and that the default is to match PEP8, but is it such a crime to write 'for x in seq'? Apparently yes because you can't write a variable name with less than 3 letters. I will change that.
  • Very very talkative. Be ready to use your eyes.

Corrected script (with lazy doc strings and variable names):

#!/usr/local/bin/python
# by Daniel Rosengren, modified by e-satis
"""
Module doctring
"""


import time
from sys import stdout

BAILOUT = 16
MAX_ITERATIONS = 1000

def mandelbrot(dim_1, dim_2):
    """
    function doc string
    """
    cr1 = dim_1 - 0.5
    ci1 = dim_2
    zi1 = 0.0
    zr1 = 0.0

    for i in xrange(MAX_ITERATIONS) :
        temp = zr1 * zi1
        zr2 = zr1 * zr1
        zi2 = zi1 * zi1
        zr1 = zr2 - zi2 + cr1
        zi1 = temp + temp + ci1

        if zi2 + zr2 > BAILOUT:
            return i

    return 0

def execute() :
    """
    func doc string
    """
    print 'Rendering...'
    for dim_1 in xrange(-39, 39):
        stdout.write('\n')
        for dim_2 in xrange(-39, 39):
            if mandelbrot(dim_1/40.0, dim_2/40.0) :
                stdout.write(' ')
            else:
                stdout.write('*')


START_TIME = time.time()
execute()
print '\nPython Elapsed %.02f' % (time.time() - START_TIME)

Thanks to Rudiger Wolf, I discovered pep8 that does exactly what its name suggests: matching PEP8. It has found several syntax no-nos that Pylint did not. But Pylint found stuff that was not specifically linked to PEP8 but interesting. Both tools are interesting and complementary.

Eventually I will use both since there are really easy to install (via packages or setuptools) and the output text is so easy to chain.

To give you a little idea of their output:

pep8:

./python_mandelbrot.py:4:11: E401 multiple imports on one line
./python_mandelbrot.py:10:1: E302 expected 2 blank lines, found 1
./python_mandelbrot.py:10:23: E203 whitespace before ':'
./python_mandelbrot.py:15:80: E501 line too long (108 characters)
./python_mandelbrot.py:23:1: W291 trailing whitespace
./python_mandelbrot.py:41:5: E301 expected 1 blank line, found 3

Pylint:

************* Module python_mandelbrot
C: 15: Line too long (108/80)
C: 61: Line too long (85/80)
C:  1: Missing docstring
C:  5: Invalid name "stdout" (should match (([A-Z_][A-Z0-9_]*)|(__.*__))$)
C: 10:Iterator: Missing docstring
C: 15:Iterator.__init__: Invalid name "y" (should match [a-z_][a-z0-9_]{2,30}$)
C: 17:Iterator.__init__: Invalid name "x" (should match [a-z_][a-z0-9_]{2,30}$)

[...] and a very long report with useful stats like :

Duplication
-----------

+-------------------------+------+---------+-----------+
|                         |now   |previous |difference |
+=========================+======+=========+===========+
|nb duplicated lines      |0     |0        |=          |
+-------------------------+------+---------+-----------+
|percent duplicated lines |0.000 |0.000    |=          |
+-------------------------+------+---------+-----------+

How to find all links / pages on a website

Check out linkchecker—it will crawl the site (while obeying robots.txt) and generate a report. From there, you can script up a solution for creating the directory tree.

How to create table using select query in SQL Server?

select <column list> into <table name> from <source> where <whereclause>

Push local Git repo to new remote including all branches and tags

This is the most concise way I have found, provided the destination is empty. Switch to an empty folder and then:

# Note the period for cwd >>>>>>>>>>>>>>>>>>>>>>>> v
git clone --bare https://your-source-repo/repo.git .
git push --mirror https://your-destination-repo/repo.git

Substitute https://... for file:///your/repo etc. as appropriate.

make: *** [ ] Error 1 error

From GNU Make error appendix, as you see this is not a Make error but an error coming from gcc.

‘[foo] Error NN’ ‘[foo] signal description’ These errors are not really make errors at all. They mean that a program that make invoked as part of a recipe returned a non-0 error code (‘Error NN’), which make interprets as failure, or it exited in some other abnormal fashion (with a signal of some type). See Errors in Recipes. If no *** is attached to the message, then the subprocess failed but the rule in the makefile was prefixed with the - special character, so make ignored the error.

So in order to attack the problem, the error message from gcc is required. Paste the command in the Makefile directly to the command line and see what gcc says. For more details on Make errors click here.

Add a background image to shape in XML Android

Here is another most easy way to get a custom shape for your image (Image View). It may be helpful for someone. It's just a single line code.

First you need to add a dependency:

dependencies {
    compile 'com.mafstech.libs:mafs-image-shape:1.0.4'   
}

And then just write a line of code like this:

Shaper.shape(context, 
       R.drawable.your_original_image_which_will_be_displayed, 
       R.drawable.shaped_image_your_original_image_will_get_this_images_shape,
       imageView,
       height, 
       weight);   

How to embed a Facebook page's feed into my website

Ahhh, that's super simple, no programming required.

See: https://developers.facebook.com/docs/plugins/page-plugin

You'll want to keep the show stream option turned on. You can adjust width and heigth and a few other things.

Bash mkdir and subfolders

To create multiple sub-folders

mkdir -p parentfolder/{subfolder1,subfolder2,subfolder3}

Can you change a path without reloading the controller in AngularJS?

why not just put the ng-controller one level higher,

<body ng-controller="ProjectController">
    <div ng-view><div>

And don't set controller in the route,

.when('/', { templateUrl: "abc.html" })

it works for me.

How do I put a clear button inside my HTML text input box like the iPhone does?

Check out our jQuery-ClearSearch plugin. It's a configurable jQuery plugin - adapting it to your needs by styling the input field is straightforward. Just use it as follows:

<input class="clearable" type="text" placeholder="search">

<script type="text/javascript">
    $('.clearable').clearSearch();
</script>

? Example: http://jsfiddle.net/wldaunfr/FERw3/

How to handle change of checkbox using jQuery?

get radio value by name

  $('input').on('className', function(event){
        console.log($(this).attr('name'));
        if($(this).attr('name') == "worker")
            {
                resetAll();                 
            }
    });

Passing two command parameters using a WPF binding

This task can also be solved with a different approach. Instead of programming a converter and enlarging the code in the XAML, you can also aggregate the various parameters in the ViewModel. As a result, the ViewModel then has one more property that contains all parameters.

An example of my current application, which also let me deal with the topic. A generic RelayCommand is required: https://stackoverflow.com/a/22286816/7678085

The ViewModelBase is extended here by a command SaveAndClose. The generic type is a named tuple that represents the various parameters.

public ICommand SaveAndCloseCommand => saveAndCloseCommand ??= new RelayCommand<(IBaseModel Item, Window Window)>
    (execute =>
    {
        execute.Item.Save();
        execute.Window?.Close(); // if NULL it isn't closed.
    },
    canExecute =>
    {
        return canExecute.Item?.IsItemValide ?? false;
    });
private ICommand saveAndCloseCommand;

Then it contains a property according to the generic type:

public (IBaseModel Item, Window Window) SaveAndCloseParameter 
{ 
    get => saveAndCloseParameter ; 
    set 
    {
        SetProperty(ref saveAndCloseParameter, value);
    }
}
private (IBaseModel Item, Window Window) saveAndCloseParameter;

The XAML code of the view then looks like this: (Pay attention to the classic click event)

<Button 
    Command="{Binding SaveAndCloseCommand}" 
    CommandParameter="{Binding SaveAndCloseParameter}" 
    Click="ButtonApply_Click" 
    Content="Apply"
    Height="25" Width="100" />
<Button 
    Command="{Binding SaveAndCloseCommand}" 
    CommandParameter="{Binding SaveAndCloseParameter}" 
    Click="ButtonSave_Click" 
    Content="Save"
    Height="25" Width="100" />

and in the code behind of the view, then evaluating the click events, which then set the parameter property.

private void ButtonApply_Click(object sender, RoutedEventArgs e)
{
    computerViewModel.SaveAndCloseParameter = (computerViewModel.Computer, null);
}

private void ButtonSave_Click(object sender, RoutedEventArgs e)
{
    computerViewModel.SaveAndCloseParameter = (computerViewModel.Computer, this);
}

Personally, I think that using the click events is not a break with the MVVM pattern. The program flow control is still located in the area of ??the ViewModel.

How can I initialize an array without knowing it size?

You can't... an array's size is always fixed in Java. Typically instead of using an array, you'd use an implementation of List<T> here - usually ArrayList<T>, but with plenty of other alternatives available.

You can create an array from the list as a final step, of course - or just change the signature of the method to return a List<T> to start with.

How to convert JSONObjects to JSONArray?

Something like this:

JSONObject songs= json.getJSONObject("songs");
Iterator x = songs.keys();
JSONArray jsonArray = new JSONArray();

while (x.hasNext()){
    String key = (String) x.next();
    jsonArray.put(songs.get(key));
}

How do you wait for input on the same Console.WriteLine() line?

As Matt has said, use Console.Write. I would also recommend explicitly flushing the output, however - I believe WriteLine does this automatically, but I'd seen oddities when just using Console.Write and then waiting. So Matt's code becomes:

Console.Write("What is your name? ");
Console.Out.Flush();
var name = Console.ReadLine();

Spring: return @ResponseBody "ResponseEntity<List<JSONObject>>"

Now I return Object. I don't know better solution, but it works.

@RequestMapping(value="", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody ResponseEntity<Object> getAll() {
    List<Entity> entityList = entityManager.findAll();

    List<JSONObject> entities = new ArrayList<JSONObject>();
    for (Entity n : entityList) {
        JSONObject Entity = new JSONObject();
        entity.put("id", n.getId());
        entity.put("address", n.getAddress());
        entities.add(entity);
    }
    return new ResponseEntity<Object>(entities, HttpStatus.OK);
}

Render partial view with dynamic model in Razor view engine and ASP.NET MVC 3

Can also be called as

@Html.Partial("_PartialView", (ModelClass)View.Data)

How do I turn off Oracle password expiration?

To alter the password expiry policy for a certain user profile in Oracle first check which profile the user is using:

select profile from DBA_USERS where username = '<username>';

Then you can change the limit to never expire using:

alter profile <profile_name> limit password_life_time UNLIMITED;

If you want to previously check the limit you may use:

select resource_name,limit from dba_profiles where profile='<profile_name>';

Get screen width and height in Android

Just to update the answer by parag and SpK to align with current SDK backward compatibility from deprecated methods:

int Measuredwidth = 0;  
int Measuredheight = 0;  
Point size = new Point();
WindowManager w = getWindowManager();

if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)    {
    w.getDefaultDisplay().getSize(size);
    Measuredwidth = size.x;
    Measuredheight = size.y; 
}else{
    Display d = w.getDefaultDisplay(); 
    Measuredwidth = d.getWidth(); 
    Measuredheight = d.getHeight(); 
}

Convert a JSON Object to Buffer and Buffer to JSON Object back

You need to stringify the json, not calling toString

var buf = Buffer.from(JSON.stringify(obj));

And for converting string to json obj :

var temp = JSON.parse(buf.toString());

SQL Insert Query Using C#

class Program
{
    static void Main(string[] args)
    {
        string connetionString = null;
        SqlConnection connection;
        SqlCommand command;
        string sql = null;

        connetionString = "Data Source=Server Name;Initial Catalog=DataBaseName;User ID=UserID;Password=Password";
        sql = "INSERT INTO LoanRequest(idLoanRequest,RequestDate,Pickupdate,ReturnDate,EventDescription,LocationOfEvent,ApprovalComments,Quantity,Approved,EquipmentAvailable,ModifyRequest,Equipment,Requester)VALUES('5','2016-1-1','2016-2-2','2016-3-3','DescP','Loca1','Appcoment','2','true','true','true','4','5')";
        connection = new SqlConnection(connetionString);

        try
        {
            connection.Open();
            Console.WriteLine(" Connection Opened ");
            command = new SqlCommand(sql, connection);                
            SqlDataReader dr1 = command.ExecuteReader();         

            connection.Close();
        }
        catch (Exception ex)
        {
            Console.WriteLine("Can not open connection ! ");
        }
    }
}

super() in Java

The super keyword can be used to call the superclass constructor and to refer to a member of the superclass

When you call super() with the right arguments, we actually call the constructor Box, which initializes variables width, height and depth, referred to it by using the values of the corresponding parameters. You only remains to initialize its value added weight. If necessary, you can do now class variables Box as private. Put down in the fields of the Box class private modifier and make sure that you can access them without any problems.

At the superclass can be several overloaded versions constructors, so you can call the method super() with different parameters. The program will perform the constructor that matches the specified arguments.

public class Box {

    int width;
    int height;
    int depth;

    Box(int w, int h, int d) {
        width = w;
        height = h;
        depth = d;
    }

    public static void main(String[] args){
        HeavyBox heavy = new HeavyBox(12, 32, 23, 13);
    }

}

class HeavyBox extends Box {

    int weight;

    HeavyBox(int w, int h, int d, int m) {

        //call the superclass constructor
        super(w, h, d);
        weight = m;
    }

}

Laravel 5 Application Key

This line in your app.php, 'key' => env('APP_KEY', 'SomeRandomString'),, is saying that the key for your application can be found in your .env file on the line APP_KEY.

Basically it tells Laravel to look for the key in the .env file first and if there isn't one there then to use 'SomeRandomString'.

When you use the php artisan key:generate it will generate the new key to your .env file and not the app.php file.

As kotapeter said, your .env will be inside your root Laravel directory and may be hidden; xampp/htdocs/laravel/blog

Difference between Constructor and ngOnInit

Like a lot of other languages, you can initialize variables at the class level, the constructor, or a method. It is up to the developer to decide what is best in their particular case. But below are a list of best practices when it comes to deciding.

Class level variables

Usually, you will declare all your variables here that will be used in the rest of you component. You can initialize them if the value doesn't depend on anything else, or use const keyword to create constants if they will not change.

export class TestClass{
    let varA: string = "hello";
}

Constructor

Normally it's best practice to not do anything in the constructor and just use it for classes that will be injected. Most of the time your constructor should look like this:

   constructor(private http: Http, private customService: CustomService) {}

this will automatically create the class level variables, so you will have access to customService.myMethod() without having to do it manually.

NgOnInit

NgOnit is a lifecycle hook provided by the Angular 2 framework. Your component must implement OnInit in order to use it. This lifecycle hook gets called after the constructor is called and all the variables are initialized. The bulk of your initialization should go here. You will have the certainty that Angular has initialized your component correctly and you can start doing any logic you need in OnInit versus doing things when your component hasn't finished loading properly.

Here is an image detailing the order of what gets called:

enter image description here

https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html

TLDR

If you are using Angular 2 framework and need to interact with certain lifecycle events, use the methods provided by the framework for this to avoid problems.

How to set initial size of std::vector?

std::vector<CustomClass *> whatever(20000);

or:

std::vector<CustomClass *> whatever;
whatever.reserve(20000);

The former sets the actual size of the array -- i.e., makes it a vector of 20000 pointers. The latter leaves the vector empty, but reserves space for 20000 pointers, so you can insert (up to) that many without it having to reallocate.

At least in my experience, it's fairly unusual for either of these to make a huge difference in performance--but either can affect correctness under some circumstances. In particular, as long as no reallocation takes place, iterators into the vector are guaranteed to remain valid, and once you've set the size/reserved space, you're guaranteed there won't be any reallocations as long as you don't increase the size beyond that.

Format date and time in a Windows batch script

This bat file (save as datetimestr.bat) produces the datetime string 3 times: (1) long datetime string with day of week and seconds, (2) short datetime string without them and (3) short version of the code.

@echo off
REM "%date: =0%" replaces spaces with zeros
set d=%date: =0%
REM "set yyyy=%d:~-4%" pulls the last 4 characters
set yyyy=%d:~-4%
set mm=%d:~4,2%
set dd=%d:~7,2%
set dow=%d:~0,3%
set d=%yyyy%-%mm%-%dd%_%dow%

set t=%TIME: =0%
REM "%t::=%" removes semi-colons
REM Instead of above, you could use "%t::=-%" to 
REM replace semi-colons with hyphens (or any 
REM non-special character)
set t=%t::=%
set t=%t:.=%

set datetimestr=%d%_%t%
@echo  Long date time str = %datetimestr%

set d=%d:~0,10%
set t=%t:~0,4%
set datetimestr=%d%_%t%
@echo Short date time str = %datetimestr%


@REM Short version of the code above
set d=%date: =0%
set t=%TIME: =0%
set datetimestr=%d:~-4%-%d:~4,2%-%d:~7,2%_%d:~0,3%_%t:~0,2%%t:~3,2%%t:~6,2%%t:~9,2%
@echo Datetimestr = %datetimestr%

pause

To give proper credit, I merged the concepts from Peter Mortensen (Jun 18 '14 at 21:02) and opello (Aug 25 '11 at 14:27).

You can write this much shorter, but this long version makes reading and understanding the code easy.

Get current domain

Try using this:

$_SERVER['SERVER_NAME']

Or parse :

$_SERVER['REQUEST_URI']

apache_request_headers()

How can I check whether a option already exist in select by JQuery

This evaluates to true if it already exists:

$("#yourSelect option[value='yourValue']").length > 0;

Exact time measurement for performance testing

Stopwatch is fine, but loop the work 10^6 times, then divide by 10^6. You'll get a lot more precision.

@Resource vs @Autowired

With @Resource you can do bean self-injection, it might be needed in order to run all extra logic added by bean post processors like transactional or security related stuff.

With Spring 4.3+ @Autowired is also capable of doing this.

Disable building workspace process in Eclipse

Building workspace is about incremental build of any evolution detected in one of the opened projects in the currently used workspace.

You can also disable it through the menu "Project / Build automatically".

But I would recommend first to check:

  • if a Project Clean all / Build result in the same kind of long wait (after disabling this option)
  • if you have (this time with building automatically activated) some validation options you could disable to see if they have an influence on the global compilation time (Preferences / Validations, or Preferences / XML / ... if you have WTP installed)
  • if a fresh eclipse installation referencing the same workspace (see this eclipse.ini for more) results in the same issue (with building automatically activated)

Note that bug 329657 (open in 2011, in progress in 2014) is about interrupting a (too lengthy) build, instead of cancelling it:

There is an important difference between build interrupt and cancel.

  • When a build is cancelled, it typically handles this by discarding incremental build state and letting the next build be a full rebuild. This can be quite expensive in some projects.
    As a user I think I would rather wait for the 5 second incremental build to finish rather than cancel and result in a 30 second rebuild afterwards.

  • The idea with interrupt is that a builder could more efficiently handle interrupt by saving its intermediate state and resuming on the next invocation.
    In practice this is hard to implement so the most common boundary is when we check for interrupt before/after calling each builder in the chain.

 

Embed HTML5 YouTube video without iframe?

Here is a example of embedding without an iFrame:

_x000D_
_x000D_
<div style="width: 560px; height: 315px; float: none; clear: both; margin: 2px auto;">
  <embed
    src="https://www.youtube.com/embed/J---aiyznGQ?autohide=1&autoplay=1"
    wmode="transparent"
    type="video/mp4"
    width="100%" height="100%"
    allow="autoplay; encrypted-media; picture-in-picture"
    allowfullscreen
    title="Keyboard Cat"
  >
</div>
_x000D_
_x000D_
_x000D_

compare to regular iframe "embed" code from YouTube:

_x000D_
_x000D_
<iframe
  width="560"
  height="315"
  src="https://www.youtube.com/embed/J---aiyznGQ?autoplay=1"
  frameborder="0"
  allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
  allowfullscreen>
</iframe>
_x000D_
_x000D_
_x000D_

and as far as HTML5 goes, use <object> tag like so (corrected):

_x000D_
_x000D_
<object
  style="width: 820px; height: 461.25px; float: none; clear: both; margin: 2px auto;"
  data="http://www.youtube.com/embed/J---aiyznGQ?autoplay=1">
</object>
_x000D_
_x000D_
_x000D_

What is the difference between window, screen, and document in Javascript?

Well, the window is the first thing that gets loaded into the browser. This window object has the majority of the properties like length, innerWidth, innerHeight, name, if it has been closed, its parents, and more.

What about the document object then? The document object is your html, aspx, php, or other document that will be loaded into the browser. The document actually gets loaded inside the window object and has properties available to it like title, URL, cookie, etc. What does this really mean? That means if you want to access a property for the window it is window.property, if it is document it is window.document.property which is also available in short as document.property.

dom

That seems simple enough. But what happens once an IFRAME is introduced?

iframe

Specifying and saving a figure with exact size in pixels

plt.imsave worked for me. You can find the documentation here: https://matplotlib.org/3.2.1/api/_as_gen/matplotlib.pyplot.imsave.html

#file_path = directory address where the image will be stored along with file name and extension
#array = variable where the image is stored. I think for the original post this variable is im_np
plt.imsave(file_path, array)

What are .iml files in Android Studio?

They are project files, that hold the module information and meta data.

Just add *.iml to .gitignore.

In Android Studio: Press CTRL + F9 to rebuild your project. The missing *.iml files will be generated.

Add IIS 7 AppPool Identities as SQL Server Logons

As a side note processes that uses virtual accounts (NT Service\MyService and IIS AppPool\MyAppPool) are still running under the "NETWORK SERVICE" account as this post suggests http://www.adopenstatic.com/cs/blogs/ken/archive/2008/01/29/15759.aspx. The only difference is that these processes are members of the "NT Service\MyService" or "IIS AppPool\MyAppPool" groups (as these are actually groups and not users). This is also the reason why the processes authenticate at the network as the machine the same way NETWORK SERVICE account does.

The way to secure access is not to depend upon this accounts not having NETWORK SERVICE privileges but to grant more permissions specifically to "NT Service\MyService" or "IIS AppPool\MyAppPool" and to remove permissions for "Users" if necessary.

If anyone has more accurate or contradictional information please post.

Setting dynamic scope variables in AngularJs - scope.<some_string>

Just to add into alread given answers, the following worked for me:

HTML:

<div id="div{{$index+1}}" data-ng-show="val{{$index}}">

Where $index is the loop index.

Javascript (where value is the passed parameter to the function and it will be the value of $index, current loop index):

var variable = "val"+value;
if ($scope[variable] === undefined)
{
    $scope[variable] = true;
}else {
    $scope[variable] = !$scope[variable];
}

NoSQL Use Case Scenarios or WHEN to use NoSQL

It really is an "it depends" kinda question. Some general points:

  • NoSQL is typically good for unstructured/"schemaless" data - usually, you don't need to explicitly define your schema up front and can just include new fields without any ceremony
  • NoSQL typically favours a denormalised schema due to no support for JOINs per the RDBMS world. So you would usually have a flattened, denormalized representation of your data.
  • Using NoSQL doesn't mean you could lose data. Different DBs have different strategies. e.g. MongoDB - you can essentially choose what level to trade off performance vs potential for data loss - best performance = greater scope for data loss.
  • It's often very easy to scale out NoSQL solutions. Adding more nodes to replicate data to is one way to a) offer more scalability and b) offer more protection against data loss if one node goes down. But again, depends on the NoSQL DB/configuration. NoSQL does not necessarily mean "data loss" like you infer.
  • IMHO, complex/dynamic queries/reporting are best served from an RDBMS. Often the query functionality for a NoSQL DB is limited.
  • It doesn't have to be a 1 or the other choice. My experience has been using RDBMS in conjunction with NoSQL for certain use cases.
  • NoSQL DBs often lack the ability to perform atomic operations across multiple "tables".

You really need to look at and understand what the various types of NoSQL stores are, and how they go about providing scalability/data security etc. It's difficult to give an across-the-board answer as they really are all different and tackle things differently.

For MongoDb as an example, check out their Use Cases to see what they suggest as being "well suited" and "less well suited" uses of MongoDb.