Programs & Examples On #Array map

PHP's array_map() function accepts Callback function to run for each element in each array and an array to run through the callback function.

javax.net.ssl.SSLException: Read error: ssl=0x9524b800: I/O error during system call, Connection reset by peer

Android Supports SSL implementation by default except for Android N (API level 24) and below Android 5.1 (API level 22)
I was getting the error when making the API call below API level 22 devices after implementing SSL at the server side; that was while creating OkHttpClient client object, and fixed by adding connectionSpecs() method OkHttpClient.Builder class.

the error received was

response failure: javax.net.ssl.SSLException: SSL handshake aborted: ssl=0xb8882c00: I/O error during system call, Connection reset by peer

so I fixed this by added the check like

if ( Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1) {
            // Do something for below api level 22
            List<ConnectionSpec> specsList = getSpecsBelowLollipopMR1(okb);
            if (specsList != null) {
                okb.connectionSpecs(specsList);
            }
        }

Also for the Android N (API level 24); I was getting the error while making the HTTP call like

HTTP FAILED: javax.net.ssl.SSLHandshakeException: Handshake failed

and this is fixed by adding the check for Android 7 particularly, like

if (android.os.Build.VERSION.SDK_INT == Build.VERSION_CODES.N){
            // Do something for naugat ; 7
            okb.connectionSpecs(Collections.singletonList(getSpec()));
        }

So my final OkHttpClient object will be like:

         OkHttpClient client
         HttpLoggingInterceptor httpLoggingInterceptor2 = new
         HttpLoggingInterceptor();
         httpLoggingInterceptor2.setLevel(HttpLoggingInterceptor.Level.BODY);

         OkHttpClient.Builder okb = new OkHttpClient.Builder()
                 .addInterceptor(httpLoggingInterceptor2)
               .addInterceptor(new Interceptor() {
                     @Override
                     public Response intercept(Chain chain) throws IOException {
                         Request request = chain.request();
                         Request request2 = request.newBuilder().addHeader(AUTH_KEYWORD, AUTH_TYPE_JW + " " + password).build();
                         return chain.proceed(request2);
                     }
                 }).connectTimeout(30, TimeUnit.SECONDS)
                 .writeTimeout(30, TimeUnit.SECONDS)
                 .readTimeout(30, TimeUnit.SECONDS);

         if (android.os.Build.VERSION.SDK_INT == Build.VERSION_CODES.N){
             // Do something for naugat ; 7
             okb.connectionSpecs(Collections.singletonList(getSpec()));
         }

         if ( Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1) {
             List<ConnectionSpec> specsList = getSpecsBelowLollipopMR1(okb);
             if (specsList != null) {
                 okb.connectionSpecs(specsList);
             }
         }

         //init client
         client = okb.build();

getSpecsBelowLollipopMR1 function be like,

   private List<ConnectionSpec> getSpecsBelowLollipopMR1(OkHttpClient.Builder okb) {

        try {

            SSLContext sc = SSLContext.getInstance("TLSv1.2");
            sc.init(null, null, null);
            okb.sslSocketFactory(new Tls12SocketFactory(sc.getSocketFactory()));

            ConnectionSpec cs = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
                    .tlsVersions(TlsVersion.TLS_1_2)
                    .build();

            List<ConnectionSpec> specs = new ArrayList<>();
            specs.add(cs);
            specs.add(ConnectionSpec.COMPATIBLE_TLS);

            return specs;

        } catch (Exception exc) {
            Timber.e("OkHttpTLSCompat Error while setting TLS 1.2"+ exc);

            return null;
        }
    }

The Tls12SocketFactory class will be found in below link (comment by gotev):

https://github.com/square/okhttp/issues/2372


For more support adding some links below this will help you in detail,

https://developer.android.com/training/articles/security-ssl

D/OkHttp: <-- HTTP FAILED: javax.net.ssl.SSLException: SSL handshake aborted: ssl=0x64e3c938: I/O error during system call, Connection reset by peer

error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’

int &z = 12;

On the right hand side, a temporary object of type int is created from the integral literal 12, but the temporary cannot be bound to non-const reference. Hence the error. It is same as:

int &z = int(12); //still same error

Why a temporary gets created? Because a reference has to refer to an object in the memory, and for an object to exist, it has to be created first. Since the object is unnamed, it is a temporary object. It has no name. From this explanation, it became pretty much clear why the second case is fine.

A temporary object can be bound to const reference, which means, you can do this:

const int &z = 12; //ok

C++11 and Rvalue Reference:

For the sake of the completeness, I would like to add that C++11 has introduced rvalue-reference, which can bind to temporary object. So in C++11, you can write this:

int && z = 12; //C+11 only 

Note that there is && intead of &. Also note that const is not needed anymore, even though the object which z binds to is a temporary object created out of integral-literal 12.

Since C++11 has introduced rvalue-reference, int& is now henceforth called lvalue-reference.

Matching strings with wildcard

Just FYI, you could use the VB.NET Like-Operator:

string text = "x is not the same as X and yz not the same as YZ";
bool contains = LikeOperator.LikeString(text,"*X*YZ*", Microsoft.VisualBasic.CompareMethod.Binary);  

Use CompareMethod.Text if you want to ignore the case.

You need to add using Microsoft.VisualBasic.CompilerServices;.

Is there a way to run Python on Android?

From the Python for android site:

Python for android is a project to create your own Python distribution including the modules you want, and create an apk including python, libs, and your application.

Custom Authentication in ASP.Net-Core

I would like to add something to brilliant @AmiNadimi answer for everyone who going implement his solution in .NET Core 3:

First of all, you should change signature of SignIn method in UserManager class from:

public async void SignIn(HttpContext httpContext, UserDbModel user, bool isPersistent = false)

to:

public async Task SignIn(HttpContext httpContext, UserDbModel user, bool isPersistent = false)

It's because you should never use async void, especially if you work with HttpContext. Source: Microsoft Docs

The last, but not least, your Configure() method in Startup.cs should contains app.UseAuthorization and app.UseAuthentication in proper order:

if (env.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}
else
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseAuthentication();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
});

How to "flatten" a multi-dimensional array to simple one in PHP?

Another method from PHP's user comments (simplified) and here:

function array_flatten_recursive($array) { 
   if (!$array) return false;
   $flat = array();
   $RII = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
   foreach ($RII as $value) $flat[] = $value;
   return $flat;
}

The big benefit of this method is that it tracks the depth of the recursion, should you need that while flattening.
This will output:

$array = array( 
    'A' => array('B' => array( 1, 2, 3)), 
    'C' => array(4, 5) 
); 
print_r(array_flatten_recursive($array)); 

#Returns: 
Array ( 
    [0] => 1 
    [1] => 2 
    [2] => 3 
    [3] => 4 
    [4] => 5 
)

How to call a stored procedure (with parameters) from another stored procedure without temp table

You can call a stored procedure from another stored procedure by using the EXECUTE command.

Say your procedure is X. Then in X you can use

EXECUTE PROCEDURE Y () RETURNING_VALUES RESULT;"

Are the PUT, DELETE, HEAD, etc methods available in most web browsers?

XMLHttpRequest is a standard object in the JavaScript Object model.

According to Wikipedia, XMLHttpRequest first appeared in Internet Explorer 5 as an ActiveX object, but has since been made into a standard and has been included for use in JavaScript in the Mozilla family since 1.0, Apple Safari 1.2, Opera 7.60-p1, and IE 7.0.

The open() method on the object takes the HTTP Method as an argument - and is specified as taking any valid HTTP method (see the item number 5 of the link) - including GET, POST, HEAD, PUT and DELETE, as specified by RFC 2616.

As a side note IE 7–8 only permit the following HTTP methods: "GET", "POST", "HEAD", "PUT", "DELETE", "MOVE", "PROPFIND", "PROPPATCH", "MKCOL", "COPY", "LOCK", "UNLOCK", and "OPTIONS".

Echo newline in Bash prints literal \n

You could also use echo with braces,

$ (echo hello; echo world)
hello
world

In SQL how to compare date values?

Uh, WHERE mydate<='2008-11-25' is the way to do it. That should work.

Do you get an error message? Are you using an ancient version of MySQL?

Edit: The following works fine for me on MySQL 5.x

create temporary table foo(d datetime);
insert into foo(d) VALUES ('2000-01-01');
insert into foo(d) VALUES ('2001-01-01');
select * from foo where d <= '2000-06-01';

java.lang.NoClassDefFoundError:failed resolution of :Lorg/apache/http/ProtocolVersion

Do any of the following:

1- Update the play-services-maps library to the latest version:

com.google.android.gms:play-services-maps:16.1.0

2- Or include the following declaration within the <application> element of AndroidManifest.xml.

<uses-library
      android:name="org.apache.http.legacy"
      android:required="false" />

Declaring variables inside loops, good practice or bad practice?

Generally, it's a very good practice to keep it very close.

In some cases, there will be a consideration such as performance which justifies pulling the variable out of the loop.

In your example, the program creates and destroys the string each time. Some libraries use a small string optimization (SSO), so the dynamic allocation could be avoided in some cases.

Suppose you wanted to avoid those redundant creations/allocations, you would write it as:

for (int counter = 0; counter <= 10; counter++) {
   // compiler can pull this out
   const char testing[] = "testing";
   cout << testing;
}

or you can pull the constant out:

const std::string testing = "testing";
for (int counter = 0; counter <= 10; counter++) {
   cout << testing;
}

Do most compilers realize that the variable has already been declared and just skip that portion, or does it actually create a spot for it in memory each time?

It can reuse the space the variable consumes, and it can pull invariants out of your loop. In the case of the const char array (above) - that array could be pulled out. However, the constructor and destructor must be executed at each iteration in the case of an object (such as std::string). In the case of the std::string, that 'space' includes a pointer which contains the dynamic allocation representing the characters. So this:

for (int counter = 0; counter <= 10; counter++) {
   string testing = "testing";
   cout << testing;
}

would require redundant copying in each case, and dynamic allocation and free if the variable sits above the threshold for SSO character count (and SSO is implemented by your std library).

Doing this:

string testing;
for (int counter = 0; counter <= 10; counter++) {
   testing = "testing";
   cout << testing;
}

would still require a physical copy of the characters at each iteration, but the form could result in one dynamic allocation because you assign the string and the implementation should see there is no need to resize the string's backing allocation. Of course, you wouldn't do that in this example (because multiple superior alternatives have already been demonstrated), but you might consider it when the string or vector's content varies.

So what do you do with all those options (and more)? Keep it very close as a default -- until you understand the costs well and know when you should deviate.

PHP Email sending BCC

You were setting BCC but then overwriting the variable with the FROM

$to = "[email protected]";
     $subject .= "".$emailSubject."";
 $headers .= "Bcc: ".$emailList."\r\n";
 $headers .= "From: [email protected]\r\n" .
     "X-Mailer: php";
     $headers .= "MIME-Version: 1.0\r\n";
     $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
 $message = '<html><body>';
 $message .= 'THE MESSAGE FROM THE FORM';

     if (mail($to, $subject, $message, $headers)) {
     $sent = "Your email was sent!";
     } else {
      $sent = ("Error sending email.");
     }

How can I strip first and last double quotes?

If string is always as you show:

string[1:-1]

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

Via Type.GetType you can get the type information. You can use this class to get the method information and then invoke the method (for static methods, leave the first parameter null).

You might also need the Assembly name to correctly identify the type.

If the type is in the currently executing assembly or in Mscorlib.dll, it is sufficient to supply the type name qualified by its namespace.

Clear text from textarea with selenium

It is general syntax

driver.find_element_by_id('Locator value').clear();
driver.find_element_by_name('Locator value').clear();

Laravel: Get Object From Collection By Attribute

I know this question was originally asked before Laravel 5.0 was released, but as of Laravel 5.0, Collections support the where() method for this purpose.

For Laravel 5.0, 5.1, and 5.2, the where() method on the Collection will only do an equals comparison. Also, it does a strict equals comparison (===) by default. To do a loose comparison (==), you can either pass false as the third parameter or use the whereLoose() method.

As of Laravel 5.3, the where() method was expanded to work more like the where() method for the query builder, which accepts an operator as the second parameter. Also like the query builder, the operator will default to an equals comparison if none is supplied. The default comparison was also switched from strict by default to loose by default. So, if you'd like a strict comparison, you can use whereStrict(), or just use === as the operator for where().

Therefore, as of Laravel 5.0, the last code example in the question will work exactly as intended:

$foods = Food::all();
$green_foods = $foods->where('color', 'green'); // This will work.  :)

// This will only work in Laravel 5.3+
$cheap_foods = $foods->where('price', '<', 5);

// Assuming "quantity" is an integer...
// This will not match any records in 5.0, 5.1, 5.2 due to the default strict comparison.
// This will match records just fine in 5.3+ due to the default loose comparison.
$dozen_foods = $foods->where('quantity', '12');

Program to find largest and smallest among 5 numbers without using array

You could use list (or vector), which is not an array:

#include<list>
#include<algorithm>
#include<iostream>
using namespace std;
int main()
{
    list<int> l;
    l.push_back(3); 
    l.push_back(9); 
    l.push_back(30);    
    l.push_back(0); 
    l.push_back(5); 

    list<int>::iterator it_max = max_element(l.begin(), l.end());
    list<int>::iterator it_min = min_element(l.begin(), l.end());

    cout << "Max: " << *it_max << endl;
    cout << "Min: " << *it_min << endl;
}

change figure size and figure format in matplotlib

If you need to change the figure size after you have created it, use the methods

fig = plt.figure()
fig.set_figheight(value_height)
fig.set_figwidth(value_width)

where value_height and value_width are in inches. For me this is the most practical way.

How to display raw JSON data on a HTML page

I think all you need to display the data on an HTML page is JSON.stringify.

For example, if your JSON is stored like this:

var jsonVar = {
        text: "example",
        number: 1
    };

Then you need only do this to convert it to a string:

var jsonStr = JSON.stringify(jsonVar);

And then you can insert into your HTML directly, for example:

document.body.innerHTML = jsonStr;

Of course you will probably want to replace body with some other element via getElementById.

As for the CSS part of your question, you could use RegExp to manipulate the stringified object before you put it into the DOM. For example, this code (also on JSFiddle for demonstration purposes) should take care of indenting of curly braces.

var jsonVar = {
        text: "example",
        number: 1,
        obj: {
            "more text": "another example"
        },
        obj2: {
             "yet more text": "yet another example"
        }
    }, // THE RAW OBJECT
    jsonStr = JSON.stringify(jsonVar),  // THE OBJECT STRINGIFIED
    regeStr = '', // A EMPTY STRING TO EVENTUALLY HOLD THE FORMATTED STRINGIFIED OBJECT
    f = {
            brace: 0
        }; // AN OBJECT FOR TRACKING INCREMENTS/DECREMENTS,
           // IN PARTICULAR CURLY BRACES (OTHER PROPERTIES COULD BE ADDED)

regeStr = jsonStr.replace(/({|}[,]*|[^{}:]+:[^{}:,]*[,{]*)/g, function (m, p1) {
var rtnFn = function() {
        return '<div style="text-indent: ' + (f['brace'] * 20) + 'px;">' + p1 + '</div>';
    },
    rtnStr = 0;
    if (p1.lastIndexOf('{') === (p1.length - 1)) {
        rtnStr = rtnFn();
        f['brace'] += 1;
    } else if (p1.indexOf('}') === 0) {
         f['brace'] -= 1;
        rtnStr = rtnFn();
    } else {
        rtnStr = rtnFn();
    }
    return rtnStr;
});

document.body.innerHTML += regeStr; // appends the result to the body of the HTML document

This code simply looks for sections of the object within the string and separates them into divs (though you could change the HTML part of that). Every time it encounters a curly brace, however, it increments or decrements the indentation depending on whether it's an opening brace or a closing (behaviour similar to the space argument of 'JSON.stringify'). But you could this as a basis for different types of formatting.

Multiple conditions with CASE statements

It's not a cut and paste. The CASE expression must return a value, and you are returning a string containing SQL (which is technically a value but of a wrong type). This is what you wanted to write, I think:

SELECT * FROM [Purchasing].[Vendor] WHERE  
CASE
  WHEN @url IS null OR @url = '' OR @url = 'ALL'
    THEN PurchasingWebServiceURL LIKE '%'
  WHEN @url = 'blank'
    THEN PurchasingWebServiceURL = ''
  WHEN @url = 'fail'
    THEN PurchasingWebServiceURL NOT LIKE '%treyresearch%'
  ELSE PurchasingWebServiceURL = '%' + @url + '%' 
END

I also suspect that this might not work in some dialects, but can't test now (Oracle, I'm looking at you), due to not having booleans.

However, since @url is not dependent on the table values, why not make three different queries, and choose which to evaluate based on your parameter?

Meaning of numbers in "col-md-4"," col-xs-1", "col-lg-2" in Bootstrap

Applies to Bootstrap 3 only.

Ignoring the letters (xs, sm, md, lg) for now, I'll start with just the numbers...

  • the numbers (1-12) represent a portion of the total width of any div
  • all divs are divided into 12 columns
  • so, col-*-6 spans 6 of 12 columns (half the width), col-*-12 spans 12 of 12 columns (the entire width), etc

So, if you want two equal columns to span a div, write

<div class="col-xs-6">Column 1</div>
<div class="col-xs-6">Column 2</div>

Or, if you want three unequal columns to span that same width, you could write:

<div class="col-xs-2">Column 1</div>
<div class="col-xs-6">Column 2</div>
<div class="col-xs-4">Column 3</div>

You'll notice the # of columns always add up to 12. It can be less than twelve, but beware if more than 12, as your offending divs will bump down to the next row (not .row, which is another story altogether).

You can also nest columns within columns, (best with a .row wrapper around them) such as:

<div class="col-xs-6">
  <div class="row">
    <div class="col-xs-4">Column 1-a</div>
    <div class="col-xs-8">Column 1-b</div>
  </div>
</div>
<div class="col-xs-6">
  <div class="row">
    <div class="col-xs-2">Column 2-a</div>
    <div class="col-xs-10">Column 2-b</div>
  </div>
</div>

Each set of nested divs also span up to 12 columns of their parent div. NOTE: Since each .col class has 15px padding on either side, you should usually wrap nested columns in a .row, which has -15px margins. This avoids duplicating the padding and keeps the content lined up between nested and non-nested col classes.

-- You didn't specifically ask about the xs, sm, md, lg usage, but they go hand-in-hand so I can't help but touch on it...

In short, they are used to define at which screen size that class should apply:

  • xs = extra small screens (mobile phones)
  • sm = small screens (tablets)
  • md = medium screens (some desktops)
  • lg = large screens (remaining desktops)

Read the "Grid Options" chapter from the official Bootstrap documentation for more details.

You should usually classify a div using multiple column classes so it behaves differently depending on the screen size (this is the heart of what makes bootstrap responsive). eg: a div with classes col-xs-6 and col-sm-4 will span half the screen on the mobile phone (xs) and 1/3 of the screen on tablets(sm).

<div class="col-xs-6 col-sm-4">Column 1</div> <!-- 1/2 width on mobile, 1/3 screen on tablet) -->
<div class="col-xs-6 col-sm-8">Column 2</div> <!-- 1/2 width on mobile, 2/3 width on tablet -->

NOTE: as per comment below, grid classes for a given screen size apply to that screen size and larger unless another declaration overrides it (i.e. col-xs-6 col-md-4 spans 6 columns on xs and sm, and 4 columns on md and lg, even though sm and lg were never explicitly declared)

NOTE: if you don't define xs, it will default to col-xs-12 (i.e. col-sm-6 is half the width on sm, md and lg screens, but full-width on xs screens).

NOTE: it's actually totally fine if your .row includes more than 12 cols, as long as you are aware of how they will react. --This is a contentious issue, and not everyone agrees.

List of phone number country codes

Android ready county list and flag images

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- country list -->
    <string-array name="data000">
        <item name="code">+93</item>
        <item name="country">Afghanistan</item>
        <item name="iso">AF</item>
        <item name="flag">@drawable/afghanistan</item>
    </string-array>
    <string-array name="data001">
        <item name="code">+355</item>
        <item name="country">Albania</item>
        <item name="iso">AL</item>
        <item name="flag">@drawable/albania</item>
    </string-array>
    ...

    <array name="countries">
        <item>@array/data000</item>
        <item>@array/data001</item>
        ...
    </array>
</resources>

Is it possible to wait until all javascript files are loaded before executing javascript code?

You can use .getScript() and run your code after it loads:

 $.getScript("my_lovely_script.js", function(){

    alert("Script loaded and executed.");
    // here you can use anything you defined in the loaded script

 });

You can see a better explanation here: How do I include a JavaScript file in another JavaScript file?

"CAUTION: provisional headers are shown" in Chrome debugger

The resource could be being blocked by an extension (AdBlock in my case).

The message is there because the request to retrieve that resource was never made, so the headers being shown are not the real thing. As explained in the issue you referenced, the real headers are updated when the server responds, but there is no response if the request was blocked.


The way I found about the extension that was blocking my resource was through the net-internals tool in Chrome:

For Latest Versions of chrome

  • Type chrome://net-export/ in the address bar and hit enter.
  • Start Recording. And save Recording file to local.
  • Open the page that is showing problems.
  • Go back to net-internals
  • You can view Recorded Log file Here https://netlog-viewer.appspot.com/#import
  • click on events (###) and use the textfield to find the event related to your resource (use parts of the URL).
  • Finally, click on the event and see if the info shown tells you something.

For Older Versions of chrome

  • Type chrome://net-internals in the address bar and hit enter.
  • Open the page that is showing problems.
  • Go back to net-internals, click on events (###) and use the textfield to find the event related to your resource (use parts of the URL).
  • Finally, click on the event and see if the info shown tells you something.

What are Covering Indexes and Covered Queries in SQL Server?

A covering query is on where all the predicates can be matched using the indices on the underlying tables.

This is the first step towards improving the performance of the sql under consideration.

z-index not working with position absolute

Old question but this answer might help someone.

If you are trying to display the contents of the container outside of the boundaries of the container, make sure that it doesn't have overflow:hidden, otherwise anything outside of it will be cut off.

How to use a WSDL file to create a WCF service (not make a call)

There are good resources out there if you know what to search for. Try "Contract First" and WCF. or "WSDL First" and WCF.

Here is a selection:

awk without printing newline

The ORS (output record separator) variable in AWK defaults to "\n" and is printed after every line. You can change it to " " in the BEGIN section if you want everything printed consecutively.

Search for all occurrences of a string in a mysql database

In phpMyAdmin a 'Search' feature is available:

  1. Select particular database not table.
  2. Click 'Search' tab
  3. Enter the search term you want
  4. Select the tables you want to search in

phpMyAdmin screen shot:

phpMyAdmin Database Search tab

The 'Search' feature is also available in MySQL Workbench:

  1. Database Menu > Search Table Data
  2. Select database and tables you want to search (it will search in selected tables only)
  3. In search you can use wildChars.

MySQL Workbench screen shot:

MySQL Workbench Database Search

IsNumeric function in c#

You could make a helper method. Something like:

public bool IsNumeric(string input) {
    int test;
    return int.TryParse(input, out test);
}

Jquery to get the id of selected value from dropdown

Try the change event and selected selector

$('#jobSel').change(function(){
    var optId = $(this).find('option:selected').attr('id')
})

How to include the reference of DocumentFormat.OpenXml.dll on Mono2.10?

You need to have DocumentFormat.OpenXML.dll in the same folder as your application - or in the 'bin' path if you are developing an ASP.NET application. However, I'm not certain that the OpenXML SDK is supported on non-Windows operating systems - you may need to look into a third-party solution.

Yes, this answer is right, the only difference is that you copy your .dll into bin folder of the project.

Redirect to an external URL from controller action in Spring MVC

Did you try RedirectView where you can provide the contextRelative parameter?

IIS sc-win32-status codes

Here's the list of all Win32 error codes. You can use this page to lookup the error code mentioned in IIS logs:
http://msdn.microsoft.com/en-us/library/ms681381.aspx

You can also use command line utility net to find information about a Win32 error code. The syntax would be:
net helpmsg Win32_Status_Code

Solr vs. ElasticSearch

Imagine the use case:

  1. A lot(100+) of small(10Mb-100Mb, 1000-100000 documents) search indexes.
  2. They are using by a lot of applications (microservices)
  3. Each application can use more than one index
  4. Small by size index, yes. But huge load(hundreds search-requests per second) and requests are complex (multiple aggregations, conditions and so on)
  5. Downtimes are not allowed
  6. All of that is working years long, and constantly growing.

Idea to have individual ES instance per each index - is huge overhead in this case.

Based on my experience, this kind of use case is very complex to support with Elasticsearch.

Why?

FIRST.

The major problem is fundamental back compatibility disregard.

Breaking changes are so cool! (Note: imagine SQL-server which require you to do small change in all your SQL-statements, when upgraded... can't imagine it. But for ES it's normal)

Deprecations which will dropped in next major release are so sexy! (Note: you know, Java contain some deprecations, which 20+ years old, but still working in actual Java version...)

And not only that, sometimes you even have something which nowhere documented (personally came across only once but... )

So. If you want to upgrade ES (because you need new features for some app or you want to get bug fixes) - you are in hell. Especially if it is about major version upgrade.

Client API will not back compatible. Index settings will not back compatible. And upgrade all app/services same moment with ES upgrade is not realistic.

But you must do it time to time. No other way.

Existing indexes is automatically upgraded? - Yes. But it not help you when you will need to change some old-index settings.

To live with that, you need constantly invest a lot of power in ... forward compatibility of you apps/services with future releases of ES. Or you need to build(and anyway constantly support) some kind of middleware between you app/services and ES, which provide you back compatible client API. (And, you can't use Transport Client (because it required jar upgrade for every minor version ES upgrade), and this fact do not make your life easier)

Is it looks simple & cheap? No, it's not. Far from it. Continuous maintenance of complex infrastructure which based on ES, is way to expensive in all possible senses.

SECOND. Simple API ? Well... no really. When you is really using complex conditions and aggregations.... JSON-request with 5 nested levels is whatever, but not simple.


Unfortunately, I have no experience with SOLR, can't say anything about it.

But Sphinxsearch is much better it this scenario, becasue of totally back compatible SphinxQL.

Note: Sphinxsearch/Manticore are indeed interesting. It's not Lucine based, and as result seriously different. Contain several unique features from the box which ES do not have and crazy fast with small/middle size indexes.

How to select the comparison of two columns as one column in Oracle

If you want to consider null values equality too, try the following

select column1, column2, 
   case
      when column1 is NULL and column2 is NULL then 'true'  
      when column1=column2 then 'true' 
      else 'false' 
   end 
from table;

Why is the gets function so dangerous that it should not be used?

Because gets doesn't do any kind of check while getting bytes from stdin and putting them somewhere. A simple example:

char array1[] = "12345";
char array2[] = "67890";

gets(array1);

Now, first of all you are allowed to input how many characters you want, gets won't care about it. Secondly the bytes over the size of the array in which you put them (in this case array1) will overwrite whatever they find in memory because gets will write them. In the previous example this means that if you input "abcdefghijklmnopqrts" maybe, unpredictably, it will overwrite also array2 or whatever.

The function is unsafe because it assumes consistent input. NEVER USE IT!

Is it possible to use Visual Studio on macOS?

I recently purchased a MacBook Air (mid-2011 model) and was really happy to find that Apple officially supports Windows 7. If you purchase Windows 7 (I got DSP), you can use the Boot Camp assistant in OSX to designate part of your hard drive to Windows. Then you can install and run Windows 7 natively as if it were as Windows notebook.

I use Visual Studio 2010 on Windows 7 on my MacBook Air (I kept OSX as well) and I could not be happier. Heck, the initial start-up of the program only takes 3 seconds thanks to the SSD.

As others have mentions, you can run it on OSX using Parallels, etc. but I prefer to run it natively.

How to implement a queue using two stacks?

for c# developer here is the complete program :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QueueImplimentationUsingStack
{
    class Program
    {
        public class Stack<T>
        {
            public int size;
            public Node<T> head;
            public void Push(T data)
            {
                Node<T> node = new Node<T>();
                node.data = data;
                if (head == null)
                    head = node;
                else
                {
                    node.link = head;
                    head = node;
                }
                size++;
                Display();
            }
            public Node<T> Pop()
            {
                if (head == null)
                    return null;
                else
                {
                    Node<T> temp = head;
                    //temp.link = null;
                    head = head.link;
                    size--;
                    Display();
                    return temp;
                }
            }
            public void Display()
            {
                if (size == 0)
                    Console.WriteLine("Empty");
                else
                {
                    Console.Clear();
                    Node<T> temp = head;
                    while (temp!= null)
                    {
                        Console.WriteLine(temp.data);
                        temp = temp.link;
                    }
                }
            }
        }

        public class Queue<T>
        {
            public int size;
            public Stack<T> inbox;
            public Stack<T> outbox;
            public Queue()
            {
                inbox = new Stack<T>();
                outbox = new Stack<T>();
            }
            public void EnQueue(T data)
            {
                inbox.Push(data);
                size++;
            }
            public Node<T> DeQueue()
            {
                if (outbox.size == 0)
                {
                    while (inbox.size != 0)
                    {
                        outbox.Push(inbox.Pop().data);
                    }
                }
                Node<T> temp = new Node<T>();
                if (outbox.size != 0)
                {
                    temp = outbox.Pop();
                    size--;
                }
                return temp;
            }

        }
        public class Node<T>
        {
            public T data;
            public Node<T> link;
        }

        static void Main(string[] args)
        {
            Queue<int> q = new Queue<int>();
            for (int i = 1; i <= 3; i++)
                q.EnQueue(i);
           // q.Display();
            for (int i = 1; i < 3; i++)
                q.DeQueue();
            //q.Display();
            Console.ReadKey();
        }
    }
}

Inline instantiation of a constant List

You are looking for a simple code, like this:

    List<string> tagList = new List<string>(new[]
    {
         "A"
        ,"B"
        ,"C"
        ,"D"
        ,"E"
    });

What is a Java String's default initial value?

That depends. Is it just a variable (in a method)? Or a class-member?

If it's just a variable you'll get an error that no value has been set when trying to read from it without first assinging it a value.

If it's a class-member it will be initialized to null by the VM.

How do I move files in node.js?

util.pump is deprecated in node 0.10 and generates warning message

 util.pump() is deprecated. Use readableStream.pipe() instead

So the solution for copying files using streams is:

var source = fs.createReadStream('/path/to/source');
var dest = fs.createWriteStream('/path/to/dest');

source.pipe(dest);
source.on('end', function() { /* copied */ });
source.on('error', function(err) { /* error */ });

make: Nothing to be done for `all'

Make is behaving correctly. hello already exists and is not older than the .c files, and therefore there is no more work to be done. There are four scenarios in which make will need to (re)build:

  • If you modify one of your .c files, then it will be newer than hello, and then it will have to rebuild when you run make.
  • If you delete hello, then it will obviously have to rebuild it
  • You can force make to rebuild everything with the -B option. make -B all
  • make clean all will delete hello and require a rebuild. (I suggest you look at @Mat's comment about rm -f *.o hello

Skipping error in for-loop

Instead of catching the error, wouldn't it be possible to test in or before the myplotfunction() function first if the error will occur (i.e. if the breaks are unique) and only plot it for those cases where it won't appear?!

How do you comment an MS-access Query?

NOTE: Confirmed with Access 2003, don't know about earlier versions.

For a query in an MDB you can right-click in the query designer (anywhere in the empty space where the tables are), select Properties from the context menu, and enter text in the Description property.

You're limited to 256 characters, but it's better than nothing.

You can get at the description programatically with something like this:

Dim db As Database
Dim qry As QueryDef

Set db = Application.CurrentDb
Set qry = db.QueryDefs("myQuery")

Debug.Print qry.Properties("Description")

Manually highlight selected text in Notepad++

To highlight a block of code in Notepad++, please do the following steps

  1. Select the required text.
  2. Right click to display the context menu
  3. Choose Style token and select any of the five choices available ( styles from Using 1st style to using 5th style). Each is of different colors.If you want yellow color choose using 3rd style.

If you want to create your own style you can use Style Configurator under Settings menu.

How to embed a YouTube channel into a webpage

Seems like the accepted answer does not work anymore. I found the correct method from another post: https://stackoverflow.com/a/46811403/6368026

Now you should use:

http://www.youtube.com/embed/videoseries?list=USERID And the USERID is your youtube user id with 'UU' appended.

For example, if your user id is TlQ5niAIDsLdEHpQKQsupg then you should put UUTlQ5niAIDsLdEHpQKQsupg. If you only have the channel id (which you can find in your channel URL) then just replace the first two characters (UC) with UU.

So in the end you would have an URL like this:

http://www.youtube.com/embed/videoseries?list=UUTlQ5niAIDsLdEHpQKQsupg

How can I check if a string only contains letters in Python?

(1) Use str.isalpha() when you print the string.

(2) Please check below program for your reference:-

 str = "this";  # No space & digit in this string
 print str.isalpha() # it gives return True

 str = "this is 2";
 print str.isalpha() # it gives return False

Note:- I checked above example in Ubuntu.

SQL Server FOR EACH Loop

Here is an option with a table variable:

DECLARE @MyVar TABLE(Val DATETIME)
DECLARE @I INT, @StartDate DATETIME
SET @I = 1
SET @StartDate = '20100101'

WHILE @I <= 5
BEGIN
    INSERT INTO @MyVar(Val)
    VALUES(@StartDate)

    SET @StartDate = DATEADD(DAY,1,@StartDate)
    SET @I = @I + 1
END
SELECT *
FROM @MyVar

You can do the same with a temp table:

CREATE TABLE #MyVar(Val DATETIME)
DECLARE @I INT, @StartDate DATETIME
SET @I = 1
SET @StartDate = '20100101'

WHILE @I <= 5
BEGIN
    INSERT INTO #MyVar(Val)
    VALUES(@StartDate)

    SET @StartDate = DATEADD(DAY,1,@StartDate)
    SET @I = @I + 1
END
SELECT *
FROM #MyVar

You should tell us what is your main goal, as was said by @JohnFx, this could probably be done another (more efficient) way.

Ternary operator in AngularJS templates

This answer predates version 1.1.5 where a proper ternary in the $parse function wasn't available. Use this answer if you're on a lower version, or as an example of filters:

angular.module('myApp.filters', [])
  
  .filter('conditional', function() {
    return function(condition, ifTrue, ifFalse) {
      return condition ? ifTrue : ifFalse;
    };
  });

And then use it as

<i ng-class="checked | conditional:'icon-check':'icon-check-empty'"></i>

react-native - Fit Image in containing View, not the whole screen size

I think it's because you didn't specify the width and height for the item.

If you only want to have 2 images in a row, you can try something like this instead of using flex:

item: {
    width: '50%',
    height: '100%',
    overflow: 'hidden',
    alignItems: 'center',
    backgroundColor: 'orange',
    position: 'relative',
    margin: 10,
},

This works for me, hope it helps.

Change image source with JavaScript

I also tube that problem. But solve it by an instance of an image every time you change the source (image).

It seems that would be called onload only once. But this way, you can change image whenever you want.

function chageIcon(domImg,srcImage)
    {
        var img = new Image();
        img.onload = function()
        {
            // Load completed
            domImg.src = this.src;
        };
        img.src = srcImage;
    }

Mode use.

chageIcon(document.getElementById("img"),"newIcon.png");

How to close a GUI when I push a JButton?

In Java 8, you can use Lambda expressions to make it simpler.

Close application

JButton btnClose = new JButton("Close");
btnClose.addActionListener(e -> System.exit(0));

Close window

JButton btnClose = new JButton("Close");
btnClose.addActionListener(e -> this.dispose());

JavaScript set object key by variable

You need to make the object first, then use [] to set it.

var key = "happyCount";
var obj = {};
obj[key] = someValueArray;
myArray.push(obj);

UPDATE 2018:

If you're able to use ES6 and Babel, you can use this new feature:

{
    [yourKeyVariable]: someValueArray,
}  

How do I execute .js files locally in my browser?

If you're using Google Chrome you can use the Chrome Dev Editor: https://github.com/dart-lang/chromedeveditor

How to change visibility of layout programmatically

this is a programatical approach:

 view.setVisibility(View.GONE); //For GONE
 view.setVisibility(View.INVISIBLE); //For INVISIBLE
 view.setVisibility(View.VISIBLE); //For VISIBLE

How can I debug a HTTP POST in Chrome?

You can use Canary version of Chrome to see request payload of POST requests.

Request payload

How to Edit a row in the datatable

If your data set is too large first select required rows by Select(). it will stop further looping.

DataRow[] selected = table.Select("Product_id = 2")

Then loop through subset and update

    foreach (DataRow row in selected)
    {
        row["Product_price"] = "<new price>";
    }

Get installed applications in a system

it's worth noting that the Win32_Product WMI class represents products as they are installed by Windows Installer. not every application use windows installer

however "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" represents applications for 32 bit. For 64 bit you also need to traverse "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall" and since not every software has a 64 bit version the total applications installed are a union of keys on both locations that have "UninstallString" Value with them.

but the best options remains the same .traverse registry keys is a better approach since every application have an entry in registry[including the ones in Windows Installer].however the registry method is insecure as if anyone removes the corresponding key then you will not know the Application entry.On the contrary Altering the HKEY_Classes_ROOT\Installers is more tricky as it is linked with licensing issues such as Microsoft office or other products. for more robust solution you can always combine registry alternative with the WMI.

why is plotting with Matplotlib so slow?

Matplotlib makes great publication-quality graphics, but is not very well optimized for speed. There are a variety of python plotting packages that are designed with speed in mind:

Deep cloning objects

The reason not to use ICloneable is not because it doesn't have a generic interface. The reason not to use it is because it's vague. It doesn't make clear whether you're getting a shallow or a deep copy; that's up to the implementer.

Yes, MemberwiseClone makes a shallow copy, but the opposite of MemberwiseClone isn't Clone; it would be, perhaps, DeepClone, which doesn't exist. When you use an object through its ICloneable interface, you can't know which kind of cloning the underlying object performs. (And XML comments won't make it clear, because you'll get the interface comments rather than the ones on the object's Clone method.)

What I usually do is simply make a Copy method that does exactly what I want.

Can I concatenate multiple MySQL rows into one field?

You can use GROUP_CONCAT:

SELECT person_id,
   GROUP_CONCAT(hobbies SEPARATOR ', ')
FROM peoples_hobbies
GROUP BY person_id;

As Ludwig stated in his comment, you can add the DISTINCT operator to avoid duplicates:

SELECT person_id,
   GROUP_CONCAT(DISTINCT hobbies SEPARATOR ', ')
FROM peoples_hobbies
GROUP BY person_id;

As Jan stated in their comment, you can also sort the values before imploding it using ORDER BY:

SELECT person_id, 
       GROUP_CONCAT(hobbies ORDER BY hobbies ASC SEPARATOR ', ')
FROM peoples_hobbies
GROUP BY person_id;

As Dag stated in his comment, there is a 1024 byte limit on the result. To solve this, run this query before your query:

SET group_concat_max_len = 2048;

Of course, you can change 2048 according to your needs. To calculate and assign the value:

SET group_concat_max_len = CAST(
                     (SELECT SUM(LENGTH(hobbies)) + COUNT(*) * LENGTH(', ')
                           FROM peoples_hobbies
                           GROUP BY person_id) AS UNSIGNED);

PHP array printing using a loop

for using both things variables value and kye

foreach($array as $key=>$value){
 print "$key holds $value\n";
}

for using variables value only

foreach($array as $value){
 print $value."\n";
}

if you want to do something repeatedly until equal the length of array us this

// for loop
for($i = 0; $i < count($array); $i++) {
 // do something with $array[$i]
}

Thanks!

How to run Unix shell script from Java code?

You can use Apache Commons exec library also.

Example :

package testShellScript;

import java.io.IOException;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteException;

public class TestScript {
    int iExitValue;
    String sCommandString;

    public void runScript(String command){
        sCommandString = command;
        CommandLine oCmdLine = CommandLine.parse(sCommandString);
        DefaultExecutor oDefaultExecutor = new DefaultExecutor();
        oDefaultExecutor.setExitValue(0);
        try {
            iExitValue = oDefaultExecutor.execute(oCmdLine);
        } catch (ExecuteException e) {
            System.err.println("Execution failed.");
            e.printStackTrace();
        } catch (IOException e) {
            System.err.println("permission denied.");
            e.printStackTrace();
        }
    }

    public static void main(String args[]){
        TestScript testScript = new TestScript();
        testScript.runScript("sh /root/Desktop/testScript.sh");
    }
}

For further reference, An example is given on Apache Doc also.

How to add noise (Gaussian/salt and pepper etc) to image in Python with OpenCV

I don't know is there any method in Python API.But you can use this simple code to add Salt-and-Pepper noise to an image.

import numpy as np
import random
import cv2

def sp_noise(image,prob):
    '''
    Add salt and pepper noise to image
    prob: Probability of the noise
    '''
    output = np.zeros(image.shape,np.uint8)
    thres = 1 - prob 
    for i in range(image.shape[0]):
        for j in range(image.shape[1]):
            rdn = random.random()
            if rdn < prob:
                output[i][j] = 0
            elif rdn > thres:
                output[i][j] = 255
            else:
                output[i][j] = image[i][j]
    return output

image = cv2.imread('image.jpg',0) # Only for grayscale image
noise_img = sp_noise(image,0.05)
cv2.imwrite('sp_noise.jpg', noise_img)

Python - Move and overwrite files and folders

I had a similar problem. I wanted to move files and folder structures and overwrite existing files, but not delete anything which is in the destination folder structure.

I solved it by using os.walk(), recursively calling my function and using shutil.move() on files which I wanted to overwrite and folders which did not exist.

It works like shutil.move(), but with the benefit that existing files are only overwritten, but not deleted.

import os
import shutil

def moverecursively(source_folder, destination_folder):
    basename = os.path.basename(source_folder)
    dest_dir = os.path.join(destination_folder, basename)
    if not os.path.exists(dest_dir):
        shutil.move(source_folder, destination_folder)
    else:
        dst_path = os.path.join(destination_folder, basename)
        for root, dirs, files in os.walk(source_folder):
            for item in files:
                src_path = os.path.join(root, item)
                if os.path.exists(dst_file):
                    os.remove(dst_file)
                shutil.move(src_path, dst_path)
            for item in dirs:
                src_path = os.path.join(root, item)
                moverecursively(src_path, dst_path)

NPM doesn't install module dependencies

It looks like you hit a bug that has existed for quite a while and doesn't have solution yet. There are several open issues for this case in the npm repository:

In the first one people list several workarounds that you may try.

An alternative solution may be (a little hackish) to explicitly list the dependencies as first level dependents. This requires you to maintain the list but practically it has to be done very infrequently.

Removing trailing newline character from fgets() input

size_t ln = strlen(name) - 1;
if (*name && name[ln] == '\n') 
    name[ln] = '\0';

Use ASP.NET MVC validation with jquery ajax?

You can do it this way:

(Edit: Considering that you're waiting for a response json with dataType: 'json')

.NET

public JsonResult Edit(EditPostViewModel data)
{
    if(ModelState.IsValid) 
    {
       // Save  
       return Json(new { Ok = true } );
    }

    return Json(new { Ok = false } );
}

JS:

success: function (data) {
    if (data.Ok) {
      alert('success');
    }
    else {
      alert('problem');
    }
},

If you need I can also explain how to do it by returning a error 500, and get the error in the event error (ajax). But in your case this may be an option

How to remove/delete a large file from commit history in Git repository?

If you know your commit was recent instead of going through the entire tree do the following: git filter-branch --tree-filter 'rm LARGE_FILE.zip' HEAD~10..HEAD

Create comma separated strings C#?

You can use the string.Join method to do something like string.Join(",", o.Number, o.Id, o.whatever, ...).

edit: As digEmAll said, string.Join is faster than StringBuilder. They use an external implementation for the string.Join.

Profiling code (of course run in release without debug symbols):

class Program
{
    static void Main(string[] args)
    {
        Stopwatch sw = new Stopwatch();
        string r;
        int iter = 10000;

        string[] values = { "a", "b", "c", "d", "a little bit longer please", "one more time" };

        sw.Restart();
        for (int i = 0; i < iter; i++)
            r = Program.StringJoin(",", values);
        sw.Stop();
        Console.WriteLine("string.Join ({0} times): {1}ms", iter, sw.ElapsedMilliseconds);

        sw.Restart();
        for (int i = 0; i < iter; i++)
            r = Program.StringBuilderAppend(",", values);
        sw.Stop();
        Console.WriteLine("StringBuilder.Append ({0} times): {1}ms", iter, sw.ElapsedMilliseconds);
        Console.ReadLine();
    }

    static string StringJoin(string seperator, params string[] values)
    {
        return string.Join(seperator, values);
    }

    static string StringBuilderAppend(string seperator, params string[] values)
    {
        StringBuilder builder = new StringBuilder();
        builder.Append(values[0]);
        for (int i = 1; i < values.Length; i++)
        {
            builder.Append(seperator);
            builder.Append(values[i]);
        }
        return builder.ToString();
    }
}

string.Join took 2ms on my machine and StringBuilder.Append 5ms. So there is noteworthy difference. Thanks to digAmAll for the hint.

seek() function?

Regarding seek() there's not too much to worry about.

First of all, it is useful when operating over an open file.

It's important to note that its syntax is as follows:

fp.seek(offset, from_what)

where fp is the file pointer you're working with; offset means how many positions you will move; from_what defines your point of reference:

  • 0: means your reference point is the beginning of the file
  • 1: means your reference point is the current file position
  • 2: means your reference point is the end of the file

if omitted, from_what defaults to 0.

Never forget that when managing files, there'll always be a position inside that file where you are currently working on. When just open, that position is the beginning of the file, but as you work with it, you may advance.
seek will be useful to you when you need to walk along that open file, just as a path you are traveling into.

The transaction log for database is full. To find out why space in the log cannot be reused, see the log_reuse_wait_desc column in sys.databases

As an aside, it is always a good practice (and possibly a solution for this type of issue) to delete a large number of rows by using batches:

WHILE EXISTS (SELECT 1 
              FROM   YourTable 
              WHERE  <yourCondition>) 
  DELETE TOP(10000) FROM YourTable 
  WHERE  <yourCondition>

How can I make a div stick to the top of the screen once it's been scrolled to?

You've seen this example on Google Code's issue page and (only recently) on Stack Overflow's edit page.

CMS's answer doesn't revert the positioning when you scroll back up. Here's the shamelessly stolen code from Stack Overflow:

function moveScroller() {
    var $anchor = $("#scroller-anchor");
    var $scroller = $('#scroller');

    var move = function() {
        var st = $(window).scrollTop();
        var ot = $anchor.offset().top;
        if(st > ot) {
            $scroller.css({
                position: "fixed",
                top: "0px"
            });
        } else {
            $scroller.css({
                position: "relative",
                top: ""
            });
        }
    };
    $(window).scroll(move);
    move();
}
<div id="sidebar" style="width:270px;"> 
  <div id="scroller-anchor"></div> 
  <div id="scroller" style="margin-top:10px; width:270px"> 
    Scroller Scroller Scroller
  </div>
</div>

<script type="text/javascript"> 
  $(function() {
    moveScroller();
  });
</script> 

And a simple live demo.

A nascent, script-free alternative is position: sticky, which is supported in Chrome, Firefox, and Safari. See the article on HTML5Rocks and demo, and Mozilla docs.

What are the best use cases for Akka framework

If you abstract the chat server up a level, then you get the answer.

Akka provides a messaging system that is akin to Erlang's "let it crash" mentality.

So examples are things that need varying levels of durability and reliability of messaging:

  • Chat server
  • Network layer for an MMO
  • Financial data pump
  • Notification system for an iPhone/mobile/whatever app
  • REST Server
  • Maybe something akin to WebMachine (guess)

The nice things about Akka are the choices it affords for persistence, it's STM implementation, REST server and fault-tolerance.

Don't get annoyed by the example of a chat server, think of it as an example of a certain class of solution.

With all their excellent documentation, I feel like a gap is this exact question, use-cases and examples. Keeping in mind the examples are non-trivial.

(Written with only experience of watching videos and playing with the source, I have implemented nothing using akka.)

Creating a 3D sphere in Opengl using Visual C++

I like the answer of coin. It's simple to understand and works with triangles. However the indexes of his program are sometimes over the bounds. So I post here his code with two tiny corrections:

inline void push_indices(vector<GLushort>& indices, int sectors, int r, int s) {
    int curRow = r * sectors;
    int nextRow = (r+1) * sectors;
    int nextS = (s+1) % sectors;

    indices.push_back(curRow + s);
    indices.push_back(nextRow + s);
    indices.push_back(nextRow + nextS);

    indices.push_back(curRow + s);
    indices.push_back(nextRow + nextS);
    indices.push_back(curRow + nextS);
}

void createSphere(vector<vec3>& vertices, vector<GLushort>& indices, vector<vec2>& texcoords,
                  float radius, unsigned int rings, unsigned int sectors)
{
    float const R = 1./(float)(rings-1);
    float const S = 1./(float)(sectors-1);

    for(int r = 0; r < rings; ++r) {
        for(int s = 0; s < sectors; ++s) {
            float const y = sin( -M_PI_2 + M_PI * r * R );
            float const x = cos(2*M_PI * s * S) * sin( M_PI * r * R );
            float const z = sin(2*M_PI * s * S) * sin( M_PI * r * R );

            texcoords.push_back(vec2(s*S, r*R));
            vertices.push_back(vec3(x,y,z) * radius);
            if(r < rings-1)
                push_indices(indices, sectors, r, s);
        }
    }
}

How do you create optional arguments in php?

The default value of the argument must be a constant expression. It can't be a variable or a function call.

If you need this functionality however:

function foo($foo, $bar = false)
{
    if(!$bar)
    {
        $bar = $foo;
    }
}

Assuming $bar isn't expected to be a boolean of course.

How to check if input file is empty in jQuery

Just check the length of files property, which is a FileList object contained on the input element

if( document.getElementById("videoUploadFile").files.length == 0 ){
    console.log("no files selected");
}

Programmatically get height of navigation bar

My application has a couple views that required a customized navigation bar in the UI for look & feel, however without navigation controller. And the application is required to support iOS version prior to iOS 11, so the handy safe area layout guide could not be used, and I have to adjust the position and height of navigation bar programmatically.

I attached the Navigation Bar to its superview directly, skipping the safe area layout guide as mentioned above. And the status bar height could be retrieved from UIApplication easily, but the default navigation bar height is really a pain-ass...

It struck me for almost half a night, with a number of searching and testing, until I finally got the hint from another post (not working to me though), that you could actually get the height from UIView.sizeThatFits(), like this:

- (void)viewWillLayoutSubviews {
    self.topBarHeightConstraint.constant = [UIApplication sharedApplication].statusBarFrame.size.height;
    self.navBarHeightConstraint.constant = [self.navigationBar sizeThatFits:CGSizeZero].height;

    [super viewWillLayoutSubviews];    
}

Finally, a perfect navigation bar looking exactly the same as the built-in one!

int to string in MySQL

Try it using CONCAT

CONCAT('site.com/path/','%', CAST(t1.id AS CHAR(25)), '%','/more')

How to check a string against null in java?

import it in your class

import org.apache.commons.lang.StringUtils;

then use it, they both will return true

System.out.println(StringUtils.isEmpty(""));
System.out.println(StringUtils.isEmpty(null)); 

Unable to load config info from /usr/local/ssl/openssl.cnf on Windows

After installing OpenSSL, you need to restart your computer and use Run As Administrator. Then its works.

How to convert NSData to byte array in iPhone?

You can't declare an array using a variable so Byte byteData[len]; won't work. If you want to copy the data from a pointer, you also need to memcpy (which will go through the data pointed to by the pointer and copy each byte up to a specified length).

Try:

NSData *data = [NSData dataWithContentsOfFile:filePath];
NSUInteger len = [data length];
Byte *byteData = (Byte*)malloc(len);
memcpy(byteData, [data bytes], len);

This code will dynamically allocate the array to the correct size (you must free(byteData) when you're done) and copy the bytes into it.

You could also use getBytes:length: as indicated by others if you want to use a fixed length array. This avoids malloc/free but is less extensible and more prone to buffer overflow issues so I rarely ever use it.

How to Set Variables in a Laravel Blade Template

In Laravel 5.1, 5.2:

https://laravel.com/docs/5.2/views#sharing-data-with-all-views

You may need to share a piece of data with all views that are rendered by your application. You may do so using the view factory's share method. Typically, you should place calls to share within a service provider's boot method. You are free to add them to the AppServiceProvider or generate a separate service provider to house them.

Edit file: /app/Providers/AppServiceProvider.php

<?php

namespace App\Providers;

class AppServiceProvider extends ServiceProvider
{        
    public function boot()
    {
        view()->share('key', 'value');
    }

    public function register()
    {
        // ...
    }
}

Timing Delays in VBA

Access can always use the Excel procedure as long as the project has the Microsoft Excel XX.X object reference included:

Call Excel.Application.Wait(DateAdd("s",10,Now()))

How do I execute a program from Python? os.system fails due to spaces in path

subprocess.call will avoid problems with having to deal with quoting conventions of various shells. It accepts a list, rather than a string, so arguments are more easily delimited. i.e.

import subprocess
subprocess.call(['C:\\Temp\\a b c\\Notepad.exe', 'C:\\test.txt'])

How to resolve javax.mail.AuthenticationFailedException issue?

The problem is, you are creating a transport object and using it's connect method to authenticate yourself. But then you use a static method to send the message which ignores authentication done by the object.

So, you should either use the sendMessage(message, message.getAllRecipients()) method on the object or use an authenticator as suggested by others to get authorize through the session.

Here's the Java Mail FAQ, you need to read.

Convert date to YYYYMM format

SELECT LEFT(CONVERT(varchar, GetDate(),112),6)

How to install CocoaPods?

FOR EL CAPITAN

rvm install ruby-2.2.2.

rvm use ruby-2.2.2.

sudo gem install -n /usr/local/bin cocoapods

How to quickly form groups (quartiles, deciles, etc) by ordering column(s) in a data frame

There's a handy ntile function in package dplyr. It's flexible in the sense that you can very easily define the number of *tiles or "bins" you want to create.

Load the package (install first if you haven't) and add the quartile column:

library(dplyr)
temp$quartile <- ntile(temp$value, 4)  

Or, if you want to use dplyr syntax:

temp <- temp %>% mutate(quartile = ntile(value, 4))

Result in both cases is:

temp
#   name       value quartile
#1     a -0.56047565        1
#2     b -0.23017749        2
#3     c  1.55870831        4
#4     d  0.07050839        2
#5     e  0.12928774        3
#6     f  1.71506499        4
#7     g  0.46091621        3
#8     h -1.26506123        1
#9     i -0.68685285        1
#10    j -0.44566197        2
#11    k  1.22408180        4
#12    l  0.35981383        3

data:

Note that you don't need to create the "quartile" column in advance and use set.seed to make the randomization reproducible:

set.seed(123)
temp <- data.frame(name=letters[1:12], value=rnorm(12))

disable horizontal scroll on mobile web

Simply add this CSS:

html, body {
  overflow-x: hidden;
}
body {
  position: relative
}

Can't concat bytes to str

You can convert type of plaintext to string:

f.write(str(plaintext) + '\n')

How can I solve a connection pool problem between ASP.NET and SQL Server?

Use this:

finally
{
    connection.Close();
    connection.Dispose();
    SqlConnection.ClearPool();
}

How to fix .pch file missing on build?

  1. Right click to the project and select the property menu item
  2. goto C/C++ -> Precompiled Headers
  3. Select Not Using Precompiled Headers

Where is GACUTIL for .net Framework 4.0 in windows 7?

There is no Gacutil included in the .net 4.0 standard installation. They have moved the GAC too, from %Windir%\assembly to %Windir%\Microsoft.NET\Assembly.

They havent' even bothered adding a "special view" for the folder in Windows explorer, as they have for the .net 1.0/2.0 GAC.

Gacutil is part of the Windows SDK, so if you want to use it on your developement machine, just install the Windows SDK for your current platform. Then you will find it somewhere like this (depending on your SDK version):

C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\NETFX 4.0 Tools

There is a discussion on the new GAC here: .NET 4.0 has a new GAC, why?

If you want to install something in GAC on a production machine, you need to do it the "proper" way (gacutil was never meant as a tool for installing stuff on production servers, only as a development tool), with a Windows Installer, or with other tools. You can e.g. do it with PowerShell and the System.EnterpriseServices dll.

On a general note, and coming from several years of experience, I would personally strongly recommend against using GAC at all. Your application will always work if you deploy the DLL with each application in its bin folder as well. Yes, you will get multiple copies of the DLL on your server if you have e.g. multiple web apps on one server, but it's definitely worth the flexibility of being able to upgrade one application without breaking the others (by introducing an incompatible version of the shared DLL in the GAC).

How to get all of the IDs with jQuery?

My suggestion?

var arr = $.map($("#mydiv [id]"), function(n, i) {
  return n.id;
});

you could also do this as:

var arr = $.map($("#mydiv span"), function(n, i) {

or

var arr = $.map($("#mydiv span[id]"), function(n, i) {

or even just:

var arr = $("#mydiv [id]").map(function() {
  return this.id;
});

Lots of ways basically.

Hibernate Query By Example and Projections

The real problem here is that there is a bug in hibernate where it uses select-list aliases in the where-clause:

http://opensource.atlassian.com/projects/hibernate/browse/HHH-817

Just in case someone lands here looking for answers, go look at the ticket. It took 5 years to fix but in theory it'll be in one of the next releases and then I suspect your issue will go away.

Twitter Bootstrap Multilevel Dropdown Menu

Updated Answer

* Updated answer which support the v2.1.1** bootstrap version stylesheet.

**But be careful because this solution has been removed from v3

Just wanted to point out that this solution is not needed anymore as the latest bootstrap now supports multi-level dropdowns by default. You can still use it if you're on older versions but for those who updated to the latest (v2.1.1 at the time of writing) it is not needed anymore. Here is a fiddle with the updated default multi-level dropdown straight from the documentation:

http://jsfiddle.net/2Smgv/2858/


Original Answer

There have been some issues raised on submenu support over at github and they are usually closed by the bootstrap developers, such as this one, so i think it is left to the developers using the bootstrap to work something out. Here is a demo i put together showing you how you can hack together a working sub-menu.

Relevant code

CSS

.dropdown-menu .sub-menu {
    left: 100%;
    position: absolute;
    top: 0;
    visibility: hidden;
    margin-top: -1px;
}

.dropdown-menu li:hover .sub-menu {
    visibility: visible;
    display: block;
}

.navbar .sub-menu:before {
    border-bottom: 7px solid transparent;
    border-left: none;
    border-right: 7px solid rgba(0, 0, 0, 0.2);
    border-top: 7px solid transparent;
    left: -7px;
    top: 10px;
}
.navbar .sub-menu:after {
    border-top: 6px solid transparent;
    border-left: none;
    border-right: 6px solid #fff;
    border-bottom: 6px solid transparent;
    left: 10px;
    top: 11px;
    left: -6px;
}

Created my own .sub-menu class to apply to the 2-level drop down menus, this way we can position them next to our menu items. Also modified the arrow to display it on the left of the submenu group.

Demo

Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

I encountered the same error and got stalled with a pyspark dataframe for few days, I was able to resolve it successfully by filling na values with 0 since I was comparing integer values from 2 fields.

Remove scrollbars from textarea

style="overflow: hidden" and style="resize: none" were the ones that did the trick.

Graphviz's executables are not found (Python 3.4)

I was stuck for a very long time at this problem but after sometime I found a solution:

How do I script a "yes" response for installing programs?

Although this may be more complicated/heavier-weight than you want, one very flexible way to do it is using something like Expect (or one of the derivatives in another programming language).

Expect is a language designed specifically to control text-based applications, which is exactly what you are looking to do. If you end up needing to do something more complicated (like with logic to actually decide what to do/answer next), Expect is the way to go.

Disable the postback on an <ASP:LinkButton>

You can do it too

...LinkButton ID="BtnForgotPassword" runat="server" OnClientClick="ChangeText('1');return false"...

And it stop the link button postback

Manually raising (throwing) an exception in Python

You should learn the raise statement of python for that. It should be kept inside the try block. Example -

try:
    raise TypeError            #remove TypeError by any other error if you want
except TypeError:
    print('TypeError raised')

PHP Parse error: syntax error, unexpected T_PUBLIC

You can remove public keyword from your functions, because, you have to define a class in order to declare public, private or protected function

In Django, how do I check if a user is in a certain group?

You can access the groups simply through the groups attribute on User.

from django.contrib.auth.models import User, Group

group = Group(name = "Editor")
group.save()                    # save this new group for this example
user = User.objects.get(pk = 1) # assuming, there is one initial user 
user.groups.add(group)          # user is now in the "Editor" group

then user.groups.all() returns [<Group: Editor>].

Alternatively, and more directly, you can check if a a user is in a group by:

if django_user.groups.filter(name = groupname).exists():

    ...

Note that groupname can also be the actual Django Group object.

How to clear input buffer in C?

I am surprised nobody mentioned this:

scanf("%*[^\n]");

How to remove all duplicate items from a list

The modern way to do it that maintains the order is:

>>> from collections import OrderedDict
>>> list(OrderedDict.fromkeys(lseparatedOrbList))

as discussed by Raymond Hettinger (python core dev) in this answer. In python 3.5 and above this is also the fastest way - see the linked answer for details. However the keys must be hashable (as is the case in your list I think)

Shuffle DataFrame rows

The idiomatic way to do this with Pandas is to use the .sample method of your dataframe to sample all rows without replacement:

df.sample(frac=1)

The frac keyword argument specifies the fraction of rows to return in the random sample, so frac=1 means return all rows (in random order).


Note: If you wish to shuffle your dataframe in-place and reset the index, you could do e.g.

df = df.sample(frac=1).reset_index(drop=True)

Here, specifying drop=True prevents .reset_index from creating a column containing the old index entries.

Follow-up note: Although it may not look like the above operation is in-place, python/pandas is smart enough not to do another malloc for the shuffled object. That is, even though the reference object has changed (by which I mean id(df_old) is not the same as id(df_new)), the underlying C object is still the same. To show that this is indeed the case, you could run a simple memory profiler:

$ python3 -m memory_profiler .\test.py
Filename: .\test.py

Line #    Mem usage    Increment   Line Contents
================================================
     5     68.5 MiB     68.5 MiB   @profile
     6                             def shuffle():
     7    847.8 MiB    779.3 MiB       df = pd.DataFrame(np.random.randn(100, 1000000))
     8    847.9 MiB      0.1 MiB       df = df.sample(frac=1).reset_index(drop=True)

Non-numeric Argument to Binary Operator Error in R

Because your question is phrased regarding your error message and not whatever your function is trying to accomplish, I will address the error.

- is the 'binary operator' your error is referencing, and either CurrentDay or MA (or both) are non-numeric.

A binary operation is a calculation that takes two values (operands) and produces another value (see wikipedia for more). + is one such operator: "1 + 1" takes two operands (1 and 1) and produces another value (2). Note that the produced value isn't necessarily different from the operands (e.g., 1 + 0 = 1).

R only knows how to apply + (and other binary operators, such as -) to numeric arguments:

> 1 + 1
[1] 2
> 1 + 'one'
Error in 1 + "one" : non-numeric argument to binary operator

When you see that error message, it means that you are (or the function you're calling is) trying to perform a binary operation with something that isn't a number.

EDIT:

Your error lies in the use of [ instead of [[. Because Day is a list, subsetting with [ will return a list, not a numeric vector. [[, however, returns an object of the class of the item contained in the list:

> Day <- Transaction(1, 2)["b"]
> class(Day)
[1] "list"
> Day + 1
Error in Day + 1 : non-numeric argument to binary operator

> Day2 <- Transaction(1, 2)[["b"]]
> class(Day2)
[1] "numeric"
> Day2 + 1
[1] 3

Transaction, as you've defined it, returns a list of two vectors. Above, Day is a list contain one vector. Day2, however, is simply a vector.

Do I need to compile the header files in a C program?

I think we do need preprocess(maybe NOT call the compile) the head file. Because from my understanding, during the compile stage, the head file should be included in c file. For example, in test.h we have

typedef enum{
    a,
    b,
    c
}test_t

and in test.c we have

void foo()
{
    test_t test;
    ...
}

during the compile, i think the compiler will put the code in head file and c file together and code in head file will be pre-processed and substitute the code in c file. Meanwhile, we'd better to define the include path in makefile.

EC2 instance types's exact network performance?

Bandwidth is tiered by instance size, here's a comprehensive answer:

For t2/m3/c3/c4/r3/i2/d2 instances:

  • t2.nano = ??? (Based on the scaling factors, I'd expect 20-30 MBit/s)
  • t2.micro = ~70 MBit/s (qiita says 63 MBit/s) - t1.micro gets about ~100 Mbit/s
  • t2.small = ~125 MBit/s (t2, qiita says 127 MBit/s, cloudharmony says 125 Mbit/s with spikes to 200+ Mbit/s)
  • *.medium = t2.medium gets 250-300 MBit/s, m3.medium ~400 MBit/s
  • *.large = ~450-600 MBit/s (the most variation, see below)
  • *.xlarge = 700-900 MBit/s
  • *.2xlarge = ~1 GBit/s +- 10%
  • *.4xlarge = ~2 GBit/s +- 10%
  • *.8xlarge and marked specialty = 10 Gbit, expect ~8.5 GBit/s, requires enhanced networking & VPC for full throughput

m1 small, medium, and large instances tend to perform higher than expected. c1.medium is another freak, at 800 MBit/s.

I gathered this by combing dozens of sources doing benchmarks (primarily using iPerf & TCP connections). Credit to CloudHarmony & flux7 in particular for many of the benchmarks (note that those two links go to google searches showing the numerous individual benchmarks).

Caveats & Notes:

The large instance size has the most variation reported:

  • m1.large is ~800 Mbit/s (!!!)
  • t2.large = ~500 MBit/s
  • c3.large = ~500-570 Mbit/s (different results from different sources)
  • c4.large = ~520 MBit/s (I've confirmed this independently, by the way)
  • m3.large is better at ~700 MBit/s
  • m4.large is ~445 Mbit/s
  • r3.large is ~390 Mbit/s

Burstable (T2) instances appear to exhibit burstable networking performance too:

  • The CloudHarmony iperf benchmarks show initial transfers start at 1 GBit/s and then gradually drop to the sustained levels above after a few minutes. PDF links to reports below:

  • t2.small (PDF)

  • t2.medium (PDF)
  • t2.large (PDF)

Note that these are within the same region - if you're transferring across regions, real performance may be much slower. Even for the larger instances, I'm seeing numbers of a few hundred MBit/s.

What are ABAP and SAP?

In addition to all the regular confusion around SAP issues might also stem form the fact that SAP used to have their own DBMS ..

It used to be called Adabas (marketed originally by Nixdorf and then by Software AG) and was a quite popular DBMS for smaller SAP (the ERP solution) installations in Germany. At some point (AFAIK around 2000) SAP started to co-develop/support/take over Adabas and marketed it as SAP DB and later MaxDB under commercial and open-source licenses. There also was/is some agreement with MySQL.

But when people talk about SAP, they usually refer to the ERP solution as the other posters have noted.

SELECT INTO a table variable in T-SQL

You could try using temporary tables...if you are not doing it from an application. (It may be ok to run this manually)

SELECT name, location INTO #userData FROM myTable
INNER JOIN otherTable ON ...
WHERE age>30

You skip the effort to declare the table that way... Helps for adhoc queries...This creates a local temp table which wont be visible to other sessions unless you are in the same session. Maybe a problem if you are running query from an app.

if you require it to running on an app, use variables declared this way :

DECLARE @userData TABLE(
    name varchar(30) NOT NULL,
    oldlocation varchar(30) NOT NULL
);

INSERT INTO @userData
SELECT name, location FROM myTable
INNER JOIN otherTable ON ...
WHERE age > 30;

Edit: as many of you mentioned updated visibility to session from connection. Creating temp tables is not an option for web applications, as sessions can be reused, stick to temp variables in those cases

Dump all documents of Elasticsearch

ElasticSearch itself provides a way to create data backup and restoration. The simple command to do it is:

CURL -XPUT 'localhost:9200/_snapshot/<backup_folder name>/<backupname>' -d '{
    "indices": "<index_name>",
    "ignore_unavailable": true,
    "include_global_state": false
}'

Now, how to create, this folder, how to include this folder path in ElasticSearch configuration, so that it will be available for ElasticSearch, restoration method, is well explained here. To see its practical demo surf here.

Checkout old commit and make it a new commit

The other answers so far create new commits that undo what is in older commits. It is possible to go back and "change history" as it were, but this can be a bit dangerous. You should only do this if the commit you're changing has not been pushed to other repositories.

The command you're looking for is git rebase --interactive

If you want to change HEAD~3, the command you want to issue is git rebase --interactive HEAD~4. This will open a text editor and allow you to specify which commits you want to change.

Practice on a different repository before you try this with something important. The man pages should give you all the rest of the information you need.

Import JavaScript file and call functions using webpack, ES6, ReactJS

Named exports:

Let's say you create a file called utils.js, with utility functions that you want to make available for other modules (e.g. a React component). Then you would make each function a named export:

export function add(x, y) {
  return x + y
}

export function mutiply(x, y) {
  return x * y
}

Assuming that utils.js is located in the same directory as your React component, you can use its exports like this:

import { add, multiply } from './utils.js';
...
add(2, 3) // Can be called wherever in your component, and would return 5.

Or if you prefer, place the entire module's contents under a common namespace:

import * as utils from './utils.js'; 
...
utils.multiply(2,3)

Default exports:

If you on the other hand have a module that only does one thing (could be a React class, a normal function, a constant, or anything else) and want to make that thing available to others, you can use a default export. Let's say we have a file log.js, with only one function that logs out whatever argument it's called with:

export default function log(message) {
  console.log(message);
}

This can now be used like this:

import log from './log.js';
...
log('test') // Would print 'test' in the console.

You don't have to call it log when you import it, you could actually call it whatever you want:

import logToConsole from './log.js';
...
logToConsole('test') // Would also print 'test' in the console.

Combined:

A module can have both a default export (max 1), and named exports (imported either one by one, or using * with an alias). React actually has this, consider:

import React, { Component, PropTypes } from 'react';

sequelize findAll sort order in nodejs

You can accomplish this in a very back-handed way with the following code:

exports.getStaticCompanies = function () {
    var ids = [46128, 2865, 49569, 1488, 45600, 61991, 1418, 61919, 53326, 61680]
    return Company.findAll({
        where: {
            id: ids
        },
        attributes: ['id', 'logo_version', 'logo_content_type', 'name', 'updated_at'],
        order: sequelize.literal('(' + ids.map(function(id) {
            return '"Company"."id" = \'' + id + '\'');
        }).join(', ') + ') DESC')
    });
};

This is somewhat limited because it's got very bad performance characteristics past a few dozen records, but it's acceptable at the scale you're using.

This will produce a SQL query that looks something like this:

[...] ORDER BY ("Company"."id"='46128', "Company"."id"='2865', "Company"."id"='49569', [...])

ViewDidAppear is not called when opening app from background

I think registering for the UIApplicationWillEnterForegroundNotification is risky as you may end up with more than one controller reacting to that notification. Nothing garanties that these controllers are still visible when the notification is received.

Here is what I do: I force call viewDidAppear on the active controller directly from the App's delegate didBecomeActive method:

Add the code below to - (void)applicationDidBecomeActive:(UIApplication *)application

UIViewController *activeController = window.rootViewController;
if ([activeController isKindOfClass:[UINavigationController class]]) {
    activeController = [(UINavigationController*)window.rootViewController topViewController];
}
[activeController viewDidAppear:NO];

How to download a file using a Java REST service and a data stream

See example here: Input and Output binary streams using JERSEY?

Pseudo code would be something like this (there are a few other similar options in above mentioned post):

@Path("file/")
@GET
@Produces({"application/pdf"})
public StreamingOutput getFileContent() throws Exception {
     public void write(OutputStream output) throws IOException, WebApplicationException {
        try {
          //
          // 1. Get Stream to file from first server
          //
          while(<read stream from first server>) {
              output.write(<bytes read from first server>)
          }
        } catch (Exception e) {
            throw new WebApplicationException(e);
        } finally {
              // close input stream
        }
    }
}

How do I move focus to next input with jQuery?

why not simply just give the input field where you want to jump to a id and do a simple focus

$("#newListField").focus();

ip address validation in python using regex

try:
    parts = ip.split('.')
    return len(parts) == 4 and all(0 <= int(part) < 256 for part in parts)
except ValueError:
    return False # one of the 'parts' not convertible to integer
except (AttributeError, TypeError):
    return False # `ip` isn't even a string

How do I use typedef and typedef enum in C?

typedef defines a new data type. So you can have:

typedef char* my_string;
typedef struct{
  int member1;
  int member2;
} my_struct;

So now you can declare variables with these new data types

my_string s;
my_struct x;

s = "welcome";
x.member1 = 10;

For enum, things are a bit different - consider the following examples:

enum Ranks {FIRST, SECOND};
int main()
{
   int data = 20;
   if (data == FIRST)
   {
      //do something
   }
}

using typedef enum creates an alias for a type:

typedef enum Ranks {FIRST, SECOND} Order;
int main()
{
   Order data = (Order)20;  // Must cast to defined type to prevent error

   if (data == FIRST)
   {
      //do something
   }
}

What is this: [Ljava.lang.Object;?

If you are here because of the Liquibase error saying:

Caused By: Precondition Error
...
Can't detect type of array [Ljava.lang.Short

and you are using

not {
  indexExists()
}

precondition multiple times, then you are facing an old bug: https://liquibase.jira.com/browse/CORE-1342

We can try to execute an above check using bare sqlCheck(Postgres):

SELECT COUNT(i.relname)
FROM
    pg_class t,
    pg_class i,
    pg_index ix
WHERE
    t.oid = ix.indrelid
    and i.oid = ix.indexrelid
    and t.relkind = 'r'
    and t.relname = 'tableName'
    and i.relname = 'indexName';

where tableName - is an index table name and indexName - is an index name

How to make a great R reproducible example

If you have one or more factor variable(s) in your data that you want to make reproducible with dput(head(mydata)), consider adding droplevels to it, so that levels of factors that are not present in the minimized data set are not included in your dput output, in order to make the example minimal:

dput(droplevels(head(mydata)))

Unit Testing: DateTime.Now

Mock Objects.

A mock DateTime that returns a Now that's appropriate for your test.

CodeIgniter removing index.php from url

you can go to application\config\config.php file and remove index.php


 $config['index_page'] = 'index.php';   // delete index.php

Change to


 $config['index_page'] = '';

How do I get the find command to print out the file size with the file name?

You could try this:

find. -name *.ear -exec du {} \;

This will give you the size in bytes. But the du command also accepts the parameters -k for KB and -m for MB. It will give you an output like

5000  ./dir1/dir2/earFile1.ear
5400  ./dir1/dir2/earFile2.ear
5400  ./dir1/dir3/earFile1.ear

Google Maps: how to get country, state/province/region, city given a lat/long value?

Just try this code this code work with me

var posOptions = {timeout: 10000, enableHighAccuracy: false};
$cordovaGeolocation.getCurrentPosition(posOptions).then(function (position) {
var lat = position.coords.latitude;
var long = position.coords.longitude;
 //console.log(lat +"          "+long);
$http.get('https://maps.googleapis.com/maps/api/geocode/json?latlng=' + lat + ',' + long + '&key=your key here').success(function (output) {
//console.log( JSON.stringify(output.results[0]));
//console.log( JSON.stringify(output.results[0].address_components[4].short_name));
var results = output.results;
if (results[0]) {
//console.log("results.length= "+results.length);
//console.log("hi "+JSON.stringify(results[0],null,4));
for (var j = 0; j < results.length; j++){
 //console.log("j= "+j);
//console.log(JSON.stringify(results[j],null,4));
for (var i = 0; i < results[j].address_components.length; i++){
 if(results[j].address_components[i].types[0] == "country") {
 //this is the object you are looking for
  country = results[j].address_components[i];
 }
 }
 }
 console.log(country.long_name);
 console.log(country.short_name);
 } else {
 alert("No results found");
 console.log("No results found");
 }
 });
 }, function (err) {
 });

Clearing an input text field in Angular2

What about something like this, without a button:

<input type="text" placeholder="Search..." [value]="searchValue" onblur="this.value=''">

How to Install Font Awesome in Laravel Mix

I found all answers above incomplete somehow, Below are exact steps to get it working.

  1. We use npm in order to install the package. For this open the Console and go to your Laravel application directory. Enter the following:

    npm install font-awesome --save-dev

  2. Now we have to copy the needed files to the public/css and public/fonts directory. In order to do this open the webpack.mix.js file and add the following:

    mix.copy('node_modules/font-awesome/css/font-awesome.min.css', 'public/css'); mix.copy('node_modules/font-awesome/fonts/*', 'public/fonts');

  3. Run the following command in order to execute Laravel Mix:

    npm run dev

  4. Add the stylesheet for the Font Awesome in your applications layout file (resources/views/layouts/app.blade.phpapp.blade.php):

    <link href="{{ asset('css/font-awesome.min.css') }}" rel="stylesheet" />

  5. Use font awesome icons in templates like

    <i class="fa fa-address-book" aria-hidden="true"></i>

I hope it helps!

Fixing "Lock wait timeout exceeded; try restarting transaction" for a 'stuck" Mysql table?

This started happening to me when my database size grew and I was doing a lot of transactions on it.

Truth is there is probably some way to optimize either your queries or your DB but try these 2 queries for a work around fix.

Run this:

SET GLOBAL innodb_lock_wait_timeout = 5000; 

And then this:

SET innodb_lock_wait_timeout = 5000; 

C++ convert string to hexadecimal and vice versa

Simplest example using the Standard Library.

#include <iostream>
using namespace std;

int main()
{
  char c = 'n';
  cout << "HEX " << hex << (int)c << endl;  // output in hexadecimal
  cout << "ASC" << c << endl; // output in ascii
  return 0;
}

To check the output, codepad returns: 6e

and an online ascii-to-hexadecimal conversion tool yields 6e as well. So it works.

You can also do this:

template<class T> std::string toHexString(const T& value, int width) {
    std::ostringstream oss;
    oss << hex;
    if (width > 0) {
        oss << setw(width) << setfill('0');
    }
    oss << value;
    return oss.str();
}

Why does find -exec mv {} ./target/ + not work?

The manual page (or the online GNU manual) pretty much explains everything.

find -exec command {} \;

For each result, command {} is executed. All occurences of {} are replaced by the filename. ; is prefixed with a slash to prevent the shell from interpreting it.

find -exec command {} +

Each result is appended to command and executed afterwards. Taking the command length limitations into account, I guess that this command may be executed more times, with the manual page supporting me:

the total number of invocations of the command will be much less than the number of matched files.

Note this quote from the manual page:

The command line is built in much the same way that xargs builds its command lines

That's why no characters are allowed between {} and + except for whitespace. + makes find detect that the arguments should be appended to the command just like xargs.

The solution

Luckily, the GNU implementation of mv can accept the target directory as an argument, with either -t or the longer parameter --target. It's usage will be:

mv -t target file1 file2 ...

Your find command becomes:

find . -type f -iname '*.cpp' -exec mv -t ./test/ {} \+

From the manual page:

-exec command ;

Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead.

-exec command {} +

This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command. The command is executed in the starting directory.

How do you add CSS with Javascript?

This easy example of add <style> in head of html

var sheet = document.createElement('style');
sheet.innerHTML = "table th{padding-bottom: 0 !important;padding-top: 0 !important;}\n"
+ "table ul {    margin-top: 0 !important;    margin-bottom: 0 !important;}\n"
+ "table td{padding-bottom: 0 !important;padding-top: 0 !important;}\n"
+ ".messages.error{display:none !important;}\n"
+ ".messages.status{display:none !important;} ";

document.body.appendChild(sheet); // append in body
document.head.appendChild(sheet); // append in head

Source Dynamic style - manipulating CSS with JavaScript

Which characters need to be escaped when using Bash?

I noticed that bash automatically escapes some characters when using auto-complete.

For example, if you have a directory named dir:A, bash will auto-complete to dir\:A

Using this, I runned some experiments using characters of the ASCII table and derived the following lists:

Characters that bash escapes on auto-complete: (includes space)

 !"$&'()*,:;<=>?@[\]^`{|}

Characters that bash does not escape:

#%+-.0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz~

(I excluded /, as it cannot be used in directory names)

Conversion of a varchar data type to a datetime data type resulted in an out-of-range value in SQL query

I struggled with the same problem. I have stored dates in SQL Server with format 'YYYY-MM-DD HH:NN:SS' for about 20 years, but today that was not able anymore from a C# solution using OleDbCommand and a UPDATE query.

The solution to my problem was to remove the hyphen - in the format, so the resulting formatting is now 'YYYYMMDD HH:MM:SS'. I have no idea why my previous formatting not works anymore, but I suspect there is something to do with some Windows updates for ADO.

Please run `npm cache clean`

This error can be due to many many things.

The key here seems the hint about error reading. I see you are working on a flash drive or something similar? Try to run the install on a local folder owned by your current user.

You could also try with sudo, that might solve a permission problem if that's the case.

Another reason why it cannot read could be because it has not downloaded correctly, or saved correctly. A little problem in your network could have caused that, and the cache clean would remove the files and force a refetch but that does not solve your problem. That means it would be more on the save part, maybe it didn't save because of permissions, maybe it didn't not save correctly because it was lacking disk space...

jQuery Array of all selected checkboxes (by class)

You can also add underscore.js to your project and will be able to do it in one line:

_.map($("input[name='category_ids[]']:checked"), function(el){return $(el).val()})

How to create Gmail filter searching for text only at start of subject line?

I was wondering how to do this myself; it seems Gmail has since silently implemented this feature. I created the following filter:

Matches: subject:([test])
Do this: Skip Inbox

And then I sent a message with the subject

[test] foo

And the message was archived! So it seems all that is necessary is to create a filter for the subject prefix you wish to handle.

Query to list number of records in each table in a database

This sql script gives the schema, table name and row count of each table in a database selected:

SELECT SCHEMA_NAME(schema_id) AS [SchemaName],
[Tables].name AS [TableName],
SUM([Partitions].[rows]) AS [TotalRowCount]
FROM sys.tables AS [Tables]
JOIN sys.partitions AS [Partitions]
ON [Tables].[object_id] = [Partitions].[object_id]
AND [Partitions].index_id IN ( 0, 1 )
-- WHERE [Tables].name = N'name of the table'
GROUP BY SCHEMA_NAME(schema_id), [Tables].name
order by [TotalRowCount] desc

Ref: https://blog.sqlauthority.com/2017/05/24/sql-server-find-row-count-every-table-database-efficiently/

Another way of doing this:

SELECT  o.NAME TABLENAME,
  i.rowcnt 
FROM sysindexes AS i
  INNER JOIN sysobjects AS o ON i.id = o.id 
WHERE i.indid < 2  AND OBJECTPROPERTY(o.id, 'IsMSShipped') = 0
ORDER BY i.rowcnt desc

Calculate rolling / moving average in C++

a simple moving average for 10 items, using a list:

#include <list>

std::list<float> listDeltaMA;

float getDeltaMovingAverage(float delta)
{
    listDeltaMA.push_back(delta);
    if (listDeltaMA.size() > 10) listDeltaMA.pop_front();
    float sum = 0;
    for (std::list<float>::iterator p = listDeltaMA.begin(); p != listDeltaMA.end(); ++p)
        sum += (float)*p;
    return sum / listDeltaMA.size();
}

Assign keyboard shortcut to run procedure

The problem that I had with the above is that I wanted to associate a short cut key with a macro in an xlam which has no visible interface. I found that the folllowing worked

To associate a short cut key with a macro

In Excel (not VBA) on the Developer Tab click Macros - no macros will be shown Type the name of the Sub The Options button should then be enabled Click it Ctrl will be the default Hold down Shift and press the letter you want eg Shift and A will associate Ctrl-Shift-A with the Sub

Detect if the app was launched/opened from a push notification

For swift:

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
    PFPush.handlePush(userInfo)

    if application.applicationState == UIApplicationState.Inactive || application.applicationState == UIApplicationState.Background {
        //opened from a push notification when the app was in the background

    }

}

Selecting a row of pandas series/dataframe by integer index

The primary purpose of the DataFrame indexing operator, [] is to select columns.

When the indexing operator is passed a string or integer, it attempts to find a column with that particular name and return it as a Series.

So, in the question above: df[2] searches for a column name matching the integer value 2. This column does not exist and a KeyError is raised.


The DataFrame indexing operator completely changes behavior to select rows when slice notation is used

Strangely, when given a slice, the DataFrame indexing operator selects rows and can do so by integer location or by index label.

df[2:3]

This will slice beginning from the row with integer location 2 up to 3, exclusive of the last element. So, just a single row. The following selects rows beginning at integer location 6 up to but not including 20 by every third row.

df[6:20:3]

You can also use slices consisting of string labels if your DataFrame index has strings in it. For more details, see this solution on .iloc vs .loc.

I almost never use this slice notation with the indexing operator as its not explicit and hardly ever used. When slicing by rows, stick with .loc/.iloc.

Javascript onload not working

You are missing the ()

<body onload="imageRefreshBig();">

Can I safely delete contents of Xcode Derived data folder?

I would say it's safe--I often delete the contents of the folder for many kind of iOS projects, this way. And, I haven't had any issues with builds or submitting to the App Store. The procedure deletes derived data and cleans a project's cached assets, for both Xcode 5 and 6.

Sometimes, simply calling rm -rf on the Derived Data directory leaves a lingering file or two, but my script loops until all files are deleted.

Android Bitmap to Base64 String

All of these answers are inefficient as they needlessly decode to a bitmap and then recompress the bitmap. When you take a photo on Android, it is stored as a jpeg in the temp file you specify when you follow the android docs.

What you should do is directly convert that file to a Base64 string. Here is how to do that in easy copy-paste (in Kotlin). Note you must close the base64FilterStream to truly flush its internal buffer.

fun convertImageFileToBase64(imageFile: File): String {

    return FileInputStream(imageFile).use { inputStream ->
        ByteArrayOutputStream().use { outputStream ->
            Base64OutputStream(outputStream, Base64.DEFAULT).use { base64FilterStream ->
                inputStream.copyTo(base64FilterStream)
                base64FilterStream.close()
                outputStream.toString()
            }
        }
    }
}

As a bonus, your image quality should be slightly improved, due to bypassing the re-compressing.

Oracle SQL : timestamps in where clause

to_timestamp()

You need to use to_timestamp() to convert your string to a proper timestamp value:

to_timestamp('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')

to_date()

If your column is of type DATE (which also supports seconds), you need to use to_date()

to_date('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')

Example

To get this into a where condition use the following:

select * 
from TableA 
where startdate >= to_timestamp('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')
  and startdate <= to_timestamp('12-01-2012 21:25:33', 'dd-mm-yyyy hh24:mi:ss')

Note

You never need to use to_timestamp() on a column that is of type timestamp.

Load external css file like scripts in jquery which is compatible in ie also

    //load css first, then print <link> to header, and execute callback
    //just set var href above this..
    $.ajax({
          url: href,
          dataType: 'css',
          success: function(){                  
                $('<link rel="stylesheet" type="text/css" href="'+href+'" />').appendTo("head");
                //your callback
            }
    });

For Jquery 1.2.6 and above ( omitting the fancy attributes functions above ).

I am doing it this way because I think that this will ensure that your requested stylesheet is loaded by ajax before you try to stick it into the head. Therefore, the callback is executed after the stylesheet is ready.

How to layout multiple panels on a jFrame? (java)

You'll want to use a number of layout managers to help you achieve the basic results you want.

Check out A Visual Guide to Layout Managers for a comparision.

You could use a GridBagLayout but that's one of the most complex (and powerful) layout managers available in the JDK.

You could use a series of compound layout managers instead.

I'd place the graphics component and text area on a single JPanel, using a BorderLayout, with the graphics component in the CENTER and the text area in the SOUTH position.

I'd place the text field and button on a separate JPanel using a GridBagLayout (because it's the simplest I can think of to achieve the over result you want)

I'd place these two panels onto a third, master, panel, using a BorderLayout, with the first panel in the CENTER and the second at the SOUTH position.

But that's me

Adding to the classpath on OSX

If your shell is tcsh or csh, you can set it in /etc/profile. Open terminal, "vim /etc/profile" and add the following line:

setenv CLASSPATH (insert your classpath here)

How to find all the tables in MySQL with specific column names in them?

For those searching for the inverse of this, i.e. looking for tables that do not contain a certain column name, here is the query...

SELECT DISTINCT TABLE_NAME FROM information_schema.columns WHERE 
TABLE_SCHEMA = 'your_db_name' AND TABLE_NAME NOT IN (SELECT DISTINCT 
TABLE_NAME FROM information_schema.columns WHERE column_name = 
'column_name' AND TABLE_SCHEMA = 'your_db_name');

This came in really handy when we began to slowly implement use of InnoDB's special ai_col column and needed to figure out which of our 200 tables had yet to be upgraded.

Is it possible to register a http+domain-based URL Scheme for iPhone apps, like YouTube and Maps?

It's quite possible to do this in JavaScript as long as your fallback is another applink. Building on Nathan's suggestion:

<html>
  <head>
    <meta name="viewport" content="width=device-width" />
  </head>
  <body>

    <h2><a id="applink1" href="fb://profile/116201417">open facebook with fallback to appstore</a></h2>
    <h2><a id="applink2" href="unknown://nowhere">open unknown with fallback to appstore</a></h2>
    <p><i>Only works on iPhone!</i></p>    

  <script type="text/javascript">

// To avoid the "protocol not supported" alert, fail must open another app.
var appstorefail = "itms://itunes.apple.com/us/app/facebook/id284882215?mt=8&uo=6";

function applink(fail){
    return function(){
        var clickedAt = +new Date;
        // During tests on 3g/3gs this timeout fires immediately if less than 500ms.
        setTimeout(function(){
            // To avoid failing on return to MobileSafari, ensure freshness!
            if (+new Date - clickedAt < 2000){
                window.location = fail;
            }
        }, 500);    
    };
}

document.getElementById("applink1").onclick = applink(appstorefail);
document.getElementById("applink2").onclick = applink(appstorefail);

</script>
</body>
</html>

Check out a live demo here.

Turn off iPhone/Safari input element rounding

On iOS 5 and later:

input {
  border-radius: 0;
}

input[type="search"] {
  -webkit-appearance: none;
}

If you must only remove the rounded corners on iOS or otherwise for some reason cannot normalize rounded corners across platforms, use input { -webkit-border-radius: 0; } property instead, which is still supported. Of course do note that Apple can choose to drop support for the prefixed property at any time, but considering their other platform-specific CSS features chances are they'll keep it around.

On legacy versions you had to set -webkit-appearance: none instead:

input {
    -webkit-appearance: none;
}

Java HTTPS client certificate authentication

Given a p12 file with both the certificate and the private key (generated by openssl, for example), the following code will use that for a specific HttpsURLConnection:

    KeyStore keyStore = KeyStore.getInstance("pkcs12");
    keyStore.load(new FileInputStream(keyStorePath), keystorePassword.toCharArray());
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(keyStore, keystorePassword.toCharArray());
    SSLContext ctx = SSLContext.getInstance("TLS");
    ctx.init(kmf.getKeyManagers(), null, null);
    SSLSocketFactory sslSocketFactory = ctx.getSocketFactory();

    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
    connection.setSSLSocketFactory(sslSocketFactory);

The SSLContext takes some time to initialize, so you might want to cache it.

OpenSSL: unable to verify the first certificate for Experian URL

If you are using MacOS use:

sudo cp /usr/local/etc/openssl/cert.pem /etc/ssl/certs

after this Trust anchor not found error disappears

Variable number of arguments in C++?

There is no standard C++ way to do this without resorting to C-style varargs (...).

There are of course default arguments that sort of "look" like variable number of arguments depending on the context:

void myfunc( int i = 0, int j = 1, int k = 2 );

// other code...

myfunc();
myfunc( 2 );
myfunc( 2, 1 );
myfunc( 2, 1, 0 );

All four function calls call myfunc with varying number of arguments. If none are given, the default arguments are used. Note however, that you can only omit trailing arguments. There is no way, for example to omit i and give only j.

Rails - controller action name to string

This snippet works for Rails 3

class ReportsController < ApplicationController

  def summary
    logger.debug self.class.to_s + "." + self.action_name
  end

end

will print

. . .
ReportsController.summary
. . .

background: fixed no repeat not working on mobile

"background-size: cover;" causes a lot of issues on all mobile browsers except Firefox!

This fixed my issue:

/* Mobile first */
body{
    background-image: url(bg_mobile.jpg);
    background-attachment: fixed;
    background-repeat: no-repeat;
}

/* Then tablets, laptops and desktops (768px and up) */
@media screen and (min-width:768px) {
body{
    background-image: url(bg.jpg);
    background-size: cover;
    }
}

Get column value length, not column max length of value

LENGTH() does return the string length (just verified). I suppose that your data is padded with blanks - try

SELECT typ, LENGTH(TRIM(t1.typ))
FROM AUTA_VIEW t1;

instead.

As OraNob mentioned, another cause could be that CHAR is used in which case LENGTH() would also return the column width, not the string length. However, the TRIM() approach also works in this case.

Bulk Insert into Oracle database: Which is better: FOR Cursor loop or a simple Select?

The general rule-of-thumb is, if you can do it using a single SQL statement instead of using PL/SQL, you should. It will usually be more efficient.

However, if you need to add more procedural logic (for some reason), you might need to use PL/SQL, but you should use bulk operations instead of row-by-row processing. (Note: in Oracle 10g and later, your FOR loop will automatically use BULK COLLECT to fetch 100 rows at a time; however your insert statement will still be done row-by-row).

e.g.

DECLARE
   TYPE tA IS TABLE OF FOO.A%TYPE INDEX BY PLS_INTEGER;
   TYPE tB IS TABLE OF FOO.B%TYPE INDEX BY PLS_INTEGER;
   TYPE tC IS TABLE OF FOO.C%TYPE INDEX BY PLS_INTEGER;
   rA tA;
   rB tB;
   rC tC;
BEGIN
   SELECT * BULK COLLECT INTO rA, rB, rC FROM FOO;
   -- (do some procedural logic on the data?)
   FORALL i IN rA.FIRST..rA.LAST
      INSERT INTO BAR(A,
                      B,
                      C)
      VALUES(rA(i),
             rB(i),
             rC(i));
END;

The above has the benefit of minimising context switches between SQL and PL/SQL. Oracle 11g also has better support for tables of records so that you don't have to have a separate PL/SQL table for each column.

Also, if the volume of data is very great, it is possible to change the code to process the data in batches.

ImportError: numpy.core.multiarray failed to import

run this codes worked for me, seems to be issue with version.

pip uninstall numpy

pip install numpy==1.19.3

Merge a Branch into Trunk

If your working directory points to the trunk, then you should be able to merge your branch with:

svn merge https://HOST/repository/branches/branch_1

be sure to be to issue this command in the root directory of your trunk

How to encrypt and decrypt String with my passphrase in Java (Pc not mobile platform)?

I just want to add that if you want to somehow store the encrypted byte array as String and then retrieve it and decrypt it (often for obfuscation of database values) you can use this approach:

import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class StrongAES 
{
    public void run() 
    {
        try 
        {
            String text = "Hello World";
            String key = "Bar12345Bar12345"; // 128 bit key
            // Create key and cipher
            Key aesKey = new SecretKeySpec(key.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES");
            // encrypt the text
            cipher.init(Cipher.ENCRYPT_MODE, aesKey);
            byte[] encrypted = cipher.doFinal(text.getBytes());

            StringBuilder sb = new StringBuilder();
            for (byte b: encrypted) {
                sb.append((char)b);
            }

            // the encrypted String
            String enc = sb.toString();
            System.out.println("encrypted:" + enc);

            // now convert the string to byte array
            // for decryption
            byte[] bb = new byte[enc.length()];
            for (int i=0; i<enc.length(); i++) {
                bb[i] = (byte) enc.charAt(i);
            }

            // decrypt the text
            cipher.init(Cipher.DECRYPT_MODE, aesKey);
            String decrypted = new String(cipher.doFinal(bb));
            System.err.println("decrypted:" + decrypted);

        }
        catch(Exception e) 
        {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) 
    {
        StrongAES app = new StrongAES();
        app.run();
    }
}

Will the IE9 WebBrowser Control Support all of IE9's features, including SVG?

I had the same problem, and the registry answers here didn't work.

I had a browser control in new version of my program that worked fine on XP, failed in Windows 7 (64 bit). The old version worked on both XP and Windows 7.

The webpage displayed in the browser uses some strange plugin for showing old SVG maps (I think its a Java applet).

Turns out the problem is related to DEP protection in Windows 7.

Old versions of dotnet 2 didn't set the DEP required flag in the exe, but from dotnet 2, SP 1 onwards it did (yep, the compiling behaviour and hence runtime behaviour of exe changed depending on which machine you compiled on, nice ...).

It is documented on a MSDN blog NXCOMPAT and the C# compiler. To quote : This will undoubtedly surprise a few developers...download a framework service pack, recompile, run your app, and you're now getting IP_ON_HEAP exceptions.

Adding the following to the post build in Visual Studio, turns DEP off for the exe, and everything works as expected:

all "$(DevEnvDir)..\tools\vsvars32.bat"
editbin.exe /NXCOMPAT:NO "$(TargetPath)"

How to initialize an array of custom objects

Maybe you mean like this? I like to make an object and use Format-Table:

> $array = @()
> $object = New-Object -TypeName PSObject
> $object | Add-Member -Name 'Name' -MemberType Noteproperty -Value 'Joe'
> $object | Add-Member -Name 'Age' -MemberType Noteproperty -Value 32
> $object | Add-Member -Name 'Info' -MemberType Noteproperty -Value 'something about him'
> $array += $object
> $array | Format-Table

Name                                                                        Age Info
----                                                                        --- ----
Joe                                                                          32  something about him

This will put all objects you have in the array in columns according to their properties.

Tip: Using -auto sizes the table better

> $array | Format-Table -Auto

Name Age Info
---- --- ----
Joe   32 something about him

You can also specify which properties you want in the table. Just separate each property name with a comma:

> $array | Format-Table Name, Age -Auto

Name Age
---- ---
Joe   32

Displaying a Table in Django from Database

If you want to table do following steps:-

views.py:

def view_info(request):
    objs=Model_name.objects.all()
    ............
    return render(request,'template_name',{'objs':obj})

.html page

 {% for item in objs %}
    <tr> 
         <td>{{ item.field1 }}</td>
         <td>{{ item.field2 }}</td>
         <td>{{ item.field3 }}</td>
         <td>{{ item.field4 }}</td>
    </tr>
       {% endfor %}

How does Zalgo text work?

Zalgo text works because of combining characters. These are special characters that allow to modify character that comes before.

enter image description here

OR

y + ̆ = y̆ which actually is

y + &#x0306; = y&#x0306;

Since you can stack them one atop the other you can produce the following:


y̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆

which actually is:

y&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;

The same goes for putting stuff underneath:


y̰̰̰̰̰̰̰̰̰̰̰̰̰̰̰̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆



that in fact is:

y&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;

In Unicode, the main block of combining diacritics for European languages and the International Phonetic Alphabet is U+0300–U+036F.

More about it here

To produce a list of combining diacritical marks you can use the following script (since links keep on dying)

_x000D_
_x000D_
for(var i=768; i<879; i++){console.log(new DOMParser().parseFromString("&#"+i+";", "text/html").documentElement.textContent +"  "+"&#"+i+";");}
_x000D_
_x000D_
_x000D_

Also check em out



Mͣͭͣ̾ Vͣͥͭ͛ͤͮͥͨͥͧ̾

How to shrink temp tablespace in oracle?

The options for managing tablespaces have got a lot better over the versions starting with 8i. This is especially true if you are using the appropriate types of file for a temporary tablespace (i.e. locally managed tempfiles).

So, it could be as simple as this command, which will shrink your tablespace to 128 meg...

alter tablespace <your_temp_ts> shrink space keep 128M;

The Oracle online documentation is pretty good. Find out more.

edit

It would appear the OP has an earlier version of the database. With earlier versions we have to resize individual datafiles. So, first of all, find the file names. One or other of these queries should do it...

select file_name from dba_data_files where tablespace_name = '<your_temp_ts>'
/

select file_name from dba_temp_files where tablespace_name = '<your_temp_ts>'
/ 

Then use that path in this command:

alter database datafile '/full/file/path/temp01.dbf'  resize 128m
/

Get POST data in C#/ASP.NET

The following is OK in HTML4, but not in XHTML. Check your editor.

<input type=button value="Submit" />

HTML table with fixed headers?

I developed a simple light-weight jQuery plug-in for converting a well formatted HTML table to a scrollable table with fixed table header and columns.

The plugin works well to match pixel-to-pixel positioning the fixed section with the scrollable section. Additionally, you could also freeze the number of columns that will be always in view when scrolling horizontally.

Demo & Documentation: http://meetselva.github.io/fixed-table-rows-cols/

GitHub repository: https://github.com/meetselva/fixed-table-rows-cols

Below is the usage for a simple table with a fixed header,

$(<table selector>).fxdHdrCol({
    width:     "100%",
    height:    200,
    colModal: [{width: 30, align: 'center'},
               {width: 70, align: 'center'}, 
               {width: 200, align: 'left'}, 
               {width: 100, align: 'center'}, 
               {width: 70, align: 'center'}, 
               {width: 250, align: 'center'}
              ]
});

how can I check if a file exists?

For anyone who is looking a way to watch a specific file to exist in VBS:

Function bIsFileDownloaded(strPath, timeout)
  Dim FSO, fileIsDownloaded
  set FSO = CreateObject("Scripting.FileSystemObject")
  fileIsDownloaded = false
  limit = DateAdd("s", timeout, Now)
  Do While Now < limit
    If FSO.FileExists(strPath) Then : fileIsDownloaded = True : Exit Do : End If
    WScript.Sleep 1000      
  Loop
  Set FSO = Nothing
  bIsFileDownloaded = fileIsDownloaded
End Function

Usage:

FileName = "C:\test.txt"
fileIsDownloaded = bIsFileDownloaded(FileName, 5) ' keep watching for 5 seconds

If fileIsDownloaded Then
  WScript.Echo Now & " File is Downloaded: " & FileName
Else
  WScript.Echo Now & " Timeout, file not found: " & FileName 
End If

C++ inheritance - inaccessible base?

You have to do this:

class Bar : public Foo
{
    // ...
}

The default inheritance type of a class in C++ is private, so any public and protected members from the base class are limited to private. struct inheritance on the other hand is public by default.

How to see query history in SQL Server Management Studio

I use the below query for tracing application activity on a SQL server that does not have trace profiler enabled. The method uses Query Store (SQL Server 2016+) instead of the DMV's. This gives better ability to look into historical data, as well as faster lookups. It is very efficient to capture short-running queries that can't be captured by sp_who/sp_whoisactive.

/* Adjust script to your needs.
    Run full script (F5) -> Interact with UI -> Run full script again (F5)
    Output will contain the queries completed in that timeframe.
*/

/* Requires Query Store to be enabled:
    ALTER DATABASE <db> SET QUERY_STORE = ON
    ALTER DATABASE <db> SET QUERY_STORE (OPERATION_MODE = READ_WRITE, MAX_STORAGE_SIZE_MB = 100000)
*/

USE <db> /* Select your DB */

IF OBJECT_ID('tempdb..#lastendtime') IS NULL
    SELECT GETUTCDATE() AS dt INTO #lastendtime
ELSE IF NOT EXISTS (SELECT * FROM #lastendtime)
    INSERT INTO #lastendtime VALUES (GETUTCDATE()) 

;WITH T AS (
SELECT 
    DB_NAME() AS DBName
    , s.name + '.' + o.name AS ObjectName
    , qt.query_sql_text
    , rs.runtime_stats_id
    , p.query_id
    , p.plan_id
    , CAST(p.last_execution_time AS DATETIME) AS last_execution_time
    , CASE WHEN p.last_execution_time > #lastendtime.dt THEN 'X' ELSE '' END AS New
    , CAST(rs.last_duration / 1.0e6 AS DECIMAL(9,3)) last_duration_s
    , rs.count_executions
    , rs.last_rowcount
    , rs.last_logical_io_reads
    , rs.last_physical_io_reads
    , q.query_parameterization_type_desc
FROM (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY plan_id, runtime_stats_id ORDER BY runtime_stats_id DESC) AS recent_stats_in_current_priod
    FROM sys.query_store_runtime_stats 
    ) AS rs
INNER JOIN sys.query_store_runtime_stats_interval AS rsi ON rsi.runtime_stats_interval_id = rs.runtime_stats_interval_id
INNER JOIN sys.query_store_plan AS p ON p.plan_id = rs.plan_id
INNER JOIN sys.query_store_query AS q ON q.query_id = p.query_id
INNER JOIN sys.query_store_query_text AS qt ON qt.query_text_id = q.query_text_id
LEFT OUTER JOIN sys.objects AS o ON o.object_id = q.object_id
LEFT OUTER JOIN sys.schemas AS s ON s.schema_id = o.schema_id
CROSS APPLY #lastendtime
WHERE rsi.start_time <= GETUTCDATE() AND GETUTCDATE() < rsi.end_time
    AND recent_stats_in_current_priod = 1
    /* Adjust your filters: */
    -- AND (s.name IN ('<myschema>') OR s.name IS NULL)
UNION
SELECT NULL,NULL,NULL,NULL,NULL,NULL,dt,NULL,NULL,NULL,NULL,NULL,NULL, NULL
FROM #lastendtime
)
SELECT * FROM T
WHERE T.query_sql_text IS NULL OR T.query_sql_text NOT LIKE '%#lastendtime%' -- do not show myself
ORDER BY last_execution_time DESC

TRUNCATE TABLE #lastendtime
INSERT INTO #lastendtime VALUES (GETUTCDATE()) 

How can I add new dimensions to a Numpy array?

This worked for me:

image = image[..., None]

Mock MVC - Add Request Parameter to test

When i analyzed your code. I have also faced the same problem but my problem is if i give value for both first and last name means it is working fine. but when i give only one value means it says 400. anyway use the .andDo(print()) method to find out the error

public void testGetUserByName() throws Exception {
    String firstName = "Jack";
    String lastName = "s";       
    this.userClientObject = client.createClient();
    mockMvc.perform(get("/byName")
            .sessionAttr("userClientObject", this.userClientObject)
            .param("firstName", firstName)
            .param("lastName", lastName)               
    ).andDo(print())
     .andExpect(status().isOk())
            .andExpect(content().contentType("application/json"))
            .andExpect(jsonPath("$[0].id").exists())
            .andExpect(jsonPath("$[0].fn").value("Marge"));
}

If your problem is org.springframework.web.bind.missingservletrequestparameterexception you have to change your code to

@RequestMapping(value = "/byName", method = RequestMethod.GET)
    @ResponseStatus(HttpStatus.OK)
    public
    @ResponseBody
    String getUserByName(
        @RequestParam( value="firstName",required = false) String firstName,
        @RequestParam(value="lastName",required = false) String lastName, 
        @ModelAttribute("userClientObject") UserClient userClient)
    {

        return client.getUserByName(userClient, firstName, lastName);
    }

How to change date format using jQuery?

var d = new Date();

var curr_date = d.getDate();

var curr_month = d.getMonth();

var curr_year = d.getFullYear();

curr_year = curr_year.toString().substr(2,2);

document.write(curr_date+"-"+curr_month+"-"+curr_year);

You can change this as your need..

How to set default value for column of new created table from select statement in 11g

new table inherits only "not null" constraint and no other constraint. Thus you can alter the table after creating it with "create table as" command or you can define all constraint that you need by following the

create table t1 (id number default 1 not null);
insert into t1 (id) values (2);

create table t2 as select * from t1;

This will create table t2 with not null constraint. But for some other constraint except "not null" you should use the following syntax

create table t1 (id number default 1 unique);
insert into t1 (id) values (2);

create table t2 (id default 1 unique)
as select * from t1;

nginx: how to create an alias url route?

server {
  server_name example.com;
  root /path/to/root;
  location / {
    # bla bla
  }
  location /demo {
    alias /path/to/root/production/folder/here;
  }
}

If you need to use try_files inside /demo you'll need to replace alias with a root and do a rewrite because of the bug explained here

Change input value onclick button - pure javascript or jQuery

Another simple solution for this case using jQuery. Keep in mind it's not a good practice to use inline javascript.

JsFiddle

I've added IDs to html on the total price and on the buttons. Here is the jQuery.

$('#two').click(function(){
    $('#count').val('2');
    $('#total').text('Product price: $1000');
});

$('#four').click(function(){
    $('#count').val('4');
    $('#total').text('Product price: $2000');
});

Wait for shell command to complete

Either link the shell to an object, have the batch job terminate the shell object (exit) and have the VBA code continue once the shell object = Nothing?

Or have a look at this: Capture output value from a shell command in VBA?

How to get the version of ionic framework?

for slower machines use the browser console.

Ionic.version

It doesn't do much analysis like the terminal's

ionic info

which gathers other useful information about your ionic project.

How to prevent scrollbar from repositioning web page?

Wrap the content of your scrollable element into a div and apply padding-left: calc(100vw - 100%);.

<body>
    <div style="padding-left: calc(100vw - 100%);">
        Some Content that is higher than the user's screen
    </div>
</body>

The trick is that 100vw represents 100% of the viewport including the scrollbar. If you subtract 100%, which is the available space without the scrollbar, you end up with the width of the scrollbar or 0 if it is not present. Creating a padding of that width on the left will simulate a second scrollbar, shifting centered content back to the right.

Please note that this will only work if the scrollable element uses the page's entire width, but this should be no problem most of the time because there are only few other cases where you have centered scrollable content.

JavaScript open in a new window, not tab

Try:

window.open("", [window name], "height=XXX,width=XXX,modal=yes,alwaysRaised=yes");

I have some code that does what your say, but there is a lot of parameters in it. I think these are the bare minimum, let me know if it doesn't work, I'll post the rest.

How do I call Objective-C code from Swift?

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

Here is the relevant part:

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

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

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

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

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

How do I remove blue "selected" outline on buttons?

You can remove the blue outline by using outline: none.

However, I would highly recommend styling your focus states too. This is to help users who are visually impaired.

Check out: http://www.w3.org/TR/2008/REC-WCAG20-20081211/#navigation-mechanisms-focus-visible. More reading here: http://outlinenone.com

How to check which locks are held on a table

You can also use the built-in sp_who2 stored procedure to get current blocked and blocking processes on a SQL Server instance. Typically you'd run this alongside a SQL Profiler instance to find a blocking process and look at the most recent command that spid issued in profiler.

TypeError: 'float' object is not callable

The problem is with -3.7(prof[x]), which looks like a function call (note the parens). Just use a * like this -3.7*prof[x].

How to get random value out of an array?

I needed one line version for short array:

($array = [1, 2, 3, 4])[mt_rand(0, count($array) - 1)]

or if array is fixed:

[1, 2, 3, 4][mt_rand(0, 3]

Why are you not able to declare a class as static in Java?

Top level classes are static by default. Inner classes are non-static by default. You can change the default for inner classes by explicitly marking them static. Top level classes, by virtue of being top-level, cannot have non-static semantics because there can be no parent class to refer to. Therefore, there is no way to change the default for top-level classes.

How do I combine two dataframes?

There's another solution for the case that you are working with big data and need to concatenate multiple datasets. concat can get performance-intensive, so if you don't want to create a new df each time, you can instead use a list comprehension:

frames = [ process_file(f) for f in dataset_files ]
result = pd.append(frames)

(as pointed out here in the docs at the bottom of the section):

Note: It is worth noting however, that concat (and therefore append) makes a full copy of the data, and that constantly reusing this function can create a significant performance hit. If you need to use the operation over several datasets, use a list comprehension.

How to delete last item in list?

list.pop() removes and returns the last element of the list.

Remove a parameter to the URL with JavaScript

function removeParam(parameter)
{
  var url=document.location.href;
  var urlparts= url.split('?');

 if (urlparts.length>=2)
 {
  var urlBase=urlparts.shift(); 
  var queryString=urlparts.join("?"); 

  var prefix = encodeURIComponent(parameter)+'=';
  var pars = queryString.split(/[&;]/g);
  for (var i= pars.length; i-->0;)               
      if (pars[i].lastIndexOf(prefix, 0)!==-1)   
          pars.splice(i, 1);
  url = urlBase+'?'+pars.join('&');
  window.history.pushState('',document.title,url); // added this line to push the new url directly to url bar .

}
return url;
}

This will resolve your problem

How to remove line breaks from a file in Java?

org.apache.commons.lang.StringUtils#chopNewline

How can I loop through a C++ map of maps?

You can use an iterator.

typedef std::map<std::string, std::map<std::string, std::string>>::iterator it_type;
for(it_type iterator = m.begin(); iterator != m.end(); iterator++) {
    // iterator->first = key
    // iterator->second = value
    // Repeat if you also want to iterate through the second map.
}

Git push rejected "non-fast-forward"

I had a similar problem and I resolved it with: git pull origin

Java 8 stream map to list of keys sorted by values

Here is the simple solution with StreamEx

EntryStream.of(countByType).sortedBy(e -> e.getValue()).keys().toList();