Programs & Examples On #Find all references

Abort trap 6 error in C

You are writing to memory you do not own:

int board[2][50]; //make an array with 3 columns  (wrong)
                  //(actually makes an array with only two 'columns')
...
for (i=0; i<num3+1; i++)
    board[2][i] = 'O';
          ^

Change this line:

int board[2][50]; //array with 2 columns (legal indices [0-1][0-49])
          ^

To:

int board[3][50]; //array with 3 columns (legal indices [0-2][0-49])
          ^

When creating an array, the value used to initialize: [3] indicates array size.
However, when accessing existing array elements, index values are zero based.

For an array created: int board[3][50];
Legal indices are board[0][0]...board[2][49]

EDIT To address bad output comment and initialization comment

add an additional "\n" for formatting output:

Change:

  ...
  for (k=0; k<50;k++) {
     printf("%d",board[j][k]);
  }
 }

       ...

To:

  ...
  for (k=0; k<50;k++) {
     printf("%d",board[j][k]);
  }
  printf("\n");//at the end of every row, print a new line
}
...  

Initialize board variable:

int board[3][50] = {0};//initialize all elements to zero

( array initialization discussion... )

How to get the caller's method name in the called method?

Shorter version:

import inspect

def f1(): f2()

def f2():
    print 'caller name:', inspect.stack()[1][3]

f1()

(with thanks to @Alex, and Stefaan Lippen)

(SC) DeleteService FAILED 1072

The 3rd party application uninstaller had removed the files for the service and then left the service in this pending deletion state.

After trying to close all applications, identifing PID of service(couldn't) for kill, logging off all other users and logging off and on, rebooting was the only fix that worked for me.

Insert if not exists Oracle

It that code is on the client then you have many trips to the server so to eliminate that.

Insert all the data into a temportary table say T with the same structure as myFoo

Then

insert myFoo
  select *
     from t
       where t.primary_key not in ( select primary_key from myFoo) 

This should work on other databases as well - I have done this on Sybase

It is not the best if very few of the new data is to be inserted as you have copied all the data over the wire.

Converting string "true" / "false" to boolean value

If you're using the variable result:

result = result == "true";

jQuery Form Validation before Ajax submit

function validateForm()
{
    var a=document.forms["Form"]["firstname"].value;
    var b=document.forms["Form"]["midname"].value;
    var c=document.forms["Form"]["lastname"].value;
    var d=document.forms["Form"]["tribe"].value;
    if (a==null || a=="",b==null || b=="",c==null || c=="",d==null || d=="")
    {
        alert("Please Fill All Required Field");
        return false;
    }
    else{

        $.ajax({
        type: 'post',
        url: 'add.php',
        data: $('form').serialize(),
        success: function () {
          alert('Patient added');
          document.getElementById("form").reset();
        }
      });

    }
}

  $(function () {

    $('form').on('submit', function (e) {
      e.preventDefault();

      validateForm();


    });
  });

How to convert enum value to int?

I prefer this:

public enum Color {

   White,

   Green,

   Blue,

   Purple,

   Orange,

   Red
}

then:

//cast enum to int
int color = Color.Blue.ordinal();

Is it possible to apply CSS to half of a character?

A nice WebKit-only solution that takes advantage of the background-clip: text support: http://jsfiddle.net/sandro_paganotti/wLkVt/

span{
   font-size: 100px;
   background: linear-gradient(to right, black, black 50%, grey 50%, grey);
   -webkit-background-clip: text;
   -webkit-text-fill-color: transparent;
}

Remove the last chars of the Java String variable

import org.apache.commons.lang3.StringUtils;

// path = "http://cdn.gs.com/new/downloads/Q22010MVR_PressRelease.pdf.null"
StringUtils.removeEnd(path, ".null");
// path = "http://cdn.gs.com/new/downloads/Q22010MVR_PressRelease.pdf"

Set disable attribute based on a condition for Html.TextBoxFor

Yet another solution would be to create a Dictionary<string, object> before calling TextBoxFor and pass that dictionary. In the dictionary, add "disabled" key only if the textbox is to be diabled. Not the neatest solution but simple and straightforward.

Drop data frame columns by name

I keep thinking there must be a better idiom, but for subtraction of columns by name, I tend to do the following:

df <- data.frame(a=1:10, b=1:10, c=1:10, d=1:10)

# return everything except a and c
df <- df[,-match(c("a","c"),names(df))]
df

Looking for simple Java in-memory cache

Try @Cacheable from jcabi-aspects. With a single annotation you make the entire method result cacheable in memory:

public class Resource {
  @Cacheable(lifetime = 5, unit = TimeUnit.SECONDS)
  public String load(URL url) {
    return url.openConnection().getContent();
  }
}

Also, read this article: http://www.yegor256.com/2014/08/03/cacheable-java-annotation.html

How can I see the request headers made by curl when sending a request to the server?

The question did not specify if command line command named curl was meant or the whole cURL library.

The following PHP code using cURL library uses first parameter as HTTP method (e.g. "GET", "POST", "OPTIONS") and second parameter as URL.

<?php
$ch = curl_init();
$f = tmpfile(); # will be automatically removed after fclose()
curl_setopt_array($ch, array(
    CURLOPT_CUSTOMREQUEST  => $argv[1],
    CURLOPT_URL            => $argv[2], 
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_FOLLOWLOCATION => 0,
    CURLOPT_VERBOSE        => 1,
    CURLOPT_HEADER         => 0,
    CURLOPT_CONNECTTIMEOUT => 5,
    CURLOPT_TIMEOUT        => 30,
    CURLOPT_STDERR         => $f,
));
$response = curl_exec($ch);
fseek($f, 0);
echo fread($f, 32*1024); # output up to 32 KB cURL verbose log
fclose($f);
curl_close($ch);
echo $response;

Example usage:

php curl-test.php OPTIONS https://google.com

Note that the results are nearly identical to following command line

curl -v -s -o - -X OPTIONS https://google.com

Can't open config file: /usr/local/ssl/openssl.cnf on Windows

The solution is running this command:

set OPENSSL_CONF=C:\OpenSSL-Win32\bin\openssl.cfg   

or

set OPENSSL_CONF=[path-to-OpenSSL-install-dir]\bin\openssl.cfg

in the command prompt before using openssl command.

Let openssl know for sure where to find its .cfg file.

Alternatively you could set the same variable OPENSSL_CONF in the Windows environment variables.

NOTE: This can happen when using the OpenSSL binary distribution from Shining Light Productions (a compiled + installer version of the official OpenSSL that is free to download & use). This distribution is "semi-officially" linked from OpenSSL's site as a "service primarily for operating systems where there are no pre-compiled OpenSSL packages".

Jupyter notebook not running code. Stuck on In [*]

pip install prompt -toolkit~2.0.9 pip install --upgrade ipython conda update jupyter_core jupyter_client

Java compiler level does not match the version of the installed Java project facet

Right click the project and select properties Click the java compiler from the left and change to your required version Hope this helps

How to Deserialize JSON data?

Step 1: Go to json.org to find the JSON library for whatever technology you're using to call this web service. Download and link to that library.

Step 2: Let's say you're using Java. You would use JSONArray like this:

JSONArray myArray=new JSONArray(queryResponse);
for (int i=0;i<myArray.length;i++){
    JSONArray myInteriorArray=myArray.getJSONArray(i);
    if (i==0) {
        //this is the first one and is special because it holds the name of the query.
    }else{
        //do your stuff
        String stateCode=myInteriorArray.getString(0);
        String stateName=myInteriorArray.getString(1);
    }
}

Change hover color on a button with Bootstrap customization

This is the correct way to change btn color.

 .btn-primary:not(:disabled):not(.disabled).active, 
    .btn-primary:not(:disabled):not(.disabled):active, 
    .show>.btn-primary.dropdown-toggle{
        color: #fff;
        background-color: #F7B432;
        border-color: #F7B432;
    }

How do you give iframe 100% height

The problem with iframes not getting 100% height is not because they're unwieldy. The problem is that for them to get 100% height they need their parents to have 100% height. If one of the iframe's parents is not 100% tall the iframe won't be able to go beyond that parent's height.

So the best possible solution would be:

html, body, iframe { height: 100%; }

…given the iframe is directly under body. If the iframe has a parent between itself and the body, the iframe will still get the height of its parent. One must explicitly set the height of every parent to 100% as well (if that's what one wants).

Tested in:

Chrome 30, Firefox 24, Safari 6.0.5, Opera 16, IE 7, 8, 9 and 10

PS: I don't mean to be picky but the solution marked as correct doesn't work on Firefox 24 at the time of this writing, but worked on Chrome 30. Haven't tested on other browsers though. I came across the error on Firefox because the page I was testing had very little content... It could be it's my meager markup or the CSS reset altering the output, but if I experienced this error I guess the accepted answer doesn't work in every situation.

Update 2021

@Zeni suggested this in 2015:

iframe { height: 100vh }

...and indeed it does the trick!

Careful with positioning as it can potentially break the effect. Test thoroughly, you might not need positioning depending of what you're trying to achieve.

How to use a TRIM function in SQL Server

LTRIM(RTRIM(FCT_TYP_CD)) & ') AND (' & LTRIM(RTRIM(DEP_TYP_ID)) & ')'

I think you're missing a ) on both of the trims. Some SQL versions support just TRIM which does both L and R trims...

How to get access to raw resources that I put in res folder?

TextView txtvw = (TextView)findViewById(R.id.TextView01);
        txtvw.setText(readTxt());

 private String readTxt()
    {
    InputStream raw = getResources().openRawResource(R.raw.hello);

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

    int i;
    try
    {
        i = raw.read();
        while (i != -1)
        {
            byteArrayOutputStream.write(i);
            i = raw.read();
        }
        raw.close();
    }
    catch (IOException e)
    {
        // TODO Auto-generated catch block

        e.printStackTrace();
    }


    return byteArrayOutputStream.toString();

}

TextView01:: txtview in linearlayout hello:: .txt file in res/raw folder (u can access ny othr folder as wel)

Ist 2 lines are 2 written in onCreate() method

rest is to be written in class extending Activity!!

How to use null in switch

Just consider how the SWITCH might work,

  • in case of primitives we know it can fail with NPE for auto-boxing
  • but for String or enum, it might be invoking equals method, which obviously needs a LHS value on which equals is being invoked. So, given no method can be invoked on a null, switch cant handle null.

React - changing an uncontrolled input

When you first render your component, this.state.name isn't set, so it evaluates to undefined or null, and you end up passing value={undefined} or value={null}to your input.

When ReactDOM checks to see if a field is controlled, it checks to see if value != null (note that it's !=, not !==), and since undefined == null in JavaScript, it decides that it's uncontrolled.

So, when onFieldChange() is called, this.state.name is set to a string value, your input goes from being uncontrolled to being controlled.

If you do this.state = {name: ''} in your constructor, because '' != null, your input will have a value the whole time, and that message will go away.

"No such file or directory" but it exists

I found my solution for my Ubuntu 18 here.

sudo dpkg --add-architecture i386

Then:

sudo apt-get update
sudo apt-get install libc6:i386 libncurses5:i386 libstdc++6:i386

No MediaTypeFormatter is available to read an object of type 'String' from content with media type 'text/plain'

Or you can just create your own MediaTypeFormatter. I use this for text/html. If you add text/plain to it, it'll work for you too:

public class TextMediaTypeFormatter : MediaTypeFormatter
{
    public TextMediaTypeFormatter()
    {
        SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
    }

    public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
    {
        return ReadFromStreamAsync(type, readStream, content, formatterLogger, CancellationToken.None);
    }

    public override async Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger, CancellationToken cancellationToken)
    {
        using (var streamReader = new StreamReader(readStream))
        {
            return await streamReader.ReadToEndAsync();
        }
    }

    public override bool CanReadType(Type type)
    {
        return type == typeof(string);
    }

    public override bool CanWriteType(Type type)
    {
        return false;
    }
}

Finally you have to assign this to the HttpMethodContext.ResponseFormatter property.

How to find the socket buffer size of linux

Atomic size is 4096 bytes, max size is 65536 bytes. Sendfile uses 16 pipes each of 4096 bytes size. cmd : ioctl(fd, FIONREAD, &buff_size).

django order_by query set, ascending and descending

If for some reason you have null values you can use the F function like this:

from django.db.models import F

Reserved.objects.all().filter(client=client_id).order_by(F('check_in').desc(nulls_last=True))

So it will put last the null values. Documentation by Django: https://docs.djangoproject.com/en/stable/ref/models/expressions/#using-f-to-sort-null-values

How to bring view in front of everything?

bringToFront() is the right way, but, NOTE that you must call bringToFront() and invalidate() method on highest-level view (under your root view), for e.g.:

Your view's hierarchy is:

-RelativeLayout
|--LinearLayout1
|------Button1
|------Button2
|------Button3
|--ImageView
|--LinearLayout2
|------Button4
|------Button5
|------Button6

So, when you animate back your buttons (1->6), your buttons will under (below) the ImageView. To bring it over (above) the ImageView you must call bringToFront() and invalidate() method on your LinearLayouts. Then it will work :) **NOTE: Remember to set android:clipChildren="false" for your root layout or animate-view's gradparent_layout. Let's take a look at my real code:

.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:hw="http://schemas.android.com/apk/res-auto"
    android:id="@+id/layout_parent"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/common_theme_color"
    android:orientation="vertical" >

    <com.binh.helloworld.customviews.HWActionBar
        android:id="@+id/action_bar"
        android:layout_width="match_parent"
        android:layout_height="@dimen/dimen_actionbar_height"
        android:layout_alignParentTop="true"
        hw:titleText="@string/app_name" >
    </com.binh.helloworld.customviews.HWActionBar>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/action_bar"
        android:clipChildren="false" >

        <LinearLayout
            android:id="@+id/layout_top"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:gravity="center_horizontal"
            android:orientation="horizontal" >
        </LinearLayout>

        <ImageView
            android:id="@+id/imgv_main"
            android:layout_width="@dimen/common_imgv_height"
            android:layout_height="@dimen/common_imgv_height"
            android:layout_centerInParent="true"
            android:contentDescription="@string/app_name"
            android:src="@drawable/ic_launcher" />

        <LinearLayout
            android:id="@+id/layout_bottom"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:gravity="center_horizontal"
            android:orientation="horizontal" >
        </LinearLayout>
    </RelativeLayout>

</RelativeLayout>

Some code in .java

private LinearLayout layoutTop, layoutBottom;
...
layoutTop = (LinearLayout) rootView.findViewById(R.id.layout_top);
layoutBottom = (LinearLayout) rootView.findViewById(R.id.layout_bottom);
...
//when animate back
//dragedView is my layoutTop's child view (i added programmatically) (like buttons in above example) 
dragedView.setVisibility(View.GONE);
layoutTop.bringToFront();
layoutTop.invalidate();
dragedView.startAnimation(animation); // TranslateAnimation
dragedView.setVisibility(View.VISIBLE);

GLuck!

What are the differences between delegates and events?

An event in .net is a designated combination of an Add method and a Remove method, both of which expect some particular type of delegate. Both C# and vb.net can auto-generate code for the add and remove methods which will define a delegate to hold the event subscriptions, and add/remove the passed in delegagte to/from that subscription delegate. VB.net will also auto-generate code (with the RaiseEvent statement) to invoke the subscription list if and only if it is non-empty; for some reason, C# doesn't generate the latter.

Note that while it is common to manage event subscriptions using a multicast delegate, that is not the only means of doing so. From a public perspective, a would-be event subscriber needs to know how to let an object know it wants to receive events, but it does not need to know what mechanism the publisher will use to raise the events. Note also that while whoever defined the event data structure in .net apparently thought there should be a public means of raising them, neither C# nor vb.net makes use of that feature.

Could not create work tree dir 'example.com'.: Permission denied

use this for all user

sudo chown -R $(whoami):$(whoami) /var/..

Is it possible to run .php files on my local computer?

Sure you just need to setup a local web server. Check out XAMPP: http://www.apachefriends.org/en/xampp.html

That will get you up and running in about 10 minutes.

There is now a way to run php locally without installing a server: https://stackoverflow.com/a/21872484/672229


Yes but the files need to be processed. For example you can install test servers like mamp / lamp / wamp depending on your plateform.

Basically you need apache / php running.

How to pass command line argument to gnuplot?

You can also pass information in through the environment as is suggested here. The example by Ismail Amin is repeated here:

In the shell:

export name=plot_data_file

In a Gnuplot script:

#! /usr/bin/gnuplot

name=system("echo $name")
set title name
plot name using ($16 * 8):20 with linespoints notitle
pause -1

linux: kill background task

You can kill by job number. When you put a task in the background you'll see something like:

$ ./script &
[1] 35341

That [1] is the job number and can be referenced like:

$ kill %1
$ kill %%  # Most recent background job

To see a list of job numbers use the jobs command. More from man bash:

There are a number of ways to refer to a job in the shell. The character % introduces a job name. Job number n may be referred to as %n. A job may also be referred to using a prefix of the name used to start it, or using a substring that appears in its command line. For example, %ce refers to a stopped ce job. If a prefix matches more than one job, bash reports an error. Using %?ce, on the other hand, refers to any job containing the string ce in its command line. If the substring matches more than one job, bash reports an error. The symbols %% and %+ refer to the shell's notion of the current job, which is the last job stopped while it was in the foreground or started in the background. The previous job may be referenced using %-. In output pertaining to jobs (e.g., the output of the jobs command), the current job is always flagged with a +, and the previous job with a -. A single % (with no accompanying job specification) also refers to the current job.

Unmarshaling nested JSON objects

I was working on something like this. But is working only with structures generated from proto. https://github.com/flowup-labs/grpc-utils

in your proto

message Msg {
  Firstname string = 1 [(gogoproto.jsontag) = "name.firstname"];
  PseudoFirstname string = 2 [(gogoproto.jsontag) = "lastname"];
  EmbedMsg = 3  [(gogoproto.nullable) = false, (gogoproto.embed) = true];
  Lastname string = 4 [(gogoproto.jsontag) = "name.lastname"];
  Inside string  = 5 [(gogoproto.jsontag) = "name.inside.a.b.c"];
}

message EmbedMsg{
   Opt1 string = 1 [(gogoproto.jsontag) = "opt1"];
}

Then your output will be

{
"lastname": "Three",
"name": {
    "firstname": "One",
    "inside": {
        "a": {
            "b": {
                "c": "goo"
            }
        }
    },
    "lastname": "Two"
},
"opt1": "var"
}

How can I tell AngularJS to "refresh"

Use

$route.reload();

remember to inject $route to your controller.

How do I sort a two-dimensional (rectangular) array in C#?

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int[,] arr = { { 20, 9, 11 }, { 30, 5, 6 } };
            Console.WriteLine("before");
            for (int i = 0; i < arr.GetLength(0); i++)
            {
                for (int j = 0; j < arr.GetLength(1); j++)
                {
                    Console.Write("{0,3}", arr[i, j]);
                }
                Console.WriteLine();
            }
            Console.WriteLine("After");

            for (int i = 0; i < arr.GetLength(0); i++) // Array Sorting
            {
                for (int j = arr.GetLength(1) - 1; j > 0; j--)
                {

                    for (int k = 0; k < j; k++)
                    {
                        if (arr[i, k] > arr[i, k + 1])
                        {
                            int temp = arr[i, k];
                            arr[i, k] = arr[i, k + 1];
                            arr[i, k + 1] = temp;
                        }
                    }
                }
                Console.WriteLine();
            }

            for (int i = 0; i < arr.GetLength(0); i++)
            {
                for (int j = 0; j < arr.GetLength(1); j++)
                {
                    Console.Write("{0,3}", arr[i, j]);
                }
                Console.WriteLine();
            }
        }
    }
}

PHP strtotime +1 month adding an extra month

try this:

$endOfCycle = date("Y-m", time()+2592000);

this adds 30 days, not exactly a month tough.

How to query MongoDB with "like"?

If you want 'Like' search in mongo then you should go with $regex by using this query will be

db.product.find({name:{$regex:/m/i}})

for more you can read the documentation as well. https://docs.mongodb.com/manual/reference/operator/query/regex/

Is the buildSessionFactory() Configuration method deprecated in Hibernate

TL;DR

Yes, it is. There are better ways to bootstrap Hibernate, like the following ones.

Hibernate-native bootstrap

The legacy Configuration object is less powerful than using the BootstrapServiceRegistryBuilder, introduced since Hibernate 4:

final BootstrapServiceRegistryBuilder bsrb = new BootstrapServiceRegistryBuilder()
    .enableAutoClose();

Integrator integrator = integrator();
if (integrator != null) {
    bsrb.applyIntegrator( integrator );
}

final BootstrapServiceRegistry bsr = bsrb.build();

final StandardServiceRegistry serviceRegistry = 
    new StandardServiceRegistryBuilder(bsr)
        .applySettings(properties())
        .build();

final MetadataSources metadataSources = new MetadataSources(serviceRegistry);

for (Class annotatedClass : entities()) {
    metadataSources.addAnnotatedClass(annotatedClass);
}

String[] packages = packages();
if (packages != null) {
    for (String annotatedPackage : packages) {
        metadataSources.addPackage(annotatedPackage);
    }
}

String[] resources = resources();
if (resources != null) {
    for (String resource : resources) {
        metadataSources.addResource(resource);
    }
}

final MetadataBuilder metadataBuilder = metadataSources.getMetadataBuilder()
    .enableNewIdentifierGeneratorSupport(true)
    .applyImplicitNamingStrategy(ImplicitNamingStrategyLegacyJpaImpl.INSTANCE);

final List<Type> additionalTypes = additionalTypes();
if (additionalTypes != null) {
    additionalTypes.stream().forEach(type -> {
        metadataBuilder.applyTypes((typeContributions, sr) -> {
            if(type instanceof BasicType) {
                typeContributions.contributeType((BasicType) type);
            } else if (type instanceof UserType ){
                typeContributions.contributeType((UserType) type);
            } else if (type instanceof CompositeUserType) {
                typeContributions.contributeType((CompositeUserType) type);
            }
        });
    });
}

additionalMetadata(metadataBuilder);

MetadataImplementor metadata = (MetadataImplementor) metadataBuilder.build();

final SessionFactoryBuilder sfb = metadata.getSessionFactoryBuilder();
Interceptor interceptor = interceptor();
if(interceptor != null) {
    sfb.applyInterceptor(interceptor);
}

SessionFactory sessionFactory = sfb.build();

JPA bootstrap

You can also bootstrap Hibernate using JPA:

PersistenceUnitInfo persistenceUnitInfo = persistenceUnitInfo(getClass().getSimpleName());
Map configuration = properties();

Interceptor interceptor = interceptor();
if (interceptor != null) {
    configuration.put(AvailableSettings.INTERCEPTOR, interceptor);
}

Integrator integrator = integrator();
if (integrator != null) {
    configuration.put(
        "hibernate.integrator_provider", 
        (IntegratorProvider) () -> Collections.singletonList(integrator));
}

EntityManagerFactoryBuilderImpl entityManagerFactoryBuilder = 
    new EntityManagerFactoryBuilderImpl(
        new PersistenceUnitInfoDescriptor(persistenceUnitInfo), 
        configuration
);
EntityManagerFactory entityManagerFactory = entityManagerFactoryBuilder.build();

This way, you are building the EntityManagerFactory instead of a SessionFactory. However, the SessionFactory extends the EntityManagerFactory, so the actual object that's built is aSessionFactoryImpl` too.

Conclusion

These two bootstrapping methods affect Hibernate behavior. When using the native bootstrap, Hibernate behaves in the legacy mode, which predates JPA.

When bootstrapping using JPA, Hibernate will behave according to the JPA specification.

There are several differences between these two modes:

For more details about these differences, check out the JpaCompliance class.

Error: Cannot find module '../lib/utils/unsupported.js' while using Ionic

I got this error by mixing install/update methods: installed node via downloading package from website and later I used brew to update.

I fixed by uninstalling the brew version :

brew uninstall --ignore-dependencies node

Then I went back to node website and downloaded and installed via the package manager: https://nodejs.org/en/download/ For some reason, no amount of trying to reinstall via brew worked.

How to open generated pdf using jspdf in new window

Generally you can download it, show, or get a blob string:

const pdfActions = {
    save: () => doc.save(filename),
    getBlob: () => {
      const blob = doc.output('datauristring');
      console.log(blob)
      return blob
    },
    show: () => doc.output('dataurlnewwindow')
  }

Convert string to number field

Within Crystal, you can do it by creating a formula that uses the ToNumber function. It might be a good idea to code for the possibility that the field might include non-numeric data - like so:

If NumericText ({field}) then ToNumber ({field}) else 0

Alternatively, you might find it easier to convert the field's datatype within the query used in the report.

Create a function with optional call variables

I don't think your question is very clear, this code assumes that if you're going to include the -domain parameter, it's always 'named' (i.e. dostuff computername arg2 -domain domain); this also makes the computername parameter mandatory.

Function DoStuff(){
    param(
        [Parameter(Mandatory=$true)][string]$computername,
        [Parameter(Mandatory=$false)][string]$arg2,
        [Parameter(Mandatory=$false)][string]$domain
    )
    if(!($domain)){
        $domain = 'domain1'
    }
    write-host $domain
    if($arg2){
        write-host "arg2 present... executing script block"
    }
    else{
        write-host "arg2 missing... exiting or whatever"
    }
}

What is an undefined reference/unresolved external symbol error and how do I fix it?

what is an "undefined reference/unresolved external symbol"

I'll try to explain what is an "undefined reference/unresolved external symbol".

note: i use g++ and Linux and all examples is for it

For example we have some code

// src1.cpp
void print();

static int local_var_name; // 'static' makes variable not visible for other modules
int global_var_name = 123;

int main()
{
    print();
    return 0;
}

and

// src2.cpp
extern "C" int printf (const char*, ...);

extern int global_var_name;
//extern int local_var_name;

void print ()
{
    // printf("%d%d\n", global_var_name, local_var_name);
    printf("%d\n", global_var_name);
}

Make object files

$ g++ -c src1.cpp -o src1.o
$ g++ -c src2.cpp -o src2.o

After the assembler phase we have an object file, which contains any symbols to export. Look at the symbols

$ readelf --symbols src1.o
  Num:    Value          Size Type    Bind   Vis      Ndx Name
     5: 0000000000000000     4 OBJECT  LOCAL  DEFAULT    4 _ZL14local_var_name # [1]
     9: 0000000000000000     4 OBJECT  GLOBAL DEFAULT    3 global_var_name     # [2]

I've rejected some lines from output, because they do not matter

So, we see follow symbols to export.

[1] - this is our static (local) variable (important - Bind has a type "LOCAL")
[2] - this is our global variable

src2.cpp exports nothing and we have seen no its symbols

Link our object files

$ g++ src1.o src2.o -o prog

and run it

$ ./prog
123

Linker sees exported symbols and links it. Now we try to uncomment lines in src2.cpp like here

// src2.cpp
extern "C" int printf (const char*, ...);

extern int global_var_name;
extern int local_var_name;

void print ()
{
    printf("%d%d\n", global_var_name, local_var_name);
}

and rebuild an object file

$ g++ -c src2.cpp -o src2.o

OK (no errors), because we only build object file, linking is not done yet. Try to link

$ g++ src1.o src2.o -o prog
src2.o: In function `print()':
src2.cpp:(.text+0x6): undefined reference to `local_var_name'
collect2: error: ld returned 1 exit status

It has happened because our local_var_name is static, i.e. it is not visible for other modules. Now more deeply. Get the translation phase output

$ g++ -S src1.cpp -o src1.s

// src1.s
look src1.s

    .file   "src1.cpp"
    .local  _ZL14local_var_name
    .comm   _ZL14local_var_name,4,4
    .globl  global_var_name
    .data
    .align 4
    .type   global_var_name, @object
    .size   global_var_name, 4
global_var_name:
    .long   123
    .text
    .globl  main
    .type   main, @function
main:
; assembler code, not interesting for us
.LFE0:
    .size   main, .-main
    .ident  "GCC: (Ubuntu 4.8.2-19ubuntu1) 4.8.2"
    .section    .note.GNU-stack,"",@progbits

So, we've seen there is no label for local_var_name, that's why linker hasn't found it. But we are hackers :) and we can fix it. Open src1.s in your text editor and change

.local  _ZL14local_var_name
.comm   _ZL14local_var_name,4,4

to

    .globl  local_var_name
    .data
    .align 4
    .type   local_var_name, @object
    .size   local_var_name, 4
local_var_name:
    .long   456789

i.e. you should have like below

    .file   "src1.cpp"
    .globl  local_var_name
    .data
    .align 4
    .type   local_var_name, @object
    .size   local_var_name, 4
local_var_name:
    .long   456789
    .globl  global_var_name
    .align 4
    .type   global_var_name, @object
    .size   global_var_name, 4
global_var_name:
    .long   123
    .text
    .globl  main
    .type   main, @function
main:
; ...

we have changed the visibility of local_var_name and set its value to 456789. Try to build an object file from it

$ g++ -c src1.s -o src2.o

ok, see readelf output (symbols)

$ readelf --symbols src1.o
8: 0000000000000000     4 OBJECT  GLOBAL DEFAULT    3 local_var_name

now local_var_name has Bind GLOBAL (was LOCAL)

link

$ g++ src1.o src2.o -o prog

and run it

$ ./prog 
123456789

ok, we hack it :)

So, as a result - an "undefined reference/unresolved external symbol error" happens when the linker cannot find global symbols in the object files.

What are the minimum margins most printers can handle?

You shouldn't need to let the users specify the margin on your website - Let them do it on their computer. Print dialogs usually (Adobe and Preview, at least) give you an option to scale and center the output on the printable area of the page:

Adobe
alt text

Preview
alt text

Of course, this assumes that you have computer literate users, which may or may not be the case.

Fix height of a table row in HTML Table

the bottom cell will grow as you enter more text ... setting the table width will help too

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
</head>
<body>
<table id="content" style="min-height:525px; height:525px; width:100%; border:0px; margin:0; padding:0; border-collapse:collapse;">
<tr><td style="height:10px; background-color:#900;">Upper</td></tr>
<tr><td style="min-height:515px; height:515px; background-color:#909;">lower<br/>
</td></tr>
</table>
</body>
</html>

Python threading. How do I lock a thread?

import threading 

# global variable x 
x = 0

def increment(): 
    """ 
    function to increment global variable x 
    """
    global x 
    x += 1

def thread_task(): 
    """ 
    task for thread 
    calls increment function 100000 times. 
    """
    for _ in range(100000): 
        increment() 

def main_task(): 
    global x 
    # setting global variable x as 0 
    x = 0

    # creating threads 
    t1 = threading.Thread(target=thread_task) 
    t2 = threading.Thread(target=thread_task) 

    # start threads 
    t1.start() 
    t2.start() 

    # wait until threads finish their job 
    t1.join() 
    t2.join() 

if __name__ == "__main__": 
    for i in range(10): 
        main_task() 
        print("Iteration {0}: x = {1}".format(i,x))

Converting char[] to byte[]

char[] ch = ?
new String(ch).getBytes();

or

new String(ch).getBytes("UTF-8");

to get non-default charset.

Update: Since Java 7: new String(ch).getBytes(StandardCharsets.UTF_8);

How do I find all of the symlinks in a directory tree?

find already looks recursively by default:

[15:21:53 ~]$ mkdir foo
[15:22:28 ~]$ cd foo
[15:22:31 ~/foo]$ mkdir bar
[15:22:35 ~/foo]$ cd bar
[15:22:36 ~/foo/bar]$ ln -s ../foo abc
[15:22:40 ~/foo/bar]$ cd ..
[15:22:47 ~/foo]$ ln -s foo abc
[15:22:52 ~/foo]$ find ./ -type l
.//abc
.//bar/abc
[15:22:57 ~/foo]$ 

How can I get the executing assembly version?

I finally settled on typeof(MyClass).GetTypeInfo().Assembly.GetName().Version for a netstandard1.6 app. All of the other proposed answers presented a partial solution. This is the only thing that got me exactly what I needed.

Sourced from a combination of places:

https://msdn.microsoft.com/en-us/library/x4cw969y(v=vs.110).aspx

https://msdn.microsoft.com/en-us/library/2exyydhb(v=vs.110).aspx

How can I check the size of a collection within a Django template?

See https://docs.djangoproject.com/en/stable/ref/templates/builtins/#if : just use, to reproduce their example:

{% if athlete_list %}
    Number of athletes: {{ athlete_list|length }}
{% else %}
    No athletes.
{% endif %}

How to get Django and ReactJS to work together?

As others answered you, if you are creating a new project, you can separate frontend and backend and use any django rest plugin to create rest api for your frontend application. This is in the ideal world.

If you have a project with the django templating already in place, then you must load your react dom render in the page you want to load the application. In my case I had already django-pipeline and I just added the browserify extension. (https://github.com/j0hnsmith/django-pipeline-browserify)

As in the example, I loaded the app using django-pipeline:

PIPELINE = {
    # ...
    'javascript':{
        'browserify': {
            'source_filenames' : (
                'js/entry-point.browserify.js',
            ),
            'output_filename': 'js/entry-point.js',
        },
    }
}

Your "entry-point.browserify.js" can be an ES6 file that loads your react app in the template:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/app.js';
import "babel-polyfill";

import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import promise from 'redux-promise';
import reducers from './reducers/index.js';

const createStoreWithMiddleware = applyMiddleware(
  promise
)(createStore);

ReactDOM.render(
  <Provider store={createStoreWithMiddleware(reducers)}>
    <App/>
  </Provider>
  , document.getElementById('my-react-app')
);

In your django template, you can now load your app easily:

{% load pipeline %}

{% comment %} 
`browserify` is a PIPELINE key setup in the settings for django 
 pipeline. See the example above
{% endcomment %}

{% javascript 'browserify' %}

{% comment %} 
the app will be loaded here thanks to the entry point you created 
in PIPELINE settings. The key is the `entry-point.browserify.js` 
responsable to inject with ReactDOM.render() you react app in the div 
below
{% endcomment %}
<div id="my-react-app"></div>

The advantage of using django-pipeline is that statics get processed during the collectstatic.

How to drop all tables from the database with manage.py CLI in Django?

Here's a shell script I ended up piecing together to deal with this issue. Hope it saves someone some time.

#!/bin/sh

drop() {
    echo "Droping all tables prefixed with $1_."
    echo
    echo "show tables" | ./manage.py dbshell |
    egrep "^$1_" | xargs -I "@@" echo "DROP TABLE @@;" |
    ./manage.py dbshell
    echo "Tables dropped."
    echo
}

cancel() {
    echo "Cancelling Table Drop."
    echo
}

if [ -z "$1" ]; then
    echo "Please specify a table prefix to drop."
else
    echo "Drop all tables with $1_ prefix?"
    select choice in drop cancel;do
        $choice $1
        break
    done
fi

Assign format of DateTime with data annotations?

Try tagging it with:

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]

ArrayBuffer to base64 encoded string

My recommendation for this is to NOT use native btoa strategies—as they don't correctly encode all ArrayBuffer's…

rewrite the DOMs atob() and btoa()

Since DOMStrings are 16-bit-encoded strings, in most browsers calling window.btoa on a Unicode string will cause a Character Out Of Range exception if a character exceeds the range of a 8-bit ASCII-encoded character.

While I have never encountered this exact error, I have found that many of the ArrayBuffer's I have tried to encode have encoded incorrectly.

I would either use MDN recommendation or gist.

How to putAll on Java hashMap contents of one to another, but not replace existing keys and values?

As others have said, you can use putIfAbsent. Iterate over each entry in the map that you want to insert, and invoke this method on the original map:

mapToInsert.forEach(originalMap::putIfAbsent);

Python: count repeated elements in the list

Use Counter

>>> from collections import Counter
>>> MyList = ["a", "b", "a", "c", "c", "a", "c"]
>>> c = Counter(MyList)
>>> c
Counter({'a': 3, 'c': 3, 'b': 1})

Limit String Length

From php 4.0.6 , there is a function for the exact same thing

function mb_strimwidth can be used for your requirement

<?php
echo mb_strimwidth("Hello World", 0, 10, "...");
//Hello W...
?>

It does have more options though,here is the documentation for this mb_strimwidth

How to set initial size of std::vector?

You need to use the reserve function to set an initial allocated size or do it in the initial constructor.

vector<CustomClass *> content(20000);

or

vector<CustomClass *> content;
...
content.reserve(20000);

When you reserve() elements, the vector will allocate enough space for (at least?) that many elements. The elements do not exist in the vector, but the memory is ready to be used. This will then possibly speed up push_back() because the memory is already allocated.

Type or namespace name does not exist

I found that this is caused by me having the same namespace name as class name (MyWorld.MyWorld = Namespace.ClassName).

Change your namespace to a name that is not the same name as your class and this will compile.

Source

Android Volley - BasicNetwork.performRequest: Unexpected response code 400

What I did was append an extra '/' to my url, e.g.:

String url = "http://www.google.com" 

to

String url = "http://www.google.com/"

display data from SQL database into php/ html table

Look in the manual http://www.php.net/manual/en/mysqli.query.php

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}

/* Create table doesn't return a resultset */
if ($mysqli->query("CREATE TEMPORARY TABLE myCity LIKE City") === TRUE) {
    printf("Table myCity successfully created.\n");
}

/* Select queries return a resultset */
if ($result = $mysqli->query("SELECT Name FROM City LIMIT 10")) {
    printf("Select returned %d rows.\n", $result->num_rows);

    /* free result set */
    $result->close();
}

/* If we have to retrieve large amount of data we use MYSQLI_USE_RESULT */
if ($result = $mysqli->query("SELECT * FROM City", MYSQLI_USE_RESULT)) {

    /* Note, that we can't execute any functions which interact with the
       server until result set was closed. All calls will return an
       'out of sync' error */
    if (!$mysqli->query("SET @a:='this will not work'")) {
        printf("Error: %s\n", $mysqli->error);
    }
    $result->close();
}

$mysqli->close();
?>

A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations

Column values from the SELECT statement are assigned into @low and @day local variables; the @adjustedLow value is not assigned into any variable and it causes the problem:

The problem is here:

select 
    top 1 @low = low
    , @day = day
    , @adjustedLow  -- causes error!
--select high
from 
    securityquote sq
...

Detailed explanation and workaround: SQL Server Error Messages - Msg 141 - A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations.

the easiest way to convert matrix to one row vector

You can use the function RESHAPE:

B = reshape(A.',1,[]);

HTML input textbox with a width of 100% overflows table cells

I solved the problem by applying box-sizing:border-box; to the table cells themselves, besides doing the same with the input and the wrapper.

Transpose a data frame

df.aree <- as.data.frame(t(df.aree))
colnames(df.aree) <- df.aree[1, ]
df.aree <- df.aree[-1, ]
df.aree$myfactor <- factor(row.names(df.aree))

How to check if a word is an English word with Python?

I find that there are 3 package-based solutions to solve the problem. They are pyenchant, wordnet and corpus(self-defined or from ntlk). Pyenchant couldn't installed easily in win64 with py3. Wordnet doesn't work very well because it's corpus isn't complete. So for me, I choose the solution answered by @Sadik, and use 'set(words.words())' to speed up.

First:

pip3 install nltk
python3

import nltk
nltk.download('words')

Then:

from nltk.corpus import words
setofwords = set(words.words())

print("hello" in setofwords)
>>True

How to get changes from another branch

For other people coming upon this post on google. There are 2 options, either merging or rebasing your branch. Both works differently, but have similar outcomes.

The accepted answer is a rebase. This will take all the commits done to our-team and then apply the commits done to featurex, prompting you to merge them as needed.

One bit caveat of rebasing is that you lose/rewrite your branch history, essentially telling git that your branch did not began at commit 123abc but at commit 456cde. This will cause problems for other people working on the branch, and some remote tools will complain about it. If you are sure about what you are doing though, that's what the --force flag is for.

What other posters are suggesting is a merge. This will take the featurex branch, with whatever state it has and try to merge it with the current state of our-team, prompting you to do one, big, merge commit and fix all the merge errors before pushing to our-team. The difference is that you are applying your featurex commits before the our-team new commits and then fixing the differences. You also do not rewrite history, instead adding one commit to it instead of rewriting those that came before.

Both options are valid and can work in tandem. What is usually (by that I mean, if you are using widespread tools and methodology such as git-flow) done for a feature branch is to merge it into the main branch, often going through a merge-request, and solve all the conflicts that arise into one (or multiple) merge commits.

Rebasing is an interesting option, that may help you fix your branch before eventually going through a merge, and ease the pain of having to do one big merge commit.

How to make Apache serve index.php instead of index.html?

As of today (2015, Aug., 1st), Apache2 in Debian Jessie, you need to edit:

root@host:/etc/apache2/mods-enabled$ vi dir.conf 

And change the order of that line, bringing index.php to the first position:

DirectoryIndex index.php index.html index.cgi index.pl index.xhtml index.htm

How to convert TimeStamp to Date in Java?

    Timestamp tsp = new Timestamp(System.currentTimeMillis());
   java.util.Date dateformat = new java.util.Date(tsp.getTime());

Entity Framework - Linq query with order by and group by

Try moving the order by after group by:

var groupByReference = (from m in context.Measurements
                        group m by new { m.Reference } into g
                        order by g.Avg(i => i.CreationTime)
                        select g).Take(numOfEntries).ToList();

What is the better API to Reading Excel sheets in java - JXL or Apache POI

I have used POI.

If you use that, keep on eye those cell formatters: create one and use it several times instead of creating each time for cell, it isa huge memory consumption difference or large data.

How to Install Font Awesome in Laravel Mix

first install fontawsome using npm

npm install --save @fortawesome/fontawesome-free

add to resources\sass\app.scss

// Fonts
@import '~@fortawesome/fontawesome-free/scss/fontawesome';

and add to resources\js\app.js

require('@fortawesome/fontawesome-free/js/all.js');

then run

npm run dev

or

npm run production

Retrieving a List from a java.util.stream.Stream in Java 8

Updated:

Another approach is to use Collectors.toList:

targetLongList = 
    sourceLongList.stream().
    filter(l -> l > 100).
    collect(Collectors.toList());

Previous Solution:

Another approach is to use Collectors.toCollection:

targetLongList = 
    sourceLongList.stream().
    filter(l -> l > 100).
    collect(Collectors.toCollection(ArrayList::new));

How to use the CancellationToken property?

You can implement your work method as follows:

private static void Work(CancellationToken cancelToken)
{
    while (true)
    {
        if(cancelToken.IsCancellationRequested)
        {
            return;
        }
        Console.Write("345");
    }
}

That's it. You always need to handle cancellation by yourself - exit from method when it is appropriate time to exit (so that your work and data is in consistent state)

UPDATE: I prefer not writing while (!cancelToken.IsCancellationRequested) because often there are few exit points where you can stop executing safely across loop body, and loop usually have some logical condition to exit (iterate over all items in collection etc.). So I believe it's better not to mix that conditions as they have different intention.

Cautionary note about avoiding CancellationToken.ThrowIfCancellationRequested():

Comment in question by Eamon Nerbonne:

... replacing ThrowIfCancellationRequested with a bunch of checks for IsCancellationRequested exits gracefully, as this answer says. But that's not just an implementation detail; that affects observable behavior: the task will no longer end in the cancelled state, but in RanToCompletion. And that can affect not just explicit state checks, but also, more subtly, task chaining with e.g. ContinueWith, depending on the TaskContinuationOptions used. I'd say that avoiding ThrowIfCancellationRequested is dangerous advice.

How do I create delegates in Objective-C?

As a good practice recommended by Apple, it's good for the delegate (which is a protocol, by definition), to conform to NSObject protocol.

@protocol MyDelegate <NSObject>
    ...
@end

& to create optional methods within your delegate (i.e. methods which need not necessarily be implemented), you can use the @optional annotation like this :

@protocol MyDelegate <NSObject>
    ...
    ...
      // Declaration for Methods that 'must' be implemented'
    ...
    ...
    @optional
    ...
      // Declaration for Methods that 'need not necessarily' be implemented by the class conforming to your delegate
    ...
@end

So when using methods that you have specified as optional, you need to (in your class) check with respondsToSelector if the view (that is conforming to your delegate) has actually implemented your optional method(s) or not.

IndexError: list index out of range and python

Always keep in mind when you want to overcome this error, the default value of indexing and range starts from 0, so if total items is 100 then l[99] and range(99) will give you access up to the last element.

whenever you get this type of error please cross check with items that comes between/middle in range, and insure that their index is not last if you get output then you have made perfect error that mentioned above.

How to read text files with ANSI encoding and non-English letters?

using (StreamWriter writer = new StreamWriter(File.Open(@"E:\Sample.txt", FileMode.Append), Encoding.GetEncoding(1250)))  ////File.Create(path)
        {
            writer.Write("Sample Text");
        }

HttpContext.Current.Session is null when routing requests

Just add attribute runAllManagedModulesForAllRequests="true" to system.webServer\modules in web.config.

This attribute is enabled by default in MVC and Dynamic Data projects.

How to compare two dates?

Other answers using datetime and comparisons also work for time only, without a date.

For example, to check if right now it is more or less than 8:00 a.m., we can use:

import datetime

eight_am = datetime.time( 8,0,0 ) # Time, without a date

And later compare with:

datetime.datetime.now().time() > eight_am  

which will return True

Lollipop : draw behind statusBar with its color set to transparent

All you need to do is set these properties in your theme

<item name="android:windowTranslucentStatus">true</item>
<item name="android:windowTranslucentNavigation">true</item>

How do I call an Angular.js filter with multiple arguments?

If you want to call your filter inside ng-options the code will be as follows:

ng-options="productSize as ( productSize | sizeWithPrice: product )  for productSize in productSizes track by productSize.id"

where the filter is sizeWithPriceFilter and it has two parameters product and productSize

Adding blank spaces to layout

Below is the simple way to create blank line with line size. Here we can adjust size of the blank line. Try this one.

           <TextView
            android:id="@id/textView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="5dp"/>

Passing an array/list into a Python function

You can pass lists just like other types:

l = [1,2,3]

def stuff(a):
   for x in a:
      print a


stuff(l)

This prints the list l. Keep in mind lists are passed as references not as a deep copy.

Stop a youtube video with jquery?

I was facing the same problem. After a lot of alternatives what I did was just reset the embed src="" with the same URL.

Code snippet:

  $("#videocontainer").fadeOut(200);<br/>
  $("#videoplayer").attr("src",videoURL);

I was able to at least stop the video from playing when I hide it.:-)

In Tkinter is there any way to make a widget not visible?

import tkinter as tk
...
x = tk.Label(text='Hello', visible=True)
def visiblelabel(lb, visible):
    lb.config(visible=visible)
visiblelabel(x, False)  # Hide
visiblelabel(x, True)  # Show

P.S. config can change any attribute:

x.config(text='Hello')  # Text: Hello
x.config(text='Bye', font=('Arial', 20, 'bold'))  # Text: Bye, Font: Arial Bold 20
x.config(bg='red', fg='white')  # Background: red, Foreground: white

It's a bypass of StringVar, IntVar etc.

How to declare a variable in a template in Angular

I am using angular 6x and I've ended up by using below snippet. I've a scenerio where I've to find user from a task object. it contains array of users but I've to pick assigned user.

<ng-container *ngTemplateOutlet="memberTemplate; context:{o: getAssignee(task) }">
</ng-container>
<ng-template #memberTemplate let-user="o">
  <ng-container *ngIf="user">
    <div class="d-flex flex-row-reverse">
      <span class="image-block">
        <ngx-avatar placement="left" ngbTooltip="{{user.firstName}} {{user.lastName}}" class="task-assigned" value="28%" [src]="user.googleId" size="32"></ngx-avatar>
      </span>
    </div>
  </ng-container>
</ng-template>

"The remote certificate is invalid according to the validation procedure." using Gmail SMTP server

use my function as diagnostic certificates issues - see screen

            System.Net.ServicePointManager.ServerCertificateValidationCallback = Function(s As Object,
                                                                                          cert As System.Security.Cryptography.X509Certificates.X509Certificate,
                                                                                          chain As System.Security.Cryptography.X509Certificates.X509Chain,
                                                                                          err As System.Net.Security.SslPolicyErrors)
                                                                                     Return True
                                                                                 End Function

enter image description here

How can I strip first and last double quotes?

Starting in Python 3.9, you can use removeprefix and removesuffix:

'"" " " ""\\1" " "" ""'.removeprefix('"').removesuffix('"')
# '" " " ""\\1" " "" "'

Check if a string is palindrome

Note that reversing the whole string (either with the rbegin()/rend() range constructor or with std::reverse) and comparing it with the input would perform unnecessary work.

It's sufficient to compare the first half of the string with the latter half, in reverse:

#include <string>
#include <algorithm>
#include <iostream>
int main()
{
    std::string s;
    std::cin >> s;
    if( equal(s.begin(), s.begin() + s.size()/2, s.rbegin()) )
        std::cout << "is a palindrome.\n";
    else
        std::cout << "is NOT a palindrome.\n";
}

demo: http://ideone.com/mq8qK

How to write a multidimensional array to a text file?

There exist special libraries to do just that. (Plus wrappers for python)

hope this helps

getCurrentPosition() and watchPosition() are deprecated on insecure origins

Give some time to install an SSL cert getCurrentPosition() and watchPosition() no longer work on insecure origins. To use this feature, you should consider switching your application to a secure origin, such as HTTPS.

Top 1 with a left join

Use OUTER APPLY instead of LEFT JOIN:

SELECT u.id, mbg.marker_value 
FROM dps_user u
OUTER APPLY 
    (SELECT TOP 1 m.marker_value, um.profile_id
     FROM dps_usr_markers um (NOLOCK)
         INNER JOIN dps_markers m (NOLOCK) 
             ON m.marker_id= um.marker_id AND 
                m.marker_key = 'moneyBackGuaranteeLength'
     WHERE um.profile_id=u.id 
     ORDER BY m.creation_date
    ) AS MBG
WHERE u.id = 'u162231993';

Unlike JOIN, APPLY allows you to reference the u.id inside the inner query.

How do I format a string using a dictionary in python-3.x?

To unpack a dictionary into keyword arguments, use **. Also,, new-style formatting supports referring to attributes of objects and items of mappings:

'{0[latitude]} {0[longitude]}'.format(geopoint)
'The title is {0.title}s'.format(a) # the a from your first example

What is the Difference Between read() and recv() , and Between send() and write()?

The difference is that recv()/send() work only on socket descriptors and let you specify certain options for the actual operation. Those functions are slightly more specialized (for instance, you can set a flag to ignore SIGPIPE, or to send out-of-band messages...).

Functions read()/write() are the universal file descriptor functions working on all descriptors.

Angular 2 How to redirect to 404 or other path if the path does not exist

For version v2.2.2 and newer

In version v2.2.2 and up, name property no longer exists and it shouldn't be used to define the route. path should be used instead of name and no leading slash is needed on the path. In this case use path: '404' instead of path: '/404':

 {path: '404', component: NotFoundComponent},
 {path: '**', redirectTo: '/404'}

For versions older than v2.2.2

you can use {path: '/*path', redirectTo: ['redirectPathName']}:

{path: '/home/...', name: 'Home', component: HomeComponent}
{path: '/', redirectTo: ['Home']},
{path: '/user/...', name: 'User', component: UserComponent},
{path: '/404', name: 'NotFound', component: NotFoundComponent},

{path: '/*path', redirectTo: ['NotFound']}

if no path matches then redirect to NotFound path

how to add <script>alert('test');</script> inside a text box?

is you want fix XSS on input element? you can encode string before output to input field

PHP:

$str = htmlentities($str);

C#:

str = WebUtility.HtmlEncode(str);

after that output value direct to input field:

<input type="text" value="<?php echo $str" />

Run command on the Ansible host

you can try this way

What is the difference between LATERAL and a subquery in PostgreSQL?

What is a LATERAL join?

The feature was introduced with PostgreSQL 9.3.
Quoting the manual:

Subqueries appearing in FROM can be preceded by the key word LATERAL. This allows them to reference columns provided by preceding FROM items. (Without LATERAL, each subquery is evaluated independently and so cannot cross-reference any other FROM item.)

Table functions appearing in FROM can also be preceded by the key word LATERAL, but for functions the key word is optional; the function's arguments can contain references to columns provided by preceding FROM items in any case.

Basic code examples are given there.

More like a correlated subquery

A LATERAL join is more like a correlated subquery, not a plain subquery, in that expressions to the right of a LATERAL join are evaluated once for each row left of it - just like a correlated subquery - while a plain subquery (table expression) is evaluated once only. (The query planner has ways to optimize performance for either, though.)
Related answer with code examples for both side by side, solving the same problem:

For returning more than one column, a LATERAL join is typically simpler, cleaner and faster.
Also, remember that the equivalent of a correlated subquery is LEFT JOIN LATERAL ... ON true:

Things a subquery can't do

There are things that a LATERAL join can do, but a (correlated) subquery cannot (easily). A correlated subquery can only return a single value, not multiple columns and not multiple rows - with the exception of bare function calls (which multiply result rows if they return multiple rows). But even certain set-returning functions are only allowed in the FROM clause. Like unnest() with multiple parameters in Postgres 9.4 or later. The manual:

This is only allowed in the FROM clause;

So this works, but cannot (easily) be replaced with a subquery:

CREATE TABLE tbl (a1 int[], a2 int[]);
SELECT * FROM tbl, unnest(a1, a2) u(elem1, elem2);  -- implicit LATERAL

The comma (,) in the FROM clause is short notation for CROSS JOIN.
LATERAL is assumed automatically for table functions.
About the special case of UNNEST( array_expression [, ... ] ):

Set-returning functions in the SELECT list

You can also use set-returning functions like unnest() in the SELECT list directly. This used to exhibit surprising behavior with more than one such function in the same SELECT list up to Postgres 9.6. But it has finally been sanitized with Postgres 10 and is a valid alternative now (even if not standard SQL). See:

Building on above example:

SELECT *, unnest(a1) AS elem1, unnest(a2) AS elem2
FROM   tbl;

Comparison:

dbfiddle for pg 9.6 here
dbfiddle for pg 10 here

Clarify misinformation

The manual:

For the INNER and OUTER join types, a join condition must be specified, namely exactly one of NATURAL, ON join_condition, or USING (join_column [, ...]). See below for the meaning.
For CROSS JOIN, none of these clauses can appear.

So these two queries are valid (even if not particularly useful):

SELECT *
FROM   tbl t
LEFT   JOIN LATERAL (SELECT * FROM b WHERE b.t_id = t.t_id) t ON TRUE;

SELECT *
FROM   tbl t, LATERAL (SELECT * FROM b WHERE b.t_id = t.t_id) t;

While this one is not:

SELECT *
FROM   tbl t
LEFT   JOIN LATERAL (SELECT * FROM b WHERE b.t_id = t.t_id) t;

That's why Andomar's code example is correct (the CROSS JOIN does not require a join condition) and Attila's is was not.

Width equal to content

If you are using display: flex for whatever reason and need on browsers like Edge/IE, you can instead use:

display: inline-flex

With ~97% browser support for inline-flex.

How to detect scroll position of page using jQuery

$('.div').scroll(function (event) {
 event.preventDefault()
 var scroll = $(this).scrollTop();
 if(scroll == 0){
   alert(123)
 }
});

This code for chat_boxes for loading previous messages

The best way to remove duplicate values from NSMutableArray in Objective-C?

Yes, using NSSet is a sensible approach.

To add to Jim Puls' answer, here's an alternative approach to stripping duplicates while retaining order:

// Initialise a new, empty mutable array 
NSMutableArray *unique = [NSMutableArray array];

for (id obj in originalArray) {
    if (![unique containsObject:obj]) {
        [unique addObject:obj];
    }
}

It's essentially the same approach as Jim's but copies unique items to a fresh mutable array rather than deleting duplicates from the original. This makes it slightly more memory efficient in the case of a large array with lots of duplicates (no need to make a copy of the entire array), and is in my opinion a little more readable.

Note that in either case, checking to see if an item is already included in the target array (using containsObject: in my example, or indexOfObject:inRange: in Jim's) doesn't scale well for large arrays. Those checks run in O(N) time, meaning that if you double the size of the original array then each check will take twice as long to run. Since you're doing the check for each object in the array, you'll also be running more of those more expensive checks. The overall algorithm (both mine and Jim's) runs in O(N2) time, which gets expensive quickly as the original array grows.

To get that down to O(N) time you could use a NSMutableSet to store a record of items already added to the new array, since NSSet lookups are O(1) rather than O(N). In other words, checking to see whether an element is a member of an NSSet takes the same time regardless of how many elements are in the set.

Code using this approach would look something like this:

NSMutableArray *unique = [NSMutableArray array];
NSMutableSet *seen = [NSMutableSet set];

for (id obj in originalArray) {
    if (![seen containsObject:obj]) {
        [unique addObject:obj];
        [seen addObject:obj];
    }
}

This still seems a little wasteful though; we're still generating a new array when the question made clear that the original array is mutable, so we should be able to de-dupe it in place and save some memory. Something like this:

NSMutableSet *seen = [NSMutableSet set];
NSUInteger i = 0;

while (i < [originalArray count]) {
    id obj = [originalArray objectAtIndex:i];

    if ([seen containsObject:obj]) {
        [originalArray removeObjectAtIndex:i];
        // NB: we *don't* increment i here; since
        // we've removed the object previously at
        // index i, [originalArray objectAtIndex:i]
        // now points to the next object in the array.
    } else {
        [seen addObject:obj];
        i++;
    }
}

UPDATE: Yuri Niyazov pointed out that my last answer actually runs in O(N2) because removeObjectAtIndex: probably runs in O(N) time.

(He says "probably" because we don't know for sure how it's implemented; but one possible implementation is that after deleting the object at index X the method then loops through every element from index X+1 to the last object in the array, moving them to the previous index. If that's the case then that is indeed O(N) performance.)

So, what to do? It depends on the situation. If you've got a large array and you're only expecting a small number of duplicates then the in-place de-duplication will work just fine and save you having to build up a duplicate array. If you've got an array where you're expecting lots of duplicates then building up a separate, de-duped array is probably the best approach. The take-away here is that big-O notation only describes the characteristics of an algorithm, it won't tell you definitively which is best for any given circumstance.

How to downgrade the installed version of 'pip' on windows?

well the only thing that will work is

python -m pip install pip==

you can and should run it under IDE terminal (mine was pycharm)

How to use the onClick event for Hyperlink using C# code?

Wow, you have a huge misunderstanding how asp.net works.

This line of code

System.Diagnostics.Process.Start("help/AdminTutorial.html");

Will not redirect a admin user to a new site, but start a new process on the server (usually a browser, IE) and load the site. That is for sure not what you want.

A very easy solution would be to change the href attribute of the link in you page_load method.

Your aspx code:

<a href="#" runat="server" id="myLink">Tutorial</a>

Your codebehind / cs code of page_load:

...
if (userinfo.user == "Admin")
{
  myLink.Attributes["href"] = "help/AdminTutorial.html";
}
else 
{
  myLink.Attributes["href"] = "help/otherSite.html";
}
...

Don't forget to check the Admin rights again on "AdminTutorial.html" to "prevent" hacking.

Ruby Array find_first object?

use array detect method if you wanted to return first value where block returns true

[1,2,3,11,34].detect(&:even?) #=> 2

OR

[1,2,3,11,34].detect{|i| i.even?} #=> 2

If you wanted to return all values where block returns true then use select

[1,2,3,11,34].select(&:even?)  #=> [2, 34]

How to make Python script run as service?

I use this code to daemonize my applications. It allows you start/stop/restart the script using the following commands.

python myscript.py start
python myscript.py stop
python myscript.py restart

In addition to this I also have an init.d script for controlling my service. This allows you to automatically start the service when your operating system boots-up.

Here is a simple example to get your going. Simply move your code inside a class, and call it from the run function inside MyDeamon.

import sys
import time

from daemon import Daemon


class YourCode(object):
    def run(self):
        while True:
            time.sleep(1)


class MyDaemon(Daemon):
    def run(self):
        # Or simply merge your code with MyDaemon.
        your_code = YourCode()
        your_code.run()


if __name__ == "__main__":
    daemon = MyDaemon('/tmp/daemon-example.pid')
    if len(sys.argv) == 2:
        if 'start' == sys.argv[1]:
            daemon.start()
        elif 'stop' == sys.argv[1]:
            daemon.stop()
        elif 'restart' == sys.argv[1]:
            daemon.restart()
        else:
            print "Unknown command"
            sys.exit(2)
        sys.exit(0)
    else:
        print "usage: %s start|stop|restart" % sys.argv[0]
        sys.exit(2)

Upstart

If you are running an operating system that is using Upstart (e.g. CentOS 6) - you can also use Upstart to manage the service. If you use Upstart you can keep your script as is, and simply add something like this under /etc/init/my-service.conf

start on started sshd
stop on runlevel [!2345]

exec /usr/bin/python /opt/my_service.py
respawn

You can then use start/stop/restart to manage your service.

e.g.

start my-service
stop my-service
restart my-service

A more detailed example of working with upstart is available here.

Systemd

If you are running an operating system that uses Systemd (e.g. CentOS 7) you can take a look at the following Stackoverflow answer.

Migration: Cannot add foreign key constraint

i know thats a old question but make sure if you are working with references the proper supporting engine is defined. set innodb engine for both tables and same data type for the reference columns

$table->engine = 'InnoDB';

WampServer: php-win.exe The program can't start because MSVCR110.dll is missing

As far as I am aware, the MSVCRxxx.dlls are in %SystemRoot%\System32 (usually C:\Windows\System32).

The xxx refers to the version of the MS Visual C Runtime (hence MSVCR...)

However, the complication seems to be that the xxx version is not the same as the two digits of the year "version".

For example, Visual C Runtime 2013 yields MSVCR120.dll and "...Runtime 2012" yields MSVCR110.dll. And then Microsoft packages these as vcredist_x86.exe or vcredist_x64.exe, seemingly irrespective of the xxx version or the Visual Studio version number (2012, 2013 etc) - confused? You have every right to be!

So, firstly, you need to determine whether you need 32 bit, 64 bit or even both (some PHP distributions apparently do need both), then download the relevant vcredist... for the bits AND for the Visual Studio version. As far as I can tell, the only way to tell which vcredist... you have is to start to install it. Recent versions give an intro screen that quotes the Visual Studio version and the xxx version. I have renamed by vcredists to something like vcredist_x64_2012_V11.exe.

[EDIT] Forgot to add earlier that if you are simply looking to "install" the missing DLL (as opposed to resolve some bigger set of issues), then you probably won't do any harm by simply installing the relevant vcredist for your architecture (32 bit, 64 bit) and "missing" version.

How to persist data in a dockerized postgres database using volumes

I think you just need to create your volume outside docker first with a docker create -v /location --name and then reuse it.

And by the time I used to use docker a lot, it wasn't possible to use a static docker volume with dockerfile definition so my suggestion is to try the command line (eventually with a script ) .

How can I change UIButton title color?

Solution in Swift 3:

button.setTitleColor(UIColor.red, for: .normal)

This will set the title color of button.

Spring profiles and testing

Can I recommend doing it this way, define your test like this:

@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({
    TestPreperationExecutionListener.class
    })
@Transactional
@ActiveProfiles(profiles = "localtest")
@ContextConfiguration
public class TestContext {

  @Test
  public void testContext(){

  }

  @Configuration
  @PropertySource("classpath:/myprops.properties")
  @ImportResource({"classpath:context.xml" })
  public static class MyContextConfiguration{

  }
}

with the following content in myprops.properties file:

spring.profiles.active=localtest

With this your second properties file should get resolved:

META-INF/spring/config_${spring.profiles.active}.properties

angular ng-repeat in reverse

When using MVC in .NET with Angular you can always use OrderByDecending() when doing your db query like this:

var reversedList = dbContext.GetAll().OrderByDecending(x => x.Id).ToList();

Then on the Angular side, it will already be reversed in some browsers (IE). When supporting Chrome and FF, you would then need to add orderBy:

<tr ng-repeat="item in items | orderBy:'-Id'">

In this example, you'd be sorting in descending order on the .Id property. If you're using paging, this gets more complicated because only the first page would be sorted. You'd need to handle this via a .js filter file for your controller, or in some other way.

Using OpenSSL what does "unable to write 'random state'" mean?

You should set the $RANDFILE environment variable and/or create $HOME/.rnd file. (OpenSSL FAQ). (Of course, you should have rights to that file. Others answers here are about that. But first you should have the file and a reference to it.)

Up to version 0.9.6 OpenSSL wrote the seeding file in the current directory in the file ".rnd". At version 0.9.6a you have no default seeding file. OpenSSL 0.9.6b and later will behave similarly to 0.9.6a, but will use a default of "C:\" for HOME on Windows systems if the environment variable has not been set.

If the default seeding file does not exist or is too short, the "PRNG not seeded" error message may occur.

The $RANDFILE environment variable and $HOME/.rnd are only used by the OpenSSL command line tools. Applications using the OpenSSL library provide their own configuration options to specify the entropy source, please check out the documentation coming the with application.

nodemon command is not recognized in terminal for node js server

To use nodemon you must install it globally.

For Windows

npm i -g nodemon

For Mac

sudo npm i -g nodemon

If you don't want to install it globally you can install it locally in your project folder by running command npm i nodemon . It will give error something like this if run locally:

nodemon : The term 'nodemon' is not recognized as the name of a
cmdlet, function, script file, or operable program. Check the spelling
of the name, or if a path was included, verify that the path is
correct and try again.

To remove this error open package.json file and add

"scripts": {
     "server": "nodemon server.js"
 },

and after that just run command

npm run server

and your nodemon will start working properly.

Cannot deserialize the JSON array (e.g. [1,2,3]) into type ' ' because type requires JSON object (e.g. {"name":"value"}) to deserialize correctly

Your json string is wrapped within square brackets ([]), hence it is interpreted as array instead of single RetrieveMultipleResponse object. Therefore, you need to deserialize it to type collection of RetrieveMultipleResponse, for example :

var objResponse1 = 
    JsonConvert.DeserializeObject<List<RetrieveMultipleResponse>>(JsonStr);

getch and arrow codes

how about trying this?

void CheckKey(void) {
int key;
if (kbhit()) {
    key=getch();
    if (key == 224) {
        do {
            key=getch();
        } while(key==224);
        switch (key) {
            case 72:
                printf("up");
                break;
            case 75:
                printf("left");
                break;
            case 77:
                printf("right");
                break;
            case 80:
                printf("down");
                break;
        }
    }
    printf("%d\n",key);
}

int main() {
    while (1) {
        if (kbhit()) {
            CheckKey();
        }
    }
}

(if you can't understand why there is 224, then try running this code: )

#include <stdio.h>
#include <conio.h>

int main() {
    while (1) {
        if (kbhit()) {
            printf("%d\n",getch());
        }
    }
}

but I don't know why it's 224. can you write down a comment if you know why?

How to stop the Timer in android?

     CountDownTimer waitTimer;
     waitTimer = new CountDownTimer(60000, 300) {

       public void onTick(long millisUntilFinished) {
          //called every 300 milliseconds, which could be used to
          //send messages or some other action
       }

       public void onFinish() {
          //After 60000 milliseconds (60 sec) finish current 
          //if you would like to execute something when time finishes          
       }
     }.start();

to stop the timer early:

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

Dictionary text file

http://www.math.sjsu.edu/~foster/dictionary.txt

350,000 words

Very late, but might be useful for others.

What is an "index out of range" exception, and how do I fix it?

Why does this error occur?

Because you tried to access an element in a collection, using a numeric index that exceeds the collection's boundaries.

The first element in a collection is generally located at index 0. The last element is at index n-1, where n is the Size of the collection (the number of elements it contains). If you attempt to use a negative number as an index, or a number that is larger than Size-1, you're going to get an error.

How indexing arrays works

When you declare an array like this:

var array = new int[6]

The first and last elements in the array are

var firstElement = array[0];
var lastElement = array[5];

So when you write:

var element = array[5];

you are retrieving the sixth element in the array, not the fifth one.

Typically, you would loop over an array like this:

for (int index = 0; index < array.Length; index++)
{
    Console.WriteLine(array[index]);
}

This works, because the loop starts at zero, and ends at Length-1 because index is no longer less than Length.

This, however, will throw an exception:

for (int index = 0; index <= array.Length; index++)
{
    Console.WriteLine(array[index]);
}

Notice the <= there? index will now be out of range in the last loop iteration, because the loop thinks that Length is a valid index, but it is not.

How other collections work

Lists work the same way, except that you generally use Count instead of Length. They still start at zero, and end at Count - 1.

for (int index = 0; i < list.Count; index++)
{
    Console.WriteLine(list[index]);
} 

However, you can also iterate through a list using foreach, avoiding the whole problem of indexing entirely:

foreach (var element in list)
{
    Console.WriteLine(element.ToString());
}

You cannot index an element that hasn't been added to a collection yet.

var list = new List<string>();
list.Add("Zero");
list.Add("One");
list.Add("Two");
Console.WriteLine(list[3]);  // Throws exception.

No module named setuptools

For ubuntu users, this error may arise because setuptool is not installed system-wide. Simply install setuptool using the command:

sudo apt-get install -y python-setuptools

For python3:

sudo apt-get install -y python3-setuptools

After that, install your package again normally, using

sudo python setup.py install

That's all.

Ajax - 500 Internal Server Error

I fixed an error like this changing the places of the routes in routes.php, for example i had something like this:

Route::resource('Mensajes', 'MensajeriaController');
Route::get('Mensajes/modificar', 'MensajeriaController@modificarEstado');

and then I put it like this:

Route::get('Mensajes/modificar', 'MensajeriaController@modificarEstado');
Route::resource('Mensajes', 'MensajeriaController');

Brew doctor says: "Warning: /usr/local/include isn't writable."

You can alias the command to fix this problem in your .bash_profile and run it every time you encounter it:

At the end of the file ~/.bash_profile, add:

alias fix_brew='sudo chown -R $USER /usr/local/'

And now inside your terminal you can run:

$ fix_brew

How do I pipe a subprocess call to a text file?

If you want to write the output to a file you can use the stdout-argument of subprocess.call.

It takes None, subprocess.PIPE, a file object or a file descriptor. The first is the default, stdout is inherited from the parent (your script). The second allows you to pipe from one command/process to another. The third and fourth are what you want, to have the output written to a file.

You need to open a file with something like open and pass the object or file descriptor integer to call:

f = open("blah.txt", "w")
subprocess.call(["/home/myuser/run.sh", "/tmp/ad_xml",  "/tmp/video_xml"], stdout=f)

I'm guessing any valid file-like object would work, like a socket (gasp :)), but I've never tried.

As marcog mentions in the comments you might want to redirect stderr as well, you can redirect this to the same location as stdout with stderr=subprocess.STDOUT. Any of the above mentioned values works as well, you can redirect to different places.

Fastest way to check if a string matches a regexp in ruby?

Starting with Ruby 2.4.0, you may use RegExp#match?:

pattern.match?(string)

Regexp#match? is explicitly listed as a performance enhancement in the release notes for 2.4.0, as it avoids object allocations performed by other methods such as Regexp#match and =~:

Regexp#match?
Added Regexp#match?, which executes a regexp match without creating a back reference object and changing $~ to reduce object allocation.

What are the differences between NP, NP-Complete and NP-Hard?

In addition to the other great answers, here is the typical schema people use to show the difference between NP, NP-Complete, and NP-Hard:

enter image description here

vim line numbers - how to have them on by default?

To change the default setting to display line numbers in vi/vim:

vi ~/.vimrc

then add the following line to the file:

set number

Either we can source ~/.vimrc or save and quit by :wq, now future vi/vim sessions will have numbering :)

Apply function to each column in a data frame observing each columns existing data type

If it were an "ordered factor" things would be different. Which is not to say I like "ordered factors", I don't, only to say that some relationships are defined for 'ordered factors' that are not defined for "factors". Factors are thought of as ordinary categorical variables. You are seeing the natural sort order of factors which is alphabetical lexical order for your locale. If you want to get an automatic coercion to "numeric" for every column, ... dates and factors and all, then try:

sapply(df, function(x) max(as.numeric(x)) )   # not generally a useful result

Or if you want to test for factors first and return as you expect then:

sapply( df, function(x) if("factor" %in% class(x) ) { 
            max(as.numeric(as.character(x)))
            } else { max(x) } )

@Darrens comment does work better:

 sapply(df, function(x) max(as.character(x)) )  

max does succeed with character vectors.

Have a reloadData for a UITableView animate when changing

If you want to add your own custom animations to UITableView cells, use

[theTableView reloadData];
[theTableView layoutSubviews];
NSArray* visibleViews = [theTableView visibleCells];

to get an array of visible cells. Then add any custom animation to each cell.

Check out this gist I posted for a smooth custom cell animation. https://gist.github.com/floprr/1b7a58e4a18449d962bd

Chart.js v2 - hiding grid lines

Please refer to the official documentation:

https://www.chartjs.org/docs/latest/axes/styling.html#grid-line-configuration

Below code changes would hide the gridLines:

        gridLines: {
            display:false
        }

enter image description here

Passing an array of data as an input parameter to an Oracle procedure

If the types of the parameters are all the same (varchar2 for example), you can have a package like this which will do the following:

CREATE OR REPLACE PACKAGE testuser.test_pkg IS

   TYPE assoc_array_varchar2_t IS TABLE OF VARCHAR2(4000) INDEX BY BINARY_INTEGER;

   PROCEDURE your_proc(p_parm IN assoc_array_varchar2_t);

END test_pkg;

CREATE OR REPLACE PACKAGE BODY testuser.test_pkg IS

   PROCEDURE your_proc(p_parm IN assoc_array_varchar2_t) AS
   BEGIN
      FOR i IN p_parm.first .. p_parm.last
      LOOP
         dbms_output.put_line(p_parm(i));
      END LOOP;

   END;

END test_pkg;

Then, to call it you'd need to set up the array and pass it:

DECLARE
  l_array testuser.test_pkg.assoc_array_varchar2_t;
BEGIN
  l_array(0) := 'hello';
  l_array(1) := 'there';  

  testuser.test_pkg.your_proc(l_array);
END;
/

Android - How to download a file from a webserver

It is bad practice to perform network operations on the main thread, which is why you are seeing the NetworkOnMainThreadException. It is prevented by the policy. If you really must do it for testing, put the following in your OnCreate:

 StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
 StrictMode.setThreadPolicy(policy); 

Please remember that is is very bad practice to do this, and should ideally move your network code to an AsyncTask or a Thread.

How can I wait In Node.js (JavaScript)? l need to pause for a period of time

The other answers are great but I thought I'd take a different tact.

If all you are really looking for is to slow down a specific file in linux:

 rm slowfile; mkfifo slowfile; perl -e 'select STDOUT; $| = 1; while(<>) {print $_; sleep(1) if (($ii++ % 5) == 0); }' myfile > slowfile  &

node myprog slowfile

This will sleep 1 sec every five lines. The node program will go as slow as the writer. If it is doing other things they will continue at normal speed.

The mkfifo creates a first-in-first-out pipe. It's what makes this work. The perl line will write as fast as you want. The $|=1 says don't buffer the output.

Calling a function of a module by using its name (a string)

Although getattr() is elegant (and about 7x faster) method, you can get return value from the function (local, class method, module) with eval as elegant as x = eval('foo.bar')(). And when you implement some error handling then quite securely (the same principle can be used for getattr). Example with module import and class:

# import module, call module function, pass parameters and print retured value with eval():
import random
bar = 'random.randint'
randint = eval(bar)(0,100)
print(randint) # will print random int from <0;100)

# also class method returning (or not) value(s) can be used with eval: 
class Say:
    def say(something='nothing'):
        return something

bar = 'Say.say'
print(eval(bar)('nice to meet you too')) # will print 'nice to meet you' 

When module or class does not exist (typo or anything better) then NameError is raised. When function does not exist, then AttributeError is raised. This can be used to handle errors:

# try/except block can be used to catch both errors
try:
    eval('Say.talk')() # raises AttributeError because function does not exist
    eval('Says.say')() # raises NameError because the class does not exist
    # or the same with getattr:
    getattr(Say, 'talk')() # raises AttributeError
    getattr(Says, 'say')() # raises NameError
except AttributeError:
    # do domething or just...
    print('Function does not exist')
except NameError:
    # do domething or just...
    print('Module does not exist')

VBA Excel sort range by specific column

Try this code:

Dim lastrow As Long
lastrow = Cells(Rows.Count, 2).End(xlUp).Row
Range("A3:D" & lastrow).Sort key1:=Range("B3:B" & lastrow), _
   order1:=xlAscending, Header:=xlNo

From ND to 1D arrays

I wanted to see a benchmark result of functions mentioned in answers including unutbu's.

Also want to point out that numpy doc recommend to use arr.reshape(-1) in case view is preferable. (even though ravel is tad faster in the following result)


TL;DR: np.ravel is the most performant (by very small amount).

Benchmark

Functions:

numpy version: '1.18.0'

Execution times on different ndarray sizes

+-------------+----------+-----------+-----------+-------------+
|  function   |   10x10  |  100x100  | 1000x1000 | 10000x10000 |
+-------------+----------+-----------+-----------+-------------+
| ravel       | 0.002073 |  0.002123 |  0.002153 |    0.002077 |
| reshape(-1) | 0.002612 |  0.002635 |  0.002674 |    0.002701 |
| flatten     | 0.000810 |  0.007467 |  0.587538 |  107.321913 |
| flat        | 0.000337 |  0.000255 |  0.000227 |    0.000216 |
+-------------+----------+-----------+-----------+-------------+

Conclusion

ravel and reshape(-1)'s execution time was consistent and independent from ndarray size. However, ravel is tad faster, but reshape provides flexibility in reshaping size. (maybe that's why numpy doc recommend to use it instead. Or there could be some cases where reshape returns view and ravel doesn't).
If you are dealing with large size ndarray, using flatten can cause a performance issue. Recommend not to use it. Unless you need a copy of the data to do something else.

Used code

import timeit
setup = '''
import numpy as np
nd = np.random.randint(10, size=(10, 10))
'''

timeit.timeit('nd = np.reshape(nd, -1)', setup=setup, number=1000)
timeit.timeit('nd = np.ravel(nd)', setup=setup, number=1000)
timeit.timeit('nd = nd.flatten()', setup=setup, number=1000)
timeit.timeit('nd.flat', setup=setup, number=1000)

Encoding Javascript Object to Json string

You can use JSON.stringify like:

JSON.stringify(new_tweets);

ASP.NET MVC 3 - redirect to another action

return RedirectToAction("ActionName", "ControllerName");

Adding an assets folder in Android Studio

To specify any additional asset folder I've used this with my Gradle. This adds moreAssets, a folder in the project root, to the assets.

android {
    sourceSets {
        main.assets.srcDirs += '../moreAssets'
    }
}

HTML code for an apostrophe

A List Apart has a nice reference on characters and typography in HTML. According to that article, the correct HTML entity for the apostrophe is &#8217;. Example use: ’ .

Static variable inside of a function in C

That is the same as having the following program:

static int x = 5;

void foo()
{
    x++;
    printf("%d", x);
}

int main()
{
     foo();
     foo();
     return 0;
}

All that the static keyword does in that program is it tells the compiler (essentially) 'hey, I have a variable here that I don't want anyone else accessing, don't tell anyone else it exists'.

Inside a method, the static keyword tells the compiler the same as above, but also, 'don't tell anyone that this exists outside of this function, it should only be accessible inside this function'.

I hope this helps

Java POI : How to read Excel cell value and not the formula computing it?

For formula cells, excel stores two things. One is the Formula itself, the other is the "cached" value (the last value that the forumla was evaluated as)

If you want to get the last cached value (which may no longer be correct, but as long as Excel saved the file and you haven't changed it it should be), you'll want something like:

 for(Cell cell : row) {
     if(cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
        System.out.println("Formula is " + cell.getCellFormula());
        switch(cell.getCachedFormulaResultType()) {
            case Cell.CELL_TYPE_NUMERIC:
                System.out.println("Last evaluated as: " + cell.getNumericCellValue());
                break;
            case Cell.CELL_TYPE_STRING:
                System.out.println("Last evaluated as \"" + cell.getRichStringCellValue() + "\"");
                break;
        }
     }
 }

getting only name of the class Class.getName()

The below both ways works fine.

System.out.println("The Class Name is: " + this.getClass().getName());
System.out.println("The simple Class Name is: " + this.getClass().getSimpleName());

Output as below:

The Class Name is: package.Student

The simple Class Name is: Student

How can I maintain fragment state when added to the back stack?

Public void replaceFragment(Fragment mFragment, int id, String tag, boolean addToStack) {
        FragmentTransaction mTransaction = getSupportFragmentManager().beginTransaction();
        mTransaction.replace(id, mFragment);
        hideKeyboard();
        if (addToStack) {
            mTransaction.addToBackStack(tag);
        }
        mTransaction.commitAllowingStateLoss();
    }
replaceFragment(new Splash_Fragment(), R.id.container, null, false);

Error :The remote server returned an error: (401) Unauthorized

I add credentials for HttpWebRequest.

myReq.UseDefaultCredentials = true;
myReq.PreAuthenticate = true;
myReq.Credentials = CredentialCache.DefaultCredentials;

How to find out the MySQL root password

The default password which worked for me after immediate installation of mysql server is : mysql

Convert Numeric value to Varchar

i think it should be

select convert(varchar(10),StandardCost) +'S' from DimProduct where ProductKey = 212

or

select cast(StandardCost as varchar(10)) + 'S' from DimProduct where ProductKey = 212

Can someone explain how to append an element to an array in C programming?

If you have a code like int arr[10] = {0, 5, 3, 64}; , and you want to append or add a value to next index, you can simply add it by typing a[5] = 5.

The main advantage of doing it like this is you can add or append a value to an any index not required to be continued one, like if I want to append the value 8 to index 9, I can do it by the above concept prior to filling up before indices. But in python by using list.append() you can do it by continued indices.

How to position a table at the center of div horizontally & vertically

Centering is one of the biggest issues in CSS. However, some tricks exist:

To center your table horizontally, you can set left and right margin to auto:

<style>
  #test {
    width:100%;
    height:100%;
  }
  table {
    margin: 0 auto; /* or margin: 0 auto 0 auto */
  }
</style>

To center it vertically, the only way is to use javascript:

var tableMarginTop = Math.round( (testHeight - tableHeight) / 2 );
$('table').css('margin-top', tableMarginTop) # with jQuery
$$('table')[0].setStyle('margin-top', tableMarginTop) # with Mootools

No vertical-align:middle is possible as a table is a block and not an inline element.

Edit

Here is a website that sums up CSS centering solutions: http://howtocenterincss.com/

Android Failed to install HelloWorld.apk on device (null) Error

If you are running it on an Android Emulator you do not want to close it between runs. The system will try to load the app and it will time out because of how long it takes the emulator to boot up. You can fix this by increasing the ADB time by going to Window -> Preferences -> Android -> DDMS and increasing the ADB time out (default is 5000ms) or by leaving the emulator open and just running it after the emulator is up and running.

I personally would recommend leaving the emulator open as it does load the apps relatively quickly once it is running, but it could be a drain on the system. Do whichever would help you more.

How to get text with Selenium WebDriver in Python

To print the text my text you can use either of the following Locator Strategies:

  • Using class_name and get_attribute("textContent"):

    print(driver.find_element(By.CLASS_NAME, "current-stage").get_attribute("textContent"))
    
  • Using css_selector and get_attribute("innerHTML"):

    print(driver.find_element(By.CSS_SELECTOR, "span.current-stage").get_attribute("innerHTML"))
    
  • Using xpath and text attribute:

    print(driver.find_element(By.XPATH, "//span[@class='current-stage']").text)
    

Ideally you need to induce WebDriverWait for the visibility_of_element_located() and you can use either of the following Locator Strategies:

  • Using CLASS_NAME and get_attribute("textContent"):

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CLASS_NAME, "current-stage"))).get_attribute("textContent"))
    
  • Using CSS_SELECTOR and text attribute:

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "span.current-stage"))).text)
    
  • Using XPATH and get_attribute("innerHTML"):

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//span[@class='current-stage']"))).get_attribute("innerHTML"))
    
  • Note : You have to add the following imports :

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    

You can find a relevant discussion in How to retrieve the text of a WebElement using Selenium - Python


References

Link to useful documentation:

How to insert a character in a string at a certain position?

int j = 123456;
String x = Integer.toString(j);
x = x.substring(0, 4) + "." + x.substring(4, x.length());

Left join only selected columns in R with the merge() function

You can do this by subsetting the data you pass into your merge:

merge(x = DF1, y = DF2[ , c("Client", "LO")], by = "Client", all.x=TRUE)

Or you can simply delete the column after your current merge :)

How to force a web browser NOT to cache images

When uploading an image, its filename is not kept in the database. It is renamed as Image.jpg (to simply things out when using it).

Change this, and you've fixed your problem. I use timestamps, as with the solutions proposed above: Image-<timestamp>.jpg

Presumably, whatever problems you're avoiding by keeping the same filename for the image can be overcome, but you don't say what they are.

How can I match multiple occurrences with a regex in JavaScript similar to PHP's preg_match_all()?

If someone (like me) needs Tomalak's method with array support (ie. multiple select), here it is:

function getUrlParams(url) {
  var re = /(?:\?|&(?:amp;)?)([^=&#]+)(?:=?([^&#]*))/g,
      match, params = {},
      decode = function (s) {return decodeURIComponent(s.replace(/\+/g, " "));};

  if (typeof url == "undefined") url = document.location.href;

  while (match = re.exec(url)) {
    if( params[decode(match[1])] ) {
        if( typeof params[decode(match[1])] != 'object' ) {
            params[decode(match[1])] = new Array( params[decode(match[1])], decode(match[2]) );
        } else {
            params[decode(match[1])].push(decode(match[2]));
        }
    }
    else
        params[decode(match[1])] = decode(match[2]);
  }
  return params;
}
var urlParams = getUrlParams(location.search);

input ?my=1&my=2&my=things

result 1,2,things (earlier returned only: things)

How do I reflect over the members of dynamic object?

If the IDynamicMetaObjectProvider can provide the dynamic member names, you can get them. See GetMemberNames implementation in the apache licensed PCL library Dynamitey (which can be found in nuget), it works for ExpandoObjects and DynamicObjects that implement GetDynamicMemberNames and any other IDynamicMetaObjectProvider who provides a meta object with an implementation of GetDynamicMemberNames without custom testing beyond is IDynamicMetaObjectProvider.

After getting the member names it's a little more work to get the value the right way, but Impromptu does this but it's harder to point to just the interesting bits and have it make sense. Here's the documentation and it is equal or faster than reflection, however, unlikely to be faster than a dictionary lookup for expando, but it works for any object, expando, dynamic or original - you name it.

How do I filter ForeignKey choices in a Django ModelForm?

So, I've really tried to understand this, but it seems that Django still doesn't make this very straightforward. I'm not all that dumb, but I just can't see any (somewhat) simple solution.

I find it generally pretty ugly to have to override the Admin views for this sort of thing, and every example I find never fully applies to the Admin views.

This is such a common circumstance with the models I make that I find it appalling that there's no obvious solution to this...

I've got these classes:

# models.py
class Company(models.Model):
    # ...
class Contract(models.Model):
    company = models.ForeignKey(Company)
    locations = models.ManyToManyField('Location')
class Location(models.Model):
    company = models.ForeignKey(Company)

This creates a problem when setting up the Admin for Company, because it has inlines for both Contract and Location, and Contract's m2m options for Location are not properly filtered according to the Company that you're currently editing.

In short, I would need some admin option to do something like this:

# admin.py
class LocationInline(admin.TabularInline):
    model = Location
class ContractInline(admin.TabularInline):
    model = Contract
class CompanyAdmin(admin.ModelAdmin):
    inlines = (ContractInline, LocationInline)
    inline_filter = dict(Location__company='self')

Ultimately I wouldn't care if the filtering process was placed on the base CompanyAdmin, or if it was placed on the ContractInline. (Placing it on the inline makes more sense, but it makes it hard to reference the base Contract as 'self'.)

Is there anyone out there who knows of something as straightforward as this badly needed shortcut? Back when I made PHP admins for this sort of thing, this was considered basic functionality! In fact, it was always automatic, and had to be disabled if you really didn't want it!

CSS list item width/height does not work

Remove the <br> from the .navcontainer-top li styles.

ASP.NET jQuery Ajax Calling Code-Behind Method

This hasn't solved my problem too, so I changed the parameters slightly.
This code worked for me:

var dataValue = "{ name: 'person', isGoing: 'true', returnAddress: 'returnEmail' }";

$.ajax({
    type: "POST",
    url: "Default.aspx/OnSubmit",
    data: dataValue,
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
    },
    success: function (result) {
        alert("We returned: " + result.d);
    }
});

'negative' pattern matching in python

and(re.search("bla_bla_pattern", str_item, re.IGNORECASE) == None)

is working.

Multiple file-extensions searchPattern for System.IO.Directory.GetFiles

    /// <summary>
    /// Returns the names of files in a specified directories that match the specified patterns using LINQ
    /// </summary>
    /// <param name="srcDirs">The directories to seach</param>
    /// <param name="searchPatterns">the list of search patterns</param>
    /// <param name="searchOption"></param>
    /// <returns>The list of files that match the specified pattern</returns>
    public static string[] GetFilesUsingLINQ(string[] srcDirs,
         string[] searchPatterns,
         SearchOption searchOption = SearchOption.AllDirectories)
    {
        var r = from dir in srcDirs
                from searchPattern in searchPatterns
                from f in Directory.GetFiles(dir, searchPattern, searchOption)
                select f;

        return r.ToArray();
    }

How do I get the coordinates of a mouse click on a canvas element?

Update (5/5/16): patriques' answer should be used instead, as it's both simpler and more reliable.


Since the canvas isn't always styled relative to the entire page, the canvas.offsetLeft/Top doesn't always return what you need. It will return the number of pixels it is offset relative to its offsetParent element, which can be something like a div element containing the canvas with a position: relative style applied. To account for this you need to loop through the chain of offsetParents, beginning with the canvas element itself. This code works perfectly for me, tested in Firefox and Safari but should work for all.

function relMouseCoords(event){
    var totalOffsetX = 0;
    var totalOffsetY = 0;
    var canvasX = 0;
    var canvasY = 0;
    var currentElement = this;

    do{
        totalOffsetX += currentElement.offsetLeft - currentElement.scrollLeft;
        totalOffsetY += currentElement.offsetTop - currentElement.scrollTop;
    }
    while(currentElement = currentElement.offsetParent)

    canvasX = event.pageX - totalOffsetX;
    canvasY = event.pageY - totalOffsetY;

    return {x:canvasX, y:canvasY}
}
HTMLCanvasElement.prototype.relMouseCoords = relMouseCoords;

The last line makes things convenient for getting the mouse coordinates relative to a canvas element. All that's needed to get the useful coordinates is

coords = canvas.relMouseCoords(event);
canvasX = coords.x;
canvasY = coords.y;

Python "extend" for a dictionary

In case you need it as a Class, you can extend it with dict and use update method:

Class a(dict):
  # some stuff
  self.update(b)

PHP Connection failed: SQLSTATE[HY000] [2002] Connection refused

Using MAMP ON Mac, I solve my problem by renaming

/Applications/MAMP/tmp/mysql/mysql.sock.lock

to

/Applications/MAMP/tmp/mysql/mysql.sock

Just what is an IntPtr exactly?

It's a "native (platform-specific) size integer." It's internally represented as void* but exposed as an integer. You can use it whenever you need to store an unmanaged pointer and don't want to use unsafe code. IntPtr.Zero is effectively NULL (a null pointer).

Cross domain POST request is not sending cookie Ajax Jquery

I had this same problem. The session ID is sent in a cookie, but since the request is cross-domain, the browser's security settings will block the cookie from being sent.

Solution: Generate the session ID on the client (in the browser), use Javascript sessionStorage to store the session ID then send the session ID with each request to the server.

I struggled a lot with this issue, and there weren't many good answers around. Here's an article detailing the solution: Javascript Cross-Domain Request With Session

How to initialize a private static const map in C++?

The C++11 standard introduced uniform initialization which makes this much simpler if your compiler supports it:

//myClass.hpp
class myClass {
  private:
    static map<int,int> myMap;
};


//myClass.cpp
map<int,int> myClass::myMap = {
   {1, 2},
   {3, 4},
   {5, 6}
};

See also this section from Professional C++, on unordered_maps.

Escape double quote in VB string

Escaping quotes in VB6 or VBScript strings is simple in theory although often frightening when viewed. You escape a double quote with another double quote.

An example:

"c:\program files\my app\app.exe"

If I want to escape the double quotes so I could pass this to the shell execute function listed by Joe or the VB6 Shell function I would write it:

escapedString = """c:\program files\my app\app.exe"""

How does this work? The first and last quotes wrap the string and let VB know this is a string. Then each quote that is displayed literally in the string has another double quote added in front of it to escape it.

It gets crazier when you are trying to pass a string with multiple quoted sections. Remember, every quote you want to pass has to be escaped.

If I want to pass these two quoted phrases as a single string separated by a space (which is not uncommon):

"c:\program files\my app\app.exe" "c:\documents and settings\steve"

I would enter this:

escapedQuoteHell = """c:\program files\my app\app.exe"" ""c:\documents and settings\steve"""

I've helped my sysadmins with some VBScripts that have had even more quotes.

It's not pretty, but that's how it works.

How to escape % in String.Format?

This is a stronger regex replace that won't replace %% that are already doubled in the input.

str = str.replaceAll("(?:[^%]|\\A)%(?:[^%]|\\z)", "%%");

Sorting multiple keys with Unix sort

Take care though:

If you want to sort the file primarily by field 3, and secondarily by field 2 you want this:

sort -k 3,3 -k 2,2 < inputfile

Not this: sort -k 3 -k 2 < inputfile which sorts the file by the string from the beginning of field 3 to the end of line (which is potentially unique).

-k, --key=POS1[,POS2]     start a key at POS1 (origin 1), end it at POS2
                          (default end of line)

How to get a thread and heap dump of a Java process on Windows that's not running in a console

In addition to using the mentioned jconsole/visualvm, you can use jstack -l <vm-id> on another command line window, and capture that output.

The <vm-id> can be found using the task manager (it is the process id on windows and unix), or using jps.

Both jstack and jps are include in the Sun JDK version 6 and higher.

Sequelize.js delete query?

  1. the best way to delete a record is to find it firstly (if exist in data base in the same time you want to delete it)
  2. watch this code
const StudentSequelize = require("../models/studientSequelize");
const StudentWork = StudentSequelize.Student;

const id = req.params.id;
    StudentWork.findByPk(id) // here i fetch result by ID sequelize V. 5
    .then( resultToDelete=>{
        resultToDelete.destroy(id); // when i find the result i deleted it by destroy function
    })
    .then( resultAfterDestroy=>{
        console.log("Deleted :",resultAfterDestroy);
    })
    .catch(err=> console.log(err));

What are Runtime.getRuntime().totalMemory() and freeMemory()?

To understand it better, run this following program (in jdk1.7.x) :

$ java -Xms1025k -Xmx1025k -XshowSettings:vm  MemoryTest

This will print jvm options and the used, free, total and maximum memory available in jvm.

public class MemoryTest {    
    public static void main(String args[]) {
                System.out.println("Used Memory   :  " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) + " bytes");
                System.out.println("Free Memory   : " + Runtime.getRuntime().freeMemory() + " bytes");
                System.out.println("Total Memory  : " + Runtime.getRuntime().totalMemory() + " bytes");
                System.out.println("Max Memory    : " + Runtime.getRuntime().maxMemory() + " bytes");            
        }
}

Linq UNION query to select two elements

EDIT:

Ok I found why the int.ToString() in LINQtoEF fails, please read this post: Problem with converting int to string in Linq to entities

This works on my side :

        List<string> materialTypes = (from u in result.Users
                                      select u.LastName)
                       .Union(from u in result.Users
                               select SqlFunctions.StringConvert((double) u.UserId)).ToList();

On yours it should be like this:

    IList<String> materialTypes = ((from tom in context.MaterialTypes
                                       where tom.IsActive == true
                                       select tom.Name)
                                       .Union(from tom in context.MaterialTypes
                                       where tom.IsActive == true
                                       select SqlFunctions.StringConvert((double)tom.ID))).ToList();

Thanks, i've learnt something today :)

fatal: 'origin' does not appear to be a git repository

It is possible the other branch you try to pull from is out of synch; so before adding and removing remote try to (if you are trying to pull from master)

git pull origin master

for me that simple call solved those error messages:

  • fatal: 'master' does not appear to be a git repository
  • fatal: Could not read from remote repository.

How to give ASP.NET access to a private key in a certificate in the certificate store?

Although I have attended the above, I have come to this point after many attempts. 1- If you want access to the certificate from the store, you can do this as an example 2- It is much easier and cleaner to produce the certificate and use it via a path

Asp.net Core 2.2 OR1:

using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Operators;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto.Prng;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.X509;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

namespace Tursys.Pool.Storage.Api.Utility
{
    class CertificateManager
    {
        public static X509Certificate2 GetCertificate(string caller)
        {
            AsymmetricKeyParameter caPrivateKey = null;
            X509Certificate2 clientCert;
            X509Certificate2 serverCert;

            clientCert = GetCertificateIfExist("CN=127.0.0.1", StoreName.My, StoreLocation.LocalMachine);
            serverCert = GetCertificateIfExist("CN=MyROOTCA", StoreName.Root, StoreLocation.LocalMachine);
            if (clientCert == null || serverCert == null)
            {
                var caCert = GenerateCACertificate("CN=MyROOTCA", ref caPrivateKey);
                addCertToStore(caCert, StoreName.Root, StoreLocation.LocalMachine);

                clientCert = GenerateSelfSignedCertificate("CN=127.0.0.1", "CN=MyROOTCA", caPrivateKey);
                var p12 = clientCert.Export(X509ContentType.Pfx);

                addCertToStore(new X509Certificate2(p12, (string)null, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet), StoreName.My, StoreLocation.LocalMachine);
            }

            if (caller == "client")
                return clientCert;

            return serverCert;
        }

        public static X509Certificate2 GenerateSelfSignedCertificate(string subjectName, string issuerName, AsymmetricKeyParameter issuerPrivKey)
        {
            const int keyStrength = 2048;

            // Generating Random Numbers
            CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator();
            SecureRandom random = new SecureRandom(randomGenerator);

            // The Certificate Generator
            X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();

            // Serial Number
            BigInteger serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);
            certificateGenerator.SetSerialNumber(serialNumber);

            // Signature Algorithm
            //const string signatureAlgorithm = "SHA256WithRSA";
            //certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm);

            // Issuer and Subject Name
            X509Name subjectDN = new X509Name(subjectName);
            X509Name issuerDN = new X509Name(issuerName);
            certificateGenerator.SetIssuerDN(issuerDN);
            certificateGenerator.SetSubjectDN(subjectDN);

            // Valid For
            DateTime notBefore = DateTime.UtcNow.Date;
            DateTime notAfter = notBefore.AddYears(2);

            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);

            // Subject Public Key
            AsymmetricCipherKeyPair subjectKeyPair;
            var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
            var keyPairGenerator = new RsaKeyPairGenerator();
            keyPairGenerator.Init(keyGenerationParameters);
            subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            // Generating the Certificate
            AsymmetricCipherKeyPair issuerKeyPair = subjectKeyPair;

            ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA512WITHRSA", issuerKeyPair.Private, random);
            // selfsign certificate
            Org.BouncyCastle.X509.X509Certificate certificate = certificateGenerator.Generate(signatureFactory);


            // correcponding private key
            PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private);


            // merge into X509Certificate2
            X509Certificate2 x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded());

            Asn1Sequence seq = (Asn1Sequence)Asn1Object.FromByteArray(info.PrivateKeyAlgorithm.GetDerEncoded());
            if (seq.Count != 9)
            {
                //throw new PemException("malformed sequence in RSA private key");
            }

            RsaPrivateKeyStructure rsa = RsaPrivateKeyStructure.GetInstance(info.ParsePrivateKey());
            RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters(
                rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient);

            try
            {
                var rsap = DotNetUtilities.ToRSA(rsaparams);
                x509 = x509.CopyWithPrivateKey(rsap);

                //x509.PrivateKey = ToDotNetKey(rsaparams);
            }
            catch(Exception ex)
            {
                ;
            }
            //x509.PrivateKey = DotNetUtilities.ToRSA(rsaparams);
            return x509;

        }

        public static AsymmetricAlgorithm ToDotNetKey(RsaPrivateCrtKeyParameters privateKey)
        {
            var cspParams = new CspParameters
            {
                KeyContainerName = Guid.NewGuid().ToString(),
                KeyNumber = (int)KeyNumber.Exchange,
                Flags = CspProviderFlags.UseMachineKeyStore
            };

            var rsaProvider = new RSACryptoServiceProvider(cspParams);
            var parameters = new RSAParameters
            {
                Modulus = privateKey.Modulus.ToByteArrayUnsigned(),
                P = privateKey.P.ToByteArrayUnsigned(),
                Q = privateKey.Q.ToByteArrayUnsigned(),
                DP = privateKey.DP.ToByteArrayUnsigned(),
                DQ = privateKey.DQ.ToByteArrayUnsigned(),
                InverseQ = privateKey.QInv.ToByteArrayUnsigned(),
                D = privateKey.Exponent.ToByteArrayUnsigned(),
                Exponent = privateKey.PublicExponent.ToByteArrayUnsigned()
            };

            rsaProvider.ImportParameters(parameters);
            return rsaProvider;
        }

        public static X509Certificate2 GenerateCACertificate(string subjectName, ref AsymmetricKeyParameter CaPrivateKey)
        {
            const int keyStrength = 2048;

            // Generating Random Numbers
            CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator();
            SecureRandom random = new SecureRandom(randomGenerator);

            // The Certificate Generator
            X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();

            // Serial Number
            BigInteger serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);
            certificateGenerator.SetSerialNumber(serialNumber);

            // Signature Algorithm
            //const string signatureAlgorithm = "SHA256WithRSA";
            //certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm);

            // Issuer and Subject Name
            X509Name subjectDN = new X509Name(subjectName);
            X509Name issuerDN = subjectDN;
            certificateGenerator.SetIssuerDN(issuerDN);
            certificateGenerator.SetSubjectDN(subjectDN);

            // Valid For
            DateTime notBefore = DateTime.UtcNow.Date;
            DateTime notAfter = notBefore.AddYears(2);

            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);

            // Subject Public Key
            AsymmetricCipherKeyPair subjectKeyPair;
            KeyGenerationParameters keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
            RsaKeyPairGenerator keyPairGenerator = new RsaKeyPairGenerator();
            keyPairGenerator.Init(keyGenerationParameters);
            subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            // Generating the Certificate
            AsymmetricCipherKeyPair issuerKeyPair = subjectKeyPair;

            // selfsign certificate
            //Org.BouncyCastle.X509.X509Certificate certificate = certificateGenerator.Generate(issuerKeyPair.Private, random);

            ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA512WITHRSA", issuerKeyPair.Private, random);
            // selfsign certificate
            Org.BouncyCastle.X509.X509Certificate certificate = certificateGenerator.Generate(signatureFactory);


            X509Certificate2 x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded());

            CaPrivateKey = issuerKeyPair.Private;

            return x509;
            //return issuerKeyPair.Private;

        }

        public static bool addCertToStore(System.Security.Cryptography.X509Certificates.X509Certificate2 cert, System.Security.Cryptography.X509Certificates.StoreName st, System.Security.Cryptography.X509Certificates.StoreLocation sl)
        {
            bool bRet = false;

            try
            {
                X509Store store = new X509Store(st, sl);
                store.Open(OpenFlags.ReadWrite);
                store.Add(cert);

                store.Close();
            }
            catch
            {

            }

            return bRet;
        }

        protected internal static X509Certificate2 GetCertificateIfExist(string subjectName, StoreName store, StoreLocation location)
        {
            using (var certStore = new X509Store(store, location))
            {
                certStore.Open(OpenFlags.ReadOnly);
                var certCollection = certStore.Certificates.Find(
                                           X509FindType.FindBySubjectDistinguishedName, subjectName, false);
                X509Certificate2 certificate = null;
                if (certCollection.Count > 0)
                {
                    certificate = certCollection[0];
                }
                return certificate;
            }
        }

    }
}

OR 2:

    services.AddDataProtection()
//.PersistKeysToFileSystem(new DirectoryInfo(@"c:\temp-keys"))
.ProtectKeysWithCertificate(
        new X509Certificate2(Path.Combine(Directory.GetCurrentDirectory(), "clientCert.pfx"), "Password")
        )
.UnprotectKeysWithAnyCertificate(
        new X509Certificate2(Path.Combine(Directory.GetCurrentDirectory(), "clientCert.pfx"), "Password")
        );

Detecting TCP Client Disconnect

To expand on this a bit more:

If you are running a server you either need to use TCP_KEEPALIVE to monitor the client connections, or do something similar yourself, or have knowledge about the data/protocol that you are running over the connection.

Basically, if the connection gets killed (i.e. not properly closed) then the server won't notice until it tries to write something to the client, which is what the keepalive achieves for you. Alternatively, if you know the protocol better, you could just disconnect on an inactivity timeout anyway.

Datatables on-the-fly resizing

You should try this one.

var table = $('#example').DataTable();
table.columns.adjust().draw();

Link: column adjust in datatable

CSS3 equivalent to jQuery slideUp and slideDown?

why not to take advantage of modern browsers css transition and make things simpler and fast using more css and less jquery

Here is the code for sliding up and down

Here is the code for sliding left to right

Similarly we can change the sliding from top to bottom or right to left by changing transform-origin and transform: scaleX(0) or transform: scaleY(0) appropriately.

Generate 'n' unique random numbers within a range

Generate the range of data first and then shuffle it like this

import random
data = range(numLow, numHigh)
random.shuffle(data)
print data

By doing this way, you will get all the numbers in the particular range but in a random order.

But you can use random.sample to get the number of elements you need, from a range of numbers like this

print random.sample(range(numLow, numHigh), 3)

How to get a value from the last inserted row?

Use sequences in postgres for id columns:

INSERT mytable(myid) VALUES (nextval('MySequence'));

SELECT currval('MySequence');

currval will return the current value of the sequence in the same session.

(In MS SQL, you would use @@identity or SCOPE_IDENTITY())

How to change the color of the axis, ticks and labels for a plot in matplotlib

As a quick example (using a slightly cleaner method than the potentially duplicate question):

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)

ax.plot(range(10))
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')

ax.spines['bottom'].set_color('red')
ax.spines['top'].set_color('red')
ax.xaxis.label.set_color('red')
ax.tick_params(axis='x', colors='red')

plt.show()

alt text

Alternatively

[t.set_color('red') for t in ax.xaxis.get_ticklines()]
[t.set_color('red') for t in ax.xaxis.get_ticklabels()]

Creating a LINQ select from multiple tables

change

select op) 

to

select new { op, pg })

How can I use ":" as an AWK field separator?

You have multiple ways to set : as the separator:

awk -F: '{print $1}'

awk -v FS=: '{print $1}'

awk '{print $1}' FS=:

awk 'BEGIN{FS=":"} {print $1}'

All of them are equivalent and will return 1 given a sample input "1:2:3":

$ awk -F: '{print $1}' <<< "1:2:3"
1
$ awk -v FS=: '{print $1}' <<< "1:2:3"
1
$ awk '{print $1}' FS=: <<< "1:2:3"
1
$ awk 'BEGIN{FS=":"} {print $1}' <<< "1:2:3"
1

writing integer values to a file using out.write()

Also you can use f-string formatting to write integer to file

For appending use following code, for writing once replace 'a' with 'w'.

for i in s_list:
    with open('path_to_file','a') as file:
        file.write(f'{i}\n')

file.close()

Undefined reference to main - collect2: ld returned 1 exit status

Perhaps your main function has been commented out because of e.g. preprocessing. To learn what preprocessing is doing, try gcc -C -E es3.c > es3.i then look with an editor into the generated file es3.i (and search main inside it).

First, you should always (since you are a newbie) compile with

  gcc -Wall -g -c es3.c
  gcc -Wall -g es3.o -o es3

The -Wall flag is extremely important, and you should always use it. It tells the compiler to give you (almost) all warnings. And you should always listen to the warnings, i.e. correct your source code file es3.C till you got no more warnings.

The -g flag is important also, because it asks gcc to put debugging information in the object file and the executable. Then you are able to use a debugger (like gdb) to debug your program.

To get the list of symbols in an object file or an executable, you can use nm.

Of course, I'm assuming you use a GNU/Linux system (and I invite you to use GNU/Linux if you don't use it already).

How to open a web server port on EC2 instance

Follow the steps that are described on this answer just instead of using the drop down, type the port (8787) in "port range" an then "Add rule".

Go to the "Network & Security" -> Security Group settings in the left hand navigation

enter image description here Find the Security Group that your instance is apart of Click on Inbound Rules enter image description here Use the drop down and add HTTP (port 80) enter image description here Click Apply and enjoy

How to UPSERT (MERGE, INSERT ... ON DUPLICATE UPDATE) in PostgreSQL?

9.5 and newer:

PostgreSQL 9.5 and newer support INSERT ... ON CONFLICT (key) DO UPDATE (and ON CONFLICT (key) DO NOTHING), i.e. upsert.

Comparison with ON DUPLICATE KEY UPDATE.

Quick explanation.

For usage see the manual - specifically the conflict_action clause in the syntax diagram, and the explanatory text.

Unlike the solutions for 9.4 and older that are given below, this feature works with multiple conflicting rows and it doesn't require exclusive locking or a retry loop.

The commit adding the feature is here and the discussion around its development is here.


If you're on 9.5 and don't need to be backward-compatible you can stop reading now.


9.4 and older:

PostgreSQL doesn't have any built-in UPSERT (or MERGE) facility, and doing it efficiently in the face of concurrent use is very difficult.

This article discusses the problem in useful detail.

In general you must choose between two options:

  • Individual insert/update operations in a retry loop; or
  • Locking the table and doing batch merge

Individual row retry loop

Using individual row upserts in a retry loop is the reasonable option if you want many connections concurrently trying to perform inserts.

The PostgreSQL documentation contains a useful procedure that'll let you do this in a loop inside the database. It guards against lost updates and insert races, unlike most naive solutions. It will only work in READ COMMITTED mode and is only safe if it's the only thing you do in the transaction, though. The function won't work correctly if triggers or secondary unique keys cause unique violations.

This strategy is very inefficient. Whenever practical you should queue up work and do a bulk upsert as described below instead.

Many attempted solutions to this problem fail to consider rollbacks, so they result in incomplete updates. Two transactions race with each other; one of them successfully INSERTs; the other gets a duplicate key error and does an UPDATE instead. The UPDATE blocks waiting for the INSERT to rollback or commit. When it rolls back, the UPDATE condition re-check matches zero rows, so even though the UPDATE commits it hasn't actually done the upsert you expected. You have to check the result row counts and re-try where necessary.

Some attempted solutions also fail to consider SELECT races. If you try the obvious and simple:

-- THIS IS WRONG. DO NOT COPY IT. It's an EXAMPLE.

BEGIN;

UPDATE testtable
SET somedata = 'blah'
WHERE id = 2;

-- Remember, this is WRONG. Do NOT COPY IT.

INSERT INTO testtable (id, somedata)
SELECT 2, 'blah'
WHERE NOT EXISTS (SELECT 1 FROM testtable WHERE testtable.id = 2);

COMMIT;

then when two run at once there are several failure modes. One is the already discussed issue with an update re-check. Another is where both UPDATE at the same time, matching zero rows and continuing. Then they both do the EXISTS test, which happens before the INSERT. Both get zero rows, so both do the INSERT. One fails with a duplicate key error.

This is why you need a re-try loop. You might think that you can prevent duplicate key errors or lost updates with clever SQL, but you can't. You need to check row counts or handle duplicate key errors (depending on the chosen approach) and re-try.

Please don't roll your own solution for this. Like with message queuing, it's probably wrong.

Bulk upsert with lock

Sometimes you want to do a bulk upsert, where you have a new data set that you want to merge into an older existing data set. This is vastly more efficient than individual row upserts and should be preferred whenever practical.

In this case, you typically follow the following process:

  • CREATE a TEMPORARY table

  • COPY or bulk-insert the new data into the temp table

  • LOCK the target table IN EXCLUSIVE MODE. This permits other transactions to SELECT, but not make any changes to the table.

  • Do an UPDATE ... FROM of existing records using the values in the temp table;

  • Do an INSERT of rows that don't already exist in the target table;

  • COMMIT, releasing the lock.

For example, for the example given in the question, using multi-valued INSERT to populate the temp table:

BEGIN;

CREATE TEMPORARY TABLE newvals(id integer, somedata text);

INSERT INTO newvals(id, somedata) VALUES (2, 'Joe'), (3, 'Alan');

LOCK TABLE testtable IN EXCLUSIVE MODE;

UPDATE testtable
SET somedata = newvals.somedata
FROM newvals
WHERE newvals.id = testtable.id;

INSERT INTO testtable
SELECT newvals.id, newvals.somedata
FROM newvals
LEFT OUTER JOIN testtable ON (testtable.id = newvals.id)
WHERE testtable.id IS NULL;

COMMIT;

Related reading

What about MERGE?

SQL-standard MERGE actually has poorly defined concurrency semantics and is not suitable for upserting without locking a table first.

It's a really useful OLAP statement for data merging, but it's not actually a useful solution for concurrency-safe upsert. There's lots of advice to people using other DBMSes to use MERGE for upserts, but it's actually wrong.

Other DBs:

How do I generate a SALT in Java for Salted-Hash?

Here's my solution, i would love anyone's opinion on this, it's simple for beginners

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.util.Base64;
import java.util.Base64.Encoder;
import java.util.Scanner;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;

public class Cryptography {

    public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeySpecException {
        Encoder encoder = Base64.getUrlEncoder().withoutPadding();
        System.out.print("Password: ");
        String strPassword = new Scanner(System.in).nextLine();
        byte[] bSalt = Salt();
        String strSalt = encoder.encodeToString(bSalt); // Byte to String
        System.out.println("Salt: " + strSalt);
        System.out.println("String to be hashed: " + strPassword + strSalt);
        String strHash = encoder.encodeToString(Hash(strPassword, bSalt)); // Byte to String
        System.out.println("Hashed value (Password + Salt value): " + strHash);
    }

    private static byte[] Salt() {
        SecureRandom random = new SecureRandom();
        byte salt[] = new byte[6];
        random.nextBytes(salt);
        return salt;
    }

    private static byte[] Hash(String password, byte[] salt) throws NoSuchAlgorithmException, InvalidKeySpecException {
        KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 65536, 128);
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        byte[] hash = factory.generateSecret(spec).getEncoded();
        return hash;
    }

}

You can validate by just decoding the strSalt and using the same hash method:

public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeySpecException {
        Encoder encoder = Base64.getUrlEncoder().withoutPadding();
        Decoder decoder = Base64.getUrlDecoder();
        System.out.print("Password: ");
        String strPassword = new Scanner(System.in).nextLine();
        String strSalt = "Your Salt String Here";
        byte[] bSalt = decoder.decode(strSalt); // String to Byte
        System.out.println("Salt: " + strSalt);
        System.out.println("String to be hashed: " + strPassword + strSalt);
        String strHash = encoder.encodeToString(Hash(strPassword, bSalt)); // Byte to String
        System.out.println("Hashed value (Password + Salt value): " + strHash);
    }

Cross compile Go on OSX?

The process of creating executables for many platforms can be a little tedious, so I suggest to use a script:

#!/usr/bin/env bash

package=$1
if [[ -z "$package" ]]; then
  echo "usage: $0 <package-name>"
  exit 1
fi
package_name=$package

#the full list of the platforms: https://golang.org/doc/install/source#environment
platforms=(
"darwin/386"
"dragonfly/amd64"
"freebsd/386"
"freebsd/amd64"
"freebsd/arm"
"linux/386"
"linux/amd64"
"linux/arm"
"linux/arm64"
"netbsd/386"
"netbsd/amd64"
"netbsd/arm"
"openbsd/386"
"openbsd/amd64"
"openbsd/arm"
"plan9/386"
"plan9/amd64"
"solaris/amd64"
"windows/amd64"
"windows/386" )

for platform in "${platforms[@]}"
do
    platform_split=(${platform//\// })
    GOOS=${platform_split[0]}
    GOARCH=${platform_split[1]}
    output_name=$package_name'-'$GOOS'-'$GOARCH
    if [ $GOOS = "windows" ]; then
        output_name+='.exe'
    fi

    env GOOS=$GOOS GOARCH=$GOARCH go build -o $output_name $package
    if [ $? -ne 0 ]; then
        echo 'An error has occurred! Aborting the script execution...'
        exit 1
    fi
done

I checked this script on OSX only

gist - go-executable-build.sh

What 'additional configuration' is necessary to reference a .NET 2.0 mixed mode assembly in a .NET 4.0 project?

I was facing a similar issue while migrating some code from VS 2008 to VS 2010 Making changes to the App.config file resolved the issue for me.

<configuration>
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0.30319"
         sku=".NETFramework,Version=v4.0,Profile=Client" />
</startup>
</configuration>

Python Brute Force algorithm

If you really want a bruteforce algorithm, don't save any big list in the memory of your computer, unless you want a slow algorithm that crashes with a MemoryError.

You could try to use itertools.product like this :

from string import ascii_lowercase
from itertools import product

charset = ascii_lowercase  # abcdefghijklmnopqrstuvwxyz
maxrange = 10


def solve_password(password, maxrange):
    for i in range(maxrange+1):
        for attempt in product(charset, repeat=i):
            if ''.join(attempt) == password:
                return ''.join(attempt)


solved = solve_password('solve', maxrange)  # This worked for me in 2.51 sec

itertools.product(*iterables) returns the cartesian products of the iterables you entered.

[i for i in product('bar', (42,))] returns e.g. [('b', 42), ('a', 42), ('r', 42)]

The repeat parameter allows you to make exactly what you asked :

[i for i in product('abc', repeat=2)]

Returns

[('a', 'a'),
 ('a', 'b'),
 ('a', 'c'),
 ('b', 'a'),
 ('b', 'b'),
 ('b', 'c'),
 ('c', 'a'),
 ('c', 'b'),
 ('c', 'c')]

Note:

You wanted a brute-force algorithm so I gave it to you. Now, it is a very long method when the password starts to get bigger because it grows exponentially (it took 62 sec to find the word 'solved').

Background image jumps when address bar hides iOS/Android/Mobile Chrome

I ran into this issue as well when I was trying to create an entrance screen that would cover the whole viewport. Unfortunately, the accepted answer no longer works.

1) Elements with the height set to 100vh get resized every time the viewport size changes, including those cases when it is caused by (dis)appearing URL bar.

2) $(window).height() returns values also affected by the size of the URL bar.

One solution is to "freeze" the element using transition: height 999999s as suggested in the answer by AlexKempton. The disadvantage is that this effectively disables adaptation to all viewport size changes, including those caused by screen rotation.

So my solution is to manage viewport changes manually using JavaScript. That enables me to ignore the small changes that are likely to be caused by the URL bar and react only on the big ones.

function greedyJumbotron() {
    var HEIGHT_CHANGE_TOLERANCE = 100; // Approximately URL bar height in Chrome on tablet

    var jumbotron = $(this);
    var viewportHeight = $(window).height();

    $(window).resize(function () {
        if (Math.abs(viewportHeight - $(window).height()) > HEIGHT_CHANGE_TOLERANCE) {
            viewportHeight = $(window).height();
            update();
        }
    });

    function update() {
        jumbotron.css('height', viewportHeight + 'px');
    }

    update();
}

$('.greedy-jumbotron').each(greedyJumbotron);

EDIT: I actually use this technique together with height: 100vh. The page is rendered properly from the very beginning and then the javascript kicks in and starts managing the height manually. This way there is no flickering at all while the page is loading (or even afterwards).

declaring a priority_queue in c++ with a custom comparator

One can also use a lambda function.

auto Compare = [](Node &a, Node &b) { //compare };
std::priority_queue<Node, std::vector<Node>, decltype(Compare)> openset(Compare);

How to get current route in react-router 2.0.0-rc5

In App.js add the below code and try

window.location.pathname

Application Error - The connection to the server was unsuccessful. (file:///android_asset/www/index.html)

Another reason this error might occur is: there is no index.html in .../YourApp/www/ !

I just followed the ionic guide, and one of the steps is:

$ rm www/index.html

On iOS this is no problem as during the build the compiler takes some default HTML instead. However, when building for android, NO example index.html is used. Took me sometime to find out ("WHY does it work on iOS, but not on android...?)

Easy solution: create a index.html, save it under .../YourApp/www, rebuild ...et voila!

How to change href attribute using JavaScript after opening the link in a new window?

You can delay your code using setTimeout to execute after click

function changeLink(){
    setTimeout(function() {
        var link = document.getElementById("mylink");
        link.setAttribute('href', "http://facebook.com");
        document.getElementById("mylink").innerHTML = "facebook";
    }, 100);
}

Rails: Check output of path helper from console

In the Rails console, the variable app holds a session object on which you can call path and URL helpers as instance methods.

app.users_path