Programs & Examples On #Python extensions

Python is an interpreted, general-purpose high-level programming language whose design philosophy emphasizes code readability.

How do I convert a Swift Array to a String?

Since no one has mentioned reduce, here it is:

[0, 1, 1, 0].map {"\($0)"}.reduce("") { $0 + $1 } // "0110"

In the spirit of functional programming

Checking Maven Version

Open command prompt go inside the maven folder and execute mvn -version, it will show you maven vesrion al

How to increase application heap size in Eclipse?

In Eclipse Folder there is eclipse.ini file. Increase size -Xms512m -Xmx1024m

Visual Studio can't 'see' my included header files

Try adding the header file to your project's files. (right click on project -> add existing file).

How to retrieve an element from a set without removing it?

Two options that don't require copying the whole set:

for e in s:
    break
# e is now an element from s

Or...

e = next(iter(s))

But in general, sets don't support indexing or slicing.

jQuery Find and List all LI elements within a UL within a specific DIV

Are you thinking about something like this?

$('ul li').each(function(i)
{
   $(this).attr('rel'); // This is your rel value
});

How to replace all strings to numbers contained in each string in Notepad++?

In Notepad++ to replace, hit Ctrl+H to open the Replace menu.

Then if you check the "Regular expression" button and you want in your replacement to use a part of your matching pattern, you must use "capture groups" (read more on google). For example, let's say that you want to match each of the following lines

value="4"
value="403"
value="200"
value="201"
value="116"
value="15"

using the .*"\d+" pattern and want to keep only the number. You can then use a capture group in your matching pattern, using parentheses ( and ), like that: .*"(\d+)". So now in your replacement you can simply write $1, where $1 references to the value of the 1st capturing group and will return the number for each successful match. If you had two capture groups, for example (.*)="(\d+)", $1 will return the string value and $2 will return the number.

So by using:

Find: .*"(\d+)"

Replace: $1

It will return you

4
403
200
201
116
15

Please note that there many alternate and better ways of matching the aforementioned pattern. For example the pattern value="([0-9]+)" would be better, since it is more specific and you will be sure that it will match only these lines. It's even possible of making the replacement without the use of capture groups, but this is a slightly more advanced topic, so I'll leave it for now :)

How to convert array to a string using methods other than JSON?

You are looking for serialize(). Here is an example:

$array = array('foo', 'bar');

//Array to String
$string = serialize($array);

//String to array
$array = unserialize($string);

php mail setup in xampp

My favorite smtp server is hMailServer.

It has a nice windows friendly installer and wizard. Hands down the easiest mail server I've ever setup.

It can proxy through your gmail/yahoo/etc account or send email directly.

Once it is installed, email in xampp just works with no config changes.

WebSocket with SSL

1 additional caveat (besides the answer by kanaka/peter): if you use WSS, and the server certificate is not acceptable to the browser, you may not get any browser rendered dialog (like it happens for Web pages). This is because WebSockets is treated as a so-called "subresource", and certificate accept / security exception / whatever dialogs are not rendered for subresources.

How can I delete all cookies with JavaScript?

On the face of it, it looks okay - if you call eraseCookie() on each cookie that is read from document.cookie, then all of your cookies will be gone.

Try this:

var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++)
  eraseCookie(cookies[i].split("=")[0]);

All of this with the following caveat:

  • JavaScript cannot remove cookies that have the HttpOnly flag set.

How do I read the contents of a Node.js stream into a string variable?

Streams don't have a simple .toString() function (which I understand) nor something like a .toStringAsync(cb) function (which I don't understand).

So I created my own helper function:

var streamToString = function(stream, callback) {
  var str = '';
  stream.on('data', function(chunk) {
    str += chunk;
  });
  stream.on('end', function() {
    callback(str);
  });
}

// how to use:
streamToString(myStream, function(myStr) {
  console.log(myStr);
});

How to use protractor to check if an element is visible?

If there are multiple elements in DOM with same class name. But only one of element is visible.

element.all(by.css('.text-input-input')).filter(function(ele){
        return ele.isDisplayed();
    }).then(function(filteredElement){
        filteredElement[0].click();
    });

In this example filter takes a collection of elements and returns a single visible element using isDisplayed().

Show current assembly instruction in GDB

If you want the next few instructions to display automatically while stepping through the program you can use the display command as follows -

display /3i $pc

The above will display 3 instructions whenever a breakpoint is hit or when you single step the program.

More details at the blog entry here.

htaccess - How to force the client's browser to clear the cache?

You can force browsers to cache something, but

You can't force browsers to clear their cache.

Thus the only (AMAIK) way is to use a new URL for your resources. Something like versioning.

How to check if a subclass is an instance of a class at runtime?

Class.isAssignableFrom() - works for interfaces as well. If you don't want that, you'll have to call getSuperclass() and test until you reach Object.

How to remove specific session in asp.net?

There is nothing like session container , so you can set it as null

but rather you can set individual session element as null or ""

like Session["userid"] = null;

Is there a “not in” operator in JavaScript for checking object properties?

Personally I find

if (id in tutorTimes === false) { ... }

easier to read than

if (!(id in tutorTimes)) { ... }

but both will work.

How do I create a singleton service in Angular 2?

this seems to be working well for me

@Injectable()
export class MyStaticService {
  static instance: MyStaticService;

  constructor() {
    return MyStaticService.instance = MyStaticService.instance || this;
  }
}

Div width 100% minus fixed amount of pixels

The usual way to do it is as outlined by Guffa, nested elements. It's a bit sad having to add extra markup to get the hooks you need for this, but in practice a wrapper div here or there isn't going to hurt anyone.

If you must do it without extra elements (eg. when you don't have control of the page markup), you can use box-sizing, which has pretty decent but not complete or simple browser support. Likely more fun than having to rely on scripting though.

Spring Boot - Error creating bean with name 'dataSource' defined in class path resource

Looks like the initial problem is with the auto-config.

If you don't need the datasource, simply remove it from the auto-config process:

@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})

Should C# or C++ be chosen for learning Games Programming (consoles)?

I'm not going to answer the original question since most post here have. I'm going to point something out to you that you missed in your post. Simply knowing C\C++\C# isn't going to get you a career in game development. Most game studios get dozens to hundreds of applications for a simple code monkey job. What makes you stand out compared to them? What makes you a better hire than someone else who has experience making games at another studio?

If you really want a career in the games industry, even on consoles, you should make a demo of some kind that shows what you know. C++ would be great language choice to use in the demo if you're applying for a console development position. You could show off more by making a tool in C#\XNA to create the assets for your demo. You'll show the hiring managers and tech leads that you're not JUST a C++ guy or JUST a C# guy: you're a developer.

c# foreach (property in object)... Is there a simple way of doing this?

Your'e almost there, you just need to get the properties from the type, rather than expect the properties to be accessible in the form of a collection or property bag:

var property in obj.GetType().GetProperties()

From there you can access like so:

property.Name
property.GetValue(obj, null)

With GetValue the second parameter will allow you to specify index values, which will work with properties returning collections - since a string is a collection of chars, you can also specify an index to return a character if needs be.

Start thread with member function

@hop5 and @RnMss suggested to use C++11 lambdas, but if you deal with pointers, you can use them directly:

#include <thread>
#include <iostream>

class CFoo {
  public:
    int m_i = 0;
    void bar() {
      ++m_i;
    }
};

int main() {
  CFoo foo;
  std::thread t1(&CFoo::bar, &foo);
  t1.join();
  std::thread t2(&CFoo::bar, &foo);
  t2.join();
  std::cout << foo.m_i << std::endl;
  return 0;
}

outputs

2

Rewritten sample from this answer would be then:

#include <thread>
#include <iostream>

class Wrapper {
  public:
      void member1() {
          std::cout << "i am member1" << std::endl;
      }
      void member2(const char *arg1, unsigned arg2) {
          std::cout << "i am member2 and my first arg is (" << arg1 << ") and second arg is (" << arg2 << ")" << std::endl;
      }
      std::thread member1Thread() {
          return std::thread(&Wrapper::member1, this);
      }
      std::thread member2Thread(const char *arg1, unsigned arg2) {
          return std::thread(&Wrapper::member2, this, arg1, arg2);
      }
};

int main() {
  Wrapper *w = new Wrapper();
  std::thread tw1 = w->member1Thread();
  tw1.join();
  std::thread tw2 = w->member2Thread("hello", 100);
  tw2.join();
  return 0;
}

Bootstrap radio button "checked" flag

A javascript fix to apply the 'active' class to all labels that are parents of checked inputs:

$(':input:checked').parent('.btn').addClass('active');

insert right after

$('.btn').button();

How do I create a batch file timer to execute / call another batch throughout the day

Below is a batch file that will wait for 1 minute, check the day, and then perform an action. It uses PING.EXE, but requires no files that aren't included with Windows.

@ECHO OFF

:LOOP
ECHO Waiting for 1 minute...
  PING -n 60 127.0.0.1>nul
  IF %DATE:~0,3%==Mon CALL SomeOtherFile.cmd
  IF %DATE:~0,3%==Tue CALL SomeOtherFile.cmd
  IF %DATE:~0,3%==Wed CALL SomeOtherFile.cmd
  IF %DATE:~0,3%==Thu CALL WootSomeOtherFile.cmd
  IF %DATE:~0,3%==Fri CALL SomeOtherFile.cmd
  IF %DATE:~0,3%==Sat ECHO Saturday...nothing to do.
  IF %DATE:~0,3%==Sun ECHO Sunday...nothing to do.
GOTO LOOP

It could be improved upon in many ways, but it might get you started.

In Java what is the syntax for commenting out multiple lines?

  • The simple question to your answer is already answered a lot of times:

    /*
    LINES I WANT COMMENTED
    LINES I WANT COMMENTED
    LINES I WANT COMMENTED
    */
    
  • From your question it sounds like you want to comment out a lot of code?? I would advise to use a repository(git/github) to manage your files instead of commenting out lines.

  • My last advice would be to learn about javadoc if not already familiar because documenting your code is really important.

Closing Excel Application Process in C# after Data Access

excelBook.Close(); excelApp.Quit(); add end of the code, it could be enough. it is working on my code

What is the best open source help ticket system?

I recommend OTRS, its very easily customizable, and we also use it for hundreds of employees (University).

GCC fatal error: stdio.h: No such file or directory

I know my case is rare, but I'll still add it here for someone who troubleshoots it later. I had a Linux Kernel module target in my Makefile and I tried to compile my user space program together with the kernel module that doesn't have stdio. Making it a separate target solved the problem.

Jenkins: Can comments be added to a Jenkinsfile?

You can use block (/***/) or single line comment (//) for each line. You should use "#" in sh command.

Block comment

_x000D_
_x000D_
/*  _x000D_
post {_x000D_
    success {_x000D_
      mail to: "[email protected]", _x000D_
      subject:"SUCCESS: ${currentBuild.fullDisplayName}", _x000D_
      body: "Yay, we passed."_x000D_
    }_x000D_
    failure {_x000D_
      mail to: "[email protected]", _x000D_
      subject:"FAILURE: ${currentBuild.fullDisplayName}", _x000D_
      body: "Boo, we failed."_x000D_
    }_x000D_
  }_x000D_
*/
_x000D_
_x000D_
_x000D_

Single Line

_x000D_
_x000D_
// post {_x000D_
//     success {_x000D_
//       mail to: "[email protected]", _x000D_
//       subject:"SUCCESS: ${currentBuild.fullDisplayName}", _x000D_
//       body: "Yay, we passed."_x000D_
//     }_x000D_
//     failure {_x000D_
//       mail to: "[email protected]", _x000D_
//       subject:"FAILURE: ${currentBuild.fullDisplayName}", _x000D_
//       body: "Boo, we failed."_x000D_
//     }_x000D_
// }
_x000D_
_x000D_
_x000D_

Comment in 'sh' command

_x000D_
_x000D_
        stage('Unit Test') {_x000D_
            steps {_x000D_
                ansiColor('xterm'){_x000D_
                  sh '''_x000D_
                  npm test_x000D_
                  # this is a comment in sh_x000D_
                  '''_x000D_
                }_x000D_
            }_x000D_
        }
_x000D_
_x000D_
_x000D_

Load an image from a url into a PictureBox

Try this:

var request = WebRequest.Create("http://www.gravatar.com/avatar/6810d91caff032b202c50701dd3af745?d=identicon&r=PG");

using (var response = request.GetResponse())
using (var stream = response.GetResponseStream())
{
    pictureBox1.Image = Bitmap.FromStream(stream);
}

Meaning of tilde in Linux bash (not home directory)

Are they the home directories of users in /etc/passwd? Services like postgres, sendmail, apache, etc., create system users that have home directories just like normal users.

Select distinct values from a large DataTable column

This will retrun you distinct Ids

 var distinctIds = datatable.AsEnumerable()
                    .Select(s=> new {
                        id = s.Field<string>("id"),                           
                     })
                    .Distinct().ToList();

Rename Pandas DataFrame Index

If you want to use the same mapping for renaming both columns and index you can do:

mapping = {0:'Date', 1:'SM'}
df.index.names = list(map(lambda name: mapping.get(name, name), df.index.names))
df.rename(columns=mapping, inplace=True)

How do I make a dotted/dashed line in Android?

By using this class you can apply "dashed and underline" effect to multiple lines text. to use DashPathEffect you have to turn off hardwareAccelerated of your TextView(though DashPathEffect method has a problem with long text). you can find my sample project here: https://github.com/jintoga/Dashed-Underlined-TextView/blob/master/Untitled.png.

public class DashedUnderlineSpan implements LineBackgroundSpan, LineHeightSpan {

    private Paint paint;
    private TextView textView;
    private float offsetY;
    private float spacingExtra;

    public DashedUnderlineSpan(TextView textView, int color, float thickness, float dashPath,
                               float offsetY, float spacingExtra) {
        this.paint = new Paint();
        this.paint.setColor(color);
        this.paint.setStyle(Paint.Style.STROKE);
        this.paint.setPathEffect(new DashPathEffect(new float[] { dashPath, dashPath }, 0));
        this.paint.setStrokeWidth(thickness);
        this.textView = textView;
        this.offsetY = offsetY;
        this.spacingExtra = spacingExtra;
    }

    @Override
    public void chooseHeight(CharSequence text, int start, int end, int spanstartv, int v,
                             Paint.FontMetricsInt fm) {
        fm.ascent -= spacingExtra;
        fm.top -= spacingExtra;
        fm.descent += spacingExtra;
        fm.bottom += spacingExtra;
    }

    @Override
    public void drawBackground(Canvas canvas, Paint p, int left, int right, int top, int baseline,
                               int bottom, CharSequence text, int start, int end, int lnum) {
        int lineNum = textView.getLineCount();
        for (int i = 0; i < lineNum; i++) {
            Layout layout = textView.getLayout();
            canvas.drawLine(layout.getLineLeft(i), layout.getLineBottom(i) - spacingExtra + offsetY,
                    layout.getLineRight(i), layout.getLineBottom(i) - spacingExtra + offsetY,
                    this.paint);
        }
    }
}

Result:

dashed underline

Connection attempt failed with "ECONNREFUSED - Connection refused by server"

For me, I was receiving this error when connecting to the new IP Address I had configured FileZilla to bind to and saved the configuration. After trying all of the other answers unsuccessfully, I decided to connect to the old IP Address to see what came up; lo and behold it responded.

I restarted the FileZilla Windows Service and it immediately came back listening on the correct IP. Pretty elementary, but it cost me some time today as a noob to FZ.

Hopefully this helps someone out in the same predicament.

How to check if a file exists in a folder?

if (File.Exists(localUploadDirectory + "/" + fileName))
{                        
    `Your code here`
}

MySQL select one column DISTINCT, with corresponding other columns

Not sure if you can do this with MySQL, but you can use a CTE in T-SQL

; WITH tmpPeople AS (
 SELECT 
   DISTINCT(FirstName),
   MIN(Id)      
 FROM People
)
SELECT
 tP.Id,
 tP.FirstName,
 P.LastName
FROM tmpPeople tP
JOIN People P ON tP.Id = P.Id

Otherwise you might have to use a temporary table.

Getting content/message from HttpResponseMessage

The quick answer I suggest is:

response.Result.Content.ReadAsStringAsync().Result

How to generate components in a specific folder with Angular CLI?

Go to project folder in command prompt or in Project Terminal.

Run cmd : ng g c componentname

enter image description here

No connection could be made because the target machine actively refused it 127.0.0.1

Delete Temp files by run > %temp%

And Open VS2015 by run as admin,

it works for me.

Is there a workaround for ORA-01795: maximum number of expressions in a list is 1000 error?

There's also workaround doing disjunction of your array, worked for me as other solutions were hard to implement using some old framework.

select * from tableA where id = 1 or id = 2 or id = 3 ...

But for better perfo, I would use Nikolai Nechai's solution with unions, if possible.

PHP random string generator

Helper function from Laravel 5 framework

/**
 * Generate a "random" alpha-numeric string.
 *
 * Should not be considered sufficient for cryptography, etc.
 *
 * @param  int  $length
 * @return string
 */
function str_random($length = 16)
{
    $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

    return substr(str_shuffle(str_repeat($pool, $length)), 0, $length);
}

Format the date using Ruby on Rails

First you will need to convert the timestamp to an actual Ruby Date/Time. If you receive it just as a string or int from facebook, you will need to do something like this:

my_date = Time.at(timestamp_from_facebook.to_i)

Then to format it nicely in the view, you can just use to_s (for the default formatting):

<%= my_date.to_s %>

Note that if you don't put to_s, it will still be called by default if you use it in a view or in a string e.g. the following will also call to_s on the date:

<%= "Here is a date: #{my_date}" %>

or if you want the date formatted in a specific way (eg using "d/m/Y") - you can use strftime as outlined in the other answer.

Finding the second highest number in array

   /* Function to print the second largest elements */
    void print2largest(int arr[], int arr_size)
    {
   int i, first, second;

   /* There should be atleast two elements */
   if (arr_size < 2)
   {
    printf(" Invalid Input ");
    return;
    }

   first = second = INT_MIN;
   for (i = 0; i < arr_size ; i ++)
   {
    /* If current element is smaller than first
       then update both first and second */
    if (arr[i] > first)
    {
        second = first;
        first = arr[i];
    }

    /* If arr[i] is in between first and 
       second then update second  */
    else if (arr[i] > second && arr[i] != first)
        second = arr[i];
   }
   if (second == INT_MIN)
    printf("There is no second largest elementn");
    else
    printf("The second largest element is %dn", second);
    }

How to POST form data with Spring RestTemplate?

here is the full program to make a POST rest call using spring's RestTemplate.

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

import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.ituple.common.dto.ServiceResponse;

   public class PostRequestMain {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
        Map map = new HashMap<String, String>();
        map.put("Content-Type", "application/json");

        headers.setAll(map);

        Map req_payload = new HashMap();
        req_payload.put("name", "piyush");

        HttpEntity<?> request = new HttpEntity<>(req_payload, headers);
        String url = "http://localhost:8080/xxx/xxx/";

        ResponseEntity<?> response = new RestTemplate().postForEntity(url, request, String.class);
        ServiceResponse entityResponse = (ServiceResponse) response.getBody();
        System.out.println(entityResponse.getData());
    }

}

What are the differences between the urllib, urllib2, urllib3 and requests module?

To get the content of a url:

try: # Try importing requests first.
    import requests
except ImportError: 
    try: # Try importing Python3 urllib
        import urllib.request
    except AttributeError: # Now importing Python2 urllib
        import urllib


def get_content(url):
    try:  # Using requests.
        return requests.get(url).content # Returns requests.models.Response.
    except NameError:  
        try: # Using Python3 urllib.
            with urllib.request.urlopen(index_url) as response:
                return response.read() # Returns http.client.HTTPResponse.
        except AttributeError: # Using Python3 urllib.
            return urllib.urlopen(url).read() # Returns an instance.

It's hard to write Python2 and Python3 and request dependencies code for the responses because they urlopen() functions and requests.get() function return different types:

  • Python2 urllib.request.urlopen() returns a http.client.HTTPResponse
  • Python3 urllib.urlopen(url) returns an instance
  • Request request.get(url) returns a requests.models.Response

Get data from fs.readFile

you can read file by

var readMyFile = function(path, cb) {
      fs.readFile(path, 'utf8', function(err, content) {
        if (err) return cb(err, null);
        cb(null, content);
      });
    };

Adding on you can write to file,

var createMyFile = (path, data, cb) => {
  fs.writeFile(path, data, function(err) {
    if (err) return console.error(err);
    cb();
  });
};

and even chain it together

var readFileAndConvertToSentence = function(path, callback) {
  readMyFile(path, function(err, content) {
    if (err) {
      callback(err, null);
    } else {
      var sentence = content.split('\n').join(' ');
      callback(null, sentence);
    }
  });
};

Moment Js UTC to Local Time

I've written this Codesandbox for a roundtrip from UTC to local time and from local time to UTC. You can change the timezone and the format. Enjoy!

Full Example on Codesandbox (DEMO):

https://codesandbox.io/s/momentjs-utc-to-local-roundtrip-foj57?file=/src/App.js

How to manually force a commit in a @Transactional method?

I know that due to this ugly anonymous inner class usage of TransactionTemplate doesn't look nice, but when for some reason we want to have a test method transactional IMHO it is the most flexible option.

In some cases (it depends on the application type) the best way to use transactions in Spring tests is a turned-off @Transactional on the test methods. Why? Because @Transactional may leads to many false-positive tests. You may look at this sample article to find out details. In such cases TransactionTemplate can be perfect for controlling transaction boundries when we want that control.

Error CS2001: Source file '.cs' could not be found

I open the project,.csproj, using a notepad and delete that missing file reference.

R not finding package even after package installation

Do .libPaths(), close every R runing, check in the first directory, remove the zoo package restart R and install zoo again. Of course you need to have sufficient rights.

display HTML page after loading complete

try using javascript for this! Seems like its the best and easiest way to do this. You'll get inbuilt funcn to execute a html code only after HTML page loads completely.

or else you may use state based programming where an event occurs at a particular state of the browser..

Styling a disabled input with css only

A space in a CSS selector selects child elements.

.btn input

This is basically what you wrote and it would select <input> elements within any element that has the btn class.

I think you're looking for

input[disabled].btn:hover, input[disabled].btn:active, input[disabled].btn:focus

This would select <input> elements with the disabled attribute and the btn class in the three different states of hover, active and focus.

How can I find my Apple Developer Team id and Team Agent Apple ID?

For personal teams

grep DEVELOPMENT_TEAM MyProject.xcodeproj/project.pbxproj

should give you the team ID

DEVELOPMENT_TEAM = ZU88ND8437;

CodeIgniter: How to use WHERE clause and OR clause

You can use or_where() for that - example from the CI docs:

$this->db->where('name !=', $name);

$this->db->or_where('id >', $id); 

// Produces: WHERE name != 'Joe' OR id > 50

Static Final Variable in Java

Declaring the field as 'final' will ensure that the field is a constant and cannot change. The difference comes in the usage of 'static' keyword.

Declaring a field as static means that it is associated with the type and not with the instances. i.e. only one copy of the field will be present for all the objects and not individual copy for each object. Due to this, the static fields can be accessed through the class name.

As you can see, your requirement that the field should be constant is achieved in both cases (declaring the field as 'final' and as 'static final').

Similar question is private final static attribute vs private final attribute

Hope it helps

using setTimeout on promise chain

The shorter ES6 version of the answer:

const delay = t => new Promise(resolve => setTimeout(resolve, t));

And then you can do:

delay(3000).then(() => console.log('Hello'));

Best way to make WPF ListView/GridView sort on column-header clicking?

I made an adaptation of the Microsoft way, where I override the ListView control to make a SortableListView:

public partial class SortableListView : ListView
    {        
        private GridViewColumnHeader lastHeaderClicked = null;
        private ListSortDirection lastDirection = ListSortDirection.Ascending;       

        public void GridViewColumnHeaderClicked(GridViewColumnHeader clickedHeader)
        {
            ListSortDirection direction;

            if (clickedHeader != null)
            {
                if (clickedHeader.Role != GridViewColumnHeaderRole.Padding)
                {
                    if (clickedHeader != lastHeaderClicked)
                    {
                        direction = ListSortDirection.Ascending;
                    }
                    else
                    {
                        if (lastDirection == ListSortDirection.Ascending)
                        {
                            direction = ListSortDirection.Descending;
                        }
                        else
                        {
                            direction = ListSortDirection.Ascending;
                        }
                    }

                    string sortString = ((Binding)clickedHeader.Column.DisplayMemberBinding).Path.Path;

                    Sort(sortString, direction);

                    lastHeaderClicked = clickedHeader;
                    lastDirection = direction;
                }
            }
        }

        private void Sort(string sortBy, ListSortDirection direction)
        {
            ICollectionView dataView = CollectionViewSource.GetDefaultView(this.ItemsSource != null ? this.ItemsSource : this.Items);

            dataView.SortDescriptions.Clear();
            SortDescription sD = new SortDescription(sortBy, direction);
            dataView.SortDescriptions.Add(sD);
            dataView.Refresh();
        }
    }

The line ((Binding)clickedHeader.Column.DisplayMemberBinding).Path.Path bit handles the cases where your column names are not the same as their binding paths, which the Microsoft method does not do.

I wanted to intercept the GridViewColumnHeader.Click event so that I wouldn't have to think about it anymore, but I couldn't find a way to to do. As a result I add the following in XAML for every SortableListView:

GridViewColumnHeader.Click="SortableListViewColumnHeaderClicked"

And then on any Window that contains any number of SortableListViews, just add the following code:

private void SortableListViewColumnHeaderClicked(object sender, RoutedEventArgs e)
        {
            ((Controls.SortableListView)sender).GridViewColumnHeaderClicked(e.OriginalSource as GridViewColumnHeader);
        }

Where Controls is just the XAML ID for the namespace in which you made the SortableListView control.

So, this does prevent code duplication on the sorting side, you just need to remember to handle the event as above.

Grid of responsive squares

You could use vw (view-width) units, which would make the squares responsive according to the width of the screen.

A quick mock-up of this would be:

_x000D_
_x000D_
html,_x000D_
body {_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
}_x000D_
div {_x000D_
  height: 25vw;_x000D_
  width: 25vw;_x000D_
  background: tomato;_x000D_
  display: inline-block;_x000D_
  text-align: center;_x000D_
  line-height: 25vw;_x000D_
  font-size: 20vw;_x000D_
  margin-right: -4px;_x000D_
  position: relative;_x000D_
}_x000D_
/*demo only*/_x000D_
_x000D_
div:before {_x000D_
  content: "";_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  height: inherit;_x000D_
  width: inherit;_x000D_
  background: rgba(200, 200, 200, 0.6);_x000D_
  transition: all 0.4s;_x000D_
}_x000D_
div:hover:before {_x000D_
  background: rgba(200, 200, 200, 0);_x000D_
}
_x000D_
<div>1</div>_x000D_
<div>2</div>_x000D_
<div>3</div>_x000D_
<div>4</div>_x000D_
<div>5</div>_x000D_
<div>6</div>_x000D_
<div>7</div>_x000D_
<div>8</div>
_x000D_
_x000D_
_x000D_

Get values from an object in JavaScript

In ES2017 you can use Object.values():

Object.values(data)

At the time of writing support is limited (FireFox and Chrome).All major browsers except IE support this now.

In ES2015 you can use this:

Object.keys(data).map(k => data[k])

Creating an Instance of a Class with a variable in Python

If you just want to pass a class to a function, so that this function can create new instances of that class, just treat the class like any other value you would give as a parameter:

def printinstance(someclass):
  print someclass()

Result:

>>> printinstance(list)
[]
>>> printinstance(dict)
{}

Calling a Sub and returning a value

You should be using a Property:

Private _myValue As String
Public Property MyValue As String
    Get
        Return _myValue
    End Get
    Set(value As String)
        _myValue = value
     End Set
End Property

Then use it like so:

MyValue = "Hello"
Console.write(MyValue)

How to force garbage collection in Java?

If you are running out of memory and getting an OutOfMemoryException you can try increasing the amount of heap space available to java by starting you program with java -Xms128m -Xmx512m instead of just java. This will give you an initial heap size of 128Mb and a maximum of 512Mb, which is far more than the standard 32Mb/128Mb.

Is there a way to view past mysql queries with phpmyadmin?

Here is a trick that some may find useful:

For Select queries (only), you can create Views, especially where you find yourself running the same select queries over and over e.g. in production support scenarios.

The main advantages of creating Views are:

  • they are resident within the database and therefore permanent
  • they can be shared across sessions and users
  • they provide all the usual benefits of working with tables
  • they can be queried further, just like tables e.g. to filter down the results further
  • as they are stored as queries under the hood, they do not add any overheads.

You can create a view easily by simply clicking the "Create view" link at the bottom of the results table display.

what do <form action="#"> and <form method="post" action="#"> do?

Action normally specifies the file/page that the form is submitted to (using the method described in the method paramater (post, get etc.))

An action of # indicates that the form stays on the same page, simply suffixing the url with a #. Similar use occurs in anchors. <a href=#">Link</a> for example, will stay on the same page.

Thus, the form is submitted to the same page, which then processes the data etc.

Chaining Observables in RxJS

About promise composition vs. Rxjs, as this is a frequently asked question, you can refer to a number of previously asked questions on SO, among which :

Basically, flatMap is the equivalent of Promise.then.

For your second question, do you want to replay values already emitted, or do you want to process new values as they arrive? In the first case, check the publishReplay operator. In the second case, standard subscription is enough. However you might need to be aware of the cold. vs. hot dichotomy depending on your source (cf. Hot and Cold observables : are there 'hot' and 'cold' operators? for an illustrated explanation of the concept)

How to install pip with Python 3?

pip is installed together when you install Python. You can use sudo pip install (module) or python3 -m pip install (module).

How to use EditText onTextChanged event when I press the number?

In Kotlin Android EditText listener is set using,

   val searchTo : EditText = findViewById(R.id.searchTo)
   searchTo.addTextChangedListener(object : TextWatcher {
    override fun afterTextChanged(s: Editable) {

        // you can call or do what you want with your EditText here

        // yourEditText...
    }

    override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
    override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
})

Combining "LIKE" and "IN" for SQL Server

One other option would be to use something like this

SELECT  * 
FROM    table t INNER JOIN
        (
            SELECT  'Text%' Col
            UNION SELECT 'Link%'
            UNION SELECT 'Hello%'
            UNION SELECT '%World%'
        ) List ON t.COLUMN LIKE List.Col

Easiest way to make lua script wait/pause/sleep/block for a few seconds?

I would implement a simple function to wrap the host system's sleep function in C.

Fixed point vs Floating point number

From my understanding, fixed-point arithmetic is done using integers. where the decimal part is stored in a fixed amount of bits, or the number is multiplied by how many digits of decimal precision is needed.

For example, If the number 12.34 needs to be stored and we only need two digits of precision after the decimal point, the number is multiplied by 100 to get 1234. When performing math on this number, we'd use this rule set. Adding 5620 or 56.20 to this number would yield 6854 in data or 68.54.

If we want to calculate the decimal part of a fixed-point number, we use the modulo (%) operand.

12.34 (pseudocode):

v1 = 1234 / 100 // get the whole number
v2 = 1234 % 100 // get the decimal number (100ths of a whole).
print v1 + "." + v2 // "12.34"

Floating point numbers are a completely different story in programming. The current standard for floating point numbers use something like 23 bits for the data of the number, 8 bits for the exponent, and 1 but for sign. See this Wikipedia link for more information on this.

How to use the PRINT statement to track execution as stored procedure is running?

I'm sure you can use RAISERROR ... WITH NOWAIT

If you use severity 10 it's not an error. This also provides some handy formatting eg %s, %i and you can use state too to track where you are.

Add border-bottom to table row <tr>

I had a problem like this before. I don't think tr can take a border styling directly. My workaround was to style the tds in the row:

<tr class="border_bottom">

CSS:

tr.border_bottom td {
  border-bottom: 1px solid black;
}

Creating an object: with or without `new`

The first allocates an object with automatic storage duration, which means it will be destructed automatically upon exit from the scope in which it is defined.

The second allocated an object with dynamic storage duration, which means it will not be destructed until you explicitly use delete to do so.

Running Python code in Vim

Plugin: jupyter-vim

So you can send lines (<leader>E), visual selection (<leader>e) to a running jupyter-client (the replacement of ipython)

enter image description here

I prefer to separate editor and interpreter (each one in its shell). Imagine you send a bad input reading command ...

Get date from input form within PHP

    <?php
if (isset($_POST['birthdate'])) {
    $timestamp = strtotime($_POST['birthdate']); 
    $date=date('d',$timestamp);
    $month=date('m',$timestamp);
    $year=date('Y',$timestamp);
}
?>  

Difference between the annotations @GetMapping and @RequestMapping(method = RequestMethod.GET)

@GetMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.GET).

@GetMapping is the newer annotaion. It supports consumes

Consume options are :

consumes = "text/plain"
consumes = {"text/plain", "application/*"}

For Further details see: GetMapping Annotation

or read: request mapping variants

RequestMapping supports consumes as well

GetMapping we can apply only on method level and RequestMapping annotation we can apply on class level and as well as on method level

How can I send an Ajax Request on button click from a form with 2 buttons?

Use jQuery multiple-selector if the only difference between the two functions is the value of the button being triggered.

$("#button_1, #button_2").on("click", function(e) {
    e.preventDefault();
    $.ajax({type: "POST",
        url: "/pages/test/",
        data: { id: $(this).val(), access_token: $("#access_token").val() },
        success:function(result) {
          alert('ok');
        },
        error:function(result) {
          alert('error');
        }
    });
});

Set color of text in a Textbox/Label to Red and make it bold in asp.net C#

TextBox1.ForeColor = Color.Red;
TextBox1.Font.Bold = True;

Or this can be done using a CssClass (recommended):

.highlight
{
  color:red;
  font-weight:bold;
}

TextBox1.CssClass = "highlight";

Or the styles can be added inline:

TextBox1.Attributes["style"] = "color:red; font-weight:bold;";

How to justify navbar-nav in Bootstrap 3

I know this is an old post but I would like share my solution. I spent several hours trying to make a justified navigation menu. You do not really need to modify anything in bootstrap css. Just need to add the correct class in the html.

   <nav class="nav navbar-default navbar-fixed-top">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#collapsable-1" aria-expanded="false">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="#top">Brand Name</a>
        </div>
        <div class="collapse navbar-collapse" id="collapsable-1">
            <ul class="nav nav-justified">
                <li><a href="#about-me">About Me</a></li>
                <li><a href="#skills">Skills</a></li>
                <li><a href="#projects">Projects</a></li>
                <li><a href="#contact-me">Contact Me</a></li>
            </ul>
        </div>
    </nav>

This CSS code will simply remove the navbar-brand class when the screen reaches 768px.

media@(min-width: 768px){
   .navbar-brand{
        display: none;
    }
}

What's a good way to extend Error in JavaScript?

In 2018, I think this is the best way; that supports IE9+ and modern browsers.

UPDATE: See this test and repo for comparison on different implementations.

function CustomError(message) {
    Object.defineProperty(this, 'name', {
        enumerable: false,
        writable: false,
        value: 'CustomError'
    });

    Object.defineProperty(this, 'message', {
        enumerable: false,
        writable: true,
        value: message
    });

    if (Error.hasOwnProperty('captureStackTrace')) { // V8
        Error.captureStackTrace(this, CustomError);
    } else {
        Object.defineProperty(this, 'stack', {
            enumerable: false,
            writable: false,
            value: (new Error(message)).stack
        });
    }
}

if (typeof Object.setPrototypeOf === 'function') {
    Object.setPrototypeOf(CustomError.prototype, Error.prototype);
} else {
    CustomError.prototype = Object.create(Error.prototype, {
        constructor: { value: CustomError }
    });
}

Also beware that __proto__ property is deprecated which is widely used in other answers.

The transaction manager has disabled its support for remote/network transactions

In my scenario, the exception was being thrown because I was trying to create a new connection instance within a TransactionScope on an already existing connection:

Example:

void someFunction()
{
    using (var db = new DBContext(GetConnectionString()))
    {
        using (var transaction = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted }))
        {
            someOtherFunction(); // This function opens a new connection within this transaction, causing the exception.
        }
    }
}

void someOtherFunction()
{
    using (var db = new DBContext(GetConnectionString()))
    {
        db.Whatever // <- Exception.
    }
}

Writing a dictionary to a text file?

If you want a dictionary you can import from a file by name, and also that adds entries that are nicely sorted, and contains strings you want to preserve, you can try this:

data = {'A': 'a', 'B': 'b', }

with open('file.py','w') as file:
    file.write("dictionary_name = { \n")
    for k in sorted (data.keys()):
        file.write("'%s':'%s', \n" % (k, data[k]))
    file.write("}")

Then to import:

from file import dictionary_name

Read lines from a text file but skip the first two lines

Dim sFileName As String
Dim iFileNum As Integer
Dim sBuf As String
Dim Fields as String
Dim TempStr as String

sFileName = "c:\fields.ini"
''//Does the file exist?
If Len(Dir$(sFileName)) = 0 Then
    MsgBox ("Cannot find fields.ini")
End If

iFileNum = FreeFile()
Open sFileName For Input As iFileNum

''//This part skips the first two lines
if not(EOF(iFileNum)) Then Line Input #iFilenum, TempStr
if not(EOF(iFileNum)) Then Line Input #iFilenum, TempStr

Do While Not EOF(iFileNum)
    Line Input #iFileNum, Fields

    MsgBox (Fields)
Loop

whitespaces in the path of windows filepath

(WINDOWS - AWS solution)
Solved for windows by putting tripple quotes around files and paths.
Benefits:
1) Prevents excludes that quietly were getting ignored.
2) Files/folders with spaces in them, will no longer kick errors.

    aws_command = 'aws s3 sync """D:/""" """s3://mybucket/my folder/"  --exclude """*RECYCLE.BIN/*""" --exclude """*.cab""" --exclude """System Volume Information/*""" '

    r = subprocess.run(f"powershell.exe {aws_command}", shell=True, capture_output=True, text=True)

Visual Studio Code Automatic Imports

I've come across this problem on Typescript Version 3.8.3.

Intellisense is the best thing we could have but for me, the auto-import feature doesn't seem to work either. I've tried installing an extension even though auto-import didn't work. I've rechecked all the settings related to extensions. Finally, the auto-import feature started working when I clear the cache, from

C:\Users\username\AppData\Roaming\Code\Cache

& reload the VSCode

Note: AppData can only be visible in username if you select, Show (Hidden Items) from (View) Menu.

In some cases, we may end up thinking there is an import related error, while in actuality, unknowingly we might be coding using deprecated features or APIs in angular.

For example: if you're trying to code something like this

constructor (http: Http) {

//...}

Where Http is already deprecated and replaced with HttpClient in the newer version, so we may end up thinking an error related to this might be related to the auto-import error. For more information, you can refer Deprecated APIs and Features

Setting the zoom level for a MKMapView

I hope following code fragment would help you.

- (void)handleZoomOutAction:(id)sender {
    MKCoordinateRegion newRegion=MKCoordinateRegionMake(mapView.region.center,MKCoordinateSpanMake(mapView.region.s       pan.latitudeDelta/0.5, mapView.region.span.longitudeDelta/0.5));
    [mapView setRegion:newRegion];
}


- (void)handleZoomInAction:(id)sender {
    MKCoordinateRegion newRegion=MKCoordinateRegionMake(mapView.region.center,MKCoordinateSpanMake(mapView.region.span.latitudeDelta*0.5, mapView.region.span.longitudeDelta*0.5));
    [mapView setRegion:newRegion];
}

You can choose any value in stead of 0.5 to reduce or increase zoom level. I have used these methods on click of two buttons.

Nesting await in Parallel.ForEach

I am a little late to party but you may want to consider using GetAwaiter.GetResult() to run your async code in sync context but as paralled as below;

 Parallel.ForEach(ids, i =>
{
    ICustomerRepo repo = new CustomerRepo();
    // Run this in thread which Parallel library occupied.
    var cust = repo.GetCustomer(i).GetAwaiter().GetResult();
    customers.Add(cust);
});

Why am I seeing net::ERR_CLEARTEXT_NOT_PERMITTED errors after upgrading to Cordova Android 8?

Just add this line to platforms/android/app/src/main/AndroidManifest.xml file

<application android:hardwareAccelerated="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:usesCleartextTraffic="true">

Fastest way to add an Item to an Array

Dim arr As Integer() = {1, 2, 3}
Dim newItem As Integer = 4
ReDim Preserve arr (3)
arr(3)=newItem

for more info Redim

grep without showing path/file:line

No need to find. If you are just looking for a pattern within a specific directory, this should suffice:

grep -hn FOO /your/path/*.bar

Where -h is the parameter to hide the filename, as from man grep:

-h, --no-filename

Suppress the prefixing of file names on output. This is the default when there is only one file (or only standard input) to search.

Note that you were using

-H, --with-filename

Print the file name for each match. This is the default when there is more than one file to search.

IIS w3svc error

Well finally after a week struggle, I came to a solution. I am listing down the steps which I followed to solve my error:

  1. Confirm that "Windows Management Instrumentation" is started and its start up type is set to automatic.

  2. Also make sure the following dependency services are started for World Wide Web Publishing Service:

    • Windows Process Activation Service
    • Remote Procedure Call (RPC)
    • DCOM Server Process Launcher
    • RPC Endpoint Mapper.
  3. Open regedit, navigate to [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\HTTP]:
    a) Double click on Start and change value data from 4(disabled) to 3(automatically).
    b) Delete "NoRun" key if this key exists.

  4. (warning: backup any IIS website configuration first). UN-install "Internet information Service" and "Windows process activation service(if it is already installed)" from "Turn windows feature on or off" and Restart your PC.

  5. Type the below command in CMD and press enter:

    net start http
    

Now it will notify you that service is already running.

  1. Re-install Internet information Service from "Turn windows feature on or off".

  2. Start IIS and my websites are started now, no more "w3svc service is not running error."

How to import multiple .csv files at once?

In my view, most of the other answers are obsoleted by rio::import_list, which is a succinct one-liner:

library(rio)
my_data <- import_list(dir("path_to_directory", pattern = ".csv", rbind = TRUE))

Any extra arguments are passed to rio::import. rio can deal with almost any file format R can read, and it uses data.table's fread where possible, so it should be fast too.

How to read a local text file?

Jon Perryman,

Yes JS can read local files (see FileReader()) but not automatically: the user has to pass the file or a list of files to the script with an html <input type="file">.

Then with JS it is possible to process (example view) the file or the list of files, some of their properties and the file or files content.

What JS cannot do for security reasons is to access automatically (without the user input) to the filesystem of his computer.

To allow JS to access to the local fs automatically is needed to create not an html file with JS inside it but an hta document.

An hta file can contain JS or VBS inside it.

But the hta executable will work on windows systems only.

This is standard browser behavior.

Also Google Chrome worked at the fs API, more info here: http://www.html5rocks.com/en/tutorials/file/filesystem/

Vue v-on:click does not work on component

A bit verbose but this is how I do it:

@click="$emit('click', $event)"

UPDATE: Example added by @sparkyspider

<div-container @click="doSomething"></div-container>

In div-container component...

<template>
  <div @click="$emit('click', $event);">The inner div</div>
</template>

Foreach loop in java for a custom object list

If this code fails to operate on every item in the list, it must be because something is throwing an exception before you have completed the list; the likeliest candidate is the method called "insertOrThrow". You could wrap that call in a try-catch structure to handle the exception for whichever items are failing without exiting the loop and the method prematurely.

How to add an object to an array

Using ES6 notation, you can do something like this:

For appending you can use the spread operator like this:

_x000D_
_x000D_
var arr1 = [1,2,3]_x000D_
var obj = 4_x000D_
var newData = [...arr1, obj] // [1,2,3,4]_x000D_
console.log(newData);
_x000D_
_x000D_
_x000D_

ls command: how can I get a recursive full-path listing, one line per file?

ls -lR is what you were looking for, or atleast I was. cheers

How can I read large text files in Python, line by line, without loading it into memory?

I provided this answer because Keith's, while succinct, doesn't close the file explicitly

with open("log.txt") as infile:
    for line in infile:
        do_something_with(line)

Read int values from a text file in C

A simple solution using fscanf:

void read_ints (const char* file_name)
{
  FILE* file = fopen (file_name, "r");
  int i = 0;

  fscanf (file, "%d", &i);    
  while (!feof (file))
    {  
      printf ("%d ", i);
      fscanf (file, "%d", &i);      
    }
  fclose (file);        
}

How to rollback a specific migration?

If you want to rollback and migrate you can run:

rake db:migrate:redo

That's the same as:

rake db:rollback
rake db:migrate

Rename Excel Sheet with VBA Macro

The "no frills" options are as follows:

ActiveSheet.Name = "New Name"

and

Sheets("Sheet2").Name = "New Name"

You can also check out recording macros and seeing what code it gives you, it's a great way to start learning some of the more vanilla functions.

How to access a property of an object (stdClass Object) member/element of an array?

Try this, working fine -

$array = json_decode(json_encode($array), true);

Code coverage with Mocha

Blanket.js works perfect too.

npm install --save-dev blanket

in front of your test/tests.js

require('blanket')({
    pattern: function (filename) {
        return !/node_modules/.test(filename);
    }
});

run mocha -R html-cov > coverage.html

How to go to each directory and execute a command?

You can achieve this by piping and then using xargs. The catch is you need to use the -I flag which will replace the substring in your bash command with the substring passed by each of the xargs.

ls -d */ | xargs -I {} bash -c "cd '{}' && pwd"

You may want to replace pwd with whatever command you want to execute in each directory.

"Strict Standards: Only variables should be passed by reference" error

Instead of parsing it manually it's better to use pathinfo function:

$path_parts = pathinfo($value);
$extension = strtolower($path_parts['extension']);
$fileName = $path_parts['filename'];

How to determine if a decimal/double is an integer?

bool IsInteger(double num) {
    if (ceil(num) == num && floor(num) == num)
        return true;
    else
        return false;
}

Problemo solvo.

Edit: Pwned by Mark Rushakoff.

"Eliminate render-blocking CSS in above-the-fold content"

Few tips that may help:

  • I came across this article in CSS optimization yesterday: CSS profiling for ... optimization
    A lot of useful info on CSS and what CSS causes the most performance drains.

  • I saw the following presentation on jQueryUK on "hidden secrets" in Googe Chrome (Canary) Dev Tools: DevTools Can do that. Check out the sections on Time to First Paint, repaints and costly CSS.

  • Also, if you are using a loader like requireJS you could have a look at one of the CSS loader plugins, called require-CSS, which uses CSSO - a optimzer that also does structural optimization, eg. merging blocks with identical properties. I used it a few times and it can save quite a lot of CSS from case to case.

Off the question: I second @Enzino in creating a sprite for all the small icons you are loading. The file sizes are so small it does not really warrant a server roundtrip for each icon. Also keep in mind the total number of concurrent http requests are browser can do. So requests for a larger number of small icons are "render-blocking" as well. Although an empty page compare to yours, I like how duckduckgo loads for example.

pandas dataframe groupby datetime month

One solution which avoids MultiIndex is to create a new datetime column setting day = 1. Then group by this column.

Normalise day of month

df = pd.DataFrame({'Date': pd.to_datetime(['2017-10-05', '2017-10-20', '2017-10-01', '2017-09-01']),
                   'Values': [5, 10, 15, 20]})

# normalize day to beginning of month, 4 alternative methods below
df['YearMonth'] = df['Date'] + pd.offsets.MonthEnd(-1) + pd.offsets.Day(1)
df['YearMonth'] = df['Date'] - pd.to_timedelta(df['Date'].dt.day-1, unit='D')
df['YearMonth'] = df['Date'].map(lambda dt: dt.replace(day=1))
df['YearMonth'] = df['Date'].dt.normalize().map(pd.tseries.offsets.MonthBegin().rollback)

Then use groupby as normal:

g = df.groupby('YearMonth')

res = g['Values'].sum()

# YearMonth
# 2017-09-01    20
# 2017-10-01    30
# Name: Values, dtype: int64

Comparison with pd.Grouper

The subtle benefit of this solution is, unlike pd.Grouper, the grouper index is normalized to the beginning of each month rather than the end, and therefore you can easily extract groups via get_group:

some_group = g.get_group('2017-10-01')

Calculating the last day of October is slightly more cumbersome. pd.Grouper, as of v0.23, does support a convention parameter, but this is only applicable for a PeriodIndex grouper.

Comparison with string conversion

An alternative to the above idea is to convert to a string, e.g. convert datetime 2017-10-XX to string '2017-10'. However, this is not recommended since you lose all the efficiency benefits of a datetime series (stored internally as numerical data in a contiguous memory block) versus an object series of strings (stored as an array of pointers).

How do I fix twitter-bootstrap on IE?

You can add the meta tag:

<meta http-equiv="X-UA-Compatible" content="IE=edge" />

A brief explanation on what it is and how it works is found on this link.

Include CSS and Javascript in my django template

Read this https://docs.djangoproject.com/en/dev/howto/static-files/:

For local development, if you are using runserver or adding staticfiles_urlpatterns to your URLconf, you’re done with the setup – your static files will automatically be served at the default (for newly created projects) STATIC_URL of /static/.

And try:

~/tmp$ django-admin.py startproject myprj
~/tmp$ cd myprj/
~/tmp/myprj$ chmod a+x manage.py
~/tmp/myprj$ ./manage.py startapp myapp

Then add 'myapp' to INSTALLED_APPS (myprj/settings.py).

~/tmp/myprj$ cd myapp/
~/tmp/myprj/myapp$ mkdir static
~/tmp/myprj/myapp$ echo 'alert("hello!");' > static/hello.js
~/tmp/myprj/myapp$ mkdir templates
~/tmp/myprj/myapp$ echo '<script src="{{ STATIC_URL }}hello.js"></script>' > templates/hello.html

Edit myprj/urls.py:

from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView

class HelloView(TemplateView):
    template_name = "hello.html"

urlpatterns = patterns('',
    url(r'^$', HelloView.as_view(), name='hello'),
)

And run it:

~/tmp/myprj/myapp$ cd ..
~/tmp/myprj$ ./manage.py runserver

It works!

How to get $(this) selected option in jQuery?

 $(this).find('option:selected').text();

How to make the corners of a button round?

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

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

Facebook Oauth Logout

it's simple just type : $facebook->setSession(null); for logout

How to handle AssertionError in Python and find out which line or statement it occurred on?

The traceback module and sys.exc_info are overkill for tracking down the source of an exception. That's all in the default traceback. So instead of calling exit(1) just re-raise:

try:
    assert "birthday cake" == "ice cream cake", "Should've asked for pie"
except AssertionError:
    print 'Houston, we have a problem.'
    raise

Which gives the following output that includes the offending statement and line number:

Houston, we have a problem.
Traceback (most recent call last):
  File "/tmp/poop.py", line 2, in <module>
    assert "birthday cake" == "ice cream cake", "Should've asked for pie"
AssertionError: Should've asked for pie

Similarly the logging module makes it easy to log a traceback for any exception (including those which are caught and never re-raised):

import logging

try:
    assert False == True 
except AssertionError:
    logging.error("Nothing is real but I can't quit...", exc_info=True)

How to suppress "error TS2533: Object is possibly 'null' or 'undefined'"?

This is not an answer for the OP but I've seen a lot of people confused about how to avoid this error in the comments. This is a simple way to pass the compiler check

if (typeof(object) !== 'undefined') {
    // your code
}

Note: This won't work

if (object !== undefined) {
        // your code
    }

Error Importing SSL certificate : Not an X.509 Certificate

Many CAs will provide a cert in PKCS7 format.

According to Oracle documentation, the keytool commmand can handle PKCS#7 but sometimes it fails

The keytool command can import X.509 v1, v2, and v3 certificates, and PKCS#7 formatted certificate chains consisting of certificates of that type. The data to be imported must be provided either in binary encoding format or in printable encoding format (also known as Base64 encoding) as defined by the Internet RFC 1421 standard. In the latter case, the encoding must be bounded at the beginning by a string that starts with -----BEGIN, and bounded at the end by a string that starts with -----END.

If the PKCS7 file can't be imported try to transform it from PKCS7 to X.509:

openssl pkcs7 -print_certs -in certificate.p7b -out certificate.cer

Convert date from String to Date format in Dataframes

you can also do this query...!

sqlContext.sql("""
select from_unixtime(unix_timestamp('08/26/2016', 'MM/dd/yyyy'), 'yyyy:MM:dd') as new_format
""").show()

enter image description here

how concatenate two variables in batch script?

Enabling delayed variable expansion solves you problem, the script produces "hi":

setlocal EnableDelayedExpansion

set var1=A
set var2=B

set AB=hi

set newvar=!%var1%%var2%!

echo %newvar%

javac: file not found: first.java Usage: javac <options> <source files>

just open file then click on save as then name it as first.java then in that box there is another dropdown in that dropdown (save as type) select type as all and save it now you can compile it

exclude @Component from @ComponentScan

In case of excluding test component or test configuration, Spring Boot 1.4 introduced new testing annotations @TestComponent and @TestConfiguration.

Sqlite: CURRENT_TIMESTAMP is in GMT, not the timezone of the machine

Time ( 'now', 'localtime' ) and Date ( 'now', 'localtime' ) works.

Format date with Moment.js

You Probably Don't Need Moment.js Anymore

Moment is great time manipulation library but it's considered as a legacy project, and the team is recommending to use other libraries.

date-fns is one of the best lightweight libraries, it's modular, so you can pick the functions you need and reduce bundle size (issue & statement).

Another common argument against using Moment in modern applications is its size. Moment doesn't work well with modern "tree shaking" algorithms, so it tends to increase the size of web application bundles.

import { format } from 'date-fns' // 21K (gzipped: 5.8K)
import moment from 'moment' // 292.3K (gzipped: 71.6K)

Format date with date-fns:

// moment.js
moment().format('MM/DD/YYYY');
// => "12/18/2020"

// date-fns
import { format } from 'date-fns'
format(new Date(), 'MM/dd/yyyy');
// => "12/18/2020"

More on cheat sheet with the list of functions which you can use to replace moment.js: You-Dont-Need-Momentjs

How to find the first and second maximum number?

If you want the second highest number you can use

=LARGE(E4:E9;2)

although that doesn't account for duplicates so you could get the same result as the Max

If you want the largest number that is smaller than the maximum number you can use this version

=LARGE(E4:E9;COUNTIF(E4:E9;MAX(E4:E9))+1)

An invalid XML character (Unicode: 0xc) was found

public String stripNonValidXMLCharacters(String in) {
    StringBuffer out = new StringBuffer(); // Used to hold the output.
    char current; // Used to reference the current character.

    if (in == null || ("".equals(in))) return ""; // vacancy test.
    for (int i = 0; i < in.length(); i++) {
        current = in.charAt(i); // NOTE: No IndexOutOfBoundsException caught here; it should not happen.
        if ((current == 0x9) ||
            (current == 0xA) ||
            (current == 0xD) ||
            ((current >= 0x20) && (current <= 0xD7FF)) ||
            ((current >= 0xE000) && (current <= 0xFFFD)) ||
            ((current >= 0x10000) && (current <= 0x10FFFF)))
            out.append(current);
    }
    return out.toString();
}    

CSS Border Not Working

Do this:

border: solid #000;
border-width: 0 1px;

Live demo: http://jsfiddle.net/aFzKy/

Video format or MIME type is not supported

For Ubuntu 14.04

Just removed the package Oxideqt-dodecs then install flash or ubuntu restricted extras

and you are good to go!!

Moving items around in an ArrayList

As Mikkel posted before Collections.rotate is a simple way. I'm using this method for moving items up- and downward in a List.

public static <T> void moveItem(int sourceIndex, int targetIndex, List<T> list) {
    if (sourceIndex <= targetIndex) {
        Collections.rotate(list.subList(sourceIndex, targetIndex + 1), -1);
    } else {
        Collections.rotate(list.subList(targetIndex, sourceIndex + 1), 1);
    }
}

Convert generic List/Enumerable to DataTable?

I had to modify Marc Gravell's sample code to handle nullable types and null values. I have included a working version below. Thanks Marc.

public static DataTable ToDataTable<T>(this IList<T> data)
{
    PropertyDescriptorCollection properties = 
        TypeDescriptor.GetProperties(typeof(T));
    DataTable table = new DataTable();
    foreach (PropertyDescriptor prop in properties)
        table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
    foreach (T item in data)
    {
        DataRow row = table.NewRow();
        foreach (PropertyDescriptor prop in properties)
             row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
        table.Rows.Add(row);
    }
    return table;
}

How to check if a word is an English word with Python?

For All Linux/Unix Users

If your OS uses the Linux kernel, there is a simple way to get all the words from the English/American dictionary. In the directory /usr/share/dict you have a words file. There is also a more specific american-english and british-english files. These contain all of the words in that specific language. You can access this throughout every programming language which is why I thought you might want to know about this.

Now, for python specific users, the python code below should assign the list words to have the value of every single word:

import re
file = open("/usr/share/dict/words", "r")
words = re.sub("[^\w]", " ",  file.read()).split()

def is_word(word):
    return word.lower() in words

is_word("tarts") ## Returns true
is_word("jwiefjiojrfiorj") ## Returns False

Hope this helps!!!

How to overcome the CORS issue in ReactJS

Another way besides @Nahush's answer, if you are already using Express framework in the project then you can avoid using Nginx for reverse-proxy.

A simpler way is to use express-http-proxy

  1. run npm run build to create the bundle.

    var proxy = require('express-http-proxy');
    
    var app = require('express')();
    
    //define the path of build
    
    var staticFilesPath = path.resolve(__dirname, '..', 'build');
    
    app.use(express.static(staticFilesPath));
    
    app.use('/api/api-server', proxy('www.api-server.com'));
    

Use "/api/api-server" from react code to call the API.

So, that browser will send request to the same host which will be internally redirecting the request to another server and the browser will feel that It is coming from the same origin ;)

How to draw a line in android

You can make a drawable like circle, line, rectangle etc through shapes in xml as follow:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="line" >

    <solid android:color="#00000000" />

    <stroke
        android:width="2dp"
        android:color="#808080" />

</shape>

Undefined reference to pthread_create in Linux

Acutally, it gives several examples of compile commands used for pthreads codes are listed in the table below, if you continue reading the following tutorial:

https://computing.llnl.gov/tutorials/pthreads/#Compiling

enter image description here

How to downgrade Node version

 curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.11/install.sh | bash
 sudo npm install -g n
 sudo n 10.15
 npm install
 npm audit fix
 npm start

Bootstrap 3 with remote Modal

If you don't want to send the full modal structure you can replicate the old behaviour doing something like this:

// this is just an example, remember to adapt the selectors to your code!
$('.modal-link').click(function(e) {
    var modal = $('#modal'), modalBody = $('#modal .modal-body');

    modal
        .on('show.bs.modal', function () {
            modalBody.load(e.currentTarget.href)
        })
        .modal();
    e.preventDefault();
});

An established connection was aborted by the software in your host machine

I was getting these errors too and was stumped. After reading and trying the two answers above, I was still getting the error.

However,I checked the processes tab of Task Manager to find a rogue copy of 'eclipse.exe *32' that the UI didn' t show as running. I guess this should have been obvious as the error does suggest that the reason the emulator/phone cannot connect is because it's already established a connection with the second copy.

Long story short, make sure via Task Manager that no other Eclipse instances are running before resorting to a PC restart!

disable editing default value of text input

Probably due to the fact that I could not explain well you do not really understand my question. In general, I found the solution.

Sorry for my english

How to change the floating label color of TextInputLayout

In my case I added this "app:hintTextAppearance="@color/colorPrimaryDark"in my TextInputLayout widget.

How to create a timer using tkinter?

The root.after(ms, func) is the method you need to use. Just call it once before the mainloop starts and reschedule it inside the bound function every time it is called. Here is an example:

from tkinter import *
import time


def update_clock():
    timer_label.config(text=time.strftime('%H:%M:%S',time.localtime()),
                  font='Times 25')  # change the text of the time_label according to the current time
    root.after(100, update_clock)  # reschedule update_clock function to update time_label every 100 ms

root = Tk()  # create the root window
timer_label = Label(root, justify='center')  # create the label for timer
timer_label.pack()  # show the timer_label using pack geometry manager
root.after(0, update_clock)  # schedule update_clock function first call
root.mainloop()  # start the root window mainloop

UITextField text change event

SwiftUI

If you are using the native SwiftUI TextField or just using the UIKit UITextField (here is how), you can observe for text changes like:

SwiftUI 2.0

From iOS 14, macOS 11, or any other OS contains SwiftUI 2.0, there is a new modifier called .onChange that detects any change of the given state:

struct ContentView: View {
    @State var text: String = ""

    var body: some View {
        TextField("Enter text here", text: $text)
            .onChange(of: text) {
                print($0) // You can do anything due to the change here.
                // self.autocomplete($0) // like this
            }
    }
}

SwiftUI 1.0

For older iOS and other SwiftUI 1.0 platforms, you can use onReceive with the help of the combine framework:

import Combine
.onReceive(Just(text)) { 
    print($0)
}

Note that you can use text.publisher instead of Just(text) but it returns the change instead of the entire value.

"Sub or Function not defined" when trying to run a VBA script in Outlook

I solved the problem by following the instructions on msdn.microsoft.com more closely. There, it is stated that one must create the new macro by selecting Developer -> Macros, typing a new macro name, and clicking "Create". Creating the macro in this way, I was able to run it (see message box below).

enter image description here

Is it possible to force row level locking in SQL Server?

You can use the ROWLOCK hint, but AFAIK SQL may decide to escalate it if it runs low on resources

From the doco:

ROWLOCK Specifies that row locks are taken when page or table locks are ordinarily taken. When specified in transactions operating at the SNAPSHOT isolation level, row locks are not taken unless ROWLOCK is combined with other table hints that require locks, such as UPDLOCK and HOLDLOCK.

and

Lock hints ROWLOCK, UPDLOCK, AND XLOCK that acquire row-level locks may place locks on index keys rather than the actual data rows. For example, if a table has a nonclustered index, and a SELECT statement using a lock hint is handled by a covering index, a lock is acquired on the index key in the covering index rather than on the data row in the base table.

And finally this gives a pretty in-depth explanation about lock escalation in SQL Server 2005 which was changed in SQL Server 2008.

There is also, the very in depth: Locking in The Database Engine (in books online)

So, in general

UPDATE
Employees WITH (ROWLOCK)
SET Name='Mr Bean'
WHERE Age>93

Should be ok, but depending on the indexes and load on the server it may end up escalating to a page lock.

What is the Angular equivalent to an AngularJS $watch?

In Angular 2, change detection is automatic... $scope.$watch() and $scope.$digest() R.I.P.

Unfortunately, the Change Detection section of the dev guide is not written yet (there is a placeholder near the bottom of the Architecture Overview page, in section "The Other Stuff").

Here's my understanding of how change detection works:

  • Zone.js "monkey patches the world" -- it intercepts all of the asynchronous APIs in the browser (when Angular runs). This is why we can use setTimeout() inside our components rather than something like $timeout... because setTimeout() is monkey patched.
  • Angular builds and maintains a tree of "change detectors". There is one such change detector (class) per component/directive. (You can get access to this object by injecting ChangeDetectorRef.) These change detectors are created when Angular creates components. They keep track of the state of all of your bindings, for dirty checking. These are, in a sense, similar to the automatic $watches() that Angular 1 would set up for {{}} template bindings.
    Unlike Angular 1, the change detection graph is a directed tree and cannot have cycles (this makes Angular 2 much more performant, as we'll see below).
  • When an event fires (inside the Angular zone), the code we wrote (the event handler callback) runs. It can update whatever data it wants to -- the shared application model/state and/or the component's view state.
  • After that, because of the hooks Zone.js added, it then runs Angular's change detection algorithm. By default (i.e., if you are not using the onPush change detection strategy on any of your components), every component in the tree is examined once (TTL=1)... from the top, in depth-first order. (Well, if you're in dev mode, change detection runs twice (TTL=2). See ApplicationRef.tick() for more about this.) It performs dirty checking on all of your bindings, using those change detector objects.
    • Lifecycle hooks are called as part of change detection.
      If the component data you want to watch is a primitive input property (String, boolean, number), you can implement ngOnChanges() to be notified of changes.
      If the input property is a reference type (object, array, etc.), but the reference didn't change (e.g., you added an item to an existing array), you'll need to implement ngDoCheck() (see this SO answer for more on this).
      You should only change the component's properties and/or properties of descendant components (because of the single tree walk implementation -- i.e., unidirectional data flow). Here's a plunker that violates that. Stateful pipes can also trip you up here.
  • For any binding changes that are found, the Components are updated, and then the DOM is updated. Change detection is now finished.
  • The browser notices the DOM changes and updates the screen.

Other references to learn more:

How to hide form code from view code/inspect element browser?

Below JavaScript code worked for me to disable inspect element.

// Disable inspect element
$(document).bind("contextmenu",function(e) {
 e.preventDefault();
});
$(document).keydown(function(e){
    if(e.which === 123){
       return false;
    }
});

MISCONF Redis is configured to save RDB snapshots

# on redis 6.0.4 
# if show error 'MISCONF Redis is configured to save RDB snapshots'
# Because redis doesn't have permissions to create dump.rdb file
sudo redis/bin/redis-server 
sudo redis/bin/redis-cli

jQuery jump or scroll to certain position, div or target on the page from button onclick

$("html, body").scrollTop($(element).offset().top); // <-- Also integer can be used

How to tackle daylight savings using TimeZone in Java

Other answers are correct, especially the one by Jon Skeet, but outdated.

java.time

These old date-time classes have been supplanted by the java.time framework built into Java 8 and later.

If you simply want the current time in UTC, use the Instant class.

Instant now = Instant.now();

EST is not a time zone, as explained in the correct Answer by Jon Skeet. Such 3-4 letter codes are neither standardized nor unique, and further the confusion over Daylight Saving Time (DST). Use a proper time zone name in the "continent/region" format.

Perhaps you meant Eastern Standard Time in east coast of north America? Or Egypt Standard Time? Or European Standard Time?

ZoneId zoneId = ZoneId.of( "America/New_York" );
ZoneId zoneId = ZoneId.of( "Africa/Cairo" );
ZoneId zoneId = ZoneId.of( "Europe/Lisbon" );

Use any such ZoneId object to get the current moment adjusted to a particular time zone to produce a ZonedDateTime object.

ZonedDateTime zdt = ZonedDateTime.now( zoneId ) ;

Adjust that ZonedDateTime into a different time zone by producing another ZonedDateTime object from the first. The java.time framework uses immutable objects rather than changing (mutating) existing objects.

ZonedDateTime zdtGuam = zdt.withZoneSameInstant( ZoneId.of( "Pacific/Guam" ) ) ;

Table of date-time types in Java, both modern and legacy.

How do I escape double and single quotes in sed?

Prompt% cat t1
This is "Unix"
This is "Unix sed"
Prompt% sed -i 's/\"Unix\"/\"Linux\"/g' t1
Prompt% sed -i 's/\"Unix sed\"/\"Linux SED\"/g' t1
Prompt% cat t1
This is "Linux"
This is "Linux SED"
Prompt%

Access denied for user 'homestead'@'localhost' (using password: YES)

in my case, after restarting my server the problem was gone.

exit/close the "php artisan serve" command and

re-run the command "php artisan serve" command.

Where is Maven Installed on Ubuntu

Ubuntu 11.10 doesn't have maven3 in repo.

Follow below step to install maven3 on ubuntu 11.10

sudo add-apt-repository ppa:natecarlson/maven3
sudo apt-get update && sudo apt-get install maven3

Open terminal: mvn3 -v

if you want mvn as a binary then execute below script:

sudo ln -s /usr/bin/mvn3 /usr/bin/mvn

I hope this will help you.

Thanks, Rajam

How to remove item from array by value?

//This function allows remove even array from array
var removeFromArr = function(arr, elem) { 
    var i, len = arr.length, new_arr = [],
    sort_fn = function (a, b) { return a - b; };
    for (i = 0; i < len; i += 1) {
        if (typeof elem === 'object' && typeof arr[i] === 'object') {
            if (arr[i].toString() === elem.toString()) {
                continue;
            } else {                    
                if (arr[i].sort(sort_fn).toString() === elem.sort(sort_fn).toString()) {
                    continue;
                }
            }
        }
        if (arr[i] !== elem) {
            new_arr.push(arr[i]);
        }
    }
    return new_arr;
}

Example of using

var arr = [1, '2', [1 , 1] , 'abc', 1, '1', 1];
removeFromArr(arr, 1);
//["2", [1, 1], "abc", "1"]

var arr = [[1, 2] , 2, 'a', [2, 1], [1, 1, 2]];
removeFromArr(arr, [1,2]);
//[2, "a", [1, 1, 2]]

How to split strings over multiple lines in Bash?

This probably doesn't really answer your question but you might find it useful anyway.

The first command creates the script that's displayed by the second command.

The third command makes that script executable.

The fourth command provides a usage example.

john@malkovich:~/tmp/so$ echo $'#!/usr/bin/env python\nimport textwrap, sys\n\ndef bash_dedent(text):\n    """Dedent all but the first line in the passed `text`."""\n    try:\n        first, rest = text.split("\\n", 1)\n        return "\\n".join([first, textwrap.dedent(rest)])\n    except ValueError:\n        return text  # single-line string\n\nprint bash_dedent(sys.argv[1])'  > bash_dedent
john@malkovich:~/tmp/so$ cat bash_dedent 
#!/usr/bin/env python
import textwrap, sys

def bash_dedent(text):
    """Dedent all but the first line in the passed `text`."""
    try:
        first, rest = text.split("\n", 1)
        return "\n".join([first, textwrap.dedent(rest)])
    except ValueError:
        return text  # single-line string

print bash_dedent(sys.argv[1])
john@malkovich:~/tmp/so$ chmod a+x bash_dedent
john@malkovich:~/tmp/so$ echo "$(./bash_dedent "first line
>     second line
>     third line")"
first line
second line
third line

Note that if you really want to use this script, it makes more sense to move the executable script into ~/bin so that it will be in your path.

Check the python reference for details on how textwrap.dedent works.

If the usage of $'...' or "$(...)" is confusing to you, ask another question (one per construct) if there's not already one up. It might be nice to provide a link to the question you find/ask so that other people will have a linked reference.

Jenkins - How to access BUILD_NUMBER environment variable

Assuming I am understanding your question and setup correctly,

If you're trying to use the build number in your script, you have two options:

1) When calling ant, use: ant -Dbuild_parameter=${BUILD_NUMBER}

2) Change your script so that:

<property environment="env" />
<property name="build_parameter"  value="${env.BUILD_NUMBER}"/>

How to set a hidden value in Razor

There is a Hidden helper alongside HiddenFor which lets you set the value.

@Html.Hidden("RequiredProperty", "default")

EDIT Based on the edit you've made to the question, you could do this, but I believe you're moving into territory where it will be cheaper and more effective, in the long run, to fight for making the code change. As has been said, even by yourself, the controller or view model should be setting the default.

This code:

<ul>
@{
        var stacks = new System.Diagnostics.StackTrace().GetFrames();
        foreach (var frame in stacks)
        {
            <li>@frame.GetMethod().Name - @frame.GetMethod().DeclaringType</li>
        }
}
</ul>

Will give output like this:

Execute - ASP._Page_Views_ViewDirectoryX__SubView_cshtml
ExecutePageHierarchy - System.Web.WebPages.WebPageBase
ExecutePageHierarchy - System.Web.Mvc.WebViewPage
ExecutePageHierarchy - System.Web.WebPages.WebPageBase
RenderView - System.Web.Mvc.RazorView
Render - System.Web.Mvc.BuildManagerCompiledView
RenderPartialInternal - System.Web.Mvc.HtmlHelper
RenderPartial - System.Web.Mvc.Html.RenderPartialExtensions
Execute - ASP._Page_Views_ViewDirectoryY__MainView_cshtml

So assuming the MVC framework will always go through the same stack, you can grab var frame = stacks[8]; and use the declaring type to determine who your parent view is, and then use that determination to set (or not) the default value. You could also walk the stack instead of directly grabbing [8] which would be safer but even less efficient.

Can a foreign key be NULL and/or duplicate?

By default there are no constraints on the foreign key, foreign key can be null and duplicate.

while creating a table / altering the table, if you add any constrain of uniqueness or not null then only it will not allow the null/ duplicate values.

How to get the cookie value in asp.net website

HttpCookie cook = new HttpCookie("testcook");
cook = Request.Cookies["CookName"];
if (cook != null)
{
    lbl_cookie_value.Text = cook.Value;
}
else
{
    lbl_cookie_value.Text = "Empty value";
}

Reference Click here

Swing JLabel text change on the running application

Use setText(str) method of JLabel to dynamically change text displayed. In actionPerform of button write this:

jLabel.setText("new Value");

A simple demo code will be:

    JFrame frame = new JFrame("Demo");
    frame.setLayout(new BorderLayout());
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.setSize(250,100);

    final JLabel label = new JLabel("flag");
    JButton button = new JButton("Change flag");
    button.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            label.setText("new value");
        }
    });

    frame.add(label, BorderLayout.NORTH);
    frame.add(button, BorderLayout.CENTER);
    frame.setVisible(true);

How do you make an anchor link non-clickable or disabled?

Add a css class:

.disable_a_href{
    pointer-events: none;
}

Add this jquery:

$("#ThisLink").addClass("disable_a_href"); 

How to put a link on a button with bootstrap?

You can just simply add the following code;

<a class="btn btn-primary" href="http://localhost:8080/Home" role="button">Home Page</a>

How do you remove the title text from the Android ActionBar?

If you only want to do it for one activity and perhaps even dynamically, you can also use

ActionBar actionBar = getActionBar();
actionBar.setDisplayOptions(actionBar.getDisplayOptions() ^ ActionBar.DISPLAY_SHOW_TITLE);

Generating (pseudo)random alpha-numeric strings

One line solution:

echo substr( str_shuffle( str_repeat( 'abcdefghijklmnopqrstuvwxyz0123456789', 10 ) ), 0, 7 );

You can change the substr parameter in order to set a different length for your string.

html button to send email

You can use mailto, here is the HTML code:

<a href="mailto:EMAILADDRESS">

Replace EMAILADDRESS with your email.

Amazon Linux: apt-get: command not found

There can be 2 issues :=

1. Your are trying the command in machine that does not support apt-get command
because apt-get is suitable for Linux based Ubuntu machines; for MAC, try
apt-get equivalent such as Brew

2. The other issue can be that your installation was not completed properly So

The short answer:

Re-install Ubuntu from a Live CD or USB.

The long version:

The long version would be a waste of your time: your system will never
be clean, but if you insist you could try:

==> Copying everything (missing) except for the /home folder from the Live
CD/USB to your HDD.

OR

==> Do a re-install/repair over the broken system again with the Live
CD / USB stick.

OR

==> Download the deb file for apt-get and install as explained on above posts.
I would definitely go for a fresh new install as there are so many things to
do and so little time.

Get Character value from KeyCode in JavaScript... then trim

Just an important note: the accepted answer above will not work correctly for keyCode >= 144, i.e. period, comma, dash, etc. For those you should use a more general algorithm:

let chrCode = keyCode - 48 * Math.floor(keyCode / 48);
let chr = String.fromCharCode((96 <= keyCode) ? chrCode: keyCode);

If you're curious as to why, this is apparently necessary because of the behavior of the built-in JS function String.fromCharCode(). For values of keyCode <= 96 it seems to map using the function:

chrCode = keyCode - 48 * Math.floor(keyCode / 48)

For values of keyCode > 96 it seems to map using the function:

chrCode = keyCode

If this seems like odd behavior then well..I agree. Sadly enough, it would be very far from the weirdest thing I've seen in the JS core.

_x000D_
_x000D_
document.onkeydown = function(e) {_x000D_
    let keyCode = e.keyCode;_x000D_
    let chrCode = keyCode - 48 * Math.floor(keyCode / 48);_x000D_
    let chr = String.fromCharCode((96 <= keyCode) ? chrCode: keyCode);_x000D_
    console.log(chr);_x000D_
};
_x000D_
<input type="text" placeholder="Focus and Type"/>
_x000D_
_x000D_
_x000D_

How can I have linebreaks in my long LaTeX equations?

This worked for me while using mathtools package.

\documentclass{article}
\usepackage{mathtools}
\begin{document}
    \begin{equation}
        \begin{multlined}
            first term \\
            second term                 
        \end{multlined}
    \end{equation}
\end{document}

How to handle the new window in Selenium WebDriver using Java?

It seems like you are not actually switching to any new window. You are supposed get the window handle of your original window, save that, then get the window handle of the new window and switch to that. Once you are done with the new window you need to close it, then switch back to the original window handle. See my sample below:

i.e.

String parentHandle = driver.getWindowHandle(); // get the current window handle
driver.findElement(By.xpath("//*[@id='someXpath']")).click(); // click some link that opens a new window

for (String winHandle : driver.getWindowHandles()) {
    driver.switchTo().window(winHandle); // switch focus of WebDriver to the next found window handle (that's your newly opened window)
}

//code to do something on new window

driver.close(); // close newly opened window when done with it
driver.switchTo().window(parentHandle); // switch back to the original window

long long in C/C++

Try:

num3 = 100000000000LL;

And BTW, in C++ this is a compiler extension, the standard does not define long long, thats part of C99.

Why use String.Format?

There's interesting stuff on the performance aspects in this question

However I personally would still recommend string.Format unless performance is critical for readability reasons.

string.Format("{0}: {1}", key, value);

Is more readable than

key + ": " + value

For instance. Also provides a nice separation of concerns. Means you can have

string.Format(GetConfigValue("KeyValueFormat"), key, value);

And then changing your key value format from "{0}: {1}" to "{0} - {1}" becomes a config change rather than a code change.

string.Format also has a bunch of format provision built into it, integers, date formatting, etc.

How do I set session timeout of greater than 30 minutes

Setting the timeout in the web.xml is the correct way to set the timeout.

What are the different NameID format used for?

1 and 2 are SAML 1.1 because those URIs were part of the OASIS SAML 1.1 standard. Section 8.3 of the linked PDF for the OASIS SAML 2.0 standard explains this:

Where possible an existing URN is used to specify a protocol. In the case of IETF protocols, the URN of the most current RFC that specifies the protocol is used. URI references created specifically for SAML have one of the following stems, according to the specification set version in which they were first introduced:

urn:oasis:names:tc:SAML:1.0:
urn:oasis:names:tc:SAML:1.1:
urn:oasis:names:tc:SAML:2.0:

Transpose a data frame

Take advantage of as.matrix:

# keep the first column 
names <-  df.aree[,1]

# Transpose everything other than the first column
df.aree.T <- as.data.frame(as.matrix(t(df.aree[,-1])))

# Assign first column as the column names of the transposed dataframe
colnames(df.aree.T) <- names

PackagesNotFoundError: The following packages are not available from current channels:

Have you tried:

pip install <package>

or

conda install -c conda-forge <package>

R Apply() function on specific dataframe columns

lapply is probably a better choice than apply here, as apply first coerces your data.frame to an array which means all the columns must have the same type. Depending on your context, this could have unintended consequences.

The pattern is:

df[cols] <- lapply(df[cols], FUN)

The 'cols' vector can be variable names or indices. I prefer to use names whenever possible (it's robust to column reordering). So in your case this might be:

wifi[4:9] <- lapply(wifi[4:9], A)

An example of using column names:

wifi <- data.frame(A=1:4, B=runif(4), C=5:8)
wifi[c("B", "C")] <- lapply(wifi[c("B", "C")], function(x) -1 * x)

Why isn't ProjectName-Prefix.pch created automatically in Xcode 6?

You need to create own PCH file
Add New file -> Other-> PCH file

Then add the path of this PCH file to your build setting->prefix header->path

($(SRCROOT)/filename.pch)

enter image description here

Open Cygwin at a specific folder

I have made a registry edit script to open Cygwin at any folder you right click. It's on my GitHub.

Here's my GitHub

Sample RegEdit code from Github for 64-bit machines:

REGEDIT4

[HKEY_CLASSES_ROOT\Directory\shell\CygwinHere]
@="&Cygwin Bash Here"

[HKEY_CLASSES_ROOT\Directory\shell\CygwinHere\command]
@="C:\\cygwin64\\bin\\mintty.exe -i /Cygwin-Terminal.ico C:\\cygwin64\\bin\\bash.exe --login -c \"cd \\\"%V\\\" ; exec bash -rcfile ~/.bashrc\""

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Directory\Background\shell\CygwinHere]
@="&Cygwin Bash Here"

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Directory\Background\shell\CygwinHere\command]
@="C:\\cygwin64\\bin\\mintty.exe -i /Cygwin-Terminal.ico C:\\cygwin64\\bin\\bash.exe --login -c \"cd \\\"%V\\\" ; exec bash -rcfile ~/.bashrc\""

Setting table column width

_x000D_
_x000D_
    table { table-layout: fixed; }_x000D_
    .subject { width: 70%; }
_x000D_
    <table>_x000D_
      <tr>_x000D_
        <th>From</th>_x000D_
        <th class="subject">Subject</th>_x000D_
        <th>Date</th>_x000D_
      </tr>_x000D_
    </table>
_x000D_
_x000D_
_x000D_

Excel - Sum column if condition is met by checking other column in same table

Actually a more refined solution is use the build-in function sumif, this function does exactly what you need, will only sum those expenses of a specified month.

example

=SUMIF(A2:A100,"=January",B2:B100)

Vertically align text to top within a UILabel

yourLabel.baselineAdjustment = UIBaselineAdjustmentAlignCenters;

How to get Domain name from URL using jquery..?

In a browser

You can leverage the browser's URL parser using an <a> element:

var hostname = $('<a>').prop('href', url).prop('hostname');

or without jQuery:

var a = document.createElement('a');
a.href = url;
var hostname = a.hostname;

(This trick is particularly useful for resolving paths relative to the current page.)

Outside of a browser (and probably more efficiently):

Use the following function:

function get_hostname(url) {
    var m = url.match(/^http:\/\/[^/]+/);
    return m ? m[0] : null;
}

Use it like this:

get_hostname("http://example.com/path");

This will return http://example.com/ as in your example output.

Hostname of the current page

If you are only trying the get the hostname of the current page, use document.location.hostname.

how to hide <li> bullets in navigation menu and footer links BUT show them for listing items

Let's say you're using this HTML5 layout:

<html>
    <body>
        <header>
            <nav><ul>...</ul></nav>
        </header>
        <article>
            <ul>...</ul>
        </article>
        <footer>
            <ul>...</ul>
        </footer>
    </body>
</html>

You could say in your CSS:

header ul, footer ul, nav ul { list-style-type: none; }

If you're using HTML 4, assign IDs to your DIVs (instead of using the new fancy-pants elements) and change this to:

#header ul, #footer ul, #nav ul { list-style-type: none; }

If you're using a CSS reset stylesheet (like Eric Meyer's), you would actually have to give the list style back, since the reset removes the list style from all lists.

#content ul { list-style-type: disc; margin-left: 1.5em; }

How do I turn a C# object into a JSON string in .NET?

Since we all love one-liners

... this one depends on the Newtonsoft NuGet package, which is popular and better than the default serializer.

Newtonsoft.Json.JsonConvert.SerializeObject(new {foo = "bar"})

Documentation: Serializing and Deserializing JSON

How to get root view controller?

Objective-C

UIViewController *controller = [UIApplication sharedApplication].keyWindow.rootViewController;

Swift 2.0

let viewController = UIApplication.sharedApplication().keyWindow?.rootViewController

Swift 5

let viewController = UIApplication.shared.keyWindow?.rootViewController

How to use continue in jQuery each() loop?

return or return false are not the same as continue. If the loop is inside a function the remainder of the function will not execute as you would expect with a true "continue".

Prevent Caching in ASP.NET MVC for specific actions using an attribute

You can use the built in cache attribute to prevent caching.

For .net Framework: [OutputCache(NoStore = true, Duration = 0)]

For .net Core: [ResponseCache(NoStore = true, Duration = 0)]

Be aware that it is impossible to force the browser to disable caching. The best you can do is provide suggestions that most browsers will honor, usually in the form of headers or meta tags. This decorator attribute will disable server caching and also add this header: Cache-Control: public, no-store, max-age=0. It does not add meta tags. If desired, those can be added manually in the view.

Additionally, JQuery and other client frameworks will attempt to trick the browser into not using it's cached version of a resource by adding stuff to the url, like a timestamp or GUID. This is effective in making the browser ask for the resource again but doesn't really prevent caching.

On a final note. You should be aware that resources can also be cached in between the server and client. ISP's, proxies, and other network devices also cache resources and they often use internal rules without looking at the actual resource. There isn't much you can do about these. The good news is that they typically cache for shorter time frames, like seconds or minutes.

How to take a screenshot programmatically on iOS

This will work with swift 4.2, the screenshot will be saved in library, but please don't forget to edit the info.plist @ NSPhotoLibraryAddUsageDescription :

  @IBAction func takeScreenshot(_ sender: UIButton) {

    //Start full Screenshot
    print("full Screenshot")
    UIGraphicsBeginImageContext(card.frame.size)
    view.layer.render(in: UIGraphicsGetCurrentContext()!)
    var sourceImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    UIImageWriteToSavedPhotosAlbum(sourceImage!, nil, nil, nil)

    //Start partial Screenshot
    print("partial Screenshot")
    UIGraphicsBeginImageContext(card.frame.size)
    sourceImage?.draw(at: CGPoint(x:-25,y:-100)) //the screenshot starts at -25, -100
    var croppedImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    UIImageWriteToSavedPhotosAlbum(croppedImage!, nil, nil, nil)

}

How should I do integer division in Perl?

Eg 9 / 4 = 2.25

int(9) / int(4) = 2

9 / 4 - remainder / deniminator = 2

9 /4 - 9 % 4 / 4 = 2

seek() function?

For strings, forget about using WHENCE: use f.seek(0) to position at beginning of file and f.seek(len(f)+1) to position at the end of file. Use open(file, "r+") to read/write anywhere in a file. If you use "a+" you'll only be able to write (append) at the end of the file regardless of where you position the cursor.

Nginx sites-enabled, sites-available: Cannot create soft-link between config files in Ubuntu 12.04

My site configuration file is example.conf in sites-available folder So you can create a symbolic link as

ln -s /etc/nginx/sites-available/example.conf /etc/nginx/sites-enabled/

How to minify php page html output?

This work for me.

function Minify_Html($Html)
{
   $Search = array(
    '/(\n|^)(\x20+|\t)/',
    '/(\n|^)\/\/(.*?)(\n|$)/',
    '/\n/',
    '/\<\!--.*?-->/',
    '/(\x20+|\t)/', # Delete multispace (Without \n)
    '/\>\s+\</', # strip whitespaces between tags
    '/(\"|\')\s+\>/', # strip whitespaces between quotation ("') and end tags
    '/=\s+(\"|\')/'); # strip whitespaces between = "'

   $Replace = array(
    "\n",
    "\n",
    " ",
    "",
    " ",
    "><",
    "$1>",
    "=$1");

$Html = preg_replace($Search,$Replace,$Html);
return $Html;
}

Best way to randomize an array with .NET

This is a complete working Console solution based on the example provided in here:

class Program
{
    static string[] words1 = new string[] { "brown", "jumped", "the", "fox", "quick" };

    static void Main()
    {
        var result = Shuffle(words1);
        foreach (var i in result)
        {
            Console.Write(i + " ");
        }
        Console.ReadKey();
    }

   static string[] Shuffle(string[] wordArray) {
        Random random = new Random();
        for (int i = wordArray.Length - 1; i > 0; i--)
        {
            int swapIndex = random.Next(i + 1);
            string temp = wordArray[i];
            wordArray[i] = wordArray[swapIndex];
            wordArray[swapIndex] = temp;
        }
        return wordArray;
    }         
}

Set JavaScript variable = null, or leave undefined?

I declare them as undefined when I don't assign a value because they are undefined after all.

PHP how to get the base domain/url?

Please try this:

$uri = $_SERVER['REQUEST_URI']; // $uri == example.com/sub
$exploded_uri = explode('/', $uri); //$exploded_uri == array('example.com','sub')
$domain_name = $exploded_uri[1]; //$domain_name = 'example.com'

I hope this will help you.

Convert array of integers to comma-separated string

var result = string.Join(",", arr);

This uses the following overload of string.Join:

public static string Join<T>(string separator, IEnumerable<T> values);