Programs & Examples On #Cpu cache

A CPU-cache is a hardware structure used by the CPU to reduce the average access memory time.

What is a "cache-friendly" code?

Processors today work with many levels of cascading memory areas. So the CPU will have a bunch of memory that is on the CPU chip itself. It has very fast access to this memory. There are different levels of cache each one slower access ( and larger ) than the next, until you get to system memory which is not on the CPU and is relatively much slower to access.

Logically, to the CPU's instruction set you just refer to memory addresses in a giant virtual address space. When you access a single memory address the CPU will go fetch it. in the old days it would fetch just that single address. But today the CPU will fetch a bunch of memory around the bit you asked for, and copy it into the cache. It assumes that if you asked for a particular address that is is highly likely that you are going to ask for an address nearby very soon. For example if you were copying a buffer you would read and write from consecutive addresses - one right after the other.

So today when you fetch an address it checks the first level of cache to see if it already read that address into cache, if it doesn't find it, then this is a cache miss and it has to go out to the next level of cache to find it, until it eventually has to go out into main memory.

Cache friendly code tries to keep accesses close together in memory so that you minimize cache misses.

So an example would be imagine you wanted to copy a giant 2 dimensional table. It is organized with reach row in consecutive in memory, and one row follow the next right after.

If you copied the elements one row at a time from left to right - that would be cache friendly. If you decided to copy the table one column at a time, you would copy the exact same amount of memory - but it would be cache unfriendly.

Write-back vs Write-Through caching?

Write-Back is a more complex one and requires a complicated Cache Coherence Protocol(MOESI) but it is worth it as it makes the system fast and efficient.

The only benefit of Write-Through is that it makes the implementation extremely simple and no complicated cache coherency protocol is required.

Tomcat won't stop or restart

I faced the same problem as mentioned below.

PID file found but no matching process was found. Stop aborted.

Solution is to find the free space of the linux machine by using the following command

df -h

The above command shows my home directory was 100% used. Then identified which files to be removed by using the following command

du -h .

After removing, it was able to perform IO operation on the linux machine and the tomcat was able to start.

How to get the part of a file after the first line that matches a regular expression?

If for any reason, you want to avoid using sed, the following will print the line matching TERMINATE till the end of the file:

tail -n "+$(grep -n 'TERMINATE' file | head -n 1 | cut -d ":" -f 1)" file

and the following will print from the following line matching TERMINATE till the end of the file:

tail -n "+$(($(grep -n 'TERMINATE' file | head -n 1 | cut -d ":" -f 1)+1))" file

It takes 2 processes to do what sed can do in one process, and if the file changes between the execution of grep and tail, the result can be incoherent, so I recommend using sed. Moreover, if the file dones not contain TERMINATE, the 1st command fails.

Using Postman to access OAuth 2.0 Google APIs

Postman will query Google API impersonating a Web Application

Generate an OAuth 2.0 token:

  1. Ensure that the Google APIs are enabled
  2. Create an OAuth 2.0 client ID

    • Go to Google Console -> API -> OAuth consent screen
      • Add getpostman.com to the Authorized domains. Click Save.
    • Go to Google Console -> API -> Credentials
      • Click 'Create credentials' -> OAuth client ID -> Web application
        • Name: 'getpostman'
        • Authorized redirect URIs: https://www.getpostman.com/oauth2/callback
    • Copy the generated Client ID and Client secret fields for later use
  3. In Postman select Authorization tab and select "OAuth 2.0" type. Click 'Get New Access Token'

    • Fill the GET NEW ACCESS TOKEN form as following
      • Token Name: 'Google OAuth getpostman'
      • Grant Type: 'Authorization Code'
      • Callback URL: https://www.getpostman.com/oauth2/callback
      • Auth URL: https://accounts.google.com/o/oauth2/auth
      • Access Token URL: https://accounts.google.com/o/oauth2/token
      • Client ID: Client ID generated in the step 2 (e.g., '123456789012-abracadabra1234546789blablabla12.apps.googleusercontent.com')
      • Client Secret: Client secret generated in the step 2 (e.g., 'ABRACADABRAus1ZMGHvq9R-L')
      • Scope: see the Google docs for the required OAuth scope (e.g., https://www.googleapis.com/auth/cloud-platform)
      • State: Empty
      • Client Authentication: "Send as Basic Auth header"
    • Click 'Request Token' and 'Use Token'
  4. Set the method, parameters, and body of your request according to the Google docs

How to keep :active css style after click a button

CSS

:active denotes the interaction state (so for a button will be applied during press), :focus may be a better choice here. However, the styling will be lost once another element gains focus.

The final potential alternative using CSS would be to use :target, assuming the items being clicked are setting routes (e.g. anchors) within the page- however this can be interrupted if you are using routing (e.g. Angular), however this doesnt seem the case here.

_x000D_
_x000D_
.active:active {_x000D_
  color: red;_x000D_
}_x000D_
.focus:focus {_x000D_
  color: red;_x000D_
}_x000D_
:target {_x000D_
  color: red;_x000D_
}
_x000D_
<button class='active'>Active</button>_x000D_
<button class='focus'>Focus</button>_x000D_
<a href='#target1' id='target1' class='target'>Target 1</a>_x000D_
<a href='#target2' id='target2' class='target'>Target 2</a>_x000D_
<a href='#target3' id='target3' class='target'>Target 3</a>
_x000D_
_x000D_
_x000D_

Javascript / jQuery

As such, there is no way in CSS to absolutely toggle a styled state- if none of the above work for you, you will either need to combine with a change in your HTML (e.g. based on a checkbox) or programatically apply/remove a class using e.g. jQuery

_x000D_
_x000D_
$('button').on('click', function(){_x000D_
    $('button').removeClass('selected');_x000D_
    $(this).addClass('selected');_x000D_
});
_x000D_
button.selected{_x000D_
  color:red;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<button>Item</button><button>Item</button><button>Item</button>_x000D_
  
_x000D_
_x000D_
_x000D_

Finish an activity from another activity

I know this is an old question, a few of these methods didn't work for me so for anyone looking in the future or having my troubles this worked for me

I overrode onPause and called finish() inside that method.

How to delete files recursively from an S3 bucket

The voted up answer is missing a step.

Per aws s3 help:

Currently, there is no support for the use of UNIX style wildcards in a command's path arguments. However, most commands have --exclude "<value>" and --include "<value>" parameters that can achieve the desired result......... When there are multiple filters, the rule is the filters that appear later in the command take precedence over filters that appear earlier in the command. For example, if the filter parameters passed to the command were --exclude "*" --include "*.txt" All files will be excluded from the command except for files ending with .txt

aws s3 rm --recursive s3://bucket/ --exclude="*" --include="/folder_path/*" 

Insert multiple rows with one query MySQL

In most cases inserting multiple records with one Insert statement is much faster in MySQL than inserting records with for/foreach loop in PHP.

Let's assume $column1 and $column2 are arrays with same size posted by html form.

You can create your query like this:

<?php
    $query = 'INSERT INTO TABLE (`column1`, `column2`) VALUES ';
    $query_parts = array();
    for($x=0; $x<count($column1); $x++){
        $query_parts[] = "('" . $column1[$x] . "', '" . $column2[$x] . "')";
    }
    echo $query .= implode(',', $query_parts);
?>

If data is posted for two records the query will become:

INSERT INTO TABLE (column1, column2) VALUES ('data', 'data'), ('data', 'data')

Determine if char is a num or letter

You can normally check for ASCII letters or numbers using simple conditions

if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
{
    /*This is an alphabet*/
}

For digits you can use

if (ch >= '0' && ch <= '9')
{
    /*It is a digit*/
}

But since characters in C are internally treated as ASCII values you can also use ASCII values to check the same.

How to check if a character is number or letter

How to store a datetime in MySQL with timezone info

All the symptoms you describe suggest that you never tell MySQL what time zone to use so it defaults to system's zone. Think about it: if all it has is '2011-03-13 02:49:10', how can it guess that it's a local Tanzanian date?

As far as I know, MySQL doesn't provide any syntax to specify time zone information in dates. You have to change it a per-connection basis; something like:

SET time_zone = 'EAT';

If this doesn't work (to use named zones you need that the server has been configured to do so and it's often not the case) you can use UTC offsets because Tanzania does not observe daylight saving time at the time of writing but of course it isn't the best option:

SET time_zone = '+03:00';

Entity Framework - Include Multiple Levels of Properties

For EF 6

using System.Data.Entity;

query.Include(x => x.Collection.Select(y => y.Property))

Make sure to add using System.Data.Entity; to get the version of Include that takes in a lambda.


For EF Core

Use the new method ThenInclude

query.Include(x => x.Collection)
     .ThenInclude(x => x.Property);

Tensorflow 2.0 - AttributeError: module 'tensorflow' has no attribute 'Session'

I faced this problem when I first tried python after installing windows10 + python3.7(64bit) + anacconda3 + jupyter notebook.

I solved this problem by refering to "https://vispud.blogspot.com/2019/05/tensorflow200a0-attributeerror-module.html"

I agree with

I believe "Session()" has been removed with TF 2.0.

I inserted two lines. One is tf.compat.v1.disable_eager_execution() and the other is sess = tf.compat.v1.Session()

My Hello.py is as follows:

import tensorflow as tf

tf.compat.v1.disable_eager_execution()

hello = tf.constant('Hello, TensorFlow!')

sess = tf.compat.v1.Session()

print(sess.run(hello))

How to center Font Awesome icons horizontally?

Since you don't want to add a class to cells containing an icon, how about this...

Wrap the contents of each non-icon td in a span:

<td><span>consectetur</span></td>
<td><span>adipiscing</span></td>
<td><span>elit</span></td>

And use this CSS:

td {
    text-align: center;
}
td span {
    text-align: left;
    display: block;
}

I wouldn't normally post an answer in this situation, but this seems too long for a comment.

How to generate class diagram from project in Visual Studio 2013?

Right click on the project in solution explorer or class view window --> "View" --> "View Class Diagram"

In git, what is the difference between merge --squash and rebase?

Merge commits: retains all of the commits in your branch and interleaves them with commits on the base branchenter image description here

Merge Squash: retains the changes but omits the individual commits from history enter image description here

Rebase: This moves the entire feature branch to begin on the tip of the master branch, effectively incorporating all of the new commits in master

enter image description here

More on here

Android SDK location

The default location for Android sdk(s) on a Mac is:

/Users/*username*/Library/Android/sdk

Pdf.js: rendering a pdf file using a base64 file source instead of url

from the sourcecode at http://mozilla.github.com/pdf.js/build/pdf.js

/**
 * This is the main entry point for loading a PDF and interacting with it.
 * NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR)
 * is used, which means it must follow the same origin rules that any XHR does
 * e.g. No cross domain requests without CORS.
 *
 * @param {string|TypedAray|object} source Can be an url to where a PDF is
 * located, a typed array (Uint8Array) already populated with data or
 * and parameter object with the following possible fields:
 *  - url   - The URL of the PDF.
 *  - data  - A typed array with PDF data.
 *  - httpHeaders - Basic authentication headers.
 *  - password - For decrypting password-protected PDFs.
 *
 * @return {Promise} A promise that is resolved with {PDFDocumentProxy} object.
 */

So a standard XMLHttpRequest(XHR) is used for retrieving the document. The Problem with this is that XMLHttpRequests do not support data: uris (eg. data:application/pdf;base64,JVBERi0xLjUK...).

But there is the possibility of passing a typed Javascript Array to the function. The only thing you need to do is to convert the base64 string to a Uint8Array. You can use this function found at https://gist.github.com/1032746

var BASE64_MARKER = ';base64,';

function convertDataURIToBinary(dataURI) {
  var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
  var base64 = dataURI.substring(base64Index);
  var raw = window.atob(base64);
  var rawLength = raw.length;
  var array = new Uint8Array(new ArrayBuffer(rawLength));

  for(var i = 0; i < rawLength; i++) {
    array[i] = raw.charCodeAt(i);
  }
  return array;
}

tl;dr

var pdfAsDataUri = "data:application/pdf;base64,JVBERi0xLjUK..."; // shortened
var pdfAsArray = convertDataURIToBinary(pdfAsDataUri);
PDFJS.getDocument(pdfAsArray)

Python - AttributeError: 'numpy.ndarray' object has no attribute 'append'

append on an ndarray is ambiguous; to which axis do you want to append the data? Without knowing precisely what your data looks like, I can only provide an example using numpy.concatenate that I hope will help:

import numpy as np

pixels = np.array([[3,3]])
pix = [4,4]
pixels = np.concatenate((pixels,[pix]),axis=0)

# [[3 3]
#  [4 4]]

Iterate through a C array

I think you should store the size somewhere.

The null-terminated-string kind of model for determining array length is a bad idea. For instance, getting the size of the array will be O(N) when it could very easily have been O(1) otherwise.

Having that said, a good solution might be glib's Arrays, they have the added advantage of expanding automatically if you need to add more items.

P.S. to be completely honest, I haven't used much of glib, but I think it's a (very) reputable library.

Pandas read in table without headers

Previous answers were good and correct, but in my opinion, an extra names parameter will make it perfect, and it should be the recommended way, especially when the csv has no headers.

Solution

Use usecols and names parameters

df = pd.read_csv(file_path, usecols=[3,6], names=['colA', 'colB'])

Additional reading

or use header=None to explicitly tells people that the csv has no headers (anyway both lines are identical)

df = pd.read_csv(file_path, usecols=[3,6], names=['colA', 'colB'], header=None)

So that you can retrieve your data by

# with `names` parameter
df['colA']
df['colB'] 

instead of

# without `names` parameter
df[0]
df[1]

Explain

Based on read_csv, when names are passed explicitly, then header will be behaving like None instead of 0, so one can skip header=None when names exist.

Setting the default Java character encoding

I have tried a lot of things, but the sample code here works perfect. Link

The crux of the code is:

String s = "?? ??? ??? ?? ?????";
String out = new String(s.getBytes("UTF-8"), "ISO-8859-1");

How can you dynamically create variables via a while loop?

Unless there is an overwhelming need to create a mess of variable names, I would just use a dictionary, where you can dynamically create the key names and associate a value to each.

a = {}
k = 0
while k < 10:
    <dynamically create key> 
    key = ...
    <calculate value> 
    value = ...
    a[key] = value 
    k += 1

There are also some interesting data structures in the new 'collections' module that might be applicable:

http://docs.python.org/dev/library/collections.html

Is there an eval() function in Java?

Writing your own library is not that hard as u might thing. Here is link for Shunting-yard algorithm with step by step algorithm explenation. Although, you will have to parse the input for tokens first.

There are 2 other questions wich can give you some information too: Turn a String into a Math Expression? What's a good library for parsing mathematical expressions in java?

Why am I getting "IndentationError: expected an indented block"?

You might want to check you spaces and tabs. A tab is a default of 4 spaces. However, your "if" and "elif" match, so I am not quite sure why. Go into Options in the top bar, and click "Configure IDLE". Check the Indentation Width on the right in Fonts/Tabs, and make sure your indents have that many spaces.

Show / hide div on click with CSS

This can be achieved by attaching a "tabindex" to an element. This will make that element "clickable". You can then use :focus to select your hidden div as follows...

_x000D_
_x000D_
.clicker {_x000D_
width:100px;_x000D_
height:100px;_x000D_
background-color:blue;_x000D_
outline:none;_x000D_
cursor:pointer;_x000D_
}_x000D_
_x000D_
.hiddendiv{_x000D_
display:none;_x000D_
height:200px;_x000D_
background-color:green;_x000D_
}_x000D_
_x000D_
.clicker:focus + .hiddendiv{_x000D_
display:block;_x000D_
}
_x000D_
<html>_x000D_
<head>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div>_x000D_
<div class="clicker" tabindex="1">Click me</div>_x000D_
<div class="hiddendiv"></div>_x000D_
</div>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

The + selector will select the nearest element AFTER the "clicker" div. You can use other selectors but I believe there is no current way to select an element that is not a sibling or child.

When to use MongoDB or other document oriented database systems?

In NoSQL: If Only It Was That Easy, the author writes about MongoDB:

MongoDB is not a key/value store, it’s quite a bit more. It’s definitely not a RDBMS either. I haven’t used MongoDB in production, but I have used it a little building a test app and it is a very cool piece of kit. It seems to be very performant and either has, or will have soon, fault tolerance and auto-sharding (aka it will scale). I think Mongo might be the closest thing to a RDBMS replacement that I’ve seen so far. It won’t work for all data sets and access patterns, but it’s built for your typical CRUD stuff. Storing what is essentially a huge hash, and being able to select on any of those keys, is what most people use a relational database for. If your DB is 3NF and you don’t do any joins (you’re just selecting a bunch of tables and putting all the objects together, AKA what most people do in a web app), MongoDB would probably kick ass for you.

Then, in the conclusion:

The real thing to point out is that if you are being held back from making something super awesome because you can’t choose a database, you are doing it wrong. If you know mysql, just use it. Optimize when you actually need to. Use it like a k/v store, use it like a rdbms, but for god sake, build your killer app! None of this will matter to most apps. Facebook still uses MySQL, a lot. Wikipedia uses MySQL, a lot. FriendFeed uses MySQL, a lot. NoSQL is a great tool, but it’s certainly not going to be your competitive edge, it’s not going to make your app hot, and most of all, your users won’t care about any of this.

What am I going to build my next app on? Probably Postgres. Will I use NoSQL? Maybe. I might also use Hadoop and Hive. I might keep everything in flat files. Maybe I’ll start hacking on Maglev. I’ll use whatever is best for the job. If I need reporting, I won’t be using any NoSQL. If I need caching, I’ll probably use Tokyo Tyrant. If I need ACIDity, I won’t use NoSQL. If I need a ton of counters, I’ll use Redis. If I need transactions, I’ll use Postgres. If I have a ton of a single type of documents, I’ll probably use Mongo. If I need to write 1 billion objects a day, I’d probably use Voldemort. If I need full text search, I’d probably use Solr. If I need full text search of volatile data, I’d probably use Sphinx.

I like this article, I find it very informative, it gives a good overview of the NoSQL landscape and hype. But, and that's the most important part, it really helps to ask yourself the right questions when it comes to choose between RDBMS and NoSQL. Worth the read IMHO.

Alternate link to article

Mapping two integers to one, in a unique and deterministic way

It isn't that tough to construct a mapping:

   1  2  3  4  5  use this mapping if (a,b) != (b,a)
1  0  1  3  6 10
2  2  4  7 11 16
3  5  8 12 17 23
4  9 13 18 24 31
5 14 19 25 32 40

   1  2  3  4  5 use this mapping if (a,b) == (b,a) (mirror)
1  0  1  2  4  6
2  1  3  5  7 10
3  2  5  8 11 14
4  4  8 11 15 19
5  6 10 14 19 24


    0  1 -1  2 -2 use this if you need negative/positive
 0  0  1  2  4  6
 1  1  3  5  7 10
-1  2  5  8 11 14
 2  4  8 11 15 19
-2  6 10 14 19 24

Figuring out how to get the value for an arbitrary a,b is a little more difficult.

Defining array with multiple types in TypeScript

I've settled on the following format for typing arrays that can have items of multiple types.

Array<ItemType1 | ItemType2 | ItemType3>

This works well with testing and type guards. https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-differentiating-types

This format doesn't work well with testing or type guards:

(ItemType1 | ItemType2 | ItemType3)[]

Select multiple columns using Entity Framework

Why don't you create a new object right in the .Select:

.Select(x => new PInfo{ 
    ServerName = x.ServerName, 
    ProcessID = x.ProcessID, 
    UserName = x.Username }).ToList();

How to remove all of the data in a table using Django

You can use the Django-Truncate library to delete all data of a table without destroying the table structure.

Example:

  1. First, install django-turncate using your terminal/command line:
pip install django-truncate
  1. Add "django_truncate" to your INSTALLED_APPS in the settings.py file:
INSTALLED_APPS = [
    ...
    'django_truncate',
]
  1. Use this command in your terminal to delete all data of the table from the app.
python manage.py truncate --apps app_name --models table_name

Debugging with command-line parameters in Visual Studio

With VS 2015 and up, Use the Smart Command Line Arguments extension. This plug-in adds a window that allows you to turn arguments on and off:

Smart Command Line Arguments interface

The extension additionally stores the arguments in a JSON file, allowing you to commit them to source control. In addition to ensuring you don't have to type in all the arguments every single time, this serves as a useful supplement to your documentation for other developers to discover the available options.

javascript: optional first argument in function

Just to kick a long-dead horse, because I've had to implement an optional argument in the middle of two or more required arguments. Use the arguments array and use the last one as the required non-optional argument.

my_function() {
  var options = arguments[argument.length - 1];
  var content = arguments.length > 1 ? arguments[0] : null;
}

How can I get the current screen orientation?

In your activity class use the method below :

 @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        // Checks the orientation of the screen
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {

            setlogo();// Your Method
            Log.d("Daiya", "ORIENTATION_LANDSCAPE");

        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {

            setlogoForLandScape();// Your Method
            Log.d("Daiya", "ORIENTATION_PORTRAIT");
        }
    }

Then to declare that your activity handles a configuration change, edit the appropriate element in your manifest file to include the android:configChanges attribute with a value that represents the configuration you want to handle. Possible values are listed in the documentation for the android:configChanges attribute (the most commonly used values are "orientation" to prevent restarts when the screen orientation changes and "keyboardHidden" to prevent restarts when the keyboard availability changes). You can declare multiple configuration values in the attribute by separating them with a pipe | character.

<activity android:name=".MyActivity"
          android:configChanges="orientation|keyboardHidden"
          android:label="@string/app_name">

That's all!!

How to check if a table exists in MS Access for vb macros

I know the question is already answered, but I find that the existing answers are not valid:
they will return True for linked tables with a non working back-end.
Using DCount can be much slower, but is more reliable.

Function IsTable(sTblName As String) As Boolean
    'does table exists and work ?
    'note: finding the name in the TableDefs collection is not enough,
    '      since the backend might be invalid or missing

    On Error GoTo hell
    Dim x
    x = DCount("*", sTblName)
    IsTable = True
    Exit Function
hell:
    Debug.Print Now, sTblName, Err.Number, Err.Description
    IsTable = False

End Function

SQL Left Join first match only

distinct is not a function. It always operates on all columns of the select list.

Your problem is a typical "greatest N per group" problem which can easily be solved using a window function:

select ...
from (
  select IDNo,
         FirstName,
         LastName,
         ....,
         row_number() over (partition by lower(idno) order by firstname) as rn 
  from people 
) t
where rn = 1;

Using the order by clause you can select which of the duplicates you want to pick.

The above can be used in a left join, see below:

select ...
from x
  left join (
    select IDNo,
           FirstName,
           LastName,
           ....,
           row_number() over (partition by lower(idno) order by firstname) as rn 
    from people 
  ) p on p.idno = x.idno and p.rn = 1
where ...

How do I check that a number is float or integer?

Another method is:

    function isFloat(float) {
        return /\./.test(float.toString());
    }

Might not be as efficient as the others but another method all the same.

What is limiting the # of simultaneous connections my ASP.NET application can make to a web service?

I realize the question might be rather old, but you say the backend is running on the same server. That means on a different port, probably other than the default port 80.

I've read that when you use the "connectionManagement" configuration element, you need to specify the port number if it differs from the default 80.

LINK: maxConnection setting may not work even autoConfig = false in ASP.NET

Secondly, if you choose to use the default configuration (address="*") extended with your own backend specific value, you might consider putting the specific value first! Otherwise, if a request is made, the * matches first and the default of 2 connections is taken. Just like when you use the section in web.config.

LINK: <remove> Element for connectionManagement (Network Settings)

Hope it helps someone.

Use the auto keyword in C++ STL

The auto keyword gets the type from the expression on the right of =. Therefore it will work with any type, the only requirement is to initialize the auto variable when declaring it so that the compiler can deduce the type.

Examples:

auto a = 0.0f;  // a is float
auto b = std::vector<int>();  // b is std::vector<int>()

MyType foo()  { return MyType(); }

auto c = foo();  // c is MyType

Declaring variables inside loops, good practice or bad practice?

Once upon a time (pre C++98); the following would break:

{
    for (int i=0; i<.; ++i) {std::string foo;}
    for (int i=0; i<.; ++i) {std::string foo;}
}

with the warning that i was already declared (foo was fine as that's scoped within the {}). This is likely the WHY people would first argue it's bad. It stopped being true a long time ago though.

If you STILL have to support such an old compiler (some people are on Borland) then the answer is yes, a case could be made to put the i out the loop, because not doing so makes it makes it "harder" for people to put multiple loops in with the same variable, though honestly the compiler will still fail, which is all you want if there's going to be a problem.

If you no longer have to support such an old compiler, variables should be kept to the smallest scope you can get them so that you not only minimise the memory usage; but also make understanding the project easier. It's a bit like asking why don't you have all your variables global. Same argument applies, but the scopes just change a bit.

A hex viewer / editor plugin for Notepad++?

The hex editor plugin mentioned by ellak still works, but it seems that you need the TextFX Characters plugin as well.

I initially installed only the hex plugin and Notepad++ would no longer pop up; instead it started eating memory (killed it at 1.2 GB). I removed it again and for other reasons installed the TextFX plugin (based on Find multiple lines in Notepad++)

Out of curiosity I installed the hex plugin again and now it works.

Note that this is on a fresh install of Windows 7 64 bit.

Upgrade python in a virtualenv

I just want to clarify, because some of the answers refer to venv and others refer to virtualenv.

Use of the -p or --python flag is supported on virtualenv, but not on venv. If you have more than one Python version and you want to specify which one to create the venv with, do it on the command line, like this:

malikarumi@Tetuoan2:~/Projects$ python3.6 -m venv {path to pre-existing dir you want venv in}

You can of course upgrade with venv as others have pointed out, but that assumes you have already upgraded the Python that was used to create that venv in the first place. You can't upgrade to a Python version you don't already have on your system somewhere, so make sure to get the version you want, first, then make all the venvs you want from it.

How do I get the current time zone of MySQL?

From the manual (section 9.6):

The current values of the global and client-specific time zones can be retrieved like this:
mysql> SELECT @@global.time_zone, @@session.time_zone;

Edit The above returns SYSTEM if MySQL is set to slave to the system's timezone, which is less than helpful. Since you're using PHP, if the answer from MySQL is SYSTEM, you can then ask the system what timezone it's using via date_default_timezone_get. (Of course, as VolkerK pointed out, PHP may be running on a different server, but as assumptions go, assuming the web server and the DB server it's talking to are set to [if not actually in] the same timezone isn't a huge leap.) But beware that (as with MySQL), you can set the timezone that PHP uses (date_default_timezone_set), which means it may report a different value than the OS is using. If you're in control of the PHP code, you should know whether you're doing that and be okay.

But the whole question of what timezone the MySQL server is using may be a tangent, because asking the server what timezone it's in tells you absolutely nothing about the data in the database. Read on for details:

Further discussion:

If you're in control of the server, of course you can ensure that the timezone is a known quantity. If you're not in control of the server, you can set the timezone used by your connection like this:

set time_zone = '+00:00';

That sets the timezone to GMT, so that any further operations (like now()) will use GMT.

Note, though, that time and date values are not stored with timezone information in MySQL:

mysql> create table foo (tstamp datetime) Engine=MyISAM;
Query OK, 0 rows affected (0.06 sec)

mysql> insert into foo (tstamp) values (now());
Query OK, 1 row affected (0.00 sec)

mysql> set time_zone = '+01:00';
Query OK, 0 rows affected (0.00 sec)

mysql> select tstamp from foo;
+---------------------+
| tstamp              |
+---------------------+
| 2010-05-29 08:31:59 |
+---------------------+
1 row in set (0.00 sec)

mysql> set time_zone = '+02:00';
Query OK, 0 rows affected (0.00 sec)

mysql> select tstamp from foo;
+---------------------+
| tstamp              |
+---------------------+
| 2010-05-29 08:31:59 |      <== Note, no change!
+---------------------+
1 row in set (0.00 sec)

mysql> select now();
+---------------------+
| now()               |
+---------------------+
| 2010-05-29 10:32:32 |
+---------------------+
1 row in set (0.00 sec)

mysql> set time_zone = '+00:00';
Query OK, 0 rows affected (0.00 sec)

mysql> select now();
+---------------------+
| now()               |
+---------------------+
| 2010-05-29 08:32:38 |      <== Note, it changed!
+---------------------+
1 row in set (0.00 sec)

So knowing the timezone of the server is only important in terms of functions that get the time right now, such as now(), unix_timestamp(), etc.; it doesn't tell you anything about what timezone the dates in the database data are using. You might choose to assume they were written using the server's timezone, but that assumption may well be flawed. To know the timezone of any dates or times stored in the data, you have to ensure that they're stored with timezone information or (as I do) ensure they're always in GMT.

Why is assuming the data was written using the server's timezone flawed? Well, for one thing, the data may have been written using a connection that set a different timezone. The database may have been moved from one server to another, where the servers were in different timezones (I ran into that when I inherited a database that had moved from Texas to California). But even if the data is written on the server, with its current time zone, it's still ambiguous. Last year, in the United States, Daylight Savings Time was turned off at 2:00 a.m. on November 1st. Suppose my server is in California using the Pacific timezone and I have the value 2009-11-01 01:30:00 in the database. When was it? Was that 1:30 a.m. November 1st PDT, or 1:30 a.m. November 1st PST (an hour later)? You have absolutely no way of knowing. Moral: Always store dates/times in GMT (which doesn't do DST) and convert to the desired timezone as/when necessary.

Bootstrap 3 select input form inline

I think I've accidentally found a solution. The only thing to do is inserting an empty <span class="input-group-addon"></span> between the <input> and the <select>.

Additionally you can make it "invisible" by reducing its width, horizontal padding and borders:

_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="input-group">_x000D_
    <span class="input-group-addon" title="* Price" id="priceLabel">Price</span>_x000D_
    <input type="number" id="searchbygenerals_priceFrom" name="searchbygenerals[priceFrom]" required="required" class="form-control" value="0">_x000D_
    <span class="input-group-addon">-</span>_x000D_
    <input type="number" id="searchbygenerals_priceTo" name="searchbygenerals[priceTo]" required="required" class="form-control" value="0">_x000D_
  _x000D_
    <!-- insert this line -->_x000D_
    <span class="input-group-addon" style="width:0px; padding-left:0px; padding-right:0px; border:none;"></span>_x000D_
  _x000D_
    <select id="searchbygenerals_currency" name="searchbygenerals[currency]" class="form-control">_x000D_
        <option value="1">HUF</option>_x000D_
        <option value="2">EUR</option>_x000D_
    </select>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Tested on Chrome and FireFox.

How to implement LIMIT with SQL Server?

This is one of the reasons I try to avoid using MS Server... but anyway. Sometimes you just don't have an option (yei! and I have to use an outdated version!!).

My suggestion is to create a virtual table:

From:

SELECT * FROM table

To:

CREATE VIEW v_table AS    
    SELECT ROW_NUMBER() OVER (ORDER BY table_key) AS row,* FROM table

Then just query:

SELECT * FROM v_table WHERE row BETWEEN 10 AND 20

If fields are added, or removed, "row" is updated automatically.

The main problem with this option is that ORDER BY is fixed. So if you want a different order, you would have to create another view.

UPDATE

There is another problem with this approach: if you try to filter your data, it won't work as expected. For example, if you do:

SELECT * FROM v_table WHERE field = 'test' AND row BETWEEN 10 AND 20

WHERE becomes limited to those data which are in the rows between 10 and 20 (instead of searching the whole dataset and limiting the output).

jQuery click event not working after adding class

on document ready event there is no a tag with class tabclick. so you have to bind click event dynamically when you are adding tabclick class. please this code:

$("a.applicationdata").click(function() {
    var appid = $(this).attr("id");

   $('#gentab a').addClass("tabclick")
    .click(function() {
          var liId = $(this).parent("li").attr("id");
         alert(liId);        
      });


 $('#gentab a').attr('href', '#datacollector');

});

How to get Javascript Select box's selected text

I know no-one is asking for a jQuery solution here, but might be worth mentioning that with jQuery you can just ask for:$('#selectorid').val()

How to List All Redis Databases?

There is no command to do it (like you would do it with MySQL for instance). The number of Redis databases is fixed, and set in the configuration file. By default, you have 16 databases. Each database is identified by a number (not a name).

You can use the following command to know the number of databases:

CONFIG GET databases
1) "databases"
2) "16"

You can use the following command to list the databases for which some keys are defined:

INFO keyspace
# Keyspace
db0:keys=10,expires=0
db1:keys=1,expires=0
db3:keys=1,expires=0

Please note that you are supposed to use the "redis-cli" client to run these commands, not telnet. If you want to use telnet, then you need to run these commands formatted using the Redis protocol.

For instance:

*2
$4
INFO
$8
keyspace

$79
# Keyspace
db0:keys=10,expires=0
db1:keys=1,expires=0
db3:keys=1,expires=0

You can find the description of the Redis protocol here: http://redis.io/topics/protocol

Thin Black Border for a Table

Style the td and th instead

td, th {
    border: 1px solid black;
}

And also to make it so there is no spacing between cells use:

table {
    border-collapse: collapse;
}

(also note, you have border-style: none; which should be border-style: solid;)

See an example here: http://jsfiddle.net/KbjNr/

Returning a stream from File.OpenRead()

You forgot to reset the position of the memory stream:

private void Test()
{            
    System.IO.MemoryStream data = new System.IO.MemoryStream();
    System.IO.Stream str = TestStream();

    str.CopyTo(data);
    // Reset memory stream
    data.Seek(0, SeekOrigin.Begin);
    byte[] buf = new byte[data.Length];
    data.Read(buf, 0, buf.Length);                       
}

Update:

There is one more thing to note: It usually pays not to ignore the return values of methods. A more robust implementation should check how many bytes have been read after the call returns:

private void Test()
{            
    using(MemoryStream data = new MemoryStream())
    {
        using(Stream str = TestStream())
        {
           str.CopyTo(data);
        }
        // Reset memory stream
        data.Seek(0, SeekOrigin.Begin);
        byte[] buf = new byte[data.Length];
        int bytesRead = data.Read(buf, 0, buf.Length);

        Debug.Assert(bytesRead == data.Length, 
                    String.Format("Expected to read {0} bytes, but read {1}.",
                        data.Length, bytesRead));
    }                     
}

assign value using linq

It can be done this way as well

foreach (Company company in listofCompany.Where(d => d.Id = 1)).ToList())
                {
                    //do your stuff here
                    company.Id= 2;
                    company.Name= "Sample"
                }

Collection that allows only unique items in .NET?

From the HashSet<T> page on MSDN:

The HashSet(Of T) class provides high-performance set operations. A set is a collection that contains no duplicate elements, and whose elements are in no particular order.

(emphasis mine)

How to write a cron that will run a script every day at midnight?

from the man page

linux$ man -S 5 crontab

   cron(8) examines cron entries once every minute.

   The time and date fields are:

          field          allowed values
          -----          --------------
          minute         0-59
          hour           0-23
          day of month   1-31
          month          1-12 (or names, see below)
          day of week    0-7 (0 or 7 is Sun, or use names)
   ...
   # run five minutes after midnight, every day
   5 0 * * *       $HOME/bin/daily.job >> $HOME/tmp/out 2>&1
   ...

It is good to note the special "nicknames" that can be used (documented in the man page), particularly "@reboot" which has no time and date alternative.

   # Run once after reboot.
   @reboot         /usr/local/sbin/run_only_once_after_reboot.sh

You can also use this trick to run your cron job multiple times per minute.

   # Run every minute at 0, 20, and 40 second intervals
   * * * * *       sleep 00; /usr/local/sbin/run_3times_per_minute.sh
   * * * * *       sleep 20; /usr/local/sbin/run_3times_per_minute.sh
   * * * * *       sleep 40; /usr/local/sbin/run_3times_per_minute.sh

To add a cron job, you can do one of three things:

  1. add a command to a user's crontab, as shown above (and from the crontab, section 5, man page).

    • edit a user's crontab as root with crontab -e -u <username>
    • or edit the current user's crontab with just crontab -e
    • You can set the editor with the EDITOR environment variable
      • env EDITOR=nano crontab -e -u <username>
      • or set the value of EDITOR for your entire shell session
        1. export EDITOR=vim
        2. crontab -e
    • Make scripts executable with chmod a+x <file>


  1. create a script/program as a cron job, and add it to the system's anacron /etc/cron.*ly directories

    • anacron /etc/cron.*ly directories:
      • /etc/cron.daily
      • /etc/cron.hourly
      • /etc/cron.monthly
      • /etc/cron.weekly
    • as in:
      • /etc/cron.daily/script_runs_daily.sh
      • chmod a+x /etc/cron.daily/script_runs_daily.sh -- make it executable
    • See also the anacron man page: man anacron
    • Make scripts executable with chmod a+x <file>
    • When do these cron.*ly script run?
      • For RHEL/CentOS 5.x, they are configured in /etc/crontab or /etc/anacrontab to run at a set time
      • RHEL/CentOS 6.x+ and Fedora 17+ Linux systems only define this in /etc/anacrontab, and define cron.hourly in /etc/cron.d/0hourly


  1. Or, One can create system crontables in /etc/cron.d.

    • The previously described crontab syntax (with additionally providing a user to execute each job as) is put into a file, and the file is dropped into the /etc/cron.d directory.
    • These are easy to manage in system packaging (e.g. RPM packages), so may usually be application specific.
    • The syntax difference is that a user must be specified for the cron job after the time/date fields and before the command to execute.
    • The files added to /etc/cron.d do not need to be executable.
    • Here is an example job that is executed as the user someuser, and the use of /bin/bash as the shell is forced.


   File: /etc/cron.d/myapp-cron
   # use /bin/bash to run commands, no matter what /etc/passwd says
   SHELL=/bin/bash
   # Execute a nightly (11:00pm) cron job to scrub application records
   00 23 * * * someuser /opt/myapp/bin/scrubrecords.php

Java: How can I compile an entire directory structure of code ?

The already existing answers seem to only concern oneself with the *.java files themselves and not how to easily do it with library files that might be needed for the build.

A nice one-line situation which recursively gets all *.java files as well as includes *.jar files necessary for building is:

javac -cp ".:lib/*" -d bin $(find ./src/* | grep .java)

Here the bin file is the destination of class files, lib (and potentially the current working directory) contain the library files and all the java files in the src directory and beneath are compiled.

Merge trunk to branch in Subversion

Is there something that prevents you from merging all revisions on trunk since the last merge?

svn merge -rLastRevisionMergedFromTrunkToBranch:HEAD url/of/trunk path/to/branch/wc

should work just fine. At least if you want to merge all changes on trunk to your branch.

How do I call ::CreateProcess in c++ to launch a Windows executable?

If you application is a Windows GUI application then using the code below to do the waiting is not ideal as messages for your application will not be getting processing. To the user it will look like your application has hung.

WaitForSingleObject(&processInfo.hProcess, INFINITE)

Something like the untested code below might be better as it will keep processing the windows message queue and your application will remain responsive:

//-- wait for the process to finish
while (true)
{
  //-- see if the task has terminated
  DWORD dwExitCode = WaitForSingleObject(ProcessInfo.hProcess, 0);

  if (   (dwExitCode == WAIT_FAILED   )
      || (dwExitCode == WAIT_OBJECT_0 )
      || (dwExitCode == WAIT_ABANDONED) )
  {
    DWORD dwExitCode;

    //-- get the process exit code
    GetExitCodeProcess(ProcessInfo.hProcess, &dwExitCode);

    //-- the task has ended so close the handle
    CloseHandle(ProcessInfo.hThread);
    CloseHandle(ProcessInfo.hProcess);

    //-- save the exit code
    lExitCode = dwExitCode;

    return;
  }
  else
  {
    //-- see if there are any message that need to be processed
    while (PeekMessage(&message.msg, 0, 0, 0, PM_NOREMOVE))
    {
      if (message.msg.message == WM_QUIT)
      {
        return;
      }

      //-- process the message queue
      if (GetMessage(&message.msg, 0, 0, 0))
      {
        //-- process the message
        TranslateMessage(&pMessage->msg);
        DispatchMessage(&pMessage->msg);
      }
    }
  }
}

Python spacing and aligning strings

You can use expandtabs to specify the tabstop, like this:

>>> print ('Location:'+'10-10-10-10'+'\t'+ 'Revision: 1'.expandtabs(30))
>>> print ('District: Tower'+'\t'+ 'Date: May 16, 2012'.expandtabs(30))
#Output:
Location:10-10-10-10          Revision: 1
District: Tower               Date: May 16, 2012

How does one target IE7 and IE8 with valid CSS?

I would recommend looking into conditional comments and making a separate sheet for the IEs you are having problems with.

 <!--[if IE 7]>
   <link rel="stylesheet" type="text/css" href="ie7.css" />
 <![endif]-->

Cannot use a leading ../ to exit above the top directory

In my case it turned out to be commented out HTML in a master page!

Who knew that commented out HTML such as this were actually interpreted by ASP.NET!

<!--
<link rel="icon" href="../../favicon.ico">
-->

Combine Multiple child rows into one row MYSQL

If you know you're going to have a limited number of max options then I would try this (example for max of 4 options per order):

Select OI.ID, OI.Item_Name, OO1.Value, OO2.Value, OO3.Value, OO4.Value

FROM Ordered_Items OI
    LEFT JOIN Ordered_Options OO1 ON OO1.Ordered_Item_ID = OI.ID
    LEFT JOIN Ordered_Options OO2 ON OO2.Ordered_Item_ID = OI.ID AND OO2.ID != OO1.ID
    LEFT JOIN Ordered_Options OO3 ON OO3.Ordered_Item_ID = OI.ID AND OO3.ID != OO1.ID AND OO3.ID != OO2.ID
    LEFT JOIN Ordered_Options OO4 ON OO4.Ordered_Item_ID = OI.ID AND OO4.ID != OO1.ID AND OO4.ID != OO2.ID AND OO4.ID != OO3.ID

GROUP BY OI.ID, OI.Item_Name

The group by condition gets rid of all of the duplicates that you would otherwise get. I've just implemented something similar on a site I'm working on where I knew I'd always have 1 or 2 matched in my child table, and I wanted to make sure I only had 1 row for each parent item.

java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;

java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;

That method was added in Servlet 2.5.

So this problem can have at least 3 causes:

  1. The servlet container does not support Servlet 2.5.
  2. The web.xml is not declared conform Servlet 2.5 or newer.
  3. The webapp's runtime classpath is littered with servlet container specific JAR files of a different servlet container make/version which does not support Servlet 2.5.

To solve it,

  1. Make sure that your servlet container supports at least Servlet 2.5. That are at least Tomcat 6, Glassfish 2, JBoss AS 4.1, etcetera. Tomcat 5.5 for example supports at highest Servlet 2.4. If you can't upgrade Tomcat, then you'd need to downgrade Spring to a Servlet 2.4 compatible version.
  2. Make sure that the root declaration of web.xml complies Servlet 2.5 (or newer, at least the highest whatever your target runtime supports). For an example, see also somewhere halfway our servlets wiki page.
  3. Make sure that you don't have any servlet container specific libraries like servlet-api.jar or j2ee.jar in /WEB-INF/lib or even worse, the JRE/lib or JRE/lib/ext. They do not belong there. This is a pretty common beginner's mistake in an attempt to circumvent compilation errors in an IDE, see also How do I import the javax.servlet API in my Eclipse project?.

How to load/reference a file as a File instance from the classpath

Or use directly the InputStream of the resource using the absolute CLASSPATH path (starting with the / slash character):


getClass().getResourceAsStream("/com/path/to/file.txt");

Or relative CLASSPATH path (when the class you are writing is in the same Java package as the resource file itself, i.e. com.path.to):


getClass().getResourceAsStream("file.txt");

How do I abort the execution of a Python script?

To exit a script you can use,

import sys
sys.exit()

You can also provide an exit status value, usually an integer.

import sys
sys.exit(0)

Exits with zero, which is generally interpreted as success. Non-zero codes are usually treated as errors. The default is to exit with zero.

import sys
sys.exit("aa! errors!")

Prints "aa! errors!" and exits with a status code of 1.

There is also an _exit() function in the os module. The sys.exit() function raises a SystemExit exception to exit the program, so try statements and cleanup code can execute. The os._exit() version doesn't do this. It just ends the program without doing any cleanup or flushing output buffers, so it shouldn't normally be used.

The Python docs indicate that os._exit() is the normal way to end a child process created with a call to os.fork(), so it does have a use in certain circumstances.

How to Bulk Insert from XLSX file extension?

you can save the xlsx file as a tab-delimited text file and do

BULK INSERT TableName
        FROM 'C:\SomeDirectory\my table.txt'
            WITH
    (
                FIELDTERMINATOR = '\t',
                ROWTERMINATOR = '\n'
    )
GO

How can I convert this foreach code to Parallel.ForEach?

These lines Worked for me.

string[] lines = File.ReadAllLines(txtProxyListPath.Text);
var options = new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount * 10 };
Parallel.ForEach(lines , options, (item) =>
{
 //My Stuff
});

SQL Server Management Studio missing

Did you include "Management Tools" as a chosen option during setup?

enter image description here

Ensure this option is selected, and SQL Server Management Studio will be installed on the machine.

How to get the size of a range in Excel

The overall dimensions of a range are in its Width and Height properties.

Dim r As Range
Set r = ActiveSheet.Range("A4:H12")

Debug.Print r.Width
Debug.Print r.Height

How to get address location from latitude and longitude in Google Map.?

You have to make one ajax call to get the required result, in this case you can use Google API to get the same

http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=true/false

Build this kind of url and replace the lat long with the one you want to. do the call and response will be in JSON, parse the JSON and you will get the complete address up to street level

Get 2 Digit Number For The Month

For me the quickest solution was

DATE_FORMAT(CURDATE(),'%m')

How to find out if a file exists in C# / .NET?

I use WinForms and my way to use File.Exists(string path) is the next one:

public bool FileExists(string fileName)
{
    var workingDirectory = Environment.CurrentDirectory;
    var file = $"{workingDirectory}\{fileName}";
    return File.Exists(file);
}

fileName must include the extension like myfile.txt

Sending email with PHP from an SMTP server

For another approach, you can take a file like this:

From: Sunday <[email protected]>
To: Monday <[email protected]>
Subject: Day

Tuesday Wednesday

and send like this:

<?php
$a1 = ['[email protected]'];
$r1 = fopen('a.txt', 'r');
$r2 = curl_init('smtps://smtp.gmail.com');
curl_setopt($r2, CURLOPT_MAIL_RCPT, $a1);
curl_setopt($r2, CURLOPT_NETRC, true);
curl_setopt($r2, CURLOPT_READDATA, $r1);
curl_setopt($r2, CURLOPT_UPLOAD, true);
curl_exec($r2);

https://php.net/function.curl-setopt

How to right-align form input boxes?

Try use this:

input {
  clear: both;
  float: right;
  margin-bottom: 10px;
  width: 100px;
}

The role of #ifdef and #ifndef

"#if one" means that if "#define one" has been written "#if one" is executed otherwise "#ifndef one" is executed.

This is just the C Pre-Processor (CPP) Directive equivalent of the if, then, else branch statements in the C language.

i.e. if {#define one} then printf("one evaluates to a truth "); else printf("one is not defined "); so if there was no #define one statement then the else branch of the statement would be executed.

How to construct a WebSocket URI relative to the page URI?

Using the Window.URL API - https://developer.mozilla.org/en-US/docs/Web/API/Window/URL

Works with http(s), ports etc.

var url = new URL('/path/to/websocket', window.location.href);

url.protocol = url.protocol.replace('http', 'ws');

url.href // => ws://www.example.com:9999/path/to/websocket

Using $_POST to get select option value from HTML

Depends on if the form that the select is contained in has the method set to "get" or "post".

If <form method="get"> then the value of the select will be located in the super global array $_GET['taskOption'].

If <form method="post"> then the value of the select will be located in the super global array $_POST['taskOption'].

To store it into a variable you would:

$option = $_POST['taskOption']

A good place for more information would be the PHP manual: http://php.net/manual/en/tutorial.forms.php

Replace all occurrences of a String using StringBuilder?

Well, you can write a loop:

public static void replaceAll(StringBuilder builder, String from, String to)
{
    int index = builder.indexOf(from);
    while (index != -1)
    {
        builder.replace(index, index + from.length(), to);
        index += to.length(); // Move to the end of the replacement
        index = builder.indexOf(from, index);
    }
}

Note that in some cases it may be faster to use lastIndexOf, working from the back. I suspect that's the case if you're replacing a long string with a short one - so when you get to the start, any replacements have less to copy. Anyway, this should give you a starting point.

Why is the Java main method static?

The public keyword is an access modifier, which allows the programmer to control the visibility of class members. When a class member is preceded by public, then that member may be accessed by code outside the class in which it is declared.

The opposite of public is private, which prevents a member from being used by code defined outside of its class.

In this case, main() must be declared as public, since it must be called by code outside of its class when the program is started.

The keyword static allows main() to be called without having to instantiate a particular instance of the class. This is necessary since main() is called by the Java interpreter before any objects are made.

The keyword void simply tells the compiler that main() does not return a value.

How to use a global array in C#?

Your class shoud look something like this:

class Something {     int[] array; //global array, replace type of course     void function1() {        array = new int[10]; //let say you declare it here that will be 10 integers in size     }     void function2() {        array[0] = 12; //assing value at index 0 to 12.     } } 

That way you array will be accessible in both functions. However, you must be careful with global stuff, as you can quickly overwrite something.

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

There is also second parameter on JSON.stringify. So, more elegant solution would be:

function escape (key, val) {
    if (typeof(val)!="string") return val;
    return val
      .replace(/[\"]/g, '\\"')
      .replace(/[\\]/g, '\\\\')
      .replace(/[\/]/g, '\\/')
      .replace(/[\b]/g, '\\b')
      .replace(/[\f]/g, '\\f')
      .replace(/[\n]/g, '\\n')
      .replace(/[\r]/g, '\\r')
      .replace(/[\t]/g, '\\t')
    ; 
}

var myJSONString = JSON.stringify(myJSON,escape);

Ignore duplicates when producing map using streams

As said in JavaDocs:

If the mapped keys contains duplicates (according to Object.equals(Object)), an IllegalStateException is thrown when the collection operation is performed. If the mapped keys may have duplicates, use toMap(Function keyMapper, Function valueMapper, BinaryOperator mergeFunction) instead.

So you should use toMap(Function keyMapper, Function valueMapper, BinaryOperator mergeFunction) instead. Just provide a merge function, that will determine which one of duplicates is put in the map.

For example, if you don't care which one, just call

Map<String, String> phoneBook = 
        people.stream()
              .collect(Collectors.toMap(Person::getName, 
                                        Person::getAddress, 
                                        (a1, a2) -> a1));

filter out multiple criteria using excel vba

I think (from experimenting - MSDN is unhelpful here) that there is no direct way of doing this. Setting Criteria1 to an Array is equivalent to using the tick boxes in the dropdown - as you say it will only filter a list based on items that match one of those in the array.

Interestingly, if you have the literal values "<>A" and "<>B" in the list and filter on these the macro recorder comes up with

Range.AutoFilter Field:=1, Criteria1:="=<>A", Operator:=xlOr, Criteria2:="=<>B"

which works. But if you then have the literal value "<>C" as well and you filter for all three (using tick boxes) while recording a macro, the macro recorder replicates precisely your code which then fails with an error. I guess I'd call that a bug - there are filters you can do using the UI which you can't do with VBA.

Anyway, back to your problem. It is possible to filter values not equal to some criteria, but only up to two values which doesn't work for you:

Range("$A$1:$A$9").AutoFilter Field:=1, Criteria1:="<>A", Criteria2:="<>B", Operator:=xlAnd

There are a couple of workarounds possible depending on the exact problem:

  1. Use a "helper column" with a formula in column B and then filter on that - e.g. =ISNUMBER(A2) or =NOT(A2="A", A2="B", A2="C") then filter on TRUE
  2. If you can't add a column, use autofilter with Criteria1:=">-65535" (or a suitable number lower than any you expect) which will filter out non-numeric values - assuming this is what you want
  3. Write a VBA sub to hide rows (not exactly the same as an autofilter but it may suffice depending on your needs).

For example:

Public Sub hideABCRows(rangeToFilter As Range)
  Dim oCurrentCell As Range
  On Error GoTo errHandler

  Application.ScreenUpdating = False
  For Each oCurrentCell In rangeToFilter.Cells
    If oCurrentCell.Value = "A" Or oCurrentCell.Value = "B" Or oCurrentCell.Value = "C" Then
      oCurrentCell.EntireRow.Hidden = True
    End If
  Next oCurrentCell

  Application.ScreenUpdating = True
  Exit Sub

errHandler:
    Application.ScreenUpdating = True
End Sub

How to get table list in database, using MS SQL 2008?

Answering the question in your title, you can query sys.tables or sys.objects where type = 'U' to check for the existence of a table. You can also use OBJECT_ID('table_name', 'U'). If it returns a non-null value then the table exists:

IF (OBJECT_ID('dbo.My_Table', 'U') IS NULL)
BEGIN
    CREATE TABLE dbo.My_Table (...)
END

You can do the same for databases with DB_ID():

IF (DB_ID('My_Database') IS NULL)
BEGIN
    CREATE DATABASE My_Database
END

If you want to create the database and then start using it, that needs to be done in separate batches. I don't know the specifics of your case, but there shouldn't be many cases where this isn't possible. In a SQL script you can use GO statements. In an application it's easy enough to send across a new command after the database is created.

The only place that you might have an issue is if you were trying to do this in a stored procedure and creating databases on the fly like that is usually a bad idea.

If you really need to do this in one batch, you can get around the issue by using EXEC to get around the parsing error of the database not existing:

CREATE DATABASE Test_DB2

IF (OBJECT_ID('Test_DB2.dbo.My_Table', 'U') IS NULL)
BEGIN
    EXEC('CREATE TABLE Test_DB2.dbo.My_Table (my_id INT)')
END

EDIT: As others have suggested, the INFORMATION_SCHEMA.TABLES system view is probably preferable since it is supposedly a standard going forward and possibly between RDBMSs.

How can I convert a zero-terminated byte array to string?

For example,

package main

import "fmt"

func CToGoString(c []byte) string {
    n := -1
    for i, b := range c {
        if b == 0 {
            break
        }
        n = i
    }
    return string(c[:n+1])
}

func main() {
    c := [100]byte{'a', 'b', 'c'}
    fmt.Println("C: ", len(c), c[:4])
    g := CToGoString(c[:])
    fmt.Println("Go:", len(g), g)
}

Output:

C:  100 [97 98 99 0]
Go: 3 abc

Bootstrap table striped: How do I change the stripe background colour?

.table-striped > tbody > tr:nth-child(2n+1) > td, .table-striped > tbody > tr:nth-child(2n+1) > th {
   background-color: red;
}

change this line in bootstrap.css or you could use (odd) or (even) instead of (2n+1)

$watch'ing for data changes in an Angular directive

You need to enable deep object dirty checking. By default angular only checks the reference of the top level variable that you watch.

App.directive('d3Visualization', function() {
    return {
        restrict: 'E',
        scope: {
            val: '='
        },
        link: function(scope, element, attrs) {
            scope.$watch('val', function(newValue, oldValue) {
                if (newValue)
                    console.log("I see a data change!");
            }, true);
        }
    }
});

see Scope. The third parameter of the $watch function enables deep dirty checking if it's set to true.

Take note that deep dirty checking is expensive. So if you just need to watch the children array instead of the whole data variable the watch the variable directly.

scope.$watch('val.children', function(newValue, oldValue) {}, true);

version 1.2.x introduced $watchCollection

Shallow watches the properties of an object and fires whenever any of the properties change (for arrays, this implies watching the array items; for object maps, this implies watching the properties)

scope.$watchCollection('val.children', function(newValue, oldValue) {});

R - Concatenate two dataframes?

Try the plyr package:

rbind.fill(a,b,c)

Display A Popup Only Once Per User

*Note : This will show popup once per browser as the data is stored in browser memory.

Try HTML localStorage.

Methods :

  • localStorage.getItem('key');
  • localStorage.setItem('key','value');

$j(document).ready(function() {
    if(localStorage.getItem('popState') != 'shown'){
        $j('#popup').delay(2000).fadeIn();
        localStorage.setItem('popState','shown')
    }

    $j('#popup-close, #popup').click(function() // You are clicking the close button
    {
        $j('#popup').fadeOut(); // Now the pop up is hidden.
    });
});

Working Demo

LinearLayout not expanding inside a ScrollView

I know this post is very old, For those who don't want to use android:fillViewport="true" because it sometimes doesn't bring up the edittext above keyboard. Use Relative layout instead of LinearLayout it solves the purpose.

Do you have to include <link rel="icon" href="favicon.ico" type="image/x-icon" />?

Simply adding it to the root folder works after a fashion, but I've found that if I need to change the favicon, it can take days to update... even a cache refresh doesn't do the trick.

Javac is not found

You don't have jdk1.7.0_17 in your PATH - check again. There is only JRE which may not contain 'javac' compiler.

Besides it is best to set JAVA_HOME variable, and then include it in PATH.

How can I reference a dll in the GAC from Visual Studio?

In VS, right click your project, select "Add Reference...", and you will see all the namespaces that exist in your GAC. Choose Microsoft.SqlServer.Management.RegisteredServers and click OK, and you should be good to go

EDIT:

That is the way you want to do this most of the time. However, after a bit of poking around I found this issue on MS Connect. MS says it is a known deployment issue, and they don't have a work around. The guy says if he copies the dll from the GAC folder and drops it in his bin, it works.

'heroku' does not appear to be a git repository

If this error pops up, its because there is no remote named Heroku. When you do a Heroku create, if the git remote doesn’t already exist, we automatically create one (assuming you are in a git repo). To view your remotes type in:

git remote -v”. # For an app called ‘appname’ you will see the following:

$ git remote -v
heroku [email protected]:appname.git (fetch)
heroku [email protected]:appname.git (push)

If you see a remote for your app, you can just “git push master” and replace with the actual remote name.

If it’s missing, you can add the remote with the following command:

git remote add heroku [email protected]:appname.git

If you’ve already added a remote called Heroku, you may get an error like this:

fatal: remote heroku already exists.

so, then remove the existing remote and add it again with the above command:

git remote rm heroku

Hope this helps…

PHP Create and Save a txt file to root directory

If you are running PHP on Apache then you can use the enviroment variable called DOCUMENT_ROOT. This means that the path is dynamic, and can be moved between servers without messing about with the code.

<?php
  $fileLocation = getenv("DOCUMENT_ROOT") . "/myfile.txt";
  $file = fopen($fileLocation,"w");
  $content = "Your text here";
  fwrite($file,$content);
  fclose($file);
?>

How to delete row in gridview using rowdeleting event?

     protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int index = GridView1.SelectedIndex;
        int id = Convert.ToInt32(GridView1.DataKeys[index].Value);
        SqlConnection con = new SqlConnection(str);
        SqlCommand com = new SqlCommand("spDelete", con);
        com.Parameters.AddWithValue("@PatientId", id);
        con.Open();
        com.ExecuteNonQuery();

Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index

How do you change Background for a Button MouseOver in WPF?

To remove the default MouseOver behaviour on the Button you will need to modify the ControlTemplate. Changing your Style definition to the following should do the trick:

<Style TargetType="{x:Type Button}">
    <Setter Property="Background" Value="Green"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <Border Background="{TemplateBinding Background}" BorderBrush="Black" BorderThickness="1">
                    <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
    <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
            <Setter Property="Background" Value="Red"/>
        </Trigger>
    </Style.Triggers>
</Style>

EDIT: It's a few years late, but you are actually able to set the border brush inside of the border that is in there. Idk if that was pointed out but it doesn't seem like it was...

Redeploy alternatives to JRebel

I have written an article about DCEVM: Spring-mvc + Velocity + DCEVM

I think it's worth it, since my environment is running without any problems.

HEAD and ORIG_HEAD in Git

HEAD is (direct or indirect, i.e. symbolic) reference to the current commit. It is a commit that you have checked in the working directory (unless you made some changes, or equivalent), and it is a commit on top of which "git commit" would make a new one. Usually HEAD is symbolic reference to some other named branch; this branch is currently checked out branch, or current branch. HEAD can also point directly to a commit; this state is called "detached HEAD", and can be understood as being on unnamed, anonymous branch.

And @ alone is a shortcut for HEAD, since Git 1.8.5

ORIG_HEAD is previous state of HEAD, set by commands that have possibly dangerous behavior, to be easy to revert them. It is less useful now that Git has reflog: HEAD@{1} is roughly equivalent to ORIG_HEAD (HEAD@{1} is always last value of HEAD, ORIG_HEAD is last value of HEAD before dangerous operation).

For more information read git(1) manpage / [gitrevisions(7) manpage][git-revisions], Git User's Manual, the Git Community Book and Git Glossary

Generating CSV file for Excel, how to have a newline inside a value

On a PC, ASCII character #10 is what you want to place a newline within a value.

Once you get it into Excel, however, you need to make sure word wrap is turned on for the multi-line cells or the newline will appear as a square box.

jQuery get content between <div> tags

jQuery has two methods

// First. Get content as HTML
$("#my_div_id").html();

// Second. Get content as text
$("#my_div_id").text();

How to delete Project from Google Developers Console

Simply go to https://console.developers.google.com/iam-admin/projects you must be signed in of course. There you will see the all your projects google console projects so just select the project you want to delete, and click delete project option which is shown at the top of the table. I have provided the screenshothere

How do I decode a string with escaped unicode?

I don't have enough rep to put this under comments to the existing answers:

unescape is only deprecated for working with URIs (or any encoded utf-8) which is probably the case for most people's needs. encodeURIComponent converts a js string to escaped UTF-8 and decodeURIComponent only works on escaped UTF-8 bytes. It throws an error for something like decodeURIComponent('%a9'); // error because extended ascii isn't valid utf-8 (even though that's still a unicode value), whereas unescape('%a9'); // © So you need to know your data when using decodeURIComponent.

decodeURIComponent won't work on "%C2" or any lone byte over 0x7f because in utf-8 that indicates part of a surrogate. However decodeURIComponent("%C2%A9") //gives you © Unescape wouldn't work properly on that // © AND it wouldn't throw an error, so unescape can lead to buggy code if you don't know your data.

how to use "tab space" while writing in text file

You can use \t to create a tab in a file.

PHP function overloading

Sadly there is no overload in PHP as it is done in C#. But i have a little trick. I declare arguments with default null values and check them in a function. That way my function can do different things depending on arguments. Below is simple example:

public function query($queryString, $class = null) //second arg. is optional
{
    $query = $this->dbLink->prepare($queryString);
    $query->execute();

    //if there is second argument method does different thing
    if (!is_null($class)) { 
        $query->setFetchMode(PDO::FETCH_CLASS, $class);
    }

    return $query->fetchAll();
}

//This loads rows in to array of class
$Result = $this->query($queryString, "SomeClass");
//This loads rows as standard arrays
$Result = $this->query($queryString);

How does one sum only those rows in excel not filtered out?

You need to use the SUBTOTAL function. The SUBTOTAL function ignores rows that have been excluded by a filter.

The formula would look like this:

=SUBTOTAL(9,B1:B20)

The function number 9, tells it to use the SUM function on the data range B1:B20.

If you are 'filtering' by hiding rows, the function number should be updated to 109.

=SUBTOTAL(109,B1:B20)

The function number 109 is for the SUM function as well, but hidden rows are ignored.

Using Java 8's Optional with Stream::flatMap

Late to the party, but what about

things.stream()
    .map(this::resolve)
    .filter(Optional::isPresent)
    .findFirst().get();

You can get rid of the last get() if you create a util method to convert optional to stream manually:

things.stream()
    .map(this::resolve)
    .flatMap(Util::optionalToStream)
    .findFirst();

If you return stream right away from your resolve function, you save one more line.

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

The Host property will return the domain name you used when accessing the site. So, in your development environment, since you're requesting

http://localhost:950/m/pages/Searchresults.aspx?search=knife&filter=kitchen

It's returning localhost. You can break apart your URL like so:

Protocol: http
Host: localhost
Port: 950
PathAndQuery: /m/pages/SearchResults.aspx?search=knight&filter=kitchen

Disable Tensorflow debugging information

To anyone still struggling to get the os.environ solution to work as I was, check that this is placed before you import tensorflow in your script, just like mwweb's answer:

import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'  # or any {'0', '1', '2'}
import tensorflow as tf

Add ... if string is too long PHP

I use this solution on my website. If $str is shorter, than $max, it will remain unchanged. If $str has no spaces among first $max characters, it will be brutally cut at $max position. Otherwise 3 dots will be added after the last whole word.

function short_str($str, $max = 50) {
    $str = trim($str);
    if (strlen($str) > $max) {
        $s_pos = strpos($str, ' ');
        $cut = $s_pos === false || $s_pos > $max;
        $str = wordwrap($str, $max, ';;', $cut);
        $str = explode(';;', $str);
        $str = $str[0] . '...';
    }
    return $str;
}

How to check null objects in jQuery

no matter what you selection is the function $() always returns a jQuery object so that cant be used to test. The best way yet (if not the only) is to use the size() function or the native length property as explained above.

if ( $('selector').size() ) {...}                   

Redis strings vs Redis hashes to represent JSON: efficiency?

This article can provide a lot of insight here: http://redis.io/topics/memory-optimization

There are many ways to store an array of Objects in Redis (spoiler: I like option 1 for most use cases):

  1. Store the entire object as JSON-encoded string in a single key and keep track of all Objects using a set (or list, if more appropriate). For example:

    INCR id:users
    SET user:{id} '{"name":"Fred","age":25}'
    SADD users {id}
    

    Generally speaking, this is probably the best method in most cases. If there are a lot of fields in the Object, your Objects are not nested with other Objects, and you tend to only access a small subset of fields at a time, it might be better to go with option 2.

    Advantages: considered a "good practice." Each Object is a full-blown Redis key. JSON parsing is fast, especially when you need to access many fields for this Object at once. Disadvantages: slower when you only need to access a single field.

  2. Store each Object's properties in a Redis hash.

    INCR id:users
    HMSET user:{id} name "Fred" age 25
    SADD users {id}
    

    Advantages: considered a "good practice." Each Object is a full-blown Redis key. No need to parse JSON strings. Disadvantages: possibly slower when you need to access all/most of the fields in an Object. Also, nested Objects (Objects within Objects) cannot be easily stored.

  3. Store each Object as a JSON string in a Redis hash.

    INCR id:users
    HMSET users {id} '{"name":"Fred","age":25}'
    

    This allows you to consolidate a bit and only use two keys instead of lots of keys. The obvious disadvantage is that you can't set the TTL (and other stuff) on each user Object, since it is merely a field in the Redis hash and not a full-blown Redis key.

    Advantages: JSON parsing is fast, especially when you need to access many fields for this Object at once. Less "polluting" of the main key namespace. Disadvantages: About same memory usage as #1 when you have a lot of Objects. Slower than #2 when you only need to access a single field. Probably not considered a "good practice."

  4. Store each property of each Object in a dedicated key.

    INCR id:users
    SET user:{id}:name "Fred"
    SET user:{id}:age 25
    SADD users {id}
    

    According to the article above, this option is almost never preferred (unless the property of the Object needs to have specific TTL or something).

    Advantages: Object properties are full-blown Redis keys, which might not be overkill for your app. Disadvantages: slow, uses more memory, and not considered "best practice." Lots of polluting of the main key namespace.

Overall Summary

Option 4 is generally not preferred. Options 1 and 2 are very similar, and they are both pretty common. I prefer option 1 (generally speaking) because it allows you to store more complicated Objects (with multiple layers of nesting, etc.) Option 3 is used when you really care about not polluting the main key namespace (i.e. you don't want there to be a lot of keys in your database and you don't care about things like TTL, key sharding, or whatever).

If I got something wrong here, please consider leaving a comment and allowing me to revise the answer before downvoting. Thanks! :)

What is size_t in C?

In general, if you are starting at 0 and going upward, always use an unsigned type to avoid an overflow taking you into a negative value situation. This is critically important, because if your array bounds happens to be less than the max of your loop, but your loop max happens to be greater than the max of your type, you will wrap around negative and you may experience a segmentation fault (SIGSEGV). So, in general, never use int for a loop starting at 0 and going upwards. Use an unsigned.

Extract substring using regexp in plain bash

Using pure :

$ cat file.txt
US/Central - 10:26 PM (CST)
$ while read a b time x; do [[ $b == - ]] && echo $time; done < file.txt

another solution with bash regex :

$ [[ "US/Central - 10:26 PM (CST)" =~ -[[:space:]]*([0-9]{2}:[0-9]{2}) ]] &&
    echo ${BASH_REMATCH[1]}

another solution using grep and look-around advanced regex :

$ echo "US/Central - 10:26 PM (CST)" | grep -oP "\-\s+\K\d{2}:\d{2}"

another solution using sed :

$ echo "US/Central - 10:26 PM (CST)" |
    sed 's/.*\- *\([0-9]\{2\}:[0-9]\{2\}\).*/\1/'

another solution using perl :

$ echo "US/Central - 10:26 PM (CST)" |
    perl -lne 'print $& if /\-\s+\K\d{2}:\d{2}/'

and last one using awk :

$ echo "US/Central - 10:26 PM (CST)" |
    awk '{for (i=0; i<=NF; i++){if ($i == "-"){print $(i+1);exit}}}'

How to escape comma and double quote at same time for CSV file?

"cell one","cell "" two","cell "" ,three"

Save this to csv file and see the results, so double quote is used to escape itself

Important Note

"cell one","cell "" two", "cell "" ,three"

will give you a different result because there is a space after the comma, and that will be treated as "

wait() or sleep() function in jquery?

setTimeout will execute some code after a delay of some period of time (measured in milliseconds). However, an important note: because of the nature of javascript, the rest of the code continues to run after the timer is setup:

$('#someid').addClass("load");

setTimeout(function(){
  $('#someid').addClass("done");
}, 2000);

// Any code here will execute immediately after the 'load' class is added to the element.

How to terminate a window in tmux?

<Prefix> & for killing a window

<Prefix> x for killing a pane

If there is only one pane (i.e. the window is not split into multiple panes, <Prefix> x would kill the window)

As always iterated, <Prefix> is generally CTRL+b. (I think for beginner questions, we can just say CTRL+b all the time, and not talk about prefix at all, but anyway :) )

Select distinct using linq

Using morelinq you can use DistinctBy:

myList.DistinctBy(x => x.id);

Otherwise, you can use a group:

myList.GroupBy(x => x.id)
      .Select(g => g.First());

How to check if a file exists from a url

Do a request with curl and see if it returns a 404 status code. Do the request using the HEAD request method so it only returns the headers without a body.

User Get-ADUser to list all properties and export to .csv

@AnsgarWiechers - it's not my experience that querying everything and then pruning the result is more efficient when you're doing a targeted search of known accounts. Although, yes, it is also more efficient to select just the properties you need to return.

The below examples are based on a domain in the range of 20,000 account objects.

measure-command {Get-ADUser -Filter '*' -Properties DisplayName,st }
...
Seconds           : 16
Milliseconds      : 208

measure-command {$userlist | get-aduser -Properties DisplayName,st}
...
Seconds           : 3
Milliseconds      : 496

In the second example, $userlist contains 368 account names (just strings, not pre-fetched account objects).

Note that if I include the where clause per your suggestion to prune to the actually desired results, it's even more expensive.

measure-command {Get-ADUser -Filter '*' -Properties DisplayName,st |where {$userlist -Contains $_.samaccountname } }
...
Seconds           : 17
Milliseconds      : 876

Indexed attributes seem to have similar performance (I tried just returning displayName).

Even if I return all user account properties in my set, it's more efficient. (Adding a select statement to the below brings it down by a half-second).

measure-command {$userlist | get-aduser -Properties *}
...
Seconds           : 12
Milliseconds      : 75

I can't find a good document that was written in ye olde days about AD queries to link to, but you're hitting every account in your search scope to return the properties. This discusses the basics of doing effective AD queries - scoping and filtering: https://msdn.microsoft.com/en-us/library/ms808539.aspx#efficientadapps_topic01

When your search scope is "*", you're still building a (big) list of the objects and iterating through each one. An LDAP search filter is always more efficient to build the list first (or a narrow search base, which is again building a smaller list to query).

Where does npm install packages?

Windows 10: When I ran npm prefix -g, I noticed that the install location was inside of the git shell's path that I used to install. Even when that location was added to the path, the command from the globally installed package would not be recognized. Fixed by:

  1. running npm config edit
  2. changing the prefix to 'C:\Users\username\AppData\Roaming\npm'
  3. adding that path to the system path variable
  4. reinstalling the package with -g.

How do I fix "The expression of type List needs unchecked conversion...'?

If you look at the javadoc for the class SyndFeed (I guess you are referring to the class com.sun.syndication.feed.synd.SyndFeed), the method getEntries() doesn't return java.util.List<SyndEntry>, but returns just java.util.List.

So you need an explicit cast for this.

Using the grep and cut delimiter command (in bash shell scripting UNIX) - and kind of "reversing" it?

You don't need to change the delimiter to display the right part of the string with cut.

The -f switch of the cut command is the n-TH element separated by your delimiter : :, so you can just type :

 grep puddle2_1557936 | cut -d ":" -f2

Another solutions (adapt it a bit) if you want fun :

Using :

grep -oP 'puddle2_1557936:\K.*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                                        
/home/rogers.williams/folderz/puddle2

or still with look around

grep -oP '(?<=puddle2_1557936:).*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                                    
/home/rogers.williams/folderz/puddle2

or with :

perl -lne '/puddle2_1557936:(.*)/ and print $1' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                      
/home/rogers.williams/folderz/puddle2

or using (thanks to glenn jackman)

ruby -F: -ane '/puddle2_1557936/ and puts $F[1]' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or with :

awk -F'puddle2_1557936:' '{print $2}'  <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or with :

python -c 'import sys; print(sys.argv[1].split("puddle2_1557936:")[1])' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or using only :

IFS=: read _ a <<< "puddle2_1557936:/home/rogers.williams/folderz/puddle2"
echo "$a"
/home/rogers.williams/folderz/puddle2

or using in a :

js<<EOF
var x = 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
print(x.substr(x.indexOf(":")+1))
EOF
/home/rogers.williams/folderz/puddle2

or using in a :

php -r 'preg_match("/puddle2_1557936:(.*)/", $argv[1], $m); echo "$m[1]\n";' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2' 
/home/rogers.williams/folderz/puddle2

What is the difference between H.264 video and MPEG-4 video?

They are names for the same standard from two different industries with different naming methods, the guys who make & sell movies and the guys who transfer the movies over the internet. Since 2003: "MPEG 4 Part 10" = "H.264" = "AVC". Before that the relationship was a little looser in that they are not equal but an "MPEG 4 Part 2" decoder can render a stream that's "H.263". The Next standard is "MPEG H Part 2" = "H.265" = "HEVC"

What is trunk, branch and tag in Subversion?

To use Subversion in Visual Studio 2008, install TortoiseSVN and AnkhSVN.

TortoiseSVN is a really easy to use Revision control / version control / source control software for Windows. Since it's not an integration for a specific IDE you can use it with whatever development tools you like. TortoiseSVN is free to use. You don't need to get a loan or pay a full years salary to use it.

AnkhSVN is a Subversion SourceControl Provider for Visual Studio. The software allows you to perform the most common version control operations directly from inside the Microsoft Visual Studio IDE. With AnkhSVN you no longer need to leave your IDE to perform tasks like viewing the status of your source code, updating your Subversion working copy and committing changes. You can even browse your repository and you can plug-in your favorite diff tool.

How to insert a newline in front of a pattern?

You can use perl one-liners much like you do with sed, with the advantage of full perl regular expression support (which is much more powerful than what you get with sed). There is also very little variation across *nix platforms - perl is generally perl. So you can stop worrying about how to make your particular system's version of sed do what you want.

In this case, you can do

perl -pe 's/(regex)/\n$1/'

-pe puts perl into a "execute and print" loop, much like sed's normal mode of operation.

' quotes everything else so the shell won't interfere

() surrounding the regex is a grouping operator. $1 on the right side of the substitution prints out whatever was matched inside these parens.

Finally, \n is a newline.

Regardless of whether you are using parentheses as a grouping operator, you have to escape any parentheses you are trying to match. So a regex to match the pattern you list above would be something like

\(\d\d\d\)\d\d\d-\d\d\d\d

\( or \) matches a literal paren, and \d matches a digit.

Better:

\(\d{3}\)\d{3}-\d{4}

I imagine you can figure out what the numbers in braces are doing.

Additionally, you can use delimiters other than / for your regex. So if you need to match / you won't need to escape it. Either of the below is equivalent to the regex at the beginning of my answer. In theory you can substitute any character for the standard /'s.

perl -pe 's#(regex)#\n$1#'
perl -pe 's{(regex)}{\n$1}'

A couple final thoughts.

using -ne instead of -pe acts similarly, but doesn't automatically print at the end. It can be handy if you want to print on your own. E.g., here's a grep-alike (m/foobar/ is a regex match):

perl -ne 'if (m/foobar/) {print}'

If you are finding dealing with newlines troublesome, and you want it to be magically handled for you, add -l. Not useful for the OP, who was working with newlines, though.

Bonus tip - if you have the pcre package installed, it comes with pcregrep, which uses full perl-compatible regexes.

Multiple types were found that match the controller named 'Home'

Some time in a single application this Issue also come In that case select these checkbox when you publish your application enter image description here

unix - count of columns in file

awk -F'|' '{print NF; exit}' stores.dat 

Just quit right after the first line.

pyplot axes labels for subplots

One simple way using subplots:

import matplotlib.pyplot as plt

fig, axes = plt.subplots(3, 4, sharex=True, sharey=True)
# add a big axes, hide frame
fig.add_subplot(111, frameon=False)
# hide tick and tick label of the big axes
plt.tick_params(labelcolor='none', top=False, bottom=False, left=False, right=False)
plt.grid(False)
plt.xlabel("common X")
plt.ylabel("common Y")

How to set a border for an HTML div tag

You need to set more fields then just border-width. The style basically puts the border on the page. Width controls the thickness, and color tells it what color to make the border.

border-style: solid; border-width:thin; border-color: #FFFFFF;

javascript setTimeout() not working

Two things.

  1. Remove the parenthesis in setTimeout(startTimer(),startInterval);. Keeping the parentheses invokes the function immediately.

  2. Your startTimer function will overwrite the page content with your use of document.write (without the above fix), and wipes out the script and HTML in the process.

IndexError: too many indices for array

The message that you are getting is not for the default Exception of Python:

For a fresh python list, IndexError is thrown only on index not being in range (even docs say so).

>>> l = []
>>> l[1]
IndexError: list index out of range

If we try passing multiple items to list, or some other value, we get the TypeError:

>>> l[1, 2]
TypeError: list indices must be integers, not tuple

>>> l[float('NaN')]
TypeError: list indices must be integers, not float

However, here, you seem to be using matplotlib that internally uses numpy for handling arrays. On digging deeper through the codebase for numpy, we see:

static NPY_INLINE npy_intp
unpack_tuple(PyTupleObject *index, PyObject **result, npy_intp result_n)
{
    npy_intp n, i;
    n = PyTuple_GET_SIZE(index);
    if (n > result_n) {
        PyErr_SetString(PyExc_IndexError,
                        "too many indices for array");
        return -1;
    }
    for (i = 0; i < n; i++) {
        result[i] = PyTuple_GET_ITEM(index, i);
        Py_INCREF(result[i]);
    }
    return n;
}

where, the unpack method will throw an error if it the size of the index is greater than that of the results.

So, Unlike Python which raises a TypeError on incorrect Indexes, Numpy raises the IndexError because it supports multidimensional arrays.

Checking if a website is up via Python

I use requests for this, then it is easy and clean. Instead of print function you can define and call new function (notify via email etc.). Try-except block is essential, because if host is unreachable then it will rise a lot of exceptions so you need to catch them all.

import requests

URL = "https://api.github.com"

try:
    response = requests.head(URL)
except Exception as e:
    print(f"NOT OK: {str(e)}")
else:
    if response.status_code == 200:
        print("OK")
    else:
        print(f"NOT OK: HTTP response code {response.status_code}")

How do I read a file line by line in VB Script?

If anyone like me is searching to read only a specific line, example only line 18 here is the code:

filename = "C:\log.log"

Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(filename)

For i = 1 to 17
    f.ReadLine
Next

strLine = f.ReadLine
Wscript.Echo strLine

f.Close

Get IFrame's document, from JavaScript in main document

You should be able to access the document in the IFRAME using the following code:

document.getElementById('myframe').contentWindow.document

However, you will not be able to do this if the page in the frame is loaded from a different domain (such as google.com). THis is because of the browser's Same Origin Policy.

splitting a string into an array in C++ without using vector

#define MAXSPACE 25

string line =  "test one two three.";
string arr[MAXSPACE];
string search = " ";
int spacePos;
int currPos = 0;
int k = 0;
int prevPos = 0;

do
{

    spacePos = line.find(search,currPos);

    if(spacePos >= 0)
    {

        currPos = spacePos;
        arr[k] = line.substr(prevPos, currPos - prevPos);
        currPos++;
        prevPos = currPos;
        k++;
    }


}while( spacePos >= 0);

arr[k] = line.substr(prevPos,line.length());

for(int i = 0; i < k; i++)
{
   cout << arr[i] << endl;
}

Binding ConverterParameter

There is also an alternative way to use MarkupExtension in order to use Binding for a ConverterParameter. With this solution you can still use the default IValueConverter instead of the IMultiValueConverter because the ConverterParameter is passed into the IValueConverter just like you expected in your first sample.

Here is my reusable MarkupExtension:

/// <summary>
///     <example>
///         <TextBox>
///             <TextBox.Text>
///                 <wpfAdditions:ConverterBindableParameter Binding="{Binding FirstName}"
///                     Converter="{StaticResource TestValueConverter}"
///                     ConverterParameterBinding="{Binding ConcatSign}" />
///             </TextBox.Text>
///         </TextBox>
///     </example>
/// </summary>
[ContentProperty(nameof(Binding))]
public class ConverterBindableParameter : MarkupExtension
{
    #region Public Properties

    public Binding Binding { get; set; }
    public BindingMode Mode { get; set; }
    public IValueConverter Converter { get; set; }
    public Binding ConverterParameter { get; set; }

    #endregion

    public ConverterBindableParameter()
    { }

    public ConverterBindableParameter(string path)
    {
        Binding = new Binding(path);
    }

    public ConverterBindableParameter(Binding binding)
    {
        Binding = binding;
    }

    #region Overridden Methods

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        var multiBinding = new MultiBinding();
        Binding.Mode = Mode;
        multiBinding.Bindings.Add(Binding);
        if (ConverterParameter != null)
        {
            ConverterParameter.Mode = BindingMode.OneWay;
            multiBinding.Bindings.Add(ConverterParameter);
        }
        var adapter = new MultiValueConverterAdapter
        {
            Converter = Converter
        };
        multiBinding.Converter = adapter;
        return multiBinding.ProvideValue(serviceProvider);
    }

    #endregion

    [ContentProperty(nameof(Converter))]
    private class MultiValueConverterAdapter : IMultiValueConverter
    {
        public IValueConverter Converter { get; set; }

        private object lastParameter;

        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            if (Converter == null) return values[0]; // Required for VS design-time
            if (values.Length > 1) lastParameter = values[1];
            return Converter.Convert(values[0], targetType, lastParameter, culture);
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            if (Converter == null) return new object[] { value }; // Required for VS design-time

            return new object[] { Converter.ConvertBack(value, targetTypes[0], lastParameter, culture) };
        }
    }
}

With this MarkupExtension in your code base you can simply bind the ConverterParameter the following way:

<Style TargetType="FrameworkElement">
<Setter Property="Visibility">
    <Setter.Value>
     <wpfAdditions:ConverterBindableParameter Binding="{Binding Tag, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}"
                 Converter="{StaticResource AccessLevelToVisibilityConverter}"
                 ConverterParameterBinding="{Binding RelativeSource={RelativeSource Mode=Self}, Path=Tag}" />          
    </Setter.Value>
</Setter>

Which looks almost like your initial proposal.

java.lang.NullPointerException: Attempt to invoke virtual method on a null object reference

Your app is crashing at:

welcomePlayer.setText("Welcome Back, " + String.valueOf(mPlayer.getName(this)) + " !");

because mPlayer=null.

You forgot to initialize Player mPlayer in your PlayGame Activity.

mPlayer = new Player(context,"");

How to Programmatically Add Views to Views

for anyone yet interested:

the best way I found is to use the inflate static method of View.

View inflatedView = View.inflate(context, yourViewXML, yourLinearLayout);

where yourViewXML is something like R.layout.myView

please notice that you need a ViewGroup in order to add a view (which is any layout you can think of)

so as an example lets say you have a fragment which it view already been inflated and you know that the root view is a layout, and you want to add a view to it:

    View view = getView(); // returns base view of the fragment
    if (view == null)
        return;
    if (!(view instanceof ViewGroup))
        return;

    ViewGroup viewGroup = (ViewGroup) view;
    View popup = View.inflate(viewGroup.getContext(), R.layout.someView, viewGroup);

Global variables in Javascript across multiple files

The variable can be declared in the .js file and simply referenced in the HTML file. My version of helpers.js:

var myFunctionWasCalled = false;

function doFoo()
{
    if (!myFunctionWasCalled) {
        alert("doFoo called for the very first time!");
        myFunctionWasCalled = true;
    }
    else {
        alert("doFoo called again");
    }
}

And a page to test it:

<html>
<head>
<title>Test Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<script type="text/javascript" src="helpers.js"></script>
</head>

<body>


<p>myFunctionWasCalled is
<script type="text/javascript">document.write(myFunctionWasCalled);</script>
</p>

<script type="text/javascript">doFoo();</script>

<p>Some stuff in between</p>

<script type="text/javascript">doFoo();</script>

<p>myFunctionWasCalled is
<script type="text/javascript">document.write(myFunctionWasCalled);</script>
</p>

</body>
</html>

You'll see the test alert() will display two different things, and the value written to the page will be different the second time.

How to copy a java.util.List into another java.util.List

If you do not want changes in one list to effect another list try this.It worked for me
Hope this helps.

  public class MainClass {
  public static void main(String[] a) {

    List list = new ArrayList();
    list.add("A");

    List list2 = ((List) ((ArrayList) list).clone());

    System.out.println(list);
    System.out.println(list2);

    list.clear();

    System.out.println(list);
    System.out.println(list2);
  }
}

> Output:   
[A]  
[A]  
[]  
[A]

Update a local branch with the changes from a tracked remote branch

You have set the upstream of that branch

(see:

git branch -f --track my_local_branch origin/my_remote_branch
# OR (if my_local_branch is currently checked out):
$ git branch --set-upstream-to my_local_branch origin/my_remote_branch

(git branch -f --track won't work if the branch is checked out: use the second command git branch --set-upstream-to instead, or you would get "fatal: Cannot force update the current branch.")

That means your branch is already configured with:

branch.my_local_branch.remote origin
branch.my_local_branch.merge my_remote_branch

Git already has all the necessary information.
In that case:

# if you weren't already on my_local_branch branch:
git checkout my_local_branch 
# then:
git pull

is enough.


If you hadn't establish that upstream branch relationship when it came to push your 'my_local_branch', then a simple git push -u origin my_local_branch:my_remote_branch would have been enough to push and set the upstream branch.
After that, for the subsequent pulls/pushes, git pull or git push would, again, have been enough.

Read line by line in bash script

The correct version of your script is as follows;

FILE="cat test"
$FILE | \
while read CMD; do
echo $CMD
done

However this kind of indirection --putting your command in a variable named FILE-- is unnecessary. Use one of the solutions already provided. I just wanted to point out your mistake.

ngOnInit not being called when Injectable class is Instantiated

I had to call a function once my dataService was initialized, instead, I called it inside the constructor, that worked for me.

Difference between "and" and && in Ruby?

I don't know if this is Ruby intention or if this is a bug but try this code below. This code was run on Ruby version 2.5.1 and was on a Linux system.

puts 1 > -1 and 257 < 256
# => false

puts 1 > -1 && 257 < 256
# => true

C# Reflection: How to get class reference from string?

You can use Type.GetType(string), but you'll need to know the full class name including namespace, and if it's not in the current assembly or mscorlib you'll need the assembly name instead. (Ideally, use Assembly.GetType(typeName) instead - I find that easier in terms of getting the assembly reference right!)

For instance:

// "I know String is in the same assembly as Int32..."
Type stringType = typeof(int).Assembly.GetType("System.String");

// "It's in the current assembly"
Type myType = Type.GetType("MyNamespace.MyType");

// "It's in System.Windows.Forms.dll..."
Type formType = Type.GetType ("System.Windows.Forms.Form, " + 
    "System.Windows.Forms, Version=2.0.0.0, Culture=neutral, " + 
    "PublicKeyToken=b77a5c561934e089");

Ansible - Use default if a variable is not defined

If you have a single play that you want to loop over the items, define that list in group_vars/all or somewhere else that makes sense:

all_items:
  - first
  - second
  - third
  - fourth

Then your task can look like this:

  - name: List items or default list
    debug:
      var: item
    with_items: "{{ varlist | default(all_items) }}"

Pass in varlist as a JSON array:

ansible-playbook <playbook_name> --extra-vars='{"varlist": [first,third]}'

Prior to that, you might also want a task that checks that each item in varlist is also in all_items:

  - name: Ensure passed variables are in all_items
    fail:
      msg: "{{ item }} not  in all_items list"
    when: item not in all_items
    with_items: "{{ varlist | default(all_items) }}"

jquery.ajax Access-Control-Allow-Origin

At my work we have our restful services on a different port number and the data resides in db2 on a pair of AS400s. We typically use the $.getJSON AJAX method because it easily returns JSONP using the ?callback=? without having any issues with CORS.

data ='USER=<?echo trim($USER)?>' +
         '&QRYTYPE=' + $("input[name=QRYTYPE]:checked").val();

        //Call the REST program/method returns: JSONP 
        $.getJSON( "http://www.stackoverflow.com/rest/resttest?callback=?",data)
        .done(function( json ) {        

              //  loading...
                if ($.trim(json.ERROR) != '') {
                    $("#error-msg").text(message).show();
                }
                else{
                    $(".error").hide();
                    $("#jsonp").text(json.whatever);

                }

        })  
        .fail(function( jqXHR, textStatus, error ) {
        var err = textStatus + ", " + error;
        alert('Unable to Connect to Server.\n Try again Later.\n Request Failed: ' + err);
        });     

Soft hyphen in HTML (<wbr> vs. &shy;)

This is a crossbrowser solution that I was looking at a little while ago that runs on the client and using jQuery:

(function($) { 
  $.fn.breakWords = function() { 
    this.each(function() { 
      if(this.nodeType !== 1) { return; } 

      if(this.currentStyle && typeof this.currentStyle.wordBreak === 'string') { 
        //Lazy Function Definition Pattern, Peter's Blog 
        //From http://peter.michaux.ca/article/3556 
        this.runtimeStyle.wordBreak = 'break-all'; 
      } 
      else if(document.createTreeWalker) { 

        //Faster Trim in Javascript, Flagrant Badassery 
        //http://blog.stevenlevithan.com/archives/faster-trim-javascript 

        var trim = function(str) { 
          str = str.replace(/^\s\s*/, ''); 
          var ws = /\s/, 
          i = str.length; 
          while (ws.test(str.charAt(--i))); 
          return str.slice(0, i + 1); 
        }; 

        //Lazy Function Definition Pattern, Peter's Blog 
        //From http://peter.michaux.ca/article/3556 

        //For Opera, Safari, and Firefox 
        var dWalker = document.createTreeWalker(this, NodeFilter.SHOW_TEXT, null, false); 
        var node,s,c = String.fromCharCode('8203'); 
        while (dWalker.nextNode()) { 
          node = dWalker.currentNode; 
          //we need to trim String otherwise Firefox will display 
          //incorect text-indent with space characters 
          s = trim( node.nodeValue ).split('').join(c); 
          node.nodeValue = s; 
        } 
      } 
    }); 

    return this; 
  }; 
})(jQuery); 

React Native fetch() Network Request Failed

By running the mock-server on 0.0.0.0
Note: This works on Expo when you are running another server using json-server.


Another approach is to run the mock server on 0.0.0.0 instead of localhost or 127.0.0.1.

This makes the mock server accessible on the LAN and because Expo requires the development machine and the mobile running the Expo app to be on the same network the mock server becomes accessible too.

This can be achieved with the following command when using json-server

json-server --host 0.0.0.0 --port 8000 ./db.json --watch

Visit this link for more information.

StringUtils.isBlank() vs String.isEmpty()

StringUtils.isBlank(foo) will perform a null check for you. If you perform foo.isEmpty() and foo is null, you will raise a NullPointerException.

AngularJS ng-repeat handle empty list case

You might want to check out the angular-ui directive ui-if if you just want to remove the ul from the DOM when the list is empty:

<ul ui-if="!!events.length">
    <li ng-repeat="event in events">{{event.title}}</li>
</ul>

Use of alloc init instead of new

Frequently, you are going to need to pass arguments to init and so you will be using a different method, such as [[SomeObject alloc] initWithString: @"Foo"]. If you're used to writing this, you get in the habit of doing it this way and so [[SomeObject alloc] init] may come more naturally that [SomeObject new].

What is the '.well' equivalent class in Bootstrap 4

Sure officially version says the cards are the new replacements for Bootstrap wells. But Cards are a quite broad Bootstrap components now. In simple terms, you can also use Bootstrap Jumbotron too.

What is the difference between <%, <%=, <%# and -%> in ERB in Rails?

These are use in ruby on rails :-

<% %> :-

The <% %> tags are used to execute Ruby code that does not return anything, such as conditions, loops or blocks. Eg :-

<h1>Names of all the people</h1>
<% @people.each do |person| %>
  Name: <%= person.name %><br>
<% end %>

<%= %> :-

use to display the content .

Name: <%= person.name %><br>

<% -%>:-

Rails extends ERB, so that you can suppress the newline simply by adding a trailing hyphen to tags in Rails templates

<%# %>:-

comment out the code

<%# WRONG %>
Hi, Mr. <% puts "Frodo" %>

PDO support for multiple queries (PDO_MYSQL, PDO_MYSQLND)

Tried following code

 $db = new PDO("mysql:host={$dbhost};dbname={$dbname};charset=utf8", $dbuser, $dbpass, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));

Then

 try {
 $db->query('SET NAMES gbk');
 $stmt = $db->prepare('SELECT * FROM 2_1_paidused WHERE NumberRenamed = ? LIMIT 1');
 $stmt->execute(array("\xbf\x27 OR 1=1 /*"));
 }
 catch (PDOException $e){
 echo "DataBase Errorz: " .$e->getMessage() .'<br>';
 }
 catch (Exception $e) {
 echo "General Errorz: ".$e->getMessage() .'<br>';
 }

And got

DataBase Errorz: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '/*' LIMIT 1' at line 1

If added $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); after $db = ...

Then got blank page

If instead SELECT tried DELETE, then in both cases got error like

 DataBase Errorz: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '* FROM 2_1_paidused WHERE NumberRenamed = '¿\' OR 1=1 /*' LIMIT 1' at line 1

So my conclusion that no injection possible...

Download an SVN repository?

If you have proxy i suggest using SVNGITDownloader it is under .NET Framework and its source code is available

Validate fields after user has left a field

Angular 1.3 now has ng-model-options, and you can set the option to { 'updateOn': 'blur'} for example, and you can even debounce, when the use is either typing too fast, or you want to save a few expensive DOM operations (like a model writing to multiple DOM places and you don't want a $digest cycle happening on every key down)

https://docs.angularjs.org/guide/forms#custom-triggers and https://docs.angularjs.org/guide/forms#non-immediate-debounced-model-updates

By default, any change to the content will trigger a model update and form validation. You can override this behavior using the ngModelOptions directive to bind only to specified list of events. I.e. ng-model-options="{ updateOn: 'blur' }" will update and validate only after the control loses focus. You can set several events using a space delimited list. I.e. ng-model-options="{ updateOn: 'mousedown blur' }"

And debounce

You can delay the model update/validation by using the debounce key with the ngModelOptions directive. This delay will also apply to parsers, validators and model flags like $dirty or $pristine.

I.e. ng-model-options="{ debounce: 500 }" will wait for half a second since the last content change before triggering the model update and form validation.

Get UTC time and local time from NSDate object

The documentation says that the date method returns a new date set to the current date and time regardless of the language used.

The issue probably sits somewhere where you present the date using NSDateFormatter. NSDate is just a point on a time line. There is no time zones when talking about NSDate. I made a test.

Swift

print(NSDate())

Output: 2014-07-23 17:56:45 +0000

Objective-C

NSLog(@"%@", [NSDate date]);

Output: 2014-07-23 17:58:15 +0000

Result - No difference.

Iterate over array of objects in Typescript

In Typescript and ES6 you can also use for..of:

for (var product of products) {
     console.log(product.product_desc)
}

which will be transcoded to javascript:

for (var _i = 0, products_1 = products; _i < products_1.length; _i++) {
    var product = products_1[_i];
    console.log(product.product_desc);
}

How to update cursor limit for ORA-01000: maximum open cursors exceed

you can update the setting under init.ora in oraclexe\app\oracle\product\11.2.0\server\config\scripts

jQuery Uncaught TypeError: Property '$' of object [object Window] is not a function

In Wordpress just replace

$(function(){...});

with

jQuery(function(){...});

No content to map due to end-of-input jackson parser

I got this error when sending a GET request with postman. The request required no parameters. My mistake was I had a blank line in the request body.

How do I do a multi-line string in node.js?

If you use io.js, it has support for multi-line strings as they are in ECMAScript 6.

var a =
`this is
a multi-line
string`;

See "New String Methods" at http://davidwalsh.name/es6-io for details and "template strings" at http://kangax.github.io/compat-table/es6/ for tracking compatibility.

How can I quantify difference between two images?

Have you seen the Algorithm for finding similar images question? Check it out to see suggestions.

I would suggest a wavelet transformation of your frames (I've written a C extension for that using Haar transformation); then, comparing the indexes of the largest (proportionally) wavelet factors between the two pictures, you should get a numerical similarity approximation.

link_to image tag. how to add class to a tag

Hey guys this is a good way of link w/ image and has lot of props in case you want to css attribute for example replace "alt" or "title" etc.....also including a logical restriction (?)

<%= link_to image_tag("#{request.ssl? ? @image_domain_secure : @image_domain}/images/linkImage.png", {:alt=>"Alt title", :title=>"Link title"}) , "http://www.site.com"%>

Hope this helps!

Install Qt on Ubuntu

Also take a look at awesome project aqtinstall https://github.com/miurahr/aqtinstall/ (it can install any Qt version on Linux, Mac and Windows machines without any interaction!) and GitHub Action that uses this tool: https://github.com/jurplel/install-qt-action

Set the absolute position of a view

My code for Xamarin, I am using FrameLayout for this purpose and following is my code:

               List<object> content = new List<object>();

        object aWebView = new {ContentType="web",Width="300", Height = "300",X="10",Y="30",ContentUrl="http://www.google.com" };
        content.Add(aWebView);
        object aWebView2 = new { ContentType = "image", Width = "300", Height = "300", X = "20", Y = "40", ContentUrl = "https://www.nasa.gov/sites/default/files/styles/image_card_4x3_ratio/public/thumbnails/image/leisa_christmas_false_color.png?itok=Jxf0IlS4" };
        content.Add(aWebView2);
        FrameLayout myLayout = (FrameLayout)FindViewById(Resource.Id.frameLayout1);
        foreach (object item in content)
        {

            string contentType = item.GetType().GetProperty("ContentType").GetValue(item, null).ToString();
            FrameLayout.LayoutParams param = new FrameLayout.LayoutParams(Convert.ToInt32(item.GetType().GetProperty("Width").GetValue(item, null).ToString()), Convert.ToInt32(item.GetType().GetProperty("Height").GetValue(item, null).ToString()));
            param.LeftMargin = Convert.ToInt32(item.GetType().GetProperty("X").GetValue(item, null).ToString());
            param.TopMargin = Convert.ToInt32(item.GetType().GetProperty("Y").GetValue(item, null).ToString());

            switch (contentType) {
                case "web":{
                        WebView webview = new WebView(this);

                        //webview.hei;
                        myLayout.AddView(webview, param);
                        webview.SetWebViewClient(new WebViewClient());
                        webview.LoadUrl(item.GetType().GetProperty("ContentUrl").GetValue(item, null).ToString());

                        break;
                    }
                case "image":
                    {
                        ImageView imageview = new ImageView(this);

                        //webview.hei;
                        myLayout.AddView(imageview, param);
                        var imageBitmap =  GetImageBitmapFromUrl("https://www.nasa.gov/sites/default/files/styles/image_card_4x3_ratio/public/thumbnails/image/leisa_christmas_false_color.png?itok=Jxf0IlS4");
                        imageview.SetImageBitmap(imageBitmap);


                        break;
                    }

            }

        }

It was useful for me because I needed the property of view to overlap each other on basis of their appearance, e.g the views get stacked one above other.

How do I change the android actionbar title and icon

Go to manifest in which specific activity you want to change Action bar Title name and write android:label="Title name"

How to center a component in Material-UI and make it responsive?

You can do this with the Box component:

import Box from "@material-ui/core/Box";

...

<Box
  display="flex"
  justifyContent="center"
  alignItems="center"
  minHeight="100vh"
>
  <YourComponent/>
</Box>

Removing black dots from li and ul

CSS :

ul{
list-style-type:none;
}

You can take a look at W3School

pip install failing with: OSError: [Errno 13] Permission denied on directory

So, I got this same exact error for a completely different reason. Due to a totally separate, but known Homebrew + pip bug, I had followed this workaround listed on Google Cloud's help docs, where you create a .pydistutils.cfg file in your home directory. This file has special config that you're only supposed to use for your install of certain libraries. I should have removed that disutils.cfg file after installing the packages, but I forgot to do so. So the fix for me was actually just...

rm ~/.pydistutils.cfg.

And then everything worked as normal. Of course, if you have some config in that file for a real reason, then you won't want to just straight rm that file. But in case anyone else did that workaround, and forgot to remove that file, this did the trick for me!

How to create a self-signed certificate for a domain name for development?

To Create the new certificate for your specific domain:

Open Powershell ISE as admin, run the command:

New-SelfSignedCertificate -DnsName *.mydomain.com, localhost -CertStoreLocation cert:\LocalMachine\My

To trust the new certificate:

  • Open mmc.exe
  • Go to Console Root -> Certificates (Local Computer) -> Personal
  • Select the certificate you have created, do right click -> All Tasks -> Export and follow the export wizard to create a .pfx file
  • Go to Console Root -> Certificates -> Trusted Root Certification Authorities and import the new .pfx file

To bind the certificate to your site:

  • Open IIS Manager
  • Select your site and choose Edit Site -> Bindings in the right pane
  • Add new https binding with the correct hostname and the new certificate

Angular.js ng-repeat filter by property having one of multiple values (OR of values)

In HTML:

<div ng-repeat="product in products | filter: colorFilter">

In Angular:

$scope.colorFilter = function (item) { 
  if (item.color === 'red' || item.color === 'blue') {
  return item;
 }
};

How to cast from List<Double> to double[] in Java?

High performance - every Double object wraps a single double value. If you want to store all these values into a double[] array, then you have to iterate over the collection of Double instances. A O(1) mapping is not possible, this should be the fastest you can get:

 double[] target = new double[doubles.size()];
 for (int i = 0; i < target.length; i++) {
    target[i] = doubles.get(i).doubleValue();  // java 1.4 style
    // or:
    target[i] = doubles.get(i);                // java 1.5+ style (outboxing)
 }

Thanks for the additional question in the comments ;) Here's the sourcecode of the fitting ArrayUtils#toPrimitive method:

public static double[] toPrimitive(Double[] array) {
  if (array == null) {
    return null;
  } else if (array.length == 0) {
    return EMPTY_DOUBLE_ARRAY;
  }
  final double[] result = new double[array.length];
  for (int i = 0; i < array.length; i++) {
    result[i] = array[i].doubleValue();
  }
  return result;
}

(And trust me, I didn't use it for my first answer - even though it looks ... pretty similiar :-D )

By the way, the complexity of Marcelos answer is O(2n), because it iterates twice (behind the scenes): first to make a Double[] from the list, then to unwrap the double values.

How to exclude 0 from MIN formula Excel

Try this formula

=SMALL((A1,C1,E1),INDEX(FREQUENCY((A1,C1,E1),0),1)+1)

Both SMALL and FREQUENCY functions accept "unions" as arguments, i.e. single cell references separated by commas and enclosed in brackets like (A1,C1,E1).

So the formula uses FREQUENCY and INDEX to find the number of zeroes in a range and if you add 1 to that you get the k value such that the kth smallest is always the minimum value excluding zero.

I'm assuming you don't have negative numbers.....

Error inflating class fragment

I was receiving this error for different reasons.

Steps to reproduce:

~> My issue was that I created a brand new blank application.

~> I then generated a custom fragment from the File ~> New File Menu.

~> Proceeded to customize the fragment by adding layouts and buttons etc.

~> Referenced the new custom fragment in the auto generated activity_my.xml that was generated for me when creating the application. Doing this allowed the XML to generate the objects for me.

Heres is the catch when generating the custom fragment via File ~> New File Menu it auto generates an interface function stub and places it at the bottom of the fragment class file.

This means that your MyActivity class must implement this interface. If it does not then the the above error occurs only when referencing the fragment from xml. By removing the reference for the Fragment in the XML completely, and creating the fragment through code in the MyActivity.java class file Logcat generates a more concise error explaining the issue in detail and complaining about the interface. This is demonstrated in the Project Template Activity+Fragment. Although, <~that Project Template does not generate the interface stub.

How to pass parameters to $http in angularjs?

Here is how you do it:

$http.get("/url/to/resource/", {params:{"param1": val1, "param2": val2}})
    .then(function (response) { /* */ })...

Angular takes care of encoding the parameters.

Maxim Shoustin's answer does not work ({method:'GET', url:'/search', jsonData} is not a valid JavaScript literal) and JeyTheva's answer, although simple, is dangerous as it allows XSS (unsafe values are not escaped when you concatenate them).

Where does the iPhone Simulator store its data?

Easiest way ever.

  1. Catch a Breakpoint somewhere.

  2. Enter po NSHomeDirectory() in console window

Result:

(lldb) po NSHomeDirectory() /Users/usernam/Library/Developer/CoreSimulator/Devices/4734F8C7-B90F-4566-8E89-5060505E387F/data/Containers/Data/Application/395818BB-6D0F-499F-AAFE-068A783D9753

How do I copy a string to the clipboard?

import wx

def ctc(text):

    if not wx.TheClipboard.IsOpened():
        wx.TheClipboard.Open()
        data = wx.TextDataObject()
        data.SetText(text)
        wx.TheClipboard.SetData(data)
    wx.TheClipboard.Close()

ctc(text)

SQL datetime format to date only

if you are using SQL Server use convert

e.g. select convert(varchar(10), DeliveryDate, 103) as ShortDate

more information here: http://msdn.microsoft.com/en-us/library/aa226054(v=sql.80).aspx

Integrate ZXing in Android Studio

this tutorial help me to integrate to android studio: http://wahidgazzah.olympe.in/integrating-zxing-in-your-android-app-as-standalone-scanner/ if down try THIS

just add to AndroidManifest.xml

<activity
         android:name="com.google.zxing.client.android.CaptureActivity"
         android:configChanges="orientation|keyboardHidden"
         android:screenOrientation="landscape"
         android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
         android:windowSoftInputMode="stateAlwaysHidden" >
         <intent-filter>
             <action android:name="com.google.zxing.client.android.SCAN" />
             <category android:name="android.intent.category.DEFAULT" />
         </intent-filter>
     </activity>

Hope this help!.

Why does 'git commit' not save my changes?

The reason why this is happening is because you have a folder that is already being tracked by Git inside another folder that is also tracked by Git. For example, I had a project and I added a subfolder to it. Both of them were being tracked by Git before I put one inside the other. In order to stop tracking the one inside, find it and remove the Git file with:

rm -rf .git

In my case I had a WordPress application and the folder I added inside was a theme. So I had to go to the theme root, and remove the Git file, so that the whole project would now be tracked by the parent, the WordPress application.

Is the size of C "int" 2 bytes or 4 bytes?

Is the size of C “int” 2 bytes or 4 bytes?

Does an Integer variable in C occupy 2 bytes or 4 bytes?

C allows "bytes" to be something other than 8 bits per "byte".

CHAR_BIT number of bits for smallest object that is not a bit-field (byte) C11dr §5.2.4.2.1 1

A value of something than 8 is increasingly uncommon. For maximum portability, use CHAR_BIT rather than 8. The size of an int in bits in C is sizeof(int) * CHAR_BIT.

#include <limits.h>
printf("(int) Bit size %zu\n", sizeof(int) * CHAR_BIT);

What are the factors that it depends on?

The int bit size is commonly 32 or 16 bits. C specified minimum ranges:

minimum value for an object of type int INT_MIN -32767
maximum value for an object of type int INT_MAX +32767
C11dr §5.2.4.2.1 1

The minimum range for int forces the bit size to be at least 16 - even if the processor was "8-bit". A size like 64 bits is seen in specialized processors. Other values like 18, 24, 36, etc. have occurred on historic platforms or are at least theoretically possible. Modern coding rarely worries about non-power-of-2 int bit sizes.

The computer's processor and architecture drive the int bit size selection.

Yet even with 64-bit processors, the compiler's int size may be 32-bit for compatibility reasons as large code bases depend on int being 32-bit (or 32/16).

How to get a ListBox ItemTemplate to stretch horizontally the full width of the ListBox?

I also had the same problem, as a quick workaround, I used blend to determine how much padding was being added. In my case it was 12, so I used a negative margin to get rid of it. Now everything can now be centered properly

MS Access DB Engine (32-bit) with Office 64-bit

I hate to answer my own questions, but I did finally find a solution that actually works (using socket communication between services may fix the problem, but it creates even more problems). Since our database is legacy, it merely required Microsoft.ACE.OLEDB.12.0 in the connection string. It turns out that this was also included in Office 2007 (and MSDE 2007), where there is only a 32-bit version available. So, instead of installing MSDE 2010 32-bit, we install MSDE 2007, and it works just fine. Other applications can then install 64-bit MSDE 2010 (or 64-bit Office 2010), and it does not conflict with our application.

Thus far, it appears this is an acceptable solution for all Windows OS environments.

Call removeView() on the child's parent first

What I was doing wrong so I got this error is I wasn't instantiating dynamic layout and adding childs to it so got this error

Python 3 - ValueError: not enough values to unpack (expected 3, got 2)

You probably want to assign the lastname you are reading out here

lastname = sheet.cell(row=r, column=3).value

to something; currently the program just forgets it

you could do that two lines after, like so

unpaidMembers[name] = lastname, email

your program will still crash at the same place, because .items() still won't give you 3-tuples but rather something that has this structure: (name, (lastname, email))

good news is, python can handle this

for name, (lastname, email) in unpaidMembers.items():

etc.

Peak signal detection in realtime timeseries data

In computational topology the idea of persistent homology leads to an efficient – fast as sorting numbers – solution. It does not only detect peaks, it quantifies the "significance" of the peaks in a natural way that allows you to select the peaks that are significant for you.

Algorithm summary. In a 1-dimensional setting (time series, real-valued signal) the algorithm can be easily described by the following figure:

Most persistent peaks

Think of the function graph (or its sub-level set) as a landscape and consider a decreasing water level starting at level infinity (or 1.8 in this picture). While the level decreases, at local maxima islands pop up. At local minima these islands merge together. One detail in this idea is that the island that appeared later in time is merged into the island that is older. The "persistence" of an island is its birth time minus its death time. The lengths of the blue bars depict the persistence, which is the above mentioned "significance" of a peak.

Efficiency. It is not too hard to find an implementation that runs in linear time – in fact it is a single, simple loop – after the function values were sorted. So this implementation should be fast in practice and is easily implemented, too.

References. A write-up of the entire story and references to the motivation from persistent homology (a field in computatioal algebraic topology) can be found here: https://www.sthu.org/blog/13-perstopology-peakdetection/index.html

oracle varchar to number

Since the column is of type VARCHAR, you should convert the input parameter to a string rather than converting the column value to a number:

select * from exception where exception_value = to_char(105);

Parenthesis/Brackets Matching using Stack algorithm

  Check balanced parenthesis or brackets with stack-- 
  var excp = "{{()}[{a+b+b}][{(c+d){}}][]}";
   var stk = [];   
   function bracket_balance(){
      for(var i=0;i<excp.length;i++){
          if(excp[i]=='[' || excp[i]=='(' || excp[i]=='{'){
             stk.push(excp[i]);
          }else if(excp[i]== ']' && stk.pop() != '['){
             return false;
          }else if(excp[i]== '}' && stk.pop() != '{'){

            return false;
          }else if(excp[i]== ')' && stk.pop() != '('){

            return false;
          }
      }

      return true;
   }

  console.log(bracket_balance());
  //Parenthesis are balance then return true else false

Git fails when pushing commit to github

The Problem to push mostly is because of the size of the files that need to be pushed. I was trying to push some libraries of just size 2 mb, then too the push was giving error of RPC with result 7. The line is of 4 mbps and is working fine. Some subsequent tries to the push got me success. If such error comes, wait for few minutes and keep on trying.

I also found out that there are some RPC failures if the github is down or is getting unstable network at their side.

So keeping up trying after some intervals is the only option!

How do I position a div at the bottom center of the screen

If you aren't comfortable with using negative margins, check this out.

div {
  position: fixed;
  left: 50%;
  bottom: 20px;
  transform: translate(-50%, -50%);
  margin: 0 auto;
}
<div>
  Your Text
</div>

Especially useful when you don't know the width of the div.


align="center" has no effect.

Since you have position:absolute, I would recommend positioning it 50% from the left and then subtracting half of its width from its left margin.

#manipulate {
    position:absolute;
    width:300px;
    height:300px;
    background:#063;
    bottom:0px;
    right:25%;
    left:50%;
    margin-left:-150px;
}

jQuery-UI datepicker default date

$("#birthdate" ).datepicker("setDate", new Date(1985,01,01))

Java Security: Illegal key size or default parameters?

With Java 9, Java 8u161, Java 7u171 and Java 6u181 the limitation is now disabled by default. See issue in Java Bug Database.


Beginning with Java 8u151 you can disable the limitation programmatically.

In older releases, JCE jurisdiction files had to be downloaded and installed separately to allow unlimited cryptography to be used by the JDK. The download and install steps are no longer necessary.

Instead you can now invoke the following line before first use of JCE classes (i.e. preferably right after application start):

Security.setProperty("crypto.policy", "unlimited");

Testing web application on Mac/Safari when I don't own a Mac

The best site to test website and see them realtime on MAC Safari is by using

Browserstack

They have like 25 free minutes of first time testing and then 10 free mins each day..You can even test your pages from your local PC by using their WEB TUNNEL Feature

I tested 7 to 8 pages in browserstack...And I think they have some java debugging tool in the upper right corner that is great help

PHP Sort a multidimensional array by element containing date

For 'd/m/Y' dates:

usort($array, function ($a, $b, $i = 'datetime') { 
    $t1 = strtotime(str_replace('/', '-', $a[$i]));
    $t2 = strtotime(str_replace('/', '-', $b[$i]));

    return $t1 > $t2;
});

where $i is the array index

Expected response code 250 but got code "535", with message "535-5.7.8 Username and Password not accepted

i had same issue i resolve this use under

go to gmail.com

my account

and enable

Allow less secure apps: ON

it start works

in angularjs how to access the element that triggered the event?

if you wanna ng-model value, if you can write like this in the triggered event: $scope.searchText

PHP - Failed to open stream : No such file or directory

For me I got this error because I was trying to read a file which required HTTP auth, with a username and password. Hope that helps others. Might be another corner case.

pull out p-values and r-squared from a linear regression

You can see the structure of the object returned by summary() by calling str(summary(fit)). Each piece can be accessed using $. The p-value for the F statistic is more easily had from the object returned by anova.

Concisely, you can do this:

rSquared <- summary(fit)$r.squared
pVal <- anova(fit)$'Pr(>F)'[1]

OR condition in Regex

Try

\d \w |\d

or add a positive lookahead if you don't want to include the trailing space in the match

\d \w(?= )|\d

When you have two alternatives where one is an extension of the other, put the longer one first, otherwise it will have no opportunity to be matched.