Programs & Examples On #P2

p2 is the platform provisioning system used by the eclipse IDE and the eclipse RCP framework. It is an artifact and metadata repository and allows some kind of dependency resolution. it supports mirroring and has an extensive set of ant task for managing repositories and publishing artifacts. The eclipse IDE uses p2 to provision updates and install new plugins.

My eclipse won't open, i download the bundle pack it keeps saying error log

Make sure you have the prerequisite, a JVM (http://wiki.eclipse.org/Eclipse/Installation#Install_a_JVM) installed.

This will be a JRE and JDK package.

There are a number of sources which includes: http://www.oracle.com/technetwork/java/javase/downloads/index.html.

What's the net::ERR_HTTP2_PROTOCOL_ERROR about?

My team saw this on a single javascript file we were serving up. Every other file worked fine. We switched from http2 back to http1.1 and then either net::ERR_INCOMPLETE_CHUNKED_ENCODING or ERR_CONTENT_LENGTH_MISMATCH. We ultimately discovered that there was a corporate filter (Trustwave) that was erroneously detecting an "infoleak" (we suspect it detected something in our file/filename that resembled a social security number). Getting corporate to tweak this filter resolved our issues.

HTTP Error 500.30 - ANCM In-Process Start Failure

In ASP.NET Core 2.2, a new Server/ hosting pattern was released with IIS called IIS InProcess hosting. To enable inprocess hosting, the csproj element AspNetCoreHostingModel is added to set the hostingModel to inprocess in the web.config file. Also, the web.config points to a new module called AspNetCoreModuleV2 which is required for inprocess hosting.

If the target machine you are deploying to doesn't have ANCMV2, you can't use IIS InProcess hosting. If so, the right behavior is to either install the dotnet hosting bundle to the target machine or downgrade to the AspNetCoreModule.

Source: jkotalik (Github)

Try changing the section in csproj (edit with a text editor)

  <PropertyGroup>
    <TargetFramework>netcoreapp2.2</TargetFramework>
    <AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
  </PropertyGroup>

to the following ...

 <PropertyGroup>
    <TargetFramework>netcoreapp2.2</TargetFramework>
    <AspNetCoreHostingModel>OutOfProcess</AspNetCoreHostingModel>
    <AspNetCoreModuleName>AspNetCoreModule</AspNetCoreModuleName>
 </PropertyGroup>

Source (Github)

What is the Record type in typescript?

  1. Can someone give a simple definition of what Record is?

A Record<K, T> is an object type whose property keys are K and whose property values are T. That is, keyof Record<K, T> is equivalent to K, and Record<K, T>[K] is (basically) equivalent to T.

  1. Is Record<K,T> merely a way of saying "all properties on this object will have type T"? Probably not all objects, since K has some purpose...

As you note, K has a purpose... to limit the property keys to particular values. If you want to accept all possible string-valued keys, you could do something like Record<string, T>, but the idiomatic way of doing that is to use an index signature like { [k: string]: T }.

  1. Does the K generic forbid additional keys on the object that are not K, or does it allow them and just indicate that their properties are not transformed to T?

It doesn't exactly "forbid" additional keys: after all, a value is generally allowed to have properties not explicitly mentioned in its type... but it wouldn't recognize that such properties exist:

declare const x: Record<"a", string>;
x.b; // error, Property 'b' does not exist on type 'Record<"a", string>'

and it would treat them as excess properties which are sometimes rejected:

declare function acceptR(x: Record<"a", string>): void;
acceptR({a: "hey", b: "you"}); // error, Object literal may only specify known properties

and sometimes accepted:

const y = {a: "hey", b: "you"};
acceptR(y); // okay
  1. With the given example:

    type ThreeStringProps = Record<'prop1' | 'prop2' | 'prop3', string>
    

    Is it exactly the same as this?:

    type ThreeStringProps = {prop1: string, prop2: string, prop3: string}
    

Yes!

Hope that helps. Good luck!

Is ConfigurationManager.AppSettings available in .NET Core 2.0?

You can use Configuration to resolve this.

Ex (Startup.cs):

You can pass by DI to the controllers after this implementation.

public class Startup
{
    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

        Configuration = builder.Build();

    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {

        var microserviceName = Configuration["microserviceName"];

       services.AddSingleton(Configuration);

       ...
    }

I get "Http failure response for (unknown url): 0 Unknown Error" instead of actual error message in Angular

If you are using .NET Core application, this solution might help!

Moreover this might not be an Angular or other request error in your front end application

First, you have to add the Microsoft CORS Nuget package:

Install-Package Microsoft.AspNetCore.Cors

You then need to add the CORS services in your startup.cs. In your ConfigureServices method you should have something similar to the following:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors();
}

Next, add the CORS middleware to your app. In your startup.cs you should have a Configure method. You need to have it similar to this:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, 
ILoggerFactory loggerFactory)
{
    app.UseCors( options => 
    options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
    app.UseMvc();
}

The options lambda is a fluent API so you can add/remove any extra options you need. You can actually use the option “AllowAnyOrigin” to accept any domain, but I highly recommend you do not do this as it opens up cross origin calls from anyone. You can also limit cross origin calls to their HTTP Method (GET/PUT/POST etc), so you can only expose GET calls cross domain etc.

React: Expected an assignment or function call and instead saw an expression

Possible way is (sure you can change array declaration to getting from db or another external resource):

const MyPosts = () => {

  let postsRawData = [
    { id: 1, text: 'Post 1', likesCount: '1' },
    { id: 2, text: 'Post 2', likesCount: '231' },
    { id: 3, text: 'Post 3', likesCount: '547' }
  ];

  const postsItems = []
  for (const [key, value] of postsRawData.entries()) {
    postsItems.push(<Post text={value.text} likesCount={value.likesCount} />)
  }

  return (
      <div className={css.posts}>Posts:
          {postsItems}
      </div>
  )
}

React navigation goBack() and update parent state

With React Navigation v5, just use the navigate method. From the docs:

To achieve this, you can use the navigate method, which acts like goBack if the screen already exists. You can pass the params with navigate to pass the data back

Full example:

import React from 'react';
import { StyleSheet, Button, Text, View } from 'react-native';

import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';

const Stack = createStackNavigator();

function ScreenA ({ navigation, route }) {
  const { params } = route;

  return (
    <View style={styles.container}>
      <Text>Params: {JSON.stringify(params)}</Text>
      <Button title='Go to B' onPress={() => navigation.navigate('B')} />
    </View>
  );
}

function ScreenB ({ navigation }) {
  return (
    <View style={styles.container}>
      <Button title='Go to A'
        onPress={() => {
          navigation.navigate('A', { data: 'Something' })
        }}
      />
    </View>
  );
}

export default function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator mode="modal">
        <Stack.Screen name="A" component={ScreenA} />
        <Stack.Screen name="B" component={ScreenB} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

How to integrate SAP Crystal Reports in Visual Studio 2017

So to sum up, this is what worked for me after upgrading my VB 2010 (CR18) to VB 2017:

  1. Uninstall all runtimes AND CRforVS.
  2. Reboot
  3. Install CRforVS SP23 (no runtimes needed on developer machine).
  4. Open project, remove old DLL references.
  5. Add new references (DLL files that you need from C:\Program Files (x86)\SAP BusinessObjects\Crystal Reports for .NET Framework 4.0\Common\SAP BusinessObjects Enterprise XI 4.0\win32_x86\dotnet)
  6. Rebuild All.
  7. Have fun.

Angular2 module has no exported member

In my module i am exporting classes this way:

export { SigninComponent } from './SigninComponent';
export { RegisterComponent } from './RegisterComponent';

This allow me to import multiple classes in file from same module:

import { SigninComponent, RegisterComponent} from "../auth.module";

PS: Of course @Fjut answer is correct, but same time it doesn't support multiple imports from same file. I would suggest to use both answers for your needs. But importing from module makes folder structure refactorings more easier.

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

On a rather unrelated note: more performance hacks!

  • [the first «conjecture» has been finally debunked by @ShreevatsaR; removed]

  • When traversing the sequence, we can only get 3 possible cases in the 2-neighborhood of the current element N (shown first):

    1. [even] [odd]
    2. [odd] [even]
    3. [even] [even]

    To leap past these 2 elements means to compute (N >> 1) + N + 1, ((N << 1) + N + 1) >> 1 and N >> 2, respectively.

    Let`s prove that for both cases (1) and (2) it is possible to use the first formula, (N >> 1) + N + 1.

    Case (1) is obvious. Case (2) implies (N & 1) == 1, so if we assume (without loss of generality) that N is 2-bit long and its bits are ba from most- to least-significant, then a = 1, and the following holds:

    (N << 1) + N + 1:     (N >> 1) + N + 1:
    
            b10                    b1
             b1                     b
           +  1                   + 1
           ----                   ---
           bBb0                   bBb
    

    where B = !b. Right-shifting the first result gives us exactly what we want.

    Q.E.D.: (N & 1) == 1 ? (N >> 1) + N + 1 == ((N << 1) + N + 1) >> 1.

    As proven, we can traverse the sequence 2 elements at a time, using a single ternary operation. Another 2× time reduction.

The resulting algorithm looks like this:

uint64_t sequence(uint64_t size, uint64_t *path) {
    uint64_t n, i, c, maxi = 0, maxc = 0;

    for (n = i = (size - 1) | 1; i > 2; n = i -= 2) {
        c = 2;
        while ((n = ((n & 3)? (n >> 1) + n + 1 : (n >> 2))) > 2)
            c += 2;
        if (n == 2)
            c++;
        if (c > maxc) {
            maxi = i;
            maxc = c;
        }
    }
    *path = maxc;
    return maxi;
}

int main() {
    uint64_t maxi, maxc;

    maxi = sequence(1000000, &maxc);
    printf("%llu, %llu\n", maxi, maxc);
    return 0;
}

Here we compare n > 2 because the process may stop at 2 instead of 1 if the total length of the sequence is odd.

[EDIT:]

Let`s translate this into assembly!

MOV RCX, 1000000;



DEC RCX;
AND RCX, -2;
XOR RAX, RAX;
MOV RBX, RAX;

@main:
  XOR RSI, RSI;
  LEA RDI, [RCX + 1];

  @loop:
    ADD RSI, 2;
    LEA RDX, [RDI + RDI*2 + 2];
    SHR RDX, 1;
    SHRD RDI, RDI, 2;    ror rdi,2   would do the same thing
    CMOVL RDI, RDX;      Note that SHRD leaves OF = undefined with count>1, and this doesn't work on all CPUs.
    CMOVS RDI, RDX;
    CMP RDI, 2;
  JA @loop;

  LEA RDX, [RSI + 1];
  CMOVE RSI, RDX;

  CMP RAX, RSI;
  CMOVB RAX, RSI;
  CMOVB RBX, RCX;

  SUB RCX, 2;
JA @main;



MOV RDI, RCX;
ADD RCX, 10;
PUSH RDI;
PUSH RCX;

@itoa:
  XOR RDX, RDX;
  DIV RCX;
  ADD RDX, '0';
  PUSH RDX;
  TEST RAX, RAX;
JNE @itoa;

  PUSH RCX;
  LEA RAX, [RBX + 1];
  TEST RBX, RBX;
  MOV RBX, RDI;
JNE @itoa;

POP RCX;
INC RDI;
MOV RDX, RDI;

@outp:
  MOV RSI, RSP;
  MOV RAX, RDI;
  SYSCALL;
  POP RAX;
  TEST RAX, RAX;
JNE @outp;

LEA RAX, [RDI + 59];
DEC RDI;
SYSCALL;

Use these commands to compile:

nasm -f elf64 file.asm
ld -o file file.o

See the C and an improved/bugfixed version of the asm by Peter Cordes on Godbolt. (editor's note: Sorry for putting my stuff in your answer, but my answer hit the 30k char limit from Godbolt links + text!)

How can I use/create dynamic template to compile dynamic Component with Angular 2.0?

2019 June answer

Great news! It seems that the @angular/cdk package now has first-class support for portals!

As of the time of writing, I didn't find the above official docs particularly helpful (particularly with regard to sending data into and receiving events from the dynamic components). In summary, you will need to:

Step 1) Update your AppModule

Import PortalModule from the @angular/cdk/portal package and register your dynamic component(s) inside entryComponents

@NgModule({
  declarations: [ ..., AppComponent, MyDynamicComponent, ... ]
  imports:      [ ..., PortalModule, ... ],
  entryComponents: [ ..., MyDynamicComponent, ... ]
})
export class AppModule { }

Step 2. Option A: If you do NOT need to pass data into and receive events from your dynamic components:

@Component({
  selector: 'my-app',
  template: `
    <button (click)="onClickAddChild()">Click to add child component</button>
    <ng-template [cdkPortalOutlet]="myPortal"></ng-template>
  `
})
export class AppComponent  {
  myPortal: ComponentPortal<any>;
  onClickAddChild() {
    this.myPortal = new ComponentPortal(MyDynamicComponent);
  }
}

@Component({
  selector: 'app-child',
  template: `<p>I am a child.</p>`
})
export class MyDynamicComponent{
}

See it in action

Step 2. Option B: If you DO need to pass data into and receive events from your dynamic components:

// A bit of boilerplate here. Recommend putting this function in a utils 
// file in order to keep your component code a little cleaner.
function createDomPortalHost(elRef: ElementRef, injector: Injector) {
  return new DomPortalHost(
    elRef.nativeElement,
    injector.get(ComponentFactoryResolver),
    injector.get(ApplicationRef),
    injector
  );
}

@Component({
  selector: 'my-app',
  template: `
    <button (click)="onClickAddChild()">Click to add random child component</button>
    <div #portalHost></div>
  `
})
export class AppComponent {

  portalHost: DomPortalHost;
  @ViewChild('portalHost') elRef: ElementRef;

  constructor(readonly injector: Injector) {
  }

  ngOnInit() {
    this.portalHost = createDomPortalHost(this.elRef, this.injector);
  }

  onClickAddChild() {
    const myPortal = new ComponentPortal(MyDynamicComponent);
    const componentRef = this.portalHost.attach(myPortal);
    setTimeout(() => componentRef.instance.myInput 
      = '> This is data passed from AppComponent <', 1000);
    // ... if we had an output called 'myOutput' in a child component, 
    // this is how we would receive events...
    // this.componentRef.instance.myOutput.subscribe(() => ...);
  }
}

@Component({
  selector: 'app-child',
  template: `<p>I am a child. <strong>{{myInput}}</strong></p>`
})
export class MyDynamicComponent {
  @Input() myInput = '';
}

See it in action

How to configure Spring Security to allow Swagger URL to be accessed without authentication

Some security config and you are ready with swagger open to all

For Swagger V2

@Configuration
@EnableWebSecurity
public class CabSecurityConfig extends WebSecurityConfigurerAdapter {


    private static final String[] AUTH_WHITELIST = {
            // -- swagger ui
            "/v2/api-docs", 
            "/swagger-resources/**", 
            "/configuration/ui",
            "/configuration/security", 
            "/swagger-ui.html",
            "/webjars/**"
    };

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        // ... here goes your custom security configuration
        http.authorizeRequests().
        antMatchers(AUTH_WHITELIST).permitAll(). // whitelist URL permitted
        antMatchers("/**").authenticated(); // others need auth
    }

}

For Swagger V3

@Configuration
@EnableWebSecurity
public class CabSecurityConfig extends WebSecurityConfigurerAdapter {


    private static final String[] AUTH_WHITELIST = {
            // -- swagger ui
            "/v2/api-docs",
            "/v3/api-docs",  
            "/swagger-resources/**", 
            "/swagger-ui/**",
             };

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        // ... here goes your custom security configuration
        http.authorizeRequests().
        antMatchers(AUTH_WHITELIST).permitAll(). // whitelist URL permitted
        antMatchers("/**").authenticated(); // others need auth
    }

}

How do I pass data to Angular routed components?

It is 2019 and many of the answers here would work, depending on what you want to do. If you want to pass in some internal state not visible in URL (params, query) you can use state since 7.2 (as I have learned just today :) ).

From the blog (credits Tomasz Kula) - you navigate to route....

...from ts: this.router.navigateByUrl('/details', { state: { hello: 'world' } });

...from HTML template: <a routerLink="/details" [state]="{ hello: 'world' }">Go</a>

And to pick it up in the target component:

constructor(public activatedRoute: ActivatedRoute) {}

  ngOnInit() {
    this.state$ = this.activatedRoute.paramMap
      .pipe(map(() => window.history.state))
  }

Late, but hope this helps someone with recent Angular.

extract column value based on another column pandas dataframe

Use df[df['B']==3]['A'].values if you just want item itself without the brackets

What's the fastest way of checking if a point is inside a polygon in python

Your test is good, but it measures only some specific situation: we have one polygon with many vertices, and long array of points to check them within polygon.

Moreover, I suppose that you're measuring not matplotlib-inside-polygon-method vs ray-method, but matplotlib-somehow-optimized-iteration vs simple-list-iteration

Let's make N independent comparisons (N pairs of point and polygon)?

# ... your code...
lenpoly = 100
polygon = [[np.sin(x)+0.5,np.cos(x)+0.5] for x in np.linspace(0,2*np.pi,lenpoly)[:-1]]

M = 10000
start_time = time()
# Ray tracing
for i in range(M):
    x,y = np.random.random(), np.random.random()
    inside1 = ray_tracing_method(x,y, polygon)
print "Ray Tracing Elapsed time: " + str(time()-start_time)

# Matplotlib mplPath
start_time = time()
for i in range(M):
    x,y = np.random.random(), np.random.random()
    inside2 = path.contains_points([[x,y]])
print "Matplotlib contains_points Elapsed time: " + str(time()-start_time)

Result:

Ray Tracing Elapsed time: 0.548588991165
Matplotlib contains_points Elapsed time: 0.103765010834

Matplotlib is still much better, but not 100 times better. Now let's try much simpler polygon...

lenpoly = 5
# ... same code

result:

Ray Tracing Elapsed time: 0.0727779865265
Matplotlib contains_points Elapsed time: 0.105288982391

ssh : Permission denied (publickey,gssapi-with-mic)

This can happen if you are missing the correct id_rsa key set up in authorized_keys for an AWS instance.

Exact error I got (this article came up when I googled the error):

[email protected]: Permission denied (publickey,gssapi-keyex,gssapi-with-mic).

Note: If you have many keys, you have to either specify the key on the ssh command line or else add it to you ssh-agent keys (see ssh-add -l). Only the first 6 keys from ssh-agent may work - the default sshd MaxAuthTries config value is 6.

How can I enable the MySQLi extension in PHP 7?

sudo phpenmod mysqli
sudo service apache2 restart

  • phpenmod moduleName enables a module to PHP 7 (restart Apache after that sudo service apache2 restart)
  • phpdismod moduleName disables a module to PHP 7 (restart Apache after that sudo service apache2 restart)
  • php -m lists the loaded modules

AttributeError: 'dict' object has no attribute 'predictors'

#Try without dot notation
sample_dict = {'name': 'John', 'age': 29}
print(sample_dict['name']) # John
print(sample_dict['age']) # 29

Change URL without refresh the page

When you use a function ...

<p onclick="update_url('/en/step2');">Link</p>

<script>
function update_url(url) {
    history.pushState(null, null, url);
}
</script>

Angular: conditional class with *ngClass

to extend MostafaMashayekhi his answer for option two> you can also chain multiple options with a ','

[ngClass]="{'my-class': step=='step1', 'my-class2':step=='step2' }"

Also *ngIf can be used in some of these situations usually combined with a *ngFor

class="mats p" *ngIf="mat=='painted'"

ES6 exporting/importing in index file

Too late but I want to share the way that I resolve it.

Having model file which has two named export:

export { Schema, Model };

and having controller file which has the default export:

export default Controller;

I exposed in the index file in this way:

import { Schema, Model } from './model';
import Controller from './controller';

export { Schema, Model, Controller };

and assuming that I want import all of them:

import { Schema, Model, Controller } from '../../path/';

Angular EXCEPTION: No provider for Http

because it was only in the comment section I repeat the answer from Eric:

I had to include HTTP_PROVIDERS

ImportError: No module named pandas

You're missing a few (not terribly clear) steps. Pandas is distributed through pip as a wheel, which means you need to do:

pip install wheel
pip install pandas

You're probably going to run into other issues after this - it looks like you're installing on Windows which isn't the most friendly of targets for numpy/scipy/pandas. Alternatively, you could pickup a binary installer from here.

You also had an error installing numpy. Like before, I recommend grabbing a binary installer for this, as it's not a simple process. However, you can resolve your current error by installing this package from Microsoft.

While it's completely possible to get a perfect environment setup on Windows, I have found the quality-of-life for a Python dev is vastly improved by setting up a debian VM. Especially with the scientific packages, you will run into many cases like this.

Bootstrap - 5 column layout

_x000D_
_x000D_
.col-xs-2{_x000D_
    background:#00f;_x000D_
    color:#FFF;_x000D_
}_x000D_
.col-half-offset{_x000D_
    margin-left:4.166666667%_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<div class="container">_x000D_
    <div class="row" style="border: 1px solid red">_x000D_
        <div class="col-xs-2" id="p1">One</div>_x000D_
        <div class="col-xs-2 col-half-offset" id="p2">Two</div>_x000D_
        <div class="col-xs-2 col-half-offset" id="p3">Three</div>_x000D_
        <div class="col-xs-2 col-half-offset" id="p4">Four</div>_x000D_
        <div class="col-xs-2 col-half-offset" id="p5">Five</div>_x000D_
        <div>lorem</div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

This should be ok.

Why should Java 8's Optional not be used in arguments

The pattern with Optional is for one to avoid returning null. It's still perfectly possible to pass in null to a method.

While these aren't really official yet, you can use JSR-308 style annotations to indicate whether or not you accept null values into the function. Note that you'd have to have the right tooling to actually identify it, and it'd provide more of a static check than an enforceable runtime policy, but it would help.

public int calculateSomething(@NotNull final String p1, @NotNull final String p2) {}

How to do a deep comparison between 2 objects with lodash?

I took a stab a Adam Boduch's code to output a deep diff - this is entirely untested but the pieces are there:

function diff (obj1, obj2, path) {
    obj1 = obj1 || {};
    obj2 = obj2 || {};

    return _.reduce(obj1, function(result, value, key) {
        var p = path ? path + '.' + key : key;
        if (_.isObject(value)) {
            var d = diff(value, obj2[key], p);
            return d.length ? result.concat(d) : result;
        }
        return _.isEqual(value, obj2[key]) ? result : result.concat(p);
    }, []);
}

diff({ foo: 'lol', bar: { baz: true }}, {}) // returns ["foo", "bar.baz"]

UnicodeEncodeError: 'ascii' codec can't encode character at special name

Try setting the system default encoding as utf-8 at the start of the script, so that all strings are encoded using that.

Example -

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

The above should set the default encoding as utf-8 .

SSH Key: “Permissions 0644 for 'id_rsa.pub' are too open.” on mac

In my case, it was a .pem file. Turns out holds good for that too. Changed permissions of the file and it worked.

chmod 400 ~/.ssh/dev-shared.pem

Thanks for all of those who helped above.

Remove first Item of the array (like popping from stack)

const a = [1, 2, 3]; // -> [2, 3]

// Mutable solutions: update array 'a', 'c' will contain the removed item
const c = a.shift(); // prefered mutable way
const [c] = a.splice(0, 1);

// Immutable solutions: create new array 'b' and leave array 'a' untouched
const b = a.slice(1); // prefered immutable way
const b = a.filter((_, i) => i > 0);
const [c, ...b] = a; // c: the removed item

Multiple radio button groups in one form

To create a group of inputs you can create a custom html element

window.customElements.define('radio-group', RadioGroup);

https://gist.github.com/robdodson/85deb2f821f9beb2ed1ce049f6a6ed47

to keep selected option in each group, you need to add name attribute to inputs in group, if you not add it then all is one group.

How to use class from other files in C# with visual studio?

According to your example here it seems that they both reside in the same namespace, i conclude that they are both part of the same project ( if you haven't created another project with the same namespace) and all class by default are defined as internal to the project they are defined in, if haven't declared otherwise, therefore i guess the problem is that your file is not included in your project. You can include it by right clicking the file in the solution explorer window => Include in project, if you cannot see the file inside the project files in the solution explorer then click the show the upper menu button of the solution explorer called show all files ( just hove your mouse cursor over the button there and you'll see the names of the buttons)

Just for basic knowledge: If the file resides in a different project\ assembly then it has to be defined, otherwise it has to be define at least as internal or public. in case your class is inheriting from that class that it can be protected as well.

is there a function in lodash to replace matched item

Not bad variant too)

var arr = [{id: 1, name: "Person 1"}, {id: 2, name: "Person 2"}];

var id = 1; //id to find

arr[_.find(arr, {id: id})].name = 'New Person';

Fatal error: Call to a member function bind_param() on boolean

This particular error has very little to do with the actual error. Here is my similar experience and the solution...

I had a table that I use in my statement with |database-name|.login composite name. I thought this wouldn't be a problem. It was the problem indeed. Enclosing it inside square brackets solved my problem ([|database-name|].[login]). So, the problem is MySQL preserved words (other way around)... make sure your columns too are not failing to this type of error scenario...

How to load local file in sc.textFile, instead of HDFS

Try explicitly specify sc.textFile("file:///path to the file/"). The error occurs when Hadoop environment is set.

SparkContext.textFile internally calls org.apache.hadoop.mapred.FileInputFormat.getSplits, which in turn uses org.apache.hadoop.fs.getDefaultUri if schema is absent. This method reads "fs.defaultFS" parameter of Hadoop conf. If you set HADOOP_CONF_DIR environment variable, the parameter is usually set as "hdfs://..."; otherwise "file://".

How to fix request failed on channel 0

This was happening when I was trying to use sudo on ssh -t [email protected] after adding my local user's public key to github

Just a head's up to the google happy people like me

Convert Pandas Column to DateTime

raw_data['Mycol'] =  pd.to_datetime(raw_data['Mycol'], format='%d%b%Y:%H:%M:%S.%f')

works, however it results in a Python warning of A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead

I would guess this is due to some chaining indexing.

Github permission denied: ssh add agent has no identities

I had this issue after restoring a hard drive from a backup.

My problem: I could check & see my remote (using git remote -v), but when I executed git push origin master, it returned : Permission denied (publickey). fatal: Could not read from remote repository.

I already had an SSH folder and SSH keys, and adding them via Terminal (ssh-add /path/to/my-ssh-folder/id_rsa) successfully added my identity, but I still couldn't push and still got the same error. Generating a new key was a bad idea for me, because it was tied to other very secure permissions on AWS.

It turned out the link between the key and my Github profile had broken.

Solution: Re-adding the key to Github in Profile > Settings > SSH and GPG keys resolved the issue.

Also: My account had 2-factor authentication set up. When this is the case, if Terminal requests credentials, use your username - but NOT your Github password. For 2-factor authentication, you need to use your authentication code (for me, this was generated by Authy on my phone, and I had to copy it into Terminal for the pw).

Spring Hibernate - Could not obtain transaction-synchronized Session for current thread

I added these configuration in web.xml and it works well for me!

<filter>
    <filter-name>OpenSessionInViewFilter</filter-name>
    <filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class>
    <init-param>
        <param-name>sessionFactoryBeanName</param-name>
        <param-value>sessionFactory</param-value>
    </init-param>
    <init-param>
        <param-name>flushMode</param-name>
        <param-value>AUTO</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>OpenSessionInViewFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Additionally, the most ranked answer give me clues to prevent application from panic at the first run.

How to turn off INFO logging in Spark?

I you want to keep using the logging (Logging facility for Python) you can try splitting configurations for your application and for Spark:

LoggerManager()
logger = logging.getLogger(__name__)
loggerSpark = logging.getLogger('py4j')
loggerSpark.setLevel('WARNING')

Comparing strings, c++

Regarding the question,

can someone explain why the compare() function exists if a comparison can be made using simple operands?

Relative to < and ==, the compare function is conceptually simpler and in practice it can be more efficient since it avoids two comparisons per item for ordinary ordering of items.


As an example of simplicity, for small integer values you can write a compare function like this:

auto compare( int a, int b ) -> int { return a - b; }

which is highly efficient.

Now for a structure

struct Foo
{
    int a;
    int b;
    int c;
};

auto compare( Foo const& x, Foo const& y )
    -> int
{
    if( int const r = compare( x.a, y.a ) ) { return r; }
    if( int const r = compare( x.b, y.b ) ) { return r; }
    return compare( x.c, y.c );
}

Trying to express this lexicographic compare directly in terms of < you wind up with horrendous complexity and inefficiency, relatively speaking.


With C++11, for the simplicity alone ordinary less-than comparison based lexicographic compare can be very simply implemented in terms of tuple comparison.

Command Prompt Error 'C:\Program' is not recognized as an internal or external command, operable program or batch file

try put cd before the file path

example:

C:\Users\user>cd C:\Program Files\MongoDB\Server\4.4\bin

ReactJS - Does render get called any time "setState" is called?

Not All Components.

the state in component looks like the source of the waterfall of state of the whole APP.

So the change happens from where the setState called. The tree of renders then get called from there. If you've used pure component, the render will be skipped.

Add external libraries to CMakeList.txt c++

I would start with upgrade of CMAKE version.

You can use INCLUDE_DIRECTORIES for header location and LINK_DIRECTORIES + TARGET_LINK_LIBRARIES for libraries

INCLUDE_DIRECTORIES(your/header/dir)
LINK_DIRECTORIES(your/library/dir)
rosbuild_add_executable(kinectueye src/kinect_ueye.cpp)
TARGET_LINK_LIBRARIES(kinectueye lib1 lib2 lib2 ...)

note that lib1 is expanded to liblib1.so (on Linux), so use ln to create appropriate links in case you do not have them

MySQL Select last 7 days

Since you are using an INNER JOIN you can just put the conditions in the WHERE clause, like this:

SELECT 
    p1.kArtikel, 
    p1.cName, 
    p1.cKurzBeschreibung, 
    p1.dLetzteAktualisierung, 
    p1.dErstellt, 
    p1.cSeo,
    p2.kartikelpict,
    p2.nNr,
    p2.cPfad  
FROM 
    tartikel AS p1 INNER JOIN tartikelpict AS p2 
    ON p1.kArtikel = p2.kArtikel
WHERE
  DATE(dErstellt) > (NOW() - INTERVAL 7 DAY)
  AND p2.nNr = 1
ORDER BY 
  p1.kArtikel DESC
LIMIT
    100;

'Syntax Error: invalid syntax' for no apparent reason

I noticed that invalid syntax error for no apparent reason can be caused by using space in:

print(f'{something something}')

Python IDLE seems to jump and highlight a part of the first line for some reason (even if the first line happens to be a comment), which is misleading.

python to arduino serial read & write

First you have to install a module call Serial. To do that go to the folder call Scripts which is located in python installed folder. If you are using Python 3 version it's normally located in location below,

C:\Python34\Scripts  

Once you open that folder right click on that folder with shift key. Then click on 'open command window here'. After that cmd will pop up. Write the below code in that cmd window,

pip install PySerial

and press enter.after that PySerial module will be installed. Remember to install the module u must have an INTERNET connection.


after successfully installed the module open python IDLE and write down the bellow code and run it.

import serial
# "COM11" is the port that your Arduino board is connected.set it to port that your are using        
ser = serial.Serial("COM11", 9600)
while True:
    cc=str(ser.readline())
    print(cc[2:][:-5])   

How to count the number of observations in R like Stata command count

The with function will let you use shorthand column references and sum will count TRUE results from the expression(s).

sum(with(aaa, sex==1 & group1==2))
## [1] 3

sum(with(aaa, sex==1 & group2=="A"))
## [1] 2

As @mnel pointed out, you can also do:

nrow(aaa[aaa$sex==1 & aaa$group1==2,])
## [1] 3

nrow(aaa[aaa$sex==1 & aaa$group2=="A",])
## [1] 2

The benefit of that is that you can do:

nrow(aaa)
## [1] 6

And, the behaviour matches Stata's count almost exactly (syntax notwithstanding).

Saving binary data as file using JavaScript from a browser

Use FileSaver.js. It supports Chrome, Edge, Firefox, and IE 10+ (and probably IE < 10 with a few "polyfills" - see Note 4). FileSaver.js implements the saveAs() FileSaver interface in browsers that do not natively support it:
     https://github.com/eligrey/FileSaver.js

Minified version is really small at < 2.5KB, gzipped < 1.2KB.

Usage:

/* TODO: replace the blob content with your byte[] */
var blob = new Blob([yourBinaryDataAsAnArrayOrAsAString], {type: "application/octet-stream"});
var fileName = "myFileName.myExtension";
saveAs(blob, fileName);

You might need Blob.js in some browsers (see Note 3). Blob.js implements the W3C Blob interface in browsers that do not natively support it. It is a cross-browser implementation:
     https://github.com/eligrey/Blob.js

Consider StreamSaver.js if you have files larger than blob's size limitations.

Complete example:

_x000D_
_x000D_
/* Two options_x000D_
 * 1. Get FileSaver.js from here_x000D_
 *     https://github.com/eligrey/FileSaver.js/blob/master/FileSaver.min.js -->_x000D_
 *     <script src="FileSaver.min.js" />_x000D_
 *_x000D_
 * Or_x000D_
 *_x000D_
 * 2. If you want to support only modern browsers like Chrome, Edge, Firefox, etc., _x000D_
 *    then a simple implementation of saveAs function can be:_x000D_
 */_x000D_
function saveAs(blob, fileName) {_x000D_
    var url = window.URL.createObjectURL(blob);_x000D_
_x000D_
    var anchorElem = document.createElement("a");_x000D_
    anchorElem.style = "display: none";_x000D_
    anchorElem.href = url;_x000D_
    anchorElem.download = fileName;_x000D_
_x000D_
    document.body.appendChild(anchorElem);_x000D_
    anchorElem.click();_x000D_
_x000D_
    document.body.removeChild(anchorElem);_x000D_
_x000D_
    // On Edge, revokeObjectURL should be called only after_x000D_
    // a.click() has completed, atleast on EdgeHTML 15.15048_x000D_
    setTimeout(function() {_x000D_
        window.URL.revokeObjectURL(url);_x000D_
    }, 1000);_x000D_
}_x000D_
_x000D_
(function() {_x000D_
    // convert base64 string to byte array_x000D_
    var byteCharacters = atob("R0lGODlhkwBYAPcAAAAAAAABGRMAAxUAFQAAJwAANAgwJSUAACQfDzIoFSMoLQIAQAAcQwAEYAAHfAARYwEQfhkPfxwXfQA9aigTezchdABBckAaAFwpAUIZflAre3pGHFpWVFBIf1ZbYWNcXGdnYnl3dAQXhwAXowkgigIllgIxnhkjhxktkRo4mwYzrC0Tgi4tiSQzpwBIkBJIsyxCmylQtDVivglSxBZu0SlYwS9vzDp94EcUg0wziWY0iFROlElcqkxrtW5OjWlKo31kmXp9hG9xrkty0ziG2jqQ42qek3CPqn6Qvk6I2FOZ41qn7mWNz2qZzGaV1nGOzHWY1Gqp3Wy93XOkx3W1x3i33G6z73nD+ZZIHL14KLB4N4FyWOsECesJFu0VCewUGvALCvACEfEcDfAcEusKJuoINuwYIuoXN+4jFPEjCvAgEPM3CfI5GfAxKuoRR+oaYustTus2cPRLE/NFJ/RMO/dfJ/VXNPVkNvFPTu5KcfdmQ/VuVvl5SPd4V/Nub4hVj49ol5RxoqZfl6x0mKp5q8Z+pu5NhuxXiu1YlvBdk/BZpu5pmvBsjfBilvR/jvF3lO5nq+1yre98ufBoqvBrtfB6p/B+uPF2yJiEc9aQMsSKQOibUvqKSPmEWPyfVfiQaOqkSfaqTfyhXvqwU+u7dfykZvqkdv+/bfy1fpGvvbiFnL+fjLGJqqekuYmTx4SqzJ2+2Yy36rGawrSwzpjG3YjB6ojG9YrU/5XI853U75bV/J3l/6PB6aDU76TZ+LHH6LHX7rDd+7Lh3KPl/bTo/bry/MGJm82VqsmkjtSptfWMj/KLsfu0je6vsNW1x/GIxPKXx/KX1ea8w/Wnx/Oo1/a3yPW42/S45fvFiv3IlP/anvzLp/fGu/3Xo/zZt//knP7iqP7qt//xpf/0uMTE3MPd1NXI3MXL5crS6cfe99fV6cXp/cj5/tbq+9j5/vbQy+bY5/bH6vbJ8vfV6ffY+f7px/3n2f/4yP742OPm8ef9//zp5vjn/f775/7+/gAAACwAAAAAkwBYAAAI/wD9CRxIsKDBgwgTKlzIsKHDhxAjSpxIsaLFixgzatzIsaPHjxD7YQrSyp09TCFSrQrxCqTLlzD9bUAAAMADfVkYwCIFoErMn0AvnlpAxR82A+tGWWgnLoCvoFCjOsxEopzRAUYwBFCQgEAvqWDDFgTVQJhRAVI2TUj3LUAusXDB4jsQxZ8WAMNCrW37NK7foN4u1HThD0sBWpoANPnL+GG/OV2gSUT24Yi/eltAcPAAooO+xqAVbkPT5VDo0zGzfemyqLE3a6hhmurSpRLjcGDI0ItdsROXSAn5dCGzTOC+d8j3gbzX5ky8g+BoTzq4706XL1/KzONdEBWXL3AS3v/5YubavU9fuKg/44jfQmbK4hdn+Jj2/ILRv0wv+MnLdezpweEed/i0YcYXkCQkB3h+tPEfgF3AsdtBzLSxGm1ftCHJQqhc54Y8B9UzxheJ8NfFgWakSF6EA57WTDN9kPdFJS+2ONAaKq6Whx88enFgeAYx892FJ66GyEHvvGggeMs0M01B9ajRRYkD1WMgF60JpAx5ZEgGWjZ44MHFdSkeSBsceIAoED5gqFgGbAMxQx4XlxjESRdcnFENcmmcGBlBfuDh4Ikq0kYGHoxUKSWVApmCnRsFCddlaEPSVuaFED7pDz5F5nGQJ9cJWFA/d1hSUCfYlSFQfdgRaqal6UH/epmUjRDUx3VHEtTPHp5SOuYyn5x4xiMv3jEmlgKNI+w1B/WTxhdnwLnQY2ZwEY1AeqgHRzN0/PiiMmh8x8Vu9YjRxX4CjYcgdwhhE6qNn8DBrD/5AXnQeF3ct1Ap1/VakB3YbThQgXEIVG4X1w7UyXUFs2tnvwq5+0XDBy38RZYMKQuejf7Yw4YZXVCjEHwFyQmyyA4TBPAXhiiUDcMJzfaFvwXdgWYbz/jTjxjgTTiQN2qYQca8DxV44KQpC7SyIi7DjJCcExeET7YAplcGNQvC8RxB3qS6XUTacHEgF7mmvHTTUT+Nnb06Ozi2emOWYeEZRAvUdXZfR/SJ2AdS/8zuymUf9HLaFGLnt3DkPTIQqTLSXRDQ2W0tETbYHSgru3eyjLbfJa9dpYEIG6QHdo4T5LHQdUfUjduas9vhxglJzLaJhKtGOEHdhKrm4gB3YapFdlznHLvhiB1tQtqEmpDFFL9umkH3hNGzQTF+8YZjzGi6uBgg58yuHH0nFM67CIH/xfP+OH9Q9LAXRHn3Du1NhuQCgY80dyZ/4caee58xocYSOgg+uOe7gWzDcwaRWMsOQocVLQI5bOBCggzSDzx8wQsTFEg4RnQ8h1nnVdchA8rucZ02+Iwg4xOaly4DOu8tbg4HogRC6uGfVx3oege5FbQ0VQ8Yts9hnxiUpf9qtapntYF+AxFFqE54qwPlYR772Mc2xpAiLqSOIPiwIG3OJC0ooQFAOVrNFbnTj/jEJ3U4MgPK/oUdmumMDUWCm6u6wDGDbMOMylhINli3IjO4MGkLqcMX7rc4B1nRIPboXdVUdLmNvExFGAMkQxZGHAHmYYXQ4xGPogGO1QBHkn/ZhhfIsDuL3IMLbjghKDECj3O40pWrjIk6XvkZj9hDCEKggAh26QAR9IAJsfzILXkpghj0RSPOYAEJdikCEjjTmczURTA3cgxmQlMEJbBFRlixAms+85vL3KUVpomRQOwSnMtUwTos8g4WnBOd8BTBCNxBzooA4p3oFAENKLL/Dx/g85neRCcEblDPifjzm/+UJz0jkgx35tMBSWDFCZqZTxWwo6AQYQVFwzkFh17zChG550YBKoJx9iMHIwVoCY6J0YVUk6K7TII/UEpSJRQNpSkNZy1WRdN8lgAXLWXIOyYKUIv2o5sklWlD7EHUfIrApsbxKDixqc2gJqQfOBipA4qwqRVMdQgNaWdOw2kD00kVodm0akL+MNJdfuYdbRWBUhVy1LGmc6ECEWs8S0AMtR4kGfjcJREEAliEPnUh9uipU1nqD8COVQQqwKtfBWIPXSJUBcEQCFsNO06F3BOe4ZzrQDQKWhHMYLIFEURKRVCDz5w0rlVFiEbtCtla/xLks/B0wBImAo98iJSZIrDBRTPSjqECd5c7hUgzElpSyjb1msNF0j+nCtJRaeCxIoiuQ2YhhF4el5cquIg9kJAD735Xt47RwWqzS9iEhjch/qTtaQ0C18fO1yHvQAFzmflTiwBiohv97n0bstzV3pcQCR0sQlQxXZLGliDVjGdzwxrfADvgBULo60WSEQHm8uAJE8EHUqfaWX8clKSMHViDAfoC2xJksxWVbEKSMWKSOgGvhOCBjlO8kPgi1AEqAMbifqDjsjLkpVNVZ15rvMwWI4SttBXBLQR41muWWCFQnuoLhquOCoNXxggRa1yVuo9Z6PK4okVklZdpZH8YY//MYWZykhFS4Io2JMsIjQE97cED814TstpFkgSY29lk4DTAMZ1xTncJVX+oF60aNgiMS8vVg4h0qiJ4MEJ8jNAX0FPMpR2wQaRRZUYLZBArDueVCXJdn0rzMgmttEHwYddr8riy603zQfBM0uE6o5u0dcCqB/IOyxq2zeasNWTBvNx4OtkfSL4mmE9d6yZPm8EVdfFBZovpRm/qzBJ+tq7WvEvtclvCw540QvepsxOH09u6UqxTdd3V1UZ2IY7FdAy0/drSrtQg7ibpsJsd6oLoNZ+vdsY7d9nmUT/XqcP2RyGYy+NxL9oB1TX4isVZkHxredq4zec8CXJuhI5guCH/L3dCLu3vYtD3rCpfCKoXPQJFl7bh/TC2YendbuwOg9WPZXd9ba2QgNtZ0ohWQaQTYo81L5PdzZI3QBse4XyS4NV/bfAusQ7X0ioVxrvUdEHsIeepQn0gdQ6nqBOCagmLneRah3rTH6sCbeuq7LvMeNUxPU69hn0hBAft0w0ycxEAORYI2YcrWJoBuq8zIdLQeps9PtWG73rRUh6I0aHZ3wqrAKiArzYJ0FsQbjjAASWIRTtkywIH3Hfo+RQ3ksjd5pCDU9gyx/zPN+V0EZiAGM3o5YVXP5Bk1OAgbxa8M3EfEXNUgJltnnk8bWB3i+dztzprfGkzTmfMDzftH8fH/w9igHWBBF8EuzBI8pUvAu43JNnLL7G6EWp5Na8X9GQXvAjKf5DAF3Ug0fZxCPFaIrB7BOF/8fR2COFYMFV3q7IDtFV/Y1dqniYQ3KBs/GcQhXV72OcPtpdn1eeBzBRo/tB1ysd8C+EMELhwIqBg/rAPUjd1IZhXMBdcaKdsCjgQbWdYx7R50KRn28ZM71UQ+6B9+gdvFMRp16RklOV01qYQARhOWLd3AoWEBfFoJCVuPrhM+6aB52SDllZt+pQQswAE3jVVpPeAUZaBBGF0pkUQJuhsCgF714R4mkdbTDhavRROoGcQUThVJQBmrLADZ4hpQzgQ87duCUGH4fRgIuOmfyXAhgLBctDkgHfob+UHf00Wgv1WWpDFC+qADuZwaNiVhwCYarvEY1gFZwURg9fUhV4YV0vnD+bkiS+ADurACoW4dQoBfk71XcFmA9NWD6mWTozVD+oVYBAge9SmfyIgAwbhDINmWEhIeZh2XNckgQVBicrHfrvkBFgmhsW0UC+FaMxIg8qGTZ3FD0r4bgfBVKKnbzM4EP1UjN64Sz1AgmOHU854eoUYTg4gjIqGirx0eoGFTVbYjN0IUMs4bc1yXfFoWIZHA/ngEGRnjxImVwwxWxFpWCPgclfVagtpeC9AfKIPwY3eGAM94JCehZGGFQOzuIj8uJDLhHrgKFRlh2k8xxCz8HwBFU4FaQOzwJIMQQ5mCFzXaHg28AsRUWbA9pNA2UtQ8HgNAQ8QuV6HdxHvkALudFwpAAMtEJMWMQgsAAPAyJVgxU47AANdCVwlAJaSuJEsAGDMBJYGiBH94Ap6uZdEiRGysJd7OY8S8Q6AqZe8kBHOUJiCiVqM2ZiO+ZgxERAAOw==");_x000D_
    var byteNumbers = new Array(byteCharacters.length);_x000D_
    for (var i = 0; i < byteCharacters.length; i++) {_x000D_
        byteNumbers[i] = byteCharacters.charCodeAt(i);_x000D_
    }_x000D_
    var byteArray = new Uint8Array(byteNumbers);_x000D_
    _x000D_
    // now that we have the byte array, construct the blob from it_x000D_
    var blob1 = new Blob([byteArray], {type: "application/octet-stream"});_x000D_
_x000D_
    var fileName1 = "cool.gif";_x000D_
    saveAs(blob1, fileName1);_x000D_
_x000D_
    // saving text file_x000D_
    var blob2 = new Blob(["cool"], {type: "text/plain"});_x000D_
    var fileName2 = "cool.txt";_x000D_
    saveAs(blob2, fileName2);_x000D_
})();
_x000D_
_x000D_
_x000D_


Tested on Chrome, Edge, Firefox, and IE 11 (use FileSaver.js for supporting IE 11).
You can also save from a canvas element. See https://github.com/eligrey/FileSaver.js#saving-a-canvas.

Demos: https://eligrey.com/demos/FileSaver.js/

Blog post by author of FileSaver.js: http://eligrey.com/blog/post/saving-generated-files-on-the-client-side

Note 1: Browser support: https://github.com/eligrey/FileSaver.js#supported-browsers

Note 2: Failed to execute 'atob' on 'Window'

Note 3: Polyfill for browsers not supporting Blob: https://github.com/eligrey/Blob.js
                See http://caniuse.com/#search=blob

Note 4: IE < 10 support (I've not tested this part):
                https://github.com/eligrey/FileSaver.js#ie--10
                https://github.com/eligrey/FileSaver.js/issues/56#issuecomment-30917476

Downloadify is a Flash-based polyfill for supporting IE6-9: https://github.com/dcneiner/downloadify (I don't recommend Flash-based solutions in general, though.)
Demo using Downloadify and FileSaver.js for supporting IE6-9 also: http://sheetjs.com/demos/table.html

Note 5: Creating a BLOB from a Base64 string in JavaScript

Note 6: FileSaver.js examples: https://github.com/eligrey/FileSaver.js#examples

How to merge two json string in Python?

As of Python 3.5, you can merge two dicts with:

merged = {**dictA, **dictB}

(https://www.python.org/dev/peps/pep-0448/)

So:

jsonMerged = {**json.loads(jsonStringA), **json.loads(jsonStringB)}
asString = json.dumps(jsonMerged)

etc.

mysqldump & gzip commands to properly create a compressed file of a MySQL database using crontab

Personally, I have create a file.sh (right 755) in the root directory, file who do this job, on order of the crontab.

Crontab code:

10 2 * * * root /root/backupautomatique.sh

File.sh code:

rm -f /home/mordb-148-251-89-66.sql.gz #(To erase the old one)

mysqldump mor | gzip > /home/mordb-148-251-89-66.sql.gz (what you have done)

scp -P2222 /home/mordb-148-251-89-66.sql.gz root@otherip:/home/mordbexternes/mordb-148-251-89-66.sql.gz

(to send a copy somewhere else if the sending server crashes, because too old, like me ;-))

How to download a file from my server using SSH (using PuTTY on Windows)

try this scp -r -P2222 [email protected]:/home2/kwazy/www/utrecht-connected.nl /Desktop

Another easier option if you're going to be pulling files left and right is to just use an SFTP client like WinSCP. Then you're not typing out 100 characters every time you want to pull something, just drag and drop.

Edit: Just noticed /Desktop probably isn't where you're looking to download the file to. Should be something like C:\Users\you\Desktop

Failed to install Python Cryptography package with PIP and setup.py

For those of you running OS X, here is what worked for me:

brew install openssl
env ARCHFLAGS="-arch x86_64" LDFLAGS="-L/usr/local/opt/openssl/lib" CFLAGS="-I/usr/local/opt/openssl/include"
pip install cryptography

(Running 10.9 Mavericks)

You may also want to try merging the flags and pip commands to the following per the comment below:

brew install openssl
env ARCHFLAGS="-arch x86_64" LDFLAGS="-L/usr/local/opt/openssl/lib" CFLAGS="-I/usr/local/opt/openssl/include" pip install cryptography

Sonar properties files

You can define a Multi-module project structure, then you can set the configuration for sonar in one properties file in the root folder of your project, (Way #1)

json: cannot unmarshal object into Go value of type

Here's a fixed version of it: http://play.golang.org/p/w2ZcOzGHKR

The biggest fix that was needed is when Unmarshalling an array, that property needs to be an array/slice in the struct as well.

For example:

{ "things": ["a", "b", "c"] }

Would Unmarshal into a:

type Item struct {
    Things []string
}

And not into:

type Item struct {
    Things string
}

The other thing to watch out for when Unmarshaling is that the types line up exactly. It will fail when Unmarshalling a JSON string representation of a number into an int or float field -- "1" needs to Unmarshal into a string, not into an int like we saw with ShippingAdditionalCost int

Why am I getting an Exception with the message "Invalid setup on a non-virtual (overridable in VB) member..."?

You'll get this error as well if you are verifying that an extension method of an interface is called.

For example if you are mocking:

var mockValidator = new Mock<IValidator<Foo>>();
mockValidator
  .Verify(validator => validator.ValidateAndThrow(foo, null));

You will get the same exception because .ValidateAndThrow() is an extension on the IValidator<T> interface.

public static void ValidateAndThrow<T>(this IValidator<T> validator, T instance, string ruleSet = null)...

Find max and second max salary for a employee table MySQL

I think, It is the simplest way to find MAX and second MAX Salary.You may try this way.

SELECT MAX(Salary) FROM Employee; -- For Maximum Salary.

SELECT MAX(Salary) FROM Employee WHERE Salary < (SELECT MAX(Salary) FROM Employee); -- For Second Maximum Salary

Can we locate a user via user's phone number in Android?

Quick answer: No, at least not with native SMS service.

Long answer: Sure, but the receiver's phone should have the correct setup first. An app that detects incoming sms, and if a keyword matches, reports its current location to your server, which then pushes that info to the sender.

"application blocked by security settings" prevent applets running using oracle SE 7 update 51 on firefox on Linux mint

I had this issue. The security settings in the ControlPanel seem to be user specific. Try running it as the user you are actually running your browser as (you are not browsing as root!??) and setting the security level to Medium there. - For me, that did it.

Insert node at a certain position in a linked list C++

Try this function.

structure of node object:

class Node
{
private:
    int data;
    Node *next;

public:
    Node(int);
    ~Node();
    void setData(int);
    int getData();
    void setNext(Node*);
    Node* getNext();
};

Implementation of the function:

Returning a status value is always a god practice, constants defined here are meant for debugging/logging the application usage.

//constants
static int const SUCCESS = 0;
static int const FAILURE = 1;
static int const NULL_OBJ = 2;
static int const POS_EXCEED = 3;

int addAt(int data, int pos){
    Node *tmp = new Node(data);
    if (tmp == NULL){
        //print for debugging only.
        cout << "Object not created. Out of memory maybe" << endl;
        return NULL_OBJ;
    }
    if (pos == 0){
        // add at beginning
        tmp->setNext(this->head);
        this->head = tmp;
        return SUCCESS;
    }else{
        // add element in between or at end
        int counter = 1;
        Node* currentNode = this->head;
        while (counter < pos && currentNode->getNext() != NULL){
            currentNode= currentNode->getNext();
            counter++;
       }
       tmp->setNext(currentNode->getNext());
       currentNode->setNext(tmp);
       return SUCCESS;
   }
   cout << "Failed due to unknown reason.";
   return FAILURE;
}

Assumption here is that, you will call the function after validating the inputs (data and position). Though we can validate the parameters inside the function, it is not a good practice.

Hope this helps.

How to list AD group membership for AD users using input list?

Or add "sort name" to list alphabetically

Get-ADPrincipalGroupMembership username | select name | sort name

Difference in make_shared and normal shared_ptr in C++

I think the exception safety part of mr mpark's answer is still a valid concern. when creating a shared_ptr like this: shared_ptr< T >(new T), the new T may succeed, while the shared_ptr's allocation of control block may fail. in this scenario, the newly allocated T will leak, since the shared_ptr has no way of knowing that it was created in-place and it is safe to delete it. or am I missing something? I don't think the stricter rules on function parameter evaluation help in any way here...

Visual Studio 6 Windows Common Controls 6.0 (sp6) Windows 7, 64 bit

Just today I had the (questionable) pleasure to get VB6 code running on Windows / 64 Bit. I did come across this thread, but none of the proposed solutions worked for me. Neither worked adding references using the "Project -> References..." menu.

To get it running, I had to manually modify the VB6 project file (*.vbp). For all the libraries I had load issue with I had to use the following notation to define as reference: Object={Registry Key}#Version#0; LIBRARY.OCX Example: Object={FAEEE763-117E-101B-8933-08002B2F4F5A}#1.1#0; DBLIST32.OCX

I had not to register any of the libraries (using regsvr32), these were all already correctly registered. I guess why my solution works is that if the "object={[...]" notation is used (instead of the "Reference=*\G{[...]" notation) VB Studio is using the Registry Key only and gets rooted to C:\Windows\SysWOW64 while as the other way ends up looking in C:\Windows\System32

By the way, IE11 is installed. Whether or not this matters, only Bill G might know. My guess is that my solution works regardless which IE is installed. You just might have to unregister and register the missing libraries as mentioned in this thread.

Hope that helps anyone who faces similar issues.

Update Top 1 record in table sql server

WITH UpdateList_view AS (
  SELECT TOP 1  * from TX_Master_PCBA 
  WHERE SERIAL_NO IN ('0500030309') 
  ORDER BY TIMESTAMP2 DESC 
)

update UpdateList_view 
set TIMESTAMP2 = '2013-12-12 15:40:31.593'

How do I change Bootstrap 3 column order on mobile layout?

Starting with the mobile version first, you can achieve what you want, most of the time.

Examples here:

http://jsbin.com/wulexiq/edit?html,css,output

<div class="container">
      <h1>PUSH - PULL Bootstrap demo</h1>
    <h2>Version 1:</h2>

    <div class="row">

      <div class="col-xs-12 col-sm-5 col-sm-push-3 green">
        IN MIDDLE ON SMALL/MEDIUM/LARGE SCREEN
        <hr> TOP ROW XS-SMALL SCREEN
      </div>

      <div class="col-xs-12 col-sm-4 col-sm-push-3 gold">
        TO THE RIGHT ON SMALL/MEDIUM/LARGE SCREEN
        <hr> MIDDLE ROW ON XS-SMALL
      </div>

      <div class="col-xs-12 col-sm-3 col-sm-pull-9 red">
        TO THE LEFT ON SMALL/MEDIUM/LARGE SCREEN
        <hr> BOTTOM ROW ON XS-SMALL
      </div>

    </div>

    <h2>Version 2:</h2>

    <div class="row">

      <div class="col-xs-12 col-sm-4 col-sm-push-8 yellow">
        TO THE RIGHT ON SMALL/MEDIUM/LARGE SCREEN
        <hr> TOP ROW ON XS-SMALL
      </div>

      <div class="col-xs-12 col-sm-4 col-sm-pull-4 blue">
        TO THE LEFT ON SMALL/MEDIUM/LARGE SCREEN
        <hr> MIDDLE ROW XS-SMALL SCREEN
      </div>

      <div class="col-xs-12 col-sm-4 col-sm-pull-4 pink">
        IN MIDDLE ON SMALL/MEDIUM/LARGE SCREEN
        <hr> BOTTOM ROW ON XS-SMALL
      </div>

    </div>

    <h2>Version 3:</h2>

    <div class="row">

      <div class="col-xs-12 col-sm-5 cyan">
        TO THE LEFT ON SMALL/MEDIUM/LARGE SCREEN TOP ROW ON XS-SMALL
      </div>

      <div class="col-xs-12 col-sm-3 col-sm-push-4 orange">
        TO THE RIGHT ON SMALL/MEDIUM/LARGE SCREEN
        <hr> MIDDLE ROW ON XS-SMALL
      </div>

      <div class="col-xs-12 col-sm-4 col-sm-pull-3 brown">
        IN THE MIDDLE ON SMALL/MEDIUM/LARGE SCREEN
        <hr> BOTTOM ROW XS-SMALL SCREEN
      </div>

    </div>

    <h2>Version 4:</h2>
    <div class="row">

      <div class="col-xs-12 col-sm-4 col-sm-push-8 darkblue">
        TO THE RIGHT ON SMALL/MEDIUM/LARGE SCREEN
        <hr> TOP ROW XS-SMALL SCREEN
      </div>

      <div class="col-xs-12 col-sm-4 beige">
        MIDDLE ON SMALL/MEDIUM/LARGE SCREEN
        <hr> MIDDLE ROW ON XS-SMALL
      </div>

      <div class="col-xs-12 col-sm-4 col-sm-pull-8 silver">
        TO THE LEFT ON SMALL/MEDIUM/LARGE SCREEN
        <hr> BOTTOM ROW ON XS-SMALL
      </div>

    </div>

  </div>

Aesthetics must either be length one, or the same length as the dataProblems

The problem is that skew isn't being subsetted in colour=factor(skew), so it's the wrong length. Since subset(skew, product == 'p1') is the same as subset(skew, product == 'p3'), in this case it doesn't matter which subset is used. So you can solve your problem with:

p1 <- ggplot(df, aes(x=subset(price, product=='p1'),
                     y=subset(price, product=='p3'),
                     colour=factor(subset(skew, product == 'p1')))) +
              geom_point(size=2, shape=19)

Note that most R users would write this as the more concise:

p1 <- ggplot(df, aes(x=price[product=='p1'],
                     y=price[product=='p3'],
                     colour=factor(skew[product == 'p1']))) +
              geom_point(size=2, shape=19)

How can I parse a local JSON file from assets folder into a ListView?

Source code How to fetch Local Json from Assets folder

https://drive.google.com/open?id=1NG1amTVWPNViim_caBr8eeB4zczTDK2p

    {
        "responseCode": "200",
        "responseMessage": "Recode Fetch Successfully!",
        "responseTime": "10:22",
        "employeesList": [
            {
                "empId": "1",
                "empName": "Keshav",
                "empFatherName": "Mr Ramesh Chand Gera",
                "empSalary": "9654267338",
                "empDesignation": "Sr. Java Developer",
                "leaveBalance": "3",
                "pfBalance": "60,000",
                "pfAccountNo.": "12345678"
            },
            {
                "empId": "2",
                "empName": "Ram",
                "empFatherName": "Mr Dasrath ji",
                "empSalary": "9999999999",
                "empDesignation": "Sr. Java Developer",
                "leaveBalance": "3",
                "pfBalance": "60,000",
                "pfAccountNo.": "12345678"
            },
            {
                "empId": "3",
                "empName": "Manisha",
                "empFatherName": "Mr Ramesh Chand Gera",
                "empSalary": "8826420999",
                "empDesignation": "BusinessMan",
                "leaveBalance": "3",
                "pfBalance": "60,000",
                "pfAccountNo.": "12345678"
            },
            {
                "empId": "4",
                "empName": "Happy",
                "empFatherName": "Mr Ramesh Chand Gera",
                "empSalary": "9582401701",
                "empDesignation": "Two Wheeler",
                "leaveBalance": "3",
                "pfBalance": "60,000",
                "pfAccountNo.": "12345678"
            },
            {
                "empId": "5",
                "empName": "Ritu",
                "empFatherName": "Mr Keshav Gera",
                "empSalary": "8888888888",
                "empDesignation": "Sararat Vibhag",
                "leaveBalance": "3",
                "pfBalance": "60,000",
                "pfAccountNo.": "12345678"
            }
        ]
    }


 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_employee);


        emp_recycler_view = (RecyclerView) findViewById(R.id.emp_recycler_view);

        emp_recycler_view.setLayoutManager(new LinearLayoutManager(EmployeeActivity.this, 
        LinearLayoutManager.VERTICAL, false));
        emp_recycler_view.setItemAnimator(new DefaultItemAnimator());

        employeeAdapter = new EmployeeAdapter(EmployeeActivity.this , employeeModelArrayList);

        emp_recycler_view.setAdapter(employeeAdapter);

        getJsonFileFromLocally();
    }



    public String loadJSONFromAsset() {
        String json = null;
        try {
            InputStream is = EmployeeActivity.this.getAssets().open("employees.json");       //TODO Json File  name from assets folder
            int size = is.available();
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            json = new String(buffer, "UTF-8");
        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        return json;
    }

    private void getJsonFileFromLocally() {
        try {

            JSONObject jsonObject = new JSONObject(loadJSONFromAsset());
            String responseCode = jsonObject.getString("responseCode");
            String responseMessage = jsonObject.getString("responseMessage");
            String responseTime = jsonObject.getString("responseTime");

            Log.e("keshav", "responseCode -->" + responseCode);
            Log.e("keshav", "responseMessage -->" + responseMessage);
            Log.e("keshav", "responseTime -->" + responseTime);


            if(responseCode.equals("200")){

            }else{
                Toast.makeText(this, "No Receord Found ", Toast.LENGTH_SHORT).show();
            }

            JSONArray jsonArray = jsonObject.getJSONArray("employeesList");                  //TODO pass array object name
            Log.e("keshav", "m_jArry -->" + jsonArray.length());


            for (int i = 0; i < jsonArray.length(); i++)
            {
                EmployeeModel employeeModel = new EmployeeModel();

                JSONObject jsonObjectEmployee = jsonArray.getJSONObject(i);


                String empId = jsonObjectEmployee.getString("empId");
                String empName = jsonObjectEmployee.getString("empName");
                String empDesignation = jsonObjectEmployee.getString("empDesignation");
                String empSalary = jsonObjectEmployee.getString("empSalary");
                String empFatherName = jsonObjectEmployee.getString("empFatherName");

                employeeModel.setEmpId(""+empId);
                employeeModel.setEmpName(""+empName);
                employeeModel.setEmpDesignation(""+empDesignation);
                employeeModel.setEmpSalary(""+empSalary);
                employeeModel.setEmpFatherNamer(""+empFatherName);

                employeeModelArrayList.add(employeeModel);

            }       // for

            if(employeeModelArrayList!=null) {
                employeeAdapter.dataChanged(employeeModelArrayList);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

Is it possible to use global variables in Rust?

You can use static variables fairly easily as long as they are thread-local.

The downside is that the object will not be visible to other threads your program might spawn. The upside is that unlike truly global state, it is entirely safe and is not a pain to use - true global state is a massive pain in any language. Here's an example:

extern mod sqlite;

use std::cell::RefCell;

thread_local!(static ODB: RefCell<sqlite::database::Database> = RefCell::new(sqlite::open("test.db"));

fn main() {
    ODB.with(|odb_cell| {
        let odb = odb_cell.borrow_mut();
        // code that uses odb goes here
    });
}

Here we create a thread-local static variable and then use it in a function. Note that it is static and immutable; this means that the address at which it resides is immutable, but thanks to RefCell the value itself will be mutable.

Unlike regular static, in thread-local!(static ...) you can create pretty much arbitrary objects, including those that require heap allocations for initialization such as Vec, HashMap and others.

If you cannot initialize the value right away, e.g. it depends on user input, you may also have to throw Option in there, in which case accessing it gets a bit unwieldy:

extern mod sqlite;

use std::cell::RefCell;

thread_local!(static ODB: RefCell<Option<sqlite::database::Database>> = RefCell::New(None));

fn main() {
    ODB.with(|odb_cell| {
        // assumes the value has already been initialized, panics otherwise
        let odb = odb_cell.borrow_mut().as_mut().unwrap();
        // code that uses odb goes here
    });
}

How to get host name with port from a http or https request

Seems like you need to strip the URL from the URL, so you can do it in a following way:

request.getRequestURL().toString().replace(request.getRequestURI(), "")

Angular - Can't make ng-repeat orderBy work

orderby works on arrays that contain objects with immidiate values which can be used as filters, ie

controller.images = [{favs:1,name:"something"},{favs:0,name:"something else"}];

When the above array is repeated, you may use | orderBy:'favs' to refer to that value immidiately, or use a minus in front to order descending

<div class="timeline-image" ng-repeat="image in controller.images | orderBy:'-favs'">
    <img ng-src="{{ images.name }}"/>
</div>

Unable to compile class for JSP: The type java.util.Map$Entry cannot be resolved. It is indirectly referenced from required .class files

The class format of JDK8 has changed and thats the reason why Tomcat is not able to compile JSPs. Try to get a newer version of Tomcat.

I recently had the same problem. This is a bug in Tomcat, or rather, JDK 8 has a slightly different class file format than what prior-JDK8 versions had. This causes inconsistency and Tomcat is not able to compile JSPs in JDK8.

See following references:

Import-Module : The specified module 'activedirectory' was not loaded because no valid module file was found in any module directory

On Windows 10 - This happened for me after the latest update in 2020.

What solved this issue for me was running the following in PowerShell

C:\>Install-Module -Name MicrosoftPowerBIMgmt

SSL Error When installing rubygems, Unable to pull data from 'https://rubygems.org/

For Fedora users

Update the cert.pem to newest file that provide by cURL: http://curl.haxx.se/ca/cacert.pem

curl -o `ruby -ropenssl -e 'p OpenSSL::X509::DEFAULT_CERT_FILE' |tr -d \"` http://curl.haxx.se/ca/cacert.pem

How to find difference between two columns data?

IF the table is alias t

SELECT t.Present , t.previous, t.previous- t.Present AS Difference
FROM   temp1 as t

Adding a legend to PyPlot in Matplotlib in the simplest manner possible

Here's an example to help you out ...

fig = plt.figure(figsize=(10,5))
ax = fig.add_subplot(111)
ax.set_title('ADR vs Rating (CS:GO)')
ax.scatter(x=data[:,0],y=data[:,1],label='Data')
plt.plot(data[:,0], m*data[:,0] + b,color='red',label='Our Fitting 
Line')
ax.set_xlabel('ADR')
ax.set_ylabel('Rating')
ax.legend(loc='best')
plt.show()

enter image description here

cannot load such file -- bundler/setup (LoadError)

You can try to run:

bundle exec rake rails:update:bin

As @Dinesh mentioned in Rails 5:

rails app:update:bin

How to limit the number of selected checkboxes?

$('.checkbox').click(function(){
  if ($('.checkbox:checked').length >= 3) {
    $(".checkbox").not(":checked").attr("disabled",true);
  }
  else 
    $(".checkbox").not(":checked").removeAttr('disabled');
});

i used this.

WebRTC vs Websockets: If WebRTC can do Video, Audio, and Data, why do I need Websockets?

Comparing websocket and webrtc is unfair.

Websocket is based on top of TCP. Packet's boundary can be detected from header information of a websocket packet unlike tcp.

Typically, webrtc makes use of websocket. The signalling for webrtc is not defined, it is upto the service provider what kind of signalling he wants to use. It may be SIP, HTTP, JSON or any text / binary message.

The signalling messages can be send / received using websocket.

Syntax error "syntax error, unexpected end-of-input, expecting keyword_end (SyntaxError)"

Do you perhaps have one too many here?

 describe "when name is too long" do
     before { @user.name = "a" * 51 }
     it { should_not be_valid }
 end
 end

Arduino error: does not name a type?

Usually Header file syntax start with capital letter.I found that code written all in smaller letter

#ifndef DIAG_H
#define DIAG_H

#endif

AngularJS Multiple ng-app within a page

I have modified your jsfiddle, can make top most module as rootModule for rest of the modules. Below Modifications updated on your jsfiddle.

  1. Second Module can injected in RootModule.
  2. In Html second defined ng-app placed inside the Root ng-app.

Updated JsFiddle: http://jsfiddle.net/ep2sQ/1011/

Apache is downloading php files instead of displaying them

After struggling a lot I finally solved the problem.

If you are prompted to download a .php file instead of executing it, then here is the perfect solution: I assume that you have installed PHP5 already and still getting this error.

$ sudo su
$ a2enmod php5

This is it.

But If you are still getting the error :

Config file php5.conf not properly enabled: /etc/apache2/mods-enabled/php5.conf is a real file, not touching it

then do the following:

Turns out files shouldn't be stored in mods-enabled, but should rather be stored in mods-available. A symlink should then be created in mods-enabled pointing to the file stored in mods-available.

First remove the original:

$ mv /etc/apache2/mods-enabled/php5.conf /etc/apache2/mods-available/

Then create the symbolic link:

$ ln -s /etc/apache2/mods-available/php5.conf /etc/apache2/mods-enabled/php5.conf

I hope your problem is solved.

Subset and ggplot2

Your formulation is almost correct. You want:

subset(dat, ID=="P1" | ID=="P3") 

Where the | ('pipe') means 'or'. Your solution, ID=="P1 & P3", is looking for a case where ID is literally "P1 & P3"

Grouped bar plot in ggplot

First you need to get the counts for each category, i.e. how many Bads and Goods and so on are there for each group (Food, Music, People). This would be done like so:

raw <- read.csv("http://pastebin.com/raw.php?i=L8cEKcxS",sep=",")
raw[,2]<-factor(raw[,2],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,3]<-factor(raw[,3],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,4]<-factor(raw[,4],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)

raw=raw[,c(2,3,4)] # getting rid of the "people" variable as I see no use for it

freq=table(col(raw), as.matrix(raw)) # get the counts of each factor level

Then you need to create a data frame out of it, melt it and plot it:

Names=c("Food","Music","People")     # create list of names
data=data.frame(cbind(freq),Names)   # combine them into a data frame
data=data[,c(5,3,1,2,4)]             # sort columns

# melt the data frame for plotting
data.m <- melt(data, id.vars='Names')

# plot everything
ggplot(data.m, aes(Names, value)) +   
  geom_bar(aes(fill = variable), position = "dodge", stat="identity")

Is this what you're after?

enter image description here

To clarify a little bit, in ggplot multiple grouping bar you had a data frame that looked like this:

> head(df)
  ID Type Annee X1PCE X2PCE X3PCE X4PCE X5PCE X6PCE
1  1    A  1980   450   338   154    36    13     9
2  2    A  2000   288   407   212    54    16    23
3  3    A  2020   196   434   246    68    19    36
4  4    B  1980   111   326   441    90    21    11
5  5    B  2000    63   298   443   133    42    21
6  6    B  2020    36   257   462   162    55    30

Since you have numerical values in columns 4-9, which would later be plotted on the y axis, this can be easily transformed with reshape and plotted.

For our current data set, we needed something similar, so we used freq=table(col(raw), as.matrix(raw)) to get this:

> data
   Names Very.Bad Bad Good Very.Good
1   Food        7   6    5         2
2  Music        5   5    7         3
3 People        6   3    7         4

Just imagine you have Very.Bad, Bad, Good and so on instead of X1PCE, X2PCE, X3PCE. See the similarity? But we needed to create such structure first. Hence the freq=table(col(raw), as.matrix(raw)).

SQL Server Case Statement when IS NULL

CASE WHEN B.[STAT] IS NULL THEN (C.[EVENT DATE]+10)   -- Type DATETIME
     ELSE '-'                                         -- Type VARCHAR
     END AS [DATE]

You need to select one type or the other for the field, the field type can't vary by row. The simplest is to remove the ELSE '-' and let it implicitly get the value NULL instead for the second case.

phpinfo() is not working on my CentOS server

Be sure that the tag "php" is stick in the code like this:

?php phpinfo(); ?>

Not like this:

? php phpinfo(); ?>

OR the server will treat it as a (normal word), so the server will not understand the language you are writing to deal with it so it will be blank.

I know it's a silly error ...but it happened ^_^

Procedure or function !!! has too many arguments specified

Use the following command before defining them:

cmd.Parameters.Clear()

How to parse XML to R data frame

Use xpath more directly for both performance and clarity.

time_path <- "//start-valid-time"
temp_path <- "//temperature[@type='hourly']/value"

df <- data.frame(
    latitude=data[["number(//point/@latitude)"]],
    longitude=data[["number(//point/@longitude)"]],
    start_valid_time=sapply(data[time_path], xmlValue),
    hourly_temperature=as.integer(sapply(data[temp_path], as, "integer"))

leading to

> head(df, 2)
  latitude longitude          start_valid_time hourly_temperature
1    29.81    -82.42 2014-02-14T18:00:00-05:00                 60
2    29.81    -82.42 2014-02-14T19:00:00-05:00                 55

Spring MVC: Complex object as GET @RequestParam

Since the question on how to set fields mandatory pops up under each post, I wrote a small example on how to set fields as required:

public class ExampleDTO {
    @NotNull
    private String mandatoryParam;

    private String optionalParam;
    
    @DateTimeFormat(iso = ISO.DATE) //accept Dates only in YYYY-MM-DD
    @NotNull
    private LocalDate testDate;

    public String getMandatoryParam() {
        return mandatoryParam;
    }
    public void setMandatoryParam(String mandatoryParam) {
        this.mandatoryParam = mandatoryParam;
    }
    public String getOptionalParam() {
        return optionalParam;
    }
    public void setOptionalParam(String optionalParam) {
        this.optionalParam = optionalParam;
    }
    public LocalDate getTestDate() {
        return testDate;
    }
    public void setTestDate(LocalDate testDate) {
        this.testDate = testDate;
    }
}

//Add this to your rest controller class
@RequestMapping(value = "/test", method = RequestMethod.GET)
public String testComplexObject (@Valid ExampleDTO e){
    System.out.println(e.getMandatoryParam() + " " + e.getTestDate());
    return "Does this work?";
}

Excel VBA Code: Compile Error in x64 Version ('PtrSafe' attribute required)

I'm quite sure you won't get this 32Bit DLL working in Office 64Bit. The DLL needs to be updated by the author to be compatible with 64Bit versions of Office.

The code changes you have found and supplied in the question are used to convert calls to APIs that have already been rewritten for Office 64Bit. (Most Windows APIs have been updated.)

From: http://technet.microsoft.com/en-us/library/ee681792.aspx:

"ActiveX controls and add-in (COM) DLLs (dynamic link libraries) that were written for 32-bit Office will not work in a 64-bit process."

Edit: Further to your comment, I've tried the 64Bit DLL version on Win 8 64Bit with Office 2010 64Bit. Since you are using User Defined Functions called from the Excel worksheet you are not able to see the error thrown by Excel and just end up with the #VALUE returned.

If we create a custom procedure within VBA and try one of the DLL functions we see the exact error thrown. I tried a simple function of swe_day_of_week which just has a time as an input and I get the error Run-time error '48' File not found: swedll32.dll.

Now I have the 64Bit DLL you supplied in the correct locations so it should be found which suggests it has dependencies which cannot be located as per https://stackoverflow.com/a/8607250/1733206

I've got all the .NET frameworks installed which would be my first guess, so without further information from the author it might be difficult to find the problem.

Edit2: And after a bit more investigating it appears the 64Bit version you have supplied is actually a 32Bit version. Hence the error message on the 64Bit Office. You can check this by trying to access the '64Bit' version in Office 32Bit.

Linq: GroupBy, Sum and Count

I don't understand where the first "result with sample data" is coming from, but the problem in the console app is that you're using SelectMany to look at each item in each group.

I think you just want:

List<ResultLine> result = Lines
    .GroupBy(l => l.ProductCode)
    .Select(cl => new ResultLine
            {
                ProductName = cl.First().Name,
                Quantity = cl.Count().ToString(),
                Price = cl.Sum(c => c.Price).ToString(),
            }).ToList();

The use of First() here to get the product name assumes that every product with the same product code has the same product name. As noted in comments, you could group by product name as well as product code, which will give the same results if the name is always the same for any given code, but apparently generates better SQL in EF.

I'd also suggest that you should change the Quantity and Price properties to be int and decimal types respectively - why use a string property for data which is clearly not textual?

How to clear exisiting dropdownlist items when its content changes?

Please use the following

ddlCity.Items.Clear();

Parse JSON file using GSON

One thing that to be remembered while solving such problems is that in JSON file, a { indicates a JSONObject and a [ indicates JSONArray. If one could manage them properly, it would be very easy to accomplish the task of parsing the JSON file. The above code was really very helpful for me and I hope this content adds some meaning to the above code.

The Gson JsonReader documentation explains how to handle parsing of JsonObjects and JsonArrays:

  • Within array handling methods, first call beginArray() to consume the array's opening bracket. Then create a while loop that accumulates values, terminating when hasNext() is false. Finally, read the array's closing bracket by calling endArray().
  • Within object handling methods, first call beginObject() to consume the object's opening brace. Then create a while loop that assigns values to local variables based on their name. This loop should terminate when hasNext() is false. Finally, read the object's closing brace by calling endObject().

Creating a Shopping Cart using only HTML/JavaScript

For a project this size, you should stop writing pure JavaScript and turn to some of the libraries available. I'd recommend jQuery (http://jquery.com/), which allows you to select elements by css-selectors, which I recon should speed up your development quite a bit.

Example of your code then becomes;

function AddtoCart() {
  var len = $("#Items tr").length, $row, $inp1, $inp2, $cells;

  $row = $("#Items td:first").clone(true);
  $cells = $row.find("td");

  $cells.get(0).html( len );

  $inp1 = $cells.get(1).find("input:first");
  $inp1.attr("id", $inp1.attr("id") + len).val("");

  $inp2 = $cells.get(2).find("input:first");
  $inp2.attr("id", $inp2.attr("id") + len).val("");

  $("#Items").append($row);
    }

I can see that you might not understand that code yet, but take a look at jQuery, it's easy to learn and will make this development way faster.

I would use the libraries already created specifically for js shopping carts if I were you though.

To your problem; If i look at your jsFiddle, it doesn't even seem like you have defined a table with the id Items? Maybe that's why it doesn't work?

TERM environment variable not set

You can see if it's really not set. Run the command set | grep TERM.

If not, you can set it like that: export TERM=xterm

Selenium WebDriver How to Resolve Stale Element Reference Exception?

In Selenium 3, you can use ExpectedConditions.refreshed(your condition).

It will handle the StaleElementReferenceException and retry the condition.

Get the index of the object inside an array, matching a condition

var CarId = 23;

//x.VehicleId property to match in the object array
var carIndex = CarsList.map(function (x) { return x.VehicleId; }).indexOf(CarId);

And for basic array numbers you can also do this:

var numberList = [100,200,300,400,500];
var index = numberList.indexOf(200); // 1

You will get -1 if it cannot find a value in the array.

Limiting Powershell Get-ChildItem by File Creation Date Range

Use Where-Object and test the $_.CreationTime:

Get-ChildItem 'PATH' -recurse -include @("*.tif*","*.jp2","*.pdf") | 
    Where-Object { $_.CreationTime -ge "03/01/2013" -and $_.CreationTime -le "03/31/2013" }

Declare and initialize a Dictionary in Typescript

Typescript fails in your case because it expects all the fields to be present. Use Record and Partial utility types to solve it.

Record<string, Partial<IPerson>>

interface IPerson {
   firstName: string;
   lastName: string;
}

var persons: Record<string, Partial<IPerson>> = {
   "p1": { firstName: "F1", lastName: "L1" },
   "p2": { firstName: "F2" }
};

Explanation.

  1. Record type creates a dictionary/hashmap.
  2. Partial type says some of the fields may be missing.

Alternate.

If you wish to make last name optional you can append a ? Typescript will know that it's optional.

lastName?: string;

https://www.typescriptlang.org/docs/handbook/utility-types.html

jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class

Typically when you see this message, it is benign. If it says

INFO: validateJarFile(/<webapp>/WEB-INF/lib/servlet-api-2.5.jar) - jar not loaded. 
See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class

It means it is ignoring your servlet-api-2.5.jar because tomcat already has a built-in version of that jar, so it isn't going to be using yours. Typically this doesn't cause an issue.

If however it says WEB-INF/lib/my_jar.jar - jar not loaded...Offending class: javax/servlet/Servlet.class

then what you can do (in my instance, it's a shaded jar) is run

$ mvn dependency:tree

and discover that you have a transitive dependency on "something" that depends on a jar that is either servlet-api or something like it (ex: tomcat-servlet-api-9.0.0). So add an exclusion to that to your pom, ex: (in my case, tomcat, in your case, probably the ones mentioned in the other answers):

 <dependency>
    ...
    <exclusions>
      <exclusion>
        <groupId>org.apache.tomcat</groupId>
        <artifactId>tomcat-servlet</artifactId>
      </exclusion>
    </exclusions> 
</dependency>

How to make Java 6, which fails SSL connection with "SSL peer shut down incorrectly", succeed like Java 7?

update the server arguments from -Dhttps.protocols=SSLv3 to -Dhttps.protocols=TLSv1,SSLv3

Select 50 items from list at random to write to file

If the list is in random order, you can just take the first 50.

Otherwise, use

import random
random.sample(the_list, 50)

random.sample help text:

sample(self, population, k) method of random.Random instance
    Chooses k unique random elements from a population sequence.

    Returns a new list containing elements from the population while
    leaving the original population unchanged.  The resulting list is
    in selection order so that all sub-slices will also be valid random
    samples.  This allows raffle winners (the sample) to be partitioned
    into grand prize and second place winners (the subslices).

    Members of the population need not be hashable or unique.  If the
    population contains repeats, then each occurrence is a possible
    selection in the sample.

    To choose a sample in a range of integers, use xrange as an argument.
    This is especially fast and space efficient for sampling from a
    large population:   sample(xrange(10000000), 60)

Eclipse will not start and I haven't changed anything

If you deleted all data in .metadata directory. There is a quick way to import all your projects again. Try this:

File --> Import --> General: Select Existing projects into workspace --> Select root directory: Browse to old workspace folder (the SAME with the current workspace folder is OK) --> Finish.

wait process until all subprocess finish?

A Popen object has a .wait() method exactly defined for this: to wait for the completion of a given subprocess (and, besides, for retuning its exit status).

If you use this method, you'll prevent that the process zombies are lying around for too long.

(Alternatively, you can use subprocess.call() or subprocess.check_call() for calling and waiting. If you don't need IO with the process, that might be enough. But probably this is not an option, because your if the two subprocesses seem to be supposed to run in parallel, which they won't with (check_)call().)

If you have several subprocesses to wait for, you can do

exit_codes = [p.wait() for p in p1, p2]

which returns as soon as all subprocesses have finished. You then have a list of return codes which you maybe can evaluate.

Non-Static method cannot be referenced from a static context with methods and variables

You should place Scanner input = new Scanner (System.in); into the main method rather than creating the input object outside.

Can't access Eclipse marketplace

Considering this as a general programming problem, some possible causes are:

  • The service could be temporarily broken

  • You could have a problem with a firewall. These could be local or they could be implemented by your ISPs.

  • Your proxy HTTP settings (if you need one) could be incorrect. This Answer explains how to adjust the Eclipse-internal proxy settings ... if that is where the problem lies.

  • It is possible that your access may be blocked by over-active antivirus software.

  • The service could have blacklisted some net range and your hosts IP address is "collateral damage".

Try connecting to that URL with a web browser to try to see if it is just Eclipse that is affected ... or a broader problem.


Considering this in the context of the Eclipse Marketplace service, first address any local proxy / firewall / AV issues, if they apply. If that doesn't help, the best thing that you can do is to be patient.

  • It has been observed that the Eclipse Marketplace service does sometimes go down. It doesn't happen often, and when it does happen the problem does get fixed relatively quickly. (Hours, not days ...)

  • I can't find a "service status" page or feed or similar for the Eclipse services. (If you know of one, please add it as a comment below.)

  • There may be an "outage" notice on the Eclipse front page. Check for that.

  • Try to connect to the service URL (refer to the exception message!) using a web browser and/or from other locations. If you succeed, the real problem may be a networking issue at your end.

  • If you feel the need to complain about Eclipse's services, please don't do it here!! (It is off topic.)

Convert Python dictionary to JSON array

One possible solution that I use is to use python3. It seems to solve many utf issues.

Sorry for the late answer, but it may help people in the future.

For example,

#!/usr/bin/env python3
import json
# your code follows

Svn switch from trunk to branch

You don't need to --relocate since the branch is within the same repository URL. Just do:

svn switch https://www.example.com/svn/branches/v1p2p3

Turning off some legends in a ggplot

You can simply add show.legend=FALSE to geom to suppress the corresponding legend

How to add java plugin for Firefox on Linux?

you should add plug in to your local setting of firefox in your user home

 vladimir@shinsengumi ~/.mozilla/plugins $ pwd
 /home/vladimir/.mozilla/plugins 
 vladimir@shinsengumi ~/.mozilla/plugins $ ls -ltr
 lrwxrwxrwx 1 vladimir vladimir 60 Jan  1 23:06 libnpjp2.so -> /home/vladimir/Install/jdk1.6.0_32/jre/lib/amd64/libnpjp2.so

How to remove outliers in boxplot in R?

See ?boxplot for all the help you need.

 outline: if ‘outline’ is not true, the outliers are not drawn (as
          points whereas S+ uses lines).

boxplot(x,horizontal=TRUE,axes=FALSE,outline=FALSE)

And for extending the range of the whiskers and suppressing the outliers inside this range:

   range: this determines how far the plot whiskers extend out from the
          box.  If ‘range’ is positive, the whiskers extend to the most
          extreme data point which is no more than ‘range’ times the
          interquartile range from the box. A value of zero causes the
          whiskers to extend to the data extremes.

# change the value of range to change the whisker length
boxplot(x,horizontal=TRUE,axes=FALSE,range=2)

TypeScript and field initializers

To init a class without redeclaring all the properties for defaults:

class MyClass{ 
  prop1!: string  //required to be passed in
  prop2!: string  //required to be passed in
  prop3 = 'some default'
  prop4 = 123

  constructor(opts:{prop1:string, prop2:string} & Partial<MyClass>){
    Object.assign(this,opts)
  }
}

This combines some of the already excellent answers

\n or \n in php echo not print

\n must be in double quotes!

echo "hello\nworld";

Output

hello
world

A nice way around this is to use PHP as a more of a templating language

<p>
    Hello <span><?php echo $world ?></span>
</p>

Output

<p>
    Hello <span>Planet Earth</span>
</p>

Notice, all newlines are kept in tact!

Unable instantiate android.gms.maps.MapFragment

Add Google Play Services to Your Project

To make the Google Play services APIs available to your app:

follow the steps present in this link : http://developer.android.com/google/play-services/setup.html#Setup

Datatables warning(table id = 'example'): cannot reinitialise data table

This problem occurs if we initialize dataTable more than once.Then we have to remove the previous.

On the other hand we can destroy the old datatable in this way also before creating the new datatable use the following code :

$(“#example”).dataTable().fnDestroy();

There is an another scenario ,say you send more than one ajax request which response will access same table in same template then we will get error also.In this case fnDestroy method doesn’t work properly because you don’t know which response comes first or later.Then you have to set bRetrieve TRUE in data table configuration.That’s it.

This is My senario:

<script type="text/javascript">

$(document).ready(function () {

        $('#DatatableNone').dataTable({
            "bDestroy": true
        }).fnDestroy();

        $('#DatatableOne').dataTable({
            "aoColumnDefs": [{
                "bSortable": false,
                "aTargets": ["sorting_disabled"]
            }],
            "bDestroy": true
        }).fnDestroy();

});

</script>

Add a common Legend for combined ggplots

Roland's answer needs updating. See: https://github.com/hadley/ggplot2/wiki/Share-a-legend-between-two-ggplot2-graphs

This method has been updated for ggplot2 v1.0.0.

library(ggplot2)
library(gridExtra)
library(grid)


grid_arrange_shared_legend <- function(...) {
    plots <- list(...)
    g <- ggplotGrob(plots[[1]] + theme(legend.position="bottom"))$grobs
    legend <- g[[which(sapply(g, function(x) x$name) == "guide-box")]]
    lheight <- sum(legend$height)
    grid.arrange(
        do.call(arrangeGrob, lapply(plots, function(x)
            x + theme(legend.position="none"))),
        legend,
        ncol = 1,
        heights = unit.c(unit(1, "npc") - lheight, lheight))
}

dsamp <- diamonds[sample(nrow(diamonds), 1000), ]
p1 <- qplot(carat, price, data=dsamp, colour=clarity)
p2 <- qplot(cut, price, data=dsamp, colour=clarity)
p3 <- qplot(color, price, data=dsamp, colour=clarity)
p4 <- qplot(depth, price, data=dsamp, colour=clarity)
grid_arrange_shared_legend(p1, p2, p3, p4)

Note the lack of ggplot_gtable and ggplot_build. ggplotGrob is used instead. This example is a bit more convoluted than the above solution but it still solved it for me.

How to initialize List<String> object in Java?

In most cases you want simple ArrayList - an implementation of List

Before JDK version 7

List<String> list = new ArrayList<String>();

JDK 7 and later you can use the diamond operator

List<String> list = new ArrayList<>();

Further informations are written here Oracle documentation - Collections

List(of String) or Array or ArrayList

List(Of String) will handle that, mostly - though you need to either use AddRange to add a collection of items, or Add to add one at a time:

lstOfString.Add(String1)
lstOfString.Add(String2)
lstOfString.Add(String3)
lstOfString.Add(String4)

If you're adding known values, as you show, a good option is to use something like:

Dim inputs() As String = { "some value", _
                              "some value2", _
                              "some value3", _
                              "some value4" }

Dim lstOfString as List(Of String) = new List(Of String)(inputs)

' ...
Dim s3 = lstOfStrings(3)

This will still allow you to add items later as desired, but also get your initial values in quickly.


Edit:

In your code, you need to fix the declaration. Change:

Dim lstWriteBits() As List(Of String) 

To:

Dim lstWriteBits As List(Of String) 

Currently, you're declaring an Array of List(Of String) objects.

oracle SQL how to remove time from date

We can use TRUNC function in Oracle DB. Here is an example.

SELECT TRUNC(TO_DATE('01 Jan 2018 08:00:00','DD-MON-YYYY HH24:MI:SS')) FROM DUAL

Output: 1/1/2018

Calculating Waiting Time and Turnaround Time in (non-preemptive) FCFS queue

For non-preemptive system,

waitingTime = startTime - arrivalTime

turnaroundTime = burstTime + waitingTime = finishTime- arrivalTime

startTime = Time at which the process started executing

finishTime = Time at which the process finished executing

You can keep track of the current time elapsed in the system(timeElapsed). Assign all processors to a process in the beginning, and execute until the shortest process is done executing. Then assign this processor which is free to the next process in the queue. Do this until the queue is empty and all processes are done executing. Also, whenever a process starts executing, recored its startTime, when finishes, record its finishTime (both same as timeElapsed). That way you can calculate what you need.

If isset $_POST

You can simply use:

if($_POST['username'] and $_POST['password']){
  $username = $_POST['username'];
  $password = $_POST['password'];
}

Alternatively, use empty()

if(!empty($_POST['username']) and !empty($_POST['password'])){
  $username = $_POST['username'];
  $password = $_POST['password'];
}

Execute jar file with multiple classpath libraries from command prompt

Using java 1.7, on UNIX -

java -cp myjar.jar:lib/*:. mypackage.MyClass

On Windows you need to use ';' instead of ':' -

java -cp myjar.jar;lib/*;. mypackage.MyClass

How to convert Nvarchar column to INT

CONVERT takes the column name, not a string containing the column name; your current expression tries to convert the string A.my_NvarcharColumn to an integer instead of the column content.

SELECT convert (int, N'A.my_NvarcharColumn') FROM A;

should instead be

SELECT convert (int, A.my_NvarcharColumn) FROM A;

Simple SQLfiddle here.

How to apply Hovering on html area tag?

You can use jQuery to achieve this

Example:

$(function () {
        $('.map').maphilight();
    });

Go through this LINK to know more.

If the above one doesnt work then go through this link.

EDIT :

Give same class to each area tag like class="mapping"

and try this below code

$('.mapping').mouseover(function() {
    alert($(this).attr('id'));
}).mouseout(function(){
    alert('Mouseout....');      
});

How to use google maps without api key

You can still use free with iframe in google maps share button for example enter image description here

Getting visitors country from their IP

Use following services

1) http://api.hostip.info/get_html.php?ip=12.215.42.19

2)

$json = file_get_contents('http://freegeoip.appspot.com/json/66.102.13.106');
$expression = json_decode($json);
print_r($expression);

3) http://ipinfodb.com/ip_location_api.php

Show div #id on click with jQuery

You can use jQuery toggle to show and hide the div. The script will be like this

  <script type="text/javascript">
    jQuery(function(){
      jQuery("#music").click(function () {
        jQuery("#musicinfo").toggle("slow");
      });
    });
</script>

AngularJS: How can I pass variables between controllers?

The following example shows how to pass variables between siblings controllers and take an action when the value changes.

Use case example: you have a filter in a sidebar that changes the content of another view.

_x000D_
_x000D_
angular.module('myApp', [])_x000D_
_x000D_
  .factory('MyService', function() {_x000D_
_x000D_
    // private_x000D_
    var value = 0;_x000D_
_x000D_
    // public_x000D_
    return {_x000D_
      _x000D_
      getValue: function() {_x000D_
        return value;_x000D_
      },_x000D_
      _x000D_
      setValue: function(val) {_x000D_
        value = val;_x000D_
      }_x000D_
      _x000D_
    };_x000D_
  })_x000D_
  _x000D_
  .controller('Ctrl1', function($scope, $rootScope, MyService) {_x000D_
_x000D_
    $scope.update = function() {_x000D_
      MyService.setValue($scope.value);_x000D_
      $rootScope.$broadcast('increment-value-event');_x000D_
    };_x000D_
  })_x000D_
  _x000D_
  .controller('Ctrl2', function($scope, MyService) {_x000D_
_x000D_
    $scope.value = MyService.getValue();_x000D_
_x000D_
    $scope.$on('increment-value-event', function() {    _x000D_
      $scope.value = MyService.getValue();_x000D_
    });_x000D_
  });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
_x000D_
<div ng-app="myApp">_x000D_
  _x000D_
  <h3>Controller 1 Scope</h3>_x000D_
  <div ng-controller="Ctrl1">_x000D_
    <input type="text" ng-model="value"/>_x000D_
    <button ng-click="update()">Update</button>_x000D_
  </div>_x000D_
  _x000D_
  <hr>_x000D_
  _x000D_
  <h3>Controller 2 Scope</h3>_x000D_
  <div ng-controller="Ctrl2">_x000D_
    Value: {{ value }}_x000D_
  </div>  _x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

Cygwin - Makefile-error: recipe for target `main.o' failed

You see the two empty -D entries in the g++ command line? They're causing the problem. You must have values in the -D items e.g. -DWIN32

if you're insistent on using something like -D$(SYSTEM) -D$(ENVIRONMENT) then you can use something like:

SYSTEM ?= generic
ENVIRONMENT ?= generic

in the makefile which gives them default values.

Your output looks to be missing the all important output:

<command-line>:0:1: error: macro names must be identifiers
<command-line>:0:1: error: macro names must be identifiers

just to clarify, what actually got sent to g++ was -D -DWindows_NT, i.e. define a preprocessor macro called -DWindows_NT; which is of course not a valid identifier (similarly for -D -I.)

Remove multiple objects with rm()

Another variation you can try is(expanding @mnel's answer) if you have many temp'x'.

here "n" could be the number of temp variables present

rm(list = c(paste("temp",c(1:n),sep="")))

What does the 'u' symbol mean in front of string values?

This is a feature, not a bug.

See http://docs.python.org/howto/unicode.html, specifically the 'unicode type' section.

'int' object has no attribute '__getitem__'

I had a similar issue recently while working on recursion and nested lists. I declared:

print(r_sum([1,2,3[1,2,3],]))

instead of

print(r_sum([1,2,3,[1,2,3],]))

Note the comma after the number 3

how to save canvas as png image?

Submit a form that contains an input with value of canvas toDataURL('image/png') e.g

//JAVASCRIPT

    var canvas = document.getElementById("canvas");
    var url = canvas.toDataUrl('image/png');

Insert the value of the url to your hidden input on form element.

//PHP

    $data = $_POST['photo'];
    $data = str_replace('data:image/png;base64,', '', $data);
    $data = base64_decode($data);
    file_put_contents("i".  rand(0, 50).".png", $data);

Alternative to header("Content-type: text/xml");

No. You can't send headers after they were sent. Try to use hooks in wordpress

Not receiving Google OAuth refresh token

In order to get the refresh_token you need to include access_type=offline in the OAuth request URL. When a user authenticates for the first time you will get back a non-nil refresh_token as well as an access_token that expires.

If you have a situation where a user might re-authenticate an account you already have an authentication token for (like @SsjCosty mentions above), you need to get back information from Google on which account the token is for. To do that, add profile to your scopes. Using the OAuth2 Ruby gem, your final request might look something like this:

client = OAuth2::Client.new(
  ENV["GOOGLE_CLIENT_ID"],
  ENV["GOOGLE_CLIENT_SECRET"],
  authorize_url: "https://accounts.google.com/o/oauth2/auth",
  token_url: "https://accounts.google.com/o/oauth2/token"
)

# Configure authorization url
client.authorize_url(
  scope: "https://www.googleapis.com/auth/analytics.readonly profile",
  redirect_uri: callback_url,
  access_type: "offline",
  prompt: "select_account"
)

Note the scope has two space-delimited entries, one for read-only access to Google Analytics, and the other is just profile, which is an OpenID Connect standard.

This will result in Google providing an additional attribute called id_token in the get_token response. To get information out of the id_token, check out this page in the Google docs. There are a handful of Google-provided libraries that will validate and “decode” this for you (I used the Ruby google-id-token gem). Once you get it parsed, the sub parameter is effectively the unique Google account ID.

Worth noting, if you change the scope, you'll get back a refresh token again for users that have already authenticated with the original scope. This is useful if, say, you have a bunch of users already and don't want to make them all un-auth the app in Google.

Oh, and one final note: you don't need prompt=select_account, but it's useful if you have a situation where your users might want to authenticate with more than one Google account (i.e., you're not using this for sign-in / authentication).

How to convert image into byte array and byte array to base64 String in android?

Try this simple solution to convert file to base64 string

String base64String = imageFileToByte(file);

public String imageFileToByte(File file){

    Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath());
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
    byte[] b = baos.toByteArray();
    return Base64.encodeToString(b, Base64.DEFAULT);
}

Difference between Node object and Element object?

A node is the generic name for any type of object in the DOM hierarchy. A node could be one of the built-in DOM elements such as document or document.body, it could be an HTML tag specified in the HTML such as <input> or <p> or it could be a text node that is created by the system to hold a block of text inside another element. So, in a nutshell, a node is any DOM object.

An element is one specific type of node as there are many other types of nodes (text nodes, comment nodes, document nodes, etc...).

The DOM consists of a hierarchy of nodes where each node can have a parent, a list of child nodes and a nextSibling and previousSibling. That structure forms a tree-like hierarchy. The document node has the html node as its child. The html node has its list of child nodes (the head node and the body node). The body node would have its list of child nodes (the top level elements in your HTML page) and so on.

So, a nodeList is simply an array-like list of nodes.

An element is a specific type of node, one that can be directly specified in the HTML with an HTML tag and can have properties like an id or a class. can have children, etc... There are other types of nodes such as comment nodes, text nodes, etc... with different characteristics. Each node has a property .nodeType which reports what type of node it is. You can see the various types of nodes here (diagram from MDN):

enter image description here

You can see an ELEMENT_NODE is one particular type of node where the nodeType property has a value of 1.

So document.getElementById("test") can only return one node and it's guaranteed to be an element (a specific type of node). Because of that it just returns the element rather than a list.

Since document.getElementsByClassName("para") can return more than one object, the designers chose to return a nodeList because that's the data type they created for a list of more than one node. Since these can only be elements (only elements typically have a class name), it's technically a nodeList that only has nodes of type element in it and the designers could have made a differently named collection that was an elementList, but they chose to use just one type of collection whether it had only elements in it or not.


EDIT: HTML5 defines an HTMLCollection which is a list of HTML Elements (not any node, only Elements). A number of properties or methods in HTML5 now return an HTMLCollection. While it is very similar in interface to a nodeList, a distinction is now made in that it only contains Elements, not any type of node.

The distinction between a nodeList and an HTMLCollection has little impact on how you use one (as far as I can tell), but the designers of HTML5 have now made that distinction.

For example, the element.children property returns a live HTMLCollection.

onChange and onSelect in DropDownList

I bet the onchange is getting fired after the onselect, essentially re-enabling the select.

I'd recommend you implement only the onchange, inspect which option has been selected, and enable or disabled based on that.

To get the value of the selected option use:

document.getElementById("mySelect").options[document.getElementById("mySelect").selectedIndex].value

Which will yield .. nothing since you haven't specified a value for each option .. :(

<select id="mySelect" onChange="enable();">
<option onSelect="disable();" value="no">No</option>
<option onSelect="enable();" value="yes">Yes</option>
</select>

Now it will yield "yes" or "no"

Deserialize JSON to ArrayList<POJO> using Jackson

I am also having the same problem. I have a json which is to be converted to ArrayList.

Account looks like this.

Account{
  Person p ;
  Related r ;

}

Person{
    String Name ;
    Address a ;
}

All of the above classes have been annotated properly. I have tried TypeReference>() {} but is not working.

It gives me Arraylist but ArrayList has a linkedHashMap which contains some more linked hashmaps containing final values.

My code is as Follows:

public T unmarshal(String responseXML,String c)
{
    ObjectMapper mapper = new ObjectMapper();

    AnnotationIntrospector introspector = new JacksonAnnotationIntrospector();

    mapper.getDeserializationConfig().withAnnotationIntrospector(introspector);

    mapper.getSerializationConfig().withAnnotationIntrospector(introspector);
    try
    {
      this.targetclass = (T) mapper.readValue(responseXML,  new TypeReference<ArrayList<T>>() {});
    }
    catch (JsonParseException e)
    {
      e.printStackTrace();
    }
    catch (JsonMappingException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    return this.targetclass;
}

I finally solved the problem. I am able to convert the List in Json String directly to ArrayList as follows:

JsonMarshallerUnmarshaller<T>{

     T targetClass ;

     public ArrayList<T> unmarshal(String jsonString)
     {
        ObjectMapper mapper = new ObjectMapper();

        AnnotationIntrospector introspector = new JacksonAnnotationIntrospector();

        mapper.getDeserializationConfig().withAnnotationIntrospector(introspector);

        mapper.getSerializationConfig().withAnnotationIntrospector(introspector);
        JavaType type = mapper.getTypeFactory().
                    constructCollectionType(ArrayList.class, targetclass.getClass()) ;
        try
        {
        Class c1 = this.targetclass.getClass() ;
        Class c2 = this.targetclass1.getClass() ;
            ArrayList<T> temp = (ArrayList<T>) mapper.readValue(jsonString,  type);
        return temp ;
        }
       catch (JsonParseException e)
       {
        e.printStackTrace();
       }
       catch (JsonMappingException e) {
           e.printStackTrace();
       } catch (IOException e) {
          e.printStackTrace();
       }

     return null ;
    }  

}

Postgresql column reference "id" is ambiguous

SELECT (vg.id, name) FROM v_groups vg 
INNER JOIN people2v_groups p2vg ON vg.id = p2vg.v_group_id
WHERE p2vg.people_id = 0;

Properties file with a list as the value for an individual key

Try writing the properties as a comma separated list, then split the value after the properties file is loaded. For example

a=one,two,three
b=nine,ten,fourteen

You can also use org.apache.commons.configuration and change the value delimiter using the AbstractConfiguration.setListDelimiter(char) method if you're using comma in your values.

Parsing command-line arguments in C

Your C/C++ program always has a main function. It looks like that:

    int main(int argc, char**argv) {
        ...
    }

Here argc is a number of command line arguments, that have been passed to your program, and argv is an array of strings with these arguments. So command line is separated in-to arguments by the caller process (this is not a single line, like in windows).

Now you need to sort them out:

  • Command name is always the first argument (index 0).
  • Options are just special arguments that specify how a program should work. By convention they start from - sign. Usually - for one letter options and -- for anything longer. So in your task "options" are all arguments, that start from - and are not the 0th.
  • Arguments. Just all other arguments which are not program name or options.

Resolving javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed Error?

For Tomcat running on Ubuntu server, to find out which Java is being used, use "ps -ef | grep tomcat" command:

Sample:

/home/mcp01$ **ps -ef |grep tomcat**
tomcat7  28477     1  0 10:59 ?        00:00:18 **/usr/local/java/jdk1.7.0_15/bin/java** -Djava.util.logging.config.file=/var/lib/tomcat7/conf/logging.properties -Djava.awt.headless=true -Xmx512m -XX:+UseConcMarkSweepGC -Djava.net.preferIPv4Stack=true -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Djava.endorsed.dirs=/usr/share/tomcat7/endorsed -classpath /usr/share/tomcat7/bin/bootstrap.jar:/usr/share/tomcat7/bin/tomcat-juli.jar -Dcatalina.base=/var/lib/tomcat7 -Dcatalina.home=/usr/share/tomcat7 -Djava.io.tmpdir=/tmp/tomcat7-tomcat7-tmp org.apache.catalina.startup.Bootstrap start
1005     28567 28131  0 11:34 pts/1    00:00:00 grep --color=auto tomcat

Then, we can go in to: cd /usr/local/java/jdk1.7.0_15/jre/lib/security

Default cacerts file is located in here. Insert the untrusted certificate into it.

What are some reasons for jquery .focus() not working?

Only "keyboard focusable" elements can be focused with .focus(). div aren't meant to be natively focusable. You have to add tabindex="0" attributes to it to achieve that. input, button, a etc... are natively focusable.

How to parse JSON without JSON.NET library?

Have you tried using JavaScriptSerializer ? There's also DataContractJsonSerializer

Cannot create PoolableConnectionFactory (Io exception: The Network Adapter could not establish the connection)

I had the same error and ended up solving it by upgrading my Oracle ojdbc driver to a version compatible with the Oracle database version

Using a dictionary to select function to execute

You can just use

myDict = {
    "P1": (lambda x: function1()),
    "P2": (lambda x: function2()),
    ...,
    "Pn": (lambda x: functionn())}
myItems = ["P1", "P2", ..., "Pn"]

for item in myItems:
    myDict[item]()

google maps v3 marker info window on mouseover

Thanks to duncan answer, I end up with this:

marker.addListener('mouseover', () => infoWindow.open(map, marker))
marker.addListener('mouseout', () => infoWindow.close())

How to declare strings in C

You shouldn't use the third one because its wrong. "String" takes 7 bytes, not 5.

The first one is a pointer (can be reassigned to a different address), the other two are declared as arrays, and cannot be reassigned to different memory locations (but their content may change, use const to avoid that).

Making a button invisible by clicking another button in HTML

To get an element by its ID, use this:

document.getElementById("p2")

Instead of:

document.getElementsByName("p2")

So the final product would be:

document.getElementsById("p2").style.visibility = "hidden";

How does jQuery work when there are multiple elements with the same ID value?

Having 2 elements with the same ID is not valid html according to the W3C specification.

When your CSS selector only has an ID selector (and is not used on a specific context), jQuery uses the native document.getElementById method, which returns only the first element with that ID.

However, in the other two instances, jQuery relies on the Sizzle selector engine (or querySelectorAll, if available), which apparently selects both elements. Results may vary on a per browser basis.

However, you should never have two elements on the same page with the same ID. If you need it for your CSS, use a class instead.


If you absolutely must select by duplicate ID, use an attribute selector:

$('[id="a"]');

Take a look at the fiddle: http://jsfiddle.net/P2j3f/2/

Note: if possible, you should qualify that selector with a tag selector, like this:

$('span[id="a"]');

phpMyAdmin - The MySQL Extension is Missing

I just add

apt-get install php5-mysqlnd

This will ask to overwrite mysql.so from "php5-mysql".

This work for me.

Convert an integer to an array of digits

The immediate problem is due to you using <= temp.length() instead of < temp.length(). However, you can achieve this a lot more simply. Even if you use the string approach, you can use:

String temp = Integer.toString(guess);
int[] newGuess = new int[temp.length()];
for (int i = 0; i < temp.length(); i++)
{
    newGuess[i] = temp.charAt(i) - '0';
}

You need to make the same change to use < newGuess.length() when printing out the content too - otherwise for an array of length 4 (which has valid indexes 0, 1, 2, 3) you'll try to use newGuess[4]. The vast majority of for loops I write use < in the condition, rather than <=.

How to extract code of .apk file which is not working?

Click here this is a good tutorial for both window/ubuntu.

  1. apktool1.5.1.jar download from here.

  2. apktool-install-linux-r05-ibot download from here.

  3. dex2jar-0.0.9.15.zip download from here.

  4. jd-gui-0.3.3.linux.i686.tar.gz (java de-complier) download from here.

  5. framework-res.apk ( Located at your android device /system/framework/)

Procedure:

  1. Rename the .apk file and change the extension to .zip ,

it will become .zip.

  1. Then extract .zip.

  2. Unzip downloaded dex2jar-0.0.9.15.zip file , copy the contents and paste it to unzip folder.

  3. Open terminal and change directory to unzip “dex2jar-0.0.9.15 “

– cd – sh dex2jar.sh classes.dex (result of this command “classes.dex.dex2jar.jar” will be in your extracted folder itself).

  1. Now, create new folder and copy “classes.dex.dex2jar.jar” into it.

  2. Unzip “jd-gui-0.3.3.linux.i686.zip“ and open up the “Java Decompiler” in full screen mode.

  3. Click on open file and select “classes.dex.dex2jar.jar” into the window.

  4. “Java Decompiler” and go to file > save and save the source in a .zip file.

  5. Create “source_code” folder.

  6. Extract the saved .zip and copy the contents to “source_code” folder.

  7. This will be where we keep your source code.

  8. Extract apktool1.5.1.tar.bz2 , you get apktool.jar

  9. Now, unzip “apktool-install-linux-r05-ibot.zip”

  10. Copy “framework-res.apk” , “.apk” and apktool.jar

  11. Paste it to the unzip “apktool-install-linux-r05-ibot” folder (line no 13).

  12. Then open terminal and type:

    – cd

    – chown -R : ‘apktool.jar’

    – chown -R : ‘apktool’

    – chown -R : ‘aapt’

    – sudo chmod +x ‘apktool.jar’

    – sudo chmod +x ‘apktool’

    – sudo chmod +x ‘aapt’

    – sudo mv apktool.jar /usr/local/bin

    – sudo mv apktool /usr/local/bin

    – sudo mv aapt /usr/local/bin

    – apktool if framework-res.apk – apktool d .apk

php $_GET and undefined index

I recommend you check your arrays before you blindly access them :

if(isset($_GET['s'])){
    if ($_GET['s'] == 'jwshxnsyllabus')
        /* your code here*/
}

Another (quick) fix is to disable the error reporting by writing this on the top of the script :

error_reporting(0);  

In your case, it is very probable that your other server had the error reporting configuration in php.ini set to 0 as default.
By calling the error_reporting with 0 as parameter, you are turning off all notices/warnings and errors. For more details check the php manual.

Remeber that this is a quick fix and it's highly recommended to avoid errors rather than ignore them.

How to order a data frame by one descending and one ascending column?

Simple one without rank :

rum[order(rum$I1, -rum$I2, decreasing = TRUE), ]

PHP fopen() Error: failed to open stream: Permission denied

[function.fopen]: failed to open stream

If you have access to your php.ini file, try enabling Fopen. Find the respective line and set it to be "on": & if in wp e.g localhost/wordpress/function.fopen in the php.ini :

allow_url_fopen = off
should bee this 
allow_url_fopen = On

And add this line below it:
allow_url_include = off
should bee this 
allow_url_include = on

How to calculate the angle between a line and the horizontal axis?

import math
from collections import namedtuple


Point = namedtuple("Point", ["x", "y"])


def get_angle(p1: Point, p2: Point) -> float:
    """Get the angle of this line with the horizontal axis."""
    dx = p2.x - p1.x
    dy = p2.y - p1.y
    theta = math.atan2(dy, dx)
    angle = math.degrees(theta)  # angle is in (-180, 180]
    if angle < 0:
        angle = 360 + angle
    return angle

Testing

For testing I let hypothesis generate test cases.

enter image description here

import hypothesis.strategies as s
from hypothesis import given


@given(s.floats(min_value=0.0, max_value=360.0))
def test_angle(angle: float):
    epsilon = 0.0001
    x = math.cos(math.radians(angle))
    y = math.sin(math.radians(angle))
    p1 = Point(0, 0)
    p2 = Point(x, y)
    assert abs(get_angle(p1, p2) - angle) < epsilon

How to sort alphabetically while ignoring case sensitive?

I can't believe no one made a reference to the Collator. Almost all of these answers will only work for the English language.

You should almost always use a Collator for dictionary based sorting.

For case insensitive collator searching for the English language you do the following:

Collator usCollator = Collator.getInstance(Locale.US);
usCollator.setStrength(Collator.PRIMARY);
Collections.sort(listToSort, usCollator);

RequiredIf Conditional Validation Attribute

I know the topic was asked some time ago, but recently I had faced similar issue and found yet another, but in my opinion a more complete solution. I decided to implement mechanism which provides conditional attributes to calculate validation results based on other properties values and relations between them, which are defined in logical expressions.

Using it you are able to achieve the result you asked about in the following manner:

[RequiredIf("MyProperty2 == null && MyProperty3 == false")]
public string MyProperty1 { get; set; }

[RequiredIf("MyProperty1 == null && MyProperty3 == false")]
public string MyProperty2 { get; set; }

[AssertThat("MyProperty1 != null || MyProperty2 != null || MyProperty3 == true")]
public bool MyProperty3 { get; set; }

More information about ExpressiveAnnotations library can be found here. It should simplify many declarative validation cases without the necessity of writing additional case-specific attributes or using imperative way of validation inside controllers.

Android: why setVisibility(View.GONE); or setVisibility(View.INVISIBLE); do not work

First see your code:

dp2.setVisibility(View.GONE);
dp2.setVisibility(View.INVISIBLE);
btn2.setVisibility(View.GONE);
btn2.setVisibility(View.INVISIBLE);

Here you set both visibility to same field so that's the problem. I give one sample for that sample demo

Getting RSA private key from PEM BASE64 Encoded private key file

Parsing PKCS1 (only PKCS8 format works out of the box on Android) key turned out to be a tedious task on Android because of the lack of ASN1 suport, yet solvable if you include Spongy castle jar to read DER Integers.

String privKeyPEM = key.replace(
"-----BEGIN RSA PRIVATE KEY-----\n", "")
    .replace("-----END RSA PRIVATE KEY-----", "");

// Base64 decode the data

byte[] encodedPrivateKey = Base64.decode(privKeyPEM, Base64.DEFAULT);

try {
    ASN1Sequence primitive = (ASN1Sequence) ASN1Sequence
        .fromByteArray(encodedPrivateKey);
    Enumeration<?> e = primitive.getObjects();
    BigInteger v = ((DERInteger) e.nextElement()).getValue();

    int version = v.intValue();
    if (version != 0 && version != 1) {
        throw new IllegalArgumentException("wrong version for RSA private key");
    }
    /**
     * In fact only modulus and private exponent are in use.
     */
    BigInteger modulus = ((DERInteger) e.nextElement()).getValue();
    BigInteger publicExponent = ((DERInteger) e.nextElement()).getValue();
    BigInteger privateExponent = ((DERInteger) e.nextElement()).getValue();
    BigInteger prime1 = ((DERInteger) e.nextElement()).getValue();
    BigInteger prime2 = ((DERInteger) e.nextElement()).getValue();
    BigInteger exponent1 = ((DERInteger) e.nextElement()).getValue();
    BigInteger exponent2 = ((DERInteger) e.nextElement()).getValue();
    BigInteger coefficient = ((DERInteger) e.nextElement()).getValue();

    RSAPrivateKeySpec spec = new RSAPrivateKeySpec(modulus, privateExponent);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PrivateKey pk = kf.generatePrivate(spec);
} catch (IOException e2) {
    throw new IllegalStateException();
} catch (NoSuchAlgorithmException e) {
    throw new IllegalStateException(e);
} catch (InvalidKeySpecException e) {
    throw new IllegalStateException(e);
}

Generate an integer that is not among four billion given ones

Check the size of the input file, then output any number which is too large to be represented by a file that size. This may seem like a cheap trick, but it's a creative solution to an interview problem, it neatly sidesteps the memory issue, and it's technically O(n).

void maxNum(ulong filesize)
{
    ulong bitcount = filesize * 8; //number of bits in file

    for (ulong i = 0; i < bitcount; i++)
    {
        Console.Write(9);
    }
}

Should print 10 bitcount - 1, which will always be greater than 2 bitcount. Technically, the number you have to beat is 2 bitcount - (4 * 109 - 1), since you know there are (4 billion - 1) other integers in the file, and even with perfect compression they'll take up at least one bit each.

How to check for empty value in Javascript?

In my opinion, using "if(value)" to judge a value whether is an empty value is not strict, because the result of "v?true:false" is false when the value of v is 0(0 is not an empty value). You can use this function:

const isEmptyValue = (value) => {
    if (value === '' || value === null || value === undefined) {
        return true
    } else {
        return false
    }
}

How to update all MySQL table rows at the same time?

update mytable set online_status = 'online'

If you want to assign different values, you should use the TRANSACTION technique.

Left Outer Join using + sign in Oracle 11g

There is some incorrect information in this thread. I copied and pasted the incorrect information:

LEFT OUTER JOIN

SELECT *
FROM A, B
WHERE A.column = B.column(+)

RIGHT OUTER JOIN

SELECT *
FROM A, B
WHERE B.column(+) = A.column

The above is WRONG!!!!! It's reversed. How I determined it's incorrect is from the following book:

Oracle OCP Introduction to Oracle 9i: SQL Exam Guide. Page 115 Table 3-1 has a good summary on this. I could not figure why my converted SQL was not working properly until I went old school and looked in a printed book!

Here is the summary from this book, copied line by line:

Oracle outer Join Syntax:

from tab_a a, tab_b b,                                       
where a.col_1 + = b.col_1                                     

ANSI/ISO Equivalent:

from tab_a a left outer join  
tab_b b on a.col_1 = b.col_1

Notice here that it's the reverse of what is posted above. I suppose it's possible for this book to have errata, however I trust this book more so than what is in this thread. It's an exam guide for crying out loud...

What to do about Eclipse's "No repository found containing: ..." error messages?

Simple!!!!!!!!

Right click on eclipse folder and go to properties. Uncheck checkbox "read only" if checked. apply changes.click oK.

after go to Help>Install new software>Uncheck “Contact all update sites during install to find required software”.

"This SqlTransaction has completed; it is no longer usable."... configuration error?

For what it's worth, I've run into this on what was previously working code. I had added SELECT statements in a trigger for debug testing and forgot to remove them. Entity Framework / MVC doesnt play nice when other stuff is output to the "grid". Make sure to check for any rogue queries and remove them.

exceeds the list view threshold 5000 items in Sharepoint 2010

I had the same problem.please do the following it may help you: By Default List View Threshold set at only 5,000 items this is because of Sharepoint server performance.

To Change the LVT:

  1. Click SharePoint Central Administration,
  2. Go to Application Management
  3. Manage Web Applications
  4. Select your application
  5. Click General Settings at the ribbon
  6. Select Resource Throttling
  7. List View Threshold limit --> change the value to your need.
  8. Also change the List View Threshold for Auditors and Administrators.if you are a administrator.

Click OK to save it.

Playing .mp3 and .wav in Java?

Java FX has Media and MediaPlayer classes which will play mp3 files.

Example code:

String bip = "bip.mp3";
Media hit = new Media(new File(bip).toURI().toString());
MediaPlayer mediaPlayer = new MediaPlayer(hit);
mediaPlayer.play();

You will need the following import statements:

import java.io.File;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;

jQuery: How to get the event object in an event handler function without passing it as an argument?

If you call your event handler on markup, as you're doing now, you can't (x-browser). But if you bind the click event with jquery, it's possible the following way:

Markup:

  <a href="#" id="link1" >click</a>

Javascript:

  $(document).ready(function(){
      $("#link1").click(clickWithEvent);  //Bind the click event to the link
  });
  function clickWithEvent(evt){
     myFunc('p1', 'p2', 'p3');
     function myFunc(p1,p2,p3){  //Defined as local function, but has access to evt
        alert(evt.type);        
     }
  }

Since the event ob

Xml serialization - Hide null values

Additionally to what Chris Taylor wrote: if you have something serialized as an attribute, you can have a property on your class named {PropertyName}Specified to control if it should be serialized. In code:

public class MyClass
{
    [XmlAttribute]
    public int MyValue;

    [XmlIgnore]
    public bool MyValueSpecified;
}

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

I eventually stumbled upon an example of the usage I was looking for - to assign an error to the Model in general, rather than one of it's properties, as usual you call:

ModelState.AddModelError(string key, string errorMessage);

but use an empty string for the key:

ModelState.AddModelError(string.Empty, "There is something wrong with Foo.");

The error message will present itself in the <%: Html.ValidationSummary() %> as you'd expect.

Does JavaScript guarantee object property order?

From the JSON standard:

An object is an unordered collection of zero or more name/value pairs, where a name is a string and a value is a string, number, boolean, null, object, or array.

(emphasis mine).

So, no you can't guarantee the order.

Unable to find the wrapper "https" - did you forget to enable it when you configured PHP?

PHP7, in php.ini file, remove the ";" before extension=openssl

what does this mean ? image/png;base64?

That data:image/png;base64 URL is cool, I’ve never run into it before. The long encrypted link is the actual image, i.e. no image call to the server. See RFC 2397 for details.

Side note: I have had trouble getting larger base64 images to render on IE8. I believe IE8 has a 32K limit that can be problematic for larger files. See this other StackOverflow thread for details.

sorting a List of Map<String, String>

There are many ways to solve the same. One of the easiest ways to solve using Java 8 is given below :

As per your requirement, To sort in alphabetical order based on the map's key name

1st way :

list = list.stream()
           .sorted((a,b)-> (a.get("name")).compareTo(b.get("name")))
           .collect(Collectors.toList());

Or,

list = list.stream()
           .sorted(Comparator.comparing(map->map.get("name")))
           .collect(Collectors.toList());

2nd way :

Collections.sort(list, Comparator.comparing(map -> map.get("name")));

3rd way :

list.sort(Comparator.comparing(map-> map.get("name")));

Mapping many-to-many association table with extra column(s)

As said before, with JPA, in order to have the chance to have extra columns, you need to use two OneToMany associations, instead of a single ManyToMany relationship. You can also add a column with autogenerated values; this way, it can work as the primary key of the table, if useful.

For instance, the implementation code of the extra class should look like that:

@Entity
@Table(name = "USER_SERVICES")
public class UserService{

    // example of auto-generated ID
    @Id
    @Column(name = "USER_SERVICES_ID", nullable = false)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long userServiceID;



    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "USER_ID")
    private User user;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "SERVICE_ID")
    private Service service;



    // example of extra column
    @Column(name="VISIBILITY")    
    private boolean visibility;



    public long getUserServiceID() {
        return userServiceID;
    }


    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public Service getService() {
        return service;
    }

    public void setService(Service service) {
        this.service = service;
    }

    public boolean getVisibility() {
        return visibility;
    }

    public void setVisibility(boolean visibility) {
        this.visibility = visibility;
    }

}

Converting from signed char to unsigned char and back again?

I'm not 100% sure that I understand your question, so tell me if I'm wrong.

If I got it right, you are reading jbytes that are technically signed chars, but really pixel values ranging from 0 to 255, and you're wondering how you should handle them without corrupting the values in the process.

Then, you should do the following:

  • convert jbytes to unsigned char before doing anything else, this will definetly restore the pixel values you are trying to manipulate

  • use a larger signed integer type, such as int while doing intermediate calculations, this to make sure that over- and underflows can be detected and dealt with (in particular, not casting to a signed type could force to compiler to promote every type to an unsigned type in which case you wouldn't be able to detect underflows later on)

  • when assigning back to a jbyte, you'll want to clamp your value to the 0-255 range, convert to unsigned char and then convert again to signed char: I'm not certain the first conversion is strictly necessary, but you just can't be wrong if you do both

For example:

inline int fromJByte(jbyte pixel) {
    // cast to unsigned char re-interprets values as 0-255
    // cast to int will make intermediate calculations safer
    return static_cast<int>(static_cast<unsigned char>(pixel));
}

inline jbyte fromInt(int pixel) {
    if(pixel < 0)
        pixel = 0;

    if(pixel > 255)
        pixel = 255;

    return static_cast<jbyte>(static_cast<unsigned char>(pixel));
}

jbyte in = ...
int intermediate = fromJByte(in) + 30;
jbyte out = fromInt(intermediate);

How to run multiple Python versions on Windows

let's say if we have python 3.7 and python 3.6 installed.

they are respectively stored in following folder by default.

C:\Users\name\AppData\Local\Programs\Python\Python36 C:\Users\name\AppData\Local\Programs\Python\Python37

if we want to use cmd prompt to install/run command in any of the above specific environment do this:

There should be python.exe in each of the above folder.

so when we try running any file for ex. (see image1) python hello.py. we call that respective python.exe. by default it picks lower version of file. (means in this case it will use from python 3.6 )

image

so if we want to run using python3.7. just change the .exe file name. for ex. if I change to python37.exe and i want to use python3.7 to run hello.py

I will use python37 hello.py . or if i want to use python3.7 by default i will change the python.exe filename in python3.6 folder to something else . so that it will use python3.7 each time when I use only python hello.py

Can I change the name of `nohup.out`?

For some reason, the above answer did not work for me; I did not return to the command prompt after running it as I expected with the trailing &. Instead, I simply tried with

nohup some_command > nohup2.out&

and it works just as I want it to. Leaving this here in case someone else is in the same situation. Running Bash 4.3.8 for reference.

Importing files from different folder

Note: This answer was intended for a very specific question. For most programmers coming here from a search engine, this is not the answer you are looking for. Typically you would structure your files into packages (see other answers) instead of modifying the search path.


By default, you can't. When importing a file, Python only searches the directory that the entry-point script is running from and sys.path which includes locations such as the package installation directory (it's actually a little more complex than this, but this covers most cases).

However, you can add to the Python path at runtime:

# some_file.py
import sys
# insert at 1, 0 is the script path (or '' in REPL)
sys.path.insert(1, '/path/to/application/app/folder')

import file

How can I combine two HashMap objects containing the same types?

One-liner using Java 8 Stream API:

map3 = Stream.of(map1, map2).flatMap(m -> m.entrySet().stream())
       .collect(Collectors.toMap(Entry::getKey, Entry::getValue))

Among the benefits of this method is ability to pass a merge function, which will deal with values that have the same key, for example:

map3 = Stream.of(map1, map2).flatMap(m -> m.entrySet().stream())
       .collect(Collectors.toMap(Entry::getKey, Entry::getValue, Math::max))

Simple GUI Java calculator

This is the working code...

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;

public class JavaCalculator extends JFrame {

    private JButton jbtNum1;
    private JButton jbtNum2;
    private JButton jbtNum3;
    private JButton jbtNum4;
    private JButton jbtNum5;
    private JButton jbtNum6;
    private JButton jbtNum7;
    private JButton jbtNum8;
    private JButton jbtNum9;
    private JButton jbtNum0;
    private JButton jbtEqual;
    private JButton jbtAdd;
    private JButton jbtSubtract;
    private JButton jbtMultiply;
    private JButton jbtDivide;
    private JButton jbtSolve;
    private JButton jbtClear;
    private double TEMP;
    private double SolveTEMP;
    private JTextField jtfResult;

    Boolean addBool = false;
    Boolean subBool = false;
    Boolean divBool = false;
    Boolean mulBool = false;

    String display = "";

    public JavaCalculator() {

        JPanel p1 = new JPanel();
        p1.setLayout(new GridLayout(4, 3));
        p1.add(jbtNum1 = new JButton("1"));
        p1.add(jbtNum2 = new JButton("2"));
        p1.add(jbtNum3 = new JButton("3"));
        p1.add(jbtNum4 = new JButton("4"));
        p1.add(jbtNum5 = new JButton("5"));
        p1.add(jbtNum6 = new JButton("6"));
        p1.add(jbtNum7 = new JButton("7"));
        p1.add(jbtNum8 = new JButton("8"));
        p1.add(jbtNum9 = new JButton("9"));
        p1.add(jbtNum0 = new JButton("0"));
        p1.add(jbtClear = new JButton("C"));

        JPanel p2 = new JPanel();
        p2.setLayout(new FlowLayout());
        p2.add(jtfResult = new JTextField(20));
        jtfResult.setHorizontalAlignment(JTextField.RIGHT);
        jtfResult.setEditable(false);

        JPanel p3 = new JPanel();
        p3.setLayout(new GridLayout(5, 1));
        p3.add(jbtAdd = new JButton("+"));
        p3.add(jbtSubtract = new JButton("-"));
        p3.add(jbtMultiply = new JButton("*"));
        p3.add(jbtDivide = new JButton("/"));
        p3.add(jbtSolve = new JButton("="));

        JPanel p = new JPanel();
        p.setLayout(new GridLayout());
        p.add(p2, BorderLayout.NORTH);
        p.add(p1, BorderLayout.SOUTH);
        p.add(p3, BorderLayout.EAST);

        add(p);

        jbtNum1.addActionListener(new ListenToOne());
        jbtNum2.addActionListener(new ListenToTwo());
        jbtNum3.addActionListener(new ListenToThree());
        jbtNum4.addActionListener(new ListenToFour());
        jbtNum5.addActionListener(new ListenToFive());
        jbtNum6.addActionListener(new ListenToSix());
        jbtNum7.addActionListener(new ListenToSeven());
        jbtNum8.addActionListener(new ListenToEight());
        jbtNum9.addActionListener(new ListenToNine());
        jbtNum0.addActionListener(new ListenToZero());

        jbtAdd.addActionListener(new ListenToAdd());
        jbtSubtract.addActionListener(new ListenToSubtract());
        jbtMultiply.addActionListener(new ListenToMultiply());
        jbtDivide.addActionListener(new ListenToDivide());
        jbtSolve.addActionListener(new ListenToSolve());
        jbtClear.addActionListener(new ListenToClear());
    } //JavaCaluclator()

    class ListenToClear implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            //display = jtfResult.getText();
            jtfResult.setText("");
            addBool = false;
            subBool = false;
            mulBool = false;
            divBool = false;

            TEMP = 0;
            SolveTEMP = 0;
        }
    }

    class ListenToOne implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            display = jtfResult.getText();
            jtfResult.setText(display + "1");
        }
    }

    class ListenToTwo implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            display = jtfResult.getText();
            jtfResult.setText(display + "2");
        }
    }

    class ListenToThree implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            display = jtfResult.getText();
            jtfResult.setText(display + "3");
        }
    }

    class ListenToFour implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            display = jtfResult.getText();
            jtfResult.setText(display + "4");
        }
    }

    class ListenToFive implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            display = jtfResult.getText();
            jtfResult.setText(display + "5");
        }
    }

    class ListenToSix implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            display = jtfResult.getText();
            jtfResult.setText(display + "6");
        }
    }

    class ListenToSeven implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            display = jtfResult.getText();
            jtfResult.setText(display + "7");
        }
    }

    class ListenToEight implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            display = jtfResult.getText();
            jtfResult.setText(display + "8");
        }
    }

    class ListenToNine implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            display = jtfResult.getText();
            jtfResult.setText(display + "9");
        }
    }

    class ListenToZero implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            display = jtfResult.getText();
            jtfResult.setText(display + "0");
        }
    }

    class ListenToAdd implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            TEMP = Double.parseDouble(jtfResult.getText());
            jtfResult.setText("");
            addBool = true;
        }
    }

    class ListenToSubtract implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            TEMP = Double.parseDouble(jtfResult.getText());
            jtfResult.setText("");
            subBool = true;
        }
    }

    class ListenToMultiply implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            TEMP = Double.parseDouble(jtfResult.getText());
            jtfResult.setText("");
            mulBool = true;
        }
    }

    class ListenToDivide implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            TEMP = Double.parseDouble(jtfResult.getText());
            jtfResult.setText("");
            divBool = true;
        }
    }

    class ListenToSolve implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            SolveTEMP = Double.parseDouble(jtfResult.getText());
            if (addBool == true)
                SolveTEMP = SolveTEMP + TEMP;
            else if ( subBool == true)
                SolveTEMP = SolveTEMP - TEMP;
            else if ( mulBool == true)
                SolveTEMP = SolveTEMP * TEMP;
            else if ( divBool == true)
                            SolveTEMP = SolveTEMP / TEMP;
            jtfResult.setText(  Double.toString(SolveTEMP));

            addBool = false;
            subBool = false;
            mulBool = false;
            divBool = false;
        }
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        JavaCalculator calc = new JavaCalculator();
        calc.pack();
        calc.setLocationRelativeTo(null);
                calc.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        calc.setVisible(true);
    }

} //JavaCalculator

SQL Server: Attach incorrect version 661

SQL Server 2008 databases are version 655. SQL Server 2008 R2 databases are 661. You are trying to attach an 2008 R2 database (v. 661) to an 2008 instance and this is not supported. Once the database has been upgraded to an 2008 R2 version, it cannot be downgraded. You'll have to either upgrade your 2008 SP2 instance to R2, or you have to copy out the data in that database into an 2008 database (eg using the data migration wizard, or something equivalent).

The message is misleading, to say the least, it says 662 because SQL Server 2008 SP2 does support 662 as a database version, this is when 15000 partitions are enabled in the database, see Support for 15000 Partitions.docx. Enabling the support bumps the DB version to 662, disabling it moves it back to 655. But SQL Server 2008 SP2 does not support 661 (the R2 version).

How do I resolve "Run-time error '429': ActiveX component can't create object"?

The file msrdo20.dll is missing from the installation.

According to the Support Statement for Visual Basic 6.0 on Windows Vista, Windows Server 2008 and Windows 7 this file should be distributed with the application.

I'm not sure why it isn't, but my solution is to place the file somewhere on the machine, and register it using regsvr32 in the command line, eg:

regsvr32 c:\windows\system32\msrdo20.dll

In an ideal world you would package this up with the redistributable.

Sending Multipart File as POST parameters with RestTemplate requests

I had to do the same thing that @Luxspes did above..and I am using Spring 4.2.6. Spent quite some time figuring why is ByteArrayResource getting transferred from client to server, but the server is not recognizing it.

ByteArrayResource contentsAsResource = new ByteArrayResource(byteArr){
            @Override
            public String getFilename(){
                return filename;
            }
        };

How to Display Multiple Google Maps per page with API V3

OP wanted two specific maps, but if you'd like to have a dynamic number of maps on one page (for instance a list of retailer locations) you need to go another route. The standard implementation of Google maps API defines the map as a global variable, this won't work with a dynamic number of maps. Here's my code to solve this without global variables:

function mapAddress(mapElement, address) {
var geocoder = new google.maps.Geocoder();

geocoder.geocode({ 'address': address }, function (results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
        var mapOptions = {
            zoom: 14,
            center: results[0].geometry.location,
            disableDefaultUI: true
        };
        var map = new google.maps.Map(document.getElementById(mapElement), mapOptions);
        var marker = new google.maps.Marker({
            map: map,
            position: results[0].geometry.location
        });
    } else {
        alert("Geocode was not successful for the following reason: " + status);
    }
});
}

Just pass the ID and address of each map to the function to plot the map and mark the address.

Errors: "INSERT EXEC statement cannot be nested." and "Cannot use the ROLLBACK statement within an INSERT-EXEC statement." How to solve this?

OK, encouraged by jimhark here is an example of the old single hash table approach: -

CREATE PROCEDURE SP3 as

BEGIN

    SELECT 1, 'Data1'
    UNION ALL
    SELECT 2, 'Data2'

END
go


CREATE PROCEDURE SP2 as

BEGIN

    if exists (select  * from tempdb.dbo.sysobjects o where o.xtype in ('U') and o.id = object_id(N'tempdb..#tmp1'))
        INSERT INTO #tmp1
        EXEC SP3
    else
        EXEC SP3

END
go

CREATE PROCEDURE SP1 as

BEGIN

    EXEC SP2

END
GO


/*
--I want some data back from SP3

-- Just run the SP1

EXEC SP1
*/


/*
--I want some data back from SP3 into a table to do something useful
--Try run this - get an error - can't nest Execs

if exists (select  * from tempdb.dbo.sysobjects o where o.xtype in ('U') and o.id = object_id(N'tempdb..#tmp1'))
    DROP TABLE #tmp1

CREATE TABLE #tmp1 (ID INT, Data VARCHAR(20))

INSERT INTO #tmp1
EXEC SP1


*/

/*
--I want some data back from SP3 into a table to do something useful
--However, if we run this single hash temp table it is in scope anyway so
--no need for the exec insert

if exists (select  * from tempdb.dbo.sysobjects o where o.xtype in ('U') and o.id = object_id(N'tempdb..#tmp1'))
    DROP TABLE #tmp1

CREATE TABLE #tmp1 (ID INT, Data VARCHAR(20))

EXEC SP1

SELECT * FROM #tmp1

*/

Javascript split regex question

Say your string is:

let str = `word1
word2;word3,word4,word5;word7
word8,word9;word10`;

You want to split the string by the following delimiters:

  • Colon
  • Semicolon
  • New line

You could split the string like this:

let rawElements = str.split(new RegExp('[,;\n]', 'g'));

Finally, you may need to trim the elements in the array:

let elements = rawElements.map(element => element.trim());

How to use a class from one C# project with another C# project

The first step is to make P2 reference P1 by doing the following

  • Right Click on the project and select "Add Reference"
  • Go to the Projects Tab
  • Select P1 and hit OK

Next you'll need to make sure that the classes in P1 are accessible to P2. The easiest way is to make them public.

public class MyType { ... }

Now you should be able to use them in P2 via their fully qualified name. Assuming the namespace of P1 is Project1 then the following would work

Project1.MyType obj = new Project1.MyType();

The preferred way though is to add a using for Project1 so you can use the types without qualification

using Project1;
...

public void Example() {
  MyType obj = new MyType();
}

WPF What is the correct way of using SVG files as icons in WPF

Another alternative is dotnetprojects SVGImage

This allows native use of .svg files directly in xaml.

The nice part is, it is only one assembly which is about 100k. In comparision to sharpvectors which is much bigger any many files.

Usage:

...
xmlns:svg1="clr-namespace:SVGImage.SVG;assembly=DotNetProjects.SVGImage"
...
<svg1:SVGImage Name="mySVGImage" Source="/MyDemoApp;component/Resources/MyImage.svg"/>
...

That's all.

See:

Python base64 data decode

Note Slipstream's response, that base64.b64encode and base64.b64decode need bytes-like object, not string.

>>> import base64
>>> a = '{"name": "John", "age": 42}'
>>> base64.b64encode(a)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/usr/lib/python3.6/base64.py", line 58, in b64encode
    encoded = binascii.b2a_base64(s, newline=False)
TypeError: a bytes-like object is required, not 'str'

Get difference between two lists

Let's say we have two lists

list1 = [1, 3, 5, 7, 9]
list2 = [1, 2, 3, 4, 5]

we can see from the above two lists that items 1, 3, 5 exist in list2 and items 7, 9 do not. On the other hand, items 1, 3, 5 exist in list1 and items 2, 4 do not.

What is the best solution to return a new list containing items 7, 9 and 2, 4?

All answers above find the solution, now whats the most optimal?

def difference(list1, list2):
    new_list = []
    for i in list1:
        if i not in list2:
            new_list.append(i)

    for j in list2:
        if j not in list1:
            new_list.append(j)
    return new_list

versus

def sym_diff(list1, list2):
    return list(set(list1).symmetric_difference(set(list2)))

Using timeit we can see the results

t1 = timeit.Timer("difference(list1, list2)", "from __main__ import difference, 
list1, list2")
t2 = timeit.Timer("sym_diff(list1, list2)", "from __main__ import sym_diff, 
list1, list2")

print('Using two for loops', t1.timeit(number=100000), 'Milliseconds')
print('Using two for loops', t2.timeit(number=100000), 'Milliseconds')

returns

[7, 9, 2, 4]
Using two for loops 0.11572412995155901 Milliseconds
Using symmetric_difference 0.11285737506113946 Milliseconds

Process finished with exit code 0

How do I use IValidatableObject?

Just to add a couple of points:

Because the Validate() method signature returns IEnumerable<>, that yield return can be used to lazily generate the results - this is beneficial if some of the validation checks are IO or CPU intensive.

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
    if (this.Enable)
    {
        // ...
        if (this.Prop1 > this.Prop2)
        {
            yield return new ValidationResult("Prop1 must be larger than Prop2");
        }

Also, if you are using MVC ModelState, you can convert the validation result failures to ModelState entries as follows (this might be useful if you are doing the validation in a custom model binder):

var resultsGroupedByMembers = validationResults
    .SelectMany(vr => vr.MemberNames
                        .Select(mn => new { MemberName = mn ?? "", 
                                            Error = vr.ErrorMessage }))
    .GroupBy(x => x.MemberName);

foreach (var member in resultsGroupedByMembers)
{
    ModelState.AddModelError(
        member.Key,
        string.Join(". ", member.Select(m => m.Error)));
}

Fast way of finding lines in one file that are not in another?

If you're short of "fancy tools", e.g. in some minimal Linux distribution, there is a solution with just cat, sort and uniq:

cat includes.txt excludes.txt excludes.txt | sort | uniq --unique

Test:

seq 1 1 7 | sort --random-sort > includes.txt
seq 3 1 9 | sort --random-sort > excludes.txt
cat includes.txt excludes.txt excludes.txt | sort | uniq --unique

# Output:
1
2    

This is also relatively fast, compared to grep.

Check if a String contains numbers Java

If you want to extract the first number out of the input string, you can do-

public static String extractNumber(final String str) {                
    
    if(str == null || str.isEmpty()) return "";
    
    StringBuilder sb = new StringBuilder();
    boolean found = false;
    for(char c : str.toCharArray()){
        if(Character.isDigit(c)){
            sb.append(c);
            found = true;
        } else if(found){
            // If we already found a digit before and this char is not a digit, stop looping
            break;                
        }
    }
    
    return sb.toString();
}

Examples:

For input "123abc", the method above will return 123.

For "abc1000def", 1000.

For "555abc45", 555.

For "abc", will return an empty string.

How to block calls in android

It is possible and you don't need to code it on your own.

Just set the ringer volume to zero and vibration to none if incomingNumber equals an empty string. Thats it ...

Its just done for you with the application Nostalk from Android Market. Just give it a try ...

How do I ignore files in Subversion?

  1. open you use JetBrains Product(i.e. Pycharm)
  2. then click the 'commit' button on the top toolbar or use shortcut 'ctrl + k' screenshot_toolbar
  3. on the commit interface, move your unwanted files to another change list as follows. screenshot_commit_change
  4. next time you can only commit default change list.

How to convert numbers to alphabet?

If you have a number, for example 65, and if you want to get the corresponding ASCII character, you can use the chr function, like this

>>> chr(65)
'A'

similarly if you have 97,

>>> chr(97)
'a'

EDIT: The above solution works for 8 bit characters or ASCII characters. If you are dealing with unicode characters, you have to specify unicode value of the starting character of the alphabet to ord and the result has to be converted using unichr instead of chr.

>>> print unichr(ord(u'\u0B85'))
?

>>> print unichr(1 + ord(u'\u0B85'))
?

NOTE: The unicode characters used here are of the language called "Tamil", my first language. This is the unicode table for the same http://www.unicode.org/charts/PDF/U0B80.pdf

How to change the URI (URL) for a remote Git repository?

In the Git Bash, enter the command:

git remote set-url origin https://NewRepoLink.git

Enter the Credentials

Done

UILabel with text of two different colors

Anups answer in swift. Can be reused from any class.

In swift file

extension NSMutableAttributedString {

    func setColorForStr(textToFind: String, color: UIColor) {

        let range = self.mutableString.rangeOfString(textToFind, options:NSStringCompareOptions.CaseInsensitiveSearch);
        if range.location != NSNotFound {
            self.addAttribute(NSForegroundColorAttributeName, value: color, range: range);
        }

    }
}

In Some view controller

let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: self.labelShopInYourNetwork.text!);
attributedString.setColorForStr("YOUR NETWORK", color: UIColor(red: 0.039, green: 0.020, blue: 0.490, alpha: 1.0));
self.labelShopInYourNetwork.attributedText = attributedString;

Read text from response

response.GetResponseStream() should be used to return the response stream. And don't forget to close the Stream and Response objects.

Adding simple legend to plot in R

Take a look at ?legend and try this:

legend('topright', names(a)[-1] , 
   lty=1, col=c('red', 'blue', 'green',' brown'), bty='n', cex=.75)

enter image description here

Is it possible in Java to check if objects fields are null and then add default value to all those attributes?

You can create a function that returns a boolean value and checks every attribute. You can call that function to do the job for you.

Alternatively, you can initialize the object with default values. That way there is no need for you to do any checking.

DTO pattern: Best way to copy properties between two objects

You can use Apache Commmons Beanutils. The API is

org.apache.commons.beanutils.PropertyUtilsBean.copyProperties(Object dest, Object orig).

It copies property values from the "origin" bean to the "destination" bean for all cases where the property names are the same.

Now I am going to off topic. Using DTO is mostly considered an anti-pattern in EJB3. If your DTO and your domain objects are very alike, there is really no need to duplicate codes. DTO still has merits, especially for saving network bandwidth when remote access is involved. I do not have details about your application architecture, but if the layers you talked about are logical layers and does not cross network, I do not see the need for DTO.

How can I make space between two buttons in same div?

I ended up doing something similar to what mark dibe did, but I needed to figure out the spacing for a slightly different manner.

The col-x classes in bootstrap can be an absolute lifesaver. I ended up doing something similar to this:

<div class="row col-12">
    <div class="col-3">Title</div>
</div>
<div class="row col-12">
    <div class="col-3">Bootstrap Switch</div>
<div>

This allowed me to align titles and input switches in a nicely spaced manner. The same idea can be applied to the buttons and allow you to stop the buttons from touching.

(Side note: I wanted this to be a comment on the above link, but my reputation is not high enough)

VBA: Convert Text to Number

This converts all text in columns of an Excel Workbook to numbers.

Sub ConvertTextToNumbers()
Dim wBook As Workbook
Dim LastRow As Long, LastCol As Long
Dim Rangetemp As Range

'Enter here the path of your workbook
Set wBook = Workbooks.Open("yourWorkbook")
LastRow = Cells.Find(What:="*", After:=Range("A1"), SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
LastCol = Cells.Find(What:="*", After:=Range("A1"), SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column

For c = 1 To LastCol
Set Rangetemp = Cells(c).EntireColumn
Rangetemp.TextToColumns DataType:=xlDelimited, _
    TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
    Semicolon:=False, Comma:=False, Space:=False, Other:=False, FieldInfo _
    :=Array(1, 1), TrailingMinusNumbers:=True
Next c
End Sub

Websocket onerror - how to read error description?

The error Event the onerror handler receives is a simple event not containing such information:

If the user agent was required to fail the WebSocket connection or the WebSocket connection is closed with prejudice, fire a simple event named error at the WebSocket object.

You may have better luck listening for the close event, which is a CloseEvent and indeed has a CloseEvent.code property containing a numerical code according to RFC 6455 11.7 and a CloseEvent.reason string property.

Please note however, that CloseEvent.code (and CloseEvent.reason) are limited in such a way that network probing and other security issues are avoided.

Array Index Out of Bounds Exception (Java)

import java.io.*;
import java.util.Scanner;
class ar1 {
    public static void main(String[] args) {
        //Scanner sc=new Scanner(System.in);
        int[] a={10,20,30,40,12,32};
        int bi=0,sm=0;
        //bi=sc.nextInt();
        //sm=sc.nextInt();
        for(int i=0;i<=a.length-1;i++) {
            if(a[i]>a[i+1]) 
                bi=a[i];

            if(a[i]<a[i+1])
                sm=a[i];
        }
        System.out.println("big"+bi+"small"+sm);
    }
}

Netbeans - Error: Could not find or load main class

Try to rename the package name and the class/jframe names... The clean and build the application.

  1. Right Click on the package name
  2. Go to Refactor
  3. Select Rename
  4. Give it a meaningful name, preferably all in small letters
  5. Click on Refactor

    Do the same for the class/jframe names.

  6. Last Select Run from Menu 7.Select Clean and build main project

That should do it!!! All best

Jackson serialization: ignore empty values (or null)

Code bellow may help if you want to exclude boolean type from serialization either:

@JsonInclude(JsonInclude.Include.NON_ABSENT)

How to turn off Wifi via ADB?

I can just do:

settings put global wifi_on 0
settings put global wifi_scan_always_enabled 0

Sometimes, if done during boot (i.e. to fix bootloop such as this), it doesn't apply well and you can proceed also enabling airplane mode first:

settings put global airplane_mode_on 1
settings put global wifi_on 0
settings put global wifi_scan_always_enabled 0

Other option is to force this with:

while true; do settings put global wifi_on 0; done

Tested in Android 7 on LG G5 (SE) with (unrooted) stock mod.

How to revert multiple git commits?

None of those worked for me, so I had three commits to revert (the last three commits), so I did:

git revert HEAD
git revert HEAD~2
git revert HEAD~4
git rebase -i HEAD~3 # pick, squash, squash

Worked like a charm :)

PowerShell: Run command from script's directory

Do you mean you want the script's own path so you can reference a file next to the script? Try this:

$scriptpath = $MyInvocation.MyCommand.Path
$dir = Split-Path $scriptpath
Write-host "My directory is $dir"

You can get a lot of info from $MyInvocation and its properties.

If you want to reference a file in the current working directory, you can use Resolve-Path or Get-ChildItem:

$filepath = Resolve-Path "somefile.txt"

EDIT (based on comment from OP):

# temporarily change to the correct folder
Push-Location $folder

# do stuff, call ant, etc

# now back to previous directory
Pop-Location

There's probably other ways of achieving something similar using Invoke-Command as well.

Redraw datatables after using ajax to refresh the table content?

In the initialization use:

"fnServerData": function ( sSource, aoData, fnCallback ) {
                    //* Add some extra data to the sender *
                    newData = aoData;
                    newData.push({ "name": "key", "value": $('#value').val() });

                    $.getJSON( sSource, newData, function (json) {
                        //* Do whatever additional processing you want on the callback, then tell DataTables *
                        fnCallback(json);
                    } );
                },

And then just use:

$("#table_id").dataTable().fnDraw();

The important thing in the fnServerData is:

    newData = aoData;
    newData.push({ "name": "key", "value": $('#value').val() });

if you push directly to aoData, the change is permanent the first time you draw the table and fnDraw don't work the way you want.

Check if inputs form are empty jQuery

You could do it like this :

bool areFieldEmpty = YES;
//Label to leave the loops
outer_loop;

//For each input (except of submit) in your form
$('form input[type!=submit]').each(function(){
   //If the field's empty
   if($(this).val() != '')
   {
      //Mark it
      areFieldEmpty = NO;
      //Then leave all the loops
      break outer_loop;
   }
});

//Then test your bool 

What is the difference between the 'COPY' and 'ADD' commands in a Dockerfile?

Important Note

I had to COPY and untar java package in my docker image. When I compared the docker image size created using ADD it was 180MB bigger than the one created using COPY, tar -xzf *.tar.gz and rm *.tar.gz

This means that although ADD removes the tar file, it is still kept somewhere. And its making the image bigger!!

How to generate a GUID in Oracle?

you can use function bellow in order to generate your UUID

create or replace FUNCTION RANDOM_GUID
    RETURN VARCHAR2 IS

    RNG    NUMBER;
    N      BINARY_INTEGER;
    CCS    VARCHAR2 (128);
    XSTR   VARCHAR2 (4000) := NULL;
  BEGIN
    CCS := '0123456789' || 'ABCDEF';
    RNG := 15;

    FOR I IN 1 .. 32 LOOP
      N := TRUNC (RNG * DBMS_RANDOM.VALUE) + 1;
      XSTR := XSTR || SUBSTR (CCS, N, 1);
    END LOOP;

    RETURN SUBSTR(XSTR, 1, 4) || '-' ||
        SUBSTR(XSTR, 5, 4)        || '-' ||
        SUBSTR(XSTR, 9, 4)        || '-' ||
        SUBSTR(XSTR, 13,4)        || '-' ||
        SUBSTR(XSTR, 17,4)        || '-' ||
        SUBSTR(XSTR, 21,4)        || '-' ||
        SUBSTR(XSTR, 24,4)        || '-' ||
        SUBSTR(XSTR, 28,4);
END RANDOM_GUID;

Example of GUID genedrated by the function above:
8EA4-196D-BC48-9793-8AE8-5500-03DC-9D04

Autoincrement VersionCode with gradle extra properties

Another way of getting a versionCode automatically is setting versionCode to the number of commits in the checked out git branch. It accomplishes following objectives:

  1. versionCode is generated automatically and consistently on any machine (including a Continuous Integration and/or Continuous Deployment server).
  2. App with this versionCode is submittable to GooglePlay.
  3. Doesn't rely on any files outside of repo.
  4. Doesn't push anything to the repo
  5. Can be manually overridden, if needed

Using gradle-git library to accomplish the above objectives. Add code below to your build.gradle file the /app directory:

import org.ajoberstar.grgit.Grgit

repositories {
    mavenCentral()
}

buildscript {
    repositories {
        mavenCentral()
    }

    dependencies {
        classpath 'org.ajoberstar:grgit:1.5.0'
    }
}

android {
/*
    if you need a build with a custom version, just add it here, but don't commit to repo,
    unless you'd like to disable versionCode to be the number of commits in the current branch.

    ex. project.ext.set("versionCodeManualOverride", 123)
*/
    project.ext.set("versionCodeManualOverride", null)

    defaultConfig {
        versionCode getCustomVersionCode()
    }
}

def getCustomVersionCode() {

    if (project.versionCodeManualOverride != null) {
        return project.versionCodeManualOverride
    }

    // current dir is <your proj>/app, so it's likely that all your git repo files are in the dir
    // above.
    ext.repo = Grgit.open(project.file('..'))

    // should result in the same value as running
    // git rev-list <checked out branch name> | wc -l
    def numOfCommits = ext.repo.log().size()
    return numOfCommits
}

NOTE: For this method to work, it's best to only deploy to Google Play Store from the same branch (ex. master).

What is the meaning of "$" sign in JavaScript

As all the other answers say; it can be almost anything but is usually "JQuery".

However, in ES6 it is a string interpolation operator in a template "literal" eg.

var s = "new" ; // you can put whatever you think appropriate here.
var s2 = `There are so many ${s} ideas these days !!` ; //back-ticks not quotes
console.log(s2) ;

result:

There are so many new ideas these days !!

How to do fade-in and fade-out with JavaScript and CSS

I like Ibu's one but, I think I have a better solution using his idea.

//Fade In.
element.style.opacity = 0;
var Op1 = 0;
var Op2 = 1;
var foo1, foo2;
foo1 = setInterval(Timer1, 20);
function Timer1()
{
    element.style.opacity = Op1;
    Op1 = Op1 + .01;
    console.log(Op1); //Option, but I recommend it for testing purposes.
    if (Op1 > 1)
    {
        clearInterval(foo1);
        foo2 = setInterval(Timer3, 20);
    }
}

This solution uses a additional equation unlike Ibu's solution, which used a multiplicative equation. The way it works is it takes a time increment (t), an opacity increment (o), and a opacity limit (l) in the equation, which is: (T = time of fade in miliseconds) [T = (l/o)*t]. the "20" represents the time increments or intervals (t), the ".01" represents the opacity increments (o), and the 1 represents the opacity limit (l). When you plug the numbers in the equation you get 2000 milliseconds (or 2 seconds). Here is the console log:

0.01
0.02
0.03
0.04
0.05
0.060000000000000005
0.07
0.08
0.09
0.09999999999999999
0.10999999999999999
0.11999999999999998
0.12999999999999998
0.13999999999999999
0.15
0.16
0.17
0.18000000000000002
0.19000000000000003
0.20000000000000004
0.21000000000000005
0.22000000000000006
0.23000000000000007
0.24000000000000007
0.25000000000000006
0.26000000000000006
0.2700000000000001
0.2800000000000001
0.2900000000000001
0.3000000000000001
0.3100000000000001
0.3200000000000001
0.3300000000000001
0.34000000000000014
0.35000000000000014
0.36000000000000015
0.37000000000000016
0.38000000000000017
0.3900000000000002
0.4000000000000002
0.4100000000000002
0.4200000000000002
0.4300000000000002
0.4400000000000002
0.45000000000000023
0.46000000000000024
0.47000000000000025
0.48000000000000026
0.49000000000000027
0.5000000000000002
0.5100000000000002
0.5200000000000002
0.5300000000000002
0.5400000000000003
0.5500000000000003
0.5600000000000003
0.5700000000000003
0.5800000000000003
0.5900000000000003
0.6000000000000003
0.6100000000000003
0.6200000000000003
0.6300000000000003
0.6400000000000003
0.6500000000000004
0.6600000000000004
0.6700000000000004
0.6800000000000004
0.6900000000000004
0.7000000000000004
0.7100000000000004
0.7200000000000004
0.7300000000000004
0.7400000000000004
0.7500000000000004
0.7600000000000005
0.7700000000000005
0.7800000000000005
0.7900000000000005
0.8000000000000005
0.8100000000000005
0.8200000000000005
0.8300000000000005
0.8400000000000005
0.8500000000000005
0.8600000000000005
0.8700000000000006
0.8800000000000006
0.8900000000000006
0.9000000000000006
0.9100000000000006
0.9200000000000006
0.9300000000000006
0.9400000000000006
0.9500000000000006
0.9600000000000006
0.9700000000000006
0.9800000000000006
0.9900000000000007
1.0000000000000007
1.0100000000000007

Notice how the opacity follows the opacity increment amount of .01 just like in the code. If you use the code Ibu made,

//I made slight edits but keeped the ESSENTIAL stuff in it.
var op = 0.01;  // initial opacity
var timer = setInterval(function () {
    if (op >= 1){
        clearInterval(timer);
    }
    element.style.opacity = op;
    op += op * 0.1;
}, 20);

you will get these numbers (or something similar) in you console log. Here is what I got.

0.0101
0.010201
0.01030301
0.0104060401
0.010510100501
0.010615201506009999
0.0107213535210701
0.0108285670562808
0.010936852726843608
0.011046221254112044
0.011156683466653165
0.011268250301319695
0.011380932804332892
0.01149474213237622
0.011609689553699983
0.011725786449236983
0.011843044313729352
0.011961474756866645
0.012081089504435313
0.012201900399479666
0.012323919403474463
0.012447158597509207
0.0125716301834843
0.012697346485319142
0.012824319950172334
0.012952563149674056
0.013082088781170797
0.013212909668982505
0.01334503876567233
0.013478489153329052
0.013613274044862343
0.013749406785310966
0.013886900853164076
0.014025769861695717
0.014166027560312674
0.014307687835915801
0.01445076471427496
0.01459527236141771
0.014741225085031886
0.014888637335882205
0.015037523709241028
0.015187898946333437
0.01533977793579677
0.015493175715154739
0.015648107472306286
0.01580458854702935
0.015962634432499644
0.01612226077682464
0.016283483384592887
0.016446318218438817
0.016610781400623206
0.01677688921462944
0.016944658106775732
0.01711410468784349
0.017285245734721923
0.017458098192069144
0.017632679173989835
0.01780900596572973
0.01798709602538703
0.018166966985640902
0.01834863665549731
0.018532123022052285
0.018717444252272807
0.018904618694795535
0.01909366488174349
0.019284601530560927
0.019477447545866538
0.0196722220213252
0.019868944241538455
0.02006763368395384
0.02026831002079338
0.020470993121001313
0.020675703052211326
0.02088246008273344
0.021091284683560776
0.021302197530396385
0.02151521950570035
0.021730371700757353
0.021947675417764927
0.022167152171942577
0.022388823693662
0.022612711930598623
0.022838839049904608
0.023067227440403654
0.02329789971480769
0.023530878711955767
0.023766187499075324
0.024003849374066077
0.02424388786780674
0.024486326746484807
0.024731190013949654
0.024978501914089152
0.025228286933230044
0.025480569802562344
0.025735375500587968
0.025992729255593847
0.026252656548149785
0.026515183113631283
0.026780334944767597
0.027048138294215273
0.027318619677157426
0.027591805873929
0.02786772393266829
0.028146401171994972
0.028427865183714922
0.02871214383555207
0.02899926527390759
0.029289257926646668
0.029582150505913136
0.029877972010972267
0.030176751731081992
0.030478519248392812
0.03078330444087674
0.031091137485285508
0.031402048860138365
0.03171606934873975
0.03203323004222715
0.03235356234264942
0.03267709796607591
0.03300386894573667
0.03333390763519403
0.03366724671154597
0.03400391917866143
0.03434395837044805
0.03468739795415253
0.03503427193369406
0.035384614653031
0.035738460799561306
0.03609584540755692
0.03645680386163249
0.03682137190024882
0.03718958561925131
0.03756148147544382
0.03793709629019826
0.03831646725310024
0.038699631925631243
0.03908662824488755
0.039477494527336426
0.03987226947260979
0.040270992167335894
0.04067370208900925
0.04108043910989934
0.04149124350099834
0.04190615593600832
0.042325217495368404
0.04274846967032209
0.04317595436702531
0.04360771391069556
0.044043791049802515
0.04448422896030054
0.04492907124990354
0.04537836196240258
0.045832145582026605
0.04629046703784687
0.04675337170822534
0.047220905425307595
0.04769311447956067
0.04817004562435628
0.04865174608059984
0.04913826354140584
0.0496296461768199
0.0501259426385881
0.05062720206497398
0.05113347408562372
0.05164480882647996
0.05216125691474476
0.05268286948389221
0.053209698178731134
0.05374179516051845
0.05427921311212363
0.05482200524324487
0.05537022529567732
0.05592392754863409
0.056483166824120426
0.05704799849236163
0.05761847847728525
0.0581946632620581
0.05877660989467868
0.059364375993625464
0.05995801975356172
0.060557599951097336
0.06116317595060831
0.06177480771011439
0.06239255578721554
0.0630164813450877
0.06364664615853857
0.06428311262012396
0.0649259437463252
0.06557520318378844
0.06623095521562633
0.0668932647677826
0.06756219741546042
0.06823781938961503
0.06892019758351117
0.06960939955934628
0.07030549355493974
0.07100854849048914
0.07171863397539403
0.07243582031514798
0.07316017851829945
0.07389178030348245
0.07463069810651728
0.07537700508758245
0.07613077513845827
0.07689208288984285
0.07766100371874128
0.0784376137559287
0.07922198989348798
0.08001420979242287
0.0808143518903471
0.08162249540925057
0.08243872036334307
0.0832631075669765
0.08409573864264626
0.08493669602907272
0.08578606298936345
0.08664392361925709
0.08751036285544966
0.08838546648400417
0.08926932114884421
0.09016201436033265
0.09106363450393598
0.09197427084897535
0.0928940135574651
0.09382295369303975
0.09476118322997015
0.09570879506226986
0.09666588301289256
0.09763254184302148
0.0986088672614517
0.09959495593406621
0.10059090549340688
0.10159681454834095
0.10261278269382436
0.1036389105207626
0.10467529962597022
0.10572205262222992
0.10677927314845222
0.10784706587993674
0.10892553653873611
0.11001479190412347
0.1111149398231647
0.11222608922139635
0.11334835011361032
0.11448183361474643
0.11562665195089389
0.11678291847040283
0.11795074765510685
0.11913025513165793
0.1203215576829745
0.12152477325980425
0.12274002099240229
0.12396742120232632
0.12520709541434957
0.12645916636849308
0.127723758032178
0.12900099561249978
0.13029100556862477
0.13159391562431103
0.13290985478055414
0.1342389533283597
0.13558134286164328
0.1369371562902597
0.1383065278531623
0.13968959313169393
0.14108648906301088
0.142497353953641
0.1439223274931774
0.14536155076810917
0.14681516627579025
0.14828331793854815
0.14976615111793362
0.15126381262911295
0.15277645075540408
0.15430421526295812
0.1558472574155877
0.15740572998974356
0.158979787289641
0.1605695851625374
0.16217528101416276
0.16379703382430438
0.16543500416254742
0.1670893542041729
0.16876024774621462
0.17044785022367676
0.17215232872591352
0.17387385201317265
0.17561259053330439
0.17736871643863744
0.1791424036030238
0.18093382763905405
0.1827431659154446
0.18457059757459904
0.18641630355034502
0.1882804665858485
0.19016327125170698
0.19206490396422404
0.19398555300386627
0.19592540853390494
0.197884662619244
0.19986350924543644
0.20186214433789082
0.20388076578126973
0.20591957343908243
0.20797876917347324
0.21005855686520797
0.21215914243386005
0.21428073385819865
0.21642354119678064
0.21858777660874845
0.22077365437483593
0.2229813909185843
0.22521120482777013
0.22746331687604782
0.2297379500448083
0.23203532954525638
0.23435568284070896
0.23669923966911605
0.2390662320658072
0.24145689438646528
0.24387146333032994
0.24631017796363325
0.24877327974326957
0.25126101254070227
0.2537736226661093
0.2563113588927704
0.2588744724816981
0.26146321720651505
0.2640778493785802
0.266718627872366
0.26938581415108964
0.27207967229260055
0.27480046901552657
0.27754847370568186
0.28032395844273866
0.28312719802716607
0.28595847000743774
0.2888180547075121
0.2917062352545872
0.2946232976071331
0.2975695305832044
0.3005452258890364
0.3035506781479268
0.3065861849294061
0.3096520467787002
0.3127485672464872
0.31587605291895204
0.31903481344814155
0.322225161582623
0.3254474131984492
0.3287018873304337
0.33198890620373805
0.33530879526577545
0.3386618832184332
0.34204850205061754
0.3454689870711237
0.34892367694183496
0.35241291371125333
0.35593704284836586
0.3594964132768495
0.363091377409618
0.3667222911837142
0.3703895140955513
0.37409340923650686
0.37783434332887195
0.38161268676216065
0.38542881362978226
0.3892831017660801
0.3931759327837409
0.3971076921115783
0.40107876903269407
0.405089556723021
0.4091404522902512
0.4132318568131537
0.41736417538128523
0.4215378171350981
0.42575319530644906
0.43001072725951356
0.43431083453210867
0.43865394287742976
0.4430404823062041
0.44747088712926614
0.4519455960005588
0.45646505196056436
0.46102970248017
0.4656399995049717
0.47029639950002144
0.47499936349502164
0.47974935712997185
0.48454685070127157
0.4893923192082843
0.4942862424003671
0.4992291048243708
0.5042213958726145
0.5092636098313407
0.5143562459296541
0.5194998083889507
0.5246948064728402
0.5299417545375685
0.5352411720829442
0.5405935838037736
0.5459995196418114
0.5514595148382295
0.5569741099866118
0.5625438510864779
0.5681692895973427
0.5738509824933161
0.5795894923182493
0.5853853872414317
0.5912392411138461
0.5971516335249846
0.6031231498602344
0.6091543813588367
0.615245925172425
0.6213983844241493
0.6276123682683908
0.6338884919510748
0.6402273768705855
0.6466296506392913
0.6530959471456843
0.6596269066171412
0.6662231756833126
0.6728854074401457
0.6796142615145472
0.6864104041296927
0.6932745081709896
0.7002072532526995
0.7072093257852266
0.7142814190430788
0.7214242332335097
0.7286384755658448
0.7359248603215033
0.7432841089247183
0.7507169500139654
0.7582241195141051
0.7658063607092461
0.7734644243163386
0.7811990685595019
0.789011059245097
0.7969011698375479
0.8048701815359234
0.8129188833512826
0.8210480721847955
0.8292585529066434
0.8375511384357098
0.8459266498200669
0.8543859163182677
0.8629297754814503
0.8715590732362648
0.8802746639686274
0.8890774106083137
0.8979681847143969
0.9069478665615408
0.9160173452271562
0.9251775186794278
0.9344292938662221
0.9437735868048843
0.9532113226729332
0.9627434358996625
0.9723708702586591
0.9820945789612456
0.9919155247508581
1.0018346799983666
1.0118530267983503

Notice that there is no discernible pattern. If you ran Ibu's code, you would never know how long the fade was. You would have to grab a timer and guess and check 2 seconds. Nonetheless, Ibu's code did make a pretty nice fade in (it probably works for fade out. I don't know because I didn't use a fade out yet). My code will also work for a fade out. Let's just say you wanted 2 seconds for a fade out. You can do that with my code. Here is how it would look:

//Fade out. (Continued from the fade in.
function Timer2()
{
    element.style.opacity = Op2;
    Op2 = Op2 - .01;
    console.log(Op2); //Option, but I recommend it for testing purposes.
    if (Op2 < 0)
    { 
        clearInterval(foo2);
    }
}

All I did was change the opacity to 1 (or fully opaque). I changed the opacity increment to -.01 so it would start turning invisible. Lastly, I changed the opacity limit to 0. When it hits the opacity limit, the timer will stop. Same as the last one, except it used 1 instead of 0. When you run the code, here is what the console log should relatively look like.

.99
0.98
0.97
0.96
0.95
0.94
0.9299999999999999
0.9199999999999999
0.9099999999999999
0.8999999999999999
0.8899999999999999
0.8799999999999999
0.8699999999999999
0.8599999999999999
0.8499999999999999
0.8399999999999999
0.8299999999999998
0.8199999999999998
0.8099999999999998
0.7999999999999998
0.7899999999999998
0.7799999999999998
0.7699999999999998
0.7599999999999998
0.7499999999999998
0.7399999999999998
0.7299999999999998
0.7199999999999998
0.7099999999999997
0.6999999999999997
0.6899999999999997
0.6799999999999997
0.6699999999999997
0.6599999999999997
0.6499999999999997
0.6399999999999997
0.6299999999999997
0.6199999999999997
0.6099999999999997
0.5999999999999996
0.5899999999999996
0.5799999999999996
0.5699999999999996
0.5599999999999996
0.5499999999999996
0.5399999999999996
0.5299999999999996
0.5199999999999996
0.5099999999999996
0.49999999999999956
0.48999999999999955
0.47999999999999954
0.46999999999999953
0.4599999999999995
0.4499999999999995
0.4399999999999995
0.4299999999999995
0.4199999999999995
0.4099999999999995
0.39999999999999947
0.38999999999999946
0.37999999999999945
0.36999999999999944
0.35999999999999943
0.3499999999999994
0.3399999999999994
0.3299999999999994
0.3199999999999994
0.3099999999999994
0.2999999999999994
0.28999999999999937
0.27999999999999936
0.26999999999999935
0.25999999999999934
0.24999999999999933
0.23999999999999932
0.22999999999999932
0.2199999999999993
0.2099999999999993
0.1999999999999993
0.18999999999999928
0.17999999999999927
0.16999999999999926
0.15999999999999925
0.14999999999999925
0.13999999999999924
0.12999999999999923
0.11999999999999923
0.10999999999999924
0.09999999999999924
0.08999999999999925
0.07999999999999925
0.06999999999999926
0.059999999999999255
0.04999999999999925
0.03999999999999925
0.02999999999999925
0.019999999999999248
0.009999999999999247
-7.528699885739343e-16
-0.010000000000000753

As you can see, the .01 pattern still exists in the fade out. Both fades are smooth and precise. I hope these codes helped you or gave you insight on the topic. If you have any additions or suggestions let me know. Thank you for taking the time to view this!

How can I make visible an invisible control with jquery? (hide and show not work)

Here's some code I use to deal with this.

First we show the element, which will typically set the display type to "block" via .show() function, and then set the CSS rule to "visible":

jQuery( '.element' ).show().css( 'visibility', 'visible' );

Or, assuming that the class that is hiding the element is called hidden, such as in Twitter Bootstrap, toggleClass() can be useful:

jQuery( '.element' ).toggleClass( 'hidden' );

Lastly, if you want to chain functions, perhaps with fancy with a fading effect, you can do it like so:

jQuery( '.element' ).css( 'visibility', 'visible' ).fadeIn( 5000 );

Incrementing a variable inside a Bash loop

while read -r country _; do
  if [[ $country = 'US' ]]; then
    ((USCOUNTER++))
    echo "US counter $USCOUNTER"
  fi
done < "$FILE"

Is it possible to style a select box?

You can style to some degree with CSS by itself

select {
    background: red;
    border: 2px solid pink;
}

But this is entirely up to the browser. Some browsers are stubborn.

However, this will only get you so far, and it doesn't always look very good. For complete control, you'll need to replace a select via jQuery with a widget of your own that emulates the functionality of a select box. Ensure that when JS is disabled, a normal select box is in its place. This allows more users to use your form, and it helps with accessibility.

How do I name the "row names" column in r

It sounds like you want to convert the rownames to a proper column of the data.frame. eg:

# add the rownames as a proper column
myDF <- cbind(Row.Names = rownames(myDF), myDF)
myDF

#           Row.Names id val vr2
# row_one     row_one  A   1  23
# row_two     row_two  A   2  24
# row_three row_three  B   3  25
# row_four   row_four  C   4  26

If you want to then remove the original rownames:

rownames(myDF) <- NULL
myDF
#   Row.Names id val vr2
# 1   row_one  A   1  23
# 2   row_two  A   2  24
# 3 row_three  B   3  25
# 4  row_four  C   4  26


Alternatively, if all of your data is of the same class (ie, all numeric, or all string), you can convert to Matrix and name the dimnames

myMat <- as.matrix(myDF)
names(dimnames(myMat)) <- c("Names.of.Rows", "")
myMat

# Names.of.Rows id  val vr2 
#   row_one   "A" "1" "23"
#   row_two   "A" "2" "24"
#   row_three "B" "3" "25"
#   row_four  "C" "4" "26"

How to install ADB driver for any android device?

You don't really need to install or use any third party tools.

The drivers located in ...\Android\Sdk\extras\google\usb_driver work just fine.

Step 1: In Device Manager, Right click on the malfunctioning Android ADB Interface driver

Step 2: Select Update Driver Software

Step 3: Select Browse my computer for driver software

Step 4: Select Let me pick from a list of device drivers on my computer

Step 5: Select Have Disk

This window pops up:

enter image description here

Step 6: Copy the location of the Google USB Driver (...\Android\Sdk\extras\google\usb_driver) or browse to it.

Step 7: Click Ok

This window pops up:

enter image description here

Step 8: Select Android ADB Interface and click Next

The window below pops up with a warning:

enter image description here

That's it. You driver installation will start and in a few seconds, you should be able to see your device

Create XML file using java

I liked the Xembly syntax, but it is not a statically typed API. You can get this with XMLBeam:

// Declare a projection
public interface Projection {

    @XBWrite("/root/order/@id")
    Projection setID(int id);

    @XBWrite("/root/order")
    Projection setValue(String value);
}

public static void main(String[] args) {
    // create a projector
    XBProjector projector = new XBProjector();

    // use it to create a projection instance
    Projection projection = projector.projectEmptyDocument(Projection.class);

    // You get a fluent API, with java types in parameters 
    projection.setID(553).setValue("$140.00");

    // Use the projector again to do IO stuff or create an XML-string
    projector.toXMLString(projection);
}

My experience is that this works great even when the XML gets more complicated. You can just decouple the XML structure from your java code structure.

How to delete all files and folders in a directory?

DirectoryInfo Folder = new DirectoryInfo(Server.MapPath(path)); 
if (Folder .Exists)
{
    foreach (FileInfo fl in Folder .GetFiles())
    {
        fl.Delete();
    }

    Folder .Delete();
}

LaTeX package for syntax highlighting of code in various languages

I would suggest defining your own package based on the following tex code; this gives you complete freedom. http://ubuntuforums.org/archive/index.php/t-331602.html

Search All Fields In All Tables For A Specific Value (Oracle)

Quote:

I've tried using this statement below to find an appropriate column based on what I think it should be named but it returned no results.*

SELECT * from dba_objects WHERE
object_name like '%DTN%'

A column isn't an object. If you mean that you expect the column name to be like '%DTN%', the query you want is:

SELECT owner, table_name, column_name FROM all_tab_columns WHERE column_name LIKE '%DTN%';

But if the 'DTN' string is just a guess on your part, that probably won't help.

By the way, how certain are you that '1/22/2008P09RR8' is a value selected directly from a single column? If you don't know at all where it is coming from, it could be a concatenation of several columns, or the result of some function, or a value sitting in a nested table object. So you might be on a wild goose chase trying to check every column for that value. Can you not start with whatever client application is displaying this value and try to figure out what query it is using to obtain it?

Anyway, diciu's answer gives one method of generating SQL queries to check every column of every table for the value. You can also do similar stuff entirely in one SQL session using a PL/SQL block and dynamic SQL. Here's some hastily-written code for that:

    SET SERVEROUTPUT ON SIZE 100000

    DECLARE
      match_count INTEGER;
    BEGIN
      FOR t IN (SELECT owner, table_name, column_name
                  FROM all_tab_columns
                  WHERE owner <> 'SYS' and data_type LIKE '%CHAR%') LOOP

        EXECUTE IMMEDIATE
          'SELECT COUNT(*) FROM ' || t.owner || '.' || t.table_name ||
          ' WHERE '||t.column_name||' = :1'
          INTO match_count
          USING '1/22/2008P09RR8';

        IF match_count > 0 THEN
          dbms_output.put_line( t.table_name ||' '||t.column_name||' '||match_count );
        END IF;

      END LOOP;

    END;
    /

There are some ways you could make it more efficient too.

In this case, given the value you are looking for, you can clearly eliminate any column that is of NUMBER or DATE type, which would reduce the number of queries. Maybe even restrict it to columns where type is like '%CHAR%'.

Instead of one query per column, you could build one query per table like this:

SELECT * FROM table1
  WHERE column1 = 'value'
     OR column2 = 'value'
     OR column3 = 'value'
     ...
     ;

How to make Sonar ignore some classes for codeCoverage metric?

For me this worked (basically pom.xml level global properties):

<properties>
    <sonar.exclusions>**/Name*.java</sonar.exclusions>
</properties>

According to: http://docs.sonarqube.org/display/SONAR/Narrowing+the+Focus#NarrowingtheFocus-Patterns

It appears you can either end it with ".java" or possibly "*"

to get the java classes you're interested in.

Install numpy on python3.3 - Install pip for python3

In the solution below I used python3.4 as binary, but it's safe to use with any version or binary of python. it works fine on windows too (except the downloading pip with wget obviously but just save the file locally and run it with python).

This is great if you have multiple versions of python installed, so you can manage external libraries per python version.

So first, I'd recommend get-pip.py, it's great to install pip :

wget https://bootstrap.pypa.io/get-pip.py

Then you need to install pip for your version of python, I have python3.4 so for me this is the command :

python3.4 get-pip.py

Now pip is installed for python3.4 and in order to get libraries for python3.4 one need to call it within this version, like this :

python3.4 -m pip

So if you want to install numpy you would use :

python3.4 -m pip install numpy

Note that numpy is quite the heavy library. I thought my system was hanging and failing. But using the verbose option, you can see that the system is fine :

python3.4 -m pip install numpy -v

This may tell you that you lack python.h but you can easily get it :

On RHEL (Red hat, CentOS, Fedora) it would be something like this :

yum install python34-devel

On debian-like (Debian, Ubuntu, Kali, ...) :

apt-get install python34-dev

Then rerun this :

python3.4 -m pip install numpy -v

EntityType has no key defined error

There are several reasons this can happen. Some of these I found here, others I discovered on my own.

  • If the property is named something other than Id, you need to add the [Key] attribute to it.
  • The key needs to be a property, not a field.
  • The key needs to be public
  • The key needs to be a CLS-compliant type, meaning unsigned types like uint, ulong etc. are not allowed.
  • This error can also be caused by configuration mistakes.

Linking to an external URL in Javadoc?

This creates a "See Also" heading containing the link, i.e.:

/**
 * @see <a href="http://google.com">http://google.com</a>
 */

will render as:

See Also:
           http://google.com

whereas this:

/**
 * See <a href="http://google.com">http://google.com</a>
 */

will create an in-line link:

See http://google.com

How can I insert data into a MySQL database?

#Server Connection to MySQL:

import MySQLdb
conn = MySQLdb.connect(host= "localhost",
                  user="root",
                  passwd="newpassword",
                  db="engy1")
x = conn.cursor()

try:
   x.execute("""INSERT INTO anooog1 VALUES (%s,%s)""",(188,90))
   conn.commit()
except:
   conn.rollback()

conn.close()

edit working for me:

>>> import MySQLdb
>>> #connect to db
... db = MySQLdb.connect("localhost","root","password","testdb" )
>>> 
>>> #setup cursor
... cursor = db.cursor()
>>> 
>>> #create anooog1 table
... cursor.execute("DROP TABLE IF EXISTS anooog1")
__main__:2: Warning: Unknown table 'anooog1'
0L
>>> 
>>> sql = """CREATE TABLE anooog1 (
...          COL1 INT,  
...          COL2 INT )"""
>>> cursor.execute(sql)
0L
>>> 
>>> #insert to table
... try:
...     cursor.execute("""INSERT INTO anooog1 VALUES (%s,%s)""",(188,90))
...     db.commit()
... except:     
...     db.rollback()
... 
1L
>>> #show table
... cursor.execute("""SELECT * FROM anooog1;""")
1L
>>> print cursor.fetchall()
((188L, 90L),)
>>> 
>>> db.close()

table in mysql;

mysql> use testdb;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> SELECT * FROM anooog1;
+------+------+
| COL1 | COL2 |
+------+------+
|  188 |   90 |
+------+------+
1 row in set (0.00 sec)

mysql> 

MVVM Passing EventArgs As Command Parameter

Here is a version of @adabyron's answer that prevents the leaky EventArgs abstraction.

First, the modified EventToCommandBehavior class (now a generic abstract class and formatted with ReSharper code cleanup). Note the new GetCommandParameter virtual method and its default implementation:

public abstract class EventToCommandBehavior<TEventArgs> : Behavior<FrameworkElement>
    where TEventArgs : EventArgs
{
    public static readonly DependencyProperty EventProperty = DependencyProperty.Register("Event", typeof(string), typeof(EventToCommandBehavior<TEventArgs>), new PropertyMetadata(null, OnEventChanged));
    public static readonly DependencyProperty CommandProperty = DependencyProperty.Register("Command", typeof(ICommand), typeof(EventToCommandBehavior<TEventArgs>), new PropertyMetadata(null));
    public static readonly DependencyProperty PassArgumentsProperty = DependencyProperty.Register("PassArguments", typeof(bool), typeof(EventToCommandBehavior<TEventArgs>), new PropertyMetadata(false));
    private Delegate _handler;
    private EventInfo _oldEvent;

    public string Event
    {
        get { return (string)GetValue(EventProperty); }
        set { SetValue(EventProperty, value); }
    }

    public ICommand Command
    {
        get { return (ICommand)GetValue(CommandProperty); }
        set { SetValue(CommandProperty, value); }
    }

    public bool PassArguments
    {
        get { return (bool)GetValue(PassArgumentsProperty); }
        set { SetValue(PassArgumentsProperty, value); }
    }

    protected override void OnAttached()
    {
        AttachHandler(Event);
    }

    protected virtual object GetCommandParameter(TEventArgs e)
    {
        return e;
    }

    private void AttachHandler(string eventName)
    {
        _oldEvent?.RemoveEventHandler(AssociatedObject, _handler);

        if (string.IsNullOrEmpty(eventName))
        {
            return;
        }

        EventInfo eventInfo = AssociatedObject.GetType().GetEvent(eventName);

        if (eventInfo != null)
        {
            MethodInfo methodInfo = typeof(EventToCommandBehavior<TEventArgs>).GetMethod("ExecuteCommand", BindingFlags.Instance | BindingFlags.NonPublic);

            _handler = Delegate.CreateDelegate(eventInfo.EventHandlerType, this, methodInfo);
            eventInfo.AddEventHandler(AssociatedObject, _handler);
            _oldEvent = eventInfo;
        }
        else
        {
            throw new ArgumentException($"The event '{eventName}' was not found on type '{AssociatedObject.GetType().FullName}'.");
        }
    }

    private static void OnEventChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var behavior = (EventToCommandBehavior<TEventArgs>)d;

        if (behavior.AssociatedObject != null)
        {
            behavior.AttachHandler((string)e.NewValue);
        }
    }

    // ReSharper disable once UnusedMember.Local
    // ReSharper disable once UnusedParameter.Local
    private void ExecuteCommand(object sender, TEventArgs e)
    {
        object parameter = PassArguments ? GetCommandParameter(e) : null;

        if (Command?.CanExecute(parameter) == true)
        {
            Command.Execute(parameter);
        }
    }
}

Next, an example derived class that hides DragCompletedEventArgs. Some people expressed concern about leaking the EventArgs abstraction into their view model assembly. To prevent this, I created an interface that represents the values we care about. The interface can live in the view model assembly with the private implementation in the UI assembly:

// UI assembly
public class DragCompletedBehavior : EventToCommandBehavior<DragCompletedEventArgs>
{
    protected override object GetCommandParameter(DragCompletedEventArgs e)
    {
        return new DragCompletedArgs(e);
    }

    private class DragCompletedArgs : IDragCompletedArgs
    {
        public DragCompletedArgs(DragCompletedEventArgs e)
        {
            Canceled = e.Canceled;
            HorizontalChange = e.HorizontalChange;
            VerticalChange = e.VerticalChange;
        }

        public bool Canceled { get; }
        public double HorizontalChange { get; }
        public double VerticalChange { get; }
    }
}

// View model assembly
public interface IDragCompletedArgs
{
    bool Canceled { get; }
    double HorizontalChange { get; }
    double VerticalChange { get; }
}

Cast the command parameter to IDragCompletedArgs, similar to @adabyron's answer.

Rails 2.3.4 Persisting Model on Validation Failure

In your controller, render the new action from your create action if validation fails, with an instance variable, @car populated from the user input (i.e., the params hash). Then, in your view, add a logic check (either an if block around the form or a ternary on the helpers, your choice) that automatically sets the value of the form fields to the params values passed in to @car if car exists. That way, the form will be blank on first visit and in theory only be populated on re-render in the case of error. In any case, they will not be populated unless @car is set.

Saving any file to in the database, just convert it to a byte array?

Since it's not mentioned what database you mean I'm assuming SQL Server. Below solution works for both 2005 and 2008.

You have to create table with VARBINARY(MAX) as one of the columns. In my example I've created Table Raporty with column RaportPlik being VARBINARY(MAX) column.

Method to put file into database from drive:

public static void databaseFilePut(string varFilePath) {
    byte[] file;
    using (var stream = new FileStream(varFilePath, FileMode.Open, FileAccess.Read)) {
        using (var reader = new BinaryReader(stream)) {
            file = reader.ReadBytes((int) stream.Length);       
        }          
    }
    using (var varConnection = Locale.sqlConnectOneTime(Locale.sqlDataConnectionDetails))
    using (var sqlWrite = new SqlCommand("INSERT INTO Raporty (RaportPlik) Values(@File)", varConnection)) {
        sqlWrite.Parameters.Add("@File", SqlDbType.VarBinary, file.Length).Value = file;
        sqlWrite.ExecuteNonQuery();
    }
}

This method is to get file from database and save it on drive:

public static void databaseFileRead(string varID, string varPathToNewLocation) {
    using (var varConnection = Locale.sqlConnectOneTime(Locale.sqlDataConnectionDetails))
    using (var sqlQuery = new SqlCommand(@"SELECT [RaportPlik] FROM [dbo].[Raporty] WHERE [RaportID] = @varID", varConnection)) {
        sqlQuery.Parameters.AddWithValue("@varID", varID);
        using (var sqlQueryResult = sqlQuery.ExecuteReader())
            if (sqlQueryResult != null) {
                sqlQueryResult.Read();
                var blob = new Byte[(sqlQueryResult.GetBytes(0, 0, null, 0, int.MaxValue))];
                sqlQueryResult.GetBytes(0, 0, blob, 0, blob.Length);
                using (var fs = new FileStream(varPathToNewLocation, FileMode.Create, FileAccess.Write)) 
                    fs.Write(blob, 0, blob.Length);
            }
    }
}

This method is to get file from database and put it as MemoryStream:

public static MemoryStream databaseFileRead(string varID) {
    MemoryStream memoryStream = new MemoryStream();
    using (var varConnection = Locale.sqlConnectOneTime(Locale.sqlDataConnectionDetails))
    using (var sqlQuery = new SqlCommand(@"SELECT [RaportPlik] FROM [dbo].[Raporty] WHERE [RaportID] = @varID", varConnection)) {
        sqlQuery.Parameters.AddWithValue("@varID", varID);
        using (var sqlQueryResult = sqlQuery.ExecuteReader())
            if (sqlQueryResult != null) {
                sqlQueryResult.Read();
                var blob = new Byte[(sqlQueryResult.GetBytes(0, 0, null, 0, int.MaxValue))];
                sqlQueryResult.GetBytes(0, 0, blob, 0, blob.Length);
                //using (var fs = new MemoryStream(memoryStream, FileMode.Create, FileAccess.Write)) {
                memoryStream.Write(blob, 0, blob.Length);
                //}
            }
    }
    return memoryStream;
}

This method is to put MemoryStream into database:

public static int databaseFilePut(MemoryStream fileToPut) {
        int varID = 0;
        byte[] file = fileToPut.ToArray();
        const string preparedCommand = @"
                    INSERT INTO [dbo].[Raporty]
                               ([RaportPlik])
                         VALUES
                               (@File)
                        SELECT [RaportID] FROM [dbo].[Raporty]
            WHERE [RaportID] = SCOPE_IDENTITY()
                    ";
        using (var varConnection = Locale.sqlConnectOneTime(Locale.sqlDataConnectionDetails))
        using (var sqlWrite = new SqlCommand(preparedCommand, varConnection)) {
            sqlWrite.Parameters.Add("@File", SqlDbType.VarBinary, file.Length).Value = file;

            using (var sqlWriteQuery = sqlWrite.ExecuteReader())
                while (sqlWriteQuery != null && sqlWriteQuery.Read()) {
                    varID = sqlWriteQuery["RaportID"] is int ? (int) sqlWriteQuery["RaportID"] : 0;
                }
        }
        return varID;
    }

Happy coding :-)

Adding an onclick function to go to url in JavaScript?

Simply use this

onclick="location.href='pageurl.html';"

Extract substring using regexp in plain bash

Using pure :

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

another solution with bash regex :

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

another solution using grep and look-around advanced regex :

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

another solution using sed :

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

another solution using perl :

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

and last one using awk :

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

UICollectionView Set number of columns

If you are lazy using delegate.

extension UICollectionView {
    func setItemsInRow(items: Int) {
        if let layout = self.collectionViewLayout as? UICollectionViewFlowLayout {
            let contentInset = self.contentInset
            let itemsInRow: CGFloat = CGFloat(items);
            let innerSpace = layout.minimumInteritemSpacing * (itemsInRow - 1.0)
            let insetSpace = contentInset.left + contentInset.right + layout.sectionInset.left + layout.sectionInset.right
            let width = floor((CGRectGetWidth(frame) - insetSpace - innerSpace) / itemsInRow);
            layout.itemSize = CGSizeMake(width, width)
        }
    }
}

PS: Should be called after rotation too

Parse rfc3339 date strings in Python?

This has already been answered here: How do I translate a ISO 8601 datetime string into a Python datetime object?

d = datetime.datetime.strptime( "2012-10-09T19:00:55Z", "%Y-%m-%dT%H:%M:%SZ" )
d.weekday()

Changing Tint / Background color of UITabBar

[[self tabBar] insertSubview:v atIndex:0]; works perfectly for me.

AngularJS: Uncaught Error: [$injector:modulerr] Failed to instantiate module?

I had to change the js file, so to include "function()" at the beginning of it, and also "()" at the end line. That solved the problem

Excel formula to get week number in month (having Monday)

Jonathan from the ExcelCentral forums suggests:

=WEEKNUM(A1,2)-WEEKNUM(DATE(YEAR(A1),MONTH(A1),1),2)+1 

This formula extracts the week of the year [...] and then subtracts it from the week of the first day in the month to get the week of the month. You can change the day that weeks begin by changing the second argument of both WEEKNUM functions (set to 2 [for Monday] in the above example). For weeks beginning on Sunday, use:

=WEEKNUM(A1,1)-WEEKNUM(DATE(YEAR(A1),MONTH(A1),1),1)+1

For weeks beginning on Tuesday, use:

=WEEKNUM(A1,12)-WEEKNUM(DATE(YEAR(A1),MONTH(A1),1),12)+1

etc.

I like it better because it's using the built in week calculation functionality of Excel (WEEKNUM).

How can I make window.showmodaldialog work in chrome 37?

A very good, and working, javascript solution is provided here : https://github.com/niutech/showModalDialog

I personnally used it, works like before for other browser and it creates a new dialog for chrome browser.

Here is an example on how to use it :

function handleReturnValue(returnValue) {
    if (returnValue !== undefined) {
        // do what you want
    }
}

var myCallback = function (returnValue) { // callback for chrome usage
    handleReturnValue(returnValue);
};

var returnValue = window.showModalDialog('someUrl', 'someDialogTitle', 'someDialogParams', myCallback); 
handleReturnValue(returnValue); // for other browsers except Chrome

How to upload a file using Java HttpClient library working with PHP

For those having a hard time implementing the accepted answer (which requires org.apache.http.entity.mime.MultipartEntity) you may be using org.apache.httpcomponents 4.2.* In this case, you have to explicitly install httpmime dependency, in my case:

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpmime</artifactId>
    <version>4.2.5</version>
</dependency>

error: cast from 'void*' to 'int' loses precision

You can cast it to an intptr_t type. It's an int type guaranteed to be big enough to contain a pointer. Use #include <cstdint> to define it.

Add my custom http header to Spring RestTemplate request / extend RestTemplate

You can pass custom http headers with RestTemplate exchange method as below.

HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(new MediaType[] { MediaType.APPLICATION_JSON }));
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("X-TP-DeviceID", "your value");

HttpEntity<RestRequest> entityReq = new HttpEntity<RestRequest>(request, headers);

RestTemplate template = new RestTemplate();

ResponseEntity<RestResponse> respEntity = template
    .exchange("RestSvcUrl", HttpMethod.POST, entityReq, RestResponse.class);

EDIT : Below is the updated code. This link has several ways of calling rest service with examples

RestTemplate restTemplate = new RestTemplate();

HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("X-TP-DeviceID", "your value");

HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);

ResponseEntity<Mall[]> respEntity = restTemplate.exchange(url, HttpMethod.POST, entity, Mall[].class);

Mall[] resp = respEntity.getBody();

How to delete an app from iTunesConnect / App Store Connect

As per 2018 in App Store Connect. We can delete/remove application with following stats.

enter image description here

App Store Connect details for Remove an app

So, from now onwards we can delete our test applications too from app store connect.

enter image description here

C++ callback using class member

MyClass and YourClass could both be derived from SomeonesClass which has an abstract (virtual) Callback method. Your addHandler would accept objects of type SomeonesClass and MyClass and YourClass can override Callback to provide their specific implementation of callback behavior.

What does %5B and %5D in POST requests stand for?

To take a quick look, you can percent-en/decode using this online tool.

How to continue a Docker container which has exited

These commands will work for any container (not only last exited ones). This way will work even after your system has rebooted. To do so, these commands will use "container id".

Steps:

  1. List all dockers by using this command and note the container id of the container you want to restart: docker ps -a

  2. Start your container using container id: docker start <container_id>

  3. Attach and run your container: docker attach <container_id>

NOTE: Works on linux

How do I convert strings in a Pandas data frame to a 'date' data type?

Essentially equivalent to @waitingkuo, but I would use to_datetime here (it seems a little cleaner, and offers some additional functionality e.g. dayfirst):

In [11]: df
Out[11]:
   a        time
0  1  2013-01-01
1  2  2013-01-02
2  3  2013-01-03

In [12]: pd.to_datetime(df['time'])
Out[12]:
0   2013-01-01 00:00:00
1   2013-01-02 00:00:00
2   2013-01-03 00:00:00
Name: time, dtype: datetime64[ns]

In [13]: df['time'] = pd.to_datetime(df['time'])

In [14]: df
Out[14]:
   a                time
0  1 2013-01-01 00:00:00
1  2 2013-01-02 00:00:00
2  3 2013-01-03 00:00:00

Handling ValueErrors
If you run into a situation where doing

df['time'] = pd.to_datetime(df['time'])

Throws a

ValueError: Unknown string format

That means you have invalid (non-coercible) values. If you are okay with having them converted to pd.NaT, you can add an errors='coerce' argument to to_datetime:

df['time'] = pd.to_datetime(df['time'], errors='coerce')

My C# application is returning 0xE0434352 to Windows Task Scheduler but it is not crashing

I was referencing a mapped drive and I found that the mapped drives are not always available to the user account that is running the scheduled task so I used \\IPADDRESS instead of MAPDRIVELETTER: and I am up and running.

Why can't I define a default constructor for a struct in .NET?

Here's my solution to the no default constructor dilemma. I know this is a late solution, but I think it's worth noting this is a solution.

public struct Point2D {
    public static Point2D NULL = new Point2D(-1,-1);
    private int[] Data;

    public int X {
        get {
            return this.Data[ 0 ];
        }
        set {
            try {
                this.Data[ 0 ] = value;
            } catch( Exception ) {
                this.Data = new int[ 2 ];
            } finally {
                this.Data[ 0 ] = value;
            }
        }
    }

    public int Z {
        get {
            return this.Data[ 1 ];
        }
        set {
            try {
                this.Data[ 1 ] = value;
            } catch( Exception ) {
                this.Data = new int[ 2 ];
            } finally {
                this.Data[ 1 ] = value;
            }
        }
    }

    public Point2D( int x , int z ) {
        this.Data = new int[ 2 ] { x , z };
    }

    public static Point2D operator +( Point2D A , Point2D B ) {
        return new Point2D( A.X + B.X , A.Z + B.Z );
    }

    public static Point2D operator -( Point2D A , Point2D B ) {
        return new Point2D( A.X - B.X , A.Z - B.Z );
    }

    public static Point2D operator *( Point2D A , int B ) {
        return new Point2D( B * A.X , B * A.Z );
    }

    public static Point2D operator *( int A , Point2D B ) {
        return new Point2D( A * B.Z , A * B.Z );
    }

    public override string ToString() {
        return string.Format( "({0},{1})" , this.X , this.Z );
    }
}

ignoring the fact I have a static struct called null, (Note: This is for all positive quadrant only), using get;set; in C#, you can have a try/catch/finally, for dealing with the errors where a particular data type is not initialized by the default constructor Point2D(). I guess this is elusive as a solution to some people on this answer. Thats mostly why i'm adding mine. Using the getter and setter functionality in C# will allow you to bypass this default constructor non-sense and put a try catch around what you dont have initialized. For me this works fine, for someone else you might want to add some if statements. So, In the case where you would want a Numerator/Denominator setup, this code might help. I'd just like to reiterate that this solution does not look nice, probably works even worse from an efficiency standpoint, but, for someone coming from an older version of C#, using array data types gives you this functionality. If you just want something that works, try this:

public struct Rational {
    private long[] Data;

    public long Numerator {
        get {
            try {
                return this.Data[ 0 ];
            } catch( Exception ) {
                this.Data = new long[ 2 ] { 0 , 1 };
                return this.Data[ 0 ];
            }
        }
        set {
            try {
                this.Data[ 0 ] = value;
            } catch( Exception ) {
                this.Data = new long[ 2 ] { 0 , 1 };
                this.Data[ 0 ] = value;
            }
        }
    }

    public long Denominator {
        get {
            try {
                return this.Data[ 1 ];
            } catch( Exception ) {
                this.Data = new long[ 2 ] { 0 , 1 };
                return this.Data[ 1 ];
            }
        }
        set {
            try {
                this.Data[ 1 ] = value;
            } catch( Exception ) {
                this.Data = new long[ 2 ] { 0 , 1 };
                this.Data[ 1 ] = value;
            }
        }
    }

    public Rational( long num , long denom ) {
        this.Data = new long[ 2 ] { num , denom };
        /* Todo: Find GCD etc. */
    }

    public Rational( long num ) {
        this.Data = new long[ 2 ] { num , 1 };
        this.Numerator = num;
        this.Denominator = 1;
    }
}

How do I find out if first character of a string is a number?

regular expression starts with number->'^[0-9]' 
Pattern pattern = Pattern.compile('^[0-9]');
 Matcher matcher = pattern.matcher(String);

if(matcher.find()){

System.out.println("true");
}

Android Studio Stuck at Gradle Download on create new project

Invalidate Caches and Restart

It worked for me.

php: catch exception and continue execution, is it possible?

Sure:

try {
   throw new Exception('Something bad');
} catch (Exception $e) {
    // Do nothing
}

You might want to go have a read of the PHP documentation on Exceptions.

Collection was modified; enumeration operation may not execute in ArrayList

I like to iterate backward using a for loop, but this can get tedious compared to foreach. One solution I like is to create an enumerator that traverses the list backward. You can implement this as an extension method on ArrayList or List<T>. The implementation for ArrayList is below.

    public static IEnumerable GetRemoveSafeEnumerator(this ArrayList list)
    {
        for (int i = list.Count - 1; i >= 0; i--)
        {
            // Reset the value of i if it is invalid.
            // This occurs when more than one item
            // is removed from the list during the enumeration.
            if (i >= list.Count)
            {
                if (list.Count == 0)
                    yield break;

                i = list.Count - 1;
            }

            yield return list[i];
        }
    }

The implementation for List<T> is similar.

    public static IEnumerable<T> GetRemoveSafeEnumerator<T>(this List<T> list)
    {
        for (int i = list.Count - 1; i >= 0; i--)
        {
            // Reset the value of i if it is invalid.
            // This occurs when more than one item
            // is removed from the list during the enumeration.
            if (i >= list.Count)
            {
                if (list.Count == 0)
                    yield break;

                i = list.Count - 1;
            }

            yield return list[i];
        }
    }

The example below uses the enumerator to remove all even integers from an ArrayList.

    ArrayList list = new ArrayList() {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    foreach (int item in list.GetRemoveSafeEnumerator())
    {
        if (item % 2 == 0)
            list.Remove(item);
    }

Find a file with a certain extension in folder

Use this code for read file with all type of extension file.

string[] sDirectoryInfo = Directory.GetFiles(SourcePath, "*.*");

init-param and context-param

Consider the below definition in web.xml

<servlet>
    <servlet-name>HelloWorld</servlet-name>
    <servlet-class>TestServlet</servlet-class>
    <init-param>
        <param-name>myprop</param-name>
        <param-value>value</param-value>
    </init-param>
</servlet>

You can see that init-param is defined inside a servlet element. This means it is only available to the servlet under declaration and not to other parts of the web application. If you want this parameter to be available to other parts of the application say a JSP this needs to be explicitly passed to the JSP. For instance passed as request.setAttribute(). This is highly inefficient and difficult to code.

So if you want to get access to global values from anywhere within the application without explicitly passing those values, you need to use Context Init parameters.

Consider the following definition in web.xml

 <web-app>
      <context-param>
           <param-name>myprop</param-name>
           <param-value>value</param-value>
      </context-param>
 </web-app>

This context param is available to all parts of the web application and it can be retrieved from the Context object. For instance, getServletContext().getInitParameter(“dbname”);

From a JSP you can access the context parameter using the application implicit object. For example, application.getAttribute(“dbname”);

How to add an extra column to a NumPy array

I liked this:

new_column = np.zeros((len(a), 1))
b = np.block([a, new_column])

How to replace all occurrences of a character in string?

#include <iostream>
#include <string>
using namespace std;
// Replace function..
string replace(string word, string target, string replacement){
    int len, loop=0;
    string nword="", let;
    len=word.length();
    len--;
    while(loop<=len){
        let=word.substr(loop, 1);
        if(let==target){
            nword=nword+replacement;
        }else{
            nword=nword+let;
        }
        loop++;
    }
    return nword;

}
//Main..
int main() {
  string word;
  cout<<"Enter Word: ";
  cin>>word;
  cout<<replace(word, "x", "y")<<endl;
  return 0;
}

java: HashMap<String, int> not working

You can use reference type in generic arguments, not primitive type. So here you should use

Map<String, Integer> myMap = new HashMap<String, Integer>();

and store value as

myMap.put("abc", 5);

What is the default font of Sublime Text?

The default font on windows 10 is Consolas

symfony 2 twig limit the length of the text and put three dots

An even more elegant solution is to limit the text by the number of words (and not by number of characters). This prevents ugly tear throughs (e.g. 'Stackov...').

Here's an example where I shorten only text blocks longer than 10 words:

{% set text = myentity.text |split(' ') %} 

{% if text|length > 10 %} 
    {% for t in text|slice(0, 10) %}
        {{ t }} 
    {% endfor %}
    ...
{% else %}
    {{ text|join(' ') }}
{% endif %}

Servlet Mapping using web.xml

It allows servlets to have multiple servlet mappings:

<servlet>
    <servlet-name>Servlet1</servlet-name>
    <servlet-path>foo.Servlet</servlet-path>
</servlet>
<servlet-mapping>
    <servlet-name>Servlet1</servlet-name>
    <url-pattern>/enroll</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>Servlet1</servlet-name>
    <url-pattern>/pay</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>Servlet1</servlet-name>
    <url-pattern>/bill</url-pattern>
</servlet-mapping>

It allows filters to be mapped on the particular servlet:

<filter-mapping>
    <filter-name>Filter1</filter-name>
    <servlet-name>Servlet1</servlet-name>
</filter-mapping>

Your proposal would support neither of them. Note that the web.xml is read and parsed only once during application's startup, not on every HTTP request as you seem to think.

Since Servlet 3.0, there's the @WebServlet annotation which minimizes this boilerplate:

@WebServlet("/enroll")
public class Servlet1 extends HttpServlet {

See also:

Why does make think the target is up to date?

my mistake was making the target name "filename.c:" instead of just "filename:"

How to resize a VirtualBox vmdk file

Throw it away and start again. Ignore all these answers - don't waste your time.

For Loop on Lua

names = {'John', 'Joe', 'Steve'}
for names = 1, 3 do
  print (names)
end
  1. You're deleting your table and replacing it with an int
  2. You aren't pulling a value from the table

Try:

names = {'John','Joe','Steve'}
for i = 1,3 do
    print(names[i])
end

VBA Check if variable is empty

To check if a Variant is Null, you need to do it like:

Isnull(myvar) = True

or

Not Isnull(myvar)

How to fetch the row count for all tables in a SQL SERVER database

Here's a dynamic SQL approach that also gives you the schema as well:

DECLARE @sql nvarchar(MAX)

SELECT
    @sql = COALESCE(@sql + ' UNION ALL ', '') +
        'SELECT
            ''' + s.name + ''' AS ''Schema'',
            ''' + t.name + ''' AS ''Table'',
            COUNT(*) AS Count
            FROM ' + QUOTENAME(s.name) + '.' + QUOTENAME(t.name)
    FROM sys.schemas s
    INNER JOIN sys.tables t ON t.schema_id = s.schema_id
    ORDER BY
        s.name,
        t.name

EXEC(@sql)

If needed, it would be trivial to extend this to run over all databases in the instance (join to sys.databases).

How can I download a file from a URL and save it in Rails?

An even shorter version:

require 'open-uri'
download = open('http://example.com/image.png')
IO.copy_stream(download, '~/image.png')

To keep the same filename:

IO.copy_stream(download, "~/#{download.base_uri.to_s.split('/')[-1]}")

Change default icon

Your application icon shows in the taskbar. The icon on the topleft (window) is the form-icon. Go to your form and fill the property "icon" with the same icon; problem solved. You don't need to put the icon in the outputfolder (that's just for setups).

IndentationError: unexpected indent error

The indentation is wrong, as the error tells you. As you can see, you have indented the code beginning with the indicated line too little to be in the for loop, but too much to be at the same level as the for loop. Python sees the lack of indentation as ending the for loop, then complains you have indented the rest of the code too much. (The def line I'm betting is just an artifact of how Stack Overflow wants you to format your code.)

Edit: Given your correction, I'm betting you have a mixture of tabs and spaces in the source file, such that it looks to the human eye like the code lines up, but Python considers it not to. As others have suggested, using only spaces is the recommended practice (see PEP 8). If you start Python with python -t, you will get warnings if there are mixed tabs and spaces in your code, which should help you pinpoint the issue.

What's the difference between console.dir and console.log?

I think Firebug does it differently than Chrome's dev tools. It looks like Firebug gives you a stringified version of the object while console.dir gives you an expandable object. Both give you the expandable object in Chrome, and I think that's where the confusion might come from. Or it's just a bug in Chrome.

In Chrome, both do the same thing. Expanding on your test, I have noticed that Chrome gets the current value of the object when you expand it.

> o = { foo: 1 }
> console.log(o)
Expand now, o.foo = 1
> o.foo = 2
o.foo is still displayed as 1 from previous lines

> o = { foo: 1 }
> console.log(o)
> o.foo = 2
Expand now, o.foo = 2

You can use the following to get a stringified version of an object if that's what you want to see. This will show you what the object is at the time this line is called, not when you expand it.

console.log(JSON.stringify(o));

Global Git ignore

  1. Create a .gitignore file in your home directory
touch ~/.gitignore
  1. Add files to it (folders aren't recognised)

Example

# these work
*.gz
*.tmproj
*.7z

# these won't as they are folders
.vscode/
build/

# but you can do this
.vscode/*
build/*
  1. Check if a git already has a global gitignore
git config --get core.excludesfile
  1. Tell git where the file is
git config --global core.excludesfile '~/.gitignore'

Voila!!

Difference between dangling pointer and memory leak

Pointer helps to create user defined scope to a variable, which is called Dynamic variable. Dynamic Variable can be single variable or group of variable of same type (array) or group of variable of different types (struct). Default local variable scope starts when control enters into a function and ends when control comes out of that function. Default global vairable scope starts at program execution and ends once program finishes.

But scope of a dynamic variable which holds by a pointer can start and end at any point in a program execution, which has to be decided by a programmer. Dangling and memory leak comes into picture only if a programmer doesnt handle the end of scope.

Memory leak will occur if a programmer, doesnt write the code (free of pointer) for end of scope for dynamic variables. Any way once program exits complete process memory will be freed, at that time this leaked memory also will get freed. But it will cause a very serious problem for a process which is running long time.

Once scope of dynamic variable comes to end(freed), NULL should be assigned to pointer variable. Otherwise if the code wrongly accesses it undefined behaviour will happen. So dangling pointer is nothing but a pointer which is pointing a dynamic variable whose scope is already finished.

How can I count the numbers of rows that a MySQL query returned?

Assuming you're using the mysql_ or mysqli_ functions, your question should already have been answered by others.

However if you're using PDO, there is no easy function to return the number of rows retrieved by a select statement, unfortunately. You have to use count() on the resultset (after assigning it to a local variable, usually).

Or if you're only interested in the number and not the data, PDOStatement::fetchColumn() on your SELECT COUNT(1)... result.

Oracle 11g Express Edition for Windows 64bit?

Oracle 11G Express Edition is now available to install on 64-bit versions of Windows.

Oracle 11G Download Page

Git push error '[remote rejected] master -> master (branch is currently checked out)'

I had the same issue. For me, I use Git push to move code to my servers. I never change the code on the server side, so this is safe.

In the repository, you are pushing to type:

git config receive.denyCurrentBranch ignore

This will allow you to change the repository while it's a working copy.

After you run a Git push, go to the remote machine and type this:

git checkout -f

This will make the changes you pushed be reflected in the working copy of the remote machine.

Please note, this isn't always safe if you make changes on in the working copy that you're pushing to.

Concatenate in jQuery Selector

Your concatenation syntax is correct.

Most likely the callback function isn't even being called. You can test that by putting an alert(), console.log() or debugger line in that function.

If it isn't being called, most likely there's an AJAX error. Look at chaining a .fail() handler after $.post() to find out what the error is, e.g.:

$.post('ajaxskeleton.php', {
    red: text       
}, function(){
    $('#part' + number).html(text);
}).fail(function(jqXHR, textStatus, errorThrown) {
    console.log(arguments);
});

Where is array's length property defined?

Arrays are special objects in java, they have a simple attribute named length which is final.

There is no "class definition" of an array (you can't find it in any .class file), they're a part of the language itself.

10.7. Array Members

The members of an array type are all of the following:

  • The public final field length, which contains the number of components of the array. length may be positive or zero.
  • The public method clone, which overrides the method of the same name in class Object and throws no checked exceptions. The return type of the clone method of an array type T[] is T[].

    A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared.

  • All the members inherited from class Object; the only method of Object that is not inherited is its clone method.

Resources:

C Program to find day of week given date

A one-liner is unlikely, but the strptime function can be used to parse your date format and the struct tm argument can be queried for its tm_wday member on systems that modify those fields automatically (e.g. some glibc implementations).

int get_weekday(char * str) {
  struct tm tm;
  memset((void *) &tm, 0, sizeof(tm));
  if (strptime(str, "%d-%m-%Y", &tm) != NULL) {
    time_t t = mktime(&tm);
    if (t >= 0) {
      return localtime(&t)->tm_wday; // Sunday=0, Monday=1, etc.
    }
  }
  return -1;
}

Or you could encode these rules to do some arithmetic in a really long single line:

  • 1 Jan 1900 was a Monday.
  • Thirty days has September, April, June and November; all the rest have thirty-one, saving February alone, which has twenty-eight, rain or shine, and on leap years, twenty-nine.
  • A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.

EDIT: note that this solution only works for dates after the UNIX epoch (1970-01-01T00:00:00Z).

Programmatically switching between tabs within Swift

1.Create a new class which supers UITabBarController. E.g:

class xxx: UITabBarController {
override func viewDidLoad() {
        super.viewDidLoad()
}

2.Add the following code to the function viewDidLoad():

self.selectedIndex = 1; //set the tab index you want to show here, start from 0

3.Go to storyboard, and set the Custom Class of your Tab Bar Controller to this new class. (MyVotes1 as the example in the pic)

enter image description here

How to change font in ipython notebook

I would also suggest that you explore the options offered by the jupyter themer. For more modest interface changes you may be satisfied with running the syntax:

jupyter-themer [-c COLOR, --color COLOR]
                      [-l LAYOUT, --layout LAYOUT]
                      [-t TYPOGRAPHY, --typography TYPOGRAPHY]

where the options offered by themer would provide you with a less onerous way of making some changes in to the look of Jupyter Notebook. Naturally, you may still to prefer edit the .css files if the changes you want to apply are elaborate.

How to save a Python interactive session?

Some comments were asking how to save all of the IPython inputs at once. For %save magic in IPython, you can save all of the commands programmatically as shown below, to avoid the prompt message and also to avoid specifying the input numbers. currentLine = len(In)-1 %save -f my_session 1-$currentLine

The -f option is used for forcing file replacement and the len(IN)-1 shows the current input prompt in IPython, allowing you to save the whole session programmatically.

How to draw a line in android

To improve on the answers provided by @Janusz

I added this to my styles:

<style name="Divider">
    <item name="android:layout_width">match_parent</item>
    <item name="android:layout_height">1dp</item>
    <item name="android:background">?android:attr/listDivider</item>
</style>

Then in my layouts is less code and simpler to read.

<View style="@style/Divider"/>

if you want to do horizontal line spacing then do the above.


And for vertical line between two Views you have to replace android:layout_width parameters(attributes) with android:layout_height

VBA general way for pulling data out of SAP

This all depends on what sort of access you have to your SAP system. An ABAP program that exports the data and/or an RFC that your macro can call to directly get the data or have SAP create the file is probably best.

However as a general rule people looking for this sort of answer are looking for an immediate solution that does not require their IT department to spend months customizing their SAP system.

In that case you probably want to use SAP GUI Scripting. SAP GUI scripting allows you to automate the Windows SAP GUI in much the same way as you automate Excel. In fact you can call the SAP GUI directly from an Excel macro. Read up more on it here. The SAP GUI has a macro recording tool much like Excel does. It records macros in VBScript which is nearly identical to Excel VBA and can usually be copied and pasted into an Excel macro directly.

Example Code

Here is a simple example based on a SAP system I have access to.

Public Sub SimpleSAPExport()
  Set SapGuiAuto  = GetObject("SAPGUI") 'Get the SAP GUI Scripting object
  Set SAPApp = SapGuiAuto.GetScriptingEngine 'Get the currently running SAP GUI 
  Set SAPCon = SAPApp.Children(0) 'Get the first system that is currently connected
  Set session = SAPCon.Children(0) 'Get the first session (window) on that connection

  'Start the transaction to view a table
  session.StartTransaction "SE16"

  'Select table T001
  session.findById("wnd[0]/usr/ctxtDATABROWSE-TABLENAME").Text = "T001"
  session.findById("wnd[0]/tbar[1]/btn[7]").Press

  'Set our selection criteria
  session.findById("wnd[0]/usr/txtMAX_SEL").text = "2"
  session.findById("wnd[0]/tbar[1]/btn[8]").press

  'Click the export to file button
  session.findById("wnd[0]/tbar[1]/btn[45]").press

  'Choose the export format
  session.findById("wnd[1]/usr/subSUBSCREEN_STEPLOOP:SAPLSPO5:0150/sub:SAPLSPO5:0150/radSPOPLI-SELFLAG[1,0]").select
  session.findById("wnd[1]/tbar[0]/btn[0]").press

  'Choose the export filename
  session.findById("wnd[1]/usr/ctxtDY_FILENAME").text = "test.txt"
  session.findById("wnd[1]/usr/ctxtDY_PATH").text = "C:\Temp\"

  'Export the file
  session.findById("wnd[1]/tbar[0]/btn[0]").press
End Sub

Script Recording

To help find the names of elements such aswnd[1]/tbar[0]/btn[0] you can use script recording. Click the customize local layout button, it probably looks a bit like this: Customize Local Layout
Then find the Script Recording and Playback menu item.
Script Recording and Playback
Within that the More button allows you to see/change the file that the VB Script is recorded to. The output format is a bit messy, it records things like selecting text, clicking inside a text field, etc.

Edit: Early and Late binding

The provided script should work if copied directly into a VBA macro. It uses late binding, the line Set SapGuiAuto = GetObject("SAPGUI") defines the SapGuiAuto object.

If however you want to use early binding so that your VBA editor might show the properties and methods of the objects you are using, you need to add a reference to sapfewse.ocx in the SAP GUI installation folder.

open a url on click of ok button in android

    Button imageLogo = (Button)findViewById(R.id.iv_logo);
    imageLogo.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            String url = "http://www.gobloggerslive.com";

            Intent i = new Intent(Intent.ACTION_VIEW);
            i.setData(Uri.parse(url));
            startActivity(i);
        }
    });

How to determine equality for two JavaScript objects?

_x000D_
_x000D_
function isDeepEqual(obj1, obj2, testPrototypes = false) {_x000D_
  if (obj1 === obj2) {_x000D_
    return true_x000D_
  }_x000D_
_x000D_
  if (typeof obj1 === "function" && typeof obj2 === "function") {_x000D_
    return obj1.toString() === obj2.toString()_x000D_
  }_x000D_
_x000D_
  if (obj1 instanceof Date && obj2 instanceof Date) {_x000D_
    return obj1.getTime() === obj2.getTime()_x000D_
  }_x000D_
_x000D_
  if (_x000D_
    Object.prototype.toString.call(obj1) !==_x000D_
      Object.prototype.toString.call(obj2) ||_x000D_
    typeof obj1 !== "object"_x000D_
  ) {_x000D_
    return false_x000D_
  }_x000D_
_x000D_
  const prototypesAreEqual = testPrototypes_x000D_
    ? isDeepEqual(_x000D_
        Object.getPrototypeOf(obj1),_x000D_
        Object.getPrototypeOf(obj2),_x000D_
        true_x000D_
      )_x000D_
    : true_x000D_
_x000D_
  const obj1Props = Object.getOwnPropertyNames(obj1)_x000D_
  const obj2Props = Object.getOwnPropertyNames(obj2)_x000D_
_x000D_
  return (_x000D_
    obj1Props.length === obj2Props.length &&_x000D_
    prototypesAreEqual &&_x000D_
    obj1Props.every(prop => isDeepEqual(obj1[prop], obj2[prop]))_x000D_
  )_x000D_
}_x000D_
_x000D_
console.log(isDeepEqual({key: 'one'}, {key: 'first'}))_x000D_
console.log(isDeepEqual({key: 'one'}, {key: 'one'}))
_x000D_
_x000D_
_x000D_

what does "error : a nonstatic member reference must be relative to a specific object" mean?

Only static functions are called with class name.

classname::Staicfunction();

Non static functions have to be called using objects.

classname obj;
obj.Somefunction();

This is exactly what your error means. Since your function is non static you have to use a object reference to invoke it.

Python and SQLite: insert into table

This will work for a multiple row df having the dataframe as df with the same name of the columns in the df as the db.

tuples = list(df.itertuples(index=False, name=None))

columns_list = df.columns.tolist()
marks = ['?' for _ in columns_list]
columns_list = f'({(",".join(columns_list))})'
marks = f'({(",".join(marks))})'

table_name = 'whateveryouwant'

c.executemany(f'INSERT OR REPLACE INTO {table_name}{columns_list} VALUES {marks}', tuples)
conn.commit()

Calculating distance between two points, using latitude longitude?

Here's a Java function that calculates the distance between two lat/long points, posted below, just in case it disappears again.

    private double distance(double lat1, double lon1, double lat2, double lon2, char unit) {
      double theta = lon1 - lon2;
      double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta));
      dist = Math.acos(dist);
      dist = rad2deg(dist);
      dist = dist * 60 * 1.1515;
      if (unit == 'K') {
        dist = dist * 1.609344;
      } else if (unit == 'N') {
        dist = dist * 0.8684;
        }
      return (dist);
    }
    
    /*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
    /*::  This function converts decimal degrees to radians             :*/
    /*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
    private double deg2rad(double deg) {
      return (deg * Math.PI / 180.0);
    }
    
    /*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
    /*::  This function converts radians to decimal degrees             :*/
    /*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
    private double rad2deg(double rad) {
      return (rad * 180.0 / Math.PI);
    }
    
    System.out.println(distance(32.9697, -96.80322, 29.46786, -98.53506, 'M') + " Miles\n");
    System.out.println(distance(32.9697, -96.80322, 29.46786, -98.53506, 'K') + " Kilometers\n");
    System.out.println(distance(32.9697, -96.80322, 29.46786, -98.53506, 'N') + " Nautical Miles\n");

How to vertically center a container in Bootstrap?

My prefered technique :

body {
  display: table;
  position: absolute;
  height: 100%;
  width: 100%;
}

.jumbotron {
   display: table-cell;
   vertical-align: middle;
}

Demo

_x000D_
_x000D_
body {_x000D_
  display: table;_x000D_
  position: absolute;_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
.jumbotron {_x000D_
   display: table-cell;_x000D_
   vertical-align: middle;_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">_x000D_
<div class="jumbotron vertical-center">_x000D_
  <div class="container text-center">_x000D_
    <h1>The easiest and powerful way</h1>_x000D_
    <div class="row">_x000D_
      <div class="col-md-7">_x000D_
        <div class="top-bg">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div>_x000D_
      </div>_x000D_
_x000D_
      <div class="col-md-5 iPhone-features">_x000D_
        <ul class="top-features">_x000D_
          <li>_x000D_
            <span><i class="fa fa-random simple_bg top-features-bg"></i></span>_x000D_
            <p><strong>Redirect</strong><br>Visitors where they converts more.</p>_x000D_
          </li>_x000D_
          <li>_x000D_
            <span><i class="fa fa-cogs simple_bg top-features-bg"></i></span>_x000D_
            <p><strong>Track</strong><br>Views, Clicks and Conversions.</p>_x000D_
          </li>_x000D_
          <li>_x000D_
            <span><i class="fa fa-check simple_bg top-features-bg"></i></span>_x000D_
            <p><strong>Check</strong><br>Constantly the status of your links.</p>_x000D_
          </li>_x000D_
          <li>_x000D_
            <span><i class="fa fa-users simple_bg top-features-bg"></i></span>_x000D_
            <p><strong>Collaborate</strong><br>With Customers, Partners and Co-Workers.</p>_x000D_
          </li>_x000D_
          <a href="pricing-and-signup.html" class="btn-primary btn h2 lightBlue get-Started-btn">GET STARTED</a>_x000D_
          <h6 class="get-Started-sub-btn">FREE VERSION AVAILABLE!</h6>_x000D_
        </ul>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

See also this Fiddle!

Does List<T> guarantee insertion order?

As Bevan said, but keep in mind, that the list-index is 0-based. If you want to move an element to the front of the list, you have to insert it at index 0 (not 1 as shown in your example).

specifying goal in pom.xml

1.right click on your project.
2.click 'Run as' and select 'Maven Build'
3. edit Configuration window will open. write any goal but your problem specific write 'package' in Goal
4 user settings: show your maven->directory->conf->settings.xml for example; C:\maven\conf\settings.xml

org.apache.http.conn.HttpHostConnectException: Connection to http://localhost refused in android

try adding the permission outside the application tag of the manifest in addition to the above mentioned answers of changing localhost to 10.0.2.2:8080

Variable interpolation in the shell

Use

"$filepath"_newstap.sh

or

${filepath}_newstap.sh

or

$filepath\_newstap.sh

_ is a valid character in identifiers. Dot is not, so the shell tried to interpolate $filepath_newstap.

You can use set -u to make the shell exit with an error when you reference an undefined variable.

MySQL connection not working: 2002 No such file or directory

in my case I have problem with mysqli_connect.
when I want to connect
mysqli_connect('localhost', 'myuser','mypassword')
mysqli_connect_error() return me this error "No such file or directory"

this worked for me mysqli_connect('localhost:3306', 'myuser','mypassword')

Login failed for user 'IIS APPPOOL\ASP.NET v4.0'

I have faced the similar issue while host the appication in IIS

Solution

I change the Pool Identity and its work me

ApplicationPoolIdentity -> NetworkService

Where does npm install packages?

On windows I used npm list -g to find it out. By default my (global) packages were being installed to C:\Users\[Username]\AppData\Roaming\npm.

How to run wget inside Ubuntu Docker image?

I had this problem recently where apt install wget does not find anything. As it turns out apt update was never run.

apt update
apt install wget

After discussing this with a coworker we mused that apt update is likely not run in order to save both time and space in the docker image.

Static variables in JavaScript

Working with MVC websites that use jQuery, I like to make sure AJAX actions within certain event handlers can only be executed once the previous request has completed. I use a "static" jqXHR object variable to achieve this.

Given the following button:

<button type="button" onclick="ajaxAction(this, { url: '/SomeController/SomeAction' })">Action!</button>

I generally use an IIFE like this for my click handler:

var ajaxAction = (function (jqXHR) {
    return function (sender, args) {
        if (!jqXHR || jqXHR.readyState == 0 || jqXHR.readyState == 4) {
            jqXHR = $.ajax({
                url: args.url,
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify($(sender).closest('form').serialize()),
                success: function (data) {
                    // Do something here with the data.
                }
            });
        }
    };
})(null);

Correctly Parsing JSON in Swift 3

The problem is with the API interaction method. The JSON parsing is changed only in syntax. The main problem is with the way of fetching data. What you are using is a synchronous way of getting data. This doesn't work in every case. What you should be using is an asynchronous way to fetch data. In this way, you have to request data through the API and wait for it to respond with data. You can achieve this with URL session and third party libraries like Alamofire. Below is the code for URL Session method.

let urlString = "https://api.forecast.io/forecast/apiKey/37.5673776,122.048951"
let url = URL.init(string: urlString)
URLSession.shared.dataTask(with:url!) { (data, response, error) in
    guard error == nil else {
        print(error)
    }
    do {
        let Data = try JSONSerialization.jsonObject(with: data!) as! [String:Any]
        // Note if your data is coming in Array you should be using [Any]()
        //Now your data is parsed in Data variable and you can use it normally
        let currentConditions = Data["currently"] as! [String:Any]
        print(currentConditions)
        let currentTemperatureF = currentConditions["temperature"] as! Double
        print(currentTemperatureF)
    } catch let error as NSError {
        print(error)
    }
}.resume()

Changing route doesn't scroll to top in the new page

I found this solution. If you go to a new view the function gets executed.

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

    app.controller('indexController', function ($scope, $window) {
        $scope.$on('$viewContentLoaded', function () {
            $window.scrollTo(0, 0);
        });
    });

Is a Python dictionary an example of a hash table?

Yes. Internally it is implemented as open hashing based on a primitive polynomial over Z/2 (source).

Android Emulator Error Message: "PANIC: Missing emulator engine program for 'x86' CPUS."

There are two named emulator binary file. which located under $SDK/tools/emulator another under $SDK/emulator/

  • please make sure you have the right emulator configure(need add $SDK/emulator to your env PATH

I have write a script to help me to invoke the avd list

    #!/bin/bash -e


    echo "--- $# $(PWD)"
    HOME_CURRENT=$(PWD)
    HOME_EMULATOR=/Users/pcao/Library/Android/sdk/emulator

    if [ "$#" -eq 0 ]
    then
        echo "ERROR pls try avd 23 or avd 28 " 
    fi

    if [ "$1" = "23" ]
    then
        echo "enter 23"
        cd $HOME_EMULATOR
        ./emulator -avd Nexus_5_API_23_Android6_ &
        cd $HOME_CURRENT
    fi

    if [ "$1" = "28" ]
    then
        echo "enter 28"
        cd $HOME_EMULATOR
        ./emulator -avd Nexus_5_API_28_GooglePlay_ &
        cd $HOME_CURRENT
    fi


How to check postgres user and password?

You may change the pg_hba.conf and then reload the postgresql. something in the pg_hba.conf may be like below:

# "local" is for Unix domain socket connections only
local   all             all                                     trust
# IPv4 local connections:
host    all             all             127.0.0.1/32            trust

then you change your user to postgresql, you may login successfully.

su postgresql

Referring to the null object in Python

In Python, the 'null' object is the singleton None.

The best way to check things for "Noneness" is to use the identity operator, is:

if foo is None:
    ...

Why is using "for...in" for array iteration a bad idea?

As of 2016 (ES6) we may use for…of for array iteration, as John Slegers already noticed.

I would just like to add this simple demonstration code, to make things clearer:

Array.prototype.foo = 1;
var arr = [];
arr[5] = "xyz";

console.log("for...of:");
var count = 0;
for (var item of arr) {
    console.log(count + ":", item);
    count++;
    }

console.log("for...in:");
count = 0;
for (var item in arr) {
    console.log(count + ":", item);
    count++;
    }

The console shows:

for...of:

0: undefined
1: undefined
2: undefined
3: undefined
4: undefined
5: xyz

for...in:

0: 5
1: foo

In other words:

  • for...of counts from 0 to 5, and also ignores Array.prototype.foo. It shows array values.

  • for...in lists only the 5, ignoring undefined array indexes, but adding foo. It shows array property names.

Python read JSON file and modify

Set item using data['id'] = ....

import json

with open('data.json', 'r+') as f:
    data = json.load(f)
    data['id'] = 134 # <--- add `id` value.
    f.seek(0)        # <--- should reset file position to the beginning.
    json.dump(data, f, indent=4)
    f.truncate()     # remove remaining part

What are the differences between a multidimensional array and an array of arrays in C#?

I would like to update on this, because in .NET Core multi-dimensional arrays are faster than jagged arrays. I ran the tests from John Leidegren and these are the results on .NET Core 2.0 preview 2. I increased the dimension value to make any possible influences from background apps less visible.

Debug (code optimalization disabled)
Running jagged 
187.232 200.585 219.927 227.765 225.334 222.745 224.036 222.396 219.912 222.737 

Running multi-dimensional  
130.732 151.398 131.763 129.740 129.572 159.948 145.464 131.930 133.117 129.342 

Running single-dimensional  
 91.153 145.657 111.974  96.436 100.015  97.640  94.581 139.658 108.326  92.931 


Release (code optimalization enabled)
Running jagged 
108.503 95.409 128.187 121.877 119.295 118.201 102.321 116.393 125.499 116.459 

Running multi-dimensional 
 62.292  60.627  60.611  60.883  61.167  60.923  62.083  60.932  61.444  62.974 

Running single-dimensional 
 34.974  33.901  34.088  34.659  34.064  34.735  34.919  34.694  35.006  34.796 

I looked into disassemblies and this is what I found

jagged[i][j][k] = i * j * k; needed 34 instructions to execute

multi[i, j, k] = i * j * k; needed 11 instructions to execute

single[i * dim * dim + j * dim + k] = i * j * k; needed 23 instructions to execute

I wasn't able to identify why single-dimensional arrays were still faster than multi-dimensional but my guess is that it has to do with some optimalization made on the CPU

How to split csv whose columns may contain ,

Use a library like LumenWorks to do your CSV reading. It'll handle fields with quotes in them and will likely overall be more robust than your custom solution by virtue of having been around for a long time.

What is Android's file system?

It depends on what filesystem, for example /system and /data are yaffs2 while /sdcard is vfat. This is the output of mount:

rootfs / rootfs ro 0 0
tmpfs /dev tmpfs rw,mode=755 0 0
devpts /dev/pts devpts rw,mode=600 0 0
proc /proc proc rw 0 0
sysfs /sys sysfs rw 0 0
tmpfs /sqlite_stmt_journals tmpfs rw,size=4096k 0 0
none /dev/cpuctl cgroup rw,cpu 0 0
/dev/block/mtdblock0 /system yaffs2 ro 0 0
/dev/block/mtdblock1 /data yaffs2 rw,nosuid,nodev 0 0
/dev/block/mtdblock2 /cache yaffs2 rw,nosuid,nodev 0 0
/dev/block//vold/179:0 /sdcard vfat rw,dirsync,nosuid,nodev,noexec,uid=1000,gid=1015,fmask=0702,dmask=0702,allow_utime=0020,codepage=cp437,iocharset=iso8859-1,shortname=mixed,utf8,errors=remount-ro 0 0

and with respect to other filesystems supported, this is the list

nodev   sysfs
nodev   rootfs
nodev   bdev
nodev   proc
nodev   cgroup
nodev   binfmt_misc
nodev   sockfs
nodev   pipefs
nodev   anon_inodefs
nodev   tmpfs
nodev   inotifyfs
nodev   devpts
nodev   ramfs
         vfat
         msdos
nodev   nfsd
nodev   smbfs
         yaffs
         yaffs2
nodev   rpc_pipefs

How can I make SQL case sensitive string comparison on MySQL?

http://dev.mysql.com/doc/refman/5.0/en/case-sensitivity.html

The default character set and collation are latin1 and latin1_swedish_ci, so nonbinary string comparisons are case insensitive by default. This means that if you search with col_name LIKE 'a%', you get all column values that start with A or a. To make this search case sensitive, make sure that one of the operands has a case sensitive or binary collation. For example, if you are comparing a column and a string that both have the latin1 character set, you can use the COLLATE operator to cause either operand to have the latin1_general_cs or latin1_bin collation:

col_name COLLATE latin1_general_cs LIKE 'a%'
col_name LIKE 'a%' COLLATE latin1_general_cs
col_name COLLATE latin1_bin LIKE 'a%'
col_name LIKE 'a%' COLLATE latin1_bin

If you want a column always to be treated in case-sensitive fashion, declare it with a case sensitive or binary collation.

How to count number of unique values of a field in a tab-delimited text file?

Here is a bash script that fully answers the (revised) original question. That is, given any .tsv file, it provides the synopsis for each of the columns in turn. Apart from bash itself, it only uses standard *ix/Mac tools: sed tr wc cut sort uniq.

#!/bin/bash
# Syntax: $0 filename   
# The input is assumed to be a .tsv file

FILE="$1"

cols=$(sed -n 1p $FILE | tr -cd '\t' | wc -c)
cols=$((cols + 2 ))
i=0
for ((i=1; i < $cols; i++))
do
  echo Column $i ::
  cut -f $i < "$FILE" | sort | uniq -c
  echo
done

Create a <ul> and fill it based on a passed array

You may also consider the following solution:

let sum = options.set0.concat(options.set1);
const codeHTML = '<ol>' + sum.reduce((html, item) => {
    return html + "<li>" + item + "</li>";
        }, "") + '</ol>';
document.querySelector("#list").innerHTML = codeHTML;

Cannot install Aptana Studio 3.6 on Windows

Installing Aptana Studio in passive mode bypasses the installation of Git for Windows and Node.js.

Aptana_Studio_3_Setup_3.6.1 /passive /norestart

(I am unsure whether Aptana Studio will work properly without those "prerequisites", but it appears to.)

If you want a global installation in a specific directory, the command line is

Aptana_Studio_3_Setup_3.6.1.exe /passive /norestart ALLUSERS=1 APPDIR=c:\apps\AptanaStudio

Passing variables to the next middleware using next() in Express.js

I don't think that best practice will be passing a variable like req.YOUR_VAR. You might want to consider req.YOUR_APP_NAME.YOUR_VAR or req.mw_params.YOUR_VAR.

It will help you avoid overwriting other attributes.

Update May 31, 2020

res.locals is what you're looking for, the object is scoped to the request.

An object that contains response local variables scoped to the request, and therefore available only to the view(s) rendered during that request / response cycle (if any). Otherwise, this property is identical to app.locals.

This property is useful for exposing request-level information such as the request path name, authenticated user, user settings, and so on.

How to delete an object by id with entity framework

The same as @Nix with a small change to be strongly typed:

If you don't want to query for it just create an entity, and then delete it.

                Customer customer = new Customer () { Id = id };
                context.Customers.Attach(customer);
                context.Customers.DeleteObject(customer);
                context.SaveChanges();

How do I measure the execution time of JavaScript code with callbacks?

Surprised no one had mentioned yet the new built in libraries:

Available in Node >= 8.5, and should be in Modern Browers

https://developer.mozilla.org/en-US/docs/Web/API/Performance

https://nodejs.org/docs/latest-v8.x/api/perf_hooks.html#

Node 8.5 ~ 9.x (Firefox, Chrome)

_x000D_
_x000D_
// const { performance } = require('perf_hooks'); // enable for node
const delay = time => new Promise(res=>setTimeout(res,time))
async function doSomeLongRunningProcess(){
  await delay(1000);
}
performance.mark('A');
(async ()=>{
  await doSomeLongRunningProcess();
  performance.mark('B');
  performance.measure('A to B', 'A', 'B');
  const measure = performance.getEntriesByName('A to B')[0];
  // firefox appears to only show second precision.
  console.log(measure.duration);
  // apparently you should clean up...
  performance.clearMarks();
  performance.clearMeasures();         
  // Prints the number of milliseconds between Mark 'A' and Mark 'B'
})();
_x000D_
_x000D_
_x000D_

https://repl.it/@CodyGeisler/NodeJsPerformanceHooks

Node 12.x

https://nodejs.org/docs/latest-v12.x/api/perf_hooks.html

const { PerformanceObserver, performance } = require('perf_hooks');
const delay = time => new Promise(res => setTimeout(res, time))
async function doSomeLongRunningProcess() {
    await delay(1000);
}
const obs = new PerformanceObserver((items) => {
    console.log('PerformanceObserver A to B',items.getEntries()[0].duration);
      // apparently you should clean up...
      performance.clearMarks();
      // performance.clearMeasures(); // Not a function in Node.js 12
});
obs.observe({ entryTypes: ['measure'] });

performance.mark('A');

(async function main(){
    try{
        await performance.timerify(doSomeLongRunningProcess)();
        performance.mark('B');
        performance.measure('A to B', 'A', 'B');
    }catch(e){
        console.log('main() error',e);
    }
})();

Styles.Render in MVC4

Polo I wouldn't use Bundles in MVC for multiple reasons. It doesn't work in your case because you have to set up a custom BundleConfig class in your Apps_Start folder. This makes no sense when you can simple add a style in the head of your html like so:

<link rel="stylesheet" href="~/Content/bootstrap.css" />
<link rel="stylesheet" href="~/Content/bootstrap.theme.css" />

You can also add these to a Layout.cshtml or partial class that's called from all your views and dropped into each page. If your styles change, you can easily change the name and path without having to recompile.

Adding hard-coded links to CSS in a class breaks with the whole purpose of separation of the UI and design from the application model, as well. You also don't want hard coded style sheet paths managed in c# because you can no longer build "skins" or separate style models for say different devices, themes, etc. like so:

<link rel="stylesheet" href="~/UI/Skins/skin1/base.css" />
<link rel="stylesheet" href="~/UI/Skins/skin2/base.css" />

Using this system and Razor you can now switch out the Skin Path from a database or user setting and change the whole design of your website by just changing the path dynamically.

The whole purpose of CSS 15 years ago was to develop both user-controlled and application-controlled style sheet "skins" for sites so you could switch out the UI look and feel separate from the application and repurpose the content independent of the data structure.....for example a printable version, mobile, audio version, raw xml, etc.

By moving back now to this "old-fashioned", hard-coded path system using C# classes, rigid styles like Bootstrap, and merging the themes of sites with application code, we have gone backwards again to how websites were built in 1998.

How to enable production mode?

Go to src/enviroments/enviroments.ts and enable the production mode

export const environment = {
  production: true
};

for Angular 2

Absolute Positioning & Text Alignment

The div doesn't take up all the available horizontal space when absolutely positioned. Explicitly setting the width to 100% will solve the problem:

HTML

<div id="my-div">I want to be centered</div>?

CSS

#my-div {
   position: absolute;
   bottom: 15px;
   text-align: center;
   width: 100%;
}

?

How to upgrade Git to latest version on macOS?

The installer from the git homepage installs into /usr/local/git by default. However, if you install XCode4, it will install a git version in /usr/bin. To ensure you can easily upgrade from the website and use the latest git version, edit either your profile information to place /usr/local/git/bin before /usr/bin in the $PATH or edit /etc/paths and insert /usr/local/git/bin as the first entry.

It may help to someone at-least changing the order in /etc/paths worked for me.

Changing WPF title bar background color

Here's an example on how to achieve this:

    <Grid DockPanel.Dock="Right"
      HorizontalAlignment="Right">

        <StackPanel Orientation="Horizontal"
                HorizontalAlignment="Right"
                VerticalAlignment="Center">

            <Button x:Name="MinimizeButton"
                KeyboardNavigation.IsTabStop="False"
                Click="MinimizeWindow"
                Style="{StaticResource MinimizeButton}" 
                Template="{StaticResource MinimizeButtonControlTemplate}" />

            <Button x:Name="MaximizeButton"
                KeyboardNavigation.IsTabStop="False"
                Click="MaximizeClick"
                Style="{DynamicResource MaximizeButton}" 
                Template="{DynamicResource MaximizeButtonControlTemplate}" />

            <Button x:Name="CloseButton"
                KeyboardNavigation.IsTabStop="False"
                Command="{Binding ApplicationCommands.Close}"
                Style="{DynamicResource CloseButton}" 
                Template="{DynamicResource CloseButtonControlTemplate}"/>

        </StackPanel>
    </Grid>
</DockPanel>

Handle Click Events in the code-behind.

For MouseDown -

App.Current.MainWindow.DragMove();

For Minimize Button -

App.Current.MainWindow.WindowState = WindowState.Minimized;

For DoubleClick and MaximizeClick

if (App.Current.MainWindow.WindowState == WindowState.Maximized)
{
    App.Current.MainWindow.WindowState = WindowState.Normal;
}
else if (App.Current.MainWindow.WindowState == WindowState.Normal)
{
    App.Current.MainWindow.WindowState = WindowState.Maximized;
}

file_get_contents(): SSL operation failed with code 1, Failed to enable crypto

Regarding errors similar to

[11-May-2017 19:19:13 America/Chicago] PHP Warning: file_get_contents(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed

Have you checked the permissions of the cert and directories referenced by openssl?

You can do this

var_dump(openssl_get_cert_locations());

To get something similar to this

array(8) {
  ["default_cert_file"]=>
  string(21) "/usr/lib/ssl/cert.pem"
  ["default_cert_file_env"]=>
  string(13) "SSL_CERT_FILE"
  ["default_cert_dir"]=>
  string(18) "/usr/lib/ssl/certs"
  ["default_cert_dir_env"]=>
  string(12) "SSL_CERT_DIR"
  ["default_private_dir"]=>
  string(20) "/usr/lib/ssl/private"
  ["default_default_cert_area"]=>
  string(12) "/usr/lib/ssl"
  ["ini_cafile"]=>
  string(0) ""
  ["ini_capath"]=>
  string(0) ""
}

This issue frustrated me for a while, until I realized that my "certs" folder had 700 permissions, when it should have had 755 permissions. Remember, this is not the folder for keys but certificates. I recommend reading this this link on ssl permissions.

Once I did

chmod 755 certs

The problem was fixed, at least for me anyway.

How to position a div in the middle of the screen when the page is bigger than the screen

For this you would have to detect screen size. That is not possible with CSS or HTML; you need JavaScript. Here is the Mozilla Developer Center entry on window properties https://developer.mozilla.org/en/DOM/window#Properties

Detect the available height and position accordingly.

SQLAlchemy: print the actual query

I would like to point out that the solutions given above do not "just work" with non-trivial queries. One issue I came across were more complicated types, such as pgsql ARRAYs causing issues. I did find a solution that for me, did just work even with pgsql ARRAYs:

borrowed from: https://gist.github.com/gsakkis/4572159

The linked code seems to be based on an older version of SQLAlchemy. You'll get an error saying that the attribute _mapper_zero_or_none doesn't exist. Here's an updated version that will work with a newer version, you simply replace _mapper_zero_or_none with bind. Additionally, this has support for pgsql arrays:

# adapted from:
# https://gist.github.com/gsakkis/4572159
from datetime import date, timedelta
from datetime import datetime

from sqlalchemy.orm import Query


try:
    basestring
except NameError:
    basestring = str


def render_query(statement, dialect=None):
    """
    Generate an SQL expression string with bound parameters rendered inline
    for the given SQLAlchemy statement.
    WARNING: This method of escaping is insecure, incomplete, and for debugging
    purposes only. Executing SQL statements with inline-rendered user values is
    extremely insecure.
    Based on http://stackoverflow.com/questions/5631078/sqlalchemy-print-the-actual-query
    """
    if isinstance(statement, Query):
        if dialect is None:
            dialect = statement.session.bind.dialect
        statement = statement.statement
    elif dialect is None:
        dialect = statement.bind.dialect

    class LiteralCompiler(dialect.statement_compiler):

        def visit_bindparam(self, bindparam, within_columns_clause=False,
                            literal_binds=False, **kwargs):
            return self.render_literal_value(bindparam.value, bindparam.type)

        def render_array_value(self, val, item_type):
            if isinstance(val, list):
                return "{%s}" % ",".join([self.render_array_value(x, item_type) for x in val])
            return self.render_literal_value(val, item_type)

        def render_literal_value(self, value, type_):
            if isinstance(value, long):
                return str(value)
            elif isinstance(value, (basestring, date, datetime, timedelta)):
                return "'%s'" % str(value).replace("'", "''")
            elif isinstance(value, list):
                return "'{%s}'" % (",".join([self.render_array_value(x, type_.item_type) for x in value]))
            return super(LiteralCompiler, self).render_literal_value(value, type_)

    return LiteralCompiler(dialect, statement).process(statement)

Tested to two levels of nested arrays.

How to iterate through a list of dictionaries in Jinja template?

As a sidenote to @Navaneethan 's answer, Jinja2 is able to do "regular" item selections for the list and the dictionary, given we know the key of the dictionary, or the locations of items in the list.

Data:

parent_dict = [{'A':'val1','B':'val2', 'content': [["1.1", "2.2"]]},{'A':'val3','B':'val4', 'content': [["3.3", "4.4"]]}]

in Jinja2 iteration:

{% for dict_item in parent_dict %}
   This example has {{dict_item['A']}} and {{dict_item['B']}}:
       with the content --
       {% for item in dict_item['content'] %}{{item[0]}} and {{item[1]}}{% endfor %}.
{% endfor %}

The rendered output:

This example has val1 and val2:
    with the content --
    1.1 and 2.2.

This example has val3 and val4:
   with the content --
   3.3 and 4.4.

How to override trait function and call it from the overridden function?

If the class implements the method directly, it will not use the traits version. Perhaps what you are thinking of is:

trait A {
    function calc($v) {
        return $v+1;
    }
}

class MyClass {
    function calc($v) {
        return $v+2;
    }
}

class MyChildClass extends MyClass{
}

class MyTraitChildClass extends MyClass{
    use A;
}

print (new MyChildClass())->calc(2); // will print 4

print (new MyTraitChildClass())->calc(2); // will print 3

Because the child classes do not implement the method directly, they will first use that of the trait if there otherwise use that of the parent class.

If you want, the trait can use method in the parent class (assuming you know the method would be there) e.g.

trait A {
    function calc($v) {
        return parent::calc($v*3);
    }
}
// .... other code from above
print (new MyTraitChildClass())->calc(2); // will print 8 (2*3 + 2)

You can also provide for ways to override, but still access the trait method as follows:

trait A {
    function trait_calc($v) {
        return $v*3;
    }
}

class MyClass {
    function calc($v) {
        return $v+2;
    }
}


class MyTraitChildClass extends MyClass{
    use A {
      A::trait_calc as calc;
    }
}


class MySecondTraitChildClass extends MyClass{
    use A {
      A::trait_calc as calc;
    }

    public function calc($v) {
      return $this->trait_calc($v)+.5;
    }
}


print (new MyTraitChildClass())->calc(2); // will print 6
echo "\n";
print (new MySecondTraitChildClass())->calc(2); // will print 6.5

You can see it work at http://sandbox.onlinephpfunctions.com/code/e53f6e8f9834aea5e038aec4766ac7e1c19cc2b5

Not able to change TextField Border Color

Well, I really don't know why the color assigned to border does not work. But you can control the border color using other border properties of the textfield. They are:

  1. disabledBorder: Is activated when enabled is set to false
  2. enabledBorder: Is activated when enabled is set to true (by default enabled property of TextField is true)
  3. errorBorder: Is activated when there is some error (i.e. a failed validate)
  4. focusedBorder: Is activated when we click/focus on the TextField.
  5. focusedErrorBorder: Is activated when there is error and we are currently focused on that TextField.

A code snippet is given below:

TextField(
 enabled: false, // to trigger disabledBorder
 decoration: InputDecoration(
   filled: true,
   fillColor: Color(0xFFF2F2F2),
   focusedBorder: OutlineInputBorder(
     borderRadius: BorderRadius.all(Radius.circular(4)),
     borderSide: BorderSide(width: 1,color: Colors.red),
   ),
   disabledBorder: OutlineInputBorder(
     borderRadius: BorderRadius.all(Radius.circular(4)),
     borderSide: BorderSide(width: 1,color: Colors.orange),
   ),
   enabledBorder: OutlineInputBorder(
     borderRadius: BorderRadius.all(Radius.circular(4)),
     borderSide: BorderSide(width: 1,color: Colors.green),
   ),
   border: OutlineInputBorder(
     borderRadius: BorderRadius.all(Radius.circular(4)),
     borderSide: BorderSide(width: 1,)
   ),
   errorBorder: OutlineInputBorder(
     borderRadius: BorderRadius.all(Radius.circular(4)),
     borderSide: BorderSide(width: 1,color: Colors.black)
   ),
   focusedErrorBorder: OutlineInputBorder(
     borderRadius: BorderRadius.all(Radius.circular(4)),
     borderSide: BorderSide(width: 1,color: Colors.yellowAccent)
   ),
   hintText: "HintText",
   hintStyle: TextStyle(fontSize: 16,color: Color(0xFFB3B1B1)),
   errorText: snapshot.error,
 ),
 controller: _passwordController,
 onChanged: _authenticationFormBloc.onPasswordChanged,
                            obscureText: false,
),

disabledBorder:

disabledBorder


enabledBorder:

enabledBorder

focusedBorder:

focusedBorder

errorBorder:

errorBorder

errorFocusedBorder:

errorFocusedBorder

Hope it helps you.

How to define an enumerated type (enum) in C?

As written, there's nothing wrong with your code. Are you sure you haven't done something like

int strategy;
...
enum {RANDOM, IMMEDIATE, SEARCH} strategy;

What lines do the error messages point to? When it says "previous declaration of 'strategy' was here", what's "here" and what does it show?

Pandas rename column by position?

try this

df.rename(columns={ df.columns[1]: "your value" }, inplace = True)

jQuery checkbox checked state changed event

perhaps this may be an alternative for you.

<input name="chkproperty" onchange="($(this).prop('checked') ? $(this).val(true) : $(this).val(false))" type="checkbox" value="true" />`

How can I remove "\r\n" from a string in C#? Can I use a regular expression?

Try this:

private void txtEntry_KeyUp(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            string trimText;

            trimText = this.txtEntry.Text.Replace("\r\n", "").ToString();
            this.txtEntry.Text = trimText;
            btnEnter.PerformClick();
        }
    }

Codeigniter LIKE with wildcard(%)

  $this->db->like('title', 'match', 'before'); 
 // Produces: WHERE title LIKE '%match' 

 $this->db->like('title', 'match', 'after'); 
// Produces: WHERE title LIKE 'match%' 

$this->db->like('title', 'match', 'both'); 
// Produces: WHERE title LIKE '%match%'

How can I insert multiple rows into oracle with a sequence value?

insert into TABLE_NAME
(COL1,COL2)
WITH
data AS
(
    select 'some value'    x from dual
    union all
    select 'another value' x from dual
)
SELECT my_seq.NEXTVAL, x 
FROM data
;

I think that is what you want, but i don't have access to oracle to test it right now.

Eclipse - Failed to load class "org.slf4j.impl.StaticLoggerBinder"

Eclipse Juno, Indigo and Kepler when using the bundled maven version(m2e), are not suppressing the message SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". This behaviour is present from the m2e version 1.1.0.20120530-0009 and onwards.

Although, this is indicated as an error your logs will be saved normally. The highlighted error will still be present until there is a fix of this bug. More about this in the m2e support site.

The current available solution is to use an external maven version rather than the bundled version of Eclipse. You can find about this solution and more details regarding this bug in the question below which i believe describes the same problem you are facing.

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". error

PostgreSQL psql terminal command

Use \x Example from postgres manual:

    postgres=# \x
    postgres=# SELECT * FROM pg_stat_statements ORDER BY total_time DESC LIMIT 3;
    -[ RECORD 1 ]------------------------------------------------------------
    userid     | 10
    dbid       | 63781
    query      | UPDATE branches SET bbalance = bbalance + $1 WHERE bid = $2;
    calls      | 3000
    total_time | 20.716706
    rows       | 3000
    -[ RECORD 2 ]------------------------------------------------------------
    userid     | 10
    dbid       | 63781
    query      | UPDATE tellers SET tbalance = tbalance + $1 WHERE tid = $2;
    calls      | 3000
    total_time | 17.1107649999999
    rows       | 3000
    -[ RECORD 3 ]------------------------------------------------------------
    userid     | 10
    dbid       | 63781
    query      | UPDATE accounts SET abalance = abalance + $1 WHERE aid = $2;
    calls      | 3000
    total_time | 0.645601
    rows       | 3000

Using ALTER to drop a column if it exists in MySQL

I realise this thread is quite old now, but I was having the same problem. This was my very basic solution using the MySQL Workbench, but it worked fine...

  1. get a new sql editor and execute SHOW TABLES to get a list of your tables
  2. select all of the rows, and choose copy to clipboard (unquoted) from the context menu
  3. paste the list of names into another editor tab
  4. write your query, ie ALTER TABLE x DROP a;
  5. do some copying and pasting, so you end up with separate query for each table
  6. Toggle whether the workbench should stop when an error occurs
  7. Hit execute and look through the output log

any tables which had the table now haven't any tables which didn't will have shown an error in the logs

then you can find/replace 'drop a' change it to 'ADD COLUMN b INT NULL' etc and run the whole thing again....

a bit clunky, but at last you get the end result and you can control/monitor the whole process and remember to save you sql scripts in case you need them again.

How to switch Python versions in Terminal?

Here is a nice and simple way to do it (but on CENTOS), without braking the operating system.

yum install scl-utils

next

yum install centos-release-scl-rh

And lastly you install the version that you want, lets say python3.5

yum install rh-python35

And lastly:

scl enable rh-python35 bash

Since MAC-OS is a unix operating system, the way to do it it should be quite similar.

How to filter by string in JSONPath?

Drop the quotes:

List<Object> bugs = JsonPath.read(githubIssues, "$..labels[?(@.name==bug)]");

See also this Json Path Example page

How do I check whether a checkbox is checked in jQuery?

Using pure JavaScript:

let checkbox = document.getElementById('checkboxID');

if(checkbox.checked) {
  alert('is checked');
} else {
  alert('not checked yet');
}

Auto-loading lib files in Rails 4

Though this does not directly answer the question, but I think it is a good alternative to avoid the question altogether.

To avoid all the autoload_paths or eager_load_paths hassle, create a "lib" or a "misc" directory under "app" directory. Place codes as you would normally do in there, and Rails will load files just like how it will load (and reload) model files.

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

If you think a 64-bit DIV instruction is a good way to divide by two, then no wonder the compiler's asm output beat your hand-written code, even with -O0 (compile fast, no extra optimization, and store/reload to memory after/before every C statement so a debugger can modify variables).

See Agner Fog's Optimizing Assembly guide to learn how to write efficient asm. He also has instruction tables and a microarch guide for specific details for specific CPUs. See also the tag wiki for more perf links.

See also this more general question about beating the compiler with hand-written asm: Is inline assembly language slower than native C++ code?. TL:DR: yes if you do it wrong (like this question).

Usually you're fine letting the compiler do its thing, especially if you try to write C++ that can compile efficiently. Also see is assembly faster than compiled languages?. One of the answers links to these neat slides showing how various C compilers optimize some really simple functions with cool tricks. Matt Godbolt's CppCon2017 talk “What Has My Compiler Done for Me Lately? Unbolting the Compiler's Lid” is in a similar vein.


even:
    mov rbx, 2
    xor rdx, rdx
    div rbx

On Intel Haswell, div r64 is 36 uops, with a latency of 32-96 cycles, and a throughput of one per 21-74 cycles. (Plus the 2 uops to set up RBX and zero RDX, but out-of-order execution can run those early). High-uop-count instructions like DIV are microcoded, which can also cause front-end bottlenecks. In this case, latency is the most relevant factor because it's part of a loop-carried dependency chain.

shr rax, 1 does the same unsigned division: It's 1 uop, with 1c latency, and can run 2 per clock cycle.

For comparison, 32-bit division is faster, but still horrible vs. shifts. idiv r32 is 9 uops, 22-29c latency, and one per 8-11c throughput on Haswell.


As you can see from looking at gcc's -O0 asm output (Godbolt compiler explorer), it only uses shifts instructions. clang -O0 does compile naively like you thought, even using 64-bit IDIV twice. (When optimizing, compilers do use both outputs of IDIV when the source does a division and modulus with the same operands, if they use IDIV at all)

GCC doesn't have a totally-naive mode; it always transforms through GIMPLE, which means some "optimizations" can't be disabled. This includes recognizing division-by-constant and using shifts (power of 2) or a fixed-point multiplicative inverse (non power of 2) to avoid IDIV (see div_by_13 in the above godbolt link).

gcc -Os (optimize for size) does use IDIV for non-power-of-2 division, unfortunately even in cases where the multiplicative inverse code is only slightly larger but much faster.


Helping the compiler

(summary for this case: use uint64_t n)

First of all, it's only interesting to look at optimized compiler output. (-O3). -O0 speed is basically meaningless.

Look at your asm output (on Godbolt, or see How to remove "noise" from GCC/clang assembly output?). When the compiler doesn't make optimal code in the first place: Writing your C/C++ source in a way that guides the compiler into making better code is usually the best approach. You have to know asm, and know what's efficient, but you apply this knowledge indirectly. Compilers are also a good source of ideas: sometimes clang will do something cool, and you can hand-hold gcc into doing the same thing: see this answer and what I did with the non-unrolled loop in @Veedrac's code below.)

This approach is portable, and in 20 years some future compiler can compile it to whatever is efficient on future hardware (x86 or not), maybe using new ISA extension or auto-vectorizing. Hand-written x86-64 asm from 15 years ago would usually not be optimally tuned for Skylake. e.g. compare&branch macro-fusion didn't exist back then. What's optimal now for hand-crafted asm for one microarchitecture might not be optimal for other current and future CPUs. Comments on @johnfound's answer discuss major differences between AMD Bulldozer and Intel Haswell, which have a big effect on this code. But in theory, g++ -O3 -march=bdver3 and g++ -O3 -march=skylake will do the right thing. (Or -march=native.) Or -mtune=... to just tune, without using instructions that other CPUs might not support.

My feeling is that guiding the compiler to asm that's good for a current CPU you care about shouldn't be a problem for future compilers. They're hopefully better than current compilers at finding ways to transform code, and can find a way that works for future CPUs. Regardless, future x86 probably won't be terrible at anything that's good on current x86, and the future compiler will avoid any asm-specific pitfalls while implementing something like the data movement from your C source, if it doesn't see something better.

Hand-written asm is a black-box for the optimizer, so constant-propagation doesn't work when inlining makes an input a compile-time constant. Other optimizations are also affected. Read https://gcc.gnu.org/wiki/DontUseInlineAsm before using asm. (And avoid MSVC-style inline asm: inputs/outputs have to go through memory which adds overhead.)

In this case: your n has a signed type, and gcc uses the SAR/SHR/ADD sequence that gives the correct rounding. (IDIV and arithmetic-shift "round" differently for negative inputs, see the SAR insn set ref manual entry). (IDK if gcc tried and failed to prove that n can't be negative, or what. Signed-overflow is undefined behaviour, so it should have been able to.)

You should have used uint64_t n, so it can just SHR. And so it's portable to systems where long is only 32-bit (e.g. x86-64 Windows).


BTW, gcc's optimized asm output looks pretty good (using unsigned long n): the inner loop it inlines into main() does this:

 # from gcc5.4 -O3  plus my comments

 # edx= count=1
 # rax= uint64_t n

.L9:                   # do{
    lea    rcx, [rax+1+rax*2]   # rcx = 3*n + 1
    mov    rdi, rax
    shr    rdi         # rdi = n>>1;
    test   al, 1       # set flags based on n%2 (aka n&1)
    mov    rax, rcx
    cmove  rax, rdi    # n= (n%2) ? 3*n+1 : n/2;
    add    edx, 1      # ++count;
    cmp    rax, 1
    jne   .L9          #}while(n!=1)

  cmp/branch to update max and maxi, and then do the next n

The inner loop is branchless, and the critical path of the loop-carried dependency chain is:

  • 3-component LEA (3 cycles)
  • cmov (2 cycles on Haswell, 1c on Broadwell or later).

Total: 5 cycle per iteration, latency bottleneck. Out-of-order execution takes care of everything else in parallel with this (in theory: I haven't tested with perf counters to see if it really runs at 5c/iter).

The FLAGS input of cmov (produced by TEST) is faster to produce than the RAX input (from LEA->MOV), so it's not on the critical path.

Similarly, the MOV->SHR that produces CMOV's RDI input is off the critical path, because it's also faster than the LEA. MOV on IvyBridge and later has zero latency (handled at register-rename time). (It still takes a uop, and a slot in the pipeline, so it's not free, just zero latency). The extra MOV in the LEA dep chain is part of the bottleneck on other CPUs.

The cmp/jne is also not part of the critical path: it's not loop-carried, because control dependencies are handled with branch prediction + speculative execution, unlike data dependencies on the critical path.


Beating the compiler

GCC did a pretty good job here. It could save one code byte by using inc edx instead of add edx, 1, because nobody cares about P4 and its false-dependencies for partial-flag-modifying instructions.

It could also save all the MOV instructions, and the TEST: SHR sets CF= the bit shifted out, so we can use cmovc instead of test / cmovz.

 ### Hand-optimized version of what gcc does
.L9:                       #do{
    lea     rcx, [rax+1+rax*2] # rcx = 3*n + 1
    shr     rax, 1         # n>>=1;    CF = n&1 = n%2
    cmovc   rax, rcx       # n= (n&1) ? 3*n+1 : n/2;
    inc     edx            # ++count;
    cmp     rax, 1
    jne     .L9            #}while(n!=1)

See @johnfound's answer for another clever trick: remove the CMP by branching on SHR's flag result as well as using it for CMOV: zero only if n was 1 (or 0) to start with. (Fun fact: SHR with count != 1 on Nehalem or earlier causes a stall if you read the flag results. That's how they made it single-uop. The shift-by-1 special encoding is fine, though.)

Avoiding MOV doesn't help with the latency at all on Haswell (Can x86's MOV really be "free"? Why can't I reproduce this at all?). It does help significantly on CPUs like Intel pre-IvB, and AMD Bulldozer-family, where MOV is not zero-latency. The compiler's wasted MOV instructions do affect the critical path. BD's complex-LEA and CMOV are both lower latency (2c and 1c respectively), so it's a bigger fraction of the latency. Also, throughput bottlenecks become an issue, because it only has two integer ALU pipes. See @johnfound's answer, where he has timing results from an AMD CPU.

Even on Haswell, this version may help a bit by avoiding some occasional delays where a non-critical uop steals an execution port from one on the critical path, delaying execution by 1 cycle. (This is called a resource conflict). It also saves a register, which may help when doing multiple n values in parallel in an interleaved loop (see below).

LEA's latency depends on the addressing mode, on Intel SnB-family CPUs. 3c for 3 components ([base+idx+const], which takes two separate adds), but only 1c with 2 or fewer components (one add). Some CPUs (like Core2) do even a 3-component LEA in a single cycle, but SnB-family doesn't. Worse, Intel SnB-family standardizes latencies so there are no 2c uops, otherwise 3-component LEA would be only 2c like Bulldozer. (3-component LEA is slower on AMD as well, just not by as much).

So lea rcx, [rax + rax*2] / inc rcx is only 2c latency, faster than lea rcx, [rax + rax*2 + 1], on Intel SnB-family CPUs like Haswell. Break-even on BD, and worse on Core2. It does cost an extra uop, which normally isn't worth it to save 1c latency, but latency is the major bottleneck here and Haswell has a wide enough pipeline to handle the extra uop throughput.

Neither gcc, icc, nor clang (on godbolt) used SHR's CF output, always using an AND or TEST. Silly compilers. :P They're great pieces of complex machinery, but a clever human can often beat them on small-scale problems. (Given thousands to millions of times longer to think about it, of course! Compilers don't use exhaustive algorithms to search for every possible way to do things, because that would take too long when optimizing a lot of inlined code, which is what they do best. They also don't model the pipeline in the target microarchitecture, at least not in the same detail as IACA or other static-analysis tools; they just use some heuristics.)


Simple loop unrolling won't help; this loop bottlenecks on the latency of a loop-carried dependency chain, not on loop overhead / throughput. This means it would do well with hyperthreading (or any other kind of SMT), since the CPU has lots of time to interleave instructions from two threads. This would mean parallelizing the loop in main, but that's fine because each thread can just check a range of n values and produce a pair of integers as a result.

Interleaving by hand within a single thread might be viable, too. Maybe compute the sequence for a pair of numbers in parallel, since each one only takes a couple registers, and they can all update the same max / maxi. This creates more instruction-level parallelism.

The trick is deciding whether to wait until all the n values have reached 1 before getting another pair of starting n values, or whether to break out and get a new start point for just one that reached the end condition, without touching the registers for the other sequence. Probably it's best to keep each chain working on useful data, otherwise you'd have to conditionally increment its counter.


You could maybe even do this with SSE packed-compare stuff to conditionally increment the counter for vector elements where n hadn't reached 1 yet. And then to hide the even longer latency of a SIMD conditional-increment implementation, you'd need to keep more vectors of n values up in the air. Maybe only worth with 256b vector (4x uint64_t).

I think the best strategy to make detection of a 1 "sticky" is to mask the vector of all-ones that you add to increment the counter. So after you've seen a 1 in an element, the increment-vector will have a zero, and +=0 is a no-op.

Untested idea for manual vectorization

# starting with YMM0 = [ n_d, n_c, n_b, n_a ]  (64-bit elements)
# ymm4 = _mm256_set1_epi64x(1):  increment vector
# ymm5 = all-zeros:  count vector

.inner_loop:
    vpaddq    ymm1, ymm0, xmm0
    vpaddq    ymm1, ymm1, xmm0
    vpaddq    ymm1, ymm1, set1_epi64(1)     # ymm1= 3*n + 1.  Maybe could do this more efficiently?

    vprllq    ymm3, ymm0, 63                # shift bit 1 to the sign bit

    vpsrlq    ymm0, ymm0, 1                 # n /= 2

    # FP blend between integer insns may cost extra bypass latency, but integer blends don't have 1 bit controlling a whole qword.
    vpblendvpd ymm0, ymm0, ymm1, ymm3       # variable blend controlled by the sign bit of each 64-bit element.  I might have the source operands backwards, I always have to look this up.

    # ymm0 = updated n  in each element.

    vpcmpeqq ymm1, ymm0, set1_epi64(1)
    vpandn   ymm4, ymm1, ymm4         # zero out elements of ymm4 where the compare was true

    vpaddq   ymm5, ymm5, ymm4         # count++ in elements where n has never been == 1

    vptest   ymm4, ymm4
    jnz  .inner_loop
    # Fall through when all the n values have reached 1 at some point, and our increment vector is all-zero

    vextracti128 ymm0, ymm5, 1
    vpmaxq .... crap this doesn't exist
    # Actually just delay doing a horizontal max until the very very end.  But you need some way to record max and maxi.

You can and should implement this with intrinsics instead of hand-written asm.


Algorithmic / implementation improvement:

Besides just implementing the same logic with more efficient asm, look for ways to simplify the logic, or avoid redundant work. e.g. memoize to detect common endings to sequences. Or even better, look at 8 trailing bits at once (gnasher's answer)

@EOF points out that tzcnt (or bsf) could be used to do multiple n/=2 iterations in one step. That's probably better than SIMD vectorizing; no SSE or AVX instruction can do that. It's still compatible with doing multiple scalar ns in parallel in different integer registers, though.

So the loop might look like this:

goto loop_entry;  // C++ structured like the asm, for illustration only
do {
   n = n*3 + 1;
  loop_entry:
   shift = _tzcnt_u64(n);
   n >>= shift;
   count += shift;
} while(n != 1);

This may do significantly fewer iterations, but variable-count shifts are slow on Intel SnB-family CPUs without BMI2. 3 uops, 2c latency. (They have an input dependency on the FLAGS because count=0 means the flags are unmodified. They handle this as a data dependency, and take multiple uops because a uop can only have 2 inputs (pre-HSW/BDW anyway)). This is the kind that people complaining about x86's crazy-CISC design are referring to. It makes x86 CPUs slower than they would be if the ISA was designed from scratch today, even in a mostly-similar way. (i.e. this is part of the "x86 tax" that costs speed / power.) SHRX/SHLX/SARX (BMI2) are a big win (1 uop / 1c latency).

It also puts tzcnt (3c on Haswell and later) on the critical path, so it significantly lengthens the total latency of the loop-carried dependency chain. It does remove any need for a CMOV, or for preparing a register holding n>>1, though. @Veedrac's answer overcomes all this by deferring the tzcnt/shift for multiple iterations, which is highly effective (see below).

We can safely use BSF or TZCNT interchangeably, because n can never be zero at that point. TZCNT's machine-code decodes as BSF on CPUs that don't support BMI1. (Meaningless prefixes are ignored, so REP BSF runs as BSF).

TZCNT performs much better than BSF on AMD CPUs that support it, so it can be a good idea to use REP BSF, even if you don't care about setting ZF if the input is zero rather than the output. Some compilers do this when you use __builtin_ctzll even with -mno-bmi.

They perform the same on Intel CPUs, so just save the byte if that's all that matters. TZCNT on Intel (pre-Skylake) still has a false-dependency on the supposedly write-only output operand, just like BSF, to support the undocumented behaviour that BSF with input = 0 leaves its destination unmodified. So you need to work around that unless optimizing only for Skylake, so there's nothing to gain from the extra REP byte. (Intel often goes above and beyond what the x86 ISA manual requires, to avoid breaking widely-used code that depends on something it shouldn't, or that is retroactively disallowed. e.g. Windows 9x's assumes no speculative prefetching of TLB entries, which was safe when the code was written, before Intel updated the TLB management rules.)

Anyway, LZCNT/TZCNT on Haswell have the same false dep as POPCNT: see this Q&A. This is why in gcc's asm output for @Veedrac's code, you see it breaking the dep chain with xor-zeroing on the register it's about to use as TZCNT's destination when it doesn't use dst=src. Since TZCNT/LZCNT/POPCNT never leave their destination undefined or unmodified, this false dependency on the output on Intel CPUs is a performance bug / limitation. Presumably it's worth some transistors / power to have them behave like other uops that go to the same execution unit. The only perf upside is interaction with another uarch limitation: they can micro-fuse a memory operand with an indexed addressing mode on Haswell, but on Skylake where Intel removed the false dep for LZCNT/TZCNT they "un-laminate" indexed addressing modes while POPCNT can still micro-fuse any addr mode.


Improvements to ideas / code from other answers:

@hidefromkgb's answer has a nice observation that you're guaranteed to be able to do one right shift after a 3n+1. You can compute this more even more efficiently than just leaving out the checks between steps. The asm implementation in that answer is broken, though (it depends on OF, which is undefined after SHRD with a count > 1), and slow: ROR rdi,2 is faster than SHRD rdi,rdi,2, and using two CMOV instructions on the critical path is slower than an extra TEST that can run in parallel.

I put tidied / improved C (which guides the compiler to produce better asm), and tested+working faster asm (in comments below the C) up on Godbolt: see the link in @hidefromkgb's answer. (This answer hit the 30k char limit from the large Godbolt URLs, but shortlinks can rot and were too long for goo.gl anyway.)

Also improved the output-printing to convert to a string and make one write() instead of writing one char at a time. This minimizes impact on timing the whole program with perf stat ./collatz (to record performance counters), and I de-obfuscated some of the non-critical asm.


@Veedrac's code

I got a minor speedup from right-shifting as much as we know needs doing, and checking to continue the loop. From 7.5s for limit=1e8 down to 7.275s, on Core2Duo (Merom), with an unroll factor of 16.

code + comments on Godbolt. Don't use this version with clang; it does something silly with the defer-loop. Using a tmp counter k and then adding it to count later changes what clang does, but that slightly hurts gcc.

See discussion in comments: Veedrac's code is excellent on CPUs with BMI1 (i.e. not Celeron/Pentium)

Get a list of all the files in a directory (recursive)

This is what I came up with for a gradle build script:

task doLast {
    ext.FindFile = { list, curPath ->
        def files = file(curPath).listFiles().sort()

        files.each {  File file ->

            if (file.isFile()) {
                list << file
            }
            else {
                list << file  // If you want the directories in the list

                list = FindFile( list, file.path) 
            }
        }
        return list
    }

    def list = []
    def theFile = FindFile(list, "${project.projectDir}")

    list.each {
        println it.path
    }
}

HTTP GET in VBS

Dim o
Set o = CreateObject("MSXML2.XMLHTTP")
o.open "GET", "http://www.example.com", False
o.send
' o.responseText now holds the response as a string.

How can I limit possible inputs in a HTML5 "number" element?

As I found out you cannot use any of onkeydown, onkeypress or onkeyup events for a complete solution including mobile browsers. By the way onkeypress is deprecated and not present anymore in chrome/opera for android (see: UI Events W3C Working Draft, 04 August 2016).

I figured out a solution using the oninput event only. You may have to do additional number checking as required such as negative/positive sign or decimal and thousand separators and the like but as a start the following should suffice:

_x000D_
_x000D_
function checkMaxLength(event) {_x000D_
 // Prepare to restore the previous value._x000D_
 if (this.oldValue === undefined) {_x000D_
  this.oldValue = this.defaultValue;_x000D_
 }_x000D_
_x000D_
 if (this.value.length > this.maxLength) {_x000D_
  // Set back to the previous value._x000D_
  this.value = oldVal;_x000D_
 }_x000D_
 else {_x000D_
  // Store the previous value._x000D_
  this.oldValue = this.value;_x000D_
  _x000D_
  // Make additional checks for +/- or ./, etc._x000D_
  // Also consider to combine 'maxlength'_x000D_
  // with 'min' and 'max' to prevent wrong submits._x000D_
 }_x000D_
}
_x000D_
_x000D_
_x000D_

I would also recommend to combine maxlength with min and max to prevent wrong submits as stated above several times.

jQuery get the name of a select option

For anyone who comes across this late, like me.

As others have stated, name isn't a valid attribute of an option element. Combining the accepted answer above with the answer from this other question, you get:

$(this).find('option:selected').text();

Plotting multiple curves same graph and same scale

My solution is to use ggplot2. It takes care of these types of things automatically. The biggest thing is to arrange the data appropriately.

y1 <- c(100, 200, 300, 400, 500)
y2 <- c(1, 2, 3, 4, 5)
x <- c(1, 2, 3, 4, 5)
df <- data.frame(x=rep(x,2), y=c(y1, y2), class=c(rep("y1", 5), rep("y2", 5)))

Then use ggplot2 to plot it

library(ggplot2)
ggplot(df, aes(x=x, y=y, color=class)) + geom_point()

This is saying plot the data in df, and separate the points by class.

The plot generated isenter image description here

How to pass a parameter to Vue @click event handler

When you are using Vue directives, the expressions are evaluated in the context of Vue, so you don't need to wrap things in {}.

@click is just shorthand for v-on:click directive so the same rules apply.

In your case, simply use @click="addToCount(item.contactID)"

Filling a List with all enum values in Java

List<Something> result = new ArrayList<Something>(all);

EnumSet is a Java Collection, as it implements the Set interface:

public interface Set<E> extends Collection<E> 

So anything you can do with a Collection you can do with an EnumSet.

Android how to convert int to String?

Normal ways would be Integer.toString(i) or String.valueOf(i).

int i = 5;
String strI = String.valueOf(i);

Or

int aInt = 1;    
String aString = Integer.toString(aInt);

Read String line by line

You can also use the split method of String:

String[] lines = myString.split(System.getProperty("line.separator"));

This gives you all lines in a handy array.

I don't know about the performance of split. It uses regular expressions.

What is the idiomatic Go equivalent of C's ternary operator?

If all your branches make side-effects or are computationally expensive the following would a semantically-preserving refactoring:

index := func() int {
    if val > 0 {
        return printPositiveAndReturn(val)
    } else {
        return slowlyReturn(-val)  // or slowlyNegate(val)
    }
}();  # exactly one branch will be evaluated

with normally no overhead (inlined) and, most importantly, without cluttering your namespace with a helper functions that are only used once (which hampers readability and maintenance). Live Example

Note if you were to naively apply Gustavo's approach:

    index := printPositiveAndReturn(val);
    if val <= 0 {
        index = slowlyReturn(-val);  // or slowlyNegate(val)
    }

you'd get a program with a different behavior; in case val <= 0 program would print a non-positive value while it should not! (Analogously, if you reversed the branches, you would introduce overhead by calling a slow function unnecessarily.)

Load HTML File Contents to Div [without the use of iframes]

2019
Using fetch

<script>
fetch('page.html')
  .then(data => data.text())
  .then(html => document.getElementById('elementID').innerHTML = html);
</script>

<div id='elementID'> </div>

fetch needs to receive a http or https link, this means that it won't work locally.

Note: As Altimus Prime said, it is a feature for modern browsers

How to use jQuery to get the current value of a file input field

I've tried this and it works:

 yourelement.next().val();

yourelement could be:

$('#elementIdName').next().val();

good luck!

With block equivalent in C#?

Sometimes you can get away with doing the following:

var fill = cell.Style.Fill;
fill.PatternType = ExcelFillStyle.Solid;
fill.BackgroundColor.SetColor(Color.Gray);
fill.PatternColor = Color.Black;
fill.Gradient = ...

(Code sample for EPPLus @ http://zeeshanumardotnet.blogspot.com)

Creating a segue programmatically

For controllers that are in the storyboard.

jhilgert00 is this what you were looking for?

-(IBAction)nav_goHome:(id)sender {
UIViewController *myController = [self.storyboard instantiateViewControllerWithIdentifier:@"HomeController"];
[self.navigationController pushViewController: myController animated:YES];

}

OR...

[self performSegueWithIdentifier:@"loginMainSegue" sender:self];

Cast a Double Variable to Decimal

use default convertation class: Convert.ToDecimal(Double)

Autowiring two beans implementing same interface - how to set default bean to autowire?

The reason why @Resource(name = "{your child class name}") works but @Autowired sometimes don't work is because of the difference of their Matching sequence

Matching sequence of @Autowire
Type, Qualifier, Name

Matching sequence of @Resource
Name, Type, Qualifier

The more detail explanation can be found here:
Inject and Resource and Autowired annotations

In this case, different child class inherited from the parent class or interface confuses @Autowire, because they are from same type; As @Resource use Name as first matching priority , it works.

How to get a list of column names on Sqlite3 database?

-(NSMutableDictionary*)tableInfo:(NSString *)table
{
  sqlite3_stmt *sqlStatement;
  NSMutableDictionary *result = [[NSMutableDictionary alloc] init];
  const char *sql = [[NSString stringWithFormat:@"pragma table_info('%s')",[table UTF8String]] UTF8String];
  if(sqlite3_prepare(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK)
  {
    NSLog(@"Problem with prepare statement tableInfo %@",[NSString stringWithUTF8String:(const char *)sqlite3_errmsg(db)]);

  }
  while (sqlite3_step(sqlStatement)==SQLITE_ROW)
  {
    [result setObject:@"" forKey:[NSString stringWithUTF8String:(char*)sqlite3_column_text(sqlStatement, 1)]];

  }

  return result;
  }

C#: How to add subitems in ListView

I think the quickest/neatest way to do this:

For each class have string[] obj.ToListViewItem() method and then do this:

foreach(var item in personList)
{
    listView1.Items.Add(new ListViewItem(item.ToListViewItem()));
}

Here is an example definition

public class Person
{
    public string Name { get; set; }
    public string Address { get; set; }
    public DateTime DOB { get; set; }
    public uint ID { get; set; }

    public string[] ToListViewItem()
    {
        return new string[] {
            ID.ToString("000000"),
            Name,
            Address,
            DOB.ToShortDateString()
        };
    }
}

As an added bonus you can have a static method that returns ColumnHeader[] list for setting up the listview columns with

listView1.Columns.AddRange(Person.ListViewHeaders());

WooCommerce - get category for product page

A WC product may belong to none, one or more WC categories. Supposing you just want to get one WC category id.

global $post;
$terms = get_the_terms( $post->ID, 'product_cat' );
foreach ($terms as $term) {
    $product_cat_id = $term->term_id;
    break;
}

Please look into the meta.php file in the "templates/single-product/" folder of the WooCommerce plugin.

<?php echo $product->get_categories( ', ', '<span class="posted_in">' . _n( 'Category:', 'Categories:', sizeof( get_the_terms( $post->ID, 'product_cat' ) ), 'woocommerce' ) . ' ', '.</span>' ); ?>

Invariant Violation: Could not find "store" in either the context or props of "Connect(SportsDatabase)"

Possible solution that worked for me with jest

import React from "react";
import { shallow } from "enzyme";
import { Provider } from "react-redux";
import configureMockStore from "redux-mock-store";
import TestPage from "../TestPage";

const mockStore = configureMockStore();
const store = mockStore({});

describe("Testpage Component", () => {
    it("should render without throwing an error", () => {
        expect(
            shallow(
                <Provider store={store}>
                    <TestPage />
                </Provider>
            ).exists(<h1>Test page</h1>)
        ).toBe(true);
    });
});

Volatile vs Static in Java

If we declare a variable as static, there will be only one copy of the variable. So, whenever different threads access that variable, there will be only one final value for the variable(since there is only one memory location allocated for the variable).

If a variable is declared as volatile, all threads will have their own copy of the variable but the value is taken from the main memory.So, the value of the variable in all the threads will be the same.

So, in both cases, the main point is that the value of the variable is same across all threads.

How to show/hide if variable is null

In this case, myvar should be a boolean value. If this variable is true, it will show the div, if it's false.. It will hide.

Check this out.

find -mtime files older than 1 hour

What about -mmin?

find /var/www/html/audio -daystart -maxdepth 1 -mmin +59 -type f -name "*.mp3" \
    -exec rm -f {} \;

From man find:

-mmin n
        File's data was last modified n minutes ago.

Also, make sure to test this first!

... -exec echo rm -f '{}' \;
          ^^^^ Add the 'echo' so you just see the commands that are going to get
               run instead of actual trying them first.

Better way to convert file sizes in Python

Instead of a size divisor of 1024 * 1024 you could use the << bitwise shifting operator, i.e. 1<<20 to get megabytes, 1<<30 to get gigabytes, etc.

In the simplest scenario you can have e.g. a constant MBFACTOR = float(1<<20) which can then be used with bytes, i.e.: megas = size_in_bytes/MBFACTOR.

Megabytes are usually all that you need, or otherwise something like this can be used:

# bytes pretty-printing
UNITS_MAPPING = [
    (1<<50, ' PB'),
    (1<<40, ' TB'),
    (1<<30, ' GB'),
    (1<<20, ' MB'),
    (1<<10, ' KB'),
    (1, (' byte', ' bytes')),
]


def pretty_size(bytes, units=UNITS_MAPPING):
    """Get human-readable file sizes.
    simplified version of https://pypi.python.org/pypi/hurry.filesize/
    """
    for factor, suffix in units:
        if bytes >= factor:
            break
    amount = int(bytes / factor)

    if isinstance(suffix, tuple):
        singular, multiple = suffix
        if amount == 1:
            suffix = singular
        else:
            suffix = multiple
    return str(amount) + suffix

print(pretty_size(1))
print(pretty_size(42))
print(pretty_size(4096))
print(pretty_size(238048577))
print(pretty_size(334073741824))
print(pretty_size(96995116277763))
print(pretty_size(3125899904842624))

## [Out] ###########################
1 byte
42 bytes
4 KB
227 MB
311 GB
88 TB
2 PB

Programmatically scroll a UIScrollView

With Animation in Swift

scrollView.setContentOffset(CGPointMake(x, y), animated: true)

How do you stop MySQL on a Mac OS install?

For me it's working with a "mysql5"

sudo launchctl unload -w /Library/LaunchDaemons/org.macports.mysql5.plist
sudo launchctl load -w /Library/LaunchDaemons/org.macports.mysql5.plist

How do I compare two string variables in an 'if' statement in Bash?

For string equality comparison, use:

if [[ "$s1" == "$s2" ]]

For string does NOT equal comparison, use:

if [[ "$s1" != "$s2" ]]

For the a contains b, use:

if [[ $s1 == *"$s2"* ]]

(and make sure to add spaces between the symbols):

Bad:

if [["$s1" == "$s2"]]

Good:

if [[ "$s1" == "$s2" ]]

Calling Member Functions within Main C++

You need to create an object since printInformation() is non-static. Try:

int main() {

MyClass o;
o.printInformation();

fgetc( stdin );
return(0);

}

failed to find target with hash string android-23

AndroidSDK > SDK platforms > and install API Level 23

Toggle Checkboxes on/off

Setting 'checked' or null instead of true or false respectively will do the work.

// checkbox selection
var $chk=$(':checkbox');
$chk.prop('checked',$chk.is(':checked') ? null:'checked');

JavaScript: How to get parent element by selector?

Here's a recursive solution:

function closest(el, selector, stopSelector) {
  if(!el || !el.parentElement) return null
  else if(stopSelector && el.parentElement.matches(stopSelector)) return null
  else if(el.parentElement.matches(selector)) return el.parentElement
  else return closest(el.parentElement, selector, stopSelector)
}

Import and insert sql.gz file into database with putty

If the mysql dump was a .gz file, you need to gunzip to uncompress the file by typing $ gunzip mysqldump.sql.gz

This will uncompress the .gz file and will just store mysqldump.sql in the same location.

Type the following command to import sql data file:

$ mysql -u username -p -h localhost test-database < mysqldump.sql password: _

SQL Not Like Statement not working

I just came across the same issue, and solved it, but not before I found this post. And seeing as your question wasn't really answered, here's my solution (which will hopefully work for you, or anyone else searching for the same thing I did;

Instead of;

... AND WPP.COMMENT NOT LIKE '%CORE%' ...

Try;

... AND NOT WPP.COMMENT LIKE '%CORE%' ...

Basically moving the "NOT" the other side of the field I was evaluating worked for me.

Binding a Button's visibility to a bool value in ViewModel

Generally there are two ways to do it, a converter class or a property in the Viewmodel that essentially converts the value for you.

I tend to use the property approach if it is a one off conversion. If you want to reuse it, use the converter. Below, find an example of the converter:

<ValueConversion(GetType(Boolean), GetType(Visibility))> _
Public Class BoolToVisibilityConverter
    Implements IValueConverter

    Public Function Convert(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.Convert

        If value IsNot Nothing Then
            If value = True Then 
                Return Visibility.Visible
            Else
                Return Visibility.Collapsed
            End If
        Else
            Return Visibility.Collapsed
        End If
    End Function

    Public Function ConvertBack(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.ConvertBack
        Throw New NotImplementedException
    End Function
End Class

A ViewModel property method would just check the boolean property value, and return a visibility based on that. Be sure to implement INotifyPropertyChanged and call it on both the Boolean and Visibility properties to updated properly.

Order data frame rows according to vector with specific order

We can adjust the factor levels based on target and use it in arrange

library(dplyr)
df %>% arrange(factor(name, levels = target))

#  name value
#1    b  TRUE
#2    c FALSE
#3    a  TRUE
#4    d FALSE

Or order it and use it in slice

df %>% slice(order(factor(name, levels = target)))

Difference Between Select and SelectMany

I understand SelectMany to work like a join shortcut.

So you can:

var orders = customers
             .Where(c => c.CustomerName == "Acme")
             .SelectMany(c => c.Orders);

IF-THEN-ELSE statements in postgresql

In general, an alternative to case when ... is coalesce(nullif(x,bad_value),y) (that cannot be used in OP's case). For example,

select coalesce(nullif(y,''),x), coalesce(nullif(x,''),y), *
from (     (select 'abc' as x, '' as y)
 union all (select 'def' as x, 'ghi' as y)
 union all (select '' as x, 'jkl' as y)
 union all (select null as x, 'mno' as y)
 union all (select 'pqr' as x, null as y)
) q

gives:

 coalesce | coalesce |  x  |  y  
----------+----------+-----+-----
 abc      | abc      | abc | 
 ghi      | def      | def | ghi
 jkl      | jkl      |     | jkl
 mno      | mno      |     | mno
 pqr      | pqr      | pqr | 
(5 rows)

How to add a delay for a 2 or 3 seconds

You could use Thread.Sleep() function, e.g.

int milliseconds = 2000;
Thread.Sleep(milliseconds);

that completely stops the execution of the current thread for 2 seconds.

Probably the most appropriate scenario for Thread.Sleep is when you want to delay the operations in another thread, different from the main e.g. :

 MAIN THREAD        --------------------------------------------------------->
 (UI, CONSOLE ETC.)      |                                      |
                         |                                      |
 OTHER THREAD            ----- ADD A DELAY (Thread.Sleep) ------>

For other scenarios (e.g. starting operations after some time etc.) check Cody's answer.

Using the && operator in an if statement

So to make your expression work, changing && for -a will do the trick.

It is correct like this:

 if [ -f $VAR1 ] && [ -f $VAR2 ] && [ -f $VAR3 ]
 then  ....

or like

 if [[ -f $VAR1 && -f $VAR2 && -f $VAR3 ]]
 then  ....

or even

 if [ -f $VAR1 -a -f $VAR2 -a -f $VAR3 ]
 then  ....

You can find further details in this question bash : Multiple Unary operators in if statement and some references given there like What is the difference between test, [ and [[ ?.

How to start nginx via different port(other than 80)

If you are on windows then below port related server settings are present in file nginx.conf at < nginx installation path >/conf folder.

server {
    listen       80;
    server_name  localhost;
....

Change the port number and restart the instance.

C++ STL Vectors: Get iterator from index?

Actutally std::vector are meant to be used as C tab when needed. (C++ standard requests that for vector implementation , as far as I know - replacement for array in Wikipedia) For instance it is perfectly legal to do this folowing, according to me:

int main()
{

void foo(const char *);

sdt::vector<char> vec;
vec.push_back('h');
vec.push_back('e');
vec.push_back('l');
vec.push_back('l');
vec.push_back('o');
vec.push_back('/0');

foo(&vec[0]);
}

Of course, either foo must not copy the address passed as a parameter and store it somewhere, or you should ensure in your program to never push any new item in vec, or requesting to change its capacity. Or risk segmentation fault...

Therefore in your exemple it leads to

vector.insert(pos, &vec[first_index], &vec[last_index]);

Error handling with PHPMailer

$mail = new PHPMailer();

$mail->AddAddress($email); 
$mail->From     = $from;
$mail->Subject  = $subject; 
$mail->Body     = $body;

if($mail->Send()){
    echo 'Email Successfully Sent!';
}else{
    echo 'Email Sending Failed!';
}

the simplest way to handle email sending successful or failed...