Programs & Examples On #Qyoto

Procedure or function !!! has too many arguments specified

This answer is based on the title and not the specific case in the original post.

I had an insert procedure that kept throwing this annoying error, and even though the error says, "procedure....has too many arguments specified," the fact is that the procedure did NOT have enough arguments.

The table had an incremental id column, and since it is incremental, I did not bother to add it as a variable/argument to the proc, but it turned out that it is needed, so I added it as @Id and viola like they say...it works.

What does enumerate() mean?

As other users have mentioned, enumerate is a generator that adds an incremental index next to each item of an iterable.

So if you have a list say l = ["test_1", "test_2", "test_3"], the list(enumerate(l)) will give you something like this: [(0, 'test_1'), (1, 'test_2'), (2, 'test_3')].

Now, when this is useful? A possible use case is when you want to iterate over items, and you want to skip a specific item that you only know its index in the list but not its value (because its value is not known at the time).

for index, value in enumerate(joint_values):
   if index == 3:
       continue

   # Do something with the other `value`

So your code reads better because you could also do a regular for loop with range but then to access the items you need to index them (i.e., joint_values[i]).

Although another user mentioned an implementation of enumerate using zip, I think a more pure (but slightly more complex) way without using itertools is the following:

def enumerate(l, start=0):
    return zip(range(start, len(l) + start), l)

Example:

l = ["test_1", "test_2", "test_3"]
enumerate(l)
enumerate(l, 10)

Output:

[(0, 'test_1'), (1, 'test_2'), (2, 'test_3')]

[(10, 'test_1'), (11, 'test_2'), (12, 'test_3')]

As mentioned in the comments, this approach with range will not work with arbitrary iterables as the original enumerate function does.

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

alter table table_name modify column_name int(5)

SOAP or REST for Web Services?

Listen to this podcast to find out. If you want to know the answer without listening, then OK, its REST. But I really do recommend listening.

How do you share code between projects/solutions in Visual Studio?

Extract the common code into a class library project and add that class library project to your solutions. Then you can add a reference to the common code from other projects by adding a project reference to that class library. The advantage of having a project reference as opposed to a binary/assembly reference is that if you change your build configuration to debug, release, custom, etc, the common class library project will be built based on that configuration as well.

What are ABAP and SAP?

See http://en.wikipedia.org/wiki/SAP_AG.

In short, SAP is a modular based application that sits on top of a database (as many applications do). Many people mistake SAP as being a database, but in fact it is just the application.

By 'modular based application' I mean that 'SAP Netweaver' is a bit like 'Microsoft Office' in that it is an application or set of applications that contains many components/modules. With SAP you can add modules (such as Finance, HR, Banking, Logistics, etc.) to meet your business requirements.

ABAP is a bespoke programming language that is used within SAP. SAP also now has components that are purely ABAP based, purely JAVA based or a mixture of the two. SAP can also integrate with other technologies such as .net and PHP.

100% width table overflowing div container

From a purely "make it fit in the div" perspective, add the following to your table class (jsfiddle):

table-layout: fixed;
width: 100%;

Set your column widths as desired; otherwise, the fixed layout algorithm will distribute the table width evenly across your columns.

For quick reference, here are the table layout algorithms, emphasis mine:

  • Fixed (source)
    With this (fast) algorithm, the horizontal layout of the table does not depend on the contents of the cells; it only depends on the table's width, the width of the columns, and borders or cell spacing.
  • Automatic (source)
    In this algorithm (which generally requires no more than two passes), the table's width is given by the width of its columns [, as determined by content] (and intervening borders).

    [...] This algorithm may be inefficient since it requires the user agent to have access to all the content in the table before determining the final layout and may demand more than one pass.

Click through to the source documentation to see the specifics for each algorithm.

Determine if variable is defined in Python

For this particular case it's better to do a = None instead of del a. This will decrement reference count to object a was (if any) assigned to and won't fail when a is not defined. Note, that del statement doesn't call destructor of an object directly, but unbind it from variable. Destructor of object is called when reference count became zero.

How do I create 7-Zip archives with .NET?

I used the sdk.

eg:

using SevenZip.Compression.LZMA;
private static void CompressFileLZMA(string inFile, string outFile)
{
   SevenZip.Compression.LZMA.Encoder coder = new SevenZip.Compression.LZMA.Encoder();

   using (FileStream input = new FileStream(inFile, FileMode.Open))
   {
      using (FileStream output = new FileStream(outFile, FileMode.Create))
      {
          coder.Code(input, output, -1, -1, null);
          output.Flush();
      }
   }
}

Compare if BigDecimal is greater than zero

Possible better way:

if (value.signum() > 0)

signum returns -1, 0, or 1 as the value of this BigDecimal is negative, zero, or positive.

Difference between adjustResize and adjustPan in android?

I was also a bit confused between adjustResize and adjustPan when I was a beginner. The definitions given above are correct.
AdjustResize : Main activity's content is resized to make room for soft input i.e keyboard
AdjustPan : Instead of resizing overall contents of the window, it only pans the content so that the user can always see what is he typing
AdjustNothing : As the name suggests nothing is resized or panned. Keyboard is opened as it is irrespective of whether it is hiding the contents or not.

I have a created a example for better understanding
Below is my xml file:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:hint="Type Here"
        app:layout_constraintTop_toBottomOf="@id/button1"/>


    <Button
        android:id="@+id/button1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="Button1"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@id/button2"
        app:layout_constraintStart_toStartOf="parent"
        android:layout_marginBottom="@dimen/margin70dp"/>

    <Button
        android:id="@+id/button2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="Button2"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toEndOf="@id/button1"
        app:layout_constraintEnd_toStartOf="@id/button3"
        android:layout_marginBottom="@dimen/margin70dp"/>

    <Button
        android:id="@+id/button3"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="Button3"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@id/button2"
        android:layout_marginBottom="@dimen/margin70dp"/>
</android.support.constraint.ConstraintLayout>

Here is the design view of the xml
original view

AdjustResize Example below:
adjustResize example

AdjustPan Example below:
adjustPan example

AdjustNothing Example below:
adjustNothing example

MySQL SELECT WHERE datetime matches day (and not necessarily time)

You can use %:

SELECT * FROM datetable WHERE datecol LIKE '2012-12-25%'

Difference between a User and a Login in SQL Server

One reason to have both is so that authentication can be done by the database server, but authorization can be scoped to the database. That way, if you move your database to another server, you can always remap the user-login relationship on the database server, but your database doesn't have to change.

How do I link to part of a page? (hash?)

You use an anchor and a hash. For example:

Target of the Link:

 <a name="name_of_target">Content</a>

Link to the Target:

 <a href="#name_of_target">Link Text</a>

Or, if linking from a different page:

 <a href="http://path/to/page/#name_of_target">Link Text</a>

java.sql.SQLException: Exhausted Resultset

I've seen this error while trying to access a column value after processing the resultset.

if (rs != null) {
  while (rs.next()) {
    count = rs.getInt(1);
  }
  count = rs.getInt(1); //this will throw Exhausted resultset
}

Hope this will help you :)

How to make a simple collection view with Swift

UICollectionView is same as UITableView but it gives us the additional functionality of simply creating a grid view, which is a bit problematic in UITableView. It will be a very long post I mention a link from where you will get everything in simple steps.

jQuery - If element has class do this

First, you're missing some parentheses in your conditional:

if ($("#about").hasClass("opened")) {
  $("#about").animate({right: "-700px"}, 2000);
}

But you can also simplify this to:

$('#about.opened').animate(...);

If #about doesn't have the opened class, it won't animate.

If the problem is with the animation itself, we'd need to know more about your element positioning (absolute? absolute inside relative parent? does the parent have layout?)

XMLHttpRequest cannot load an URL with jQuery

Found a possible workaround that I don't believe was mentioned.

Here is a good description of the problem: http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

Basically as long as you use forms/url-encoded/plain text content types you are fine.

$.ajax({
    type: "POST",
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'text/plain'
    },
    dataType: "json",
    url: "http://localhost/endpoint",
    data: JSON.stringify({'DataToPost': 123}),
    success: function (data) {
        alert(JSON.stringify(data));
    }
});     

I use it with ASP.NET WebAPI2. So on the other end:

public static void RegisterWebApi(HttpConfiguration config)
{
    config.MapHttpAttributeRoutes();

    config.Formatters.Clear();
    config.Formatters.Add(new JsonMediaTypeFormatter());

    config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain"));
}

This way Json formatter gets used when parsing plain text content type.

And don't forget in Web.config:

<system.webServer>
<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Methods" value="GET, POST" />
  </customHeaders>
</httpProtocol>    

Hope this helps.

How to set button click effect in Android?

Step: set a button in XML with onClick Action:

 <Button
android:id="@+id/btnEditUserInfo"
style="?android:borderlessButtonStyle"
android:layout_width="wrap_content"
android:layout_height="@dimen/txt_height"
android:layout_gravity="center"
android:background="@drawable/round_btn"
android:contentDescription="@string/image_view"
android:onClick="edit_user_info"
android:text="Edit"
android:textColor="#000"
android:textSize="@dimen/login_textSize" />

Step: on button clicked show animation point
//pgrm mark ---- ---- ----- ---- ---- ----- ---- ---- -----  ---- ---- -----

    public void edit_user_info(View view) {

        // show click effect on button pressed
        final AlphaAnimation buttonClick = new AlphaAnimation(1F, 0.8F);
        view.startAnimation(buttonClick);

        Intent intent = new Intent(getApplicationContext(),  EditUserInfo.class);
        startActivity(intent);

    }// end edit_user_info

Creating a generic method in C#

You can use sort of Maybe monad (though I'd prefer Jay's answer)

public class Maybe<T>
{
    private readonly T _value;

    public Maybe(T value)
    {
        _value = value;
        IsNothing = false;
    }

    public Maybe()
    {
        IsNothing = true;
    }

    public bool IsNothing { get; private set; }

    public T Value
    {
        get
        {
            if (IsNothing)
            {
                throw new InvalidOperationException("Value doesn't exist");
            }
            return _value;
        }
    }

    public override bool Equals(object other)
    {
        if (IsNothing)
        {
            return (other == null);
        }
        if (other == null)
        {
            return false;
        }
        return _value.Equals(other);
    }

    public override int GetHashCode()
    {
        if (IsNothing)
        {
            return 0;
        }
        return _value.GetHashCode();
    }

    public override string ToString()
    {
        if (IsNothing)
        {
            return "";
        }
        return _value.ToString();
    }

    public static implicit operator Maybe<T>(T value)
    {
        return new Maybe<T>(value);
    }

    public static explicit operator T(Maybe<T> value)
    {
        return value.Value;
    }
}

Your method would look like:

    public static Maybe<T> GetQueryString<T>(string key) where T : IConvertible
    {
        if (String.IsNullOrEmpty(HttpContext.Current.Request.QueryString[key]) == false)
        {
            string value = HttpContext.Current.Request.QueryString[key];

            try
            {
                return (T)Convert.ChangeType(value, typeof(T));
            }
            catch
            {
                //Could not convert.  Pass back default value...
                return new Maybe<T>();
            }
        }

        return new Maybe<T>();
    }

Is it possible to see more than 65536 rows in Excel 2007?

Here is an interesting blog entry about numbers / limitations of Excel 2007. According to the author the new limit is approximately one million rows.

Sounds like you have a pre-Excel 2007 workbook open in Excel 2007 in compatibility mode (look in the title bar and see if it says compatibility mode). If so, the workbook has 65,536 rows, not 1,048,576. You can save the workbook as an Excel workbook which will be in Excel 2007 format, close the workbook and re-open it.

Unit Testing C Code

I say almost the same as ratkok but if you have a embedded twist to the unit tests then...

Unity - Highly recommended framework for unit testing C code.

#include <unity.h>

void test_true_should_be_true(void)
{
    TEST_ASSERT_TRUE(true);
}

int main(void)
{
    UNITY_BEGIN();
    RUN_TEST(test_true_should_be_true);
    return UNITY_END();
}

The examples in the book that is mentioned in this thread TDD for embedded C are written using Unity (and CppUTest).

Copy file(s) from one project to another using post build event...VS2010

I use it like this.

xcopy "$(TargetDir)$(TargetName).dll" "$(SolutionDir)Lib\TIRM\x86\" /F /Y 
xcopy "$(TargetDir)$(TargetName).lib" "$(SolutionDir)Lib\TIRM\x86\" /F /Y 


/F : Copy source is File   
/Y : Overwrite and don't ask me

Note the use of this. $(TargetDir) has already '\' "D:\MyProject\bin\" = $(TargetDir)

You can find macro in Command editor

enter image description here

How to set JAVA_HOME in Mac permanently?

To set JAVA_HOME permanently in Mac, I tried following steps.

  1. Download and install Java JDK to your Mac. When you install a Java JDK version which will be installed in the following location by default in MAC.

/Library/Java/JavaVirtualMachines

  1. Open the .bash_profile file (Here My Mac version is MacOS High Sierra. You may need to open .zshrc file in some different MacOS versions).

atom ~/.bash_profile

  1. Add following to your bash_profile file.

Change the JDK version accordingly

export JAVA_HOME="$(/usr/libexec/java_home -v 1.8)"
export JAVA_HOME='/Library/Java/JavaVirtualMachines/jdk1.8.0_271.jdk/Contents/Home'
export PATH=$JAVA_HOME/bin:$PATH
  1. Open the Terminal and execute following.

source ~/.bash_profile

Open a new terminal and check 'echo $JAVA_HOME'

Thanks.

CSS text-align: center; is not centering things

You can use flex-grow: 1. The default value is 0 and it will cause the text-align: center looks like left.

https://css-tricks.com/almanac/properties/f/flex-grow/

invalid target release: 1.7

This probably works for a lot of things but it's not enough for Maven and certainly not for the maven compiler plugin.

Check Mike's answer to his own question here: stackoverflow question 24705877

This solved the issue for me both command line AND within eclipse.

Also, @LinGao answer to stackoverflow question 2503658 and the use of the $JAVACMD variable might help but I haven't tested it myself.

How to manage Angular2 "expression has changed after it was checked" exception when a component property depends on current datetime

I got that error because I declared a variable and later wanted to
changed it's value using ngAfterViewInit

export class SomeComponent {

    header: string;

}

to fix that I switched from

ngAfterViewInit() { 

    // change variable value here...
}

to

ngAfterContentInit() {

    // change variable value here...
}

Android Spinner : Avoid onItemSelected calls during initialization

I placed a TextView on top of the Spinner, same size and background as the Spinner, so that I would have more control over what it looked like before the user clicks on it. With the TextView there, I could also use the TextView to flag when the user has started interacting.

My Kotlin code looks something like this:

private var mySpinnerHasBeenTapped = false

private fun initializeMySpinner() {

    my_hint_text_view.setOnClickListener {
        mySpinnerHasBeenTapped = true //turn flag to true
        my_spinner.performClick() //call spinner click
    }

    //Basic spinner setup stuff
    val myList = listOf("Leonardo", "Michelangelo", "Rafael", "Donatello")
    val dataAdapter: ArrayAdapter<String> = ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, myList)
    my_spinner.adapter = dataAdapter

    my_spinner.onItemSelectedListener = object : OnItemSelectedListener {

        override fun onItemSelected(parent: AdapterView<*>?, view: View, position: Int, id: Long) {

            if (mySpinnerHasBeenTapped) { //code below will only run after the user has clicked
                my_hint_text_view.visibility = View.GONE //once an item has been selected, hide the textView
                //Perform action here
            }
        }

        override fun onNothingSelected(parent: AdapterView<*>?) {
            //Do nothing
        }
    }
}

Layout file looks something like this, with the important part being that the Spinner and TextView share the same width, height, and margins:

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <Spinner
                android:id="@+id/my_spinner"
                android:layout_width="match_parent"
                android:layout_height="35dp"
                android:layout_marginStart="10dp"
                android:layout_marginEnd="10dp"
                android:background="@drawable/bg_for_spinners"

                android:paddingStart="8dp"
                android:paddingEnd="30dp"
                android:singleLine="true" />

            <TextView
                android:id="@+id/my_hint_text_view"
                android:layout_width="match_parent"
                android:layout_height="35dp"                
                android:layout_marginStart="10dp"
                android:layout_marginEnd="10dp"
                android:background="@drawable/bg_for_spinners"

                android:paddingStart="8dp"
                android:paddingEnd="30dp"
                android:singleLine="true"
                android:gravity="center_vertical"
                android:text="*Select A Turtle"
                android:textColor="@color/green_ooze"
                android:textSize="16sp" />

        </FrameLayout>

I'm sure the other solutions work where you ignore the first onItemSelected call, but I really don't like the idea of assuming it will always be called.

Handlebars.js Else If

Hello I have only a MINOR classname edit, and so far this is how iv divulged it. i think i need to pass in multpile parameters to the helper,

server.js

app.engine('handlebars', ViewEngine({
        "helpers":{
                isActive: (val, options)=>{
                    if (val === 3 || val === 0){
                        return options.fn(this)
                    }
                } 
        }
}));

header.handlebars

<ul class="navlist">
          <li   class="navitem navlink {{#isActive 0}}active{{/isActive}}"
                ><a href="#">Home</a></li>
          <li   class="navitem navlink {{#isActive 1}}active{{/isActive}}"
                ><a href="#">Trending</a></li>
          <li   class="navitem navlink {{#isActive 2}}active{{/isActive}}"
                ><a href="#">People</a></li>
          <li   class="navitem navlink {{#isActive 3}}active{{/isActive}}"
                ><a href="#">Mystery</a></li>
          <li class="navitem navbar-search">
            <input type="text" id="navbar-search-input" placeholder="Search...">
            <button type="button" id="navbar-search-button"><i class="fas fa-search"></i></button>
          </li>
        </ul>

Passive Link in Angular 2 - <a href=""> equivalent

That will be same, it doesn't have anything related to angular2. It is simple html tag.

Basically a(anchor) tag will be rendered by HTML parser.

Edit

You can disable that href by having javascript:void(0) on it so nothing will happen on it. (But its hack). I know Angular 1 provided this functionality out of the box which isn't seems correct to me now.

<a href="javascript:void(0)" >Test</a>

Plunkr


Other way around could be using, routerLink directive with passing "" value which will eventually generate blank href=""

<a routerLink="" (click)="passTheSalt()">Click me</a>

Spring Hibernate - Could not obtain transaction-synchronized Session for current thread

I encountered the same problem and finally found out that the <tx:annotaion-driven /> was not defined within the [dispatcher]-servlet.xml where component-scan element enabled @service annotated class.

Simply put <tx:annotaion-driven /> with component-scan element together, the problem disappeared.

Jenkins returned status code 128 with github

I changed the permission of my .ssh/id_rsa (private key) to 604. chmod 700 id_rsa

best OCR (Optical character recognition) example in android

Like you I also faced many problems implementing OCR in Android, but after much Googling I found the solution, and it surely is the best example of OCR.

Let me explain using step-by-step guidance.

First, download the source code from https://github.com/rmtheis/tess-two.

Import all three projects. After importing you will get an error. To solve the error you have to create a res folder in the tess-two project

enter image description here

First, just create res folder in tess-two by tess-two->RightClick->new Folder->Name it "res"

After doing this in all three project the error should be gone.

Now download the source code from https://github.com/rmtheis/android-ocr, here you will get best example.

Now you just need to import it into your workspace, but first you have to download android-ndk from this site:

http://developer.android.com/tools/sdk/ndk/index.html i have windows 7 - 32 bit PC so I have download http://dl.google.com/android/ndk/android-ndk-r9-windows-x86.zip this file

Now extract it suppose I have extract it into E:\Software\android-ndk-r9 so I will set this path on Environment Variable

Right Click on MyComputer->Property->Advance-System-Settings->Advance->Environment Variable-> find PATH on second below Box and set like path like below picture

enter image description here

done it

Now open cmd and go to on D:\Android Workspace\tess-two like below

enter image description here

If you have successfully set up environment variable of NDK then just type ndk-build just like above picture than enter you will not get any kind of error and all file will be compiled successfully:

Now download other source code also from https://github.com/rmtheis/tess-two , and extract and import it and give it name OCRTest, like in my PC which is in D:\Android Workspace\OCRTest

enter image description here

Import test-two in this and run OCRTest and run it; you will get the best example of OCR.

TempData keep() vs peek()

don't they both keep a value for another request?

Yes they do, but when the first one is void, the second one returns and object:

public void Keep(string key)
{
    _retainedKeys.Add(key); // just adds the key to the collection for retention
}

public object Peek(string key)
{
    object value;
    _data.TryGetValue(key, out value);
    return value; // returns an object without marking it for deletion
}

Auto detect mobile browser (via user-agent?)

There's a brand new solution using Zend Framework. Start from the link to Zend_HTTP_UserAgent:

http://framework.zend.com/manual/en/zend.http.html

Identify if a string is a number

You can always use the built in TryParse methods for many datatypes to see if the string in question will pass.

Example.

decimal myDec;
var Result = decimal.TryParse("123", out myDec);

Result would then = True

decimal myDec;
var Result = decimal.TryParse("abc", out myDec);

Result would then = False

How to request Location Permission at runtime

check this code from MainActivity

 // Check location permission is granted - if it is, start
// the service, otherwise request the permission
fun checkOrAskLocationPermission(callback: () -> Unit) {
    // Check GPS is enabled
    val lm = getSystemService(Context.LOCATION_SERVICE) as LocationManager
    if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        Toast.makeText(this, "Please enable location services", Toast.LENGTH_SHORT).show()
        buildAlertMessageNoGps(this)
        return
    }

    // Check location permission is granted - if it is, start
    // the service, otherwise request the permission
    val permission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
    if (permission == PackageManager.PERMISSION_GRANTED) {
        callback.invoke()
    } else {
        // callback will be inside the activity's onRequestPermissionsResult(
        ActivityCompat.requestPermissions(
            this,
            arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
            PERMISSIONS_REQUEST
        )
    }
}

plus

   override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    if (requestCode == PERMISSIONS_REQUEST) {
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED){
              // Permission ok. Do work.
         }
    }
}

plus

 fun buildAlertMessageNoGps(context: Context) {
    val builder = AlertDialog.Builder(context);
    builder.setMessage("Your GPS is disabled. Do you want to enable it?")
        .setCancelable(false)
        .setPositiveButton("Yes") { _, _ -> context.startActivity(Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)) }
        .setNegativeButton("No") { dialog, _ -> dialog.cancel(); }
    val alert = builder.create();
    alert.show();
}

usage

checkOrAskLocationPermission() {
            // Permission ok. Do work.
        }

Rerouting stdin and stdout from C

The os function dup2() should provide what you need (if not references to exactly what you need).

More specifically, you can dup2() the stdin file descriptor to another file descriptor, do other stuff with stdin, and then copy it back when you want.

The dup() function duplicates an open file descriptor. Specifically, it provides an alternate interface to the service provided by the fcntl() function using the F_DUPFD constant command value, with 0 for its third argument. The duplicated file descriptor shares any locks with the original.

On success, dup() returns a new file descriptor that has the following in common with the original:

  • Same open file (or pipe)
  • Same file pointer (both file descriptors share one file pointer)
  • Same access mode (read, write, or read/write)

How does one reorder columns in a data frame?

You can also use the subset function:

data <- subset(data, select=c(3,2,1))

You should better use the [] operator as in the other answers, but it may be useful to know that you can do a subset and a column reorder operation in a single command.

Update:

You can also use the select function from the dplyr package:

data = data %>% select(Time, out, In, Files)

I am not sure about the efficiency, but thanks to dplyr's syntax this solution should be more flexible, specially if you have a lot of columns. For example, the following will reorder the columns of the mtcars dataset in the opposite order:

mtcars %>% select(carb:mpg)

And the following will reorder only some columns, and discard others:

mtcars %>% select(mpg:disp, hp, wt, gear:qsec, starts_with('carb'))

Read more about dplyr's select syntax.

Tomcat: How to find out running tomcat version

In Linux to check the tomcat version

cd /opt/tomcat/bin

./catalina.sh version

random.seed(): What does it do?

Pseudo-random number generators work by performing some operation on a value. Generally this value is the previous number generated by the generator. However, the first time you use the generator, there is no previous value.

Seeding a pseudo-random number generator gives it its first "previous" value. Each seed value will correspond to a sequence of generated values for a given random number generator. That is, if you provide the same seed twice, you get the same sequence of numbers twice.

Generally, you want to seed your random number generator with some value that will change each execution of the program. For instance, the current time is a frequently-used seed. The reason why this doesn't happen automatically is so that if you want, you can provide a specific seed to get a known sequence of numbers.

How to save a list to a file and read it as a list type?

You can use pickle module for that. This module have two methods,

  1. Pickling(dump): Convert Python objects into string representation.
  2. Unpickling(load): Retrieving original objects from stored string representstion.

https://docs.python.org/3.3/library/pickle.html

Code:

>>> import pickle
>>> l = [1,2,3,4]
>>> with open("test.txt", "wb") as fp:   #Pickling
...   pickle.dump(l, fp)
... 
>>> with open("test.txt", "rb") as fp:   # Unpickling
...   b = pickle.load(fp)
... 
>>> b
[1, 2, 3, 4]

Also Json

  1. dump/dumps: Serialize
  2. load/loads: Deserialize

https://docs.python.org/3/library/json.html

Code:

>>> import json
>>> with open("test.txt", "w") as fp:
...     json.dump(l, fp)
...
>>> with open("test.txt", "r") as fp:
...     b = json.load(fp)
...
>>> b
[1, 2, 3, 4]

angular js unknown provider

I got an "unknown provider" error related to angular-mocks (ngMockE2E) when compiling my project with Grunt. The problem was that angular-mocks cannot be minified so I had to remove it from the list of minified files.

How to get address of a pointer in c/c++?

Having this C source:

int a = 10;
int * ptr = &a;

Use this

printf("The address of ptr is %p\n", (void *) &ptr);

to print the address of ptr.

Please note that the conversion specifier p is the only conversion specifier to print a pointer's value and it is defined to be used with void* typed pointers only.

From man printf:

p

The void * pointer argument is printed in hexadecimal (as if by %#x or %#lx).

How to sort Counter by value? - python

Use the Counter.most_common() method, it'll sort the items for you:

>>> from collections import Counter
>>> x = Counter({'a':5, 'b':3, 'c':7})
>>> x.most_common()
[('c', 7), ('a', 5), ('b', 3)]

It'll do so in the most efficient manner possible; if you ask for a Top N instead of all values, a heapq is used instead of a straight sort:

>>> x.most_common(1)
[('c', 7)]

Outside of counters, sorting can always be adjusted based on a key function; .sort() and sorted() both take callable that lets you specify a value on which to sort the input sequence; sorted(x, key=x.get, reverse=True) would give you the same sorting as x.most_common(), but only return the keys, for example:

>>> sorted(x, key=x.get, reverse=True)
['c', 'a', 'b']

or you can sort on only the value given (key, value) pairs:

>>> sorted(x.items(), key=lambda pair: pair[1], reverse=True)
[('c', 7), ('a', 5), ('b', 3)]

See the Python sorting howto for more information.

Text in Border CSS HTML

Text in Border with transparent text background

_x000D_
_x000D_
.box{
    background-image: url("https://i.stack.imgur.com/N39wV.jpg");
    width: 350px;
    padding: 10px;
}

/*begin first box*/
.first{
    width: 300px;
    height: 100px;
    margin: 10px;
    border-width: 0 2px 0 2px;
    border-color: #333;
    border-style: solid;
    position: relative;
}

.first span {
    position: absolute;
    display: flex;
    right: 0;
    left: 0;
    align-items: center;
}
.first .foo{
    top: -8px;
}
.first .bar{
    bottom: -8.5px;
}
.first span:before{
    margin-right: 15px;
}
.first span:after {
    margin-left: 15px;
}
.first span:before , .first span:after {
    content: ' ';
    height: 2px;
    background: #333;
    display: block;
    width: 50%;
}


/*begin second box*/
.second{
    width: 300px;
    height: 100px;
    margin: 10px;
    border-width: 2px 0 2px 0;
    border-color: #333;
    border-style: solid;
    position: relative;
}

.second span {
    position: absolute;
    top: 0;
    bottom: 0;
    display: flex;
    flex-direction: column;
    align-items: center;
}
.second .foo{
    left: -15px;
}
.second .bar{
    right: -15.5px;
}
.second span:before{
    margin-bottom: 15px;
}
.second span:after {
    margin-top: 15px;
}
.second span:before , .second span:after {
    content: ' ';
    width: 2px;
    background: #333;
    display: block;
    height: 50%;
}
_x000D_
<div class="box">
    <div class="first">
        <span class="foo">FOO</span>
        <span class="bar">BAR</span>
    </div>

   <br>

    <div class="second">
        <span class="foo">FOO</span>
        <span class="bar">BAR</span>
    </div>
</div>
_x000D_
_x000D_
_x000D_

Convert a Unicode string to a string in Python (containing extra symbols)

Well, if you're willing/ready to switch to Python 3 (which you may not be due to the backwards incompatibility with some Python 2 code), you don't have to do any converting; all text in Python 3 is represented with Unicode strings, which also means that there's no more usage of the u'<text>' syntax. You also have what are, in effect, strings of bytes, which are used to represent data (which may be an encoded string).

http://docs.python.org/3.1/whatsnew/3.0.html#text-vs-data-instead-of-unicode-vs-8-bit

(Of course, if you're currently using Python 3, then the problem is likely something to do with how you're attempting to save the text to a file.)

HTML select drop-down with an input field

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

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

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

How do I compile a Visual Studio project from the command-line?

I know of two ways to do it.

Method 1
The first method (which I prefer) is to use msbuild:

msbuild project.sln /Flags...

Method 2
You can also run:

vcexpress project.sln /build /Flags...

The vcexpress option returns immediately and does not print any output. I suppose that might be what you want for a script.

Note that DevEnv is not distributed with Visual Studio Express 2008 (I spent a lot of time trying to figure that out when I first had a similar issue).

So, the end result might be:

os.system("msbuild project.sln /p:Configuration=Debug")

You'll also want to make sure your environment variables are correct, as msbuild and vcexpress are not by default on the system path. Either start the Visual Studio build environment and run your script from there, or modify the paths in Python (with os.putenv).

Converting an object to a string

If you can use lodash you can do it this way:

> var o = {a:1, b:2};
> '{' + _.map(o, (value, key) => key + ':' + value).join(', ') + '}'
'{a:1, b:2}'

With lodash map() you can iterate over Objects as well. This maps every key/value entry to its string representation:

> _.map(o, (value, key) => key + ':' + value)
[ 'a:1', 'b:2' ]

And join() put the array entries together.

If you can use ES6 Template String, this works also:

> `{${_.map(o, (value, key) => `${key}:${value}`).join(', ')}}`
'{a:1, b:2}'

Please note this do not goes recursive through the Object:

> var o = {a:1, b:{c:2}}
> _.map(o, (value, key) => `${key}:${value}`)
[ 'a:1', 'b:[object Object]' ]

Like node's util.inspect() will do:

> util.inspect(o)
'{ a: 1, b: { c: 2 } }'

How to convert string to XML using C#

xDoc.LoadXML("<head><body><Inner> welcome </head> </Inner> <Outer> Bye</Outer>                    
                    </body></head>");

How can I disable the default console handler, while using the java logging API?

This is strange but Logger.getLogger("global") does not work in my setup (as well as Logger.getLogger(Logger.GLOBAL_LOGGER_NAME)).

However Logger.getLogger("") does the job well.

Hope this info also helps somebody...

Replacing a 32-bit loop counter with 64-bit introduces crazy performance deviations with _mm_popcnt_u64 on Intel CPUs

I can't give an authoritative answer, but provide an overview of a likely cause. This reference shows pretty clearly that for the instructions in the body of your loop there is a 3:1 ratio between latency and throughput. It also shows the effects of multiple dispatch. Since there are (give-or-take) three integer units in modern x86 processors, it's generally possible to dispatch three instructions per cycle.

So between peak pipeline and multiple dispatch performance and failure of these mechanisms, we have a factor of six in performance. It's pretty well known that the complexity of the x86 instruction set makes it quite easy for quirky breakage to occur. The document above has a great example:

The Pentium 4 performance for 64-bit right shifts is really poor. 64-bit left shift as well as all 32-bit shifts have acceptable performance. It appears that the data path from the upper 32 bits to the lower 32 bit of the ALU is not well designed.

I personally ran into a strange case where a hot loop ran considerably slower on a specific core of a four-core chip (AMD if I recall). We actually got better performance on a map-reduce calculation by turning that core off.

Here my guess is contention for integer units: that the popcnt, loop counter, and address calculations can all just barely run at full speed with the 32-bit wide counter, but the 64-bit counter causes contention and pipeline stalls. Since there are only about 12 cycles total, potentially 4 cycles with multiple dispatch, per loop body execution, a single stall could reasonably affect run time by a factor of 2.

The change induced by using a static variable, which I'm guessing just causes a minor reordering of instructions, is another clue that the 32-bit code is at some tipping point for contention.

I know this is not a rigorous analysis, but it is a plausible explanation.

What does -> mean in Python function definitions?

As other answers have stated, the -> symbol is used as part of function annotations. In more recent versions of Python >= 3.5, though, it has a defined meaning.

PEP 3107 -- Function Annotations described the specification, defining the grammar changes, the existence of func.__annotations__ in which they are stored and, the fact that it's use case is still open.

In Python 3.5 though, PEP 484 -- Type Hints attaches a single meaning to this: -> is used to indicate the type that the function returns. It also seems like this will be enforced in future versions as described in What about existing uses of annotations:

The fastest conceivable scheme would introduce silent deprecation of non-type-hint annotations in 3.6, full deprecation in 3.7, and declare type hints as the only allowed use of annotations in Python 3.8.

(Emphasis mine)

This hasn't been actually implemented as of 3.6 as far as I can tell so it might get bumped to future versions.

According to this, the example you've supplied:

def f(x) -> 123:
    return x

will be forbidden in the future (and in current versions will be confusing), it would need to be changed to:

def f(x) -> int:
    return x

for it to effectively describe that function f returns an object of type int.

The annotations are not used in any way by Python itself, it pretty much populates and ignores them. It's up to 3rd party libraries to work with them.

What does character set and collation mean exactly?

A character set is a subset of all written glyphs. A character encoding specifies how those characters are mapped to numeric values. Some character encodings, like UTF-8 and UTF-16, can encode any character in the Universal Character Set. Others, like US-ASCII or ISO-8859-1 can only encode a small subset, since they use 7 and 8 bits per character, respectively. Because many standards specify both a character set and a character encoding, the term "character set" is often substituted freely for "character encoding".

A collation comprises rules that specify how characters can be compared for sorting. Collations rules can be locale-specific: the proper order of two characters varies from language to language.

Choosing a character set and collation comes down to whether your application is internationalized or not. If not, what locale are you targeting?

In order to choose what character set you want to support, you have to consider your application. If you are storing user-supplied input, it might be hard to foresee all the locales in which your software will eventually be used. To support them all, it might be best to support the UCS (Unicode) from the start. However, there is a cost to this; many western European characters will now require two bytes of storage per character instead of one.

Choosing the right collation can help performance if your database uses the collation to create an index, and later uses that index to provide sorted results. However, since collation rules are often locale-specific, that index will be worthless if you need to sort results according to the rules of another locale.

Pandas - Plotting a stacked Bar Chart

If you want to change the size of plot the use arg figsize

df.groupby(['NFF', 'ABUSE']).size().unstack()
      .plot(kind='bar', stacked=True, figsize=(15, 5))

How to create a data file for gnuplot?

For future reference, I had the same problem

"warning: Skipping unreadable file"

under Linux. The reason was that I love using Tab-completing and in gnuplot this added a whitespace at the end that I did not really notice

gnuplot> plot "./datafile.txt "

Uninstalling an MSI file from the command line without using msiexec

I'm assuming that when you type int file.msi into the command line, Windows is automatically calling msiexec file.msi for you. I'm assuming this because when you type in picture.png it brings up the default picture viewer.

get the selected index value of <select> tag in php

As you said..

$Gender  = isset($_POST["gender"]); ' it returns a empty string 

because, you haven't mention method type either use POST or GET, by default it will use GET method. On the other side, you are trying to retrieve your value by using POST method, but in the form you haven't mentioned POST method. Which means miss-match method will result for empty.

Try this code..

<form name="signup_form"  action="./signup.php" onsubmit="return validateForm()"   method="post">
<table> 
  <tr> <td> First Name    </td><td> <input type="text" name="fname" size=10/></td></tr>
  <tr> <td> Last Name     </td><td> <input type="text" name="lname" size=10/></td></tr>
  <tr> <td> Your Email    </td><td> <input type="text" name="email" size=10/></td></tr>
  <tr> <td> Re-type Email </td><td> <input type="text" name="remail"size=10/></td></tr>
  <tr> <td> Password      </td><td> <input type="password" name="paswod" size=10/> </td></tr>
  <tr> <td> Gender        </td><td> <select name="gender">
  <option value="select">                Select </option>    
  <option value="male">   Male   </option>
  <option value="female"> Female </option></select></td></tr> 
  <tr> <td> <input type="submit" value="Sign up" id="signup"/> </td> </tr>
 </table>
 </form>

and on signup page

$Gender  = $_POST["gender"];

i'm sure.. now, you will get the value..

Byte[] to InputStream or OutputStream

There is no conversion between InputStream/OutputStream and the bytes they are working with. They are made for binary data, and just read (or write) the bytes one by one as is.

A conversion needs to happen when you want to go from byte to char. Then you need to convert using a character set. This happens when you make String or Reader from bytes, which are made for character data.

Get last key-value pair in PHP array

try to use

end($array);

Controller 'ngModel', required by directive '...', can't be found

As described here: Angular NgModelController, you should provide the <input with the required controller ngModel

<input submit-required="true" ng-model="user.Name"></input>

PHP mail function doesn't complete sending of e-mail

You can use config email by CodeIgniter. For example, using SMTP (simple way):

$config = Array(
        'protocol' => 'smtp',
        'smtp_host' => 'mail.domain.com', // Your SMTP host
        'smtp_port' => 26, // Default port for SMTP
        'smtp_user' => '[email protected]',
        'smtp_pass' => 'password',
        'mailtype' => 'html',
        'charset' => 'iso-8859-1',
        'wordwrap' => TRUE
);
$message = 'Your msg';
$this->load->library('email', $config);
$this->email->from('[email protected]', 'Title');
$this->email->to('[email protected]');
$this->email->subject('Header');
$this->email->message($message);

if($this->email->send()) 
{
   // Conditional true
}

It works for me!

ASP.NET MVC3 Razor - Html.ActionLink style

VB sample:

 @Html.ActionLink("Home", "Index", Nothing, New With {.style = "font-weight:bold;", .class = "someClass"})

Sample Css:

.someClass
{
    color: Green !important;
}

In my case, I found that I need the !important attribute to over ride the site.css a:link css class

Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0

Somehow I had the wrong versions of the DLLs registered in my project.

  • I removed the three references to the Crystal Report dlls from my project. Crystal DLLs
  • I right click References, and click Add Reference
  • In the popup window, I click the Browse menu on the left and the Browse button Reference Manager
  • In the Directory window where your DLLs reside (perhaps your application's bin directory), select the three Crystal Reports DLLs and then click Add. DLLs
  • Back at the Reference Manager window, click in the first column to the left of the three Crystal dlls, and then click OK enter image description here
  • At this point your Crystal Reports should work again.

phpmysql error - #1273 - #1273 - Unknown collation: 'utf8mb4_general_ci'

This solution worked for me

1) Click the "Export" tab for the database

2) Click the "Custom" radio button

3) Go the section titled "Format-specific options" and change the dropdown for "Database system or older MySQL server to maximize output compatibility with:" from NONE to MYSQL40.

4) Scroll to the bottom and click "GO".

If it's related to wordpress, more info on why it is happening.

Solr vs. ElasticSearch

Update

Now that the question scope has been corrected, I might add something in this regard as well:

There are many comparisons between Apache Solr and ElasticSearch available, so I'll reference those I found most useful myself, i.e. covering the most important aspects:

  • Bob Yoplait already linked kimchy's answer to ElasticSearch, Sphinx, Lucene, Solr, Xapian. Which fits for which usage?, which summarizes the reasons why he went ahead and created ElasticSearch, which in his opinion provides a much superior distributed model and ease of use in comparison to Solr.

  • Ryan Sonnek's Realtime Search: Solr vs Elasticsearch provides an insightful analysis/comparison and explains why he switched from Solr to ElasticSeach, despite being a happy Solr user already - he summarizes this as follows:

    Solr may be the weapon of choice when building standard search applications, but Elasticsearch takes it to the next level with an architecture for creating modern realtime search applications. Percolation is an exciting and innovative feature that singlehandedly blows Solr right out of the water. Elasticsearch is scalable, speedy and a dream to integrate with. Adios Solr, it was nice knowing you. [emphasis mine]

  • The Wikipedia article on ElasticSearch quotes a comparison from the reputed German iX magazine, listing advantages and disadvantages, which pretty much summarize what has been said above already:

    Advantages:

    • ElasticSearch is distributed. No separate project required. Replicas are near real-time too, which is called "Push replication".
    • ElasticSearch fully supports the near real-time search of Apache Lucene.
    • Handling multitenancy is not a special configuration, where with Solr a more advanced setup is necessary.
    • ElasticSearch introduces the concept of the Gateway, which makes full backups easier.

    Disadvantages:

    • Only one main developer [not applicable anymore according to the current elasticsearch GitHub organization, besides having a pretty active committer base in the first place]
    • No autowarming feature [not applicable anymore according to the new Index Warmup API]

Initial Answer

They are completely different technologies addressing completely different use cases, thus cannot be compared at all in any meaningful way:

  • Apache Solr - Apache Solr offers Lucene's capabilities in an easy to use, fast search server with additional features like faceting, scalability and much more

  • Amazon ElastiCache - Amazon ElastiCache is a web service that makes it easy to deploy, operate, and scale an in-memory cache in the cloud.

    • Please note that Amazon ElastiCache is protocol-compliant with Memcached, a widely adopted memory object caching system, so code, applications, and popular tools that you use today with existing Memcached environments will work seamlessly with the service (see Memcached for details).

[emphasis mine]

Maybe this has been confused with the following two related technologies one way or another:

  • ElasticSearch - It is an Open Source (Apache 2), Distributed, RESTful, Search Engine built on top of Apache Lucene.

  • Amazon CloudSearch - Amazon CloudSearch is a fully-managed search service in the cloud that allows customers to easily integrate fast and highly scalable search functionality into their applications.

The Solr and ElasticSearch offerings sound strikingly similar at first sight, and both use the same backend search engine, namely Apache Lucene.

While Solr is older, quite versatile and mature and widely used accordingly, ElasticSearch has been developed specifically to address Solr shortcomings with scalability requirements in modern cloud environments, which are hard(er) to address with Solr.

As such it would probably be most useful to compare ElasticSearch with the recently introduced Amazon CloudSearch (see the introductory post Start Searching in One Hour for Less Than $100 / Month), because both claim to cover the same use cases in principle.

A CORS POST request works from plain JavaScript, but why not with jQuery?

Another possibility is that setting dataType: json causes JQuery to send the Content-Type: application/json header. This is considered a non-standard header by CORS, and requires a CORS preflight request. So a few things to try:

1) Try configuring your server to send the proper preflight responses. This will be in the form of additional headers like Access-Control-Allow-Methods and Access-Control-Allow-Headers.

2) Drop the dataType: json setting. JQuery should request Content-Type: application/x-www-form-urlencoded by default, but just to be sure, you can replace dataType: json with contentType: 'application/x-www-form-urlencoded'

Sum columns with null values in oracle

NVL(value, default) is the function you are looking for.

select type, craft, sum(NVL(regular, 0) + NVL(overtime, 0) ) as total_hours
from hours_t
group by type, craft
order by type, craft

Oracle have 5 NULL-related functions:

  1. NVL
  2. NVL2
  3. COALESCE
  4. NULLIF
  5. LNNVL

NVL:

NVL(expr1, expr2)

NVL lets you replace null (returned as a blank) with a string in the results of a query. If expr1 is null, then NVL returns expr2. If expr1 is not null, then NVL returns expr1.

NVL2 :

NVL2(expr1, expr2, expr3)

NVL2 lets you determine the value returned by a query based on whether a specified expression is null or not null. If expr1 is not null, then NVL2 returns expr2. If expr1 is null, then NVL2 returns expr3.

COALESCE

COALESCE(expr1, expr2, ...)

COALESCE returns the first non-null expr in the expression list. At least one expr must not be the literal NULL. If all occurrences of expr evaluate to null, then the function returns null.

NULLIF

NULLIF(expr1, expr2)

NULLIF compares expr1 and expr2. If they are equal, then the function returns null. If they are not equal, then the function returns expr1. You cannot specify the literal NULL for expr1.

LNNVL

LNNVL(condition)

LNNVL provides a concise way to evaluate a condition when one or both operands of the condition may be null.

More info on Oracle SQL Functions

Detect enter press in JTextField

Do you want to do something like this ?

JTextField mTextField = new JTextField();
    mTextField.addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent e) {
            if(e.getKeyCode() == KeyEvent.VK_ENTER){
                // something like...
               //mTextField.getText();
               // or...
               //mButton.doClick();
            }
        }

    });

Updating state on props change in React Form

Use Memoize

The op's derivation of state is a direct manipulation of props, with no true derivation needed. In other words, if you have a prop which can be utilized or transformed directly there is no need to store the prop on state.

Given that the state value of start_time is simply the prop start_time.format("HH:mm"), the information contained in the prop is already in itself sufficient for updating the component.

However if you did want to only call format on a prop change, the correct way to do this per latest documentation would be via Memoize: https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#what-about-memoization

How to use Python's "easy_install" on Windows ... it's not so easy

If you are using windows 7 64-bit version, then the solution is found here: http://pypi.python.org/pypi/setuptools

namely, you need to download a python script, run it, and then easy_install will work normally from commandline.

P.S. I agree with the original poster saying that this should work out of the box.

Why do we use Base64?

In addition to the other (somewhat lengthy) answers: even ignoring old systems that support only 7-bit ASCII, basic problems with supplying binary data in text-mode are:

  • Newlines are typically transformed in text-mode.
  • One must be careful not to treat a NUL byte as the end of a text string, which is all too easy to do in any program with C lineage.

How to set HTTP headers (for cache-control)?

This is the best .htaccess I have used in my actual website:

<ifModule mod_gzip.c>
mod_gzip_on Yes
mod_gzip_dechunk Yes
mod_gzip_item_include file .(html?|txt|css|js|php|pl)$
mod_gzip_item_include handler ^cgi-script$
mod_gzip_item_include mime ^text/.*
mod_gzip_item_include mime ^application/x-javascript.*
mod_gzip_item_exclude mime ^image/.*
mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</ifModule>

##Tweaks##
Header set X-Frame-Options SAMEORIGIN

## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType text/html "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 1 month"
</IfModule>
## EXPIRES CACHING ##

<IfModule mod_headers.c>
    Header set Connection keep-alive
    <filesmatch "\.(ico|flv|gif|swf|eot|woff|otf|ttf|svg)$">
        Header set Cache-Control "max-age=2592000, public"
    </filesmatch>
    <filesmatch "\.(jpg|jpeg|png)$">
        Header set Cache-Control "max-age=1209600, public"
    </filesmatch>
    # css and js should use private for proxy caching https://developers.google.com/speed/docs/best-practices/caching#LeverageProxyCaching
    <filesmatch "\.(css)$">
        Header set Cache-Control "max-age=31536000, private"
    </filesmatch>
    <filesmatch "\.(js)$">
        Header set Cache-Control "max-age=1209600, private"
    </filesmatch>
    <filesMatch "\.(x?html?|php)$">
        Header set Cache-Control "max-age=600, private, must-revalidate"
      </filesMatch>
</IfModule>

How to create empty folder in java?

Looks file you use the .mkdirs() method on a File object: http://www.roseindia.net/java/beginners/java-create-directory.shtml

// Create a directory; all non-existent ancestor directories are
// automatically created
success = (new File("../potentially/long/pathname/without/all/dirs")).mkdirs();
if (!success) {
    // Directory creation failed
}

git cherry-pick says "...38c74d is a merge but no -m option was given"

@Borealid's answer is correct, but suppose that you don't care about preserving the exact merging history of a branch and just want to cherry-pick a linearized version of it. Here's an easy and safe way to do that:

Starting state: you are on branch X, and you want to cherry-pick the commits Y..Z.

  1. git checkout -b tempZ Z
  2. git rebase Y
  3. git checkout -b newX X
  4. git cherry-pick Y..tempZ
  5. (optional) git branch -D tempZ

What this does is to create a branch tempZ based on Z, but with the history from Y onward linearized, and then cherry-pick that onto a copy of X called newX. (It's safer to do this on a new branch rather than to mutate X.) Of course there might be conflicts in step 4, which you'll have to resolve in the usual way (cherry-pick works very much like rebase in that respect). Finally it deletes the temporary tempZ branch.

If step 2 gives the message "Current branch tempZ is up to date", then Y..Z was already linear, so just ignore that message and proceed with steps 3 onward.

Then review newX and see whether that did what you wanted.

(Note: this is not the same as a simple git rebase X when on branch Z, because it doesn't depend in any way on the relationship between X and Y; there may be commits between the common ancestor and Y that you didn't want.)

ADB Shell Input Events

If you want to send a text to specific device when multiple devices connected. First look for the attached devices using adb devices

adb devices
List of devices attached
3004e25a57192200        device
31002d9e592b7300        device

then get your specific device id and try the following

adb -s 31002d9e592b7300 shell input text 'your text'

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

You can use isin method:

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

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

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

And to get the opposite use ~:

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

How to download all files (but not HTML) from a website using wget?

To filter for specific file extensions:

wget -A pdf,jpg -m -p -E -k -K -np http://site/path/

Or, if you prefer long option names:

wget --accept pdf,jpg --mirror --page-requisites --adjust-extension --convert-links --backup-converted --no-parent http://site/path/

This will mirror the site, but the files without jpg or pdf extension will be automatically removed.

Postgres: How to do Composite keys?

The error you are getting is in line 3. i.e. it is not in

CONSTRAINT no_duplicate_tag UNIQUE (question_id, tag_id)

but earlier:

CREATE TABLE tags
     (
              (question_id, tag_id) NOT NULL,

Correct table definition is like pilcrow showed.

And if you want to add unique on tag1, tag2, tag3 (which sounds very suspicious), then the syntax is:

CREATE TABLE tags (
    question_id INTEGER NOT NULL,
    tag_id SERIAL NOT NULL,
    tag1 VARCHAR(20),
    tag2 VARCHAR(20),
    tag3 VARCHAR(20),
    PRIMARY KEY(question_id, tag_id),
    UNIQUE (tag1, tag2, tag3)
);

or, if you want to have the constraint named according to your wish:

CREATE TABLE tags (
    question_id INTEGER NOT NULL,
    tag_id SERIAL NOT NULL,
    tag1 VARCHAR(20),
    tag2 VARCHAR(20),
    tag3 VARCHAR(20),
    PRIMARY KEY(question_id, tag_id),
    CONSTRAINT some_name UNIQUE (tag1, tag2, tag3)
);

How to express a NOT IN query with ActiveRecord/Rails?

Can these forum ids be worked out in a pragmatic way? e.g. can you find these forums somehow - if that is the case you should do something like

Topic.all(:joins => "left join forums on (forums.id = topics.forum_id and some_condition)", :conditions => "forums.id is null")

Which would be more efficient than doing an SQL not in

Is it possible to access an SQLite database from JavaScript?

Up to date answer

My fork of sql.js has now be merged into the original version, on kriken's repo.

The good documentation is also available on the original repo.

Original answer (outdated)

You should use the newer version of sql.js. It is a port of sqlite 3.8, has a good documentation and is actively maintained (by me). It supports prepared statements, and BLOB data type.

How to improve Netbeans performance?

I had big problems with NetBeans 8.0.2. It's an old question but perhaps somebody else will end up here like me with the same problem, and I found no answer that helped me anywhere.

I have NetBeans 8.0.2 with Ruby on Rails plugin, on Windows 7. The IDE was hanging up to 10 seconds on almost every change I did in some files. It was problem only with big files, but it must depend on more than that, there were other big files without the problem.

The problem was caused by the "hint" "Rails 3 Deprecations", I turned it off and now it's very fast, I can have everything else turned on without problems.
It's under Tools -> Options -> Editor -> Hints.

There is also some suggestions in the other answers of optimizing with startup parameters. I found these links about JVM-switches that helped me when testing to optimize (but it turned out that these settings have nothing to do with my problem), they are very old but have some useful information:
Explanation of JVM-switches.
Some (old) recommendations

get number of columns of a particular row in given excel using Java

Sometimes using row.getLastCellNum() gives you a higher value than what is actually filled in the file.
I used the method below to get the last column index that contains an actual value.

private int getLastFilledCellPosition(Row row) {
        int columnIndex = -1;

        for (int i = row.getLastCellNum() - 1; i >= 0; i--) {
            Cell cell = row.getCell(i);

            if (cell == null || CellType.BLANK.equals(cell.getCellType()) || StringUtils.isBlank(cell.getStringCellValue())) {
                continue;
            } else {
                columnIndex = cell.getColumnIndex();
                break;
            }
        }

        return columnIndex;
    }

Find html label associated with a given input

$("label[for='inputId']").text()

This helped me to get the label of an input element using its ID.

Set Google Chrome as the debugging browser in Visual Studio

For MVC developers,

  • click on a folder in Solution Explorer (say, Controllers)
  • Select Browse With...
  • Select desired browser
  • (Optionally click ) set as Default

MySql : Grant read only options?

Various permissions that you can grant to a user are

ALL PRIVILEGES- This would allow a MySQL user all access to a designated database (or if no database is selected, across the system)
CREATE- allows them to create new tables or databases
DROP- allows them to them to delete tables or databases
DELETE- allows them to delete rows from tables
INSERT- allows them to insert rows into tables
SELECT- allows them to use the Select command to read through databases
UPDATE- allow them to update table rows
GRANT OPTION- allows them to grant or remove other users' privileges

To provide a specific user with a permission, you can use this framework:

GRANT [type of permission] ON [database name].[table name] TO ‘[username]’@'localhost’;

I found this article very helpful

How do you change the formatting options in Visual Studio Code?

Same thing happened to me just now. I set prettier as the Default Formatter in Settings and it started working again. My Default Formatter was null.

To set VSCODE Default Formatter

File -> Preferences -> Settings (for Windows) Code -> Preferences -> Settings (for Mac)

Search for "Default Formatter". In the dropdown, prettier will show as esbenp.prettier-vscode.

VSCODE Editor Option

store return value of a Python script in a bash script

sys.exit(myString) doesn't mean "return this string". If you pass a string to sys.exit, sys.exit will consider that string to be an error message, and it will write that string to stderr. The closest concept to a return value for an entire program is its exit status, which must be an integer.

If you want to capture output written to stderr, you can do something like

python yourscript 2> return_file

You could do something like that in your bash script

output=$((your command here) 2> &1)

This is not guaranteed to capture only the value passed to sys.exit, though. Anything else written to stderr will also be captured, which might include logging output or stack traces.

example:

test.py

print "something"
exit('ohoh') 

t.sh

va=$(python test.py 2>&1)                                                                                                                    
mkdir $va

bash t.sh

edit

Not sure why but in that case, I would write a main script and two other scripts... Mixing python and bash is pointless unless you really need to.

import script1
import script2

if __name__ == '__main__':
    filename = script1.run(sys.args)
    script2.run(filename)

Why aren't python nested functions called closures?

I'd like to offer another simple comparison between python and JS example, if this helps make things clearer.

JS:

function make () {
  var cl = 1;
  function gett () {
    console.log(cl);
  }
  function sett (val) {
    cl = val;
  }
  return [gett, sett]
}

and executing:

a = make(); g = a[0]; s = a[1];
s(2); g(); // 2
s(3); g(); // 3

Python:

def make (): 
  cl = 1
  def gett ():
    print(cl);
  def sett (val):
    cl = val
  return gett, sett

and executing:

g, s = make()
g() #1
s(2); g() #1
s(3); g() #1

Reason: As many others said above, in python, if there is an assignment in the inner scope to a variable with the same name, a new reference in the inner scope is created. Not so with JS, unless you explicitly declare one with the var keyword.

Singleton: How should it be used

One thing with patterns: don't generalize. They have all cases when they're useful, and when they fail.

Singleton can be nasty when you have to test the code. You're generally stuck with one instance of the class, and can choose between opening up a door in constructor or some method to reset the state and so on.

Other problem is that the Singleton in fact is nothing more than a global variable in disguise. When you have too much global shared state over your program, things tend to go back, we all know it.

It may make dependency tracking harder. When everything depends on your Singleton, it's harder to change it, split to two, etc. You're generally stuck with it. This also hampers flexibility. Investigate some Dependency Injection framework to try to alleviate this issue.

Validate a username and password against Active Directory?

Yet another .NET call to quickly authenticate LDAP credentials:

using System.DirectoryServices;

using(var DE = new DirectoryEntry(path, username, password)
{
    try
    {
        DE.RefreshCache(); // This will force credentials validation
    }
    catch (COMException ex)
    {
        // Validation failed - handle how you want
    }
}

Cannot perform runtime binding on a null reference, But it is NOT a null reference

This exception is also thrown when a non-existent property is being updated dynamically, using reflection.

If one is using reflection to dynamically update property values, it's worth checking to make sure the passed PropertyName is identical to the actual property.

In my case, I was attempting to update Employee.firstName, but the property was actually Employee.FirstName.

Worth keeping in mind. :)

Convert char array to string use C

You're saying you have this:

char array[20]; char string[100];
array[0]='1'; 
array[1]='7'; 
array[2]='8'; 
array[3]='.'; 
array[4]='9';

And you'd like to have this:

string[0]= "178.9"; // where it was stored 178.9 ....in position [0]

You can't have that. A char holds 1 character. That's it. A "string" in C is an array of characters followed by a sentinel character (NULL terminator).

Now if you want to copy the first x characters out of array to string you can do that with memcpy():

memcpy(string, array, x);
string[x] = '\0'; 

Can anyone explain what JSONP is, in layman terms?

I have found a useful article that also explains the topic quite clearly and easy language. Link is JSONP

Some of the worth noting points are:

  1. JSONP pre-dates CORS.
  2. It is a pseudo-standard way to retreive data from a different domain,
  3. It has limited CORS features (only GET method)

Working is as follows:

  1. <script src="url?callback=function_name"> is included in the html code
  2. When step 1 gets executed it sens a function with the same function name (as given in the url parameter) as a response.
  3. If the function with the given name exists in the code, it will be executed with the data, if any, returned as an argument to that function.

How can I convert uppercase letters to lowercase in Notepad++

Ctrl+A , Ctrl+Shift+U

should do the trick!

Edit: Ctrl+U is the shortcut to be used to convert capital letters to lowercase (reverse scenario)

When must we use NVARCHAR/NCHAR instead of VARCHAR/CHAR in SQL Server?

You should use NVARCHAR anytime you have to store multiple languages. I believe you have to use it for the Asian languages but don't quote me on it.

Here's the problem if you take Russian for example and store it in a varchar, you will be fine so long as you define the correct code page. But let's say your using a default english sql install, then the russian characters will not be handled correctly. If you were using NVARCHAR() they would be handled properly.

Edit

Ok let me quote MSDN and maybee I was to specific but you don't want to store more then one code page in a varcar column, while you can you shouldn't

When you deal with text data that is stored in the char, varchar, varchar(max), or text data type, the most important limitation to consider is that only information from a single code page can be validated by the system. (You can store data from multiple code pages, but this is not recommended.) The exact code page used to validate and store the data depends on the collation of the column. If a column-level collation has not been defined, the collation of the database is used. To determine the code page that is used for a given column, you can use the COLLATIONPROPERTY function, as shown in the following code examples:

Here's some more:

This example illustrates the fact that many locales, such as Georgian and Hindi, do not have code pages, as they are Unicode-only collations. Those collations are not appropriate for columns that use the char, varchar, or text data type

So Georgian or Hindi really need to be stored as nvarchar. Arabic is also a problem:

Another problem you might encounter is the inability to store data when not all of the characters you wish to support are contained in the code page. In many cases, Windows considers a particular code page to be a "best fit" code page, which means there is no guarantee that you can rely on the code page to handle all text; it is merely the best one available. An example of this is the Arabic script: it supports a wide array of languages, including Baluchi, Berber, Farsi, Kashmiri, Kazakh, Kirghiz, Pashto, Sindhi, Uighur, Urdu, and more. All of these languages have additional characters beyond those in the Arabic language as defined in Windows code page 1256. If you attempt to store these extra characters in a non-Unicode column that has the Arabic collation, the characters are converted into question marks.

Something to keep in mind when you are using Unicode although you can store different languages in a single column you can only sort using a single collation. There are some languages that use latin characters but do not sort like other latin languages. Accents is a good example of this, I can't remeber the example but there was a eastern european language whose Y didn't sort like the English Y. Then there is the spanish ch which spanish users expet to be sorted after h.

All in all with all the issues you have to deal with when dealing with internalitionalization. It is my opinion that is easier to just use Unicode characters from the start, avoid the extra conversions and take the space hit. Hence my statement earlier.

vagrant login as root by default

This works if you are on ubuntu/trusty64 box:

vagrant ssh

Once you are in the ubuntu box:

sudo su

Now you are root user. You can update root password as shown below:

sudo -i
passwd

Now edit the below line in the file /etc/ssh/sshd_config

PermitRootLogin yes

Also, it is convenient to create your own alternate username:

adduser johndoe

Wait until it asks for password.

How to get raw text from pdf file using java

For the newer versions of Apache pdfbox. Here is the example from the original source

/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.pdfbox.examples.util;

import java.io.File;
import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.encryption.AccessPermission;
import org.apache.pdfbox.text.PDFTextStripper;

/**
 * This is a simple text extraction example to get started. For more advance usage, see the
 * ExtractTextByArea and the DrawPrintTextLocations examples in this subproject, as well as the
 * ExtractText tool in the tools subproject.
 *
 * @author Tilman Hausherr
 */
public class ExtractTextSimple
{
    private ExtractTextSimple()
    {
        // example class should not be instantiated
    }

    /**
     * This will print the documents text page by page.
     *
     * @param args The command line arguments.
     *
     * @throws IOException If there is an error parsing or extracting the document.
     */
    public static void main(String[] args) throws IOException
    {
        if (args.length != 1)
        {
            usage();
        }

        try (PDDocument document = PDDocument.load(new File(args[0])))
        {
            AccessPermission ap = document.getCurrentAccessPermission();
            if (!ap.canExtractContent())
            {
                throw new IOException("You do not have permission to extract text");
            }

            PDFTextStripper stripper = new PDFTextStripper();

            // This example uses sorting, but in some cases it is more useful to switch it off,
            // e.g. in some files with columns where the PDF content stream respects the
            // column order.
            stripper.setSortByPosition(true);

            for (int p = 1; p <= document.getNumberOfPages(); ++p)
            {
                // Set the page interval to extract. If you don't, then all pages would be extracted.
                stripper.setStartPage(p);
                stripper.setEndPage(p);

                // let the magic happen
                String text = stripper.getText(document);

                // do some nice output with a header
                String pageStr = String.format("page %d:", p);
                System.out.println(pageStr);
                for (int i = 0; i < pageStr.length(); ++i)
                {
                    System.out.print("-");
                }
                System.out.println();
                System.out.println(text.trim());
                System.out.println();

                // If the extracted text is empty or gibberish, please try extracting text
                // with Adobe Reader first before asking for help. Also read the FAQ
                // on the website: 
                // https://pdfbox.apache.org/2.0/faq.html#text-extraction
            }
        }
    }

    /**
     * This will print the usage for this document.
     */
    private static void usage()
    {
        System.err.println("Usage: java " + ExtractTextSimple.class.getName() + " <input-pdf>");
        System.exit(-1);
    }
}

Convert CString to const char*

If your CString is Unicode, you'll need to do a conversion to multi-byte characters. Fortunately there is a version of CString which will do this automatically.

CString unicodestr = _T("Testing");
CStringA charstr(unicodestr);
DoMyStuff((const char *) charstr);

Maximum on http header values?

HTTP does not place a predefined limit on the length of each header field or on the length of the header section as a whole, as described in Section 2.5. Various ad hoc limitations on individual header field length are found in practice, often depending on the specific field semantics.

HTTP Header values are restricted by server implementations. Http specification doesn't restrict header size.

A server that receives a request header field, or set of fields, larger than it wishes to process MUST respond with an appropriate 4xx (Client Error) status code. Ignoring such header fields would increase the server's vulnerability to request smuggling attacks (Section 9.5).

Most servers will return 413 Entity Too Large or appropriate 4xx error when this happens.

A client MAY discard or truncate received header fields that are larger than the client wishes to process if the field semantics are such that the dropped value(s) can be safely ignored without changing the message framing or response semantics.

Uncapped HTTP header size keeps the server exposed to attacks and can bring down its capacity to serve organic traffic.

Source

How to duplicate a git repository? (without forking)

You can also use git-copy.

Install it with Gem,

gem install git-copy

Then

git copy https://github.com/exampleuser/old-repository.git \
    https://github.com/exampleuser/new-repository.git

How can I see the size of a GitHub repository before cloning it?

If you're trying to find out the size of your own repositories.

All you have to do is go to GitHub settings repositories and you see all the sizes right there in the browser no extra work needed.

https://github.com/settings/repositories

How does Python's super() work with multiple inheritance?

Another not yet covered point is passing parameters for initialization of classes. Since the destination of super depends on the subclass the only good way to pass parameters is packing them all together. Then be careful to not have the same parameter name with different meanings.

Example:

class A(object):
    def __init__(self, **kwargs):
        print('A.__init__')
        super().__init__()

class B(A):
    def __init__(self, **kwargs):
        print('B.__init__ {}'.format(kwargs['x']))
        super().__init__(**kwargs)


class C(A):
    def __init__(self, **kwargs):
        print('C.__init__ with {}, {}'.format(kwargs['a'], kwargs['b']))
        super().__init__(**kwargs)


class D(B, C): # MRO=D, B, C, A
    def __init__(self):
        print('D.__init__')
        super().__init__(a=1, b=2, x=3)

print(D.mro())
D()

gives:

[<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>]
D.__init__
B.__init__ 3
C.__init__ with 1, 2
A.__init__

Calling the super class __init__ directly to more direct assignment of parameters is tempting but fails if there is any super call in a super class and/or the MRO is changed and class A may be called multiple times, depending on the implementation.

To conclude: cooperative inheritance and super and specific parameters for initialization aren't working together very well.

assign headers based on existing row in dataframe in R

Very similar to Vishnu's answer but uses the lapply to map all the data to characters then to assign them as the headers. This is really helpful if your data is imported as factors.

DF[] <- lapply(DF, as.character)
colnames(DF) <- DF[1, ]
DF <- DF[-1 ,]

note that that if you have a lot of numeric data or factors you want you'll need to convert them back. In this case it may make sense to store the character data frame, extract the row you want, and then apply it to the original data frame

tempDF <- DF
tempDF[] <- lapply(DF, as.character)
colnames(DF) <- tempDF[1, ]
DF <- DF[-1 ,]
tempDF <- NULL

How can I set the 'backend' in matplotlib in Python?

For new comers,

matplotlib.pyplot.switch_backend(newbackend)

When is the finalize() method called in Java?

Sometimes when it is destroyed, an object must make an action. For example, if an object has a non-java resource such as a file handle or a font, you can verify that these resources are released before destroying an object. To manage such situations, java offers a mechanism called "finalizing". By finalizing it, you can define specific actions that occur when an object is about to be removed from the garbage collector. To add a finalizer to a class simply define the finalize() method. Java execution time calls this method whenever it is about to delete an object of that class. Within the finalize method() you specify actions to be performed before destroying an object. The garbage collector is periodically searched for objects that no longer refer to any running state or indirectly any other object with reference. Before an asset is released, the Java runtime calls the finalize() method on the object. The finalize() method has the following general form:

protected void finalize(){
    // This is where the finalization code is entered
}

With the protected keyword, access to finalize() by code outside its class is prevented. It is important to understand that finalize() is called just just before the garbage collection. It is not called when an object leaves the scope, for example. It means you can not know when, or if, finalize() will be executed. As a result, the program must provide other means to free system resources or other resources used by the object. You should not rely on finalize() for normal running of the program.

ReferenceError: fetch is not defined

The following works for me in Node.js 12.x:

npm i node-fetch;

to initialize the Dropbox instance:

var Dropbox = require("dropbox").Dropbox;
var dbx = new Dropbox({
   accessToken: <your access token>,
   fetch: require("node-fetch")    
});

to e.g. upload a content (an asynchronous method used in this case):

await dbx.filesUpload({
  contents: <your content>,
  path: <file path>
});

Cell spacing in UICollectionView

Storyboard Approach

Select CollectionView in your storyboard and go to size inspector and set min spacing for cells and lines as 5

Swift 5 Programmatically

lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal

        //Provide Width and Height According to your need
        let width = UIScreen.main.bounds.width / 4
        let height = UIScreen.main.bounds.height / 10
        layout.itemSize = CGSize(width: width, height: height)

        //For Adjusting the cells spacing
        layout.minimumInteritemSpacing = 5
        layout.minimumLineSpacing = 5

        return UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
    }()

How to present a simple alert message in java?

I'll be the first to admit Java can be very verbose, but I don't think this is unreasonable:

JOptionPane.showMessageDialog(null, "My Goodness, this is so concise");

If you statically import javax.swing.JOptionPane.showMessageDialog using:

import static javax.swing.JOptionPane.showMessageDialog;

This further reduces to

showMessageDialog(null, "This is even shorter");

How to preserve aspect ratio when scaling image using one (CSS) dimension in IE6?

I'm glad that worked out, so I guess you had to explicitly set 'auto' on IE6 in order for it to mimic other browsers!

I actually recently found another technique for scaling images, again designed for backgrounds. This technique has some interesting features:

  1. The image aspect ratio is preserved
  2. The image's original size is maintained (that is, it can never shrink only grow)

The markup relies on a wrapper element:

<div id="wrap"><img src="test.png" /></div>

Given the above markup you then use these rules:

#wrap {
  height: 100px;
  width: 100px;
}
#wrap img {
  min-height: 100%;
  min-width: 100%;
}

If you then control the size of wrapper you get the interesting scale effects that I list above.

To be explicit, consider the following base state: A container that is 100x100 and an image that is 10x10. The result is a scaled image of 100x100.

  1. Starting at the base state, the container resized to 20x100, the image stays resized at 100x100.
  2. Starting at the base state, the image is changed to 10x20, the image resizes to 100x200.

So, in other words, the image is always at least as big as the container, but will scale beyond it to maintain it's aspect ratio.

This probably isn't useful for your site, and it doesn't work in IE6. But, it is useful to get a scaled background for your view port or container.

SQL Server r2 installation error .. update Visual Studio 2008 to SP1

Finally, I solved it. Even though the solution is a bit lengthy, I think its the simplest. The solution is as follows:

  1. Install Visual Studio 2008
  2. Install the service Package 1 (SP1)
  3. Install SQL Server 2008 r2

textarea character limit

This works on keyup and paste, it colors the text red when you are almost up to the limit, truncates it when you go over and alerts you to edit your text, which you can do.

var t2= /* textarea reference*/

t2.onkeyup= t2.onpaste= function(e){
    e= e || window.event;
    var who= e.target || e.srcElement;
    if(who){
        var val= who.value, L= val.length;
        if(L> 175){
            who.style.color= 'red';
        }
        else who.style.color= ''
        if(L> 180){
            who.value= who.value.substring(0, 175);
            alert('Your message is too long, please shorten it to 180 characters or less');
            who.style.color= '';
        }
    }
}

How to know that a string starts/ends with a specific string in jQuery?

There is no need of jQuery to do that. You could code a jQuery wrapper but it would be useless so you should better use

var str = "Hello World";

window.alert("Starts with Hello ? " + /^Hello/i.test(str));        

window.alert("Ends with Hello ? " + /Hello$/i.test(str));

as the match() method is deprecated.

PS : the "i" flag in RegExp is optional and stands for case insensitive (so it will also return true for "hello", "hEllo", etc.).

Are there dictionaries in php?

Associative array in PHP actually considered as a dictionary.

An array in PHP is actually an ordered map. A map is a type that associates values to keys. it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more.

<?php
$array = array(
    "foo" => "bar",
    "bar" => "foo",
);

// Using the short array syntax
$array = [
    "foo" => "bar",
    "bar" => "foo",
];
?>

An array is different than a dictionary in that arrays have both an index and a key. Dictionaries only have keys and no index.

Replacing Spaces with Underscores

As of others have explained how to do it using str_replace, you can also use regex to achieve this.

$name = preg_replace('/\s+/', '_', $name);

How might I extract the property values of a JavaScript object into an array?

var dataArray = [];
for(var o in dataObject) {
    dataArray.push(dataObject[o]);
}

JavaScript math, round to two decimal places

    function round(num,dec)
    {
      num = Math.round(num+'e'+dec)
      return Number(num+'e-'+dec)
    }
      //Round to a decimal of your choosing:
    round(1.3453,2)

MySQL error 2006: mysql server has gone away

In my case it was low value of open_files_limit variable, which blocked the access of mysqld to data files.

I checked it with :

mysql> SHOW VARIABLES LIKE 'open%';
+------------------+-------+
| Variable_name    | Value |
+------------------+-------+
| open_files_limit | 1185  |
+------------------+-------+
1 row in set (0.00 sec)

After I changed the variable to big value, our server was alive again :

[mysqld]
open_files_limit = 100000

How can I convert an Integer to localized month name in Java?

There is an issue when you use DateFormatSymbols class for its getMonthName method to get Month by Name it show Month by Number in some Android devices. I have resolved this issue by doing this way:

In String_array.xml

<string-array name="year_month_name">
    <item>January</item>
    <item>February</item>
    <item>March</item>
    <item>April</item>
    <item>May</item>
    <item>June</item>
    <item>July</item>
    <item>August</item>
    <item>September</item>
    <item>October</item>
    <item>November</item>
    <item>December</item>
    </string-array>

In Java class just call this array like this way:

public String[] getYearMonthName() {
        return getResources().getStringArray(R.array.year_month_names);
        //or like 
       //return cntx.getResources().getStringArray(R.array.month_names);
    } 

      String[] months = getYearMonthName(); 
           if (i < months.length) {
            monthShow.setMonthName(months[i] + " " + year);

            }

Happy Coding :)

Access Controller method from another controller in Laravel 5

//In Controller A
public static function function1(){

}

In Controller B, View or anywhere
A::function1();

MySQL SELECT statement for the "length" of the field is greater than 1

Try:

SELECT
    *
FROM
    YourTable
WHERE
    CHAR_LENGTH(Link) > x

GSON - Date format

This won't really work at all. There is no date type in JSON. I would recommend to serialize to ISO8601 back and forth (for format agnostics and JS compat). Consider that you have to know which fields contain dates.

Visual studio equivalent of java System.out

You can use Console.WriteLine() to write out any native type. To see the output you must write console application (like in Java), then the output will be displayed in the Command Prompt, or if you are developing a windows GUI application, in Visual Studio you must turn on "Output" panel (under View) to see the commands output.

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

If the class implements the method directly, it will not use the traits version. Perhaps what you are thinking of is:

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

class MyClass {
    function calc($v) {
        return $v+2;
    }
}

class MyChildClass extends MyClass{
}

class MyTraitChildClass extends MyClass{
    use A;
}

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

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

Because the child classes do not implement the method directly, they will first use that of the trait if there otherwise use that of the parent class.

If you want, the trait can use method in the parent class (assuming you know the method would be there) e.g.

trait A {
    function calc($v) {
        return parent::calc($v*3);
    }
}
// .... other code from above
print (new MyTraitChildClass())->calc(2); // will print 8 (2*3 + 2)

You can also provide for ways to override, but still access the trait method as follows:

trait A {
    function trait_calc($v) {
        return $v*3;
    }
}

class MyClass {
    function calc($v) {
        return $v+2;
    }
}


class MyTraitChildClass extends MyClass{
    use A {
      A::trait_calc as calc;
    }
}


class MySecondTraitChildClass extends MyClass{
    use A {
      A::trait_calc as calc;
    }

    public function calc($v) {
      return $this->trait_calc($v)+.5;
    }
}


print (new MyTraitChildClass())->calc(2); // will print 6
echo "\n";
print (new MySecondTraitChildClass())->calc(2); // will print 6.5

You can see it work at http://sandbox.onlinephpfunctions.com/code/e53f6e8f9834aea5e038aec4766ac7e1c19cc2b5

Batch Extract path and filename from a variable

You can only extract path and filename from (1) a parameter of the BAT itself %1, or (2) the parameter of a CALL %1 or (3) a local FOR variable %%a.


in HELP CALL or HELP FOR you may find more detailed information:

%~1 - expands %1 removing any surrounding quotes (")
%~f1 - expands %1 to a fully qualified path name
%~d1 - expands %1 to a drive letter only
%~p1 - expands %1 to a path only
%~n1 - expands %1 to a file name only
%~x1 - expands %1 to a file extension only
%~s1 - expanded path contains short names only
%~a1 - expands %1 to file attributes
%~t1 - expands %1 to date/time of file
%~z1 - expands %1 to size of file


And then try the following:

Either pass the string to be parsed as a parameter to a CALL

call :setfile ..\Desktop\fs.cfg
echo %file% = %filepath% + %filename%
goto :eof

:setfile
set file=%~f1
set filepath=%~dp1
set filename=%~nx1
goto :eof

or the equivalent, pass the filename as a local FOR variable

for %%a in (..\Desktop\fs.cfg) do (
    set file=%%~fa
    set filepath=%%~dpa
    set filename=%%~nxa
)    
echo %file% = %filepath% + %filename%

How can you program if you're blind?

One place to start is the Blinux project:

http://leb.net/blinux/

That project describes how to get Emacspeak (editor with text-to-speech) and has a lot of other resources.

I worked with one person who's eye sight all but prevented them from using a monitor - they did well with Screen reader software and spent a lot of time using text based applications and the shell.

Wikipedia's list of screen reader packages is another place to start: http://en.wikipedia.org/wiki/List_of_screen_readers

Include an SVG (hosted on GitHub) in MarkDown

The purpose of raw.github.com is to allow users to view the contents of a file, so for text based files this means (for certain content types) you can get the wrong headers and things break in the browser.

When this question was asked (in 2012) SVGs didn't work. Since then Github has implemented various improvements. Now (at least for SVG), the correct Content-Type headers are sent.

Examples

All of the ways stated below will work.

I copied the SVG image from the question to a repo on github in order to create the examples below

Linking to files using relative paths (Works, but obviously only on github.com / github.io)

Code

![Alt text](./controllers_brief.svg)
<img src="./controllers_brief.svg">

Result

See the working example on github.com.

Linking to RAW files

Code

![Alt text](https://raw.github.com/potherca-blog/StackOverflow/master/question.13808020.include-an-svg-hosted-on-github-in-markdown/controllers_brief.svg)
<img src="https://raw.github.com/potherca-blog/StackOverflow/master/question.13808020.include-an-svg-hosted-on-github-in-markdown/controllers_brief.svg">

Result

Alt text

Linking to RAW files using ?sanitize=true

Code

![Alt text](https://raw.github.com/potherca-blog/StackOverflow/master/question.13808020.include-an-svg-hosted-on-github-in-markdown/controllers_brief.svg?sanitize=true)
<img src="https://raw.github.com/potherca-blog/StackOverflow/master/question.13808020.include-an-svg-hosted-on-github-in-markdown/controllers_brief.svg?sanitize=true">

Result

Alt text

Linking to files hosted on github.io

Code

![Alt text](https://potherca-blog.github.io/StackOverflow/question.13808020.include-an-svg-hosted-on-github-in-markdown/controllers_brief.svg)
<img src="https://potherca-blog.github.io/StackOverflow/question.13808020.include-an-svg-hosted-on-github-in-markdown/controllers_brief.svg">

Result

Alt text


Some comments regarding changes that happened along the way:

  • Github has implemented a feature which makes it possible for SVG's to be used with the Markdown image syntax. The SVG image will be sanitized and displayed with the correct HTTP header. Certain tags (like <script>) are removed.

    To view the sanitized SVG or to achieve this effect from other places (i.e. from markdown files not hosted in repos on http://github.com/) simply append ?sanitize=true to the SVG's raw URL.

  • As stated by AdamKatz in the comments, using a source other than github.io can introduce potentially privacy and security risks. See the answer by CiroSantilli and the answer by DavidChambers for more details.

  • The issue to resolve this was opened on Github on October 13th 2015 and was resolved on August 31th 2017

Remove an array element and shift the remaining ones

You just need to overwrite what you're deleting with the next value in the array, propagate that change, and then keep in mind where the new end is:

int array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};

// delete 3 (index 2)
for (int i = 2; i < 8; ++i)
    array[i] = array[i + 1]; // copy next element left

Now your array is {1, 2, 4, 5, 6, 7, 8, 9, 9}. You cannot delete the extra 9 since this is a statically-sized array, you just have to ignore it. This can be done with std::copy:

std::copy(array + 3, // copy everything starting here
          array + 9, // and ending here, not including it,
          array + 2) // to this destination

In C++11, use can use std::move (the algorithm overload, not the utility overload) instead.

More generally, use std::remove to remove elements matching a value:

// remove *all* 3's, return new ending (remaining elements unspecified)
auto arrayEnd = std::remove(std::begin(array), std::end(array), 3);

Even more generally, there is std::remove_if.

Note that the use of std::vector<int> may be more appropriate here, as its a "true" dynamically-allocated resizing array. (In the sense that asking for its size() reflects removed elements.)

What exactly is the meaning of an API?

Searches should include Wikipedia, which is surprisingly good for a number of programming concepts/terms such as Application Programming Interface:

What is an API?

An application programming interface (API) is a particular set of rules ('code') and specifications that software programs can follow to communicate with each other. It serves as an interface between different software programs and facilitates their interaction, similar to the way the user interface facilitates interaction between humans and computers.

How is it used?

The same way any set of rules are used.

When and where is it used?

Depends upon realm and API, naturally. Consider these:

  1. The x86 (IA-32) Instruction Set (very useful ;-)
  2. A BIOS interrupt call
  3. OpenGL which is often exposed as a C library
  4. Core Windows system calls: WinAPI
  5. The Classes and Methods in Ruby's core library
  6. The Document Object Model exposed by browsers to JavaScript
  7. Web services, such as those provided by Facebook's Graph API
  8. An implementation of a protocol such as JNI in Java

Happy coding.

Which is the preferred way to concatenate a string in Python?

The best way of appending a string to a string variable is to use + or +=. This is because it's readable and fast. They are also just as fast, which one you choose is a matter of taste, the latter one is the most common. Here are timings with the timeit module:

a = a + b:
0.11338996887207031
a += b:
0.11040496826171875

However, those who recommend having lists and appending to them and then joining those lists, do so because appending a string to a list is presumably very fast compared to extending a string. And this can be true, in some cases. Here, for example, is one million appends of a one-character string, first to a string, then to a list:

a += b:
0.10780501365661621
a.append(b):
0.1123361587524414

OK, turns out that even when the resulting string is a million characters long, appending was still faster.

Now let's try with appending a thousand character long string a hundred thousand times:

a += b:
0.41823482513427734
a.append(b):
0.010656118392944336

The end string, therefore, ends up being about 100MB long. That was pretty slow, appending to a list was much faster. That that timing doesn't include the final a.join(). So how long would that take?

a.join(a):
0.43739795684814453

Oups. Turns out even in this case, append/join is slower.

So where does this recommendation come from? Python 2?

a += b:
0.165287017822
a.append(b):
0.0132720470428
a.join(a):
0.114929914474

Well, append/join is marginally faster there if you are using extremely long strings (which you usually aren't, what would you have a string that's 100MB in memory?)

But the real clincher is Python 2.3. Where I won't even show you the timings, because it's so slow that it hasn't finished yet. These tests suddenly take minutes. Except for the append/join, which is just as fast as under later Pythons.

Yup. String concatenation was very slow in Python back in the stone age. But on 2.4 it isn't anymore (or at least Python 2.4.7), so the recommendation to use append/join became outdated in 2008, when Python 2.3 stopped being updated, and you should have stopped using it. :-)

(Update: Turns out when I did the testing more carefully that using + and += is faster for two strings on Python 2.3 as well. The recommendation to use ''.join() must be a misunderstanding)

However, this is CPython. Other implementations may have other concerns. And this is just yet another reason why premature optimization is the root of all evil. Don't use a technique that's supposed "faster" unless you first measure it.

Therefore the "best" version to do string concatenation is to use + or +=. And if that turns out to be slow for you, which is pretty unlikely, then do something else.

So why do I use a lot of append/join in my code? Because sometimes it's actually clearer. Especially when whatever you should concatenate together should be separated by spaces or commas or newlines.

How to create a video from images with FFmpeg?

To create frames from video:

ffmpeg\ffmpeg -i %video% test\thumb%04d.jpg -hide_banner

Optional: remove frames you don't want in output video
(more accurate than trimming video with -ss & -t)

Then create video from image/frames eg.:

ffmpeg\ffmpeg -framerate 30 -start_number 56 -i test\thumb%04d.jpg -vf format=yuv420p test/output.mp4

How to download/upload files from/to SharePoint 2013 using CSOM?

Upload a file

Upload a file to a SharePoint site (including SharePoint Online) using File.SaveBinaryDirect Method:

using (var clientContext = new ClientContext(url))
{
     using (var fs = new FileStream(fileName, FileMode.Open))
     {
         var fi = new FileInfo(fileName);
         var list = clientContext.Web.Lists.GetByTitle(listTitle);
         clientContext.Load(list.RootFolder);
         clientContext.ExecuteQuery();
         var fileUrl = String.Format("{0}/{1}", list.RootFolder.ServerRelativeUrl, fi.Name);

         Microsoft.SharePoint.Client.File.SaveBinaryDirect(clientContext, fileUrl, fs, true);
     }
}

Download file

Download file from a SharePoint site (including SharePoint Online) using File.OpenBinaryDirect Method:

using (var clientContext = new ClientContext(url))
{

     var list = clientContext.Web.Lists.GetByTitle(listTitle);
     var listItem = list.GetItemById(listItemId);
     clientContext.Load(list);
     clientContext.Load(listItem, i => i.File);
     clientContext.ExecuteQuery();

     var fileRef = listItem.File.ServerRelativeUrl;
     var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, fileRef);
     var fileName = Path.Combine(filePath,(string)listItem.File.Name);
     using (var fileStream = System.IO.File.Create(fileName))
     {                  
          fileInfo.Stream.CopyTo(fileStream);
     }
}

File Upload in WebView

Working Method from HONEYCOMB (API 11) to Oreo(API 27)
[Not Tested on Pie 9.0]

static WebView mWebView;
private ValueCallback<Uri> mUploadMessage;
public ValueCallback<Uri[]> uploadMessage;
public static final int REQUEST_SELECT_FILE = 100;
private final static int FILECHOOSER_RESULTCODE = 1;

Modified onActivityResult()

@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent)
{
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
    {
        if (requestCode == REQUEST_SELECT_FILE)
        {
            if (uploadMessage == null)
                return;
            uploadMessage.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, intent));
            uploadMessage = null;
        }
    }
    else if (requestCode == FILECHOOSER_RESULTCODE)
    {
        if (null == mUploadMessage)
            return;
    // Use MainActivity.RESULT_OK if you're implementing WebView inside Fragment
    // Use RESULT_OK only if you're implementing WebView inside an Activity
        Uri result = intent == null || resultCode != MainActivity.RESULT_OK ? null : intent.getData();
        mUploadMessage.onReceiveValue(result);
        mUploadMessage = null;
    }
    else
        Toast.makeText(getActivity().getApplicationContext(), "Failed to Upload Image", Toast.LENGTH_LONG).show();
}

Now in onCreate() or onCreateView() paste the following code

    WebSettings mWebSettings = mWebView.getSettings();
    mWebSettings.setJavaScriptEnabled(true);
    mWebSettings.setSupportZoom(false);
    mWebSettings.setAllowFileAccess(true);
    mWebSettings.setAllowContentAccess(true);

mWebView.setWebChromeClient(new WebChromeClient()
{
    // For 3.0+ Devices (Start)
    // onActivityResult attached before constructor
    protected void openFileChooser(ValueCallback uploadMsg, String acceptType)
    {
        mUploadMessage = uploadMsg;
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");
        startActivityForResult(Intent.createChooser(i, "File Browser"), FILECHOOSER_RESULTCODE);
    }
   

    // For Lollipop 5.0+ Devices
    public boolean onShowFileChooser(WebView mWebView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams)
    {
        if (uploadMessage != null) {
            uploadMessage.onReceiveValue(null);
            uploadMessage = null;
        }

        uploadMessage = filePathCallback;

        Intent intent = fileChooserParams.createIntent();
        try
        {
            startActivityForResult(intent, REQUEST_SELECT_FILE);
        } catch (ActivityNotFoundException e)
        {
            uploadMessage = null;
            Toast.makeText(getActivity().getApplicationContext(), "Cannot Open File Chooser", Toast.LENGTH_LONG).show();
            return false;
        }
        return true;
    }
    
    //For Android 4.1 only
    protected void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture)
    {
        mUploadMessage = uploadMsg;
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("image/*");
        startActivityForResult(Intent.createChooser(intent, "File Browser"), FILECHOOSER_RESULTCODE);
    }

    protected void openFileChooser(ValueCallback<Uri> uploadMsg)
    {
        mUploadMessage = uploadMsg;
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");
        startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
    }
});

Getting Date or Time only from a DateTime Object

You can use Instance.ToShortDateString() for the date,
and Instance.ToShortTimeString() for the time to get date and time from the same instance.

How to enter a series of numbers automatically in Excel

If you want to pick cell entries from a list then you have a couple of non-code based options

I would recommend The Data Validation approach where

  • creating a list of your 100 records in a single column,
  • provide a range name to this list,
  • then using Data Validation's List option

sample from Debra's site below, click on the first link above to access it.

Data Validation

Remove all child nodes from a parent?

A other users suggested,

.empty()

is good enought, because it removes all descendant nodes (both tag-nodes and text-nodes) AND all kind of data stored inside those nodes. See the JQuery's API empty documentation.

If you wish to keep data, like event handlers for example, you should use

.detach()

as described on the JQuery's API detach documentation.

The method .remove() could be usefull for similar purposes.

How do you make websites with Java?

While a lot of others should be mentioned, Apache Wicket should be preferred.

Wicket doesn't just reduce lots of boilerplate code, it actually removes it entirely and you can work with excellent separation of business code and markup without mixing the two and a wide variety of other things you can read about from the website.

Preferred way of loading resources in Java

I know it really late for another answer but I just wanted to share what helped me at the end. It will also load resources/files from the absolute path of the file system (not only the classpath's).

public class ResourceLoader {

    public static URL getResource(String resource) {
        final List<ClassLoader> classLoaders = new ArrayList<ClassLoader>();
        classLoaders.add(Thread.currentThread().getContextClassLoader());
        classLoaders.add(ResourceLoader.class.getClassLoader());

        for (ClassLoader classLoader : classLoaders) {
            final URL url = getResourceWith(classLoader, resource);
            if (url != null) {
                return url;
            }
        }

        final URL systemResource = ClassLoader.getSystemResource(resource);
        if (systemResource != null) {
            return systemResource;
        } else {
            try {
                return new File(resource).toURI().toURL();
            } catch (MalformedURLException e) {
                return null;
            }
        }
    }

    private static URL getResourceWith(ClassLoader classLoader, String resource) {
        if (classLoader != null) {
            return classLoader.getResource(resource);
        }
        return null;
    }

}

Cannot resolve symbol AppCompatActivity - Support v7 libraries aren't recognized?

androidX users

Change your minSdkVersion to api level 21.

like this minSdkVersion 21 or build your app with compileSdkVersion 28 and also change targetSdkVersion to targetSdkVersion 28

and you will see v7 error will gone. After that if you face a problem with creating Toolbar or other widget. press Alt+Enter and create a method for it.

Only detect click event on pseudo-element

My answer will work for anyone wanting to click a definitive area of the page. This worked for me on my absolutely-positioned :after

Thanks to this article, I realized (with jQuery) I can use e.pageY and e.pageX instead of worrying about e.offsetY/X and e.clientY/X issue between browsers.

Through my trial and error, I started to use the clientX and clientY mouse coordinates in the jQuery event object. These coordinates gave me the X and Y offset of the mouse relative to the top-left corner of the browser's view port. As I was reading the jQuery 1.4 Reference Guide by Karl Swedberg and Jonathan Chaffer, however, I saw that they often referred to the pageX and pageY coordinates. After checking the updated jQuery documentation, I saw that these were the coordinates standardized by jQuery; and, I saw that they gave me the X and Y offset of the mouse relative to the entire document (not just the view port).

I liked this event.pageY idea because it would always be the same, as it was relative to the document. I can compare it to my :after's parent element using offset(), which returns its X and Y also relative to the document.

Therefore, I can come up with a range of "clickable" region on the entire page that never changes.


Here's my demo on codepen.


or if too lazy for codepen, here's the JS:

* I only cared about the Y values for my example.

var box = $('.box');
// clickable range - never changes
var max = box.offset().top + box.outerHeight();
var min = max - 30; // 30 is the height of the :after

var checkRange = function(y) {
  return (y >= min && y <= max);
}

box.click(function(e){
  if ( checkRange(e.pageY) ) {
    // do click action
    box.toggleClass('toggle');
  }
});

How to set delay in vbscript

A lot of the answers here assume that you're running your VBScript in the Windows Scripting Host (usually wscript.exe or cscript.exe). If you're getting errors like 'Variable is undefined: "WScript"' then you're probably not.

The WScript object is only available if you're running under the Windows Scripting Host, if you're running under another script host, such as Internet Explorer's (and you might be without realising it if you're in something like an HTA) it's not automatically available.

Microsoft's Hey, Scripting Guy! Blog has an article that goes into just this topic How Can I Temporarily Pause a Script in an HTA? in which they use a VBScript setTimeout to create a timer to simulate a Sleep without needing to use CPU hogging loops, etc.

The code used is this:

<script language = "VBScript">

    Dim dtmStartTime

    Sub Test
        dtmStartTime = Now 
        idTimer = window.setTimeout("PausedSection", 5000, "VBScript")
    End Sub

    Sub PausedSection
        Msgbox dtmStartTime & vbCrLf & Now
        window.clearTimeout(idTimer)
    End Sub

</script>

<body>
    <input id=runbutton  type="button" value="Run Button" onClick="Test">
</body>

See the linked blog post for the full explanation, but essentially when the button is clicked it creates a timer that fires 5,000 milliseconds from now, and when it fires runs the VBScript sub-routine called "PausedSection" which clears the timer, and runs whatever code you want it to.

How to check if object has been disposed in C#

A good way is to derive from TcpClient and override the Disposing(bool) method:

class MyClient : TcpClient {
    public bool IsDead { get; set; }
    protected override void Dispose(bool disposing) {
        IsDead = true;
        base.Dispose(disposing);
    }
}

Which won't work if the other code created the instance. Then you'll have to do something desperate like using Reflection to get the value of the private m_CleanedUp member. Or catch the exception.

Frankly, none is this is likely to come to a very good end. You really did want to write to the TCP port. But you won't, that buggy code you can't control is now in control of your code. You've increased the impact of the bug. Talking to the owner of that code and working something out is by far the best solution.

EDIT: A reflection example:

using System.Reflection;
public static bool SocketIsDisposed(Socket s)
{
   BindingFlags bfIsDisposed = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetProperty;
   // Retrieve a FieldInfo instance corresponding to the field
   PropertyInfo field = s.GetType().GetProperty("CleanedUp", bfIsDisposed);
   // Retrieve the value of the field, and cast as necessary
   return (bool)field.GetValue(s, null);
}

Is there an easy way to check the .NET Framework version?

This class allows your application to throw out a graceful notification message rather than crash and burn if it couldn't find the proper .NET version. All you need to do is this in your main code:

[STAThread]
static void Main(string[] args)
{
    if (!DotNetUtils.IsCompatible())
        return;
   . . .
}

By default it takes 4.5.2, but you can tweak it to your liking, the class (feel free to replace MessageBox with Console):

Updated for 4.8:

public class DotNetUtils
{
    public enum DotNetRelease
    {
        NOTFOUND,
        NET45,
        NET451,
        NET452,
        NET46,
        NET461,
        NET462,
        NET47,
        NET471,
        NET472,
        NET48,
    }

    public static bool IsCompatible(DotNetRelease req = DotNetRelease.NET452)
    {
        DotNetRelease r = GetRelease();
        if (r < req)
        {
            MessageBox.Show(String.Format("This this application requires {0} or greater.", req.ToString()));
            return false;
        }
        return true;
    }

    public static DotNetRelease GetRelease(int release = default(int))
    {
        int r = release != default(int) ? release : GetVersion();
        if (r >= 528040) return DotNetRelease.NET48;
        if (r >= 461808) return DotNetRelease.NET472;
        if (r >= 461308) return DotNetRelease.NET471;
        if (r >= 460798) return DotNetRelease.NET47;
        if (r >= 394802) return DotNetRelease.NET462;
        if (r >= 394254) return DotNetRelease.NET461;
        if (r >= 393295) return DotNetRelease.NET46;
        if (r >= 379893) return DotNetRelease.NET452;
        if (r >= 378675) return DotNetRelease.NET451;
        if (r >= 378389) return DotNetRelease.NET45;
        return DotNetRelease.NOTFOUND;
    }

    public static int GetVersion()
    {
        int release = 0;
        using (RegistryKey key = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32)
                                            .OpenSubKey("SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v4\\Full\\"))
        {
            release = Convert.ToInt32(key.GetValue("Release"));
        }
        return release;
    }
}

Easily extendable when they add a new version later on. I didn't bother with anything before 4.5 but you get the idea.

Error 'LINK : fatal error LNK1123: failure during conversion to COFF: file invalid or corrupt' after installing Visual Studio 2012 Release Preview

I had the same problem with Microsoft Visual Studio 2010 Ultimate and it was solved by the method described in this youtube video

The video suggests to rename the file cvtres.exe in C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin (in my Win7X64 matchine) to cvtres-old.exe

How can I show line numbers in Eclipse?

Window ? Preferences ? General ? Editors ? Text Editors ? Show line numbers.


Edit: I wrote this long ago but as @ArtOfWarfar and @voidstate mentioned you can now simply:

Right click the gutter and select "Show Line Numbers":

Pointers in JavaScript?

I have found a slightly different way implement pointers that is perhaps more general and easier to understand from a C perspective (and thus fits more into the format of the users example).

In JavaScript, like in C, array variables are actually just pointers to the array, so you can use an array as exactly the same as declaring a pointer. This way, all pointers in your code can be used the same way, despite what you named the variable in the original object.

It also allows one to use two different notations referring to the address of the pointer and what is at the address of the pointer.

Here is an example (I use the underscore to denote a pointer):

var _x = [ 10 ];

function foo(_a){
    _a[0] += 10;
}

foo(_x);

console.log(_x[0]);

Yields

output: 20

Copy a git repo without history

Use the following command:

git clone --depth <depth> -b <branch> <repo_url>

Where:

  • depth is the amount of commits you want to include. i.e. if you just want the latest commit use git clone --depth 1
  • branch is the name of the remote branch that you want to clone from. i.e. if you want the last 3 commits from master branch use git clone --depth 3 -b master
  • repo_url is the url of your repository

How to install Boost on Ubuntu

Install libboost-all-dev by entering the following commands in the terminal

Step 1

Update package repositories and get latest package information.

sudo apt update -y

Step 2

Install the packages and dependencies with -y flag .

sudo apt install -y libboost-all-dev

Now that you have your libboost-all-dev installed source: https://linuxtutorial.me/ubuntu/focal/libboost-all-dev/

jQuery - hashchange event

Here is updated version of @johnny.rodgers

Hope helps someone.

// ie9 ve ie7 return true but never fire, lets remove ie less then 10
if(("onhashchange" in window) && navigator.userAgent.toLowerCase().indexOf('msie') == -1){ // event supported?
    window.onhashchange = function(){
        var url = window.location.hash.substring(1);
        alert(url);
    }
}
else{ // event not supported:
    var storedhash = window.location.hash;
    window.setInterval(function(){
        if(window.location.hash != storedhash){
            storedhash = window.location.hash;
            alert(url);
        }
    }, 100);
}

Reading specific XML elements from XML file

XDocument xdoc = XDocument.Load(path_to_xml);
var word = xdoc.Elements("word")
               .SingleOrDefault(w => (string)w.Element("category") == "verb");

This query will return whole word XElement. If there is more than one word element with category verb, than you will get an InvalidOperationException. If there is no elements with category verb, result will be null.

Mail not sending with PHPMailer over SSL using SMTP

First, Google created the "use less secure accounts method" function:

https://myaccount.google.com/security

Then created the another permission:

https://accounts.google.com/b/0/DisplayUnlockCaptcha

Hope it helps.

WPF What is the correct way of using SVG files as icons in WPF

Use the SvgImage or the SvgImageConverter extensions, the SvgImageConverter supports binding. See the following link for samples demonstrating both extensions.

https://github.com/ElinamLLC/SharpVectors/tree/master/TutorialSamples/ControlSamplesWpf

multi line comment vb.net in Visual studio 2010

multi comment in vb.net

VB.NET doesn't support for multi line comment.

The only way to do multi-line comments in VB.NET is to do a lot of single line comments(').

Or just highlight the whole code and just use (Ctrl+E,C), (Ctrl+E,U) to comment or uncomment.

Only in c# /* */

Or in ASP.NET html source using <!-- -->.

HttpContext.Current.Request.Url.Host what it returns?

Yes, as long as the url you type into the browser www.someshopping.com and you aren't using url rewriting then

string currentURL = HttpContext.Current.Request.Url.Host;

will return www.someshopping.com

Note the difference between a local debugging environment and a production environment

Download text/csv content as files from server in Angular

This is what worked for me for IE 11+, Firefox and Chrome. In safari it downloads a file but as unknown and the filename is not set.

if (window.navigator.msSaveOrOpenBlob) {
    var blob = new Blob([csvDataString]);  //csv data string as an array.
    // IE hack; see http://msdn.microsoft.com/en-us/library/ie/hh779016.aspx
    window.navigator.msSaveBlob(blob, fileName);
} else {
    var anchor = angular.element('<a/>');
    anchor.css({display: 'none'}); // Make sure it's not visible
    angular.element(document.body).append(anchor); // Attach to document for FireFox

    anchor.attr({
        href: 'data:attachment/csv;charset=utf-8,' + encodeURI(csvDataString),
        target: '_blank',
        download: fileName
})[0].click();
anchor.remove();
}

How can I check the size of a collection within a Django template?

If you're using a recent Django, changelist 9530 introduced an {% empty %} block, allowing you to write

{% for athlete in athlete_list %}
  ...
{% empty %}
  No athletes
{% endfor %}

Useful when the something that you want to do involves special treatment for lists that might be empty.

'mat-form-field' is not a known element - Angular 5 & Material2

When using MatAutocompleteModule in your angular application, you need to import Input Module also in app.module.ts

Please import below:

import { MatInputModule } from '@angular/material';

What does "O(1) access time" mean?

Every answer currently responding to this question tells you that the O(1) means constant time (whatever it happens to measuring; could be runtime, number of operations, etc.). This is not accurate.

To say that runtime is O(1) means that there is a constant c such that the runtime is bounded above by c, independent of the input. For example, returning the first element of an array of n integers is O(1):

int firstElement(int *a, int n) {
    return a[0];
}

But this function is O(1) too:

int identity(int i) {
    if(i == 0) {
        sleep(60 * 60 * 24 * 365);
    }
    return i;
}

The runtime here is bounded above by 1 year, but most of the time the runtime is on the order of nanoseconds.

To say that runtime is O(n) means that there is a constant c such that the runtime is bounded above by c * n, where n measures the size of the input. For example, finding the number of occurrences of a particular integer in an unsorted array of n integers by the following algorithm is O(n):

int count(int *a, int n, int item) {
    int c = 0;
    for(int i = 0; i < n; i++) {
        if(a[i] == item) c++;
    }
    return c;
}

This is because we have to iterate through the array inspecting each element one at a time.

Is it possible to put a ConstraintLayout inside a ScrollView?

Anyone who has set below property to

ScrollView:: android:fillViewport="true"

constraint layout: android:layout_height="wrap_content"

And it's still not working then make sure then you have not set the Inner scrollable layout (RecycleView) bottom constraint to bottom of the parent.

Add below lines of code:

android:nestedScrollingEnabled="false"
android:layout_height="wrap_content"

Make sure to remove below constraint:

app:layout_constraintBottom_toBottomOf="parent"

Full code

   <androidx.core.widget.NestedScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true">

<androidx.constraintlayout.widget.ConstraintLayout
    android:id="@+id/selectHubLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:context=".ui.hubs.SelectHubFragment">

    <include
        android:id="@+id/include"
        layout="@layout/signup_hub_selection_details"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rv_HubSelection"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:nestedScrollingEnabled="false"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/include" />
</androidx.constraintlayout.widget.ConstraintLayout>

How to override and extend basic Django admin templates?

I agree with Chris Pratt. But I think it's better to create the symlink to original Django folder where the admin templates place in:

ln -s /usr/local/lib/python2.7/dist-packages/django/contrib/admin/templates/admin/ templates/django_admin

and as you can see it depends on python version and the folder where the Django installed. So in future or on a production server you might need to change the path.

Creating temporary files in Android

Best practices on internal and external temporary files:

Internal Cache

If you'd like to cache some data, rather than store it persistently, you should use getCacheDir() to open a File that represents the internal directory where your application should save temporary cache files.

When the device is low on internal storage space, Android may delete these cache files to recover space. However, you should not rely on the system to clean up these files for you. You should always maintain the cache files yourself and stay within a reasonable limit of space consumed, such as 1MB. When the user uninstalls your application, these files are removed.

External Cache

To open a File that represents the external storage directory where you should save cache files, call getExternalCacheDir(). If the user uninstalls your application, these files will be automatically deleted.

Similar to ContextCompat.getExternalFilesDirs(), mentioned above, you can also access a cache directory on a secondary external storage (if available) by calling ContextCompat.getExternalCacheDirs().

Tip: To preserve file space and maintain your app's performance, it's important that you carefully manage your cache files and remove those that aren't needed anymore throughout your app's lifecycle.

How can we print line numbers to the log in java

you can use -> Reporter.log("");

jQuery: Wait/Delay 1 second without executing code

If you are using ES6 features and you're in an async function, you can effectively halt the code execution for a certain time with this function:

const delay = millis => new Promise((resolve, reject) => {
  setTimeout(_ => resolve(), millis)
});

This is how you use it:

await delay(5000);

It will stall for the requested amount of milliseconds, but only if you're in an async function. Example below:

const myFunction = async function() {
  // first code block ...

  await delay(5000);

  // some more code, executed 5 seconds after the first code block finishes
}

Circular (or cyclic) imports in Python

There was a really good discussion on this over at comp.lang.python last year. It answers your question pretty thoroughly.

Imports are pretty straightforward really. Just remember the following:

'import' and 'from xxx import yyy' are executable statements. They execute when the running program reaches that line.

If a module is not in sys.modules, then an import creates the new module entry in sys.modules and then executes the code in the module. It does not return control to the calling module until the execution has completed.

If a module does exist in sys.modules then an import simply returns that module whether or not it has completed executing. That is the reason why cyclic imports may return modules which appear to be partly empty.

Finally, the executing script runs in a module named __main__, importing the script under its own name will create a new module unrelated to __main__.

Take that lot together and you shouldn't get any surprises when importing modules.

Laravel eloquent update record without loading from database

The common way is to load the row to update:

$post = Post::find($id);

I your case

$post = Post::find(3);
$post->title = "Updated title";
$post->save();

But in one step (just update) you can do this:

$affectedRows = Post::where("id", 3)->update(["title" => "Updated title"]);

How do I to insert data into an SQL table using C# as well as implement an upload function?

using System;
using System.Data;
using System.Data.SqlClient;

namespace InsertingData
{
    class sqlinsertdata
    {
        static void Main(string[] args)
        {
            try
            { 
            SqlConnection conn = new SqlConnection("Data source=USER-PC; Database=Emp123;User Id=sa;Password=sa123");
            conn.Open();
                SqlCommand cmd = new SqlCommand("insert into <Table Name>values(1,'nagendra',10000);",conn);
                cmd.ExecuteNonQuery();
                Console.WriteLine("Inserting Data Successfully");
                conn.Close();
        }
            catch(Exception e)
            {
                Console.WriteLine("Exception Occre while creating table:" + e.Message + "\t"  + e.GetType());
            }
            Console.ReadKey();

    }
    }
}

Vertical Align Center in Bootstrap 4

Place your content within a flexbox container that is 100% high i.e h-100. Then justify the content centrally by using justify-content-center class.

<section class="container h-100 d-flex justify-content-center">
    <div class="jumbotron my-auto">
        <h1 class="display-3">Hello, Malawi!</h1>
    </div>
</section>

How to highlight a selected row in ngRepeat?

Each row has an ID. All you have to do is to send this ID to the function setSelected(), store it (in $scope.idSelectedVote for instance), and then check for each row if the selected ID is the same as the current one. Here is a solution (see the documentation for ngClass, if needed):

$scope.idSelectedVote = null;
$scope.setSelected = function (idSelectedVote) {
   $scope.idSelectedVote = idSelectedVote;
};
<ul ng-repeat="vote in votes" ng-click="setSelected(vote.id)" ng-class="{selected: vote.id === idSelectedVote}">
    ...
</ul>

Plunker

Importing CSV with line breaks in Excel 2007

This is for Excel 2016:

Just had the same problem with line breaks inside a csv file with the Excel Wizard.

Afterwards I was trying it with the "New Query" Feature: Data -> New Query -> From File -> From CSV -> Choose the File -> Import -> Load

It was working perfectly and a very quick workaround for all of you that have the same problem.

Saving results with headers in Sql Server Management Studio

Got here when looking for a way to make SSMS properly escape CSV separators when exporting results.

Guess what? - this is actually an option, and it is unchecked by default. So by default, you get broken CSV files (and may not even realize it, esp. if your export is large and your data doesn't have commas normally) - and you have to go in and click a checkbox so that your CSVs export correctly!

To me, this seems like a monumentally stupid design choice and an apt metaphor for Microsoft's approach to software in general ("broken by default, requires meaningless ritualistic actions to make trivial functionality work").

But I will gladly donate $100 to a charity of respondent's choice if someone can give me one valid real-life reason for this option to exist (i.e., an actual scenario where it was useful).

css3 text-shadow in IE9

Yes, but not how you would imagine. According to caniuse (a very good resource) there is no support and no polyfill available for adding text-shadow support to IE9. However, IE has their own proprietary text shadow (detailed here).

Example implementation, taken from their website (works in IE5.5 through IE9):

p.shadow { 
    filter: progid:DXImageTransform.Microsoft.Shadow(color=#0000FF,direction=45);
}

For cross-browser compatibility and future-proofing of code, remember to also use the CSS3 standard text-shadow property (detailed here). This is especially important considering that IE10 has officially announced their intent to drop support for legacy dx filters. Going forward, IE10+ will only support the CSS3 standard text-shadow.

What are the differences between char literals '\n' and '\r' in Java?

\n is for unix
\r is for mac (before OS X)
\r\n is for windows format

you can also take System.getProperty("line.separator")

it will give you the appropriate to your OS

Returning a regex match in VBA (excel)

You need to access the matches in order to get at the SDI number. Here is a function that will do it (assuming there is only 1 SDI number per cell).

For the regex, I used "sdi followed by a space and one or more numbers". You had "sdi followed by a space and zero or more numbers". You can simply change the + to * in my pattern to go back to what you had.

Function ExtractSDI(ByVal text As String) As String

Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")

RE.pattern = "(sdi \d+)"
RE.Global = True
RE.IgnoreCase = True
Set allMatches = RE.Execute(text)

If allMatches.count <> 0 Then
    result = allMatches.Item(0).submatches.Item(0)
End If

ExtractSDI = result

End Function

If a cell may have more than one SDI number you want to extract, here is my RegexExtract function. You can pass in a third paramter to seperate each match (like comma-seperate them), and you manually enter the pattern in the actual function call:

Ex) =RegexExtract(A1, "(sdi \d+)", ", ")

Here is:

Function RegexExtract(ByVal text As String, _
                      ByVal extract_what As String, _
                      Optional seperator As String = "") As String

Dim i As Long, j As Long
Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")

RE.pattern = extract_what
RE.Global = True
Set allMatches = RE.Execute(text)

For i = 0 To allMatches.count - 1
    For j = 0 To allMatches.Item(i).submatches.count - 1
        result = result & seperator & allMatches.Item(i).submatches.Item(j)
    Next
Next

If Len(result) <> 0 Then
    result = Right(result, Len(result) - Len(seperator))
End If

RegexExtract = result

End Function

*Please note that I have taken "RE.IgnoreCase = True" out of my RegexExtract, but you could add it back in, or even add it as an optional 4th parameter if you like.

Can I use wget to check , but not download

Yes easy.

wget --spider www.bluespark.co.nz

That will give you

Resolving www.bluespark.co.nz... 210.48.79.121
Connecting to www.bluespark.co.nz[210.48.79.121]:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: unspecified [text/html]
200 OK

Display/Print one column from a DataFrame of Series in Pandas

By using to_string

print(df.Name.to_string(index=False))


 Adam
  Bob
Cathy

How to declare an array of objects in C#

you need to initialize the object elements of the array.

GameObject[] houses = new GameObject[200];

for (int i=0;`i<house` i<houses.length; i++)
{ houses[i] = new GameObject();}

Of course you initialize elements selectively using different constructors anywhere else before you reference them.

Get LatLng from Zip Code - Google Maps API

Here is the most reliable way to get the lat/long from zip code (i.e. postal code):

https://maps.googleapis.com/maps/api/geocode/json?key=YOUR_API_KEY&components=postal_code:97403

How to run PowerShell in CMD

I'd like to add the following to Shay Levy's correct answer: You can make your life easier if you create a little batch script run.cmd to launch your powershell script:

@echo off & setlocal
set batchPath=%~dp0
powershell.exe -noexit -file "%batchPath%SQLExecutor.ps1" "MY-PC"

Put it in the same path as SQLExecutor.ps1 and from now on you can run it by simply double-clicking on run.cmd.


Note:

  • If you require command line arguments inside the run.cmd batch, simply pass them as %1 ... %9 (or use %* to pass all parameters) to the powershell script, i.e.
    powershell.exe -noexit -file "%batchPath%SQLExecutor.ps1" %*

  • The variable batchPath contains the executing path of the batch file itself (this is what the expression %~dp0 is used for). So you just put the powershell script in the same path as the calling batch file.

Write a file in UTF-8 using FileWriter (Java)?

Safe Encoding Constructors

Getting Java to properly notify you of encoding errors is tricky. You must use the most verbose and, alas, the least used of the four alternate contructors for each of InputStreamReader and OutputStreamWriter to receive a proper exception on an encoding glitch.

For file I/O, always make sure to always use as the second argument to both OutputStreamWriter and InputStreamReader the fancy encoder argument:

  Charset.forName("UTF-8").newEncoder()

There are other even fancier possibilities, but none of the three simpler possibilities work for exception handing. These do:

 OutputStreamWriter char_output = new OutputStreamWriter(
     new FileOutputStream("some_output.utf8"),
     Charset.forName("UTF-8").newEncoder() 
 );

 InputStreamReader char_input = new InputStreamReader(
     new FileInputStream("some_input.utf8"),
     Charset.forName("UTF-8").newDecoder() 
 );

As for running with

 $ java -Dfile.encoding=utf8 SomeTrulyRemarkablyLongcLassNameGoeShere

The problem is that that will not use the full encoder argument form for the character streams, and so you will again miss encoding problems.

Longer Example

Here’s a longer example, this one managing a process instead of a file, where we promote two different input bytes streams and one output byte stream all to UTF-8 character streams with full exception handling:

 // this runs a perl script with UTF-8 STD{IN,OUT,ERR} streams
 Process
 slave_process = Runtime.getRuntime().exec("perl -CS script args");

 // fetch his stdin byte stream...
 OutputStream
 __bytes_into_his_stdin  = slave_process.getOutputStream();

 // and make a character stream with exceptions on encoding errors
 OutputStreamWriter
   chars_into_his_stdin  = new OutputStreamWriter(
                             __bytes_into_his_stdin,
         /* DO NOT OMIT! */  Charset.forName("UTF-8").newEncoder()
                         );

 // fetch his stdout byte stream...
 InputStream
 __bytes_from_his_stdout = slave_process.getInputStream();

 // and make a character stream with exceptions on encoding errors
 InputStreamReader
   chars_from_his_stdout = new InputStreamReader(
                             __bytes_from_his_stdout,
         /* DO NOT OMIT! */  Charset.forName("UTF-8").newDecoder()
                         );

// fetch his stderr byte stream...
 InputStream
 __bytes_from_his_stderr = slave_process.getErrorStream();

 // and make a character stream with exceptions on encoding errors
 InputStreamReader
   chars_from_his_stderr = new InputStreamReader(
                             __bytes_from_his_stderr,
         /* DO NOT OMIT! */  Charset.forName("UTF-8").newDecoder()
                         );

Now you have three character streams that all raise exception on encoding errors, respectively called chars_into_his_stdin, chars_from_his_stdout, and chars_from_his_stderr.

This is only slightly more complicated that what you need for your problem, whose solution I gave in the first half of this answer. The key point is this is the only way to detect encoding errors.

Just don’t get me started about PrintStreams eating exceptions.

How to sort a Ruby Hash by number value?

That's not the behavior I'm seeing:

irb(main):001:0> metrics = {"sitea.com" => 745, "siteb.com" => 9, "sitec.com" =>
 10 }
=> {"siteb.com"=>9, "sitec.com"=>10, "sitea.com"=>745}
irb(main):002:0> metrics.sort {|a1,a2| a2[1]<=>a1[1]}
=> [["sitea.com", 745], ["sitec.com", 10], ["siteb.com", 9]]

Is it possible that somewhere along the line your numbers are being converted to strings? Is there more code you're not posting?

Adding image to JFrame

As martijn-courteaux said, create a custom component it's the better option. In C# exists a component called PictureBox and I tried to create this component for Java, here is the code:

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComponent;

public class JPictureBox extends JComponent {

    private Icon icon = null;
    private final Dimension dimension = new Dimension(100, 100);
    private Image image = null;
    private ImageIcon ii = null;
    private SizeMode sizeMode = SizeMode.STRETCH;
    private int newHeight, newWidth, originalHeight, originalWidth;

    public JPictureBox() {
        JPictureBox.this.setPreferredSize(dimension);
        JPictureBox.this.setOpaque(false);
        JPictureBox.this.setSizeMode(SizeMode.STRETCH);
    }

    @Override
    public void paintComponent(Graphics g) {
        if (ii != null) {
            switch (getSizeMode()) {
                case NORMAL:
                    g.drawImage(image, 0, 0, ii.getIconWidth(), ii.getIconHeight(), null);
                    break;
                case ZOOM:
                    aspectRatio();
                    g.drawImage(image, 0, 0, newWidth, newHeight, null);
                    break;
                case STRETCH:
                    g.drawImage(image, 0, 0, this.getWidth(), this.getHeight(), null);
                    break;
                case CENTER:
                    g.drawImage(image, (int) (this.getWidth() / 2) - (int) (ii.getIconWidth() / 2), (int) (this.getHeight() / 2) - (int) (ii.getIconHeight() / 2), ii.getIconWidth(), ii.getIconHeight(), null);
                    break;
                default:
                    g.drawImage(image, 0, 0, this.getWidth(), this.getHeight(), null);
            }
        }
    }

    public Icon getIcon() {
        return icon;
    }

    public void setIcon(Icon icon) {
        this.icon = icon;
        ii = (ImageIcon) icon;
        image = ii.getImage();
        originalHeight = ii.getIconHeight();
        originalWidth = ii.getIconWidth();
    }

    public SizeMode getSizeMode() {
        return sizeMode;
    }

    public void setSizeMode(SizeMode sizeMode) {
        this.sizeMode = sizeMode;
    }

    public enum SizeMode {
        NORMAL,
        STRETCH,
        CENTER,
        ZOOM
    }

    private void aspectRatio() {
        if (ii != null) {
            newHeight = this.getHeight();
            newWidth = (originalWidth * newHeight) / originalHeight;
        }
    }

}

If you want to add an image, choose the JPictureBox, after that go to Properties and find "icon" property and select an image. If you want to change the sizeMode property then choose the JPictureBox, after that go to Properties and find "sizeMode" property, you can choose some values:

  • NORMAL value, the image is positioned in the upper-left corner of the JPictureBox.
  • STRETCH value causes the image to stretch or shrink to fit the JPictureBox.
  • ZOOM value causes the image to be stretched or shrunk to fit the JPictureBox; however, the aspect ratio in the original is maintained.
  • CENTER value causes the image to be centered in the client area.

If you want to learn more about this topic, you can check this video.

Also you can see the code on Gitlab or Github.

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

Thank you! I have recently converted to python 3 and have been frustrated by using readlines(0) to read large files. This solved the problem. But to get each line, I had to do a couple extra steps. Each line was preceded by a "b'" which I guess that it was in binary format. Using "decode(utf-8)" changed it ascii.

Then I had to remove a "=\n" in the middle of each line.

Then I split the lines at the new line.

b_data=(fh.read(ele[1]))#endat This is one chunk of ascii data in binary format
        a_data=((binascii.b2a_qp(b_data)).decode('utf-8')) #Data chunk in 'split' ascii format
        data_chunk = (a_data.replace('=\n','').strip()) #Splitting characters removed
        data_list = data_chunk.split('\n')  #List containing lines in chunk
        #print(data_list,'\n')
        #time.sleep(1)
        for j in range(len(data_list)): #iterate through data_list to get each item 
            i += 1
            line_of_data = data_list[j]
            print(line_of_data)

Here is the code starting just above "print data" in Arohi's code.

How can I ping a server port with PHP?

socket_create needs to be run as root on a UNIX system with;

$socket = socket_create(AF_UNIX, SOCK_STREAM, 0);

What exactly does Double mean in java?

In a comment on @paxdiablo's answer, you asked:

"So basically, is it better to use Double than Float?"

That is a complicated question. I will deal with it in two parts


Deciding between double versus float

On the one hand, a double occupies 8 bytes versus 4 bytes for a float. If you have many of them, this may be significant, though it may also have no impact. (Consider the case where the values are in fields or local variables on a 64bit machine, and the JVM aligns them on 64 bit boundaries.) Additionally, floating point arithmetic with double values is typically slower than with float values ... though once again this is hardware dependent.

On the other hand, a double can represent larger (and smaller) numbers than a float and can represent them with more than twice the precision. For the details, refer to Wikipedia.

The tricky question is knowing whether you actually need the extra range and precision of a double. In some cases it is obvious that you need it. In others it is not so obvious. For instance if you are doing calculations such as inverting a matrix or calculating a standard deviation, the extra precision may be critical. On the other hand, in some cases not even double is going to give you enough precision. (And beware of the trap of expecting float and double to give you an exact representation. They won't and they can't!)

There is a branch of mathematics called Numerical Analysis that deals with the effects of rounding error, etc in practical numerical calculations. It used to be a standard part of computer science courses ... back in the 1970's.


Deciding between Double versus Float

For the Double versus Float case, the issues of precision and range are the same as for double versus float, but the relative performance measures will be slightly different.

  • A Double (on a 32 bit machine) typically takes 16 bytes + 4 bytes for the reference, compared with 12 + 4 bytes for a Float. Compare this to 8 bytes versus 4 bytes for the double versus float case. So the ratio is 5 to 4 versus 2 to 1.

  • Arithmetic involving Double and Float typically involves dereferencing the pointer and creating a new object to hold the result (depending on the circumstances). These extra overheads also affect the ratios in favor of the Double case.


Correctness

Having said all that, the most important thing is correctness, and this typically means getting the most accurate answer. And even if accuracy is not critical, it is usually not wrong to be "too accurate". So, the simple "rule of thumb" is to use double in preference to float, UNLESS there is an overriding performance requirement, AND you have solid evidence that using float will make a difference with respect to that requirement.

Pass a reference to DOM object with ng-click

The angular way is shown in the angular docs :)

https://docs.angularjs.org/api/ng/directive/ngReadonly

Here is the example they use:

<body>
    Check me to make text readonly: <input type="checkbox" ng-model="checked"><br/>
    <input type="text" ng-readonly="checked" value="I'm Angular"/>
</body>

Basically the angular way is to create a model object that will hold whether or not the input should be readonly and then set that model object accordingly. The beauty of angular is that most of the time you don't need to do any dom manipulation. You just have angular render the view they way your model is set (let angular do the dom manipulation for you and keep your code clean).

So basically in your case you would want to do something like below or check out this working example.

<button ng-click="isInput1ReadOnly = !isInput1ReadOnly">Click Me</button>
<input type="text" ng-readonly="isInput1ReadOnly" value="Angular Rules!"/>

SQL Order By Count

You need to aggregate the data first, this can be done using the GROUP BY clause:

SELECT Group, COUNT(*)
FROM table
GROUP BY Group
ORDER BY COUNT(*) DESC

The DESC keyword allows you to show the highest count first, ORDER BY by default orders in ascending order which would show the lowest count first.

How to print a number with commas as thousands separators in JavaScript

var formatNumber = function (number) {
  var splitNum;
  number = Math.abs(number);
  number = number.toFixed(2);
  splitNum = number.split('.');
  splitNum[0] = splitNum[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  return splitNum.join(".");
}

EDIT: The function only work with positive number. for exmaple:

var number = -123123231232;
formatNumber(number)

Output: "123,123,231,232"

But to answer the question above toLocaleString() method just solves the problem.

var number = 123123231232;
    number.toLocaleString()

Output: "123,123,231,232"

Cheer!

Android runOnUiThread explanation

If you already have the data "for (Parcelable currentHeadline : allHeadlines)," then why are you doing that in a separate thread?

You should poll the data in a separate thread, and when it's finished gathering it, then call your populateTables method on the UI thread:

private void populateTable() {
    runOnUiThread(new Runnable(){
        public void run() {
            //If there are stories, add them to the table
            for (Parcelable currentHeadline : allHeadlines) {
                addHeadlineToTable(currentHeadline);
            }
            try {
                dialog.dismiss();
            } catch (final Exception ex) {
                Log.i("---","Exception in thread");
            }
        }
    });
}

NumPy ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

The error message explains it pretty well:

ValueError: The truth value of an array with more than one element is ambiguous. 
Use a.any() or a.all()

What should bool(np.array([False, False, True])) return? You can make several plausible arguments:

(1) True, because bool(np.array(x)) should return the same as bool(list(x)), and non-empty lists are truelike;

(2) True, because at least one element is True;

(3) False, because not all elements are True;

and that's not even considering the complexity of the N-d case.

So, since "the truth value of an array with more than one element is ambiguous", you should use .any() or .all(), for example:

>>> v = np.array([1,2,3]) == np.array([1,2,4])
>>> v
array([ True,  True, False], dtype=bool)
>>> v.any()
True
>>> v.all()
False

and you might want to consider np.allclose if you're comparing arrays of floats:

>>> np.allclose(np.array([1,2,3+1e-8]), np.array([1,2,3]))
True

Extract source code from .jar file

Steps to get sources of a jar file as a zip :

  1. Download JD-GUI from http://java-decompiler.github.io/ and save it at any location on your system.

  2. Drag and drop the jar or open .jar file for which you want the sources on the JD.

  3. Java Decompiler will open with all the package structure in a tree format.

  4. Click on File menu and select save jar sources. It will save the sources as a zip with the same name as the jar.

Example:-

enter image description here

We can use Eclipse IDE for Java EE Developers as well for update/extract code if require.

From eclipse chose Import Jar and then select jar which you need. Follow instruction as per image below

enter image description here

enter image description here

How to set Python's default version to 3.x on OS X?

Changing the default python executable's version system-wide could break some applications that depend on python2.

However, you can alias the commands in most shells, Since the default shells in macOS (bash in 10.14 and below; zsh in 10.15) share a similar syntax. You could put alias python='python3' in your ~/.profile, and then source ~/.profile in your ~/.bash_profile and/or your~/.zsh_profile with a line like:

[ -e ~/.profile ] && . ~/.profile

This way, your alias will work across shells.

With this, python command now invokes python3. If you want to invoke the "original" python (that refers to python2) on occasion, you can use command python, which will leaving the alias untouched, and works in all shells.

If you launch interpreters more often (I do), you can always create more aliases to add as well, i.e.:

alias 2='python2'
alias 3='python3'

Tip: For scripts, instead of using a shebang like:

#!/usr/bin/env python

use:

#!/usr/bin/env python3

This way, the system will use python3 for running python executables.

Postman - How to see request with headers and body data with variables substituted

If, like me, you are still using the browser version (which will be deprecated soon), have you tried the "Code" button?

enter image description here

This should generate a snippet which contains the entire request Postman is firing. You can even choose the language for the snippet. I find it quite handy when I need to debug stuff.

Hope this helps.

Constants in Objective-C

If you like namespace constant, you can leverage struct, Friday Q&A 2011-08-19: Namespaced Constants and Functions

// in the header
extern const struct MANotifyingArrayNotificationsStruct
{
    NSString *didAddObject;
    NSString *didChangeObject;
    NSString *didRemoveObject;
} MANotifyingArrayNotifications;

// in the implementation
const struct MANotifyingArrayNotificationsStruct MANotifyingArrayNotifications = {
    .didAddObject = @"didAddObject",
    .didChangeObject = @"didChangeObject",
    .didRemoveObject = @"didRemoveObject"
};

Installing cmake with home-brew

  1. Download the latest CMake Mac binary distribution here: https://cmake.org/download/ (current latest is: https://cmake.org/files/v3.17/cmake-3.17.1-Darwin-x86_64.dmg)

  2. Double click the downloaded .dmg file to install it. In the window that pops up, drag the CMake icon into the Application folder.

  3. Add this line to your .bashrc file: PATH="/Applications/CMake.app/Contents/bin":"$PATH"

  4. Reload your .bashrc file: source ~/.bashrc

  5. Verify the latest cmake version is installed: cmake --version

  6. You can launch the CMake GUI by clicking on LaunchPad and typing cmake. Click on the CMake icon that appears.

Check if SQL Connection is Open or Closed

The .NET documentation says: State Property: A bitwise combination of the ConnectionState values

So I think you should check

!myConnection.State.HasFlag(ConnectionState.Open)

instead of

myConnection.State != ConnectionState.Open

because State can have multiple flags.