Programs & Examples On #Parsecontrol

ParseControl is an ASP.NET function that parses an input string to create an ASP.NET server control object.

Angular ng-click with call to a controller function not working

I'm going to guess you aren't getting errors or you would've mentioned them. If that's the case, try removing the href attribute value so the page doesn't navigate away before your code is executed. In Angular it's perfectly acceptable to leave href attributes blank.

<a href="" data-router="article" ng-click="changeListName('metro')">

Also I don't know what data-router is doing but if you still aren't getting the proper result, that could be why.

ComboBox.SelectedText doesn't give me the SelectedText

To get selected item, you have to use SELECTEDITEM property of comboBox. And since this is an Object, if you wanna assign it to a string, you have to convert it to string, by using ToString() method:

string myItem = comboBox1.SelectedItem.ToString(); //this does the trick

What is the difference between substr and substring?

substring (MDN) takes parameters as (from, to).
substr (MDN) takes parameters as (from, length).

Update: MDN considers substr legacy.

alert("abc".substr(1,2)); // returns "bc"
alert("abc".substring(1,2)); // returns "b"

You can remember substring (with an i) takes indices, as does yet another string extraction method, slice (with an i).

When starting from 0 you can use either method.

Angular2 material dialog has issues - Did you add it to @NgModule.entryComponents?

I had the same issues and i had dialogComponent in EntryComponents and it still did not work. this is how I was able to solve the problem. the link is here to a previously answered post:

https://stackoverflow.com/a/64224799/14385758

How to export data to CSV in PowerShell?

what you are searching for is the Export-Csv file.csv

try using Get-Help Export-Csv to see whats possible

also Out-File -FilePath "file.csv" will work

When increasing the size of VARCHAR column on a large table could there be any problems?

Changing to Varchar(1200) from Varchar(200) should cause you no issue as it is only a metadata change and as SQL server 2008 truncates excesive blank spaces you should see no performance differences either so in short there should be no issues with making the change.

Array versus List<T>: When to use which?

Notwithstanding the other answers recommending List<T>, you'll want to use arrays when handling:

  • image bitmap data
  • other low-level data-structures (i.e. network protocols)

Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes

By process (in the JSF specification it's called execute) you tell JSF to limit the processing to component that are specified every thing else is just ignored.

update indicates which element will be updated when the server respond back to you request.

@all : Every component is processed/rendered.

@this: The requesting component with the execute attribute is processed/rendered.

@form : The form that contains the requesting component is processed/rendered.

@parent: The parent that contains the requesting component is processed/rendered.

With Primefaces you can even use JQuery selectors, check out this blog: http://blog.primefaces.org/?p=1867

Load vs. Stress testing

Load Testing: Load testing is meant to test the system by constantly and steadily increasing the load on the system till the time it reaches the threshold limit.

Example For example, to check the email functionality of an application, it could be flooded with 1000 users at a time. Now, 1000 users can fire the email transactions (read, send, delete, forward, reply) in many different ways. If we take one transaction per user per hour, then it would be 1000 transactions per hour. By simulating 10 transactions/user, we could load test the email server by occupying it with 10000 transactions/hour.

Stress Testing: Under stress testing, various activities to overload the existing resources with excess jobs are carried out in an attempt to break the system down.

Example: As an example, a word processor like Writer1.1.0 by OpenOffice.org is utilized in development of letters, presentations, spread sheets etc… Purpose of our stress testing is to load it with the excess of characters.

To do this, we will repeatedly paste a line of data, till it reaches its threshold limit of handling large volume of text. As soon as the character size reaches 65,535 characters, it would simply refuse to accept more data. The result of stress testing on Writer 1.1.0 produces the result that, it does not crash under the stress and that it handle the situation gracefully, which make sure that application is working correctly even under rigorous stress conditions.

float:left; vs display:inline; vs display:inline-block; vs display:table-cell;

Of the options you asked about:

  • float:left;
    I dislike floats because of the need to have additional markup to clear the float. As far as I'm concerned, the whole float concept was poorly designed in the CSS specs. Nothing we can do about that now though. But the important thing is it does work, and it works in all browsers (even IE6/7), so use it if you like it.

The additional markup for clearing may not be necessary if you use the :after selector to clear the floats, but this isn't an option if you want to support IE6 or IE7.

  • display:inline;
    This shouldn't be used for layout, with the exception of IE6/7, where display:inline; zoom:1 is a fall-back hack for the broken support for inline-block.

  • display:inline-block;
    This is my favourite option. It works well and consistently across all browsers, with a caveat for IE6/7, which support it for some elements. But see above for the hacky solution to work around this.

The other big caveat with inline-block is that because of the inline aspect, the white spaces between elements are treated the same as white spaces between words of text, so you can get gaps appearing between elements. There are work-arounds to this, but none of them are ideal. (the best is simply to not have any spaces between the elements)

  • display:table-cell;
    Another one where you'll have problems with browser compatibility. Older IEs won't work with this at all. But even for other browsers, it's worth noting that table-cell is designed to be used in a context of being inside elements that are styled as table and table-row; using table-cell in isolation is not the intended way to do it, so you may experience different browsers treating it differently.

Other techniques you may have missed? Yes.

  • Since you say this is for a multi-column layout, there is a CSS Columns feature that you might want to know about. However it isn't the most well supported feature (not supported by IE even in IE9, and a vendor prefix required by all other browsers), so you may not want to use it. But it is another option, and you did ask.

  • There's also CSS FlexBox feature, which is intended to allow you to have text flowing from box to box. It's an exciting feature that will allow some complex layouts, but this is still very much in development -- see http://html5please.com/#flexbox

Hope that helps.

Find methods calls in Eclipse project

Move the cursor to the method name. Right click and select References > Project or References > Workspace from the pop-up menu.

Git says remote ref does not exist when I delete remote branch

The meaning of remotes/origin/test is that you have a branch called test in the remote server origin. So the command would be

git push origin --delete test

Opening a new tab to read a PDF file

Change the <a> tag like this:

<a href="newsletter_01.pdf" target="_blank">

You can find more about the target attribute here.

Return from lambda forEach() in java

I suggest you to first try to understand Java 8 in the whole picture, most importantly in your case it will be streams, lambdas and method references.

You should never convert existing code to Java 8 code on a line-by-line basis, you should extract features and convert those.

What I identified in your first case is the following:

  • You want to add elements of an input structure to an output list if they match some predicate.

Let's see how we do that, we can do it with the following:

List<Player> playersOfTeam = players.stream()
    .filter(player -> player.getTeam().equals(teamName))
    .collect(Collectors.toList());

What you do here is:

  1. Turn your input structure into a stream (I am assuming here that it is of type Collection<Player>, now you have a Stream<Player>.
  2. Filter out all unwanted elements with a Predicate<Player>, mapping every player to the boolean true if it is wished to be kept.
  3. Collect the resulting elements in a list, via a Collector, here we can use one of the standard library collectors, which is Collectors.toList().

This also incorporates two other points:

  1. Code against interfaces, so code against List<E> over ArrayList<E>.
  2. Use diamond inference for the type parameter in new ArrayList<>(), you are using Java 8 after all.

Now onto your second point:

You again want to convert something of legacy Java to Java 8 without looking at the bigger picture. This part has already been answered by @IanRoberts, though I think that you need to do players.stream().filter(...)... over what he suggested.

How to implement custom JsonConverter in JSON.NET to deserialize a List of base class objects?

The project JsonSubTypes implement a generic converter that handle this feature with the helps of attributes.

For the concrete sample provided here is how it works:

    [JsonConverter(typeof(JsonSubtypes))]
    [JsonSubtypes.KnownSubTypeWithProperty(typeof(Employee), "JobTitle")]
    [JsonSubtypes.KnownSubTypeWithProperty(typeof(Artist), "Skill")]
    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

    public class Employee : Person
    {
        public string Department { get; set; }
        public string JobTitle { get; set; }
    }

    public class Artist : Person
    {
        public string Skill { get; set; }
    }

    [TestMethod]
    public void Demo()
    {
        string json = "[{\"Department\":\"Department1\",\"JobTitle\":\"JobTitle1\",\"FirstName\":\"FirstName1\",\"LastName\":\"LastName1\"}," +
                      "{\"Department\":\"Department1\",\"JobTitle\":\"JobTitle1\",\"FirstName\":\"FirstName1\",\"LastName\":\"LastName1\"}," +
                      "{\"Skill\":\"Painter\",\"FirstName\":\"FirstName1\",\"LastName\":\"LastName1\"}]";


        var persons = JsonConvert.DeserializeObject<IReadOnlyCollection<Person>>(json);
        Assert.AreEqual("Painter", (persons.Last() as Artist)?.Skill);
    }

Android TextView Text not getting wrapped

I had a similar problem where were my two horizontally weighted TextViews didn't wrap the text. I later found out that the issue was because my viewparents parent had wrap_content instead of match_parent.

How to print matched regex pattern using awk?

This is the very basic

awk '/pattern/{ print $0 }' file

ask awk to search for pattern using //, then print out the line, which by default is called a record, denoted by $0. At least read up the documentation.

If you only want to get print out the matched word.

awk '{for(i=1;i<=NF;i++){ if($i=="yyy"){print $i} } }' file

How to query a CLOB column in Oracle

For big CLOB selects also can be used:

SELECT dbms_lob.substr( column_name, dbms_lob.getlength(column_name), 1) FROM foo

How to convert Rows to Columns in Oracle?

You can do it with a pivot query, like this:

select * from (
   select LOAN_NUMBER, DOCUMENT_TYPE, DOCUMENT_ID
   from my_table t
)
pivot 
(
   MIN(DOCUMENT_ID)
   for DOCUMENT_TYPE in ('Voters ID','Pan card','Drivers licence')
)

Here is a demo on sqlfiddle.com.

How do you put an image file in a json object?

Use data URL scheme: https://en.wikipedia.org/wiki/Data_URI_scheme

In this case you use that string directly in html : <img src="data:image/png;base64,iVBOR....">

Getting the "real" Facebook profile picture URL from graph API

For anyone else looking to get the profile pic in iOS:

I just did this to get the user's Facebook pic:

NSString *profilePicURL = [NSString stringWithFormat:@"http://graph.facebook.com/%@/picture?type=large", fbUserID];

where 'fbUserID' is the Facebook user's profile ID.

This way I can always just call the url in profilePicURL to get the image, and I always get it, no problem. If you've already got the user ID, you don't need any API requests, just stick the ID into the url after facebook.com/.

FYI to anyone looking who needs the fbUserID in iOS:

if (FBSession.activeSession.isOpen) {
    [[FBRequest requestForMe] startWithCompletionHandler:
     ^(FBRequestConnection *connection,
       NSDictionary<FBGraphUser> *user,
       NSError *error) {
         if (!error) {
             self.userName = user.name;
             self.fbUserID = user.id;
         }
     }];
}

You'll need an active FBSession for that to work (see Facebook's docs, and the "Scrumptious" example).

Working with $scope.$emit and $scope.$on

First of all, parent-child scope relation does matter. You have two possibilities to emit some event:

  • $broadcast -- dispatches the event downwards to all child scopes,
  • $emit -- dispatches the event upwards through the scope hierarchy.

I don't know anything about your controllers (scopes) relation, but there are several options:

  1. If scope of firstCtrl is parent of the secondCtrl scope, your code should work by replacing $emit by $broadcast in firstCtrl:

    function firstCtrl($scope)
    {
        $scope.$broadcast('someEvent', [1,2,3]);
    }
    
    function secondCtrl($scope)
    {
        $scope.$on('someEvent', function(event, mass) { console.log(mass); });
    }
    
  2. In case there is no parent-child relation between your scopes you can inject $rootScope into the controller and broadcast the event to all child scopes (i.e. also secondCtrl).

    function firstCtrl($rootScope)
    {
        $rootScope.$broadcast('someEvent', [1,2,3]);
    }
    
  3. Finally, when you need to dispatch the event from child controller to scopes upwards you can use $scope.$emit. If scope of firstCtrl is parent of the secondCtrl scope:

    function firstCtrl($scope)
    {
        $scope.$on('someEvent', function(event, data) { console.log(data); });
    }
    
    function secondCtrl($scope)
    {
        $scope.$emit('someEvent', [1,2,3]);
    }
    

How to call getClass() from a static method in Java?

As for the code example in the question, the standard solution is to reference the class explicitly by its name, and it is even possible to do without getClassLoader() call:

class MyClass {
  public static void startMusic() {
    URL songPath = MyClass.class.getResource("background.midi");
  }
}

This approach still has a back side that it is not very safe against copy/paste errors in case you need to replicate this code to a number of similar classes.

And as for the exact question in the headline, there is a trick posted in the adjacent thread:

Class currentClass = new Object() { }.getClass().getEnclosingClass();

It uses a nested anonymous Object subclass to get hold of the execution context. This trick has a benefit of being copy/paste safe...

Caution when using this in a Base Class that other classes inherit from:

It is also worth noting that if this snippet is shaped as a static method of some base class then currentClass value will always be a reference to that base class rather than to any subclass that may be using that method.

how to remove untracked files in Git?

For deleting untracked files:

git clean -f

For deleting untracked directories as well, use:

git clean -f -d

For preventing any cardiac arrest, use

git clean -n -f -d

How do I count unique values inside a list

If you would like to have a histogram of unique values here's oneliner

import numpy as np    
unique_labels, unique_counts = np.unique(labels_list, return_counts=True)
labels_histogram = dict(zip(unique_labels, unique_counts))

Check if a varchar is a number (TSQL)

Damien_The_Unbeliever noted that his was only good for digits

Wade73 added a bit to handle decimal points

neizan made an additional tweak as did notwhereuareat

Unfortunately, none appear to handle negative values and they appear to have issues with a comma in the value...

Here's my tweak to pick up negative values and those with commas

declare @MyTable table(MyVar nvarchar(10));
insert into @MyTable (MyVar) 
values 
(N'1234')
, (N'000005')
, (N'1,000')
, (N'293.8457')
, (N'x')
, (N'+')
, (N'293.8457.')
, (N'......')
, (N'.')
, (N'-375.4')
, (N'-00003')
, (N'-2,000')
, (N'3-3')
, (N'3000-')
;

-- This shows that Neizan's answer allows "." to slip through.
select * from (
select 
    MyVar
    , case when MyVar not like N'%[^0-9.]%' then 1 else 0 end as IsNumber 
from 
    @MyTable
) t order by IsNumber;

-- Notice the addition of "and MyVar not like '.'".
select * from (
select 
    MyVar
    , case when MyVar not like N'%[^0-9.]%' and MyVar not like N'%.%.%' and MyVar not like '.' then 1 else 0 end as IsNumber 
from 
    @MyTable
) t 
order by IsNumber;

--Trying to tweak for negative values and the comma
--Modified when comparison
select * from (
select 
    MyVar
    , case 
        when MyVar not like N'%[^0-9.,-]%' and MyVar not like '.' and isnumeric(MyVar) = 1 then 1
        else 0 
    end as IsNumber 
from 
    @MyTable
) t 
order by IsNumber;

Laravel - Eloquent "Has", "With", "WhereHas" - What do they mean?

With

with() is for eager loading. That basically means, along the main model, Laravel will preload the relationship(s) you specify. This is especially helpful if you have a collection of models and you want to load a relation for all of them. Because with eager loading you run only one additional DB query instead of one for every model in the collection.

Example:

User > hasMany > Post

$users = User::with('posts')->get();
foreach($users as $user){
    $users->posts; // posts is already loaded and no additional DB query is run
}

Has

has() is to filter the selecting model based on a relationship. So it acts very similarly to a normal WHERE condition. If you just use has('relation') that means you only want to get the models that have at least one related model in this relation.

Example:

User > hasMany > Post

$users = User::has('posts')->get();
// only users that have at least one post are contained in the collection

WhereHas

whereHas() works basically the same as has() but allows you to specify additional filters for the related model to check.

Example:

User > hasMany > Post

$users = User::whereHas('posts', function($q){
    $q->where('created_at', '>=', '2015-01-01 00:00:00');
})->get();
// only users that have posts from 2015 on forward are returned

org.springframework.web.client.HttpClientErrorException: 400 Bad Request

This is what worked for me. Issue is earlier I didn't set Content Type(header) when I used exchange method.

MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("param1", "123");
map.add("param2", "456");
map.add("param3", "789");
map.add("param4", "123");
map.add("param5", "456");

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

final HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<MultiValueMap<String, String>>(map ,
        headers);
JSONObject jsonObject = null;

try {
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<String> responseEntity = restTemplate.exchange(
            "https://url", HttpMethod.POST, entity,
            String.class);

    if (responseEntity.getStatusCode() == HttpStatus.CREATED) {
        try {
            jsonObject = new JSONObject(responseEntity.getBody());
        } catch (JSONException e) {
            throw new RuntimeException("JSONException occurred");
        }
    }
  } catch (final HttpClientErrorException httpClientErrorException) {
        throw new ExternalCallBadRequestException();
  } catch (HttpServerErrorException httpServerErrorException) {
        throw new ExternalCallServerErrorException(httpServerErrorException);
  } catch (Exception exception) {
        throw new ExternalCallServerErrorException(exception);
    } 

ExternalCallBadRequestException and ExternalCallServerErrorException are the custom exceptions here.

Note: Remember HttpClientErrorException is thrown when a 4xx error is received. So if the request you send is wrong either setting header or sending wrong data, you could receive this exception.

Why use @PostConstruct?

Consider the following scenario:

public class Car {
  @Inject
  private Engine engine;  

  public Car() {
    engine.initialize();  
  }
  ...
}

Since Car has to be instantiated prior to field injection, the injection point engine is still null during the execution of the constructor, resulting in a NullPointerException.

This problem can be solved either by JSR-330 Dependency Injection for Java constructor injection or JSR 250 Common Annotations for the Java @PostConstruct method annotation.

@PostConstruct

JSR-250 defines a common set of annotations which has been included in Java SE 6.

The PostConstruct annotation is used on a method that needs to be executed after dependency injection is done to perform any initialization. This method MUST be invoked before the class is put into service. This annotation MUST be supported on all classes that support dependency injection.

JSR-250 Chap. 2.5 javax.annotation.PostConstruct

The @PostConstruct annotation allows for the definition of methods to be executed after the instance has been instantiated and all injects have been performed.

public class Car {
  @Inject
  private Engine engine;  

  @PostConstruct
  public void postConstruct() {
    engine.initialize();  
  }
  ...
} 

Instead of performing the initialization in the constructor, the code is moved to a method annotated with @PostConstruct.

The processing of post-construct methods is a simple matter of finding all methods annotated with @PostConstruct and invoking them in turn.

private  void processPostConstruct(Class type, T targetInstance) {
  Method[] declaredMethods = type.getDeclaredMethods();

  Arrays.stream(declaredMethods)
      .filter(method -> method.getAnnotation(PostConstruct.class) != null) 
      .forEach(postConstructMethod -> {
         try {
           postConstructMethod.setAccessible(true);
           postConstructMethod.invoke(targetInstance, new Object[]{});
        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {      
          throw new RuntimeException(ex);
        }
      });
}

The processing of post-construct methods has to be performed after instantiation and injection have been completed.

Javascript "Cannot read property 'length' of undefined" when checking a variable's length

In addition to others' proposals, there is another option to handle that issue.

If your application should behave the same in case of lack of "href" attribute, as in case of it being empty, just replace this:

var theHref = $(obj.mainImg_select).attr('href');

with this:

var theHref = $(obj.mainImg_select).attr('href') || '';

which will treat empty string ('') as the default, if the attribute has not been found.

But it really depends, on how you want to handle undefined "href" attribute. This answer assumes you will want to handle it as if it was empty string.

What is causing ImportError: No module named pkg_resources after upgrade of Python on os X?

[UPDATE] TL;DR pkg_resources is provided by either Distribute or setuptools.

[UPDATE 2] As announced at PyCon 2013, the Distribute and setuptools projects have re-merged. Distribute is now deprecated and you should just use the new current setuptools. Try this:

curl -O https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py
python ez_setup.py

Or, better, use a current pip as the high level interface and which will use setuptools under the covers.

[Longer answer for OP's specific problem]:

You don't say in your question but I'm assuming you upgraded from the Apple-supplied Python (2.5 on 10.5 or 2.6.1 on 10.6) or that you upgraded from a python.org Python 2.5. In any of those cases, the important point is that each Python instance has its own library, including its own site-packages library, which is where additional packages are installed. (And none of them use /usr/local/lib by default, by the way.) That means you'll need to install those additional packages you need for your new python 2.6. The easiest way to do this is to first ensure that the new python2.6 appears first on your search $PATH (that is, typing python2.6 invokes it as expected); the python2.6 installer should have modified your .bash_profile to put its framework bin directory at the front of $PATH. Then install easy_install using setuptools following the instructions there. The pkg_resources module is also automatically installed by this step.

Then use the newly-installed version of easy_install (or pip) to install ipython.

easy_install ipython

or

pip install ipython

It should automatically get installed to the correct site-packages location for that python instance and you should be good to go.

Google Maps API v3: How do I dynamically change the marker icon?

Call the marker.setIcon('newImage.png')... Look here for the docs.

Are you asking about the actual way to do it? You could just create each div, and a add a mouseover and mouseout listener that would change the icon and back for the markers.

ImportError: No module named 'encodings'

I could also fix this. PYTHONPATH and PYTHONHOME were in cause.

run this in a terminal

   touch ~/.bash_profile
   open ~/.bash_profile

and then delete all useless parts of this file, and save. I do not know how recommended it is to do that !

Get environment variable value in Dockerfile

You should use the ARG directive in your Dockerfile which is meant for this purpose.

The ARG instruction defines a variable that users can pass at build-time to the builder with the docker build command using the --build-arg <varname>=<value> flag.

So your Dockerfile will have this line:

ARG request_domain

or if you'd prefer a default value:

ARG request_domain=127.0.0.1

Now you can reference this variable inside your Dockerfile:

ENV request_domain=$request_domain

then you will build your container like so:

$ docker build --build-arg request_domain=mydomain Dockerfile


Note 1: Your image will not build if you have referenced an ARG in your Dockerfile but excluded it in --build-arg.

Note 2: If a user specifies a build argument that was not defined in the Dockerfile, the build outputs a warning:

[Warning] One or more build-args [foo] were not consumed.

Detect end of ScrollView

To determine if you are at the end of your custom ScrollView you could also use a member variable and store the last y-position. Then you can compare the last y-position with the current scroll position.

private int scrollViewPos;

...

@Override
public void onScrollChanged(ScrollViewExt scrollView, int x, int y, int oldx, int oldy) {

   //reached end of scrollview
   if (y > 0 && scrollViewPos == y){
      //do something
   }

   scrollViewPos = y;
}

How to install JQ on Mac by command-line?

On a Mac, the "most efficient" way to install jq would probably be using homebrew, e.g.

brew install jq

If you want the development version, you could try:

brew install --HEAD jq

but this has various pre-requisites.

Detailed instructions are on the "Installation" page of the jq wiki: https://github.com/stedolan/jq/wiki/Installation

The same page also includes details regarding installation from source, and has notes on installing with MacPorts.

how to set auto increment column with sql developer

UPDATE: In Oracle 12c onward we have an option to create auto increment field, its better than trigger and sequence.

  • Right click on the table and select "Edit".
  • In "Edit" Table window, select "columns", and then select your PK column.
  • Go to Identity Column tab and select "Generated as Identity" as Type, put 1 in both start with and increment field. This will make this column auto increment.

See the below image

enter image description here

From SQL Statement

IDENTITY column is now available on Oracle 12c:

 create table t1 (
     c1 NUMBER GENERATED by default on null as IDENTITY,
     c2 VARCHAR2(10)
     );

or specify starting and increment values, also preventing any insert into the identity column (GENERATED ALWAYS) (again, Oracle 12c+ only)

create table t1 (
    c1 NUMBER GENERATED ALWAYS as IDENTITY(START with 1 INCREMENT by 1),
    c2 VARCHAR2(10)
    );

EDIT : if you face any error like "ORA-30673: column to be modified is not an identity column", then you need to create new column and delete the old one.

How to disable HTML button using JavaScript?

It's still an attribute. Setting it to:

<input type="button" name=myButton value="disable" disabled="disabled">

... is valid.

Disable ONLY_FULL_GROUP_BY

Be careful using

SET sql_mode = '' 

This actually clears all the modes currently enabled. If you don't want to mess with other settings, you'll want to do a

SELECT @@sql_mode 

first, to get a comma-separated list of the modes enabled, then SET it to this list without the ONLY_FULL_GROUP_BY option.

How to append rows in a pandas dataframe in a for loop?

A more compact and efficient way would be perhaps:

cols = ['frame', 'count']
N = 4
dat = pd.DataFrame(columns = cols)
for i in range(N):

    dat = dat.append({'frame': str(i), 'count':i},ignore_index=True)

output would be:

>>> dat
   frame count
0     0     0
1     1     1
2     2     2
3     3     3

How does one Display a Hyperlink in React Native App?

If you want to do links and other types of rich text, a more comprehensive solution is to use React Native HTMLView.

What is the recommended project structure for spring boot rest projects?

I have an example which I have been using for couple years. Please take a look as a reference.

https://github.com/bigzidane/springboot-rest-h2-swagger

AngularJS $location not changing the path

This wroks for me(in CoffeeScript)

 $location.path '/url/path'
 $scope.$apply() if (!$scope.$$phase)

Pass variables from servlet to jsp

If you are using Action, Actionforward way to process business logic and next page to show, check out if redirect is called. As many others pointed out, redirecting doesn't keep your original request since it is basically forcing you to make a new request to designated path. So the value set in original request will be vanished if you use redirection instead of requestdispatch.

SQL Server converting varbinary to string

This works in both SQL 2005 and 2008:

declare @source varbinary(max);
set @source = 0x21232F297A57A5A743894A0E4A801FC3;
select cast('' as xml).value('xs:hexBinary(sql:variable("@source"))', 'varchar(max)');

Find a file by name in Visual Studio Code

Press Ctl+T will open a search box. Delete # symbol and enter your file name.

How can I get the concatenation of two lists in Python without modifying either one?

The simplest method is just to use the + operator, which returns the concatenation of the lists:

concat = first_list + second_list

One disadvantage of this method is that twice the memory is now being used . For very large lists, depending on how you're going to use it once it's created, itertools.chain might be your best bet:

>>> import itertools
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = itertools.chain(a, b)

This creates a generator for the items in the combined list, which has the advantage that no new list needs to be created, but you can still use c as though it were the concatenation of the two lists:

>>> for i in c:
...     print i
1
2
3
4
5
6

If your lists are large and efficiency is a concern then this and other methods from the itertools module are very handy to know.

Note that this example uses up the items in c, so you'd need to reinitialise it before you can reuse it. Of course you can just use list(c) to create the full list, but that will create a new list in memory.

Vim and Ctags tips and tricks

You can add directories to your ctags lookup. For example, I have a ctags index built for Qt4, and have this in my .vimrc:

set tags+=/usr/local/share/ctags/qt4

How to detect browser using angularjs?

Why not use document.documentMode only available under IE:

var doc = $window.document;
if (!!doc.documentMode)
{
  if (doc.documentMode === 10)
  {
    doc.documentElement.className += ' isIE isIE10';
  }
  else if (doc.documentMode === 11)
  {
    doc.documentElement.className += ' isIE isIE11';
  }
  // etc.
}

remove item from stored array in angular 2

//declaration 
list: Array<any> = new Array<any>(); 

//remove item from an array 
removeitem() 
{
const index = this.list.findIndex(user => user._id === 2); 
this.list.splice(index, 1); 
}

How can I clear the NuGet package cache using the command line?

This adds to rm8x's answer.

Download and install the NuGet command line tool.

List all of our locals:

$ nuget locals all -list
http-cache: C:\Users\MyUser\AppData\Local\NuGet\v3-cache
packages-cache: C:\Users\MyUser\AppData\Local\NuGet\Cache
global-packages: C:\Users\MyUser\.nuget\packages\

We can now delete these manually or as rm8x suggests, use nuget locals all -clear.

How to format DateTime to 24 hours time?

Console.WriteLine(curr.ToString("HH:mm"));

PHP, Get tomorrows date from date

 $tomorrow = date("Y-m-d", strtotime('tomorrow'));

or

  $tomorrow = date("Y-m-d", strtotime("+1 day"));

Help Link: STRTOTIME()

Remove a parameter to the URL with JavaScript

Try this. Just pass in the param you want to remove from the URL and the original URL value, and the function will strip it out for you.

function removeParam(key, sourceURL) {
    var rtn = sourceURL.split("?")[0],
        param,
        params_arr = [],
        queryString = (sourceURL.indexOf("?") !== -1) ? sourceURL.split("?")[1] : "";
    if (queryString !== "") {
        params_arr = queryString.split("&");
        for (var i = params_arr.length - 1; i >= 0; i -= 1) {
            param = params_arr[i].split("=")[0];
            if (param === key) {
                params_arr.splice(i, 1);
            }
        }
        if (params_arr.length) rtn = rtn + "?" + params_arr.join("&");
    }
    return rtn;
}

To use it, simply do something like this:

var originalURL = "http://yourewebsite.com?id=10&color_id=1";
var alteredURL = removeParam("color_id", originalURL);

The var alteredURL will be the output you desire.

Hope it helps!

How can I backup a remote SQL Server database to a local drive?

You can use Copy database ... right click on the remote database ... select tasks and use copy database ... it will asks you about source server and destination server . that your source is the remote and destination is your local instance of sql server.

it's that easy

Twitter Bootstrap alert message close and open again

I just used a model variable to show/hide the dialog and removed the data-dismiss="alert"

Example:

<div data-ng-show="vm.result == 'error'" class="alert alert-danger alert-dismissable">
    <button type="button" class="close" data-ng-click="vm.result = null" aria-hidden="true">&times;</button>
    <strong>Error  !  </strong>{{vm.exception}}
</div>

works for me and stops the need to go out to jquery

Flushing footer to bottom of the page, twitter bootstrap

A working example for Twitter bootstrap NOT STICKY FOOTER

<script>
$(document).ready(function() {

    var docHeight = $(window).height();
    var footerHeight = $('#footer').height();
    var footerTop = $('#footer').position().top + footerHeight;

    if (footerTop < docHeight)
        $('#footer').css('margin-top', 10+ (docHeight - footerTop) + 'px');
});
</script>

Version that always updates in case user opens devtools or resizes window.

<script>
    $(document).ready(function() {
        setInterval(function() {
            var docHeight = $(window).height();
            var footerHeight = $('#footer').height();
            var footerTop = $('#footer').position().top + footerHeight;
            var marginTop = (docHeight - footerTop + 10);

            if (footerTop < docHeight)
                $('#footer').css('margin-top', marginTop + 'px'); // padding of 30 on footer
            else
                $('#footer').css('margin-top', '0px');
            // console.log("docheight: " + docHeight + "\n" + "footerheight: " + footerHeight + "\n" + "footertop: " + footerTop + "\n" + "new docheight: " + $(window).height() + "\n" + "margintop: " + marginTop);
        }, 250);
    });
</script>

You need at least an element with a #footer

When not want the scrollbar if content would fit to screen just change the value of 10 to 0
The scrollbar will show up if content not fits to screen.

Uncaught TypeError: undefined is not a function while using jQuery UI

I had trouble getting selectable to work with ASP.NET. It turns out I wasn't properly including everything, but this gentleman made it foolproof: Three steps to use jQuery UI in ASP.NET MVC 5.

What are the ways to sum matrix elements in MATLAB?

Another answer for the first question is to use one for loop and perform linear indexing into the array using the function NUMEL to get the total number of elements:

total = 0;
for i = 1:numel(A)
  total = total+A(i);
end

How to extract .war files in java? ZIP vs JAR

If you using Linux or Ubuntu than you can directly extract data from .war file.

A war file is just a jar file, to extract it, just issue following command using the jar program:

jar -xvf yourWARfileName.war

Correct way of getting Client's IP Addresses from http.Request

This is how I come up with the IP

func ReadUserIP(r *http.Request) string {
    IPAddress := r.Header.Get("X-Real-Ip")
    if IPAddress == "" {
        IPAddress = r.Header.Get("X-Forwarded-For")
    }
    if IPAddress == "" {
        IPAddress = r.RemoteAddr
    }
    return IPAddress
}
  • X-Real-Ip - fetches first true IP (if the requests sits behind multiple NAT sources/load balancer)

  • X-Forwarded-For - if for some reason X-Real-Ip is blank and does not return response, get from X-Forwarded-For

  • Remote Address - last resort (usually won't be reliable as this might be the last ip or if it is a naked http request to server ie no load balancer)

Differences between arm64 and aarch64

AArch64 is the 64-bit state introduced in the Armv8-A architecture (https://en.wikipedia.org/wiki/ARM_architecture#ARMv8-A). The 32-bit state which is backwards compatible with Armv7-A and previous 32-bit Arm architectures is referred to as AArch32. Therefore the GNU triplet for the 64-bit ISA is aarch64. The Linux kernel community chose to call their port of the kernel to this architecture arm64 rather than aarch64, so that's where some of the arm64 usage comes from.

As far as I know the Apple backend for aarch64 was called arm64 whereas the LLVM community-developed backend was called aarch64 (as it is the canonical name for the 64-bit ISA) and later the two were merged and the backend now is called aarch64.

So AArch64 and ARM64 refer to the same thing.

How exactly does __attribute__((constructor)) work?

Here is another concrete example.It is for a shared library. The shared library's main function is to communicate with a smart card reader. But it can also receive 'configuration information' at runtime over udp. The udp is handled by a thread which MUST be started at init time.

__attribute__((constructor))  static void startUdpReceiveThread (void) {
    pthread_create( &tid_udpthread, NULL, __feigh_udp_receive_loop, NULL );
    return;

  }

The library was written in c.

jQuery attr() change img src

You remove the original image here:

newImg.animate(css, SPEED, function() {
    img.remove();
    newImg.removeClass('morpher');
    (callback || function() {})();
});

And all that's left behind is newImg. Then you reset link references the image using #rocket:

$("#rocket").attr('src', ...

But your newImg doesn't have an id attribute let alone an id of rocket.

To fix this, you need to remove img and then set the id attribute of newImg to rocket:

newImg.animate(css, SPEED, function() {
    var old_id = img.attr('id');
    img.remove();
    newImg.attr('id', old_id);
    newImg.removeClass('morpher');
    (callback || function() {})();
});

And then you'll get the shiny black rocket back again: http://jsfiddle.net/ambiguous/W2K9D/

UPDATE: A better approach (as noted by mellamokb) would be to hide the original image and then show it again when you hit the reset button. First, change the reset action to something like this:

$("#resetlink").click(function(){
    clearInterval(timerRocket);
    $("#wrapper").css('top', '250px');
    $('.throbber, .morpher').remove(); // Clear out the new stuff.
    $("#rocket").show();               // Bring the original back.
});

And in the newImg.load function, grab the images original size:

var orig = {
    width: img.width(),
    height: img.height()
};

And finally, the callback for finishing the morphing animation becomes this:

newImg.animate(css, SPEED, function() {
    img.css(orig).hide();
    (callback || function() {})();
});

New and improved: http://jsfiddle.net/ambiguous/W2K9D/1/

The leaking of $('.throbber, .morpher') outside the plugin isn't the best thing ever but it isn't a big deal as long as it is documented.

how to include glyphicons in bootstrap 3

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

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

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

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

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

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

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

You then include your Bootstrap file like so:

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

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

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

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

So, why do this?

Bootstrap.css has this specific line for Glyphfonts:

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

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

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

/fonts
Bootstrap.css
index.html

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

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

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

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

C:\fonts

but your folder is actually in:

C:\www\fonts

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

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

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

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

Writing a new line to file in PHP (line feed)

Replace '\n' with "\n". The escape sequence is not recognized when you use '.

See the manual.

For the question of how to write line endings, see the note here. Basically, different operating systems have different conventions for line endings. Windows uses "\r\n", unix based operating systems use "\n". You should stick to one convention (I'd chose "\n") and open your file in binary mode (fopen should get "wb", not "w").

django import error - No module named core.management

As known this was a path issue.

the base of my custom packages shared a name with a directory set in a /etc/profile. The packages were in a different location however for the webserver. So I removed the offending entries from my $PYTHONPATH and was good to go!

Thanks for the help.

How to darken a background using CSS?

This is the easiest way I found

  background: black;
  opacity: 0.5;

how to use #ifdef with an OR condition?

Like this

#if defined(LINUX) || defined(ANDROID)

How to return JSON with ASP.NET & jQuery

Asp.net is pretty good at automatically converting .net objects to json. Your List object if returned in your webmethod should return a json/javascript array. What I mean by this is that you shouldn't change the return type to string (because that's what you think the client is expecting) when returning data from a method. If you return a .net array from a webmethod a javaScript array will be returned to the client. It doesn't actually work too well for more complicated objects, but for simple array data its fine.

Of course, it's then up to you to do what you need to do on the client side.

I would be thinking something like this:

[WebMethod]
public static List GetProducts()
{
   var products  = context.GetProducts().ToList();   
   return products;
}

There shouldn't really be any need to initialise any custom converters unless your data is more complicated than simple row/col data

Multiple lines of text in UILabel

This code is returning size height according to text

+ (CGFloat)findHeightForText:(NSString *)text havingWidth:(CGFloat)widthValue andFont:(UIFont *)font
 {
    CGFloat result = font.pointSize+4;
    if (text) 
{
        CGSize size;

        CGRect frame = [text boundingRectWithSize:CGSizeMake(widthValue, 999)
                                          options:NSStringDrawingUsesLineFragmentOrigin
                                       attributes:@{NSFontAttributeName:font}
                                          context:nil];
        size = CGSizeMake(frame.size.width, frame.size.height+1);
        result = MAX(size.height, result); //At least one row
    }
    return result;
}

Write a file in UTF-8 using FileWriter (Java)?

Ditch FileWriter and FileReader, which are useless exactly because they do not allow you to specify the encoding. Instead, use

new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8)

and

new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8);

How can I color a UIImage in Swift?

Add this extension in your code and change image color in storyboard itself.

Swift 4 & 5:

extension UIImageView {
    @IBInspectable
    var changeColor: UIColor? {
        get {
            let color = UIColor(cgColor: layer.borderColor!);
            return color
        }
        set {
            let templateImage = self.image?.withRenderingMode(.alwaysTemplate)
            self.image = templateImage
            self.tintColor = newValue
        }
    }
}

Storyboard Preview:

enter image description here

Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error, while Postman does not?

Because
$.ajax({type: "POST" - calls OPTIONS
$.post( - Calls POST

Both are different. Postman calls "POST" properly, but when we call it, it will be "OPTIONS".

For C# web services - Web API

Please add the following code in your web.config file under <system.webServer> tag. This will work:

<httpProtocol>
    <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
    </customHeaders>
</httpProtocol>

Please make sure you are not doing any mistake in the Ajax call

jQuery

$.ajax({
    url: 'http://mysite.microsoft.sample.xyz.com/api/mycall',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    type: "POST", /* or type:"GET" or type:"PUT" */
    dataType: "json",
    data: {
    },
    success: function (result) {
        console.log(result);
    },
    error: function () {
        console.log("error");
    }
});

Note: If you are looking for downloading content from a third-party website then this will not help you. You can try the following code, but not JavaScript.

System.Net.WebClient wc = new System.Net.WebClient();
string str = wc.DownloadString("http://mysite.microsoft.sample.xyz.com/api/mycall");

Find common substring between two strings

**Return the comman longest substring** 
def longestSubString(str1, str2):
    longestString = ""
    maxLength = 0
    for i in range(0, len(str1)):
        if str1[i] in str2:
            for j in range(i + 1, len(str1)):
                if str1[i:j] in str2:
                    if(len(str1[i:j]) > maxLength):
                        maxLength = len(str1[i:j])
                        longestString =  str1[i:j]
return longestString

Make Bootstrap's Carousel both center AND responsive?

On Boostrap 4 simply add mx-auto to your carousel image class.

<div class="carousel-item">
  <img class="d-block mx-auto" src="http://placehold.it/600x400" />
</div> 

Combine with the samples from the bootstrap carousel documentation as desired.

Are all Spring Framework Java Configuration injection examples buggy?

In your test, you are comparing the two TestParent beans, not the single TestedChild bean.

Also, Spring proxies your @Configuration class so that when you call one of the @Bean annotated methods, it caches the result and always returns the same object on future calls.

See here:

Install msi with msiexec in a Specific Directory

Actually, both INSTALLPATH/TARGETDIR are correct. It depends on how MSI processes this.

I create a MSG using wixToolSet. In WXS file, there is "Directory" Node, which root dir maybe like the following:

<Directory Id="**TARGETDIR**" Name="SourceDir">;

As you can see: Id is which you should use.

How can I apply a border only inside a table?

Due to mantain compatibility with ie7, ie8 I suggest using first-child and not last-child to doing this:

table tr td{border-top:1px solid #ffffff;border-left:1px solid #ffffff;}

table tr td:first-child{border-left:0;}

table tr:first-child td{border-top:0;}

You can learn about CSS 2.1 Pseudo-classes at: http://msdn.microsoft.com/en-us/library/cc351024(VS.85).aspx

How to get a list of images on docker registry v2

If some on get this far.

Taking what others have already said above. Here is a one-liner that puts the answer into a text file formatted, json.

curl "http://mydocker.registry.domain/v2/_catalog?n=2000" | jq . - > /tmp/registry.lst

This looks like

{
  "repositories": [
    "somerepo/somecontiner",
    "somerepo_other/someothercontiner",
 ...
  ]
}

You might need to change the `?n=xxxx' to match how many containers you have.

Next is a way to automatically remove old and unused containers.

Android - Best and safe way to stop thread

There are 2 following ways preferred to stop a thread.

  1. Create a volatile boolean variable and change its value to false and check inside the thread.

    volatile isRunning = false;
    
    public void run() {
    if(!isRunning) {return;}       
    
    }
    
  2. Or you can use the interrupt() method which can be receive inside a thread.

    SomeThread.interrupt();
    
    public void run() {
    if(Thread.currentThread.isInterrupted()) {return;}
     }
    

How to open maximized window with Javascript?

Checkout this jquery window plugin: http://fstoke.me/jquery/window/

// create a window
sampleWnd = $.window({
   .....
});

// resize the window by passed w,h parameter
sampleWnd.resize(screen.width, screen.height);

Http Post With Body

You can use HttpClient and HttpPost to send a json string as body:

public void post(String completeUrl, String body) {
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(completeUrl);
    httpPost.setHeader("Content-type", "application/json");
    try {
        StringEntity stringEntity = new StringEntity(body);
        httpPost.getRequestLine();
        httpPost.setEntity(stringEntity);

        httpClient.execute(httpPost);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

Json body example:

{
  "param1": "value 1",
  "param2": 123,
  "testStudentArray": [
    {
      "name": "Test Name 1",
      "gpa": 3.5
    },
    {
      "name": "Test Name 2",
      "gpa": 3.8
    }
  ]
}

C# how to create a Guid value?

Guid id = Guid.NewGuid();

Retrieve specific commit from a remote Git repository

In a project we had a problem so that we had to revert back to a certain commit. We made it with the following command successfully:

git reset --hard <commitID>

How do I get the collection of Model State Errors in ASP.NET MVC?

<% ViewData.ModelState.IsValid %>

or

<% ViewData.ModelState.Values.Any(x => x.Errors.Count >= 1) %>

and for a specific property...

<% ViewData.ModelState["Property"].Errors %> // Note this returns a collection

How to get only filenames within a directory using c#?

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GetNameOfFiles
{
    public class Program
    {
        static void Main(string[] args)
        {
           string[] fileArray = Directory.GetFiles(@"YOUR PATH");
           for (int i = 0; i < fileArray.Length; i++)
           {

               Console.WriteLine(fileArray[i]);
           }
            Console.ReadLine();
        }
    }
}

Async/Await Class Constructor

Variation on the builder pattern, using call():

function asyncMethod(arg) {
    function innerPromise() { return new Promise((...)=> {...}) }
    innerPromise().then(result => {
        this.setStuff(result);
    }
}

const getInstance = async (arg) => {
    let instance = new Instance();
    await asyncMethod.call(instance, arg);
    return instance;
}

How to construct a REST API that takes an array of id's for the resources

I find another way of doing the same thing by using @PathParam. Here is the code sample.

@GET
@Path("data/xml/{Ids}")
@Produces("application/xml")
public Object getData(@PathParam("zrssIds") String Ids)
{
  System.out.println("zrssIds = " + Ids);
  //Here you need to use String tokenizer to make the array from the string.
}

Call the service by using following url.

http://localhost:8080/MyServices/resources/cm/data/xml/12,13,56,76

where

http://localhost:8080/[War File Name]/[Servlet Mapping]/[Class Path]/data/xml/12,13,56,76

Call to undefined function mysql_query() with Login

What is your PHP version? Extension "Mysql" was deprecated in PHP 5.5.0. Use extension Mysqli (like mysqli_query).

Using Google Text-To-Speech in Javascript

Another option now may be HTML5 text to speech, which is in Chrome 33+ and many others.

Here is a sample:

var msg = new SpeechSynthesisUtterance('Hello World');
window.speechSynthesis.speak(msg);

With this, perhaps you do not need to use a web service at all.

jQuery check if an input is type checkbox?

>>> a=$("#communitymode")[0]
<input id="communitymode" type="checkbox" name="communitymode">
>>> a.type
"checkbox"

Or, more of the style of jQuery:

$("#myinput").attr('type') == 'checkbox'

How to quit android application programmatically

Easy and simple way to quit from the application

Intent homeIntent = new Intent(Intent.ACTION_MAIN);
homeIntent.addCategory(Intent.CATEGORY_HOME);
homeIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(homeIntent);

Oracle SQL escape character (for a '&')

The real answer is you need to set the escape character to '\': SET ESCAPE ON

The problem may have occurred either because escaping was disabled, or the escape character was set to something other than '\'. The above statement will enable escaping and set it to '\'.


None of the other answers previously posted actually answer the original question. They all work around the problem but don't resolve it.

Assigning more than one class for one event

    $('.tag1, .tag2').on('click', function() {

      if ($(this).hasClass('clickedTag')){
         // code here
      } else {
         // and here
      }

   });

or

function dothing() {
   if ($(this).hasClass('clickedTag')){
        // code here
    } else {
        // and here
   }
}

$('.tag1, .tag2').on('click', dothing);

or

 $('[class^=tag]').on('click', dothing);

Angular2 - Focusing a textbox on component load

Directive for autoFocus first field

_x000D_
_x000D_
import {_x000D_
  Directive,_x000D_
  ElementRef,_x000D_
  AfterViewInit_x000D_
} from "@angular/core";_x000D_
_x000D_
@Directive({_x000D_
  selector: "[appFocusFirstEmptyInput]"_x000D_
})_x000D_
export class FocusFirstEmptyInputDirective implements AfterViewInit {_x000D_
  constructor(private el: ElementRef) {}_x000D_
  ngAfterViewInit(): void {_x000D_
    const invalidControl = this.el.nativeElement.querySelector(".ng-untouched");_x000D_
    if (invalidControl) {_x000D_
      invalidControl.focus();_x000D_
    }_x000D_
  }_x000D_
}
_x000D_
_x000D_
_x000D_

How to hide Soft Keyboard when activity starts

In the AndroidManifest.xml:

<activity android:name="com.your.package.ActivityName"
          android:windowSoftInputMode="stateHidden"  />

or try

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN)??;

Please check this also

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

In my case it is because the server is giving http error occasionally. So basically once in a while my script gets the response like this rahter than the expected response:

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html>
<head><title>502 Bad Gateway</title></head>
<body bgcolor="white">
<h1>502 Bad Gateway</h1>
<p>The proxy server received an invalid response from an upstream server.<hr/>Powered by Tengine</body>
</html>

Clearly this is not in json format and trying to call .json() will yield JSONDecodeError: Expecting value: line 1 column 1 (char 0)

You can print the exact response that causes this error to better debug. For example if you are using requests and then simply print the .text field (before you call .json()) would do.

ASP.NET Web API session or something?

Well, REST by design is stateless. By adding session (or anything else of that kind) you are making it stateful and defeating any purpose of having a RESTful API.

The whole idea of RESTful service is that every resource is uniquely addressable using a universal syntax for use in hypermedia links and each HTTP request should carry enough information by itself for its recipient to process it to be in complete harmony with the stateless nature of HTTP".

So whatever you are trying to do with Web API here, should most likely be re-architectured if you wish to have a RESTful API.

With that said, if you are still willing to go down that route, there is a hacky way of adding session to Web API, and it's been posted by Imran here http://forums.asp.net/t/1780385.aspx/1

Code (though I wouldn't really recommend that):

public class MyHttpControllerHandler
  : HttpControllerHandler, IRequiresSessionState
{
    public MyHttpControllerHandler(RouteData routeData): base(routeData)
    { }
}

public class MyHttpControllerRouteHandler : HttpControllerRouteHandler
{
    protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        return new MyHttpControllerHandler(requestContext.RouteData);
    }
}

public class ValuesController : ApiController
{
   public string GET(string input)
   {
       var session = HttpContext.Current.Session;
       if (session != null)
       {
           if (session["Time"] == null)
           {
               session["Time"] = DateTime.Now;
           }
           return "Session Time: " + session["Time"] + input;
       }
       return "Session is not availabe" + input;
    }
}

and then add the HttpControllerHandler to your API route:

route.RouteHandler = new MyHttpControllerRouteHandler();

Pointers in C: when to use the ampersand and the asterisk?

I think you are a bit confused. You should read a good tutorial/book on pointers.

This tutorial is very good for starters(clearly explains what & and * are). And yeah don't forget to read the book Pointers in C by Kenneth Reek.

The difference between & and * is very clear.

Example:

#include <stdio.h>

int main(){
  int x, *p;

  p = &x;         /* initialise pointer(take the address of x) */
  *p = 0;         /* set x to zero */
  printf("x is %d\n", x);
  printf("*p is %d\n", *p);

  *p += 1;        /* increment what p points to i.e x */
  printf("x is %d\n", x);

  (*p)++;         /* increment what p points to i.e x */
  printf("x is %d\n", x);

  return 0;
}

How to get $HOME directory of different user in bash script?

I was struggling with this question because I was looking for a way to do this in a bash script for OS X, hence /etc/passwd was out of the question, and my script was meant to be executed as root, therefore making the solutions invoking eval or bash -c dangerous as they allowed code injection into the variable specifying the username.

Here is what I found. It's simple and doesn't put a variable inside a subshell. However it does require the script to be ran by root as it sudos into the specified user account.

Presuming that $SOMEUSER contains a valid username:

echo "$(sudo -H -u "$SOMEUSER" -s -- "cd ~ && pwd")"

I hope this helps somebody!

How can I solve "Either the parameter @objname is ambiguous or the claimed @objtype (COLUMN) is wrong."?

Are you running the query in the correct database? i.e.,

Use MyDatabase;
GO
EXEC sp_rename 'ENG_TEst.[ENG_Test_A/C_TYPE]', 'ENG_Test_AC_TYPE', 'COLUMN';
GO

Web API Put Request generates an Http 405 Method Not Allowed error

Your client application and server application must be under same domain, for example :

client - localhost

server - localhost

and not :

client - localhost:21234

server - localhost

How do I detect IE 8 with jQuery?

You should also look at jQuery.support. Feature detection is a lot more reliable than browser detection for coding your functionality (unless you are just trying to log browser versions).

How can I decrypt a password hash in PHP?

Bcrypt is a one-way hashing algorithm, you can't decrypt hashes. Use password_verify to check whether a password matches the stored hash:

<?php
// See the password_hash() example to see where this came from.
$hash = '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq';

if (password_verify('rasmuslerdorf', $hash)) {
    echo 'Password is valid!';
} else {
    echo 'Invalid password.';
}

In your case, run the SQL query using only the username:

$sql_script = 'SELECT * FROM USERS WHERE username=?';

And do the password validation in PHP using a code that is similar to the example above.

The way you are constructing the query is very dangerous. If you don't parameterize the input properly, the code will be vulnerable to SQL injection attacks. See this Stack Overflow answer on how to prevent SQL injection.

Convert file to byte array and vice versa

Apache FileUtil gives very handy methods to do the conversion

try {
    File file = new File(imagefilePath);
    byte[] byteArray = new byte[file.length()]();
    byteArray = FileUtils.readFileToByteArray(file);  
 }catch(Exception e){
     e.printStackTrace();

 }

NameError: name 'python' is not defined

When you run the Windows Command Prompt, and type in python, it starts the Python interpreter.

Typing it again tries to interpret python as a variable, which doesn't exist and thus won't work:

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Users\USER>python
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> python
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'python' is not defined
>>> print("interpreter has started")
interpreter has started
>>> quit() # leave the interpreter, and go back to the command line

C:\Users\USER>

If you're not doing this from the command line, and instead running the Python interpreter (python.exe or IDLE's shell) directly, you are not in the Windows Command Line, and python is interpreted as a variable, which you have not defined.

Laravel Eloquent limit and offset

Maybe this

$products = $art->products->take($limit)->skip($offset)->get();

How can I commit a single file using SVN over a network?

You can use

cd /You folder name
svn commit 'your file path' -m "Commit message you want to give"

You can also drage you files to command promt instead to write cd [common in MAC OSx]

C++ IDE for Macs

Code::Blocks is cross-platform, using the wxWidgets library. It's the one I use.

Reading from stdin

You can do something like this to read 10 bytes:

char buffer[10];
read(STDIN_FILENO, buffer, 10);

remember read() doesn't add '\0' to terminate to make it string (just gives raw buffer).

To read 1 byte at a time:

char ch;
while(read(STDIN_FILENO, &ch, 1) > 0)
{
 //do stuff
}

and don't forget to #include <unistd.h>, STDIN_FILENO defined as macro in this file.

There are three standard POSIX file descriptors, corresponding to the three standard streams, which presumably every process should expect to have:

Integer value   Name
       0        Standard input (stdin)
       1        Standard output (stdout)
       2        Standard error (stderr)

So instead STDIN_FILENO you can use 0.

Edit:
In Linux System you can find this using following command:

$ sudo grep 'STDIN_FILENO' /usr/include/* -R | grep 'define'
/usr/include/unistd.h:#define   STDIN_FILENO    0   /* Standard input.  */

Notice the comment /* Standard input. */

An efficient way to transpose a file in Bash

I normally use this little awk snippet for this requirement:

  awk '{for (i=1; i<=NF; i++) a[i,NR]=$i
        max=(max<NF?NF:max)}
        END {for (i=1; i<=max; i++)
              {for (j=1; j<=NR; j++) 
                  printf "%s%s", a[i,j], (j==NR?RS:FS)
              }
        }' file

This just loads all the data into a bidimensional array a[line,column] and then prints it back as a[column,line], so that it transposes the given input.

This needs to keep track of the maximum amount of columns the initial file has, so that it is used as the number of rows to print back.

In Perl, how can I read an entire file into a string?

I would do it like this:

my $file = "index.html";
my $document = do {
    local $/ = undef;
    open my $fh, "<", $file
        or die "could not open $file: $!";
    <$fh>;
};

Note the use of the three-argument version of open. It is much safer than the old two- (or one-) argument versions. Also note the use of a lexical filehandle. Lexical filehandles are nicer than the old bareword variants, for many reasons. We are taking advantage of one of them here: they close when they go out of scope.

Conda command is not recognized on Windows 10

If you have installed Visual studio 2017 (profressional)

The install location:

C:\ProgramData\Anaconda3\Scripts

If you do not want the hassle of putting this in your path environment variable on windows and restarting you can run it by simply:

C:\>"C:\ProgramData\Anaconda3\Scripts\conda.exe" update qt pyqt

How do I check out a specific version of a submodule using 'git submodule'?

Submodule repositories stay in a detached HEAD state pointing to a specific commit. Changing that commit simply involves checking out a different tag or commit then adding the change to the parent repository.

$ cd submodule
$ git checkout v2.0
Previous HEAD position was 5c1277e... bumped version to 2.0.5
HEAD is now at f0a0036... version 2.0

git-status on the parent repository will now report a dirty tree:

# On branch dev [...]
#
#   modified:   submodule (new commits)

Add the submodule directory and commit to store the new pointer.

Issue with adding common code as git submodule: "already exists in the index"

Go to the repository folder. Delete relevant submodules from .gitmodules. Select show hidden files. Go to .git folder, delete the submodules from module folder and config.

How to get the location of the DLL currently executing?

You are looking for System.Reflection.Assembly.GetExecutingAssembly()

string assemblyFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string xmlFileName = Path.Combine(assemblyFolder,"AggregatorItems.xml");

Note:

The .Location property returns the location of the currently running DLL file.

Under some conditions the DLL is shadow copied before execution, and the .Location property will return the path of the copy. If you want the path of the original DLL, use the Assembly.GetExecutingAssembly().CodeBase property instead.

.CodeBase contains a prefix (file:\), which you may need to remove.

Checking from shell script if a directory contains files

Could you compare the output of this?

 ls -A /some/dir | wc -l

How can I get just the first row in a result set AFTER ordering?

This question is similar to How do I limit the number of rows returned by an Oracle query after ordering?.

It talks about how to implement a MySQL limit on an oracle database which judging by your tags and post is what you are using.

The relevant section is:

select *
from  
  ( select * 
  from emp 
  order by sal desc ) 
  where ROWNUM <= 5;

How to run an android app in background?

As apps run in the background anyway. I’m assuming what your really asking is how do you make apps do stuff in the background. The solution below will make your app do stuff in the background after opening the app and after the system has rebooted.

Below, I’ve added a link to a fully working example (in the form of an Android Studio Project)

This subject seems to be out of the scope of the Android docs, and there doesn’t seem to be any one comprehensive doc on this. The information is spread across a few docs.

The following docs tell you indirectly how to do this: https://developer.android.com/reference/android/app/Service.html

https://developer.android.com/reference/android/content/BroadcastReceiver.html

https://developer.android.com/guide/components/bound-services.html

In the interests of getting your usage requirements correct, the important part of this above doc to read carefully is: #Binder, #Messenger and the components link below:

https://developer.android.com/guide/components/aidl.html

Here is the link to a fully working example (in Android Studio format): http://developersfound.com/BackgroundServiceDemo.zip

This project will start an Activity which binds to a service; implementing the AIDL.

This project is also useful to re-factor for the purpose of IPC across different apps.

This project is also developed to start automatically when Android restarts (provided the app has been run at least one after installation and app is not installed on SD card)

When this app/project runs after reboot, it dynamically uses a transparent view to make it look like no app has started but the service of the associated app starts cleanly.

This code is written in such a way that it’s very easy to tweak to simulate a scheduled service.

This project is developed in accordance to the above docs and is subsequently a clean solution.

There is however a part of this project which is not clean being: I have not found a way to start a service on reboot without using an Activity. If any of you guys reading this post have a clean way to do this please post a comment.

How to ensure a <select> form field is submitted when it is disabled?

Same solution suggested by Tres without using jQuery

<form onsubmit="document.getElementById('mysel').disabled = false;" action="..." method="GET">

   <select id="mysel" disabled="disabled">....</select>

   <input name="submit" id="submit" type="submit" value="SEND FORM">
</form>

This might help someone understand more, but obviously is less flexible than the jQuery one.

Delete multiple rows by selecting checkboxes using PHP

Something that sometimes crops up you may/maynot be aware of

Won't always be picked up by by $_POST['delete'] when using IE. Firefox and chrome should work fine though. I use a seperate isntead which solves the problem for IE

As for your not deleting in your code above you appear to be echoing out 2x sets of check boxes both pulling the same data? Is this just a copy + paste mistake or is this actually how your code is?

If its how your code is that'll be the problem as the user could be ticking one checkbox array item but the other one will be unchecked so the php code for delete is getting confused. Either rename the 2nd check box or delete that block of html surely you don't need to display the same list twice ?

What is a non-capturing group in regular expressions?

?: is used when you want to group an expression, but you do not want to save it as a matched/captured portion of the string.

An example would be something to match an IP address:

/(?:\d{1,3}\.){3}\d{1,3}/

Note that I don't care about saving the first 3 octets, but the (?:...) grouping allows me to shorten the regex without incurring the overhead of capturing and storing a match.

How to check if variable's type matches Type stored in a variable

You need to see if the Type of your instance is equal to the Type of the class. To get the type of the instance you use the GetType() method:

 u.GetType().Equals(t);

or

 u.GetType.Equals(typeof(User));

should do it. Obviously you could use '==' to do your comparison if you prefer.

The OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)"

I had the exact same error message, and tried the suggested solutions in this thread but without success.

what solved the problem for me is opening the .xlsx file and saving it as .xls (excel 2003) file.

maybe the file was corrupted or in a different format, and saving it again fixed it.

Adding an identity to an existing column

If the original poster was actually wanting to set an existing column to be a PRIMARY KEY for the table and actually did not need the column to be an IDENTITY column (two different things) then this can be done via t-SQL with:

ALTER TABLE [YourTableName]
ADD CONSTRAINT [ColumnToSetAsPrimaryKey] PRIMARY KEY ([ColumnToSetAsPrimaryKey])

Note the parenthesis around the column name after the PRIMARY KEY option.

Although this post is old and I am making an assumption about the requestors need, I felt this additional information could be helpful to users encountering this thread as I believe the conversation could lead one to believe that an existing column can not be set to be a primary key without adding it as a new column first which would be incorrect.

Creating all possible k combinations of n items in C++

It can also be done using backtracking by maintaining a visited array.

void foo(vector<vector<int> > &s,vector<int> &data,int go,int k,vector<int> &vis,int tot)
{

    vis[go]=1;
    data.push_back(go);
    if(data.size()==k)
    {
        s.push_back(data);
        vis[go]=0;
    data.pop_back();
        return;
    }

    for(int i=go+1;i<=tot;++i)
    {
       if(!vis[i])
       {
           foo(s,data,i,k,vis,tot);
       }
    }
    vis[go]=0;
    data.pop_back();
}


vector<vector<int> > Solution::combine(int n, int k) {
   vector<int> data;
   vector<int> vis(n+1,0);
   vector<vector<int> > sol;
   for(int i=1;i<=n;++i)
   {
       for(int i=1;i<=n;++i) vis[i]=0;
   foo(sol,data,i,k,vis,n);
   }
   return sol;

}

Min/Max-value validators in asp.net mvc

Here is how I would write a validator for MaxValue

public class MaxValueAttribute : ValidationAttribute
    {
        private readonly int _maxValue;

        public MaxValueAttribute(int maxValue)
        {
            _maxValue = maxValue;
        }

        public override bool IsValid(object value)
        {
            return (int) value <= _maxValue;
        }
    }

The MinValue Attribute should be fairly the same

Change Select List Option background colour on hover

In FF also CSS filter works fine. E.g. hue-rotate:

option {
    filter: hue-rotate(90deg);
}

https://jsfiddle.net/w3a740jq/4/

LINQ: "contains" and a Lambda query

The Linq extension method Any could work for you...

buildingStatus.Any(item => item.GetCharValue() == v.Status)

Flutter: Trying to bottom-center an item in a Column, but it keeps left-aligning

Just expanding the answers:

  • Spacer is an option no one mentioned yet; it is used in case you prefer not to use Positioned / Align.
  • Align works if you want to specify the alignment of a child inside a parent. Use it anywhere but directly inside Stack
  • Positioned is similar to Align, but works only under Stack directly.

How do I check if file exists in jQuery or pure JavaScript?

This doesn't address the OP's question, but for anyone who is returning results from a database: here's a simple method I used.

If the user didn't upload an avatar the avatar field would be NULL, so I'd insert a default avatar image from the img directory.

function getAvatar(avatar) {
    if(avatar == null) {
        return '/img/avatar.jpg';
    } else {
        return '/avi/' + avatar;
    }
}

then

<img src="' + getAvatar(data.user.avatar) + '" alt="">

Make git automatically remove trailing whitespace before committing

Those settings (core.whitespace and apply.whitespace) are not there to remove trailing whitespace but to:

  • core.whitespace: detect them, and raise errors
  • apply.whitespace: and strip them, but only during patch, not "always automatically"

I believe the git hook pre-commit would do a better job for that (includes removing trailing whitespace)


Note that at any given time you can choose to not run the pre-commit hook:

  • temporarily: git commit --no-verify .
  • permanently: cd .git/hooks/ ; chmod -x pre-commit

Warning: by default, a pre-commit script (like this one), has not a "remove trailing" feature", but a "warning" feature like:

if (/\s$/) {
    bad_line("trailing whitespace", $_);
}

You could however build a better pre-commit hook, especially when you consider that:

Committing in Git with only some changes added to the staging area still results in an “atomic” revision that may never have existed as a working copy and may not work.


For instance, oldman proposes in another answer a pre-commit hook which detects and remove whitespace.
Since that hook get the file name of each file, I would recommend to be careful for certain type of files: you don't want to remove trailing whitespace in .md (markdown) files!

Using PHP to upload file and add the path to MySQL database

First you should use print_r($_FILES) to debug, and see what it contains. :

your uploads.php would look like:

//This is the directory where images will be saved
$target = "pics/";
$target = $target . basename( $_FILES['Filename']['name']);

//This gets all the other information from the form
$Filename=basename( $_FILES['Filename']['name']);
$Description=$_POST['Description'];


//Writes the Filename to the server
if(move_uploaded_file($_FILES['Filename']['tmp_name'], $target)) {
    //Tells you if its all ok
    echo "The file ". basename( $_FILES['Filename']['name']). " has been uploaded, and your information has been added to the directory";
    // Connects to your Database
    mysql_connect("localhost", "root", "") or die(mysql_error()) ;
    mysql_select_db("altabotanikk") or die(mysql_error()) ;

    //Writes the information to the database
    mysql_query("INSERT INTO picture (Filename,Description)
    VALUES ('$Filename', '$Description')") ;
} else {
    //Gives and error if its not
    echo "Sorry, there was a problem uploading your file.";
}



?>

EDIT: Since this is old post, currently it is strongly recommended to use either mysqli or pdo instead mysql_ functions in php

Excel VBA Open a Folder

I use this to open a workbook and then copy that workbook's data to the template.

Private Sub CommandButton24_Click()
Set Template = ActiveWorkbook
 With Application.FileDialog(msoFileDialogOpen)
    .InitialFileName = "I:\Group - Finance" ' Yu can select any folder you want
    .Filters.Clear
    .Title = "Your Title"
    If Not .Show Then
        MsgBox "No file selected.": Exit Sub
    End If
    Workbooks.OpenText .SelectedItems(1)

'The below is to copy the file into a new sheet in the workbook and paste those values in sheet 1

    Set myfile = ActiveWorkbook
    ActiveWorkbook.Sheets(1).Copy after:=ThisWorkbook.Sheets(1)
    myfile.Close
    Template.Activate
    ActiveSheet.Cells.Select
    Selection.Copy
    Sheets("Sheet1").Select
    Cells.Select
    ActiveSheet.Paste

End With

WP -- Get posts by category?

add_shortcode( 'seriesposts', 'series_posts' );

function series_posts( $atts )
{ ob_start();

$myseriesoption = get_option( '_myseries', null );

$type = $myseriesoption;
$args=array(  'post_type' => $type,  'post_status' => 'publish',  'posts_per_page' => 5,  'caller_get_posts'=> 1);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
echo '<ul>'; 
while ($my_query->have_posts()) : $my_query->the_post();
echo '<li><a href="';
echo the_permalink();
echo '">';
echo the_title();
echo '</a></li>'; 
endwhile;
echo '</ul>'; 
}
wp_reset_query();




return ob_get_clean(); }

//this will generate a shortcode function to be used on your site [seriesposts]

Find all packages installed with easy_install/pip?

For those who don't have pip installed, I found this quick script on github (works with Python 2.7.13):

import pkg_resources
distros = pkg_resources.AvailableDistributions()
for key in distros:
  print distros[key]

Hosting ASP.NET in IIS7 gives Access is denied?

In my case running c:\windows\Microsoft.Net\Framework64\v4.0.30319\aspnet_regiis.exe /i resolved the 403 access denied issue.

How to set cookie in node js using express framework?

Setting cookie in the express is easy

  1. first install cookie parser
npm install cookie parser
  1. using middleware
const cookieParser = require('cookie-parser');
app.use(cookieParser());
  1. Set cookie know more
res.cookie('cookieName', '1', { expires: new Date(Date.now() + 900000), httpOnly: true })
  1. Accessing that cookie know more
console.dir(req.cookies.cookieName)

How to check if IsNumeric

You could write an extension method:

public static class Extension
{
    public static bool IsNumeric(this string s)
    {
        float output;
        return float.TryParse(s, out output);
    }
}

c++ array - expression must have a constant value

When you declare a variable as here

int a[10][10];

you are telling the C++ compiler that you want 100 consecutive integers allocated in the program's memory at runtime. The compiler will then provide for your program to have that much memory available and all is well with the world.

If however you tell the compiler

int x = 9001;
int y = 5;
int a[x][y];

the compiler has no way of knowing how much memory you are actually going to need at run time without doing a lot of very complex analysis to track down every last place where the values of x and y changed [if any]. Rather than support such variable size arrays, C++ and C strongly suggest if not outright demand that you use malloc() to manually allocate the space you want.

TL;DR

int x = 5;
int y = 5;
int **a = malloc(x*sizeof(int*));
for(int i = 0; i < y; i++) {
    a[i] = malloc(sizeof(int*)*y);
}

a is now a 2D array of size 5x5 and will behave the same as int a[5][5]. Because you have manually allocated memory, C++ and C demand that you delete it by hand too...

for(int i = 0; i < x; i++) {
    free(a[i]); // delete the 2nd dimension array
}
free(a); // delete a itself

How can I get the nth character of a string?

You would do:

char c = str[1];

Or even:

char c = "Hello"[1];

edit: updated to find the "E".

How to add a "open git-bash here..." context menu to the windows explorer?

Usually git bash here can be run only on directories so you have to go up a directory and right click on the previous directory then select git bash here (of course on Windows OS).
Note: context menu inside a directory does not have a git bash here option.

Django: Display Choice Value

It looks like you were on the right track - get_FOO_display() is most certainly what you want:

In templates, you don't include () in the name of a method. Do the following:

{{ person.get_gender_display }}

How to add buttons at top of map fragment API v2 layout

extending de Almeida's answer I am editing code little bit here. since previous code was hiding gps location icon I did following way which worked better.

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"

>

<RadioGroup 
    android:id="@+id/radio_group_list_selector"
    android:layout_width="match_parent"
    android:layout_height="48dp"
    android:orientation="horizontal" 
    android:background="#80000000"
    android:padding="4dp" >

    <RadioButton
        android:id="@+id/radioPopular"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:text="@string/Popular"
        android:gravity="center_horizontal|center_vertical"
        android:layout_weight="1"
        android:button="@null"
        android:background="@drawable/shape_radiobutton"
        android:textColor="@drawable/textcolor_radiobutton" />
    <View
        android:id="@+id/VerticalLine"
        android:layout_width="1dip"
        android:layout_height="match_parent"
        android:background="#aaa" />

    <RadioButton
        android:id="@+id/radioAZ"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:gravity="center_horizontal|center_vertical"
        android:text="@string/AZ"
        android:layout_weight="1"
        android:button="@null"
        android:background="@drawable/shape_radiobutton2"
        android:textColor="@drawable/textcolor_radiobutton" />

    <View
        android:id="@+id/VerticalLine"
        android:layout_width="1dip"
        android:layout_height="match_parent"
        android:background="#aaa" />

    <RadioButton
        android:id="@+id/radioCategory"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:gravity="center_horizontal|center_vertical"
        android:text="@string/Category"
        android:layout_weight="1"
        android:button="@null"
        android:background="@drawable/shape_radiobutton2"
        android:textColor="@drawable/textcolor_radiobutton" />
    <View
        android:id="@+id/VerticalLine"
        android:layout_width="1dip"
        android:layout_height="match_parent"
        android:background="#aaa" />

    <RadioButton
        android:id="@+id/radioNearBy"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:gravity="center_horizontal|center_vertical"
        android:text="@string/NearBy"
        android:layout_weight="1"
        android:button="@null"
        android:background="@drawable/shape_radiobutton3"
        android:textColor="@drawable/textcolor_radiobutton" />
</RadioGroup>

<fragment
    xmlns:map="http://schemas.android.com/apk/res-auto"
    android:id="@+id/map"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    class="com.google.android.gms.maps.SupportMapFragment"
    android:scrollbars="vertical" />

SQL Query Where Date = Today Minus 7 Days

You can subtract 7 from the current date with this:

WHERE datex BETWEEN DATEADD(day, -7, GETDATE()) AND GETDATE()

How to get the screen width and height in iOS?

Here is a Swift way to get screen sizes:

print(screenWidth)
print(screenHeight)

var screenWidth: CGFloat {
    if UIInterfaceOrientationIsPortrait(screenOrientation) {
        return UIScreen.mainScreen().bounds.size.width
    } else {
        return UIScreen.mainScreen().bounds.size.height
    }
}

var screenHeight: CGFloat {
    if UIInterfaceOrientationIsPortrait(screenOrientation) {
        return UIScreen.mainScreen().bounds.size.height
    } else {
        return UIScreen.mainScreen().bounds.size.width
    }
}

var screenOrientation: UIInterfaceOrientation {
    return UIApplication.sharedApplication().statusBarOrientation
}

These are included as a standard function in:

https://github.com/goktugyil/EZSwiftExtensions

Getting result of dynamic SQL into a variable for sql-server

DECLARE @sqlCommand nvarchar(1000)
DECLARE @city varchar(75)
DECLARE @cnt int
SET @city = 'London'
SET @sqlCommand = 'SELECT @cnt=COUNT(*) FROM customers WHERE City = @city'
EXECUTE sp_executesql @sqlCommand, N'@city nvarchar(75)', @city = @city
RETURN @cnt

Datatables - Search Box outside datatable

More recent versions have a different syntax:

var table = $('#example').DataTable();

// #myInput is a <input type="text"> element
$('#myInput').on('keyup change', function () {
    table.search(this.value).draw();
});

Note that this example uses the variable table assigned when datatables is first initialised. If you don't have this variable available, simply use:

var table = $('#example').dataTable().api();

// #myInput is a <input type="text"> element
$('#myInput').on('keyup change', function () {
    table.search(this.value).draw();
});

Since: DataTables 1.10

– Source: https://datatables.net/reference/api/search()

write multiple lines in a file in python

with open('target.txt','w') as out:
    line1 = raw_input("line 1: ")
    line2 = raw_input("line 2: ")
    line3 = raw_input("line 3: ")
    print("I'm going to write these to the file.")
    out.write('{}\n{}\n{}\n'.format(line1,line2,line3))

Where are my postgres *.conf files?

On Fedora 20

$ cd /var/lib/pgsql/data
$ ls -ltr *.conf

-rw-------. 1 postgres postgres 20453 Jan 18 23:22 postgresql.conf
-rw-------. 1 postgres postgres  1636 Jan 18 23:22 pg_ident.conf
-rw-------. 1 postgres postgres  4476 Jan 18 23:22 pg_hba.conf

Run Stored Procedure in SQL Developer?

Using SQL Developer Version 4.0.2.15 Build 15.21 the following works:

SET SERVEROUTPUT ON
var InParam1 varchar2(100)
var InParam2 varchar2(100)
var InParam3 varchar2(100)
var OutParam1 varchar2(100)

BEGIN
    /* Assign values to IN parameters */
    :InParam1 := 'one';
    :InParam2 := 'two';
    :InParam3 := 'three';

    /* Call procedure within package, identifying schema if necessary */
    schema.package.procedure(:InParam1, :InParam2, :InParam3, :OutParam1);
    dbms_output.enable;
    dbms_output.put_line('OutParam1: ' || :OutParam1);
END;
/

Official way to ask jQuery wait for all images to load before executing something

None of the answers so far have given what seems to be the simplest solution.

$('#image_id').load(
  function () {
    //code here
});

I want to use CASE statement to update some records in sql server 2005

Add a WHERE clause

UPDATE dbo.TestStudents  
SET     LASTNAME =  CASE  
                        WHEN LASTNAME = 'AAA' THEN 'BBB' 
                        WHEN LASTNAME = 'CCC' THEN 'DDD' 
                        WHEN LASTNAME = 'EEE' THEN 'FFF' 
                        ELSE LASTNAME
                    END 
WHERE   LASTNAME IN ('AAA', 'CCC', 'EEE')

Why do I need an IoC container as opposed to straightforward DI code?

Dependency Injection in an ASP.NET project can be accomplished with a few lines of code. I suppose there is some advantage to using a container when you have an app that uses multiple front ends and needs unit tests.

call a static method inside a class?

This is a very late response, but adds some detail on the previous answers

When it comes to calling static methods in PHP from another static method on the same class, it is important to differentiate between self and the class name.

Take for instance this code:

class static_test_class {
    public static function test() {
        echo "Original class\n";
    }

    public static function run($use_self) {
        if($use_self) {
            self::test();
        } else {
            $class = get_called_class();
            $class::test(); 
        }
    }
}

class extended_static_test_class extends static_test_class {
    public static function test() {
        echo "Extended class\n";
    }
}

extended_static_test_class::run(true);
extended_static_test_class::run(false);

The output of this code is:

Original class

Extended class

This is because self refers to the class the code is in, rather than the class of the code it is being called from.

If you want to use a method defined on a class which inherits the original class, you need to use something like:

$class = get_called_class();
$class::function_name(); 

How to call javascript function from asp.net button click event

If you don't need to initiate a post back when you press this button, then making the overhead of a server control isn't necesary.

<input id="addButton" type="button" value="Add" />

<script type="text/javascript" language="javascript">
     $(document).ready(function()
     {
         $('#addButton').click(function() 
         { 
             showDialog('#addPerson'); 
         });
     });
</script>

If you still need to be able to do a post back, you can conditionally stop the rest of the button actions with a little different code:

<asp:Button ID="buttonAdd" runat="server" Text="Add" />

<script type="text/javascript" language="javascript">
     $(document).ready(function()
     {
         $('#<%= buttonAdd.ClientID %>').click(function(e) 
         { 
             showDialog('#addPerson');

             if(/*Some Condition Is Not Met*/) 
                return false;
         });
     });
</script>

Is it possible to get a history of queries made in postgres

pgBadger is another option - also listed here: https://github.com/dhamaniasad/awesome-postgres#utilities

Requires some additional setup in advance to capture the necessary data in the postgres logs though, see the official website.

How to change default timezone for Active Record in Rails?

On rails 4.2.2, go to application.rb and use config.time_zone='city' (e.g.:'London' or 'Bucharest' or 'Amsterdam' and so on).

It should work just fine. It worked for me.

SQLite: How do I save the result of a query as a CSV file?

In addition to the above answers you can also use .once in a similar way to .output. This outputs only the next query to the specified file, so that you don't have to follow with .output stdout.

So in the above example

.mode csv
.headers on
.once test.csv
select * from tbl1;

How to refresh page on back button click?

A more recent solution is using the The PerformanceNavigation interface:

if(!!window.performance && window.performance.navigation.type === 2)
{
    console.log('Reloading');
    window.location.reload();
}

Where the value 2 means "The page was accessed by navigating into the history".

View browser support here: http://caniuse.com/#search=Navigation%20Timing%20API

Reload the site when reached via browsers back button

How to run function in AngularJS controller on document ready?

Angular initializes automatically upon DOMContentLoaded event or when the angular.js script is evaluated if at that time document.readyState is set to 'complete'. At this point Angular looks for the ng-app directive which designates your application root.

https://docs.angularjs.org/guide/bootstrap

This means that the controller code will run after the DOM is ready.

Thus it's just $scope.init().

Limit text length to n lines using CSS

Basic Example Code, learning to code is easy. Check Style CSS comments.

_x000D_
_x000D_
table tr {_x000D_
  display: flex;_x000D_
}_x000D_
table tr td {_x000D_
  /* start */_x000D_
  display: inline-block; /* <- Prevent <tr> in a display css */_x000D_
  text-overflow: ellipsis;_x000D_
  white-space: nowrap;_x000D_
  /* end */_x000D_
  padding: 10px;_x000D_
  width: 150px; /* Space size limit */_x000D_
  border: 1px solid black;_x000D_
  overflow: hidden;_x000D_
}
_x000D_
<table>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td>_x000D_
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla egestas erat ut luctus posuere. Praesent et commodo eros. Vestibulum eu nisl vel dui ultrices ultricies vel in tellus._x000D_
      </td>_x000D_
      <td>_x000D_
        Praesent vitae tempus nulla. Donec vel porta velit. Fusce mattis enim ex. Mauris eu malesuada ante. Aenean id aliquet leo, nec ultricies tortor. Curabitur non mollis elit. Morbi euismod ante sit amet iaculis pharetra. Mauris id ultricies urna. Cras ut_x000D_
        nisi dolor. Curabitur tellus erat, condimentum ac enim non, varius tempor nisi. Donec dapibus justo odio, sed consequat eros feugiat feugiat._x000D_
      </td>_x000D_
      <td>_x000D_
        Pellentesque mattis consequat ipsum sed sagittis. Pellentesque consectetur vestibulum odio, aliquet auctor ex elementum sed. Suspendisse porta massa nisl, quis molestie libero auctor varius. Ut erat nibh, fringilla sed ligula ut, iaculis interdum sapien._x000D_
        Ut dictum massa mi, sit amet interdum mi bibendum nec._x000D_
      </td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>_x000D_
        Sed viverra massa laoreet urna dictum, et fringilla dui molestie. Duis porta, ligula ut venenatis pretium, sapien tellus blandit felis, non lobortis orci erat sed justo. Vivamus hendrerit, quam at iaculis vehicula, nibh nisi fermentum augue, at sagittis_x000D_
        nibh dui et erat._x000D_
      </td>_x000D_
      <td>_x000D_
        Nullam mollis nulla justo, nec tincidunt urna suscipit non. Donec malesuada dolor non dolor interdum, id ultrices neque egestas. Integer ac ante sed magna gravida dapibus sit amet eu diam. Etiam dignissim est sit amet libero dapibus, in consequat est_x000D_
        aliquet._x000D_
      </td>_x000D_
      <td>_x000D_
        Vestibulum mollis, dui eu eleifend tincidunt, erat eros tempor nibh, non finibus quam ante nec felis. Fusce egestas, orci in volutpat imperdiet, risus velit convallis sapien, sodales lobortis risus lectus id leo. Nunc vel diam vel nunc congue finibus._x000D_
        Vestibulum turpis tortor, pharetra sed ipsum eu, tincidunt imperdiet lorem. Donec rutrum purus at tincidunt sagittis. Quisque nec hendrerit justo._x000D_
      </td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

npm global path prefix

Try running:

PATH=$PATH:~/npm/bin

and then do a test by running express in the command line. This worked for me.

Setting the zoom level for a MKMapView

You can also zoom by using MKCoordinateRegion and setting its span latitude & longitude delta. Below is a quick reference and here is the iOS reference. It won't do anything fancy but should allow you to set zoom when it draws the map.


MKCoordinateRegion region;
region.center.latitude = {desired lat};
region.center.longitude = {desired lng};
region.span.latitudeDelta = 1;
region.span.longitudeDelta = 1;
mapView.region = region;

Edit 1:

MKCoordinateRegion region;
region.center.latitude = {desired lat};
region.center.longitude = {desired lng};
region.span.latitudeDelta = 1;
region.span.longitudeDelta = 1;
region = [mapView regionThatFits:region];
[mapView setRegion:region animated:TRUE];

DataRow: Select cell value by a given column name

You can get the column value in VB.net

Dim row As DataRow = fooTable.Rows(0)
Dim temp = Convert.ToString(row("ColumnName"))

And in C# you can use Jimmy's Answer, just be careful while converting it to ToString(). It can throw null exception if the data is null instead Use Convert.ToString(your_expression) to avoid null exception reference

How to include scripts located inside the node_modules folder?

To use multiple files from node_modules in html, the best way I've found is to put them to an array and then loop on them to make them visible for web clients, for example to use filepond modules from node_modules:

const filePondModules = ['filepond-plugin-file-encode', 'filepond-plugin-image-preview', 'filepond-plugin-image-resize', 'filepond']
filePondModules.forEach(currentModule => {
    let module_dir = require.resolve(currentModule)
                           .match(/.*\/node_modules\/[^/]+\//)[0];
    app.use('/' + currentModule, express.static(module_dir + 'dist/'));
})

And then in the html (or layout) file, just call them like this :

    <link rel="stylesheet" href="/filepond/filepond.css">
    <link rel="stylesheet" href="/filepond-plugin-image-preview/filepond-plugin-image-preview.css">
...
    <script src="/filepond-plugin-image-preview/filepond-plugin-image-preview.js" ></script>
    <script src="/filepond-plugin-file-encode/filepond-plugin-file-encode.js"></script>
    <script src="/filepond-plugin-image-resize/filepond-plugin-image-resize.js"></script>
    <script src="/filepond/filepond.js"></script>

Docker Repository Does Not Have a Release File on Running apt-get update on Ubuntu

Warning: Use the below steps at your own risk. You may receive different results as indicated in the comments. Please exercise caution and have a full backup prior to doing this.

Below is a list of steps used to solve the issue:

  1. Remove Docker (this won't delete images, containers, volumes, or customized configuration files):

    sudo apt-get purge docker-engine

  2. Remove the Docker apt key:

    sudo apt-key del 58118E89F3A912897C070ADBF76221572C52609D

  3. Delete the docker.list file:

    sudo rm /etc/apt/sources.list.d/docker.list

  4. Manually delete apt cache files:

    sudo rm /var/lib/apt/lists/apt.dockerproject.org_repo_dists_ubuntu-xenial_*

  5. Delete apt-transport-https and ca-certificates:

    sudo apt-get purge apt-transport-https ca-certificates

  6. Clean apt and perform autoremove:

    sudo apt-get clean && sudo apt-get autoremove

  7. Reboot Ubuntu:

    sudo reboot

  8. Run apt-get update:

    sudo apt-get update

  9. Install apt-transport-https and ca-certificates again:

    sudo apt-get install apt-transport-https ca-certificates

  10. Add the apt key:

> sudo apt-key adv \
       --keyserver hkp://ha.pool.sks-keyservers.net:80 \
       --recv-keys 58118E89F3A912897C070ADBF76221572C52609D
  1. Add the docker.list file again:
> echo "deb https://apt.dockerproject.org/repo ubuntu-xenial main" |
sudo tee /etc/apt/sources.list.d/docker.list
  1. Run apt-get update:
> sudo apt-get update
  1. Install Docker:
> sudo apt-get install docker-engine

Granted, there are plenty of variables and your results may vary. However, these steps cover as many areas as possible to ensure potential problem spots are scrubbed so that the likelihood of success is higher.

Update 7/6/2017

It appears newer versions of Docker are using a different installation process which should eliminate many of these problems. Be sure to check out https://docs.docker.com/engine/installation/linux/ubuntu/.

NuGet auto package restore does not work with MSBuild

There is a packages.config file with the project, it contains the package details.

Also there is a .nuget folder which contains the NuGet.exe and NuGet.targets. if any one of the file is missing it will not restore the missing package and cause "are you missing a using directive or an assembly reference?" error

Why is __dirname not defined in node REPL?

If you got node __dirname not defined with node --experimental-modules, you can do :

const __dirname = path.dirname(import.meta.url)
                      .replace(/^file:\/\/\//, '') // can be usefull

Because othe example, work only with current/pwd directory not other directory.

How can I display an image from a file in Jupyter Notebook?

from IPython.display import Image

Image(filename =r'C:\user\path')

I've seen some solutions and some wont work because of the raw directory, when adding codes like the one above, just remember to add 'r' before the directory. this should avoid this kind of error: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

writing integer values to a file using out.write()

any of these should work

outf.write("%s" % num)

outf.write(str(num))

print >> outf, num

SQL Server ON DELETE Trigger

I would suggest the use of exists instead of in because in some scenarios that implies null values the behavior is different, so

CREATE TRIGGER sampleTrigger
    ON database1.dbo.table1
    FOR DELETE
AS
    DELETE FROM database2.dbo.table2 childTable
    WHERE bar = 4 AND exists (SELECT id FROM deleted where deleted.id = childTable.id)
GO

msvcr110.dll is missing from computer error while installing PHP

I was missing the MSVCR110.dll. Which I corrected. I could run php from the command line but not the web server. Then I clicked on php-cgi.exe and it gave me the answer. The php5.dll was missing (I downloaded the wrong copy). So for my 2012 IIS box I re-installed using php's x86 non thread safe zip.

How to upload files to server using Putty (ssh)

"C:\Program Files\PuTTY\pscp.exe" -scp file.py server.com:

file.py will be uploaded into your HOME dir on remote server.

or when the remote server has a different user, use "C:\Program Files\PuTTY\pscp.exe" -l username -scp file.py server.com:

After connecting to the server pscp will ask for a password.

How to collapse blocks of code in Eclipse?

I was using salesforce apex classes with Eclipse Neon 3.3 for Java.
I found an option "define folding region" on right click in the editor, I selected the block of code i wanted to collapse and selected this property for that code. Now I am seeing + and - symbol to expand and collapse that block of code

How find out which process is using a file in Linux?

You can use the fuser command, like:

fuser file_name

You will receive a list of processes using the file.

You can use different flags with it, in order to receive a more detailed output.

You can find more info in the fuser's Wikipedia article, or in the man pages.

How to repair a serialized string which has been corrupted by an incorrect byte count length?

public function unserializeKeySkills($string) {
    $output = array();
    $string = trim(preg_replace('/\s\s+/', ' ',$string));
    $string = preg_replace_callback('!s:(\d+):"(.*?)";!', function($m) { return 's:'.strlen($m[2]).':"'.$m[2].'";'; }, utf8_encode( trim(preg_replace('/\s\s+/', ' ',$string)) ));
    try {
        $output =  unserialize($string);
    } catch (\Exception $e) {
        \Log::error("unserialize Data : " .print_r($string,true));
    }
    return $output;
}

MAC addresses in JavaScript

No you cannot get the MAC address in JavaScript, mainly because the MAC address uniquely identifies the running computer so it would be a security vulnerability.

Now if all you need is a unique identifier, I suggest you create one yourself using some cryptographic algorithm and store it in a cookie.

If you really need to know the MAC address of the computer AND you are developing for internal applications, then I suggest you use an external component to do that: ActiveX for IE, XPCOM for Firefox (installed as an extension).

Regex: match word that ends with "Id"

Try this regular expression:

\w*Id\b

\w* allows word characters in front of Id and the \b ensures that Id is at the end of the word (\b is word boundary assertion).

how to use concatenate a fixed string and a variable in Python

If you need to add two strings you have to use the '+' operator

hence

msg['Subject'] = 'your string' + sys.argv[1]

and also you have to import sys in the beginning

as

import sys

msg['Subject'] = "Auto Hella Restart Report " + sys.argv[1]

apache mod_rewrite is not working or not enabled

To get mod_rewrite to work for me in Apache 2.4, I had to add the "Require all granted" line below.

<Directory /var/www>
   # Required if running apache > 2.4
   Require all granted

   RewriteEngine on 
   RewriteRule ^cachebust-([a-z0-9]+)\/(.*) /$2 [L] 
 </Directory>

supposedly a similar requirement exists for Apache 2.2 as well, if you're using that:

<Directory /var/www>
   # Required if running apache 2.2
   Order allow,deny
   Allow from all

   RewriteEngine on 
   RewriteRule ^cachebust-([a-z0-9]+)\/(.*) /$2 [L] 
 </Directory>

Note that an ErrorDocument 404 directive can sometimes override these things as well, so if it's not working try commenting out your ErrorDocument directive and see if it works. The above example can be used to ensure a site isn't served from cache by including a subfolder in the path, though the files reside at the root of the server.

How to press back button in android programmatically?

onBackPressed() is supported since: API Level 5

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_BACK)) {
        onBackPressed();
    }
}

@Override
public void onBackPressed() {
    //this is only needed if you have specific things
    //that you want to do when the user presses the back button.
    /* your specific things...*/
    super.onBackPressed();   
}

How to receive POST data in django

res = request.GET['paymentid'] will raise a KeyError if paymentid is not in the GET data.

Your sample php code checks to see if paymentid is in the POST data, and sets $payID to '' otherwise:

$payID = isset($_POST['paymentid']) ? $_POST['paymentid'] : ''

The equivalent in python is to use the get() method with a default argument:

payment_id = request.POST.get('payment_id', '')

while debugging, this is what I see in the response.GET: <QueryDict: {}>, request.POST: <QueryDict: {}>

It looks as if the problem is not accessing the POST data, but that there is no POST data. How are you are debugging? Are you using your browser, or is it the payment gateway accessing your page? It would be helpful if you shared your view.

Once you are managing to submit some post data to your page, it shouldn't be too tricky to convert the sample php to python.

Sorting list based on values from another list

Also, if you don't mind using numpy arrays (or in fact already are dealing with numpy arrays...), here is another nice solution:

people = ['Jim', 'Pam', 'Micheal', 'Dwight']
ages = [27, 25, 4, 9]

import numpy
people = numpy.array(people)
ages = numpy.array(ages)
inds = ages.argsort()
sortedPeople = people[inds]

I found it here: http://scienceoss.com/sort-one-list-by-another-list/

Get screen width and height in Android

For kotlin user's

fun Activity.displayMetrics(): DisplayMetrics {
   val displayMetrics = DisplayMetrics()
   windowManager.defaultDisplay.getMetrics(displayMetrics)
   return displayMetrics
}

And in Activity you could use it like

     resources.displayMetrics.let { displayMetrics ->
        val height = displayMetrics.heightPixels
        val width = displayMetrics.widthPixels
    }

Or in fragment

    activity?.displayMetrics()?.run {
        val height = heightPixels
        val width = widthPixels
    }

How to count the number of lines of a string in javascript

I was testing out the speed of the functions, and I found consistently that this solution that I had written was much faster than matching. We check the new length of the string as compared to the previous length.

const lines = str.length - str.replace(/\n/g, "").length+1;

_x000D_
_x000D_
let str = `Line1
Line2
Line3`;
console.time("LinesTimer")
console.log("Lines: ",str.length - str.replace(/\n/g, "").length+1);
console.timeEnd("LinesTimer")
_x000D_
_x000D_
_x000D_

Styling Form with Label above Inputs

You could try something like

<form name="message" method="post">
    <section>
    <div>
      <label for="name">Name</label>
      <input id="name" type="text" value="" name="name">
    </div>
    <div>
      <label for="email">Email</label>
      <input id="email" type="text" value="" name="email">
    </div>
    </section>
    <section>
    <div>
      <label for="subject">Subject</label>
      <input id="subject" type="text" value="" name="subject">
    </div>
    <div class="full">
      <label for="message">Message</label>
      <input id="message" type="text" value="" name="message">
    </div>
    </section>
</form>

and then css it like

form { width: 400px; }
form section div { float: left; }
form section div.full { clear: both; }
form section div label { display: block; }

In Unix, how do you remove everything in the current directory and below it?

I believe this answer is better:

https://unix.stackexchange.com/questions/12593/how-to-remove-all-the-files-in-a-directory

If your top-level directory is called images, then run rm -r images/*. This uses the shell glob operator * to run rm -r on every file or directory within images.

basically you go up one level, and then say delete everything inside X directory. This way you are still specifying what folder should have its content deleted, which is safer than just saying 'delete everything here", while preserving the original folder, (which sometimes you want to because you aren't allowed or just don't want to modify the folder's existing permissions)

How to edit default dark theme for Visual Studio Code?

In VS code 'User Settings', you can edit visible colours using the following tags(this is a sample and there are much more tags),

"workbench.colorCustomizations": {
    "list.inactiveSelectionBackground": "#C5DEF0",
    "sideBar.background": "#F8F6F6",
    "sideBar.foreground": "#000000",
    "editor.background": "#FFFFFF",
    "editor.foreground": "#000000",
    "sideBarSectionHeader.background": "#CAC9C9",
    "sideBarSectionHeader.foreground": "#000000",
    "activityBar.border": "#FFFFFF",
    "statusBar.background": "#102F97",
    "scrollbarSlider.activeBackground": "#77D4CB",
    "scrollbarSlider.hoverBackground": "#8CE6DA",
    "badge.background": "#81CA91"}

If you want to edit some C++ color tokens, use the following tag,

"editor.tokenColorCustomizations": {
    "numbers": "#2247EB",
    "comments": "#6D929C",
    "functions": "#0D7C28"
}

When would you use the Builder Pattern?

You use it when you have lots of options to deal with. Think about things like jmock:

m.expects(once())
    .method("testMethod")
    .with(eq(1), eq(2))
    .returns("someResponse");

It feels a lot more natural and is...possible.

There's also xml building, string building and many other things. Imagine if java.util.Map had put as a builder. You could do stuff like this:

Map<String, Integer> m = new HashMap<String, Integer>()
    .put("a", 1)
    .put("b", 2)
    .put("c", 3);

How to hide/show more text within a certain length (like youtube)

Updated @Hussein solution with preview height that will adapt to the paragraph number of lines.

So with this bit of code : - You can choose the number of lines you want to show in preview, it will works for all screen sizes, even if font-size is responsive. - There is no need to add classes or back-end editing to separate preview from whole content.

http://jsfiddle.net/7Vv8u/5816/

var h = $('div')[0].scrollHeight;

divLineHeight = parseInt($('div').css('line-height'));
divPaddingTop = parseInt($('div').css('padding-top'));
lineToShow = 2;
divPreviewHeight = divLineHeight*lineToShow - divPaddingTop;
$('div').css('height', divPreviewHeight );

$('#more').click(function(e) {
  e.stopPropagation();
  $('div').animate({
    'height': h
  })
});

$(document).click(function() {
  $('div').animate({
    'height': divPreviewHeight
  })
})

How to get AM/PM from a datetime in PHP

Just simply right A

{{ date('h:i A', strtotime($varname->created_at))}}

String concatenation: concat() vs "+" operator

Basically, there are two important differences between + and the concat method.

  1. If you are using the concat method then you would only be able to concatenate strings while in case of the + operator, you can also concatenate the string with any data type.

    For Example:

    String s = 10 + "Hello";
    

    In this case, the output should be 10Hello.

    String s = "I";
    String s1 = s.concat("am").concat("good").concat("boy");
    System.out.println(s1);
    

    In the above case you have to provide two strings mandatory.

  2. The second and main difference between + and concat is that:

    Case 1: Suppose I concat the same strings with concat operator in this way

    String s="I";
    String s1=s.concat("am").concat("good").concat("boy");
    System.out.println(s1);
    

    In this case total number of objects created in the pool are 7 like this:

    I
    am
    good
    boy
    Iam
    Iamgood
    Iamgoodboy
    

    Case 2:

    Now I am going to concatinate the same strings via + operator

    String s="I"+"am"+"good"+"boy";
    System.out.println(s);
    

    In the above case total number of objects created are only 5.

    Actually when we concatinate the strings via + operator then it maintains a StringBuffer class to perform the same task as follows:-

    StringBuffer sb = new StringBuffer("I");
    sb.append("am");
    sb.append("good");
    sb.append("boy");
    System.out.println(sb);
    

    In this way it will create only five objects.

So guys these are the basic differences between + and the concat method. Enjoy :)