Programs & Examples On #Execute immediate

An Oracle statement to execute a dynamic query or anonymous PL/SQL block.

Using bind variables with dynamic SELECT INTO clause in PL/SQL

No you can't use bind variables that way. In your second example :into_bind in v_query_str is just a placeholder for value of variable v_num_of_employees. Your select into statement will turn into something like:

SELECT COUNT(*) INTO  FROM emp_...

because the value of v_num_of_employees is null at EXECUTE IMMEDIATE.

Your first example presents the correct way to bind the return value to a variable.

Edit

The original poster has edited the second code block that I'm referring in my answer to use OUT parameter mode for v_num_of_employees instead of the default IN mode. This modification makes the both examples functionally equivalent.

SQL Server - Case Statement

I am looking for a way to create a select without repeating the conditional query.

I'm assuming that you don't want to repeat Foo-stuff+bar. You could put your calculation into a derived table:

SELECT CASE WHEN a.TestValue > 2 THEN a.TestValue ELSE 'Fail' END 
FROM (SELECT (Foo-stuff+bar) AS TestValue FROM MyTable) AS a

A common table expression would work just as well:

WITH a AS (SELECT (Foo-stuff+bar) AS TestValue FROM MyTable)
SELECT CASE WHEN a.TestValue > 2 THEN a.TestValue ELSE 'Fail' END    
FROM a

Also, each part of your switch should return the same datatype, so you may have to cast one or more cases.

"The semaphore timeout period has expired" error for USB connection

Too many big files all in one go. Windows barfs. Essentially the copying took too long because you asked too much of the computer and the file locking was locked too long and set a flag off, the flag is a semaphore error.

The computer stuffed itself and choked on it. I saw the RAM memory here get progressively filled with a Cache in RAM. Then when filled the subsystem ground to a halt with a semaphore error.

I have a workaround; copy or transfer fewer files not one humongous block. Break it down into sets of blocks and send across the files one at a time, maybe a few at a time, but not never the lot.

References:

https://appuals.com/how-to-fix-the-semaphore-timeout-period-has-expired-0x80070079/

https://www-01.ibm.com/support/docview.wss?uid=swg21094630

How can I resize an image using Java?

FWIW I just released (Apache 2, hosted on GitHub) a simple image-scaling library for Java called imgscalr (available on Maven central).

The library implements a few different approaches to image-scaling (including Chris Campbell's incremental approach with a few minor enhancements) and will either pick the most optimal approach for you if you ask it to, or give you the fastest or best looking (if you ask for that).

Usage is dead-simple, just a bunch of static methods. The simplest use-case is:

BufferedImage scaledImage = Scalr.resize(myImage, 200);

All operations maintain the image's original proportions, so in this case you are asking imgscalr to resize your image within a bounds of 200 pixels wide and 200 pixels tall and by default it will automatically select the best-looking and fastest approach for that since it wasn't specified.

I realize on the outset this looks like self-promotion (it is), but I spent my fair share of time googling this exact same subject and kept coming up with different results/approaches/thoughts/suggestions and decided to sit down and write a simple implementation that would address that 80-85% use-cases where you have an image and probably want a thumbnail for it -- either as fast as possible or as good-looking as possible (for those that have tried, you'll notice doing a Graphics.drawImage even with BICUBIC interpolation to a small enough image, it still looks like garbage).

Telling gcc directly to link a library statically

You can add .a file in the linking command:

  gcc yourfiles /path/to/library/libLIBRARY.a

But this is not talking with gcc driver, but with ld linker as options like -Wl,anything are.

When you tell gcc or ld -Ldir -lLIBRARY, linker will check both static and dynamic versions of library (you can see a process with -Wl,--verbose). To change order of library types checked you can use -Wl,-Bstatic and -Wl,-Bdynamic. Here is a man page of gnu LD: http://linux.die.net/man/1/ld

To link your program with lib1, lib3 dynamically and lib2 statically, use such gcc call:

gcc program.o -llib1 -Wl,-Bstatic -llib2 -Wl,-Bdynamic -llib3

Assuming that default setting of ld is to use dynamic libraries (it is on Linux).

Make sure that the controller has a parameterless public constructor error

I've got this error when I accidentally defined a property as a specific object type, instead of the interface type I have defined in UnityContainer.

For example:

Defining UnityContainer:

var container = new UnityContainer();
container.RegisterInstance(typeof(IDashboardRepository), DashboardRepository);
config.DependencyResolver = new UnityResolver(container);

SiteController (the wrong way - notice repo type):

private readonly DashboardRepository _repo;

public SiteController(DashboardRepository repo)
{
    _repo = repo;
}

SiteController (the right way):

private readonly IDashboardRepository _repo;

public SiteController(IDashboardRepository repo)
{
    _repo = repo;
}

How do you sort an array on multiple columns?

I found multisotr. This is simple, powerfull and small library for multiple sorting. I was need to sort an array of objects with dynamics sorting criteria:

_x000D_
_x000D_
const criteria = ['name', 'speciality']_x000D_
const data = [_x000D_
  { name: 'Mike', speciality: 'JS', age: 22 },_x000D_
  { name: 'Tom', speciality: 'Java', age: 30 },_x000D_
  { name: 'Mike', speciality: 'PHP', age: 40 },_x000D_
  { name: 'Abby', speciality: 'Design', age: 20 },_x000D_
]_x000D_
_x000D_
const sorted = multisort(data, criteria)_x000D_
_x000D_
console.log(sorted)
_x000D_
<script src="https://cdn.rawgit.com/peterkhayes/multisort/master/multisort.js"></script>
_x000D_
_x000D_
_x000D_

This library more mutch powerful, that was my case. Try it.

How do I test if a variable is a number in Bash?

Below is a Script written by me and used for a script integration with Nagios and it is working properly till now

#!/bin/bash
# Script to test variable is numeric or not
# Shirish Shukla
# Pass arg1 as number
a1=$1
a=$(echo $a1|awk '{if($1 > 0) print $1; else print $1"*-1"}')
b=$(echo "scale=2;$a/$a + 1" | bc -l 2>/dev/null)
if [[ $b > 1 ]]
then
    echo "$1 is Numeric"
else
    echo "$1 is Non Numeric"
fi

EG:

# sh isnumsks.sh   "-22.22"
-22.22 is Numeric

# sh isnumsks.sh   "22.22"
22.22 is Numeric

# sh isnumsks.sh   "shirish22.22"
shirish22.22 is Non  Numeric

Listing only directories in UNIX

du -d1 is perhaps the shortest option. (As long as you don't need to pipe the input to another command.)

Mockito: Mock private field initialization

I already found the solution to this problem which I forgot to post here.

@RunWith(PowerMockRunner.class)
@PrepareForTest({ Test.class })
public class SampleTest {

@Mock
Person person;

@Test
public void testPrintName() throws Exception {
    PowerMockito.whenNew(Person.class).withNoArguments().thenReturn(person);
    Test test= new Test();
    test.testMethod();
    }
}

Key points to this solution are:

  1. Running my test cases with PowerMockRunner: @RunWith(PowerMockRunner.class)

  2. Instruct Powermock to prepare Test.class for manipulation of private fields: @PrepareForTest({ Test.class })

  3. And finally mock the constructor for Person class:

    PowerMockito.mockStatic(Person.class); PowerMockito.whenNew(Person.class).withNoArguments().thenReturn(person);

How do I add FTP support to Eclipse?

I'm not sure if this works for you, but when I do small solo PHP projects with Eclipse, the first thing I set up is an Ant script for deploying the project to a remote testing environment. I code away locally, and whenever I want to test it, I just hit the shortcut which updates the remote site.

Eclipse has good Ant support out of the box, and the scripts aren't hard to make.

enable/disable zoom in Android WebView

hey there for anyone who might be looking for solution like this.. i had issue with scaling inside WebView so best way to do is in your java.class where you set all for webView put this two line of code: (webViewSearch is name of my webView -->webViewSearch = (WebView) findViewById(R.id.id_webview_search);)

// force WebView to show content not zoomed---------------------------------------------------------
    webViewSearch.getSettings().setLoadWithOverviewMode(true);
    webViewSearch.getSettings().setUseWideViewPort(true);

Angular2 If ngModel is used within a form tag, either the name attribute must be set or the form

If ngForm is used, all the input fields which have [(ngModel)]="" must have an attribute name with a value.

<input [(ngModel)]="firstname" name="something">

Parsing a JSON string in Ruby

Just to extend the answers a bit with what to do with the parsed object:

# JSON Parsing example
require "rubygems" # don't need this if you're Ruby v1.9.3 or higher
require "json"

string = '{"desc":{"someKey":"someValue","anotherKey":"value"},"main_item":{"stats":{"a":8,"b":12,"c":10}}}'
parsed = JSON.parse(string) # returns a hash

p parsed["desc"]["someKey"]
p parsed["main_item"]["stats"]["a"]

# Read JSON from a file, iterate over objects
file = open("shops.json")
json = file.read

parsed = JSON.parse(json)

parsed["shop"].each do |shop|
  p shop["id"]
end

Javascript to Select Multiple options

Based on @Peter Baley answer, I created a more generic function:

   @objectId: HTML object ID
   @values: can be a string or an array. String is less "secure" (should not contain repeated value).
   function checkMultiValues(objectId, values){
        selectMultiObject=document.getElementById(objectId);
        for ( var i = 0, l = selectMultiObject.options.length, o; i < l; i++ )
        {
          o = selectMultiObject.options[i];
          if ( values.indexOf( o.value ) != -1 )
          {
            o.selected = true;
          } else {
            o.selected = false;
          }
        }
    }

Example: checkMultiValues('thisMultiHTMLObject','a,b,c,d');

When should I use double or single quotes in JavaScript?

Strictly speaking, there is no difference in meaning; so the choice comes down to convenience.

Here are several factors that could influence your choice:

  • House style: Some groups of developers already use one convention or the other.
  • Client-side requirements: Will you be using quotes within the strings? (See Ady's answer.)
  • Server-side language: VB.NET people might choose to use single quotes for JavaScript so that the scripts can be built server-side (VB.NET uses double-quotes for strings, so the JavaScript strings are easy to distinguished if they use single quotes).
  • Library code: If you're using a library that uses a particular style, you might consider using the same style yourself.
  • Personal preference: You might think one or other style looks better.

How to make a loop in x86 assembly language?

You need to use conditional jmp commands. This isn't the same syntax as you're using; looks like MASM, but using GAS here's an example from some code I wrote to calculate gcd:

gcd_alg:
    subl    %ecx, %eax      /* a = a - c */
    cmpl    $0, %eax        /* if a == 0 */
    je      gcd_done        /* jump to end */
    cmpl    %ecx, %eax      /* if a < c */
    jl      gcd_preswap     /* swap and start over */
    jmp     gcd_alg         /* keep subtracting */

Basically, I compare two registers with the cmpl instruction (compare long). If it is less the JL (jump less) instruction jumps to the preswap location, otherwise it jumps back to the same label.

As for clearing the screen, that depends on the system you're using.

How to prevent buttons from submitting forms

The return false prevents the default behavior. but the return false breaks the bubbling of additional click events. This means if there are any other click bindings after this function gets called, those others do not Consider.

 <button id="btnSubmit" type="button">PostData</button>
 <Script> $("#btnSubmit").click(function(){
   // do stuff
   return false;
}); </Script>

Or simply you can put like this

 <button type="submit" onclick="return false"> PostData</button>

Postgresql : syntax error at or near "-"

I have reproduced the issue in my system,

postgres=# alter user my-sys with password 'pass11';
ERROR:  syntax error at or near "-"
LINE 1: alter user my-sys with password 'pass11';
                       ^

Here is the issue,

psql is asking for input and you have given again the alter query see postgres-#That's why it's giving error at alter

postgres-# alter user "my-sys" with password 'pass11';
ERROR:  syntax error at or near "alter"
LINE 2: alter user "my-sys" with password 'pass11';
        ^

Solution is as simple as the error,

postgres=# alter user "my-sys" with password 'pass11';
ALTER ROLE

iconv - Detected an illegal character in input string

I found one Solution :

echo iconv('UTF-8', 'ASCII//TRANSLIT', utf8_encode($string));

use utf8_encode()

CSS Circular Cropping of Rectangle Image

You need to use jQuery to do this. This approach gives you the abbility to have dynamic images and do them round no matter the size.

My demo has one flaw right now I don't center the image in the container, but ill return to it in a minute (need to finish a script I'm working on).

DEMO

<div class="container">
    <img src="" class="image" alt="lambo" />
</div>

//script
var container = $('.container'),
    image = container.find('img');

container.width(image.height());


//css    
.container {
    height: auto;
    overflow: hidden;
    border-radius: 50%;    
}

.image {
    height: 100%;    
    display: block;    
}

What is android:weightSum in android, and how does it work?

Per documentation, android:weightSum defines the maximum weight sum, and is calculated as the sum of the layout_weight of all the children if not specified explicitly.

Let's consider an example with a LinearLayout with horizontal orientation and 3 ImageViews inside it. Now we want these ImageViews always to take equal space. To acheive this, you can set the layout_weight of each ImageView to 1 and the weightSum will be calculated to be equal to 3 as shown in the comment.

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    <!-- android:weightSum="3" -->
    android:orientation="horizontal"
    android:layout_gravity="center">

   <ImageView
       android:layout_height="wrap_content"       
       android:layout_weight="1"
       android:layout_width="0dp"/>
  .....

weightSum is useful for having the layout rendered correctly for any device, which will not happen if you set width and height directly.

Trigger standard HTML5 validation (form) without using submit button?

The accepted answer to this question appears to be what you're looking for.

Short summary: in the event handler for the submit, call event.preventDefault().

How to get last inserted row ID from WordPress database?

Something like this should do it too :

$last = $wpdb->get_row("SHOW TABLE STATUS LIKE 'table_name'");
$lastid = $last->Auto_increment;

Find text in string with C#

If you know that you always want the string between "my" and "is", then you can always perform the following:

string message = "This is an example string and my data is here";

//Get the string position of the first word and add two (for it's length)
int pos1 = message.IndexOf("my") + 2;

//Get the string position of the next word, starting index being after the first position
int pos2 = message.IndexOf("is", pos1);

//use substring to obtain the information in between and store in a new string
string data = message.Substring(pos1, pos2 - pos1).Trim();

How can I open two pages from a single click without using JavaScript?

If you have the authority to edit the pages to be opened, you can href to 'A' page and in the A page you can put link to B page in onpageload attribute of body tag.

Add CSS or JavaScript files to layout head from views or partial views

I tried to solve this issue.

My answer is here.

"DynamicHeader" - http://dynamicheader.codeplex.com/, https://nuget.org/packages/DynamicHeader

For example, _Layout.cshtml is:

<head>
@Html.DynamicHeader()
</head>
...

And, you can register .js and .css files to "DynamicHeader" anywhere you want.

For example, the code block in AnotherPartial.cshtml is:

@{
  DynamicHeader.AddSyleSheet("~/Content/themes/base/AnotherPartial.css");
  DynamicHeader.AddScript("~/some/myscript.js");
}

Result HTML output for this sample is:

<html>
  <link href="/myapp/Content/themes/base/AnotherPartial.css" .../>
  <script src="/myapp/some/myscript.js" ...></script>
</html>
...

Eloquent get only one column as an array

If you receive multiple entries the correct method is called lists.

    Word_relation::select('word_two')->where('word_one', $word_id)->lists('word_one')->toArray();

Sequel Pro Alternative for Windows

You can try DBVisualizer some features are not free, but you can get an evaluate license...

MongoDB SELECT COUNT GROUP BY

This type of query worked for me:

 db.events.aggregate({$group: {_id : "$date", number:  { $sum : 1} }} )

See http://docs.mongodb.org/manual/tutorial/aggregation-with-user-preference-data/

How to store Emoji Character in MySQL Database

Step 1, change your database's default charset:

ALTER DATABASE database_name CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;

if the db is not created yet, create it with correct encodings:

CREATE DATABASE database_name DEFAULT CHARSET = utf8mb4 DEFAULT COLLATE = utf8mb4_unicode_ci;

Step 2, set charset when creating table:

CREATE TABLE IF NOT EXISTS table_name (
...
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE utf8mb4_unicode_ci;

or alter table

ALTER TABLE table_name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
ALTER TABLE table_name MODIFY field_name TEXT CHARSET utf8mb4;

How to convert Seconds to HH:MM:SS using T-SQL

This is what I use (typically for html table email reports)

declare @time int, @hms varchar(20)
set @time = 12345
set @hms = cast(cast((@Time)/3600 as int) as varchar(3)) 
  +':'+ right('0'+ cast(cast(((@Time)%3600)/60 as int) as varchar(2)),2) 
  +':'+ right('0'+ cast(((@Time)%3600)%60 as varchar(2)),2) +' (hh:mm:ss)'
select @hms

Undefined variable: $_SESSION

You need make sure to start the session at the top of every PHP file where you want to use the $_SESSION superglobal. Like this:

<?php
  session_start();
  echo $_SESSION['youritem'];
?>

You forgot the Session HELPER.

Check this link : book.cakephp.org/2.0/en/core-libraries/helpers/session.html

C++ Cout & Cin & System "Ambiguous"

This kind of thing doesn't just magically happen on its own; you changed something! In industry we use version control to make regular savepoints, so when something goes wrong we can trace back the specific changes we made that resulted in that problem.

Since you haven't done that here, we can only really guess. In Visual Studio, Intellisense (the technology that gives you auto-complete dropdowns and those squiggly red lines) works separately from the actual C++ compiler under the bonnet, and sometimes gets things a bit wrong.

In this case I'd ask why you're including both cstdlib and stdlib.h; you should only use one of them, and I recommend the former. They are basically the same header, a C header, but cstdlib puts them in the namespace std in order to "C++-ise" them. In theory, including both wouldn't conflict but, well, this is Microsoft we're talking about. Their C++ toolchain sometimes leaves something to be desired. Any time the Intellisense disagrees with the compiler has to be considered a bug, whichever way you look at it!

Anyway, your use of using namespace std (which I would recommend against, in future) means that std::system from cstdlib now conflicts with system from stdlib.h. I can't explain what's going on with std::cout and std::cin.

Try removing #include <stdlib.h> and see what happens.

If your program is building successfully then you don't need to worry too much about this, but I can imagine the false positives being annoying when you're working in your IDE.

Posting JSON data via jQuery to ASP .NET MVC 4 controller action

I think you'll find your answer if you refer to this post: Deserialize JSON into C# dynamic object?

There are various ways of achieving what you want here. The System.Web.Helpers.Json approach (a few answers down) seems to be the simplest.

How can I know if a process is running?

Process.GetProcesses() is the way to go. But you may need to use one or more different criteria to find your process, depending on how it is running (i.e. as a service or a normal app, whether or not it has a titlebar).

Show/hide div if checkbox selected

<input type="checkbox" name="check1" value="checkbox" onchange="showMe('div1')" /> checkbox

<div id="div1" style="display:none;">NOTICE</div>

  <script type="text/javascript">
<!--
   function showMe (box) {
    var chboxs = document.getElementById("div1").style.display;
    var vis = "none";
        if(chboxs=="none"){
         vis = "block"; }
        if(chboxs=="block"){
         vis = "none"; }
    document.getElementById(box).style.display = vis;
}
  //-->
</script>

How to efficiently remove duplicates from an array without using Set

What if you create two boolean arrays: 1 for negative values and 1 for positive values and init it all on false.

Then you cycle thorugh the input array and lookup in the arrays if you've encoutered the value already. If not, you add it to the output array and mark it as already used.

How do I correct this Illegal String Offset?

I get the same error in WP when I use php ver 7.1.6 - just take your php version back to 7.0.20 and the error will disappear.

How do I filter date range in DataTables?

Follow the link below and configure it to what you need. Daterangepicker does it for you, very easily. :)

http://www.daterangepicker.com/#ex1

Should methods in a Java interface be declared with or without a public access modifier?

The public modifier should be omitted in Java interfaces (in my opinion).

Since it does not add any extra information, it just draws attention away from the important stuff.

Most style-guides will recommend that you leave it out, but of course, the most important thing is to be consistent across your codebase, and especially for each interface. The following example could easily confuse someone, who is not 100% fluent in Java:

public interface Foo{
  public void MakeFoo();
  void PerformBar();
}

How to find index position of an element in a list when contains returns true

Here is an example:

List<String> names;
names.add("toto");
names.add("Lala");
names.add("papa");
int index = names.indexOf("papa"); // index = 2

Where does Android app package gets installed on phone

->List all the packages by :

adb shell su 0 pm list packages -f

->Search for your package name by holding keys "ctrl+alt+f".

->Once found, look for the location associated with it.

How do I combine the first character of a cell with another cell in Excel?

Not sure why no one is using semicolons. This is how it works for me:

=CONCATENATE(LEFT(A1;1); B1)

Solutions with comma produce an error in Excel.

How do you declare an interface in C++?

If you're using Microsoft's C++ compiler, then you could do the following:

struct __declspec(novtable) IFoo
{
    virtual void Bar() = 0;
};

class Child : public IFoo
{
public:
    virtual void Bar() override { /* Do Something */ }
}

I like this approach because it results in a lot smaller interface code and the generated code size can be significantly smaller. The use of novtable removes all reference to the vtable pointer in that class, so you can never instantiate it directly. See the documentation here - novtable.

HTTP 401 - what's an appropriate WWW-Authenticate header value?

No, you'll have to specify the authentication method to use (typically "Basic") and the authentication realm. See http://en.wikipedia.org/wiki/Basic_access_authentication for an example request and response.

You might also want to read RFC 2617 - HTTP Authentication: Basic and Digest Access Authentication.

How to reset radiobuttons in jQuery so that none is checked

Set all radio buttons back to the default:

$("input[name='correctAnswer']").checkboxradio( "refresh" );

Detect user scroll down or scroll up in jQuery

To differentiate between scroll up/down in jQuery, you could use:

var mousewheelevt = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel" //FF doesn't recognize mousewheel as of FF3.x
$('#yourDiv').bind(mousewheelevt, function(e){

    var evt = window.event || e //equalize event object     
    evt = evt.originalEvent ? evt.originalEvent : evt; //convert to originalEvent if possible               
    var delta = evt.detail ? evt.detail*(-40) : evt.wheelDelta //check for detail first, because it is used by Opera and FF

    if(delta > 0) {
        //scroll up
    }
    else{
        //scroll down
    }   
});

This method also works in divs that have overflow:hidden.

I successfully tested it in FireFox, IE and Chrome.

std::string length() and size() member functions

Ruby's just the same, btw, offering both #length and #size as synonyms for the number of items in arrays and hashes (C++ only does it for strings).

Minimalists and people who believe "there ought to be one, and ideally only one, obvious way to do it" (as the Zen of Python recites) will, I guess, mostly agree with your doubts, @Naveen, while fans of Perl's "There's more than one way to do it" (or SQL's syntax with a bazillion optional "noise words" giving umpteen identically equivalent syntactic forms to express one concept) will no doubt be complaining that Ruby, and especially C++, just don't go far enough in offering such synonymical redundancy;-).

Programmatically get own phone number in iOS

Using Private API you can get user phone number on the following way:

extern NSString* CTSettingCopyMyPhoneNumber();


+(NSString *) phoneNumber {
NSString *phone = CTSettingCopyMyPhoneNumber();

return phone;
}

Also include CoreTelephony.framework to your project.

How to make an ImageView with rounded corners?

In Layout Make your ImageView like:

<com.example..CircularImageView
    android:id="@+id/profile_image_round_corner"
    android:layout_width="80dp"
    android:layout_height="80dp"
    android:scaleType="fitCenter"
    android:padding="2dp"
    android:background="@null"
    android:adjustViewBounds="true"
    android:layout_centerInParent="true"
    android:src="@drawable/dummy"
    />

And Create a Class:

package com.example;

import java.util.Formatter.BigDecimalLayoutForm;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

public class CircularImageView extends ImageView {

    public CircularImageView(Context context) {
        super(context);
    }

    public CircularImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CircularImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onDraw(Canvas canvas) {

        Drawable drawable = getDrawable();

        if (drawable == null) {
            return;
        }

        if (getWidth() == 0 || getHeight() == 0) {
            return;
        }
        Bitmap b = ((BitmapDrawable) drawable).getBitmap();
        Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);

        int w = getWidth(), h = getHeight();

        Bitmap roundBitmap = getRoundBitmap(bitmap, w);
        canvas.drawBitmap(roundBitmap, 0, 0, null);

    }

    public static Bitmap getRoundBitmap(Bitmap bmp, int radius) {
        Bitmap sBmp;

        if (bmp.getWidth() != radius || bmp.getHeight() != radius) {
            float smallest = Math.min(bmp.getWidth(), bmp.getHeight());
            float factor = smallest / radius;
            sBmp = Bitmap.createScaledBitmap(bmp, (int)(bmp.getWidth() / factor), (int)(bmp.getHeight() / factor), false);
        } else {
            sBmp = bmp;
        }

        Bitmap output = Bitmap.createBitmap(radius, radius, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
        final int color = 0xffa19774;
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, radius, radius);
        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);
        paint.setDither(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(Color.parseColor("#BAB399"));
        canvas.drawCircle(radius / 2 + 0.7f,
                radius / 2 + 0.7f, radius / 2 + 0.1f, paint);
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(sBmp, rect, rect, paint);

        return output;
    }

}

Quickest way to find missing number in an array of numbers

Quick sort is the best choice with maximum efficiency....

Get Unix timestamp with C++

The most common advice is wrong, you can't just rely on time(). That's used for relative timing: ISO C++ doesn't specify that 1970-01-01T00:00Z is time_t(0)

What's worse is that you can't easily figure it out, either. Sure, you can find the calendar date of time_t(0) with gmtime, but what are you going to do if that's 2000-01-01T00:00Z ? How many seconds were there between 1970-01-01T00:00Z and 2000-01-01T00:00Z? It's certainly no multiple of 60, due to leap seconds.

Backporting Python 3 open(encoding="utf-8") to Python 2

Not a general answer, but may be useful for the specific case where you are happy with the default python 2 encoding, but want to specify utf-8 for python 3:

if sys.version_info.major > 2:
    do_open = lambda filename: open(filename, encoding='utf-8')
else:
    do_open = lambda filename: open(filename)

with do_open(filename) as file:
    pass

Linker Command failed with exit code 1 (use -v to see invocation), Xcode 8, Swift 3

In my case I have change the Target name in my Podfile So it's create the same Error for me.

Solution

Just go project-> Build Phase->Link Binary with libraries Remove the old FrameWorks by click on minus button(-) And clean and Run again. It's work me.

enter image description here

Remove Unwanted .framework.

PHP using Gettext inside <<<EOF string

As far as I can see in the manual, it is not possible to call functions inside HEREDOC strings. A cumbersome way would be to prepare the words beforehand:

<?php

    $world = _("World");

    $str = <<<EOF
    <p>Hello</p>
    <p>$world</p>
EOF;
    echo $str;
?>

a workaround idea that comes to mind is building a class with a magic getter method.

You would declare a class like this:

class Translator
{
 public function __get($name) {
  return _($name); // Does the gettext lookup
  }
 }

Initialize an object of the class at some point:

  $translate = new Translator();

You can then use the following syntax to do a gettext lookup inside a HEREDOC block:

    $str = <<<EOF
    <p>Hello</p>
    <p>{$translate->World}</p>
EOF;
    echo $str;
?>

$translate->World will automatically be translated to the gettext lookup thanks to the magic getter method.

To use this method for words with spaces or special characters (e.g. a gettext entry named Hello World!!!!!!, you will have to use the following notation:

 $translate->{"Hello World!!!!!!"}

This is all untested but should work.

Update: As @mario found out, it is possible to call functions from HEREDOC strings after all. I think using getters like this is a sleek solution, but using a direct function call may be easier. See the comments on how to do this.

Expected block end YAML error

This error also occurs if you use four-space instead of two-space indentation.

e.g., the following would throw the error:

fields:
    - metadata: {}
        name: colName
        nullable: true

whereas changing indentation to two-spaces would fix it:

fields:
  - metadata: {}
    name: colName
    nullable: true

How do I make this file.sh executable via double click?

you can change the file executable by using chmod like this

chmod 755 file.sh

and use this command for execute

./file.sh

How can I cast int to enum?

var result = Enum.TryParse(yourString, out yourEnum) 

And make sure to check the result to determine if the conversion failed.

Spring Data: "delete by" is supported?

2 ways:-

1st one Custom Query

@Modifying
@Query("delete from User where firstName = :firstName")
void deleteUsersByFirstName(@Param("firstName") String firstName);

2nd one JPA Query by method

List<User> deleteByLastname(String lastname);

When you go with query by method (2nd way) it will first do a get call

select * from user where last_name = :firstName

Then it will load it in a List Then it will call delete id one by one

delete from user where id = 18
delete from user where id = 19

First fetch list of object, then for loop to delete id one by one

But, the 1st option (custom query),

It's just a single query It will delete wherever the value exists.

Go through this link too https://www.baeldung.com/spring-data-jpa-deleteby

How to use switch statement inside a React component?

I was not absolutely happy with any of the answers. But I have picked up some ideas from @Matt Way.

Here is my solution:

Definitions:

const Switch = props => {
    const { test, children = null } = props;
    return children && children.find(child => child && child.props && child.props.casevalue === test) || null;
}

const Case = ({ casevalue = false, children = null }) => <div casevalue={`${casevalue}`}>{children}</div>;

Case.propTypes = {
    casevalue: PropTypes.string.isRequired,
    children: PropTypes.node.isRequired,
}

const Default = ({ children }) => children || <h1>NO_RESULT</h1>;

const SwitchCase = ({ test, cases = [], defaultValue = null }) => {

    const defaultVal = defaultValue
        && React.cloneElement(defaultValue, { key: 'default-key', casevalue: `${test}` })
        || <Default key='default-key' casevalue={`${test}`} />;

    return (
        <Switch test={`${test}`} >
            {
                cases.map((cas, i) => {
                    const { props = {} } = cas || {};
                    const { casevalue = false, ...rest } = props || {};

                    return <Case key={`case-key-${i}`} casevalue={`${casevalue}`}>{ React.cloneElement(cas, rest)}</Case>
                })
                .concat(defaultVal)
            }
        </Switch>
    );
}

Usage:

<SwitchCase
  cases={[
    <div casevalue={`${false}`}>#1</div>,
    <div casevalue={`${true}`}>#2</div>,
    <div casevalue={`${false}`}>#3</div>,
  ]}
  defaultValue={<h1>...nothing to see here</h1>} // You can leave it blank.
  test={`${true}`}
/>

Oracle: not a valid month

1.

To_Date(To_Char(MaxDate, 'DD/MM/YYYY')) = REP_DATE

is causing the issue. when you use to_date without the time format, oracle will use the current sessions NLS format to convert, which in your case might not be "DD/MM/YYYY". Check this...

SQL> select sysdate from dual;

SYSDATE
---------
26-SEP-12

Which means my session's setting is DD-Mon-YY

SQL> select to_char(sysdate,'MM/DD/YYYY') from dual;

TO_CHAR(SY
----------
09/26/2012


SQL> select to_date(to_char(sysdate,'MM/DD/YYYY')) from dual;
select to_date(to_char(sysdate,'MM/DD/YYYY')) from dual
               *
ERROR at line 1:
ORA-01843: not a valid month

SQL> select to_date(to_char(sysdate,'MM/DD/YYYY'),'MM/DD/YYYY') from dual;

TO_DATE(T
---------
26-SEP-12

2.

More importantly, Why are you converting to char and then to date, instead of directly comparing

MaxDate = REP_DATE

If you want to ignore the time component in MaxDate before comparision, you should use..

trunc(MaxDate ) = rep_date

instead.

==Update : based on updated question.

Rep_Date = 01/04/2009 Rep_Time = 01/01/1753 13:00:00

I think the problem is more complex. if rep_time is intended to be only time, then you cannot store it in the database as a date. It would have to be a string or date to time interval or numerically as seconds (thanks to Alex, see this) . If possible, I would suggest using one column rep_date that has both the date and time and compare it to the max date column directly.

If it is a running system and you have no control over repdate, you could try this.

trunc(rep_date) = trunc(maxdate) and 
to_char(rep_date,'HH24:MI:SS') = to_char(maxdate,'HH24:MI:SS')

Either way, the time is being stored incorrectly (as you can tell from the year 1753) and there could be other issues going forward.

How can I use the python HTMLParser library to extract data from a specific div tag?

Little correction at Line 3

HTMLParser.HTMLParser.__init__(self)

it should be

HTMLParser.__init__(self)

The following worked for me though

import urllib2 

from HTMLParser import HTMLParser  

class MyHTMLParser(HTMLParser):

  def __init__(self):
    HTMLParser.__init__(self)
    self.recording = 0 
    self.data = []
  def handle_starttag(self, tag, attrs):
    if tag == 'required_tag':
      for name, value in attrs:
        if name == 'somename' and value == 'somevale':
          print name, value
          print "Encountered the beginning of a %s tag" % tag 
          self.recording = 1 


  def handle_endtag(self, tag):
    if tag == 'required_tag':
      self.recording -=1 
      print "Encountered the end of a %s tag" % tag 

  def handle_data(self, data):
    if self.recording:
      self.data.append(data)

 p = MyHTMLParser()
 f = urllib2.urlopen('http://www.someurl.com')
 html = f.read()
 p.feed(html)
 print p.data
 p.close()

`

How to find difference between two Joda-Time DateTimes in minutes

Something like...

Minutes.minutesBetween(getStart(), getEnd()).getMinutes();

Run cmd commands through Java

Stopping and Disabling a service can be done via below code:

static void sdService() {
    String[] cmd = {"cmd.exe", "/c", "net", "stop", "MSSQLSERVER"};
    try {           
        Process process = new ProcessBuilder(cmd).start();
        process.waitFor();      
        String line = null;
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        while((line = bufferedReader.readLine()) != null) {
            System.out.println(line);
        }
                            
        line = null;
        bufferedReader = null;
        Process p = Runtime.getRuntime().exec("sc config MSSQLSERVER start= disabled");
        p.waitFor();
        bufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
        while((line = bufferedReader.readLine()) != null) {
            System.out.println(line);
        }                   
    } catch (Exception e) {
        e.printStackTrace();
    }                   
}

Enabling and Starting a service can be done via below code

static void esService() {
    String[] cmd = {"cmd.exe", "/c", "net", "start", "MSSQLSERVER"};
                    
    try {
        Process p = Runtime.getRuntime().exec("sc config MSSQLSERVER start= auto");
        //Process p = Runtime.getRuntime().exec("sc config MSSQLSERVER start= demand");
        p.waitFor();        
        String line = null;
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
        while((line = bufferedReader.readLine()) != null) {
            System.out.println(line);
        }
                            
        line = null;
        bufferedReader = null;
        Process process = new ProcessBuilder(cmd).start();          
        process.waitFor();
        bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        while((line = bufferedReader.readLine()) != null) {
            System.out.println(line);
        }
                        
    } catch (Exception e) {
        e.printStackTrace();
    }               
}

Executing command from any folder can be done via below code.

static void runFromSpecificFolder() {       
    try {
        ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe", "/c", "cd \"C:\\Users\\himan\\Desktop\\Java_Test_Deployment\\jarfiles\" && dir");
        //processBuilder.directory(new File("C://Users//himan//Desktop//Java_Test_Deployment//jarfiles"));
        processBuilder.redirectErrorStream(true);
        Process p = processBuilder.start();
        p.waitFor();        
        String line = null;
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
        while((line = bufferedReader.readLine()) != null) {
            System.out.println(line);
        }                
    } catch (Exception e) {
        e.printStackTrace();
    }               
}
    
public static void main(String args[]) {
    sdService();
    runFromSpecificFolder();
    esService();
}

Transactions in .net

You could also wrap the transaction up into it's own stored procedure and handle it that way instead of doing transactions in C# itself.

How can I pass selected row to commandLink inside dataTable or ui:repeat?

As to the cause, the <f:attribute> is specific to the component itself (populated during view build time), not to the iterated row (populated during view render time).

There are several ways to achieve the requirement.

  1. If your servletcontainer supports a minimum of Servlet 3.0 / EL 2.2, then just pass it as an argument of action/listener method of UICommand component or AjaxBehavior tag. E.g.

     <h:commandLink action="#{bean.insert(item.id)}" value="insert" />
    

    In combination with:

     public void insert(Long id) {
         // ...
     }
    

    This only requires that the datamodel is preserved for the form submit request. Best is to put the bean in the view scope by @ViewScoped.

    You can even pass the entire item object:

     <h:commandLink action="#{bean.insert(item)}" value="insert" />
    

    with:

     public void insert(Item item) {
         // ...
     }
    

    On Servlet 2.5 containers, this is also possible if you supply an EL implementation which supports this, like as JBoss EL. For configuration detail, see this answer.


  2. Use <f:param> in UICommand component. It adds a request parameter.

     <h:commandLink action="#{bean.insert}" value="insert">
         <f:param name="id" value="#{item.id}" />
     </h:commandLink>
    

    If your bean is request scoped, let JSF set it by @ManagedProperty

     @ManagedProperty(value="#{param.id}")
     private Long id; // +setter
    

    Or if your bean has a broader scope or if you want more fine grained validation/conversion, use <f:viewParam> on the target view, see also f:viewParam vs @ManagedProperty:

     <f:viewParam name="id" value="#{bean.id}" required="true" />
    

    Either way, this has the advantage that the datamodel doesn't necessarily need to be preserved for the form submit (for the case that your bean is request scoped).


  3. Use <f:setPropertyActionListener> in UICommand component. The advantage is that this removes the need for accessing the request parameter map when the bean has a broader scope than the request scope.

     <h:commandLink action="#{bean.insert}" value="insert">
         <f:setPropertyActionListener target="#{bean.id}" value="#{item.id}" />
     </h:commandLink>
    

    In combination with

     private Long id; // +setter
    

    It'll be just available by property id in action method. This only requires that the datamodel is preserved for the form submit request. Best is to put the bean in the view scope by @ViewScoped.


  4. Bind the datatable value to DataModel<E> instead which in turn wraps the items.

     <h:dataTable value="#{bean.model}" var="item">
    

    with

     private transient DataModel<Item> model;
    
     public DataModel<Item> getModel() {
         if (model == null) {
             model = new ListDataModel<Item>(items);
         }
         return model;
     }
    

    (making it transient and lazily instantiating it in the getter is mandatory when you're using this on a view or session scoped bean since DataModel doesn't implement Serializable)

    Then you'll be able to access the current row by DataModel#getRowData() without passing anything around (JSF determines the row based on the request parameter name of the clicked command link/button).

     public void insert() {
         Item item = model.getRowData();
         Long id = item.getId();
         // ...
     }
    

    This also requires that the datamodel is preserved for the form submit request. Best is to put the bean in the view scope by @ViewScoped.


  5. Use Application#evaluateExpressionGet() to programmatically evaluate the current #{item}.

     public void insert() {
         FacesContext context = FacesContext.getCurrentInstance();
         Item item = context.getApplication().evaluateExpressionGet(context, "#{item}", Item.class);
         Long id = item.getId();
         // ...
     }
    

Which way to choose depends on the functional requirements and whether the one or the other offers more advantages for other purposes. I personally would go ahead with #1 or, when you'd like to support servlet 2.5 containers as well, with #2.

Auto start node.js server on boot

Here is another solution I wrote in C# to auto startup native node server or pm2 server on Windows.

Use curly braces to initialize a Set in Python

Compare also the difference between {} and set() with a single word argument.

>>> a = set('aardvark')
>>> a
{'d', 'v', 'a', 'r', 'k'} 
>>> b = {'aardvark'}
>>> b
{'aardvark'}

but both a and b are sets of course.

Meaning of end='' in the statement print("\t",end='')?

The default value of end is \n meaning that after the print statement it will print a new line. So simply stated end is what you want to be printed after the print statement has been executed

Eg: - print ("hello",end=" +") will print hello +

How do I get the month and day with leading 0's in SQL? (e.g. 9 => 09)

select right('0000' + cast(datepart(year, GETDATE()) as varchar(4)), 4) + '-'+ + right('00' + cast(datepart(month, GETDATE()) as varchar(2)), 2) + '-'+ + right('00' + cast(datepart(day, getdate()) as varchar(2)), 2) as YearMonthDay

HTML 5 video recording and storing a stream

RecordRTC: WebRTC audio/video recording

https://github.com/muaz-khan/WebRTC-Experiment/tree/master/RecordRTC

  • Audio recording both for Chrome and Firefox
  • Video/Gif recording for Chrome; (Firefox has a little bit issues, will be recovered soon)

Demo : https://www.webrtc-experiment.com/RecordRTC/


Creating .webm video from getUserMedia()

http://ericbidelman.tumblr.com/post/31486670538/creating-webm-video-from-getusermedia

Demo : http://html5-demos.appspot.com/static/getusermedia/record-user-webm.html


Capturing Audio & Video in HTML5

http://www.html5rocks.com/en/tutorials/getusermedia/intro/

Send form data with jquery ajax json

here is a simple one

here is my test.php for testing only

<?php

// this is just a test
//send back to the ajax request the request

echo json_encode($_POST);

here is my index.html

<!DOCTYPE html>
<html>

<head>

</head>
<body>

<form id="form" action="" method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="email"><br>
FavColor: <input type="text" name="favc"><br>
<input id="submit" type="button" name="submit" value="submit">
</form>




<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
    $(document).ready(function(){
        // click on button submit
        $("#submit").on('click', function(){
            // send ajax
            $.ajax({
                url: 'test.php', // url where to submit the request
                type : "POST", // type of action POST || GET
                dataType : 'json', // data type
                data : $("#form").serialize(), // post data || get data
                success : function(result) {
                    // you can see the result from the console
                    // tab of the developer tools
                    console.log(result);
                },
                error: function(xhr, resp, text) {
                    console.log(xhr, resp, text);
                }
            })
        });
    });

</script>
</body>
</html>

Both file are place in the same directory

How to extract elements from a list using indices in Python?

Perhaps use this:

[a[i] for i in (1,2,5)]
# [11, 12, 15]

Best way to add Gradle support to IntelliJ Project

Just as a future reference, if you already have a Maven project all you need to do is doing a gradle init in your project directory which will generates build.gradle and other dependencies, then do a gradle build in the same directory.

SQL select * from column where year = 2010

its just simple

  select * from myTable where year(columnX) = 2010

SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified

We got the same issue recently. We found out that the code is looking for the connection string named "LocalSqlServer" in the machine.confg file. We added this line and it is working fine.

How to fix IndexError: invalid index to scalar variable

You are trying to index into a scalar (non-iterable) value:

[y[1] for y in y_test]
#  ^ this is the problem

When you call [y for y in test] you are iterating over the values already, so you get a single value in y.

Your code is the same as trying to do the following:

y_test = [1, 2, 3]
y = y_test[0] # y = 1
print(y[0]) # this line will fail

I'm not sure what you're trying to get into your results array, but you need to get rid of [y[1] for y in y_test].

If you want to append each y in y_test to results, you'll need to expand your list comprehension out further to something like this:

[results.append(..., y) for y in y_test]

Or just use a for loop:

for y in y_test:
    results.append(..., y)

JavaScript override methods

the method modify() that you called in the last is called in global context if you want to override modify() you first have to inherit A or B.

Maybe you're trying to do this:

In this case C inherits A

function A() {
    this.modify = function() {
        alert("in A");
    }
}

function B() {
    this.modify = function() {
        alert("in B");
    }
}

C = function() {
    this.modify = function() {
        alert("in C");
    };

    C.prototype.modify(); // you can call this method where you need to call modify of the parent class
}

C.prototype = new A();

How to import local packages without gopath

Perhaps you're trying to modularize your package. I'm assuming that package1 and package2 are, in a way, part of the same package but for readability you're splitting those into multiple files.

If the previous case was yours, you could use the same package name into those multiples files and it will be like if there were the same file.

This is an example:

add.go

package math

func add(n1, n2 int) int {
   return n1 + n2
}

subtract.go

package math

func subtract(n1, n2 int) int {
    return n1 - n2
}

donothing.go

package math

func donothing(n1, n2 int) int {
    s := add(n1, n2)
    s = subtract(n1, n2)
    return s
}

I am not a Go expert and this is my first post in StackOveflow, so if you have some advice it will be well received.

Getting scroll bar width using JavaScript

This function should give you width of scrollbar

function getScrollbarWidth() {

  // Creating invisible container
  const outer = document.createElement('div');
  outer.style.visibility = 'hidden';
  outer.style.overflow = 'scroll'; // forcing scrollbar to appear
  outer.style.msOverflowStyle = 'scrollbar'; // needed for WinJS apps
  document.body.appendChild(outer);

  // Creating inner element and placing it in the container
  const inner = document.createElement('div');
  outer.appendChild(inner);

  // Calculating difference between container's full width and the child width
  const scrollbarWidth = (outer.offsetWidth - inner.offsetWidth);

  // Removing temporary elements from the DOM
  outer.parentNode.removeChild(outer);

  return scrollbarWidth;

}

Basic steps here are:

  1. Create hidden div (outer) and get it's offset width
  2. Force scroll bars to appear in div (outer) using CSS overflow property
  3. Create new div (inner) and append to outer, set its width to '100%' and get offset width
  4. Calculate scrollbar width based on gathered offsets

Working example here: http://jsfiddle.net/slavafomin/tsrmgcu9/

Update

If you're using this on a Windows (metro) App, make sure you set the -ms-overflow-style property of the 'outer' div to scrollbar, otherwise the width will not be correctly detected. (code updated)

Update #2 This will not work on Mac OS with the default "Only show scrollbars when scrolling" setting (Yosemite and up).

Bootstrap 3 Navbar with Logo

You must use code as this:

<div class="navbar-header">
    <button type="button" class="navbar-toggle" data-toggle="collapse" 
            data-target=".navbar-ex1-collapse">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
    </button>
    <a class="logo" rel="home" href="#" title="Buy Sell Rent Everyting">
        <img style=""
             src="/img/transparent-white-logo.png">
    </a>
</div>

Class of A tag must be "logo" not navbar-brand.

Apache is downloading php files instead of displaying them

I had similar symptoms, yet another solution: in /etc/apache2/mods-enabled/php5.conf there was a helpful advice in the comment, which I followed:

# To re-enable php in user directories comment the following lines
# (from <IfModule ...> to </IfModule>.) Do NOT set it to On as it
# prevents .htaccess files from disabling it.

How do I add my new User Control to the Toolbox or a new Winform?

One user control can't be applied to it ownself. So open another winform and the one will appear in the toolbox.

Abort trap 6 error in C

You are writing to memory you do not own:

int board[2][50]; //make an array with 3 columns  (wrong)
                  //(actually makes an array with only two 'columns')
...
for (i=0; i<num3+1; i++)
    board[2][i] = 'O';
          ^

Change this line:

int board[2][50]; //array with 2 columns (legal indices [0-1][0-49])
          ^

To:

int board[3][50]; //array with 3 columns (legal indices [0-2][0-49])
          ^

When creating an array, the value used to initialize: [3] indicates array size.
However, when accessing existing array elements, index values are zero based.

For an array created: int board[3][50];
Legal indices are board[0][0]...board[2][49]

EDIT To address bad output comment and initialization comment

add an additional "\n" for formatting output:

Change:

  ...
  for (k=0; k<50;k++) {
     printf("%d",board[j][k]);
  }
 }

       ...

To:

  ...
  for (k=0; k<50;k++) {
     printf("%d",board[j][k]);
  }
  printf("\n");//at the end of every row, print a new line
}
...  

Initialize board variable:

int board[3][50] = {0};//initialize all elements to zero

( array initialization discussion... )

Bold & Non-Bold Text In A Single UILabel?

No need for NSRange with the following code I just implemented in my project (in Swift):

//Code sets label (yourLabel)'s text to "Tap and hold(BOLD) button to start recording."
let boldAttribute = [
  //You can add as many attributes as you want here.
  NSFontAttributeName: UIFont(name: "HelveticaNeue-Bold", size: 18.0)!
]
        
let regularAttribute = [NSFontAttributeName: UIFont(name: "HelveticaNeue-Light", size: 18.0)!]
        
let beginningAttributedString = NSAttributedString(string: "Tap and ", attributes: regularAttribute )
let boldAttributedString = NSAttributedString(string: "hold ", attributes: boldAttribute)
let endAttributedString = NSAttributedString(string: "button to start recording.", attributes: regularAttribute )
let fullString =  NSMutableAttributedString()
        
fullString.appendAttributedString(beginningAttributedString)
fullString.appendAttributedString(boldAttributedString)
fullString.appendAttributedString(endAttributedString)

yourLabel.attributedText = fullString

Import Excel Spreadsheet Data to an EXISTING sql table?

If you would like a software tool to do this, you might like to check out this step-by-step guide:

"How to Validate and Import Excel spreadsheet to SQL Server database"

http://leansoftware.net/forum/en-us/help/excel-database-tasks/worked-examples/how-to-import-excel-spreadsheet-to-sql-server-data.aspx

Add views in UIStackView programmatically

Stack views use intrinsic content size, so use layout constraints to define the dimensions of the views.

There is an easy way to add constraints quickly (example):

[view1.heightAnchor constraintEqualToConstant:100].active = true;

Complete Code:

- (void) setup {

    //View 1
    UIView *view1 = [[UIView alloc] init];
    view1.backgroundColor = [UIColor blueColor];
    [view1.heightAnchor constraintEqualToConstant:100].active = true;
    [view1.widthAnchor constraintEqualToConstant:120].active = true;


    //View 2
    UIView *view2 = [[UIView alloc] init];
    view2.backgroundColor = [UIColor greenColor];
    [view2.heightAnchor constraintEqualToConstant:100].active = true;
    [view2.widthAnchor constraintEqualToConstant:70].active = true;

    //View 3
    UIView *view3 = [[UIView alloc] init];
    view3.backgroundColor = [UIColor magentaColor];
    [view3.heightAnchor constraintEqualToConstant:100].active = true;
    [view3.widthAnchor constraintEqualToConstant:180].active = true;

    //Stack View
    UIStackView *stackView = [[UIStackView alloc] init];

    stackView.axis = UILayoutConstraintAxisVertical;
    stackView.distribution = UIStackViewDistributionEqualSpacing;
    stackView.alignment = UIStackViewAlignmentCenter;
    stackView.spacing = 30;


    [stackView addArrangedSubview:view1];
    [stackView addArrangedSubview:view2];
    [stackView addArrangedSubview:view3];

    stackView.translatesAutoresizingMaskIntoConstraints = false;
    [self.view addSubview:stackView];


    //Layout for Stack View
    [stackView.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor].active = true;
    [stackView.centerYAnchor constraintEqualToAnchor:self.view.centerYAnchor].active = true;
}

Note: This was tested on iOS 9

UIStackView Equal Spacing (centered)

Exception is never thrown in body of corresponding try statement

As pointed out in the comments, you cannot catch an exception that's not thrown by the code within your try block. Try changing your code to:

try{
    Integer.parseInt(args[i-1]); // this only throws a NumberFormatException
}
catch(NumberFormatException e){
    throw new MojException("Bledne dane");
}

Always check the documentation to see what exceptions are thrown by each method. You may also wish to read up on the subject of checked vs unchecked exceptions before that causes you any confusion in the future.

What is a LAMP stack?

There are various technological stacks present. Have a look:

LAMP:

Linux
Apache
MySQL
PHP

WAMP:

Windows
Apache
MySQL
PHP

MAMP:

Mac operating system
Apache web server
MySQL as database
PHP for scripting

XAMPP:

X is cross-platform
Apache
MySQL
PHP
Perl

MEAN:

MongoDB
Express.js
Angular
Node.js

MERN:

MongoDB
Express.js
React
Node.js

Get index of element as child relative to parent

Take a look at this example.

$("#wizard li").click(function () {
    alert($(this).index()); // alert index of li relative to ul parent
});

MySQL: Selecting multiple fields into multiple variables in a stored procedure

Alternatively to Martin's answer, you could also add the INTO part at the end of the query to make the query more readable:

SELECT Id, dateCreated FROM products INTO iId, dCreate

Spring MVC Missing URI template variable

@PathVariable is used to tell Spring that part of the URI path is a value you want passed to your method. Is this what you want, or are the variables supposed to be form data posted to the URI?

If you want form data, use @RequestParam instead of @PathVariable.

If you want @PathVariable, you need to specify placeholders in the @RequestMapping entry to tell Spring where the path variables fit in the URI. For example, if you want to extract a path variable called contentId, you would use:

@RequestMapping(value = "/whatever/{contentId}", method = RequestMethod.POST)

Edit: Additionally, if your path variable could contain a '.' and you want that part of the data, then you will need to tell Spring to grab everything, not just the stuff before the '.':

@RequestMapping(value = "/whatever/{contentId:.*}", method = RequestMethod.POST)

This is because the default behaviour of Spring is to treat that part of the URL as if it is a file extension, and excludes it from variable extraction.

How to create a label inside an <input> element?

If you're using HTML5, you can use the placeholder attribute.

<input type="text" name="user" placeholder="Username">

Ruby Array find_first object?

Guess you just missed the find method in the docs:

my_array.find {|e| e.satisfies_condition? }

How to escape a JSON string containing newline characters using JavaScript?

I used the built in jQuery.serialize() to extract the value from a textarea to urlencode the input. The pro part is that you don't have to search replace every special char on your own and i also keep the newlines and escapes html. For serialize to work it seems the input field needs to have a name attribute though and it also adds same attribute to the escaped string which needs to be replaced away. Might not be what you are looking for but it works for me.

var myinputfield = jQuery("#myinputfield"); 
var text = myinputfield.serialize();
text = text.replace(myinputfield.attr('name') + '=','');

Ruby String to Date Conversion

str = "Tue, 10 Aug 2010 01:20:19 -0400 (EDT)"
str.to_date
=> Tue, 10 Aug 2010

How to uninstall jupyter

If you don't want to use pip-autoremove (since it removes dependencies shared among other packages) and pip3 uninstall jupyter just removed some packages, then do the following:

Copy-Paste:

sudo may be needed as per your need.

python3 -m pip uninstall -y jupyter jupyter_core jupyter-client jupyter-console jupyterlab_pygments notebook qtconsole nbconvert nbformat

Note:

The above command will only uninstall jupyter specific packages. I have not added other packages to uninstall since they might be shared among other packages (eg: Jinja2 is used by Flask, ipython is a separate set of packages themselves, tornado again might be used by others).

In any case, all the dependencies are mentioned below(as of 21 Nov, 2020. jupyter==4.4.0 )

If you are sure you want to remove all the dependencies, then you can use Stan_MD's answer.

attrs
backcall
bleach
decorator
defusedxml
entrypoints
importlib-metadata
ipykernel
ipython
ipython-genutils
ipywidgets
jedi
Jinja2
jsonschema
jupyter
jupyter-client
jupyter-console
jupyter-core
jupyterlab-pygments
MarkupSafe
mistune
more-itertools
nbconvert
nbformat
notebook
pandocfilters
parso
pexpect
pickleshare
prometheus-client
prompt-toolkit
ptyprocess
Pygments
pyrsistent
python-dateutil
pyzmq
qtconsole
Send2Trash
six
terminado
testpath
tornado
traitlets
wcwidth
webencodings
widgetsnbextension
zipp

Executive Edit:

pip3 uninstall jupyter
pip3 uninstall jupyter_core
pip3 uninstall jupyter-client
pip3 uninstall jupyter-console
pip3 uninstall jupyterlab_pygments
pip3 uninstall notebook
pip3 uninstall qtconsole
pip3 uninstall nbconvert
pip3 uninstall nbformat

Explanation of each:

  1. Uninstall jupyter dist-packages:

    pip3 uninstall jupyter

  2. Uninstall jupyter_core dist-packages (It also uninstalls following binaries: jupyter, jupyter-migrate,jupyter-troubleshoot):

    pip3 uninstall jupyter_core

  3. Uninstall jupyter-client:

    pip3 uninstall jupyter-client

  4. Uninstall jupyter-console:

    pip3 uninstall jupyter-console

  5. Uninstall jupyter-notebook (It also uninstalls following binaries: jupyter-bundlerextension, jupyter-nbextension, jupyter-notebook, jupyter-serverextension):

    pip3 uninstall notebook

  6. Uninstall jupyter-qtconsole :

    pip3 uninstall qtconsole

  7. Uninstall jupyter-nbconvert:

    pip3 uninstall nbconvert

  8. Uninstall jupyter-trust:

    pip3 uninstall nbformat

Using Composer's Autoload

The composer documentation states that:

After adding the autoload field, you have to re-run install to re-generate the vendor/autoload.php file.

Assuming your "src" dir resides at the same level as "vendor" dir:

  • src
    • AppName
  • vendor
  • composer.json

the following config is absolutely correct:

{
    "autoload": {
        "psr-0": {"AppName": "src/"}
    }
}

but you must re-update/install dependencies to make it work for you, i.e. run:

php composer.phar update

This command will get the latest versions of the dependencies and update the file "vendor/composer/autoload_namespaces.php" to match your configuration.

Also as noted by @Dom, you can use composer dump-autoload to update the autoloader without having to go through an update.

Android Split string

String s = "String="

String[] str = s.split("="); //now str[0] is "hello" and str[1] is "goodmorning,2,1"

add this string

Checkout multiple git repos into same Jenkins workspace

Checking out more than one repo at a time in a single workspace is possible with Jenkins + Git Plugin (maybe only in more recent versions?).

In section "Source-Code-Management", do not select "Git", but "Multiple SCMs" and add several git repositories.

Be sure that in all but one you add as an "Additional behavior" the action "Check out to a sub-directory" and specify an individual subdirectory.

convert json ipython notebook(.ipynb) to .py file

In short: This command-line option converts mynotebook.ipynb to python code:

jupyter nbconvert mynotebook.ipynb --to python

note: this is different from above answer. ipython has been renamed to jupyter. the old executable name (ipython) is deprecated.


More details: jupyter command-line has an nbconvert argument which helps convert notebook files (*.ipynb) to various other formats.

You could even convert it to any one of these formats using the same command but different --to option:

  • asciidoc
  • custom
  • html
  • latex. (Awesome if you want to paste code in conference/journal papers).
  • markdown
  • notebook
  • pdf
  • python
  • rst
  • script
  • slides. (Whooh! Convert to slides for easy presentation )

the same command jupyter nbconvert --to latex mynotebook.ipynb

For more see jupyter nbconvert --help. There are extensive options to this. You could even to execute the code first before converting, different log-level options etc.

How to write Unicode characters to the console?

Console.OutputEncoding Property

https://docs.microsoft.com/en-us/dotnet/api/system.console.outputencoding

Note that successfully displaying Unicode characters to the console requires the following:

  • The console must use a TrueType font, such as Lucida Console or Consolas, to display characters.

Reload activity in Android

After login I had the same problem so I used

@Override
protected void onRestart() {
    this.recreate();
    super.onRestart();
}

Finding the source code for built-in Python functions?

The iPython shell makes this easy: function? will give you the documentation. function?? shows also the code. BUT this only works for pure python functions.

Then you can always download the source code for the (c)Python.

If you're interested in pythonic implementations of core functionality have a look at PyPy source.

multiple axis in matplotlib with different scales

Bootstrapping something fast to chart multiple y-axes sharing an x-axis using @joe-kington's answer: enter image description here

# d = Pandas Dataframe, 
# ys = [ [cols in the same y], [cols in the same y], [cols in the same y], .. ] 
def chart(d,ys):

    from itertools import cycle
    fig, ax = plt.subplots()

    axes = [ax]
    for y in ys[1:]:
        # Twin the x-axis twice to make independent y-axes.
        axes.append(ax.twinx())

    extra_ys =  len(axes[2:])

    # Make some space on the right side for the extra y-axes.
    if extra_ys>0:
        temp = 0.85
        if extra_ys<=2:
            temp = 0.75
        elif extra_ys<=4:
            temp = 0.6
        if extra_ys>5:
            print 'you are being ridiculous'
        fig.subplots_adjust(right=temp)
        right_additive = (0.98-temp)/float(extra_ys)
    # Move the last y-axis spine over to the right by x% of the width of the axes
    i = 1.
    for ax in axes[2:]:
        ax.spines['right'].set_position(('axes', 1.+right_additive*i))
        ax.set_frame_on(True)
        ax.patch.set_visible(False)
        ax.yaxis.set_major_formatter(matplotlib.ticker.OldScalarFormatter())
        i +=1.
    # To make the border of the right-most axis visible, we need to turn the frame
    # on. This hides the other plots, however, so we need to turn its fill off.

    cols = []
    lines = []
    line_styles = cycle(['-','-','-', '--', '-.', ':', '.', ',', 'o', 'v', '^', '<', '>',
               '1', '2', '3', '4', 's', 'p', '*', 'h', 'H', '+', 'x', 'D', 'd', '|', '_'])
    colors = cycle(matplotlib.rcParams['axes.color_cycle'])
    for ax,y in zip(axes,ys):
        ls=line_styles.next()
        if len(y)==1:
            col = y[0]
            cols.append(col)
            color = colors.next()
            lines.append(ax.plot(d[col],linestyle =ls,label = col,color=color))
            ax.set_ylabel(col,color=color)
            #ax.tick_params(axis='y', colors=color)
            ax.spines['right'].set_color(color)
        else:
            for col in y:
                color = colors.next()
                lines.append(ax.plot(d[col],linestyle =ls,label = col,color=color))
                cols.append(col)
            ax.set_ylabel(', '.join(y))
            #ax.tick_params(axis='y')
    axes[0].set_xlabel(d.index.name)
    lns = lines[0]
    for l in lines[1:]:
        lns +=l
    labs = [l.get_label() for l in lns]
    axes[0].legend(lns, labs, loc=0)

    plt.show()

How to declare variable and use it in the same Oracle SQL script?

In PL/SQL v.10

keyword declare is used to declare variable

DECLARE stupidvar varchar(20);

to assign a value you can set it when you declare

DECLARE stupidvar varchar(20) := '12345678';

or to select something into that variable you use INTO statement, however you need to wrap statement in BEGIN and END, also you need to make sure that only single value is returned, and don't forget semicolons.

so the full statement would come out following:

DECLARE stupidvar varchar(20);
BEGIN
    SELECT stupid into stupidvar FROM stupiddata CC 
    WHERE stupidid = 2;
END;

Your variable is only usable within BEGIN and END so if you want to use more than one you will have to do multiple BEGIN END wrappings

DECLARE stupidvar varchar(20);
BEGIN
    SELECT stupid into stupidvar FROM stupiddata CC 
    WHERE stupidid = 2;

    DECLARE evenmorestupidvar varchar(20);
    BEGIN
        SELECT evenmorestupid into evenmorestupidvar FROM evenmorestupiddata CCC 
        WHERE evenmorestupidid = 42;

        INSERT INTO newstupiddata (newstupidcolumn, newevenmorestupidstupidcolumn)
        SELECT stupidvar, evenmorestupidvar 
        FROM dual

    END;
END;

Hope this saves you some time

How To Get The Current Year Using Vba

Try =Year(Now()) and format the cell as General.

In HTML5, should the main navigation be inside or outside the <header> element?

To expand on what @JoshuaMaddox said, in the MDN Learning Area, under the "Introduction to HTML" section, the Document and website structure sub-section says (bold/emphasis is by me):

Header

Usually a big strip across the top with a big heading and/or logo. This is where the main common information about a website usually stays from one webpage to another.

Navigation bar

Links to the site's main sections; usually represented by menu buttons, links, or tabs. Like the header, this content usually remains consistent from one webpage to another — having an inconsistent navigation on your website will just lead to confused, frustrated users. Many web designers consider the navigation bar to be part of the header rather than a individual component, but that's not a requirement; in fact some also argue that having the two separate is better for accessibility, as screen readers can read the two features better if they are separate.

Android 5.0 - Add header/footer to a RecyclerView

I haven't tried this, but I would simply add 1 (or 2, if you want both a header and footer) to the integer returned by getItemCount in your adapter. You can then override getItemViewType in your adapter to return a different integer when i==0: https://developer.android.com/reference/android/support/v7/widget/RecyclerView.Adapter.html#getItemViewType(int)

createViewHolder is then passed the integer you returned from getItemViewType, allowing you to create or configure the view holder differently for the header view: https://developer.android.com/reference/android/support/v7/widget/RecyclerView.Adapter.html#createViewHolder(android.view.ViewGroup, int)

Don't forget to subtract one from the position integer passed to bindViewHolder.

Where can I find a list of keyboard keycodes?

I know this was asked awhile back, but I found a comprehensive list of the virtual keyboard key codes right in MSDN, for use in C/C++. This also includes the mouse events. Note it is different than the javascript key codes (I noticed it around the VK_OEM section).

Here's the link:
http://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx

jQuery not working with IE 11

The problem was caused because the page was an intranet site, & IE had compatibility mode set to default for this. IE11 does support addEventListener()

QuotaExceededError: Dom exception 22: An attempt was made to add something to storage that exceeded the quota

In April 2017 a patch was merged into Safari, so it aligned with the other browsers. This was released with Safari 11.

https://bugs.webkit.org/show_bug.cgi?id=157010

Why there is no ConcurrentHashSet against ConcurrentHashMap

It looks like Java provides a concurrent Set implementation with its ConcurrentSkipListSet. A SkipList Set is just a special kind of set implementation. It still implements the Serializable, Cloneable, Iterable, Collection, NavigableSet, Set, SortedSet interfaces. This might work for you if you only need the Set interface.

Maven Installation OSX Error Unsupported major.minor version 51.0

I solved it putting a old version of maven (2.x), using brew:

brew uninstall maven
brew tap homebrew/versions 
brew install maven2

How to connect to LocalDb

I think you hit the same issue as discussed in this post. You forgot to escape your \ character.

Change Bootstrap tooltip color

my jQuery fix:

HTML:

   <a href="#" data-toggle="tooltip" data-placement="right" data-original-title="some text">
       <span class="glyphicon glyphicon-question-sign"></span>
   </a>

jQuery:

$('[data-toggle="tooltip"]').hover(function(){
    $('.tooltip-inner').css('min-width', '400px');
    $('.tooltip-inner').css('color', 'red');
});

How do I do an OR filter in a Django query?

Similar to older answers, but a bit simpler, without the lambda:

filter_kwargs = {
    'field_a': 123,
    'field_b__in': (3, 4, 5, ),
}

To filter these two conditions using OR:

Item.objects.filter(Q(field_a=123) | Q(field_b__in=(3, 4, 5, ))

To get the same result programmatically:

list_of_Q = [Q(**{key: val}) for key, val in filter_kwargs.items()]
Item.objects.filter(reduce(operator.or_, list_of_Q))

(broken in two lines here, for clarity)

operator is in standard library: import operator
From docstring:

or_(a, b) -- Same as a | b.

For Python3, reduce is not a builtin any more but is still in the standard library: from functools import reduce


P.S.

Don't forget to make sure list_of_Q is not empty - reduce() will choke on empty list, it needs at least one element.

Matplotlib - Move X-Axis label downwards, but not X-Axis Ticks

If the variable ax.xaxis._autolabelpos = True, matplotlib sets the label position in function _update_label_position in axis.py according to (some excerpts):

    bboxes, bboxes2 = self._get_tick_bboxes(ticks_to_draw, renderer)
    bbox = mtransforms.Bbox.union(bboxes)
    bottom = bbox.y0
    x, y = self.label.get_position()
    self.label.set_position((x, bottom - self.labelpad * self.figure.dpi / 72.0))

You can set the label position independently of the ticks by using:

    ax.xaxis.set_label_coords(x0, y0)

that sets _autolabelpos to False or as mentioned above by changing the labelpad parameter.

Why specify @charset "UTF-8"; in your CSS file?

One reason to always include a character set specification on every page containing text is to avoid cross site scripting vulnerabilities. In most cases the UTF-8 character set is the best choice for text, including HTML pages.

Maximum request length exceeded.

There's an element in web.config to configure the max size of the uploaded file:

<httpRuntime 
    maxRequestLength="1048576"
  />

Problems with local variable scope. How to solve it?

Firstly, we just CAN'T make the variable final as its state may be changing during the run of the program and our decisions within the inner class override may depend on its current state.

Secondly, good object-oriented programming practice suggests using only variables/constants that are vital to the class definition as class members. This means that if the variable we are referencing within the anonymous inner class override is just a utility variable, then it should not be listed amongst the class members.

But – as of Java 8 – we have a third option, described here :

https://docs.oracle.com/javase/tutorial/java/javaOO/localclasses.html

Starting in Java SE 8, if you declare the local class in a method, it can access the method's parameters.

So now we can simply put the code containing the new inner class & its method override into a private method whose parameters include the variable we call from inside the override. This static method is then called after the btnInsert declaration statement :-

 . . . .
 . . . .

 Statement statement = null;                                 

 . . . .
 . . . .

 Button btnInsert = new Button(shell, SWT.NONE);
 addMouseListener(Button btnInsert, Statement statement);    // Call new private method

 . . . 
 . . .
 . . . 

 private static void addMouseListener(Button btn, Statement st) // New private method giving access to statement 
 {
    btn.addMouseListener(new MouseAdapter() 
    {
      @Override
      public void mouseDown(MouseEvent e) 
      {
        String name = text.getText();
        String from = text_1.getText();
        String to = text_2.getText();
        String price = text_3.getText();
        String query = "INSERT INTO booking (name, fromst, tost,price) VALUES ('"+name+"', '"+from+"', '"+to+"', '"+price+"')";
        try 
        {
            st.executeUpdate(query);
        } 
        catch (SQLException e1) 
        {
            e1.printStackTrace();                                    // TODO Auto-generated catch block
        }
    }
  });
  return;
}

 . . . .
 . . . .
 . . . .

How do I pass options to the Selenium Chrome driver using Python?

Found the chrome Options class in the Selenium source code.

Usage to create a Chrome driver instance:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("--disable-extensions")
driver = webdriver.Chrome(chrome_options=chrome_options)

How to get cookie expiration date / creation date from javascript?

It's impossible. document.cookie contains information in string like this:

key1=value1;key2=value2;...

So there isn't any information about dates.

You can store these dates in separate cookie variable:

auth_user=Riateche;auth_expire=01/01/2012

But user can change this variable.

Identifying and removing null characters in UNIX

I faced the same error with:

import codecs as cd
f=cd.open(filePath,'r','ISO-8859-1')

I solved the problem by changing the encoding to utf-16

f=cd.open(filePath,'r','utf-16')

Run bash script from Windows PowerShell

If you add the extension .SH to the environment variable PATHEXT, you will be able to run shell scripts from PowerShell by only using the script name with arguments:

PS> .\script.sh args

If you store your scripts in a directory that is included in your PATH environment variable, you can run it from anywhere, and omit the extension and path:

PS> script args

Note: sh.exe or another *nix shell must be associated with the .sh extension.

How do I get column names to print in this C# program?

foreach (DataRow row in dt.Rows)
{
    foreach (DataColumn column in dt.Columns)
    {
        ColumnName = column.ColumnName;
        ColumnData = row[column].ToString();
    }
}

Keyboard shortcut for Jump to Previous View Location (Navigate back/forward) in IntelliJ IDEA

Many excellent answers so far, and they do answer the question...But, if you don't want to have to deal with disabling graphics driver's settings, or creating new keyboard mappings, or are developing through a remote session (RDP) or within a VM that intercepts your keystrokes, good-old keyboard navigation still works. Just do Alt-N to bring up the Navigate menu and then hit the B key.

Please note that you don't hit all keys at the same time. So:

Alt-N wait B

This is what I use all the time, for exactly the case that the OP asked about. Also, this will probably hold through any IntelliJ updates.

How to split a string to 2 strings in C

For purposes such as this, I tend to use strtok_r() instead of strtok().

For example ...

int main (void) {
char str[128];
char *ptr;

strcpy (str, "123456 789asdf");
strtok_r (str, " ", &ptr);

printf ("'%s'  '%s'\n", str, ptr);
return 0;
}

This will output ...

'123456' '789asdf'

If more delimiters are needed, then loop.

Hope this helps.

Difference between checkout and export in SVN

Any chance the build process is looking into the subdirectories and including something it shouldn't? BTW, you can do a legal checkout, then remove the .svn and all it contains. That should give you the same as an export. Try compiling that, before and after removing the metadata, as it were.

How to make Firefox headless programmatically in Selenium with Python?

The first answer does't work anymore.

This worked for me:

from selenium.webdriver.firefox.options import Options as FirefoxOptions
from selenium import webdriver

options = FirefoxOptions()
options.add_argument("--headless")
driver = webdriver.Firefox(options=options)
driver.get("http://google.com")

How to make div same height as parent (displayed as table-cell)

You can use this CSS:

.content {
    height: 100%;
    display: inline-table;
    background-color: blue;
}

JSFiddle

How to call a stored procedure (with parameters) from another stored procedure without temp table

You can call Stored Procedure like this inside Stored Procedure B.

CREATE PROCEDURE spA
@myDate DATETIME
AS
    EXEC spB @myDate

RETURN 0

Hashing a string with Sha256

This work for me in .NET Core 3.1.
But not in .NET 5 preview 7.

using System;
using System.Security.Cryptography;
using System.Text;

namespace PortalAplicaciones.Shared.Models
{
    public class Encriptar
    {
        public static string EncriptaPassWord(string Password)
        {
            try
            {
                SHA256Managed hasher = new SHA256Managed();

                byte[] pwdBytes = new UTF8Encoding().GetBytes(Password);
                byte[] keyBytes = hasher.ComputeHash(pwdBytes);

                hasher.Dispose();
                return Convert.ToBase64String(keyBytes);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex);
            }
        }  
    }
}
 

How do I change the ID of a HTML element with JavaScript?

You can modify the id without having to use getElementById

Example:

<div id = 'One' onclick = "One.id = 'Two'; return false;">One</div>

You can see it here: http://jsbin.com/elikaj/1/

Tested with Mozilla Firefox 22 and Google Chrome 60.0

How to multi-line "Replace in files..." in Notepad++

The workaround is

  1. search and replace \r\n to thisismynewlineword

(this will remove all the new lines and there should be whole one line)

  1. now perform your replacements

  2. search and replace thisismynewlineword to \r\n

(to undo the step 1)

To enable extensions, verify that they are enabled in those .ini files - Vagrant/Ubuntu/Magento 2.0.2

First installed

sudo apt-get install php5-gd

then

sudo apt-get install php5-intl

and last one was

sudo apt-get install php5-xsl

After that, it is installing as it should.

How to select last one week data from today's date

Yes, the syntax is accurate and it should be fine.

Here is the SQL Fiddle Demo I created for your particular case

create table sample2
(
    id int primary key,
    created_date date,
    data varchar(10)
  )

insert into sample2 values (1,'2012-01-01','testing');

And here is how to select the data

SELECT Created_Date
FROM sample2
WHERE Created_Date >= DATEADD(day,-11117, GETDATE())

Loop inside React JSX

return (
    <table>
       <tbody>
          {
            numrows.map((item, index) => {
              <ObjectRow data={item} key={index}>
            })
          }
       </tbody>
    </table>
);

Clone only one branch

From the announcement Git 1.7.10 (April 2012):

  • git clone learned --single-branch option to limit cloning to a single branch (surprise!); tags that do not point into the history of the branch are not fetched.

Git actually allows you to clone only one branch, for example:

git clone -b mybranch --single-branch git://sub.domain.com/repo.git

Note: Also you can add another single branch or "undo" this action.

how to convert a string date into datetime format in python?

The particular format for strptime:

datetime.datetime.strptime(string_date, "%Y-%m-%d %H:%M:%S.%f")
#>>> datetime.datetime(2013, 9, 28, 20, 30, 55, 782000)

How does the ARM architecture differ from x86?

Neither has anything specific to keyboard or mobile, other than the fact that for years ARM has had a pretty substantial advantage in terms of power consumption, which made it attractive for all sorts of battery operated devices.

As far as the actual differences: ARM has more registers, supported predication for most instructions long before Intel added it, and has long incorporated all sorts of techniques (call them "tricks", if you prefer) to save power almost everywhere it could.

There's also a considerable difference in how the two encode instructions. Intel uses a fairly complex variable-length encoding in which an instruction can occupy anywhere from 1 up to 15 byte. This allows programs to be quite small, but makes instruction decoding relatively difficult (as in: decoding instructions fast in parallel is more like a complete nightmare).

ARM has two different instruction encoding modes: ARM and THUMB. In ARM mode, you get access to all instructions, and the encoding is extremely simple and fast to decode. Unfortunately, ARM mode code tends to be fairly large, so it's fairly common for a program to occupy around twice as much memory as Intel code would. Thumb mode attempts to mitigate that. It still uses quite a regular instruction encoding, but reduces most instructions from 32 bits to 16 bits, such as by reducing the number of registers, eliminating predication from most instructions, and reducing the range of branches. At least in my experience, this still doesn't usually give quite as dense of coding as x86 code can get, but it's fairly close, and decoding is still fairly simple and straightforward. Lower code density means you generally need at least a little more memory and (generally more seriously) a larger cache to get equivalent performance.

At one time Intel put a lot more emphasis on speed than power consumption. They started emphasizing power consumption primarily on the context of laptops. For laptops their typical power goal was on the order of 6 watts for a fairly small laptop. More recently (much more recently) they've started to target mobile devices (phones, tablets, etc.) For this market, they're looking at a couple of watts or so at most. They seem to be doing pretty well at that, though their approach has been substantially different from ARM's, emphasizing fabrication technology where ARM has mostly emphasized micro-architecture (not surprising, considering that ARM sells designs, and leaves fabrication to others).

Depending on the situation, a CPU's energy consumption is often more important than its power consumption though. At least as I'm using the terms, power consumption refers to power usage on a (more or less) instantaneous basis. Energy consumption, however, normalizes for speed, so if (for example) CPU A consumes 1 watt for 2 seconds to do a job, and CPU B consumes 2 watts for 1 second to do the same job, both CPUs consume the same total amount of energy (two watt seconds) to do that job--but with CPU B, you get results twice as fast.

ARM processors tend to do very well in terms of power consumption. So if you need something that needs a processor's "presence" almost constantly, but isn't really doing much work, they can work out pretty well. For example, if you're doing video conferencing, you gather a few milliseconds of data, compress it, send it, receive data from others, decompress it, play it back, and repeat. Even a really fast processor can't spend much time sleeping, so for tasks like this, ARM does really well.

Intel's processors (especially their Atom processors, which are actually intended for low power applications) are extremely competitive in terms of energy consumption. While they're running close to their full speed, they will consume more power than most ARM processors--but they also finish work quickly, so they can go back to sleep sooner. As a result, they can combine good battery life with good performance.

So, when comparing the two, you have to be careful about what you measure, to be sure that it reflects what you honestly care about. ARM does very well at power consumption, but depending on the situation you may easily care more about energy consumption than instantaneous power consumption.

What is the meaning of {...this.props} in Reactjs

It's called spread attributes and its aim is to make the passing of props easier.

Let us imagine that you have a component that accepts N number of properties. Passing these down can be tedious and unwieldy if the number grows.

<Component x={} y={} z={} />

Thus instead you do this, wrap them up in an object and use the spread notation

var props = { x: 1, y: 1, z:1 };
<Component {...props} />

which will unpack it into the props on your component, i.e., you "never" use {... props} inside your render() function, only when you pass the props down to another component. Use your unpacked props as normal this.props.x.

c# search string in txt file

If your pair of lines will only appear once in your file, you could use

File.ReadLines(pathToTextFile)
    .SkipWhile(line => !line.Contains("CustomerEN"))
    .Skip(1) // optional
    .TakeWhile(line => !line.Contains("CustomerCh"));

If you could have multiple occurrences in one file, you're probably better off using a regular foreach loop - reading lines, keeping track of whether you're currently inside or outside a customer etc:

List<List<string>> groups = new List<List<string>>();
List<string> current = null;
foreach (var line in File.ReadAllLines(pathToFile))
{
    if (line.Contains("CustomerEN") && current == null)
        current = new List<string>();
    else if (line.Contains("CustomerCh") && current != null)
    {
        groups.Add(current);
        current = null;
    }
    if (current != null)
        current.Add(line);
}

Template not provided using create-react-app

If you are getting this error 'Template not provided ...." again and again, then straigt away do the followiong to steps:

  1. npm uninstall -g create-react-app
  2. check the location of your file 'create-react-app' by using the command "which create-react-app"
  3. Now manually delete that file using the command "rm -rf /usr/local/bin/create-react-app" replacing this command with the exact path shown in the previous step.
  4. Finally run 'npx create-react-app '

This will replace your old file 'create-react-app' which is causing the problem with the new file downloaded with npx.

Happy coding...

Python, how to check if a result set is empty?

I had issues with rowcount always returning -1 no matter what solution I tried.

I found the following a good replacement to check for a null result.

c.execute("SELECT * FROM users WHERE id=?", (id_num,))
row = c.fetchone()
if row == None:
   print("There are no results for this query")

how do I set height of container DIV to 100% of window height?

Did you set the CSS:

html, body
{
    height: 100%;
}

You need this to be able to make the div take up all the space. :)

Polling the keyboard (detect a keypress) in python

From the comments:

import msvcrt # built-in module

def kbfunc():
    return ord(msvcrt.getch()) if msvcrt.kbhit() else 0

Thanks for the help. I ended up writing a C DLL called PyKeyboardAccess.dll and accessing the crt conio functions, exporting this routine:

#include <conio.h>

int kb_inkey () {
   int rc;
   int key;

   key = _kbhit();

   if (key == 0) {
      rc = 0;
   } else {
      rc = _getch();
   }

   return rc;
}

And I access it in python using the ctypes module (built into python 2.5):

import ctypes
import time

#
# first, load the DLL
#


try:
    kblib = ctypes.CDLL("PyKeyboardAccess.dll")
except:
    raise ("Error Loading PyKeyboardAccess.dll")


#
# now, find our function
#

try:
    kbfunc = kblib.kb_inkey
except:
    raise ("Could not find the kb_inkey function in the dll!")


#
# Ok, now let's demo the capability
#

while 1:
    x = kbfunc()

    if x != 0:
        print "Got key: %d" % x
    else:
        time.sleep(.01)

What does git rev-parse do?

git rev-parse Also works for getting the current branch name using the --abbrev-ref flag like:

git rev-parse --abbrev-ref HEAD

Assign one struct to another in C

Did you mean "Complex" as in complex number with real and imaginary parts? This seems unlikely, so if not you'd have to give an example since "complex" means nothing specific in terms of the C language.

You will get a direct memory copy of the structure; whether that is what you want depends on the structure. For example if the structure contains a pointer, both copies will point to the same data. This may or may not be what you want; that is down to your program design.

To perform a 'smart' copy (or a 'deep' copy), you will need to implement a function to perform the copy. This can be very difficult to achieve if the structure itself contains pointers and structures that also contain pointers, and perhaps pointers to such structures (perhaps that's what you mean by "complex"), and it is hard to maintain. The simple solution is to use C++ and implement copy constructors and assignment operators for each structure or class, then each one becomes responsible for its own copy semantics, you can use assignment syntax, and it is more easily maintained.

Flutter- wrapping text

You Can Wrap your widget with Flexible Widget and than you can set property of Text using overflow property of Text Widget. you have to set TextOverflow.clip for example:-

Flexible
(child: new Text("This is Dummy Long Text",
 style: TextStyle(
 fontFamily: "Roboto",
 color: Colors.black,
 fontSize: 10.0,
 fontWeight: FontWeight.bold),
 overflow: TextOverflow.clip,),)

hope this help someone :)

APK signing error : Failed to read key from keystore

The big thing is either the alias or the other password is wrong. Kindly check your passwords and your issue is solved. Incase you have forgotten password, you can recover it from the androidStuido3.0/System/Log ... Search for the keyword password and their you are saved

How to add a classname/id to React-Bootstrap Component?

1st way is to use props

<Row id = "someRandomID">

Wherein, in the Definition, you may just go

const Row = props  => {
 div id = {props.id}
}

The same could be done with class, replacing id with className in the above example.


You might as well use react-html-id, that is an npm package. This is an npm package that allows you to use unique html IDs for components without any dependencies on other libraries.

Ref: react-html-id


Peace.

Angular and debounce

Solution with initialization subscriber directly in event function:

import {Subject} from 'rxjs';
import {debounceTime, distinctUntilChanged} from 'rxjs/operators';

class MyAppComponent {
    searchTermChanged: Subject<string> = new Subject<string>();

    constructor() {
    }

    onFind(event: any) {
        if (this.searchTermChanged.observers.length === 0) {
            this.searchTermChanged.pipe(debounceTime(1000), distinctUntilChanged())
                .subscribe(term => {
                    // your code here
                    console.log(term);
                });
        }
        this.searchTermChanged.next(event);
    }
}

And html:

<input type="text" (input)="onFind($event.target.value)">

How do I clear/delete the current line in terminal?

Just to summarise all the answers:

  • Clean up the line: You can use Ctrl+U to clear up to the beginning.
  • Clean up the line: Ctrl+E Ctrl+U to wipe the current line in the terminal
  • Clean up the line: Ctrl+A Ctrl+K to wipe the current line in the terminal
  • Cancel the current command/line: Ctrl+C.
  • Recall the deleted command: Ctrl+Y (then Alt+Y)
  • Go to beginning of the line: Ctrl+A
  • Go to end of the line: Ctrl+E
  • Remove the forward words for example, if you are middle of the command: Ctrl+K
  • Remove characters on the left, until the beginning of the word: Ctrl+W
  • To clear your entire command prompt: Ctrl + L
  • Toggle between the start of line and current cursor position: Ctrl + XX

"The breakpoint will not currently be hit. The source code is different from the original version." What does this mean?

Closing Visual Studio and reopening the solution can fix the problem, i.e. it's a bug within the IDE itself (I'm running VS2010).

If you have more than one instances of Visual Studio running, you only need to close the instance running the solution with the problem.

Showing empty view when ListView is empty

I highly recommend you to use ViewStubs like this

<FrameLayout
    android:layout_width="fill_parent"
    android:layout_height="0dp"
    android:layout_weight="1" >

    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

    <ViewStub
        android:id="@android:id/empty"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout="@layout/empty" />
</FrameLayout>

See the full example from Cyril Mottier

How to debug Apache mod_rewrite

Based on Ben's answer you you could do the following when running apache on Linux (Debian in my case).

First create the file rewrite-log.load

/etc/apache2/mods-availabe/rewrite-log.load

RewriteLog "/var/log/apache2/rewrite.log"
RewriteLogLevel 3

Then enter

$ a2enmod rewrite-log

followed by

$ service apache2 restart

And when you finished with debuging your rewrite rules

$ a2dismod rewrite-log && service apache2 restart

$rootScope.$broadcast vs. $scope.$emit

I made the following graphic out of the following link: https://toddmotto.com/all-about-angulars-emit-broadcast-on-publish-subscribing/

Scope, rootScope, emit, broadcast

As you can see, $rootScope.$broadcast hits a lot more listeners than $scope.$emit.

Also, $scope.$emit's bubbling effect can be cancelled, whereas $rootScope.$broadcast cannot.

Array of Matrices in MATLAB

Use cell arrays. This has an advantage over 3D arrays in that it does not require a contiguous memory space to store all the matrices. In fact, each matrix can be stored in a different space in memory, which will save you from Out-of-Memory errors if your free memory is fragmented. Here is a sample function to create your matrices in a cell array:

function result = createArrays(nArrays, arraySize)
    result = cell(1, nArrays);
    for i = 1 : nArrays
        result{i} = zeros(arraySize);
    end
end

To use it:

myArray = createArrays(requiredNumberOfArrays, [500 800]);

And to access your elements:

myArray{1}(2,3) = 10;

If you can't know the number of matrices in advance, you could simply use MATLAB's dynamic indexing to make the array as large as you need. The performance overhead will be proportional to the size of the cell array, and is not affected by the size of the matrices themselves. For example:

myArray{1} = zeros(500, 800);
if twoRequired, myArray{2} = zeros(500, 800); end

SQL Error: ORA-01861: literal does not match format string 01861

Try the format as dd-mon-yyyy, For example 02-08-2016 should be in the format '08-feb-2016'.

How does @synchronized lock/unlock in Objective-C?

Actually

{
  @synchronized(self) {
    return [[myString retain] autorelease];
  }
}

transforms directly into:

// needs #import <objc/objc-sync.h>
{
  objc_sync_enter(self)
    id retVal = [[myString retain] autorelease];
  objc_sync_exit(self);
  return retVal;
}

This API available since iOS 2.0 and imported using...

#import <objc/objc-sync.h>

Deserializing JSON to .NET object using Newtonsoft (or LINQ to JSON maybe?)

With the dynamic keyword, it becomes really easy to parse any object of this kind:

dynamic x = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonString);
var page = x.page;
var total_pages = x.total_pages
var albums = x.albums;
foreach(var album in albums)
{
    var albumName = album.name;

    // Access album data;
}

Django template how to look up a dictionary value with a variable

Since I can't comment, let me do this in the form of an answer:
to build on culebrón's answer or Yuji 'Tomita' Tomita's answer, the dictionary passed into the function is in the form of a string, so perhaps use ast.literal_eval to convert the string to a dictionary first, like in this example.

With this edit, the code should look like this:

# code for custom template tag
@register.filter(name='lookup')
def lookup(value, arg):
    value_dict = ast.literal_eval(value)
    return value_dict.get(arg)

<!--template tag (in the template)-->
{{ mydict|lookup:item.name }}

Cannot access a disposed object - How to fix?

Another place you could stop the timer is the FormClosing event - this happens before the form is actually closed, so is a good place to stop things before they might access unavailable resources.

Combine two tables that have no common fields

SELECT *
FROM table1, table2

This will join every row in table1 with table2 (the Cartesian product) returning all columns.

Most simple code to populate JTable from ResultSet

Well I'm sure that this is the simplest way to populate JTable from ResultSet, without any external library. I have included comments in this method.

public void resultSetToTableModel(ResultSet rs, JTable table) throws SQLException{
        //Create new table model
        DefaultTableModel tableModel = new DefaultTableModel();

        //Retrieve meta data from ResultSet
        ResultSetMetaData metaData = rs.getMetaData();

        //Get number of columns from meta data
        int columnCount = metaData.getColumnCount();

        //Get all column names from meta data and add columns to table model
        for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++){
            tableModel.addColumn(metaData.getColumnLabel(columnIndex));
        }

        //Create array of Objects with size of column count from meta data
        Object[] row = new Object[columnCount];

        //Scroll through result set
        while (rs.next()){
            //Get object from column with specific index of result set to array of objects
            for (int i = 0; i < columnCount; i++){
                row[i] = rs.getObject(i+1);
            }
            //Now add row to table model with that array of objects as an argument
            tableModel.addRow(row);
        }

        //Now add that table model to your table and you are done :D
        table.setModel(tableModel);
    }

Java method to swap primitives

It depends on what you want to do. This code swaps two elements of an array.

void swap(int i, int j, int[] arr) {
  int t = arr[i];
  arr[i] = arr[j];
  arr[j] = t;
}

Something like this swaps the content of two int[] of equal length.

void swap(int[] arr1, int[] arr2) {
  int[] t = arr1.clone();
  System.arraycopy(arr2, 0, arr1, 0, t.length);
  System.arraycopy(t, 0, arr2, 0, t.length);
}

Something like this swaps the content of two BitSet (using the XOR swap algorithm):

void swap(BitSet s1, BitSet s2) {
  s1.xor(s2);
  s2.xor(s1);
  s1.xor(s2);
}

Something like this swaps the x and y fields of some Point class:

void swapXY(Point p) {
  int t = p.x;
  p.x = p.y;
  p.y = t;
}

Launch Android application without main Activity and start Service on launching application

Android Studio Version 2.3

You can create a Service without a Main Activity by following a few easy steps. You'll be able to install this app through Android Studio and debug it like a normal app.

First, create a project in Android Studio without an activity. Then create your Service class and add the service to your AndroidManifest.xml

<application android:allowBackup="true"
    android:label="@string/app_name"
    android:icon="@mipmap/ic_launcher"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <service android:name="com.whatever.myservice.MyService">
        <intent-filter>
            <action android:name="com.whatever.myservice.MyService" />
        </intent-filter>
    </service>
</application>

Now, in the drop down next to the "Run" button(green arrow), go to "edit configurations" and within the "Launch Options" choose "Nothing". This will allow you to install your Service without Android Studio complaining about not having a Main Activity.

Once installed, the service will NOT be running but you will be able to start it with this adb shell command...

am startservice -n com.whatever.myservice/.MyService

Can check it's running with...

ps | grep whatever

I haven't tried yet but you can likely have Android Studio automatically start the service too. This would be done in that "Edit Configurations" menu.

'dict' object has no attribute 'has_key'

has_key was removed in Python 3. From the documentation:

  • Removed dict.has_key() – use the in operator instead.

Here's an example:

if start not in graph:
    return None

How to prevent downloading images and video files from my website?

This is an old post, but for video you might want to consider using MPEG-DASH to obfuscate your files. Plus, it will provide a better streaming experience for your users without the need for a separate streaming server. More info in this post: How to disable video/audio downloading in web pages?

Using logging in multiple modules

Best practice is, in each module, to have a logger defined like this:

import logging
logger = logging.getLogger(__name__)

near the top of the module, and then in other code in the module do e.g.

logger.debug('My message with %s', 'variable data')

If you need to subdivide logging activity inside a module, use e.g.

loggerA = logging.getLogger(__name__ + '.A')
loggerB = logging.getLogger(__name__ + '.B')

and log to loggerA and loggerB as appropriate.

In your main program or programs, do e.g.:

def main():
    "your program code"

if __name__ == '__main__':
    import logging.config
    logging.config.fileConfig('/path/to/logging.conf')
    main()

or

def main():
    import logging.config
    logging.config.fileConfig('/path/to/logging.conf')
    # your program code

if __name__ == '__main__':
    main()

See here for logging from multiple modules, and here for logging configuration for code which will be used as a library module by other code.

Update: When calling fileConfig(), you may want to specify disable_existing_loggers=False if you're using Python 2.6 or later (see the docs for more information). The default value is True for backward compatibility, which causes all existing loggers to be disabled by fileConfig() unless they or their ancestor are explicitly named in the configuration. With the value set to False, existing loggers are left alone. If using Python 2.7/Python 3.2 or later, you may wish to consider the dictConfig() API which is better than fileConfig() as it gives more control over the configuration.

Firefox and SSL: sec_error_unknown_issuer

If you got your cert from COMODO your need to add this line, the file is on the zip file you received.

SSLCertificateChainFile /path/COMODORSADomainValidationSecureServerCA.crt

How to make method call another one in classes?

Because the Method2 is static, all you have to do is call like this:

public class AllMethods
{
    public static void Method2()
    {
        // code here
    }
}

class Caller
{
    public static void Main(string[] args)
    {
        AllMethods.Method2();
    }
}

If they are in different namespaces you will also need to add the namespace of AllMethods to caller.cs in a using statement.

If you wanted to call an instance method (non-static), you'd need an instance of the class to call the method on. For example:

public class MyClass
{
    public void InstanceMethod() 
    { 
        // ...
    }
}

public static void Main(string[] args)
{
    var instance = new MyClass();
    instance.InstanceMethod();
}

Update

As of C# 6, you can now also achieve this with using static directive to call static methods somewhat more gracefully, for example:

// AllMethods.cs
namespace Some.Namespace
{
    public class AllMethods
    {
        public static void Method2()
        {
            // code here
        }
    }
}

// Caller.cs
using static Some.Namespace.AllMethods;

namespace Other.Namespace
{
    class Caller
    {
        public static void Main(string[] args)
        {
            Method2(); // No need to mention AllMethods here
        }
    }
}

Further Reading

bash "if [ false ];" returns true instead of false -- why?

You are running the [ (aka test) command with the argument "false", not running the command false. Since "false" is a non-empty string, the test command always succeeds. To actually run the command, drop the [ command.

if false; then
   echo "True"
else
   echo "False"
fi

How to target the href to div

Try this code in jquery

$(document).ready(function(){
  $("a").click(function(){
  var id=$(this).attr('href');
  var value=$(id).text();
  $(".target").text(value);
  });
});

Capture iOS Simulator video for App Preview

You should use QuickTime in Yosemite to connect and record the screen of your iOS devices.

iPhone Portrait

When you finished the recording, you can use iMovie to edit the video. When you're working on an iPhone Portrait App Preview, the resolution must be 1080x1920 but iMovie can only export in 16:9 (1920x1080).

One solution would be to imported the recorded video with the resolution 1080x1920 and rotate it 90 degree. Then export the movie at 1920x1080 and rotate the exported video back 90 degrees using ffmpeg and the following command

ffmpeg -i Landscape.mp4 -vf "transpose=1" Portrait.mp4

iPad

The iPad is a little bit trickier because it requires a resolution of 1200x900 (4:3) but iMovie only exports in 16:9.

Here is what I've done.

  1. Record the movie on iPad Air in Landscape (1200x900, 4:3)
  2. Import into iMovie and export as 1920x1080, 16:9 (iPadLandscape16_9-1920x1080.mp4)
  3. Remove left and right black bars to a video with 1440x1080. The width of one bar is 240

    ffmpeg -i iPadLandscape16_9-1920x1080.mp4 -filter:v "crop=1440:1080:240:0" -c:a copy iPadLandscape4_3-1440x1080.mp4
    
  4. Scale down movie to 1220x900

    ffmpeg -i iPadLandscape4_3-1440x1080.mp4 -filter:v scale=1200:-1 -c:a copy iPadLandscape4_3-1200x900.mp4
    

Taken from my answer on the Apple Developer Forum

How can I post data as form data instead of a request payload?

You can define the behavior globally:

$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";

So you don't have to redefine it every time:

$http.post("/handle/post", {
    foo: "FOO",
    bar: "BAR"
}).success(function (data, status, headers, config) {
    // TODO
}).error(function (data, status, headers, config) {
    // TODO
});

How to add new contacts in android

Here I am posting a piece of code that i use to add a new contact. It works fine for me. I hope it will help you.

 String DisplayName = "XYZ";
 String MobileNumber = "123456";
 String HomeNumber = "1111";
 String WorkNumber = "2222";
 String emailID = "[email protected]";
 String company = "bad";
 String jobTitle = "abcd";

 ArrayList < ContentProviderOperation > ops = new ArrayList < ContentProviderOperation > ();

 ops.add(ContentProviderOperation.newInsert(
 ContactsContract.RawContacts.CONTENT_URI)
     .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
     .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
     .build());

 //------------------------------------------------------ Names
 if (DisplayName != null) {
     ops.add(ContentProviderOperation.newInsert(
     ContactsContract.Data.CONTENT_URI)
         .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
         .withValue(ContactsContract.Data.MIMETYPE,
     ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
         .withValue(
     ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME,
     DisplayName).build());
 }

 //------------------------------------------------------ Mobile Number                     
 if (MobileNumber != null) {
     ops.add(ContentProviderOperation.
     newInsert(ContactsContract.Data.CONTENT_URI)
         .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
         .withValue(ContactsContract.Data.MIMETYPE,
     ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
         .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, MobileNumber)
         .withValue(ContactsContract.CommonDataKinds.Phone.TYPE,
     ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE)
         .build());
 }

 //------------------------------------------------------ Home Numbers
 if (HomeNumber != null) {
     ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
         .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
         .withValue(ContactsContract.Data.MIMETYPE,
     ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
         .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, HomeNumber)
         .withValue(ContactsContract.CommonDataKinds.Phone.TYPE,
     ContactsContract.CommonDataKinds.Phone.TYPE_HOME)
         .build());
 }

 //------------------------------------------------------ Work Numbers
 if (WorkNumber != null) {
     ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
         .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
         .withValue(ContactsContract.Data.MIMETYPE,
     ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
         .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, WorkNumber)
         .withValue(ContactsContract.CommonDataKinds.Phone.TYPE,
     ContactsContract.CommonDataKinds.Phone.TYPE_WORK)
         .build());
 }

 //------------------------------------------------------ Email
 if (emailID != null) {
     ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
         .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
         .withValue(ContactsContract.Data.MIMETYPE,
     ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
         .withValue(ContactsContract.CommonDataKinds.Email.DATA, emailID)
         .withValue(ContactsContract.CommonDataKinds.Email.TYPE, ContactsContract.CommonDataKinds.Email.TYPE_WORK)
         .build());
 }

 //------------------------------------------------------ Organization
 if (!company.equals("") && !jobTitle.equals("")) {
     ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
         .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
         .withValue(ContactsContract.Data.MIMETYPE,
     ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)
         .withValue(ContactsContract.CommonDataKinds.Organization.COMPANY, company)
         .withValue(ContactsContract.CommonDataKinds.Organization.TYPE, ContactsContract.CommonDataKinds.Organization.TYPE_WORK)
         .withValue(ContactsContract.CommonDataKinds.Organization.TITLE, jobTitle)
         .withValue(ContactsContract.CommonDataKinds.Organization.TYPE, ContactsContract.CommonDataKinds.Organization.TYPE_WORK)
         .build());
 }

 // Asking the Contact provider to create a new contact                 
 try {
     getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
 } catch (Exception e) {
     e.printStackTrace();
     Toast.makeText(myContext, "Exception: " + e.getMessage(), Toast.LENGTH_SHORT).show();
 } 

Here is the code. Integrate it according to your need. I hope it will help.

Prevent content from expanding grid items

The previous answer is pretty good, but I also wanted to mention that there is a fixed layout equivalent for grids, you just need to write minmax(0, 1fr) instead of 1fr as your track size.

Overlapping Views in Android

If you want to add you custom Overlay screen on Layout, you can create a Custom Linear Layout and get control of drawing and key events. You can my tutorial- Overlay on Android Layout- http://prasanta-paul.blogspot.com/2010/08/overlay-on-android-layout.html

Can I fade in a background image (CSS: background-image) with jQuery?

With modern browser i prefer a much lightweight approach with a bit of Js and CSS3...

transition: background 300ms ease-in 200ms;

Look at this demo:

http://codepen.io/nicolasbonnici/pen/gPVNbr

How to find the socket buffer size of linux

Whilst, as has been pointed out, it is possible to see the current default socket buffer sizes in /proc, it is also possible to check them using sysctl (Note: Whilst the name includes ipv4 these sizes also apply to ipv6 sockets - the ipv6 tcp_v6_init_sock() code just calls the ipv4 tcp_init_sock() function):

 sysctl net.ipv4.tcp_rmem
 sysctl net.ipv4.tcp_wmem

However, the default socket buffers are just set when the sock is initialised but the kernel then dynamically sizes them (unless set using setsockopt() with SO_SNDBUF). The actual size of the buffers for currently open sockets may be inspected using the ss command (part of the iproute package), which can also provide a bunch more info on sockets like congestion control parameter etc. E.g. To list the currently open TCP (t option) sockets and associated memory (m) information:

ss -tm

Here's some example output:

State       Recv-Q Send-Q        Local Address:Port        Peer Address:Port
ESTAB       0      0             192.168.56.102:ssh        192.168.56.1:56328
skmem:(r0,rb369280,t0,tb87040,f0,w0,o0,bl0,d0)

Here's a brief explanation of skmem (socket memory) - for more info you'll need to look at the kernel sources (e.g. sock.h):

r:sk_rmem_alloc
rb:sk_rcvbuf          # current receive buffer size
t:sk_wmem_alloc
tb:sk_sndbuf          # current transmit buffer size
f:sk_forward_alloc
w:sk_wmem_queued      # persistent transmit queue size
o:sk_omem_alloc
bl:sk_backlog
d:sk_drops

How to redirect in a servlet filter?

If you also want to keep hash and get parameter, you can do something like this (fill redirectMap at filter init):

String uri = request.getRequestURI();

String[] uriParts = uri.split("[#?]");
String path = uriParts[0];
String rest = uri.substring(uriParts[0].length());

if(redirectMap.containsKey(path)) {
    response.sendRedirect(redirectMap.get(path) + rest);
} else {
    chain.doFilter(request, response);
}

ansible : how to pass multiple commands

To run multiple shell commands with ansible you can use the shell module with a multi-line string (note the pipe after shell:), as shown in this example:

  - name: Build nginx 
    shell: |
      cd nginx-1.11.13
      sudo ./configure
      sudo make
      sudo make install

Difference between / and /* in servlet mapping url pattern

<url-pattern>/*</url-pattern>

The /* on a servlet overrides all other servlets, including all servlets provided by the servletcontainer such as the default servlet and the JSP servlet. Whatever request you fire, it will end up in that servlet. This is thus a bad URL pattern for servlets. Usually, you'd like to use /* on a Filter only. It is able to let the request continue to any of the servlets listening on a more specific URL pattern by calling FilterChain#doFilter().

<url-pattern>/</url-pattern>

The / doesn't override any other servlet. It only replaces the servletcontainer's builtin default servlet for all requests which doesn't match any other registered servlet. This is normally only invoked on static resources (CSS/JS/image/etc) and directory listings. The servletcontainer's builtin default servlet is also capable of dealing with HTTP cache requests, media (audio/video) streaming and file download resumes. Usually, you don't want to override the default servlet as you would otherwise have to take care of all its tasks, which is not exactly trivial (JSF utility library OmniFaces has an open source example). This is thus also a bad URL pattern for servlets. As to why JSP pages doesn't hit this servlet, it's because the servletcontainer's builtin JSP servlet will be invoked, which is already by default mapped on the more specific URL pattern *.jsp.

<url-pattern></url-pattern>

Then there's also the empty string URL pattern . This will be invoked when the context root is requested. This is different from the <welcome-file> approach that it isn't invoked when any subfolder is requested. This is most likely the URL pattern you're actually looking for in case you want a "home page servlet". I only have to admit that I'd intuitively expect the empty string URL pattern and the slash URL pattern / be defined exactly the other way round, so I can understand that a lot of starters got confused on this. But it is what it is.

Front Controller

In case you actually intend to have a front controller servlet, then you'd best map it on a more specific URL pattern like *.html, *.do, /pages/*, /app/*, etc. You can hide away the front controller URL pattern and cover static resources on a common URL pattern like /resources/*, /static/*, etc with help of a servlet filter. See also How to prevent static resources from being handled by front controller servlet which is mapped on /*. Noted should be that Spring MVC has a builtin static resource servlet, so that's why you could map its front controller on / if you configure a common URL pattern for static resources in Spring. See also How to handle static content in Spring MVC?

Making TextView scrollable on Android

For a vertically or horizontally scrollable TextView some of the other answers help, but I needed to be able to scroll both ways.

What finally worked is a ScrollView with a HorizontalScrollView inside of it, and a TextView inside the HSV. It's very smooth and can easily go side to side or top to bottom in one swipe. It also only allows scrolling in one direction at a time so there's none of the jumping side to side while scrolling up or down.

An EditText with editing and cursor disabled works, but it feels terrible. Each attempt to scroll moves the cursor and it requires many swipes to go top to bottom or side to side in even a ~100-line file.

Using setHorizontallyScrolling(true) can work, but there's no similar method to allow vertical scrolling, and it doesn't work inside of a ScrollView as far as I can tell (just learning though, could be wrong).

Redirect with CodeIgniter

If you want to redirect previous location or last request then you have to include user_agent library:

$this->load->library('user_agent');

and then use at last in a function that you are using:

redirect($this->agent->referrer());

its working for me.

Asyncio.gather vs asyncio.wait

In addition to all the previous answers, I would like to tell about the different behavior of gather() and wait() in case they are cancelled.

Gather cancellation

If gather() is cancelled, all submitted awaitables (that have not completed yet) are also cancelled.

Wait cancellation

If the wait() task is cancelled, it simply throws an CancelledError and the waited tasks remain intact.

Simple example:

import asyncio


async def task(arg):
    await asyncio.sleep(5)
    return arg


async def cancel_waiting_task(work_task, waiting_task):
    await asyncio.sleep(2)
    waiting_task.cancel()
    try:
        await waiting_task
        print("Waiting done")
    except asyncio.CancelledError:
        print("Waiting task cancelled")

    try:
        res = await work_task
        print(f"Work result: {res}")
    except asyncio.CancelledError:
        print("Work task cancelled")


async def main():
    work_task = asyncio.create_task(task("done"))
    waiting = asyncio.create_task(asyncio.wait({work_task}))
    await cancel_waiting_task(work_task, waiting)

    work_task = asyncio.create_task(task("done"))
    waiting = asyncio.gather(work_task)
    await cancel_waiting_task(work_task, waiting)


asyncio.run(main())

Output:

asyncio.wait()
Waiting task cancelled
Work result: done
----------------
asyncio.gather()
Waiting task cancelled
Work task cancelled

Sometimes it becomes necessary to combine wait() and gather() functionality. For example, we want to wait for the completion of at least one task and cancel the rest pending tasks after that, and if the waiting itself was canceled, then also cancel all pending tasks.

As real examples, let's say we have a disconnect event and a work task. And we want to wait for the results of the work task, but if the connection was lost, then cancel it. Or we will make several parallel requests, but upon completion of at least one response, cancel all others.

It could be done this way:

import asyncio
from typing import Optional, Tuple, Set


async def wait_any(
        tasks: Set[asyncio.Future], *, timeout: Optional[int] = None,
) -> Tuple[Set[asyncio.Future], Set[asyncio.Future]]:
    tasks_to_cancel: Set[asyncio.Future] = set()
    try:
        done, tasks_to_cancel = await asyncio.wait(
            tasks, timeout=timeout, return_when=asyncio.FIRST_COMPLETED
        )
        return done, tasks_to_cancel
    except asyncio.CancelledError:
        tasks_to_cancel = tasks
        raise
    finally:
        for task in tasks_to_cancel:
            task.cancel()


async def task():
    await asyncio.sleep(5)


async def cancel_waiting_task(work_task, waiting_task):
    await asyncio.sleep(2)
    waiting_task.cancel()
    try:
        await waiting_task
        print("Waiting done")
    except asyncio.CancelledError:
        print("Waiting task cancelled")

    try:
        res = await work_task
        print(f"Work result: {res}")
    except asyncio.CancelledError:
        print("Work task cancelled")


async def check_tasks(waiting_task, working_task, waiting_conn_lost_task):
    try:
        await waiting_task
        print("waiting is done")
    except asyncio.CancelledError:
        print("waiting is cancelled")

    try:
        await waiting_conn_lost_task
        print("connection is lost")
    except asyncio.CancelledError:
        print("waiting connection lost is cancelled")

    try:
        await working_task
        print("work is done")
    except asyncio.CancelledError:
        print("work is cancelled")


async def work_done_case():
    working_task = asyncio.create_task(task())
    connection_lost_event = asyncio.Event()
    waiting_conn_lost_task = asyncio.create_task(connection_lost_event.wait())
    waiting_task = asyncio.create_task(wait_any({working_task, waiting_conn_lost_task}))
    await check_tasks(waiting_task, working_task, waiting_conn_lost_task)


async def conn_lost_case():
    working_task = asyncio.create_task(task())
    connection_lost_event = asyncio.Event()
    waiting_conn_lost_task = asyncio.create_task(connection_lost_event.wait())
    waiting_task = asyncio.create_task(wait_any({working_task, waiting_conn_lost_task}))
    await asyncio.sleep(2)
    connection_lost_event.set()  # <---
    await check_tasks(waiting_task, working_task, waiting_conn_lost_task)


async def cancel_waiting_case():
    working_task = asyncio.create_task(task())
    connection_lost_event = asyncio.Event()
    waiting_conn_lost_task = asyncio.create_task(connection_lost_event.wait())
    waiting_task = asyncio.create_task(wait_any({working_task, waiting_conn_lost_task}))
    await asyncio.sleep(2)
    waiting_task.cancel()  # <---
    await check_tasks(waiting_task, working_task, waiting_conn_lost_task)


async def main():
    print("Work done")
    print("-------------------")
    await work_done_case()
    print("\nConnection lost")
    print("-------------------")
    await conn_lost_case()
    print("\nCancel waiting")
    print("-------------------")
    await cancel_waiting_case()


asyncio.run(main())

Output:

Work done
-------------------
waiting is done
waiting connection lost is cancelled
work is done

Connection lost
-------------------
waiting is done
connection is lost
work is cancelled

Cancel waiting
-------------------
waiting is cancelled
waiting connection lost is cancelled
work is cancelled

How to find my Subversion server version number?

There really isn't an easy way to find out what version of Subversion your server is running -- except to get onto the server and see for yourself.

However, this may not be as big a problem as you may think. Subversion clients is were much of the grunt work is handled, and most versions of the Subversion clients can work with almost any version of the server.

The last release where the server version really made a difference to the client was the change from release 1.4 to release 1.5 when merge tracking was added. Merge tracking had been greatly improved in version 1.6, but that doesn't really affect the interactions between the client and server.

Let's take the latest changes in Subversion 1.8:

  • svn move is now a first class operation: Subversion finally understands the svn move is not a svn copy and svn delete. However, this is something that the client handles and doesn't really affect the server version.
  • svn merge --reintegrate deprecated: Again, as long as the server is at version 1.5 or greater this isn't an issue.
  • Property Inheritance: This is another 1.8 release update, but this will work with any Subversion server -- although Subversion servers running 1.8 will deliver better performance on inheritable properties.
  • Two new inheritable properties - svn:global-ignores and svn:auto-props: Alas! What we really wanted. A way to setup these two properties without depending upon the Subversion configuration file itself. However, this is a client-only issue, so it again doesn't matter what version of the server you're using.
  • gnu-agent memory caching: Another client-only feature.
  • fsfs performance enhancements and authz in-repository authentication. Nice features, but these work no matter what version of the client you're using.

Of all the features, only one depends upon the version of the server being 1.5 or greater (and 1.4 has been obsolete for quite a while. The newer features of 1.8 will improve performance of your working copy, but the server being at revision 1.8 isn't necessary. You're much more affected by your client version than your server version.

I know this isn't the answer you wanted (no official way to see the server version), but fortunately the server version doesn't really affect you that much.

Android - default value in editText

We wish there is a default value attribute in each view of android views or group view in future versions of SDK. but to overcome that, simply before submission, check if the view is empty equal true, then assign a default value

example:

   /* add 0 as default numeric value to a price field when skipped by a user,
                    in order to avoid parsing error of empty or improper format value. */
                    if (Objects.requireNonNull(edPrice.getText()).toString().trim().isEmpty())
                    edPrice.setText("0");

UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in position 3 2: ordinal not in range(128)

I had the same problem. This work fine for me:

str(objdata).encode('utf-8')

Centering floating divs within another div

First, remove the float attribute on the inner divs. Then, put text-align: center on the main outer div. And for the inner divs, use display: inline-block. Might also be wise to give them explicit widths too.


<div style="margin: auto 1.5em; display: inline-block;">
  <img title="Nadia Bjorlin" alt="Nadia Bjorlin" src="headshot.nadia.png"/>
  <br/>
  Nadia Bjorlin
</div>

CSS: How to change colour of active navigation page menu

Add ID current for active/current page:

<div class="menuBar">
  <ul>
  <li id="current"><a href="index.php">HOME</a></li>
  <li><a href="two.php">PORTFOLIO</a></li>
  <li><a href="three.php">ABOUT</a></li>
  <li><a href="four.php">CONTACT</a></li>
  <li><a href="five.php">SHOP</a></li>
 </ul>

#current a { color: #ff0000; }

Android - implementing startForeground for a service?

Add given code Service class for "OS >= Build.VERSION_CODES.O" in onCreate()

@Override
public void onCreate(){
    super.onCreate();

     .................................
     .................................

    //For creating the Foreground Service
    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    String channelId = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ? getNotificationChannel(notificationManager) : "";
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId);
    Notification notification = notificationBuilder.setOngoing(true)
            .setSmallIcon(R.mipmap.ic_launcher)
           // .setPriority(PRIORITY_MIN)
            .setCategory(NotificationCompat.CATEGORY_SERVICE)
            .build();

    startForeground(110, notification);
}



@RequiresApi(Build.VERSION_CODES.O)
private String getNotificationChannel(NotificationManager notificationManager){
    String channelId = "channelid";
    String channelName = getResources().getString(R.string.app_name);
    NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH);
    channel.setImportance(NotificationManager.IMPORTANCE_NONE);
    channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
    notificationManager.createNotificationChannel(channel);
    return channelId;
}

Add this permission in manifest file:

 <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

How to empty a list?

You could try:

alist[:] = []

Which means: Splice in the list [] (0 elements) at the location [:] (all indexes from start to finish)

The [:] is the slice operator. See this question for more information.

how to make jni.h be found?

Installing the OpenJDK Development Kit (JDK) should fix your problem.

sudo apt-get install openjdk-X-jdk

This should make you able to compile without problems.

How to style the <option> with only CSS?

There is no cross-browser way of styling option elements, certainly not to the extent of your second screenshot. You might be able to make them bold, and set the font-size, but that will be about it...

How can I make Java print quotes, like "Hello"?

Escape double-quotes in your string: "\"Hello\""

More on the topic (check 'Escape Sequences' part)