Programs & Examples On #Lossy compression

Reducing video size with same format and reducing frame size

Instead of chosing fixed bit rates, with the H.264 codec, you can also chose a different preset as described at https://trac.ffmpeg.org/wiki/x264EncodingGuide. I also found Video encoder comparison at KeyJ's blog (archived version) an interesting read, it compares H.264 against Theora and others.

Following is a comparison of various options I tried. The recorded video was originally 673M in size, taken on an iPad using RecordMyScreen. It has a duration of about 20 minutes with a resolution of 1024x768 (with half of the video being blank, so I cropped it to 768x768). In order to reduce size, I lowered the resolution to 480x480. There is no audio.

The results, taking the same 1024x768 as base (and applying cropping, scaling and a filter):

  • With no special options: 95M (encoding time: 1m19s).
  • With only -b 512k added, the size dropped to 77M (encoding time: 1m17s).
  • With only -preset veryslow (and no -b), it became 70M (encoding time: 6m14s)
  • With both -b 512k and -preset veryslow, the size becomes 77M (100K smaller than just -b 512k).
  • With -preset veryslow -crf 28, I get a file of 39M which took 5m47s (with no visual quality difference to me).

N=1, so take the results with a grain of salt and perform your own tests.

How to unzip a file using the command line?

Thanks Rich, I will take note of that. So here is the script for my own solution. It requires no third party unzip tools.

Include the script below at the start of the batch file to create the function, and then to call the function, the command is... cscript /B j_unzip.vbs zip_file_name_goes_here.zip

Here is the script to add to the top...

REM Changing working folder back to current directory for Vista & 7 compatibility
%~d0
CD %~dp0
REM Folder changed

REM This script upzip's files...

    > j_unzip.vbs ECHO '
    >> j_unzip.vbs ECHO ' UnZip a file script
    >> j_unzip.vbs ECHO '
    >> j_unzip.vbs ECHO ' It's a mess, I know!!!
    >> j_unzip.vbs ECHO '
    >> j_unzip.vbs ECHO.
    >> j_unzip.vbs ECHO ' Dim ArgObj, var1, var2
    >> j_unzip.vbs ECHO Set ArgObj = WScript.Arguments
    >> j_unzip.vbs ECHO.
    >> j_unzip.vbs ECHO If (Wscript.Arguments.Count ^> 0) Then
    >> j_unzip.vbs ECHO. var1 = ArgObj(0)
    >> j_unzip.vbs ECHO Else
    >> j_unzip.vbs ECHO. var1 = ""
    >> j_unzip.vbs ECHO End if
    >> j_unzip.vbs ECHO.
    >> j_unzip.vbs ECHO If var1 = "" then
    >> j_unzip.vbs ECHO. strFileZIP = "example.zip"
    >> j_unzip.vbs ECHO Else
    >> j_unzip.vbs ECHO. strFileZIP = var1
    >> j_unzip.vbs ECHO End if
    >> j_unzip.vbs ECHO.
    >> j_unzip.vbs ECHO 'The location of the zip file.
    >> j_unzip.vbs ECHO REM Set WshShell = CreateObject("Wscript.Shell")
    >> j_unzip.vbs ECHO REM CurDir = WshShell.ExpandEnvironmentStrings("%%cd%%")
    >> j_unzip.vbs ECHO Dim sCurPath
    >> j_unzip.vbs ECHO sCurPath = CreateObject("Scripting.FileSystemObject").GetAbsolutePathName(".")
    >> j_unzip.vbs ECHO strZipFile = sCurPath ^& "\" ^& strFileZIP
    >> j_unzip.vbs ECHO 'The folder the contents should be extracted to.
    >> j_unzip.vbs ECHO outFolder = sCurPath ^& "\"
    >> j_unzip.vbs ECHO.
    >> j_unzip.vbs ECHO. WScript.Echo ( "Extracting file " ^& strFileZIP)
    >> j_unzip.vbs ECHO.
    >> j_unzip.vbs ECHO Set objShell = CreateObject( "Shell.Application" )
    >> j_unzip.vbs ECHO Set objSource = objShell.NameSpace(strZipFile).Items()
    >> j_unzip.vbs ECHO Set objTarget = objShell.NameSpace(outFolder)
    >> j_unzip.vbs ECHO intOptions = 256
    >> j_unzip.vbs ECHO objTarget.CopyHere objSource, intOptions
    >> j_unzip.vbs ECHO.
    >> j_unzip.vbs ECHO. WScript.Echo ( "Extracted." )
    >> j_unzip.vbs ECHO.

Statically rotate font-awesome icons

If you want to rotate 45 degrees, you can use the CSS transform property:

.fa-rotate-45 {
    -ms-transform:rotate(45deg);     /* Internet Explorer 9 */
    -webkit-transform:rotate(45deg); /* Chrome, Safari, Opera */
    transform:rotate(45deg);         /* Standard syntax */
}

How to run single test method with phpunit?

I prefer marking the test in annotation as

/**
 * @group failing
 * Tests the api edit form
 */
public function testEditAction()

Then running it with

phpunit --group failing

No need to specify the full path in the command line, but you have to remember removing this before commit, not to clutter the code.

You may also specify several groups for a single test

/**
  * @group failing
  * @group bug2204 
  */
public function testSomethingElse()
{
}

Import CSV file as a pandas DataFrame

import pandas as pd
dataset = pd.read_csv('/home/nspython/Downloads/movie_metadata1.csv')

How to change the background color of the options menu?

After spending a considerable amount of time trying all the options, the only way I was able to get an app using AppCompat v7 to change the overflow menu background was using the itemBackground attribute:

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    ...
    <item name="android:itemBackground">@color/overflow_background</item>
    ...
</style>

Tested from API 4.2 to 5.0.

Auto code completion on Eclipse

Use the Ctrl+Space shortcut for getting all possible autocomplete options available in a particular context in the editor.

Auto Complete will also allow you to insert custom code templates into the editor, with placeholders for various inputs. For instance, attempting to auto complete the word "test" in a Java editor, in the context of a class body, will allow you to create a unit test that uses JUnit; you'll have to code the body of the method though. Some code templates like the former, come out of the box.

Configuration options of interest

  • Auto-activation delay. If the list of auto complete options is taking too long to appear, the delay can be reduced from Windows -> Preferences -> Java -> Editor -> Content Assist -> Auto Activation delay (specify the reduced delay here).
  • Auto activation trigger for Java. Accessible in the same pane, this happens to be the . character by default. When you have just keyed in typeA. and you expect to see relevant members that can be accessed, the auto completion list will automatically popup with the appropriate members, on this trigger.
  • Proposal types. If you do not want to see proposals of a particular variety, you can disable them from Windows -> Preferences -> Java -> Editor -> Content Assist -> Advanced. I typically switch off proposals of most kinds except Java and Template proposals. Hitting Ctrl+Space multiple times will cycle you through proposals of various kinds.
  • Template Proposals. These are different from your run of the mill proposals. You could add your code templates in here; it can be accessed from Windows -> Preferences -> Java -> Editor -> Templates. Configuration of existing templates is allowed and so is addition of new ones. Reserve usage however for the tedious typing tasks that do not have a template yet.

Find Java classes implementing an interface

Spring can do this for you...

BeanDefinitionRegistry bdr = new SimpleBeanDefinitionRegistry();
ClassPathBeanDefinitionScanner s = new ClassPathBeanDefinitionScanner(bdr);

TypeFilter tf = new AssignableTypeFilter(CLASS_YOU_WANT.class);
s.addIncludeFilter(tf);
s.scan("package.you.want1", "package.you.want2");       
String[] beans = bdr.getBeanDefinitionNames();

N.B. The TypeFilter is important if you want the correct results! You can also use exclusion filters here instead.

The Scanner can be found in the spring-context jar, the registry in spring-beans, the type filter is in spring-core.

How to build a 'release' APK in Android Studio?

AndroidStudio is alpha version for now. So you have to edit gradle build script files by yourself. Add next lines to your build.gradle

android {

    signingConfigs {

        release {

            storeFile file('android.keystore')
            storePassword "pwd"
            keyAlias "alias"
            keyPassword "pwd"
        }
    }

    buildTypes {

       release {

           signingConfig signingConfigs.release
       }
    }
}

To actually run your application at emulator or device run gradle installDebug or gradle installRelease.

You can create helloworld project from AndroidStudio wizard to see what structure of gradle files is needed. Or export gradle files from working eclipse project. Also this series of articles are helpfull http://blog.stylingandroid.com/archives/1872#more-1872

Convert a Map<String, String> to a POJO

A solution with Gson:

Gson gson = new Gson();
JsonElement jsonElement = gson.toJsonTree(map);
MyPojo pojo = gson.fromJson(jsonElement, MyPojo.class);

How to avoid a System.Runtime.InteropServices.COMException?

Probably you are trying to access the excel with the index 0, please note that Excel rows/columns start from 1.

How to convert NSNumber to NSString

Try:

NSString *myString = [NSNumber stringValue];

How to convert Nvarchar column to INT

I know its Too late But I hope it will work new comers Try This Its Working ... :D

select 
  case 
      when isnumeric(my_NvarcharColumn) = 1 then 
              cast(my_NvarcharColumn AS int)
      else
              NULL
 end

AS 'my_NvarcharColumnmitter'
from A

Android Studio - Gradle sync project failed

The Android plugin 0.8.x doesn't support Gradle 1.11, you need to use 1.10.

You can read the proper error message in the "Gradle Console" tab.

EDIT

You need to change gradle/wrapper/gradle-wrapper.properties file in this way:

distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=http\://services.gradle.org/distributions/gradle-1.10-all.zip

conversion from string to json object android

You just need the lines of code as below:

   try {
        String myjsonString = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";
        JSONObject jsonObject = new JSONObject(myjsonString );
        //displaying the JSONObject as a String
        Log.d("JSONObject = ", jsonObject.toString());
        //getting specific key values
        Log.d("phonetype = ", jsonObject.getString("phonetype"));
        Log.d("cat = ", jsonObject.getString("cat");
    }catch (Exception ex) {
         StringWriter stringWriter = new StringWriter();
         ex.printStackTrace(new PrintWriter(stringWriter));
         Log.e("exception ::: ", stringwriter.toString());
    }

How to set a default value in react-select

I was having a similar error. Make sure your options have a value attribute.

<option key={index} value={item}> {item} </option>

Then match the selects element value initially to the options value.

<select 
    value={this.value} />

How to set null value to int in c#?

Use Null.NullInteger ex: private int _ReservationID = Null.NullInteger;

How to remove an iOS app from the App Store

Since itunesconnect has been changed i am updating with the new steps here.

You have to follow through these steps

  1. Login to itunesconnect
  2. Choose your app in My Apps section
  3. Under Appstore tab choose "Pricing and Availability"
  4. Under Availability section click edit will open a popup listing the territories
  5. Uncheck all the territories and click Done

enter image description here

enter image description here

Java LinkedHashMap get first or last entry

One more way to get first and last entry of a LinkedHashMap is to use toArray() method of Set interface.

But I think iterating over the entries in the entry set and getting the first and last entry is a better approach.

The usage of array methods leads to warning of the form " ...needs unchecked conversion to conform to ..." which cannot be fixed [but can be only be suppressed by using the annotation @SuppressWarnings("unchecked")].

Here is a small example to demonstrate the usage of toArray() method:

    public static void main(final String[] args) {
        final Map<Integer,String> orderMap = new LinkedHashMap<Integer,String>();
        orderMap.put(6, "Six");
        orderMap.put(7, "Seven");
        orderMap.put(3, "Three");
        orderMap.put(100, "Hundered");
        orderMap.put(10, "Ten");

        final Set<Entry<Integer, String>> mapValues = orderMap.entrySet();
        final int maplength = mapValues.size();
        final Entry<Integer,String>[] test = new Entry[maplength];
        mapValues.toArray(test);

        System.out.print("First Key:"+test[0].getKey());
        System.out.println(" First Value:"+test[0].getValue());

        System.out.print("Last Key:"+test[maplength-1].getKey());
        System.out.println(" Last Value:"+test[maplength-1].getValue());
    }

    // the output geneated is :
    First Key:6 First Value:Six
    Last Key:10 Last Value:Ten

Boolean checking in the 'if' condition

The first one, or if (status) { /*second clause*/ } else { /* first clause */ }

EDIT

If the second form is really desired, then if (false == status) <etc>, while uglier, is probably safer (wrt typos).

Correct way to import lodash

You can import them as

import {concat, filter, orderBy} from 'lodash';

or as

import concat from 'lodash/concat';
import orderBy from 'lodash/orderBy';
import filter from 'lodash/filter';

the second one is much optimized than the first because it only loads the needed modules

then use like this

pendingArray: concat(
                    orderBy(
                        filter(payload, obj => obj.flag),
                        ['flag'],
                        ['desc'],
                    ),
                    filter(payload, obj => !obj.flag),

jQuery select option elements by value

To get the value just use this:

<select id ="ari_select" onchange = "getvalue()">
<option value = "1"></option>
<option value = "2"></option>
<option value = "3"></option>
<option value = "4"></option>
</select>

<script>
function getvalue()
{
    alert($("#ari_select option:selected").val()); 
}
</script>

this will fetch the values

Create Word Document using PHP in Linux

There are 2 options to create quality word documents. Use COM to communicate with word (this requires a windows php server at least). Use openoffice and it's API to create and save documents in word format.

Can I hide/show asp:Menu items based on role?

This is best done in the MenuItemDataBound.

protected void NavigationMenu_MenuItemDataBound(object sender, MenuEventArgs e)
{
    if (!Page.User.IsInRole("Admin"))
    {
        if (e.Item.NavigateUrl.Equals("/admin"))
        {
            if (e.Item.Parent != null)
            {
                MenuItem menu = e.Item.Parent;

                menu.ChildItems.Remove(e.Item);
            }
            else
            {
                Menu menu = (Menu)sender;

                menu.Items.Remove(e.Item);
            }               
        }
    }
}

Because the example used the NavigateUrl it is not language specific and works on sites with localized site maps.

VideoView Full screen in android application

I had to make my VideoView sit in a RelativeLayout in order to make the chosen answer work.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <VideoView android:id="@+id/videoViewRelative"
         android:layout_alignParentTop="true"
         android:layout_alignParentBottom="true"
         android:layout_alignParentLeft="true"
         android:layout_alignParentRight="true"
         android:layout_width="fill_parent"
         android:layout_height="fill_parent">
    </VideoView>

</RelativeLayout>

As given here: Android - How to stretch video to fill VideoView area Toggling between screen sizes would be as simple as changing the layout parameters as given in the chosen answer.

Postgresql - change the size of a varchar column to lower length

There's a description of how to do this at Resize a column in a PostgreSQL table without changing data. You have to hack the database catalog data. The only way to do this officially is with ALTER TABLE, and as you've noted that change will lock and rewrite the entire table while it's running.

Make sure you read the Character Types section of the docs before changing this. All sorts of weird cases to be aware of here. The length check is done when values are stored into the rows. If you hack a lower limit in there, that will not reduce the size of existing values at all. You would be wise to do a scan over the whole table looking for rows where the length of the field is >40 characters after making the change. You'll need to figure out how to truncate those manually--so you're back some locks just on oversize ones--because if someone tries to update anything on that row it's going to reject it as too big now, at the point it goes to store the new version of the row. Hilarity ensues for the user.

VARCHAR is a terrible type that exists in PostgreSQL only to comply with its associated terrible part of the SQL standard. If you don't care about multi-database compatibility, consider storing your data as TEXT and add a constraint to limits its length. Constraints you can change around without this table lock/rewrite problem, and they can do more integrity checking than just the weak length check.

How do I encrypt and decrypt a string in python?

Encrypt Data

First, we need to install the cryptography library:

pip3 install cryptography
  • From the cryptography library, we need to import Fernet and start generating a key - this key is required for symmetric encryption/decryption.

  • To generate a key, we call the generate_key() method.

    • We only need to execute the above method once to generate a key.

    You need to keep this key in a safe place. If you lose the key, you won't be able to decrypt the data that was encrypted with this key.

  • Once we have generated a key, we need to load the key with load_key()

Encrypt a Message

This is a three step process:

  1. encode the message
  2. initialize the Fernet class
  3. pass the encoded message to encrypt() method

Below is a full working example of encrypting a message :

from cryptography.fernet import Fernet

def generate_key():
    """
    Generates a key and save it into a file
    """
    key = Fernet.generate_key()
    with open("secret.key", "wb") as key_file:
        key_file.write(key)

def load_key():
    """
    Load the previously generated key
    """
    return open("secret.key", "rb").read()

def encrypt_message(message):
    """
    Encrypts a message
    """
    key = load_key()
    encoded_message = message.encode()
    f = Fernet(key)
    encrypted_message = f.encrypt(encoded_message)

    print(encrypted_message)

if __name__ == "__main__":
    # generate_key() # execute only once 
    encrypt_message("Hello stackoverflow!")

output:

b'gAAAAABgLX7Zj-kn-We2BI_c9NQhEtfJEnHUVhVqtiqjkDi5dgJafj-_8QUDyeNS2zsJTdBWg6SntRJOjOM1U5mIxxsGny7IEGqpVVdHwheTnwzSBlgpb80='

Decrypt Data

To decrypt the message, we just call the decrypt() method from the Fernet library. Remember, we also need to load the key as well, because the key is needed to decrypt the message.

from cryptography.fernet import Fernet

def load_key():
    """
    Load the previously generated key
    """
    return open("secret.key", "rb").read()

def decrypt_message(encrypted_message):
    """
    Decrypts an encrypted message
    """
    key = load_key()
    f = Fernet(key)
    decrypted_message = f.decrypt(encrypted_message)

    print(decrypted_message.decode())

if __name__ == "__main__":
    decrypt_message(b'gAAAAABgLX7Zj-kn-We2BI_c9NQhEtfJEnHUVhVqtiqjkDi5dgJafj-_8QUDyeNS2zsJTdBWg6SntRJOjOM1U5mIxxsGny7IEGqpVVdHwheTnwzSBlgpb80=')

output:

Hello stackoverflow!


Your password is in the secret.key in a form similar to the password below:

B8wtXqwBA_zb2Iaz5pW8CIQIwGSYSFoBiLsVz-vTqzw=

How to compare LocalDate instances Java 8

LocalDate ld ....;
LocalDateTime ldtime ...;

ld.isEqual(LocalDate.from(ldtime));

Populating a ComboBox using C#

Create a class Language

public class Language
{
     public string Name{get;set;}
     public string Value{get;set;}
     public override string ToString() { return this.Name;}
}

Then, add as many language to the combobox that you want:

yourCombobox.Items.Add(new Language{Name="English",Value="En"});

Can I set an unlimited length for maxJsonLength in web.config?

Just ran into this. I'm getting over 6,000 records. Just decided I'd just do some paging. As in, I accept a page number in my MVC JsonResult endpoint, which is defaulted to 0 so it's not necessary, like so:

public JsonResult MyObjects(int pageNumber = 0)

Then instead of saying:

return Json(_repository.MyObjects.ToList(), JsonRequestBehavior.AllowGet);

I say:

return Json(_repository.MyObjects.OrderBy(obj => obj.ID).Skip(1000 * pageNumber).Take(1000).ToList(), JsonRequestBehavior.AllowGet);

It's very simple. Then, in JavaScript, instead of this:

function myAJAXCallback(items) {
    // Do stuff here
}

I instead say:

var pageNumber = 0;
function myAJAXCallback(items) {
    if(items.length == 1000)
        // Call same endpoint but add this to the end: '?pageNumber=' + ++pageNumber
    }
    // Do stuff here
}

And append your records to whatever you were doing with them in the first place. Or just wait until all the calls finish and cobble the results together.

Location of the mongodb database on mac

Env: macOS Mojave 10.14.4

Install: homebrew

Location:/usr/local/Cellar/mongodb/4.0.3_1

Note :If update version by brew upgrade mongo,the folder 4.0.4_1 will be removed and replace with the new version folder

What is web.xml file and what are all things can I do with it?

I am trying to figure out exactly how this works too. This site might be helpful to you. It has all of the possible tags for web.xml along with examples and descriptions of each tag.

http://wiki.metawerx.net/wiki/Web.xml

Execute SQLite script

You want to feed the create.sql into sqlite3 from the shell, not from inside SQLite itself:

$ sqlite3 auction.db < create.sql

SQLite's version of SQL doesn't understand < for files, your shell does.

How to create a Java / Maven project that works in Visual Studio Code?

An alternative way is to install the Maven for Java plugin and create a maven project within Visual Studio. The steps are described in the official documentation:

  1. From the Command Palette (Crtl+Shift+P), select Maven: Generate from Maven Archetype and follow the instructions, or
  2. Right-click on a folder and select Generate from Maven Archetype.

How to make asynchronous HTTP requests in PHP

You can use non-blocking sockets and one of pecl extensions for PHP:

You can use library which gives you an abstraction layer between your code and a pecl extension: https://github.com/reactphp/event-loop

You can also use async http-client, based on the previous library: https://github.com/reactphp/http-client

See others libraries of ReactPHP: http://reactphp.org

Be careful with an asynchronous model. I recommend to see this video on youtube: http://www.youtube.com/watch?v=MWNcItWuKpI

Getting error "The package appears to be corrupt" while installing apk file

In my case; If you receive this error while updating your application, It may be because of the target SDK version. In such case you will receive this error on logs;

"Package com.android.myapp new target SDK 22 doesn't support runtime permissions but the old target SDK 23 does"

This is because your previous aplication was build with a higher version of sdk. If your new app was build with 22 and your installed application was build with 23, you will get The package appears to be corrupt error on update.

How to move (and overwrite) all files from one directory to another?

It's just mv srcdir/* targetdir/.

If there are too many files in srcdir you might want to try something like the following approach:

cd srcdir
find -exec mv {} targetdir/ +

In contrast to \; the final + collects arguments in an xargs like manner instead of executing mv once for every file.

Can Android Studio be used to run standard Java projects?

To run a java file in Android ensure your class has the main method. In Android Studio 3.5 just right click inside the file and select "Run 'Filename.main()'" or click on "Run" on the menu and select "Run Filename" from the resulting drop-down menu.

PHP get dropdown value and text

You will have to save the relationship on the server side. The value is the only part that is transmitted when the form is posted. You could do something nasty like...

<option value="2|Dog">Dog</option>

Then split the result apart if you really wanted to, but that is an ugly hack and a waste of bandwidth assuming the numbers are truly unique and have a one to one relationship with the text.

The best way would be to create an array, and loop over the array to create the HTML. Once the form is posted you can use the value to look up the text in that same array.

Loop through each cell in a range of cells when given a Range object

I'm resurrecting the dead here, but because a range can be defined as "A:A", using a for each loop ends up with a potential infinite loop. The solution, as far as I know, is to use the Do Until loop.

Do Until Selection.Value = ""
  Rem Do things here...
Loop

From inside of a Docker container, how do I connect to the localhost of the machine?

None of the answers worked for me when using Docker Toolbox on Windows 10 Home, but 10.0.2.2 did, since it uses VirtualBox which exposes the host to the VM on this address.

display Java.util.Date in a specific format

You can use simple date format in Java using the code below

SimpleDateFormat simpledatafo = new SimpleDateFormat("dd/MM/yyyy");
Date newDate = new Date();
String expectedDate= simpledatafo.format(newDate);

sudo: npm: command not found

simply reinstall .

On RHEL, CentOS and Fedora

sudo yum remove nodejs npm
sudo dnf remove nodejs npm   [On Fedora 22+ versions]

then

yum -y install nodejs npm
dnf -y install nodejs npm   [On Fedora 22+ versions]

easy!.. both node and npm works like a charm now!

Refresh Page and Keep Scroll Position

this will do the magic

    <script>
        document.addEventListener("DOMContentLoaded", function(event) { 
            var scrollpos = localStorage.getItem('scrollpos');
            if (scrollpos) window.scrollTo(0, scrollpos);
        });

        window.onbeforeunload = function(e) {
            localStorage.setItem('scrollpos', window.scrollY);
        };
    </script>

Eclipse error, "The selection cannot be launched, and there are no recent launches"

Follow these steps to run your application on the device connected. 1. Change directories to the root of your Android project and execute: ant debug 2. Make sure the Android SDK platform-tools/ directory is included in your PATH environment variable, then execute: adb install bin/<*your app name*>-debug.apk On your device, locate <*your app name*> and open it.

Refer Running App

Recursive directory listing in DOS

You can use various options with FINDSTR to remove the lines do not want, like so:

DIR /S | FINDSTR "\-" | FINDSTR /VI DIR

Normal output contains entries like these:

28-Aug-14  05:14 PM    <DIR>          .
28-Aug-14  05:14 PM    <DIR>          ..

You could remove these using the various filtering options offered by FINDSTR. You can also use the excellent unxutils, but it converts the output to UNIX by default, so you no longer get CR+LF; FINDSTR offers the best Windows option.

How to get response as String using retrofit without using GSON or any other library in android

** Update ** A scalars converter has been added to retrofit that allows for a String response with less ceremony than my original answer below.

Example interface --

public interface GitHubService {
    @GET("/users/{user}")
    Call<String> listRepos(@Path("user") String user);
}

Add the ScalarsConverterFactory to your retrofit builder. Note: If using ScalarsConverterFactory and another factory, add the scalars factory first.

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(BASE_URL)
    .addConverterFactory(ScalarsConverterFactory.create())
    // add other factories here, if needed.
    .build();

You will also need to include the scalars converter in your gradle file --

implementation 'com.squareup.retrofit2:converter-scalars:2.1.0'

--- Original Answer (still works, just more code) ---

I agree with @CommonsWare that it seems a bit odd that you want to intercept the request to process the JSON yourself. Most of the time the POJO has all the data you need, so no need to mess around in JSONObject land. I suspect your specific problem might be better solved using a custom gson TypeAdapter or a retrofit Converter if you need to manipulate the JSON. However, retrofit provides more the just JSON parsing via Gson. It also manages a lot of the other tedious tasks involved in REST requests. Just because you don't want to use one of the features, doesn't mean you have to throw the whole thing out. There are times you just want to get the raw stream, so here is how to do it -

First, if you are using Retrofit 2, you should start using the Call API. Instead of sending an object to convert as the type parameter, use ResponseBody from okhttp --

public interface GitHubService {
    @GET("/users/{user}")
    Call<ResponseBody> listRepos(@Path("user") String user);
}

then you can create and execute your call --

GitHubService service = retrofit.create(GitHubService.class);
Call<ResponseBody> result = service.listRepos(username);
result.enqueue(new Callback<ResponseBody>() {
    @Override
    public void onResponse(Response<ResponseBody> response) {
        try {
            System.out.println(response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onFailure(Throwable t) {
        e.printStackTrace();
    }
});

Note The code above calls string() on the response object, which reads the entire response into a String. If you are passing the body off to something that can ingest streams, you can call charStream() instead. See the ResponseBody docs.

How do I call Objective-C code from Swift?

Apple has provided official guide in this doc: how-to-call-objective-c-code-from-swift

Here is the relevant part:

To import a set of Objective-C files into Swift code within the same app target, you rely on an Objective-C bridging header file to expose those files to Swift. Xcode offers to create this header when you add a Swift file to an existing Objective-C app, or an Objective-C file to an existing Swift app.

If you accept, Xcode creates the bridging header file along with the file you were creating, and names it by using your product module name followed by "-Bridging-Header.h". Alternatively, you can create a bridging header yourself by choosing File > New > File > [operating system] > Source > Header File

Edit the bridging header to expose your Objective-C code to your Swift code:

  1. In your Objective-C bridging header, import every Objective-C header you want to expose to Swift.
  2. In Build Settings, in Swift Compiler - Code Generation, make sure the Objective-C Bridging Header build setting has a path to the bridging header file. The path should be relative to your project, similar to the way your Info.plist path is specified in Build Settings. In most cases, you won't need to modify this setting.

Any public Objective-C headers listed in the bridging header are visible to Swift.

Enable vertical scrolling on textarea

You can try adding:

#aboutDescription
{
    height: 100px;
    max-height: 100px;  
}

'No JUnit tests found' in Eclipse

Right Click on Project > Properties > Java Build Path > Add the Test folder as source folder.

All source folders including Test Classes need to be in Eclipse Java Build Path. So that the sources such as main and test classes can be compiled into the build directory (Eclipse default folder is bin).

how to get date of yesterday using php?

Another OOP method for DateTime with setting the exact hour:

$yesterday = new DateTime("yesterday 09:00:59", new DateTimeZone('Europe/London'));
echo $yesterday->format('Y-m-d H:i:s') . "\n";

How to append elements into a dictionary in Swift?

In Swift, if you are using NSDictionary, you can use setValue:

dict.setValue("value", forKey: "key")

How to format a phone number with jQuery

Consider libphonenumber-js (https://github.com/halt-hammerzeit/libphonenumber-js) which is a smaller version of the full and famous libphonenumber.

Quick and dirty example:

$(".phone-format").keyup(function() {
// Don't reformat backspace/delete so correcting mistakes is easier
if (event.keyCode != 46 && event.keyCode != 8) {
    var val_old = $(this).val();
    var newString = new libphonenumber.asYouType('US').input(val_old);
    $(this).focus().val('').val(newString);
}
});

(If you do use a regex to avoid a library download, avoid reformat on backspace/delete will make it easier to correct typos.)

Format ints into string of hex

''.join('%02x'%i for i in input)

If my interface must return Task what is the best way to have a no-operation implementation?

I prefer the Task completedTask = Task.CompletedTask; solution of .Net 4.6, but another approach is to mark the method async and return void:

    public async Task WillBeLongRunningAsyncInTheMajorityOfImplementations()
    {
    }

You'll get a warning (CS1998 - Async function without await expression), but this is safe to ignore in this context.

Why use static_cast<int>(x) instead of (int)x?

  1. Allows casts to be found easily in your code using grep or similar tools.
  2. Makes it explicit what kind of cast you are doing, and engaging the compiler's help in enforcing it. If you only want to cast away const-ness, then you can use const_cast, which will not allow you to do other types of conversions.
  3. Casts are inherently ugly -- you as a programmer are overruling how the compiler would ordinarily treat your code. You are saying to the compiler, "I know better than you." That being the case, it makes sense that performing a cast should be a moderately painful thing to do, and that they should stick out in your code, since they are a likely source of problems.

See Effective C++ Introduction

Multiple IF AND statements excel

Making these 2 communicate

=IF(OR(AND(MID(K27,6,1)="N",(MID(K27,6,1)="C"),(MID(K27,6,1)="H"),(MID(K27,6,1)="I"),(MID(K27,6,1)="B"),(MID(K27,6,1)="F"),(MID(K27,6,1)="L"),(MID(K27,6,1)="M"),(MID(K27,6,1)="P"),(MID(K27,6,1)="R"),(MID(K27,6,1)="P"),ISTEXT(G27)="61"),AND(RIGHT(K27,2)=G27)),"Good","Review")

=IF(AND(RIGHT(K27,2)=G27),"Good","Review")

How to config routeProvider and locationProvider in angularJS?

@Simple-Solution

I use a simple Python HTTP server. When in the directory of the Angular app in question (using a MBP with Mavericks 10.9 and Python 2.x) I simply run

python -m SimpleHTTPServer 8080

And that sets up the simple server on port 8080 letting you visit localhost:8080 on your browser to view the app in development.

Hope that helped!

Get value of a string after last slash in JavaScript

At least three ways:

A regular expression:

var result = /[^/]*$/.exec("foo/bar/test.html")[0];

...which says "grab the series of characters not containing a slash" ([^/]*) at the end of the string ($). Then it grabs the matched characters from the returned match object by indexing into it ([0]); in a match object, the first entry is the whole matched string. No need for capture groups.

Live example

Using lastIndexOf and substring:

var str = "foo/bar/test.html";
var n = str.lastIndexOf('/');
var result = str.substring(n + 1);

lastIndexOf does what it sounds like it does: It finds the index of the last occurrence of a character (well, string) in a string, returning -1 if not found. Nine times out of ten you probably want to check that return value (if (n !== -1)), but in the above since we're adding 1 to it and calling substring, we'd end up doing str.substring(0) which just returns the string.

Using Array#split

Sudhir and Tom Walters have this covered here and here, but just for completeness:

var parts = "foo/bar/test.html".split("/");
var result = parts[parts.length - 1]; // Or parts.pop();

split splits up a string using the given delimiter, returning an array.

The lastIndexOf / substring solution is probably the most efficient (although one always has to be careful saying anything about JavaScript and performance, since the engines vary so radically from each other), but unless you're doing this thousands of times in a loop, it doesn't matter and I'd strive for clarity of code.

IE8 issue with Twitter Bootstrap 3

I faced the same problem, tried the first answer but something was missing.

If you guys are using Webpack, your css will be loaded as a style tag which is not supported by respond.js, it needs a file, so make sure bootstrap is loaded as a css file

Personally I used extract-text-webpack-plugin

const webpack = require("webpack")
const ExtractTextPlugin = require("extract-text-webpack-plugin")
const path = require("path")

module.exports = {
    context: __dirname+"/src",
    entry: "./index.js",
    output: {
        filename: "./dist/bundle.js",
        path: __dirname
    },
    plugins: [
        ...,
        new ExtractTextPlugin("./dist/bootstrap.css", {
            allChunks: true
        })
    ],
    module: {
        loaders: [
            ...,
            // your css loader excluding bootstrap
            {
                test: /\.css$/,
                loader: "style!css",
                exclude: [
                    path.resolve(__dirname, "node_modules/bootstrap/dist/css/bootstrap.css")
                ]
            },

            {
                // loads bootstrap as a file, change path accordingly if needs be, path needs to be absolute
                include: [
                    path.resolve(__dirname, "node_modules/bootstrap/dist/css/bootstrap.css")
                ],
                loader: ExtractTextPlugin.extract("style-loader", "css-loader?minimize")
            }
        ]
    }
}

Hope it will help you

How do I create an .exe for a Java program?

If Java is installed on the target machine, there is no need to create an .exe file. A .jar file should be sufficient.

What's the main difference between int.Parse() and Convert.ToInt32

No difference as such.
Convert.ToInt32() calls int.Parse() internally

Except for one thing Convert.ToInt32() returns 0 when argument is null

Otherwise both work the same way

How to update Identity Column in SQL Server?

You need to

set identity_insert YourTable ON

Then delete your row and reinsert it with different identity.

Once you have done the insert don't forget to turn identity_insert off

set identity_insert YourTable OFF

Syntax behind sorted(key=lambda: ...)

Just to rephrase, the key (Optional. A Function to execute to decide the order. Default is None) in sorted functions expects a function and you use lambda.

To define lambda, you specify the object property you want to sort and python's built-in sorted function will automatically take care of it.

If you want to sort by multiple properties then assign key = lambda x: (property1, property2).

To specify order-by, pass reverse= true as the third argument(Optional. A Boolean. False will sort ascending, True will sort descending. Default is False) of sorted function.

How to set the font size in Emacs?

From Emacswiki, GNU Emacs 23 has a built-in key combination:

C-xC-+ and C-xC-- to increase or decrease the buffer text size

How do I check whether an array contains a string in TypeScript?

The same as in JavaScript, using Array.prototype.indexOf():

console.log(channelArray.indexOf('three') > -1);

Or using ECMAScript 2016 Array.prototype.includes():

console.log(channelArray.includes('three'));

Note that you could also use methods like showed by @Nitzan to find a string. However you wouldn't usually do that for a string array, but rather for an array of objects. There those methods were more sensible. For example

const arr = [{foo: 'bar'}, {foo: 'bar'}, {foo: 'baz'}];
console.log(arr.find(e => e.foo === 'bar')); // {foo: 'bar'} (first match)
console.log(arr.some(e => e.foo === 'bar')); // true
console.log(arr.filter(e => e.foo === 'bar')); // [{foo: 'bar'}, {foo: 'bar'}]

Reference

Array.find()

Array.some()

Array.filter()

Java equivalent to Explode and Implode(PHP)

if you are talking about in the reference of String Class. so you can use

subString/split

for Explode & use String

concate

for Implode.

How to remove all debug logging calls before building the release version of an Android app?

ProGuard will do it for you on your release build and now the good news from android.com:

http://developer.android.com/tools/help/proguard.html

The ProGuard tool shrinks, optimizes, and obfuscates your code by removing unused code and renaming classes, fields, and methods with semantically obscure names. The result is a smaller sized .apk file that is more difficult to reverse engineer. Because ProGuard makes your application harder to reverse engineer, it is important that you use it when your application utilizes features that are sensitive to security like when you are Licensing Your Applications.

ProGuard is integrated into the Android build system, so you do not have to invoke it manually. ProGuard runs only when you build your application in release mode, so you do not have to deal with obfuscated code when you build your application in debug mode. Having ProGuard run is completely optional, but highly recommended.

This document describes how to enable and configure ProGuard as well as use the retrace tool to decode obfuscated stack traces

jQuery - replace all instances of a character in a string

You need to use a regular expression, so that you can specify the global (g) flag:

var s = 'some+multi+word+string'.replace(/\+/g, ' ');

(I removed the $() around the string, as replace is not a jQuery method, so that won't work at all.)

Bloomberg Open API

This API has been available for a long time and enables to get access to market data (including live) if you are running a Bloomberg Terminal or have access to a Bloomberg Server, which is chargeable.

The only difference is that the API (not its code) has been open sourced, so it can now be used as a dependency in an open source project for example, without any copyrights issues, which was not the case before.

pass parameter by link_to ruby on rails

The above did not work for me but this did

<%= link_to "text_to_show_in_url", action_controller_path(:gender => "male", :param2=> "something_else") %>

Export tables to an excel spreadsheet in same directory

Lawrence has given you a good answer. But if you want more control over what gets exported to where in Excel see Modules: Sample Excel Automation - cell by cell which is slow and Modules: Transferring Records to Excel with Automation You can do things such as export the recordset starting in row 2 and insert custom text in row 1. As well as any custom formatting required.

Parse JSON String to JSON Object in C#.NET

I see that this question is very old, but this is the solution I used for the same problem, and it seems to require a bit less code than the others.

As @Maloric mentioned in his answer to this question:

var jo = JObject.Parse(myJsonString);

To use JObject, you need the following in your class file

using Newtonsoft.Json.Linq;

Using Helvetica Neue in a Website

Assuming you have referenced and correctly integrated your font to your site (presumably using an @font-face kit) it should be alright to just reference yours the way you do. Presumably it is like this so they have fall backs incase some browsers do not render the fonts correctly

How do I check if a property exists on a dynamic anonymous type in c#?

In case someone need to handle a dynamic object come from Json, I has modified Seth Reno answer to handle dynamic object deserialized from NewtonSoft.Json.JObjcet.

public static bool PropertyExists(dynamic obj, string name)
    {
        if (obj == null) return false;
        if (obj is ExpandoObject)
            return ((IDictionary<string, object>)obj).ContainsKey(name);
        if (obj is IDictionary<string, object> dict1)
            return dict1.ContainsKey(name);
        if (obj is IDictionary<string, JToken> dict2)
            return dict2.ContainsKey(name);
        return obj.GetType().GetProperty(name) != null;
    }

How to implement my very own URI scheme on Android

This is very possible; you define the URI scheme in your AndroidManifest.xml, using the <data> element. You setup an intent filter with the <data> element filled out, and you'll be able to create your own scheme. (More on intent filters and intent resolution here.)

Here's a short example:

<activity android:name=".MyUriActivity">
    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="myapp" android:host="path" />
    </intent-filter>
</activity>

As per how implicit intents work, you need to define at least one action and one category as well; here I picked VIEW as the action (though it could be anything), and made sure to add the DEFAULT category (as this is required for all implicit intents). Also notice how I added the category BROWSABLE - this is not necessary, but it will allow your URIs to be openable from the browser (a nifty feature).

Is string in array?

You can also use LINQ to iterate over the array. or you can use the Find method which takes a delegate to search for it. However I think the find method is a bit more expensive then just looping through.

Reducing MongoDB database file size

Mongodb 3.0 and higher has a new storage engine - WiredTiger. In my case switching engine reduced disk usage from 100 Gb to 25Gb.

Table 'performance_schema.session_variables' doesn't exist

I was able to log on to the mysql server after running the command @robregonm suggested:

mysql_upgrade -u root -p --force

A MySQL server restart is required.

Vue.js get selected option on @change

The changed value will be in event.target.value

_x000D_
_x000D_
const app = new Vue({_x000D_
  el: "#app",_x000D_
  data: function() {_x000D_
    return {_x000D_
      message: "Vue"_x000D_
    }_x000D_
  },_x000D_
  methods: {_x000D_
    onChange(event) {_x000D_
      console.log(event.target.value);_x000D_
    }_x000D_
  }_x000D_
})
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>_x000D_
<div id="app">_x000D_
  <select name="LeaveType" @change="onChange" class="form-control">_x000D_
   <option value="1">Annual Leave/ Off-Day</option>_x000D_
   <option value="2">On Demand Leave</option>_x000D_
</select>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Delete data with foreign key in SQL Server table

Usefull script which you can delete all data in all tables of a database , replace tt with you databse name :

declare @tablename nvarchar(100)
declare c1 cursor for
SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_CATALOG='tt' AND TABLE_TYPE='BASE TABLE'

open  c1
fetch next from c1 into @tablename

while @@FETCH_STATUS = 0
    begin
    print @t1
        exec('alter table ' + @tablename + ' nocheck constraint all')
        exec('delete from ' + @tablename)
        exec ('alter table ' + @tablename + ' check constraint all')
        fetch next from c1 into @tablename
    end
close c1
DEALLOCATE c1

Extract images from PDF without resampling, in python?

Well I have been struggling with this for many weeks, many of these answers helped me through, but there was always something missing, apparently no one here has ever had problems with jbig2 encoded images.

In the bunch of PDF that I am to scan, images encoded in jbig2 are very popular.

As far as I understand there are many copy/scan machines that scan papers and transform them into PDF files full of jbig2 encoded images.

So after many days of tests decided to go for the answer proposed here by dkagedal long time ago.

Here is my step by step on linux: (if you have another OS I suggest to use a linux docker it's going to be much easier.)

First step:

apt-get install poppler-utils

Then I was able to run command line tool called pdfimages like this:

pdfimages -all myfile.pdf ./images_found/

With the above command you will be able to extract all the images contained in myfile.pdf and you will have them saved inside images_found (you have to create images_found before)

In the list you will find several types of images, png, jpg, tiff; all these are easily readable with any graphic tool.

Then you will have some files named like: -145.jb2e and -145.jb2g.

These 2 files contain ONE IMAGE encoded in jbig2 saved in 2 different files one for the header and one for the data

Again I have lost many days trying to find out how to convert those files into something readable and finally I came across this tool called jbig2dec

So first you need to install this magic tool:

apt-get install jbig2dec

then you can run:

jbig2dec -t png -145.jb2g -145.jb2e

You are going to finally be able to get all extracted images converted into something useful.

good luck!

What is the total amount of public IPv4 addresses?

Public IP Addresses

https://github.com/stephenlb/geo-ip will generate a list of Valid IP Public Addresses including Localities.

'1.0.0.0/8' to '191.0.0.0/8' are the valid public IP Address range exclusive of the reserved Private IP Addresses as follows:

import iptools
## Private IP Addresses
private_ips = iptools.IpRangeList(
    '0.0.0.0/8',      '10.0.0.0/8',     '100.64.0.0/10', '127.0.0.0/8',
    '169.254.0.0/16', '172.16.0.0/12',  '192.0.0.0/24',  '192.0.2.0/24',
    '192.88.99.0/24', '192.168.0.0/16', '198.18.0.0/15', '198.51.100.0/24',
    '203.0.113.0/24', '224.0.0.0/4',    '240.0.0.0/4',   '255.255.255.255/32'
)

IP Generator

Generates a JSON dump of IP Addresses and associated Geo information. Note that the valid public IP Address range is from '1.0.0.0/8' to '191.0.0.0/8' excluding the reserved Private IP Address ranges shown lower down in this readme.

docker build -t geo-ip .
docker run -e IPRANGE='54.0.0.0/30' geo-ip               ## a few IPs
docker run -e IPRANGE='54.0.0.0/26' geo-ip               ## a few more IPs
docker run -e IPRANGE='54.0.0.0/16' geo-ip               ## a lot more IPs
docker run -e IPRANGE='0.0.0.0/0'   geo-ip               ## ALL IPs ( slooooowwwwww )
docker run -e IPRANGE='0.0.0.0/0'   geo-ip > geo-ip.json ## ALL IPs saved to JSON File
docker run geo-ip 

A little faster option for scanning all valid public addresses:

for i in $(seq 1 191); do \
    docker run -e IPRANGE="$i.0.0.0/8" geo-ip; \
    sleep 1; \ 
done

This prints less than 4,228,250,625 JSON lines to STDOUT. Here is an example of one of the lines:

{"city": "Palo Alto", "ip": "0.0.0.0", "longitude": -122.1274,
 "continent": "North America", "continent_code": "NA",
 "state": "California", "country": "United States", "latitude": 37.418,
 "iso_code": "US", "state_code": "CA", "aso": "PubNub",
 "asn": "11404", "zip_code": "94107"}

Private and Reserved IP Range

The dockerfile in the repo above will exclude non-usable IP addresses following the guide from the wikipedia article: https://en.wikipedia.org/wiki/Reserved_IP_addresses

MaxMind Geo IP

The dockerfile imports a free public Database provided by https://www.maxmind.com/en/home

In PHP, how do you change the key of an array element?

best way is using reference, and not using unset (which make another step to clean memory)

$tab = ['two' => [] ];

solution:

$tab['newname'] = & $tab['two'];

you have one original and one reference with new name.

or if you don't want have two names in one value is good make another tab and foreach on reference

foreach($tab as $key=> & $value) {
    if($key=='two') { 
        $newtab["newname"] = & $tab[$key];
     } else {
        $newtab[$key] = & $tab[$key];
     }
}

Iterration is better on keys than clone all array, and cleaning old array if you have long data like 100 rows +++ etc..

Bash checking if string does not contain other string

As mainframer said, you can use grep, but i would use exit status for testing, try this:

#!/bin/bash
# Test if anotherstring is contained in teststring
teststring="put you string here"
anotherstring="string"

echo ${teststring} | grep --quiet "${anotherstring}"
# Exit status 0 means anotherstring was found
# Exit status 1 means anotherstring was not found

if [ $? = 1 ]
then
  echo "$anotherstring was not found"
fi

SQLite3 database or disk is full / the database disk image is malformed

To repair a corrupt database you can use the sqlite3 commandline utility. Type in the following commands in a shell after setting the environment variables:

cd $DATABASE_LOCATION
echo '.dump'|sqlite3 $DB_NAME|sqlite3 repaired_$DB_NAME
mv $DB_NAME corrupt_$DB_NAME
mv repaired_$DB_NAME $DB_NAME

This code helped me recover a SQLite database I use as a persistent store for Core Data and which produced the following error upon save:

Could not save: NSError 259 in Domain NSCocoaErrorDomain { NSFilePath = mydata.db NSUnderlyingException = Fatal error. The database at mydata.db is corrupted. SQLite error code:11, 'database disk image is malformed' }

Open files in 'rt' and 'wt' modes

The t indicates text mode, meaning that \n characters will be translated to the host OS line endings when writing to a file, and back again when reading. The flag is basically just noise, since text mode is the default.

Other than U, those mode flags come directly from the standard C library's fopen() function, a fact that is documented in the sixth paragraph of the python2 documentation for open().

As far as I know, t is not and has never been part of the C standard, so although many implementations of the C library accept it anyway, there's no guarantee that they all will, and therefore no guarantee that it will work on every build of python. That explains why the python2 docs didn't list it, and why it generally worked anyway. The python3 docs make it official.

Custom seekbar (thumb size, color and background)

No shadow and no rounded borders in the bar

You are using an image so the easiest solution is row your boat with the flow,

You cannot give heights manually,yes you can but make sure it gets enough space to show your full image view there

  • easiest way is use android:layout_height="wrap_content" for SeekBar
  • To get more clear rounded borders you can easily use the same image that you have used with another color.

I am no good with Photoshop but I managed to edit a background one for a test

seekbar_brown seekbar_brown_to_show_progress.png

<SeekBar
    android:splitTrack="false"   // for unwanted white space in thumb
    android:id="@+id/seekBar_luminosite"
    android:layout_width="250dp"   // use your own size
    android:layout_height="wrap_content"
    android:minHeight="10dp"
    android:minWidth="15dp"
    android:maxHeight="15dp"
    android:maxWidth="15dp"
    android:progress="50"
    android:progressDrawable="@drawable/custom_seekbar_progress"
    android:thumb="@drawable/custom_thumb" />

custom_seekbar_progress.xml

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@android:id/background"
        android:drawable="@drawable/seekbar" />
    <item android:id="@android:id/progress">
        <clip android:drawable="@drawable/seekbar_brown_to_show_progress" />
    </item>
</layer-list>

custom_thumb.xml is same as yours

Finally android:splitTrack="false" will remove the unwanted white space in your thumb

Let's have a look at the output :

enter image description here

How to import an existing project from GitHub into Android Studio

In Github click the "Clone or download" button of the project you want to import --> download the ZIP file and unzip it. In Android Studio Go to File -> New Project -> Import Project and select the newly unzipped folder -> press OK. It will build the Gradle automatically.

Good Luck with your project

How to set cursor position in EditText?

as a reminder: if you are using edittext.setSelection() to set the cursor, and it is NOT working while setting up an alertdialog for example, make sure to set the selection() AFTER the dialog has been created

example:

AlertDialog dialog = builder.show();
input.setSelection(x,y);

How to generate serial version UID in Intellij

with in the code editor, Open the class you want to create the UID for , Right click -> Generate -> SerialVersionUID. You may need to have the GenerateSerialVersionUID plugin installed for this to work.

In the shell, what does " 2>&1 " mean?

I found this brilliant post on redirection: All about redirections

Redirect both standard output and standard error to a file

$ command &>file

This one-liner uses the &> operator to redirect both output streams - stdout and stderr - from command to file. This is Bash's shortcut for quickly redirecting both streams to the same destination.

Here is how the file descriptor table looks like after Bash has redirected both streams:

Enter image description here

As you can see, both stdout and stderr now point to file. So anything written to stdout and stderr gets written to file.

There are several ways to redirect both streams to the same destination. You can redirect each stream one after another:

$ command >file 2>&1

This is a much more common way to redirect both streams to a file. First stdout is redirected to file, and then stderr is duplicated to be the same as stdout. So both streams end up pointing to file.

When Bash sees several redirections it processes them from left to right. Let's go through the steps and see how that happens. Before running any commands, Bash's file descriptor table looks like this:

Enter image description here

Now Bash processes the first redirection >file. We've seen this before and it makes stdout point to file:

Enter image description here

Next Bash sees the second redirection 2>&1. We haven't seen this redirection before. This one duplicates file descriptor 2 to be a copy of file descriptor 1 and we get:

Enter image description here

Both streams have been redirected to file.

However be careful here! Writing

command >file 2>&1

is not the same as writing:

$ command 2>&1 >file

The order of redirects matters in Bash! This command redirects only the standard output to the file. The stderr will still print to the terminal. To understand why that happens, let's go through the steps again. So before running the command, the file descriptor table looks like this:

Enter image description here

Now Bash processes redirections left to right. It first sees 2>&1 so it duplicates stderr to stdout. The file descriptor table becomes:

Enter image description here

Now Bash sees the second redirect, >file, and it redirects stdout to file:

Enter image description here

Do you see what happens here? Stdout now points to file, but the stderr still points to the terminal! Everything that gets written to stderr still gets printed out to the screen! So be very, very careful with the order of redirects!

Also note that in Bash, writing

$ command &>file

is exactly the same as:

$ command >&file

How to margin the body of the page (html)?

You need to use css. It's how modern web design gets things done.

This is a basic css walk through.

Your html file would be like:

(really simple html)

    <html>
    <head>
    <link rel="stylesheet" type="text/css" href="mystyle.css" />
    </head>
    <body>
    </body>
    <html>

Your css file (mystyle.css) would look like:

body 
{
 margin-top:0px;
 margin-left:0px;
 margin-right:0px;

}

PHP/MySQL: How to create a comment section in your website

I'm working on this right now as well. You should also add a datetime of the comment. You'll need this later when you want to sort by most recent.

Here are some of the db fields i'm using.

id (auto incremented)
name
email
text
datetime
approved

Checking if a string array contains a value, and if so, getting its position

EDIT: I hadn't noticed you needed the position as well. You can't use IndexOf directly on a value of an array type, because it's implemented explicitly. However, you can use:

IList<string> arrayAsList = (IList<string>) stringArray;
int index = arrayAsList.IndexOf(value);
if (index != -1)
{
    ...
}

(This is similar to calling Array.IndexOf as per Darin's answer - just an alternative approach. It's not clear to me why IList<T>.IndexOf is implemented explicitly in arrays, but never mind...)

How to inject Javascript in WebBrowser control?

The managed wrapper for the HTML document doesn't completely implement the functionality you need, so you need to dip into the MSHTML API to accomplish what you want:

1) Add a reference to MSHTML, which will probalby be called "Microsoft HTML Object Library" under COM references.

2) Add 'using mshtml;' to your namespaces.

3) Get a reference to your script element's IHTMLElement:

IHTMLElement iScriptEl = (IHTMLElement)scriptEl.DomElement;

4) Call the insertAdjacentText method, with the first parameter value of "afterBegin". All the possible values are listed here:

iScriptEl.insertAdjacentText("afterBegin", "function sayHello() { alert('hello') }");

5) Now you'll be able to see the code in the scriptEl.InnerText property.

Hth, Richard

Class type check in TypeScript

4.19.4 The instanceof operator

The instanceof operator requires the left operand to be of type Any, an object type, or a type parameter type, and the right operand to be of type Any or a subtype of the 'Function' interface type. The result is always of the Boolean primitive type.

So you could use

mySprite instanceof Sprite;

Note that this operator is also in ActionScript but it shouldn't be used there anymore:

The is operator, which is new for ActionScript 3.0, allows you to test whether a variable or expression is a member of a given data type. In previous versions of ActionScript, the instanceof operator provided this functionality, but in ActionScript 3.0 the instanceof operator should not be used to test for data type membership. The is operator should be used instead of the instanceof operator for manual type checking, because the expression x instanceof y merely checks the prototype chain of x for the existence of y (and in ActionScript 3.0, the prototype chain does not provide a complete picture of the inheritance hierarchy).

TypeScript's instanceof shares the same problems. As it is a language which is still in its development I recommend you to state a proposal of such facility.

See also:

Check if Internet Connection Exists with jQuery?

Sending XHR requests is bad because it could fail if that particular server is down. Instead, use googles API library to load their cached version(s) of jQuery.

You can use googles API to perform a callback after loading jQuery, and this will check if jQuery was loaded successfully. Something like the code below should work:

<script type="text/javascript">
    google.load("jquery");

    // Call this function when the page has been loaded
    function test_connection() {
        if($){
            //jQuery WAS loaded.
        } else {
            //jQuery failed to load.  Grab the local copy.
        }
    }
    google.setOnLoadCallback(test_connection);
</script>

The google API documentation can be found here.

"unadd" a file to svn before commit

Try svn revert filename for every file you don't need and haven't yet committed. Or alternatively do svn revert -R folder for the problematic folder and then re-do the operation with correct ignoring configuration.

From the documentation:

 you can undo any scheduling operations:

$ svn add mistake.txt whoops
A         mistake.txt
A         whoops
A         whoops/oopsie.c

$ svn revert mistake.txt whoops
Reverted mistake.txt
Reverted whoops

Console app arguments, how arguments are passed to Main method

The main method of the runtime engine looks something like int main(int argc, char *argv[]), where argc is a count of the number of arguments and argv is an array of pointers to each. The runtime engine converts this into a form that is more natural to c#.

Prior to that main method being called, everything is in assembly language. It has access to the command line arguments (because the operating system makes that available to every process that starts), but that assembly language needs to convert a single string of the full command line into multiple substrings (using whitespace to separate them) before it's ready to pass them into main().

Query to count the number of tables I have in MySQL

There may be multiple ways to count the tables of a database. My favorite is this on:

SELECT
    COUNT(*)
FROM
    `information_schema`.`tables`
WHERE
    `table_schema` = 'my_database_name'
;

Inheriting constructors

Constructors are not inherited. They are called implicitly or explicitly by the child constructor.

The compiler creates a default constructor (one with no arguments) and a default copy constructor (one with an argument which is a reference to the same type). But if you want a constructor that will accept an int, you have to define it explicitly.

class A
{
public: 
    explicit A(int x) {}
};

class B: public A
{
public:
    explicit B(int x) : A(x) { }
};

UPDATE: In C++11, constructors can be inherited. See Suma's answer for details.

How to save a PNG image server-side, from a base64 data string

You need to extract the base64 image data from that string, decode it and then you can save it to disk, you don't need GD since it already is a png.

$data = 'data:image/png;base64,AAAFBfj42Pj4';

list($type, $data) = explode(';', $data);
list(, $data)      = explode(',', $data);
$data = base64_decode($data);

file_put_contents('/tmp/image.png', $data);

And as a one-liner:

$data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $data));

An efficient method for extracting, decoding, and checking for errors is:

if (preg_match('/^data:image\/(\w+);base64,/', $data, $type)) {
    $data = substr($data, strpos($data, ',') + 1);
    $type = strtolower($type[1]); // jpg, png, gif

    if (!in_array($type, [ 'jpg', 'jpeg', 'gif', 'png' ])) {
        throw new \Exception('invalid image type');
    }
    $data = str_replace( ' ', '+', $data );
    $data = base64_decode($data);

    if ($data === false) {
        throw new \Exception('base64_decode failed');
    }
} else {
    throw new \Exception('did not match data URI with image data');
}

file_put_contents("img.{$type}", $data);

Re-sign IPA (iPhone)

If you have an app with extensions and/or a watch app and you have multiple provisioning profiles for each extension/watch app then you should use this script to re-sign the ipa file.

Re-signing script at Github

Here is an example of how to use this script:

./resign.sh YourApp.ipa "iPhone Distribution: YourCompanyOrDeveloperName" -p <path_to_provisioning_profile_for_app>.mobileprovision -p <path_to_provisioning_profile_for_watchkitextension>.mobileprovision -p <path_to_provisioning_profile_for_watchkitapp>.mobileprovision -p <path_to_provisioning_profile_for_todayextension>.mobileprovision  resignedYourApp.ipa

You can include other extension provisioning profiles too by adding it with yet another -p option.

For me - all the provisioning profiles were signed by the same certificate/signing identity.

How to find out what type of a Mat object is with Mat::type() in OpenCV

This was answered by a few others but I found a solution that worked really well for me.

System.out.println(CvType.typeToString(yourMat.type()));

What is the difference between statically typed and dynamically typed languages?

Simply put it this way: in a statically typed language variables' types are static, meaning once you set a variable to a type, you cannot change it. That is because typing is associated with the variable rather than the value it refers to.

For example in Java:

String str = "Hello";  //variable str statically typed as string
str = 5;               //would throw an error since str is supposed to be a string only

Where on the other hand: in a dynamically typed language variables' types are dynamic, meaning after you set a variable to a type, you CAN change it. That is because typing is associated with the value it assumes rather than the variable itself.

For example in Python:

str = "Hello" # variable str is linked to a string value
str = 5       # now it is linked to an integer value; perfectly OK

So, it is best to think of variables in dynamically typed languages as just generic pointers to typed values.

To sum up, type describes (or should have described) the variables in the language rather than the language itself. It could have been better used as a language with statically typed variables versus a language with dynamically typed variables IMHO.

Statically typed languages are generally compiled languages, thus, the compilers check the types (make perfect sense right? as types are not allowed to be changed later on at run time).

Dynamically typed languages are generally interpreted, thus type checking (if any) happens at run time when they are used. This of course brings some performance cost, and is one of the reasons dynamic languages (e.g., python, ruby, php) do not scale as good as the typed ones (java, c#, etc.). From another perspective, statically typed languages have more of a start-up cost: makes you usually write more code, harder code. But that pays later off.

The good thing is both sides are borrowing features from the other side. Typed languages are incorporating more dynamic features, e.g., generics and dynamic libraries in c#, and dynamic languages are including more type checking, e.g., type annotations in python, or HACK variant of PHP, which are usually not core to the language and usable on demand.

When it comes to technology selection, neither side has an intrinsic superiority over the other. It is just a matter of preference whether you want more control to begin with or flexibility. just pick the right tool for the job, and make sure to check what is available in terms of the opposite before considering a switch.

How to increase an array's length

By definition arrays are fixed size. You can use instead an Arraylist wich is that, a "dynamic size" array. Actually what happens is that the VM "adjust the size"* of the array exposed by the ArrayList.

See also

*using back-copy arrays

Pipe to/from the clipboard in Bash script

on Wayland xcopy doesn't seem to work, use wl-clipboard instead. e.g. on fedora

sudo dnf install wl-clipboard

tree | wl-copy

wl-paste > file

Is there a max array length limit in C++?

There are two limits, both not enforced by C++ but rather by the hardware.

The first limit (should never be reached) is set by the restrictions of the size type used to describe an index in the array (and the size thereof). It is given by the maximum value the system's std::size_t can take. This data type is large enough to contain the size in bytes of any object

The other limit is a physical memory limit. The larger your objects in the array are, the sooner this limit is reached because memory is full. For example, a vector<int> of a given size n typically takes multiple times as much memory as an array of type vector<char> (minus a small constant value), since int is usually bigger than char. Therefore, a vector<char> may contain more items than a vector<int> before memory is full. The same counts for raw C-style arrays like int[] and char[].

Additionally, this upper limit may be influenced by the type of allocator used to construct the vector because an allocator is free to manage memory any way it wants. A very odd but nontheless conceivable allocator could pool memory in such a way that identical instances of an object share resources. This way, you could insert a lot of identical objects into a container that would otherwise use up all the available memory.

Apart from that, C++ doesn't enforce any limits.

How to solve Notice: Undefined index: id in C:\xampp\htdocs\invmgt\manufactured_goods\change.php on line 21

You are not getting value of $id=$_GET['id'];

And you are using it (before it gets initialised).

Use php's in built isset() function to check whether the variable is defied or not.

So, please update the line to:

$id = isset($_GET['id']) ? $_GET['id'] : '';

How to do a https request with bad certificate?

All of these answers are wrong! Do not use InsecureSkipVerify to deal with a CN that doesn't match the hostname. The Go developers unwisely were adamant about not disabling hostname checks (which has legitimate uses - tunnels, nats, shared cluster certs, etc), while also having something that looks similar but actually completely ignores the certificate check. You need to know that the certificate is valid and signed by a cert that you trust. But in common scenarios, you know that the CN won't match the hostname you connected with. For those, set ServerName on tls.Config. If tls.Config.ServerName == remoteServerCN, then the certificate check will succeed. This is what you want. InsecureSkipVerify means that there is NO authentication; and it's ripe for a Man-In-The-Middle; defeating the purpose of using TLS.

There is one legitimate use for InsecureSkipVerify: use it to connect to a host and grab its certificate, then immediately disconnect. If you setup your code to use InsecureSkipVerify, it's generally because you didn't set ServerName properly (it will need to come from an env var or something - don't belly-ache about this requirement... do it correctly).

In particular, if you use client certs and rely on them for authentication, you basically have a fake login that doesn't actually login any more. Refuse code that does InsecureSkipVerify, or you will learn what is wrong with it the hard way!

Way to create multiline comments in Bash?

I tried the chosen answer, but found when I ran a shell script having it, the whole thing was getting printed to screen (similar to how jupyter notebooks print out everything in '''xx''' quotes) and there was an error message at end. It wasn't doing anything, but: scary. Then I realised while editing it that single-quotes can span multiple lines. So.. lets just assign the block to a variable.

x='
echo "these lines will all become comments."
echo "just make sure you don_t use single-quotes!"

ls -l
date

'

MySQL default datetime through phpmyadmin

You can't set CURRENT_TIMESTAMP as default value with DATETIME.

But you can do it with TIMESTAMP.

See the difference here.

Words from this blog

The DEFAULT value clause in a data type specification indicates a default value for a column. With one exception, the default value must be a constant; it cannot be a function or an expression.

This means, for example, that you cannot set the default for a date column to be the value of a function such as NOW() or CURRENT_DATE.

The exception is that you can specify CURRENT_TIMESTAMP as the default for a TIMESTAMP column.

What are the differences between LinearLayout, RelativeLayout, and AbsoluteLayout?

Definitions:

  • Frame Layout: This is designed to block out an area on the screen to display a single item.
  • Linear Layout: A layout that arranges its children in a single column or a single row.
  • Relative Layout: This layout is a view group that displays child views in relative positions.
  • Table Layout: A layout that arranges its children into rows and columns.

More Information:

FrameLayout

FrameLayout is designed to block out an area on the screen to display a single item. Generally, FrameLayout should be used to hold a single child view, because it can be difficult to organize child views in a way that's scalable to different screen sizes without the children overlapping each other. You can, however, add multiple children to a FrameLayout and control their position within the FrameLayout by assigning gravity to each child, using the android:layout_gravity attribute.

Child views are drawn in a stack, with the most recently added child on top. The size of the FrameLayout is the size of its largest child (plus padding), visible or not (if the FrameLayout's parent permits).

RelativeLayout

A RelativeLayout is a very powerful utility for designing a user interface because it can eliminate nested view groups and keep your layout hierarchy flat, which improves performance. If you find yourself using several nested LinearLayout groups, you may be able to replace them with a single RelativeLayout.

(Current docs here)

TableLayout

A TableLayout consists of a number of TableRow objects, each defining a row (actually, you can have other children, which will be explained below). TableLayout containers do not display border lines for their rows, columns, or cells. Each row has zero or more cells; each cell can hold one View object. The table has as many columns as the row with the most cells. A table can leave cells empty. Cells can span columns, as they can in HTML.

The width of a column is defined by the row with the widest cell in that column.


Note: Absolute Layout is deprecated.

What is the difference between method overloading and overriding?

Method overriding is when a child class redefines the same method as a parent class, with the same parameters. For example, the standard Java class java.util.LinkedHashSet extends java.util.HashSet. The method add() is overridden in LinkedHashSet. If you have a variable that is of type HashSet, and you call its add() method, it will call the appropriate implementation of add(), based on whether it is a HashSet or a LinkedHashSet. This is called polymorphism.

Method overloading is defining several methods in the same class, that accept different numbers and types of parameters. In this case, the actual method called is decided at compile-time, based on the number and types of arguments. For instance, the method System.out.println() is overloaded, so that you can pass ints as well as Strings, and it will call a different version of the method.

PostgreSQL return result set as JSON array?

Also if you want selected field from table and aggregated then as array .

SELECT json_agg(json_build_object('data_a',a,
                                  'data_b',b,
))  from t;

The result will come .

 [{'data_a':1,'data_b':'value1'}
  {'data_a':2,'data_b':'value2'}]

Creating a new column based on if-elif-else condition

enter image description here

Lets say above one is your original dataframe and you want to add a new column 'old'

If age greater than 50 then we consider as older=yes otherwise False

step 1: Get the indexes of rows whose age greater than 50

row_indexes=df[df['age']>=50].index

step 2: Using .loc we can assign a new value to column

df.loc[row_indexes,'elderly']="yes"

same for age below less than 50

row_indexes=df[df['age']<50].index

df[row_indexes,'elderly']="no"

how to copy only the columns in a DataTable to another DataTable?

DataTable.Clone() should do the trick.

DataTable newTable = originalTable.Clone();

Why "net use * /delete" does not work but waits for confirmation in my PowerShell script?

With PowerShell 5.1 in Windows 10 you can use:

Get-SmbMapping | Remove-SmbMapping -Confirm:$false

Iterating over Numpy matrix rows to apply a function each?

While you should certainly provide more information, if you are trying to go through each row, you can just iterate with a for loop:

import numpy
m = numpy.ones((3,5),dtype='int')
for row in m:
  print str(row)

How to read data from excel file using c#

Convert the excel file to .csv file (comma separated value file) and now you can easily be able to read it.

How to make div follow scrolling smoothly with jQuery?

The solution can be boiled down to this:

var el=$('#follow-scroll');
var elpos=el.offset().top;
$(window).scroll(function () {
    var y=$(this).scrollTop();
    if(y<elpos){el.stop().animate({'top':0},500);}
    else{el.stop().animate({'top':y-elpos},500);}
});

I have changed the assignment of el because finding a single element by class is not a great habit to get in to; if you only want one element find it by id, if you want to iterate over a collection of elements then find them by class.

please note - my answer here refers to the accepted answer at that time (it still is the accepted answer at the moment, but has since been edited and therefore my answer no longer "boils down" what you see in @Martti Lane's answer on this page; my answer "boils down" his original, accepted, answer; you can take a look at the edit history of @Martti's answer if you're interested in what I "boiled down".)

Save PL/pgSQL output from PostgreSQL to a CSV file

To Download CSV file with column names as HEADER use this command:

Copy (Select * From tableName) To '/tmp/fileName.csv' With CSV HEADER;

Getting Keyboard Input

You can use Scanner class

To Read from Keyboard (Standard Input) You can use Scanner is a class in java.util package.

Scanner package used for obtaining the input of the primitive types like int, double etc. and strings. It is the easiest way to read input in a Java program, though not very efficient.

  1. To create an object of Scanner class, we usually pass the predefined object System.in, which represents the standard input stream (Keyboard).

For example, this code allows a user to read a number from System.in:

Scanner sc = new Scanner(System.in);
     int i = sc.nextInt();

Some Public methods in Scanner class.

  • hasNext() Returns true if this scanner has another token in its input.
  • nextInt() Scans the next token of the input as an int.
  • nextFloat() Scans the next token of the input as a float.
  • nextLine() Advances this scanner past the current line and returns the input that was skipped.
  • nextDouble() Scans the next token of the input as a double.
  • close() Closes this scanner.

For more details of Public methods in Scanner class.

Example:-

import java.util.Scanner;                      //importing class

class ScannerTest {
  public static void main(String args[]) {
    Scanner sc = new Scanner(System.in);       // Scanner object

    System.out.println("Enter your rollno");
    int rollno = sc.nextInt();
    System.out.println("Enter your name");
    String name = sc.next();
    System.out.println("Enter your fee");
    double fee = sc.nextDouble();
    System.out.println("Rollno:" + rollno + " name:" + name + " fee:" + fee);
    sc.close();                              // closing object
  }
}

How do I escape a reserved word in Oracle?

Oracle does use double-quotes, but you most likely need to place the object name in upper case, e.g. "TABLE". By default, if you create an object without double quotes, e.g.

CREATE TABLE table AS ...

Oracle would create the object as upper case. However, the referencing is not case sensitive unless you use double-quotes!

Android: Getting a file URI from a content URI?

Trying to handle the URI with content:// scheme by calling ContentResolver.query()is not a good solution. On HTC Desire running 4.2.2 you could get NULL as a query result.

Why not to use ContentResolver instead? https://stackoverflow.com/a/29141800/3205334

cannot redeclare block scoped variable (typescript)

The best explanation I could get is from Tamas Piro's post.

TLDR; TypeScript uses the DOM typings for the global execution environment. In your case there is a 'co' property on the global window object.

To solve this:

  1. Rename the variable, or
  2. Use TypeScript modules, and add an empty export{}:
export {};

or

  1. Configure your compiler options by not adding DOM typings:

Edit tsconfig.json in the TypeScript project directory.

{
    "compilerOptions": {
        "lib": ["es6"]
      }
}

Handle JSON Decode Error when nothing returned

If you don't mind importing the json module, then the best way to handle it is through json.JSONDecodeError (or json.decoder.JSONDecodeError as they are the same) as using default errors like ValueError could catch also other exceptions not necessarily connected to the json decode one.

from json.decoder import JSONDecodeError


try:
    qByUser = byUsrUrlObj.read()
    qUserData = json.loads(qByUser).decode('utf-8')
    questionSubjs = qUserData["all"]["questions"]
except JSONDecodeError as e:
    # do whatever you want

//EDIT (Oct 2020):

As @Jacob Lee noted in the comment, there could be the basic common TypeError raised when the JSON object is not a str, bytes, or bytearray. Your question is about JSONDecodeError, but still it is worth mentioning here as a note; to handle also this situation, but differentiate between different issues, the following could be used:

from json.decoder import JSONDecodeError


try:
    qByUser = byUsrUrlObj.read()
    qUserData = json.loads(qByUser).decode('utf-8')
    questionSubjs = qUserData["all"]["questions"]
except JSONDecodeError as e:
    # do whatever you want
except TypeError as e:
    # do whatever you want in this case

How to use Python requests to fake a browser visit a.k.a and generate User Agent?

Try doing this, using firefox as fake user agent (moreover, it's a good startup script for web scraping with the use of cookies):

#!/usr/bin/env python2
# -*- coding: utf8 -*-
# vim:ts=4:sw=4


import cookielib, urllib2, sys

def doIt(uri):
    cj = cookielib.CookieJar()
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
    page = opener.open(uri)
    page.addheaders = [('User-agent', 'Mozilla/5.0')]
    print page.read()

for i in sys.argv[1:]:
    doIt(i)

USAGE:

python script.py "http://www.ichangtou.com/#company:data_000008.html"

Why doesn't JavaScript support multithreading?

Without proper language support for thread syncronization, it doesn't even make sense for new implementations to try. Existing complex JS apps (e.g. anything using ExtJS) would most likely crash unexpectedly, but without a synchronized keyword or something similar, it would also be very hard or even impossible to write new programs that behave correctly.

Why doesn't os.path.join() work in this case?

The latter strings shouldn't start with a slash. If they start with a slash, then they're considered an "absolute path" and everything before them is discarded.

Quoting the Python docs for os.path.join:

If a component is an absolute path, all previous components are thrown away and joining continues from the absolute path component.

Note on Windows, the behaviour in relation to drive letters, which seems to have changed compared to earlier Python versions:

On Windows, the drive letter is not reset when an absolute path component (e.g., r'\foo') is encountered. If a component contains a drive letter, all previous components are thrown away and the drive letter is reset. Note that since there is a current directory for each drive, os.path.join("c:", "foo") represents a path relative to the current directory on drive C: (c:foo), not c:\foo.

Ignore Duplicates and Create New List of Unique Values in Excel

To remove duplicates from a column

  1. Sort the values in column A A->Z
  2. Select column B
  3. While column B is still selected, in the formula input box, enter

    =IF(TRIM(A1)=TRIM(A2),"",TRIM(A1))
    
  4. While Column B is still selected, select Edit -> Fill -> Down (in newer versions, simply select cell B1 and pull down the outer box to expand all the way down in the column)

Note: if column B is on another sheet, you may do Sheet1!A1 and Sheet1!A2.

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

How do you turn a Mongoose document into a plain object?

Mongoose Models inherit from Documents, which have a toObject() method. I believe what you're looking for should be the result of doc.toObject().

http://mongoosejs.com/docs/api.html#document_Document-toObject

How to do a SQL NOT NULL with a DateTime?

Just to rule out a possibility - it doesn't appear to have anything to do with the ANSI_NULLS option, because that controls comparing to NULL with the = and <> operators. IS [NOT] NULL works whether ANSI_NULLS is ON or OFF.

I've also tried this against SQL Server 2005 with isql, because ANSI_NULLS defaults to OFF when using DB-Library.

How do you modify a CSS style in the code behind file for divs in ASP.NET?

If you're newing up an element with initializer syntax, you can do something like this:

var row = new HtmlTableRow
{
  Cells =
  {
    new HtmlTableCell
    {
        InnerText = text,
        Attributes = { ["style"] = "min-width: 35px;" }
    },
  }
};

Or if using the CssStyleCollection specifically:

var row = new HtmlTableRow
{
  Cells =
  {
    new HtmlTableCell
    {
        InnerText = text,
        Style = { ["min-width"] = "35px" }
    },
  }
};

What does "\r" do in the following script?

The '\r' character is the carriage return, and the carriage return-newline pair is both needed for newline in a network virtual terminal session.


From the old telnet specification (RFC 854) (page 11):

The sequence "CR LF", as defined, will cause the NVT to be positioned at the left margin of the next print line (as would, for example, the sequence "LF CR").

However, from the latest specification (RFC5198) (page 13):

  1. ...

  2. In Net-ASCII, CR MUST NOT appear except when immediately followed by either NUL or LF, with the latter (CR LF) designating the "new line" function. Today and as specified above, CR should generally appear only when followed by LF. Because page layout is better done in other ways, because NUL has a special interpretation in some programming languages, and to avoid other types of confusion, CR NUL should preferably be avoided as specified above.

  3. LF CR SHOULD NOT appear except as a side-effect of multiple CR LF sequences (e.g., CR LF CR LF).

So newline in Telnet should always be '\r\n' but most implementations have either not been updated, or keeps the old '\n\r' for backwards compatibility.

htaccess - How to force the client's browser to clear the cache?

You can force browsers to cache something, but

You can't force browsers to clear their cache.

Thus the only (AMAIK) way is to use a new URL for your resources. Something like versioning.

What are the benefits of learning Vim?

I recently switched to VIM, and I think it's worth it. If you need to "just get something done", you can always stay in insert mode, where vim is (mostly) like a normal text editor.

I've noticed that things that didn't use to bother me, like reaching for the arrow keys, now feel wrong and too much effort. It's definitely decreased my hand motion and usage of the mouse, which is good for both ergonomics and productivity

What's the difference between '$(this)' and 'this'?

this reference a javascript object and $(this) used to encapsulate with jQuery.

Example =>

// Getting Name and modify css property of dom object through jQuery
var name = $(this).attr('name');
$(this).css('background-color','white')

// Getting form object and its data and work on..
this = document.getElementsByName("new_photo")[0]
formData = new FormData(this)

// Calling blur method on find input field with help of both as below
$(this).find('input[type=text]')[0].blur()

//Above is equivalent to
this = $(this).find('input[type=text]')[0]
this.blur()

//Find value of a text field with id "index-number"
this = document.getElementById("index-number");
this.value

or 

this = $('#index-number');
$(this).val(); // Equivalent to $('#index-number').val()
$(this).css('color','#000000')

Best Java obfuscator?

First, you really need to keep in mind that it's never impossible to reverse-engineer something. Everything is hackable. A smart developer using a smart IDE can already get far enough.

Well, you can find here a list. ProGuard is pretty good. I've used it myself, but only to "minify" Java code.

Python: Random numbers into a list

This is way late but in-case someone finds this helpful.

You could use list comprehension.

rand = [random.randint(0, 100) for x in range(1, 11)]
print(rand)

Output:

[974, 440, 305, 102, 822, 128, 205, 362, 948, 751]

Cheers!

Reading local text file into a JavaScript array

Using Node.js

sync mode:

var fs = require("fs");
var text = fs.readFileSync("./mytext.txt");
var textByLine = text.split("\n")

async mode:

var fs = require("fs");
fs.readFile("./mytext.txt", function(text){
    var textByLine = text.split("\n")
});

UPDATE

As of at least Node 6, readFileSync returns a Buffer, so it must first be converted to a string in order for split to work:

var text = fs.readFileSync("./mytext.txt").toString('utf-8');

Or

var text = fs.readFileSync("./mytext.txt", "utf-8");

What are good ways to prevent SQL injection?

SQL injection should not be prevented by trying to validate your input; instead, that input should be properly escaped before being passed to the database.

How to escape input totally depends on what technology you are using to interface with the database. In most cases and unless you are writing bare SQL (which you should avoid as hard as you can) it will be taken care of automatically by the framework so you get bulletproof protection for free.

You should explore this question further after you have decided exactly what your interfacing technology will be.

The model backing the <Database> context has changed since the database was created

I spent many days to solve this issue, analyzed many different posts and tried many options and finally fixed. This 2 projects in my solution using EF code first migrations:

  • Console Application "DataModel" that mainly using as assembly which contains all my code first entities, DbContext, Mirgations and generic repository. I have included to this project separate empty local database file (in DataModel/App_Data folder) to be able generate migrations from Package Manager Console.
  • WebApi, which references to DataModel project and uses local database file from WebApi/App_Data folder, that not included in project

I got this error when requested WebApi...

My environment:

  • Windows 8.1 x64
  • Visual Studio 2015 Professional with Update 1
  • all my projects targeted for .NET Framework 4.6.1
  • EntityFramework 6.1.3 from NuGet

Here I collected all the remarks you should pay attention and all conditions/requirements which must be met, to avoid mentioned exception :

  1. You should use only one version of EntityFramework Nuget package for all projects in your solution.
  2. Database, created by running sequentially all migration scripts should have the same structure/schema as you target database and correspond to entity model. Following 3 things must exactly correspond/reflect/match each other:
    • Your all migration script up to last
    • Current code first entity model state (DbContext, entities)
    • Target database
  3. Target database (mdf file) should be updated/correspond up to last migration script. Verify that "__MigrationHistory" table in your target database contains records for all migration scripts that you have, it means that all migration scripts was successfully applied to that database. I recommend you to use Visual Studio for generation correct code first entities and context that corresponds to your database, Project -> Add New Item -> ADO.NET Entity Data Model -> Code First from database: Of course, as an alternative, if you have no database you can write manually model (code first entities and context) and then generate initial migration and database.
  4. Name of connection string e.g. MyConnectionString in config file of startup project (Web.config/App.config):

    <configuration>
      <connectionStrings>
        <add name="MyConnectionString" connectionString="...">
      </connectionStrings>
    <configuration>
    

    should be equal to parameter passed in constructor of your DbContext:

     public partial class MyDbContext : DbContext
     {
        public MyDbContext()
           : base("name=MyConnectionString"){}
        ...
    
  5. Before using Package Manager Console, make sure that you are using correct database for update or generate migration and needed project is set as startup project of solution. For connect to database it will use connection string from that .config file, which in project, that is set as startup project.
  6. And the main, which fixed my issue: It is weird, but in my WebApi/bin folder DataModel.exe was old, not refreshed since last build. Since migrations was embedded in my assembly DataModel.exe then my WebApi updated database using old mirgations. I was confused why after updating database in WebApi it not corresponds to latest migration script from DataModel. Following code automatically creates(if not exists) or updates to latest migration local database in my WebApi/App_Data folder.

       public class WebApiApplication : System.Web.HttpApplication
       {
           protected void Application_Start()
           {
               Database.SetInitializer(new MigrateDatabaseToLatestVersion<ODS_DbContext, Configuration>()); 
               ...
    

    I tried clean and rebuild solution but it did not help, than I completely removed bin and obj folders from WebApi, deleted database files from WebApi/App_Data, built, restarted WebApi, made request to it, it created correct database - lazy initialization (using lines above), which corresponds to latest migration and exception didn't appear more. So, this may fix your problem:

    1. remove manually bin, obj folders from your startup project (which generates/updates your database)
    2. build your startup project or better clean and rebuild all you solution.
    3. recreate database by starting project (will execute lines above) or use Package Manager Console "update-database" command.
    4. manually check whether generated db and __MirgationHistory corresponds to latest migration script.

How to concatenate a std::string and an int?

#include <sstream>

template <class T>
inline std::string to_string (const T& t)
{
   std::stringstream ss;
   ss << t;
   return ss.str();
}

Then your usage would look something like this

   std::string szName = "John";
   int numAge = 23;
   szName += to_string<int>(numAge);
   cout << szName << endl;

Googled [and tested :p ]

No restricted globals

This is a simple and maybe not the best solution, but it works.

On the line above the line you get your error, paste this:

// eslint-disable-next-line no-restricted-globals

Creating Accordion Table with Bootstrap

For anyone who came here looking for how to get the true accordion effect and only allow one row to be expanded at a time, you can add an event handler for show.bs.collapse like so:

$('.collapse').on('show.bs.collapse', function () {
    $('.collapse.in').collapse('hide');
});

I modified this example to do so here: http://jsfiddle.net/QLfMU/116/

Calling Python in Java?

It depends on what do you mean by python functions? if they were written in cpython you can not directly call them you will have to use JNI, but if they were written in Jython you can easily call them from java, as jython ultimately generates java byte code.

Now when I say written in cpython or jython it doesn't make much sense because python is python and most code will run on both implementations unless you are using specific libraries which relies on cpython or java.

see here how to use Python interpreter in Java.

Print time in a batch file (milliseconds)

To time task in CMD is as simple as

echo %TIME% && your_command && cmd /v:on /c echo !TIME!

How do I select a random value from an enumeration?

Here's an alternative version as an Extension Method using LINQ.

using System;
using System.Linq;

public static class EnumExtensions
{
    public static Enum GetRandomEnumValue(this Type t)
    {
        return Enum.GetValues(t)          // get values from Type provided
            .OfType<Enum>()               // casts to Enum
            .OrderBy(e => Guid.NewGuid()) // mess with order of results
            .FirstOrDefault();            // take first item in result
    }
}

public static class Program
{
    public enum SomeEnum
    {
        One = 1,
        Two = 2,
        Three = 3,
        Four = 4
    }

    public static void Main()
    {
        for(int i=0; i < 10; i++)
        {
            Console.WriteLine(typeof(SomeEnum).GetRandomEnumValue());
        }
    }           
}

Two
One
Four
Four
Four
Three
Two
Four
One
Three

laravel the requested url was not found on this server

I resolved by doing the following: Check if there is a module called rewrite.load in your apache at:

cd /etc/apache2/mods-enabled/

If it does not exist execute the following excerpt:

sudo a2enmod rewrite

Otherwise, change the Apache configuration file to consolidate use of the "friendly URL".

sudo nano /etc/apache2/apache2.conf

Find the following code inside the editor:

<Directory /var/www/> 
   Options Indexes FollowSymLinks
   AllowOverride None
   Require all granted
</Directory> 

Change to:

<Directory /var/www/> 
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>

After that restart the Apache server via:

sudo /etc/init.d/apache2 restart

Is it possible to open a Windows Explorer window from PowerShell?

Just use the Invoke-Item cmdlet. For example, if you want to open a explorer window on the current directory you can do:

Invoke-Item .

Is there a version of JavaScript's String.indexOf() that allows for regular expressions?

It does not natively, but you certainly can add this functionality

<script type="text/javascript">

String.prototype.regexIndexOf = function( pattern, startIndex )
{
    startIndex = startIndex || 0;
    var searchResult = this.substr( startIndex ).search( pattern );
    return ( -1 === searchResult ) ? -1 : searchResult + startIndex;
}

String.prototype.regexLastIndexOf = function( pattern, startIndex )
{
    startIndex = startIndex === undefined ? this.length : startIndex;
    var searchResult = this.substr( 0, startIndex ).reverse().regexIndexOf( pattern, 0 );
    return ( -1 === searchResult ) ? -1 : this.length - ++searchResult;
}

String.prototype.reverse = function()
{
    return this.split('').reverse().join('');
}

// Indexes 0123456789
var str = 'caabbccdda';

alert( [
        str.regexIndexOf( /[cd]/, 4 )
    ,   str.regexLastIndexOf( /[cd]/, 4 )
    ,   str.regexIndexOf( /[yz]/, 4 )
    ,   str.regexLastIndexOf( /[yz]/, 4 )
    ,   str.lastIndexOf( 'd', 4 )
    ,   str.regexLastIndexOf( /d/, 4 )
    ,   str.lastIndexOf( 'd' )
    ,   str.regexLastIndexOf( /d/ )
    ]
);

</script>

I didn't fully test these methods, but they seem to work so far.

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

You don't need jQuery to achieve this. In your form add:

onsubmit="return buttonSubmit(this)

or in JavaScript:

myform.setAttribute("onsubmit", "return buttonSubmit(this)");

In your buttonSubmit function (or whatver you call it), you can submit the form using AJAX. buttonSubmit will only get called if your form is validated in HTML5.

In case this helps anyone, here is my buttonSubmit function:

function buttonSubmit(e)
{
    var ajax;
    var formData = new FormData();
    for (i = 0; i < e.elements.length; i++)
    {
        if (e.elements[i].type == "submit")
        {
            if (submitvalue == e.elements[i].value)
            {
                submit = e.elements[i];
                submit.disabled = true;
            }
        }
        else if (e.elements[i].type == "radio")
        {
            if (e.elements[i].checked)
                formData.append(e.elements[i].name, e.elements[i].value);
        }
        else
            formData.append(e.elements[i].name, e.elements[i].value);
    }
    formData.append("javascript", "javascript");
    var action = e.action;
    status = action.split('/').reverse()[0] + "-status";
    ajax = new XMLHttpRequest();
    ajax.addEventListener("load", manageLoad, false);
    ajax.addEventListener("error", manageError, false);
    ajax.open("POST", action);
    ajax.send(formData);
    return false;
}

Some of my forms contain multiple submit buttons, hence this line if (submitvalue == e.elements[i].value). I set the value of submitvalue using a click event.

Programmatically retrieve SQL Server stored procedure source that is identical to the source returned by the SQL Server Management Studio gui?

EXEC sp_helptext 'your procedure name';

This avoids the problem with INFORMATION_SCHEMA approach wherein the stored procedure gets cut off if it is too long.

Update: David writes that this isn't identical to his sproc...perhaps because it returns the lines as 'records' to preserve formatting? If you want to see the results in a more 'natural' format, you can use Ctrl-T first (output as text) and it should print it out exactly as you've entered it. If you are doing this in code, it is trivial to do a foreach to put together your results in exactly the same way.

Update 2: This will provide the source with a "CREATE PROCEDURE" rather than an "ALTER PROCEDURE" but I know of no way to make it use "ALTER" instead. Kind of a trivial thing, though, isn't it?

Update 3: See the comments for some more insight on how to maintain your SQL DDL (database structure) in a source control system. That is really the key to this question.

What is the C++ function to raise a number to a power?

Use the pow(x,y) function: See Here

Just include math.h and you're all set.

How to prevent page from reloading after form submit - JQuery

The <button> element, when placed in a form, will submit the form automatically unless otherwise specified. You can use the following 2 strategies:

  1. Use <button type="button"> to override default submission behavior
  2. Use event.preventDefault() in the onSubmit event to prevent form submission

Solution 1:

  • Advantage: simple change to markup
  • Disadvantage: subverts default form behavior, especially when JS is disabled. What if the user wants to hit "enter" to submit?

Insert extra type attribute to your button markup:

<button id="button" type="button" value="send" class="btn btn-primary">Submit</button>

Solution 2:

  • Advantage: form will work even when JS is disabled, and respects standard form UI/UX such that at least one button is used for submission

Prevent default form submission when button is clicked. Note that this is not the ideal solution because you should be in fact listening to the submit event, not the button click event:

$(document).ready(function () {
  // Listen to click event on the submit button
  $('#button').click(function (e) {

    e.preventDefault();

    var name = $("#name").val();
    var email = $("#email").val();

    $.post("process.php", {
      name: name,
      email: email
    }).complete(function() {
        console.log("Success");
      });
  });
});

Better variant:

In this improvement, we listen to the submit event emitted from the <form> element:

$(document).ready(function () {
  // Listen to submit event on the <form> itself!
  $('#main').submit(function (e) {

    e.preventDefault();

    var name = $("#name").val();
    var email = $("#email").val();

    $.post("process.php", {
      name: name,
      email: email
    }).complete(function() {
        console.log("Success");
      });
  });
});

Even better variant: use .serialize() to serialize your form, but remember to add name attributes to your input:

The name attribute is required for .serialize() to work, as per jQuery's documentation:

For a form element's value to be included in the serialized string, the element must have a name attribute.

<input type="text" id="name" name="name" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="Jane Doe">
<input type="text" id="email" name="email" class="form-control" id="inlineFormInputGroup" placeholder="[email protected]">

And then in your JS:

$(document).ready(function () {
  // Listen to submit event on the <form> itself!
  $('#main').submit(function (e) {

    // Prevent form submission which refreshes page
    e.preventDefault();

    // Serialize data
    var formData = $(this).serialize();

    // Make AJAX request
    $.post("process.php", formData).complete(function() {
      console.log("Success");
    });
  });
});

get all the images from a folder in php

//path to the directory to search/scan
        $directory = "";
         //echo "$directory"
        //get all files in a directory. If any specific extension needed just have to put the .extension
        //$local = glob($directory . "*"); 
        $local = glob("" . $directory . "{*.jpg,*.gif,*.png}", GLOB_BRACE);
        //print each file name
        echo "<ul>";

        foreach($local as $item)
        {
        echo '<li><a href="'.$item.'">'.$item.'</a></li>';
        }

        echo "</ul>";

How to stop line breaking in vim

Its strange that such a simple setting would require this amount of 'hocus-pocus' to work.

To answer your question now, for me it seemed to work with the combination of the following:

:set wrap linebreak nolist

(this seems to prevent existing lines from breaking, just wrap.)

AND

set formatoptions=l

(this prevents new/edited lines from breaking, while += does not do it for me as other settings/plugins seem to find space and add their own options which override mine.)

Blocking device rotation on mobile web pages

New API's are developing (and are currently available)!

screen.orientation.lock();   // webkit only

and

screen.lockOrientation("orientation");

Where "orientation" can be any of the following:

portrait-primary - It represents the orientation of the screen when it is in its primary portrait mode. A screen is considered in its primary portrait mode if the device is held in its normal position and that position is in portrait, or if the normal position of the device is in landscape and the device held turned by 90° clockwise. The normal position is device dependant.

portrait-secondary - It represents the orientation of the screen when it is in its secondary portrait mode. A screen is considered in its secondary portrait mode if the device is held 180° from its normal position and that position is in portrait, or if the normal position of the device is in landscape and the device held is turned by 90° anticlockwise. The normal position is device dependant.

landscape-primary - It represents the orientation of the screen when it is in its primary landscape mode. A screen is considered in its primary landscape mode if the device is held in its normal position and that position is in landscape, or if the normal position of the device is in portrait and the device held is turned by 90° clockwise. The normal position is device dependant.

landscape-secondary - It represents the orientation of the screen when it is in its secondary landscape mode. A screen is considered in its secondary landscape mode if the device held is 180° from its normal position and that position is in landscape, or if the normal position of the device is in portrait and the device held is turned by 90° anticlockwise. The normal position is device dependant.

portrait - It represents both portrait-primary and portrait-secondary.

landscape - It represents both landscape-primary and landscape-secondary.

default - It represents either portrait-primary and landscape-primary depends on natural orientation of devices. For example, if the panel resolution is 1280*800, default will make it landscape, if the resolution is 800*1280, default will make it to portrait.

Mozilla recommends adding a lockOrientationUniversal to screen to make it more cross-browser compatible.

screen.lockOrientationUniversal = screen.lockOrientation || screen.mozLockOrientation || screen.msLockOrientation;

Go here for more info: https://developer.mozilla.org/en-US/docs/Web/API/Screen/lockOrientation

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

According to my perspective,

O(1) means time to execute one operation or instruction at a time is one, in time complexity analysis of algorithm for best case.

Extracting Path from OpenFileDialog path/filename

how about this:

string fullPath = ofd.FileName;
string fileName = ofd.SafeFileName;
string path = fullPath.Replace(fileName, "");

How to get maximum value from the Collection (for example ArrayList)?

model =list.stream().max(Comparator.comparing(Model::yourSortList)).get();

C++ Fatal Error LNK1120: 1 unresolved externals

I incurred this error once.

It turns out I had named my program ProgramMame.ccp instead of ProgramName.cpp

easy to do ...

Hope this may help

Angular pass callback function to child component as @Input similar to AngularJS way

UPDATE

This answer was submitted when Angular 2 was still in alpha and many of the features were unavailable / undocumented. While the below will still work, this method is now entirely outdated. I strongly recommend the accepted answer over the below.

Original Answer

Yes in fact it is, however you will want to make sure that it is scoped correctly. For this I've used a property to ensure that this means what I want it to.

@Component({
  ...
  template: '<child [myCallback]="theBoundCallback"></child>',
  directives: [ChildComponent]
})
export class ParentComponent{
  public theBoundCallback: Function;

  public ngOnInit(){
    this.theBoundCallback = this.theCallback.bind(this);
  }

  public theCallback(){
    ...
  }
}

@Component({...})
export class ChildComponent{
  //This will be bound to the ParentComponent.theCallback
  @Input()
  public myCallback: Function; 
  ...
}

How to get names of classes inside a jar file?

You can try this :

unzip -v /your/jar.jar

This will be helpful only if your jar is executable i.e. in manifest you have defined some class as main class

using c# .net libraries to check for IMAP messages from gmail servers

Lumisoft.net has both IMAP client and server code that you can use.

I've used it to download email from Gmail. The object model isn't the best, but it is workable, and seems to be rather flexible and stable.

Here is the partial result of my spike to use it. It fetches the first 10 headers with envelopes, and then fetches the full message:

using (var client = new IMAP_Client())
{
    client.Connect(_hostname, _port, _useSsl);
    client.Authenticate(_username, _password);
    client.SelectFolder("INBOX");
     var sequence = new IMAP_SequenceSet();
    sequence.Parse("0:10");
    var fetchItems = client.FetchMessages(sequence, IMAP_FetchItem_Flags.Envelope | IMAP_FetchItlags.UID,
                                        false, true);
    foreach (var fetchItem in fetchItems)
    {
        Console.Out.WriteLine("message.UID = {0}", fetchItem.UID);
        Console.Out.WriteLine("message.Envelope.From = {0}", fetchItem.Envelope.From);
        Console.Out.WriteLine("message.Envelope.To = {0}", fetchItem.Envelope.To);
        Console.Out.WriteLine("message.Envelope.Subject = {0}", fetchItem.Envelope.Subject);
        Console.Out.WriteLine("message.Envelope.MessageID = {0}", fetchItem.Envelope.MessageID);
    }
    Console.Out.WriteLine("Fetching bodies");
    foreach (var fetchItem in client.FetchMessages(sequence, IMAP_FetchItem_Flags.All, false, true)
    {             
        var email = LumiSoft.Net.Mail.Mail_Message.ParseFromByte(fetchItem.MessageData);             
        Console.Out.WriteLine("email.BodyText = {0}", email.BodyText);

    }
}

Convert byte to string in Java

String str = "0x63";
int temp = Integer.parseInt(str.substring(2, 4), 16);
char c = (char)temp;
System.out.print(c);

Interfaces vs. abstract classes

Another thing to consider is that, since there is no multiple inheritance, if you want a class to be able to implement/inherit from your interface/abstract class, but inherit from another base class, use an interface.

Getting the thread ID from a thread

You can use the deprecated AppDomain.GetCurrentThreadId to get the ID of the currently running thread. This method uses a PInvoke to the Win32 API method GetCurrentThreadID, and will return the Windows thread ID.

This method is marked as deprecated because the .NET Thread object does not correspond to a single Windows thread, and as such there is no stable ID which can be returned by Windows for a given .NET thread.

See configurator's answer for more reasons why this is the case.

How to save a dictionary to a file?

We can also use the json module in the case when dictionaries or some other data can be easily mapped to JSON format.

import json

# Serialize data into file:
json.dump( data, open( "file_name.json", 'w' ) )

# Read data from file:
data = json.load( open( "file_name.json" ) )

This solution brings many benefits, eg works for Python 2.x and Python 3.x in an unchanged form and in addition, data saved in JSON format can be easily transferred between many different platforms or programs. This data are also human-readable.

How do I align spans or divs horizontally?

you can do:

<div style="float: left;"></div>

or

<div style="display: inline;"></div>

Either one will cause the divs to tile horizontally.

Check if element is visible in DOM

If you're interested in visible by the user:

function isVisible(elem) {
    if (!(elem instanceof Element)) throw Error('DomUtil: elem is not an element.');
    const style = getComputedStyle(elem);
    if (style.display === 'none') return false;
    if (style.visibility !== 'visible') return false;
    if (style.opacity < 0.1) return false;
    if (elem.offsetWidth + elem.offsetHeight + elem.getBoundingClientRect().height +
        elem.getBoundingClientRect().width === 0) {
        return false;
    }
    const elemCenter   = {
        x: elem.getBoundingClientRect().left + elem.offsetWidth / 2,
        y: elem.getBoundingClientRect().top + elem.offsetHeight / 2
    };
    if (elemCenter.x < 0) return false;
    if (elemCenter.x > (document.documentElement.clientWidth || window.innerWidth)) return false;
    if (elemCenter.y < 0) return false;
    if (elemCenter.y > (document.documentElement.clientHeight || window.innerHeight)) return false;
    let pointContainer = document.elementFromPoint(elemCenter.x, elemCenter.y);
    do {
        if (pointContainer === elem) return true;
    } while (pointContainer = pointContainer.parentNode);
    return false;
}

Tested on (using mocha terminology):

describe.only('visibility', function () {
    let div, visible, notVisible, inViewport, leftOfViewport, rightOfViewport, aboveViewport,
        belowViewport, notDisplayed, zeroOpacity, zIndex1, zIndex2;
    before(() => {
        div = document.createElement('div');
        document.querySelector('body').appendChild(div);
        div.appendChild(visible = document.createElement('div'));
        visible.style       = 'border: 1px solid black; margin: 5px; display: inline-block;';
        visible.textContent = 'visible';
        div.appendChild(inViewport = visible.cloneNode(false));
        inViewport.textContent = 'inViewport';
        div.appendChild(notDisplayed = visible.cloneNode(false));
        notDisplayed.style.display = 'none';
        notDisplayed.textContent   = 'notDisplayed';
        div.appendChild(notVisible = visible.cloneNode(false));
        notVisible.style.visibility = 'hidden';
        notVisible.textContent      = 'notVisible';
        div.appendChild(leftOfViewport = visible.cloneNode(false));
        leftOfViewport.style.position = 'absolute';
        leftOfViewport.style.right = '100000px';
        leftOfViewport.textContent = 'leftOfViewport';
        div.appendChild(rightOfViewport = leftOfViewport.cloneNode(false));
        rightOfViewport.style.right       = '0';
        rightOfViewport.style.left       = '100000px';
        rightOfViewport.textContent = 'rightOfViewport';
        div.appendChild(aboveViewport = leftOfViewport.cloneNode(false));
        aboveViewport.style.right       = '0';
        aboveViewport.style.bottom       = '100000px';
        aboveViewport.textContent = 'aboveViewport';
        div.appendChild(belowViewport = leftOfViewport.cloneNode(false));
        belowViewport.style.right       = '0';
        belowViewport.style.top       = '100000px';
        belowViewport.textContent = 'belowViewport';
        div.appendChild(zeroOpacity = visible.cloneNode(false));
        zeroOpacity.textContent   = 'zeroOpacity';
        zeroOpacity.style.opacity = '0';
        div.appendChild(zIndex1 = visible.cloneNode(false));
        zIndex1.textContent = 'zIndex1';
        zIndex1.style.position = 'absolute';
        zIndex1.style.left = zIndex1.style.top = zIndex1.style.width = zIndex1.style.height = '100px';
        zIndex1.style.zIndex = '1';
        div.appendChild(zIndex2 = zIndex1.cloneNode(false));
        zIndex2.textContent = 'zIndex2';
        zIndex2.style.left = zIndex2.style.top = '90px';
        zIndex2.style.width = zIndex2.style.height = '120px';
        zIndex2.style.backgroundColor = 'red';
        zIndex2.style.zIndex = '2';
    });
    after(() => {
        div.parentNode.removeChild(div);
    });
    it('isVisible = true', () => {
        expect(isVisible(div)).to.be.true;
        expect(isVisible(visible)).to.be.true;
        expect(isVisible(inViewport)).to.be.true;
        expect(isVisible(zIndex2)).to.be.true;
    });
    it('isVisible = false', () => {
        expect(isVisible(notDisplayed)).to.be.false;
        expect(isVisible(notVisible)).to.be.false;
        expect(isVisible(document.createElement('div'))).to.be.false;
        expect(isVisible(zIndex1)).to.be.false;
        expect(isVisible(zeroOpacity)).to.be.false;
        expect(isVisible(leftOfViewport)).to.be.false;
        expect(isVisible(rightOfViewport)).to.be.false;
        expect(isVisible(aboveViewport)).to.be.false;
        expect(isVisible(belowViewport)).to.be.false;
    });
});

What does string::npos mean in this code?

npos is just a token value that tells you that find() did not find anything (probably -1 or something like that). find() checks for the first occurence of the parameter, and returns the index at which the parameter begins. For Example,

  string name = "asad.txt";
  int i = name.find(".txt");
  //i holds the value 4 now, that's the index at which ".txt" starts
  if (i==string::npos) //if ".txt" was NOT found - in this case it was, so  this condition is false
    name.append(".txt");

How to set xampp open localhost:8080 instead of just localhost

you can get loccalhost page by writing localhost/xampp or by writing http://127.0.0.1 you will get the local host page. After starting the apache serve that can be from wamp, xamp or lamp.

Fatal error: Can't open and lock privilege tables: Table 'mysql.host' doesn't exist

If you move your datadir, you not only need to give the new datadir permissions, but you need to ensure all parent directories have permission.

I moved my datadir to a hard drive, mounted in Ubuntu as:

/media/*user*/Data/

and my datadir was Databases.

I had to set permissions to 771 to each of the media, user and Data directories:

sudo chmod 771 *DIR*

If this does not work, another way you can get mysql to work is to change user in /etc/mysql/my.cnf to root; though there are no doubt some issues with doing that from a security perspective.

Where is the Global.asax.cs file?

It don't create normally; you need to add it by yourself.

After adding Global.asax by

  • Right clicking your website -> Add New Item -> Global Application Class -> Add

You need to add a class

  • Right clicking App_Code -> Add New Item -> Class -> name it Global.cs -> Add

Inherit the newly generated by System.Web.HttpApplication and copy all the method created Global.asax to Global.cs and also add an inherit attribute to the Global.asax file.

Your Global.asax will look like this: -

<%@ Application Language="C#" Inherits="Global" %>

Your Global.cs in App_Code will look like this: -

public class Global : System.Web.HttpApplication
{
    public Global()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup

    }
    /// Many other events like begin request...e.t.c, e.t.c
}

Sorting a Dictionary in place with respect to keys

Due to this answers high search placing I thought the LINQ OrderBy solution is worth showing:

class Person
{
    public Person(string firstname, string lastname)
    {
        FirstName = firstname;
        LastName = lastname;
    }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

static void Main(string[] args)
{
    Dictionary<Person, int> People = new Dictionary<Person, int>();

    People.Add(new Person("John", "Doe"), 1);
    People.Add(new Person("Mary", "Poe"), 2);
    People.Add(new Person("Richard", "Roe"), 3);
    People.Add(new Person("Anne", "Roe"), 4);
    People.Add(new Person("Mark", "Moe"), 5);
    People.Add(new Person("Larry", "Loe"), 6);
    People.Add(new Person("Jane", "Doe"), 7);

    foreach (KeyValuePair<Person, int> person in People.OrderBy(i => i.Key.LastName))
    {
        Debug.WriteLine(person.Key.LastName + ", " + person.Key.FirstName + " - Id: " + person.Value.ToString());
    }
}

Output:

Doe, John - Id: 1
Doe, Jane - Id: 7
Loe, Larry - Id: 6
Moe, Mark - Id: 5
Poe, Mary - Id: 2
Roe, Richard - Id: 3
Roe, Anne - Id: 4

In this example it would make sense to also use ThenBy for first names:

foreach (KeyValuePair<Person, int> person in People.OrderBy(i => i.Key.LastName).ThenBy(i => i.Key.FirstName))

Then the output is:

Doe, Jane - Id: 7
Doe, John - Id: 1
Loe, Larry - Id: 6
Moe, Mark - Id: 5
Poe, Mary - Id: 2
Roe, Anne - Id: 4
Roe, Richard - Id: 3

LINQ also has the OrderByDescending and ThenByDescending for those that need it.

HTML/JavaScript: Simple form validation on submit

HTML Form Element Validation

Run Function

<script>
    $("#validationForm").validation({
         button: "#btnGonder",
         onSubmit: function () {
             alert("Submit Process");
         },
         onCompleted: function () {
             alert("onCompleted");
         },
         onError: function () {
             alert("Error Process");
         }
    });
</script>

Go to example and download https://github.com/naimserin/Validation.

How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?

Because XMLHttpReponse synchronous operation is deprecated I came up with the following solution that wraps XMLHttpRequest. This allows ordered AJAX queries while still being asycnronous in nature, which is very useful for single use CSRF tokens.

It is also transparent so libraries such as jQuery will operate seamlessly.

/* wrap XMLHttpRequest for synchronous operation */
var XHRQueue = [];
var _XMLHttpRequest = XMLHttpRequest;
XMLHttpRequest = function()
{
  var xhr   = new _XMLHttpRequest();
  var _send = xhr.send;

  xhr.send = function()
  {
    /* queue the request, and if it's the first, process it */
    XHRQueue.push([this, arguments]);
    if (XHRQueue.length == 1)
      this.processQueue();
  };

  xhr.processQueue = function()
  {
    var call = XHRQueue[0];
    var xhr  = call[0];
    var args = call[1];

    /* you could also set a CSRF token header here */

    /* send the request */
    _send.apply(xhr, args);
  };

  xhr.addEventListener('load', function(e)
  {
    /* you could also retrieve a CSRF token header here */

    /* remove the completed request and if there is more, trigger the next */
    XHRQueue.shift();
    if (XHRQueue.length)
      this.processQueue();
  });

  return xhr;
};

How to set background color of HTML element using css properties in JavaScript

A simple js can solve this:

document.getElementById("idName").style.background = "blue";

Angular 2: Passing Data to Routes?

You can do this:

app-routing-modules.ts:

import { NgModule                  }    from '@angular/core';
import { RouterModule, Routes      }    from '@angular/router';
import { PowerBoosterComponent     }    from './component/power-booster.component';


export const routes: Routes = [
  { path:  'pipeexamples',component: PowerBoosterComponent, 
data:{  name:'shubham' } },
    ];
    @NgModule({
      imports: [ RouterModule.forRoot(routes) ],
      exports: [ RouterModule ]
    })
    export class AppRoutingModule {}

In this above route, I want to send data via a pipeexamples path to PowerBoosterComponent.So now I can receive this data in PowerBoosterComponent like this:

power-booster-component.ts

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params, Data } from '@angular/router';

@Component({
  selector: 'power-booster',
  template: `
    <h2>Power Booster</h2>`
})

export class PowerBoosterComponent implements OnInit {
  constructor(
    private route: ActivatedRoute,
    private router: Router

  ) { }
  ngOnInit() {
    //this.route.snapshot.data['name']
    console.log("Data via params: ",this.route.snapshot.data['name']);
  }
}

So you can get the data by this.route.snapshot.data['name'].

How to make canvas responsive

extending accepted answer with jquery

what if you want to add more canvas?, this jquery.each answer it

responsiveCanvas(); //first init
$(window).resize(function(){
  responsiveCanvas(); //every resizing
  stage.update(); //update the canvas, stage is object of easeljs

});
function responsiveCanvas(target){
  $(canvas).each(function(e){

    var parentWidth = $(this).parent().outerWidth();
    var parentHeight =  $(this).parent().outerHeight();
    $(this).attr('width', parentWidth);
    $(this).attr('height', parentHeight);
    console.log(parentWidth);
  })

}

it will do all the job for you

why we dont set the width or the height via css or style? because it will stretch your canvas instead of make it into expecting size

jQuery UI Sortable, then write order into a database

Thought this might help as well. A) it was designed to keep payload to its minimum while sending back to server, after each sort. (instead of sending all elements each time or iterating through many elements that server might chuck out) B) I needed to send back custom id without compromising the id / name of the element. This code will get the list from asp.net server and then upon sorting only 2 values will be sent back: The db id of sorted element and db id of the element next to which it was dropped. Based on those 2 values, server can easily identify the new postion.

<div id="planlist" style="width:1000px">
    <ul style="width:1000px">
       <li plid="listId1"><a href="#pl-1">List 1</a></li>
       <li plid="listId2"><a href="#pl-2">List 1</a></li>
       <li plid="listId3"><a href="#pl-3">List 1</a></li>
       <li plid="listId4"><a href="#pl-4">List 1</a></li>
    </ul>
    <div id="pl-1"></div>
    <div id="pl-2"></div>
    <div id="pl-3"></div>
    <div id="pl-4"></div>
</div>
<script type="text/javascript" language="javascript">
    $(function () {
        var tabs = $("#planlist").tabs();
        tabs.find(".ui-tabs-nav").sortable({
            axis: "x",
            stop: function () {
                tabs.tabs("refresh");
            },
            update: function (event, ui) {
                //db id of the item sorted
                alert(ui.item.attr('plid'));
                //db id of the item next to which the dragged item was dropped
                alert(ui.item.prev().attr('plid'));

                //make ajax call
            }
        });
    });
</script>

Making a flex item float right

You can't use float inside flex container and the reason is that float property does not apply to flex-level boxes as you can see here Fiddle.

So if you want to position child element to right of parent element you can use margin-left: auto but now child element will also push other div to the right as you can see here Fiddle.

What you can do now is change order of elements and set order: 2 on child element so it doesn't affect second div

_x000D_
_x000D_
.parent {_x000D_
  display: flex;_x000D_
}_x000D_
.child {_x000D_
  margin-left: auto;_x000D_
  order: 2;_x000D_
}
_x000D_
<div class="parent">_x000D_
  <div class="child">Ignore parent?</div>_x000D_
  <div>another child</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Support for ES6 in Internet Explorer 11

The statement from Microsoft regarding the end of Internet Explorer 11 support mentions that it will continue to receive security updates, compatibility fixes, and technical support until its end of life. The wording of this statement leads me to believe that Microsoft has no plans to continue adding features to Internet Explorer 11, and instead will be focusing on Edge.

If you require ES6 features in Internet Explorer 11, check out a transpiler such as Babel.

Delete entire row if cell contains the string X

This is not necessarily a VBA task - This specific task is easiest sollowed with Auto filter.

1.Insert Auto filter (In Excel 2010 click on home-> (Editing) Sort & Filter -> Filter)
2. Filter on the 'Websites' column
3. Mark the 'none' and delete them
4. Clear filter

Rebasing remote branches in Git

You can disable the check (if you're really sure you know what you're doing) by using the --force option to git push.

Convert date from 'Thu Jun 09 2011 00:00:00 GMT+0530 (India Standard Time)' to 'YYYY-MM-DD' in javascript

 function convertDatePickerTimeToMySQLTime(str) {
        var month, day, year, hours, minutes, seconds;
        var date = new Date(str),
            month = ("0" + (date.getMonth() + 1)).slice(-2),
            day = ("0" + date.getDate()).slice(-2);
        hours = ("0" + date.getHours()).slice(-2);
        minutes = ("0" + date.getMinutes()).slice(-2);
        seconds = ("0" + date.getSeconds()).slice(-2);

        var mySQLDate = [date.getFullYear(), month, day].join("-");
        var mySQLTime = [hours, minutes, seconds].join(":");
        return [mySQLDate, mySQLTime].join(" ");
    }

Need help rounding to 2 decimal places

It is caused by a lack of precision with doubles / decimals (i.e. - the function will not always give the result you expect).

See the following link: MSDN on Math.Round

Here is the relevant quote:

Because of the loss of precision that can result from representing decimal values as floating-point numbers or performing arithmetic operations on floating-point values, in some cases the Round(Double, Int32, MidpointRounding) method may not appear to round midpoint values as specified by the mode parameter.This is illustrated in the following example, where 2.135 is rounded to 2.13 instead of 2.14.This occurs because internally the method multiplies value by 10digits, and the multiplication operation in this case suffers from a loss of precision.

How do you see recent SVN log entries?

To add to what others have said, you could also create an alias in your .bashrc or .bash_aliases file:

alias svnlog='svn log -l 30 | less'

or whatever you want as your default

Input type for HTML form for integer

This might help:

<input type="number" step="1" pattern="\d+" />

step is for convenience (and could be set to another integer), but pattern does some actual enforcing.

Note that since pattern matches the whole expression, it wasn't necessary to express it as ^\d+$.

Even with this outwardly tight regular expression, Chrome and Firefox's implementations, interestingly allow for e here (presumably for scientific notation) as well as - for negative numbers, and Chrome also allows for . whereas Firefox is tighter in rejecting unless the . is followed by 0's only. (Firefox marks the field as red upon the input losing focus whereas Chrome doesn't let you input disallowed values in the first place.)

Since, as observed by others, one should always validate on the server (or on the client too, if using the value locally on the client or wishing to prevent the user from a roundtrip to the server).

What are the ascii values of up down left right?

In short:

left arrow: 37
up arrow: 38
right arrow: 39
down arrow: 40

PHP Multidimensional Array Searching (Find key by specific value)

Very simple:

function myfunction($products, $field, $value)
{
   foreach($products as $key => $product)
   {
      if ( $product[$field] === $value )
         return $key;
   }
   return false;
}

Difference between <input type='button' /> and <input type='submit' />

type='Submit' is set to forward & get the values on BACK-END (PHP, .NET etc). type='button' will reflect normal button behavior.

What's the difference between implementation and compile in Gradle?

The brief difference in layman's term is:

  • If you are working on an interface or module that provides support to other modules by exposing the members of the stated dependency you should be using 'api'.
  • If you are making an application or module that is going to implement or use the stated dependency internally, use 'implementation'.
  • 'compile' worked same as 'api', however, if you are only implementing or using any library, 'implementation' will work better and save you resources.

read the answer by @aldok for a comprehensive example.