Programs & Examples On #Propel

Propel is an open-source Object-Relational Mapping (ORM) for PHP5. It allows you to access your database using a set of objects, providing a simple API for storing and retrieving data. There are two major versions, 1 and 2.

'node' is not recognized as an internal or an external command, operable program or batch file while using phonegap/cordova

As you're using Windows, installation should automatically edit the %PATH% variable. Therefore, I suspect you simply need to reboot your system after installing.

warning: control reaches end of non-void function [-Wreturn-type]

You can also use EXIT_SUCCESS instead of return 0;. The macro EXIT_SUCCESS is actually defined as zero, but makes your program more readable.

How to use andWhere and orWhere in Doctrine?

Here's an example for those who have more complicated conditions and using Doctrine 2.* with QueryBuilder:

$qb->where('o.foo = 1')
   ->andWhere($qb->expr()->orX(
      $qb->expr()->eq('o.bar', 1),
      $qb->expr()->eq('o.bar', 2)
   ))
  ;

Those are expressions mentioned in Czechnology answer.

Check if an array item is set in JS

TLDR; The best I can come up with is this: (Depending on your use case, there are a number of ways to optimize this function.)

function arrayIndexExists(array, index){
    if ( typeof index !== 'number' && index === parseInt(index).toString()) {
        index = parseInt(index);
    } else {
        return false;//to avoid checking typeof again
    }
    return typeof index === 'number' && index % 1===0 && index >= 0 && array.hasOwnKey(index);
}

The other answer's examples get close and will work for some (probably most) purposes, but are technically quite incorrect for reasons I explain below.

Javascript arrays only use 'numerical' keys. When you set an "associative key" on an array, you are actually setting a property on that array object, not an element of that array. For example, this means that the "associative key" will not be iterated over when using Array.forEach() and will not be included when calculating Array.length. (The exception for this is strings like '0' will resolve to an element of the array, but strings like ' 0' won't.)

Additionally, checking array element or object property that doesn't exist does evaluate as undefined, but that doesn't actually tell you that the array element or object property hasn't been set yet. For example, undefined is also the result you get by calling a function that doesn't terminate with a return statement. This could lead to some strange errors and difficulty debugging code.

This can be confusing, but can be explored very easily using your browser's javascript console. (I used chrome, each comment indicates the evaluated value of the line before it.);

var foo = new Array();
foo;
//[]
foo.length;
//0
foo['bar'] = 'bar';
//"bar"
foo;
//[]
foo.length;
//0
foo.bar;
//"bar"

This shows that associative keys are not used to access elements in the array, but for properties of the object.

foo[0] = 0;
//0
foo;
//[0]
foo.length;
//1
foo[2] = undefined
//undefined
typeof foo[2]
//"undefined"
foo.length
//3

This shows that checking typeof doesn't allow you to see if an element has been set.

var foo = new Array();
//undefined
foo;
//[]
foo[0] = 0;
//0
foo['0']
//0
foo[' 0']
//undefined

This shows the exception I mentioned above and why you can't just use parseInt();

If you want to use associative arrays, you are better off using simple objects as other answers have recommended.

Can we rely on String.isEmpty for checking null condition on a String in Java?

String s1=""; // empty string assigned to s1 , s1 has length 0, it holds a value of no length string

String s2=null; // absolutely nothing, it holds no value, you are not assigning any value to s2

so null is not the same as empty.

hope that helps!!!

batch file Copy files with certain extensions from multiple directories into one directory

Brandon, short and sweet. Also flexible.

set dSource=C:\Main directory\sub directory
set dTarget=D:\Documents
set fType=*.doc
for /f "delims=" %%f in ('dir /a-d /b /s "%dSource%\%fType%"') do (
    copy /V "%%f" "%dTarget%\" 2>nul
)

Hope this helps.

I would add some checks after the copy (using '||') but i'm not sure how "copy /v" reacts when it encounters an error.

you may want to try this:

copy /V "%%f" "%dTarget%\" 2>nul|| echo En error occured copying "%%F".&& exit /b 1

As the copy line. let me know if you get something out of it (in no position to test a copy failure atm..)

Git: "Corrupt loose object"

I solved this way: I decided to simply copy the uncorrupted object file from the backup's clone to my original repository. This worked just as well. (By the way: If you can't find the object in .git/objects/ by its name, it probably has been [packed][pack] to conserve space.)

Random state (Pseudo-random number) in Scikit learn

If you don't specify the random_state in your code, then every time you run(execute) your code a new random value is generated and the train and test datasets would have different values each time.

However, if a fixed value is assigned like random_state = 42 then no matter how many times you execute your code the result would be the same .i.e, same values in train and test datasets.

UILabel is not auto-shrinking text to fit label size

You can write like

UILabel *reviews = [[UILabel alloc]initWithFrame:CGRectMake(14, 13,270,30)];//Set frame
reviews.numberOfLines=0;
reviews.textAlignment = UITextAlignmentLeft;
reviews.font = [UIFont fontWithName:@"Arial Rounded MT Bold" size:12];
reviews.textColor=[UIColor colorWithRed:0.0/255.0 green:0.0/255.0 blue:0.0/255.0 alpha:0.8]; 
reviews.backgroundColor=[UIColor clearColor];

You can calculate number of lines like that

CGSize maxlblSize = CGSizeMake(270,9999);
CGSize totalSize = [reviews.text sizeWithFont:reviews.font 
              constrainedToSize:maxlblSize lineBreakMode:reviews.lineBreakMode];

CGRect newFrame =reviews.frame;
newFrame.size.height = totalSize.height;
reviews.frame = newFrame;

CGFloat reviewlblheight = totalSize.height;

int lines=reviewlblheight/12;//12 is the font size of label

UILabel *lbl=[[UILabel alloc]init];
lbl.frame=CGRectMake(140,220 , 100, 25);//set frame as your requirement
lbl.font=[UIFont fontWithName:@"Arial" size:20];
[lbl setAutoresizingMask:UIViewContentModeScaleAspectFill];
[lbl setLineBreakMode:UILineBreakModeClip];
lbl.adjustsFontSizeToFitWidth=YES;//This is main for shrinking font
lbl.text=@"HelloHelloHello";

Hope this will help you :-) waiting for your reply

get current date from [NSDate date] but set the time to 10:00 am

I just set the timezone with Matthias Bauch answer And it worked for me. else it was adding 18:30 min more.

let cal: NSCalendar = NSCalendar.currentCalendar()
cal.timeZone = NSTimeZone(forSecondsFromGMT: 0)
let newDate: NSDate = cal.dateBySettingHour(1, minute: 0, second: 0, ofDate: NSDate(), options: NSCalendarOptions())!

How can I connect to a Tor hidden service using cURL in PHP?

TL;DR: Set CURLOPT_PROXYTYPE to use CURLPROXY_SOCKS5_HOSTNAME if you have a modern PHP, the value 7 otherwise, and/or correct the CURLOPT_PROXY value.

As you correctly deduced, you cannot resolve .onion domains via the normal DNS system, because this is a reserved top-level domain specifically for use by Tor and such domains by design have no IP addresses to map to.

Using CURLPROXY_SOCKS5 will direct the cURL command to send its traffic to the proxy, but will not do the same for domain name resolution. The DNS requests, which are emitted before cURL attempts to establish the actual connection with the Onion site, will still be sent to the system's normal DNS resolver. These DNS requests will surely fail, because the system's normal DNS resolver will not know what to do with a .onion address unless it, too, is specifically forwarding such queries to Tor.

Instead of CURLPROXY_SOCKS5, you must use CURLPROXY_SOCKS5_HOSTNAME. Alternatively, you can also use CURLPROXY_SOCKS4A, but SOCKS5 is much preferred. Either of these proxy types informs cURL to perform both its DNS lookups and its actual data transfer via the proxy. This is required to successfully resolve any .onion domain.

There are also two additional errors in the code in the original question that have yet to be corrected by previous commenters. These are:

  • Missing semicolon at end of line 1.
  • The proxy address value is set to an HTTP URL, but its type is SOCKS; these are incompatible. For SOCKS proxies, the value must be an IP or domain name and port number combination without a scheme/protocol/prefix.

Here is the correct code in full, with comments to indicate the changes.

<?php
$url = 'http://jhiwjjlqpyawmpjx.onion/'; // Note the addition of a semicolon.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_PROXY, "127.0.0.1:9050"); // Note the address here is just `IP:port`, not an HTTP URL.
curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5_HOSTNAME); // Note use of `CURLPROXY_SOCKS5_HOSTNAME`.
$output = curl_exec($ch);
$curl_error = curl_error($ch);
curl_close($ch);

print_r($output);
print_r($curl_error);

You can also omit setting CURLOPT_PROXYTYPE entirely by changing the CURLOPT_PROXY value to include the socks5h:// prefix:

// Note no trailing slash, as this is a SOCKS address, not an HTTP URL.
curl_setopt(CURLOPT_PROXY, 'socks5h://127.0.0.1:9050');

Ways to save enums in database

If saving enums as strings in the database, you can create utility methods to (de)serialize any enum:

   public static String getSerializedForm(Enum<?> enumVal) {
        String name = enumVal.name();
        // possibly quote value?
        return name;
    }

    public static <E extends Enum<E>> E deserialize(Class<E> enumType, String dbVal) {
        // possibly handle unknown values, below throws IllegalArgEx
        return Enum.valueOf(enumType, dbVal.trim());
    }

    // Sample use:
    String dbVal = getSerializedForm(Suit.SPADE);
    // save dbVal to db in larger insert/update ...
    Suit suit = deserialize(Suit.class, dbVal);

Angular js init ng-model from default values

If you can't rework your app to do what @blesh suggests (pull JSON data down with $http or $resource and populate $scope), you can use ng-init instead:

<input name="card[description]" ng-model="card.description" ng-init="card.description='Visa-4242'">

See also AngularJS - Value attribute on an input text box is ignored when there is a ng-model used?

Difference between chr(13) and chr(10)

Chr(10) is the Line Feed character and Chr(13) is the Carriage Return character.

You probably won't notice a difference if you use only one or the other, but you might find yourself in a situation where the output doesn't show properly with only one or the other. So it's safer to include both.


Historically, Line Feed would move down a line but not return to column 1:

This  
    is  
        a  
            test.

Similarly Carriage Return would return to column 1 but not move down a line:

This  
is  
a  
test.

Paste this into a text editor and then choose to "show all characters", and you'll see both characters present at the end of each line. Better safe than sorry.

Angular-cli from css to scss

For Angular 6 check the Official documentation

Note: For @angular/cli versions older than 6.0.0-beta.6 use ng set in place of ng config.

For existing projects

In an existing angular-cli project that was set up with the default css styles you will need to do a few things:

  1. Change the default style extension to scss

Manually change in .angular-cli.json (Angular 5.x and older) or angular.json (Angular 6+) or run:

ng config defaults.styleExt=scss

if you get an error: Value cannot be found. use the command:

ng config schematics.@schematics/angular:component.styleext scss

(*source: Angular CLI SASS options)

  1. Rename your existing .css files to .scss (i.e. styles.css and app/app.component.css)

  2. Point the CLI to find styles.scss

Manually change the file extensions in apps[0].styles in angular.json

  1. Point the components to find your new style files

Change the styleUrls in your components to match your new file names

For future projects

As @Serginho mentioned you can set the style extension when running the ng new command

ng new your-project-name --style=scss

If you want to set the default for all projects you create in the future run the following command:

ng config --global defaults.styleExt=scss

How to convert / cast long to String?

String strLong = Long.toString(longNumber);

Simple and works fine :-)

Java associative-array

You can accomplish this via Maps. Something like

Map<String, String>[] arr = new HashMap<String, String>[2]();
arr[0].put("name", "demo");

But as you start using Java I am sure you will find that if you create a class/model that represents your data will be your best options. I would do

class Person{
String name;
String fname;
}
List<Person> people = new ArrayList<Person>();
Person p = new Person();
p.name = "demo";
p.fname = "fdemo";
people.add(p);

'System.OutOfMemoryException' was thrown when there is still plenty of memory free

As you probably figured out, the issue is that you are trying to allocate one large contiguous block of memory, which does not work due to memory fragmentation. If I needed to do what you are doing I would do the following:

int sizeA = 10000,
    sizeB = 10000;
double sizeInMegabytes = (sizeA * sizeB * 8.0) / 1024.0 / 1024.0; //762 mb
double[][] randomNumbers = new double[sizeA][];
for (int i = 0; i < randomNumbers.Length; i++)
{
    randomNumbers[i] = new double[sizeB];
}

Then, to get a particular index you would use randomNumbers[i / sizeB][i % sizeB].

Another option if you always access the values in order might be to use the overloaded constructor to specify the seed. This way you would get a semi random number (like the DateTime.Now.Ticks) store it in a variable, then when ever you start going through the list you would create a new Random instance using the original seed:

private static int randSeed = (int)DateTime.Now.Ticks;  //Must stay the same unless you want to get different random numbers.
private static Random GetNewRandomIterator()
{
    return new Random(randSeed);
}

It is important to note that while the blog linked in Fredrik Mörk's answer indicates that the issue is usually due to a lack of address space it does not list a number of other issues, like the 2GB CLR object size limitation (mentioned in a comment from ShuggyCoUk on the same blog), glosses over memory fragmentation, and fails to mention the impact of page file size (and how it can be addressed with the use of the CreateFileMapping function).

The 2GB limitation means that randomNumbers must be less than 2GB. Since arrays are classes and have some overhead them selves this means an array of double will need to be smaller then 2^31. I am not sure how much smaller then 2^31 the Length would have to be, but Overhead of a .NET array? indicates 12 - 16 bytes.

Memory fragmentation is very similar to HDD fragmentation. You might have 2GB of address space, but as you create and destroy objects there will be gaps between the values. If these gaps are too small for your large object, and additional space can not be requested, then you will get the System.OutOfMemoryException. For example, if you create 2 million, 1024 byte objects, then you are using 1.9GB. If you delete every object where the address is not a multiple of 3 then you will be using .6GB of memory, but it will be spread out across the address space with 2024 byte open blocks in between. If you need to create an object which was .2GB you would not be able to do it because there is not a block large enough to fit it in and additional space cannot be obtained (assuming a 32 bit environment). Possible solutions to this issue are things like using smaller objects, reducing the amount of data you store in memory, or using a memory management algorithm to limit/prevent memory fragmentation. It should be noted that unless you are developing a large program which uses a large amount of memory this will not be an issue. Also, this issue can arise on 64 bit systems as windows is limited mostly by the page file size and the amount of RAM on the system.

Since most programs request working memory from the OS and do not request a file mapping, they will be limited by the system's RAM and page file size. As noted in the comment by Néstor Sánchez (Néstor Sánchez) on the blog, with managed code like C# you are stuck to the RAM/page file limitation and the address space of the operating system.


That was way longer then expected. Hopefully it helps someone. I posted it because I ran into the System.OutOfMemoryException running a x64 program on a system with 24GB of RAM even though my array was only holding 2GB of stuff.

Hide html horizontal but not vertical scrollbar

selector{
 overflow-y: scroll;
 overflow-x: hidden;
}

Working example with snippet and jsfiddle link https://jsfiddle.net/sx8u82xp/3/

enter image description here

_x000D_
_x000D_
.container{_x000D_
  height:100vh;_x000D_
  overflow-y:scroll;_x000D_
  overflow-x: hidden;_x000D_
  background:yellow;_x000D_
}
_x000D_
<div class="container">_x000D_
_x000D_
<p>_x000D_
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
_x000D_
Why do we use it?_x000D_
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like)._x000D_
</p>_x000D_
_x000D_
<p>_x000D_
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
_x000D_
Why do we use it?_x000D_
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like)._x000D_
</p>_x000D_
_x000D_
<p>_x000D_
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
_x000D_
Why do we use it?_x000D_
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like)._x000D_
</p>_x000D_
_x000D_
<p>_x000D_
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
_x000D_
Why do we use it?_x000D_
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like)._x000D_
</p>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

SVN repository backup strategies

svnbackup over at Google Code, a .NET console application.

Nginx serves .php files as downloads, instead of executing them

For me it helped to add ?$query_string at the end of /index.php, like below:

location / {
        try_files $uri $uri/ /index.php?$query_string;
}

Python concatenate text files

If you have a lot of files in the directory then glob2 might be a better option to generate a list of filenames rather than writing them by hand.

import glob2

filenames = glob2.glob('*.txt')  # list of all .txt files in the directory

with open('outfile.txt', 'w') as f:
    for file in filenames:
        with open(file) as infile:
            f.write(infile.read()+'\n')

Parsing JSON using Json.net

Edit: Thanks Marc, read up on the struct vs class issue and you're right, thank you!

I tend to use the following method for doing what you describe, using a static method of JSon.Net:

MyObject deserializedObject = JsonConvert.DeserializeObject<MyObject>(json);

Link: Serializing and Deserializing JSON with Json.NET

For the Objects list, may I suggest using generic lists out made out of your own small class containing attributes and position class. You can use the Point struct in System.Drawing (System.Drawing.Point or System.Drawing.PointF for floating point numbers) for you X and Y.

After object creation it's much easier to get the data you're after vs. the text parsing you're otherwise looking at.

How can I sort generic list DESC and ASC?

With Linq

var ascendingOrder = li.OrderBy(i => i);
var descendingOrder = li.OrderByDescending(i => i);

Without Linq

li.Sort((a, b) => a.CompareTo(b)); // ascending sort
li.Sort((a, b) => b.CompareTo(a)); // descending sort

Note that without Linq, the list itself is being sorted. With Linq, you're getting an ordered enumerable of the list but the list itself hasn't changed. If you want to mutate the list, you would change the Linq methods to something like

li = li.OrderBy(i => i).ToList();

Change multiple files

u can make

'xxxx' text u search and will replace it with 'yyyy'

grep -Rn '**xxxx**' /path | awk -F: '{print $1}' | xargs sed -i 's/**xxxx**/**yyyy**/'

Getting Error "Form submission canceled because the form is not connected"

alternatively include event.preventDefault(); in your handleSubmit(event) {

see https://facebook.github.io/react/docs/forms.html

How to discard uncommitted changes in SourceTree?

On the unstaged file, click on the three dots on the right side. Once you click it, a popover menu will appear where you can then Discard file.

PostgreSQL JOIN data from 3 tables

Something like:

select t1.name, t2.image_id, t3.path
from table1 t1 inner join table2 t2 on t1.person_id = t2.person_id
inner join table3 t3 on t2.image_id=t3.image_id

Get characters after last / in url

You could explode based on "/", and return the last entry:

print end( explode( "/", "http://www.vimeo.com/1234567" ) );

That's based on blowing the string apart, something that isn't necessary if you know the pattern of the string itself will not soon be changing. You could, alternatively, use a regular expression to locate that value at the end of the string:

$url = "http://www.vimeo.com/1234567";

if ( preg_match( "/\d+$/", $url, $matches ) ) {
    print $matches[0];
}

LOAD DATA INFILE Error Code : 13

I know that this post is old, but this still comes up in search results. I couldn't find the solution to this problem online, so I ended up figuring it out myself. If you're using Ubuntu, then there is a program called "Apparmor" that is preventing MySQL from seeing the file. Here's what you need to do if you want MySQL to be able to read files from the "tmp" directory:

sudo vim /etc/apparmor.d/usr.sbin.mysqld

Once you are in the file, you're going to see a bunch of directories that MySQL can use. Add the line /tmp/** rwk to the file (I am not sure that it matters where, but here is a sample of where I put it):

  /etc/mysql/*.pem r,

  /etc/mysql/conf.d/ r,

  /etc/mysql/conf.d/* r,

  /etc/mysql/*.cnf r,

  /usr/lib/mysql/plugin/ r,

  /usr/lib/mysql/plugin/*.so* mr,

  /usr/sbin/mysqld mr,

  /usr/share/mysql/** r,

  /var/log/mysql.log rw,

  /var/log/mysql.err rw,

  /var/lib/mysql/ r,

  /var/lib/mysql/** rwk,


  /tmp/** rwk,


  /var/log/mysql/ r,

  /var/log/mysql/* rw,

  /var/run/mysqld/mysqld.pid w,

  /var/run/mysqld/mysqld.sock w,

  /run/mysqld/mysqld.pid w,

  /run/mysqld/mysqld.sock w,

Now all you need to do is reload Apparmor:

sudo /etc/init.d/apparmor reload

Note I used "vim", but substitute that with whatever your favorite text editor is that you know how to use.

Normalizing a list of numbers in Python

Use scikit-learn:

from sklearn.preprocessing import MinMaxScaler
data = np.array([1,2,3]).reshape(-1, 1)
scaler = MinMaxScaler()
scaler.fit(data)
print(scaler.transform(data))

How to check String in response body with mockMvc

One possible approach is to simply include gson dependency:

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
</dependency>

and parse the value to make your verifications:

@RunWith(SpringRunner.class)
@WebMvcTest(HelloController.class)
public class HelloControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private HelloService helloService;

    @Before
    public void before() {
        Mockito.when(helloService.message()).thenReturn("hello world!");
    }

    @Test
    public void testMessage() throws Exception {
        MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/"))
                .andExpect(status().isOk())
                .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON_VALUE))
                .andReturn();

        String responseBody = mvcResult.getResponse().getContentAsString();
        ResponseDto responseDto
                = new Gson().fromJson(responseBody, ResponseDto.class);
        Assertions.assertThat(responseDto.message).isEqualTo("hello world!");
    }
}

Disable click outside of angular material dialog area to close the dialog (With Angular Version 4.0+)

There are two ways to do it.

  1. In the method that opens the dialog, pass in the following configuration option disableClose as the second parameter in MatDialog#open() and set it to true:

    export class AppComponent {
      constructor(private dialog: MatDialog){}
      openDialog() {
        this.dialog.open(DialogComponent, { disableClose: true });
      }
    }
    
  2. Alternatively, do it in the dialog component itself.

    export class DialogComponent {
      constructor(private dialogRef: MatDialogRef<DialogComponent>){
        dialogRef.disableClose = true;
      }
    }
    

Here's what you're looking for:

<code>disableClose</code> property in material.angular.io

And here's a Stackblitz demo


Other use cases

Here's some other use cases and code snippets of how to implement them.

Allow esc to close the dialog but disallow clicking on the backdrop to close the dialog

As what @MarcBrazeau said in the comment below my answer, you can allow the esc key to close the modal but still disallow clicking outside the modal. Use this code on your dialog component:

import { Component, OnInit, HostListener } from '@angular/core';
import { MatDialogRef } from '@angular/material';
@Component({
  selector: 'app-third-dialog',
  templateUrl: './third-dialog.component.html'
})
export class ThirdDialogComponent {
  constructor(private dialogRef: MatDialogRef<ThirdDialogComponent>) {      
}
  @HostListener('window:keyup.esc') onKeyUp() {
    this.dialogRef.close();
  }

}

Prevent esc from closing the dialog but allow clicking on the backdrop to close

P.S. This is an answer which originated from this answer, where the demo was based on this answer.

To prevent the esc key from closing the dialog but allow clicking on the backdrop to close, I've adapted Marc's answer, as well as using MatDialogRef#backdropClick to listen for click events to the backdrop.

Initially, the dialog will have the configuration option disableClose set as true. This ensures that the esc keypress, as well as clicking on the backdrop will not cause the dialog to close.

Afterwards, subscribe to the MatDialogRef#backdropClick method (which emits when the backdrop gets clicked and returns as a MouseEvent).

Anyways, enough technical talk. Here's the code:

openDialog() {
  let dialogRef = this.dialog.open(DialogComponent, { disableClose: true });
  /*
     Subscribe to events emitted when the backdrop is clicked
     NOTE: Since we won't actually be using the `MouseEvent` event, we'll just use an underscore here
     See https://stackoverflow.com/a/41086381 for more info
  */
  dialogRef.backdropClick().subscribe(() => {
    // Close the dialog
    dialogRef.close();
  })

  // ...
}

Alternatively, this can be done in the dialog component:

export class DialogComponent {
  constructor(private dialogRef: MatDialogRef<DialogComponent>) {
    dialogRef.disableClose = true;
    /*
      Subscribe to events emitted when the backdrop is clicked
      NOTE: Since we won't actually be using the `MouseEvent` event, we'll just use an underscore here
      See https://stackoverflow.com/a/41086381 for more info
    */
    dialogRef.backdropClick().subscribe(() => {
      // Close the dialog
      dialogRef.close();
    })
  }
}

How can I pretty-print JSON using node.js?

I think this might be useful... I love example code :)

var fs = require('fs');

var myData = {
  name:'test',
  version:'1.0'
}

var outputFilename = '/tmp/my.json';

fs.writeFile(outputFilename, JSON.stringify(myData, null, 4), function(err) {
    if(err) {
      console.log(err);
    } else {
      console.log("JSON saved to " + outputFilename);
    }
}); 

Recursively counting files in a Linux directory

If you want to avoid error cases, don't allow wc -l to see files with newlines (which it will count as 2+ files)

e.g. Consider a case where we have a single file with a single EOL character in it

> mkdir emptydir && cd emptydir
> touch $'file with EOL(\n) character in it'
> find -type f
./file with EOL(?) character in it
> find -type f | wc -l
2

Since at least gnu wc does not appear to have an option to read/count a null terminated list (except from a file), the easiest solution would just be to not pass it filenames, but a static output each time a file is found, e.g. in the same directory as above

> find -type f -exec printf '\n' \; | wc -l
1

Or if your find supports it

> find -type f -printf '\n' | wc -l
1 

Convert decimal to hexadecimal in UNIX shell script

# number conversion.

while `test $ans='y'`
do
    echo "Menu"
    echo "1.Decimal to Hexadecimal"
    echo "2.Decimal to Octal"
    echo "3.Hexadecimal to Binary"
    echo "4.Octal to Binary"
    echo "5.Hexadecimal to  Octal"
    echo "6.Octal to Hexadecimal"
    echo "7.Exit"

    read choice
    case $choice in

        1) echo "Enter the decimal no."
           read n
           hex=`echo "ibase=10;obase=16;$n"|bc`
           echo "The hexadecimal no. is $hex"
           ;;

        2) echo "Enter the decimal no."
           read n
           oct=`echo "ibase=10;obase=8;$n"|bc`
           echo "The octal no. is $oct"
           ;;

        3) echo "Enter the hexadecimal no."
           read n
           binary=`echo "ibase=16;obase=2;$n"|bc`
           echo "The binary no. is $binary"
           ;;

        4) echo "Enter the octal no."
           read n
           binary=`echo "ibase=8;obase=2;$n"|bc`
           echo "The binary no. is $binary"
           ;;

        5) echo "Enter the hexadecimal no."
           read n
           oct=`echo "ibase=16;obase=8;$n"|bc`
           echo "The octal no. is $oct"
           ;;

        6) echo "Enter the octal no."
           read n
           hex=`echo "ibase=8;obase=16;$n"|bc`
           echo "The hexadecimal no. is $hex"
           ;;

        7) exit 
        ;;
        *) echo "invalid no." 
        ;;

    esac
done

Your content must have a ListView whose id attribute is 'android.R.id.list'

<ListView android:id="@id/android:list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:drawSelectorOnTop="false"
        android:scrollbars="vertical"/>

Does Python have a string 'contains' substring method?

If it's just a substring search you can use string.find("substring").

You do have to be a little careful with find, index, and in though, as they are substring searches. In other words, this:

s = "This be a string"
if s.find("is") == -1:
    print("No 'is' here!")
else:
    print("Found 'is' in the string.")

It would print Found 'is' in the string. Similarly, if "is" in s: would evaluate to True. This may or may not be what you want.

How do I properly set the Datetimeindex for a Pandas datetime object in a dataframe?

You are not creating datetime index properly,

format = '%Y-%m-%d %H:%M:%S'
df['Datetime'] = pd.to_datetime(df['date'] + ' ' + df['time'], format=format)
df = df.set_index(pd.DatetimeIndex(df['Datetime']))

Auto populate columns in one sheet from another sheet

If I understood you right you want to have sheet1!A1 in sheet2!A1, sheet1!A2 in sheet2!A2,...right?

It might not be the best way but you may type the following

=IF(sheet1!A1<>"",sheet1!A1,"")

and drag it down to the maximum number of rows you expect.

facebook Uncaught OAuthException: An active access token must be used to query information about the current user

So I had the same issue, but it was because I was saving the access token but not using it. It could be because I'm super sleepy because of due dates, or maybe I just didn't think about it! But in case anyone else is in the same situation:

When I log in the user I save the access token:

$facebook = new Facebook(array(
    'appId' => <insert the app id you get from facebook here>,
    'secret' => <insert the app secret you get from facebook here>
));

$accessToken = $facebook->getAccessToken();
//save the access token for later

Now when I make requests to facebook I just do something like this:

$facebook = new Facebook(array(
    'appId' => <insert the app id you get from facebook here>,
    'secret' => <insert the app secret you get from facebook here>
));

$facebook->setAccessToken($accessToken);
$facebook->api(... insert own code here ...)

Create local maven repository

Yes you can! For a simple repository that only publish/retrieve artifacts, you can use nginx.

  1. Make sure nginx has http dav module enabled, it should, but nonetheless verify it.

  2. Configure nginx http dav module:

    In Windows: d:\servers\nginx\nginx.conf

    location / {
        # maven repository
        dav_methods  PUT DELETE MKCOL COPY MOVE;
        create_full_put_path  on;
        dav_access  user:rw group:rw all:r;
    }
    

    In Linux (Ubuntu): /etc/nginx/sites-available/default

    location / {
            # First attempt to serve request as file, then
            # as directory, then fall back to displaying a 404.
            # try_files $uri $uri/ =404;  # IMPORTANT comment this
            dav_methods  PUT DELETE MKCOL COPY MOVE;
            create_full_put_path  on;
            dav_access  user:rw group:rw all:r;
    }
    

    Don't forget to give permissions to the directory where the repo will be located:

    sudo chmod +777 /var/www/html/repository

  3. In your project's pom.xml add the respective configuration:

    Retrieve artifacts:

    <repositories>
        <repository>
            <id>repository</id>
            <url>http://<your.ip.or.hostname>/repository</url>
        </repository>
    </repositories>
    

    Publish artifacts:

    <build>
        <extensions>
            <extension>
                <groupId>org.apache.maven.wagon</groupId>
                <artifactId>wagon-http</artifactId>
                <version>3.2.0</version>
            </extension>
        </extensions>
    </build>
    <distributionManagement>
        <repository>
            <id>repository</id>
            <url>http://<your.ip.or.hostname>/repository</url>
        </repository>
    </distributionManagement>
    
  4. To publish artifacts use mvn deploy. To retrieve artifacts, maven will do it automatically.

And there you have it a simple maven repo.

Conditionally formatting cells if their value equals any value of another column

All you need to do for that is a simple loop.
This doesn't handle testing for lower case, upper-case mismatch. If this isn't exactly what you are looking for, comment, and I can revise.

If you are planning to learn VBA. This is a great start.

TESTED:

Sub MatchAndColor()

Dim lastRow As Long
Dim sheetName As String

    sheetName = "Sheet1"            'Insert your sheet name here
    lastRow = Sheets(sheetName).Range("A" & Rows.Count).End(xlUp).Row

    For lRow = 2 To lastRow         'Loop through all rows

        If Sheets(sheetName).Cells(lRow, "A") = Sheets(sheetName).Cells(lRow, "B") Then
            Sheets(sheetName).Cells(lRow, "A").Interior.ColorIndex = 3  'Set Color to RED
        End If

    Next lRow

End Sub

EXAMPLE

How to use _CRT_SECURE_NO_WARNINGS

Add by

Configuration Properties>>C/C++>>Preporocessor>>Preprocessor Definitions>> _CRT_SECURE_NO_WARNINGS

screenshot of the relevant config interface

How to correctly set Http Request Header in Angular 2

You have a typo.

Change: headers.append('authentication', ${student.token});

To: headers.append('Authentication', student.token);

NOTE the Authentication is capitalized

Declaring & Setting Variables in a Select Statement

I have tried this and it worked:

define PROPp_START_DT = TO_DATE('01-SEP-1999')

select * from proposal where prop_start_dt = &PROPp_START_DT

 

How to find count of Null and Nan values for each column in a PySpark dataframe efficiently?

Here is my one liner. Here 'c' is the name of the column

df.select('c').withColumn('isNull_c',F.col('c').isNull()).where('isNull_c = True').count()

Uninstall / remove a Homebrew package including all its dependencies

Save the following script as brew-purge

#!/bin/bash
#:Usage: brew purge formula
#: 
#:Removes the package and all dependancies.
#: 
#: 
PKG="$1"
if [ -z "$PKG" ];then
   brew purge --help
   exit 1
fi
brew rm $PKG
[ $? -ne 0 ] && exit 1
while brew rm $(join <(brew leaves) <(brew deps $PKG)) 2>/dev/null
  do :
done
echo Package $PKG and its dependancies have been removed.
exit 0

Now install it with the following command

sudo install brew-purge /usr/local/bin

Now run it

brew purge package

Example using gpg

$ brew purge gpg
Uninstalling /usr/local/Cellar/gnupg/2.2.13... (134 files, 11.0MB)
Uninstalling /usr/local/Cellar/adns/1.5.1... (14 files, 597.5KB)
Uninstalling /usr/local/Cellar/gnutls/3.6.6... (1,200 files, 8.9MB)
Uninstalling /usr/local/Cellar/libgcrypt/1.8.4... (21 files, 2.6MB)
Uninstalling /usr/local/Cellar/libksba/1.3.5... (14 files, 344.2KB)
Uninstalling /usr/local/Cellar/libusb/1.0.22... (29 files, 508KB)
Uninstalling /usr/local/Cellar/npth/1.6... (11 files, 71.7KB)
Uninstalling /usr/local/Cellar/pinentry/1.1.0_1... (12 files, 263.9KB)
Uninstalling /usr/local/Cellar/libassuan/2.5.3... (16 files, 444.2KB)
Uninstalling /usr/local/Cellar/libtasn1/4.13... (59 files, 436KB)
Uninstalling /usr/local/Cellar/libunistring/0.9.10... (54 files, 4.4MB)
Uninstalling /usr/local/Cellar/nettle/3.4.1... (85 files, 2MB)
Uninstalling /usr/local/Cellar/p11-kit/0.23.15... (63 files, 2.9MB)
Uninstalling /usr/local/Cellar/gmp/6.1.2_2... (18 files, 3.1MB)
Uninstalling /usr/local/Cellar/libffi/3.2.1... (16 files, 296.8KB)
Uninstalling /usr/local/Cellar/libgpg-error/1.35... (27 files, 854.8KB)
Package gpg and its dependancies have been removed.
$ 

How to redirect the output of the time command to a file in Linux?

If you don't want to touch the original process' stdout and stderr, you can redirect stderr to file descriptor 3 and back:

$ { time { perl -le "print 'foo'; warn 'bar';" 2>&3; }; } 3>&2 2> time.out
foo
bar at -e line 1.
$ cat time.out

real    0m0.009s
user    0m0.004s
sys     0m0.000s

You could use that for a wrapper (e.g. for cronjobs) to monitor runtimes:

#!/bin/bash

echo "[$(date)]" "$@" >> /my/runtime.log

{ time { "$@" 2>&3; }; } 3>&2 2>> /my/runtime.log

What does the exclamation mark do before the function?

It returns whether the statement can evaluate to false. eg:

!false      // true
!true       // false
!isValid()  // is not valid

You can use it twice to coerce a value to boolean:

!!1    // true
!!0    // false

So, to more directly answer your question:

var myVar = !function(){ return false; }();  // myVar contains true

Edit: It has the side effect of changing the function declaration to a function expression. E.g. the following code is not valid because it is interpreted as a function declaration that is missing the required identifier (or function name):

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

How to access JSON Object name/value?

Here is a friendly piece of advice. Use something like Chrome Developer Tools or Firebug for Firefox to inspect your Ajax calls and results.

You may also want to invest some time in understanding a helper library like Underscore, which complements jQuery and gives you 60+ useful functions for manipulating data objects with JavaScript.

Python IndentationError: unexpected indent

Simply copy your script and put under """ your entire code """ ...

specify this line in a variable.. like,

a = """ your entire code """
print a.replace('    ','    ') # first 4 spaces tab second four space from space bar

print a.replace('here please press tab button it will insert some space"," here simply press space bar four times")
# here we replacing tab space by four char space as per pep 8 style guide..

now execute this code, in sublime using ctrl+b, now it will print indented code in console. that's it

What's onCreate(Bundle savedInstanceState)

onCreate(Bundle savedInstanceState) gets called and savedInstanceState will be non-null if your Activity and it was terminated in a scenario(visual view) described above. Your app can then grab (catch) the data from savedInstanceState and regenerate your Activity

Pandas: change data type of Series to String

Personally none of the above worked for me. What did:

new_str = [str(x) for x in old_obj][0]

Bootstrap - dropdown menu not working?

If I am getting you correctly, when you say that clicking does nothing, do you mean that it does not point to your URL?

In the anchor tag <a href>it looks like you did not pass your file path to the href attribute. So, replace the # with your actual path for the file that you want to link.

<li><a href="#">Action</a></li>
<li><a href="action link here">Another action</a></li>
<li><a href="something else link here">Something else here</a></li>
<li class="divider"></li>
<li><a href="seperated link here">Separated link</a></li>

I hope this helps with your issue.

How to query MongoDB with "like"?

db.customer.find({"customerid": {"$regex": "CU_00000*", "$options": "i"}}).pretty()

When we are searching for string patterns, always it is better to use the above pattern as when we are not sure about case. Hope that helps!!!

What is the 'pythonic' equivalent to the 'fold' function from functional programming?

You can reinvent the wheel as well:

def fold(f, l, a):
    """
    f: the function to apply
    l: the list to fold
    a: the accumulator, who is also the 'zero' on the first call
    """ 
    return a if(len(l) == 0) else fold(f, l[1:], f(a, l[0]))

print "Sum:", fold(lambda x, y : x+y, [1,2,3,4,5], 0)

print "Any:", fold(lambda x, y : x or y, [False, True, False], False)

print "All:", fold(lambda x, y : x and y, [False, True, False], True)

# Prove that result can be of a different type of the list's elements
print "Count(x==True):", 
print fold(lambda x, y : x+1 if(y) else x, [False, True, True], 0)

What is the best Java email address validation method?

This is the best method:

public static boolean isValidEmail(String enteredEmail){
        String EMAIL_REGIX = "^[\\\\w!#$%&’*+/=?`{|}~^-]+(?:\\\\.[\\\\w!#$%&’*+/=?`{|}~^-]+)*@(?:[a-zA-Z0-9-]+\\\\.)+[a-zA-Z]{2,6}$";
        Pattern pattern = Pattern.compile(EMAIL_REGIX);
        Matcher matcher = pattern.matcher(enteredEmail);
        return ((!enteredEmail.isEmpty()) && (enteredEmail!=null) && (matcher.matches()));
    }

Sources:- http://howtodoinjava.com/2014/11/11/java-regex-validate-email-address/

http://www.rfc-editor.org/rfc/rfc5322.txt

Validate phone number with JavaScript

This reg ex is suitable for international phone numbers and multiple formats of mobile cell numbers.

Here is the regular expression: /^(+{1}\d{2,3}\s?[(]{1}\d{1,3}[)]{1}\s?\d+|+\d{2,3}\s{1}\d+|\d+){1}[\s|-]?\d+([\s|-]?\d+){1,2}$/

Here is the JavaScript function

function isValidPhone(phoneNumber) {
    var found = phoneNumber.search(/^(\+{1}\d{2,3}\s?[(]{1}\d{1,3}[)]{1}\s?\d+|\+\d{2,3}\s{1}\d+|\d+){1}[\s|-]?\d+([\s|-]?\d+){1,2}$/);
    if(found > -1) {
        return true;
    }
    else {
        return false;
    }
}

This validates the following formats:

+44 07988-825 465 (with any combination of hyphens in place of space except that only a space must follow the +44)

+44 (0) 7988-825 465 (with any combination of hyphens in place of spaces except that no hyphen can exist directly before or after the (0) and the space before or after the (0) need not exist)

123 456-789 0123 (with any combination of hyphens in place of the spaces)

123-123 123 (with any combination of hyphens in place of the spaces)

123 123456 (Space can be replaced with a hyphen)

1234567890

No double spaces or double hyphens can exist for all formats.

How do I compare two variables containing strings in JavaScript?

I used below function to compare two strings and It is working good.

function CompareUserId (first, second)
{

   var regex = new RegExp('^' + first+ '$', 'i');
   if (regex.test(second)) 
   {
        return true;
   }
   else 
   {
        return false;
   }
   return false;
}

How to convert a huge list-of-vector to a matrix more efficiently?

You can also use,

output <- as.matrix(as.data.frame(z))

The memory usage is very similar to

output <- matrix(unlist(z), ncol = 10, byrow = TRUE)

Which can be verified, with mem_changed() from library(pryr).

How do I delete files programmatically on Android?

File file=new File(getFilePath(imageUri.getValue()));
boolean b= file.delete();

not working in my case. The issue has been resolved by using below code-

ContentResolver contentResolver = getContentResolver ();
contentResolver.delete (uriDelete,null ,null );

How to get the fragment instance from the FragmentActivity?

To get the fragment instance in a class that extends FragmentActivity:

MyclassFragment instanceFragment=
    (MyclassFragment)getSupportFragmentManager().findFragmentById(R.id.idFragment);

To get the fragment instance in a class that extends Fragment:

MyclassFragment instanceFragment =  
    (MyclassFragment)getFragmentManager().findFragmentById(R.id.idFragment);

passing form data to another HTML page

Use "Get" Method to send the value of a particular field through the browser:

<form action="display.html" method="GET">
    <input type="text" name="serialNumber" />
    <input type="submit" value="Submit" />
</form>

How to analyze disk usage of a Docker container

The volume part did not work anymore so if anyone is insterested I just change the above script a little bit:

for d in `docker ps | awk '{print $1}' | tail -n +2`; do
    d_name=`docker inspect -f {{.Name}} $d`
    echo "========================================================="
    echo "$d_name ($d) container size:"
    sudo du -d 2 -h /var/lib/docker/aufs | grep `docker inspect -f "{{.Id}}" $d`
    echo "$d_name ($d) volumes:"
    for mount in `docker inspect -f "{{range .Mounts}} {{.Source}}:{{.Destination}}                                                                                                                                                      
    {{end}}" $d`; do
        size=`echo $mount | cut -d':' -f1 | sudo xargs du -d 0 -h`
        mnt=`echo $mount | cut -d':' -f2`
        echo "$size mounted on $mnt"
    done
done

Integrating Dropzone.js into existing HTML form with other fields

You can modify the formData by catching the 'sending' event from your dropzone.

dropZone.on('sending', function(data, xhr, formData){
        formData.append('fieldname', 'value');
});

Dialog with transparent background in Android

Kotlin way to create dialog with transparent background:

 Dialog(activity!!, R.style.LoadingIndicatorDialogStyle)
            .apply {
                // requestWindowFeature(Window.FEATURE_NO_TITLE)
                setCancelable(true)
                setContentView(R.layout.define_your_custom_view_id_here)

                //access your custom view buttons/editText like below.z
                val createBt = findViewById<TextView>(R.id.clipboard_create_project)
                val cancelBt = findViewById<TextView>(R.id.clipboard_cancel_project)
                val clipboard_et = findViewById<TextView>(R.id.clipboard_et)
                val manualOption =
                    findViewById<TextView>(R.id.clipboard_manual_add_project_option)

                //if you want to perform any operation on the button do like this

                createBt.setOnClickListener {
                    //handle your button click here
                    val enteredData = clipboard_et.text.toString()
                    if (enteredData.isEmpty()) {
                        Utils.toast("Enter project details")
                    } else {
                        navigateToAddProject(enteredData, true)
                        dismiss()
                    }
                }

                cancelBt.setOnClickListener {
                    dismiss()
                }
                manualOption.setOnClickListener {
                    navigateToAddProject("", false)
                    dismiss()
                }
                show()
            }

Create LoadingIndicatorDialogStyle in style.xml like this:

<style name="LoadingIndicatorDialogStyle" parent="Theme.AppCompat.Light.Dialog.Alert">
    <item name="android:windowIsTranslucent">true</item>
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="android:windowNoTitle">true</item>
    <item name="android:statusBarColor">@color/black_transperant</item>
    <item name="android:layout_gravity">center</item>
    <item name="android:background">@android:color/transparent</item>
    <!--<item name="android:windowAnimationStyle">@style/MaterialDialogSheetAnimation</item>-->
</style>

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

SQL Server: How to set auto-increment on a table with rows in it:

This strategy physically copies the rows around twice which can take a much longer time if the table you are copying is very large.

You could save out your data, drop and rebuild the table with the auto-increment and primary key, then load the data back in.

I'll walk you through with an example:

Step 1, create table foobar (without primary key or auto-increment):

CREATE TABLE foobar(
    id int NOT NULL,
    name nchar(100) NOT NULL,
)

Step 2, insert some rows

insert into foobar values(1, 'one');
insert into foobar values(2, 'two');
insert into foobar values(3, 'three');

Step 3, copy out foobar data into a temp table:

select * into temp_foobar from foobar

Step 4, drop table foobar:

drop table foobar;

Step 5, recreate your table with the primary key and auto-increment properties:

CREATE TABLE foobar(
    id int primary key IDENTITY(1, 1) NOT NULL,
    name nchar(100) NOT NULL,
)

Step 6, insert your data from temp table back into foobar

SET IDENTITY_INSERT temp_foobar ON
INSERT into foobar (id, name) select id, name from temp_foobar;

Step 7, drop your temp table, and check to see if it worked:

drop table temp_foobar;
select * from foobar;

You should get this, and when you inspect the foobar table, the id column is auto-increment of 1 and id is a primary key:

1    one
2    two
3    three

Xcode 6 iPhone Simulator Application Support location

This location has, once again, changed, if using Swift, use this to find out where the folder is (this is copied from the AppDelegate.swift file that Apple creates for you so if it doesn't work on your machine, search in that file for the right syntax, this works on mine using Xcode 6.1 and iOS 8 simulator):

let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
println("Possible sqlite file: \(urls)")

How to make execution pause, sleep, wait for X seconds in R?

Sys.sleep() will not work if the CPU usage is very high; as in other critical high priority processes are running (in parallel).

This code worked for me. Here I am printing 1 to 1000 at a 2.5 second interval.

for (i in 1:1000)
{
  print(i)
  date_time<-Sys.time()
  while((as.numeric(Sys.time()) - as.numeric(date_time))<2.5){} #dummy while loop
}

How to select first child with jQuery?

$('div.alldivs :first-child');

Or you can just refer to the id directly:

$('#div1');

As suggested, you might be better of using the child selector:

$('div.alldivs > div:first-child')

If you dont have to use first-child, you could use :first as also suggested, or $('div.alldivs').children(0).

Objective-C: Extract filename from path string

If you're displaying a user-readable file name, you do not want to use lastPathComponent. Instead, pass the full path to NSFileManager's displayNameAtPath: method. This basically does does the same thing, only it correctly localizes the file name and removes the extension based on the user's preferences.

Array formula on Excel for Mac

CTRL+SHIFT+ENTER, ARRAY FORMULA EXCEL 2016 MAC. So I arrive late into the game, but maybe someone else will. This almost drove me nuts. No matter what I searched for in Google I came up empty. Whatever I tried, no solution seemed to be in sight. Switched to Excel 2016 quite some time ago and today I needed to do some array formulas. Also sitting on a MacBook Pro 15 Touch Bar 2016. Not that it really matters, but still, since the solution was published on Youtube in 2013. The reason why, for me anyway, nothing worked, is in the Mac OS, the control key by default, for me anyway, is set to manage Mission control, which, at least for me, disabled the control button in Excel. In order to enable the key to actually control functions in Excel, you need to go to System preferences > Mission Control, and disable shortcuts for Mission control. So, let's see how long this solution will last. Probably be back to square one after the coffee break. Have a good one!

How do you determine the size of a file in C?

Based on NilObject's code:

#include <sys/stat.h>
#include <sys/types.h>

off_t fsize(const char *filename) {
    struct stat st; 

    if (stat(filename, &st) == 0)
        return st.st_size;

    return -1; 
}

Changes:

  • Made the filename argument a const char.
  • Corrected the struct stat definition, which was missing the variable name.
  • Returns -1 on error instead of 0, which would be ambiguous for an empty file. off_t is a signed type so this is possible.

If you want fsize() to print a message on error, you can use this:

#include <sys/stat.h>
#include <sys/types.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>

off_t fsize(const char *filename) {
    struct stat st;

    if (stat(filename, &st) == 0)
        return st.st_size;

    fprintf(stderr, "Cannot determine size of %s: %s\n",
            filename, strerror(errno));

    return -1;
}

On 32-bit systems you should compile this with the option -D_FILE_OFFSET_BITS=64, otherwise off_t will only hold values up to 2 GB. See the "Using LFS" section of Large File Support in Linux for details.

How to increase Maximum Upload size in cPanel?

Since there is no php.ini file in your /public_html directory......create a new file as phpinfo.php in /public_html directory

-Type this code in phpinfo.php and save it:

<?php phpinfo(); ?>

-Then type yourdomain.com/phpinfo.php...you will see all the details of your configuration

-To edit that config, create another file as php.ini in /public_html directory and paste this code: memory_limit=512M
post_max_size=200M
upload_max_filesize=200M

-And then refresh yourdomain.com/phpinfo.php and see the changes,it will be done.

How to run function in AngularJS controller on document ready?

We can use the angular.element(document).ready() method to attach callbacks for when the document is ready. We can simply attach the callback in the controller like so:

angular.module('MyApp', [])

.controller('MyCtrl', [function() {
    angular.element(document).ready(function () {
        document.getElementById('msg').innerHTML = 'Hello';
    });
}]);

http://jsfiddle.net/jgentes/stwyvq38/1/

Multiple GitHub Accounts & SSH Config

Follow these steps to fix this it looks too long but trust me it won't take more than 5 minutes:

Step-1: Create two ssh key pairs:

ssh-keygen -t rsa -C "[email protected]"

Step-2: It will create two ssh keys here:

~/.ssh/id_rsa_account1
~/.ssh/id_rsa_account2

Step-3: Now we need to add these keys:

ssh-add ~/.ssh/id_rsa_account2
ssh-add ~/.ssh/id_rsa_account1
  • You can see the added keys list by using this command: ssh-add -l
  • You can remove old cached keys by this command: ssh-add -D

Step-4: Modify the ssh config

cd ~/.ssh/
touch config

subl -a config or code config or nano config

Step-5: Add this to config file:

#Github account1
Host github.com-account1
    HostName github.com
    User account1
    IdentityFile ~/.ssh/id_rsa_account1

#Github account2
Host github.com-account2
    HostName github.com
    User account2
    IdentityFile ~/.ssh/id_rsa_account2

Step-6: Update your .git/config file:

Step-6.1: Navigate to account1's project and update host:

[remote "origin"]
        url = [email protected]:account1/gfs.git

If you are invited by some other user in their git Repository. Then you need to update the host like this:

[remote "origin"]
            url = [email protected]:invitedByUserName/gfs.git

Step-6.2: Navigate to account2's project and update host:

[remote "origin"]
        url = [email protected]:account2/gfs.git

Step-7: Update user name and email for each repository separately if required this is not an amendatory step:

Navigate to account1 project and run these:

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

Navigate to account2 project and run these:

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

How to select and change value of table cell with jQuery?

$("td:contains('c')").html("new");

or, more precisely $("#table_headers td:contains('c')").html("new");

and maybe for reuse you could create a function to call

function ReplaceCellContent(find, replace)
{
    $("#table_headers td:contains('" + find + "')").html(replace);
}

C++ error: "Array must be initialized with a brace enclosed initializer"

You can't initialize arrays like this:

int cipher[Array_size][Array_size]=0;

The syntax for 2D arrays is:

int cipher[Array_size][Array_size]={{0}};

Note the curly braces on the right hand side of the initialization statement.

for 1D arrays:

int tomultiply[Array_size]={0};

Using SHA1 and RSA with java.security.Signature vs. MessageDigest and Cipher

Erm, after understanding your question: are you sure that the signature-method only creates a SHA1 and encrypts it? GPG et al offer to compress/clear sign the data. Maybe this java-signature-alg also creates a detachable/attachable signature.

How to get multiple selected values of select box in php?

You could do like this too. It worked out for me.

<form action="ResultsDulith.php" id="intermediate" name="inputMachine[]" multiple="multiple" method="post">
    <select id="selectDuration" name="selectDuration[]" multiple="multiple"> 
        <option value="1 WEEK" >Last 1 Week</option>
        <option value="2 WEEK" >Last 2 Week </option>
        <option value="3 WEEK" >Last 3 Week</option>
         <option value="4 WEEK" >Last 4 Week</option>
          <option value="5 WEEK" >Last 5 Week</option>
           <option value="6 WEEK" >Last 6 Week</option>
    </select>
     <input type="submit"/> 
</form>

Then take the multiple selection from following PHP code below. It print the selected multiple values accordingly.

$shift=$_POST['selectDuration'];

print_r($shift);

Drawing Isometric game worlds

Coobird's answer is the correct, complete one. However, I combined his hints with those from another site to create code that works in my app (iOS/Objective-C), which I wanted to share with anyone who comes here looking for such a thing. Please, if you like/up-vote this answer, do the same for the originals; all I did was "stand on the shoulders of giants."

As for sort-order, my technique is a modified painter's algorithm: each object has (a) an altitude of the base (I call "level") and (b) an X/Y for the "base" or "foot" of the image (examples: avatar's base is at his feet; tree's base is at it's roots; airplane's base is center-image, etc.) Then I just sort lowest to highest level, then lowest (highest on-screen) to highest base-Y, then lowest (left-most) to highest base-X. This renders the tiles the way one would expect.

Code to convert screen (point) to tile (cell) and back:

typedef struct ASIntCell {  // like CGPoint, but with int-s vice float-s
    int x;
    int y;
} ASIntCell;

// Cell-math helper here:
//      http://gamedevelopment.tutsplus.com/tutorials/creating-isometric-worlds-a-primer-for-game-developers--gamedev-6511
// Although we had to rotate the coordinates because...
// X increases NE (not SE)
// Y increases SE (not SW)
+ (ASIntCell) cellForPoint: (CGPoint) point
{
    const float halfHeight = rfcRowHeight / 2.;

    ASIntCell cell;
    cell.x = ((point.x / rfcColWidth) - ((point.y - halfHeight) / rfcRowHeight));
    cell.y = ((point.x / rfcColWidth) + ((point.y + halfHeight) / rfcRowHeight));

    return cell;
}


// Cell-math helper here:
//      http://stackoverflow.com/questions/892811/drawing-isometric-game-worlds/893063
// X increases NE,
// Y increases SE
+ (CGPoint) centerForCell: (ASIntCell) cell
{
    CGPoint result;

    result.x = (cell.x * rfcColWidth  / 2) + (cell.y * rfcColWidth  / 2);
    result.y = (cell.y * rfcRowHeight / 2) - (cell.x * rfcRowHeight / 2);

    return result;
}

ng-repeat :filter by single field

my way is this

subjcts is

[{"id":"1","title":"GFATM"},{"id":"2","title":"Court Case"},{"id":"3","title":"Renewal\/Validity"},{"id":"4","title":"Change of Details"},{"id":"5","title":"Student Query"},{"id":"6","title":"Complains"}]

sub is a Input field or whatever you like

Displaying like this

<div ng-if="x.id === sub" ng-repeat=" x in subjcts">{{x.title}}</div>

Printing out a number in assembly language?

Assuming you are writing a bootloader or other application that has access to the BIOS, here is a rough sketch of what you can do:

  • Isolate the first digit of the hex byte
  • If it is greater than 9 (i.e. 0x0A to 0x0F), subtract 10 from it (scaling it down to 0 to 5), and add 'A' (0x41).
  • If it is less than or equal to 9 (i.e. 0x00 to 0x09), add '0' to it.
  • Repeat this with the next hex digit.

Here is my implementation of this:

; Prints AL in hex.
printhexb:
    push ax
    shr al, 0x04
    call print_nibble
    pop ax
    and al, 0x0F
    call print_nibble
    ret
print_nibble:
    cmp al, 0x09
    jg .letter
    add al, 0x30
    mov ah, 0x0E
    int 0x10
    ret
.letter:
    add al, 0x37
    mov ah, 0x0E
    int 0x10
    ret   

How to create a GUID / UUID

Because i can, i thought i should share my solution, since it is a very fascinating problem and it has so many solutions.

It works for nodejs too, if you replace let buffer = new Uint8Array(); crypto.getRandomValues with let buffer = crypto.randomBytes(16)

I hope it helps somebody. It should beat most regex solutions in performance.

_x000D_
_x000D_
const hex = '0123456789ABCDEF'

let generateToken = function() {
    let buffer = new Uint8Array(16)
    
    crypto.getRandomValues(buffer)

    buffer[6] = 0x40 | (buffer[6] & 0xF)
    buffer[8] = 0x80 | (buffer[8] & 0xF)

    let segments = []

    for (let i = 0; i < 16; ++i) {
        segments.push(hex[(buffer[i] >> 4 & 0xF)])
        segments.push(hex[(buffer[i] >> 0 & 0xF)])

        if (i == 3 || i == 5 || i == 7 || i == 9) {
            segments.push('-')
        }
    }

    return segments.join('')
}

for (let i = 0; i < 100; ++i) {
  console.log(generateToken())
}
_x000D_
_x000D_
_x000D_

Performance charts, everybody loves them: jsbench

Have fun and thank you for all the other solutions, some served my quite long.

"Unable to locate tools.jar" when running ant

I was also having the same problem So I just removed the JDK path from the end and put it in start even before all System or Windows 32 paths.

Before it was like this:

C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\Microsoft SQL Server\100\Tools\Binn\;C:\Program Files\Microsoft SQL Server\100\DTS\Binn\;C:\Program Files\Microsoft SQL Server\100\Tools\Binn\VSShell\Common7\IDE\;C:\Users\Rajkaran\AppData\Local\Smartbar\Application\;C:\Users\Rajkaran\AppData\Local\Smartbar\Application\;C:\Program Files\doxygen\bin;%JAVA_HOME%\bin;%ANT_HOME%\bin

So I made it like this:

%JAVA_HOME%\bin;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\Microsoft SQL Server\100\Tools\Binn\;C:\Program Files\Microsoft SQL Server\100\DTS\Binn\;C:\Program Files\Microsoft SQL Server\100\Tools\Binn\VSShell\Common7\IDE\;C:\Users\Rajkaran\AppData\Local\Smartbar\Application\;C:\Users\Rajkaran\AppData\Local\Smartbar\Application\;C:\Program Files\doxygen\bin;%ANT_HOME%\bin

Table 'performance_schema.session_variables' doesn't exist

mysql -u app -p
mysql> set @@global.show_compatibility_56=ON;

as per http://bugs.mysql.com/bug.php?id=78159 worked for me.

CSS: Responsive way to center a fluid div (without px width) while limiting the maximum width?

From Chris Coyier's article on centering percentage width elements:

Instead of using negative margins, you use negative translate() transforms.

.center {
  position: absolute;
  left: 50%;
  top: 50%;

  /*
  Nope =(
  margin-left: -25%;
  margin-top: -25%;
  */

  /* 
  Yep!
  */
  transform: translate(-50%, -50%);

  /*
  Not even necessary really. 
  e.g. Height could be left out!
  */
  width: 40%;
  height: 50%;
}

Codepen

invalid multibyte char (US-ASCII) with Rails and Ruby 1.9

Just a note that as of Ruby 2.0 there is no need to add # encoding: utf-8. UTF-8 is automatically detected.

How do I test which class an object is in Objective-C?

If you want to check for a specific class then you can use

if([MyClass class] == [myClassObj class]) {
//your object is instance of MyClass
}

Apache POI error loading XSSFWorkbook class

Yeah, resolved the exception by adding commons-collections4-4.1 jar file to the CLASSPATH user varible of system. Downloaded from https://mvnrepository.com/artifact/org.apache.commons/commons-collections4/4.1

How do I force git to checkout the master branch and remove carriage returns after I've normalized files using the "text" attribute?

Ahah! Checkout the previous commit, then checkout the master.

git checkout HEAD^
git checkout -f master

Is it possible to return empty in react render function?

Returning falsy value in the render() function will render nothing. So you can just do

 render() {
    let finalClasses = "" + (this.state.classes || "");
    return !isTimeout && <div>{this.props.children}</div>;
  }

Class method differences in Python: bound, unbound and static

Methods in Python are a very, very simple thing once you understood the basics of the descriptor system. Imagine the following class:

class C(object):
    def foo(self):
        pass

Now let's have a look at that class in the shell:

>>> C.foo
<unbound method C.foo>
>>> C.__dict__['foo']
<function foo at 0x17d05b0>

As you can see if you access the foo attribute on the class you get back an unbound method, however inside the class storage (the dict) there is a function. Why's that? The reason for this is that the class of your class implements a __getattribute__ that resolves descriptors. Sounds complex, but is not. C.foo is roughly equivalent to this code in that special case:

>>> C.__dict__['foo'].__get__(None, C)
<unbound method C.foo>

That's because functions have a __get__ method which makes them descriptors. If you have an instance of a class it's nearly the same, just that None is the class instance:

>>> c = C()
>>> C.__dict__['foo'].__get__(c, C)
<bound method C.foo of <__main__.C object at 0x17bd4d0>>

Now why does Python do that? Because the method object binds the first parameter of a function to the instance of the class. That's where self comes from. Now sometimes you don't want your class to make a function a method, that's where staticmethod comes into play:

 class C(object):
  @staticmethod
  def foo():
   pass

The staticmethod decorator wraps your class and implements a dummy __get__ that returns the wrapped function as function and not as a method:

>>> C.__dict__['foo'].__get__(None, C)
<function foo at 0x17d0c30>

Hope that explains it.

A potentially dangerous Request.Form value was detected from the client

The answer to this question is simple:

var varname = Request.Unvalidated["parameter_name"];

This would disable validation for the particular request.

How does the @property decorator work in Python?

This following:

class C(object):
    def __init__(self):
        self._x = None

    @property
    def x(self):
        """I'm the 'x' property."""
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

    @x.deleter
    def x(self):
        del self._x

Is the same as:

class C(object):
    def __init__(self):
        self._x = None

    def _x_get(self):
        return self._x

    def _x_set(self, value):
        self._x = value

    def _x_del(self):
        del self._x

    x = property(_x_get, _x_set, _x_del, 
                    "I'm the 'x' property.")

Is the same as:

class C(object):
    def __init__(self):
        self._x = None

    def _x_get(self):
        return self._x

    def _x_set(self, value):
        self._x = value

    def _x_del(self):
        del self._x

    x = property(_x_get, doc="I'm the 'x' property.")
    x = x.setter(_x_set)
    x = x.deleter(_x_del)

Is the same as:

class C(object):
    def __init__(self):
        self._x = None

    def _x_get(self):
        return self._x
    x = property(_x_get, doc="I'm the 'x' property.")

    def _x_set(self, value):
        self._x = value
    x = x.setter(_x_set)

    def _x_del(self):
        del self._x
    x = x.deleter(_x_del)

Which is the same as :

class C(object):
    def __init__(self):
        self._x = None

    @property
    def x(self):
        """I'm the 'x' property."""
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

    @x.deleter
    def x(self):
        del self._x

Python initializing a list of lists

The problem is that they're all the same exact list in memory. When you use the [x]*n syntax, what you get is a list of n many x objects, but they're all references to the same object. They're not distinct instances, rather, just n references to the same instance.

To make a list of 3 different lists, do this:

x = [[] for i in range(3)]

This gives you 3 separate instances of [], which is what you want

[[]]*n is similar to

l = []
x = []
for i in range(n):
    x.append(l)

While [[] for i in range(3)] is similar to:

x = []
for i in range(n):
    x.append([])   # appending a new list!

In [20]: x = [[]] * 4

In [21]: [id(i) for i in x]
Out[21]: [164363948, 164363948, 164363948, 164363948] # same id()'s for each list,i.e same object


In [22]: x=[[] for i in range(4)]

In [23]: [id(i) for i in x]
Out[23]: [164382060, 164364140, 164363628, 164381292] #different id(), i.e unique objects this time

Access blocked by CORS policy: Response to preflight request doesn't pass access control check

You can just create the required CORS configuration as a bean. As per the code below this will allow all requests coming from any origin. This is good for development but insecure. Spring Docs

@Bean
WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurer() {
        @Override
        void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedOrigins("*")
        }
    }
}

Changing API level Android Studio

In build.gradle change minSdkVersion 13 to minSdkVersion 8 Thats all you need to do. I solved my problem by only doing this.

defaultConfig {
    applicationId "com.example.sabrim.sbrtest"
    minSdkVersion 8
    targetSdkVersion 20
    versionCode 1
    versionName "1.0"
}

Can I perform a DNS lookup (hostname to IP address) using client-side Javascript?

The hosted JSONP version works like a charm, but it seems it goes over its resources during night time most days (Eastern Time), so I had to create my own version.

This is how I accomplished it with PHP:

<?php
header('content-type: application/json; charset=utf-8');

$data = json_encode($_SERVER['REMOTE_ADDR']);
echo $_GET['callback'] . '(' . $data . ');';
?>

Then the Javascript is exactly the same as before, just not an array:

<script type="application/javascript">
function getip(ip){
    alert('IP Address: ' + ip);
}
</script>

<script type="application/javascript" src="http://www.anotherdomain.com/file.php?callback=getip"> </script>

Simple as that!

Side note: Be sure to clean your $_GET if you're using this in any public-facing environment!

What is the difference between logical data model and conceptual data model?

Conceptual Schema - covers entities and relationships. Should be created first. Contrary to some of the other answers; tables are not defined here. For example a 'many to many' table is not included in a conceptual data model but is defined as a 'many to many' relationship between entities.

Logical Schema - Covers tables, attributes, keys, mandatory role constraints, and referential integrity with no regards to the physical implementation. Things like indexes are not defined, attribute types should be kept logical, e.g. text instead of varchar2. Should be created based on the conceptual schema.

Pass a local file in to URL in Java

new URL("file:///your/file/here")

Optimal way to concatenate/aggregate strings

For those of us who found this and are not using Azure SQL Database:

STRING_AGG() in PostgreSQL, SQL Server 2017 and Azure SQL
https://www.postgresql.org/docs/current/static/functions-aggregate.html
https://docs.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql

GROUP_CONCAT() in MySQL
http://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html#function_group-concat

(Thanks to @Brianjorden and @milanio for Azure update)

Example Code:

select Id
, STRING_AGG(Name, ', ') Names 
from Demo
group by Id

SQL Fiddle: http://sqlfiddle.com/#!18/89251/1

How to convert DateTime to/from specific string format (both ways, e.g. given Format is "yyyyMMdd")?

You could use DateTime.TryParse() instead of DateTime.Parse().
With TryParse() you have a return value if it was successful and with Parse() you have to handle an exception

How to replace deprecated android.support.v4.app.ActionBarDrawerToggle

Adding only android-support-v7-appcompat.jar to library dependencies is not enough, you have also to import in your project the module that you can find in your SDK at the path \android-sdk\extras\android\support\v7\appcompatand after that add module dependencies configuring the project structure in this way

enter image description here

otherwise are included only the class files of support library and the app is not able to load the other resources causing the error.

In addition as reVerse suggested replace this

public CustomActionBarDrawerToggle(Activity mActivity,
                                           DrawerLayout mDrawerLayout) {
            super(mActivity, mDrawerLayout,new Toolbar(MyActivity.this) ,
                    R.string.ns_menu_open, R.string.ns_menu_close);
        }

with

public CustomActionBarDrawerToggle(Activity mActivity,
                                           DrawerLayout mDrawerLayout) {
            super(mActivity, mDrawerLayout, R.string.ns_menu_open, R.string.ns_menu_close);
        }

Interview Question: Merge two sorted singly linked lists without creating new nodes

Node mergeList(Node h1, Node h2) {
    if (h1 == null) return h2;
    if (h2 == null) return h1;
    Node head;
    if (h1.data < h2.data) {
        head = h1;
    } else {
        head = h2;
        h2 = h1;
        h1 = head;
    }

    while (h1.next != null && h2 != null) {
        if (h1.next.data < h2.data) {
            h1 = h1.next;
        } else {
            Node afterh2 = h2.next;
            Node afterh1 = h1.next;
            h1.next = h2;
            h2.next = afterh1;

            if (h2.next != null) {
                h2 = afterh2;
            }
        }
    }
    return head;
}

How can I show/hide a specific alert with twitter bootstrap?

JS

        function showAlert(){
         $('#alert').show();
         setTimeout(function() { 
             $('#alert').hide(); 
         }, 5000);
        }

HTML

<div class="alert alert-success" id="alert" role="alert" style="display:none;" >YOUR MESSAGE</div>

How to implement a property in an interface

Interfaces can not contain any implementation (including default values). You need to switch to abstract class.

"Could not get any response" response when using postman with subdomain

In my case, I forgot to set the value of the variable in the "CURRENT VALUE" field.

String Padding in C

The argument you passed "Hello" is on the constant data area. Unless you've allocated enough memory to char * string, it's overrunning to other variables.

char buffer[1024];
memset(buffer, 0, sizeof(buffer));
strncpy(buffer, "Hello", sizeof(buffer));
StringPadRight(buffer, 10, "0");

Edit: Corrected from stack to constant data area.

How to negate code in "if" statement block in JavaScript -JQuery like 'if not then..'

You can use the Logical NOT ! operator:

if (!$(this).parent().next().is('ul')){

Or equivalently (see comments below):

if (! ($(this).parent().next().is('ul'))){

For more information, see the Logical Operators section of the MDN docs.

AngularJS ng-if with multiple conditions

HTML code

<div ng-app>
<div ng-controller='ctrl'>
    <div ng-class='whatClassIsIt(call.state[0])'>{{call.state[0]}}</div>
    <div ng-class='whatClassIsIt(call.state[1])'>{{call.state[1]}}</div>
    <div ng-class='whatClassIsIt(call.state[2])'>{{call.state[2]}}</div>
    <div ng-class='whatClassIsIt(call.state[3])'>{{call.state[3]}}</div>
    <div ng-class='whatClassIsIt(call.state[4])'>{{call.state[4]}}</div>
    <div ng-class='whatClassIsIt(call.state[5])'>{{call.state[5]}}</div>
    <div ng-class='whatClassIsIt(call.state[6])'>{{call.state[6]}}</div>
    <div ng-class='whatClassIsIt(call.state[7])'>{{call.state[7]}}</div>
</div>

JavaScript Code

function ctrl($scope){
$scope.call={state:['second','first','nothing','Never', 'Gonna', 'Give', 'You', 'Up']}


$scope.whatClassIsIt= function(someValue){
     if(someValue=="first")
            return "ClassA"
     else if(someValue=="second")
         return "ClassB";
    else
         return "ClassC";
}
}

How to randomly select an item from a list?

How to randomly select an item from a list?

Assume I have the following list:

foo = ['a', 'b', 'c', 'd', 'e']  

What is the simplest way to retrieve an item at random from this list?

If you want close to truly random, then I suggest secrets.choice from the standard library (New in Python 3.6.):

>>> from secrets import choice         # Python 3 only
>>> choice(list('abcde'))
'c'

The above is equivalent to my former recommendation, using a SystemRandom object from the random module with the choice method - available earlier in Python 2:

>>> import random                      # Python 2 compatible
>>> sr = random.SystemRandom()
>>> foo = list('abcde')
>>> foo
['a', 'b', 'c', 'd', 'e']

And now:

>>> sr.choice(foo)
'd'
>>> sr.choice(foo)
'e'
>>> sr.choice(foo)
'a'
>>> sr.choice(foo)
'b'
>>> sr.choice(foo)
'a'
>>> sr.choice(foo)
'c'
>>> sr.choice(foo)
'c'

If you want a deterministic pseudorandom selection, use the choice function (which is actually a bound method on a Random object):

>>> random.choice
<bound method Random.choice of <random.Random object at 0x800c1034>>

It seems random, but it's actually not, which we can see if we reseed it repeatedly:

>>> random.seed(42); random.choice(foo), random.choice(foo), random.choice(foo)
('d', 'a', 'b')
>>> random.seed(42); random.choice(foo), random.choice(foo), random.choice(foo)
('d', 'a', 'b')
>>> random.seed(42); random.choice(foo), random.choice(foo), random.choice(foo)
('d', 'a', 'b')
>>> random.seed(42); random.choice(foo), random.choice(foo), random.choice(foo)
('d', 'a', 'b')
>>> random.seed(42); random.choice(foo), random.choice(foo), random.choice(foo)
('d', 'a', 'b')

A comment:

This is not about whether random.choice is truly random or not. If you fix the seed, you will get the reproducible results -- and that's what seed is designed for. You can pass a seed to SystemRandom, too. sr = random.SystemRandom(42)

Well, yes you can pass it a "seed" argument, but you'll see that the SystemRandom object simply ignores it:

def seed(self, *args, **kwds):
    "Stub method.  Not used for a system random number generator."
    return None

How can I view array structure in JavaScript with alert()?

I'd recommend using toString().

Ex. alert(array.toString()), or console.log(array.toString())

How to validate a form with multiple checkboxes to have atleast one checked

I checked all answers and even in other similar questions, I tried to find optimal way with help of html class and custom rule.

my html structure for multiple checkboxes are like this

_x000D_
_x000D_
$.validator.addMethod('multicheckbox_rule', function (value, element) {_x000D_
   var $parent = $(element).closest('.checkbox_wrapper');_x000D_
   if($parent.find('.checkbox_item').is(':checked')) return true;_x000D_
            return false;_x000D_
}, 'Please at least select one');
_x000D_
<div class="checkbox_wrapper">_x000D_
<label for="checkbox-1"><input class="checkbox_item" id="checkbox-1"  name="checkbox_item[1]" type="checkbox" value="1" data-rule-multicheckbox_rule="1" /> Checkbox_item 1</label>_x000D_
<label for="checkbox-2"><input class="checkbox_item" id="checkbox-2" name="checkbox_item[2]" type="checkbox" value="1" data-rule-multicheckbox_rule="1" /> Checkbox_item 1</label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to make graphics with transparent background in R using ggplot2?

There is also a plot.background option in addition to panel.background:

df <- data.frame(y=d,x=1)
p <- ggplot(df) + stat_boxplot(aes(x = x,y=y)) 
p <- p + opts(
    panel.background = theme_rect(fill = "transparent",colour = NA), # or theme_blank()
    panel.grid.minor = theme_blank(), 
    panel.grid.major = theme_blank(),
    plot.background = theme_rect(fill = "transparent",colour = NA)
)
#returns white background
png('tr_tst2.png',width=300,height=300,units="px",bg = "transparent")
print(p)
dev.off()

For some reason, the uploaded image is displaying differently than on my computer, so I've omitted it. But for me, I get a plot with an entirely gray background except for the box part of the boxplot which is still white. That can be changed using the fill aesthetic in the boxplot geom as well, I believe.

Edit

ggplot2 has since been updated and the opts() function has been deprecated. Currently, you would use theme() instead of opts() and element_rect() instead of theme_rect(), etc.

How to download file from database/folder using php

butangDonload.php

$file = "Bang.png"; //Let say If I put the file name Bang.png
$_SESSION['name']=$file;    

Try this,

<?php

$name=$_SESSION['name'];
download($name);

function download($name){
$file = $nama_fail;
?>

Close Current Tab

Try this:

<script>
    var myWindow = window.open("ANYURL", "MyWindowName", "width=700,height=700");
    this.window.close();
</script>

This worked for me in some cases in Google Chrome 50. It does not seem to work when put inside a javascript function, though.

How do I delete NuGet packages that are not referenced by any project in my solution?

You can use Package Manager Console with command: Uninstall-Package PackageId to remove it, or just delete package folder from 'packages' folder under solution folder. More information about Package Manager Console you can find here: http://docs.nuget.org/docs/reference/package-manager-console-powershell-reference

How do I format a date in Jinja2?

Here's the filter that I ended up using for strftime in Jinja2 and Flask

@app.template_filter('strftime')
def _jinja2_filter_datetime(date, fmt=None):
    date = dateutil.parser.parse(date)
    native = date.replace(tzinfo=None)
    format='%b %d, %Y'
    return native.strftime(format) 

And then you use the filter like so:

{{car.date_of_manufacture|strftime}}

R dplyr: Drop multiple columns

We can try

iris %>% 
      select_(.dots= setdiff(names(.),drop.cols))

Does a `+` in a URL scheme/host/path represent a space?

Space characters may only be encoded as "+" in one context: application/x-www-form-urlencoded key-value pairs.

The RFC-1866 (HTML 2.0 specification), paragraph 8.2.1. subparagraph 1. says: "The form field names and values are escaped: space characters are replaced by `+', and then reserved characters are escaped").

Here is an example of such a string in URL where RFC-1866 allows encoding spaces as pluses: "http://example.com/over/there?name=foo+bar". So, only after "?", spaces can be replaced by pluses (in other cases, spaces should be encoded to %20). This way of encoding form data is also given in later HTML specifications, for example, look for relevant paragraphs about application/x-www-form-urlencoded in HTML 4.01 Specification, and so on.

But, because it's hard to always correctly determine the context, it's the best practice to never encode spaces as "+". It's better to percent-encode all character except "unreserved" defined in RFC-3986, p.2.3. Here is a code example that illustrates what should be encoded. It is given in Delphi (pascal) programming language, but it is very easy to understand how it works for any programmer regardless of the language possessed:

(* percent-encode all unreserved characters as defined in RFC-3986, p.2.3 *)
function UrlEncodeRfcA(const S: AnsiString): AnsiString;
const    
  HexCharArrA: array [0..15] of AnsiChar = '0123456789ABCDEF';
var
  I: Integer;
  c: AnsiChar;
begin
 // percent-encoding, see RFC-3986, p. 2.1
  Result := S;
  for I := Length(S) downto 1 do
  begin
    c := S[I];
    case c of
      'A' .. 'Z', 'a' .. 'z', // alpha
      '0' .. '9',             // digit
      '-', '.', '_', '~':;    // rest of unreserved characters as defined in the RFC-3986, p.2.3
      else
        begin
          Result[I] := '%';
          Insert('00', Result, I + 1);
          Result[I + 1] := HexCharArrA[(Byte(C) shr 4) and $F)];
          Result[I + 2] := HexCharArrA[Byte(C) and $F];
        end;
    end;
  end;
end;

function UrlEncodeRfcW(const S: UnicodeString): AnsiString;
begin
  Result := UrlEncodeRfcA(Utf8Encode(S));
end;

How to show one layout on top of the other programmatically in my case?

The answer, given by Alexandru is working quite nice. As he said, it is important that this "accessor"-view is added as the last element. Here is some code which did the trick for me:

        ...

        ...

            </LinearLayout>

        </LinearLayout>

    </FrameLayout>

</LinearLayout>

<!-- place a FrameLayout (match_parent) as the last child -->
<FrameLayout
    android:id="@+id/icon_frame_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</FrameLayout>

</TabHost>

in Java:

final MaterialDialog materialDialog = (MaterialDialog) dialogInterface;

FrameLayout frameLayout = (FrameLayout) materialDialog
        .findViewById(R.id.icon_frame_container);

frameLayout.setOnTouchListener(
        new OnSwipeTouchListener(ShowCardActivity.this) {

How to get class object's name as a string in Javascript?

If you don't want to use a function constructor like in Brian's answer you can use Object.create() instead:-

var myVar = {
count: 0
}

myVar.init = function(n) {
    this.count = n
    this.newDiv()
}

myVar.newDiv = function() {
    var newDiv = document.createElement("div")
    var contents = document.createTextNode("Click me!")
    var func = myVar.func(this)
    newDiv.addEventListener ? 
        newDiv.addEventListener('click', func, false) : 
        newDiv.attachEvent('onclick', func)
    newDiv.appendChild(contents)
    document.getElementsByTagName("body")[0].appendChild(newDiv)
}

myVar.func = function (thys) {
   return function() {
      thys.clickme()
   }
} 

myVar.clickme = function () {
   this.count += 1
   alert(this.count)
}

myVar.init(2)

var myVar1 = Object.create(myVar)
myVar1.init(55) 

var myVar2 = Object.create(myVar)
myVar2.init(150) 

// etc

Strangely, I couldn't get the above to work using newDiv.onClick, but it works with newDiv.addEventListener / newDiv.attachEvent.

Since Object.create is newish, include the following code from Douglas Crockford for older browsers, including IE8.

if (typeof Object.create !== 'function') {
    Object.create = function (o) {
        function F() {}
        F.prototype = o
        return new F()
    }
}

Check if a number is a perfect square

import math

def is_square(n):
    sqrt = math.sqrt(n)
    return sqrt == int(sqrt)

It fails for a large non-square such as 152415789666209426002111556165263283035677490.

How to: "Separate table rows with a line"

There are several ways to do that. Using HTML alone, you can write

<table border=1 frame=void rules=rows>

or, if you want a border above the first row and below the last row too,

<table border=1 frame=hsides rules=rows>

This is rather inflexible, though; you cannot e.g. make the lines dotted this way, or thicker than one pixel. This is why in the past people used special separator rows, consisting of nothing but some content intended to produce a line (it gets somewhat dirty, especially when you need to make rows e.g. just a few pixels high, but it’s possible).

For the most of it, people nowadays use CSS border properties for the purpose. It’s fairly simple and cross-browser. But note that to make the lines continuous, you need to prevent spacing between cells, using either the cellspacing=0 attribute in the table tag or the CSS rule table { border-collapse: collapse; }. Removing such spacing may necessitate adding some padding (with CSS, preferably) inside the cells.

At the simplest, you could use

<style>
table {
  border-collapse: collapse;
}
tr { 
  border: solid;
  border-width: 1px 0;
}
</style>

This puts a border above the first row and below the last row too. To prevent that, add e.g. the following into the style sheet:

tr:first-child {
  border-top: none;
}
tr:last-child {
  border-bottom: none;
}

How do I remove the top margin in a web page?

I had this exact same problem. For me, this was the only thing that worked:

div.mainContainer { padding-top: 1px; }

It actually works with any number that's not zero. I really have no idea why this took care of it. I'm not that knowledgeable about CSS and HTML and it seems counterintuitive. Setting the body, html, h1 margins and paddings to 0 had no effect for me. I also had an h1 at the top of my page

Java 8 optional: ifPresent return object orElseThrow exception

Use the map-function instead. It transforms the value inside the optional.

Like this:

private String getStringIfObjectIsPresent(Optional<Object> object) {
    return object.map(() -> {
        String result = "result";
        //some logic with result and return it
        return result;
    }).orElseThrow(MyCustomException::new);
}

What exactly does an #if 0 ..... #endif block do?

Lines beginning with a # are preprocessor directives. #if 0 [...] #endif blocks do not make it to the compiler and will generate no machine code.

You can demonstrate what happens with the preprocessor with a source file ifdef.cxx:

#if 0
This code will not be compiled
#else
int i = 0;
#endif

Running gcc -E ifdef.cxx will show you what gets compiled.

You may choose to use this mechanism to prevent a block of code being compiled during the development cycle, but you would probably not want to check it in to your source control as it just adds cruft to your code and reduces readability. If it's a historical piece of code that has been commented out, then it should be removed: source control contains the history, right?

Also, the answer may be the same for both C and C++ but there is no language called C/C++ and it's not a good habit to refer to such a language.

Manually adding a Userscript to Google Chrome

The best thing to do is to install the Tampermonkey extension.

This will allow you to easily install Greasemonkey scripts, and to easily manage them. Also it makes it easier to install userscripts directly from sites like OpenUserJS, MonkeyGuts, etc.

Finally, it unlocks most all of the GM functionality that you don't get by installing a GM script directly with Chrome. That is, more of what GM on Firefox can do, is available with Tampermonkey.


But, if you really want to install a GM script directly, it's easy a right pain on Chrome these days...

Chrome After about August, 2014:

You can still drag a file to the extensions page and it will work... Until you restart Chrome. Then it will be permanently disabled. See Continuing to "protect" Chrome users from malicious extensions for more information. Again, Tampermonkey is the smart way to go. (Or switch browsers altogether to Opera or Firefox.)

Chrome 21+ :

Chrome is changing the way extensions are installed. Userscripts are pared-down extensions on Chrome but. Starting in Chrome 21, link-click behavior is disabled for userscripts. To install a user script, drag the **.user.js* file into the Extensions page (chrome://extensions in the address input).

Older Chrome versions:

Merely drag your **.user.js* files into any Chrome window. Or click on any Greasemonkey script-link.

You'll get an installation warning:
Initial warning

Click Continue.


You'll get a confirmation dialog:
confirmation dialog

Click Add.


Notes:

  1. Scripts installed this way have limitations compared to a Greasemonkey (Firefox) script or a Tampermonkey script. See Cross-browser user-scripting, Chrome section.

Controlling the Script and name:

By default, Chrome installs scripts in the Extensions folder1, full of cryptic names and version numbers. And, if you try to manually add a script under this folder tree, it will be wiped the next time Chrome restarts.

To control the directories and filenames to something more meaningful, you can:

  1. Create a directory that's convenient to you, and not where Chrome normally looks for extensions. For example, Create: C:\MyChromeScripts\.

  2. For each script create its own subdirectory. For example, HelloWorld.

  3. In that subdirectory, create or copy the script file. For example, Save this question's code as: HelloWorld.user.js.

  4. You must also create a manifest file in that subdirectory, it must be named: manifest.json.

    For our example, it should contain:

    {
        "manifest_version": 2,
        "content_scripts": [ {
            "exclude_globs":    [  ],
            "include_globs":    [ "*" ],
            "js":               [ "HelloWorld.user.js" ],
            "matches":          [   "https://stackoverflow.com/*",
                                    "https://stackoverflow.com/*"
                                ],
            "run_at": "document_end"
        } ],
        "converted_from_user_script": true,
        "description":  "My first sensibly named script!",
        "name":         "Hello World",
        "version":      "1"
    }
    

    The manifest.json file is automatically generated from the meta-block by Chrome, when an user script is installed. The values of @include and @exclude meta-rules are stored in include_globs and exclude_globs, @match (recommended) is stored in the matches list. "converted_from_user_script": true is required if you want to use any of the supported GM_* methods.

  5. Now, in Chrome's Extension manager (URL = chrome://extensions/), Expand "Developer mode".

  6. Click the Load unpacked extension... button.

  7. For the folder, paste in the folder for your script, In this example it is: C:\MyChromeScripts\HelloWorld.

  8. Your script is now installed, and operational!

  9. If you make any changes to the script source, hit the Reload link for them to take effect:

    Reload link




1 The folder defaults to:

Windows XP:
  Chrome  : %AppData%\..\Local Settings\Application Data\Google\Chrome\User Data\Default\Extensions\
  Chromium: %AppData%\..\Local Settings\Application Data\Chromium\User Data\Default\Extensions\

Windows Vista/7/8:
  Chrome  : %LocalAppData%\Google\Chrome\User Data\Default\Extensions\
  Chromium: %LocalAppData%\Chromium\User Data\Default\Extensions\

Linux:
  Chrome  : ~/.config/google-chrome/Default/Extensions/
  Chromium: ~/.config/chromium/Default/Extensions/

Mac OS X:
  Chrome  : ~/Library/Application Support/Google/Chrome/Default/Extensions/
  Chromium: ~/Library/Application Support/Chromium/Default/Extensions/

Although you can change it by running Chrome with the --user-data-dir= option.

basic authorization command for curl

One way, provide --user flag as part of curl, as follows:

curl --user username:password http://example.com

Another way is to get Base64 encoded token of "username:password" from any online website like - https://www.base64encode.org/ and pass it as Authorization header of curl as follows:

curl -i -H 'Authorization:Basic dXNlcm5hbWU6cGFzc3dvcmQ=' http://localhost:8080/

Here, dXNlcm5hbWU6cGFzc3dvcmQ= is Base64 encoded token of username:password.

Is there a way to select sibling nodes?

The following function will return an array containing all the siblings of the given element.

function getSiblings(elem) {
    return [...elem.parentNode.children].filter(item => item !== elem);
}

Just pass the selected element into the getSiblings() function as it's only parameter.

Linear regression with matplotlib / numpy

This code:

from scipy.stats import linregress

linregress(x,y) #x and y are arrays or lists.

gives out a list with the following:

slope : float
slope of the regression line
intercept : float
intercept of the regression line
r-value : float
correlation coefficient
p-value : float
two-sided p-value for a hypothesis test whose null hypothesis is that the slope is zero
stderr : float
Standard error of the estimate

Source

How to get StackPanel's children to fill maximum space downward?

It sounds like you want a StackPanel where the final element uses up all the remaining space. But why not use a DockPanel? Decorate the other elements in the DockPanel with DockPanel.Dock="Top", and then your help control can fill the remaining space.

XAML:

<DockPanel Width="200" Height="200" Background="PowderBlue">
    <TextBlock DockPanel.Dock="Top">Something</TextBlock>
    <TextBlock DockPanel.Dock="Top">Something else</TextBlock>
    <DockPanel
        HorizontalAlignment="Stretch" 
        VerticalAlignment="Stretch" 
        Height="Auto" 
        Margin="10">

      <GroupBox 
        DockPanel.Dock="Right" 
        Header="Help" 
        Width="100" 
        Background="Beige" 
        VerticalAlignment="Stretch" 
        VerticalContentAlignment="Stretch" 
        Height="Auto">
        <TextBlock Text="This is the help that is available on the news screen." 
                   TextWrapping="Wrap" />
     </GroupBox>

      <StackPanel DockPanel.Dock="Left" Margin="10" 
           Width="Auto" HorizontalAlignment="Stretch">
          <TextBlock Text="Here is the news that should wrap around." 
                     TextWrapping="Wrap"/>
      </StackPanel>
    </DockPanel>
</DockPanel>

If you are on a platform without DockPanel available (e.g. WindowsStore), you can create the same effect with a grid. Here's the above example accomplished using grids instead:

<Grid Width="200" Height="200" Background="PowderBlue">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <StackPanel Grid.Row="0">
        <TextBlock>Something</TextBlock>
        <TextBlock>Something else</TextBlock>
    </StackPanel>
    <Grid Height="Auto" Grid.Row="1" Margin="10">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="100"/>
        </Grid.ColumnDefinitions>
        <GroupBox
            Width="100"
            Height="Auto"
            Grid.Column="1"
            Background="Beige"
            Header="Help">
            <TextBlock Text="This is the help that is available on the news screen." 
              TextWrapping="Wrap"/>
        </GroupBox>
        <StackPanel Width="Auto" Margin="10" DockPanel.Dock="Left">
            <TextBlock Text="Here is the news that should wrap around." 
              TextWrapping="Wrap"/>
        </StackPanel>
    </Grid>
</Grid>

C++ vector's insert & push_back difference

Beside the fact, that push_back(x) does the same as insert(x, end()) (maybe with slightly better performance), there are several important thing to know about these functions:

  1. push_back exists only on BackInsertionSequence containers - so, for example, it doesn't exist on set. It couldn't because push_back() grants you that it will always add at the end.
  2. Some containers can also satisfy FrontInsertionSequence and they have push_front. This is satisfied by deque, but not by vector.
  3. The insert(x, ITERATOR) is from InsertionSequence, which is common for set and vector. This way you can use either set or vector as a target for multiple insertions. However, set has additionally insert(x), which does practically the same thing (this first insert in set means only to speed up searching for appropriate place by starting from a different iterator - a feature not used in this case).

Note about the last case that if you are going to add elements in the loop, then doing container.push_back(x) and container.insert(x, container.end()) will do effectively the same thing. However this won't be true if you get this container.end() first and then use it in the whole loop.

For example, you could risk the following code:

auto pe = v.end();
for (auto& s: a)
    v.insert(pe, v);

This will effectively copy whole a into v vector, in reverse order, and only if you are lucky enough to not get the vector reallocated for extension (you can prevent this by calling reserve() first); if you are not so lucky, you'll get so-called UndefinedBehavior(tm). Theoretically this isn't allowed because vector's iterators are considered invalidated every time a new element is added.

If you do it this way:

copy(a.begin(), a.end(), back_inserter(v);

it will copy a at the end of v in the original order, and this doesn't carry a risk of iterator invalidation.

[EDIT] I made previously this code look this way, and it was a mistake because inserter actually maintains the validity and advancement of the iterator:

copy(a.begin(), a.end(), inserter(v, v.end());

So this code will also add all elements in the original order without any risk.

jQuery SVG, why can't I addClass?

I use Snap.svg to add a class to and SVG.

var jimmy = Snap(" .jimmy ")

jimmy.addClass("exampleClass");

http://snapsvg.io/docs/#Element.addClass

The service cannot be started, either because it is disabled or because it has no enabled devices associated with it

This error can occur on anything that requires elevated privileges in Windows.

It happens when the "Application Information" service is disabled in Windows services. There are a few viruses that use this as an attack vector to prevent people from removing the virus. It also prevents people from installing software to remove viruses.

The normal way to fix this would be to run services.msc, or to go into Administrative Tools and run "Services". However, you will not be able to do that if the "Application Information" service is disabled.

Instead, reboot your computer into Safe Mode (reboot and press F8 until the Windows boot menu appears, select Safe Mode with Networking). Then run services.msc and look for services that are designated as "Disabled" in the Startup Type column. Change these "Disabled" services to "Automatic".

Make sure the "Application Information" service is set to a Startup Type of "Automatic".

When you are done enabling your services, click Ok at the bottom of the tool and reboot your computer back into normal mode. The problem should be resolved when Windows reboots.

Elegant way to check for missing packages and install them?

I use the following which will check if package is installed and if dependencies are updated, then loads the package.

p<-c('ggplot2','Rcpp')
install_package<-function(pack)
{if(!(pack %in% row.names(installed.packages())))
{
  update.packages(ask=F)
  install.packages(pack,dependencies=T)
}
 require(pack,character.only=TRUE)
}
for(pack in p) {install_package(pack)}

completeFun <- function(data, desiredCols) {
  completeVec <- complete.cases(data[, desiredCols])
  return(data[completeVec, ])
}

How to get Selected Text from select2 when using <input>

The correct way to do this as of v4 is:

$('.select2-chosen').select2('data')[0].text

It is undocumented so could break in the future without warning.

You will probably want to check if there is a selection first however:

var s = $('.select2-chosen');

if(s.select2('data') && !!s.select2('data')[0]){
    //do work
}

Calling an executable program using awk

I use the power of awk to delete some of my stopped docker containers. Observe carefully how i construct the cmd string first before passing it to system.

docker ps -a | awk '$3 ~ "/bin/clish" { cmd="docker rm "$1;system(cmd)}'

Here, I use the 3rd column having the pattern "/bin/clish" and then I extract the container ID in the first column to construct my cmd string and passed that to system.

How to fix System.NullReferenceException: Object reference not set to an instance of an object

During debug, break on all exceptions thrown. Debug->Exceptions

Check all 'Thrown' exceptions. F5, the code will stop on the offending line.

Specifying an Index (Non-Unique Key) Using JPA

EclipseLink provided an annotation (e.g. @Index) to define an index on columns. There is an example of its use. Part of the example is included...

The firstName and lastName fields are indexed, together and individually.

@Entity
@Index(name="EMP_NAME_INDEX", columnNames={"F_NAME","L_NAME"})  // Columns indexed together
public class Employee{
    @Id
    private long id;

    @Index                      // F_NAME column indexed
    @Column(name="F_NAME")
    private String firstName;

    @Index                      // L_NAME column indexed
    @Column(name="L_NAME")
    private String lastName;
    ...
}

The iOS Simulator deployment targets is set to 7.0, but the range of supported deployment target version for this platform is 8.0 to 12.1

Iterating over the answer from Tao-Nhan Nguyen, accounting the original value set for every pod, adjusting it only if it's not greater than 8.0... Add the following to the Podfile:

post_install do |installer|
  installer.pods_project.targets.each do |target|
    target.build_configurations.each do |config|
      if Gem::Version.new('8.0') > Gem::Version.new(config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'])
        config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '8.0'
      end
    end
  end
end

How to install an apk on the emulator in Android Studio?

EDIT: Even though this answer is marked as the correct answer (in 2013), currently, as answered by @user2511630 below, you can drag-n-drop apk files directly into the emulator to install them.


Original Answer:

You can install .apk files to emulator regardless of what you are using (Eclipse or Android Studio)

here's what I always do: (For full beginners)

1- Run the emulator, and wait until it's completely started.

2- Go to your sdk installation folder then go to platform-tools (you should see an executable called adb.exe)

3- create a new file and call it run.bat, edit the file with notepad and write CMD in it and save it.

4- copy your desired apk to the same folder

5- now open run.bat and write adb install "your_apk_file.apk"

6- wait until the installation is complete

7- voila your apk is installed to your emulator.

Note: to re-install the application if it already existe use adb install -r "your_apk_file.apk"

sorry for the detailed instruction as I said for full beginners

Hope this help.

Regards,

Tarek

Example 1

Example 2

Get Android .apk file VersionName or VersionCode WITHOUT installing apk

Using apkanalyzer that is now part of cmdline-tools:

$ apkanalyzer manifest version-code my_app.apk
1
$ apkanalyzer manifest version-name my_app.apk
1.2.3.4

CSS z-index not working (position absolute)

How about this?

http://jsfiddle.net/P7c9q/4/

<div class="relative">
  <div class="yellow-div"></div>
  <div class="yellow-div"></div>
  <div class="absolute"></div>
</div>

.relative{
position:relative;
}

.absolute {
position:absolute;
width: 40px;
height: 100px;
background: #000;
z-index: 1;
top:30px;
left:0px;
}
.yellow-div {
position:relative;
width: 200px;
height: 50px;
background: yellow;
margin-bottom:4px;
z-index:0;
}

use the relative div as wrapper and let the yellow div's have normal positioning.

Only the black block need to have an absolute position then.

ActionBarActivity: cannot be resolved to a type

UPDATE:

Since the version 22.1.0, the class ActionBarActivity is deprecated, so instead use AppCompatActivity. For more details see here

Using ActionBarActivity:

In Eclipse:

1 - Make sure library project(appcompat_v7) is open & is proper referenced (added as library) in your application project.

2 - Delete android-support-v4.jar from your project's libs folder(if jar is present).

3 - Appcompat_v7 must have android-support-v4.jar & android-support-v7-appcompat.jar inside it's libs folder. (If jars are not present copy them from /sdk/extras/android/support/v7/appcompat/libs folder of your installed android sdk location)

4- Check whether ActionBarActivity is properly imported.

import android.support.v7.app.ActionBarActivity;

In Android Studio

Just add compile dependencies to app's build.gradle

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.1.1'
}

Bootstrap combining rows (rowspan)

Check this one. hope it will help full for you.

http://jsfiddle.net/j6amM/

.row-fix { margin-bottom:20px;}

.row-fix > [class*="span"]{ height:100px; background:#f1f1f1;}

.row-fix .two-col{ background:none;}

.two-col > [class*="col"]{ height:40px; background:#ccc;}

.two-col > .col1{margin-bottom:20px;}

How to use makefiles in Visual Studio?

I actually use a makefile to build any dependencies needed before invoking devenv to build a particular project as in the following:

debug: coratools_debug
    devenv coralib.vcproj /build debug

coratools_debug: nothing
    cd ../coratools
    nmake debug
    cd $(MAKEDIR)

You can also use the msbuild tool to do the same thing:

debug: coratools_debug
    msbuild coralib.vcxproj /p:Configuration=debug

coratools_debug: nothing
    cd ../coratools
    nmake debug
    cd $(MAKEDIR)

In my opinion, this is much easier than trying to figure out the overly complicated visual studio project management scheme.

Polygon Drawing and Getting Coordinates with Google Map API v3

The other answers show you to create the polygons, but not how to get the coordinates...

I'm not sure the best way to do it, but heres one way.. It seems like there should be a method to get the paths from the polygon, but I can't find one, and getPath() doesn't seem to work for me. So here's a manual approach that worked for me..

Once you've finished drawing your polygon, and pass in your polygon to the overlay complete function, you can find the coordinates in the polygon.overlay.latLngs.b[0].b

google.maps.event.addListener(drawingManager, 'overlaycomplete', function(polygon) {
        $.each(polygon.overlay.latLngs.b[0].b, function(key, latlng){
            var lat = latlng.d;
            var lon = latlng.e;
            console.log(lat, lon); //do something with the coordinates
        });
});

note, i'm using jquery to loop over the list of coordinates, but you can do loop however.

How to find serial number of Android device?

Build.SERIAL is the simplest way to go, although not entirely reliable as it can be empty or sometimes return a different value (proof 1, proof 2) than what you can see in your device's settings.

There are several ways to get that number depending on the device's manufacturer and Android version, so I decided to compile every possible solution I could found in a single gist. Here's a simplified version of it :

public static String getSerialNumber() {
    String serialNumber;

    try {
        Class<?> c = Class.forName("android.os.SystemProperties");
        Method get = c.getMethod("get", String.class);

        serialNumber = (String) get.invoke(c, "gsm.sn1");
        if (serialNumber.equals(""))
            serialNumber = (String) get.invoke(c, "ril.serialnumber");
        if (serialNumber.equals(""))
            serialNumber = (String) get.invoke(c, "ro.serialno");
        if (serialNumber.equals(""))
            serialNumber = (String) get.invoke(c, "sys.serialnumber");
        if (serialNumber.equals(""))
            serialNumber = Build.SERIAL;

        // If none of the methods above worked
        if (serialNumber.equals(""))
            serialNumber = null;
    } catch (Exception e) {
        e.printStackTrace();
        serialNumber = null;
    }

    return serialNumber;
}

How to compare times in Python?

Another way to do this without adding dependencies or using datetime is to simply do some math on the attributes of the time object. It has hours, minutes, seconds, milliseconds, and a timezone. For very simple comparisons, hours and minutes should be sufficient.

d = datetime.utcnow()
t = d.time()
print t.hour,t.minute,t.second

I don't recommend doing this unless you have an incredibly simple use-case. For anything requiring timezone awareness or awareness of dates, you should be using datetime.

Hex to ascii string conversion

If I understand correctly, you want to know how to convert bytes encoded as a hex string to its form as an ASCII text, like "537461636B" would be converted to "Stack", in such case then the following code should solve your problem.

Have not run any benchmarks but I assume it is not the peak of efficiency.

static char ByteToAscii(const char *input) {
  char singleChar, out;
  memcpy(&singleChar, input, 2);
  sprintf(&out, "%c", (int)strtol(&singleChar, NULL, 16));
  return out;
}

int HexStringToAscii(const char *input, unsigned int length,
                            char **output) {
  int mIndex, sIndex = 0;
  char buffer[length];
  for (mIndex = 0; mIndex < length; mIndex++) {
    sIndex = mIndex * 2;
    char b = ByteToAscii(&input[sIndex]);
    memcpy(&buffer[mIndex], &b, 1);
  }
  *output = strdup(buffer);
  return 0;
}

Calculate execution time of a SQL query?

I found this one more helpful and simple

DECLARE @StartTime datetime,@EndTime datetime   
SELECT @StartTime=GETDATE() 
--Your Query to be run goes here--  
SELECT @EndTime=GETDATE()   
SELECT DATEDIFF(ms,@StartTime,@EndTime) AS [Duration in milliseconds]   

Git copy file preserving history

Unlike subversion, git does not have a per-file history. If you look at the commit data structure, it only points to the previous commits and the new tree object for this commit. No explicit information is stored in the commit object which files are changed by the commit; nor the nature of these changes.

The tools to inspect changes can detect renames based on heuristics. E.g. "git diff" has the option -M that turns on rename detection. So in case of a rename, "git diff" might show you that one file has been deleted and another one created, while "git diff -M" will actually detect the move and display the change accordingly (see "man git diff" for details).

So in git this is not a matter of how you commit your changes but how you look at the committed changes later.

Using Spring 3 autowire in a standalone Java application

I case you are running SpringBoot:

I just had the same problem, that I could not Autowire one of my services from the static main method.

See below an approach in case you are relying on SpringApplication.run:

@SpringBootApplication
public class PricingOnlineApplication {

    @Autowired
    OrchestratorService orchestratorService;

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(PricingOnlineApplication.class, args);
        PricingOnlineApplication application = context.getBean(PricingOnlineApplication.class);

        application.start();
    }

    private void start() {
        orchestratorService.performPricingRequest(null);
    }

}

I noticed that SpringApplication.run returns a context which can be used similar to the above described approaches. From there, it is exactly the same as above ;-)

CSS - make div's inherit a height

As already mentioned this can't be done with floats, they can't inherit heights, they're unaware of their siblings so for example the side two floats don't know the height of the centre content, so they can't inherit from anything.

Usually inherited height has to come from either an element which has an explicit height or if height: 100%; has been passed down through the display tree to it.. The only thing I'm aware of that passes on height which hasn't come from top of the "tree" is an absolutely positioned element - so you could for example absolutely position all the top right bottom left sides and corners (you know the height and width of the corners anyway) And as you seem to know the widths (of left/right borders) and heights of top/bottom) borders, and the widths of the top/bottom centers, are easy at 100% - the only thing that needs calculating is the height of the right/left sides if the content grows -

This you can do, even without using all four positioning co-ordinates which IE6 /7 doesn't support

I've put up an example based on what you gave, it does rely on a fixed width (your frame), but I think it could work with a flexible width too? the uses of this could be cool for those fancy image borders we can't get support for until multiple background images or image borders become fully available.. who knows, I was playing, so just sticking it out there!

proof of concept example is here

Python, Unicode, and the Windows console

Despite the other plausible-sounding answers that suggest changing the code page to 65001, that does not work. (Also, changing the default encoding using sys.setdefaultencoding is not a good idea.)

See this question for details and code that does work.

Abort a git cherry-pick?

You can do the following

git cherry-pick --abort

From the git cherry-pick docs

--abort  

Cancel the operation and return to the pre-sequence state.

#1130 - Host ‘localhost’ is not allowed to connect to this MySQL server

Use the IP instead:

DROP USER 'root'@'127.0.0.1'; GRANT ALL PRIVILEGES ON . TO 'root'@'%';

For more possibilities, see this link.

To create the root user, seeing as MySQL is local & all, execute the following from the command line (Start > Run > "cmd" without quotes):

mysqladmin -u root password 'mynewpassword'

Documentation, and Lost root access in MySQL.

How can I execute a python script from an html button?

There are various ways to make it done, very simple technique with security peace in mind, here might help you


1. First you need to install Flask
pip install flask
in your command prompt, which is a python microframework, don't be afraid that you need to have another prior knowledge to learn that, it's really simple and just a few line of code. If you wish you learn Flask quickly for complete novice here is the tutorial that I also learn from Flask Tutorial for beginner (YouTube)

2.Create a new folder
- 1st file will be server.py

_x000D_
_x000D_
from flask import Flask, render_template_x000D_
app = Flask(__name__)_x000D_
_x000D_
@app.route('/')_x000D_
def index():_x000D_
  return render_template('index.html')_x000D_
_x000D_
@app.route('/my-link/')_x000D_
def my_link():_x000D_
  print ('I got clicked!')_x000D_
_x000D_
  return 'Click.'_x000D_
_x000D_
if __name__ == '__main__':_x000D_
  app.run(debug=True)
_x000D_
_x000D_
_x000D_

-2nd create another subfolder inside previous folder and name it as templates file will be your html file
index.html

_x000D_
_x000D_
<!doctype html>_x000D_
_x000D_
_x000D_
<head><title>Test</title> _x000D_
    <meta charset=utf-8> </head>_x000D_
    <body>_x000D_
        <h1>My Website</h1>_x000D_
        <form action="/my-link/">_x000D_
            <input type="submit" value="Click me" />_x000D_
        </form>_x000D_
        _x000D_
        <button> <a href="/my-link/">Click me</a></button>_x000D_
_x000D_
    </body>
_x000D_
_x000D_
_x000D_

3.. To run, open command prompt to the New folder directory, type python server.py to run the script, then go to browser type localhost:5000, then you will see button. You can click and route to destination script file you created.

Hope this helpful. thank you.

how to write javascript code inside php

You can put up all your JS like this, so it doesn't execute before your HTML is ready

$(document).ready(function() {
   // some code here
 });

Remember this is jQuery so include it in the head section. Also see Why you should use jQuery and not onload

How to get the last char of a string in PHP?

Or by direct string access:

$string[strlen($string)-1];

Note that this doesn't work for multibyte strings. If you need to work with multibyte string, consider using the mb_* string family of functions.

As of PHP 7.1.0 negative numeric indices are also supported, e.g just $string[-1];

HTML select drop-down with an input field

You can use input text with "list" attribute, which refers to the datalist of values.

_x000D_
_x000D_
<input type="text" name="city" list="cityname">_x000D_
    <datalist id="cityname">_x000D_
      <option value="Boston">_x000D_
      <option value="Cambridge">_x000D_
    </datalist>
_x000D_
_x000D_
_x000D_

This creates a free text input field that also has a drop-down to select predefined choices. Attribution for example and more information: https://www.w3.org/wiki/HTML/Elements/datalist

Corrupted Access .accdb file: "Unrecognized Database Format"

Open access, go to the database tools tab, select compact and repair database. You can choose the database from there.

How to use order by with union all in sql?

select CONCAT(Name, '(',substr(occupation, 1, 1), ')') AS f1
from OCCUPATIONS
union
select temp.str AS f1 from 
(select count(occupation) AS counts, occupation, concat('There are a total of ' ,count(occupation) ,' ', lower(occupation),'s.') As str  from OCCUPATIONS group by occupation order by counts ASC, occupation ASC
 ) As temp
 order by f1

How to open a txt file and read numbers in Java

   try{

    BufferedReader br = new BufferedReader(new FileReader("textfile.txt"));
    String strLine;
    //Read File Line By Line
    while ((strLine = br.readLine()) != null)   {
      // Print the content on the console
      System.out.println (strLine);
    }
    //Close the input stream
    in.close();
    }catch (Exception e){//Catch exception if any
      System.err.println("Error: " + e.getMessage());
    }finally{
     in.close();
    }

This will read line by line,

If your no. are saperated by newline char. then in place of

 System.out.println (strLine);

You can have

try{
int i = Integer.parseInt(strLine);
}catch(NumberFormatException npe){
//do something
}  

If it is separated by spaces then

try{
    String noInStringArr[] = strLine.split(" ");
//then you can parse it to Int as above
    }catch(NumberFormatException npe){
    //do something
    }  

UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block

I suggest removing the below code from getMails

 .catch(error => { throw error})

In your main function you should put await and related code in Try block and also add one catch block where you failure code.


you function gmaiLHelper.getEmails should return a promise which has reject and resolve in it.

Now while calling and using await put that in try catch block(remove the .catch) as below.

router.get("/emailfetch", authCheck, async (req, res) => {
  //listing messages in users mailbox 
try{
  let emailFetch = await gmaiLHelper.getEmails(req.user._doc.profile_id , '/messages', req.user.accessToken)
}
catch (error) { 
 // your catch block code goes here
})

Iterate through every file in one directory

As others have said, Dir::foreach is a good option here. However, note that Dir::foreach and Dir::entries will always include . and .. (the current and parent directories). You will generally not want to work on them, so you can use Dir::each_child or Dir::children (as suggested by ma11hew28) or do something like this:

Dir.foreach('/path/to/dir') do |filename|
  next if filename == '.' or filename == '..'
  # Do work on the remaining files & directories
end

Dir::foreach and Dir::entries (as well as Dir::each_child and Dir::children) also include hidden files & directories. Often this is what you want, but if it isn't, you need to do something to skip over them.

Alternatively, you might want to look into Dir::glob which provides simple wildcard matching:

Dir.glob('/path/to/dir/*.rb') do |rb_filename|
  # Do work on files & directories ending in .rb
end

Resolving require paths with webpack

This thread is old but since no one posted about require.context I'm going to mention it:

You can use require.context to set the folder to look through like this:

var req = require.context('../../mydir/', true)
// true here is for use subdirectories, you can also specify regex as third param

return req('./myfile.js')

Find an element in DOM based on an attribute value

you could use getAttribute:

 var p = document.getElementById("p");
 var alignP = p.getAttribute("align");

https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute

How to attach a process in gdb

With a running instance of myExecutableName having a PID 15073:

hitting Tab twice after $ gdb myExecu in the command line, will automagically autocompletes to:

$ gdb myExecutableName 15073

and will attach gdb to this process. That's nice!

Insecure content in iframe on secure page

Based on generality of this question, I think, that you'll need to setup your own HTTPS proxy on some server online. Do the following steps:

  • Prepare your proxy server - install IIS, Apache
  • Get valid SSL certificate to avoid security errors (free from startssl.com for example)
  • Write a wrapper, which will download insecure content (how to below)
  • From your site/app get https://yourproxy.com/?page=http://insecurepage.com

If you simply download remote site content via file_get_contents or similiar, you can still have insecure links to content. You'll have to find them with regex and also replace. Images are hard to solve, but Ï found workaround here: http://foundationphp.com/tutorials/image_proxy.php


Note: While this solution may have worked in some browsers when it was written in 2014, it no longer works. Navigating or redirecting to an HTTP URL in an iframe embedded in an HTTPS page is not permitted by modern browsers, even if the frame started out with an HTTPS URL.

The best solution I created is to simply use google as the ssl proxy...

https://www.google.com/search?q=%http://yourhttpsite.com&btnI=Im+Feeling+Lucky

Tested and works in firefox.

Other Methods:

  • Use a Third party such as embed.ly (but it it really only good for well known http APIs).

  • Create your own redirect script on an https page you control (a simple javascript redirect on a relative linked page should do the trick. Something like: (you can use any langauge/method)

    https://example.com That has a iframe linking to...

    https://example.com/utilities/redirect.html Which has a simple js redirect script like...

    document.location.href ="http://thenonsslsite.com";

  • Alternatively, you could add an RSS feed or write some reader/parser to read the http site and display it within your https site.

  • You could/should also recommend to the http site owner that they create an ssl connection. If for no other reason than it increases seo.

Unless you can get the http site owner to create an ssl certificate, the most secure and permanent solution would be to create an RSS feed grabing the content you need (presumably you are not actually 'doing' anything on the http site -that is to say not logging in to any system).

The real issue is that having http elements inside a https site represents a security issue. There are no completely kosher ways around this security risk so the above are just current work arounds.

Note, that you can disable this security measure in most browsers (yourself, not for others). Also note that these 'hacks' may become obsolete over time.

What is the difference between a candidate key and a primary key?

A primary key is a column (or columns) in a table that uniquely identifies the rows in that table.

CUSTOMERS


CustomerNo  FirstName   LastName
1   Sally   Thompson
2   Sally   Henderson
3   Harry   Henderson
4   Sandra  Wellington

For example, in the table above, CustomerNo is the primary key.

The values placed in primary key columns must be unique for each row: no duplicates can be tolerated. In addition, nulls are not allowed in primary key columns.

So, having told you that it is possible to use one or more columns as a primary key, how do you decide which columns (and how many) to choose?

Well there are times when it is advisable or essential to use multiple columns. However, if you cannot see an immediate reason to use multiple columns, then use one. This isn't an absolute rule, it is simply advice. However, primary keys made up of single columns are generally easier to maintain and faster in operation. This means that if you query the database, you will usually get the answer back faster if the tables have single column primary keys.

Next question — which column should you pick? The easiest way to choose a column as a primary key (and a method that is reasonably commonly employed) is to get the database itself to automatically allocate a unique number to each row.

In a table of employees, clearly any column like FirstName is a poor choice since you cannot control employee's first names. Often there is only one choice for the primary key, as in the case above. However, if there is more than one, these can be described as 'candidate keys' — the name reflects that they are candidates for the responsible job of primary key.

Renaming branches remotely in Git

TL;DR

"Renaming" a remote branch is actually a 2 step process (not necessarily ordered):

  • deletion of the old remote branch (git push [space]:<old_name> as ksrb explained);
  • push into a new remote branch (difference between a couple of answers commands below).

Deleting

I use TortoiseGit and when I first tried to delete the branch through the command line, I got this:

$ git push origin :in
  • fatal: 'origin' does not appear to be a git repository

  • fatal: Could not read from remote repository.

Please make sure you have the correct access rights and the repository exists.

This was likely due to pageant not having the private key loaded (which TortoiseGit loads automatically into pageant). Moreover, I noticed that TortoiseGit commands do not have the origin ref in them (e.g. git.exe push --progress "my_project" interesting_local:interesting).

I am also using Bitbucket and, as others web-based online git managers of the sort (GitHub, GitLab), I was able to delete the remote branch directly through their interface (branches page):

Delete branch Bitbucket

However, in TortoiseGit you may also delete remote branches through Browse References:

Browse References menu

By right-clicking on a remote branch (remotes list) the Delete remote branch option shows up:

TortoiseGit remote branch delete

Pushing

After deleting the old remote branch I pushed directly into a new remote branch through TortoiseGit just by typing the new name in the Remote: field of the Push window and this branch was automatically created and visible in Bitbucket.

However, if you still prefer to do it manually, a point that has not been mentioned yet in this thread is that -u = --set-upstream.

From git push docs, -u is just an alias of --set-upstream, so the commands in the answers of Sylvain (-set-upstream new-branch) and Shashank (-u origin new_branch) are equivalent, since the remote ref defaults to origin if no other ref was previously defined:

  • git push origin -u new_branch = git push -u new_branch from the docs description:

    If the configuration is missing, it defaults to origin.

In the end, I did not manually type in or used any of the commands suggested by the other answers in here, so perhaps this might be useful to others in a similar situation.

How can I monitor the thread count of a process on linux?

If you're interested in those threads which are really active -- as in doing something (not blocked, not timed_waiting, not reporting "thread running" but really waiting for a stream to give data) as opposed to sitting around idle but live -- then you might be interested in jstack-active.

This simple bash script runs jstack then filters out all the threads which by heuristics seem to be idling, showing you stack traces for those threads which are actually consuming CPU cycles.

Pinging servers in Python

This function works in any OS (Unix, Linux, macOS, and Windows)
Python 2 and Python 3

EDITS:
By @radato os.system was replaced by subprocess.call. This avoids shell injection vulnerability in cases where your hostname string might not be validated.

import platform    # For getting the operating system name
import subprocess  # For executing a shell command

def ping(host):
    """
    Returns True if host (str) responds to a ping request.
    Remember that a host may not respond to a ping (ICMP) request even if the host name is valid.
    """

    # Option for the number of packets as a function of
    param = '-n' if platform.system().lower()=='windows' else '-c'

    # Building the command. Ex: "ping -c 1 google.com"
    command = ['ping', param, '1', host]

    return subprocess.call(command) == 0

Note that, according to @ikrase on Windows this function will still return True if you get a Destination Host Unreachable error.

Explanation

The command is ping in both Windows and Unix-like systems.
The option -n (Windows) or -c (Unix) controls the number of packets which in this example was set to 1.

platform.system() returns the platform name. Ex. 'Darwin' on macOS.
subprocess.call() performs a system call. Ex. subprocess.call(['ls','-l']).

javascript close current window

TRY this out it works fine ...

<!DOCTYPE html>
<html>
<body>

<input type="button"  onclick="openWin()" value="open"/>
<input type="button"  onclick="closeWin()" value="close"/>

<script>
var myWindow;

function openWin()
{
myWindow = window.open("","myWindow","width=200,height=100");
myWindow.document.write("<p>This is 'myWindow'</p>");
}

function closeWin()
{
myWindow.close();
}
</script>

</body>
</html>

this works as you want it to work

how to remove key+value from hash in javascript

Another option may be this John Resig remove method. can better fit what you need. if you know the index in the array.

Usage of @see in JavaDoc?

@see is useful for information about related methods/classes in an API. It will produce a link to the referenced method/code on the documentation. Use it when there is related code that might help the user understand how to use the API.

How to find the nearest parent of a Git branch?

git log -2 --pretty=format:'%d' --abbrev-commit | tail -n 1 | sed 's/\s(//g; s/,/\n/g';

(origin/parent-name, parent-name)

git log -2 --pretty=format:'%d' --abbrev-commit | tail -n 1 | sed 's/\s(//g; s/,/\n/g';

origin/parent-name

git log -2 --pretty=format:'%d' --abbrev-commit | tail -n 1 | sed 's/(.*,//g; s/)//';

parent-name

Android- Error:Execution failed for task ':app:transformClassesWithDexForRelease'

For me, the problem was solved after I removed jar file from my project. it seems that one of the jar files inside my project was using an older version of google play services.

fetch in git doesn't get all branches

We had the same problem and you have to use

git fetch

git push origin branch_name

git branch -r

Hope this help someone facing the same problem

Uninstall Node.JS using Linux command line?

if you want to just update node, there's a neat updater too

https://github.com/creationix/nvm

to use,

git clone git://github.com/creationix/nvm.git ~/.nvm

source ~/.nvm/nvm.sh

nvm install v0.4.1

Error: Specified cast is not valid. (SqlManagerUI)

There are some funnies restoring old databases into SQL 2008 via the guy; have you tried doing it via TSQL ?

Use Master
Go
RESTORE DATABASE YourDB
FROM DISK = 'C:\YourBackUpFile.bak'
WITH MOVE 'YourMDFLogicalName' TO 'D:\Data\YourMDFFile.mdf',--check and adjust path
MOVE 'YourLDFLogicalName' TO 'D:\Data\YourLDFFile.ldf' 

What does API level mean?

This actually sums it up pretty nicely.

API Levels generally mean that as a programmer, you can communicate with the devices' built in functions and functionality. As the API level increases, functionality adds up (although some of it can get deprecated).

Choosing an API level for an application development should take at least two thing into account:

  1. Current distribution - How many devices can actually support my application, if it was developed for API level 9, it cannot run on API level 8 and below, then "only" around 60% of devices can run it (true to the date this post was made).
  2. Choosing a lower API level may support more devices but gain less functionality for your app. you may also work harder to achieve features you could've easily gained if you chose higher API level.

Android API levels can be divided to five main groups (not scientific, but what the heck):

  1. Android 1.5 - 2.3 (Cupcake to Gingerbread) - (API levels 3-10) - Android made specifically for smartphones.
  2. Android 3.0 - 3.2 (Honeycomb) (API levels 11-13) - Android made for tablets.
  3. Android 4.0 - 4.4 (KitKat) - (API levels 14-19) - A big merge with tons of additional functionality, totally revamped Android version, for both phone and tablets.
  4. Android 5.0 - 5.1 (Lollipop) - (API levels 21-22) - Material Design introduced.
  5. Android 6.0 - 6.… (Marshmallow) - (API levels 23-…) - Runtime Permissions,Apache HTTP Client Removed

Passing capturing lambda as function pointer

Not a direct answer, but a slight variation to use the "functor" template pattern to hide away the specifics of the lambda type and keeps the code nice and simple.

I was not sure how you wanted to use the decide class so I had to extend the class with a function that uses it. See full example here: https://godbolt.org/z/jtByqE

The basic form of your class might look like this:

template <typename Functor>
class Decide
{
public:
    Decide(Functor dec) : _dec{dec} {}
private:
    Functor _dec;
};

Where you pass the type of the function in as part of the class type used like:

auto decide_fc = [](int x){ return x > 3; };
Decide<decltype(decide_fc)> greaterThanThree{decide_fc};

Again, I was not sure why you are capturing x it made more sense (to me) to have a parameter that you pass in to the lambda) so you can use like:

int result = _dec(5); // or whatever value

See the link for a complete example

What is private bytes, virtual bytes, working set?

The definition of the perfmon counters has been broken since the beginning and for some reason appears to be too hard to correct.

A good overview of Windows memory management is available in the video "Mysteries of Memory Management Revealed" on MSDN: It covers more topics than needed to track memory leaks (eg working set management) but gives enough detail in the relevant topics.


To give you a hint of the problem with the perfmon counter descriptions, here is the inside story about private bytes from "Private Bytes Performance Counter -- Beware!" on MSDN:

Q: When is a Private Byte not a Private Byte?

A: When it isn't resident.

The Private Bytes counter reports the commit charge of the process. That is to say, the amount of space that has been allocated in the swap file to hold the contents of the private memory in the event that it is swapped out. Note: I'm avoiding the word "reserved" because of possible confusion with virtual memory in the reserved state which is not committed.


From "Performance Planning" on MSDN:

3.3 Private Bytes

3.3.1 Description

Private memory, is defined as memory allocated for a process which cannot be shared by other processes. This memory is more expensive than shared memory when multiple such processes execute on a machine. Private memory in (traditional) unmanaged dlls usually constitutes of C++ statics and is of the order of 5% of the total working set of the dll.

error TS2339: Property 'x' does not exist on type 'Y'

If you want to be able to access images.main then you must define it explicitly:

interface Images {
    main: string;
    [key:string]: string;
}

function getMainImageUrl(images: Images): string {
    return images.main;
}

You can not access indexed properties using the dot notation because typescript has no way of knowing whether or not the object has that property.
However, when you specifically define a property then the compiler knows that it's there (or not), whether it's optional or not and what's the type.


Edit

You can have a helper class for map instances, something like:

class Map<T> {
    private items: { [key: string]: T };

    public constructor() {
        this.items = Object.create(null);
    }

    public set(key: string, value: T): void {
        this.items[key] = value;
    }

    public get(key: string): T {
        return this.items[key];
    }

    public remove(key: string): T {
        let value = this.get(key);
        delete this.items[key];
        return value;
    }
}

function getMainImageUrl(images: Map<string>): string {
    return images.get("main");
}

I have something like that implemented, and I find it very useful.

Javascript reduce() on Object

What you actually want in this case are the Object.values. Here is a concise ES6 implementation with that in mind:

const add = {
  a: {value:1},
  b: {value:2},
  c: {value:3}
}

const total = Object.values(add).reduce((t, {value}) => t + value, 0)

console.log(total) // 6

or simply:

const add = {
  a: 1,
  b: 2,
  c: 3
}

const total = Object.values(add).reduce((t, n) => t + n)

console.log(total) // 6

How to add a touch event to a UIView?

Create a gesture recognizer (subclass), that will implement touch events, like touchesBegan. You can add it to the view after that.

This way you'll use composition instead subclassing (which was the request).

How do I hide an element on a click event anywhere outside of the element?

This doesn't work - it hides the .myDIV when you click inside of it.

$('.openDiv').click(function(e) {
$('.myDiv').show(); 
e.stopPropagation();
})

$(document).click(function(){  
$('.myDiv').hide(); 

});

});

<a class="openDiv">DISPLAY DIV</a>

<div class="myDiv">HIDE DIV</div>

Collections.emptyList() returns a List<Object>?

The issue you're encountering is that even though the method emptyList() returns List<T>, you haven't provided it with the type, so it defaults to returning List<Object>. You can supply the type parameter, and have your code behave as expected, like this:

public Person(String name) {
  this(name,Collections.<String>emptyList());
}

Now when you're doing straight assignment, the compiler can figure out the generic type parameters for you. It's called type inference. For example, if you did this:

public Person(String name) {
  List<String> emptyList = Collections.emptyList();
  this(name, emptyList);
}

then the emptyList() call would correctly return a List<String>.

Check if a string matches a regex in Bash script

You can use the test construct, [[ ]], along with the regular expression match operator, =~, to check if a string matches a regex pattern.

For your specific case, you can write:

[[ $date =~ ^[0-9]{8}$ ]] && echo "yes"

Or more a accurate test:

[[ $date =~ ^[0-9]{4}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|3[0-1])$ ]] && echo "yes"
#           |^^^^^^^^ ^^^^^^ ^^^^^^  ^^^^^^ ^^^^^^^^^^ ^^^^^^ |
#           |   |     ^^^^^^^^^^^^^  ^^^^^^^^^^^^^^^^^^^^^^^^ |
#           |   |          |                   |              |
#           |   |           \                  |              |
#           | --year--   --month--           --day--          |
#           |          either 01...09      either 01..09     end of line
# start of line            or 10,11,12         or 10..29
#                                              or 30, 31

That is, you can define a regex in Bash matching the format you want. This way you can do:

[[ $date =~ ^regex$ ]] && echo "matched" || echo "did not match"

where commands after && are executed if the test is successful, and commands after || are executed if the test is unsuccessful.

Note this is based on the solution by Aleks-Daniel Jakimenko in User input date format verification in bash.


In other shells you can use grep. If your shell is POSIX compliant, do

(echo "$date" | grep -Eq  ^regex$) && echo "matched" || echo "did not match"

In fish, which is not POSIX-compliant, you can do

echo "$date" | grep -Eq "^regex\$"; and echo "matched"; or echo "did not match"

How often should you use git-gc?

Note that the downside of garbage-collecting your repository is that, well, the garbage gets collected. As we all know as computer users, files we consider garbage right now might turn out to be very valuable three days in the future. The fact that git keeps most of its debris around has saved my bacon several times – by browsing all the dangling commits, I have recovered much work that I had accidentally canned.

So don’t be too much of a neat freak in your private clones. There’s little need for it.

OTOH, the value of data recoverability is questionable for repos used mainly as remotes, eg. the place all the devs push to and/or pulled from. There, it might be sensible to kick off a GC run and a repacking frequently.

How to compile C++ under Ubuntu Linux?

Install gcc and try the video below.
Try this:
https://www.youtube.com/watch?v=A6v2Ceqy4Tk
Hope it will works for you.

Round double in two decimal places in C#?

Use an interpolated string, this generates a rounded up string:

var strlen = 6;
$"{48.485:F2}"

Output

"48.49"

How to convert UTF-8 byte[] to string?

A general solution to convert from byte array to string when you don't know the encoding:

static string BytesToStringConverted(byte[] bytes)
{
    using (var stream = new MemoryStream(bytes))
    {
        using (var streamReader = new StreamReader(stream))
        {
            return streamReader.ReadToEnd();
        }
    }
}

Creating a recursive method for Palindrome

Well:

  • It's not clear why you've got two methods with the same signature. What are they meant to accomplish?
  • In the first method, why are you testing for testing for a single space or any single character?
  • You might want to consider generalizing your termination condition to "if the length is less than two"
  • Consider how you want to recurse. One option:
    • Check that the first letter is equal to the last letter. If not, return false
    • Now take a substring to effectively remove the first and last letters, and recurse
  • Is this meant to be an exercise in recursion? That's certainly one way of doing it, but it's far from the only way.

I'm not going to spell it out any more clearly than that for the moment, because I suspect this is homework - indeed some may consider the help above as too much (I'm certainly slightly hesitant myself). If you have any problems with the above hints, update your question to show how far you've got.