Programs & Examples On #Shfb

Sandcastle Helpfile Builder

Convert DataFrame column type from string to datetime, dd/mm/yyyy format

If you have a mixture of formats in your date, don't forget to set infer_datetime_format=True to make life easier.

df['date'] = pd.to_datetime(df['date'], infer_datetime_format=True)

Source: pd.to_datetime

or if you want a customized approach:

def autoconvert_datetime(value):
    formats = ['%m/%d/%Y', '%m-%d-%y']  # formats to try
    result_format = '%d-%m-%Y'  # output format
    for dt_format in formats:
        try:
            dt_obj = datetime.strptime(value, dt_format)
            return dt_obj.strftime(result_format)
        except Exception as e:  # throws exception when format doesn't match
            pass
    return value  # let it be if it doesn't match

df['date'] = df['date'].apply(autoconvert_datetime)

Python - Extracting and Saving Video Frames

I am using Python via Anaconda's Spyder software. Using the original code listed in the question of this thread by @Gshocked, the code does not work (the python won't read the mp4 file). So I downloaded OpenCV 3.2 and copied "opencv_ffmpeg320.dll" and "opencv_ffmpeg320_64.dll" from the "bin" folder. I pasted both of these dll files to Anaconda's "Dlls" folder.

Anaconda also has a "pckgs" folder...I copied and pasted the entire "OpenCV 3.2" folder that I downloaded to the Anaconda "pckgs" folder.

Finally, Anaconda has a "Library" folder which has a "bin" subfolder. I pasted the "opencv_ffmpeg320.dll" and "opencv_ffmpeg320_64.dll" files to that folder.

After closing and restarting Spyder, the code worked. I'm not sure which of the three methods worked, and I'm too lazy to go back and figure it out. But it works so, cheers!

HttpServletRequest get JSON POST data

Normaly you can GET and POST parameters in a servlet the same way:

request.getParameter("cmd");

But only if the POST data is encoded as key-value pairs of content type: "application/x-www-form-urlencoded" like when you use a standard HTML form.

If you use a different encoding schema for your post data, as in your case when you post a json data stream, you need to use a custom decoder that can process the raw datastream from:

BufferedReader reader = request.getReader();

Json post processing example (uses org.json package )

public void doPost(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {

  StringBuffer jb = new StringBuffer();
  String line = null;
  try {
    BufferedReader reader = request.getReader();
    while ((line = reader.readLine()) != null)
      jb.append(line);
  } catch (Exception e) { /*report an error*/ }

  try {
    JSONObject jsonObject =  HTTP.toJSONObject(jb.toString());
  } catch (JSONException e) {
    // crash and burn
    throw new IOException("Error parsing JSON request string");
  }

  // Work with the data using methods like...
  // int someInt = jsonObject.getInt("intParamName");
  // String someString = jsonObject.getString("stringParamName");
  // JSONObject nestedObj = jsonObject.getJSONObject("nestedObjName");
  // JSONArray arr = jsonObject.getJSONArray("arrayParamName");
  // etc...
}

Where does MySQL store database files on Windows and what are the names of the files?

MYSQL 8.0:

Search my.ini in disk, we will find this folder:

C:\ProgramData\MySQL\MySQL Server 8.0
It's ProgramData, not Program file

Data is in sub-folder: \Data.

Each database owns a folder, each table is file, each index is 1+ files.

Here is a sample database sakila: enter image description here

Get device information (such as product, model) from adb command

Why don't you try to grep the return of your command ? Something like :

adb devices -l | grep 123abc12

It should return only the line you want to.

Catching "Maximum request length exceeded"

There is no easy way to catch such exception unfortunately. What I do is either override the OnError method at the page level or the Application_Error in global.asax, then check if it was a Max Request failure and, if so, transfer to an error page.

protected override void OnError(EventArgs e) .....


private void Application_Error(object sender, EventArgs e)
{
    if (GlobalHelper.IsMaxRequestExceededException(this.Server.GetLastError()))
    {
        this.Server.ClearError();
        this.Server.Transfer("~/error/UploadTooLarge.aspx");
    }
}

It's a hack but the code below works for me

const int TimedOutExceptionCode = -2147467259;
public static bool IsMaxRequestExceededException(Exception e)
{
    // unhandled errors = caught at global.ascx level
    // http exception = caught at page level

    Exception main;
    var unhandled = e as HttpUnhandledException;

    if (unhandled != null && unhandled.ErrorCode == TimedOutExceptionCode)
    {
        main = unhandled.InnerException;
    }
    else
    {
        main = e;
    }


    var http = main as HttpException;

    if (http != null && http.ErrorCode == TimedOutExceptionCode)
    {
        // hack: no real method of identifying if the error is max request exceeded as 
        // it is treated as a timeout exception
        if (http.StackTrace.Contains("GetEntireRawContent"))
        {
            // MAX REQUEST HAS BEEN EXCEEDED
            return true;
        }
    }

    return false;
}

How to select specific columns in laravel eloquent

If you want to get single row and from the that row single column, one line code to get the value of the specific column is to use find() method alongside specifying of the column that you want to retrieve it.

Here is sample code:

ModelName::find($id_of_the_record, ['column_name'])->toArray()['column_name'];

Facebook login message: "URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Settings."

For my Node Application,

"facebook": {
        "clientID" : "##############",
        "clientSecret": "####################",
        "callbackURL": "/auth/facebook/callback/"
    }

put callback Url relative

My OAuth redirect URIs as follows

enter image description here

Make Sure "/" at the end of Facebook auth redirect URI

These setups worked for me.

Elegant Python function to convert CamelCase to snake_case?

So many complicated methods... Just find all "Titled" group and join its lower cased variant with underscore.

>>> import re
>>> def camel_to_snake(string):
...     groups = re.findall('([A-z0-9][a-z]*)', string)
...     return '_'.join([i.lower() for i in groups])
...
>>> camel_to_snake('ABCPingPongByTheWay2KWhereIsOurBorderlands3???')
'a_b_c_ping_pong_by_the_way_2_k_where_is_our_borderlands_3'

If you don't want make numbers like first character of group or separate group - you can use ([A-z][a-z0-9]*) mask.

How do you delete an ActiveRecord object?

It's destroy and destroy_all methods, like

user.destroy
User.find(15).destroy
User.destroy(15)
User.where(age: 20).destroy_all
User.destroy_all(age: 20)

Alternatively you can use delete and delete_all which won't enforce :before_destroy and :after_destroy callbacks or any dependent association options.

User.delete_all(condition: 'value') will allow you to delete records without a primary key

Note: from @hammady's comment, user.destroy won't work if User model has no primary key.

Note 2: From @pavel-chuchuva's comment, destroy_all with conditions and delete_all with conditions has been deprecated in Rails 5.1 - see guides.rubyonrails.org/5_1_release_notes.html

How to Query Database Name in Oracle SQL Developer?

Once I realized I was running an Oracle database, not MySQL, I found the answer

select * from v$database;

or

select ora_database_name from dual;

Try both. Credit and source goes to: http://www.perlmonks.org/?node_id=520376.

Unicode character in PHP string

html_entity_decode('エ', 0, 'UTF-8');

This works too. However the json_decode() solution is a lot faster (around 50 times).

How to access local files of the filesystem in the Android emulator?

You can use the adb command which comes in the tools dir of the SDK:

adb shell

It will give you a command line prompt where you can browse and access the filesystem. Or you can extract the files you want:

adb pull /sdcard/the_file_you_want.txt

Also, if you use eclipse with the ADT, there's a view to browse the file system (Window->Show View->Other... and choose Android->File Explorer)

Build Android Studio app via command line

Android Studio automatically creates a Gradle wrapper in the root of your project, which is how it invokes Gradle. The wrapper is basically a script that calls through to the actual Gradle binary and allows you to keep Gradle up to date, which makes using version control easier. To run a Gradle command, you can simply use the gradlew script found in the root of your project (or gradlew.bat on Windows) followed by the name of the task you want to run. For instance, to build a debug version of your Android application, you can run ./gradlew assembleDebug from the root of your repository. In a default project setup, the resulting apk can then be found in app/build/outputs/apk/app-debug.apk. On a *nix machine, you can also just run find . -name '*.apk' to find it, if it's not there.

How to return part of string before a certain character?

Another method could be to split the string by ":" and then pop off the end. var newString = string.split(":").pop();

How to download an entire directory and subdirectories using wget?

This will help

wget -m -np -c --level 0 --no-check-certificate -R"index.html*"http://www.your-websitepage.com/dir

How can I use an http proxy with node.js http.Client?

One thing that took me a while to figure out, use 'http' to access the proxy, even if you're trying to proxy through to a https server. This works for me using Charles (osx protocol analyser):

var http = require('http');

http.get ({
    host: '127.0.0.1',
    port: 8888,
    path: 'https://www.google.com/accounts/OAuthGetRequestToken'
}, function (response) {
    console.log (response);
});

Check key exist in python dict

Use the in keyword.

if 'apples' in d:
    if d['apples'] == 20:
        print('20 apples')
    else:
        print('Not 20 apples')

If you want to get the value only if the key exists (and avoid an exception trying to get it if it doesn't), then you can use the get function from a dictionary, passing an optional default value as the second argument (if you don't pass it it returns None instead):

if d.get('apples', 0) == 20:
    print('20 apples.')
else:
    print('Not 20 apples.')

How can I check whether a numpy array is empty or not?

Why would we want to check if an array is empty? Arrays don't grow or shrink in the same that lists do. Starting with a 'empty' array, and growing with np.append is a frequent novice error.

Using a list in if alist: hinges on its boolean value:

In [102]: bool([])                                                                       
Out[102]: False
In [103]: bool([1])                                                                      
Out[103]: True

But trying to do the same with an array produces (in version 1.18):

In [104]: bool(np.array([]))                                                             
/usr/local/bin/ipython3:1: DeprecationWarning: The truth value 
   of an empty array is ambiguous. Returning False, but in 
   future this will result in an error. Use `array.size > 0` to 
   check that an array is not empty.
  #!/usr/bin/python3
Out[104]: False

In [105]: bool(np.array([1]))                                                            
Out[105]: True

and bool(np.array([1,2]) produces the infamous ambiguity error.

edit

The accepted answer suggests size:

In [11]: x = np.array([])
In [12]: x.size
Out[12]: 0

But I (and most others) check the shape more than the size:

In [13]: x.shape
Out[13]: (0,)

Another thing in its favor is that it 'maps' on to an empty list:

In [14]: x.tolist()
Out[14]: []

But there are other other arrays with 0 size, that aren't 'empty' in that last sense:

In [15]: x = np.array([[]])
In [16]: x.size
Out[16]: 0
In [17]: x.shape
Out[17]: (1, 0)
In [18]: x.tolist()
Out[18]: [[]]
In [19]: bool(x.tolist())
Out[19]: True

np.array([[],[]]) is also size 0, but shape (2,0) and len 2.

While the concept of an empty list is well defined, an empty array is not well defined. One empty list is equal to another. The same can't be said for a size 0 array.

The answer really depends on

  • what do you mean by 'empty'?
  • what are you really test for?

RegEx to make sure that the string contains at least one lower case char, upper case char, digit and symbol

If you need one single regex, try:

(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*\W)

A short explanation:

(?=.*[a-z])        // use positive look ahead to see if at least one lower case letter exists
(?=.*[A-Z])        // use positive look ahead to see if at least one upper case letter exists
(?=.*\d)           // use positive look ahead to see if at least one digit exists
(?=.*\W])        // use positive look ahead to see if at least one non-word character exists

And I agree with SilentGhost, \W might be a bit broad. I'd replace it with a character set like this: [-+_!@#$%^&*.,?] (feel free to add more of course!)

tkinter: how to use after method

I believe, the 500ms run in the background, while the rest of the code continues to execute and empties the list.

Then after 500ms nothing happens, as no function-call is implemented in the after-callup (same as frame.after(500, function=None))

How to create an AVD for Android 4.0

I had a similar problem but using IntelliJ IDEA rather than Eclipse. I already had the ARM EABI installed, but I still got the error.

For IntelliJ IDEA, it appears you also have to create an AVB first before running the emulator, so to do this you must just go into Android SDK Manager and create a new AVB. This should solve your problem... Please make sure you have followed the above answer to include the ARM before following these steps.

How to always show the vertical scrollbar in a browser?

Just a note: In OS X Lion, overflow set to "scroll" behaves more like auto in that scrollbars will only show when being used. They will disappear when not in use. So if any the solutions above don't appear to be working that might be why.

This is what you'll need to fix it:

::-webkit-scrollbar {
  -webkit-appearance: none;
  width: 7px;
}
::-webkit-scrollbar-thumb {
  border-radius: 4px;
  background-color: rgba(0, 0, 0, .5);
  -webkit-box-shadow: 0 0 1px rgba(255, 255, 255, .5);
}

You can style it accordingly.

Convert HttpPostedFileBase to byte[]

As Darin says, you can read from the input stream - but I'd avoid relying on all the data being available in a single go. If you're using .NET 4 this is simple:

MemoryStream target = new MemoryStream();
model.File.InputStream.CopyTo(target);
byte[] data = target.ToArray();

It's easy enough to write the equivalent of CopyTo in .NET 3.5 if you want. The important part is that you read from HttpPostedFileBase.InputStream.

For efficient purposes you could check whether the stream returned is already a MemoryStream:

byte[] data;
using (Stream inputStream = model.File.InputStream)
{
    MemoryStream memoryStream = inputStream as MemoryStream;
    if (memoryStream == null)
    {
        memoryStream = new MemoryStream();
        inputStream.CopyTo(memoryStream);
    }
    data = memoryStream.ToArray();
}

Find out a Git branch creator

Adding to DarVar's answer:

git for-each-ref --format='%(committerdate) %09 %(authorname) %09 %(refname)' | sort -k5n -k2M -k3n -k4n | awk '{print $7 $8}'

P.S.: We used AWK to pretty print the author and the remote branch.

Converting a string to a date in DB2

You can use:

select VARCHAR_FORMAT(creationdate, 'MM/DD/YYYY') from table name

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

The reason to make an App with no activity or service could be making a Homescreen Widget app that doesn't need to be started.
Once you start a project don't create any activities. After you created the project just hit run. Android studio will say No default activity found.

Click Edit Configuration (From the Run menu) and in the Launch option part set the Launch value to Nothing. Then click ok and run the App.

(Since there is no launcher activity, No app will be show in the Apps menu.).

Android sqlite how to check if a record exists

Here's a simple solution based on a combination of what dipali and Piyush Gupta posted:

  public boolean dbHasData(String searchTable, String searchColumn, String searchKey) {
    String query = "Select * from " + searchTable + " where " + searchColumn + " = ?";
    return getReadableDatabase().rawQuery(query, new String[]{searchKey}).moveToFirst();
  }

Adding backslashes without escaping [Python]

The result '\\&' is only displayed - actually the string is \&:

>>> str = '&'
>>> new_str = str.replace('&', '\&')
>>> new_str
'\\&'
>>> print new_str
\&

Try it in a shell.

convert a char* to std::string

Pass it in through the constructor:

const char* dat = "my string!";
std::string my_string( dat );

You can use the function string.c_str() to go the other way:

std::string my_string("testing!");
const char* dat = my_string.c_str();

Is String.Contains() faster than String.IndexOf()?

I am running a real case (in opposite to a synthetic benchmark)

 if("=,<=,=>,<>,<,>,!=,==,".IndexOf(tmps)>=0) {

versus

 if("=,<=,=>,<>,<,>,!=,==,".Contains(tmps)) {

It is a vital part of my system and it is executed 131,953 times (thanks DotTrace).

However shocking surprise, the result is the opposite that expected

  • IndexOf 533ms.
  • Contains 266ms.

:-/

net framework 4.0 (updated as for 13-02-2012)

Gradle - Could not target platform: 'Java SE 8' using tool chain: 'JDK 7 (1.7)'

I had a very related issue but for higher Java versions:

$ ./gradlew clean assemble

... <other normal Gradle output>

Could not target platform: 'Java SE 11' using tool chain: 'JDK 8 (1.8)'.

I noticed that the task succeeded when running using InteliJ. Adding a file (same level as build.gradle) called .java-version solved my issue:

 # .java-version
 11.0.3

What is the SQL command to return the field names of a table?

If you just want the column names, then

select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'tablename'

On MS SQL Server, for more information on the table such as the types of the columns, use

sp_help 'tablename'

Pip freeze vs. pip list

The main difference is that the output of pip freeze can be dumped into a requirements.txt file and used later to re-construct the "frozen" environment.

In other words you can run: pip freeze > frozen-requirements.txt on one machine and then later on a different machine or on a clean environment you can do: pip install -r frozen-requirements.txt and you'll get the an identical environment with the exact same dependencies installed as you had in the original environment where you generated the frozen-requirements.txt.

What is the difference between JDK and JRE?

In layman terms: JDK is grandfather JRE is father and JVM is their son. [i.e. JDK > JRE > JVM ]

JDK = JRE + Development/debugging tools

JRE = JVM + Java Packages Classes(like util, math, lang, awt,swing etc)+runtime libraries.

JVM = Class loader system + runtime data area + Execution Engine.

In other words if you are a Java programmer you will need JDK in your system and this package will include JRE and JVM as well but if you are normal user who like to play online games then you will only need JRE and this package will not have JDK in it.

JVM :

The Java Virtual Machine (JVM) is the virtual machine that run the Java bytecodes. The JVM doesn't understand Java source code, that's why you compile your *.java files to obtain *.class files that contain the bytecodes understandable by the JVM. It's also the entity that allows Java to be a "portable language" (write once, run anywhere). Indeed there are specific implementations of the JVM for different systems (Windows, Linux, MacOS, see the wikipedia list..), the aim is that with the same bytecodes they all give the same results.

JDK and JRE

To explain the difference between JDK and JRE, the best is to read the Oracle documentation and consult the diagram :

Java Runtime Environment (JRE)

The Java Runtime Environment (JRE) provides the libraries, the Java Virtual Machine, and other components to run applets and applications written in the Java programming language. In addition, two key deployment technologies are part of the JRE: Java Plug-in, which enables applets to run in popular browsers; and Java Web Start, which deploys standalone applications over a network. It is also the foundation for the technologies in the Java 2 Platform, Enterprise Edition (J2EE) for enterprise software development and deployment. The JRE does not contain tools and utilities such as compilers or debuggers for developing applets and applications.

Java Development Kit (JDK)

The JDK is a superset of the JRE, and contains everything that is in the JRE, plus tools such as the compilers and debuggers necessary for developing applets and applications.

Note that Oracle is not the only one to provide JDK.

JIT Compile Process (Courtesy: Oracle documentation)

JDK > JRE > JVM

Removing an element from an Array (Java)

okay, thx a lot now i use sth like this:

public static String[] removeElements(String[] input, String deleteMe) {
    if (input != null) {
        List<String> list = new ArrayList<String>(Arrays.asList(input));
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).equals(deleteMe)) {
                list.remove(i);
            }
        }
        return list.toArray(new String[0]);
    } else {
        return new String[0];
    }
}

Wrap a text within only two lines inside div

CSS only

    line-height: 1.5;
    white-space: normal;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;

How to pass a URI to an intent?

here how I use it; This button inside my CameraActionActivity Activity class where I call camera

 btn_frag_camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intenImatToSec = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
                startActivityForResult(intenImatToSec, REQUEST_CODE_VIDEO);
                //intenImatToSec.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
                //intenImatToSec.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 10);
                //Toast.makeText(getActivity(), "Hello From Camera", Toast.LENGTH_SHORT).show();
            }
        });



@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {

            if (requestCode == REQUEST_CODE_IMG) {
                Bundle bundle = data.getExtras();
                Bitmap bitmap = (Bitmap) bundle.get("data");
                Intent intentBitMap = new Intent(getActivity(), DisplayImage.class);
                // aldigimiz imagi burda yonlendirdigimiz sinifa iletiyoruz
                ByteArrayOutputStream _bs = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG, 50, _bs);
                intentBitMap.putExtra("byteArray", _bs.toByteArray());
                startActivity(intentBitMap);

            } else if (requestCode == REQUEST_CODE_VIDEO) {
                Uri videoUrl = data.getData();
                Intent intenToDisplayVideo = new Intent(getActivity(), DisplayVideo.class);
                intenToDisplayVideo.putExtra("videoUri", videoUrl.toString());
                startActivity(intenToDisplayVideo);
            }
        }
    }

And my other DisplayVideo Activity Class

VideoView videoView = (VideoView) findViewById(R.id.videoview_display_video_actvity);
Bundle extras = getIntent().getExtras();
        Uri myUri=  Uri.parse(extras.getString("videoUri"));
        videoView.setVideoURI(myUri);

What's the difference between eval, exec, and compile?

exec is for statement and does not return anything. eval is for expression and returns value of expression.

expression means "something" while statement means "do something".

Easy login script without database

***LOGIN script that doesnt link to a database or external file. Good for a global password -

Place on Login form page - place this at the top of the login page - above everything else***

<?php

if(isset($_POST['Login'])){

if(strtolower($_POST["username"])=="ChangeThis" && $_POST["password"]=="ChangeThis"){
session_start();
$_SESSION['logged_in'] = TRUE;
header("Location: ./YourPageAfterLogin.php");

}else {
$error= "Login failed !";
}
}
//print"version3<br>";
//print"username=".$_POST["username"]."<br>";
//print"password=".$_POST["username"];
?>

*Login on following pages - Place this at the top of every page that needs to be protected by login. this checks the session and if a user name and password has *

<?php
session_start();
if(!isset($_SESSION['logged_in']) OR $_SESSION['logged_in'] != TRUE){

header("Location: ./YourLoginPage.php");
}
?>

IIS7 folder permissions for web application

Running IIS 7.5, I had luck adding permissions for the local computer user IUSR. The app pool user didn't work.

How to install toolbox for MATLAB

first, you need to find the toolbox that you need. There are many people developing 3rd party toolboxes for Matlab, so there isn't just one single place where you can find "the image processing toolbox". That said, a good place to start looking is the Matlab Central which is a Mathworks-run site for exchanging all kinds of Matlab-related material.

Once you find a toolbox you want, it will be in some compressed format, and its developers might have a "readme" file that details on how to install it. If it isn't the case, a generic way to attempt installation is to place the toolbox in any directory on your drive, and then add it to Matlab path, e.g., going to File -> Set Path... -> Add Folder or Add with Subfolders (I'm writing for memory but this is definitely close).

Otherwise, you can extract all .m files in your working directory, if you don't want to use downloaded toolbox in more than one project.

How to rename JSON key

By using map function you can do that. Please refer below code.

var userDetails = [{
  "_id":"5078c3a803ff4197dc81fbfb",
  "email":"[email protected]",
  "image":"some_image_url",
  "name":"Name 1"
},{
  "_id":"5078c3a803ff4197dc81fbfc",
  "email":"[email protected]",
  "image":"some_image_url",
  "name":"Name 2"
}];

var formattedUserDetails = userDetails.map(({ _id:id, email, image, name }) => ({
  id,
  email,
  image,
  name
}));
console.log(formattedUserDetails);

Update Jenkins from a war file

You can overwrite the existing jenkins.war file with the new one and then restart Jenkins.

This file is usually located in /usr/share/jenkins.

If this is not the case for your system, in Manage Jenkins -> System Information, it will display the path to the .war file under executable-war.

How do I get LaTeX to hyphenate a word that contains a dash?

I had the same problem. I use hyphenat plus the following macro:

\RequirePackage{hyphenat}
\RequirePackage{expl3}


% The following defs make sure words that contain an explicit `-` (hyphen) are still hyphenated the normal way, and double- and triple hyphens keep working the way they should. Just don't use a `-` as the last token of your document. Also note that `-` is now a macro that is not fully expandable

\ExplSyntaxOn

% latex2e doesn't like commands starting with 'end', apparently expl3 doesn't have any problems with it
\cs_new:Npn \hyphenfix_emdash:c {---}
\cs_new:Npn \hyphenfix_endash:c {--}

\cs_new:Npn \hyphenfix_discardnext:NN #1#2{#1}


\catcode`\-=\active

\cs_new_protected:Npn -{
    \futurelet\hyphenfix_nexttok\hyphenfix_i:w
}

\cs_new:Npn \hyphenfix_i:w {
    \cs_if_eq:NNTF{\hyphenfix_nexttok}{-}{
        %discard the next `-` token
        \hyphenfix_discardnext:NN{\futurelet\hyphenfix_nexttok\hyphenfix_ii:w}
    }{
        % from package hyphenat
        \hyp
    }
}

\cs_new:Npn \hyphenfix_ii:w {
    \cs_if_eq:NNTF{\hyphenfix_nexttok}{-}{
        \hyphenfix_discardnext:NN{\hyphenfix_emdash:c}
    }{
        \hyphenfix_endash:c
    }
}


\ExplSyntaxOff

Note that this uses the expl3 package from latex3.

It makes the - an active character that scans forward to see if it is followed by more dashes. If so, it stays a -, to make sure -- and --- keep working. If not, it becomes the \hyp command from hyphenat, enabling word breaks in the rest of the word. This is a generic solution that makes all words that contain explicit hyphens hyphenate normally.

Note that - becomes a macro that is not fully expandable, so try to include this after loading other packages that may not expect - to be a macro

Edit: This is my second version, the first version was less robust when a { or } followed a hyphen. This one is not, but unlike the first version the - in this version is not fully expandable.

What's the difference between "2*2" and "2**2" in Python?

Power has more precedence than multiply, so:

2**2*3 = (2^2)*3
2*2*3 = 2*2*3

Android Percentage Layout Height

You could add another empty layout below that one and set them both to have the same layout weight. They should get 50% of the space each.

What is content-type and datatype in an AJAX request?

See http://api.jquery.com/jQuery.ajax/, there's mention of datatype and contentType there.

They are both used in the request to the server so the server knows what kind of data to receive/send.

How do I obtain the frequencies of each value in an FFT?

Take a look at my answer here.

Answer to comment:

The FFT actually calculates the cross-correlation of the input signal with sine and cosine functions (basis functions) at a range of equally spaced frequencies. For a given FFT output, there is a corresponding frequency (F) as given by the answer I posted. The real part of the output sample is the cross-correlation of the input signal with cos(2*pi*F*t) and the imaginary part is the cross-correlation of the input signal with sin(2*pi*F*t). The reason the input signal is correlated with sin and cos functions is to account for phase differences between the input signal and basis functions.

By taking the magnitude of the complex FFT output, you get a measure of how well the input signal correlates with sinusoids at a set of frequencies regardless of the input signal phase. If you are just analyzing frequency content of a signal, you will almost always take the magnitude or magnitude squared of the complex output of the FFT.

How to output JavaScript with PHP

<?php

echo '<script type="text/javascript">document.write(\'Hello world\');</script>';
?>

How to get the mobile number of current sim card in real device?

Sometimes you can retreive the phonenumber with a USSD request to your operator. For example I can get my phonenumber by dialing *116# This can probably be done within an app, I guess, if the USSD responce somehow could be catched. Offcourse this is not a method I would recommend to use within an app that is to be distributed, the code may even differ between operators.

Registry key Error: Java version has value '1.8', but '1.7' is required

The error is explicit ...

Error: Registry key 'Software\JavaSoft\Java Runtime Environment'\CurrentVersion' has value '1.8', but '1.7' is required.

Error: could not find java.dll

Error: Could not find Java SE Runtime Environment.

... you are attempting to use the java.exe 1.7 executable while the HKEY_LOCAL_MACHINE\Software\JavaSoft\Java Runtime Environment > CurrentVersion registry key has the value 1.8.

The recurring theme to proposed solutions is that the error is a configuration error. The error can be solved in various different manners (e.g. reconfiguration of the users environment or removal of java executables with fingers-crossed and hope that there exists another fallback java.exe in the users %PATH% and that the fallback java.exe is the correct executable).

The correct solution depends on what you're trying to achieve: "are you trying to downgrade from jdk-8 to jdk-7? Are trying to upgrade to jdk-8? ..."

Reproduction steps

  1. install jdk-7u80-windows-x64.exe

notes:

  • the java.exe executable available in the users %PATH% is installed in C:\Windows\System32
  • the installation does not update the users %PATH%
  • the HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment > CurrentVersion string registry entry is created (among others) with the value 1.7
  1. install jdk-8u191-windows-x64.exe

notes:

  • the users %PATH% is updated to include C:\Program Files (x86)\Common Files\Oracle\Java\javapath as the first entry
  • the the HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment > CurrentVersion string registry entries value is updated to 1.8
  1. update the users %PATH% environment variable, remove C:\Program Files (x86)\Common Files\Oracle\Java\javapath

  2. in a new command prompt java -version

Error: Registry key 'Software\JavaSoft\Java Runtime Environment'\CurrentVersion' has value '1.8', but '1.7' is required.

Error: could not find java.dll

Error: Could not find Java SE Runtime Environment.

Solution(s)

  1. OP's solution https://stackoverflow.com/a/29769311/1423507 is a "fingers-crossed and hope that there exists a fallback java.exe in the users %PATH% and that the fallback executable is correct" approach to the error. Given the reproduction steps, removing the java.exe, javaw.exe and javaws.exe executables from C:\Windows\System32 (only in my case) will result in no longer having any java.exe present in the users %PATH% resulting in the error 'java' is not recognized as an internal or external command, operable program or batch file. which is not so much of a solution.

  2. answers https://stackoverflow.com/a/35775493/1423507 and https://stackoverflow.com/a/36516620/1423507 work however you're reverting to using java.exe 1.7 (e.g. update the CurrentVersion registry key's value to match the java.exe version found in the users %PATH%).

  3. make surejava.exe 1.8 is the first found in the users %PATH% (how you do that is irrelevant) i.e.:

    • update the users %PATH% to include C:\Program Files (x86)\Common Files\Oracle\Java\javapath first (ensure that the executables in that directory are correct)
    • update the users %PATH% to include the absolute path of your java binaries first (set PATH="C:\Program Files\Java\jre1.8.0_191\bin;%PATH%")
    • set java specific environment variables and update the users %PATH% with them (set JAVA_HOME="C:\Program Files\Java"; set JRE_HOME=%JAVA_HOME%\jre1.8.0_191; set PATH=%JRE_HOME%\bin;%PATH%)

How do I access (read, write) Google Sheets spreadsheets with Python?

I know this thread is old now, but here is some decent documentation on Google Docs API. It was ridiculously hard to find, but useful, so maybe it will help you some. http://pythonhosted.org/gdata/docs/api.html.

I used gspread recently for a project to graph employee time data. I don't know how much it might help you, but here's a link to the code: https://github.com/lightcastle/employee-timecards

Gspread made things pretty easy for me. I was also able to add logic in to check for various conditions to create month-to-date and year-to-date results. But I just imported the whole dang spreadsheet and parsed it from there, so I'm not 100% sure that it is exactly what you're looking for. Best of luck.

How can I convert a string to a float in mysql?

This will convert to a numeric value without the need to cast or specify length or digits:

STRING_COL+0.0

If your column is an INT, can leave off the .0 to avoid decimals:

STRING_COL+0

Laravel Eloquent - Get one Row

You can also use this

$user = User::whereEmail($email)->first();

How to create a new file in unix?

Try > workdirectory/filename.txt

This would:

  • truncate the file if it exists
  • create if it doesn't exist

You can consider it equivalent to:

rm -f workdirectory/filename.txt; touch workdirectory/filename.txt

javascript popup alert on link click

You can use the onclick attribute, just return false if you don't want continue;

<script type="text/javascript">
function confirm_alert(node) {
    return confirm("Please click on OK to continue.");
}
</script>
<a href="http://www.google.com" onclick="return confirm_alert(this);">Click Me</a>

Can you pass parameters to an AngularJS controller on creation?

This also works.

Javascript:

var app = angular.module('angularApp', []);

app.controller('MainCtrl', function($scope, name, id) {
    $scope.id = id;
    $scope.name = name;
    // and more init
});

Html:

<!DOCTYPE html>
<html ng-app="angularApp">
  <head lang="en">
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script>
    <script src="app.js"></script>
    <script>
       app.value("name", "James").value("id", "007");
    </script>
  </head>
  <body ng-controller="MainCtrl">
    <h1>I am  {{name}} {{id}}</h1>
  </body>
</html>

C# Threading - How to start and stop a thread

Use a static AutoResetEvent in your spawned threads to call back to the main thread using the Set() method. This guy has a fairly good demo in SO on how to use it.

AutoResetEvent clarification

Programmatically find the number of cores on a machine

Note that "number of cores" might not be a particularly useful number, you might have to qualify it a bit more. How do you want to count multi-threaded CPUs such as Intel HT, IBM Power5 and Power6, and most famously, Sun's Niagara/UltraSparc T1 and T2? Or even more interesting, the MIPS 1004k with its two levels of hardware threading (supervisor AND user-level)... Not to mention what happens when you move into hypervisor-supported systems where the hardware might have tens of CPUs but your particular OS only sees a few.

The best you can hope for is to tell the number of logical processing units that you have in your local OS partition. Forget about seeing the true machine unless you are a hypervisor. The only exception to this rule today is in x86 land, but the end of non-virtual machines is coming fast...

Capturing count from an SQL query

SqlConnection conn = new SqlConnection("ConnectionString");
conn.Open();
SqlCommand comm = new SqlCommand("SELECT COUNT(*) FROM table_name", conn);
Int32 count = (Int32) comm .ExecuteScalar();

Convert dictionary values into array

If you would like to use linq, so you can try following:

Dictionary<string, object> dict = new Dictionary<string, object>();
var arr = dict.Select(z => z.Value).ToArray();

I don't know which one is faster or better. Both work for me.

Python Database connection Close

You can define a DB class as below. Also, as andrewf suggested, use a context manager for cursor access.I'd define it as a member function. This way it keeps the connection open across multiple transactions from the app code and saves unnecessary reconnections to the server.

import pyodbc

class MS_DB():
    """ Collection of helper methods to query the MS SQL Server database.
    """

    def __init__(self, username, password, host, port=1433, initial_db='dev_db'):
        self.username = username
        self._password = password
        self.host = host
        self.port = str(port)
        self.db = initial_db
        conn_str = 'DRIVER=DRIVER=ODBC Driver 13 for SQL Server;SERVER='+ \
                    self.host + ';PORT='+ self.port +';DATABASE='+ \
                    self.db +';UID='+ self.username +';PWD='+ \ 
                    self._password +';'
        print('Connected to DB:', conn_str)
        self._connection = pyodbc.connect(conn_str)        
        pyodbc.pooling = False

    def __repr__(self):
        return f"MS-SQLServer('{self.username}', <password hidden>, '{self.host}', '{self.port}', '{self.db}')"

    def __str__(self):
        return f"MS-SQLServer Module for STP on {self.host}"

    def __del__(self):
        self._connection.close()
        print("Connection closed.")

    @contextmanager
    def cursor(self, commit: bool = False):
        """
        A context manager style of using a DB cursor for database operations. 
        This function should be used for any database queries or operations that 
        need to be done. 

        :param commit:
        A boolean value that says whether to commit any database changes to the database. Defaults to False.
        :type commit: bool
        """
        cursor = self._connection.cursor()
        try:
            yield cursor
        except pyodbc.DatabaseError as err:
            print("DatabaseError {} ".format(err))
            cursor.rollback()
            raise err
        else:
            if commit:
                cursor.commit()
        finally:
            cursor.close()

ms_db = MS_DB(username='my_user', password='my_secret', host='hostname')
with ms_db.cursor() as cursor:
        cursor.execute("SELECT @@version;")
        print(cur.fetchall())

Add day(s) to a Date object

Note : Use it if calculating / adding days from current date.

Be aware: this answer has issues (see comments)

var myDate = new Date();
myDate.setDate(myDate.getDate() + AddDaysHere);

It should be like

var newDate = new Date(date.setTime( date.getTime() + days * 86400000 ));

"Post Image data using POSTMAN"

Follow the below steps:

  1. No need to give any type of header.
  2. Select body > form-data and do same as shown in the image. 1

  3. Now in your Django view.py

def post(self, request, *args, **kwargs):
    image = request.FILES["image"]
    data = json.loads(request.data['data'])
    ...
    return Response(...)
  1. You can access all the keys (id, uid etc..) from the data variable.

check if a file is open in Python

if myfile.closed == False:
   print("File is still open ################")

How to handle anchor hash linking in AngularJS

This may be a new attribute for ngView, but I've been able to get it anchor hash links to work with angular-route using the ngView autoscroll attribute and 'double-hashes'.

ngView (see autoscroll)

(The following code was used with angular-strap)

<!-- use the autoscroll attribute to scroll to hash on $viewContentLoaded -->    
<div ng-view="" autoscroll></div>

<!-- A.href link for bs-scrollspy from angular-strap -->
<!-- A.ngHref for autoscroll on current route without a location change -->
<ul class="nav bs-sidenav">
  <li data-target="#main-html5"><a href="#main-html5" ng-href="##main-html5">HTML5</a></li>
  <li data-target="#main-angular"><a href="#main-angular" ng-href="##main-angular" >Angular</a></li>
  <li data-target="#main-karma"><a href="#main-karma" ng-href="##main-karma">Karma</a></li>
</ul>

How to find good looking font color if background color is known?

If you need an algorithm, try this: Convert the color from RGB space to HSV space (Hue, Saturation, Value). If your UI framework can't do it, check this article: http://en.wikipedia.org/wiki/HSL_and_HSV#Conversion_from_RGB_to_HSL_or_HSV

Hue is in [0,360). To find the "opposite" color (think colorwheel), just add 180 degrees:

h = (h + 180) % 360;

For saturation and value, invert them:

l = 1.0 - l;
v = 1.0 - v;

Convert back to RGB. This should always give you a high contrast even though most combinations will look ugly.

If you want to avoid the "ugly" part, build a table with several "good" combinations, find the one with the least difference

def q(x):
    return x*x
def diff(col1, col2):
    return math.sqrt(q(col1.r-col2.r) + q(col1.g-col2.g) + q(col1.b-col2.b))

and use that.

Is there a Boolean data type in Microsoft SQL Server like there is in MySQL?

There is boolean data type in SQL Server. Its values can be TRUE, FALSE or UNKNOWN. However, the boolean data type is only the result of a boolean expression containing some combination of comparison operators (e.g. =, <>, <, >=) or logical operators (e.g. AND, OR, IN, EXISTS). Boolean expressions are only allowed in a handful of places including the WHERE clause, HAVING clause, the WHEN clause of a CASE expression or the predicate of an IF or WHILE flow control statement.

For all other usages, including the data type of a column in a table, boolean is not allowed. For those other usages, the BIT data type is preferred. It behaves like a narrowed-down INTEGER which allows only the values 0, 1 and NULL, unless further restricted with a NOT NULL column constraint or a CHECK constraint.

To use a BIT column in a boolean expression it needs to be compared using a comparison operator such as =, <> or IS NULL. e.g.

SELECT
    a.answer_body
FROM answers AS a
WHERE a.is_accepted = 0;

From a formatting perspective, a bit value is typically displayed as 0 or 1 in client software. When a more user-friendly format is required, and it can't be handled at an application tier in front of the database, it can be converted "just-in-time" using a CASE expression e.g.

SELECT
    a.answer_body,
    CASE a.is_accepted WHEN 1 THEN 'TRUE' ELSE 'FALSE' END AS is_accepted
FROM answers AS a;

Storing boolean values as a character data type like char(1) or varchar(5) is also possible, but that is much less clear, has more storage/network overhead, and requires CHECK constraints on each column to restrict illegal values.

For reference, the schema of answers table would be similar to:

CREATE TABLE answers (
    ...,
    answer_body nvarchar(MAX) NOT NULL,
    is_accepted bit NOT NULL DEFAULT (0)
);

How to specify the JDK version in android studio?

On a Mac, you can use terminal to go to /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home (or wherever your Android SDK is installed) and enter the following in the command prompt:

./java -version

How to dismiss keyboard for UITextView with return key?

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range  replacementText:(NSString *)text
{
    if (range.length==0) {
        if ([text isEqualToString:@"\n"]) {
            [txtView resignFirstResponder];
            if(textView.returnKeyType== UIReturnKeyGo){

                [self PreviewLatter];
                return NO;
            }
            return NO;
        }
    }   return YES;
}

How to convert int to string on Arduino?

The solution is much too big. Try this simple one. Please provide a 7+ character buffer, no check made.

char *i2str(int i, char *buf){
  byte l=0;
  if(i<0) buf[l++]='-';
  boolean leadingZ=true;
  for(int div=10000, mod=0; div>0; div/=10){
    mod=i%div;
    i/=div;
    if(!leadingZ || i!=0){
       leadingZ=false;
       buf[l++]=i+'0';
    }
    i=mod;
  }
  buf[l]=0;
  return buf;
}

Can be easily modified to give back end of buffer, if you discard index 'l' and increment the buffer directly.

How do I add a library project to Android Studio?

You can do this easily. Go to menu File -> New -> Import Module...:

Enter image description here

Browse for the directory which contains the module. Click Finish:

Enter image description here

Go to Project Structure and add Module Dependency:

Enter image description here

Note: If you receive an SDK error, update that one.

How do I turn off the output from tar commands on Unix?

Just drop the option v.

-v is for verbose. If you don't use it then it won't display:

tar -zxf tmp.tar.gz -C ~/tmp1

Cannot hide status bar in iOS7

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
application.statusBarHidden = YES;
return YES;
}

Gradle error: could not execute build using gradle distribution

I had this issue as well and jaywhy13 answer was good but not enough.

I had to change a setting: Settings -> Gradle -> MyProject

There you need to check the "auto import" and select "use customizable gradle wrapper". After that it should refresh gradle and you can build again. If not try a reboot of Android Studio.

SELECT * FROM in MySQLi

This was already a month ago, but oh well.

I could be wrong, but for your question I get the feeling that bind_param isn't really the problem here. You always need to define some conditions, be it directly in the query string itself, of using bind_param to set the ? placeholders. That's not really an issue.

The problem I had using MySQLi SELECT * queries is the bind_result part. That's where it gets interesting. I came across this post from Jeffrey Way: http://jeff-way.com/2009/05/27/tricky-prepared-statements/(This link is no longer active). The script basically loops through the results and returns them as an array — no need to know how many columns there are, and you can still use prepared statements.

In this case it would look something like this:

$stmt = $mysqli->prepare(
  'SELECT * FROM tablename WHERE field1 = ? AND field2 = ?');
$stmt->bind_param('ss', $value, $value2);
$stmt->execute();

Then use the snippet from the site:

$meta = $stmt->result_metadata();

while ($field = $meta->fetch_field()) {
  $parameters[] = &$row[$field->name];
}

call_user_func_array(array($stmt, 'bind_result'), $parameters);

while ($stmt->fetch()) {
  foreach($row as $key => $val) {
    $x[$key] = $val;
  }
  $results[] = $x;
}

And $results now contains all the info from SELECT *. So far I found this to be an ideal solution.

CSS to hide INPUT BUTTON value text

well:

font-size: 0; line-height: 0;

work awesome for me!

Algorithm to calculate the number of divisors of a given number

This is something i came up with based on Justin answer. It might require some optimization.

n=int(input())

a=[]
b=[]

def sieve(n):
    np = n + 1
    s = list(range(np)) 
    s[1] = 0
    sqrtn = int(n**0.5)
    for i in range(2, sqrtn + 1): 
        if s[i]:
            s[i*i: np: i] = [0] * len(range(i*i, np, i))
    return filter(None, s)

k=list(sieve(n))

for i in range(len(k)):
        if n%k[i]==0:
                a.append(k[i])

a.sort()

for i in range(len(a)):
        j=1
        while n%(a[i]**j)==0: 
                j=j+1
        b.append(j-1)

nod=1

for i in range(len(b)):
        nod=nod*(b[i]+1)

print('no.of divisors of {} = {}'.format(n,nod))

How to list all files in a directory and its subdirectories in hadoop hdfs

don't use recursive approach (heap issues) :) use a queue

queue.add(param_dir)
while (queue is not empty){

  directory=  queue.pop
 - get items from current directory
 - if item is file add to a list (final list)
 - if item is directory => queue.push
}

that was easy, enjoy!

How to insert a line break in a SQL Server VARCHAR/NVARCHAR string

In some special cases you may find this useful (e.g. rendering cell-content in MS Report )
example:

select * from 
(
values
    ('use STAGING'),
    ('go'),
    ('EXEC sp_MSforeachtable 
@command1=''select ''''?'''' as tablename,count(1) as anzahl from  ? having count(1) = 0''')
) as t([Copy_and_execute_this_statement])
go

Can't concat bytes to str

f.write(plaintext)
f.write("\n".encode("utf-8"))

How to declare std::unique_ptr and what is the use of it?

Unique pointers are guaranteed to destroy the object they manage when they go out of scope. http://en.cppreference.com/w/cpp/memory/unique_ptr

In this case:

unique_ptr<double> uptr2 (pd);

pd will be destroyed when uptr2 goes out of scope. This facilitates memory management by automatic deletion.

The case of unique_ptr<int> uptr (new int(3)); is not different, except that the raw pointer is not assigned to any variable here.

finding multiples of a number in Python

Does this do what you want?

print range(0, (m+1)*n, n)[1:]

For m=5, n=20

[20, 40, 60, 80, 100]

Or better yet,

>>> print range(n, (m+1)*n, n)
[20, 40, 60, 80, 100] 

For Python3+

>>> print(list(range(n, (m+1)*n, n)))
[20, 40, 60, 80, 100] 

Android: ListView elements with multiple clickable buttons

Probably you've found how to do it, but you can call

ListView.setItemsCanFocus(true)

and now your buttons will catch focus

Hide/Show Column in an HTML Table

The following should do it:

$("input[type='checkbox']").click(function() {
    var index = $(this).attr('name').substr(2);
    $('table tr').each(function() { 
        $('td:eq(' + index + ')',this).toggle();
    });
});

This is untested code, but the principle is that you choose the table cell in each row that corresponds to the chosen index extracted from the checkbox name. You could of course limit the selectors with a class or an ID.

HTTP Error 404.3-Not Found in IIS 7.5

In my case, along with Mekanik's suggestions, I was receiving this error in Windows Server 2012 and I had to tick "HTTP Activation" in "Add Role Services".

Performance of Java matrix math libraries?

For 3d graphics applications the lwjgl.util vector implementation out-performed above mentioned jblas by a factor of about 3.

I have done 1 million matrix multiplications of a vec4 with a 4x4 matrix.

lwjgl finished in about 18ms, jblas required about 60ms.

(I assume, that the JNI approach is not very suitable for fast successive application of relatively small multiplications. Since the translation/mapping may take more time than the actual execution of the multiplication.)

Android Webview - Webpage should fit the device screen

You have to use HTML in your webView in this case. I solved this using following code

webView.loadDataWithBaseURL(null,
                "<!DOCTYPE html><html><body style = \"text-align:center\"><img src= "
                        + \"http://www.koenvangorp.be/photos/2005_09_16-moon_2000.jpg\"
                        + " alt=\"pageNo\" width=\"100%\"></body></html>",
                "text/html", "UTF-8", null);

Can you style an html radio button to look like a checkbox?

So I have been lurking on stack for so many years. This is actually my first time posting on here.

Anyhow, this might seem insane but I came across this post while struggling with the same issue and came up with a dirty solution. I know there are more elegant ways to perhaps set this as a property value but:

if you look at lines 12880-12883 in tcpdf.php :

$fx = ((($w - $this->getAbsFontMeasure($tmpfont['cw'][`110`])) / 2) * $this->k);
$fy = (($w - ((($tmpfont['desc']['Ascent'] - $tmpfont['desc']['Descent']) * $this->FontSizePt / 1000) / $this->k)) * $this->k);
$popt['ap']['n'][$onvalue] = sprintf('q %s BT /F%d %F Tf %F %F Td ('.chr(`110`).') Tj ET Q', $this->TextColor, $tmpfont['i'], $this->FontSizePt, $fx, $fy);
$popt['ap']['n']['Off'] = sprintf('q %s BT /F%d %F Tf %F %F Td ('.chr(`111`).') Tj ET Q', $this->TextColor, $tmpfont['i'], $this->FontSizePt, $fx, $fy);

and lines 13135-13138 :

$fx = ((($w - $this->getAbsFontMeasure($tmpfont['cw'][`108`])) / 2) * $this->k);
$fy = (($w - ((($tmpfont['desc']['Ascent'] - $tmpfont['desc']['Descent']) * $this->FontSizePt / 1000) / $this->k)) * $this->k);
$popt['ap']['n']['Yes'] = sprintf('q %s BT /F%d %F Tf %F %F Td ('.chr(`108`).') Tj ET Q', $this->TextColor, $tmpfont['i'], $this->FontSizePt, $fx, $fy);
$popt['ap']['n']['Off'] = sprintf('q %s BT /F%d %F Tf %F %F Td ('.chr(`109`).') Tj ET Q', $this->TextColor, $tmpfont['i'], $this->FontSizePt, $fx, $fy);

Those widgets are rendered from the zapfdingbats font set... just swap the character codes and voila... checks are radios and/or vice versa. This also opens up ideas to make a custom font set to use here and add some nice styling to your form elements.

Anyhow, just figured I would offer my two cents ... it worked awesome for me.

How to check if a variable is empty in python?

Yes, bool. It's not exactly the same -- '0' is True, but None, False, [], 0, 0.0, and "" are all False.

bool is used implicitly when you evaluate an object in a condition like an if or while statement, conditional expression, or with a boolean operator.

If you wanted to handle strings containing numbers as PHP does, you could do something like:

def empty(value):
    try:
        value = float(value)
    except ValueError:
        pass
    return bool(value)

How to connect to mysql with laravel?

In Laravel 5, there is a .env file,

It looks like

APP_ENV=local
APP_DEBUG=true
APP_KEY=YOUR_API_KEY

DB_HOST=YOUR_HOST
DB_DATABASE=YOUR_DATABASE
DB_USERNAME=YOUR_USERNAME
DB_PASSWORD=YOUR_PASSWORD

CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync

MAIL_DRIVER=smtp
MAIL_HOST=mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null

Edit that .env There is .env.sample is there , try to create from that if no such .env file found.

In PowerShell, how do I test whether or not a specific variable exists in global scope?

EDIT: Use stej's answer below. My own (partially incorrect) one is still reproduced here for reference:


You can use

Get-Variable foo -Scope Global

and trap the error that is raised when the variable doesn't exist.

How to fetch the dropdown values from database and display in jsp

  1. Make the database connection and retrieve the query result.
  2. Traverse through the result and display the query results.

The example code below demonstrates this in detail.

<%@page import="java.sql.*, java.io.*,listresult"%> //import the required library

<%

String label = request.getParameter("label"); // retrieving a variable from a previous page

Connection dbc = null; //Make connection to the database
Class.forName("com.mysql.jdbc.Driver");
dbc = DriverManager.getConnection("jdbc:mysql://localhost:3306/works", "root", "root");
if (dbc != null) 
{
    System.out.println("Connection successful");
}

ResultSet rs = listresult.dbresult.func(dbc, label); //This function is in the end. The function is defined in another package- listresult

%>

<form name="demo form" method="post">

    <table>
        <tr>
            <td>
                Label Name:
            </td>

            <td>
                <input type="text" name="label" value="<%=rs.getString("labelname")%>">
            </td>

            <td>
                <select name="label">
                <option value="">SELECT</option>

                <% while (rs.next()) {%>

                    <option value="<%=rs.getString("lname")%>"><%=rs.getString("lname")%>
                    </option>

                <%}%>
                </select>
            </td>
        </tr>
    </table>

</form>

//The function:

public static ResultSet func(Connection dbc, String x)
{
    ResultSet rs = null;
    String sql;
    PreparedStatement pst;
    try
    {
        sql = "select lname from demo where label like '" + x + "'";
        pst = dbc.prepareStatement(sql);
        rs = pst.executeQuery();
    } 
    catch (Exception e) 
    {
        e.printStackTrace();
        String sqlMessage = e.getMessage();
    }
    return rs;
}

I have tried to make this example as detailed as possible. Do ask if you have any queries.

How to open local file on Jupyter?

I would suggest you to test it firstly: copy this train.csv to the same directory as this jupyter script in and then change the path to train.csv to test whether this can be loaded successfully.

If yes, that means the previous path input is a problem

If not, that means the file it self denied your access to it, or its real filename can be something else like: train.csv.<hidden extension>

Remove trailing comma from comma-separated string

Use Guava to normalize all your commas. Split the string up around the commas, throw out the empties, and connect it all back together. Two calls. No loops. Works the first time:

import com.google.common.base.Joiner;
import com.google.common.base.Splitter;

public class TestClass {

    Splitter splitter = Splitter.on(',').omitEmptyStrings().trimResults();
    Joiner joiner = Joiner.on(',').skipNulls();

    public String cleanUpCommas(String string) {
        return joiner.join(splitter.split(string));
    }

}



public class TestMain {

    public static void main(String[] args) {
        TestClass testClass = new TestClass();

        System.out.println(testClass.cleanUpCommas("a,b,c,d,e"));
        System.out.println(testClass.cleanUpCommas("a,b,c,d,e,,,,,"));
        System.out.println(testClass.cleanUpCommas("a,b,,, ,c,d,  ,,e,,,,,"));
        System.out.println(testClass.cleanUpCommas("a,b,c,d,  e,,,,,"));
        System.out.println(testClass.cleanUpCommas(",,, ,,,,a,b,c,d,  e,,,,,"));
    }

}

Output:

a,b,c,d,e
a,b,c,d,e
a,b,c,d,e
a,b,c,d,e
a,b,c,d,e

Personally, I hate futzing around with counting limits of substrings and all that nonsense.

Letter Count on a string

A simple way is as follows:

def count_letters(word, char):
    return word.count(char)

Or, there's another way count each element directly:

from collections import Counter
Counter('banana')

Of course, you can specify one element, e.g.

Counter('banana')['a']

"The system cannot find the file specified"

Server Error in '/' Application.

The system cannot find the file specified

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ComponentModel.Win32Exception: The system cannot find the file specified

Source Error:

     {
                   SqlCommand cmd = new SqlCommand("select * from tblemployee",con);
                   con.Open();
                   GridView1.DataSource = cmd.ExecuteReader();
                   GridView1.DataBind();

Source File: d:\C# programs\kudvenkat\adobasics1\adobasics1\employeedata.aspx.cs Line: 23

if your error is same like mine..just do this

right click on your table in sqlserver object explorer,choose properties in lower left corner in general option there is a connection block with server and connection specification.in your web config for datasource=. or local choose name specified in server in properties..

Eclipse add Tomcat 7 blank server name

In my case, the tomcat directory was owned by root, and I was not running eclipse as root.

So I had to

sudo chown -R  $USER apache-tomcat-VERSION/

Maven – Always download sources and javadocs

Open your settings.xml file ~/.m2/settings.xml (create it if it doesn't exist). Add a section with the properties added. Then make sure the activeProfiles includes the new profile.

<settings>

   <!-- ... other settings here ... -->

    <profiles>
        <profile>
            <id>downloadSources</id>
            <properties>
                <downloadSources>true</downloadSources>
                <downloadJavadocs>true</downloadJavadocs>
            </properties>
        </profile>
    </profiles>

    <activeProfiles>
        <activeProfile>downloadSources</activeProfile>
    </activeProfiles>
</settings>

How to get the Android Emulator's IP address?

public String getLocalIpAddress() {

    try {
        for (Enumeration < NetworkInterface > en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration < InetAddress > enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress()) {
                    return inetAddress.getHostAddress().toString();
                }
            }
        }
    } catch (SocketException ex) {
        Log.e(LOG_TAG, ex.toString());
    }
    return null;
}

Build a basic Python iterator

There are four ways to build an iterative function:

Examples:

# generator
def uc_gen(text):
    for char in text.upper():
        yield char

# generator expression
def uc_genexp(text):
    return (char for char in text.upper())

# iterator protocol
class uc_iter():
    def __init__(self, text):
        self.text = text.upper()
        self.index = 0
    def __iter__(self):
        return self
    def __next__(self):
        try:
            result = self.text[self.index]
        except IndexError:
            raise StopIteration
        self.index += 1
        return result

# getitem method
class uc_getitem():
    def __init__(self, text):
        self.text = text.upper()
    def __getitem__(self, index):
        return self.text[index]

To see all four methods in action:

for iterator in uc_gen, uc_genexp, uc_iter, uc_getitem:
    for ch in iterator('abcde'):
        print(ch, end=' ')
    print()

Which results in:

A B C D E
A B C D E
A B C D E
A B C D E

Note:

The two generator types (uc_gen and uc_genexp) cannot be reversed(); the plain iterator (uc_iter) would need the __reversed__ magic method (which, according to the docs, must return a new iterator, but returning self works (at least in CPython)); and the getitem iteratable (uc_getitem) must have the __len__ magic method:

    # for uc_iter we add __reversed__ and update __next__
    def __reversed__(self):
        self.index = -1
        return self
    def __next__(self):
        try:
            result = self.text[self.index]
        except IndexError:
            raise StopIteration
        self.index += -1 if self.index < 0 else +1
        return result

    # for uc_getitem
    def __len__(self)
        return len(self.text)

To answer Colonel Panic's secondary question about an infinite lazily evaluated iterator, here are those examples, using each of the four methods above:

# generator
def even_gen():
    result = 0
    while True:
        yield result
        result += 2


# generator expression
def even_genexp():
    return (num for num in even_gen())  # or even_iter or even_getitem
                                        # not much value under these circumstances

# iterator protocol
class even_iter():
    def __init__(self):
        self.value = 0
    def __iter__(self):
        return self
    def __next__(self):
        next_value = self.value
        self.value += 2
        return next_value

# getitem method
class even_getitem():
    def __getitem__(self, index):
        return index * 2

import random
for iterator in even_gen, even_genexp, even_iter, even_getitem:
    limit = random.randint(15, 30)
    count = 0
    for even in iterator():
        print even,
        count += 1
        if count >= limit:
            break
    print

Which results in (at least for my sample run):

0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54
0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38
0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30
0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32

How to choose which one to use? This is mostly a matter of taste. The two methods I see most often are generators and the iterator protocol, as well as a hybrid (__iter__ returning a generator).

Generator expressions are useful for replacing list comprehensions (they are lazy and so can save on resources).

If one needs compatibility with earlier Python 2.x versions use __getitem__.

RegEx to exclude a specific string constant

This isn't easy, unless your regexp engine has special support for it. The easiest way would be to use a negative-match option, for example:

$var !~ /^foo$/
    or die "too much foo";

If not, you have to do something evil:

$var =~ /^(($)|([^f].*)|(f[^o].*)|(fo[^o].*)|(foo.+))$/
    or die "too much foo";

That one basically says "if it starts with non-f, the rest can be anything; if it starts with f, non-o, the rest can be anything; otherwise, if it starts fo, the next character had better not be another o".

Javascript: The prettiest way to compare one value against multiple values

Since nobody has added the obvious solution yet which works fine for two comparisons, I'll offer it:

if (foobar === foo || foobar === bar) {
     //do something
}

And, if you have lots of values (perhaps hundreds or thousands), then I'd suggest making a Set as this makes very clean and simple comparison code and it's fast at runtime:

// pre-construct the Set
var tSet = new Set(["foo", "bar", "test1", "test2", "test3", ...]);

// test the Set at runtime
if (tSet.has(foobar)) {
    // do something
}

For pre-ES6, you can get a Set polyfill of which there are many. One is described in this other answer.

Git: How to remove proxy

Check your enviroment:

echo $http_proxy
echo $https_proxy
echo $HTTPS_PROXY
echo $HTTP_PROXY

and delete with export http_proxy=

Or check https and http proxy

git config --global --unset https.proxy
git config --global --unset http.proxy

Or do you have the proxy in the local config?

git config --unset http.proxy
git config --unset https.proxy

How do you Encrypt and Decrypt a PHP String?

In PHP, Encryption and Decryption of a string is possible using one of the Cryptography Extensions called OpenSSL function for encrypt and decrypt.

openssl_encrypt() Function: The openssl_encrypt() function is used to encrypt the data.

Syntax is as follows :

string openssl_encrypt( string $data, string $method, string $key, $options = 0, string $iv, string $tag= NULL, string $aad, int $tag_length = 16 )

Parameters are as follows :

$data: It holds the string or data which need to be encrypted.

$method: The cipher method is adopted using openssl_get_cipher_methods() function.

$key: It holds the encryption key.

$options: It holds the bitwise disjunction of the flags OPENSSL_RAW_DATA and OPENSSL_ZERO_PADDING.

$iv: It holds the initialization vector which is not NULL.

$tag: It holds the authentication tag which is passed by reference when using AEAD cipher mode (GCM or CCM).

$aad: It holds the additional authentication data.

$tag_length: It holds the length of the authentication tag. The length of authentication tag lies between 4 to 16 for GCM mode.

Return Value: It returns the encrypted string on success or FALSE on failure.

openssl_decrypt() Function The openssl_decrypt() function is used to decrypt the data.

Syntax is as follows :

string openssl_decrypt( string $data, string $method, string $key, int $options = 0, string $iv, string $tag, string $aad)

Parameters are as follows :

$data: It holds the string or data which need to be encrypted.

$method: The cipher method is adopted using openssl_get_cipher_methods() function.

$key: It holds the encryption key.

$options: It holds the bitwise disjunction of the flags OPENSSL_RAW_DATA and OPENSSL_ZERO_PADDING.

$iv: It holds the initialization vector which is not NULL.

$tag: It holds the authentication tag using AEAD cipher mode (GCM or CCM). When authentication fails openssl_decrypt() returns FALSE.

$aad: It holds the additional authentication data.

Return Value: It returns the decrypted string on success or FALSE on failure.

Approach: First declare a string and store it into variable and use openssl_encrypt() function to encrypt the given string and use openssl_decrypt() function to descrypt the given string.

You can find the examples at : https://www.geeksforgeeks.org/how-to-encrypt-and-decrypt-a-php-string/

Prompt for user input in PowerShell

Using parameter binding is definitely the way to go here. Not only is it very quick to write (just add [Parameter(Mandatory=$true)] above your mandatory parameters), but it's also the only option that you won't hate yourself for later.

More below:

[Console]::ReadLine is explicitly forbidden by the FxCop rules for PowerShell. Why? Because it only works in PowerShell.exe, not PowerShell ISE, PowerGUI, etc.

Read-Host is, quite simply, bad form. Read-Host uncontrollably stops the script to prompt the user, which means that you can never have another script that includes the script that uses Read-Host.

You're trying to ask for parameters.

You should use the [Parameter(Mandatory=$true)] attribute, and correct typing, to ask for the parameters.

If you use this on a [SecureString], it will prompt for a password field. If you use this on a Credential type, ([Management.Automation.PSCredential]), the credentials dialog will pop up, if the parameter isn't there. A string will just become a plain old text box. If you add a HelpMessage to the parameter attribute (that is, [Parameter(Mandatory = $true, HelpMessage = 'New User Credentials')]) then it will become help text for the prompt.

Saving a Excel File into .txt format without quotes

Try this code. This does what you want.

LOGIC

  1. Save the File as a TAB delimited File in the user temp directory
  2. Read the text file in 1 go
  3. Replace "" with blanks and write to the new file at the same time.

CODE (TRIED AND TESTED)

Private Declare Function GetTempPath Lib "kernel32" Alias "GetTempPathA" _
(ByVal nBufferLength As Long, ByVal lpBuffer As String) As Long

Private Const MAX_PATH As Long = 260

'~~> Change this where and how you want to save the file
Const FlName = "C:\Users\Siddharth Rout\Desktop\MyWorkbook.txt"

Sub Sample()
    Dim tmpFile As String
    Dim MyData As String, strData() As String
    Dim entireline As String
    Dim filesize As Integer

    '~~> Create a Temp File
    tmpFile = TempPath & Format(Now, "ddmmyyyyhhmmss") & ".txt"

    ActiveWorkbook.SaveAs Filename:=tmpFile _
    , FileFormat:=xlText, CreateBackup:=False

    '~~> Read the entire file in 1 Go!
    Open tmpFile For Binary As #1
    MyData = Space$(LOF(1))
    Get #1, , MyData
    Close #1
    strData() = Split(MyData, vbCrLf)

    '~~> Get a free file handle
    filesize = FreeFile()

    '~~> Open your file
    Open FlName For Output As #filesize

    For i = LBound(strData) To UBound(strData)
        entireline = Replace(strData(i), """", "")
        '~~> Export Text
        Print #filesize, entireline
    Next i

    Close #filesize

    MsgBox "Done"
End Sub

Function TempPath() As String
    TempPath = String$(MAX_PATH, Chr$(0))
    GetTempPath MAX_PATH, TempPath
    TempPath = Replace(TempPath, Chr$(0), "")
End Function

SNAPSHOTS

Actual Workbook

enter image description here

After Saving

enter image description here

VBA changing active workbook

Use ThisWorkbook which will refer to the original workbook which holds the code.

Alternatively at code start

Dim Wb As Workbook
Set Wb = ActiveWorkbook

sample code that activates all open books before returning to ThisWorkbook

Sub Test()
Dim Wb As Workbook
Dim Wb2 As Workbook
Set Wb = ThisWorkbook
For Each Wb2 In Application.Workbooks
    Wb2.Activate
Next
Wb.Activate
End Sub

ReactJS call parent method

2019 Update with react 16+ and ES6

Posting this since React.createClass is deprecated from react version 16 and the new Javascript ES6 will give you more benefits.

Parent

import React, {Component} from 'react';
import Child from './Child';
  
export default class Parent extends Component {

  es6Function = (value) => {
    console.log(value)
  }

  simplifiedFunction (value) {
    console.log(value)
  }

  render () {
  return (
    <div>
    <Child
          es6Function = {this.es6Function}
          simplifiedFunction = {this.simplifiedFunction} 
        />
    </div>
    )
  }

}

Child

import React, {Component} from 'react';

export default class Child extends Component {

  render () {
  return (
    <div>
    <h1 onClick= { () =>
            this.props.simplifiedFunction(<SomethingThatYouWantToPassIn>)
          }
        > Something</h1>
    </div>
    )
  }
}

Simplified stateless child as ES6 constant

import React from 'react';

const Child = () => {
  return (
    <div>
    <h1 onClick= { () =>
        this.props.es6Function(<SomethingThatYouWantToPassIn>)
      }
      > Something</h1>
    </div>
  )

}
export default Child;

Regex match everything after question mark?

?(.*\n)+

With this you can get everything Even a new line

How to find a Java Memory Leak

Well, there's always the low tech solution of adding logging of the size of your maps when you modify them, then search the logs for which maps are growing beyond a reasonable size.

How to programmatically send a 404 response with Express/Node?

From the Express site, define a NotFound exception and throw it whenever you want to have a 404 page OR redirect to /404 in the below case:

function NotFound(msg){
  this.name = 'NotFound';
  Error.call(this, msg);
  Error.captureStackTrace(this, arguments.callee);
}

NotFound.prototype.__proto__ = Error.prototype;

app.get('/404', function(req, res){
  throw new NotFound;
});

app.get('/500', function(req, res){
  throw new Error('keyboard cat!');
});

Determine the number of lines within a text file

count the carriage returns/line feeds. I believe in unicode they are still 0x000D and 0x000A respectively. that way you can be as efficient or as inefficient as you want, and decide if you have to deal with both characters or not

How to change the bootstrap primary color?

This seem to work for me in Bootstrap v5 alpha 3

_variables-overrides.scss

$primary: #00adef;

$theme-colors: (
  "primary":    $primary,
);

main.scss

// Overrides
@import "variables-overrides";

// Required - Configuration
@import "@/node_modules/bootstrap/scss/functions";
@import "@/node_modules/bootstrap/scss/variables";
@import "@/node_modules/bootstrap/scss/mixins";
@import "@/node_modules/bootstrap/scss/utilities";

// Optional - Layout & components
@import "@/node_modules/bootstrap/scss/root";
@import "@/node_modules/bootstrap/scss/reboot";
@import "@/node_modules/bootstrap/scss/type";
@import "@/node_modules/bootstrap/scss/images";
@import "@/node_modules/bootstrap/scss/containers";
@import "@/node_modules/bootstrap/scss/grid";
@import "@/node_modules/bootstrap/scss/tables";
@import "@/node_modules/bootstrap/scss/forms";
@import "@/node_modules/bootstrap/scss/buttons";
@import "@/node_modules/bootstrap/scss/transitions";
@import "@/node_modules/bootstrap/scss/dropdown";
@import "@/node_modules/bootstrap/scss/button-group";
@import "@/node_modules/bootstrap/scss/nav";
@import "@/node_modules/bootstrap/scss/navbar";
@import "@/node_modules/bootstrap/scss/card";
@import "@/node_modules/bootstrap/scss/accordion";
@import "@/node_modules/bootstrap/scss/breadcrumb";
@import "@/node_modules/bootstrap/scss/pagination";
@import "@/node_modules/bootstrap/scss/badge";
@import "@/node_modules/bootstrap/scss/alert";
@import "@/node_modules/bootstrap/scss/progress";
@import "@/node_modules/bootstrap/scss/list-group";
@import "@/node_modules/bootstrap/scss/close";
@import "@/node_modules/bootstrap/scss/toasts";
@import "@/node_modules/bootstrap/scss/modal";
@import "@/node_modules/bootstrap/scss/tooltip";
@import "@/node_modules/bootstrap/scss/popover";
@import "@/node_modules/bootstrap/scss/carousel";
@import "@/node_modules/bootstrap/scss/spinners";

// Helpers
@import "@/node_modules/bootstrap/scss/helpers";

// Utilities
@import "@/node_modules/bootstrap/scss/utilities/api";

@import "custom";

How to read the output from git diff?

@@ -1,2 +3,4 @@ part of the diff

This part took me a while to understand, so I've created a minimal example.

The format is basically the same the diff -u unified diff.

For instance:

diff -u <(seq 16) <(seq 16 | grep -Ev '^(2|3|14|15)$')

Here we removed lines 2, 3, 14 and 15. Output:

@@ -1,6 +1,4 @@
 1
-2
-3
 4
 5
 6
@@ -11,6 +9,4 @@
 11
 12
 13
-14
-15
 16

@@ -1,6 +1,4 @@ means:

  • -1,6 means that this piece of the first file starts at line 1 and shows a total of 6 lines. Therefore it shows lines 1 to 6.

    1
    2
    3
    4
    5
    6
    

    - means "old", as we usually invoke it as diff -u old new.

  • +1,4 means that this piece of the second file starts at line 1 and shows a total of 4 lines. Therefore it shows lines 1 to 4.

    + means "new".

    We only have 4 lines instead of 6 because 2 lines were removed! The new hunk is just:

    1
    4
    5
    6
    

@@ -11,6 +9,4 @@ for the second hunk is analogous:

  • on the old file, we have 6 lines, starting at line 11 of the old file:

    11
    12
    13
    14
    15
    16
    
  • on the new file, we have 4 lines, starting at line 9 of the new file:

    11
    12
    13
    16
    

    Note that line 11 is the 9th line of the new file because we have already removed 2 lines on the previous hunk: 2 and 3.

Hunk header

Depending on your git version and configuration, you can also get a code line next to the @@ line, e.g. the func1() { in:

@@ -4,7 +4,6 @@ func1() {

This can also be obtained with the -p flag of plain diff.

Example: old file:

func1() {
    1;
    2;
    3;
    4;
    5;
    6;
    7;
    8;
    9;
}

If we remove line 6, the diff shows:

@@ -4,7 +4,6 @@ func1() {
     3;
     4;
     5;
-    6;
     7;
     8;
     9;

Note that this is not the correct line for func1: it skipped lines 1 and 2.

This awesome feature often tells exactly to which function or class each hunk belongs, which is very useful to interpret the diff.

How the algorithm to choose the header works exactly is discussed at: Where does the excerpt in the git diff hunk header come from?

How to get first 5 characters from string

For single-byte strings (e.g. US-ASCII, ISO 8859 family, etc.) use substr and for multi-byte strings (e.g. UTF-8, UTF-16, etc.) use mb_substr:

// singlebyte strings
$result = substr($myStr, 0, 5);
// multibyte strings
$result = mb_substr($myStr, 0, 5);

What charset does Microsoft Excel use when saving files?

CSV files could be in any format, depending on what encoding option was specified during the export from Excel: (Save Dialog, Tools Button, Web Options Item, Encoding Tab)

UPDATE: Excel (including Office 2013) doesn't actually respect the web options selected in the "save as..." dialog, so this is a bug of some sort. I just use OpenOffice Calc now to open my XLSX files and export them as CSV files (edit filter settings, choose UTF-8 encoding).

Can I redirect the stdout in python into some sort of string buffer?

A context manager for python3:

import sys
from io import StringIO


class RedirectedStdout:
    def __init__(self):
        self._stdout = None
        self._string_io = None

    def __enter__(self):
        self._stdout = sys.stdout
        sys.stdout = self._string_io = StringIO()
        return self

    def __exit__(self, type, value, traceback):
        sys.stdout = self._stdout

    def __str__(self):
        return self._string_io.getvalue()

use like this:

>>> with RedirectedStdout() as out:
>>>     print('asdf')
>>>     s = str(out)
>>>     print('bsdf')
>>> print(s, out)
'asdf\n' 'asdf\nbsdf\n'

How to create a GUID in Excel?

Italian version:

=CONCATENA(
    DECIMALE.HEX(CASUALE.TRA(0;4294967295);8);"-";
    DECIMALE.HEX(CASUALE.TRA(0;42949);4);"-";
    DECIMALE.HEX(CASUALE.TRA(0;42949);4);"-";
    DECIMALE.HEX(CASUALE.TRA(0;42949);4);"-";
    DECIMALE.HEX(CASUALE.TRA(0;4294967295);8);
    DECIMALE.HEX(CASUALE.TRA(0;42949);4))

What is the difference between call and apply?

Here's a good mnemonic. Apply uses Arrays and Always takes one or two Arguments. When you use Call you have to Count the number of arguments.

Array[n] vs Array[10] - Initializing array with variable vs real number

In C++, variable length arrays are not legal. G++ allows this as an "extension" (because C allows it), so in G++ (without being -pedantic about following the C++ standard), you can do:

int n = 10;
double a[n]; // Legal in g++ (with extensions), illegal in proper C++

If you want a "variable length array" (better called a "dynamically sized array" in C++, since proper variable length arrays aren't allowed), you either have to dynamically allocate memory yourself:

int n = 10;
double* a = new double[n]; // Don't forget to delete [] a; when you're done!

Or, better yet, use a standard container:

int n = 10;
std::vector<double> a(n); // Don't forget to #include <vector>

If you still want a proper array, you can use a constant, not a variable, when creating it:

const int n = 10;
double a[n]; // now valid, since n isn't a variable (it's a compile time constant)

Similarly, if you want to get the size from a function in C++11, you can use a constexpr:

constexpr int n()
{
    return 10;
}

double a[n()]; // n() is a compile time constant expression

IN vs OR in the SQL WHERE Clause

I assume you want to know the performance difference between the following:

WHERE foo IN ('a', 'b', 'c')
WHERE foo = 'a' OR foo = 'b' OR foo = 'c'

According to the manual for MySQL if the values are constant IN sorts the list and then uses a binary search. I would imagine that OR evaluates them one by one in no particular order. So IN is faster in some circumstances.

The best way to know is to profile both on your database with your specific data to see which is faster.

I tried both on a MySQL with 1000000 rows. When the column is indexed there is no discernable difference in performance - both are nearly instant. When the column is not indexed I got these results:

SELECT COUNT(*) FROM t_inner WHERE val IN (1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000);
1 row fetched in 0.0032 (1.2679 seconds)

SELECT COUNT(*) FROM t_inner WHERE val = 1000 OR val = 2000 OR val = 3000 OR val = 4000 OR val = 5000 OR val = 6000 OR val = 7000 OR val = 8000 OR val = 9000;
1 row fetched in 0.0026 (1.7385 seconds)

So in this case the method using OR is about 30% slower. Adding more terms makes the difference larger. Results may vary on other databases and on other data.

sass --watch with automatic minify?

There are some different way to do that

sass --watch --style=compressed main.scss main.css

or

sass --watch a.scss:a.css --style compressed

or

By Using visual studio code extension live sass compiler

see more

cd into directory without having permission

You've got several options:

  • Use a different user account, one with execute permissions on that directory.
  • Change the permissions on the directory to allow your user account execute permissions.
    • Either use chmod(1) to change the permissions or
    • Use the setfacl(1) command to add an access control list entry for your user account. (This also requires mounting the filesystem with the acl option; see mount(8) and fstab(5) for details on the mount parameter.)

It's impossible to suggest the correct approach without knowing more about the problem; why are the directory permissions set the way they are? Why do you need access to that directory?

Getting A File's Mime Type In Java

File file = new File(PropertiesReader.FILE_PATH);
MimetypesFileTypeMap fileTypeMap = new MimetypesFileTypeMap();
String mimeType = fileTypeMap.getContentType(file);
URLConnection uconnection = file.toURL().openConnection();
mimeType = uconnection.getContentType();

Entitlements file do not match those specified in your provisioning profile.(0xE8008016)

File > Workspace Settings > Build System > Legacy Build System

This worked for me. Xcode 10.0

ASP.NET Forms Authentication failed for the request. Reason: The ticket supplied has expired

AS Scott mentioned here http://weblogs.asp.net/scottgu/archive/2010/09/30/asp-net-security-fix-now-on-windows-update.aspx After windows installed security update for .net framework, you will meet this problem. just modify the configuration section in your web.config file and switch to a different cookie name.

How do you round a floating point number in Perl?

Following is a sample of five different ways to summate values. The first is a naive way to perform the summation (and fails). The second attempts to use sprintf(), but it too fails. The third uses sprintf() successfully while the final two (4th & 5th) use floor($value + 0.5).

 use strict;
 use warnings;
 use POSIX;

 my @values = (26.67,62.51,62.51,62.51,68.82,79.39,79.39);
 my $total1 = 0.00;
 my $total2 = 0;
 my $total3 = 0;
 my $total4 = 0.00;
 my $total5 = 0;
 my $value1;
 my $value2;
 my $value3;
 my $value4;
 my $value5;

 foreach $value1 (@values)
 {
      $value2 = $value1;
      $value3 = $value1;
      $value4 = $value1;
      $value5 = $value1;

      $total1 += $value1;

      $total2 += sprintf('%d', $value2 * 100);

      $value3 = sprintf('%1.2f', $value3);
      $value3 =~ s/\.//;
      $total3 += $value3;

      $total4 += $value4;

      $total5 += floor(($value5 * 100.0) + 0.5);
 }

 $total1 *= 100;
 $total4 = floor(($total4 * 100.0) + 0.5);

 print '$total1: '.sprintf('%011d', $total1)."\n";
 print '$total2: '.sprintf('%011d', $total2)."\n";
 print '$total3: '.sprintf('%011d', $total3)."\n";
 print '$total4: '.sprintf('%011d', $total4)."\n";
 print '$total5: '.sprintf('%011d', $total5)."\n";

 exit(0);

 #$total1: 00000044179
 #$total2: 00000044179
 #$total3: 00000044180
 #$total4: 00000044180
 #$total5: 00000044180

Note that floor($value + 0.5) can be replaced with int($value + 0.5) to remove the dependency on POSIX.

Java string split with "." (dot)

I believe you should escape the dot. Try:

String filename = "D:/some folder/001.docx";
String extensionRemoved = filename.split("\\.")[0];

Otherwise dot is interpreted as any character in regular expressions.

Random String Generator Returning Same String

You're instantiating the Random object inside your method.

The Random object is seeded from the system clock, which means that if you call your method several times in quick succession it'll use the same seed each time, which means that it'll generate the same sequence of random numbers, which means that you'll get the same string.

To solve the problem, move your Random instance outside of the method itself (and while you're at it you could get rid of that crazy sequence of calls to Convert and Floor and NextDouble):

private readonly Random _rng = new Random();
private const string _chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

private string RandomString(int size)
{
    char[] buffer = new char[size];

    for (int i = 0; i < size; i++)
    {
        buffer[i] = _chars[_rng.Next(_chars.Length)];
    }
    return new string(buffer);
}

Best way to get all selected checkboxes VALUES in jQuery

You want the :checkbox:checked selector and map to create an array of the values:

var checkedValues = $('input:checkbox:checked').map(function() {
    return this.value;
}).get();

If your checkboxes have a shared class it would be faster to use that instead, eg. $('.mycheckboxes:checked'), or for a common name $('input[name="Foo"]:checked')

- Update -

If you don't need IE support then you can now make the map() call more succinct by using an arrow function:

var checkedValues = $('input:checkbox:checked').map((i, el) => el.value).get();

SQL - select distinct only on one column

Since you don't care, I chose the max ID for each number.

select tbl.* from tbl
inner join (
select max(id) as maxID, number from tbl group by number) maxID
on maxID.maxID = tbl.id

Query Explanation

 select 
    tbl.*  -- give me all the data from the base table (tbl) 
 from 
    tbl    
    inner join (  -- only return rows in tbl which match this subquery
        select 
            max(id) as maxID -- MAX (ie distinct) ID per GROUP BY below
        from 
            tbl 
        group by 
            NUMBER            -- how to group rows for the MAX aggregation
    ) maxID
        on maxID.maxID = tbl.id -- join condition ie only return rows in tbl 
                                -- whose ID is also a MAX ID for a given NUMBER

jQuery convert line breaks to br (nl2br equivalent)

This JavaScript function considers whether to use insert or replace to handle the swap.

(Insert or replace HTML line breaks)

/**
 * This function is same as PHP's nl2br() with default parameters.
 *
 * @param {string} str Input text
 * @param {boolean} replaceMode Use replace instead of insert
 * @param {boolean} isXhtml Use XHTML 
 * @return {string} Filtered text
 */
function nl2br (str, replaceMode, isXhtml) {

  var breakTag = (isXhtml) ? '<br />' : '<br>';
  var replaceStr = (replaceMode) ? '$1'+ breakTag : '$1'+ breakTag +'$2';
  return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, replaceStr);
}

Demo - JSFiddle

JavaScript nl2br & br2nl functions

A CSS selector to get last visible div

This worked for me.

.alert:not(:first-child){
    margin: 30px;
}

How to make a window always stay on top in .Net?

I had a momentary 5 minute lapse and I forgot to specify the form in full like this:

  myformName.ActiveForm.TopMost = true;

But what I really wanted was THIS!

  this.TopMost = true;

List of Timezone IDs for use with FindTimeZoneById() in C#?

You will find complete list of time zone with its GMToffsets here and you can use "Name of Time Zone" column value to find time zone by ID

e.g

TimeZoneInfo objTimeZoneInfo = TimeZoneInfo.FindTimeZoneById("Dateline Standard Time");

You will get time zone info class that contains dateline standard time time zone which is used for GMT-12:00.

What does '<?=' mean in PHP?

=> is the separator for associative arrays. In the context of that foreach loop, it assigns the key of the array to $user and the value to $pass.

Example:

$user_list = array(
    'dave' => 'apassword',
    'steve' => 'secr3t'
);

foreach ($user_list as $user => $pass) {
    echo "{$user}'s pass is: {$pass}\n";
}
// Prints: 
// "dave's pass is: apassword"
// "steve's pass is: secr3t"

Note that this can be used for numerically indexed arrays too.

Example:

$foo = array('car', 'truck', 'van', 'bike', 'rickshaw');
foreach ($foo as $i => $type) {
    echo "{$i}: {$type}\n";
}
// prints:
// 0: car
// 1: truck
// 2: van
// 3: bike
// 4: rickshaw

Number prime test in JavaScript

This one is I think more efficient to check prime number :

function prime(num){
 if(num == 1) return true;
 var t = num / 2;
 var k = 2;
 while(k <= t) {
   if(num % k == 0) {
      return false
   } else {
   k++;  
  }
 }
  return true;
}
console.log(prime(37))

How can I give the Intellij compiler more heap space?

I was facing "java.lang.OutOfMemoryError: Java heap space" error while building my project using maven install command.

I was able to get rid of it by changing maven runner settings.

Settings | Build, Execution, Deployment | Build Tools | Maven | Runner | VM options to -Xmx512m

How to split a string with any whitespace chars as delimiters

To get this working in Javascript, I had to do the following:

myString.split(/\s+/g)

How do I properly set the permgen size?

So you are doing the right thing concerning "-XX:MaxPermSize=512m": it is indeed the correct syntax. You could try to set these options directly to the Catalyna server files so they are used on server start.

Maybe this post will help you!

How to make sure that Tomcat6 reads CATALINA_OPTS on Windows?

Python: find position of element in array

For your first question, find the position of some value in a list x using index(), like so:

x.index(value)

For your second question, to check for multiple same values you should split your list into chunks and use the same logic from above. They say divide and conquer. It works. Try this:

value = 1 
x = [1,2,3,4,5,6,2,1,4,5,6]

chunk_a = x[:int(len(x)/2)] # get the first half of x 
chunk_b = x[int(len(x)/2):] # get the rest half of x

print(chunk_a.index(value))
print(chunk_b.index(value))

Hope that helps!

How to emulate a do-while loop in Python?

Here's a very simple way to emulate a do-while loop:

condition = True
while condition:
    # loop body here
    condition = test_loop_condition()
# end of loop

The key features of a do-while loop are that the loop body always executes at least once, and that the condition is evaluated at the bottom of the loop body. The control structure show here accomplishes both of these with no need for exceptions or break statements. It does introduce one extra Boolean variable.

is python capable of running on multiple cores?

The answer is "Yes, But..."

But cPython cannot when you are using regular threads for concurrency.

You can either use something like multiprocessing, celery or mpi4py to split the parallel work into another process;

Or you can use something like Jython or IronPython to use an alternative interpreter that doesn't have a GIL.

A softer solution is to use libraries that don't run afoul of the GIL for heavy CPU tasks, for instance numpy can do the heavy lifting while not retaining the GIL, so other python threads can proceed. You can also use the ctypes library in this way.

If you are not doing CPU bound work, you can ignore the GIL issue entirely (kind of) since python won't aquire the GIL while it's waiting for IO.

Is it possible to install another version of Python to Virtualenv?

Although the question specifically describes installing 2.6, I would like to add some importants points to the excellent answers above in case someone comes across this. For the record, my case was that I was trying to install 2.7 on an ubuntu 10.04 box.

First, my motivation towards the methods described in all the answers here is that installing Python from deadsnake's ppa's has been a total failure. So building a local Python is the way to go.

Having tried so, I thought relying to the default installation of pip (with sudo apt-get install pip) would be adequate. This unfortunately is wrong. It turned out that I was getting all shorts of nasty issues and eventually not being able to create a virtualenv.

Therefore, I highly recommend to install pip locally with wget https://raw.github.com/pypa/pip/master/contrib/get-pip.py && python get-pip.py --user. This related question gave me this hint.

Now if this doesn't work, make sure that libssl-dev for Ubuntu or openssl-dev for CentOS is installed. Install them with apt-get or yum and then re-build Python (no need to remove anything if already installed, do so on top). get-pip complains about that, you can check so by running import ssl on a py shell.

Last, don't forget to declare .local/bin and local python to path, check with which pip and which python.

How do I find the index of a character within a string in C?

This should do it:

//Returns the index of the first occurence of char c in char* string. If not found -1 is returned.
int get_index(char* string, char c) {
    char *e = strchr(string, c);
    if (e == NULL) {
        return -1;
    }
    return (int)(e - string);
}

Operator overloading on class templates

// In MyClass.h
MyClass<T>& operator+=(const MyClass<T>& classObj);


// In MyClass.cpp
template <class T>
MyClass<T>& MyClass<T>::operator+=(const MyClass<T>& classObj) {
  // ...
  return *this;
}

This is invalid for templates. The full source code of the operator must be in all translation units that it is used in. This typically means that the code is inline in the header.

Edit: Technically, according to the Standard, it is possible to export templates, however very few compilers support it. In addition, you CAN also do the above if the template is explicitly instantiated in MyClass.cpp for all types that are T- but in reality, that normally defies the point of a template.

More edit: I read through your code, and it needs some work, for example overloading operator[]. In addition, typically, I would make the dimensions part of the template parameters, allowing for the failure of + or += to be caught at compile-time, and allowing the type to be meaningfully stack allocated. Your exception class also needs to derive from std::exception. However, none of those involve compile-time errors, they're just not great code.

Python not working in the command line of git bash

In addition to the answer of @Charles-Duffy, you can use winpty directly without installing/downloading anything extra. Just run winpty c:/Python27/python.exe. The utility winpty.exe can be found at Git\usr\bin. I'm using Git for Windows v2.7.1

The prebuilt binaries from @Charles-Duffy is version 0.1.1(according to the file name), while the included one is 0.2.2

What are the different types of keys in RDBMS?

There is also a SURROGATE KEY: it occurs if one non prime attribute depends on another non prime attribute. that time you don't now to choose which key as primary key to split up your table. In that case use a surrogate key instead of a primary key. Usually this key is system defined and always have numeric values and its value often automatically incremented for new rows. Eg : ms acces = auto number & my SQL = identity column & oracle = sequence.

Using only CSS, show div on hover over <a>

I'm by know means an expert, but I'm incredibly proud of myself for having worked something out about this code. If you do:

div {
    display: none;
}

a:hover > div {
    display: block;
} 

(Note the '>') You can contain the whole thing in an a tag, then, as long as your trigger (which can be in it's own div, or straight up in the a tag, or anything you want) is physically touching the revealed div, you can move your mouse from one to the other.

Maybe this isn't useful for a great deal, but I had to set my revealed div to overflow: auto, so sometimes it had scroll bars, which couldn't be used as soon as you move away from the div.

In fact, after finally working out how to make the revealed div, (although it is now a child of the trigger, not a sibling), sit behind the trigger, in terms of z-index, (with a little help from this page: How to get a parent element to appear above child) you don't even have to roll over the revealed div to scroll it, just stay hovering over the trigger and use your wheel, or whatever.

My revealed div covers most of the page, so this technique makes it a lot more permanent, rather than the screen flashing from one state to another with every move of the mouse. It's really intuitive actually, hence why I'm really quite proud of myself.

The only downside is that you can't put links within the whole thing, but you can use the whole thing as one big link.

How can I wait for a thread to finish with .NET?

If using from .NET 4 this sample can help you:

class Program
{
    static void Main(string[] args)
    {
        Task task1 = Task.Factory.StartNew(() => doStuff());
        Task task2 = Task.Factory.StartNew(() => doStuff());
        Task task3 = Task.Factory.StartNew(() => doStuff());
        Task.WaitAll(task1, task2, task3);
        Console.WriteLine("All threads complete");
    }

    static void doStuff()
    {
        // Do stuff here
    }
}

From: Create multiple threads and wait all of them to complete

Angular 4 - get input value

You can also use template reference variables

<form (submit)="onSubmit(player.value)">
   <input #player placeholder="player name">
</form>
onSubmit(playerName: string) {
  console.log(playerName)
}

SQL Update Multiple Fields FROM via a SELECT Statement

Something like this should work (can't test it right now - from memory):

UPDATE SHIPMENT
SET
  OrgAddress1     = BD.OrgAddress1,
  OrgAddress2     = BD.OrgAddress2,
  OrgCity         = BD.OrgCity,
  OrgState        = BD.OrgState,
  OrgZip          = BD.OrgZip,
  DestAddress1    = BD.DestAddress1,
  DestAddress2    = BD.DestAddress2,
  DestCity        = BD.DestCity,
  DestState       = BD.DestState,
  DestZip         = BD.DestZip
FROM
   BookingDetails BD
WHERE 
   SHIPMENT.MyID2 = @MyID2
   AND
   BD.MyID = @MyID

Does that help?

How to sort List<Integer>?

You are using Lists, concrete ArrayList. ArrayList also implements Collection interface. Collection interface has sort method which is used to sort the elements present in the specified list of Collection in ascending order. This will be the quickest and possibly the best way for your case.

Sorting a list in ascending order can be performed as default operation on this way:

Collections.sort(list);

Sorting a list in descending order can be performed on this way:

Collections.reverse(list);

According to these facts, your solution has to be written like this:

public class tes 
{
    public static void main(String args[])
    {
        List<Integer> lList = new ArrayList<Integer>();
        lList.add(4);
        lList.add(1);
        lList.add(7);
        lList.add(2);
        lList.add(9);
        lList.add(1);
        lList.add(5);

        Collections.sort(lList);
        for(int i=0; i<lList.size();i++ )
        {
            System.out.println(lList.get(i));
        }
     }
}

More about Collections you can read here.

Why would one omit the close tag?

As my question was marked as duplicate of this one, I think it's O.K. to post why NOT omitting closing tag ?> can be for some reasons desired.

  • With complete Processing Instructions Syntax (<?php ... ?>) PHP source is valid SGML document, which can be parsed and processed without problems with SGML parser. With additional restrictions it can be valid XML/XHTML as well.

Nothing prevents you from writing valid XML/HTML/SGML code. PHP documentation is aware of this. Excerpt:

Note: Also note that if you are embedding PHP within XML or XHTML you will need to use the < ?php ?> tags to remain compliant with standards.

Of course PHP syntax is not strict SGML/XML/HTML and you create a document, which is not SGML/XML/HTML, just like you can turn HTML into XHTML to be XML compliant or not.

  • At some point you may want to concatenate sources. This will be not as easy as simply doing cat source1.php source2.php if you have inconsistency introduced by omitting closing ?> tags.

  • Without ?> it's harder to tell if document was left in PHP escape mode or PHP ignore mode (PI tag <?php may have been opened or not). Life is easier if you consistently leave your documents in PHP ignore mode. It's just like work with well formatted HTML documents compared to documents with unclosed, badly nested tags etc.

  • It seems that some editors like Dreamweaver may have problems with PI left open [1].

Difference between "Complete binary tree", "strict binary tree","full binary Tree"?

Consider a binary tree whose nodes are drawn in a tree fashion. Now start numbering the nodes from top to bottom and left to right. A complete tree has these properties:

If n has children then all nodes numbered less than n have two children.

If n has one child it must be the left child and all nodes less than n have two children. In addition no node numbered greater than n has children.

If n has no children then no node numbered greater than n has children.

A complete binary tree can be used to represent a heap. It can be easily represented in contiguous memory with no gaps (i.e. all array elements are used save for any space that may exist at the end).

right click context menu for datagridview

For the position for the context menu, y found the problem that I needed a it to be relative to the DataGridView, and the event I needed to use gives the poistion relative to the cell clicked. I haven't found a better solution so I implemented this function in the commons class, so I call it from wherever I need.

It's quite tested and works well. I Hope you find it useful.

    /// <summary>
    /// When DataGridView_CellMouseClick ocurs, it gives the position relative to the cell clicked, but for context menus you need the position relative to the DataGridView
    /// </summary>
    /// <param name="dgv">DataGridView that produces the event</param>
    /// <param name="e">Event arguments produced</param>
    /// <returns>The Location of the click, relative to the DataGridView</returns>
    public static Point PositionRelativeToDataGridViewFromDataGridViewCellMouseEventArgs(DataGridView dgv, DataGridViewCellMouseEventArgs e)
    {
        int x = e.X;
        int y = e.Y;
        if (dgv.RowHeadersVisible)
            x += dgv.RowHeadersWidth;
        if (dgv.ColumnHeadersVisible)
            y += dgv.ColumnHeadersHeight;
        for (int j = 0; j < e.ColumnIndex; j++)
            if (dgv.Columns[j].Visible)
                x += dgv.Columns[j].Width;
        for (int i = 0; i < e.RowIndex; i++)
            if (dgv.Rows[i].Visible)
                y += dgv.Rows[i].Height;
        return new Point(x, y);
    }

How to check if a service is running on Android?

In kotlin you can add boolean variable in companion object and check its value from any class you want:

companion object{
     var isRuning = false

}

Change it value when service is created and destroyed

 override fun onCreate() {
        super.onCreate()
        isRuning = true
    }

override fun onDestroy() {
    super.onDestroy()
    isRuning = false
    }

How to do a non-greedy match in grep?

You're looking for a non-greedy (or lazy) match. To get a non-greedy match in regular expressions you need to use the modifier ? after the quantifier. For example you can change .* to .*?.

By default grep doesn't support non-greedy modifiers, but you can use grep -P to use the Perl syntax.

Getting the class name of an instance?

You can simply use __qualname__ which stands for qualified name of a function or class

Example:

>>> class C:
...     class D:
...         def meth(self):
...             pass
...
>>> C.__qualname__
'C'
>>> C.D.__qualname__
'C.D'
>>> C.D.meth.__qualname__
'C.D.meth'

documentation link qualname

"This operation requires IIS integrated pipeline mode."

The way to fix this issue is not within IIS. I was trying to run my application within IIS Express within Visual Studio. I searched the web and some articles were saying to add an identity tag to the system.web tag. This is not the correct way.

The way I was able to solve this issue was to click on the project file and go to properties. Under managed pipeline, I changed the property value from classic to integrated.

This solved my issue.

AngularJS : Prevent error $digest already in progress when calling $scope.$apply()

Understanding that the Angular documents call checking the $$phase an anti-pattern, I tried to get $timeout and _.defer to work.

The timeout and deferred methods create a flash of unparsed {{myVar}} content in the dom like a FOUT. For me this was not acceptable. It leaves me without much to be told dogmatically that something is a hack, and not have a suitable alternative.

The only thing that works every time is:

if(scope.$$phase !== '$digest'){ scope.$digest() }.

I don't understand the danger of this method, or why it's described as a hack by people in the comments and the angular team. The command seems precise and easy to read:

"Do the digest unless one is already happening"

In CoffeeScript it's even prettier:

scope.$digest() unless scope.$$phase is '$digest'

What's the issue with this? Is there an alternative that won't create a FOUT? $safeApply looks fine but uses the $$phase inspection method, too.

Emulate Samsung Galaxy Tab

What resolution and density should I set?

  • 1024x600

How can I indicate that this is large screen device?

  • you can't really (not that i know of)

What hardware does this tablet support?

What is max heap size?

  • not sure

Which Android version?

  • 2.2

Hope that helps - check the spec page for all unanswered questions.

Count distinct values

Ok, I deleted my previous answer because finally it was not what willlangford was looking for, but I made my point that maybe we were all misunderstanding the question.

I also thought of the SELECT DISTINCT... thing at first, but it seemed too weird to me that someone needed to know how many people had a different number of pets than the rest... thats why I thought that maybe the question was not clear enough.

So, now that the real question meaning is clarified, making a subquery for this its quite an overhead, I would preferably use a GROUP BY clause.

Imagine you have the table customer_pets like this:

+-----------------------+
|  customer  |   pets   |
+------------+----------+
| customer1  |    2     |
| customer2  |    3     |
| customer3  |    2     |
| customer4  |    2     |
| customer5  |    3     |
| customer6  |    4     |
+------------+----------+

then

SELECT count(customer) AS num_customers, pets FROM customer_pets GROUP BY pets

would return:

+----------------------------+
|  num_customers  |   pets   |
+-----------------+----------+
|        3        |    2     |
|        2        |    3     |
|        1        |    4     |
+-----------------+----------+

as you need.

Auto-fit TextView for Android

I'll explain how works this attribute lower android versions step by step:

1- Import android support library 26.x.x on your project gradle file. If there is no support library on IDE, they will download automatically.

dependencies {
    compile 'com.android.support:support-v4:26.1.0'
    compile 'com.android.support:appcompat-v7:26.1.0'
    compile 'com.android.support:support-v13:26.1.0' }

allprojects {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    } }

2- Open your layout XML file and refactor like this tag your TextView. This scenario is: when incrased font size on system, fit text to avaliable width, not word wrap.

<android.support.v7.widget.AppCompatTextView
            android:id="@+id/textViewAutoSize"
            android:layout_width="match_parent"
            android:layout_height="25dp"
            android:ellipsize="none"
            android:text="Auto size text with compatible lower android versions."
            android:textSize="12sp"
            app:autoSizeMaxTextSize="14sp"
            app:autoSizeMinTextSize="4sp"
            app:autoSizeStepGranularity="0.5sp"
            app:autoSizeTextType="uniform" />

C# - using List<T>.Find() with custom objects

Find() will find the element that matches the predicate that you pass as a parameter, so it is not related to Equals() or the == operator.

var element = myList.Find(e => [some condition on e]);

In this case, I have used a lambda expression as a predicate. You might want to read on this. In the case of Find(), your expression should take an element and return a bool.

In your case, that would be:

var reponse = list.Find(r => r.Statement == "statement1")

And to answer the question in the comments, this is the equivalent in .NET 2.0, before lambda expressions were introduced:

var response = list.Find(delegate (Response r) {
    return r.Statement == "statement1";
});

How do I create a message box with "Yes", "No" choices and a DialogResult?

@Mikael Svenson's answer is correct. I just wanted to add a small addition to it:

The Messagebox icon can also be included has an additional property like below:

DialogResult dialogResult = MessageBox.Show("Sure", "Please Confirm Your Action", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

How to get diff between all files inside 2 folders that are on the web?

You urls are not in the same repository, so you can't do it with the svn diff command.

svn: 'http://svn.boost.org/svn/boost/sandbox/boost/extension' isn't in the same repository as 'http://cloudobserver.googlecode.com/svn'

Another way you could do it, is export each repos using svn export, and then use the diff command to compare the 2 directories you exported.

// Export repositories
svn export http://svn.boost.org/svn/boost/sandbox/boost/extension/ repos1
svn export http://cloudobserver.googlecode.com/svn/branches/v0.4/Boost.Extension.Tutorial/libs/boost/extension/ repos2

// Compare exported directories
diff repos1 repos2 > file.diff

Clang vs GCC - which produces faster binaries?

Phoronix did some benchmarks about this, but it is about a snapshot version of Clang/LLVM from a few months back. The results being that things were more-or-less a push; neither GCC nor Clang is definitively better in all cases.

Since you'd use the latest Clang, it's maybe a little less relevant. Then again, GCC 4.6 is slated to have some major optimizations for Core 2 and i7, apparently.

I figure Clang's faster compilation speed will be nicer for original developers, and then when you push the code out into the world, Linux distro/BSD/etc. end-users will use GCC for the faster binaries.

How to change onClick handler dynamically?

OMG... It's not only a problem of "jQuery Library" and "getElementById".

Sure, jQuery helps us to put cross-browser problems aside, but using the traditional way without libraries can still work well, if you really understand JavaScript ENOUGH!!!

Both @Már Örlygsson and @Darryl Hein gave you good ALTARNATIVES(I'd say, they're just altarnatives, not anwsers), where the former used the traditional way, and the latter jQuery way. But do you really know the answer to your problem? What is wrong with your code?

First, .click is a jQuery way. If you want to use traditional way, use .onclick instead. Or I recommend you concentrating on learning to use jQuery only, in case of confusing. jQuery is a good tool to use without knowing DOM enough.

The second problem, also the critical one, new function(){} is a very bad syntax, or say it is a wrong syntax.

No matter whether you want to go with jQuery or without it, you need to clarify it.

There are 3 basic ways declaring function:

function name () {code}

... = function() {code} // known as anonymous function or function literal

... = new Function("code") // Function Object

Note that javascript is case-sensitive, so new function() is not a standard syntax of javascript. Browsers may misunderstand the meaning.

Thus your code can be modified using the second way as

 = function(){alert();}

Or using the third way as

 = new Function("alert();");

Elaborating on it, the second way works almost the same as the third way, and the second way is very common, while the third is rare. Both of your best answers use the second way.

However, the third way can do something that the second can't do, because of "runtime" and "compile time". I just hope you know new Function() can be useful sometimes. One day you meet problems using function(){}, don't forget new Function().

To understand more, you are recommended read << JavaScript: The Definitive Guide, 6th Edition >>, O'Reilly.

Converting cv::Mat to IplImage*

In case of gray image, I am using this function and it works fine! however you must take care about the function features ;)

CvMat * src=  cvCreateMat(300,300,CV_32FC1);      
IplImage *dist= cvCreateImage(cvGetSize(dist),IPL_DEPTH_32F,3);

cvConvertScale(src, dist, 1, 0);

Compilation fails with "relocation R_X86_64_32 against `.rodata.str1.8' can not be used when making a shared object"

I'm getting the same solution as @camino's comment on https://stackoverflow.com/a/19365454/10593190 and XavierStuvw's reply.

I got it to work (for installing ffmpeg) by simply reinstalling the whole thing from the beginning with all instances of $ ./configure replaced by $ ./configure --enable-shared (first make sure to delete all the folders and files including the .so files from the previous attempt).

Apparently this works because https://stackoverflow.com/a/13812368/10593190.

Search and replace a line in a file in Python

Expanding on @Kiran's answer, which I agree is more succinct and Pythonic, this adds codecs to support the reading and writing of UTF-8:

import codecs 

from tempfile import mkstemp
from shutil import move
from os import remove


def replace(source_file_path, pattern, substring):
    fh, target_file_path = mkstemp()

    with codecs.open(target_file_path, 'w', 'utf-8') as target_file:
        with codecs.open(source_file_path, 'r', 'utf-8') as source_file:
            for line in source_file:
                target_file.write(line.replace(pattern, substring))
    remove(source_file_path)
    move(target_file_path, source_file_path)

How to dynamically update labels captions in VBA form?

If you want to use this in VBA:

For i = 1 To X
    UserForm1.Controls("Label" & i).Caption =  MySheet.Cells(i + 1, i).Value
Next

How to insert pandas dataframe via mysqldb into database?

The to_sql method works for me.

However, keep in mind that the it looks like it's going to be deprecated in favor of SQLAlchemy:

FutureWarning: The 'mysql' flavor with DBAPI connection is deprecated and will be removed in future versions. MySQL will be further supported with SQLAlchemy connectables. chunksize=chunksize, dtype=dtype)

How to activate the Bootstrap modal-backdrop?

Pretty strange, it should work out of the box as the ".modal-backdrop" class is defined top-level in the css.

<div class="modal-backdrop"></div>

Made a small demo: http://jsfiddle.net/PfBnq/

How to tell if JRE or JDK is installed

the computer in question is a Mac.

A macOS-only solution:

/usr/libexec/java_home -v 1.8+ --exec javac -version

Where 1.8+ is Java 1.8 or higher.

Unfortunately, the java_home helper does not set the proper return code, so checking for failure requires parsing the output (e.g. 2>&1 |grep -v "Unable") which varies based on locale.

Note, Java may also exist in /Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin, but at time of writing this, I'm unaware of a JRE that installs there which contains javac as well.

Why do we use web.xml?

Web.xml is called as deployment descriptor file and its is is an XML file that contains information on the configuration of the web application, including the configuration of servlets.

Kotlin: How to get and set a text to TextView in Android using Kotlin?

just add below line and access direct xml object

import kotlinx.android.synthetic.main.activity_main.*

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        txt_HelloWorld.text = "abc"
    }

replace activity_main according to your XML name

What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?

So much for this simple question, but I just wanted to highlight a new feature in Java which will avoid all confusions around indexing in arrays even for beginners. Java-8 has abstracted the task of iterating for you.

int[] array = new int[5];

//If you need just the items
Arrays.stream(array).forEach(item -> { println(item); });

//If you need the index as well
IntStream.range(0, array.length).forEach(index -> { println(array[index]); })

What's the benefit? Well, one thing is the readability like English. Second, you need not worry about the ArrayIndexOutOfBoundsException

Binary search (bisection) in Python

Why not look at the code for bisect_left/right and adapt it to suit your purpose.

like this:

def binary_search(a, x, lo=0, hi=None):
    if hi is None:
        hi = len(a)
    while lo < hi:
        mid = (lo+hi)//2
        midval = a[mid]
        if midval < x:
            lo = mid+1
        elif midval > x: 
            hi = mid
        else:
            return mid
    return -1

How to select a range of the second row to the last row

Sub SelectAllCellsInSheet(SheetName As String)
    lastCol = Sheets(SheetName).Range("a1").End(xlToRight).Column
    Lastrow = Sheets(SheetName).Cells(1, 1).End(xlDown).Row
    Sheets(SheetName).Range("A2", Sheets(SheetName).Cells(Lastrow, lastCol)).Select
End Sub

To use with ActiveSheet:

Call SelectAllCellsInSheet(ActiveSheet.Name)

Set Jackson Timezone for Date deserialization

Looks like older answers were fine for older Jackson versions, but since objectMapper has method setTimeZone(tz), setting time zone on a dateFormat is totally ignored.

How to properly setup timeZone to the ObjectMapper in Jackson version 2.11.0:

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setTimeZone(TimeZone.getTimeZone("Europe/Warsaw"));

Full example

  @Test
  void test() throws Exception {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.findAndRegisterModules();
    objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    JavaTimeModule module = new JavaTimeModule();
    objectMapper.registerModule(module);
    objectMapper.setTimeZone(TimeZone.getTimeZone("Europe/Warsaw"));

    ZonedDateTime now = ZonedDateTime.now();
    String converted = objectMapper.writeValueAsString(now);

    ZonedDateTime restored = objectMapper.readValue(converted, ZonedDateTime.class);
    System.out.println("serialized: " + now);
    System.out.println("converted: " + converted);
    System.out.println("restored: " + restored);

    Assertions.assertThat(now).isEqualTo(restored);
  }
`

How to set a cookie for another domain

Probaly you can use Iframe for this. Facebook probably uses this technique. You can read more on this here. Stackoverflow uses similar technique, but with HTML5 local storage, more on this on their blog

How to stop the Timer in android?

I had a similar problem: every time I push a particular button, I create a new Timer.

my_timer = new Timer("MY_TIMER");
my_timer.schedule(new TimerTask() {
...
}

Exiting from that activity I deleted the timer:

if(my_timer!=null){
my_timer.cancel();
my_timer = null;
}

But it was not enough because the cancel() method only canceled the latest Timer. The older ones were ignored an didn't stop running. The purge() method was not useful for me. I solved the problem just checking the Timer instantiation:

if(my_timer == null){
my_timer = new Timer("MY_TIMER");
my_timer.schedule(new TimerTask() {
...
}
}

How to display alt text for an image in chrome

Internet Explorer 7 (and earlier) displays the value of the alt attribute as a tooltip, when mousing over the image. This is NOT the correct behavior, according to the HTML specification. The title attribute should be used instead. Source: http://www.w3schools.com/tags/att_img_alt.asp

HTML img align="middle" doesn't align an image

Try this:

style="margin: auto"

How do I create a foreign key in SQL Server?

Necromancing.
Actually, doing this correctly is a little bit trickier.

You first need to check if the primary-key exists for the column you want to set your foreign key to reference to.

In this example, a foreign key on table T_ZO_SYS_Language_Forms is created, referencing dbo.T_SYS_Language_Forms.LANG_UID

-- First, chech if the table exists...
IF 0 < (
    SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES 
    WHERE TABLE_TYPE = 'BASE TABLE'
    AND TABLE_SCHEMA = 'dbo'
    AND TABLE_NAME = 'T_SYS_Language_Forms'
)
BEGIN
    -- Check for NULL values in the primary-key column
    IF 0 = (SELECT COUNT(*) FROM T_SYS_Language_Forms WHERE LANG_UID IS NULL)
    BEGIN
        ALTER TABLE T_SYS_Language_Forms ALTER COLUMN LANG_UID uniqueidentifier NOT NULL 

        -- No, don't drop, FK references might already exist...
        -- Drop PK if exists 
        -- ALTER TABLE T_SYS_Language_Forms DROP CONSTRAINT pk_constraint_name 
        --DECLARE @pkDropCommand nvarchar(1000) 
        --SET @pkDropCommand = N'ALTER TABLE T_SYS_Language_Forms DROP CONSTRAINT ' + QUOTENAME((SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
        --WHERE CONSTRAINT_TYPE = 'PRIMARY KEY' 
        --AND TABLE_SCHEMA = 'dbo' 
        --AND TABLE_NAME = 'T_SYS_Language_Forms' 
        ----AND CONSTRAINT_NAME = 'PK_T_SYS_Language_Forms' 
        --))
        ---- PRINT @pkDropCommand 
        --EXECUTE(@pkDropCommand) 

        -- Instead do
        -- EXEC sp_rename 'dbo.T_SYS_Language_Forms.PK_T_SYS_Language_Forms1234565', 'PK_T_SYS_Language_Forms';


        -- Check if they keys are unique (it is very possible they might not be) 
        IF 1 >= (SELECT TOP 1 COUNT(*) AS cnt FROM T_SYS_Language_Forms GROUP BY LANG_UID ORDER BY cnt DESC)
        BEGIN

            -- If no Primary key for this table
            IF 0 =  
            (
                SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
                WHERE CONSTRAINT_TYPE = 'PRIMARY KEY' 
                AND TABLE_SCHEMA = 'dbo' 
                AND TABLE_NAME = 'T_SYS_Language_Forms' 
                -- AND CONSTRAINT_NAME = 'PK_T_SYS_Language_Forms' 
            )
                ALTER TABLE T_SYS_Language_Forms ADD CONSTRAINT PK_T_SYS_Language_Forms PRIMARY KEY CLUSTERED (LANG_UID ASC)
            ;

            -- Adding foreign key
            IF 0 = (SELECT COUNT(*) FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS WHERE CONSTRAINT_NAME = 'FK_T_ZO_SYS_Language_Forms_T_SYS_Language_Forms') 
                ALTER TABLE T_ZO_SYS_Language_Forms WITH NOCHECK ADD CONSTRAINT FK_T_ZO_SYS_Language_Forms_T_SYS_Language_Forms FOREIGN KEY(ZOLANG_LANG_UID) REFERENCES T_SYS_Language_Forms(LANG_UID); 
        END -- End uniqueness check
        ELSE
            PRINT 'FSCK, this column has duplicate keys, and can thus not be changed to primary key...' 
    END -- End NULL check
    ELSE
        PRINT 'FSCK, need to figure out how to update NULL value(s)...' 
END 

'ng' is not recognized as an internal or external command, operable program or batch file

I just installed angular cli and it solved my issue, simply run:

npm install -g @angular/cli

How to get Git to clone into current directory

The solution for Windows is to clone the repository to other folder and then copy and paste to the original location or just copy the .git invisible folder.

Get values from other sheet using VBA

Maybe you can use the script i am using to retrieve a certain cell value from another sheet back to a specific sheet.

Sub reviewRow()
Application.ScreenUpdating = False
Results = MsgBox("Do you want to View selected row?", vbYesNo, "")
If Results = vbYes And Range("C10") > 1 Then
i = Range("C10") //this is where i put the row number that i want to retrieve or review that can be changed as needed
Worksheets("Sheet1").Range("C6") = Worksheets("Sheet2").Range("C" & i) //sheet names can be changed as necessary
End if
Application.ScreenUpdating = True
End Sub

You can make a form using this and personalize it as needed.

Receiving "Attempted import error:" in react app

This is another option:

export default function Counter() {

}

HTTP vs HTTPS performance

There seems to be a nasty edge case here: Ajax over congested wifi.

Ajax usually means that the KeepAlive has timed out after say 20 seconds. However, the wifi means that the (ideally fast) ajax connection has to make multiple round trips. Worse, the wifi often loses packets, and there are TCP retransmits. In this case, HTTPS performs really really badly!

CREATE TABLE LIKE A1 as A2

Based on http://dev.mysql.com/doc/refman/5.0/en/create-table-select.html

What about:

Create Table New_Users Select * from Old_Users Where 1=2;

and if that doesn't work, just select a row and truncate after creation:

Create table New_Users select * from Old_Users Limit 1;
Truncate Table New_Users;

EDIT:

I noticed your comment below about needing indexes, etc. Try:

show create table old_users;
#copy the output ddl statement into a text editor and change the table name to new_users
#run the new query
insert into new_users(id,name...) select id,name,... form old_users group by id;

That should do it. It appears that you are doing this to get rid of duplicates? In which case you may want to put a unique index on id. if it's a primary key, this should already be in place. You can either:

#make primary key
alter table new_users add primary key (id);
#make unique
create unique index idx_new_users_id_uniq on new_users (id);

Laravel 5.1 API Enable Cors

barryvdh/laravel-cors works perfectly with Laravel 5.1 with just a few key points in enabling it.

  1. After adding it as a composer dependency, make sure you have published the CORS config file and adjusted the CORS headers as you want them. Here is how mine look in app/config/cors.php

    <?php
    
    return [
    
        'supportsCredentials' => true,
        'allowedOrigins' => ['*'],
        'allowedHeaders' => ['*'],
        'allowedMethods' => ['GET', 'POST', 'PUT',  'DELETE'],
        'exposedHeaders' => ['DAV', 'content-length', 'Allow'],
        'maxAge' => 86400,
        'hosts' => [],
    ];
    
  2. After this, there is one more step that's not mentioned in the documentation, you have to add the CORS handler 'Barryvdh\Cors\HandleCors' in the App kernel. I prefer to use it in the global middleware stack. Like this

    /**
     * The application's global HTTP middleware stack.
     *
     * @var array
     */
    protected $middleware = [
        'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
        'Illuminate\Cookie\Middleware\EncryptCookies',
        'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
        'Illuminate\Session\Middleware\StartSession',
        'Illuminate\View\Middleware\ShareErrorsFromSession',
    
        'Barryvdh\Cors\HandleCors',
    
    ];
    

    But its up to you to use it as a route middleware and place on specific routes.

This should make the package work with L5.1