Programs & Examples On #Nscollectionviewitem

How to get row number from selected rows in Oracle

you can just do

select rownum, l.* from student  l where name like %ram%

this assigns the row number as the rows are fetched (so no guaranteed ordering of course).

if you wanted to order first do:

select rownum, l.*
  from (select * from student l where name like %ram% order by...) l;

How do you copy the contents of an array to a std::vector in C++ without looping?

int dataArray[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };//source

unsigned dataArraySize = sizeof(dataArray) / sizeof(int);

std::vector<int> myvector (dataArraySize );//target

std::copy ( myints, myints+dataArraySize , myvector.begin() );

//myvector now has 1,2,3,...10 :-)

How to get first and last element in an array in java?

I think there is only one intuitive solution and it is:

int[] someArray = {1,2,3,4,5};
int first = someArray[0];
int last = someArray[someArray.length - 1];
System.out.println("First: " + first + "\n" + "Last: " + last);

Output:

First: 1
Last: 5

Printing variables in Python 3.4

The problem seems to be a mis-placed ). In your sample you have the % outside of the print(), you should move it inside:

Use this:

print("%s. %s appears %s times." % (str(i), key, str(wordBank[key])))

Inserting created_at data with Laravel

$data = array();
$data['created_at'] =new \DateTime();
DB::table('practice')->insert($data);

How can I pass arguments to anonymous functions in JavaScript?

The delegates:

function displayMessage(message, f)
{
    f(message); // execute function "f" with variable "message"
}

function alerter(message)
{
    alert(message);
}

function writer(message)
{
    document.write(message);
}

Running the displayMessage function:

function runDelegate()
{
    displayMessage("Hello World!", alerter); // alert message

    displayMessage("Hello World!", writer); // write message to DOM
}

Android: Create a toggle button with image and no text

ToggleButton inherits from TextView so you can set drawables to be displayed at the 4 borders of the text. You can use that to display the icon you want on top of the text and hide the actual text

<ToggleButton
    android:id="@+id/toggleButton1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:drawableTop="@android:drawable/ic_menu_info_details"
    android:gravity="center"
    android:textOff=""
    android:textOn=""
    android:textSize="0dp" />

The result compared to regular ToggleButton looks like

enter image description here

The seconds option is to use an ImageSpan to actually replace the text with an image. Looks slightly better since the icon is at the correct position but can't be done with layout xml directly.

You create a plain ToggleButton

<ToggleButton
    android:id="@+id/toggleButton3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:checked="false" />

Then set the "text" programmatially

ToggleButton button = (ToggleButton) findViewById(R.id.toggleButton3);
ImageSpan imageSpan = new ImageSpan(this, android.R.drawable.ic_menu_info_details);
SpannableString content = new SpannableString("X");
content.setSpan(imageSpan, 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
button.setText(content);
button.setTextOn(content);
button.setTextOff(content);

The result here in the middle - icon is placed slightly lower since it takes the place of the text.

enter image description here

Remove last specific character in a string c#

Dim psValue As String = "1,5,12,34,123,12"
psValue = psValue.Substring(0, psValue.LastIndexOf(","))

output:

1,5,12,34,123

How to sum all the values in a dictionary?

d = {'key1': 1,'key2': 14,'key3': 47}
sum1 = sum(d[item] for item in d)
print(sum1)

you can do it using the for loop

Laravel eloquent update record without loading from database

Use property exists:

$post = new Post();
$post->exists = true;
$post->id = 3; //already exists in database.
$post->title = "Updated title";
$post->save();

Here is the API documentation: http://laravel.com/api/5.0/Illuminate/Database/Eloquent/Model.html

console.log(result) returns [object Object]. How do I get result.name?

Try adding JSON.stringify(result) to convert the JS Object into a JSON string.

From your code I can see you are logging the result in error which is called if the AJAX request fails, so I'm not sure how you'd go about accessing the id/name/etc. then (you are checking for success inside the error condition!).

Note that if you use Chrome's console you should be able to browse through the object without having to stringify the JSON, which makes it easier to debug.

Typescript: How to define type for a function callback (as any function type, not universal any) used in a method parameter

There are four abstract function types, you can use them separately when you know your function will take an argument(s) or not, will return a data or not.

export declare type fEmptyVoid = () => void;
export declare type fEmptyReturn = () => any;
export declare type fArgVoid = (...args: any[]) => void;
export declare type fArgReturn = (...args: any[]) => any;

like this:

public isValid: fEmptyReturn = (): boolean => true;
public setStatus: fArgVoid = (status: boolean): void => this.status = status;

For use only one type as any function type we can combine all abstract types together, like this:

export declare type fFunction = fEmptyVoid | fEmptyReturn | fArgVoid | fArgReturn;

then use it like:

public isValid: fFunction = (): boolean => true;
public setStatus: fFunction = (status: boolean): void => this.status = status;

In the example above everything is correct. But the usage example in bellow is not correct from the point of view of most code editors.

// you can call this function with any type of function as argument
public callArgument(callback: fFunction) {

    // but you will get editor error if call callback argument like this
    callback();
}

Correct call for editors is like this:

public callArgument(callback: fFunction) {

    // pay attention in this part, for fix editor(s) error
    (callback as fFunction)();
}

Get random sample from list while maintaining ordering of items?

Apparently random.sample was introduced in python 2.3

so for version under that, we can use shuffle (example for 4 items):

myRange =  range(0,len(mylist)) 
shuffle(myRange)
coupons = [ bestCoupons[i] for i in sorted(myRange[:4]) ]

What are rvalues, lvalues, xvalues, glvalues, and prvalues?

IMHO, the best explanation about its meaning gave us Stroustrup + take into account examples of Dániel Sándor and Mohan:

Stroustrup:

Now I was seriously worried. Clearly we were headed for an impasse or a mess or both. I spent the lunchtime doing an analysis to see which of the properties (of values) were independent. There were only two independent properties:

  • has identity – i.e. and address, a pointer, the user can determine whether two copies are identical, etc.
  • can be moved from – i.e. we are allowed to leave to source of a "copy" in some indeterminate, but valid state

This led me to the conclusion that there are exactly three kinds of values (using the regex notational trick of using a capital letter to indicate a negative – I was in a hurry):

  • iM: has identity and cannot be moved from
  • im: has identity and can be moved from (e.g. the result of casting an lvalue to a rvalue reference)
  • Im: does not have identity and can be moved from.

    The fourth possibility, IM, (doesn’t have identity and cannot be moved) is not useful in C++ (or, I think) in any other language.

In addition to these three fundamental classifications of values, we have two obvious generalizations that correspond to the two independent properties:

  • i: has identity
  • m: can be moved from

This led me to put this diagram on the board: enter image description here

Naming

I observed that we had only limited freedom to name: The two points to the left (labeled iM and i) are what people with more or less formality have called lvalues and the two points on the right (labeled m and Im) are what people with more or less formality have called rvalues. This must be reflected in our naming. That is, the left "leg" of the W should have names related to lvalue and the right "leg" of the W should have names related to rvalue. I note that this whole discussion/problem arise from the introduction of rvalue references and move semantics. These notions simply don’t exist in Strachey’s world consisting of just rvalues and lvalues. Someone observed that the ideas that

  • Every value is either an lvalue or an rvalue
  • An lvalue is not an rvalue and an rvalue is not an lvalue

are deeply embedded in our consciousness, very useful properties, and traces of this dichotomy can be found all over the draft standard. We all agreed that we ought to preserve those properties (and make them precise). This further constrained our naming choices. I observed that the standard library wording uses rvalue to mean m (the generalization), so that to preserve the expectation and text of the standard library the right-hand bottom point of the W should be named rvalue.

This led to a focused discussion of naming. First, we needed to decide on lvalue. Should lvalue mean iM or the generalization i? Led by Doug Gregor, we listed the places in the core language wording where the word lvalue was qualified to mean the one or the other. A list was made and in most cases and in the most tricky/brittle text lvalue currently means iM. This is the classical meaning of lvalue because "in the old days" nothing was moved; move is a novel notion in C++0x. Also, naming the topleft point of the W lvalue gives us the property that every value is an lvalue or an rvalue, but not both.

So, the top left point of the W is lvalue and the bottom right point is rvalue. What does that make the bottom left and top right points? The bottom left point is a generalization of the classical lvalue, allowing for move. So it is a generalized lvalue. We named it glvalue. You can quibble about the abbreviation, but (I think) not with the logic. We assumed that in serious use generalized lvalue would somehow be abbreviated anyway, so we had better do it immediately (or risk confusion). The top right point of the W is less general than the bottom right (now, as ever, called rvalue). That point represent the original pure notion of an object you can move from because it cannot be referred to again (except by a destructor). I liked the phrase specialized rvalue in contrast to generalized lvalue but pure rvalue abbreviated to prvalue won out (and probably rightly so). So, the left leg of the W is lvalue and glvalue and the right leg is prvalue and rvalue. Incidentally, every value is either a glvalue or a prvalue, but not both.

This leaves the top middle of the W: im; that is, values that have identity and can be moved. We really don’t have anything that guides us to a good name for those esoteric beasts. They are important to people working with the (draft) standard text, but are unlikely to become a household name. We didn’t find any real constraints on the naming to guide us, so we picked ‘x’ for the center, the unknown, the strange, the xpert only, or even x-rated.

Steve showing off the final product

Get random boolean in Java

Words in a text are always a source of randomness. Given a certain word, nothing can be inferred about the next word. For each word, we can take the ASCII codes of its letters, add those codes to form a number. The parity of this number is a good candidate for a random boolean.

Possible drawbacks:

  1. this strategy is based upon using a text file as a source for the words. At some point, the end of the file will be reached. However, you can estimate how many times you are expected to call the randomBoolean() function from your app. If you will need to call it about 1 million times, then a text file with 1 million words will be enough. As a correction, you can use a stream of data from a live source like an online newspaper.

  2. using some statistical analysis of the common phrases and idioms in a language, one can estimate the next word in a phrase, given the first words of the phrase, with some degree of accuracy. But statistically, these cases are rare, when we can accuratelly predict the next word. So, in most cases, the next word is independent on the previous words.

    package p01;

    import java.io.File; import java.nio.file.Files; import java.nio.file.Paths;

    public class Main {

    String words[];
    int currentIndex=0;
    
    public static String readFileAsString()throws Exception 
      { 
        String data = ""; 
        File file = new File("the_comedy_of_errors");
        //System.out.println(file.exists());
        data = new String(Files.readAllBytes(Paths.get(file.getName()))); 
        return data; 
      } 
    
    public void init() throws Exception
    {
        String data = readFileAsString(); 
        words = data.split("\\t| |,|\\.|'|\\r|\\n|:");
    }
    
    public String getNextWord() throws Exception
    {
        if(currentIndex>words.length-1)
            throw new Exception("out of words; reached end of file");
    
        String currentWord = words[currentIndex];
        currentIndex++;
    
        while(currentWord.isEmpty())
        {
            currentWord = words[currentIndex];
            currentIndex++;
        }
    
        return currentWord;
    }
    
    public boolean getNextRandom() throws Exception
    {
        String nextWord = getNextWord();
        int asciiSum = 0;
    
        for (int i = 0; i < nextWord.length(); i++){
            char c = nextWord.charAt(i);        
            asciiSum = asciiSum + (int) c;
        }
    
        System.out.println(nextWord+"-"+asciiSum);
    
        return (asciiSum%2==1) ;
    }
    
    public static void main(String args[]) throws Exception
    {
        Main m = new Main();
        m.init();
        while(true)
        {
            System.out.println(m.getNextRandom());
            Thread.sleep(100);
        }
    }
    

    }

In Eclipse, in the root of my project, there is a file called 'the_comedy_of_errors' (no extension) - created with File> New > File , where I pasted some content from here: http://shakespeare.mit.edu/comedy_errors/comedy_errors.1.1.html

Background color not showing in print preview

If you download Bootstrap without the "Print media styles" option, you will not have this problem and do not have to remove the "@media print" code manually in your bootstrap.css file.

Angular ng-class if else

Just make a rule for each case:

<div id="homePage" ng-class="{ 'center': page.isSelected(1) , 'left': !page.isSelected(1)  }">

Or use the ternary operator:

<div id="homePage" ng-class="page.isSelected(1) ? 'center' : 'left'">

Set div height to fit to the browser using CSS

Setting window full height for empty divs

1st solution with absolute positioning - FIDDLE

.div1 {
  position: absolute;
  top: 0;
  bottom: 0;
  width: 25%;
}
.div2 {
  position: absolute;
  top: 0;
  left: 25%;
  bottom: 0;
  width: 75%;
}

2nd solution with static (also can be used a relative) positioning & jQuery - FIDDLE

.div1 {
  float: left;
  width: 25%;
}
.div2 {
  float: left;
  width: 75%;
}

$(function(){
  $('.div1, .div2').css({ height: $(window).innerHeight() });
  $(window).resize(function(){
    $('.div1, .div2').css({ height: $(window).innerHeight() });
  });
});

How to pad a string to a fixed length with spaces in Python?

string = ""
name = raw_input() #The value at the field
length = input() #the length of the field
string += name
string += " "*(length-len(name)) # Add extra spaces

This will add the number of spaces needed, provided the field has length >= the length of the name provided

deleting rows in numpy array

The simplest way to delete rows and columns from arrays is the numpy.delete method.

Suppose I have the following array x:

x = array([[1,2,3],
        [4,5,6],
        [7,8,9]])

To delete the first row, do this:

x = numpy.delete(x, (0), axis=0)

To delete the third column, do this:

x = numpy.delete(x,(2), axis=1)

So you could find the indices of the rows which have a 0 in them, put them in a list or a tuple and pass this as the second argument of the function.

Getting attributes of a class

import re

class MyClass:
    a = "12"
    b = "34"

    def myfunc(self):
        return self.a

attributes = [a for a, v in MyClass.__dict__.items()
              if not re.match('<function.*?>', str(v))
              and not (a.startswith('__') and a.endswith('__'))]

For an instance of MyClass, such as

mc = MyClass()

use type(mc) in place of MyClass in the list comprehension. However, if one dynamically adds an attribute to mc, such as mc.c = "42", the attribute won't show up when using type(mc) in this strategy. It only gives the attributes of the original class.

To get the complete dictionary for a class instance, you would need to COMBINE the dictionaries of type(mc).__dict__ and mc.__dict__.

mc = MyClass()
mc.c = "42"

# Python 3.5
combined_dict = {**type(mc).__dict__, **mc.__dict__}

# Or Python < 3.5
def dict_union(d1, d2):
    z = d1.copy()
    z.update(d2)
    return z

combined_dict = dict_union(type(mc).__dict__, mc.__dict__)

attributes = [a for a, v in combined_dict.items()
              if not re.match('<function.*?>', str(v))
              and not (a.startswith('__') and a.endswith('__'))]

KERNELBASE.dll Exception 0xe0434352 offset 0x000000000000a49d

0xe0434352 is the SEH code for a CLR exception. If you don't understand what that means, stop and read A Crash Course on the Depths of Win32™ Structured Exception Handling. So your process is not handling a CLR exception. Don't shoot the messenger, KERNELBASE.DLL is just the unfortunate victim. The perpetrator is MyApp.exe.

There should be a minidump of the crash in DrWatson folders with a full stack, it will contain everything you need to root cause the issue.

I suggest you wire up, in your myapp.exe code, AppDomain.UnhandledException and Application.ThreadException, as appropriate.

How to make circular background using css?

You can use the :before and :after pseudo-classes to put a multi-layered background on a element.

#divID : before {
    background: url(someImage);
}

#div : after {
    background : url(someotherImage) -10% no-repeat;
}

cannot find module "lodash"

though npm install lodash would work, I think that it's a quick solution but there is a possibility that there are other modules not correctly installed in browser-sync.

lodash is part of browser-sync. The best solution is the one provided by Saebyeok. Re-install browser-sync and that should fix the problem.

Remove sensitive files and their commits from Git history

If you pushed to GitHub, force pushing is not enough, delete the repository or contact support

Even if you force push one second afterwards, it is not enough as explained below.

The only valid courses of action are:

  • is what leaked a changeable credential like a password?

    • yes: modify your passwords immediately, and consider using more OAuth and API keys!

    • no (naked pics):

      • do you care if all issues in the repository get nuked?

        • no: delete the repository

        • yes:

          • contact support
          • if the leak is very critical to you, to the point that you are willing to get some repository downtime to make it less likely to leak, make it private while you wait for GitHub support to reply to you

Force pushing a second later is not enough because:

If you delete the repository instead of just force pushing however, commits do disappear even from the API immediately and give 404, e.g. https://api.github.com/repos/cirosantilli/test-dangling-delete/commits/8c08448b5fbf0f891696819f3b2b2d653f7a3824 This works even if you recreate another repository with the same name.

To test this out, I have created a repo: https://github.com/cirosantilli/test-dangling and did:

git init
git remote add origin [email protected]:cirosantilli/test-dangling.git

touch a
git add .
git commit -m 0
git push

touch b
git add .
git commit -m 1
git push

touch c
git rm b
git add .
git commit --amend --no-edit
git push -f

See also: How to remove a dangling commit from GitHub?

git filter-repo is now officially recommended over git filter-branch

This is mentioned in the manpage of git filter-branch in Git 2.5 itself.

With git filter repo, you could either remove certain files with: Remove folder and its contents from git/GitHub's history

pip install git-filter-repo
git filter-repo --path path/to/remove1 --path path/to/remove2 --invert-paths

This automatically removes empty commits.

Or you can replace certain strings with: How to replace a string in a whole Git history?

git filter-repo --replace-text <(echo 'my_password==>xxxxxxxx')

Android View shadow

I know this is stupidly hacky,
but if you want to support under v21, here are my achievements.

rectangle_with_10dp_radius_white_bg_and_shadow.xml

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

    <!-- Shadow layers -->
    <item
        android:left="1dp"
        android:right="1dp"
        android:top="3dp">
        <shape>
            <corners android:radius="10dp" />
            <padding
                android:bottom="1.8dp"
                android:left="1dp"
                android:right="1dp"
                android:top="1dp" />
            <solid android:color="@color/shadow_hack_level_1" />
        </shape>
    </item>
    <item
        android:left="1dp"
        android:right="1dp"
        android:top="3dp">
        <shape>
            <corners android:radius="10dp" />
            <padding
                android:bottom="1.8dp"
                android:left="1dp"
                android:right="1dp"
                android:top="1dp" />
            <solid android:color="@color/shadow_hack_level_2" />
        </shape>
    </item>
    <item
        android:left="1dp"
        android:right="1dp"
        android:top="3dp">
        <shape>
            <corners android:radius="10dp" />
            <padding
                android:bottom="1.8dp"
                android:left="1dp"
                android:right="1dp"
                android:top="1dp" />
            <solid android:color="@color/shadow_hack_level_3" />
        </shape>
    </item>
    <item
        android:left="1dp"
        android:right="1dp"
        android:top="3dp">
        <shape>
            <corners android:radius="10dp" />
            <padding
                android:bottom="1.8dp"
                android:left="1dp"
                android:right="1dp"
                android:top="1dp" />
            <solid android:color="@color/shadow_hack_level_4" />
        </shape>
    </item>
    <item
        android:left="1dp"
        android:right="1dp"
        android:top="3dp">
        <shape>
            <corners android:radius="10dp" />
            <padding
                android:bottom="1.8dp"
                android:left="1dp"
                android:right="1dp"
                android:top="1dp" />
            <solid android:color="@color/shadow_hack_level_5" />
        </shape>
    </item>
    <item
        android:left="1dp"
        android:right="1dp"
        android:top="3dp">
        <shape>
            <corners android:radius="10dp" />
            <padding
                android:bottom="1.8dp"
                android:left="1dp"
                android:right="1dp"
                android:top="1dp" />
            <solid android:color="@color/shadow_hack_level_6" />
        </shape>
    </item>
    <item
        android:left="1dp"
        android:right="1dp"
        android:top="3dp">
        <shape>
            <corners android:radius="10dp" />
            <padding
                android:bottom="1.8dp"
                android:left="1dp"
                android:right="1dp"
                android:top="1dp" />
            <solid android:color="@color/shadow_hack_level_7" />
        </shape>
    </item>
    <item
        android:left="1dp"
        android:right="1dp"
        android:top="3dp">
        <shape>
            <corners android:radius="10dp" />
            <padding
                android:bottom="1.8dp"
                android:left="1dp"
                android:right="1dp"
                android:top="1dp" />
            <solid android:color="@color/shadow_hack_level_8" />
        </shape>
    </item>
    <item
        android:left="1dp"
        android:right="1dp"
        android:top="3dp">
        <shape>
            <corners android:radius="10dp" />
            <padding
                android:bottom="1.8dp"
                android:left="1dp"
                android:right="1dp"
                android:top="1dp" />
            <solid android:color="@color/shadow_hack_level_9" />
        </shape>
    </item>
    <item
        android:left="1dp"
        android:right="1dp"
        android:top="3dp">
        <shape>
            <corners android:radius="10dp" />
            <padding
                android:bottom="1.8dp"
                android:left="1dp"
                android:right="1dp"
                android:top="1dp" />
            <solid android:color="@color/shadow_hack_level_10" />
        </shape>
    </item>

    <!-- Background layer -->
    <item>
        <shape>
            <solid android:color="@android:color/white" />
            <corners android:radius="10dp" />
        </shape>
    </item>

</layer-list>

rectangle_with_10dp_radius_white_bg_and_shadow.xml (v21)

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="@android:color/white" />
    <corners android:radius="10dp" />
</shape>

view_incoming.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/rectangle_with_10dp_radius_white_bg_and_shadow"
    android:elevation="7dp"
    android:gravity="center"
    android:minWidth="240dp"
    android:minHeight="240dp"
    android:orientation="horizontal"
    android:padding="16dp"
    tools:targetApi="lollipop">

    <TextView
        android:id="@+id/text1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        tools:text="Hello World !" />

</LinearLayout>

Here is result:

Under v21 (this is which you made with xml) enter image description here

Above v21 (real elevation rendering) enter image description here

  • The one significant difference is it will occupy the inner space from the view so your actual content area can be smaller than >= lollipop devices.

How to sum columns in a dataTable?

Try this:

            DataTable dt = new DataTable();
            int sum = 0;
            foreach (DataRow dr in dt.Rows)
            {
                foreach (DataColumn dc in dt.Columns)
                {
                    sum += (int)dr[dc];
                }
            } 

filter items in a python dictionary where keys contain a specific string

input = {"A":"a", "B":"b", "C":"c"}
output = {k:v for (k,v) in input.items() if key_satifies_condition(k)}

PowerShell script to return versions of .NET Framework on a machine?

Here's my take on this question following the msft documentation:

$gpParams = @{
    Path        = 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full'
    ErrorAction = 'SilentlyContinue'
}
$release = Get-ItemProperty @gpParams | Select-Object -ExpandProperty Release

".NET Framework$(
    switch ($release) {
        ({ $_ -ge 528040 }) { ' 4.8'; break }
        ({ $_ -ge 461808 }) { ' 4.7.2'; break }
        ({ $_ -ge 461308 }) { ' 4.7.1'; break }
        ({ $_ -ge 460798 }) { ' 4.7'; break }
        ({ $_ -ge 394802 }) { ' 4.6.2'; break }
        ({ $_ -ge 394254 }) { ' 4.6.1'; break }
        ({ $_ -ge 393295 }) { ' 4.6'; break }
        ({ $_ -ge 379893 }) { ' 4.5.2'; break }
        ({ $_ -ge 378675 }) { ' 4.5.1'; break }
        ({ $_ -ge 378389 }) { ' 4.5'; break }
        default { ': 4.5+ not installed.' }
    }
)"

This example works with all PowerShell versions and will work in perpetuity as 4.8 is the last .NET Framework version.

Adding Google Play services version to your app's manifest?

I got the solution.

  • Step 1: Right click on your project at Package explorer(left side in eclipse)
  • Step 2: goto Android.
  • Step 3: In Library section Add Library...(google-play-services_lib)
    see below buttes

    • Copy the library project at

    <android-sdk>/extras/google/google_play_services/libproject/google-play-services_lib/

    • to the location where you maintain your Android app projects. If you are using Eclipse, import the library project into your workspace. Click File > Import, select Android > Existing Android Code into Workspace, and browse to the copy of the library project to import it.
    • Click Here For more.
  • Step 4: Click Apply
  • Step 5: Click ok
  • Step 6: Refresh you app from package Explorer.
  • Step 7: you will see error is gone.

ng-if, not equal to?

Try below solution

ng-if="details.Payment[0].Status != '0'"

Use below condition(! prefix with true condition) instead of above

ng-if="!details.Payment[0].Status == '0'"

Modifying a query string without reloading the page

I want to improve Fabio's answer and create a function which adds custom key to the URL string without reloading the page.

function insertUrlParam(key, value) {
    if (history.pushState) {
        let searchParams = new URLSearchParams(window.location.search);
        searchParams.set(key, value);
        let newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?' + searchParams.toString();
        window.history.pushState({path: newurl}, '', newurl);
    }
}

Add newly created specific folder to .gitignore in Git

Try /public_html/stats/* ?

But since the files in git status reported as to be commited that means you've already added them manually. In which case, of course, it's a bit too late to ignore. You can git rm --cache them (IIRC).

What is the lifetime of a static variable in a C++ function?

The existing explanations aren't really complete without the actual rule from the Standard, found in 6.7:

The zero-initialization of all block-scope variables with static storage duration or thread storage duration is performed before any other initialization takes place. Constant initialization of a block-scope entity with static storage duration, if applicable, is performed before its block is first entered. An implementation is permitted to perform early initialization of other block-scope variables with static or thread storage duration under the same conditions that an implementation is permitted to statically initialize a variable with static or thread storage duration in namespace scope. Otherwise such a variable is initialized the first time control passes through its declaration; such a variable is considered initialized upon the completion of its initialization. If the initialization exits by throwing an exception, the initialization is not complete, so it will be tried again the next time control enters the declaration. If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization. If control re-enters the declaration recursively while the variable is being initialized, the behavior is undefined.

How do you determine the ideal buffer size when using FileInputStream?

Yes, it's probably dependent on various things - but I doubt it will make very much difference. I tend to opt for 16K or 32K as a good balance between memory usage and performance.

Note that you should have a try/finally block in the code to make sure the stream is closed even if an exception is thrown.

In bootstrap how to add borders to rows without adding up?

On my projects i give all rows the class "borders" which I want it to display more like a table with even borders. Giving each child element a border on the bottom and right and the first element of each row a left border will make all of your boxes have an even border:

First give all of the rows children a border on the right and bottom

.borders div{
    border-right:1px solid #999;
    border-bottom:1px solid #999;
}

Next give the first child of each or a left border

.borders div:first-child{
    border-left:
    1px solid #999;
}

Last make sure to clear the borders for their child elements

.borders div > div{
    border:0;
}

HTML:

<div class="row borders">
    <div class="col-xs-5 col-md-2">Email</div>
    <div class="col-xs-7 col-md-4">[email protected]</div>
    <div class="col-xs-5 col-md-2">Phone</div>
    <div class="col-xs-7 col-md-4">555-123-4567</div>
</div>

PHP is_numeric or preg_match 0-9 validation

is_numeric would accept "-0.5e+12" as a valid ID.

How do I write the 'cd' command in a makefile?

Starting from GNU make 3.82 (July 2010), you can use the .ONESHELL special target to run all recipe lines in a single instantiation of the shell (bold emphasis mine):

  • New special target: .ONESHELL instructs make to invoke a single instance of the shell and provide it with the entire recipe, regardless of how many lines it contains.
.ONESHELL: # Only applies to all target
all:
    cd ~/some_dir
    pwd # Prints ~/some_dir if cd succeeded

another_rule:
    cd ~/some_dir
    pwd # Oops, prints ~

How to automatically add user account AND password with a Bash script?

The following works for me and tested on Ubuntu 14.04. It is a one liner that does not require any user input.

sudo useradd -p $(openssl passwd -1 $PASS) $USERNAME

Taken from @Tralemonkey

Server Discovery And Monitoring engine is deprecated

if you used typescript add config to the MongoOptions

const MongoOptions: MongoClientOptions = {
  useNewUrlParser: true,
  useUnifiedTopology: true,
};

      const client = await MongoClient.connect(url, MongoOptions);

if you not used typescript  
const MongoOptions= {
  useNewUrlParser: true,
  useUnifiedTopology: true,
};

Pandas : compute mean or std (standard deviation) over entire dataframe

You could convert the dataframe to be a single column with stack (this changes the shape from 5x3 to 15x1) and then take the standard deviation:

df.stack().std()         # pandas default degrees of freedom is one

Alternatively, you can use values to convert from a pandas dataframe to a numpy array before taking the standard deviation:

df.values.std(ddof=1)    # numpy default degrees of freedom is zero

Unlike pandas, numpy will give the standard deviation of the entire array by default, so there is no need to reshape before taking the standard deviation.

A couple of additional notes:

  • The numpy approach here is a bit faster than the pandas one, which is generally true when you have the option to accomplish the same thing with either numpy or pandas. The speed difference will depend on the size of your data, but numpy was roughly 10x faster when I tested a few different sized dataframes on my laptop (numpy version 1.15.4 and pandas version 0.23.4).

  • The numpy and pandas approaches here will not give exactly the same answers, but will be extremely close (identical at several digits of precision). The discrepancy is due to slight differences in implementation behind the scenes that affect how the floating point values get rounded.

Explanation of the UML arrows

A nice cheat sheet (http://loufranco.com/wp-content/uploads/2012/11/cheatsheet.pdf):

It covers:

  • Class Diagram
  • Sequence Diagram
  • Package Diagram
  • Object Diagram
  • Use Case Diagram

And provides a few samples.

Class Diagram Elements, like parent to child relationship , subclass relationship, interface and implementor, plus Sequence Diagram Elements

iterating over each character of a String in ruby 1.8.6 (each_char)

"ABCDEFG".chars.each do |char|
  puts char
end

also

"ABCDEFG".each_char {|char| p char}

Ruby version >2.5.1

Accessing MVC's model property from Javascript

Wrapping the model property around parens worked for me. You still get the same issue with Visual Studio complaining about the semi-colon, but it works.

var closedStatusId = @(Model.ClosedStatusId);

Check if my SSL Certificate is SHA1 or SHA2

You can check by visiting the site in your browser and viewing the certificate that the browser received. The details of how to do that can vary from browser to browser, but generally if you click or right-click on the lock icon, there should be an option to view the certificate details.

In the list of certificate fields, look for one called "Certificate Signature Algorithm". (For StackOverflow's certificate, its value is "PKCS #1 SHA-1 With RSA Encryption".)

An unhandled exception occurred during the execution of the current web request. ASP.NET

I had the same problem and found out that I had forgotten to include the script in the file which I want to include in the live site.

Also, you should try this:

bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));

VueJs get url query

I think you can simple call like this, this will give you result value.

this.$route.query.page

Look image $route is object in Vue Instance and you can access with this keyword and next you can select object properties like above one :

enter image description here

Have a look Vue-router document for selecting queries value :

Vue Router Object

FIFO class in Java

Queues are First In First Out structures. You request is pretty vague, but I am guessing that you need only the basic functionality which usually comes out with Queue structures. You can take a look at how you can implement it here.

With regards to your missing package, it is most likely because you will need to either download or create the package yourself by following that tutorial.

display data from SQL database into php/ html table

Here's a simple function I wrote to display tabular data without having to input each column name: (Also, be aware: Nested looping)

function display_data($data) {
    $output = '<table>';
    foreach($data as $key => $var) {
        $output .= '<tr>';
        foreach($var as $k => $v) {
            if ($key === 0) {
                $output .= '<td><strong>' . $k . '</strong></td>';
            } else {
                $output .= '<td>' . $v . '</td>';
            }
        }
        $output .= '</tr>';
    }
    $output .= '</table>';
    echo $output;
}

UPDATED FUNCTION BELOW

Hi Jack,

your function design is fine, but this function always misses the first dataset in the array. I tested that.

Your function is so fine, that many people will use it, but they will always miss the first dataset. That is why I wrote this amendment.

The missing dataset results from the condition if key === 0. If key = 0 only the columnheaders are written, but not the data which contains $key 0 too. So there is always missing the first dataset of the array.

You can avoid that by moving the if condition above the second foreach loop like this:

function display_data($data) {
    $output = "<table>";
    foreach($data as $key => $var) {
        //$output .= '<tr>';
        if($key===0) {
            $output .= '<tr>';
            foreach($var as $col => $val) {
                $output .= "<td>" . $col . '</td>';
            }
            $output .= '</tr>';
            foreach($var as $col => $val) {
                $output .= '<td>' . $val . '</td>';
            }
            $output .= '</tr>';
        }
        else {
            $output .= '<tr>';
            foreach($var as $col => $val) {
                $output .= '<td>' . $val . '</td>';
            }
            $output .= '</tr>';
        }
    }
    $output .= '</table>';
    echo $output;
}

Best regards and thanks - Axel Arnold Bangert - Herzogenrath 2016

and another update that removes redundant code blocks that hurt maintainability of the code.

function display_data($data) {
$output = '<table>';
foreach($data as $key => $var) {
    $output .= '<tr>';
    foreach($var as $k => $v) {
        if ($key === 0) {
            $output .= '<td><strong>' . $k . '</strong></td>';
        } else {
            $output .= '<td>' . $v . '</td>';
        }
    }
    $output .= '</tr>';
}
$output .= '</table>';
echo $output;

}

How to exclude file only from root folder in Git

If the above solution does not work for you, try this:

#1.1 Do NOT ignore file pattern in  any subdirectory
!*/config.php
#1.2 ...only ignore it in the current directory
/config.php

##########################

# 2.1 Ignore file pattern everywhere
config.php
# 2.2 ...but NOT in the current directory
!/config.php

How to Convert UTC Date To Local time Zone in MySql Select Query

SELECT CONVERT_TZ() will work for that.but its not working for me.

Why, what error do you get?

SELECT CONVERT_TZ(displaytime,'GMT','MET');

should work if your column type is timestamp, or date

http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_convert-tz

Test how this works:

SELECT CONVERT_TZ(a_ad_display.displaytime,'+00:00','+04:00');

Check your timezone-table

SELECT * FROM mysql.time_zone;
SELECT * FROM mysql.time_zone_name;

http://dev.mysql.com/doc/refman/5.5/en/time-zone-support.html

If those tables are empty, you have not initialized your timezone tables. According to link above you can use mysql_tzinfo_to_sql program to load the Time Zone Tables. Please try this

shell> mysql_tzinfo_to_sql /usr/share/zoneinfo

or if not working read more: http://dev.mysql.com/doc/refman/5.5/en/mysql-tzinfo-to-sql.html

CSS: how do I create a gap between rows in a table?

You could also just modify the height for each row using CSS.

<head>
 <style>
 tr {
   height:40px;
 }
</style>
</head>

<body>
<table>

<tr> <td>One</td> <td>Two</td> </tr>
<tr> <td>Three</td> <td>Four</td> </tr>
<tr> <td>Five</td> <td>Six</td> </tr>

</table>
</body>

You could also modify the height of the <td> element, it should give you the same result.

Check if a div does NOT exist with javascript

Try getting the element with the ID and check if the return value is null:

document.getElementById('some_nonexistent_id') === null

If you're using jQuery, you can do:

$('#some_nonexistent_id').length === 0

How can I use random numbers in groovy?

Generally, I find RandomUtils (from Apache commons lang) an easier way to generate random numbers than java.util.Random

CSS :selected pseudo class similar to :checked, but for <select> elements

the :checked pseudo-class initially applies to such elements that have the HTML4 selected and checked attributes

Source: w3.org


So, this CSS works, although styling the color is not possible in every browser:

option:checked { color: red; }

An example of this in action, hiding the currently selected item from the drop down list.

_x000D_
_x000D_
option:checked { display:none; }
_x000D_
<select>_x000D_
    <option>A</option>_x000D_
    <option>B</option>_x000D_
    <option>C</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_


To style the currently selected option in the closed dropdown as well, you could try reversing the logic:

select { color: red; }
option:not(:checked) { color: black; } /* or whatever your default style is */

Maven home (M2_HOME) not being picked up by IntelliJ IDEA

Another option is to add the M2_HOME variable at: IntelliJ IDEA=>Preferences=>IDE Settings=>Path Variables

After a restart of IntelliJ, IntelliJ IDEA=>Preferences=>Project Settings=>Maven=>Maven home directory should be set to your M2_HOME variable.

Regular expression \p{L} and \p{N}

These are Unicode property shortcuts (\p{L} for Unicode letters, \p{N} for Unicode digits). They are supported by .NET, Perl, Java, PCRE, XML, XPath, JGSoft, Ruby (1.9 and higher) and PHP (since 5.1.0)

At any rate, that's a very strange regex. You should not be using alternation when a character class would suffice:

[\p{L}\p{N}_.-]*

Must issue a STARTTLS command first

I also faced the same issue while I was building email notification application. you just need to add one line. Below one saved my day.

props.put("mail.smtp.starttls.enable", "true");

com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. h13-v6sm10627790pgp.13 - gsmtp

at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2108)
at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1609)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1117)
at javax.mail.Transport.send0(Transport.java:195)
at javax.mail.Transport.send(Transport.java:124)
at com.smruti.email.EmailProject.EmailSend.main(EmailSend.java:99)

Hope this helps you.

extracting days from a numpy.timedelta64 value

You can convert it to a timedelta with a day precision. To extract the integer value of days you divide it with a timedelta of one day.

>>> x = np.timedelta64(2069211000000000, 'ns')
>>> days = x.astype('timedelta64[D]')
>>> days / np.timedelta64(1, 'D')
23

Or, as @PhillipCloud suggested, just days.astype(int) since the timedelta is just a 64bit integer that is interpreted in various ways depending on the second parameter you passed in ('D', 'ns', ...).

You can find more about it here.

when exactly are we supposed to use "public static final String"?

Usually for defining constants, that you reuse at many places making it single point for change, used within single class or shared across packages. Making a variable final avoid accidental changes.

presenting ViewController with NavigationViewController swift

Calling presentViewController presents the view controller modally, outside the existing navigation stack; it is not contained by your UINavigationController or any other. If you want your new view controller to have a navigation bar, you have two main options:

Option 1. Push the new view controller onto your existing navigation stack, rather than presenting it modally:

let VC1 = self.storyboard!.instantiateViewControllerWithIdentifier("MyViewController") as! ViewController
self.navigationController!.pushViewController(VC1, animated: true)

Option 2. Embed your new view controller into a new navigation controller and present the new navigation controller modally:

let VC1 = self.storyboard!.instantiateViewControllerWithIdentifier("MyViewController") as! ViewController
let navController = UINavigationController(rootViewController: VC1) // Creating a navigation controller with VC1 at the root of the navigation stack.
self.present(navController, animated:true, completion: nil)

Bear in mind that this option won't automatically include a "back" button. You'll have to build in a close mechanism yourself.

Which one is best for you is a human interface design question, but it's normally clear what makes the most sense.

Bulk Insert into Oracle database: Which is better: FOR Cursor loop or a simple Select?

A simple insert/select like your 2nd option is far preferable. For each insert in the 1st option you require a context switch from pl/sql to sql. Run each with trace/tkprof and examine the results.

If, as Michael mentions, your rollback cannot handle the statement then have your dba give you more. Disk is cheap, while partial results that come from inserting your data in multiple passes is potentially quite expensive. (There is almost no undo associated with an insert.)

Changes in import statement python3

Added another case to Michal Górny's answer:

Note that relative imports are based on the name of the current module. Since the name of the main module is always "__main__", modules intended for use as the main module of a Python application must always use absolute imports.

How to know Hive and Hadoop versions from command prompt?

I was able to get the version of installed Hadoop 3.0.3 by the following command
$HADOOP_HOME/bin$ ./hadoop version
which gave me the following output

Hadoop 3.0.3
Source code repository https://[email protected]/repos/asf/hadoop.git -r 37fd7d752db73d984dc31e0cdfd590d252f5e075
Compiled by yzhang on 2018-05-31T17:12Z
Compiled with protoc 2.5.0
From source with checksum 736cdcefa911261ad56d2d120bf1fa
This command was run using /usr/local/hadoop/share/hadoop/common/hadoop-common-3.0.3.jar

Removing display of row names from data frame

My answer is intended for comment though but since i havent got enough reputation, i think it will still be relevant as an answer and help some one.

I find datatable in library DT robust to handle rownames, and columnames

Library DT
datatable(df, rownames = FALSE)  # no row names 

refer to https://rstudio.github.io/DT/ for usage scenarios

CSS to set A4 paper size

CSS

body {
  background: rgb(204,204,204); 
}
page[size="A4"] {
  background: white;
  width: 21cm;
  height: 29.7cm;
  display: block;
  margin: 0 auto;
  margin-bottom: 0.5cm;
  box-shadow: 0 0 0.5cm rgba(0,0,0,0.5);
}
@media print {
  body, page[size="A4"] {
    margin: 0;
    box-shadow: 0;
  }
}

HTML

<page size="A4"></page>
<page size="A4"></page>
<page size="A4"></page>

DEMO

How can I check if a URL exists via PHP?

$headers = @get_headers($this->_value);
if(strpos($headers[0],'200')===false)return false;

so anytime you contact a website and get something else than 200 ok it will work

convert month from name to number

With PHP 5.4, you can turn Matthew's answer into a one-liner:

$date = sprintf('%d-%d-01', $year, date_parse('may')['month']);

use of entityManager.createNativeQuery(query,foo.class)

Suppose your query is "select id,name from users where rollNo = 1001".

Here query will return a object with id and name column. Your Response class is like bellow:

public class UserObject{
        int id;
        String name;
        String rollNo;

        public UserObject(Object[] columns) {
            this.id = (columns[0] != null)?((BigDecimal)columns[0]).intValue():0;
            this.name = (String) columns[1];
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getRollNo() {
            return rollNo;
        }

        public void setRollNo(String rollNo) {
            this.rollNo = rollNo;
        }
    }

here UserObject constructor will get a Object Array and set data with object.

public UserObject(Object[] columns) {
            this.id = (columns[0] != null)?((BigDecimal)columns[0]).intValue():0;
            this.name = (String) columns[1];
        }

Your query executing function is like bellow :

public UserObject getUserByRoll(EntityManager entityManager,String rollNo) {

        String queryStr = "select id,name from users where rollNo = ?1";
        try {
            Query query = entityManager.createNativeQuery(queryStr);
            query.setParameter(1, rollNo);

            return new UserObject((Object[]) query.getSingleResult());
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

Here you have to import bellow packages:

import javax.persistence.Query;
import javax.persistence.EntityManager;

Now your main class, you have to call this function. First you have to get EntityManager and call this getUserByRoll(EntityManager entityManager,String rollNo) function. Calling procedure is given bellow:

@PersistenceContext
private EntityManager entityManager;

UserObject userObject = getUserByRoll(entityManager,"1001");

Now you have data in this userObject.

Here is Imports

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

Note:

query.getSingleResult() return a array. You have to maintain the column position and data type.

select id,name from users where rollNo = ?1 

query return a array and it's [0] --> id and [1] -> name.

For more info, visit this Answer

Thanks :)

FPDF utf-8 encoding (HOW-TO)

Don't use UTF-8 encoding. Standard FPDF fonts use ISO-8859-1 or Windows-1252. It is possible to perform a conversion to ISO-8859-1 with utf8_decode(): $str = utf8_decode($str); But some characters such as Euro won't be translated correctly. If the iconv extension is available, the right way to do it is the following: $str = iconv('UTF-8', 'windows-1252', $str);

"string could not resolved" error in Eclipse for C++ (Eclipse can't resolve standard library)

I had the same problem. Change the CurrentBuilder in Properties/C/C++ Build/ToolChainEditor to another value and apply it. Then again change it the original value. It works.

how to make log4j to write to the console as well

Your log4j File should look something like below read comments.

# Define the types of logger and level of logging    
log4j.rootLogger = DEBUG,console, FILE

# Define the File appender    
log4j.appender.FILE=org.apache.log4j.FileAppender    

# Define Console Appender    
log4j.appender.console=org.apache.log4j.ConsoleAppender    

# Define the layout for console appender. If you do not 
# define it, you will get an error    
log4j.appender.console.layout=org.apache.log4j.PatternLayout

# Set the name of the file    
log4j.appender.FILE.File=log.out

# Set the immediate flush to true (default)    
log4j.appender.FILE.ImmediateFlush=true

# Set the threshold to debug mode    
log4j.appender.FILE.Threshold=debug

# Set the append to false, overwrite    
log4j.appender.FILE.Append=false

# Define the layout for file appender    
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout    
log4j.appender.FILE.layout.conversionPattern=%m%n

Why is SQL Server 2008 Management Studio Intellisense not working?

Here is the official word on this from MS.

http://support.microsoft.com/kb/2531482

Their solution is the same as above, install the SQL Server 2008 R2 updates with the version 10.50.1777.0.

http://support.microsoft.com/kb/2507770

How to loop through a dataset in powershell?

The parser is having trouble concatenating your string. Try this:

write-host 'value is : '$i' '$($ds.Tables[1].Rows[$i][0])

Edit: Using double quotes might also be clearer since you can include the expressions within the quoted string:

write-host "value is : $i $($ds.Tables[1].Rows[$i][0])"

How to make clang compile to llvm IR

Did you read clang documentation ? You're probably looking for -emit-llvm.

execute shell command from android

Process p;
StringBuffer output = new StringBuffer();
try {
    p = Runtime.getRuntime().exec(params[0]);
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(p.getInputStream()));
    String line = "";
    while ((line = reader.readLine()) != null) {
        output.append(line + "\n");
        p.waitFor();
    }
} 
catch (IOException e) {
    e.printStackTrace();
} catch (InterruptedException e) {
    e.printStackTrace();
}
String response = output.toString();
return response;

hadoop No FileSystem for scheme: file

Assuming that you are using mvn and cloudera distribution of hadoop. I'm using cdh4.6 and adding these dependencies worked for me.I think you should check the versions of hadoop and mvn dependencies.

<dependency>
        <groupId>org.apache.hadoop</groupId>
        <artifactId>hadoop-core</artifactId>
        <version>2.0.0-mr1-cdh4.6.0</version>
    </dependency>

    <dependency>
        <groupId>org.apache.hadoop</groupId>
        <artifactId>hadoop-common</artifactId>
        <version>2.0.0-cdh4.6.0</version>
    </dependency>

    <dependency>
        <groupId>org.apache.hadoop</groupId>
        <artifactId>hadoop-client</artifactId>
        <version>2.0.0-cdh4.6.0</version>
    </dependency>

don't forget to add cloudera mvn repository.

<repository>
        <id>cloudera</id>
        <url>https://repository.cloudera.com/artifactory/cloudera-repos/</url>
</repository>

Text not wrapping in p tag

EASY

p{
    word-wrap: break-word;
}

How to implement WiX installer upgrade?

I used this site to help me understand the basics about WiX Upgrade:

http://wix.tramontana.co.hu/tutorial/upgrades-and-modularization

Afterwards I created a sample Installer, (installed a test file), then created the Upgrade installer (installed 2 sample test files). This will give you a basic understanding of how the mechanism works.

And as Mike said in the book from Apress, "The Definitive Guide to Windows Installer", it will help you out to understand, but it is not written using WiX.

Another site that was pretty helpful was this one:

http://www.wixwiki.com/index.php?title=Main_Page

How do I grant read access for a user to a database in SQL Server?

This is a two-step process:

  1. you need to create a login to SQL Server for that user, based on its Windows account

    CREATE LOGIN [<domainName>\<loginName>] FROM WINDOWS;
    
  2. you need to grant this login permission to access a database:

    USE (your database)
    CREATE USER (username) FOR LOGIN (your login name)
    

Once you have that user in your database, you can give it any rights you want, e.g. you could assign it the db_datareader database role to read all tables.

USE (your database)
EXEC sp_addrolemember 'db_datareader', '(your user name)'

Set background colour of cell to RGB value of data in cell

To color each cell based on its current integer value, the following should work, if you have a recent version of Excel. (Older versions don't handle rgb as well)

Sub Colourise()
'
' Colourise Macro
'
' Colours all selected cells, based on their current integer rgb value
' For e.g. (it's a bit backward from what you might expect)
' 255 = #ff0000 = red
' 256*255 = #00ff00 = green
' 256*256*255 #0000ff = blue
' 255 + 256*256*255 #ff00ff = magenta
' and so on...
'
' Keyboard Shortcut: Ctrl+Shift+C (or whatever you want to set it to)
'
  For Each cell In Selection
    If WorksheetFunction.IsNumber(cell) Then
      cell.Interior.Color = cell.Value
    End If
  Next cell
End Sub

If instead of a number you have a string then you can split the string into three numbers and combine them using rgb().

'IF' in 'SELECT' statement - choose output value based on column values

SELECT id, amount
FROM report
WHERE type='P'

UNION

SELECT id, (amount * -1) AS amount
FROM report
WHERE type = 'N'

ORDER BY id;

Highlighting Text Color using Html.fromHtml() in Android?

Using color value from xml resource:

int labelColor = getResources().getColor(R.color.label_color);
String ?olorString = String.format("%X", labelColor).substring(2); // !!strip alpha value!!

Html.fromHtml(String.format("<font color=\"#%s\">text</font>", ?olorString), TextView.BufferType.SPANNABLE); 

Does height and width not apply to span?

spans are by default displayed inline, which means they don't have a height and width.

Try adding a display: block to your span.

Serving favicon.ico in ASP.NET MVC

Use this instead of just the favicon.ico which tends to search in for the fav icon file

> <link rel="ICON" 
> href="@System.IO.Path.Combine(Request.PhysicalApplicationPath,
> "favicon.ico")" />

Use the requested path and combine with the fav icon file so that it gets the accurate address which its search for

Using this solved the Fav.icon error which is raised always on Application_Error

Can a foreign key be NULL and/or duplicate?

From the horse's mouth:

Foreign keys allow key values that are all NULL, even if there are no matching PRIMARY or UNIQUE keys

No Constraints on the Foreign Key

When no other constraints are defined on the foreign key, any number of rows in the child table can reference the same parent key value. This model allows nulls in the foreign key. ...

NOT NULL Constraint on the Foreign Key

When nulls are not allowed in a foreign key, each row in the child table must explicitly reference a value in the parent key because nulls are not allowed in the foreign key.

Any number of rows in the child table can reference the same parent key value, so this model establishes a one-to-many relationship between the parent and foreign keys. However, each row in the child table must have a reference to a parent key value; the absence of a value (a null) in the foreign key is not allowed. The same example in the previous section can be used to illustrate such a relationship. However, in this case, employees must have a reference to a specific department.

UNIQUE Constraint on the Foreign Key

When a UNIQUE constraint is defined on the foreign key, only one row in the child table can reference a given parent key value. This model allows nulls in the foreign key.

This model establishes a one-to-one relationship between the parent and foreign keys that allows undetermined values (nulls) in the foreign key. For example, assume that the employee table had a column named MEMBERNO, referring to an employee membership number in the company insurance plan. Also, a table named INSURANCE has a primary key named MEMBERNO, and other columns of the table keep respective information relating to an employee insurance policy. The MEMBERNO in the employee table must be both a foreign key and a unique key:

  • To enforce referential integrity rules between the EMP_TAB and INSURANCE tables (the FOREIGN KEY constraint)

  • To guarantee that each employee has a unique membership number (the UNIQUE key constraint)

UNIQUE and NOT NULL Constraints on the Foreign Key

When both UNIQUE and NOT NULL constraints are defined on the foreign key, only one row in the child table can reference a given parent key value, and because NULL values are not allowed in the foreign key, each row in the child table must explicitly reference a value in the parent key.

See this:

Oracle 11g link

Using Gradle to build a jar with dependencies

Based on the proposed solution by @blootsvoets, I edited my jar target this way :

jar {
    manifest {
        attributes('Main-Class': 'eu.tib.sre.Main')
    }
    // Include the classpath from the dependencies 
    from { configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) } }
    // This help solve the issue with jar lunch
    {
    exclude "META-INF/*.SF"
    exclude "META-INF/*.DSA"
    exclude "META-INF/*.RSA"
  }
}

How to output in CLI during execution of PHP Unit tests?

If you use Laravel, then you can use logging functions such as info() to log to the Laravel log file under storage/logs. So it won't appear in your terminal but in the log file.

Is there a Google Keep API?

I have been waiting to see if Google would open a Keep API. When I discovered Google Tasks, and saw that it had an Android app, web app, and API, I converted over to Tasks. This may not directly answer your question, but it is my solution to the Keep API problem.

Tasks doesn't have a reminder alarm exactly like Keep. I can live without that if I also connect with the Calendar API.

https://developers.google.com/google-apps/tasks/

Trim a string based on the string length

   import java.util.Scanner;
   public class Task1 {
         static Scanner input=new Scanner(System.in);
         static String sentence;
         static int length;
         public static void main(String[] args) {
    // TODO code application logic here
         System.out.println("Please Enter a sentence and the length you wish it to be ");
         sentence=input.nextLine();
         System.out.println("Please Enter the length you wish it to be ");
         length=input.nextInt();
    
    //invoking the method for truncating 
         truncate(length,sentence);
}

public static void truncate(int len, String sent){
    int count=0;//used to keep a record everytime the code encounters a whitespace
    String status="not";//changes when the the truncated sentence is printed

    //iterating through the sentence in accordance to its length
    for(int i=0;i<sent.length();i++){
      //checking for whitespaces to determine where each word ends
        if(sent.substring(i, i+1).equals(" ")){
           //count is incremented everytime a whitespace is encountered i.e a word
           count=count+1;
          //if count equals length needed i.e the number of words so far equals the length needed
           if(count==len){
              //the sentence is printed substring-wise 
               for(int j=0;j<i;j++){
                   System.out.print(sent.substring(j, j+1));
               }
               status="printed";
               break;   
           }              
        }
    }

    //prints the sentence the way it is in cases where the desired length exceeds the number of words in the sentece itself
    if(status.equals("not")){
        for(int j=0;j<sent.length();j++){
            System.out.print(sent.substring(j, j+1));
        }
    }
}

}

How to fix the "java.security.cert.CertificateException: No subject alternative names present" error?

I was going through 2 way SSL in springboot. I have made all correct configuration service tomcat server and service caller RestTemplate. but I was getting error as "java.security.cert.CertificateException: No subject alternative names present"

After going through solutions, I found, JVM needs this certificate otherwise it gives handshaking error.

Now, how to add this to JVM.

go to jre/lib/security/cacerts file. we need to add our server certificate file to this cacerts file of jvm.

Command to add server cert to cacerts file via command line in windows.

C:\Program Files\Java\jdk1.8.0_191\jre\lib\security>keytool -import -noprompt -trustcacerts -alias sslserver -file E:\spring_cloud_sachin\ssl_keys\sslserver.cer -keystore cacerts -storepass changeit

Check server cert is installed or not:

C:\Program Files\Java\jdk1.8.0_191\jre\lib\security>keytool -list -keystore cacerts

you can see list of certificates installed:

for more details: https://sachin4java.blogspot.com/2019/08/javasecuritycertcertificateexception-no.html

How do I install command line MySQL client on mac?

Installation command from brew:

$ brew cask install mysql-shell

Look at what you can do:

$ mysqlsh --help

Run query from mysqlsh client installed:

$ mysqlsh --host=192.x.x.x --port=3306 --user=user --password=xxxxx

MySQL Shell 8.0.18

Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its affiliates.
Other names may be trademarks of their respective owners.

Type '\help' or '\?' for help; '\quit' to exit.
WARNING: Using a password on the command line interface can be insecure.
Creating a session to '[email protected]:3306'
Fetching schema names for autocompletion... Press ^C to stop.
Your MySQL connection id is 16
Server version: 8.0.18 MySQL Community Server - GPL
No default schema selected; 
type \use <schema> to set one.

 MySQL  192.x.x.x:3306 ssl  JS >

 MySQL  192.x.x.x:3306 ssl  JS > `\use rafdb`

Default schema set to `rafdb`.

Video 100% width and height

_x000D_
_x000D_
<style>_x000D_
    .video{position:absolute;top:0;left:0;height:100%;width:100%;object-fit:cover}_x000D_
  }_x000D_
</style>_x000D_
<video class= "video""_x000D_
  disableremoteplayback=""_x000D_
  mqn-lazyimage-video-no-play=""_x000D_
  mqn-video-css-triggers="[{&quot;fire_once&quot;: true, &quot;classes&quot;: [&quot;.mqn2-ciu&quot;], &quot;from&quot;: 1, &quot;class&quot;: &quot;mqn2-grid-1--hero-intro-video-meta-visible&quot;}]"_x000D_
  mqn-video-inview-no-reset="" mqn-video-inview-play="" muted="" playsinline="" autoplay>_x000D_
_x000D_
<source src="https://github.com/Slender1808/Web-Adobe-XD/raw/master/Home/0013-0140.mp4" type="video/mp4">_x000D_
_x000D_
</video>
_x000D_
_x000D_
_x000D_

`export const` vs. `export default` in ES6

I had the problem that the browser doesn't use ES6.

I have fix it with:

 <script type="module" src="index.js"></script>

The type module tells the browser to use ES6.

export const bla = [1,2,3];

import {bla} from './example.js';

Then it should work.

What do curly braces mean in Verilog?

The curly braces mean concatenation, from most significant bit (MSB) on the left down to the least significant bit (LSB) on the right. You are creating a 32-bit bus (result) whose 16 most significant bits consist of 16 copies of bit 15 (the MSB) of the a bus, and whose 16 least significant bits consist of just the a bus (this particular construction is known as sign extension, which is needed e.g. to right-shift a negative number in two's complement form and keep it negative rather than introduce zeros into the MSBits).

There is a tutorial here*, but it doesn't explain too much more than the above paragraph.

For what it's worth, the nested curly braces around a[15:0] are superfluous.

*Beware: the example within the tutorial link contains a typo when demonstrating multiple concatenations - the (2{C}} should be a {2{2}}.

What does the C++ standard state the size of int, long type to be?

When it comes to built in types for different architectures and different compilers just run the following code on your architecture with your compiler to see what it outputs. Below shows my Ubuntu 13.04 (Raring Ringtail) 64 bit g++4.7.3 output. Also please note what was answered below which is why the output is ordered as such:

"There are five standard signed integer types: signed char, short int, int, long int, and long long int. In this list, each type provides at least as much storage as those preceding it in the list."

#include <iostream>

int main ( int argc, char * argv[] )
{
  std::cout<< "size of char: " << sizeof (char) << std::endl;
  std::cout<< "size of short: " << sizeof (short) << std::endl;
  std::cout<< "size of int: " << sizeof (int) << std::endl;
  std::cout<< "size of long: " << sizeof (long) << std::endl;
  std::cout<< "size of long long: " << sizeof (long long) << std::endl;

  std::cout<< "size of float: " << sizeof (float) << std::endl;
  std::cout<< "size of double: " << sizeof (double) << std::endl;

  std::cout<< "size of pointer: " << sizeof (int *) << std::endl;
}


size of char: 1
size of short: 2
size of int: 4
size of long: 8
size of long long: 8
size of float: 4
size of double: 8
size of pointer: 8

Regex matching beginning AND end strings

\bdbo\..*fn

I was looking through a ton of java code for a specific library: car.csclh.server.isr.businesslogic.TypePlatform (although I only knew car and Platform at the time). Unfortunately, none of the other suggestions here worked for me, so I figured I'd post this.

Here's the regex I used to find it:

\bcar\..*Platform

How to access a preexisting collection with Mongoose?

Go to MongoDB website, Login > Connect > Connect Application > Copy > Paste in 'database_url' > Collections > Copy/Paste in 'collection' .

var mongoose = require("mongoose");
mongoose.connect(' database_url ');
var conn = mongoose.connection;
conn.on('error', console.error.bind(console, 'connection error:'));
conn.once('open', function () {

conn.db.collection(" collection ", function(err, collection){

    collection.find({}).toArray(function(err, data){
        console.log(data); // data printed in console
    })
});

});

Happy to Help. by RTTSS.

SOAP request to WebService with java

A SOAP request is an XML file consisting of the parameters you are sending to the server.

The SOAP response is equally an XML file, but now with everything the service wants to give you.

Basically the WSDL is a XML file that explains the structure of those two XML.


To implement simple SOAP clients in Java, you can use the SAAJ framework (it is shipped with JSE 1.6 and above):

SOAP with Attachments API for Java (SAAJ) is mainly used for dealing directly with SOAP Request/Response messages which happens behind the scenes in any Web Service API. It allows the developers to directly send and receive soap messages instead of using JAX-WS.

See below a working example (run it!) of a SOAP web service call using SAAJ. It calls this web service.

import javax.xml.soap.*;

public class SOAPClientSAAJ {

    // SAAJ - SOAP Client Testing
    public static void main(String args[]) {
        /*
            The example below requests from the Web Service at:
             http://www.webservicex.net/uszip.asmx?op=GetInfoByCity


            To call other WS, change the parameters below, which are:
             - the SOAP Endpoint URL (that is, where the service is responding from)
             - the SOAP Action

            Also change the contents of the method createSoapEnvelope() in this class. It constructs
             the inner part of the SOAP envelope that is actually sent.
         */
        String soapEndpointUrl = "http://www.webservicex.net/uszip.asmx";
        String soapAction = "http://www.webserviceX.NET/GetInfoByCity";

        callSoapWebService(soapEndpointUrl, soapAction);
    }

    private static void createSoapEnvelope(SOAPMessage soapMessage) throws SOAPException {
        SOAPPart soapPart = soapMessage.getSOAPPart();

        String myNamespace = "myNamespace";
        String myNamespaceURI = "http://www.webserviceX.NET";

        // SOAP Envelope
        SOAPEnvelope envelope = soapPart.getEnvelope();
        envelope.addNamespaceDeclaration(myNamespace, myNamespaceURI);

            /*
            Constructed SOAP Request Message:
            <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:myNamespace="http://www.webserviceX.NET">
                <SOAP-ENV:Header/>
                <SOAP-ENV:Body>
                    <myNamespace:GetInfoByCity>
                        <myNamespace:USCity>New York</myNamespace:USCity>
                    </myNamespace:GetInfoByCity>
                </SOAP-ENV:Body>
            </SOAP-ENV:Envelope>
            */

        // SOAP Body
        SOAPBody soapBody = envelope.getBody();
        SOAPElement soapBodyElem = soapBody.addChildElement("GetInfoByCity", myNamespace);
        SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("USCity", myNamespace);
        soapBodyElem1.addTextNode("New York");
    }

    private static void callSoapWebService(String soapEndpointUrl, String soapAction) {
        try {
            // Create SOAP Connection
            SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
            SOAPConnection soapConnection = soapConnectionFactory.createConnection();

            // Send SOAP Message to SOAP Server
            SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(soapAction), soapEndpointUrl);

            // Print the SOAP Response
            System.out.println("Response SOAP Message:");
            soapResponse.writeTo(System.out);
            System.out.println();

            soapConnection.close();
        } catch (Exception e) {
            System.err.println("\nError occurred while sending SOAP Request to Server!\nMake sure you have the correct endpoint URL and SOAPAction!\n");
            e.printStackTrace();
        }
    }

    private static SOAPMessage createSOAPRequest(String soapAction) throws Exception {
        MessageFactory messageFactory = MessageFactory.newInstance();
        SOAPMessage soapMessage = messageFactory.createMessage();

        createSoapEnvelope(soapMessage);

        MimeHeaders headers = soapMessage.getMimeHeaders();
        headers.addHeader("SOAPAction", soapAction);

        soapMessage.saveChanges();

        /* Print the request message, just for debugging purposes */
        System.out.println("Request SOAP Message:");
        soapMessage.writeTo(System.out);
        System.out.println("\n");

        return soapMessage;
    }

}

How to check null objects in jQuery

What about using "undefined"?

if (value != undefined){ // do stuff } 

How do I use Linq to obtain a unique list of properties from a list of objects?

Using straight Linq, with the Distinct() extension:

var idList = (from x in yourList select x.ID).Distinct();

How do I change the data type for a column in MySQL?

If you want to alter the column details add a comment, use this

ALTER TABLE [table_name] MODIFY [column_name] [new data type] DEFAULT [VALUE] COMMENT '[column comment]' 

How do I get the HTML code of a web page in PHP?

I tried this code and it's working for me .

$html = file_get_contents('www.google.com');
$myVar = htmlspecialchars($html, ENT_QUOTES);
echo($myVar);

Find CRLF in Notepad++

In 2013, v6.13 or later, use:

Menu Edit ? EOL Conversion ? Windows Format.

How do I print uint32_t and uint16_t variables value?

The macros defined in <inttypes.h> are the most correct way to print values of types uint32_t, uint16_t, and so forth -- but they're not the only way.

Personally, I find those macros difficult to remember and awkward to use. (Given the syntax of a printf format string, that's probably unavoidable; I'm not claiming I could have come up with a better system.)

An alternative is to cast the values to a predefined type and use the format for that type.

Types int and unsigned int are guaranteed by the language to be at least 16 bits wide, and therefore to be able to hold any converted value of type int16_t or uint16_t, respectively. Similarly, long and unsigned long are at least 32 bits wide, and long long and unsigned long long are at least 64 bits wide.

For example, I might write your program like this (with a few additional tweaks):

#include <stdio.h>
#include <stdint.h>
#include <netinet/in.h>  

int main(void)
{
    uint32_t a=12, a1;
    uint16_t b=1, b1;
    a1 = htonl(a);
    printf("%lu---------%lu\n", (unsigned long)a, (unsigned long)a1);
    b1 = htons(b);
    printf("%u-----%u\n", (unsigned)b, (unsigned)b1);
    return 0;
}

One advantage of this approach is that it can work even with pre-C99 implementations that don't support <inttypes.h>. Such an implementation most likely wouldn't have <stdint.h> either, but the technique is useful for other integer types.

Load image from url

loadImage("http://relinjose.com/directory/filename.png");

Here you go

void loadImage(String image_location) {
    URL imageURL = null;
    if (image_location != null) {
        try {
            imageURL = new URL(image_location);         
            HttpURLConnection connection = (HttpURLConnection) imageURL
                    .openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream inputStream = connection.getInputStream();
            bitmap = BitmapFactory.decodeStream(inputStream);// Convert to bitmap
            ivdpfirst.setImageBitmap(bitmap);
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {
        //set any default
    }
}

Python list sort in descending order

In one line, using a lambda:

timestamps.sort(key=lambda x: time.strptime(x, '%Y-%m-%d %H:%M:%S')[0:6], reverse=True)

Passing a function to list.sort:

def foo(x):
    return time.strptime(x, '%Y-%m-%d %H:%M:%S')[0:6]

timestamps.sort(key=foo, reverse=True)

Maven won't run my Project : Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2.1:exec

I faced the same issue. When I tried to run the project from IDE, it was giving me same error. But when I tried running from the command prompt, the project was running fine. So it came to me that there should be some issue with the settings that makes the program to Run from IDE.

I solved the problem by changing some Project settings. I traced the error and came to the following part in my pom.xml file.

            <execution>
                <id>default-cli</id>
                <goals>
                    <goal>exec</goal>                            
                </goals>
                <configuration>
                    <executable>${java.home}/bin/java</executable>
                    <commandlineArgs>${runfx.args}</commandlineArgs>
                </configuration>
            </execution>

I went to my Project Properties > Actions Categories > Action: Run Project: then I Set Properties for Run Project Action as follows:

runfx.args=-jar "${project.build.directory}/${project.build.finalName}.jar"

Then, I rebuild the project and I was able to Run the Project. As you can see, the IDE(Netbeans in my case), was not able to find 'runfx.args' which is set in Project Properties.

Determine if an element has a CSS class with jQuery

from the FAQ

elem = $("#elemid");
if (elem.is (".class")) {
   // whatever
}

or:

elem = $("#elemid");
if (elem.hasClass ("class")) {
   // whatever
}

How to execute a bash command stored as a string with quotes and asterisk

try this

$ cmd='mysql AMORE -u root --password="password" -h localhost -e "select host from amoreconfig"'
$ eval $cmd

Convert DataTable to List<T>

please try this code:

public List<T> ConvertToList<T>(DataTable dt)
{
    var columnNames = dt.Columns.Cast<DataColumn>()
        .Select(c => c.ColumnName)
        .ToList();
    var properties = typeof(T).GetProperties();
    return dt.AsEnumerable().Select(row =>
    {
        var objT = Activator.CreateInstance<T>();
        foreach (var pro in properties)
        {
            if (columnNames.Contains(pro.Name))
                pro.SetValue(objT, row[pro.Name]);
        }
        return objT;
    }).ToList();
}

Get the current file name in gulp.src()

I found this plugin to be doing what I was expecting: gulp-using

Simple usage example: Search all files in project with .jsx extension

gulp.task('reactify', function(){
        gulp.src(['../**/*.jsx']) 
            .pipe(using({}));
        ....
    });

Output:

[gulp] Using gulpfile /app/build/gulpfile.js
[gulp] Starting 'reactify'...
[gulp] Finished 'reactify' after 2.92 ms
[gulp] Using file /app/staging/web/content/view/logon.jsx
[gulp] Using file /app/staging/web/content/view/components/rauth.jsx

How to search for an element in a golang slice

There is no library function for that. You have to code by your own.

for _, value := range myconfig {
    if value.Key == "key1" {
        // logic
    }
}

Working code: https://play.golang.org/p/IJIhYWROP_

package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    type Config struct {
        Key   string
        Value string
    }

    var respbody = []byte(`[
        {"Key":"Key1", "Value":"Value1"},
        {"Key":"Key2", "Value":"Value2"}
    ]`)

    var myconfig []Config

    err := json.Unmarshal(respbody, &myconfig)
    if err != nil {
        fmt.Println("error:", err)
    }

    fmt.Printf("%+v\n", myconfig)

    for _, v := range myconfig {
        if v.Key == "Key1" {
            fmt.Println("Value: ", v.Value)
        }
    }

}

gcc-arm-linux-gnueabi command not found

You have installed a toolchain which was compiled for i686 on a box which is running an x86_64 userland.

Use an i686 VM.

Passing a local variable from one function to another

First way is

function function1()
{
  var variable1=12;
  function2(variable1);
}

function function2(val)
{
  var variableOfFunction1 = val;

// Then you will have to use this function for the variable1 so it doesn't really help much unless that's what you want to do. }

Second way is

var globalVariable;
function function1()
{
  globalVariable=12;
  function2();
}

function function2()
{
  var local = globalVariable;
}

Reading value from console, interactively

Here's a example:

const stdin = process.openStdin()

process.stdout.write('Enter name: ')

stdin.addListener('data', text => {
  const name = text.toString().trim()
  console.log('Your name is: ' + name)

  stdin.pause() // stop reading
})

Output:

Enter name: bob
Your name is: bob

How to build and fill pandas dataframe from for loop?

Make a list of tuples with your data and then create a DataFrame with it:

d = []
for p in game.players.passing():
    d.append((p, p.team, p.passer_rating()))

pd.DataFrame(d, columns=('Player', 'Team', 'Passer Rating'))

A list of tuples should have less overhead than a list dictionaries. I tested this below, but please remember to prioritize ease of code understanding over performance in most cases.

Testing functions:

def with_tuples(loop_size=1e5):
    res = []

    for x in range(int(loop_size)):
        res.append((x-1, x, x+1))

    return pd.DataFrame(res, columns=("a", "b", "c"))

def with_dict(loop_size=1e5):
    res = []

    for x in range(int(loop_size)):
        res.append({"a":x-1, "b":x, "c":x+1})

    return pd.DataFrame(res)

Results:

%timeit -n 10 with_tuples()
# 10 loops, best of 3: 55.2 ms per loop

%timeit -n 10 with_dict()
# 10 loops, best of 3: 130 ms per loop

"Continue" (to next iteration) on VBScript

Implement the iteration as a recursive function.

Function Iterate( i , N )
  If i == N Then
      Exit Function
  End If
  [Code]
  If Condition1 Then
     Call Iterate( i+1, N );
     Exit Function
  End If

  [Code]
  If Condition2 Then
     Call Iterate( i+1, N );
     Exit Function
  End If
  Call Iterate( i+1, N );
End Function

Start with a call to Iterate( 1, N )

How to set the id attribute of a HTML element dynamically with angularjs (1.x)?

In case you came to this question but related to newer Angular version >= 2.0.

<div [id]="element.id"></div>

Difference between Subquery and Correlated Subquery

Above example is not Co-related Sub-Query. It is Derived Table / Inline-View since i.e, a Sub-query within FROM Clause.

A Corelated Sub-query should refer its parent(main Query) Table in it. For example See find the Nth max salary by Co-related Sub-query:

SELECT Salary 
FROM Employee E1
WHERE N-1 = (SELECT COUNT(*)
             FROM Employee E2
             WHERE E1.salary <E2.Salary) 

Co-Related Vs Nested-SubQueries.

Technical difference between Normal Sub-query and Co-related sub-query are:

1. Looping: Co-related sub-query loop under main-query; whereas nested not; therefore co-related sub-query executes on each iteration of main query. Whereas in case of Nested-query; subquery executes first then outer query executes next. Hence, the maximum no. of executes are NXM for correlated subquery and N+M for subquery.

2. Dependency(Inner to Outer vs Outer to Inner): In the case of co-related subquery, inner query depends on outer query for processing whereas in normal sub-query, Outer query depends on inner query.

3.Performance: Using Co-related sub-query performance decreases, since, it performs NXM iterations instead of N+M iterations. ¨ Co-related Sub-query Execution.

For more information with examples :

http://dotnetauthorities.blogspot.in/2013/12/Microsoft-SQL-Server-Training-Online-Learning-Classes-Sql-Sub-Queries-Nested-Co-related.html

How to override trait function and call it from the overridden function?

Another variation: Define two functions in the trait, a protected one that performs the actual task, and a public one which in turn calls the protected one.

This just saves classes from having to mess with the 'use' statement if they want to override the function, since they can still call the protected function internally.

trait A {
    protected function traitcalc($v) {
        return $v+1;
    }

    function calc($v) {
        return $this->traitcalc($v);
    }
}

class MyClass {
    use A;

    function calc($v) {
        $v++;
        return $this->traitcalc($v);
    }
}

class MyOtherClass {
    use A;
}


print (new MyClass())->calc(2); // will print 4

print (new MyOtherClass())->calc(2); // will print 3

Can we create an instance of an interface in Java?

Short answer...yes. You can use an anonymous class when you initialize a variable. Take a look at this question: Anonymous vs named inner classes? - best practices?

CSS how to make an element fade in and then fade out?

Try this:

@keyframes animationName {
  0%   { opacity:0; }
  50%  { opacity:1; }
  100% { opacity:0; }
}
@-o-keyframes animationName{
  0%   { opacity:0; }
  50%  { opacity:1; }
  100% { opacity:0; }
}
@-moz-keyframes animationName{
  0%   { opacity:0; }
  50%  { opacity:1; }
  100% { opacity:0; }
}
@-webkit-keyframes animationName{
  0%   { opacity:0; }
  50%  { opacity:1; }
  100% { opacity:0; }
}   
.elementToFadeInAndOut {
   -webkit-animation: animationName 5s infinite;
   -moz-animation: animationName 5s infinite;
   -o-animation: animationName 5s infinite;
    animation: animationName 5s infinite;
}

Expanding tuples into arguments

This is the functional programming method. It lifts the tuple expansion feature out of syntax sugar:

apply_tuple = lambda f, t: f(*t)

Redefine apply_tuple via curry to save a lot of partial calls in the long run:

from toolz import curry
apply_tuple = curry(apply_tuple)

Example usage:

from operator import add, eq
from toolz import thread_last

thread_last(
    [(1,2), (3,4)],
    (map, apply_tuple(add)),
    list,
    (eq, [3, 7])
)
# Prints 'True'

How can I pretty-print JSON in a shell script?

If you have Node.js installed you can create one on your own with one line of code. Create a file pretty:

> vim pretty

#!/usr/bin/env node

console.log(JSON.stringify(JSON.parse(process.argv[2]), null, 2));

Add execute permission:

> chmod +x pretty

> ./pretty '{"foo": "lorem", "bar": "ipsum"}'

Or if your JSON is in a file:

#!/usr/bin/env node

console.log(JSON.stringify(require("./" + process.argv[2]), null, 2));

> ./pretty file.json

ASP MVC href to a controller/view

how about

<li>
<a href="@Url.Action("Index", "Users")" class="elements"><span>Clients</span></a>
</li>

SSH to Vagrant box in Windows?

You must patch some Vagrant code by modifying only one file, ssh.rb.

All the info is here: https://gist.github.com/2843680

vagrant ssh will now work also in Windows, just like in Linux.


EDIT: In newer Versions this became unnecessary. You still have to add the path to your ssh.exe to your PATH Variable:

Search for ssh.exe on your computer, copy the Path (i.e. C:\Program Files (x86)\Git\bin), open System Preferences, find the Environment variable Settings, click on the Path Variable, add the path, separating the existing paths using ;.

log4j: Log output of a specific class to a specific appender

Here's an answer regarding the XML configuration, note that if you don't give the file appender a ConversionPattern it will create 0 byte file and not write anything:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
    <appender name="console" class="org.apache.log4j.ConsoleAppender">
        <param name="Target" value="System.out"/>
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%-5p %c{1} - %m%n"/>
        </layout>
    </appender>

    <appender name="bdfile" class="org.apache.log4j.RollingFileAppender">
        <param name="append" value="false"/>
        <param name="maxFileSize" value="1GB"/>
        <param name="maxBackupIndex" value="2"/>
        <param name="file" value="/tmp/bd.log"/>
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%-5p %c{1} - %m%n"/>
        </layout>
    </appender>

    <logger name="com.example.mypackage" additivity="false">
        <level value="debug"/>
        <appender-ref ref="bdfile"/>
    </logger>

    <root>
        <priority value="info"/>
        <appender-ref ref="bdfile"/>
        <appender-ref ref="console"/>
    </root>

</log4j:configuration>

What is <=> (the 'Spaceship' Operator) in PHP 7?

According to the RFC that introduced the operator, $a <=> $b evaluates to:

  • 0 if $a == $b
  • -1 if $a < $b
  • 1 if $a > $b

which seems to be the case in practice in every scenario I've tried, although strictly the official docs only offer the slightly weaker guarantee that $a <=> $b will return

an integer less than, equal to, or greater than zero when $a is respectively less than, equal to, or greater than $b

Regardless, why would you want such an operator? Again, the RFC addresses this - it's pretty much entirely to make it more convenient to write comparison functions for usort (and the similar uasort and uksort).

usort takes an array to sort as its first argument, and a user-defined comparison function as its second argument. It uses that comparison function to determine which of a pair of elements from the array is greater. The comparison function needs to return:

an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

The spaceship operator makes this succinct and convenient:

$things = [
    [
        'foo' => 5.5,
        'bar' => 'abc'
    ],
    [
        'foo' => 7.7,
        'bar' => 'xyz'
    ],
    [
        'foo' => 2.2,
        'bar' => 'efg'
    ]
];

// Sort $things by 'foo' property, ascending
usort($things, function ($a, $b) {
    return $a['foo'] <=> $b['foo'];
});

// Sort $things by 'bar' property, descending
usort($things, function ($a, $b) {
    return $b['bar'] <=> $a['bar'];
});

More examples of comparison functions written using the spaceship operator can be found in the Usefulness section of the RFC.

Selenium Webdriver move mouse to Point

the solution is implementing anonymous class in this manner:

        import org.openqa.selenium.Point;
        import org.openqa.selenium.interactions.HasInputDevices;
        import org.openqa.selenium.interactions.Mouse;
        import org.openqa.selenium.interactions.internal.Coordinates;

        .....

        final Point image = page.findImage("C:\\Pictures\\marker.png") ;

        Mouse mouse = ((HasInputDevices) driver).getMouse();

        Coordinates imageCoordinates =  new Coordinates() {

              public Point onScreen() {
                throw new UnsupportedOperationException("Not supported yet.");
              }

              public Point inViewPort() {
                Response response = execute(DriverCommand.GET_ELEMENT_LOCATION_ONCE_SCROLLED_INTO_VIEW,
        ImmutableMap.of("id", getId()));

    @SuppressWarnings("unchecked")
    Map<String, Number> mapped = (Map<String, Number>) response.getValue();

    return new Point(mapped.get("x").intValue(), mapped.get("y").intValue());
              }

              public Point onPage() {
                return image;
              }

              public Object getAuxiliary() {
                // extract the selenium imageElement id (imageElement.toString() and parse out the "{sdafbsdkjfh}" format id) and return it
              }
            };

        mouse.mouseMove(imageCoordinates);

Why Doesn't C# Allow Static Methods to Implement an Interface?

Because interfaces are in inheritance structure, and static methods don't inherit well.

android studio 0.4.2: Gradle project sync failed error

  1. Open File-> Settings
  2. Choose Gradle
  3. Mark "Use local grandle distribution" and select the path of grandle home for ex: C:/Users/high_hopes/.gradle/wrapper/dists/gradle-2.1-all/27drb4udbjf4k88eh2ffdc0n55/gradle-2.1.1 then choose service directory path C:/Users/high_hopes/.gradle
  4. Apply all changes
  5. Open File-> invalidate caches/ restart ...
  6. Select Just Restart

How to fix "could not find a base address that matches schema http"... in WCF

There should be a way to solve this pretty easily with external config sections and an extra deployment step that drops a deployment specific external .config file into a known location. We typically use this solution to handle the different server configurations for our different deployment environments (Staging, QA, production, etc) with our "dev box" being the default if no special copy occurs.

Is it possible to have placeholders in strings.xml for runtime values?

A Direct Kotlin Solution to the problem:

strings.xml

<string name="customer_message">Hello, %1$s!\nYou have %2$d Products in your cart.</string>

kotlinActivityORFragmentFile.kt:

val username = "Andrew"
val products = 1000
val text: String = String.format(
      resources.getString(R.string.customer_message), username, products )

SQL time difference between two dates result in hh:mm:ss

It's A Script Write Copy then write in your script file and change your requered field and get out put

DECLARE @Sdate DATETIME, @Edate DATETIME, @Timediff VARCHAR(100)
SELECT @Sdate = '02/12/2014 08:40:18.000',@Edate='02/13/2014 09:52:48.000'
SET @Timediff=DATEDIFF(s, @Sdate, @Edate)
SELECT CONVERT(VARCHAR(5),@Timediff/3600)+':'+convert(varchar(5),@Timediff%3600/60)+':'+convert(varchar(5),@Timediff%60) AS TimeDiff

std::vector versus std::array in C++

Using the std::vector<T> class:

  • ...is just as fast as using built-in arrays, assuming you are doing only the things built-in arrays allow you to do (read and write to existing elements).

  • ...automatically resizes when new elements are inserted.

  • ...allows you to insert new elements at the beginning or in the middle of the vector, automatically "shifting" the rest of the elements "up"( does that make sense?). It allows you to remove elements anywhere in the std::vector, too, automatically shifting the rest of the elements down.

  • ...allows you to perform a range-checked read with the at() method (you can always use the indexers [] if you don't want this check to be performed).

There are two three main caveats to using std::vector<T>:

  1. You don't have reliable access to the underlying pointer, which may be an issue if you are dealing with third-party functions that demand the address of an array.

  2. The std::vector<bool> class is silly. It's implemented as a condensed bitfield, not as an array. Avoid it if you want an array of bools!

  3. During usage, std::vector<T>s are going to be a bit larger than a C++ array with the same number of elements. This is because they need to keep track of a small amount of other information, such as their current size, and because whenever std::vector<T>s resize, they reserve more space then they need. This is to prevent them from having to resize every time a new element is inserted. This behavior can be changed by providing a custom allocator, but I never felt the need to do that!


Edit: After reading Zud's reply to the question, I felt I should add this:

The std::array<T> class is not the same as a C++ array. std::array<T> is a very thin wrapper around C++ arrays, with the primary purpose of hiding the pointer from the user of the class (in C++, arrays are implicitly cast as pointers, often to dismaying effect). The std::array<T> class also stores its size (length), which can be very useful.

Hook up Raspberry Pi via Ethernet to laptop without router?

Here are the instructions for Windows users on connecting to a RPi by using just an Ethernet cable and a DHCP server. There is no need for a cross over cable, as the RPi can handle it. I have a blog post that documents this with pictures here which may be easier to follow.

Downloads

Download the DHCP Server for Windows (download link is here). Unzip the zip file and open the dhcpwiz application, which will configure the DHCP server.

DHCP Server Configuration

Hit next on the first screen.

On the second screen, look for a "Local Area Connection" row and verify its IP address is 0.0.0.0 and its status is enabled. Connect the Ethernet cable from the RPi to your laptop, and turn on the Pi. Hit refresh on this screen until the IP address changes to 169.254.*.*. If it is anything else then you should alter your network settings for the Local Area Connection (make sure it is not a static IP/DNS). Click on this Local Area Connection row and hit next.

Check HTTP (Web Server). This makes it much more easy to locate the RPi's IP address. Hit Next.

Take the defaults and hit Next until you get to the Writing the INI file screen. Check Overwrite existing file and hit the Write INI file button. Then hit Next.

On the final screen, check Run DHCP server immediately and hit `Finish.

DHCP Server and Obtaining the IP Address of your Raspberry PI

This launches the actual DHCP server, using the configuration you just created in the previous wizard. Click the Continue as tray app button, and the DHCP server will be minimized to your system tray.

Anywhere from 1 second to 5 minutes from now you will see an alert on the system tray with your laptop and your RPi's new IP address. This alert is really quick and you will probably miss it. Normally your RPi's IP is 169.254.0.2, but it could be *.01 or even something else. It is easier to access the DHCP server's web UI at http://localhost/dhcpstatus.xml. This will list the hostname as "raspberrypi" with its IP address.

Now you can putty or remote desktop into your RPi, and configure its wireless settings or whatever you want to do.

Trouble shooting

This can be somewhat finicky. I've had my connection appear to drop and have been unable to SSH back in using the IP address. Normally, I can restart the Pi and get the IP address again. Sometimes I have to restart both the RPi and the DHCP server. Sometimes I have to do this multiple times. At one point when I wasn't getting a connection for 15 minutes, I copied all of the files in the dhcpsrv2.5.1 folder to a new folder and tried again; it immediately worked.

Get Today's date in Java at midnight time

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");    
Date date = new Date(); System.out.println(dateFormat.format(date));    //2014/08/06 15:59:4

Use a list of values to select rows from a pandas dataframe

You can use isin method:

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

In [2]: df
Out[2]:
   A  B
0  5  1
1  6  2
2  3  3
3  4  5

In [3]: df[df['A'].isin([3, 6])]
Out[3]:
   A  B
1  6  2
2  3  3

And to get the opposite use ~:

In [4]: df[~df['A'].isin([3, 6])]
Out[4]:
   A  B
0  5  1
3  4  5

dbms_lob.getlength() vs. length() to find blob size in oracle

length and dbms_lob.getlength return the number of characters when applied to a CLOB (Character LOB). When applied to a BLOB (Binary LOB), dbms_lob.getlength will return the number of bytes, which may differ from the number of characters in a multi-byte character set.

As the documentation doesn't specify what happens when you apply length on a BLOB, I would advise against using it in that case. If you want the number of bytes in a BLOB, use dbms_lob.getlength.

Switch to another Git tag

Clone the repository as normal:

git clone git://github.com/rspec/rspec-tmbundle.git RSpec.tmbundle

Then checkout the tag you want like so:

git checkout tags/1.1.4

This will checkout out the tag in a 'detached HEAD' state. In this state, "you can look around, make experimental changes and commit them, and [discard those commits] without impacting any branches by performing another checkout".

To retain any changes made, move them to a new branch:

git checkout -b 1.1.4-jspooner

You can get back to the master branch by using:

git checkout master

Note, as was mentioned in the first revision of this answer, there is another way to checkout a tag:

git checkout 1.1.4

But as was mentioned in a comment, if you have a branch by that same name, this will result in git warning you that the refname is ambiguous and checking out the branch by default:

warning: refname 'test' is ambiguous.
Switched to branch '1.1.4'

The shorthand can be safely used if the repository does not share names between branches and tags.

Tomcat view catalina.out log file

locate catalina.out and find out where is your catalina out. Because it depends.

If there is several, look at their sizes: that with size 0 are not what you want.

java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver

Have you copied classes12.jar in lib folder of your web application and set the classpath in eclipse.

Right-click project in Package explorer Build path -> Add external archives...

Select your ojdbc6.jar archive

Press OK

Or

Go through this link and read and do carefully.

The library should be now referenced in the "Referenced Librairies" under the Package explorer. Now try to run your program again.

How to write to a file in Scala?

Here is a concise one-liner using the Scala compiler library:

scala.tools.nsc.io.File("filename").writeAll("hello world")

Alternatively, if you want to use the Java libraries you can do this hack:

Some(new PrintWriter("filename")).foreach{p => p.write("hello world"); p.close}

How to get user agent in PHP

You can use the jQuery ajax method link if you want to pass data from client to server. In this case you can use $_SERVER['HTTP_USER_AGENT'] variable to found browser user agent.

how to print float value upto 2 decimal place without rounding off

i'd suggest shorter and faster approach:

printf("%.2f", ((signed long)(fVal * 100) * 0.01f));

this way you won't overflow int, plus multiplication by 100 shouldn't influence the significand/mantissa itself, because the only thing that really is changing is exponent.

Activate a virtualenv with a Python script

For python2/3, Using below code snippet we can activate virtual env.

activate_this = "/home/<--path-->/<--virtual env name -->/bin/activate_this.py" #for ubuntu
activate_this = "D:\<-- path -->\<--virtual env name -->\Scripts\\activate_this.py" #for windows
with open(activate_this) as f:
    code = compile(f.read(), activate_this, 'exec')
    exec(code, dict(__file__=activate_this))

how do I get eclipse to use a different compiler version for Java?

Eclipse uses it's own internal compiler that can compile to several Java versions.

From Eclipse Help > Java development user guide > Concepts > Java Builder

The Java builder builds Java programs using its own compiler (the Eclipse Compiler for Java) that implements the Java Language Specification.

For Eclipse Mars.1 Release (4.5.1), this can target 1.3 to 1.8 inclusive.

When you configure a project:

[project-name] > Properties > Java Compiler > Compiler compliance level

This configures the Eclipse Java compiler to compile code to the specified Java version, typically 1.8 today.

Host environment variables, eg JAVA_HOME etc, are not used.

The Oracle/Sun JDK compiler is not used.

Convert Pandas column containing NaNs to dtype `int`

Assuming your DateColumn formatted 3312018.0 should be converted to 03/31/2018 as a string. And, some records are missing or 0.

df['DateColumn'] = df['DateColumn'].astype(int)
df['DateColumn'] = df['DateColumn'].astype(str)
df['DateColumn'] = df['DateColumn'].apply(lambda x: x.zfill(8))
df.loc[df['DateColumn'] == '00000000','DateColumn'] = '01011980'
df['DateColumn'] = pd.to_datetime(df['DateColumn'], format="%m%d%Y")
df['DateColumn'] = df['DateColumn'].apply(lambda x: x.strftime('%m/%d/%Y'))

form_for but to post to a different action

If you want to pass custom Controller to a form_for while rendering a partial form you can use this:

<%= render 'form', :locals => {:controller => 'my_controller', :action => 'my_action'}%>

and then in the form partial use this local variable like this:

<%= form_for(:post, :url => url_for(:controller => locals[:controller], :action => locals[:action]), html: {class: ""} ) do |f| -%>

mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in

That query is failing and returning false.

Put this after mysqli_query() to see what's going on.

if (!$check1_res) {
    printf("Error: %s\n", mysqli_error($con));
    exit();
}

For more information:

http://www.php.net/manual/en/mysqli.error.php

The SELECT permission was denied on the object 'sysobjects', database 'mssqlsystemresource', schema 'sys'

I had the same error and SOLVED by removing the DB roles db_denydatawriter and db_denydatreader of the DB user. For that, select the appropriate DB user on logins >> properties >> user mappings >> find out DB and select it >> uncheck the mentioned Db user roles. Thats it !!

Find the maximum value in a list of tuples in Python

In addition to max, you can also sort:

>>> lis
[(101, 153), (255, 827), (361, 961)]
>>> sorted(lis,key=lambda x: x[1], reverse=True)[0]
(361, 961)

CodeIgniter: Create new helper?

To create a new helper you can follow the instructions from The Pixel Developer, but my advice is not to create a helper just for the logic required by a particular part of a particular application. Instead, use that logic in the controller to set the arrays to their final intended values. Once you got that, you pass them to the view using the Template Parser Class and (hopefully) you can keep the view clean from anything that looks like PHP using simple variables or variable tag pairs instead of echos and foreachs. i.e:

{blog_entries}
<h5>{title}</h5>
<p>{body}</p>
{/blog_entries}

instead of

<?php foreach ($blog_entries as $blog_entry): ?>
<h5><?php echo $blog_entry['title']; ?></h5>
<p><?php echo $blog_entry['body']; ?></p>
<?php endforeach; ?>

Another benefit from this approach is that you don't have to worry about adding the CI instance as you would if you use custom helpers to do all the work.

How to force a html5 form validation without submitting it via jQuery

May be late to the party but yet somehow I found this question while trying to solve similar problem. As no code from this page worked for me, meanwhile I came up with solution that works as specified.

Problem is when your <form> DOM contain single <button> element, once fired, that <button> will automatically sumbit form. If you play with AJAX, You probably need to prevent default action. But there is a catch: If you just do so, You will also prevent basic HTML5 validation. Therefore, it is good call to prevent defaults on that button only if the form is valid. Otherwise, HTML5 validation will protect You from submitting. jQuery checkValidity() will help with this:

jQuery:

$(document).ready(function() {
  $('#buttonID').on('click', function(event) {
    var isvalidate = $("#formID")[0].checkValidity();
    if (isvalidate) {
      event.preventDefault();
      // HERE YOU CAN PUT YOUR AJAX CALL
    }
  });
});

Code described above will allow You to use basic HTML5 validation (with type and pattern matching) WITHOUT submitting form.

C#: HttpClient with POST parameters

A cleaner alternative would be to use a Dictionary to handle parameters. They are key-value pairs after all.

private static readonly HttpClient httpclient;

static MyClassName()
{
    // HttpClient is intended to be instantiated once and re-used throughout the life of an application. 
    // Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads. 
    // This will result in SocketException errors.
    // https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=netframework-4.7.1
    httpclient = new HttpClient();    
} 

var url = "http://myserver/method";
var parameters = new Dictionary<string, string> { { "param1", "1" }, { "param2", "2" } };
var encodedContent = new FormUrlEncodedContent (parameters);

var response = await httpclient.PostAsync (url, encodedContent).ConfigureAwait (false);
if (response.StatusCode == HttpStatusCode.OK) {
    // Do something with response. Example get content:
    // var responseContent = await response.Content.ReadAsStringAsync ().ConfigureAwait (false);
}

Also dont forget to Dispose() httpclient, if you dont use the keyword using

As stated in the Remarks section of the HttpClient class in the Microsoft docs, HttpClient should be instantiated once and re-used.

Edit:

You may want to look into response.EnsureSuccessStatusCode(); instead of if (response.StatusCode == HttpStatusCode.OK).

You may want to keep your httpclient and dont Dispose() it. See: Do HttpClient and HttpClientHandler have to be disposed?

Edit:

Do not worry about using .ConfigureAwait(false) in .NET Core. For more details look at https://blog.stephencleary.com/2017/03/aspnetcore-synchronization-context.html

How to list only top level directories in Python?

being a newbie here i can't yet directly comment but here is a small correction i'd like to add to the following part of ??O?????'s answer :

If you prefer full pathnames, then use this function:

def listdirs(folder):  
  return [
    d for d in (os.path.join(folder, d1) for d1 in os.listdir(folder))
    if os.path.isdir(d)
]

for those still on python < 2.4: the inner construct needs to be a list instead of a tuple and therefore should read like this:

def listdirs(folder):  
  return [
    d for d in [os.path.join(folder, d1) for d1 in os.listdir(folder)]
    if os.path.isdir(d)
  ]

otherwise one gets a syntax error.

React Js: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

I confirm some methods proposed here that also worked for me : you have to put your local .json file in your public directory where fetch() is looking for (looking in http://localhost:3000/) for example : I use this fetch() in my src/App.js file:

componentDidMount(){
  fetch('./data/json-data.json')
  .then ( resp1 => resp1.json() )
  .then ( users1 => this.setState( {cards : users1} ) )
}

so I created public/data/json-data.json

and everything was fine then :)

ORA-00918: column ambiguously defined in SELECT *

A query's projection can only have one instance of a given name. As your WHERE clause shows, you have several tables with a column called ID. Because you are selecting * your projection will have several columns called ID. Or it would have were it not for the compiler hurling ORA-00918.

The solution is quite simple: you will have to expand the projection to explicitly select named columns. Then you can either leave out the duplicate columns, retaining just (say) COACHES.ID or use column aliases: coaches.id as COACHES_ID.

Perhaps that strikes you as a lot of typing, but it is the only way. If it is any comfort, SELECT * is regarded as bad practice in production code: explicitly named columns are much safer.

LaTeX: Prevent line break in a span of text

Use \nolinebreak

\nolinebreak[number]

The \nolinebreak command prevents LaTeX from breaking the current line at the point of the command. With the optional argument, number, you can convert the \nolinebreak command from a demand to a request. The number must be a number from 0 to 4. The higher the number, the more insistent the request is.

Source: http://www.personal.ceu.hu/tex/breaking.htm#nolinebreak

What's the use of session.flush() in Hibernate

Flushing the Session gets the data that is currently in the session synchronized with what is in the database.

More on the Hibernate website:

flush() is useful, because there are absolutely no guarantees about when the Session executes the JDBC calls, only the order in which they are executed - except you use flush().

What does 'var that = this;' mean in JavaScript?

This is a hack to make inner functions (functions defined inside other functions) work more like they should. In javascript when you define one function inside another this automatically gets set to the global scope. This can be confusing because you expect this to have the same value as in the outer function.

var car = {};
car.starter = {};

car.start = function(){
    var that = this;

    // you can access car.starter inside this method with 'this'
    this.starter.active = false;

    var activateStarter = function(){
        // 'this' now points to the global scope
        // 'this.starter' is undefined, so we use 'that' instead.
        that.starter.active = true;

        // you could also use car.starter, but using 'that' gives
        // us more consistency and flexibility
    };

    activateStarter();

};

This is specifically a problem when you create a function as a method of an object (like car.start in the example) then create a function inside that method (like activateStarter). In the top level method this points to the object it is a method of (in this case, car) but in the inner function this now points to the global scope. This is a pain.

Creating a variable to use by convention in both scopes is a solution for this very general problem with javascript (though it's useful in jquery functions, too). This is why the very general sounding name that is used. It's an easily recognizable convention for overcoming a shortcoming in the language.

Like El Ronnoco hints at Douglas Crockford thinks this is a good idea.

jQuery get html of container including the container itself

I like to use this;

$('#container').prop('outerHTML');

How can I determine the type of an HTML element in JavaScript?

nodeName is the attribute you are looking for. For example:

var elt = document.getElementById('foo');
console.log(elt.nodeName);

Note that nodeName returns the element name capitalized and without the angle brackets, which means that if you want to check if an element is an <div> element you could do it as follows:

elt.nodeName == "DIV"

While this would not give you the expected results:

elt.nodeName == "<div>"

Configure hibernate (using JPA) to store Y/N for type Boolean instead of 0/1

To do it in a generic JPA way using getter annotations, the example below works for me with Hibernate 3.5.4 and Oracle 11g. Note that the mapped getter and setter (getOpenedYnString and setOpenedYnString) are private methods. Those methods provide the mapping but all programmatic access to the class is using the getOpenedYn and setOpenedYn methods.

private String openedYn;

@Transient
public Boolean getOpenedYn() {
  return toBoolean(openedYn);
}

public void setOpenedYn(Boolean openedYn) {
  setOpenedYnString(toYesNo(openedYn));
}

@Column(name = "OPENED_YN", length = 1)
private String getOpenedYnString() {
  return openedYn;
}

private void setOpenedYnString(String openedYn) {
  this.openedYn = openedYn;
}

Here's the util class with static methods toYesNo and toBoolean:

public class JpaUtil {

    private static final String NO = "N";
    private static final String YES = "Y";

    public static String toYesNo(Boolean value) {
        if (value == null)
            return null;
        else if (value)
            return YES;
        else
            return NO;
    }

    public static Boolean toBoolean(String yesNo) {
        if (yesNo == null)
            return null;
        else if (YES.equals(yesNo))
            return true;
        else if (NO.equals(yesNo))
            return false;
        else
            throw new RuntimeException("unexpected yes/no value:" + yesNo);
    }
}

How to get the indices list of all NaN value in numpy array?

You can use np.where to match the boolean conditions corresponding to Nan values of the array and map each outcome to generate a list of tuples.

>>>list(map(tuple, np.where(np.isnan(x))))
[(1, 2), (2, 0)]

How to run specific test cases in GoogleTest

You could use advanced options to run Google tests.

To run only some unit tests you could use --gtest_filter=Test_Cases1* command line option with value that accepts the * and ? wildcards for matching with multiple tests. I think it will solve your problem.

UPD:

Well, the question was how to run specific test cases. Integration of gtest with your GUI is another thing, which I can't really comment, because you didn't provide details of your approach. However I believe the following approach might be a good start:

  1. Get all testcases by running tests with --gtest_list_tests
  2. Parse this data into your GUI
  3. Select test cases you want ro run
  4. Run test executable with option --gtest_filter

Launch iOS simulator from Xcode and getting a black screen, followed by Xcode hanging and unable to stop tasks

I am a newbie to the iOS app development. I was practising to develop iOS apps from the very beginning and while running a very basic Hello World app, I also faced same issue that only a black blank screen appears after building and running the app in iOS simulator. Somehow while struggling to find out a solution to the problem I accidentally clicked Window-->Scale-->50% in iOS simulator and it did solve my problem. I could then see the Home page with my app and clicking on app icon I was able to run my app successfully. App versions: Xcode 5.1 iOS Simulator: 7.1 OSX: 10.9.3

java.lang.RuntimeException: Unable to instantiate activity ComponentInfo

This can happen if your activity class is inside a default package. I fixed it by moving the activity class to a new package. and changing the manifest.xml

before

activity android:name=".MainActivity" 

after

activity android:name="new_package.MainActivity"

How to read existing text files without defining path

You absolutely need to know where the files to be read can be located. However, this information can be relative of course so it may be well adapted to other systems.

So it could relate to the current directory (get it from Directory.GetCurrentDirectory()) or to the application executable path (eg. Application.ExecutablePath comes to mind if using Windows Forms or via Assembly.GetEntryAssembly().Location) or to some special Windows directory like "Documents and Settings" (you should use Environment.GetFolderPath() with one element of the Environment.SpecialFolder enumeration).

Note that the "current directory" and the path of the executable are not necessarily identical. You need to know where to look!

In either case, if you need to manipulate a path use the Path class to split or combine parts of the path.

The representation of if-elseif-else in EL using JSF

You can use "ELSE IF" using conditional operator in expression language as below:

 <p:outputLabel value="#{transaction.status.equals('PNDNG')?'Pending':
                                     transaction.status.equals('RJCTD')?'Rejected':
                                     transaction.status.equals('CNFRMD')?'Confirmed':
                                     transaction.status.equals('PSTD')?'Posted':''}"/>

Python socket.error: [Errno 111] Connection refused

The problem obviously was (as you figured it out) that port 36250 wasn't open on the server side at the time you tried to connect (hence connection refused). I can see the server was supposed to open this socket after receiving SEND command on another connection, but it apparently was "not opening [it] up in sync with the client side".

Well, the main reason would be there was no synchronisation whatsoever. Calling:

cs.send("SEND " + FILE)
cs.close()

would just place the data into a OS buffer; close would probably flush the data and push into the network, but it would almost certainly return before the data would reach the server. Adding sleep after close might mitigate the problem, but this is not synchronisation.

The correct solution would be to make sure the server has opened the connection. This would require server sending you some message back (for example OK, or better PORT 36250 to indicate where to connect). This would make sure the server is already listening.

The other thing is you must check the return values of send to make sure how many bytes was taken from your buffer. Or use sendall.

(Sorry for disturbing with this late answer, but I found this to be a high traffic question and I really didn't like the sleep idea in the comments section.)

Hide Signs that Meteor.js was Used

The amount of hacks you would need to go through to completely hide the fact your site is built by Meteor.js is absolutely ridiculous. You would have to strip essentially all core functionality and just serve straight up html, completely defeating the purpose of using the framework anyway.

That being said, I suggest looking at buildwith.com

You enter a url, and it reveals a ton of information about a site. If you only need to "fool" engines like this, there may be simple solutions.

Android Studio: Drawable Folder: How to put Images for Multiple dpi?

New -> Batch Drawable Import -> Click on Add button -> Select image -> Select Target Resolution, Target Name, Format -> Ok

Specifying a custom DateTime format when serializing with Json.Net

You could use this approach:

public class DateFormatConverter : IsoDateTimeConverter
{
    public DateFormatConverter(string format)
    {
        DateTimeFormat = format;
    }
}

And use it this way:

class ReturnObjectA 
{
    [JsonConverter(typeof(DateFormatConverter), "yyyy-MM-dd")]
    public DateTime ReturnDate { get;set;}
}

The DateTimeFormat string uses the .NET format string syntax described here: https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings

Removing an activity from the history stack

if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            super.finishAndRemoveTask();
        }
        else {
            super.finish();
        }

Proper way to assert type of variable in Python

Doing type('') is effectively equivalent to str and types.StringType

so type('') == str == types.StringType will evaluate to "True"

Note that Unicode strings which only contain ASCII will fail if checking types in this way, so you may want to do something like assert type(s) in (str, unicode) or assert isinstance(obj, basestring), the latter of which was suggested in the comments by 007Brendan and is probably preferred.

isinstance() is useful if you want to ask whether an object is an instance of a class, e.g:

class MyClass: pass

print isinstance(MyClass(), MyClass) # -> True
print isinstance(MyClass, MyClass()) # -> TypeError exception

But for basic types, e.g. str, unicode, int, float, long etc asking type(var) == TYPE will work OK.

Can I escape html special chars in javascript?

This is, by far, the fastest way I have seen it done. Plus, it does it all without adding, removing, or changing elements on the page.

function escapeHTML(unsafeText) {
    let div = document.createElement('div');
    div.innerText = unsafeText;
    return div.innerHTML;
}

return string with first match Regex

Maybe this would perform a bit better in case greater amount of input data does not contain your wanted piece because except has greater cost.

def return_first_match(text):
    result = re.findall('\d+',text)
    result = result[0] if result else ""
    return result

How can I read the contents of an URL with Python?

You can use requests and beautifulsoup libraries to read data on a website. Just install these two libraries and type the following code.

import requests
import bs4
help(requests)
help(bs4)

You will get all the information you need about the library.

Weblogic Transaction Timeout : how to set in admin console in WebLogic AS 8.1

After logging in, on the home page of the Server Console you should see 3 sections:

  • Information and Resources
  • Domain Configurations
  • Services Configurations

Under Services Configurations there is subsection Other Services. Click the JTA Configuration link under Other Services. The transaction timeout should be the top setting on the page displayed, labelled Timeout Seconds.

Weblogic Console screenshot

Setting the JVM via the command line on Windows

Yes - just explicitly provide the path to java.exe. For instance:

c:\Users\Jon\Test>"c:\Program Files\java\jdk1.6.0_03\bin\java.exe" -version
java version "1.6.0_03"
Java(TM) SE Runtime Environment (build 1.6.0_03-b05)
Java HotSpot(TM) Client VM (build 1.6.0_03-b05, mixed mode, sharing)

c:\Users\Jon\Test>"c:\Program Files\java\jdk1.6.0_12\bin\java.exe" -version
java version "1.6.0_12"
Java(TM) SE Runtime Environment (build 1.6.0_12-b04)
Java HotSpot(TM) Client VM (build 11.2-b01, mixed mode, sharing)

The easiest way to do this for a running command shell is something like:

set PATH=c:\Program Files\Java\jdk1.6.0_03\bin;%PATH%

For example, here's a complete session showing my default JVM, then the change to the path, then the new one:

c:\Users\Jon\Test>java -version
java version "1.6.0_12"
Java(TM) SE Runtime Environment (build 1.6.0_12-b04)
Java HotSpot(TM) Client VM (build 11.2-b01, mixed mode, sharing)

c:\Users\Jon\Test>set PATH=c:\Program Files\Java\jdk1.6.0_03\bin;%PATH%

c:\Users\Jon\Test>java -version
java version "1.6.0_03"
Java(TM) SE Runtime Environment (build 1.6.0_03-b05)
Java HotSpot(TM) Client VM (build 1.6.0_03-b05, mixed mode, sharing)

This won't change programs which explicitly use JAVA_HOME though.

Note that if you get the wrong directory in the path - including one that doesn't exist - you won't get any errors, it will effectively just be ignored.

How to compare DateTime without time via LINQ?

I found this question while I was stuck with the same query. I finally found it without using DbFunctions. Try this:

var q = db.Games.Where(t => t.StartDate.Day == DateTime.Now.Day && t.StartDate.Month == DateTime.Now.Month && t.StartDate.Year == DateTime.Now.Year ).OrderBy(d => d.StartDate);

This way by bifurcating the date parts we effectively compare only the dates, thus leaving out the time.

Hope that helps. Pardon me for the formatting in the answer, this is my first answer.

Enabling/Disabling Microsoft Virtual WiFi Miniport

Microsoft Virtual WiFi Miniport should start and bind automatically to the underlying function driver. Try disabling and reenabling the AR9285 driver.

XML shape drawable not rendering desired color

In drawable I use this xml code to define the border and background:

<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
  <stroke android:width="4dp" android:color="#D8FDFB" /> 
  <padding android:left="7dp" android:top="7dp" 
    android:right="7dp" android:bottom="7dp" /> 
  <corners android:radius="4dp" /> 
  <solid android:color="#f0600000"/> 
</shape> 

Exists Angularjs code/naming conventions?

I started this gist a year ago: https://gist.github.com/PascalPrecht/5411171

Brian Ford (member of the core team) has written this blog post about it: http://briantford.com/blog/angular-bower

And then we started with this component spec (which is not quite complete): https://github.com/angular/angular-component-spec

Since the last ng-conf there's this document for best practices by the core team: https://docs.google.com/document/d/1XXMvReO8-Awi1EZXAXS4PzDzdNvV6pGcuaF4Q9821Es/pub

Genymotion error at start 'Unable to load virtualbox'

In Linux at least, I had to restart VirtualBox, running this command on terminal:

/lib/virtualbox/VirtualBox restart

Seems to be the same on Mac OS X.

How to execute two mysql queries as one in PHP/MYSQL?

You'll have to use the MySQLi extension if you don't want to execute a query twice:

if (mysqli_multi_query($link, $query))
{
    $result1 = mysqli_store_result($link);
    $result2 = null;

    if (mysqli_more_results($link))
    {
        mysqli_next_result($link);
        $result2 = mysqli_store_result($link);
    }

    // do something with both result sets.

    if ($result1)
        mysqli_free_result($result1);

    if ($result2)
        mysqli_free_result($result2);
}

Get single listView SelectedItem

If you want to select single listview item no mouse click over it try this.

private void timeTable_listView_MouseUp(object sender, MouseEventArgs e)
        {
            Point mousePos = timeTable_listView.PointToClient(Control.MousePosition);
            ListViewHitTestInfo hitTest = timeTable_listView.HitTest(mousePos);



            try
            {
            int columnIndex = hitTest.Item.SubItems.IndexOf(hitTest.SubItem);
            edit_textBox.Text = timeTable_listView.SelectedItems[0].SubItems[columnIndex].Text;
            }
            catch(Exception)
            {

            }



        }

Xcode - iPhone - profile doesn't match any valid certificate-/private-key pair in the default keychain

My problem was my Target profile didn't have the proper code signing option selected:

Target Menu -> Code Signing -> Code Signing Identity

Choose "iPhone developer" then select the provisional profile you created.

Difference between hamiltonian path and euler path

Eulerian path must visit each edge exactly once, while Hamiltonian path must visit each vertex exactly once.

Set custom HTML5 required field validation message

HTML:

<form id="myform">
    <input id="email" oninvalid="InvalidMsg(this);" name="email" oninput="InvalidMsg(this);"  type="email" required="required" />
    <input type="submit" />
</form>

JAVASCRIPT :

function InvalidMsg(textbox) {
    if (textbox.value == '') {
        textbox.setCustomValidity('Required email address');
    }
    else if (textbox.validity.typeMismatch){{
        textbox.setCustomValidity('please enter a valid email address');
    }
    else {
       textbox.setCustomValidity('');
    }
    return true;
}

Demo :

http://jsfiddle.net/patelriki13/Sqq8e/

How do you read scanf until EOF in C?

Man, if you are using Windows, EOF is not reached by pressing enter, but by pressing Crtl+Z at the console. This will print "^Z", an indicator of EOF. The behavior of functions when reading this (the EOF or Crtl+Z):

Function: Output: scanf(...) EOF gets(<variable>) NULL feof(stdin) 1 getchar() EOF

How to use `@ts-ignore` for a block

You can't.

As a workaround you can use a // @ts-nocheck comment at the top of a file to disable type-checking for that file: https://devblogs.microsoft.com/typescript/announcing-typescript-3-7-beta/

So to disable checking for a block (function, class, etc.), you can move it into its own file, then use the comment/flag above. (This isn't as flexible as block-based disabling of course, but it's the best option available at the moment.)

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

I couldn't get any of the above ways to work, but this worked. The username and password for DirectoryEntry are optional.

   private List<string> getAnyDirectoryEntryPropertyValue(string userPrincipalName, string propertyToSearchFor)
    {
        List<string> returnValue = new List<string>();
        try
        {
            int index = userPrincipalName.IndexOf("@");
            string originatingServer = userPrincipalName.Remove(0, index + 1);
            string path = "LDAP://" + originatingServer; //+ @"/" + distinguishedName;
            DirectoryEntry objRootDSE = new DirectoryEntry(path, PSUsername, PSPassword);
            var objSearcher = new System.DirectoryServices.DirectorySearcher(objRootDSE);
            objSearcher.Filter = string.Format("(&(UserPrincipalName={0}))", userPrincipalName);
            SearchResultCollection properties = objSearcher.FindAll();

            ResultPropertyValueCollection resPropertyCollection = properties[0].Properties[propertyToSearchFor];
            foreach (string resProperty in resPropertyCollection)
            {
                returnValue.Add(resProperty);
            }
        }
        catch (Exception ex)
        {
            returnValue.Add(ex.Message);
            throw;
        }

        return returnValue;
    }

performSelector may cause a leak because its selector is unknown

For posterity's sake, I've decided to throw my hat into the ring :)

Recently I've been seeing more and more restructuring away from the target/selector paradigm, in favor of things such as protocols, blocks, etc. However, there is one drop-in replacement for performSelector that I've used a few times now:

[NSApp sendAction: NSSelectorFromString(@"someMethod") to: _controller from: nil];

These seem to be a clean, ARC-safe, and nearly identical replacement for performSelector without having to much about with objc_msgSend().

Though, I have no idea if there is an analog available on iOS.