Programs & Examples On #Inventory

Inventory Systems (DELETED)

vagrant primary box defined but commands still run against all boxes

The primary flag seems to only work for vagrant ssh for me.

In the past I have used the following method to hack around the issue.

# stage box intended for configuration closely matching production if ARGV[1] == 'stage'     config.vm.define "stage" do |stage|         box_setup stage, \         "10.9.8.31", "deploy/playbook_full_stack.yml", "deploy/hosts/vagrant_stage.yml"     end end 

Accessing inventory host variable in Ansible playbook

I've found also a nice and simple way to address hostsvars right on one of Ansible's Github issues

Looks like you can do this as well:

 - debug:
    msg: "{{ ansible_ssh_host }}"

Ansible: get current target host's IP address

Just use ansible_ssh_host variable

playbook_example.yml

- hosts: host1
  tasks:
  - name: Show host's ip
    debug:
      msg: "{{ ansible_ssh_host }}"

hosts.yml

[hosts]
host1   ansible_host=1.2.3.4

Result

TASK [Show host's ip] *********************************************************************************************************************************************************************************************
ok: [host1] => {
     "msg": "1.2.3.4"
}

Call to undefined function mysql_query() with Login

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

how to define ssh private key for servers fetched by dynamic inventory in files

I'm using the following configuration:

#site.yml:
- name: Example play
  hosts: all
  remote_user: ansible
  become: yes
  become_method: sudo
  vars:
    ansible_ssh_private_key_file: "/home/ansible/.ssh/id_rsa"

Spring Boot: Cannot access REST Controller on localhost (404)

You need to modify the Starter-Application class as shown below.

@SpringBootApplication

@EnableAutoConfiguration

@ComponentScan(basePackages="com.nice.application")

@EnableJpaRepositories("com.spring.app.repository")

public class InventoryApp extends SpringBootServletInitializer {..........

And update the Controller, Service and Repository packages structure as I mentioned below.

Example: REST-Controller

package com.nice.controller; --> It has to be modified as
package com.nice.application.controller;

You need to follow proper package structure for all packages which are in Spring Boot MVC flow.

So, If you modify your project bundle package structures correctly then your spring boot app will work correctly.

How to set host_key_checking=false in ansible inventory file?

Yes, you can set this on the inventory/host level.

With an already accepted answer present, I think this is a better answer to the question on how to handle this on the inventory level. I consider this more secure by isolating this insecure setting to the hosts required for this (e.g. test systems, local development machines).

What you can do at the inventory level is add

ansible_ssh_common_args='-o StrictHostKeyChecking=no'

or

ansible_ssh_extra_args='-o StrictHostKeyChecking=no'

to your host definition (see Ansible Behavioral Inventory Parameters).

This will work provided you use the ssh connection type, not paramiko or something else).

For example, a Vagrant host definition would look like…

vagrant ansible_port=2222 ansible_host=127.0.0.1 ansible_ssh_common_args='-o StrictHostKeyChecking=no'

or

vagrant ansible_port=2222 ansible_host=127.0.0.1 ansible_ssh_extra_args='-o StrictHostKeyChecking=no'

Running Ansible will then be successful without changing any environment variable.

$ ansible vagrant -i <path/to/hosts/file> -m ping
vagrant | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}

In case you want to do this for a group of hosts, here's a suggestion to make it a supplemental group var for an existing group like this:

[mytestsystems]
test[01:99].example.tld

[insecuressh:children]
mytestsystems

[insecuressh:vars]
ansible_ssh_common_args='-o StrictHostKeyChecking=no'

Spring Security exclude url patterns in security annotation configurartion

Found the solution in Spring security examples posted in Github.

WebSecurityConfigurerAdapter has a overloaded configure message that takes WebSecurity as argument which accepts ant matchers on requests to be ignored.

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/authFailure");
}

See Spring Security Samples for more details

Ansible - read inventory hosts and variables to group_vars/all file

If you want to have your vars in files under group_vars, just move them here. Vars can be in the inventory ([group:vars] section) but also (and foremost) in files under group_vars or hosts_vars.

For instance, with your example above, you can move your vars for group tests in the file group_vars/tests :

Inventory file :

[lb]
10.112.84.122

[tomcat]
10.112.84.124

[jboss5]
10.112.84.122

...

[tests:children]
lb
tomcat
jboss5

[default:children]
tests

group_vars/tests file :

data_base_user=NETWIN-4.3
data_base_password=NETWIN
data_base_encrypted_password=
data_base_host=10.112.69.48
data_base_port=1521
data_base_service=ssdenwdb
data_base_url=jdbc:oracle:thin:@10.112.69.48:1521/ssdenwdb

Specify sudo password for Ansible

Probably the best way to do this - assuming that you can't use the NOPASSWD solution provided by scottod is to use Mircea Vutcovici's solution in combination with Ansible vault.

For example, you might have a playbook something like this:

- hosts: all

  vars_files:
    - secret

  tasks:
    - name: Do something as sudo
      service: name=nginx state=restarted
      sudo: yes

Here we are including a file called secret which will contain our sudo password.

We will use ansible-vault to create an encrypted version of this file:

ansible-vault create secret

This will ask you for a password, then open your default editor to edit the file. You can put your ansible_sudo_pass in here.

e.g.: secret:

ansible_sudo_pass: mysudopassword

Save and exit, now you have an encrypted secret file which Ansible is able to decrypt when you run your playbook. Note: you can edit the file with ansible-vault edit secret (and enter the password that you used when creating the file)

The final piece of the puzzle is to provide Ansible with a --vault-password-file which it will use to decrypt your secret file.

Create a file called vault.txt and in that put the password that you used when creating your secret file. The password should be a string stored as a single line in the file.

From the Ansible Docs:

.. ensure permissions on the file are such that no one else can access your key and do not add your key to source control

Finally: you can now run your playbook with something like

ansible-playbook playbook.yml -u someuser -i hosts --sudo --vault-password-file=vault.txt 

The above is assuming the following directory layout:

.
|_ playbook.yml
|_ secret
|_ hosts
|_ vault.txt

You can read more about Ansible Vault here: https://docs.ansible.com/playbooks_vault.html

Java Object Null Check for method

Inside your for-loop, just add the following line:

if(books[i] != null) {
     total += books[i].getPrice();
}

Add multiple items to a list

Another useful way is with Concat.
More information in the official documentation.

List<string> first = new List<string> { "One", "Two", "Three" };
List<string> second = new List<string>() { "Four", "Five" };
first.Concat(second);

The output will be.

One
Two
Three
Four
Five

And there is another similar answer.

How to approach a "Got minus one from a read call" error when connecting to an Amazon RDS Oracle instance

I would like to augment to Stephen C's answer, my case was on the first dot. So since we have DHCP to allocate IP addresses in the company, DHCP changed my machine's address without of course asking neither me nor Oracle. So out of the blue oracle refused to do anything and gave the minus one dreaded exception. So if you want to workaround this once and for ever, and since TCP.INVITED_NODES of SQLNET.ora file does not accept wildcards as stated here, you can add you machine's hostname instead of the IP address.

How to align matching values in two columns in Excel, and bring along associated values in other columns

assuming the item numbers are unique, a VLOOKUP should get you the information you need.

first value would be =VLOOKUP(E1,A:B,2,FALSE), and the same type of formula to retrieve the second value would be =VLOOKUP(E1,C:D,2,FALSE). Wrap them in an IFERROR if you want to return anything other than #N/A if there is no corresponding value in the item column(s)

TypeError: can only concatenate list (not "str") to list

That's not how to add an item to a string. This:

newinv=inventory+str(add)

Means you're trying to concatenate a list and a string. To add an item to a list, use the list.append() method.

inventory.append(add) #adds a new item to inventory
print(inventory) #prints the new inventory

Hope this helps!

Spring CrudRepository findByInventoryIds(List<Long> inventoryIdList) - equivalent to IN clause

Yes, that is supported.

Check the documentation provided here for the supported keywords inside method names.

You can just define the method in the repository interface without using the @Query annotation and writing your custom query. In your case it would be as followed:

List<Inventory> findByIdIn(List<Long> ids);

I assume that you have the Inventory entity and the InventoryRepository interface. The code in your case should look like this:

The Entity

@Entity
public class Inventory implements Serializable {

  private static final long serialVersionUID = 1L;

  private Long id;

  // other fields
  // getters/setters

}

The Repository

@Repository
@Transactional
public interface InventoryRepository extends PagingAndSortingRepository<Inventory, Long> {

  List<Inventory> findByIdIn(List<Long> ids);

}

Barcode scanner for mobile phone for Website in form

Check out https://github.com/serratus/quaggaJS

"QuaggaJS is a barcode-scanner entirely written in JavaScript supporting real- time localization and decoding of various types of barcodes such as EAN, CODE 128, CODE 39, EAN 8, UPC-A, UPC-C, I2of5, 2of5, CODE 93 and CODABAR. The library is also capable of using getUserMedia to get direct access to the user's camera stream. Although the code relies on heavy image-processing even recent smartphones are capable of locating and decoding barcodes in real-time."

NameError: global name 'xrange' is not defined in Python 3

I agree with the last answer.But there is another way to solve this problem.You can download the package named future,such as pip install future.And in your .py file input this "from past.builtins import xrange".This method is for the situation that there are many xranges in your file.

Java - Opposite of .contains (does not contain)

It seems that Luiggi Mendoza and joey rohan both already answered this, but I think it can be clarified a little.

You can write it as a single if statement:

if (inventory.contains("bread") && !inventory.contains("water")) {
    // do something
}

AngularJS: How do I manually set input to $valid in controller?

It is very simple. For example : in you JS controller use this:

$scope.inputngmodel.$valid = false;

or

$scope.inputngmodel.$invalid = true;

or

$scope.formname.inputngmodel.$valid = false;

or

$scope.formname.inputngmodel.$invalid = true;

All works for me for different requirement. Hit up if this solve your problem.

How to combine results of two queries into a single dataset

I think you are after something like this; (Using row_number() with CTE and performing a FULL OUTER JOIN )

Fiddle example

;with t1 as (
  select col1,col2, row_number() over (order by col1) rn
  from table1 
),
t2 as (
  select col3,col4, row_number() over (order by col3) rn
  from table2
)
select col1,col2,col3,col4
from t1 full outer join t2 on t1.rn = t2.rn

Tables and data :

create table table1 (col1 int, col2 int)
create table table2 (col3 int, col4 int)

insert into table1 values
(1,2),(3,4)

insert into table2 values
(10,11),(30,40),(50,60)

Results :

|   COL1 |   COL2 | COL3 | COL4 |
---------------------------------
|      1 |      2 |   10 |   11 |
|      3 |      4 |   30 |   40 |
| (null) | (null) |   50 |   60 |

How do I fix a "Expected Primary-expression before ')' token" error?

showInventory(player);     // I get the error here.

void showInventory(player& obj) {   // By Johnny :D

this means that player is an datatype and showInventory expect an referance to an variable of type player.

so the correct code will be

  void showInventory(player& obj) {   // By Johnny :D
    for(int i = 0; i < 20; i++) {
        std::cout << "\nINVENTORY:\n" + obj.getItem(i);
        i++;
        std::cout << "\t\t\t" + obj.getItem(i) + "\n";
        i++;
    }
    }

players myPlayers[10];

    std::string toDo() //BY KEATON
    {
    std::string commands[5] =   // This is the valid list of commands.
        {"help", "inv"};

    std::string ans;
    std::cout << "\nWhat do you wish to do?\n>> ";
    std::cin >> ans;

    if(ans == commands[0]) {
        helpMenu();
        return NULL;
    }
    else if(ans == commands[1]) {
        showInventory(myPlayers[0]);     // or any other index,also is not necessary to have an array
        return NULL;
    }

}

How to programmatically add controls to a form in VB.NET

Yes.

Private Sub MyForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim MyTextbox as New Textbox
    With MyTextbox
       .Size = New Size(100,20)
       .Location = New Point(20,20)
    End With
    AddHandler MyTextbox.TextChanged, AddressOf MyTextbox_Changed
    Me.Controls.Add(MyTextbox)

'Without a help environment for an intelli sense substitution
'the address name and the methods name
'cannot be wrote in exchange for each other.
'Until an equality operation is prior for an exchange i have to work
'on an as is base substituted.

End Sub

Friend Sub MyTextbox_Changed(sender as Object, e as EventArgs)
   'Write code here.
End Sub

NoSQL Use Case Scenarios or WHEN to use NoSQL

I think Nosql is "more suitable" in these scenarios at least (more supplementary is welcome)

  1. Easy to scale horizontally by just adding more nodes.

  2. Query on large data set

    Imagine tons of tweets posted on twitter every day. In RDMS, there could be tables with millions (or billions?) of rows, and you don't want to do query on those tables directly, not even mentioning, most of time, table joins are also needed for complex queries.

  3. Disk I/O bottleneck

    If a website needs to send results to different users based on users' real-time info, we are probably talking about tens or hundreds of thousands of SQL read/write requests per second. Then disk i/o will be a serious bottleneck.

Chaining multiple filter() in Django, is this a bug?

The way I understand it is that they are subtly different by design (and I am certainly open for correction): filter(A, B) will first filter according to A and then subfilter according to B, while filter(A).filter(B) will return a row that matches A 'and' a potentially different row that matches B.

Look at the example here:

https://docs.djangoproject.com/en/dev/topics/db/queries/#spanning-multi-valued-relationships

particularly:

Everything inside a single filter() call is applied simultaneously to filter out items matching all those requirements. Successive filter() calls further restrict the set of objects

...

In this second example (filter(A).filter(B)), the first filter restricted the queryset to (A). The second filter restricted the set of blogs further to those that are also (B). The entries select by the second filter may or may not be the same as the entries in the first filter.`

How to solve javax.net.ssl.SSLHandshakeException Error?

Whenever we are trying to connect to URL,

if server at the other site is running on https protocol and is mandating that we should communicate via information provided in certificate then we have following option:

1) ask for the certificate(download the certificate), import this certificate in trustore. Default trustore java uses can be found in \Java\jdk1.6.0_29\jre\lib\security\cacerts, then if we retry to connect to the URL connection would be accepted.

2) In normal business cases, we might be connecting to internal URLS in organizations and we know that they are correct. In such cases, you trust that it is the correct URL, In such cases above, code can be used which will not mandate to store the certificate to connect to particular URL.

for the point no 2 we have to follow below steps :

1) write below method which sets HostnameVerifier for HttpsURLConnection which returns true for all cases meaning we are trusting the trustStore.

  // trusting all certificate 
 public void doTrustToCertificates() throws Exception {
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }

                    public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException {
                        return;
                    }

                    public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException {
                        return;
                    }
                }
        };

        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HostnameVerifier hv = new HostnameVerifier() {
            public boolean verify(String urlHostName, SSLSession session) {
                if (!urlHostName.equalsIgnoreCase(session.getPeerHost())) {
                    System.out.println("Warning: URL host '" + urlHostName + "' is different to SSLSession host '" + session.getPeerHost() + "'.");
                }
                return true;
            }
        };
        HttpsURLConnection.setDefaultHostnameVerifier(hv);
    }

2) write below method, which calls doTrustToCertificates before trying to connect to URL

    // connecting to URL
    public void connectToUrl(){
     doTrustToCertificates();//  
     URL url = new URL("https://www.example.com");
     HttpURLConnection conn = (HttpURLConnection)url.openConnection(); 
     System.out.println("ResponseCode ="+conn.getResponseCode());
   }

This call will return response code = 200 means connection is successful.

For more detail and sample example you can refer to URL.

Javascript Get Values from Multiple Select Option Box

Take a look at HTMLSelectElement.selectedOptions.

HTML

<select name="north-america" multiple>
  <option valud="ca" selected>Canada</a>
  <option value="mx" selected>Mexico</a>
  <option value="us">USA</a>
</select>

JavaScript

var elem = document.querySelector("select");

console.log(elem.selectedOptions);
//=> HTMLCollection [<option value="ca">Canada</option>, <option value="mx">Mexico</option>]

This would also work on non-multiple <select> elements


Warning: Support for this selectedOptions seems pretty unknown at this point

How do I write a method to calculate total cost for all items in an array?

The total of 7 numbers in an array can be created as:

import java.util.*;
class Sum
{
   public static void main(String arg[])
   {
     int a[]=new int[7];
     int total=0;
     Scanner n=new Scanner(System.in);
     System.out.println("Enter the no. for total");

     for(int i=0;i<=6;i++) 
     {
       a[i]=n.nextInt();
       total=total+a[i];
      }
       System.out.println("The total is :"+total);
    }
}

SqlException from Entity Framework - New transaction is not allowed because there are other threads running in the session

Indeed you cannot save changes inside a foreach loop in C# using Entity Framework.

context.SaveChanges() method acts like a commit on a regular database system (RDMS).

Just make all changes (which Entity Framework will cache) and then save all of them at once calling SaveChanges() after the loop (outside of it), like a database commit command.

This works if you can save all changes at once.

Replace Default Null Values Returned From Left Outer Join

That's as easy as

IsNull(FieldName, 0)

Or more completely:

SELECT iar.Description, 
  ISNULL(iai.Quantity,0) as Quantity, 
  ISNULL(iai.Quantity * rpl.RegularPrice,0) as 'Retail', 
  iar.Compliance 
FROM InventoryAdjustmentReason iar
LEFT OUTER JOIN InventoryAdjustmentItem iai  on (iar.Id = iai.InventoryAdjustmentReasonId)
LEFT OUTER JOIN Item i on (i.Id = iai.ItemId)
LEFT OUTER JOIN ReportPriceLookup rpl on (rpl.SkuNumber = i.SkuNo)
WHERE iar.StoreUse = 'yes'

How to sort an array of associative arrays by value of a given key in PHP?

You might try to define your own comparison function and then use usort.

How can I change NULL to 0 when getting a single value from a SQL function?

SELECT 0+COALESCE(SUM(Price),0) AS TotalPrice
FROM Inventory
WHERE (DateAdded BETWEEN @StartDate AND @EndDate)

How to Count Duplicates in List with LINQ

Slightly shorter version using methods chain:

var list = new List<string> {"a", "b", "a", "c", "a", "b"};
var q = list.GroupBy(x => x)
            .Select(g => new {Value = g.Key, Count = g.Count()})
            .OrderByDescending(x=>x.Count);

foreach (var x in q)
{
    Console.WriteLine("Value: " + x.Value + " Count: " + x.Count);
}

ASP.NET MVC - passing parameters to the controller

Using the ASP.NET Core Tag Helper feature:

<a asp-controller="Home" asp-action="SetLanguage" asp-route-yourparam1="@item.Value">@item.Text</a>

How to get base URL in Web API controller?

You could use VirtualPathRoot property from HttpRequestContext (request.GetRequestContext().VirtualPathRoot)

How to not wrap contents of a div?

If your div has a fixed-width it shouldn't expand, because you've fixed its width. However, modern browsers support a min-width CSS property.

You can emulate the min-width property in old IE browsers by using CSS expressions or by using auto width and having a spacer object in the container. This solution isn't elegant but may do the trick:

<div id="container" style="float: left">
  <div id="spacer" style="height: 1px; width: 300px"></div>
  <button>Button 1 text</button>
  <button>Button 2 text</button>
</div>

Resync git repo with new .gitignore file

I might misunderstand, but are you trying to delete files newly ignored or do you want to ignore new modifications to these files ? In this case, the thing is working.

If you want to delete ignored files previously commited, then use

git rm –cached `git ls-files -i –exclude-standard`
git commit -m 'clean up'

Intellij idea cannot resolve anything in maven

I have just had this issue when adding <dependency>...</dependency> elements to a <profile>. I just found that if I add (insert) the unresolved dependency elements to the <dependencies> element, the dependencies are downloaded from the maven repository; I can then remove the dependency element from the dependencies element.

How to append something to an array?

If arr is an array, and val is the value you wish to add use:

arr.push(val);

E.g.

_x000D_
_x000D_
var arr = ['a', 'b', 'c'];_x000D_
arr.push('d');_x000D_
console.log(arr);
_x000D_
_x000D_
_x000D_

Android Get Current timestamp?

I suggest using Hits's answer, but adding a Locale format, this is how Android Developers recommends:

try {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        return dateFormat.format(new Date()); // Find todays date
    } catch (Exception e) {
        e.printStackTrace();

        return null;
    }

Center Align on a Absolutely Positioned Div

I was having the same issue, and my limitation was that i cannot have a predefined width. If your element does not have a fixed width, then try this

div#thing 
{ 
  position: absolute; 
  top: 0px; 
  z-index: 2; 
  left:0;
  right:0;
 }

div#thing-body
{
  text-align:center;
}

then modify your html to look like this

<div id="thing">
 <div id="thing-child">
  <p>text text text with no fixed size, variable font</p>
 </div>
</div>

form confirm before submit

var r = confirm('Want to delete ?'); 

if (r == true) { 
    $('#admin-category-destroy').submit(); 
}

How do I get the current Date/time in DD/MM/YYYY HH:MM format?

time = Time.now.to_s

time = DateTime.parse(time).strftime("%d/%m/%Y %H:%M")

for increment decrement month use << >> operators

examples

datetime_month_before = DateTime.parse(time) << 1



datetime_month_before = DateTime.now << 1

FCM getting MismatchSenderId

As per response "MismatchSenderId", this is a mismatch between FireBase and your local "google-services.json", you have to make sure that both manifests matches

In FireBase console you go to "YourProject > Project OverView > Cloud Messaging" you'll see the "SenderID" which MUST match with the "google-services.json" in your Android project.

Best thing you can do is download the final json file from "General" tab and place it in your project.

How to tell bash that the line continues on the next line

\ does the job. @Guillaume's answer and @George's comment clearly answer this question. Here I explains why The backslash has to be the very last character before the end of line character. Consider this command:

   mysql -uroot \
   -hlocalhost      

If there is a space after \, the line continuation will not work. The reason is that \ removes the special meaning for the next character which is a space not the invisible line feed character. The line feed character is after the space not \ in this example.

The type java.lang.CharSequence cannot be resolved in package declaration

Just trying to compile with ant, Have same error when using org.eclipse.jdt.core-3.5.2.v_981_R35x.jar, Everything is well after upgrade to org.eclipse.jdt.core_3.10.2.v20150120-1634.jar

how to count the total number of lines in a text file using python

I am not new to stackoverflow, just never had an account and usually came here for answers. I can't comment or vote up an answer yet. BUT wanted to say that the code from Michael Bacon above works really well. I am new to Python but not to programming. I have been reading Python Crash Course and there are a few things I wanted to do to break up the reading cover to cover approach. One utility that has uses from an ETL or even data quality perspective would be to capture the row count of a file independently from any ETL. The file has X number of rows, you import into SQL or Hadoop and you end up with X number of rows. You can validate at the lowest level the row count of a raw data file.

I have been playing with his code and doing some testing and this code is very efficient so far. I have created several different CSV files, various sizes, and row counts. You can see my code below and my comments provide the times and details. The code Michael Bacon above provided runs about 6 times faster than the normal Python method of just looping the lines.

Hope this helps someone.


 import time
from itertools import (takewhile,repeat)

def readfilesimple(myfile):

    # watch me whip
    linecounter = 0
    with open(myfile,'r') as file_object:
        # watch me nae nae
         for lines in file_object:
            linecounter += 1

    return linecounter

def readfileadvanced(myfile):

    # watch me whip
    f = open(myfile, 'rb')
    # watch me nae nae
    bufgen = takewhile(lambda x: x, (f.raw.read(1024 * 1024) for _ in repeat(None)))
    return sum(buf.count(b'\n') for buf in bufgen if buf)
    #return linecounter


# ************************************
# Main
# ************************************

#start the clock

start_time = time.time()

# 6.7 seconds to read a 475MB file that has 24 million rows and 3 columns
#mycount = readfilesimple("c:/junk/book1.csv")

# 0.67 seconds to read a 475MB file that has 24 million rows and 3 columns
#mycount = readfileadvanced("c:/junk/book1.csv")

# 25.9 seconds to read a 3.9Gb file that has 3.25 million rows and 104 columns
#mycount = readfilesimple("c:/junk/WideCsvExample/ReallyWideReallyBig1.csv")

# 5.7 seconds to read a 3.9Gb file that has 3.25 million rows and 104 columns
#mycount = readfileadvanced("c:/junk/WideCsvExample/ReallyWideReallyBig1.csv")


# 292.92 seconds to read a 43Gb file that has 35.7 million rows and 104 columns
mycount = readfilesimple("c:/junk/WideCsvExample/ReallyWideReallyBig.csv")

# 57 seconds to read a 43Gb file that has 35.7 million rows and 104 columns
#mycount = readfileadvanced("c:/junk/WideCsvExample/ReallyWideReallyBig.csv")


#stop the clock
elapsed_time = time.time() - start_time


print("\nCode Execution: " + str(elapsed_time) + " seconds\n")
print("File contains: " + str(mycount) + " lines of text.")

How to sort findAll Doctrine's method?

You need to use a criteria, for example:

<?php

namespace Bundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Doctrine\Common\Collections\Criteria;

/**
* Thing controller
*/
class ThingController extends Controller
{
    public function thingsAction(Request $request, $id)
    {
        $ids=explode(',',$id);
        $criteria = new Criteria(null, <<DQL ordering expression>>, null, null );

        $rep    = $this->getDoctrine()->getManager()->getRepository('Bundle:Thing');
        $things = $rep->matching($criteria);
        return $this->render('Bundle:Thing:things.html.twig', [
            'entities' => $things,
        ]);
    }
}

Count unique values with pandas per groups

You need nunique:

df = df.groupby('domain')['ID'].nunique()

print (df)
domain
'facebook.com'    1
'google.com'      1
'twitter.com'     2
'vk.com'          3
Name: ID, dtype: int64

If you need to strip ' characters:

df = df.ID.groupby([df.domain.str.strip("'")]).nunique()
print (df)
domain
facebook.com    1
google.com      1
twitter.com     2
vk.com          3
Name: ID, dtype: int64

Or as Jon Clements commented:

df.groupby(df.domain.str.strip("'"))['ID'].nunique()

You can retain the column name like this:

df = df.groupby(by='domain', as_index=False).agg({'ID': pd.Series.nunique})
print(df)
    domain  ID
0       fb   1
1      ggl   1
2  twitter   2
3       vk   3

The difference is that nunique() returns a Series and agg() returns a DataFrame.

How to import a JSON file in ECMAScript 6?

importing JSON files are still experimental. It can be supported via the below flag.

--experimental-json-modules

otherwise you can load your JSON file relative to import.meta.url with fs directly:-

import { readFile } from 'fs/promises';
const config = JSON.parse(await readFile(new URL('../config.json', import.meta.url)));

you can also use module.createRequire()

import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const config = require('../config.json');

Find all files in a folder

You can try with Directory.GetFiles and fix your pattern

 string[] files = Directory.GetFiles(@"c:\", "*.txt");

 foreach (string file in files)
 {
    File.Copy(file, "....");
 }

 Or Move

 foreach (string file in files)
 {
    File.Move(file, "....");
 }     

http://msdn.microsoft.com/en-us/library/wz42302f

Eclipse compilation error: The hierarchy of the type 'Class name' is inconsistent

It means you are trying to implement a non-existing interface or you're extending an non-existing class.

Try to refresh your Eclipse.

If it doesn't work, it may mean that you have a reference to a JAR that is not in the build path. Check your project's classpath and verify that the jar containing the interface or the class is in it.

How to change resolution (DPI) of an image?

This article talks about modifying the EXIF data without the re-saving/re-compressing (and thus loss of information -- it actually uses a "trick"; there may be more direct libraries) required by the SetResolution approach. This was found on a quick google search, but I wanted to point out that all you need to do is modify the stored EXIF data.

Also: .NET lib for EXIF modification and another SO question. Google owns when you know good search terms.

What's the right way to create a date in Java?

The excellent joda-time library is almost always a better choice than Java's Date or Calendar classes. Here's a few examples:

DateTime aDate = new DateTime(year, month, day, hour, minute, second);
DateTime anotherDate = new DateTime(anotherYear, anotherMonth, anotherDay, ...);
if (aDate.isAfter(anotherDate)) {...}
DateTime yearFromADate = aDate.plusYears(1);

Node.js: printing to console without a trailing newline?

In Windows console (Linux, too), you should replace '\r' with its equivalent code \033[0G:

process.stdout.write('ok\033[0G');

This uses a VT220 terminal escape sequence to send the cursor to the first column.

how to find seconds since 1970 in java

Since Java8:

java.time.Instant.now().getEpochSecond()

Linq Query Group By and Selecting First Items

See LINQ: How to get the latest/last record with a group by clause

var firstItemsInGroup = from b in mainButtons
                 group b by b.category into g
select g.First();

I assume that mainButtons are already sorted correctly.

If you need to specify custom sort order, use OrderBy override with Comparer.

var firstsByCompareInGroups = from p in rows
        group p by p.ID into grp
        select grp.OrderBy(a => a, new CompareRows()).First();

See an example in my post "Select First Row In Group using Custom Comparer"

Javascript + Regex = Nothing to repeat error?

Well, in my case I had to test a Phone Number with the help of regex, and I was getting the same error,

Invalid regular expression: /+923[0-9]{2}-(?!1234567)(?!1111111)(?!7654321)[0-9]{7}/: Nothing to repeat'

So, what was the error in my case was that + operator after the / in the start of the regex. So enclosing the + operator with square brackets [+], and again sending the request, worked like a charm.

Following will work:

/[+]923[0-9]{2}-(?!1234567)(?!1111111)(?!7654321)[0-9]{7}/

This answer may be helpful for those, who got the same type of error, but their chances of getting the error from this point of view, as mine! Cheers :)

CSS override rules and specificity

The specificity is calculated based on the amount of id, class and tag selectors in your rule. Id has the highest specificity, then class, then tag. Your first rule is now more specific than the second one, since they both have a class selector, but the first one also has two tag selectors.

To make the second one override the first one, you can make more specific by adding information of it's parents:

table.rule1 tr td.rule2 {
    background-color: #ffff00;
}

Here is a nice article for more information on selector precedence.

Why would I use dirname(__FILE__) in an include or include_once statement?

Let's say I have a (fake) directory structure like:

.../root/
        /app
            bootstrap.php
        /scripts
            something/
                somescript.php
        /public
            index.php

Now assume that bootstrap.php has some code included for setting up database connections or some other kind of boostrapping stuff.

Assume you want to include a file in boostrap.php's folder called init.php. Now, to avoid scanning the entire include path with include 'init.php', you could use include './init.php'.

There's a problem though. That ./ will be relative to the script that included bootstrap.php, not bootstrap.php. (Technically speaking, it will be relative to the working directory.)

dirname(__FILE__) allows you to get an absolute path (and thus avoid an include path search) without relying on the working directory being the directory in which bootstrap.php resides.

(Note: since PHP 5.3, you can use __DIR__ in place of dirname(__FILE__).)

Now, why not just use include 'init.php';?

As odd as it is at first though, . is not guaranteed to be in the include path. Sometimes to avoid useless stat()'s people remove it from the include path when they are rarely include files in the same directory (why search the current directory when you know includes are never going to be there?).

Note: About half of this answer is address in a rather old post: What's better of require(dirname(__FILE__).'/'.'myParent.php') than just require('myParent.php')?

Is it possible to run a .NET 4.5 app on XP?

The Mono project dropped Windows XP support and "forgot" to mention it. Although they still claim Windows XP SP2 is the minimum supported version, it is actually Windows Vista.

The last version of Mono to support Windows XP was 3.2.3.

Does VBA contain a comment block syntax?

Although there isn't a syntax, you can still get close by using the built-in block comment buttons:

If you're not viewing the Edit toolbar already, right-click on the toolbar and enable the Edit toolbar:

enter image description here

Then, select a block of code and hit the "Comment Block" button; or if it's already commented out, use the "Uncomment Block" button:

enter image description here

Fast and easy!

z-index issue with twitter bootstrap dropdown menu

Ran into the same bug here. This worked for me.

.navbar {
    position: static;
}

By setting the position to static, it means the navbar will fall into the flow of the document as it normally would.

python - if not in list

You better do this syntax

if not (item in mylist):  
    Code inside the if

Lombok annotations do not compile under Intellij idea

Make sure these two requirements are satisfied:

  1. Enable annotation processing,

    Preferences > Build, Execution, Deployment > Compiler > Annotation Processors > Enable annotation processing

  2. Lombok plugin is installed and enabled for your project.

Why shouldn't I use PyPy over CPython if PyPy is 6.3 times faster?

Q: If PyPy can solve these great challenges (speed, memory consumption, parallelism) in comparison to CPython, what are its weaknesses that are preventing wider adoption?

A: First, there is little evidence that the PyPy team can solve the speed problem in general. Long-term evidence is showing that PyPy runs certain Python codes slower than CPython and this drawback seems to be rooted very deeply in PyPy.

Secondly, the current version of PyPy consumes much more memory than CPython in a rather large set of cases. So PyPy didn't solve the memory consumption problem yet.

Whether PyPy solves the mentioned great challenges and will in general be faster, less memory hungry, and more friendly to parallelism than CPython is an open question that cannot be solved in the short term. Some people are betting that PyPy will never be able to offer a general solution enabling it to dominate CPython 2.7 and 3.3 in all cases.

If PyPy succeeds to be better than CPython in general, which is questionable, the main weakness affecting its wider adoption will be its compatibility with CPython. There also exist issues such as the fact that CPython runs on a wider range of CPUs and OSes, but these issues are much less important compared to PyPy's performance and CPython-compatibility goals.


Q: Why can't I do drop in replacement of CPython with PyPy now?

A: PyPy isn't 100% compatible with CPython because it isn't simulating CPython under the hood. Some programs may still depend on CPython's unique features that are absent in PyPy such as C bindings, C implementations of Python object&methods, or the incremental nature of CPython's garbage collector.

Asp.net - <customErrors mode="Off"/> error when trying to access working webpage

For example in my case I accidentaly changed role of some users to incorrect, and my application got error during starting (NullReferenceException). When I fixed it - the app starts fine.

How to define dimens.xml for every different screen size in android?

You have to create Different values folder for different screens . Like

values-sw720dp          10.1” tablet 1280x800 mdpi

values-sw600dp          7.0”  tablet 1024x600 mdpi

values-sw480dp          5.4”  480x854 mdpi 
values-sw480dp          5.1”  480x800 mdpi 

values-xxhdpi           5.5"  1080x1920 xxhdpi
values-xxxhdpi           5.5" 1440x2560 xxxhdpi

values-xhdpi            4.7”   1280x720 xhdpi 
values-xhdpi            4.65”  720x1280 xhdpi 

values-hdpi             4.0” 480x800 hdpi
values-hdpi             3.7” 480x854 hdpi

values-mdpi             3.2” 320x480 mdpi

values-ldpi             3.4” 240x432 ldpi
values-ldpi             3.3” 240x400 ldpi
values-ldpi             2.7” 240x320 ldpi

enter image description here

For more information you may visit here

Different values folders in android

http://android-developers.blogspot.in/2011/07/new-tools-for-managing-screen-sizes.html

Edited By @humblerookie

You can make use of Android Studio plugin called Dimenify to auto generate dimension values for other pixel buckets based on custom scale factors. Its still in beta, be sure to notify any issues/suggestions you come across to the developer.

Add st, nd, rd and th (ordinal) suffix to a number

The rules are as follows:

  • st is used with numbers ending in 1 (e.g. 1st, pronounced first)
  • nd is used with numbers ending in 2 (e.g. 92nd, pronounced ninety-second)
  • rd is used with numbers ending in 3 (e.g. 33rd, pronounced thirty-third)
  • As an exception to the above rules, all the "teen" numbers ending with 11, 12 or 13 use -th (e.g. 11th, pronounced eleventh, 112th, pronounced one hundred [and] twelfth)
  • th is used for all other numbers (e.g. 9th, pronounced ninth).

The following JavaScript code (rewritten in Jun '14) accomplishes this:

function ordinal_suffix_of(i) {
    var j = i % 10,
        k = i % 100;
    if (j == 1 && k != 11) {
        return i + "st";
    }
    if (j == 2 && k != 12) {
        return i + "nd";
    }
    if (j == 3 && k != 13) {
        return i + "rd";
    }
    return i + "th";
}

Sample output for numbers between 0-115:

  0  0th
  1  1st
  2  2nd
  3  3rd
  4  4th
  5  5th
  6  6th
  7  7th
  8  8th
  9  9th
 10  10th
 11  11th
 12  12th
 13  13th
 14  14th
 15  15th
 16  16th
 17  17th
 18  18th
 19  19th
 20  20th
 21  21st
 22  22nd
 23  23rd
 24  24th
 25  25th
 26  26th
 27  27th
 28  28th
 29  29th
 30  30th
 31  31st
 32  32nd
 33  33rd
 34  34th
 35  35th
 36  36th
 37  37th
 38  38th
 39  39th
 40  40th
 41  41st
 42  42nd
 43  43rd
 44  44th
 45  45th
 46  46th
 47  47th
 48  48th
 49  49th
 50  50th
 51  51st
 52  52nd
 53  53rd
 54  54th
 55  55th
 56  56th
 57  57th
 58  58th
 59  59th
 60  60th
 61  61st
 62  62nd
 63  63rd
 64  64th
 65  65th
 66  66th
 67  67th
 68  68th
 69  69th
 70  70th
 71  71st
 72  72nd
 73  73rd
 74  74th
 75  75th
 76  76th
 77  77th
 78  78th
 79  79th
 80  80th
 81  81st
 82  82nd
 83  83rd
 84  84th
 85  85th
 86  86th
 87  87th
 88  88th
 89  89th
 90  90th
 91  91st
 92  92nd
 93  93rd
 94  94th
 95  95th
 96  96th
 97  97th
 98  98th
 99  99th
100  100th
101  101st
102  102nd
103  103rd
104  104th
105  105th
106  106th
107  107th
108  108th
109  109th
110  110th
111  111th
112  112th
113  113th
114  114th
115  115th

Description Box using "onmouseover"

Well, I made a simple two liner script for this, Its small and does what u want.

Check it http://jsfiddle.net/9RxLM/

Its a jquery solution :D

How would I get everything before a : in a string Python

You don't need regex for this

>>> s = "Username: How are you today?"

You can use the split method to split the string on the ':' character

>>> s.split(':')
['Username', ' How are you today?']

And slice out element [0] to get the first part of the string

>>> s.split(':')[0]
'Username'

How to generate sample XML documents from their DTD or XSD?

Liquid XML Studio has an XML Sample Generator wizard which will build sample XML files from an XML Schema. The resulting data seems to comply with the schema (it just can't generate data for regex patterns).

Generate an XML Sample from an XSD

Adding an arbitrary line to a matplotlib plot in ipython notebook

You can directly plot the lines you want by feeding the plot command with the corresponding data (boundaries of the segments):

plot([x1, x2], [y1, y2], color='k', linestyle='-', linewidth=2)

(of course you can choose the color, line width, line style, etc.)

From your example:

import numpy as np
import matplotlib.pyplot as plt

np.random.seed(5)
x = np.arange(1, 101)
y = 20 + 3 * x + np.random.normal(0, 60, 100)
plt.plot(x, y, "o")


# draw vertical line from (70,100) to (70, 250)
plt.plot([70, 70], [100, 250], 'k-', lw=2)

# draw diagonal line from (70, 90) to (90, 200)
plt.plot([70, 90], [90, 200], 'k-')

plt.show()

new chart

SimpleDateFormat and locale based format string

Java8

 import java.time.format.DateTimeFormatter;         
 myDate.format(DateTimeFormatter.ofPattern("dd-MMM-YYYY",new Locale("ar")))

Compile to stand alone exe for C# app in Visual Studio 2010

Are you sure you selected Console Application? I'm running VS 2010 and with the vanilla settings a C# console app builds to \bin\debug. Try to create a new Console Application project, with the language set to C#. Build the project, and go to Project/[Console Application 1]Properties. In the Build tab, what is the Output path? It should default to bin\debug, unless you have some restricted settings on your workstation,etc. Also review the build output window and see if any errors are being thrown - in which case nothing will be built to the output folder, of course...

Stop embedded youtube iframe?

Here's a pure javascript solution,

<iframe 
width="100%" 
height="443" 
class="yvideo" 
id="p1QgNF6J1h0"
src="http://www.youtube.com/embed/p1QgNF6J1h0?rel=0&controls=0&hd=1&showinfo=0&enablejsapi=1"
frameborder="0" 
allowfullscreen>
</iframe>
<button id="myStopClickButton">Stop</button>


<script>
document.getElementById("myStopClickButton").addEventListener("click",    function(evt){
var video = document.getElementsByClassName("yvideo");
for (var i=0; i<video.length; i++) {
   video.item(i).contentWindow.postMessage('{"event":"command","func":"stopVideo","args":""}', '*');
}

});

What causing this "Invalid length for a Base-64 char array"

This isn't an answer, sadly. After running into the intermittent error for some time and finally being annoyed enough to try to fix it, I have yet to find a fix. I have, however, determined a recipe for reproducing my problem, which might help others.

In my case it is SOLELY a localhost problem, on my dev machine that also has the app's DB. It's a .NET 2.0 app I'm editing with VS2005. The Win7 64 bit machine also has VS2008 and .NET 3.5 installed.

Here's what will generate the error, from a variety of forms:

  1. Load a fresh copy of the form.
  2. Enter some data, and/or postback with any of the form's controls. As long as there is no significant delay, repeat all you like, and no errors occur.
  3. Wait a little while (1 or 2 minutes maybe, not more than 5), and try another postback.

A minute or two delay "waiting for localhost" and then "Connection was reset" by the browser, and global.asax's application error trap logs:

Application_Error event: Invalid length for a Base-64 char array.
Stack Trace:
     at System.Convert.FromBase64String(String s)
     at System.Web.UI.ObjectStateFormatter.Deserialize(String inputString)
     at System.Web.UI.Util.DeserializeWithAssert(IStateFormatter formatter, String serializedState)
     at System.Web.UI.HiddenFieldPageStatePersister.Load()

In this case, it is not the SIZE of the viewstate, but something to do with page and/or viewstate caching that seems to be biting me. Setting <pages> parameters enableEventValidation="false", and viewStateEncryption="Never" in the Web.config did not change the behavior. Neither did setting the maxPageStateFieldLength to something modest.

Getting multiple keys of specified value of a generic Dictionary?

As I wanted a full fledged BiDirectional Dictionary (and not only a Map), I added the missing functions to make it an IDictionary compatible class. This is based on the version with unique Key-Value Pairs. Here's the file if desired (Most work was the XMLDoc through):

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

namespace Common
{
    /// <summary>Represents a bidirectional collection of keys and values.</summary>
    /// <typeparam name="TFirst">The type of the keys in the dictionary</typeparam>
    /// <typeparam name="TSecond">The type of the values in the dictionary</typeparam>
    [System.Runtime.InteropServices.ComVisible(false)]
    [System.Diagnostics.DebuggerDisplay("Count = {Count}")]
    //[System.Diagnostics.DebuggerTypeProxy(typeof(System.Collections.Generic.Mscorlib_DictionaryDebugView<,>))]
    //[System.Reflection.DefaultMember("Item")]
    public class BiDictionary<TFirst, TSecond> : Dictionary<TFirst, TSecond>
    {
        IDictionary<TSecond, TFirst> _ValueKey = new Dictionary<TSecond, TFirst>();
        /// <summary> PropertyAccessor for Iterator over KeyValue-Relation </summary>
        public IDictionary<TFirst, TSecond> KeyValue => this;
        /// <summary> PropertyAccessor for Iterator over ValueKey-Relation </summary>
        public IDictionary<TSecond, TFirst> ValueKey => _ValueKey;

        #region Implemented members

        /// <Summary>Gets or sets the value associated with the specified key.</Summary>
        /// <param name="key">The key of the value to get or set.</param>
        /// <Returns>The value associated with the specified key. If the specified key is not found,
        ///      a get operation throws a <see cref="KeyNotFoundException"/>, and
        ///      a set operation creates a new element with the specified key.</Returns>
        /// <exception cref="T:System.ArgumentNullException"><paramref name="key"/> is null.</exception>
        /// <exception cref="T:System.Collections.Generic.KeyNotFoundException">
        /// The property is retrieved and <paramref name="key"/> does not exist in the collection.</exception>
        /// <exception cref="T:System.ArgumentException"> An element with the same key already
        /// exists in the <see cref="ValueKey"/> <see cref="Dictionary&lt;TFirst,TSecond&gt;"/>.</exception>
        public new TSecond this[TFirst key]
        {
            get { return base[key]; }
            set { _ValueKey.Remove(base[key]); base[key] = value; _ValueKey.Add(value, key); }
        }

        /// <Summary>Gets or sets the key associated with the specified value.</Summary>
        /// <param name="val">The value of the key to get or set.</param>
        /// <Returns>The key associated with the specified value. If the specified value is not found,
        ///      a get operation throws a <see cref="KeyNotFoundException"/>, and
        ///      a set operation creates a new element with the specified value.</Returns>
        /// <exception cref="T:System.ArgumentNullException"><paramref name="val"/> is null.</exception>
        /// <exception cref="T:System.Collections.Generic.KeyNotFoundException">
        /// The property is retrieved and <paramref name="val"/> does not exist in the collection.</exception>
        /// <exception cref="T:System.ArgumentException"> An element with the same value already
        /// exists in the <see cref="KeyValue"/> <see cref="Dictionary&lt;TFirst,TSecond&gt;"/>.</exception>
        public TFirst this[TSecond val]
        {
            get { return _ValueKey[val]; }
            set { base.Remove(_ValueKey[val]); _ValueKey[val] = value; base.Add(value, val); }
        }

        /// <Summary>Adds the specified key and value to the dictionary.</Summary>
        /// <param name="key">The key of the element to add.</param>
        /// <param name="value">The value of the element to add.</param>
        /// <exception cref="T:System.ArgumentNullException"><paramref name="key"/> or <paramref name="value"/> is null.</exception>
        /// <exception cref="T:System.ArgumentException">An element with the same key or value already exists in the <see cref="Dictionary&lt;TFirst,TSecond&gt;"/>.</exception>
        public new void Add(TFirst key, TSecond value) {
            base.Add(key, value);
            _ValueKey.Add(value, key);
        }

        /// <Summary>Removes all keys and values from the <see cref="Dictionary&lt;TFirst,TSecond&gt;"/>.</Summary>
        public new void Clear() { base.Clear(); _ValueKey.Clear(); }

        /// <Summary>Determines whether the <see cref="Dictionary&lt;TFirst,TSecond&gt;"/> contains the specified
        ///      KeyValuePair.</Summary>
        /// <param name="item">The KeyValuePair to locate in the <see cref="Dictionary&lt;TFirst,TSecond&gt;"/>.</param>
        /// <Returns>true if the <see cref="Dictionary&lt;TFirst,TSecond&gt;"/> contains an element with
        ///      the specified key which links to the specified value; otherwise, false.</Returns>
        /// <exception cref="T:System.ArgumentNullException"><paramref name="item"/> is null.</exception>
        public bool Contains(KeyValuePair<TFirst, TSecond> item) => base.ContainsKey(item.Key) & _ValueKey.ContainsKey(item.Value);

        /// <Summary>Removes the specified KeyValuePair from the <see cref="Dictionary&lt;TFirst,TSecond&gt;"/>.</Summary>
        /// <param name="item">The KeyValuePair to remove.</param>
        /// <Returns>true if the KeyValuePair is successfully found and removed; otherwise, false. This
        ///      method returns false if <paramref name="item"/> is not found in the <see cref="Dictionary&lt;TFirst,TSecond&gt;"/>.</Returns>
        /// <exception cref="T:System.ArgumentNullException"><paramref name="item"/> is null.</exception>
        public bool Remove(KeyValuePair<TFirst, TSecond> item) => base.Remove(item.Key) & _ValueKey.Remove(item.Value);

        /// <Summary>Removes the value with the specified key from the <see cref="Dictionary&lt;TFirst,TSecond&gt;"/>.</Summary>
        /// <param name="key">The key of the element to remove.</param>
        /// <Returns>true if the element is successfully found and removed; otherwise, false. This
        ///      method returns false if <paramref name="key"/> is not found in the <see cref="Dictionary&lt;TFirst,TSecond&gt;"/>.</Returns>
        /// <exception cref="T:System.ArgumentNullException"><paramref name="key"/> is null.</exception>
        public new bool Remove(TFirst key) => _ValueKey.Remove(base[key]) & base.Remove(key);

        /// <Summary>Gets the key associated with the specified value.</Summary>
        /// <param name="value">The value of the key to get.</param>
        /// <param name="key">When this method returns, contains the key associated with the specified value,
        ///      if the value is found; otherwise, the default value for the type of the key parameter.
        ///      This parameter is passed uninitialized.</param>
        /// <Returns>true if <see cref="ValueKey"/> contains an element with the specified value; 
        ///      otherwise, false.</Returns>
        /// <exception cref="T:System.ArgumentNullException"><paramref name="value"/> is null.</exception>
        public bool TryGetValue(TSecond value, out TFirst key) => _ValueKey.TryGetValue(value, out key);
        #endregion
    }
}

Passing multiple parameters to pool.map() function in Python

You could use a map function that allows multiple arguments, as does the fork of multiprocessing found in pathos.

>>> from pathos.multiprocessing import ProcessingPool as Pool
>>> 
>>> def add_and_subtract(x,y):
...   return x+y, x-y
... 
>>> res = Pool().map(add_and_subtract, range(0,20,2), range(-5,5,1))
>>> res
[(-5, 5), (-2, 6), (1, 7), (4, 8), (7, 9), (10, 10), (13, 11), (16, 12), (19, 13), (22, 14)]
>>> Pool().map(add_and_subtract, *zip(*res))
[(0, -10), (4, -8), (8, -6), (12, -4), (16, -2), (20, 0), (24, 2), (28, 4), (32, 6), (36, 8)]

pathos enables you to easily nest hierarchical parallel maps with multiple inputs, so we can extend our example to demonstrate that.

>>> from pathos.multiprocessing import ThreadingPool as TPool
>>> 
>>> res = TPool().amap(add_and_subtract, *zip(*Pool().map(add_and_subtract, range(0,20,2), range(-5,5,1))))
>>> res.get()
[(0, -10), (4, -8), (8, -6), (12, -4), (16, -2), (20, 0), (24, 2), (28, 4), (32, 6), (36, 8)]

Even more fun, is to build a nested function that we can pass into the Pool. This is possible because pathos uses dill, which can serialize almost anything in python.

>>> def build_fun_things(f, g):
...   def do_fun_things(x, y):
...     return f(x,y), g(x,y)
...   return do_fun_things
... 
>>> def add(x,y):
...   return x+y
... 
>>> def sub(x,y):
...   return x-y
... 
>>> neato = build_fun_things(add, sub)
>>> 
>>> res = TPool().imap(neato, *zip(*Pool().map(neato, range(0,20,2), range(-5,5,1))))
>>> list(res)
[(0, -10), (4, -8), (8, -6), (12, -4), (16, -2), (20, 0), (24, 2), (28, 4), (32, 6), (36, 8)]

If you are not able to go outside of the standard library, however, you will have to do this another way. Your best bet in that case is to use multiprocessing.starmap as seen here: Python multiprocessing pool.map for multiple arguments (noted by @Roberto in the comments on the OP's post)

Get pathos here: https://github.com/uqfoundation

How to open a web page from my application?

I've been using this line to launch the default browser:

System.Diagnostics.Process.Start("http://www.google.com"); 

From an array of objects, extract value of a property as array

Here is a shorter way of achieving it:

let result = objArray.map(a => a.foo);

OR

let result = objArray.map(({ foo }) => foo)

You can also check Array.prototype.map().

function is not defined error in Python

Yes, but in what file is pyth_test's definition declared in? Is it also located before it's called?

Edit:

To put it into perspective, create a file called test.py with the following contents:

def pyth_test (x1, x2):
    print x1 + x2

pyth_test(1,2)

Now run the following command:

python test.py

You should see the output you desire. Now if you are in an interactive session, it should go like this:

>>> def pyth_test (x1, x2):
...     print x1 + x2
... 
>>> pyth_test(1,2)
3
>>> 

I hope this explains how the declaration works.


To give you an idea of how the layout works, we'll create a few files. Create a new empty folder to keep things clean with the following:

myfunction.py

def pyth_test (x1, x2):
    print x1 + x2 

program.py

#!/usr/bin/python

# Our function is pulled in here
from myfunction import pyth_test

pyth_test(1,2)

Now if you run:

python program.py

It will print out 3. Now to explain what went wrong, let's modify our program this way:

# Python: Huh? where's pyth_test?
# You say it's down there, but I haven't gotten there yet!
pyth_test(1,2)

# Our function is pulled in here
from myfunction import pyth_test

Now let's see what happens:

$ python program.py 
Traceback (most recent call last):
  File "program.py", line 3, in <module>
    pyth_test(1,2)
NameError: name 'pyth_test' is not defined

As noted, python cannot find the module for the reasons outlined above. For that reason, you should keep your declarations at top.

Now then, if we run the interactive python session:

>>> from myfunction import pyth_test
>>> pyth_test(1,2)
3

The same process applies. Now, package importing isn't all that simple, so I recommend you look into how modules work with Python. I hope this helps and good luck with your learnings!

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

Once you are in the directory of your project. use cd path/to/directory then use ng g c component_name --spec=false it automates everything and is error free

the g c means generate component

Using ng-if as a switch inside ng-repeat?

This one is noteworthy as well

<div ng-repeat="post in posts" ng-if="post.type=='article'">
  <h1>{{post.title}}</h1>
</div>

A long bigger than Long.MAX_VALUE

That method can't return true. That's the point of Long.MAX_VALUE. It would be really confusing if its name were... false. Then it should be just called Long.SOME_FAIRLY_LARGE_VALUE and have literally zero reasonable uses. Just use Android's isUserAGoat, or you may roll your own function that always returns false.

Note that a long in memory takes a fixed number of bytes. From Oracle:

long: The long data type is a 64-bit signed two's complement integer. It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive). Use this data type when you need a range of values wider than those provided by int.

As you may know from basic computer science or discrete math, there are 2^64 possible values for a long, since it is 64 bits. And as you know from discrete math or number theory or common sense, if there's only finitely many possibilities, one of them has to be the largest. That would be Long.MAX_VALUE. So you are asking something similar to "is there an integer that's >0 and < 1?" Mathematically nonsensical.

If you actually need this for something for real then use BigInteger class.

How to delete a whole folder and content?

Let me tell you first thing you cannot delete the DCIM folder because it is a system folder. As you delete it manually on phone it will delete the contents of that folder, but not the DCIM folder. You can delete its contents by using the method below:

Updated as per comments

File dir = new File(Environment.getExternalStorageDirectory()+"Dir_name_here"); 
if (dir.isDirectory()) 
{
    String[] children = dir.list();
    for (int i = 0; i < children.length; i++)
    {
       new File(dir, children[i]).delete();
    }
}

Get the number of rows in a HTML table

Well it depends on what you have in your table.

its one of the following If you have only one table

var count = $('#gvPerformanceResult tr').length;

If you are concerned about sub tables but this wont work with tbody and thead (if you use them)

var count = $('#gvPerformanceResult>tr').length;

Where by this will work (but is quite frankly overkill.)

var count = $('#gvPerformanceResult>tbody>tr').length;

Java best way for string find and replace?

When you dont want to put your hand yon regular expression (may be you should) you could first replace all "Milan Vasic" string with "Milan".

And than replace all "Milan" Strings with "Milan Vasic".

The Use of Multiple JFrames: Good or Bad Practice?

The multiple JFrame approach has been something I've implemented since I began programming Swing apps. For the most part, I did it in the beginning because I didn't know any better. However, as I matured in my experience and knowledge as a developer and as began to read and absorb the opinions of so many more experienced Java devs online, I made an attempt to shift away from the multiple JFrame approach (both in current projects and future projects) only to be met with... get this... resistance from my clients! As I began implementing modal dialogs to control "child" windows and JInternalFrames for separate components, my clients began to complain! I was quite surprised, as I was doing what I thought was best-practice! But, as they say, "A happy wife is a happy life." Same goes for your clients. Of course, I am a contractor so my end-users have direct access to me, the developer, which is obviously not a common scenario.

So, I'm going to explain the benefits of the multiple JFrame approach, as well as myth-bust some of the cons that others have presented.

  1. Ultimate flexibility in layout - By allowing separate JFrames, you give your end-user the ability to spread out and control what's on his/her screen. The concept feels "open" and non-constricting. You lose this when you go towards one big JFrame and a bunch of JInternalFrames.
  2. Works well for very modularized applications - In my case, most of my applications have 3 - 5 big "modules" that really have nothing to do with each other whatsoever. For instance, one module might be a sales dashboard and one might be an accounting dashboard. They don't talk to each other or anything. However, the executive might want to open both and them being separate frames on the taskbar makes his life easier.
  3. Makes it easy for end-users to reference outside material - Once, I had this situation: My app had a "data viewer," from which you could click "Add New" and it would open a data entry screen. Initially, both were JFrames. However, I wanted the data entry screen to be a JDialog whose parent was the data viewer. I made the change, and immediately I received a call from an end-user who relied heavily on the fact that he could minimize or close the viewer and keep the editor open while he referenced another part of the program (or a website, I don't remember). He's not on a multi-monitor, so he needed the entry dialog to be first and something else to be second, with the data viewer completely hidden. This was impossible with a JDialog and certainly would've been impossible with a JInternalFrame as well. I begrudgingly changed it back to being separate JFrames for his sanity, but it taught me an important lesson.
  4. Myth: Hard to code - This is not true in my experience. I don't see why it would be any easier to create a JInternalFrame than a JFrame. In fact, in my experience, JInternalFrames offer much less flexibility. I have developed a systematic way of handling the opening & closing of JFrames in my apps that really works well. I control the frame almost completely from within the frame's code itself; the creation of the new frame, SwingWorkers that control the retrieval of data on background threads and the GUI code on EDT, restoring/bringing to front the frame if the user tries to open it twice, etc. All you need to open my JFrames is call a public static method open() and the open method, combined with a windowClosing() event handles the rest (is the frame already open? is it not open, but loading? etc.) I made this approach a template so it's not difficult to implement for each frame.
  5. Myth/Unproven: Resource Heavy - I'd like to see some facts behind this speculative statement. Although, perhaps, you could say a JFrame needs more space than a JInternalFrame, even if you open up 100 JFrames, how many more resources would you really be consuming? If your concern is memory leaks because of resources: calling dispose() frees all resources used by the frame for garbage collection (and, again I say, a JInternalFrame should invoke exactly the same concern).

I've written a lot and I feel like I could write more. Anyways, I hope I don't get down-voted simply because it's an unpopular opinion. The question is clearly a valuable one and I hope I've provided a valuable answer, even if it isn't the common opinion.

A great example of multiple frames/single document per frame (SDI) vs single frame/multiple documents per frame (MDI) is Microsoft Excel. Some of MDI benefits:

  • it is possible to have a few windows in non rectangular shape - so they don't hide desktop or other window from another process (e.g. web browser)
  • it is possible to open a window from another process over one Excel window while writing in second Excel window - with MDI, trying to write in one of internal windows will give focus to the entire Excel window, hence hiding window from another process
  • it is possible to have different documents on different screens, which is especially useful when screens do not have the same resolution

SDI (Single-Document Interface, i.e., every window can only have a single document):

enter image description here

MDI (Multiple-Document Interface, i.e., every window can have multiple documents):

enter image description here

Convert pyspark string to date format

Update (1/10/2018):

For Spark 2.2+ the best way to do this is probably using the to_date or to_timestamp functions, which both support the format argument. From the docs:

>>> from pyspark.sql.functions import to_timestamp
>>> df = spark.createDataFrame([('1997-02-28 10:30:00',)], ['t'])
>>> df.select(to_timestamp(df.t, 'yyyy-MM-dd HH:mm:ss').alias('dt')).collect()
[Row(dt=datetime.datetime(1997, 2, 28, 10, 30))]

Original Answer (for Spark < 2.2)

It is possible (preferrable?) to do this without a udf:

from pyspark.sql.functions import unix_timestamp, from_unixtime

df = spark.createDataFrame(
    [("11/25/1991",), ("11/24/1991",), ("11/30/1991",)], 
    ['date_str']
)

df2 = df.select(
    'date_str', 
    from_unixtime(unix_timestamp('date_str', 'MM/dd/yyy')).alias('date')
)

print(df2)
#DataFrame[date_str: string, date: timestamp]

df2.show(truncate=False)
#+----------+-------------------+
#|date_str  |date               |
#+----------+-------------------+
#|11/25/1991|1991-11-25 00:00:00|
#|11/24/1991|1991-11-24 00:00:00|
#|11/30/1991|1991-11-30 00:00:00|
#+----------+-------------------+

Swift Set to Array

The current answer for Swift 2.x and higher (from the Swift Programming Language guide on Collection Types) seems to be to either iterate over the Set entries like so:

for item in myItemSet {
   ...
}

Or, to use the "sorted" method:

let itemsArray = myItemSet.sorted()

It seems the Swift designers did not like allObjects as an access mechanism because Sets aren't really ordered, so they wanted to make sure you didn't get out an array without an explicit ordering applied.

If you don't want the overhead of sorting and don't care about the order, I usually use the map or flatMap methods which should be a bit quicker to extract an array:

let itemsArray = myItemSet.map { $0 }

Which will build an array of the type the Set holds, if you need it to be an array of a specific type (say, entitles from a set of managed object relations that are not declared as a typed set) you can do something like:

var itemsArray : [MyObjectType] = []
if let typedSet = myItemSet as? Set<MyObjectType> {
 itemsArray = typedSet.map { $0 }
}

Twitter Bootstrap add active class to li

To activate the menus and submenus, even with params in the URL, use the code bellow:

// Highlight the active menu
$(document).ready(function () {
    var action = window.location.pathname.split('/')[1];

    // If there's no action, highlight the first menu item
    if (action == "") {
        $('ul.nav li:first').addClass('active');
    } else {
        // Highlight current menu
        $('ul.nav a[href="/' + action + '"]').parent().addClass('active');

        // Highlight parent menu item
        $('ul.nav a[href="/' + action + '"]').parents('li').addClass('active');
    }
});

This accepts URLs like:

/posts
/posts/1
/posts/1/edit

RegEx to make sure that the string contains at least one lower case char, upper case char, digit and symbol

If you need one single regex, try:

(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*\W)

A short explanation:

(?=.*[a-z])        // use positive look ahead to see if at least one lower case letter exists
(?=.*[A-Z])        // use positive look ahead to see if at least one upper case letter exists
(?=.*\d)           // use positive look ahead to see if at least one digit exists
(?=.*\W])        // use positive look ahead to see if at least one non-word character exists

And I agree with SilentGhost, \W might be a bit broad. I'd replace it with a character set like this: [-+_!@#$%^&*.,?] (feel free to add more of course!)

Definition of int64_t

int64_t is typedef you can find that in <stdint.h> in C

Floating point comparison functions for C#

Here's how I solved it, with nullable double extension method.

    public static bool NearlyEquals(this double? value1, double? value2, double unimportantDifference = 0.0001)
    {
        if (value1 != value2)
        {
            if(value1 == null || value2 == null)
                return false;

            return Math.Abs(value1.Value - value2.Value) < unimportantDifference;
        }

        return true;
    }

...

        double? value1 = 100;
        value1.NearlyEquals(100.01); // will return false
        value1.NearlyEquals(100.000001); // will return true
        value1.NearlyEquals(100.01, 0.1); // will return true

change type of input field with jQuery

I like this way, to change the type of an input element: old_input.clone().... Here is an example. There is an check box "id_select_multiple". If this is is changed to "selected", input elements with name "foo" should be changed to check boxes. If it gets unchecked, they should be become radio buttons again.

  $(function() {
    $("#id_select_multiple").change(function() {
     var new_type='';
     if ($(this).is(":checked")){ // .val() is always "on"
          new_type='checkbox';
     } else {
         new_type="radio";
     }
     $('input[name="foo"]').each(function(index){
         var new_input = $(this).clone();
         new_input.attr("type", new_type);
         new_input.insertBefore($(this));
         $(this).remove();
     });
    }
  )});

How can I write data attributes using Angular?

Use attribute binding syntax instead

<ol class="viewer-nav"><li *ngFor="let section of sections" 
    [attr.data-sectionvalue]="section.value">{{ section.text }}</li>  
</ol>

or

<ol class="viewer-nav"><li *ngFor="let section of sections" 
    attr.data-sectionvalue="{{section.value}}">{{ section.text }}</li>  
</ol>

See also :

Unable to connect to mongodb Error: couldn't connect to server 127.0.0.1:27017 at src/mongo/shell/mongo.js:L112

If you create data\db folder, firstly you must delete this folder then execute:

c:\mongodb\bin\mongo.exe 

Change the color of cells in one column when they don't match cells in another column

  1. Select your range from cell A (or the whole columns by first selecting column A). Make sure that the 'lighter coloured' cell is A1 then go to conditional formatting, new rule:

    enter image description here

  2. Put the following formula and the choice of your formatting (notice that the 'lighter coloured' cell comes into play here, because it is being used in the formula):

    =$A1<>$B1
    

    enter image description here

  3. Then press OK and that should do it.

    enter image description here

How to detect a docker daemon port

Since I also had the same problem of "How to detect a docker daemon port" however I had on OSX and after little digging in I found the answer. I thought to share the answer here for people coming from osx.

If you visit known-issues from docker for mac and github issue, you will find that by default the docker daemon only listens on unix socket /var/run/docker.sock and not on tcp. The default port for docker is 2375 (unencrypted) and 2376(encrypted) communication over tcp(although you can choose any other port).

On OSX its not straight forward to run the daemon on tcp port. To do this one way is to use socat container to redirect the Docker API exposed on the unix domain socket to the host port on OSX.

docker run -d -v /var/run/docker.sock:/var/run/docker.sock -p 127.0.0.1:2375:2375 bobrik/socat TCP-LISTEN:2375,fork UNIX-CONNECT:/var/run/docker.sock

and then

export DOCKER_HOST=tcp://localhost:2375

However for local client on mac os you don't need to export DOCKER_HOST variable to test the api.

android.view.InflateException: Binary XML file line #12: Error inflating class <unknown>

I had this problem just now and managed to figure out what it was. Was referencing a colour in my values that was causing problems. So defined it manually instead of using one from the dropdown suggestions.Then it worked!

Reading HTML content from a UIWebView

UIWebView

get HTML from UIWebView`

let content = uiWebView.stringByEvaluatingJavaScript(from: "document.body.innerHTML")

set HTML into UIWebView

//Do not forget to extend a class from `UIWebViewDelegate` and nil the delegate

func someFunction() {

    let uiWebView = UIWebView()
    uiWebView.loadHTMLString("<html><body></body></html>", baseURL: nil)
    uiWebView.delegate = self as? UIWebViewDelegate
}

func webViewDidFinishLoad(_ webView: UIWebView) {
    //ready to be processed
}

[get/set HTML from WKWebView]

How to format date and time in Android?

Use build in Time class!

Time time = new Time();
time.set(0, 0, 17, 4, 5, 1999);
Log.i("DateTime", time.format("%d.%m.%Y %H:%M:%S"));

Xcode: failed to get the task for process

If you've set the correct code signing certificate under Build Settings->Code Signing, then make sure you are also using the correct provisioning profile for Debug/Release mode as well.

I was having this issue because I was using an Ad-Hoc provisioning profile for both Debug/Release modes, which doesn't allow for a development profile to be used when doing a debug build.

Using IS NULL or IS NOT NULL on join conditions - Theory question

Your execution plan should make this clear; the JOIN takes precedence, after which the results are filtered.

header('HTTP/1.0 404 Not Found'); not doing anything

After writing

header('HTTP/1.0 404 Not Found');

add one more header for any inexisting page on your site. It works, for sure.

header("Location: http://yoursite/nowhere");
die;

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
})

Maximum size of a varchar(max) variable

As far as I can tell there is no upper limit in 2008.

In SQL Server 2005 the code in your question fails on the assignment to the @GGMMsg variable with

Attempting to grow LOB beyond maximum allowed size of 2,147,483,647 bytes.

the code below fails with

REPLICATE: The length of the result exceeds the length limit (2GB) of the target large type.

However it appears these limitations have quietly been lifted. On 2008

DECLARE @y VARCHAR(MAX) = REPLICATE(CAST('X' AS VARCHAR(MAX)),92681); 

SET @y = REPLICATE(@y,92681);

SELECT LEN(@y) 

Returns

8589767761

I ran this on my 32 bit desktop machine so this 8GB string is way in excess of addressable memory

Running

select internal_objects_alloc_page_count
from sys.dm_db_task_space_usage
WHERE session_id = @@spid

Returned

internal_objects_alloc_page_co 
------------------------------ 
2144456    

so I presume this all just gets stored in LOB pages in tempdb with no validation on length. The page count growth was all associated with the SET @y = REPLICATE(@y,92681); statement. The initial variable assignment to @y and the LEN calculation did not increase this.

The reason for mentioning this is because the page count is hugely more than I was expecting. Assuming an 8KB page then this works out at 16.36 GB which is obviously more or less double what would seem to be necessary. I speculate that this is likely due to the inefficiency of the string concatenation operation needing to copy the entire huge string and append a chunk on to the end rather than being able to add to the end of the existing string. Unfortunately at the moment the .WRITE method isn't supported for varchar(max) variables.

Addition

I've also tested the behaviour with concatenating nvarchar(max) + nvarchar(max) and nvarchar(max) + varchar(max). Both of these allow the 2GB limit to be exceeded. Trying to then store the results of this in a table then fails however with the error message Attempting to grow LOB beyond maximum allowed size of 2147483647 bytes. again. The script for that is below (may take a long time to run).

DECLARE @y1 VARCHAR(MAX) = REPLICATE(CAST('X' AS VARCHAR(MAX)),2147483647); 
SET @y1 = @y1 + @y1;
SELECT LEN(@y1), DATALENGTH(@y1)  /*4294967294, 4294967292*/


DECLARE @y2 NVARCHAR(MAX) = REPLICATE(CAST('X' AS NVARCHAR(MAX)),1073741823); 
SET @y2 = @y2 + @y2;
SELECT LEN(@y2), DATALENGTH(@y2)  /*2147483646, 4294967292*/


DECLARE @y3 NVARCHAR(MAX) = @y2 + @y1
SELECT LEN(@y3), DATALENGTH(@y3)   /*6442450940, 12884901880*/

/*This attempt fails*/
SELECT @y1 y1, @y2 y2, @y3 y3
INTO Test

jquery 3.0 url.indexOf error

Better approach may be a polyfill like this

jQuery.fn.load = function(callback){ $(window).on("load", callback) };

With this you can leave the legacy code untouched. If you use webpack be sure to use script-loader.

How to use workbook.saveas with automatic Overwrite

To split the difference of opinion

I prefer:

   xls.DisplayAlerts = False    
   wb.SaveAs fullFilePath, AccessMode:=xlExclusive, ConflictResolution:=xlLocalSessionChanges
   xls.DisplayAlerts = True

PHP - Modify current object in foreach loop

Surely using array_map and if using a container implementing ArrayAccess to derive objects is just a smarter, semantic way to go about this?

Array map semantics are similar across most languages and implementations that I've seen. It's designed to return a modified array based upon input array element (high level ignoring language compile/runtime type preference); a loop is meant to perform more logic.

For retrieving objects by ID / PK, depending upon if you are using SQL or not (it seems suggested), I'd use a filter to ensure I get an array of valid PK's, then implode with comma and place into an SQL IN() clause to return the result-set. It makes one call instead of several via SQL, optimising a bit of the call->wait cycle. Most importantly my code would read well to someone from any language with a degree of competence and we don't run into mutability problems.

<?php

$arr = [0,1,2,3,4];
$arr2 = array_map(function($value) { return is_int($value) ? $value*2 : $value; }, $arr);
var_dump($arr);
var_dump($arr2);

vs

<?php

$arr = [0,1,2,3,4];
foreach($arr as $i => $item) {
    $arr[$i] = is_int($item) ? $item * 2 : $item;
}
var_dump($arr);

If you know what you are doing will never have mutability problems (bearing in mind if you intend upon overwriting $arr you could always $arr = array_map and be explicit.

Duplicate / Copy records in the same MySQL table

You KNOW for sure, that the DUPLICATE KEY will trigger, thus you can select the MAX(ID)+1 beforehand:

INSERT INTO invoices SELECT MAX(ID)+1, ... other fields ... FROM invoices AS iv WHERE iv.ID=XXXXX 

Does calling clone() on an array also clone its contents?

clone() creates a shallow copy. Which means the elements will not be cloned. (What if they didn't implement Cloneable?)

You may want to use Arrays.copyOf(..) for copying arrays instead of clone() (though cloning is fine for arrays, unlike for anything else)

If you want deep cloning, check this answer


A little example to illustrate the shallowness of clone() even if the elements are Cloneable:

ArrayList[] array = new ArrayList[] {new ArrayList(), new ArrayList()};
ArrayList[] clone = array.clone();
for (int i = 0; i < clone.length; i ++) {
    System.out.println(System.identityHashCode(array[i]));
    System.out.println(System.identityHashCode(clone[i]));
    System.out.println(System.identityHashCode(array[i].clone()));
    System.out.println("-----");
}

Prints:

4384790  
4384790
9634993  
-----  
1641745  
1641745  
11077203  
-----  

What exactly is LLVM?

LLVM is basically a library used to build compilers and/or language oriented software. The basic gist is although you have gcc which is probably the most common suite of compilers, it is not built to be re-usable ie. it is difficult to take components from gcc and use it to build your own application. LLVM addresses this issue well by building a set of "modular and reusable compiler and toolchain technologies" which anyone could use to build compilers and language oriented software.

How to call a .NET Webservice from Android using KSOAP2?

It's very simple. You are getting the result into an Object which is a primitive one.

Your code:

Object result = (Object)envelope.getResponse();

Correct code:

SoapObject result=(SoapObject)envelope.getResponse();

//To get the data.
String resultData=result.getProperty(0).toString();
// 0 is the first object of data.

I think this should definitely work.

Change Timezone in Lumen or Laravel 5

By default time zone of laravel project is **UTC*

  • you can find time zone setting in App.php of config folder

'timezone' => 'UTC',

now change according to your time zone for me it's Asia/Calcutta

so for me setting will be 'timezone' => 'Asia/Calcutta',

  • After changing your time zone setting run command php artisan config:cache

*for time zone list visit this url https://www.w3schools.com/php/php_ref_timezones.asp

How to keep footer at bottom of screen

HTML

<div id="footer"></div>

CSS

#footer {
   position:absolute;
   bottom:0;
   width:100%;
   height:100px;   
   background:blue;//optional
}

How to iterate object in JavaScript?

There's this way too (new to EcmaScript5):

dictionary.data.forEach(function(item){
    console.log(item.name + ' ' + item.id);
});

Same approach for images

numpy division with RuntimeWarning: invalid value encountered in double_scalars

You can't solve it. Simply answer1.sum()==0, and you can't perform a division by zero.

This happens because answer1 is the exponential of 2 very large, negative numbers, so that the result is rounded to zero.

nan is returned in this case because of the division by zero.

Now to solve your problem you could:

  • go for a library for high-precision mathematics, like mpmath. But that's less fun.
  • as an alternative to a bigger weapon, do some math manipulation, as detailed below.
  • go for a tailored scipy/numpy function that does exactly what you want! Check out @Warren Weckesser answer.

Here I explain how to do some math manipulation that helps on this problem. We have that for the numerator:

exp(-x)+exp(-y) = exp(log(exp(-x)+exp(-y)))
                = exp(log(exp(-x)*[1+exp(-y+x)]))
                = exp(log(exp(-x) + log(1+exp(-y+x)))
                = exp(-x + log(1+exp(-y+x)))

where above x=3* 1089 and y=3* 1093. Now, the argument of this exponential is

-x + log(1+exp(-y+x)) = -x + 6.1441934777474324e-06

For the denominator you could proceed similarly but obtain that log(1+exp(-z+k)) is already rounded to 0, so that the argument of the exponential function at the denominator is simply rounded to -z=-3000. You then have that your result is

exp(-x + log(1+exp(-y+x)))/exp(-z) = exp(-x+z+log(1+exp(-y+x)) 
                                   = exp(-266.99999385580668)

which is already extremely close to the result that you would get if you were to keep only the 2 leading terms (i.e. the first number 1089 in the numerator and the first number 1000 at the denominator):

exp(3*(1089-1000))=exp(-267)

For the sake of it, let's see how close we are from the solution of Wolfram alpha (link):

Log[(exp[-3*1089]+exp[-3*1093])/([exp[-3*1000]+exp[-3*4443])] -> -266.999993855806522267194565420933791813296828742310997510523

The difference between this number and the exponent above is +1.7053025658242404e-13, so the approximation we made at the denominator was fine.

The final result is

'exp(-266.99999385580668) = 1.1050349147204485e-116

From wolfram alpha is (link)

1.105034914720621496.. × 10^-116 # Wolfram alpha.

and again, it is safe to use numpy here too.

Run a task every x-minutes with Windows Task Scheduler

Some of the links provided are only settings for Windows 2003's version of "Scheduled Tasks"

In Windows Server 2008 the "Tasks" setup only has a box with options for "5 Minutes, 10 minutes, 15 minutes, 30 mins, and 1 hour" (screen shot: http://i46.tinypic.com/2gwx7r8.jpg)... where the Window 2003 was a "enter whatever number you want" textbox.

I thought doing an "Export" and editing the XML from: PT30M to PT2M

and importing that as a new task would "trick" Tasks into repeating every 2 mins, but it didn't like that

My workaround for getting a task to run every 2 mins in Windows 2008 was to (ugggh) setup 30 different "triggers" for my task repeating every hour but staring at :00, :02, :04, :06 and so on and so on.... took me 8-10 mins to setup but I only had to do it once :-)

PHP create key => value pairs within a foreach

Something like this?

foreach ($Offer as $key => $value) { 
  $offerArray[$key] = $value[4];
}

Forbidden You don't have permission to access / on this server

WORKING Method { if there is no problem other than configuration }

By Default Appache is not restricting access from ipv4. (common external ip)

What may restrict is the configurations in 'httpd.conf' (or 'apache2.conf' depending on your apache configuration)

Solution:

Replace all:

<Directory />
     AllowOverride none
    Require all denied

</Directory>

with

<Directory />
     AllowOverride none
#    Require all denied

</Directory>

hence removing out all restriction given to Apache

Replace Require local with Require all granted at C:/wamp/www/ directory

<Directory "c:/wamp/www/">
    Options Indexes FollowSymLinks
    AllowOverride all
    Require all granted
#   Require local
</Directory>

Chain-calling parent initialisers in python

Python 3 includes an improved super() which allows use like this:

super().__init__(args)

Return HTML content as a string, given URL. Javascript Function

you need to return when the readystate==4 e.g.

function httpGet(theUrl)
{
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            return xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET", theUrl, false );
    xmlhttp.send();    
}

Handling NULL values in Hive

What is the datatype for column1 in your Hive table? Please note that if your column is STRING it won't be having a NULL value even though your external file does not have any data for that column.

How do I mock an open used in a with statement (using the Mock framework in Python)?

Sourced from a github snippet to patch read and write functionality in python.

The source link is over here

import configparser
import pytest

simpleconfig = """[section]\nkey = value\n\n"""

def test_monkeypatch_open_read(mockopen):
    filename = 'somefile.txt'
    mockopen.write(filename, simpleconfig)
 
    parser = configparser.ConfigParser()
    parser.read(filename)
    assert parser.sections() == ['section']
 
def test_monkeypatch_open_write(mockopen):
    parser = configparser.ConfigParser()
    parser.add_section('section')
    parser.set('section', 'key', 'value')
 
    filename = 'somefile.txt'
    parser.write(open(filename, 'wb'))
    assert mockopen.read(filename) == simpleconfig

How to set selected value from Combobox?

cmbEmployeeStatus.Text = "text"

How can I configure my makefile for debug and release builds?

Completing the answers from earlier... You need to reference the variables you define info in your commands...

DEBUG ?= 1
ifeq (DEBUG, 1)
    CFLAGS =-g3 -gdwarf2 -DDEBUG
else
    CFLAGS=-DNDEBUG
endif

CXX = g++ $(CFLAGS)
CC = gcc $(CFLAGS)

all: executable

executable: CommandParser.tab.o CommandParser.yy.o Command.o
    $(CXX) -o output CommandParser.yy.o CommandParser.tab.o Command.o -lfl

CommandParser.yy.o: CommandParser.l 
    flex -o CommandParser.yy.c CommandParser.l
    $(CC) -c CommandParser.yy.c

CommandParser.tab.o: CommandParser.y
    bison -d CommandParser.y
    $(CXX) -c CommandParser.tab.c

Command.o: Command.cpp
    $(CXX) -c Command.cpp

clean:
    rm -f CommandParser.tab.* CommandParser.yy.* output *.o

How to get an array of specific "key" in multidimensional array without looping

PHP 5.5+

Starting PHP5.5+ you have array_column() available to you, which makes all of the below obsolete.

PHP 5.3+

$ids = array_map(function ($ar) {return $ar['id'];}, $users);

Solution by @phihag will work flawlessly in PHP starting from PHP 5.3.0, if you need support before that, you will need to copy that wp_list_pluck.

PHP < 5.3

Wordpress 3.1+

In Wordpress there is a function called wp_list_pluck If you're using Wordpress that solves your problem.

PHP < 5.3

If you're not using Wordpress, since the code is open source you can copy paste the code in your project (and rename the function to something you prefer, like array_pick). View source here

JavaScript - Use variable in string match

You have to use RegExp object if your pattern is string

var xxx = "victoria";
var yyy = "i";
var rgxp = new RegExp(yyy, "g");
alert(xxx.match(rgxp).length);

If pattern is not dynamic string:

var xxx = "victoria";
var yyy = /i/g;
alert(xxx.match(yyy).length);

Checking if a folder exists (and creating folders) in Qt, C++

When you use QDir.mkpath() it returns true if the path already exists, in the other hand QDir.mkdir() returns false if the path already exists. So depending on your program you have to choose which fits better.

You can see more on Qt Documentation

How to convert a Kotlin source file to a Java source file

you can go to Tools > Kotlin > Show kotlin bytecode

enter image description here

enter image description here

enter image description here

Type datetime for input parameter in procedure

In this part of your SP:

IF @DateFirst <> '' and @DateLast <> ''
   set @FinalSQL  = @FinalSQL
       + '  or convert (Date,DateLog) >=     ''' + @DateFirst
       + ' and convert (Date,DateLog) <=''' + @DateLast  

you are trying to concatenate strings and datetimes.

As the datetime type has higher priority than varchar/nvarchar, the + operator, when it happens between a string and a datetime, is interpreted as addition, not as concatenation, and the engine then tries to convert your string parts (' or convert (Date,DateLog) >= ''' and others) to datetime or numeric values. And fails.

That doesn't happen if you omit the last two parameters when invoking the procedure, because the condition evaluates to false and the offending statement isn't executed.

To amend the situation, you need to add explicit casting of your datetime variables to strings:

set @FinalSQL  = @FinalSQL
    + '  or convert (Date,DateLog) >=     ''' + convert(date, @DateFirst)
    + ' and convert (Date,DateLog) <=''' + convert(date, @DateLast)

You'll also need to add closing single quotes:

set @FinalSQL  = @FinalSQL
    + '  or convert (Date,DateLog) >=     ''' + convert(date, @DateFirst) + ''''
    + ' and convert (Date,DateLog) <=''' + convert(date, @DateLast) + ''''

Call javascript from MVC controller action

<script>
    $(document).ready(function () {
        var msg = '@ViewBag.ErrorMessage'
        if (msg.length > 0)
            OnFailure('Register', msg);
    });

    function OnSuccess(header,Message) {
        $("#Message_Header").text(header);
        $("#Message_Text").text(Message);
        $('#MessageDialog').modal('show');
    }

    function OnFailure(header,error)
    {
        $("#Message_Header").text(header);
        $("#Message_Text").text(error);
        $('#MessageDialog').modal('show');
    }
</script>

How to make use of SQL (Oracle) to count the size of a string?

You can use LENGTH() for CHAR / VARCHAR2 and DBMS_LOB.GETLENGTH() for CLOB. Both functions will count actual characters (not bytes).

See the linked documentation if you do need bytes.

Auto height of div

div's will naturally resize in accordance with their content.

If you set no height on your div, it will expand to contain its conent.

An exception to this rule is when the div contains floating elements. If this is the case you'll need to do a bit extra to ensure that the containing div (wrapper) clears the floats.

Here's some ways to do this:

#wrapper{
overflow:hidden;
}

Or

#wrapper:after
{
content:".";
display:block;
clear:both;
visibility:hidden;
}

How to properly highlight selected item on RecyclerView?

I think, I've found the best tutorial on how to use the RecyclerView with all basic functions we need (single+multiselection, highlight, ripple, click and remove in multiselection, etc...).

Here it is --> http://enoent.fr/blog/2015/01/18/recyclerview-basics/

Based on that, I was able to create a library "FlexibleAdapter", which extends a SelectableAdapter. I think this must be a responsibility of the Adapter, actually you don't need to rewrite the basic functionalities of Adapter every time, let a library to do it, so you can just reuse the same implementation.

This Adapter is very fast, it works out of the box (you don't need to extend it); you customize the items for every view types you need; ViewHolder are predefined: common events are already implemented: single and long click; it maintains the state after rotation and much much more.

Please have a look and feel free to implement it in your projects.

https://github.com/davideas/FlexibleAdapter

A Wiki is also available.

Generating a WSDL from an XSD file

I know this question is old, but it deserves an answer. I personally prefer to create a WSDL by hand and test for compliance using SoapUI. But sometimes (specially for complex WSDLs), you have three ways to generate one out of an XSD:

  1. Generating a WSDL from a schema using Eclipse (probably the most user-friendly)
  2. Generating a WSDL via CXF (my favorite)
  3. Generating a WSDL via conventions using Spring WS (my least favorite)

I prefer the CXF approach since I'm a CLI guy. If it has a CLI, you can automate (that's my motto). And I like the Spring WS approach the least since it uses a lot of framework specific conventions.

There are more people who know CXF (I believe) than Spring WS. So anything that can throw a learning curve for a new engineer (without any clear advantage or ROI) is something I frown upon.

It should also go w/o saying that any generated WSDL should be tested for validity and compliance (and tweaked till it complies), and that your application publishes a static wsdl (as opposed to returning an auto-generated one.)

It's been my experience that you start with a WS-I compliant wsdl and then your application auto-generates (and returns to consumers) a non-compliant one.

In other words, beware of auto magic.

Center content in responsive bootstrap navbar

Update 2020...

Bootstrap 5 Beta

The Navbar is still flexbox based in Bootstrap 5 and centering content works the same as it did with Bootstrap 4. Examples

Bootstrap 4

Centering Navbar content is easier is Bootstrap 4, and you can see many centering scenarios explained here: https://stackoverflow.com/a/20362024/171456

Bootstrap 3

Another scenario that doesn't seem to have been answered yet is centering both the brand and navbar links. Here's a solution..

.navbar .navbar-header,
.navbar-collapse {
    float:none;
    display:inline-block;
    vertical-align: top;
}

@media (max-width: 768px) {
    .navbar-collapse  {
        display: block;
    }
}

http://codeply.com/go/1lrdvNH9GI

Also see: Bootstrap NavBar with left, center or right aligned items

Putting -moz-available and -webkit-fill-available in one width (css property)

I needed my ASP.NET drop down list to take up all available space, and this is all I put in the CSS and it is working in Firefox and IE11:

width: 100%

I had to add the CSS class into the asp:DropDownList element

Where are Docker images stored on the host machine?

use docker inspect container_id
find folder under MergedDir

# example. 
"MergedDir": "/var/lib/docker/overlay2/f40cc2ea8912ec3b32deeef5a1542a132f6e918acb/merged 

How to include js file in another js file?

It is not possible directly. You may as well write some preprocessor which can handle that.

If I understand it correctly then below are the things that can be helpful to achieve that:

  • Use a pre-processor which will run through your JS files for example looking for patterns like "@import somefile.js" and replace them with the content of the actual file. Nicholas Zakas(Yahoo) wrote one such library in Java which you can use (http://www.nczonline.net/blog/2009/09/22/introducing-combiner-a-javascriptcss-concatenation-tool/)

  • If you are using Ruby on Rails then you can give Jammit asset packaging a try, it uses assets.yml configuration file where you can define your packages which can contain multiple files and then refer them in your actual webpage by the package name.

  • Try using a module loader like RequireJS or a script loader like LabJs with the ability to control the loading sequence as well as taking advantage of parallel downloading.

JavaScript currently does not provide a "native" way of including a JavaScript file into another like CSS ( @import ), but all the above mentioned tools/ways can be helpful to achieve the DRY principle you mentioned. I can understand that it may not feel intuitive if you are from a Server-side background but this is the way things are. For front-end developers this problem is typically a "deployment and packaging issue".

Hope it helps.

Move entire line up and down in Vim

Just add this code to .vimrc (or .gvimrc)

nnoremap <A-j> :m+<CR>==
nnoremap <A-k> :m-2<CR>==
inoremap <A-j> <Esc>:m+<CR>==gi
inoremap <A-k> <Esc>:m-2<CR>==gi
vnoremap <A-j> :m'>+<CR>gv=gv
vnoremap <A-k> :m-2<CR>gv=gv

How to hide soft keyboard on android after clicking outside EditText?

I liked the approach of calling dispatchTouchEvent made by htafoya, but:

  • I didn't understand the timer part (don't know why measuring the downtime should be necessary?)
  • I don't like to register/unregister all EditTexts with every view-change (could be quite a lot of viewchanges and edittexts in complex hierarchies)

So, I made this somewhat easier solution:

@Override
public boolean dispatchTouchEvent(final MotionEvent ev) {
    // all touch events close the keyboard before they are processed except EditText instances.
    // if focus is an EditText we need to check, if the touchevent was inside the focus editTexts
    final View currentFocus = getCurrentFocus();
    if (!(currentFocus instanceof EditText) || !isTouchInsideView(ev, currentFocus)) {
        ((InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE))
            .hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }
    return super.dispatchTouchEvent(ev);
}

/**
 * determine if the given motionevent is inside the given view.
 * 
 * @param ev
 *            the given view
 * @param currentFocus
 *            the motion event.
 * @return if the given motionevent is inside the given view
 */
private boolean isTouchInsideView(final MotionEvent ev, final View currentFocus) {
    final int[] loc = new int[2];
    currentFocus.getLocationOnScreen(loc);
    return ev.getRawX() > loc[0] && ev.getRawY() > loc[1] && ev.getRawX() < (loc[0] + currentFocus.getWidth())
        && ev.getRawY() < (loc[1] + currentFocus.getHeight());
}

There is one disadvantage:

Switching from one EditText to another EditText makes the keyboard hide and reshow - in my case it's desired that way, because it shows that you switched between two input components.

I want to multiply two columns in a pandas DataFrame and add the result into a new column

To make things neat, I take Hayden's solution but make a small function out of it.

def create_value(row):
    if row['Action'] == 'Sell':
        return row['Prices'] * row['Amount']
    else:
        return -row['Prices']*row['Amount']

so that when we want to apply the function to our dataframe, we can do..

df['Value'] = df.apply(lambda row: create_value(row), axis=1)

...and any modifications only need to occur in the small function itself.

Concise, Readable, and Neat!

How do I compare strings in GoLang?

For the Platform Independent Users or Windows users, what you can do is:

import runtime:

import (
    "runtime"
    "strings"
)

and then trim the string like this:

if runtime.GOOS == "windows" {
  input = strings.TrimRight(input, "\r\n")
} else {
  input = strings.TrimRight(input, "\n")
}

now you can compare it like that:

if strings.Compare(input, "a") == 0 {
  //....yourCode
}

This is a better approach when you're making use of STDIN on multiple platforms.

Explanation

This happens because on windows lines end with "\r\n" which is known as CRLF, but on UNIX lines end with "\n" which is known as LF and that's why we trim "\n" on unix based operating systems while we trim "\r\n" on windows.

postgresql: INSERT INTO ... (SELECT * ...)

This notation (first seen here) looks useful too:

insert into postagem (
  resumopostagem,
  textopostagem,
  dtliberacaopostagem,
  idmediaimgpostagem,
  idcatolico,
  idminisermao,
  idtipopostagem
) select
  resumominisermao,
  textominisermao,
  diaminisermao,
  idmediaimgminisermao,
  idcatolico ,
  idminisermao,
  1
from
  minisermao    

Xcode/Simulator: How to run older iOS version?

I was searching for how to do this on a much newer version of xcode than the original question and while the answers here got me where I needed to go, they aren't quite accurate for location anymore. Xcode 11.3.1, you need to go into Preferences -> Components, then select the desired Simulators. You can also select tvOS and watchOS similators from the same window.

Components preference window from Xcode 11.3.1

Batch file to copy files from one folder to another folder

Just to be clear, when you use xcopy /s c:\source d:\target, put "" around the c:\source and d:\target,otherwise you get error.

ie if there are spaces in the path ie if you have:

"C:\Some Folder\*.txt"

but not required if you have:

C:\SomeFolder\*.txt

Excel plot time series frequency with continuous xaxis

You can get good Time Series graphs in Excel, the way you want, but you have to work with a few quirks.

  1. Be sure to select "Scatter Graph" (with a line option). This is needed if you have non-uniform time stamps, and will scale the X-axis accordingly.

  2. In your data, you need to add a column with the mid-point. Here's what I did with your sample data. (This trick ensures that the data gets plotted at the mid-point, like you desire.) enter image description here

  3. You can format the x-axis options with this menu. (Chart->Design->Layout) enter image description here

  4. Select "Axes" and go to Primary Horizontal Axis, and then select "More Primary Horizontal Axis Options"

  5. Set up the options you wish. (Fix the starting and ending points.) enter image description here

  6. And you will get a graph such as the one below. enter image description here

You can then tweak many of the options, label the axes better etc, but this should get you started.

Hope this helps you move forward.

Table is marked as crashed and should be repaired

I had the same issue when my server free disk space available was 0

You can use the command (there must be ample space for the mysql files)

REPAIR TABLE `<table name>`;

for repairing individual tables

How do I create a shortcut via command-line in Windows?

To create a shortcut for warp-cli.exe, I based rojo's Powershell command and added WorkingDirectory, Arguments, IconLocation and minimized WindowStyle attribute to it.

powershell "$s=(New-Object -COM WScript.Shell).CreateShortcut('%userprofile%\Start Menu\Programs\Startup\CWarp_DoH.lnk');$s.TargetPath='E:\Program\CloudflareWARP\warp-cli.exe';$s.Arguments='connect';$s.IconLocation='E:\Program\CloudflareWARP\Cloudflare WARP.exe';$s.WorkingDirectory='E:\Program\CloudflareWARP';$s.WindowStyle=7;$s.Save()"

Other PS attributes for CreateShortcut: https://stackoverflow.com/a/57547816/4127357

dd: How to calculate optimal blocksize?

  • for better performace use the biggest blocksize you RAM can accomodate (will send less I/O calls to the OS)
  • for better accurancy and data recovery set the blocksize to the native sector size of the input

As dd copies data with the conv=noerror,sync option, any errors it encounters will result in the remainder of the block being replaced with zero-bytes. Larger block sizes will copy more quickly, but each time an error is encountered the remainder of the block is ignored.

source

TypeError: 'bool' object is not callable

You do cls.isFilled = True. That overwrites the method called isFilled and replaces it with the value True. That method is now gone and you can't call it anymore. So when you try to call it again you get an error, since it's not there anymore.

The solution is use a different name for the variable than you do for the method.

How to keep indent for second line in ordered lists via CSS?

I believe this will do what you are looking for.

.cssClass li {
    list-style-type: disc;
    list-style-position: inside;
    text-indent: -1em;
    padding-left: 1em;
}

JSFiddle: https://jsfiddle.net/dzbos70f/

enter image description here

How do I create the small icon next to the website tab for my site?

It is called favicon.ico and you can generate it from this site.

http://www.favicon.cc/

How to redirect 'print' output to a file using python?

The easiest solution isn't through python; its through the shell. From the first line of your file (#!/usr/bin/python) I'm guessing you're on a UNIX system. Just use print statements like you normally would, and don't open the file at all in your script. When you go to run the file, instead of

./script.py

to run the file, use

./script.py > <filename>

where you replace <filename> with the name of the file you want the output to go in to. The > token tells (most) shells to set stdout to the file described by the following token.

One important thing that needs to be mentioned here is that "script.py" needs to be made executable for ./script.py to run.

So before running ./script.py,execute this command

chmod a+x script.py (make the script executable for all users)

Leading zeros for Int in Swift

Assuming you want a field length of 2 with leading zeros you'd do this:

import Foundation

for myInt in 1 ... 3 {
    print(String(format: "%02d", myInt))
}

output:

01
02
03

This requires import Foundation so technically it is not a part of the Swift language but a capability provided by the Foundation framework. Note that both import UIKit and import Cocoa include Foundation so it isn't necessary to import it again if you've already imported Cocoa or UIKit.


The format string can specify the format of multiple items. For instance, if you are trying to format 3 hours, 15 minutes and 7 seconds into 03:15:07 you could do it like this:

let hours = 3
let minutes = 15
let seconds = 7
print(String(format: "%02d:%02d:%02d", hours, minutes, seconds))

output:

03:15:07

iFrame src change event detection?

The iframe always keeps the parent page, you should use this to detect in which page you are in the iframe:

Html code:

<iframe id="iframe" frameborder="0" scrolling="no" onload="resizeIframe(this)" width="100%" src="www.google.com"></iframe>

Js:

    function resizeIframe(obj) {
        alert(obj.contentWindow.location.pathname);
    }

How can I get the current user's username in Bash?

Get the current task's user_struct

#define get_current_user()              \
({                                      \
    struct user_struct *__u;            \
    const struct cred *__cred;          \
    __cred = current_cred();            \
    __u = get_uid(__cred->user);        \
    __u;                                \
})

How to have jQuery restrict file types on upload?

No plugin necessary for just this task. Cobbled this together from a couple other scripts:

$('INPUT[type="file"]').change(function () {
    var ext = this.value.match(/\.(.+)$/)[1];
    switch (ext) {
        case 'jpg':
        case 'jpeg':
        case 'png':
        case 'gif':
            $('#uploadButton').attr('disabled', false);
            break;
        default:
            alert('This is not an allowed file type.');
            this.value = '';
    }
});

The trick here is to set the upload button to disabled unless and until a valid file type is selected.

How do ports work with IPv6?

They work almost the same as today. However, be sure you include [] around your IP.

For example : http://[1fff:0:a88:85a3::ac1f]:8001/index.html

Wikipedia has a pretty good article about IPv6: http://en.wikipedia.org/wiki/IPv6#Addressing

How to install JQ on Mac by command-line?

The simplest way to install jq and test that it works is through brew and then using the simplest filter that merely formats the JSON

Install

brew is the easiest way to manage packages on a mac:

brew install jq

Need brew? Run the following command:

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Failing that: instructions to install and use are on https://brew.sh/

Test

The . filter takes its input and produces it unchanged as output. This is the identity operator. (quote the docs)

echo '{ "name":"John", "age":31, "city":"New York" }' | jq .

The result should appear like so in your terminal:

{
  "name": "John",
  "age": 31,
  "city": "New York"
}

After MySQL install via Brew, I get the error - The server quit without updating PID file

My issue was that I started server as sudo once and then tried to restart as a local user.

Here mysql was not able to write to '.err' file owned by root. I had to remove that file and restart the server:

sudo rm /usr/local/var/mysql/*.err
mysql.server start

CSS Border Not Working

Use this line of code in your css

border: 1px solid #000 !important;

or if you want border only in left and right side of container then use:

border-right: 1px solid #000 !important;
border-left: 1px solid #000 !important;

Path of assets in CSS files in Symfony 2

I'll post what worked for me, thanks to @xavi-montero.

Put your CSS in your bundle's Resource/public/css directory, and your images in say Resource/public/img.

Change assetic paths to the form 'bundles/mybundle/css/*.css', in your layout.

In config.yml, add rule css_rewrite to assetic:

assetic:
    filters:
        cssrewrite:
            apply_to: "\.css$"

Now install assets and compile with assetic:

$ rm -r app/cache/* # just in case
$ php app/console assets:install --symlink
$ php app/console assetic:dump --env=prod

This is good enough for the development box, and --symlink is useful, so you don't have to reinstall your assets (for example, you add a new image) when you enter through app_dev.php.

For the production server, I just removed the '--symlink' option (in my deployment script), and added this command at the end:

$ rm -r web/bundles/*/css web/bundles/*/js # all this is already compiled, we don't need the originals

All is done. With this, you can use paths like this in your .css files: ../img/picture.jpeg

Default property value in React component using TypeScript

For those having optional props that need default values. Credit here :)

interface Props {
  firstName: string;
  lastName?: string;
}

interface DefaultProps {
  lastName: string;
}

type PropsWithDefaults = Props & DefaultProps;

export class User extends React.Component<Props> {
  public static defaultProps: DefaultProps = {
    lastName: 'None',
  }

  public render () {
    const { firstName, lastName } = this.props as PropsWithDefaults;

    return (
      <div>{firstName} {lastName}</div>
    )
  }
}

How to disable registration new users in Laravel

Set Register route false in your web.php.

Auth::routes(['register' => false]);

Ripple effect on Android Lollipop CardView

Use Material Cardview instead, it extends Cardview and provides multiple new features including default clickable effect :

<com.google.android.material.card.MaterialCardView>

...

</com.google.android.material.card.MaterialCardView>

Dependency (It can be used up to API 14 to support older device):

implementation 'com.google.android.material:material:1.0.0'

ValueError: Length of values does not match length of index | Pandas DataFrame.unique()

The error comes up when you are trying to assign a list of numpy array of different length to a data frame, and it can be reproduced as follows:

A data frame of four rows:

df = pd.DataFrame({'A': [1,2,3,4]})

Now trying to assign a list/array of two elements to it:

df['B'] = [3,4]   # or df['B'] = np.array([3,4])

Both errors out:

ValueError: Length of values does not match length of index

Because the data frame has four rows but the list and array has only two elements.

Work around Solution (use with caution): convert the list/array to a pandas Series, and then when you do assignment, missing index in the Series will be filled with NaN:

df['B'] = pd.Series([3,4])

df
#   A     B
#0  1   3.0
#1  2   4.0
#2  3   NaN          # NaN because the value at index 2 and 3 doesn't exist in the Series
#3  4   NaN

For your specific problem, if you don't care about the index or the correspondence of values between columns, you can reset index for each column after dropping the duplicates:

df.apply(lambda col: col.drop_duplicates().reset_index(drop=True))

#   A     B
#0  1   1.0
#1  2   5.0
#2  7   9.0
#3  8   NaN

How to add key,value pair to dictionary?

I got here looking for a way to add a key/value pair(s) as a group - in my case it was the output of a function call, so adding the pair using dictionary[key] = value would require me to know the name of the key(s).

In this case, you can use the update method: dictionary.update(function_that_returns_a_dict(*args, **kwargs)))

Beware, if dictionary already contains one of the keys, the original value will be overwritten.

python: changing row index of pandas data frame

followers_df.reset_index()
followers_df.reindex(index=range(0,20))

AngularJS. How to call controller function from outside of controller component

Dmitry's answer works fine. I just made a simple example using the same technique.

jsfiddle: http://jsfiddle.net/o895a8n8/5/

<button onclick="call()">Call Controller's method from outside</button>
<div  id="container" ng-app="" ng-controller="testController">
</div>

.

function call() {
    var scope = angular.element(document.getElementById('container')).scope();
      scope.$apply(function(){
        scope.msg = scope.msg + ' I am the newly addded message from the outside of the controller.';
    })
    alert(scope.returnHello());
}

function testController($scope) {
    $scope.msg = "Hello from a controller method.";
    $scope.returnHello = function() {
        return $scope.msg ; 
    }
}

Transparent color of Bootstrap-3 Navbar

  1. Go to http://px64.net/
  2. mess around with opacity, add your image or choose color.
  3. copy either html or css(css is easier) the site spits out.
  4. Select your element aka the navbar.

  5. .navbar{ background-image:url(link that the site provides); background-repeat:repeat;

  6. Enjoy.

JPA OneToMany and ManyToOne throw: Repeated column in mapping for entity column (should be mapped with insert="false" update="false")

I am not really sure about your question (the meaning of "empty table" etc, or how mappedBy and JoinColumn were not working).

I think you were trying to do a bi-directional relationships.

First, you need to decide which side "owns" the relationship. Hibernate is going to setup the relationship base on that side. For example, assume I make the Post side own the relationship (I am simplifying your example, just to keep things in point), the mapping will look like:

(Wish the syntax is correct. I am writing them just by memory. However the idea should be fine)

public class User{
    @OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
    private List<Post> posts;
}


public class Post {
    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="user_id")
    private User user;
}

By doing so, the table for Post will have a column user_id which store the relationship. Hibernate is getting the relationship by the user in Post (Instead of posts in User. You will notice the difference if you have Post's user but missing User's posts).

You have mentioned mappedBy and JoinColumn is not working. However, I believe this is in fact the correct way. Please tell if this approach is not working for you, and give us a bit more info on the problem. I believe the problem is due to something else.


Edit:

Just a bit extra information on the use of mappedBy as it is usually confusing at first. In mappedBy, we put the "property name" in the opposite side of the bidirectional relationship, not table column name.

Convert dd-mm-yyyy string to date

Another possibility:

var from = "10-11-2011"; 
var numbers = from.match(/\d+/g); 
var date = new Date(numbers[2], numbers[0]-1, numbers[1]);

Match the digits and reorder them

mysql error 1364 Field doesn't have a default values

As others said, this is caused by the STRICT_TRANS_TABLES SQL mode.

To check whether STRICT_TRANS_TABLES mode is enabled:

SHOW VARIABLES LIKE 'sql_mode';

To disable strict mode:

SET GLOBAL sql_mode='';

if...else within JSP or JSTL

Should I use JSTL ?

Yes.

You can use <c:if> and <c:choose> tags to make conditional rendering in jsp using JSTL.

To simulate if , you can use:

<c:if test="condition"></c:if>

To simulate if...else, you can use:

<c:choose>
    <c:when test="${param.enter=='1'}">
        pizza. 
        <br />
    </c:when>    
    <c:otherwise>
        pizzas. 
        <br />
    </c:otherwise>
</c:choose>

Calculating Page Table Size

Suppose logical address space is **32 bit so total possible logical entries will be 2^32 and other hand suppose each page size is 4 byte then size of one page is *2^2*2^10=2^12...* now we know that no. of pages in page table is pages=total possible logical address entries/page size so pages=2^32/2^12 =2^20 Now suppose that each entry in page table takes 4 bytes then total size of page table in *physical memory will be=2^2*2^20=2^22=4mb***

How to install the Raspberry Pi cross compiler on my Linux host machine?

For Windows host, I want to highly recommend this tutorial::

  • Download and install the toolchain
  • Sync sysroot with your RPi include/lib directories
  • Compile your code
  • Drag and drop the executable to your RPi using SmarTTY
  • Run it!

Nothing more, nothing less!

Prebuilt GNU Toolchains available for Raspberry, Beaglebone, Cubieboard, AVR (Atmel) and more

Convert serial.read() into a useable string using Arduino?

This would be way easier:

char data [21];
int number_of_bytes_received;

if(Serial.available() > 0)
{
    number_of_bytes_received = Serial.readBytesUntil (13,data,20); // read bytes (max. 20) from buffer, untill <CR> (13). store bytes in data. count the bytes recieved.
    data[number_of_bytes_received] = 0; // add a 0 terminator to the char array
} 

bool result = strcmp (data, "whatever");
// strcmp returns 0; if inputs match.
// http://en.cppreference.com/w/c/string/byte/strcmp


if (result == 0)
{
   Serial.println("data matches whatever");
} 
else 
{
   Serial.println("data does not match whatever");
}

Programmatically Creating UILabel

For swift

var label = UILabel(frame: CGRect(x: 0, y: 0, width: 250, height: 50))
label.textAlignment = .left
label.text = "This is a Label"
self.view.addSubview(label)

How to make a section of an image a clickable link

If you don't want to make the button a separate image, you can use the <area> tag. This is done by using html similar to this:

<img src="imgsrc" width="imgwidth" height="imgheight" alt="alttext" usemap="#mapname">

<map name="mapname">
    <area shape="rect" coords="see note 1" href="link" alt="alttext">
</map>

Note 1: The coords=" " attribute must be formatted in this way: coords="x1,y1,x2,y2" where:

x1=top left X coordinate
y1=top left Y coordinate
x2=bottom right X coordinate
y2=bottom right Y coordinate

Note 2: The usemap="#mapname" attribute must include the #.

EDIT:

I looked at your code and added in the <map> and <area> tags where they should be. I also commented out some parts that were either overlapping the image or seemed there for no use.

<div class="flexslider">
    <ul class="slides" runat="server" id="Ul">                             
        <li class="flex-active-slide" style="background: url(&quot;images/slider-bg-1.jpg&quot;) no-repeat scroll 50% 0px transparent; width: 100%; float: left; margin-right: -100%; position: relative; display: list-item;">
            <div class="container">
                <div class="sixteen columns contain"></div>   
                <img runat="server" id="imgSlide1" style="top: 1px; right: -19px; opacity: 1;" class="item" src="./test.png" data-topimage="7%" height="358" width="728" usemap="#imgmap" />
                <map name="imgmap">
                    <area shape="rect" coords="48,341,294,275" href="http://www.example.com/">
                </map>
                <!--<a href="#" style="display:block; background:#00F; width:356px; height:66px; position:absolute; left:1px; top:-19px; left: 162px; top: 279px;"></a>-->
            </div>
        </li>
    </ul>
</div>
<!-- <ul class="flex-direction-nav">
    <li><a class="flex-prev" href="#"><i class="icon-angle-left"></i></a></li>
    <li><a class="flex-next" href="#"><i class="icon-angle-right"></i></a></li>
</ul> -->

Notes:

  1. The coord="48,341,294,275" is in reference to your screenshot you posted.
  2. The src="./test.png" is the location and name of the screenshot you posted on my computer.
  3. The href="http://www.example.com/" is an example link.

Convert List<DerivedClass> to List<BaseClass>

The way to make this work is to iterate over the list and cast the elements. This can be done using ConvertAll:

List<A> listOfA = new List<C>().ConvertAll(x => (A)x);

You could also use Linq:

List<A> listOfA = new List<C>().Cast<A>().ToList();

Get the date of next monday, tuesday, etc

For some reason, strtotime('next friday') display the Friday date of the current week. Try this instead:

//Current date 2020-02-03
$fridayNextWeek = date('Y-m-d', strtotime('friday next week'); //Outputs 2020-02-14

$nextFriday = date('Y-m-d', strtotime('next friday'); //Outputs 2020-02-07

keycode and charcode

Okay, here are the explanations.

e.keyCode - used to get the number that represents the key on the keyboard

e.charCode - a number that represents the unicode character of the key on keyboard

e.which - (jQuery specific) is a property introduced in jQuery (DO Not use in plain javascript)

Below is the code snippet to get the keyCode and charCode

<script>
// get key code
function getKey(event) {
  event = event || window.event;
  var keyCode = event.which || event.keyCode;
  alert(keyCode);
}

// get char code
function getChar(event) {
  event = event || window.event;
  var keyCode = event.which || event.keyCode;
  var typedChar = String.fromCharCode(keyCode);
  alert(typedChar);
}
</script>

Live example of Getting keyCode and charCode in JavaScript.

How can I get Maven to stop attempting to check for updates for artifacts from a certain group from maven-central-repo?

I had some trouble similar to this,

<repository>
    <id>java.net</id>
    <url>https://maven-repository.dev.java.net/nonav/repository</url>
    <layout>legacy</layout>
</repository>
<repository>
    <id>java.net2</id>
    <url>https://maven2-repository.dev.java.net/nonav/repository</url>
</repository>

Setting the updatePolicy to "never" did not work. Removing these repo was the way I solved it. ps: I was following this tutorial about web services (btw, probably the best tutorial for ws for java)

How do I generate a random int number?

The question looks very simple but the answer is bit complicated. If you see almost everyone has suggested to use the Random class and some have suggested to use the RNG crypto class. But then when to choose what.

For that we need to first understand the term RANDOMNESS and the philosophy behind it.

I would encourage you to watch this video which goes in depth in the philosophy of RANDOMNESS using C# https://www.youtube.com/watch?v=tCYxc-2-3fY

First thing let us understand the philosophy of RANDOMNESS. When we tell a person to choose between RED, GREEN and YELLOW what happens internally. What makes a person choose RED or YELLOW or GREEN?

c# Random

Some initial thought goes into the persons mind which decides his choice, it can be favorite color , lucky color and so on. In other words some initial trigger which we term in RANDOM as SEED.This SEED is the beginning point, the trigger which instigates him to select the RANDOM value.

Now if a SEED is easy to guess then those kind of random numbers are termed as PSEUDO and when a seed is difficult to guess those random numbers are termed SECURED random numbers.

For example a person chooses is color depending on weather and sound combination then it would be difficult to guess the initial seed.

c# Random

Now let me make an important statement:-

*“Random” class generates only PSEUDO random number and to generate SECURE random number we need to use “RNGCryptoServiceProvider” class.

c# Random

Random class takes seed values from your CPU clock which is very much predictable. So in other words RANDOM class of C# generates pseudo random numbers , below is the code for the same.

var random = new Random();
int randomnumber = random.Next()

While the RNGCryptoServiceProvider class uses OS entropy to generate seeds. OS entropy is a random value which is generated using sound, mouse click, and keyboard timings, thermal temp etc. Below goes the code for the same.

using (RNGCryptoServiceProvider rg = new RNGCryptoServiceProvider()) 
{ 
    byte[] rno = new byte[5];    
    rg.GetBytes(rno);    
    int randomvalue = BitConverter.ToInt32(rno, 0); 
}

To understand OS entropy see this video from 14:30 https://www.youtube.com/watch?v=tCYxc-2-3fY where the logic of OS entropy is explained. So putting in simple words RNG Crypto generates SECURE random numbers.

How to get everything after last slash in a URL?

Here's a more general, regex way of doing this:

    re.sub(r'^.+/([^/]+)$', r'\1', url)

Filtering lists using LINQ

This LINQ below will generate the SQL for a left outer join and then take all of the results that don't find a match in your exclusion list.

List<Person> filteredResults =from p in people
        join e in exclusions on p.compositeKey equals e.compositeKey into temp
        from t in temp.DefaultIfEmpty()
        where t.compositeKey == null
        select p

let me know if it works!

How to generate all permutations of a list?

Anyway we could use sympy library , also support for multiset permutations

import sympy
from sympy.utilities.iterables import multiset_permutations
t = [1,2,3]
p = list(multiset_permutations(t))
print(p)

# [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]

Answer is highly inspired by Get all permutations of a numpy array

Display help message with python argparse when script is called without any arguments

If your command is something where a user needs to choose some action, then use a mutually exclusive group with required=True.

This is kind of an extension to the answer given by pd321.

import argparse

parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("--batch", action='store', type=int,  metavar='pay_id')
group.add_argument("--list", action='store_true')
group.add_argument("--all", action='store_true', help='check all payments')

args=parser.parse_args()

if args.batch:
    print('batch {}'.format(args.batch))

if args.list:
    print('list')

if args.all:
    print('all')

Output:

$ python3 a_test.py
usage: a_test.py [-h] (--batch pay_id | --list | --all)
a_test.py: error: one of the arguments --batch --list --all is required

This only give the basic help. And some of the other answers will give you the full help. But at least your users know they can do -h

How to detect when WIFI Connection has been established in Android?

November 2020:

I have dealt too much with items deprecated by Google. Finally I found a solution to my particular requirement using "registerNetworkCallback" as Google currently suggests.

What I needed was a simple way to detect that my device has an IPv4 assigned in WIFI. (I haven't tried other cases, my requirement was very specific, but maybe this method, without deprecated elements, will serve as a basis for other cases).

Tested on APIs 23, 24 and 26 (physical devices) and APIs 28 and 29 (emulated devices).

    ConnectivityManager cm 
            = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkRequest.Builder builder = new NetworkRequest.Builder();

    cm.registerNetworkCallback
            (
                    builder.build(),
                    new ConnectivityManager.NetworkCallback()
                    {
                        @Override
                        public void onAvailable(Network network)
                        {
                            //Actions to take with Wifi available.
                        }
                        @Override
                        public void onLost(Network network)
                        {
                            //Actions to take with lost Wifi.
                        }
                    }

            );

(Implemented inside "MainActivity.Oncreate")

Note: In manifest needs "android.permission.ACCESS_NETWORK_STATE"

How to find the Target *.exe file of *.appref-ms

The easiest thing is to run the program, open the task manager, right-click the process and select properties, here is the full address

iPhone/iPad browser simulator?

I use mobile-browser-emulator chrome plug-in which is has iphone device types. It actually uses user-agent and size of device on which based responsive pages are rendered

What do .c and .h file extensions mean to C?

Of course, there is nothing that says the extension of a header file must be .h and the extension of a C source file must be .c. These are useful conventions.

E:\Temp> type my.interface
#ifndef MY_INTERFACE_INCLUDED
#define MYBUFFERSIZE 8
#define MY_INTERFACE_INCLUDED
#endif

E:\Temp> type my.source
#include <stdio.h>

#include "my.interface"

int main(void) {
    char x[MYBUFFERSIZE] = {0};
    x[0] = 'a';
    puts(x);
    return 0;
}

E:\Temp> gcc -x c my.source -o my.exe

E:\Temp> my
a

How do I redirect to another webpage?

Here is the code to redirect to some other page with a timeout of 10 seconds.

<script>
    function Redirect()
    {
        window.location="http://www.adarshkr.com";
    }

    document.write("You will be redirected to a new page in 10 seconds.");
    setTimeout('Redirect()', 10000);
</script>

You can also do it like this, on click of a button using location.assign:

<input type="button" value="Load new document" onclick="newPage()">
<script>
    function newPage() {
        window.location.assign("http://www.adarshkr.com")
    }
</script>

Multiple input in JOptionPane.showInputDialog

Yes. You know that you can put any Object into the Object parameter of most JOptionPane.showXXX methods, and often that Object happens to be a JPanel.

In your situation, perhaps you could use a JPanel that has several JTextFields in it:

import javax.swing.*;

public class JOptionPaneMultiInput {
   public static void main(String[] args) {
      JTextField xField = new JTextField(5);
      JTextField yField = new JTextField(5);

      JPanel myPanel = new JPanel();
      myPanel.add(new JLabel("x:"));
      myPanel.add(xField);
      myPanel.add(Box.createHorizontalStrut(15)); // a spacer
      myPanel.add(new JLabel("y:"));
      myPanel.add(yField);

      int result = JOptionPane.showConfirmDialog(null, myPanel, 
               "Please Enter X and Y Values", JOptionPane.OK_CANCEL_OPTION);
      if (result == JOptionPane.OK_OPTION) {
         System.out.println("x value: " + xField.getText());
         System.out.println("y value: " + yField.getText());
      }
   }
}

How to check if memcache or memcached is installed for PHP?

I combined, minified and extended (some more checks) the answers from @Bijay Rungta and @J.C. Inacio

<?php
if(!extension_loaded('Memcache'))
{
    die("Memcache extension is not loaded");
}

if (!class_exists('Memcache')) 
{
    die('Memcache class not available');
}

$memcacheObj = new Memcache;
if(!$memcacheObj)
{
    die('Could not create memcache object');
}

if (!$memcacheObj->connect('localhost')) 
{
    die('Could not connect to memcache server');
}

// testdata to store in memcache
$testData = array(
    'the' => 'cake',
    'is' => 'a lie',
);

// set data (if not present)
$aData = $memcacheObj->get('data');
if (!$aData) 
{
    if(!$memcacheObj->set('data', $testData, 0, 300))
    {
        die('Memcache could not set the data');
    }
}

// try to fetch data
$aData = $memcacheObj->get('data');
if (!$aData) 
{
    die('Memcache is not responding with data');
}

if($aData !== $testData)
{
    die('Memcache is responding but with wrong data');
}

die('Memcache is working fine');

How can I recognize touch events using jQuery in Safari for iPad? Is it possible?

I was a little bit worried about using only touchmove for my project, since it only seems to fire when your touch moves from one location to another (and not on the initial touch). So I combined it with touchstart, and this seems to work very well for the initial touch and any movements.

<script>

function doTouch(e) {
    e.preventDefault();
    var touch = e.touches[0];

    document.getElementById("xtext").innerHTML = touch.pageX;
    document.getElementById("ytext").innerHTML = touch.pageY;   
}

document.addEventListener('touchstart', function(e) {doTouch(e);}, false);
document.addEventListener('touchmove', function(e) {doTouch(e);}, false);

</script>

X: <div id="xtext">0</div>
Y: <div id="ytext">0</div>

Rendering React Components from Array of Objects

This is quite likely the simplest way to achieve what you are looking for.

In order to use this map function in this instance, we will have to pass a currentValue (always-required) parameter, as well an index (optional) parameter. In the below example, station is our currentValue, and x is our index.

station represents the current value of the object within the array as it is iterated over. x automatically increments; increasing by one each time a new object is mapped.

render () {
    return (
        <div>
            {stations.map((station, x) => (
                <div key={x}> {station} </div>
            ))}
        </div>
    );
}

What Thomas Valadez had answered, while it had provided the best/simplest method to render a component from an array of objects, it had failed to properly address the way in which you would assign a key during this process.

How to stop default link click behavior with jQuery

You can use e.preventDefault(); instead of e.stopPropagation();

Path to MSBuild

If you are adventurous you can also get the source code and latest release of MsBuild from GitHub now at https://github.com/Microsoft/msbuild/releases/

Find out a Git branch creator

I tweaked the previous answers by using the --sort flag and added some color/formatting:

git for-each-ref --format='%(color:cyan)%(authordate:format:%m/%d/%Y %I:%M %p)    %(align:25,left)%(color:yellow)%(authorname)%(end) %(color:reset)%(refname:strip=3)' --sort=authordate refs/remotes

Are there any worse sorting algorithms than Bogosort (a.k.a Monkey Sort)?

A worst case performance of O(8) might not even make it an algorithm according to some.

An algorithm is just a series of steps and you can always do worse by tweaking it a little bit to get the desired output in more steps than it was previously taking. One could purposely put the knowledge of the number of steps taken into the algorithm and make it terminate and produce the correct output only after X number of steps have been done. That X could very well be of the order of O(n2) or O(nn!) or whatever the algorithm desired to do. That would effectively increase its best-case as well as average case bounds.

But your worst-case scenario cannot be topped :)

How do I push to GitHub under a different username?

If after running git push Git asks for a password of user, but you would like to push as new_user, you may want to use git config remote.origin.url:

$ git push
[email protected]:either/branch/or/path's password:

At this point use ^C to quit git push and use following to push as new_user.

$ git config remote.origin.url
[email protected]:either/branch/or/path

$ git config remote.origin.url [email protected]:either/branch/or/path

$ git push
[email protected]:either/branch/or/path's password:

What is the apply function in Scala?

1 - Treat functions as objects.

2 - The apply method is similar to __call __ in Python, which allows you to use an instance of a given class as a function.

Check if Cookie Exists

Sorry, not enough rep to add a comment, but from zmbq's answer:

Anyway, to see if a cookie exists, you can check Cookies.Get(string), this will not modify the cookie collection.

is maybe not fully correct, as Cookies.Get(string) will actually create a cookie with that name, if it does not already exist. However, as he said, you need to be looking at Request.Cookies, not Response.Cookies So, something like:

bool cookieExists = HttpContext.Current.Request.Cookies["cookie_name"] != null;

Regex to split a CSV

Worked on this for a bit and came up with this solution:

(?:,|\n|^)("(?:(?:"")*[^"]*)*"|[^",\n]*|(?:\n|$))

Try it out here!

This solution handles "nice" CSV data like

"a","b",c,"d",e,f,,"g"

0: "a"
1: "b"
2: c
3: "d"
4: e
5: f
6:
7: "g"

and uglier things like

"""test"" one",test' two,"""test"" 'three'","""test 'four'"""

0: """test"" one"
1: test' two
2: """test"" 'three'"
3: """test 'four'"""

Here's an explanation of how it works:

(?:,|\n|^)      # all values must start at the beginning of the file,  
                #   the end of the previous line, or at a comma  
(               # single capture group for ease of use; CSV can be either...  
  "             # ...(A) a double quoted string, beginning with a double quote (")  
    (?:         #        character, containing any number (0+) of  
      (?:"")*   #          escaped double quotes (""), or  
      [^"]*     #          non-double quote characters  
    )*          #        in any order and any number of times  
  "             #        and ending with a double quote character  

  |             # ...or (B) a non-quoted value  

  [^",\n]*      # containing any number of characters which are not  
                # double quotes ("), commas (,), or newlines (\n)  

  |             # ...or (C) a single newline or end-of-file character,  
                #           used to capture empty values at the end of  
  (?:\n|$)      #           the file or at the ends of lines  
)

How to display Wordpress search results?

you need to include the Wordpress loop in your search.php this is example

search.php template file:

<?php get_header(); ?>
<?php
$s=get_search_query();
$args = array(
                's' =>$s
            );
    // The Query
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) {
        _e("<h2 style='font-weight:bold;color:#000'>Search Results for: ".get_query_var('s')."</h2>");
        while ( $the_query->have_posts() ) {
           $the_query->the_post();
                 ?>
                    <li>
                        <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
                    </li>
                 <?php
        }
    }else{
?>
        <h2 style='font-weight:bold;color:#000'>Nothing Found</h2>
        <div class="alert alert-info">
          <p>Sorry, but nothing matched your search criteria. Please try again with some different keywords.</p>
        </div>
<?php } ?>

<?php get_sidebar(); ?>
<?php get_footer(); ?>

How to reload page the page with pagination in Angular 2?

This should technically be achievable using window.location.reload():

HTML:

<button (click)="refresh()">Refresh</button>

TS:

refresh(): void {
    window.location.reload();
}

Update:

Here is a basic StackBlitz example showing the refresh in action. Notice the URL on "/hello" path is retained when window.location.reload() is executed.

MySQL trigger if condition exists

Try to do...

 DELIMITER $$
        CREATE TRIGGER aumentarsalario 
        BEFORE INSERT 
        ON empregados
        FOR EACH ROW
        BEGIN
          if (NEW.SALARIO < 900) THEN 
             set NEW.SALARIO = NEW.SALARIO + (NEW.SALARIO * 0.1);
          END IF;
        END $$
  DELIMITER ;

Selenium IDE - Command to wait for 5 seconds

For those working with ant, I use this to indicate a pause of 5 seconds:

<tr>
    <td>pause</td>
    <td>5000</td>
    <td></td>
</tr>

That is, target: 5000 and value empty. As the reference indicates:

pause(waitTime)

Arguments:

  • waitTime - the amount of time to sleep (in milliseconds)

Wait for the specified amount of time (in milliseconds)

powershell - list local users and their groups

Expanding on mjswensen's answer, the command without the filter could take minutes, but the filtered command is almost instant.

PowerShell - List local user accounts

Fast way

Get-WmiObject -Class Win32_UserAccount -Filter  "LocalAccount='True'" | select name, fullname

Slow way

Get-WmiObject -Class Win32_UserAccount |? {$_.localaccount -eq $true} | select name, fullname

How to check if a process is running via a batch script

The answer provided by Matt Lacey works for Windows XP. However, in Windows Server 2003 the line

 tasklist /FI "IMAGENAME eq notepad.exe" /FO CSV > search.log

returns

INFO: No tasks are running which match the specified criteria.

which is then read as the process is running.

I don't have a heap of batch scripting experience, so my soulution is to then search for the process name in the search.log file and pump the results into another file and search that for any output.

tasklist /FI "IMAGENAME eq notepad.exe" /FO CSV > search.log

FINDSTR notepad.exe search.log > found.log

FOR /F %%A IN (found.log) DO IF %%~zA EQU 0 GOTO end

start notepad.exe

:end

del search.log
del found.log

I hope this helps someone else.

MySQL - SELECT * INTO OUTFILE LOCAL ?

You can achieve what you want with the mysql console with the -s (--silent) option passed in.

It's probably a good idea to also pass in the -r (--raw) option so that special characters don't get escaped. You can use this to pipe queries like you're wanting.

mysql -u username -h hostname -p -s -r -e "select concat('this',' ','works')"

EDIT: Also, if you want to remove the column name from your output, just add another -s (mysql -ss -r etc.)

Convert Unix timestamp into human readable date using MySQL

You can use the DATE_FORMAT function. Here's a page with examples, and the patterns you can use to select different date components.

How to import an existing directory into Eclipse?

I Using below simple way to create a project 1- First in a directory that desire to make it project, create a .project file with below contents:

<projectDescription>
    <name>Project-Name</name>
    <comment></comment>
    <projects>
    </projects>
    <buildSpec>
    </buildSpec>
    <natures>
    </natures>
</projectDescription>

2- Now instead of "Project-Name", write your project name, maybe current directory name

3- Now save this file to directory that desire to make that directory as project with name ".project" ( for save like this, use Notepad )

4- Now go to Eclips and open project and add your files to it.

get selected value in datePicker and format it

var dateObject = $("#datePickerInput").datepicker('getDate');
$.datepicker.formatDate('dd MM, yy', dateObject);

What's the difference between fill_parent and wrap_content?

Either attribute can be applied to View's (visual control) horizontal or vertical size. It's used to set a View or Layouts size based on either it's contents or the size of it's parent layout rather than explicitly specifying a dimension.

fill_parent (deprecated and renamed MATCH_PARENT in API Level 8 and higher)

Setting the layout of a widget to fill_parent will force it to expand to take up as much space as is available within the layout element it's been placed in. It's roughly equivalent of setting the dockstyle of a Windows Form Control to Fill.

Setting a top level layout or control to fill_parent will force it to take up the whole screen.

wrap_content

Setting a View's size to wrap_content will force it to expand only far enough to contain the values (or child controls) it contains. For controls -- like text boxes (TextView) or images (ImageView) -- this will wrap the text or image being shown. For layout elements it will resize the layout to fit the controls / layouts added as its children.

It's roughly the equivalent of setting a Windows Form Control's Autosize property to True.

Online Documentation

There's some details in the Android code documentation here.

Alternative to iFrames with HTML5

This also does seem to work, although W3C specifies it is not intended "for an external (typically non-HTML) application or interactive content"

<embed src="http://www.somesite.com" width=200 height=200 />

More info: http://www.w3.org/wiki/HTML/Elements/embed http://www.w3schools.com/tags/tag_embed.asp

How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops

Here is a regex_subst() function. Examples:

=regex_subst("watermellon", "[aeiou]", "")
---> wtrmlln
=regex_subst("watermellon", "[^aeiou]", "")
---> aeeo

Here is the simplified code (simpler for me, anyway). I couldn't figure out how to build a suitable output pattern using the above to work like my examples:

Function regex_subst( _
     strInput As String _
   , matchPattern As String _
   , Optional ByVal replacePattern As String = "" _
) As Variant
    Dim inputRegexObj As New VBScript_RegExp_55.RegExp

    With inputRegexObj
        .Global = True
        .MultiLine = True
        .IgnoreCase = False
        .Pattern = matchPattern
    End With

    regex_subst = inputRegexObj.Replace(strInput, replacePattern)
End Function

Securing a password in a properties file

enter image description here

Jasypt provides the org.jasypt.properties.EncryptableProperties class for loading, managing and transparently decrypting encrypted values in .properties files, allowing the mix of both encrypted and not-encrypted values in the same file.

http://www.jasypt.org/encrypting-configuration.html

By using an org.jasypt.properties.EncryptableProperties object, an application would be able to correctly read and use a .properties file like this:

datasource.driver=com.mysql.jdbc.Driver 
datasource.url=jdbc:mysql://localhost/reportsdb 
datasource.username=reportsUser 
datasource.password=ENC(G6N718UuyPE5bHyWKyuLQSm02auQPUtm) 

Note that the database password is encrypted (in fact, any other property could also be encrypted, be it related with database configuration or not).

How do we read this value? like this:

/*
* First, create (or ask some other component for) the adequate encryptor for   
* decrypting the values in our .properties file.   
*/  
StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();     
encryptor.setPassword("jasypt"); // could be got from web, env variable...    
/*   
* Create our EncryptableProperties object and load it the usual way.   
*/  
Properties props = new EncryptableProperties(encryptor);  
props.load(new FileInputStream("/path/to/my/configuration.properties"));

/*   
* To get a non-encrypted value, we just get it with getProperty...   
*/  
String datasourceUsername = props.getProperty("datasource.username");

/*   
* ...and to get an encrypted value, we do exactly the same. Decryption will   
* be transparently performed behind the scenes.   
*/ 
String datasourcePassword = props.getProperty("datasource.password");

 // From now on, datasourcePassword equals "reports_passwd"...

JQuery How to extract value from href tag?

I see two options here

var link = $('a').attr('href');
var equalPosition = link.indexOf('='); //Get the position of '='
var number = link.substring(equalPosition + 1); //Split the string and get the number.

I dont know if you're gonna use it for paging and have the text in the <a>-tag as you have it, but if you should you can also do

var number = $('a').text();

Why are there two ways to unstage a file in Git?

git rm --cached is used to remove a file from the index. In the case where the file is already in the repo, git rm --cached will remove the file from the index, leaving it in the working directory and a commit will now remove it from the repo as well. Basically, after the commit, you would have unversioned the file and kept a local copy.

git reset HEAD file ( which by default is using the --mixed flag) is different in that in the case where the file is already in the repo, it replaces the index version of the file with the one from repo (HEAD), effectively unstaging the modifications to it.

In the case of unversioned file, it is going to unstage the entire file as the file was not there in the HEAD. In this aspect git reset HEAD file and git rm --cached are same, but they are not same ( as explained in the case of files already in the repo)

To the question of Why are there 2 ways to unstage a file in git? - there is never really only one way to do anything in git. that is the beauty of it :)

how to pass command line arguments to main method dynamically

If you want to launch VM by sending arguments, you should send VM arguments and not Program arguments.

Program arguments are arguments that are passed to your application, which are accessible via the "args" String array parameter of your main method. VM arguments are arguments such as System properties that are passed to the JavaSW interpreter. The Debug configuration above is essentially equivalent to:

java -DsysProp1=sp1 -DsysProp2=sp2 test.ArgsTest pro1 pro2 pro3

The VM arguments go after the call to your Java interpreter (ie, 'java') and before the Java class. Program arguments go after your Java class.

Consider a program ArgsTest.java:

package test;

import java.io.IOException;

    public class ArgsTest {

        public static void main(String[] args) throws IOException {

            System.out.println("Program Arguments:");
            for (String arg : args) {
                System.out.println("\t" + arg);
            }

            System.out.println("System Properties from VM Arguments");
            String sysProp1 = "sysProp1";
            System.out.println("\tName:" + sysProp1 + ", Value:" + System.getProperty(sysProp1));
            String sysProp2 = "sysProp2";
            System.out.println("\tName:" + sysProp2 + ", Value:" + System.getProperty(sysProp2));

        }
    }

If given input as,

java -DsysProp1=sp1 -DsysProp2=sp2 test.ArgsTest pro1 pro2 pro3 

in the commandline, in project bin folder would give the following result:

Program Arguments:
  pro1
  pro2
  pro3
System Properties from VM Arguments
  Name:sysProp1, Value:sp1
  Name:sysProp2, Value:sp2

Mobile overflow:scroll and overflow-scrolling: touch // prevent viewport "bounce"

There's a great blog post on this here:

http://www.kylejlarson.com/blog/2011/fixed-elements-and-scrolling-divs-in-ios-5/

Along with a demo here:

http://www.kylejlarson.com/files/iosdemo/

In summary, you can use the following on a div containing your main content:

.scrollable {
    position: absolute;
    top: 50px;
    left: 0;
    right: 0;
    bottom: 0;
    overflow: scroll;
    -webkit-overflow-scrolling: touch;
}

The problem I think you're describing is when you try to scroll up within a div that is already at the top - it then scrolls up the page instead of up the div and causes a bounce effect at the top of the page. I think your question is asking how to get rid of this?

In order to fix this, the author suggests that you use ScrollFix to auto increase the height of scrollable divs.

It's also worth noting that you can use the following to prevent the user from scrolling up e.g. in a navigation element:

document.addEventListener('touchmove', function(event) {
   if(event.target.parentNode.className.indexOf('noBounce') != -1 
|| event.target.className.indexOf('noBounce') != -1 ) {
    event.preventDefault(); }
}, false);

Unfortunately there are still some issues with ScrollFix (e.g. when using form fields), but the issues list on ScrollFix is a good place to look for alternatives. Some alternative approaches are discussed in this issue.

Other alternatives, also mentioned in the blog post, are Scrollability and iScroll

time.sleep -- sleeps thread or process?

It blocks the thread. If you look in Modules/timemodule.c in the Python source, you'll see that in the call to floatsleep(), the substantive part of the sleep operation is wrapped in a Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS block, allowing other threads to continue to execute while the current one sleeps. You can also test this with a simple python program:

import time
from threading import Thread

class worker(Thread):
    def run(self):
        for x in xrange(0,11):
            print x
            time.sleep(1)

class waiter(Thread):
    def run(self):
        for x in xrange(100,103):
            print x
            time.sleep(5)

def run():
    worker().start()
    waiter().start()

Which will print:

>>> thread_test.run()
0
100
>>> 1
2
3
4
5
101
6
7
8
9
10
102

How to get the date and time values in a C program?

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

struct date
{
    int month;
    int day;
    int year;
};

int calcN(struct date d)
{
    int N;
    int f(struct date d);
    int g(int m);

    N = 1461 * f(d) / 4 + 153 * g(d.month) / 5 + d.day;

    if(d.year < 1700 || (d.year == 1700 && d.month < 3))
    {
        printf("Date must be after February 29th, 1700\n");

        return 0;
    }
    else if(d.year < 1800 || (d.year == 1800 && d.month < 3))
        N += 2;
    else if(d.year < 1900 || (d.year == 1900 && d.month < 3))
        N += 1;    

    return N;
}

int f(struct date d)
{
    if(d.month <= 2)
        d.year -= 1;

    return d.year;
}

int g(int m)
{
    if(m <=2)
        m += 13;
    else
        m += 1;
    
    return m;
}

int main(void)
{
    int calcN(struct date d);
    struct date d1, d2;
    int N1, N2;
    time_t t;

    time(&t);
    struct tm *now = localtime(&t);


    d1.month = now->tm_mon + 1;
    d1.day = now->tm_mday;
    d1.year = now->tm_year + 1900;

    printf("Today's date: %02i/%02i/%i\n", d1.month, d1.day, d1.year);

    N1 = calcN(d1);

    printf("Enter birthday (mm dd yyyy): ");
    scanf("%i%i%i", &d2.month, &d2.day, &d2.year);

    N2 = calcN(d2);

    if(N2 == 0)
        return 0;

    printf("Number of days since birthday: %i\n", N1 - N2);

    return 0;
}

How to revert initial git commit?

All what you have to do is to revert the commit.

git revert {commit_id}'

Then push it

git push origin -f