Programs & Examples On #Viewport3d

Viewport3D is a .NET framework class used to render 3-D content within the application 2-D layout.

Test class with a new() call in it with Mockito

In situations where the class under test can be modified and when it's desirable to avoid byte code manipulation, to keep things fast or to minimise third party dependencies, here is my take on the use of a factory to extract the new operation.

public class TestedClass {

    interface PojoFactory { Pojo getNewPojo(); }

    private final PojoFactory factory;

    /** For use in production - nothing needs to change. */
    public TestedClass() {
        this.factory = new PojoFactory() {
            @Override
            public Pojo getNewPojo() {
                return new Pojo();
            }
        };
    }

    /** For use in testing - provide a pojo factory. */
    public TestedClass(PojoFactory factory) {
        this.factory = factory;
    }

    public void doSomething() {
        Pojo pojo = this.factory.getNewPojo();
        anythingCouldHappen(pojo);
    }
}

With this in place, your testing, asserts and verify calls on the Pojo object are easy:

public  void testSomething() {
    Pojo testPojo = new Pojo();
    TestedClass target = new TestedClass(new TestedClass.PojoFactory() {
                @Override
                public Pojo getNewPojo() {
                    return testPojo;
                }
            });
    target.doSomething();
    assertThat(testPojo.isLifeStillBeautiful(), is(true));
}

The only downside to this approach potentially arises if TestClass has multiple constructors which you'd have to duplicate with the extra parameter.

For SOLID reasons you'd probably want to put the PojoFactory interface onto the Pojo class instead, and the production factory as well.

public class Pojo {

    interface PojoFactory { Pojo getNewPojo(); }

    public static final PojoFactory productionFactory = 
        new PojoFactory() {
            @Override 
            public Pojo getNewPojo() {
                return new Pojo();
            }
        };

Why is there no Char.Empty like String.Empty?

A char, unlike a string, is a discrete thing with a fixed size. A string is really a container of chars.

So, Char.Empty doesn't really make sense in that context. If you have a char, it's not empty.

Copying files from server to local computer using SSH

You need to name the file in both directory paths.

scp [email protected]:/dir/of/file.txt \local\dir\file.txt

while installing vc_redist.x64.exe, getting error "Failed to configure per-machine MSU package."

I would like to give you a background on Universal CRT this would help you in understanding as to why the system should be updated before installing vc_redist.x64.exe.

  1. A large portion of the C-runtime moved into the OS in Windows 10 (ucrtbase.dll) and is serviced just like any other OS DLL (e.g. kernel32.dll). It is no longer serviced by Visual Studio directly. MSU packages are the file type for Windows Updates.
  2. In order to get the Windows 10 Universal CRT to earlier OSes, Windows Update packages were created to bring this OS component downlevel. KB2999226 brings the Windows 10 RTM Universal CRT to downlevel platforms (Windows Vista through Windows 8.1). KB3118401 brings Windows 10 November Update to the Universal CRT to downlevel platforms.
    • Windows XP (latest SP) is an exception here. Windows Servicing does not provide downlevel packages for that OS, so Visual Studio (Visual C++) provides a mechanism to install the UCRT into System32 via the VCRedist and MSMs.
  3. The Windows Universal Runtime is included in the VC Redist exe package as it has dependency on the Windows Universal Runtime (KB2999226).
  4. Windows 10 is the only OS that ships the UCRT in-box. All prior OSes obtain the UCRT via Windows Update only. This applies to all Vista->8.1 and associated Server SKUs.

For Windows 7, 8, and 8.1 the Windows Universal Runtime must be installed via KB2999226. However it has a prerequisite update KB2919355 which contains updates that facilitate installing the KB2999226 package.

Why does KB2999226 not always install when the runtime is installed from the redistributable? What could prevent KB2999226 from installing as part of the runtime?

The UCRT MSU included in the VCRedist is installed by making a call into the Windows Update service and the KB can fail to install based upon Windows Update service activity/state:

  1. If the machine has not updated to the required servicing baseline, the UCRT MSU will be viewed as being “Not Applicable”. Ensure KB2919355 is installed. Also, there were known issues with KB2919355 so before this the following hotfix should be installed. KB2939087 KB2975061
  2. If the Windows Update service is installing other updates when the VCRedist installs, you can either see long delays or errors indicating the machine is busy.
    • This one can be resolved by waiting and trying again later (which may be why installing via Windows Update UI at a later time succeeds).
  3. If the Windows Update service is in a non-ready state, you can see errors reflecting that.

    • We recently investigated a failure with an error code indicating the WUSA service was shutting down.
  4. To identify if the prerequisite KB2919355 is installed there are 2 options:

    1. Registry key: 64bit hive

      HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\Packages\Package_for_KB2919355~31bf3856ad364e35~amd64~~6.3.1.14
      CurrentState = 112
      

      32bit hive

      HKLM\SOFTWARE\[WOW6432Node\]Microsoft\Windows\CurrentVersion\Component Based Servicing\Packages\Package_for_KB2919355~31bf3856ad364e35~x86~~6.3.1.14
      CurrentState = 112
      
    2. Or check the file version of:

      C:\Windows\SysWOW64\wuaueng.dll
      C:\Windows\System32\wuaueng.dll
      

      is 7.9.9600.17031 or later

What is the difference between Visual Studio Express 2013 for Windows and Visual Studio Express 2013 for Windows Desktop?

More importantly, the 2013 versions of Visual Studio Express have all the languages that comes with the commercial versions. You can use the Windows desktop versions not only to program using Windows Forms, it is possible to write those windowed applications with any language that comes with the software, may it be C++ using the windows.h header if you want to actually learn how to create windows applications from scratch, or use Windows form to create windows in C# or visual Basic.

In the past, you had to download one version for each language or type of content. Or just download an all-in-one that still installed separate versions of the software for different languages. Now with 2013 you get all the languages needed in each content oriented version of the 2013 express.

You pick what matters the most to you.

Besides, it might be a good way to learn using notepad and the command line to write and compile, but I find that a bit tedious to use. While using an IDE might be overwhelming at first, you start small, learning how to create a project, write code, compile your code. They have gone way over their heads to ease up your day when you take it for the first time.

Is there a math nCr function in python?

Do you want iteration? itertools.combinations. Common usage:

>>> import itertools
>>> itertools.combinations('abcd',2)
<itertools.combinations object at 0x01348F30>
>>> list(itertools.combinations('abcd',2))
[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]
>>> [''.join(x) for x in itertools.combinations('abcd',2)]
['ab', 'ac', 'ad', 'bc', 'bd', 'cd']

If you just need to compute the formula, use math.factorial:

import math

def nCr(n,r):
    f = math.factorial
    return f(n) / f(r) / f(n-r)

if __name__ == '__main__':
    print nCr(4,2)

In Python 3, use the integer division // instead of / to avoid overflows:

return f(n) // f(r) // f(n-r)

Output

6

How to test web service using command line curl

From the documentation on http://curl.haxx.se/docs/httpscripting.html :

HTTP Authentication

curl --user name:password http://www.example.com 

Put a file to a HTTP server with curl:

curl --upload-file uploadfile http://www.example.com/receive.cgi

Send post data with curl:

curl --data "birthyear=1905&press=%20OK%20" http://www.example.com/when.cgi

Simple way to convert datarow array to datatable

.Net 3.5+ added DataTableExtensions, use DataTableExtensions.CopyToDataTable Method

For datarow array just use .CopyToDataTable() and it will return datatable.

For single datarow use

new DataRow[] { myDataRow }.CopyToDataTable()

Cannot implicitly convert type 'System.DateTime?' to 'System.DateTime'. An explicit conversion exists

You have 3 options:

1) Get default value

dt = datetime??DateTime.Now;

it will assign DateTime.Now (or any other value which you want) if datetime is null

2) Check if datetime contains value and if not return empty string

if(!datetime.HasValue) return "";
dt = datetime.Value;

3) Change signature of method to

public string ConvertToPersianToShow(DateTime  datetime)

It's all because DateTime? means it's nullable DateTime so before assigning it to DateTime you need to check if it contains value and only then assign.

Vue.js: Conditional class style binding

if you want to apply separate css classes for same element with conditions in Vue.js you can use the below given method.it worked in my scenario.

html

 <div class="Main" v-bind:class="{ Sub: page}"  >

in here, Main and Sub are two different class names for same div element. v-bind:class directive is used to bind the sub class in here. page is the property we use to update the classes when it's value changed.

js

data:{
page : true;
}

here we can apply a condition if we needed. so, if the page property becomes true element will go with Main and Sub claases css styles. but if false only Main class css styles will be applied.

In MySQL, how to copy the content of one table to another table within the same database?

INSERT INTO TARGET_TABLE SELECT * FROM SOURCE_TABLE;

EDIT: or if the tables have different structures you can also:

INSERT INTO TARGET_TABLE (`col1`,`col2`) SELECT `col1`,`col2` FROM SOURCE_TABLE;

EDIT: to constrain this..

INSERT INTO TARGET_TABLE (`col1_`,`col2_`) SELECT `col1`,`col2` FROM SOURCE_TABLE WHERE `foo`=1

How can I check if char* variable points to empty string?

An empty string has one single null byte. So test if (s[0] == (char)0)

How to add additional libraries to Visual Studio project?

Without knowing your compiler, no one can give you specific, step by step instructions, but the basic procedure is as follows:

  1. Specify the path which should be searched in order to find the actual library (usually under Library Search Paths, Library Directories, etc. in the properties page)

  2. Under linker options, specify the actual name of the library. In VS, you would write Allegro.lib (or whatever it is), on Linux you usually just write Allegro (prefixes/suffixes are added automatically in most cases). This is usually under "Libraries->Input", just "Libraries", or something similar.

  3. Ensure that you have included the headers for the library and make sure that they can be found (similar process to that listed in step #1 and #2). If it is a static library, you should be good; if it's a DLL, you need to copy it in your project.

  4. Mash the build button.

How to convert a .eps file to a high quality 1024x1024 .jpg?

For vector graphics, ImageMagick has both a render resolution and an output size that are independent of each other.

Try something like

convert -density 300 image.eps -resize 1024x1024 image.jpg

Which will render your eps at 300dpi. If 300 * width > 1024, then it will be sharp. If you render it too high though, you waste a lot of memory drawing a really high-res graphic only to down sample it again. I don't currently know of a good way to render it at the "right" resolution in one IM command.

The order of the arguments matters! The -density X argument needs to go before image.eps because you want to affect the resolution that the input file is rendered at.

This is not super obvious in the manpage for convert, but is hinted at:

SYNOPSIS

convert [input-option] input-file [output-option] output-file

How do I retrieve a textbox value using JQuery?

Just Additional Info which took me long time to find.what if you were using the field name and not id for identifying the form field. You do it like this:

For radio button:

var inp= $('input:radio[name=PatientPreviouslyReceivedDrug]:checked').val();

For textbox:

var txt=$('input:text[name=DrugDurationLength]').val();

SQLAlchemy IN clause

How about

session.query(MyUserClass).filter(MyUserClass.id.in_((123,456))).all()

edit: Without the ORM, it would be

session.execute(
    select(
        [MyUserTable.c.id, MyUserTable.c.name], 
        MyUserTable.c.id.in_((123, 456))
    )
).fetchall()

select() takes two parameters, the first one is a list of fields to retrieve, the second one is the where condition. You can access all fields on a table object via the c (or columns) property.

How do I retrieve the number of columns in a Pandas data frame?

There are multiple option to get column number and column information such as:
let's check them.

local_df = pd.DataFrame(np.random.randint(1,12,size=(2,6)),columns =['a','b','c','d','e','f']) 1. local_df.shape[1] --> Shape attribute return tuple as (row & columns) (0,1).

  1. local_df.info() --> info Method will return detailed information about data frame and it's columns such column count, data type of columns, Not null value count, memory usage by Data Frame

  2. len(local_df.columns) --> columns attribute will return index object of data frame columns & len function will return total available columns.

  3. local_df.head(0) --> head method with parameter 0 will return 1st row of df which actually nothing but header.

Assuming number of columns are not more than 10. For loop fun: li_count =0 for x in local_df: li_count =li_count + 1 print(li_count)

Adb over wireless without usb cable at all for not rooted phones

type in Windows cmd.exe

    cd %userprofile%\.android
    dir
    copy adbkey.pub adb_keys
    dir

copy the file adb_keys to your phone folder /data/misc/adb. Reboot the phone. RSA Key is now authorized.

from: How to solve ADB device unauthorized in Android ADB host device?

now follow the instructions for adb connect, or use any app for preparing. i prefer ADB over WIFI Widget from Mehdy Bohlool, it works without root.

from: How can I connect to Android with ADB over TCP?

Graphviz's executables are not found (Python 3.4)

Tried many ways and here is what really solved the problem - it worked for both windows 8.1/10 & python 3 .

1 . pip install graphviz

2 . the key action needed is to set the path variable by following steps below:

a. Control Panel > System and Security > System > Advanced System Settings > Environment Variables > Path > Edit b. add 'C:\Program Files (x86)\Graphviz2.38\bin'

Accessing the last entry in a Map

A SortedMap is the logical/best choice, however another option is to use a LinkedHashMap which maintains two order modes, most-recently-added goes last, and most-recently-accessed goes last. See the Javadocs for more details.

What should I do if the current ASP.NET session is null?

If your Session instance is null and your in an 'ashx' file, just implement the 'IRequiresSessionState' interface.

This interface doesn't have any members so you just need to add the interface name after the class declaration (C#):

public class MyAshxClass : IHttpHandler, IRequiresSessionState

Identifying and removing null characters in UNIX

I faced the same error with:

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

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

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

Compare two Timestamp in java

Just convert the timestamp in millisec representation. Use getTime() method.

Opening Chrome From Command Line

Have a look into the start command. It should do what you're trying to achieve.

Also, you might be able to leave out path to chrome. The following works on Windows 7:

start chrome "site1.com" "site2.com"

How to write to a file in Scala?

Giving another answer, because my edits of other answers where rejected.

This is the most concise and simple answer (similar to Garret Hall's)

File("filename").writeAll("hello world")

This is similar to Jus12, but without the verbosity and with correct code style

def using[A <: {def close(): Unit}, B](resource: A)(f: A => B): B =
  try f(resource) finally resource.close()

def writeToFile(path: String, data: String): Unit = 
  using(new FileWriter(path))(_.write(data))

def appendToFile(path: String, data: String): Unit =
  using(new PrintWriter(new FileWriter(path, true)))(_.println(data))

Note you do NOT need the curly braces for try finally, nor lambdas, and note usage of placeholder syntax. Also note better naming.

Regular expression for not allowing spaces in the input field

Use + plus sign (Match one or more of the previous items),

var regexp = /^\S+$/

Split string into array

ES6 is quite powerful in iterating through objects (strings, Array, Map, Set). Let's use a Spread Operator to solve this.

entry = prompt("Enter your name");
var count = [...entry];
console.log(count);

Disabled href tag

In my case, I use

<a href="/" onClick={e => e.preventDefault()}>

postgresql sequence nextval in schema

The quoting rules are painful. I think you want:

SELECT nextval('foo."SQ_ID"');

to prevent case-folding of SQ_ID.

How to find Control in TemplateField of GridView?

string textboxID;
string da;
textboxID = "ctl00$MainContent$grd$ctl" + (grd.Columns.Count + j).ToString() + "$txtDyna" + (k).ToString();
textboxID= ctl00$MainContent$grd$ctl12$ctl00;
da = Request.Form(textboxID);

Best way to handle list.index(might-not-exist) in python?

This issue is one of language philosophy. In Java for example there has always been a tradition that exceptions should really only be used in "exceptional circumstances" that is when errors have happened, rather than for flow control. In the beginning this was for performance reasons as Java exceptions were slow but now this has become the accepted style.

In contrast Python has always used exceptions to indicate normal program flow, like raising a ValueError as we are discussing here. There is nothing "dirty" about this in Python style and there are many more where that came from. An even more common example is StopIteration exception which is raised by an iterator‘s next() method to signal that there are no further values.

Android selector & text color

Here's my implementation, which behaves exactly as item in list (at least on 2.3)

res/layout/list_video_footer.xml

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

    <TextView
        android:id="@+id/list_video_footer"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="@android:drawable/list_selector_background"
        android:clickable="true"
        android:gravity="center"
        android:minHeight="98px"
        android:text="@string/more"
        android:textColor="@color/bright_text_dark_focused"
        android:textSize="18dp"
        android:textStyle="bold" />

</FrameLayout>

res/color/bright_text_dark_focused.xml

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

    <item android:state_selected="true" android:color="#444"/>
    <item android:state_focused="true" android:color="#444"/>
    <item android:state_pressed="true" android:color="#444"/>
    <item android:color="#ccc"/>

</selector>

Make new column in Panda dataframe by adding values from other columns

Building a little more on Anton's answer, you can add all the columns like this:

df['sum'] = df[list(df.columns)].sum(axis=1)

NuGet: 'X' already has a dependency defined for 'Y'

In my case I had to delete the file NuGet.exe in the Project folder/.nuget and rebuild the project.

I also have in NuGet.targets the DownloadNuGetExe marked as true:

<DownloadNuGetExe Condition=" '$(DownloadNuGetExe)' == '' ">true</DownloadNuGetExe>

Hope it's helps.

Checking if form has been submitted - PHP

Use

if(isset($_POST['submit'])) // name of your submit button

Count table rows

It can be convenient to select count with filter by indexed field. Try this

EXPLAIN SELECT * FROM table_name WHERE key < anything; 

Calling a javascript function in another js file

Use cache if your server allows it to improve speed.

var extern =(url)=> {           // load extern javascript
    let scr = $.extend({}, {
        dataType: 'script',
        cache: true,
        url: url
    });
    return $.ajax(scr);
}
function ext(file, func) {
    extern(file).done(func);    // calls a function from an extern javascript file
}

And then use it like this:

ext('somefile.js',()=>              
    myFunc(args)
);  

Optionally, make a prototype of it to have it more flexible. So that you don't have to define the file every time, if you call a function or if you want to fetch code from multiple files.

Conda environments not showing up in Jupyter Notebook

In my case, using Windows 10 and conda 4.6.11, by running the commands

conda install nb_conda

conda install -c conda-forge nb_conda_kernels

from the terminal while having the environment active didn't do the job after I opened Jupyter from the same command line using conda jupyter notebook.

The solution was apparently to opened Jupyter from the Anaconda Navigator by going to my environment in Environments: Open Anaconda Navigator, select the environment in Environments, press on the "play" button on the chosen environment, and select 'open with Jupyter Notebook'.

Environments in Anaconda Navigator to run Jupyter from the selected environment

Change Screen Orientation programmatically using a Button

Use this to set the orientation of the screen:

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

or

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

and don't forget to add this to your manifest:

android:configChanges = "orientation"

how can I connect to a remote mongo server from Mac OS terminal

With Mongo 3.2 and higher just use your connection string as is:

mongo mongodb://username:[email protected]:10011/my_database

What is the difference between char, nchar, varchar, and nvarchar in SQL Server?

Just to clear up... or sum up...

  • nchar and nvarchar can store Unicode characters.
  • char and varchar cannot store Unicode characters.
  • char and nchar are fixed-length which will reserve storage space for number of characters you specify even if you don't use up all that space.
  • varchar and nvarchar are variable-length which will only use up spaces for the characters you store. It will not reserve storage like char or nchar.

nchar and nvarchar will take up twice as much storage space, so it may be wise to use them only if you need Unicode support.

H.264 file size for 1 hr of HD video

It would be a couple of gigs per hour.

MPEG-4 (of which H.264 is a sub-part) define high quality as around 4Mbps. which would be 1.8GB per hour.

This can vary depending on the type of video and the type of compression used.

jQuery DataTable overflow and text-wrapping issues

Try adding td {word-wrap: break-word;} to the css and see if it fixes it.

Returning a promise in an async function in TypeScript

When you do new Promise((resolve)... the type inferred was Promise<{}> because you should have used new Promise<number>((resolve).

It is interesting that this issue was only highlighted when the async keyword was added. I would recommend reporting this issue to the TS team on GitHub.

There are many ways you can get around this issue. All the following functions have the same behavior:

const whatever1 = () => {
    return new Promise<number>((resolve) => {
        resolve(4);
    });
};

const whatever2 = async () => {
    return new Promise<number>((resolve) => {
        resolve(4);
    });
};

const whatever3 = async () => {
    return await new Promise<number>((resolve) => {
        resolve(4);
    });
};

const whatever4 = async () => {
    return Promise.resolve(4);
};

const whatever5 = async () => {
    return await Promise.resolve(4);
};

const whatever6 = async () => Promise.resolve(4);

const whatever7 = async () => await Promise.resolve(4);

In your IDE you will be able to see that the inferred type for all these functions is () => Promise<number>.

org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:transformClassesWithDexForDebug'

Check build.gradle(Module: Android) fixed problem for me.

Modify it to workable version.

android {
    buildToolsVersion '23.0.1'
}

mysqldump Error 1045 Access denied despite correct passwords etc

Mysql replies with Access Denied with correct credentials when the mysql account has REQUIRE SSL on

The ssl_ca file (at a minimum) had to be provided in the connection paramiters.

Additional ssl parameters might be required and are documented here: http://dev.mysql.com/doc/refman/5.7/en/secure-connection-options.html


Also posted here https://stackoverflow.com/a/39626932/1695680

onClick not working on mobile (touch)

better to use touchstart event with .on() jQuery method:

$(window).load(function() { // better to use $(document).ready(function(){
    $('.List li').on('click touchstart', function() {
        $('.Div').slideDown('500');
    });
});

And i don't understand why you are using $(window).load() method because it waits for everything on a page to be loaded, this tend to be slow, while you can use $(document).ready() method which does not wait for each element on the page to be loaded first.

Entry point for Java applications: main(), init(), or run()?

The main() method is the entry point for a Java application. run() is typically used for new threads or tasks.

Where have you been writing a run() method, what kind of application are you writing (e.g. Swing, AWT, console etc) and what's your development environment?

Regex to get NUMBER only from String

Either [0-9] or \d1 should suffice if you only need a single digit. Append + if you need more.


1 The semantics are slightly different as \d potentially matches any decimal digit in any script out there that uses decimal digits.

Make Div Draggable using CSS

You can take a look at HTML 5, but I don't think you can restrict the area within you can drag it, just the destination:

http://www.w3schools.com/html/html5_draganddrop.asp

And if you don't mind using some great library, I would encourage you to try Dragula.

How to check if the given string is palindrome?

Here's a Python version that deals with different cases, punctuation and whitespace.

import string

def is_palindrome(palindrome):
    letters = palindrome.translate(string.maketrans("",""),
                  string.whitespace + string.punctuation).lower()
    return letters == letters[::-1]

Edit: Shamelessly stole from Blair Conrad's neater answer to remove the slightly clumsy list processing from my previous version.

Visual Studio - How to change a project's folder name and solution name without breaking the solution

You could open the SLN file in any text editor (Notepad, etc.) and simply change the project path there.

How do I rename a local Git branch?

All you have to do are the three steps:

  1. Give the old branch under .git/refs/heads the new name
  2. Give the old branch under .git/logs/refs/heads the new name
  3. Update the .git/HEAD to lead to your new branch name

How can I measure the similarity between two images?

Well a really base-level method to use could go through every pixel colour and compare it with the corresponding pixel colour on the second image - but that's a probably a very very slow solution.

How to append to a file in Node?

Besides appendFile, you can also pass a flag in writeFile to append data to an existing file.

fs.writeFile('log.txt', 'Hello Node',  {'flag':'a'},  function(err) {
    if (err) {
        return console.error(err);
    }
});

By passing flag 'a', data will be appended at the end of the file.

How to determine CPU and memory consumption from inside a process?

I used this following code in my C++ project and it worked fine:

static HANDLE self;
static int numProcessors;
SYSTEM_INFO sysInfo;

double percent;

numProcessors = sysInfo.dwNumberOfProcessors;

//Getting system times information
FILETIME SysidleTime;
FILETIME SyskernelTime; 
FILETIME SysuserTime; 
ULARGE_INTEGER SyskernelTimeInt, SysuserTimeInt;
GetSystemTimes(&SysidleTime, &SyskernelTime, &SysuserTime);
memcpy(&SyskernelTimeInt, &SyskernelTime, sizeof(FILETIME));
memcpy(&SysuserTimeInt, &SysuserTime, sizeof(FILETIME));
__int64 denomenator = SysuserTimeInt.QuadPart + SyskernelTimeInt.QuadPart;  

//Getting process times information
FILETIME ProccreationTime, ProcexitTime, ProcKernelTime, ProcUserTime;
ULARGE_INTEGER ProccreationTimeInt, ProcexitTimeInt, ProcKernelTimeInt, ProcUserTimeInt;
GetProcessTimes(self, &ProccreationTime, &ProcexitTime, &ProcKernelTime, &ProcUserTime);
memcpy(&ProcKernelTimeInt, &ProcKernelTime, sizeof(FILETIME));
memcpy(&ProcUserTimeInt, &ProcUserTime, sizeof(FILETIME));
__int64 numerator = ProcUserTimeInt.QuadPart + ProcKernelTimeInt.QuadPart;
//QuadPart represents a 64-bit signed integer (ULARGE_INTEGER)

percent = 100*(numerator/denomenator);

Column name or number of supplied values does not match table definition

Check your id. Is it Identity? If it is then make sure it is declared as ID not null Identity(1,1)

And before creating your table , Drop table and then create table.

ModelState.AddModelError - How can I add an error that isn't for a property?

You can add the model error on any property of your model, I suggest if there is nothing related to create a new property.

As an exemple we check if the email is already in use in DB and add the error to the Email property in the action so when I return the view, they know that there's an error and how to show it up by using

<%: Html.ValidationSummary(true)%>
<%: Html.ValidationMessageFor(model => model.Email) %>

and

ModelState.AddModelError("Email", Resources.EmailInUse);

Convert XLS to CSV on command line

Building on what Jon of All Trades has provided, the following (~n) removed the pesky double extension issue: FOR /f "delims=" %%i IN ('DIR *.xlsx /b') DO ExcelToCSV.vbs "%%i" "%%~ni.csv"

jQuery load more data on scroll

I spent some time trying to find a nice function to wrap a solution. Anyway, ended up with this which I feel is a better solutions when loading multiple content on a single page or across a site.

Function:

function ifViewLoadContent(elem, LoadContent)
    {
            var top_of_element = $(elem).offset().top;
            var bottom_of_element = $(elem).offset().top + $(elem).outerHeight();
            var bottom_of_screen = $(window).scrollTop() + window.innerHeight;
            var top_of_screen = $(window).scrollTop();

            if((bottom_of_screen > top_of_element) && (top_of_screen < bottom_of_element)){
            if(!$(elem).hasClass("ImLoaded"))   {
                $(elem).load(LoadContent).addClass("ImLoaded");
            }
            }
            else {
               return false;
            }
        }

You can then call the function using window on scroll (for example, you could also bind it to a click etc. as I also do, hence the function):

To use:

$(window).scroll(function (event) {
        ifViewLoadContent("#AjaxDivOne", "someFile/somecontent.html"); 

        ifViewLoadContent("#AjaxDivTwo", "someFile/somemorecontent.html"); 
    });

This approach should also work for scrolling divs etc. I hope it helps, in the question above you could use this approach to load your content in sections, maybe append and thereby dribble feed all that image data rather than bulk feed.

I used this approach to reduce the overhead on https://www.taxformcalculator.com. It died the trick, if you look at the site and inspect element etc. you can see impact on page load in Chrome (as an example).

how to delete default values in text field using selenium?

driver.findElement(locator).clear() - This command will work in all cases

Regular expression for floating point numbers

In C++ using the regex library

The answer would go about like this:

[0-9]?([0-9]*[.])?[0-9]+

Notice that I don't take the sign symbol, if you wanted it with the sign symbol it would go about this:

[+-]?([0-9]*[.])?[0-9]+

This also separates a regular number or a decimal number.

Delete empty rows

To delete rows empty in table

syntax:

DELETE FROM table_name 
WHERE column_name IS NULL;

example:

Table name: data ---> column name: pkdno

DELETE FROM data 
WHERE pkdno IS NULL;

Answer: 5 rows deleted. (sayso)

Access localhost from the internet

You go into your router configuration and forward port 80 to the LAN IP of the computer running the web server.

Then anyone outside your network (but not you inside the network) can access your site using your WAN IP address (whatismyipcom).

How to sort a HashSet?

We can not decide that the elements of a HashSet would be sorted automatically. But we can sort them by converting into TreeSet or any List like ArrayList or LinkedList etc.

// Create a TreeSet object of class E
TreeSet<E> ts = new TreeSet<E> ();

// Convert your HashSet into TreeSet
ts.addAll(yourHashSet);

System.out.println(ts.toString() + "\t Sorted Automatically");

How to set a header for a HTTP GET request, and trigger file download?

Pure jQuery.

$.ajax({
  type: "GET",
  url: "https://example.com/file",
  headers: {
    'Authorization': 'Bearer eyJraWQiFUDA.......TZxX1MGDGyg'
  },
  xhrFields: {
    responseType: 'blob'
  },
  success: function (blob) {
    var windowUrl = window.URL || window.webkitURL;
    var url = windowUrl.createObjectURL(blob);
    var anchor = document.createElement('a');
    anchor.href = url;
    anchor.download = 'filename.zip';
    anchor.click();
    anchor.parentNode.removeChild(anchor);
    windowUrl.revokeObjectURL(url);
  },
  error: function (error) {
    console.log(error);
  }
});

What is the difference between Select and Project Operations

In Relational algebra 'Selection' and 'Projection' are different operations, but the SQL SELECT combines these operations in a single statement.

Select retrieves the tuples (rows) in a relation (table) for which the condition in 'predicate' section (WHERE clause) stands true.

Project retrieves the attributes (columns) specified.

The following SQL SELECT query:

select field1,field2 from table1 where field1 = 'Value';

is a combination of both Projection and Selection operations of relational algebra.

Length of string in bash

To get the length of a string stored in a variable, say:

myvar="some string"
size=${#myvar} 

To confirm it was properly saved, echo it:

$ echo "$size"
11

String concatenation: concat() vs "+" operator

I ran a similar test as @marcio but with the following loop instead:

String c = a;
for (long i = 0; i < 100000L; i++) {
    c = c.concat(b); // make sure javac cannot skip the loop
    // using c += b for the alternative
}

Just for good measure, I threw in StringBuilder.append() as well. Each test was run 10 times, with 100k reps for each run. Here are the results:

  • StringBuilder wins hands down. The clock time result was 0 for most the runs, and the longest took 16ms.
  • a += b takes about 40000ms (40s) for each run.
  • concat only requires 10000ms (10s) per run.

I haven't decompiled the class to see the internals or run it through profiler yet, but I suspect a += b spends much of the time creating new objects of StringBuilder and then converting them back to String.

BATCH file asks for file or folder

The real trick is: Use a Backslash at the end of the target path where to copy the file. The /Y is for overwriting existing files, if you want no warnings.

Example:

xcopy /Y "C:\file\from\here.txt" "C:\file\to\here\"

customize Android Facebook Login button

You can modifiy the login button like this

<com.facebook.widget.LoginButton
            xmlns:fb="http://schemas.android.com/apk/res-auto"
            android:id="@+id/login_button"
            android:layout_width="249dp"
            android:layout_height="45dp"
            android:layout_above="@+id/textView1"
            android:layout_centerHorizontal="true"
            android:layout_gravity="center_horizontal"
            android:layout_marginBottom="30dp"
            android:layout_marginTop="30dp"
            android:contentDescription="@string/login_desc"
            android:scaleType="centerInside"
            fb:login_text=""
            fb:logout_text="" />

And in code I defined the background resource :

final LoginButton button = (LoginButton) findViewById(R.id.login_button);
button.setBackgroundResource(R.drawable.facebook);

Choosing the correct upper and lower HSV boundaries for color detection with`cv::inRange` (OpenCV)

OpenCV HSV range is: H: 0 to 179 S: 0 to 255 V: 0 to 255

On Gimp (or other photo manipulation sw) Hue range from 0 to 360, since opencv put color info in a single byte, the maximum number value in a single byte is 255 therefore openCV Hue values are equivalent to Hue values from gimp divided by 2.

I found when trying to do object detection based on HSV color space that a range of 5 (opencv range) was sufficient to filter out a specific color. I would advise you to use an HSV color palate to figure out the range that works best for your application.

HSV color palate with color detection in HSV space

MAX function in where clause mysql

You are using word 'max' as an alias for your column. Try to:

MAX(id) as mymax ... WHERE ID - mymax

Error while installing json gem 'mkmf.rb can't find header files for ruby'

In case that you are using ruby 2.0 or 2.2 (thanks @patrick-davey) or 2.3 (thanks @juanitofatas).

sudo apt-get install ruby-dev
sudo apt-get install ruby2.0-dev
sudo apt-get install ruby2.2-dev
sudo apt-get install ruby2.3-dev

And you get the pattern here...

Chrome Uncaught Syntax Error: Unexpected Token ILLEGAL

I had the same error in Chrome. The Chrome console told me that the error was in the 1st line of the HTML file.

It was actually in the .js file. So watch out for setValidNou(1060, $(this).val(), 0') error types.

cpp / c++ get pointer value or depointerize pointer

To get the value of a pointer, just de-reference the pointer.

int *ptr;
int value;
*ptr = 9;

value = *ptr;

value is now 9.

I suggest you read more about pointers, this is their base functionality.

How do I detect if software keyboard is visible on Android Device or not?

I created a simple class that can be used for this: https://github.com/ravindu1024/android-keyboardlistener. Just copy it in to your project and use as follows:

KeyboardUtils.addKeyboardToggleListener(this, new KeyboardUtils.SoftKeyboardToggleListener()
{
    @Override
    public void onToggleSoftKeyboard(boolean isVisible)
    {
        Log.d("keyboard", "keyboard visible: "+isVisible);
    }
});

How to exclude *AutoConfiguration classes in Spring Boot JUnit tests?

Top answers don't point to an even simpler and more flexible solution.

just place a

@TestPropertySource(properties=
{"spring.autoconfigure.exclude=comma.seperated.ClassNames,com.example.FooAutoConfiguration"})
@SpringBootTest
public class MySpringTest {...}

annotation above your test class. This means other tests aren't affected by the current test's special case. If there is a configuration affecting most of your tests, then consider using the spring profile instead as the current top answer suggests.

Thanks to @skirsch for encouraging me to upgrade this from a comment to an answer.

How to quickly and conveniently create a one element arraylist

Yet another alternative is double brace initialization, e.g.

new ArrayList<String>() {{ add(s); }};

but it is inefficient and obscure. Therefore only suitable:

  • in code that doesn't mind memory leaks, such as most unit tests and other short-lived programs;
  • and if none of the other solutions apply, which I think implies you've scrolled all the way down here looking to populate a different type of container than the ArrayList in the question.

How to make an image center (vertically & horizontally) inside a bigger div

This worked for me. Add this to image css:

img
{
   display: block;
   margin: auto;
}

How to filter by IP address in Wireshark?

Filtering IP Address in Wireshark:

(1)single IP filtering:

ip.addr==X.X.X.X

ip.src==X.X.X.X

ip.dst==X.X.X.X

(2)Multiple IP filtering based on logical conditions:

OR condition:

(ip.src==192.168.2.25)||(ip.dst==192.168.2.25)

AND condition:

(ip.src==192.168.2.25) && (ip.dst==74.125.236.16)

Change the content of a div based on selection from dropdown menu

here is a jsfiddle with an example of showing/hiding div's via a select.

HTML:

<div id="option1" class="group">asdf</div>
<div id="option2" class="group">kljh</div>
<div id="option3" class="group">zxcv</div>
<div id="option4" class="group">qwerty</div>
<select id="selectMe">
  <option value="option1">option1</option>
  <option value="option2">option2</option>
  <option value="option3">option3</option>
  <option value="option4">option4</option>
</select>

jQuery:

$(document).ready(function () {
  $('.group').hide();
  $('#option1').show();
  $('#selectMe').change(function () {
    $('.group').hide();
    $('#'+$(this).val()).show();
  })
});

Pandas: Convert Timestamp to datetime.date

Assume time column is in timestamp integer msec format

1 day = 86400000 ms

Here you go:

day_divider = 86400000

df['time'] = df['time'].values.astype(dtype='datetime64[ms]') # for msec format

df['time'] = (df['time']/day_divider).values.astype(dtype='datetime64[D]') # for day format

Roblox Admin Command Script

for i=1,#target do
    game.Players.target[i].Character:BreakJoints()
end

Is incorrect, if "target" contains "FakeNameHereSoNoStalkers" then the run code would be:

game.Players.target.1.Character:BreakJoints()

Which is completely incorrect.


c = game.Players:GetChildren()

Never use "Players:GetChildren()", it is not guaranteed to return only players.

Instead use:

c = Game.Players:GetPlayers()

if msg:lower()=="me" then
    table.insert(people, source)
    return people

Here you add the player's name in the list "people", where you in the other places adds the player object.


Fixed code:

local Admins = {"FakeNameHereSoNoStalkers"}

function Kill(Players)
    for i,Player in ipairs(Players) do
        if Player.Character then
            Player.Character:BreakJoints()
        end
    end
end

function IsAdmin(Player)
    for i,AdminName in ipairs(Admins) do
        if Player.Name:lower() == AdminName:lower() then return true end
    end
    return false
end

function GetPlayers(Player,Msg)
    local Targets = {}
    local Players = Game.Players:GetPlayers()

    if Msg:lower() == "me" then
        Targets = { Player }
    elseif Msg:lower() == "all" then
        Targets = Players
    elseif Msg:lower() == "others" then
        for i,Plr in ipairs(Players) do
            if Plr ~= Player then
                table.insert(Targets,Plr)
            end
        end
    else
        for i,Plr in ipairs(Players) do
            if Plr.Name:lower():sub(1,Msg:len()) == Msg then
                table.insert(Targets,Plr)
            end
        end
    end
    return Targets
end

Game.Players.PlayerAdded:connect(function(Player)
    if IsAdmin(Player) then
        Player.Chatted:connect(function(Msg)
            if Msg:lower():sub(1,6) == ":kill " then
                Kill(GetPlayers(Player,Msg:sub(7)))
            end
        end)
    end
end)

How to get a microtime in Node.js?

Node.js nanotimer

I wrote a wrapper library/object for node.js on top of the process.hrtime function call. It has useful functions, like timing synchronous and asynchronous tasks, specified in seconds, milliseconds, micro, or even nano, and follows the syntax of the built in javascript timer so as to be familiar.

Timer objects are also discrete, so you can have as many as you'd like, each with their own setTimeout or setInterval process running.

It's called nanotimer. Check it out!

Sleep function in Windows, using C

MSDN: Header: Winbase.h (include Windows.h)

What does a (+) sign mean in an Oracle SQL WHERE clause?

This is an Oracle-specific notation for an outer join. It means that it will include all rows from t1, and use NULLS in the t0 columns if there is no corresponding row in t0.

In standard SQL one would write:

SELECT t0.foo, t1.bar
  FROM FIRST_TABLE t0
 RIGHT OUTER JOIN SECOND_TABLE t1;

Oracle recommends not to use those joins anymore if your version supports ANSI joins (LEFT/RIGHT JOIN) :

Oracle recommends that you use the FROM clause OUTER JOIN syntax rather than the Oracle join operator. Outer join queries that use the Oracle join operator (+) are subject to the following rules and restrictions […]

How to add background-image using ngStyle (angular2)?

You can use 2 methods:

Method 1

<div [ngStyle]="{'background-image': 'url(&quot;' + photo + '&quot;)'}"></div>

Method 2

<div [style.background-image]="'url(&quot;' + photo + '&quot;)'"></div>

Note: it is important to surround the URL with " char.

What is a classpath and how do I set it?

CLASSPATH is an environment variable (i.e., global variables of the operating system available to all the processes) needed for the Java compiler and runtime to locate the Java packages used in a Java program. (Why not call PACKAGEPATH?) This is similar to another environment variable PATH, which is used by the CMD shell to find the executable programs.

CLASSPATH can be set in one of the following ways:

CLASSPATH can be set permanently in the environment: In Windows, choose control panel ? System ? Advanced ? Environment Variables ? choose "System Variables" (for all the users) or "User Variables" (only the currently login user) ? choose "Edit" (if CLASSPATH already exists) or "New" ? Enter "CLASSPATH" as the variable name ? Enter the required directories and JAR files (separated by semicolons) as the value (e.g., ".;c:\javaproject\classes;d:\tomcat\lib\servlet-api.jar"). Take note that you need to include the current working directory (denoted by '.') in the CLASSPATH.

To check the current setting of the CLASSPATH, issue the following command:

> SET CLASSPATH

CLASSPATH can be set temporarily for that particular CMD shell session by issuing the following command:

> SET CLASSPATH=.;c:\javaproject\classes;d:\tomcat\lib\servlet-api.jar

Instead of using the CLASSPATH environment variable, you can also use the command-line option -classpath or -cp of the javac and java commands, for example,

> java –classpath c:\javaproject\classes com.abc.project1.subproject2.MyClass3

Retrieving the output of subprocess.call()

If you have Python version >= 2.7, you can use subprocess.check_output which basically does exactly what you want (it returns standard output as string).

Simple example (linux version, see note):

import subprocess

print subprocess.check_output(["ping", "-c", "1", "8.8.8.8"])

Note that the ping command is using linux notation (-c for count). If you try this on Windows remember to change it to -n for same result.

As commented below you can find a more detailed explanation in this other answer.

AttributeError: 'module' object has no attribute

The order of the importing was the reason why I was having issues:

a.py:

############
# this is a problem
# move this to below
#############
from b import NewThing

class ProblemThing(object):
    pass

class A(object):
   ###############
   # add it here
   # from b import NewThing
   ###############
   nt = NewThing()
   pass

b.py:

from a import ProblemThing

class NewThing(ProblemThing):
    pass

Just another example of how it might look, similar to RichieHindie's answer, but with classes.

How to prevent IFRAME from redirecting top-level window

Since the page you load inside the iframe can execute the "break out" code with a setInterval, onbeforeunload might not be that practical, since it could flud the user with 'Are you sure you want to leave?' dialogs.

There is also the iframe security attribute which only works on IE & Opera

:(

How do you perform address validation?

Validating it is a valid address is one thing.

But if you're trying to validate a given person lives at a given address, your only almost-guarantee would be a test mail to the address, and even that is not certain if the person is organised or knows somebody at that address.

Otherwise people could just specify an arbitrary random address which they know exists and it would mean nothing to you.

The best you can do for immediate results is request the user send a photographed / scanned copy of the head of their bank statement or some other proof-of-recent-residence, because at least then they have to work harder to forget it, and forging said things show up easily with a basic level of image forensic analysis.

how to write procedure to insert data in to the table in phpmyadmin?

This method work for me:

DELIMITER $$
DROP PROCEDURE IF EXISTS db.test $$
CREATE PROCEDURE db.test(IN id INT(12),IN NAME VARCHAR(255))
 BEGIN
 INSERT INTO USER VALUES(id,NAME);
 END$$
DELIMITER ;

If statement in select (ORACLE)

So simple you can use case statement here.

CASE WHEN ISSUE_DIVISION = ISSUE_DIVISION_2 THEN 
         CASE WHEN  ISSUE_DIVISION is null then "Null Value found" //give your option
         Else 1 End
ELSE 0 END As Issue_Division_Result

Javascript array search and remove string?

Simple solution (ES6)

If you don't have duplicate element

Array.prototype.remove = function(elem) {
  var indexElement = this.findIndex(el => el === elem);
  if (indexElement != -1)
    this.splice(indexElement, 1);
  return this;
};   

Online demo (fiddle)

JPA: JOIN in JPQL

Join on one-to-many relation in JPQL looks as follows:

select b.fname, b.lname from Users b JOIN b.groups c where c.groupName = :groupName 

When several properties are specified in select clause, result is returned as Object[]:

Object[] temp = (Object[]) em.createNamedQuery("...")
    .setParameter("groupName", groupName)
    .getSingleResult(); 
String fname = (String) temp[0];
String lname = (String) temp[1];

By the way, why your entities are named in plural form, it's confusing. If you want to have table names in plural, you may use @Table to specify the table name for the entity explicitly, so it doesn't interfere with reserved words:

@Entity @Table(name = "Users")     
public class User implements Serializable { ... } 

Tracing XML request/responses with JAX-WS

with logback.xml configuration files, you can do :

<logger name="com.sun.xml.internal.ws.transport.http.client.HttpTransportPipe" level="trace" additivity="false">
    <appender-ref ref="STDOUT"/>
</logger>

That will log the request and the response like this (depending on your configuration for the log output) :

09:50:23.266 [qtp1068445309-21] DEBUG c.s.x.i.w.t.h.c.HttpTransportPipe - ---[HTTP request - http://xyz:8081/xyz.svc]---
Accept: application/soap+xml, multipart/related
Content-Type: application/soap+xml; charset=utf-8;action="http://xyz.Web.Services/IServiceBase/GetAccessTicket"
User-Agent: JAX-WS RI 2.2.9-b130926.1035 svn-revision#5f6196f2b90e9460065a4c2f4e30e065b245e51e
<?xml version="1.0" ?><S:Envelope xmlns:S="http://www.w3.org/2003/05/soap-envelope">[CONTENT REMOVED]</S:Envelope>--------------------

09:50:23.312 [qtp1068445309-21] DEBUG c.s.x.i.w.t.h.c.HttpTransportPipe - ---[HTTP response - http://xyz:8081/xyz.svc - 200]---
null: HTTP/1.1 200 OK
Content-Length: 792
Content-Type: application/soap+xml; charset=utf-8
Date: Tue, 12 Feb 2019 14:50:23 GMT
Server: Microsoft-IIS/10.0
X-Powered-By: ASP.NET
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://www.w3.org/2005/08/addressing">[CONTENT REMOVED]</s:Envelope>--------------------

Free easy way to draw graphs and charts in C++?

Cern's ROOT produces some pretty nice stuff, I use it to display Neural Network data a lot.

Check if table exists and if it doesn't exist, create it in SQL Server 2008

Try the following statement to check for existence of a table in the database:

If not exists (select name from sysobjects where name = 'tablename')

You may create the table inside the if block.

Copy file or directories recursively in Python

Unix cp doesn't 'support both directories and files':

betelgeuse:tmp james$ cp source/ dest/
cp: source/ is a directory (not copied).

To make cp copy a directory, you have to manually tell cp that it's a directory, by using the '-r' flag.

There is some disconnect here though - cp -r when passed a filename as the source will happily copy just the single file; copytree won't.

Python function as a function argument?

Here's another way using *args (and also optionally), **kwargs:

def a(x, y):
  print x, y

def b(other, function, *args, **kwargs):
  function(*args, **kwargs)
  print other

b('world', a, 'hello', 'dude')

Output

hello dude
world

Note that function, *args, **kwargs have to be in that order and have to be the last arguments to the function calling the function.

Program to find prime numbers

in the university it was necessary to count prime numbers up to 10,000 did so, the teacher was a little surprised, but I passed the test. Lang c#

void Main()
{
    int number=1;
    for(long i=2;i<10000;i++)
    {
        if(PrimeTest(i))
        {
            Console.WriteLine(number+++" " +i);
        }
    }
}

List<long> KnownPrime = new List<long>();
private bool PrimeTest(long i)
{
    if (i == 1) return false;
    if (i == 2)
    {
        KnownPrime.Add(i);
        return true;
    }
    foreach(int k in KnownPrime)
    {
        if(i%k==0)
            return false;
    }
    KnownPrime.Add(i);
    return true;
}

ImportError: No module named sklearn.cross_validation

Make sure you have Anaconda installed and then create a virtualenv using conda. This will ensure all the imports work

Python 2.7.9 |Anaconda 2.2.0 (64-bit)| (default, Mar  9 2015, 16:20:48) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
Anaconda is brought to you by Continuum Analytics.
Please check out: http://continuum.io/thanks and https://binstar.org
>>> from sklearn.cross_validation import train_test_split

Saving awk output to variable

as noted earlier, setting bash variables does not allow whitespace between the variable name on the LHS, and the variable value on the RHS, of the '=' sign.

awk can do everything and avoid the "awk"ward extra 'grep'. The use of awk's printf is to not add an unnecessary "\n" in the string which would give perl-ish matcher programs conniptions. The variable/parameter expansion for your case in bash doesn't have that issue, so either of these work:

variable=$(ps -ef | awk '/port 10 \-/ {print $12}')

variable=`ps -ef | awk '/port 10 \-/ {print $12}'`

The '-' int the awk record matching pattern removes the need to remove awk itself from the search results.

Adding VirtualHost fails: Access Forbidden Error 403 (XAMPP) (Windows 7)

For me (also XAMPP on Windows 7), this is what worked:

<Directory "C:\projects\myfolder\htdocs">`
   AllowOverride All
   Require all granted
   Options Indexes FollowSymLinks
</Directory>` 

It is this line that would cause the 403:

Order allow,deny

What is the equivalent of 'describe table' in SQL Server?

select * from sysobjects where name='TABLENAME'

Determine if map contains a value for a key?

Check the return value of find against end.

map<int, Bar>::iterator it = m.find('2');
if ( m.end() != it ) { 
  // contains
  ...
}

Node.js: How to send headers with form data using request module?

I found the solution of this problem and i should work i'm sure about this because i also face the same problem

here is my solution----->

var request = require('request');

//set url
var url = 'http://localhost:8088/example';

//set header
var headers = {
    'Authorization': 'Your authorization'
};

//set form data
var form = {first_name: first_name, last_name: last_name};

//set request parameter
request.post({headers: headers, url: url, form: form, method: 'POST'}, function (e, r, body) {

    var bodyValues = JSON.parse(body);
    res.send(bodyValues);
});

Recursive Fibonacci

I think that all that solutions are inefficient. They require a lot of recursive calls to get the result.

unsigned fib(unsigned n) {
    if(n == 0) return 0;
    if(n == 1) return 1;
    return fib(n-1) + fib(n-2);
}

This code requires 14 calls to get result for fib(5), 177 for fin(10) and 2.7kk for fib(30).

You should better use this approach or if you want to use recursion try this:

unsigned fib(unsigned n, unsigned prev1 = 0, unsigned prev2 = 1, int depth = 2)     
{
    if(n == 0) return 0;
    if(n == 1) return 1;
    if(depth < n) return fib(n, prev2, prev1+prev2, depth+1);
    return prev1+prev2;
}

This function requires n recursive calls to calculate Fibonacci number for n. You can still use it by calling fib(10) because all other parameters have default values.

Difference between onLoad and ng-init in angular

ng-init is a directive that can be placed inside div's, span's, whatever, whereas onload is an attribute specific to the ng-include directive that functions as an ng-init. To see what I mean try something like:

<span onload="a = 1">{{ a }}</span>
<span ng-init="b = 2">{{ b }}</span>

You'll see that only the second one shows up.

An isolated scope is a scope which does not prototypically inherit from its parent scope. In laymen's terms if you have a widget that doesn't need to read and write to the parent scope arbitrarily then you use an isolate scope on the widget so that the widget and widget container can freely use their scopes without overriding each other's properties.

Java : Cannot format given Object as a Date

DateFormat.format only works on Date values.

You should use two SimpleDateFormat objects: one for parsing, and one for formatting. For example:

// Note, MM is months, not mm
DateFormat outputFormat = new SimpleDateFormat("MM/yyyy", Locale.US);
DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX", Locale.US);

String inputText = "2012-11-17T00:00:00.000-05:00";
Date date = inputFormat.parse(inputText);
String outputText = outputFormat.format(date);

EDIT: Note that you may well want to specify the time zone and/or locale in your formats, and you should also consider using Joda Time instead of all of this to start with - it's a much better date/time API.

Can not deserialize instance of java.util.ArrayList out of START_OBJECT token

Dto response = softConvertValue(jsonData, Dto.class);


     public static <T> T softConvertValue(Object fromValue, Class<T> toValueType) 
        {
            ObjectMapper objMapper = new ObjectMapper();
            return objMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
                    .convertValue(fromValue, toValueType);
        }

Return multiple fields as a record in PostgreSQL with PL/pgSQL

You can achieve this by using simply as a returns set of records using return query.

CREATE OR REPLACE FUNCTION schemaName.get_two_users_from_school(schoolid bigint)
 RETURNS SETOF record
 LANGUAGE plpgsql
AS $function$
begin

 return query
  SELECT id, name FROM schemaName.user where school_id = schoolid;

end;
$function$

And call this function as : select * from schemaName.get_two_users_from_school(schoolid) as x(a bigint, b varchar);

Working with dictionaries/lists in R

Yes, the list type is a good approximation. You can use names() on your list to set and retrieve the 'keys':

> foo <- vector(mode="list", length=3)
> names(foo) <- c("tic", "tac", "toe")
> foo[[1]] <- 12; foo[[2]] <- 22; foo[[3]] <- 33
> foo
$tic
[1] 12

$tac
[1] 22

$toe
[1] 33

> names(foo)
[1] "tic" "tac" "toe"
> 

How Can I Set the Default Value of a Timestamp Column to the Current Timestamp with Laravel Migrations?

This doesn't work for a fact:

$table->timestamp('created_at')->default('CURRENT_TIMESTAMP');

It doesn't remove the 'default 0' that seems to come with selecting timestamp and it just appends the custom default. But we kind of need it without the quotes. Not everything that manipulates a DB is coming from Laravel4. That's his point. He wants custom defaults on certain columns like:

$table->timestamps()->default('CURRENT_TIMESTAMP');

I don't think it's possible with Laravel. I've been searching for an hour now to see whether it's possible.


Update: Paulos Freita's answer shows that it is possible, but the syntax isn't straightforward.

How to validate an email address in PHP

This will not only validate your email, but also sanitize it for unexpected characters:

$email  = $_POST['email'];
$emailB = filter_var($email, FILTER_SANITIZE_EMAIL);

if (filter_var($emailB, FILTER_VALIDATE_EMAIL) === false ||
    $emailB != $email
) {
    echo "This email adress isn't valid!";
    exit(0);
}

Initializing C# auto-properties

You can do it via the constructor of your class:

public class foo {
  public foo(){
    Bar = "bar";
  }
  public string Bar {get;set;}
}

If you've got another constructor (ie, one that takes paramters) or a bunch of constructors you can always have this (called constructor chaining):

public class foo {
  private foo(){
    Bar = "bar";
    Baz = "baz";
  }
  public foo(int something) : this(){
    //do specialized initialization here
    Baz = string.Format("{0}Baz", something);
  }
  public string Bar {get; set;}
  public string Baz {get; set;}
}

If you always chain a call to the default constructor you can have all default property initialization set there. When chaining, the chained constructor will be called before the calling constructor so that your more specialized constructors will be able to set different defaults as applicable.

Match the path of a URL, minus the filename extension

There's no need to use a regular expression to dissect a URL. PHP has built-in functions for this, pathinfo() and parse_url().

Jquery - animate height toggle

The below code worked for me in jQuery2.1.3

$("#topbar").animate('{height:"toggle"}');

Need not calculate your div height,padding,margin and borders. It will take care.

Calling a phone number in swift

Many of the other answers don't work for Swift 5. Below is the code update to Swift 5:

let formattedNumber = phoneNumberVariable.components(separatedBy: NSCharacterSet.decimalDigits.inverted).joined(separator: "")

if let url = NSURL(string: ("tel:" + (formattedNumber)!)) {
    if #available(iOS 10.0, *) {
        UIApplication.shared.open(url as URL, options: [:], completionHandler: nil)
    } else {
        UIApplication.shared.openURL(url as URL)
    }
}

PS:

  1. With most of the answers, I wasn't able to get the prompt on the device. The above code was successfully able to display the prompt.
  2. There is no // after tel: like most answers have. And it works fine.

Display PDF file inside my android application

I do not think that you can do this easily. you should consider this answer here:

How can I display a pdf document into a Webview?

basically you'll be able to see a pdf if it is hosted online via google documents, but not if you have it in your device (you'll need a standalone reader for that)

Center a button in a Linear layout

You can use the RelativeLayout.

find first sequence item that matches a criterion

If you don't have any other indexes or sorted information for your objects, then you will have to iterate until such an object is found:

next(obj for obj in objs if obj.val == 5)

This is however faster than a complete list comprehension. Compare these two:

[i for i in xrange(100000) if i == 1000][0]

next(i for i in xrange(100000) if i == 1000)

The first one needs 5.75ms, the second one 58.3µs (100 times faster because the loop 100 times shorter).

Can I install the "app store" in an IOS simulator?

This is NOT possible

The Simulator does not run ARM code, ONLY x86 code. Unless you have the raw source code from Apple, you won't see the App Store on the Simulator.

The app you write you will be able to test in the Simulator by running it directly from Xcode even if you don't have a developer account. To test your app on an actual device, you will need to be apart of the Apple Developer program.

JavaScript post request like a form submit

This is based on beauSD's code using jQuery. It is improved so it works recursively on objects.

function post(url, params, urlEncoded, newWindow) {
    var form = $('<form />').hide();
    form.attr('action', url)
        .attr('method', 'POST')
        .attr('enctype', urlEncoded ? 'application/x-www-form-urlencoded' : 'multipart/form-data');
    if(newWindow) form.attr('target', '_blank');

    function addParam(name, value, parent) {
        var fullname = (parent.length > 0 ? (parent + '[' + name + ']') : name);
        if(value instanceof Object) {
            for(var i in value) {
                addParam(i, value[i], fullname);
            }
        }
        else $('<input type="hidden" />').attr({name: fullname, value: value}).appendTo(form);
    };

    addParam('', params, '');

    $('body').append(form);
    form.submit();
}

SQL multiple column ordering

ORDER BY column1 DESC, column2

This sorts everything by column1 (descending) first, and then by column2 (ascending, which is the default) whenever the column1 fields for two or more rows are equal.

jquery smooth scroll to an anchor?

works

$('a[href*=#]').each(function () {
    $(this).attr('href', $(this).attr('href').replace('#', '#_'));
    $(this).on( "click", function() {

        var hashname = $(this).attr('href').replace('#_', '');

        if($(this).attr('href') == "#_") {
            $('html, body').animate({ scrollTop: 0 }, 300);
        }
        else {
            var target = $('a[name="' + hashname + '"], #' + hashname),
                targetOffset = target.offset().top;
            if(targetOffset >= 1) {
                $('html, body').animate({ scrollTop: targetOffset-60 }, 300);
            }
        }
    });
});

Using Lato fonts in my css (@font-face)

Well, you're missing the letter 'd' in url("~/fonts/Lato-Bol.ttf"); - but assuming that's not it, I would open up your page with developer tools in Chrome and make sure there's no errors loading any of the files (you would probably see an issue in the JavaScript console, or you can check the Network tab and see if anything is red).

(I don't see anything obviously wrong with the code you have posted above)

Other things to check: 1) Are you including your CSS file in your html above the lines where you are trying to use the font-family style? 2) What do you see in the CSS panel in the developer tools for that div? Is font-family: lato crossed out?

How to handle calendar TimeZones using Java?

Method for converting from one timeZone to other(probably it works :) ).

/**
 * Adapt calendar to client time zone.
 * @param calendar - adapting calendar
 * @param timeZone - client time zone
 * @return adapt calendar to client time zone
 */
public static Calendar convertCalendar(final Calendar calendar, final TimeZone timeZone) {
    Calendar ret = new GregorianCalendar(timeZone);
    ret.setTimeInMillis(calendar.getTimeInMillis() +
            timeZone.getOffset(calendar.getTimeInMillis()) -
            TimeZone.getDefault().getOffset(calendar.getTimeInMillis()));
    ret.getTime();
    return ret;
}

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve com.android.support:appcompat-v7:26.1.0

Below is a workaround demo image of ; Uncheck Offline work option by going to:

File -> Settings -> Build, Execution, Deployment -> Gradle

enter image description here

If above workaround not works then try this:

  1. Open the build.gradle file for your application.

  2. Make sure that the repositories section includes a maven section with the "https://maven.google.com" endpoint. For example:

    allprojects {
         repositories {
             jcenter()
             maven {
                 url "https://maven.google.com"
             }
         }
    }
    
  3. Add the support library to the dependencies section. For example, to add the v4 core-utils library, add the following lines:

    dependencies {
        ...
        compile "com.android.support:support-core-utils:27.1.0"
    }
    

Caution: Using dynamic dependencies (for example, palette-v7:23.0.+) can cause unexpected version updates and regression incompatibilities. We recommend that you explicitly specify a library version (for example, palette-v7:27.1.0).

Manifest Declaration Changes

Specifically, you should update the android:minSdkVersion element of the <uses-sdk> tag in the manifest to the new, lower version number, as shown below:

<uses-sdk
  android:minSdkVersion="14"
  android:targetSdkVersion="23" />

If you are using Gradle build files, the minSdkVersion setting in the build file overrides the manifest settings.

apply plugin: 'com.android.application'

android {
   ...
      defaultConfig {
            minSdkVersion 16
            ...
        }
        ...
    }

Following Android Developer Library Support.

SQL - Select first 10 rows only?

Firebird:

SELECT FIRST 10 * FROM MYTABLE

pandas dataframe groupby datetime month

Managed to do it:

b = pd.read_csv('b.dat')
b.index = pd.to_datetime(b['date'],format='%m/%d/%y %I:%M%p')
b.groupby(by=[b.index.month, b.index.year])

Or

b.groupby(pd.Grouper(freq='M'))  # update for v0.21+

Command to get nth line of STDOUT

Yes, the most efficient way (as already pointed out by Jonathan Leffler) is to use sed with print & quit:

set -o pipefail                        # cf. help set
time -p ls -l | sed -n -e '2{p;q;}'    # only print the second line & quit (on Mac OS X)
echo "$?: ${PIPESTATUS[*]}"            # cf. man bash | less -p 'PIPESTATUS'

Function for 'does matrix contain value X?'

For floating point data, you can use the new ismembertol function, which computes set membership with a specified tolerance. This is similar to the ismemberf function found in the File Exchange except that it is now built-in to MATLAB. Example:

>> pi_estimate = 3.14159;
>> abs(pi_estimate - pi)
ans =
   5.3590e-08
>> tol = 1e-7;
>> ismembertol(pi,pi_estimate,tol)
ans =
     1

Entity Framework Migrations renaming tables and columns

Table names and column names can be specified as part of the mapping of DbContext. Then there is no need to do it in migrations.

public class MyContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Restaurant>()
            .HasMany(p => p.Cuisines)
            .WithMany(r => r.Restaurants)
            .Map(mc =>
            {
                mc.MapLeftKey("RestaurantId");
                mc.MapRightKey("CuisineId");
                mc.ToTable("RestaurantCuisines");
            });
     }
}

Simple DateTime sql query

This has worked for me in both SQL Server 2005 and 2008:

SELECT * from TABLE
WHERE FIELDNAME > {ts '2013-02-01 15:00:00.001'}
  AND FIELDNAME < {ts '2013-08-05 00:00:00.000'}

Cannot resolve symbol 'AppCompatActivity'

It is too simple.here are the steps you need to follow

1-Exit Android studio.

2-Go to your project directory.

3-Something like this in my case( F>Android->YourProjectName->.idea).

4)-delete libraries folder present in .idea folder.

5)-restart your android studio. and your issue is resolved.

JQuery: How to get selected radio button value?

jQuery("input:radio[name=myradiobutton]:checked").val();

How to set space between listView Items in Android

<ListView
    android:clipToPadding="false"
    android:paddingTop="10dp"
    android:paddingBottom="10dp"
    android:dividerHeight="10dp"
    android:divider="@null"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</ListView>

and set paddingTop, paddingBottom and dividerHeight to the same value to get equal spacing between all elements and space at the top and bottom of the list.

I set clipToPadding to false to let the views be drawn in this padded area.

I set divider to @null to remove the lines between list elements.

How to split data into 3 sets (train, validation and test)?

However, one approach to dividing the dataset into train, test, cv with 0.6, 0.2, 0.2 would be to use the train_test_split method twice.

from sklearn.model_selection import train_test_split

x, x_test, y, y_test = train_test_split(xtrain,labels,test_size=0.2,train_size=0.8)
x_train, x_cv, y_train, y_cv = train_test_split(x,y,test_size = 0.25,train_size =0.75)

HTTP Status 500 - Error instantiating servlet class pkg.coreServlet

I had an issue with Servlet instantiation. I cleaned the project and it worked for me. In eclipse menu, Go to Project->Clean. It should work.

How do you get the list of targets in a makefile?

@nobar's answer helpfully shows how to use tab completion to list a makefile's targets.

  • This works great for platforms that provide this functionality by default (e.g., Debian, Fedora).

  • On other platforms (e.g., Ubuntu) you must explicitly load this functionality, as implied by @hek2mgl's answer:

    • . /etc/bash_completion installs several tab-completion functions, including the one for make
    • Alternatively, to install only tab completion for make:
      • . /usr/share/bash-completion/completions/make
  • For platforms that don't offer this functionality at all, such as OSX, you can source the following commands (adapated from here) to implement it:
_complete_make() { COMPREPLY=($(compgen -W "$(make -pRrq : 2>/dev/null | awk -v RS= -F: '/^# File/,/^# Finished Make data base/ {if ($1 !~ "^[#.]") {print $1}}' | egrep -v '^[^[:alnum:]]' | sort | xargs)" -- "${COMP_WORDS[$COMP_CWORD]}")); }
complete -F _complete_make make
  • Note: This is not as sophisticated as the tab-completion functionality that comes with Linux distributions: most notably, it invariably targets the makefile in the current directory, even if the command line targets a different makefile with -f <file>.

Using true and false in C

Just include <stdbool.h> if your system provides it. That defines a number of macros, including bool, false, and true (defined to _Bool, 0, and 1 respectively). See section 7.16 of C99 for more details.

How do I set headers using python's urllib?

For multiple headers do as follow:

import urllib2
req = urllib2.Request('http://www.example.com/')
req.add_header('param1', '212212')
req.add_header('param2', '12345678')
req.add_header('other_param1', 'sample')
req.add_header('other_param2', 'sample1111')
req.add_header('and_any_other_parame', 'testttt')
resp = urllib2.urlopen(req)
content = resp.read()

React-Native Button style not work

I had an issue with margin and padding with a Button. I added Button inside a View component and apply your properties to the View.

<View style={{margin:10}}>
<Button
  title="Decrypt Data"
  color="orange"
  accessibilityLabel="Tap to Decrypt Data"
  onPress={() => {
    Alert.alert('You tapped the Decrypt button!');
  }}
  />  
</View>

Razor If/Else conditional operator syntax

You need to put the entire ternary expression in parenthesis. Unfortunately that means you can't use "@:", but you could do something like this:

@(deletedView ? "Deleted" : "Created by")

Razor currently supports a subset of C# expressions without using @() and unfortunately, ternary operators are not part of that set.

ASP.NET Core configuration for .NET Core console application

You can use this code snippet. It includes Configuration and DI.

public class Program
{
    public static ILoggerFactory LoggerFactory;
    public static IConfigurationRoot Configuration;

    public static void Main(string[] args)
    {
        Console.OutputEncoding = Encoding.UTF8;

        string environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

        if (String.IsNullOrWhiteSpace(environment))
            throw new ArgumentNullException("Environment not found in ASPNETCORE_ENVIRONMENT");

        Console.WriteLine("Environment: {0}", environment);

        var services = new ServiceCollection();

        // Set up configuration sources.
        var builder = new ConfigurationBuilder()
            .SetBasePath(Path.Combine(AppContext.BaseDirectory))
            .AddJsonFile("appsettings.json", optional: true);
        if (environment == "Development")
        {

            builder
                .AddJsonFile(
                    Path.Combine(AppContext.BaseDirectory, string.Format("..{0}..{0}..{0}", Path.DirectorySeparatorChar), $"appsettings.{environment}.json"),
                    optional: true
                );
        }
        else
        {
            builder
                .AddJsonFile($"appsettings.{environment}.json", optional: false);
        }

        Configuration = builder.Build();

        LoggerFactory = new LoggerFactory()
            .AddConsole(Configuration.GetSection("Logging"))
            .AddDebug();

        services
            .AddEntityFrameworkNpgsql()
            .AddDbContext<FmDataContext>(o => o.UseNpgsql(connectionString), ServiceLifetime.Transient);

        services.AddTransient<IPackageFileService, PackageFileServiceImpl>();

        var serviceProvider = services.BuildServiceProvider();

        var packageFileService = serviceProvider.GetRequiredService<IPackageFileService>();

        ............
    }
}

Oh, and don't forget to add in the project.json

{
  "version": "1.0.0-*",
  "buildOptions": {
    "emitEntryPoint": true,
    "copyToOutput": {
      "includeFiles": [
        "appsettings.json",
        "appsettings.Integration.json",
        "appsettings.Production.json",
        "appsettings.Staging.json"
      ]
    }
  },

  "publishOptions": {
    "copyToOutput": [
      "appsettings.json",
      "appsettings.Integration.json",
      "appsettings.Production.json",
      "appsettings.Staging.json"
    ]
  },
...
}

Heroku + node.js error (Web process failed to bind to $PORT within 60 seconds of launch)

The error happens when Heroku failed to bind the port or hostname at server.listen(port, [host], [backlog], [callback]).

What Heroku requires is .listen(process.env.PORT) or .listen(process.env.PORT, '0.0.0.0')

So more generically, to support other environments, use this:

var server_port = process.env.YOUR_PORT || process.env.PORT || 80;
var server_host = process.env.YOUR_HOST || '0.0.0.0';
server.listen(server_port, server_host, function() {
    console.log('Listening on port %d', server_port);
});

Invisible characters - ASCII

I just went through the character map to get these. They are all in Calibri.

Number    Name                   HTML Code    Appearance
------    --------------------   ---------    ----------
U+2000    En Quad                &#8192;      " "
U+2001    Em Quad                &#8193;      " "
U+2002    En Space               &#8194;      " "
U+2003    Em Space               &#8195;      " "
U+2004    Three-Per-Em Space     &#8196;      " "
U+2005    Four-Per-Em Space      &#8197;      " "
U+2006    Six-Per-Em Space       &#8198;      " "
U+2007    Figure Space           &#8199;      " "
U+2008    Punctuation Space      &#8200;      " "
U+2009    Thin Space             &#8201;      " "
U+200A    Hair Space             &#8202;      " "
U+200B    Zero-Width Space       &#8203;      "​"
U+200C    Zero Width Non-Joiner  &#8204;      "‌"
U+200D    Zero Width Joiner      &#8205;      "‍"
U+200E    Left-To-Right Mark     &#8206;      "‎"
U+200F    Right-To-Left Mark     &#8207;      "‏"
U+202F    Narrow No-Break Space  &#8239;      " "

How can I change or remove HTML5 form validation default error messages?

The setCustomValidity let you change the default validation message.Here is a simple exmaple of how to use it.

var age  =  document.getElementById('age');
    age.form.onsubmit = function () {
    age.setCustomValidity("This is not a valid age.");
 };

How do I convert a file path to a URL in ASP.NET

As far as I know, there's no method to do what you want; at least not directly. I'd store the photosLocation as a path relative to the application; for example: "~/Images/". This way, you could use MapPath to get the physical location, and ResolveUrl to get the URL (with a bit of help from System.IO.Path):

string photosLocationPath = HttpContext.Current.Server.MapPath(photosLocation);
if (Directory.Exists(photosLocationPath))
{
    string[] files = Directory.GetFiles(photosLocationPath, "*.jpg");
    if (files.Length > 0)
    {
        string filenameRelative = photosLocation +  Path.GetFilename(files[0])   
        return Page.ResolveUrl(filenameRelative);
    }
}

How can I get the Windows last reboot reason

This article explains in detail how to find the reason for last startup/shutdown. In my case, this was due to windows SCCM pushing updates even though I had it disabled locally. Visit the article for full details with pictures. For reference, here are the steps copy/pasted from the website:

  1. Press the Windows + R keys to open the Run dialog, type eventvwr.msc, and press Enter.

  2. If prompted by UAC, then click/tap on Yes (Windows 7/8) or Continue (Vista).

  3. In the left pane of Event Viewer, double click/tap on Windows Logs to expand it, click on System to select it, then right click on System, and click/tap on Filter Current Log.

  4. Do either step 5 or 6 below for what shutdown events you would like to see.

  5. To See the Dates and Times of All User Shut Downs of the Computer

    A) In Event sources, click/tap on the drop down arrow and check the USER32 box.

    B) In the All Event IDs field, type 1074, then click/tap on OK.

    C) This will give you a list of power off (shutdown) and restart Shutdown Type of events at the top of the middle pane in Event Viewer.

    D) You can scroll through these listed events to find the events with power off as the Shutdown Type. You will notice the date and time, and what user was responsible for shutting down the computer per power off event listed.

    E) Go to step 7.

  6. To See the Dates and Times of All Unexpected Shut Downs of the Computer

    A) In the All Event IDs field, type 6008, then click/tap on OK.

    B) This will give you a list of unexpected shutdown events at the top of the middle pane in Event Viewer. You can scroll through these listed events to see the date and time of each one.

Excel add one hour

In cell A1, enter the time.
In cell B2, enter =A1+1/24

Simple PHP form: Attachment to email (code golf)

I haven't tested the email part of this (my test box does not send email) but I think it will work.

<?php
if ($_POST) {
$s = md5(rand());
mail('[email protected]', 'attachment', "--$s

{$_POST['m']}
--$s
Content-Type: application/octet-stream; name=\"f\"
Content-Transfer-Encoding: base64
Content-Disposition: attachment

".chunk_split(base64_encode(join(file($_FILES['f']['tmp_name']))))."
--$s--", "MIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"$s\"");
exit;
}
?>
<form method="post" enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF'] ?>">
<textarea name="m"></textarea><br>
<input type="file" name="f"/><br>
<input type="submit">
</form>

Trigger an action after selection select2

It works for me:

$('#yourselect').on("change", function(e) { 
   // what you would like to happen
});

Export DataTable to Excel File

Working code for Excel Export

 try
        {
            DataTable dt = DS.Tables[0];
            string attachment = "attachment; filename=log.xls";
            Response.ClearContent();
            Response.AddHeader("content-disposition", attachment);
            Response.ContentType = "application/vnd.ms-excel";
            string tab = "";
            foreach (DataColumn dc in dt.Columns)
            {
                Response.Write(tab + dc.ColumnName);
                tab = "\t";
            }
            Response.Write("\n");
            int i;
            foreach (DataRow dr in dt.Rows)
            {
                tab = "";
                for (i = 0; i < dt.Columns.Count; i++)
                {
                    Response.Write(tab + dr[i].ToString());
                    tab = "\t";
                }
                Response.Write("\n");
            }
            Response.End();
        }
        catch (Exception Ex)
        { }

Error retrieving parent for item: No resource found that matches the given name after upgrading to AppCompat v23

android {
    compileSdkVersion 23
    buildToolsVersion '23.0.1'

defaultConfig {
    applicationId ""
    minSdkVersion 14
    targetSdkVersion 22
    versionCode 1
    versionName "1.0"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
  }
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.google.code.gson:gson:2.3.1'
compile 'com.android.support:recyclerview-v7:23.0.0'
compile 'com.android.support:appcompat-v7:23.0.1'
}

When I run `npm install`, it returns with `ERR! code EINTEGRITY` (npm 5.3.0)

This was not yet mentioned but make sure that your SYSTEM TIME is correct. If it is too out of sync it will cause a EINTEGRITY error. When you are doing npm publish / install.

How does numpy.histogram() work?

A bin is range that represents the width of a single bar of the histogram along the X-axis. You could also call this the interval. (Wikipedia defines them more formally as "disjoint categories".)

The Numpy histogram function doesn't draw the histogram, but it computes the occurrences of input data that fall within each bin, which in turns determines the area (not necessarily the height if the bins aren't of equal width) of each bar.

In this example:

 np.histogram([1, 2, 1], bins=[0, 1, 2, 3])

There are 3 bins, for values ranging from 0 to 1 (excl 1.), 1 to 2 (excl. 2) and 2 to 3 (incl. 3), respectively. The way Numpy defines these bins if by giving a list of delimiters ([0, 1, 2, 3]) in this example, although it also returns the bins in the results, since it can choose them automatically from the input, if none are specified. If bins=5, for example, it will use 5 bins of equal width spread between the minimum input value and the maximum input value.

The input values are 1, 2 and 1. Therefore, bin "1 to 2" contains two occurrences (the two 1 values), and bin "2 to 3" contains one occurrence (the 2). These results are in the first item in the returned tuple: array([0, 2, 1]).

Since the bins here are of equal width, you can use the number of occurrences for the height of each bar. When drawn, you would have:

  • a bar of height 0 for range/bin [0,1] on the X-axis,
  • a bar of height 2 for range/bin [1,2],
  • a bar of height 1 for range/bin [2,3].

You can plot this directly with Matplotlib (its hist function also returns the bins and the values):

>>> import matplotlib.pyplot as plt
>>> plt.hist([1, 2, 1], bins=[0, 1, 2, 3])
(array([0, 2, 1]), array([0, 1, 2, 3]), <a list of 3 Patch objects>)
>>> plt.show()

enter image description here

How do I find a default constraint using INFORMATION_SCHEMA?

WHILE EXISTS( 
    SELECT * FROM  sys.all_columns 
    INNER JOIN sys.tables ST  ON all_columns.object_id = ST.object_id
    INNER JOIN sys.schemas ON ST.schema_id = schemas.schema_id
    INNER JOIN sys.default_constraints ON all_columns.default_object_id = default_constraints.object_id
    WHERE 
    schemas.name = 'dbo'
    AND ST.name = 'MyTable'
)
BEGIN 
DECLARE @SQL NVARCHAR(MAX) = N'';

SET @SQL = (  SELECT TOP 1
     'ALTER TABLE ['+  schemas.name + '].[' + ST.name + '] DROP CONSTRAINT ' + default_constraints.name + ';'
   FROM 
      sys.all_columns

         INNER JOIN
      sys.tables ST
         ON all_columns.object_id = ST.object_id

         INNER JOIN 
      sys.schemas
         ON ST.schema_id = schemas.schema_id

         INNER JOIN
      sys.default_constraints
         ON all_columns.default_object_id = default_constraints.object_id

   WHERE 
         schemas.name = 'dbo'
      AND ST.name = 'MyTable'
      )
   PRINT @SQL
   EXECUTE sp_executesql @SQL 

   --End if Error 
   IF @@ERROR <> 0 
   BREAK
END 

How to set default font family for entire Android app

To change your app font follow the following steps:

  1. Inside res directory create a new directory and name it font.
  2. Insert your font .ttf/.otf inside the font folder, Make sure the font name is lower case letters and underscore only.
  3. Inside res -> values -> styles.xml inside <resources> -> <style> add your font <item name="android:fontFamily">@font/font_name</item>.

enter image description here

Now all your app text should be in the font that you add.

How can you find out which process is listening on a TCP or UDP port on Windows?

Netstat:

  • -a displays all connection and listening ports
  • -b displays executables
  • -n stop resolve hostnames (numerical form)
  • -o owning process

    netstat -bano | findstr "7002"
    
    netstat -ano > ano.txt 
    

The Currports tool helps to search and filter

Can you use CSS to mirror/flip text?

There's also the rotateY for a real mirror one:

transform: rotateY(180deg);

Which, perhaps, is even more clear and understandable.

EDIT: Doesn't seem to work on Opera though… sadly. But it works fine on Firefox. I guess it might required to implicitly say that we are doing some kind of translate3d perhaps? Or something like that.

Is the Javascript date object always one day off?

You can convert this date to UTC date by

new Date(Date.UTC(Year, Month, Day, Hour, Minute, Second))

And it is always recommended to use UTC (universal time zone) date instead of Date with local time, as by default dates are stored in Database with UTC. So, it is good practice to use and interpret dates in UTC format throughout entire project. For example,

Date.getUTCYear(), getUTCMonth(), getUTCDay(), getUTCHours()

So, using UTC dates solves all the problem related to timezone issues.

How to set a border for an HTML div tag

In bootstrap 4, you can use border utilities like so.

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>_x000D_
_x000D_
<style>_x000D_
  .border-5 {_x000D_
    border-width: 5px !important;_x000D_
  }_x000D_
</style>_x000D_
_x000D_
<textarea class="border border-dark border-5">some content</textarea>
_x000D_
_x000D_
_x000D_

sql: check if entry in table A exists in table B

If you are set on using EXISTS you can use the below in SQL Server:

SELECT * FROM TableB as b
WHERE NOT EXISTS
(
   SELECT * FROM TableA as a
   WHERE b.id = a.id
)

How do you append rows to a table using jQuery?

You should append to the table and not the rows.

<script type="text/javascript">
$('a').click(function() {
    $('#myTable').append('<tr class="child"><td>blahblah<\/td></tr>');
});
</script>

Redefine tab as 4 spaces

Put your desired settings in the ~/.vimrc file -- See below for some guidelines and best practices.

There are four main ways to use tabs in Vim:

  1. Always keep 'tabstop' at 8, set 'softtabstop' and 'shiftwidth' to 4 (or 3 or whatever you prefer) and use 'noexpandtab'. Then Vim will use a mix of tabs and spaces, but typing and will behave like a tab appears every 4 (or 3) characters.

    Note: Setting 'tabstop' to any other value than 8 can make your file appear wrong in many places (e.g., when printing it).

  2. Set 'tabstop' and 'shiftwidth' to whatever you prefer and use 'expandtab'. This way you will always insert spaces. The formatting will never be messed up when 'tabstop' is changed.

  3. Set 'tabstop' and 'shiftwidth' to whatever you prefer and use a |modeline| to set these values when editing the file again. Only works when using Vim to edit the file.

  4. Always set 'tabstop' and 'shiftwidth' to the same value, and 'noexpandtab'. This should then work (for initial indents only) for any tabstop setting that people use. It might be nice to have tabs after the first non-blank inserted as spaces if you do this though. Otherwise aligned comments will be wrong when 'tabstop' ischanged.

Source:

PHP add elements to multidimensional array with array_push

I know the topic is old, but I just fell on it after a google search so... here is another solution:

$array_merged = array_merge($array_going_first, $array_going_second);

This one seems pretty clean to me, it works just fine!

When to use cla(), clf() or close() for clearing a plot in matplotlib?

There is just a caveat that I discovered today. If you have a function that is calling a plot a lot of times you better use plt.close(fig) instead of fig.clf() somehow the first does not accumulate in memory. In short if memory is a concern use plt.close(fig) (Although it seems that there are better ways, go to the end of this comment for relevant links).

So the the following script will produce an empty list:

for i in range(5):
    fig = plot_figure()
    plt.close(fig)
# This returns a list with all figure numbers available
print(plt.get_fignums())

Whereas this one will produce a list with five figures on it.

for i in range(5):
    fig = plot_figure()
    fig.clf()
# This returns a list with all figure numbers available
print(plt.get_fignums())

From the documentation above is not clear to me what is the difference between closing a figure and closing a window. Maybe that will clarify.

If you want to try a complete script there you have:

import numpy as np
import matplotlib.pyplot as plt
x = np.arange(1000)
y = np.sin(x)

for i in range(5):
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    ax.plot(x, y)
    plt.close(fig)

print(plt.get_fignums())

for i in range(5):
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    ax.plot(x, y)
    fig.clf()

print(plt.get_fignums())

If memory is a concern somebody already posted a work-around in SO see: Create a figure that is reference counted

Process all arguments except the first one (in a bash script)

http://wiki.bash-hackers.org/scripting/posparams

It explains the use of shift (if you want to discard the first N parameters) and then implementing Mass Usage

How do I get the type of a variable?

If you need to make a comparison between a class and a known type, for example:

class Example{};
...
Example eg = Example();

You can use this comparison line:

bool isType = string( typeid(eg).name() ).find("Example") != string::npos;

which checks the typeid name contains the string type (the typeid name has other mangled data, so its best to do a s1.find(s2) instead of ==).

Java 8, Streams to find the duplicate elements

Try this solution:

public class Anagramm {

public static boolean isAnagramLetters(String word, String anagramm) {
    if (anagramm.isEmpty()) {
        return false;
    }

    Map<Character, Integer> mapExistString = CharCountMap(word);
    Map<Character, Integer> mapCheckString = CharCountMap(anagramm);
    return enoughLetters(mapExistString, mapCheckString);
}

private static Map<Character, Integer> CharCountMap(String chars) {
    HashMap<Character, Integer> charCountMap = new HashMap<Character, Integer>();
    for (char c : chars.toCharArray()) {
        if (charCountMap.containsKey(c)) {
            charCountMap.put(c, charCountMap.get(c) + 1);
        } else {
            charCountMap.put(c, 1);
        }
    }
    return charCountMap;
}

static boolean enoughLetters(Map<Character, Integer> mapExistString, Map<Character,Integer> mapCheckString) {
    for( Entry<Character, Integer> e : mapCheckString.entrySet() ) {
        Character letter = e.getKey();
        Integer available = mapExistString.get(letter);
        if (available == null || e.getValue() > available) return false;
    }
    return true;
}

}

How do you push just a single Git branch (and no other branches)?

By default git push updates all the remote branches. But you can configure git to update only the current branch to it's upstream.

git config push.default upstream

It means git will update only the current (checked out) branch when you do git push.

Other valid options are:

  • nothing : Do not push anything (error out) unless a refspec is explicitly given. This is primarily meant for people who want to avoid mistakes by always being explicit.
  • matching : Push all branches having the same name on both ends. (default option prior to Ver 1.7.11)
  • upstream: Push the current branch to its upstream branch. This mode only makes sense if you are pushing to the same repository you would normally pull from (i.e. central workflow). No need to have the same name for local and remote branch.
  • tracking : Deprecated, use upstream instead.
  • current : Push the current branch to the remote branch of the same name on the receiving end. Works in both central and non-central workflows.
  • simple : [available since Ver 1.7.11] in centralized workflow, work like upstream with an added safety to refuse to push if the upstream branch’s name is different from the local one. When pushing to a remote that is different from the remote you normally pull from, work as current. This is the safest option and is suited for beginners. This mode has become the default in Git 2.0.

WELD-001408: Unsatisfied dependencies for type Customer with qualifiers @Default

it's also a good thing to make sure you have the right import

I had an issue like that and I found out that the bean was using

    javax.faces.view.ViewScoped;
                 ^

instead of

    javax.faces.bean.ViewScoped;
                 ^

Get value of a merged cell of an excel from its cell address in vba

Even if it is really discouraged to use merge cells in Excel (use Center Across Selection for instance if needed), the cell that "contains" the value is the one on the top left (at least, that's a way to express it).

Hence, you can get the value of merged cells in range B4:B11 in several ways:

  • Range("B4").Value
  • Range("B4:B11").Cells(1).Value
  • Range("B4:B11").Cells(1,1).Value

You can also note that all the other cells have no value in them. While debugging, you can see that the value is empty.

Also note that Range("B4:B11").Value won't work (raises an execution error number 13 if you try to Debug.Print it) because it returns an array.

Android:java.lang.OutOfMemoryError: Failed to allocate a 23970828 byte allocation with 2097152 free bytes and 2MB until OOM

I got below error

"E/art: Throwing OutOfMemoryError "Failed to allocate a 47251468 byte allocation with 16777120 free bytes and 23MB until OOM"

after adding android:largeHeap="true" in AndroidManifest.xml then I rid of all the errors

<application
    android:allowBackup="true"
    android:icon="@mipmap/guruji"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:largeHeap="true"
    android:theme="@style/AppTheme">

NSCameraUsageDescription in iOS 10.0 runtime crash?

Another instance that I faced while trying to use the camera, was that it was still busy crashing giving same _CRASHING_DUE_TO_PRIVACY even after adding the "Camera Usage Description". After failing to get anything tangible from the call stack, switched to the "Organizer" and looked into the crash reports on the device. I found that it was in fact complaining about the privacy due to the missing "Microphone Usage Description". I added that and got rid of such a cryptic break down.

Pass Method as Parameter using C#

While the accepted answer is absolutely correct, I would like to provide an additional method.

I ended up here after doing my own searching for a solution to a similar question. I am building a plugin driven framework, and as part of it I wanted people to be able to add menu items to the applications menu to a generic list without exposing an actual Menu object because the framework may deploy on other platforms that don't have Menu UI objects. Adding general info about the menu is easy enough, but allowing the plugin developer enough liberty to create the callback for when the menu is clicked was proving to be a pain. Until it dawned on me that I was trying to re-invent the wheel and normal menus call and trigger the callback from events!

So the solution, as simple as it sounds once you realize it, eluded me until now.

Just create separate classes for each of your current methods, inherited from a base if you must, and just add an event handler to each.

How can I check whether Google Maps is fully loaded?

In 2018:

var map = new google.maps.Map(...)
map.addListener('tilesloaded', function () { ... })

https://developers.google.com/maps/documentation/javascript/events

Local and global temporary tables in SQL Server

1.) A local temporary table exists only for the duration of a connection or, if defined inside a compound statement, for the duration of the compound statement.

Local temp tables are only available to the SQL Server session or connection (means single user) that created the tables. These are automatically deleted when the session that created the tables has been closed. Local temporary table name is stared with single hash ("#") sign.

CREATE TABLE #LocalTemp
(
 UserID int,
 Name varchar(50), 
 Address varchar(150)
)
GO
insert into #LocalTemp values ( 1, 'Name','Address');
GO
Select * from #LocalTemp

The scope of Local temp table exist to the current session of current user means to the current query window. If you will close the current query window or open a new query window and will try to find above created temp table, it will give you the error.


2.) A global temporary table remains in the database permanently, but the rows exist only within a given connection. When connection is closed, the data in the global temporary table disappears. However, the table definition remains with the database for access when database is opened next time.

Global temp tables are available to all SQL Server sessions or connections (means all the user). These can be created by any SQL Server connection user and these are automatically deleted when all the SQL Server connections have been closed. Global temporary table name is stared with double hash ("##") sign.

CREATE TABLE ##GlobalTemp
(
 UserID int,
 Name varchar(50), 
 Address varchar(150)
)
GO
insert into ##GlobalTemp values ( 1, 'Name','Address');
GO
Select * from ##GlobalTemp

Global temporary tables are visible to all SQL Server connections while Local temporary tables are visible to only current SQL Server connection.

Parse JSON in TSQL

Update: As of SQL Server 2016 parsing JSON in TSQL is now possible.

Natively, there is no support. You'll have to use CLR. It is as simple as that, unless you have a huge masochistic streak and want to write a JSON parser in SQL

Normally, folk ask for JSON output from the DB and there are examples on the internet. But into a DB?

Convert output of MySQL query to utf8

SELECT CONVERT(CAST(column as BINARY) USING utf8) as column FROM table 

How can I use a reportviewer control in an asp.net mvc 3 razor view?

the documentations refers to an ASP.NET application.
You can try and have a look at my answer here.
I have an example attached to my reply.
Another example for ASP.NET MVC3 can be found here.

Unix's 'ls' sort by name

ls -X works for that purpose, in case you have aliased ls to a more useful default.

AngularJS - Building a dynamic table based on a json

Just want to share with what I used so far to save your time.

Here are examples of hard-coded headers and dynamic headers (in case if don't care about data structure). In both cases I wrote some simple directive: customSort

customSort

.directive("customSort", function() {
    return {
        restrict: 'A',
        transclude: true,    
        scope: {
          order: '=',
          sort: '='
        },
        template : 
          ' <a ng-click="sort_by(order)" style="color: #555555;">'+
          '    <span ng-transclude></span>'+
          '    <i ng-class="selectedCls(order)"></i>'+
          '</a>',
        link: function(scope) {

        // change sorting order
        scope.sort_by = function(newSortingOrder) {       
            var sort = scope.sort;

            if (sort.sortingOrder == newSortingOrder){
                sort.reverse = !sort.reverse;
            }                    

            sort.sortingOrder = newSortingOrder;        
        };


        scope.selectedCls = function(column) {
            if(column == scope.sort.sortingOrder){
                return ('icon-chevron-' + ((scope.sort.reverse) ? 'down' : 'up'));
            }
            else{            
                return'icon-sort' 
            } 
        };      
      }// end link
    }
    });

[1st option with static headers]

I used single ng-repeat

This is a good example in Fiddle (Notice, there is no jQuery library!)

enter image description here

           <tbody>
                <tr ng-repeat="item in pagedItems[currentPage] | orderBy:sortingOrder:reverse">
                    <td>{{item.id}}</td>
                    <td>{{item.name}}</td>
                    <td>{{item.description}}</td>
                    <td>{{item.field3}}</td>
                    <td>{{item.field4}}</td>
                    <td>{{item.field5}}</td>
                </tr>
            </tbody>

[2nd option with dynamic headers]

Demo 2: Fiddle


HTML

<table class="table table-striped table-condensed table-hover">
            <thead>
                <tr>
                   <th ng-repeat="header in table_headers"  
                     class="{{header.name}}" custom-sort order="header.name" sort="sort"
                    >{{ header.name }}

                        </th> 
                  </tr>
            </thead>
            <tfoot>
                <td colspan="6">
                    <div class="pagination pull-right">
                        <ul>
                            <li ng-class="{disabled: currentPage == 0}">
                                <a href ng-click="prevPage()">« Prev</a>
                            </li>

                            <li ng-repeat="n in range(pagedItems.length, currentPage, currentPage + gap) "
                                ng-class="{active: n == currentPage}"
                            ng-click="setPage()">
                                <a href ng-bind="n + 1">1</a>
                            </li>

                            <li ng-class="{disabled: (currentPage) == pagedItems.length - 1}">
                                <a href ng-click="nextPage()">Next »</a>
                            </li>
                        </ul>
                    </div>
                </td>
            </tfoot>
            <pre>pagedItems.length: {{pagedItems.length|json}}</pre>
            <pre>currentPage: {{currentPage|json}}</pre>
            <pre>currentPage: {{sort|json}}</pre>
            <tbody>

                <tr ng-repeat="item in pagedItems[currentPage] | orderBy:sort.sortingOrder:sort.reverse">
                     <td ng-repeat="val in item" ng-bind-html-unsafe="item[table_headers[$index].name]"></td>
                </tr>
            </tbody>
        </table>

As a side note:

The ng-bind-html-unsafe is deprecated, so I used it only for Demo (2nd example). You welcome to edit.

Keep overflow div scrolled to bottom unless user scrolls up

$('#yourDivID').animate({ scrollTop: $(document).height() }, "slow");
return false;

This will calculate the ScrollTop Position from the height of #yourDivID using the $(document).height() property so that even if dynamic contents are added to the div the scroller will always be at the bottom position. Hope this helps. But it also has a small bug even if we scroll up and leaves the mouse pointer from the scroller it will automatically come to the bottom position. If somebody could correct that also it will be nice.

Do I need to convert .CER to .CRT for Apache SSL certificates? If so, how?

CER is an X.509 certificate in binary form, DER encoded.
CRT is a binary X.509 certificate, encapsulated in text (base-64) encoding.

It is not the same encoding.

Adding Http Headers to HttpClient

Create a HttpRequestMessage, set the Method to GET, set your headers and then use SendAsync instead of GetAsync.

var client = new HttpClient();
var request = new HttpRequestMessage() {
    RequestUri = new Uri("http://www.someURI.com"),
    Method = HttpMethod.Get,
};
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain"));
var task = client.SendAsync(request)
    .ContinueWith((taskwithmsg) =>
    {
        var response = taskwithmsg.Result;

        var jsonTask = response.Content.ReadAsAsync<JsonObject>();
        jsonTask.Wait();
        var jsonObject = jsonTask.Result;
    });
task.Wait();

How to calculate the sum of the datatable column in asp.net?

If you have a ADO.Net DataTable you could do

int sum = 0;
foreach(DataRow dr in dataTable.Rows)
{
   sum += Convert.ToInt32(dr["Amount"]);
}

If you want to query the database table, you could use

Select Sum(Amount) From DataTable

jQuery using append with effects

I was in need of a similar kind of solution, wanted to add data on a wall like facebook, when posted,use prepend() to add the latest post on top, thought might be useful for others..

$("#statusupdate").submit( function () {    
          $.post(
           'ajax.php',
            $(this).serialize(),
            function(data){

                $("#box").prepend($(data).fadeIn('slow'));                  
                $("#status").val('');
            }
          );
           event.preventDefault();   
        });   

the code in ajax.php is

if (isset($_POST))
{

    $feed = $_POST['feed'];
    echo "<p id=\"result\" style=\"width:200px;height:50px;background-color:lightgray;display:none;\">$feed</p>";


}

Find the index of a char in string?

The String class exposes some methods to enable this, such as IndexOf and LastIndexOf, so that you may do this:

Dim myText = "abcde"
Dim dIndex = myText.IndexOf("d")
If (dIndex > -1) Then

End If

Disable Transaction Log

What's your problem with Tx logs? They grow? Then just set truncate on checkpoint option.

From Microsoft documentation:

In SQL Server 2000 or in SQL Server 2005, the "Simple" recovery model is equivalent to "truncate log on checkpoint" in earlier versions of SQL Server. If the transaction log is truncated every time a checkpoint is performed on the server, this prevents you from using the log for database recovery. You can only use full database backups to restore your data. Backups of the transaction log are disabled when the "Simple" recovery model is used.

How to perform Unwind segue programmatically?

Quoting text from Apple's Technical Note on Unwind Segue: To add an unwind segue that will only be triggered programmatically, control+drag from the scene's view controller icon to its exit icon, then select an unwind action for the new segue from the popup menu.

Link to Technical Note

How to access a RowDataPacket object

You can copy all enumerable own properties of an object to a new one by Object.assign(target, ...sources):

trivial_object = Object.assign({}, non_trivial_object);

so in your scenario, it should be enough to change

ret.push(i);

to

ret.push(Object.assign({}, i));

PySpark: withColumn() with two conditions and three outcomes

You'll want to use a udf as below

from pyspark.sql.types import IntegerType
from pyspark.sql.functions import udf

def func(fruit1, fruit2):
    if fruit1 == None or fruit2 == None:
        return 3
    if fruit1 == fruit2:
        return 1
    return 0

func_udf = udf(func, IntegerType())
df = df.withColumn('new_column',func_udf(df['fruit1'], df['fruit2']))

Run bash script from Windows PowerShell

You should put the script as argument for a *NIX shell you run, equivalent to the *NIXish

sh myscriptfile

Using Java 8 to convert a list of objects into a string obtained from the toString() method

Testing both approaches suggested in Shail016 and bpedroso answer (https://stackoverflow.com/a/24883180/2832140), the simple StringBuilder + append(String) within a for loop, seems to execute much faster than list.stream().map([...].

Example: This code walks through a Map<Long, List<Long>> builds a json string, using list.stream().map([...]:

if (mapSize > 0) {
    StringBuilder sb = new StringBuilder("[");

    for (Map.Entry<Long, List<Long>> entry : threadsMap.entrySet()) {

        sb.append("{\"" + entry.getKey().toString() + "\":[");
        sb.append(entry.getValue().stream().map(Object::toString).collect(Collectors.joining(",")));
    }
    sb.delete(sb.length()-2, sb.length());
    sb.append("]");
    System.out.println(sb.toString());
}

On my dev VM, junit usually takes between 0.35 and 1.2 seconds to execute the test. While, using this following code, it takes between 0.15 and 0.33 seconds:

if (mapSize > 0) {
    StringBuilder sb = new StringBuilder("[");

    for (Map.Entry<Long, List<Long>> entry : threadsMap.entrySet()) {

        sb.append("{\"" + entry.getKey().toString() + "\":[");

        for (Long tid : entry.getValue()) {
            sb.append(tid.toString() + ", ");
        }
        sb.delete(sb.length()-2, sb.length());
        sb.append("]}, ");
    }
    sb.delete(sb.length()-2, sb.length());
    sb.append("]");
    System.out.println(sb.toString());
}

phpmailer: Reply using only "Reply To" address

I have found the answer to this, and it is annoyingly/frustratingly simple! Basically the reply to addresses needed to be added before the from address as such:

$mail->addReplyTo('[email protected]', 'Reply to name');
$mail->SetFrom('[email protected]', 'Mailbox name');

Looking at the phpmailer code in more detail this is the offending line:

public function SetFrom($address, $name = '',$auto=1) {
   $address = trim($address);
   $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
   if (!self::ValidateAddress($address)) {
     $this->SetError($this->Lang('invalid_address').': '. $address);
     if ($this->exceptions) {
       throw new phpmailerException($this->Lang('invalid_address').': '.$address);
     }
     echo $this->Lang('invalid_address').': '.$address;
     return false;
   }
   $this->From = $address;
   $this->FromName = $name;
   if ($auto) {
      if (empty($this->ReplyTo)) {
         $this->AddAnAddress('ReplyTo', $address, $name);
      }
      if (empty($this->Sender)) {
         $this->Sender = $address;
      }
   }
   return true;
}

Specifically this line:

if (empty($this->ReplyTo)) {
   $this->AddAnAddress('ReplyTo', $address, $name);
}

Thanks for your help everyone!