Programs & Examples On #Entity framework ctp5

This tag is for the ADO.NET Entity Framework Community Technical Preview 5

How to use DbContext.Database.SqlQuery<TElement>(sql, params) with stored procedure? EF Code First CTP5

You should supply the SqlParameter instances in the following way:

context.Database.SqlQuery<myEntityType>(
    "mySpName @param1, @param2, @param3",
    new SqlParameter("param1", param1),
    new SqlParameter("param2", param2),
    new SqlParameter("param3", param3)
);

Right way to write JSON deserializer in Spring or extend it

I've searched a lot and the best way I've found so far is on this article:

Class to serialize

package net.sghill.example;

import net.sghill.example.UserDeserializer
import net.sghill.example.UserSerializer
import org.codehaus.jackson.map.annotate.JsonDeserialize;
import org.codehaus.jackson.map.annotate.JsonSerialize;

@JsonDeserialize(using = UserDeserializer.class)
public class User {
    private ObjectId id;
    private String   username;
    private String   password;

    public User(ObjectId id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    }

    public ObjectId getId()       { return id; }
    public String   getUsername() { return username; }
    public String   getPassword() { return password; }
}

Deserializer class

package net.sghill.example;

import net.sghill.example.User;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.ObjectCodec;
import org.codehaus.jackson.map.DeserializationContext;
import org.codehaus.jackson.map.JsonDeserializer;

import java.io.IOException;

public class UserDeserializer extends JsonDeserializer<User> {

    @Override
    public User deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        ObjectCodec oc = jsonParser.getCodec();
        JsonNode node = oc.readTree(jsonParser);
        return new User(null, node.get("username").getTextValue(), node.get("password").getTextValue());
    }
}

Edit: Alternatively you can look at this article which uses new versions of com.fasterxml.jackson.databind.JsonDeserializer.

How to Parse JSON Array with Gson

To conver in Object Array

Gson gson=new Gson();
ElementType [] refVar=gson.fromJson(jsonString,ElementType[].class);

To convert as post type

Gson gson=new Gson();
Post [] refVar=gson.fromJson(jsonString,Post[].class);

To read it as List of objects TypeToken can be used

List<Post> posts=(List<Post>)gson.fromJson(jsonString, 
                     new TypeToken<List<Post>>(){}.getType());

How to create cross-domain request?

One of the way to enable cross domain request on local chrome browser :

  1. Create a short cut of google chrome.
  2. Properties -> append "--disable-web-security --user-data-dir" at the end of target.
  3. Close or kill all process of google chrome.
  4. Restart and hit the UI url.

Now UI and API running on different ports will be able to work together. I hope this helps.

If you are looking for an example of Cross-domain request . I'll put it in fragments for you to get enough idea.

Angular Client

user.service.ts to call the SpringWebservice.

 /** POST: Validates a user for login from Spring webservice */
      loginUrl = 'http://localhost:8091/SpringWebService/login';  // URL to web api

     validUser (user: User): Observable<User> {
        return this.http.post<User>(this.loginUrl, user, httpOptions)
       .pipe(
           catchError(this.handleError('Login User', user))
  );
}

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json;charset=utf-8',
    'Authorization': 'my-auth-token'
  })
};

login.component.html: to accept the user Name and pwd.

<form (ngSubmit)="onSubmit(loginForm)" #loginForm="ngForm">
    <!-- //ngModel is a must for each form-control  -->
  <!-- 1st group -->
  <div class="form-group">
        <label for="name">Name</label>
        <input type="text" class="form-control" id="name" 
                required name="name"  ngModel #name="ngModel"> 

        <div [hidden]="name.valid || name.pristine"
                class="alert alert-danger">
             Name is required
        </div>
  </div> 
  <!-- 2nd group -->
  <div class="form-group">
      <label for="pwd">Password</label>
      <input type="text" class="form-control" id="pwd"
            name="pwd" #pwd required ngModel>
  </div>   

  <button type="submit" class="btn btn-success" [disabled]="!loginForm.valid">Submit</button>

</form>

login.component.ts: calls and subscribes validUser method of user.service.

userModel : User;
onSubmit(loginForm : NgForm) { 
this.submitted = true; 
console.log("User : "+loginForm.value.name + " Valid :"+loginForm.valid)

this.userModel.loggedIn= false;
this.userModel=new 
User(loginForm.value.name.trim(),loginForm.value.pwd.trim())
// Passing the userModel to Service method to invoke WebAPI
this.userService.validUser(this.userModel).subscribe(user=>
    {
      if(user.loggedIn == false){
        console.log("Invalid User/PWD");

       }
      else{
        this.userService.changeUser(this.userModel);
        this.router.navigate(['/home']);
      }
  }
);

user.ts: model.

export class User {

constructor(
    public  name : String,
    public  pwd : String,
    public  email ?: String, //optional
    public  mobile ? : number,//""
    public  loggedIn : boolean = false
){  }
}

Spring Webservice.

package com.rest;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
// This annotation opens door for cross-domain(Cross-origin resource sharing (CORS)) from any host
@CrossOrigin(origins="*") 
public class MainController {

     @RequestMapping(value="/login", method=RequestMethod.POST)
     public User validUser(@RequestBody User user){


         BaseResponse response = new BaseResponse();

         if(user.getName().equalsIgnoreCase("shaz") && user.getPwd().equals("pwd")){

             user.setLoggedIn(true);
         }
         else{

             user.setLoggedIn(false);

         }
         return user;

     }
}

Now when you pass name as "shaz" and pwd as "pwd" in the form and hit submit,it gets validated from the SpringWebService and the loggedIn flag is set to true and the user entity is returned in response. Based on the loggedIn status from response,the user is redirected to home page or an error is thrown.

Login Page and Network Details Login Page

Network details

Note: I have not shared the complete setup and code

Refer this: https://shahbaazdesk.wordpress.com/2018/04/03/angular5-with-spring-webservice/

Run php script as daemon process

Check out https://github.com/shaneharter/PHP-Daemon

This is an object-oriented daemon library. It has built-in support for things like logging and error recovery, and it has support for creating background workers.

What is the meaning of single and double underscore before an object name?

Getting the facts of _ and __ is pretty easy; the other answers express them pretty well. The usage is much harder to determine.

This is how I see it:

_

Should be used to indicate that a function is not for public use as for example an API. This and the import restriction make it behave much like internal in c#.

__

Should be used to avoid name collision in the inheritace hirarchy and to avoid latebinding. Much like private in c#.

==>

If you want to indicate that something is not for public use, but it should act like protected use _. If you want to indicate that something is not for public use, but it should act like private use __.

This is also a quote that I like very much:

The problem is that the author of a class may legitimately think "this attribute/method name should be private, only accessible from within this class definition" and use the __private convention. But later on, a user of that class may make a subclass that legitimately needs access to that name. So either the superclass has to be modified (which may be difficult or impossible), or the subclass code has to use manually mangled names (which is ugly and fragile at best).

But the problem with that is in my opinion that if there's no IDE that warns you when you override methods, finding the error might take you a while if you have accidentially overriden a method from a base-class.

Angular 5 Reactive Forms - Radio Button Group

I tried your code, you didn't assign/bind a value to your formControlName.

In HTML file:

<form [formGroup]="form">
   <label>
     <input type="radio" value="Male" formControlName="gender">
       <span>male</span>
   </label>
   <label>
     <input type="radio" value="Female" formControlName="gender">
       <span>female</span>
   </label>
</form>

In the TS file:

  form: FormGroup;
  constructor(fb: FormBuilder) {
    this.name = 'Angular2'
    this.form = fb.group({
      gender: ['', Validators.required]
    });
  }

Make sure you use Reactive form properly: [formGroup]="form" and you don't need the name attribute.

In my sample. words male and female in span tags are the values display along the radio button and Male and Female values are bind to formControlName

See the screenshot: enter image description here

To make it shorter:

<form [formGroup]="form">
  <input type="radio" value='Male' formControlName="gender" >Male
  <input type="radio" value='Female' formControlName="gender">Female
</form>

enter image description here

Hope it helps:)

Insert auto increment primary key to existing table

I was able to adapt these instructions take a table with an existing non-increment primary key, and add an incrementing primary key to the table and create a new composite primary key with both the old and new keys as a composite primary key using the following code:

DROP TABLE  IF EXISTS SAKAI_USER_ID_MAP;

CREATE TABLE SAKAI_USER_ID_MAP (
       USER_ID             VARCHAR (99) NOT NULL,
       EID                 VARCHAR (255) NOT NULL,
       PRIMARY KEY (USER_ID)
);

INSERT INTO SAKAI_USER_ID_MAP VALUES ('admin', 'admin');
INSERT INTO SAKAI_USER_ID_MAP VALUES ('postmaster', 'postmaster');

ALTER TABLE  SAKAI_USER_ID_MAP 
  DROP PRIMARY KEY, 
  ADD _USER_ID INT AUTO_INCREMENT NOT NULL FIRST, 
  ADD PRIMARY KEY ( _USER_ID, USER_ID );

When this is done, the _USER_ID field exists and has all number values for the primary key exactly as you would expect. With the "DROP TABLE" at the top, you can run this over and over to experiment with variations.

What I have not been able to get working is the situation where there are incoming FOREIGN KEYs that already point at the USER_ID field. I get this message when I try to do a more complex example with an incoming foreign key from another table.

#1025 - Error on rename of './zap/#sql-da07_6d' to './zap/SAKAI_USER_ID_MAP' (errno: 150)

I am guessing that I need to tear down all foreign keys before doing the ALTER table and then rebuild them afterwards. But for now I wanted to share this solution to a more challenging version of the original question in case others ran into this situation.

How to use Switch in SQL Server

The CASE is just a "switch" to return a value - not to execute a whole code block.

You need to change your code to something like this:

SELECT 
   @selectoneCount = CASE @Temp
                         WHEN 1 THEN @selectoneCount + 1
                         WHEN 2 THEN @selectoneCount + 1
                     END

If @temp is set to none of those values (1 or 2), then you'll get back a NULL

How to modify STYLE attribute of element with known ID using JQuery

$("span").mouseover(function () {
$(this).css({"background-color":"green","font-size":"20px","color":"red"});
});

<div>
Sachin Tendulkar has been the most complete batsman of his time, the most prolific     runmaker of all time, and arguably the biggest cricket icon the game has ever known. His batting is based on the purest principles: perfect balance, economy of movement, precision in stroke-making.
</div>

Must JDBC Resultsets and Statements be closed separately although the Connection is closed afterwards?

I'm now using Oracle with Java. Here my point of view :

You should close ResultSet and Statement explicitly because Oracle has problems previously with keeping the cursors open even after closing the connection. If you don't close the ResultSet (cursor) it will throw an error like Maximum open cursors exceeded.

I think you may encounter with the same problem with other databases you use.

Here is tutorial Close ResultSet when finished:

Close ResultSet when finished

Close ResultSet object as soon as you finish working with ResultSet object even though Statement object closes the ResultSet object implicitly when it closes, closing ResultSet explicitly gives chance to garbage collector to recollect memory as early as possible because ResultSet object may occupy lot of memory depending on query.

ResultSet.close();

BigDecimal to string

By using below method you can convert java.math.BigDecimal to String.

   BigDecimal bigDecimal = new BigDecimal("10.0001");
   String bigDecimalString = String.valueOf(bigDecimal.doubleValue());
   System.out.println("bigDecimal value in String: "+bigDecimalString);

Output:
bigDecimal value in String: 10.0001

iOS download and save image inside app

If you are using AFNetworking library to download image and that images are using in UITableview then You can use below code in cellForRowAtIndexPath

 [self setImageWithURL:user.user_ProfilePicturePath toControl:cell.imgView]; 
 
-(void)setImageWithURL:(NSURL*)url toControl:(id)ctrl
{
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    AFImageRequestOperation *operation = [AFImageRequestOperation imageRequestOperationWithRequest:request imageProcessingBlock:nil success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
        if (image) {
            if([ctrl isKindOfClass:[UIButton class]])
            {
                UIButton btn =(UIButton)ctrl;
                [btn setBackgroundImage:image forState:UIControlStateNormal];
            }
            else
            {
                UIImageView imgView = (UIImageView)ctrl;
                imgView.image = image;
            }

} } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) { NSLog(@"No Image"); }]; [operation start];}

Can I write native iPhone apps using Python?

You can use PyObjC on the iPhone as well, due to the excellent work by Jay Freeman (saurik). See iPhone Applications in Python.

Note that this requires a jailbroken iPhone at the moment.

How to call a method daily, at specific time, in C#?

It may just be me but it seemed like most of these answers were not complete or would not work correctly. I made something very quick and dirty. That being said not sure how good of an idea it is to do it this way, but it works perfectly every time.

while (true)
{
    if(DateTime.Now.ToString("HH:mm") == "22:00")
    {
        //do something here
        //ExecuteFunctionTask();
        //Make sure it doesn't execute twice by pausing 61 seconds. So that the time is past 2200 to 2201
        Thread.Sleep(61000);
    }

    Thread.Sleep(10000);
}

Android Debug Bridge (adb) device - no permissions

Stephan's answer works (using sudo adb kill-server), but it is temporary. It must be re-issued after every reboot.

For a permanent solution, the udev config must be modified:

Witrant's answer is the right idea (copied from the official Android documentation). But it's just a template. If that doesn't work for your device, you need to fill in the correct device ID for your device(s).

lsusb

Bus 001 Device 002: ID 05c6:9025 Qualcomm, Inc.
Bus 002 Device 002: ID 0e0f:0003 VMware, Inc. Virtual Mouse
...

Find your android device in the list.

Then use the first half of the ID (4 digits) for the idVendor (the last half is the idProduct, but it is not necessary to get adb working).

sudo vi /etc/udev/rules.d/51-android.rules and add one rule for each unique idVendor:

SUBSYSTEM=="usb", ATTR{idVendor}=="05c6", MODE="0666", GROUP="plugdev"

It's that simple. You don't need all those other fields given in some of the answers. Save the file.

Then reboot. The change is permanent. (Roger shows a way to restart udev, if you don't want to reboot).

Convert a string to datetime in PowerShell

Hope below helps!

PS C:\Users\aameer>$invoice = $object.'Invoice Month'
$invoice = "01-" + $invoice
[datetime]$Format_date =$invoice

Now type is converted. You can use method or can access any property.

Example :$Format_date.AddDays(5)

Could not load file or assembly 'System.Web.Http 4.0.0 after update from 2012 to 2013

<dependentAssembly>
    <assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>
<dependentAssembly>
    <assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>

How to Call Controller Actions using JQuery in ASP.NET MVC

We can call Controller method using Javascript / Jquery very easily as follows:

Suppose following is the Controller method to be called returning an array of some class objects. Let the class is 'A'

public JsonResult SubMenu_Click(string param1, string param2)

    {
       A[] arr = null;
        try
        {
            Processing...
           Get Result and fill arr.

        }
        catch { }


        return Json(arr , JsonRequestBehavior.AllowGet);

    }

Following is the complex type (class)

 public class A
 {

  public string property1 {get ; set ;}

  public string property2 {get ; set ;}

 }

Now it was turn to call above controller method by JQUERY. Following is the Jquery function to call the controller method.

function callControllerMethod(value1 , value2) {
    var strMethodUrl = '@Url.Action("SubMenu_Click", "Home")?param1=value1 &param2=value2'
    $.getJSON(strMethodUrl, receieveResponse);
}


function receieveResponse(response) {

    if (response != null) {
        for (var i = 0; i < response.length; i++) {
           alert(response[i].property1);
        }
    }
}

In the above Jquery function 'callControllerMethod' we develop controller method url and put that in a variable named 'strMehodUrl' and call getJSON method of Jquery API.

receieveResponse is the callback function receiving the response or return value of the controllers method.

Here we made use of JSON , since we can't make use of the C# class object

directly into the javascript function , so we converted the result (arr) in controller method into JSON object as follows:

Json(arr , JsonRequestBehavior.AllowGet);

and returned that Json object.

Now in callback function of the Javascript / JQuery we can make use of this resultant JSON object and work accordingly to show response data on UI.

For more detaill click here

Open web in new tab Selenium + Python

tabs = {}

def new_tab():
    global browser
    hpos = browser.window_handles.index(browser.current_window_handle)
    browser.execute_script("window.open('');")
    browser.switch_to.window(browser.window_handles[hpos + 1])
    return(browser.current_window_handle)
    
def switch_tab(name):
    global tabs
    global browser
    if not name in tabs.keys():
        tabs[name] = {'window_handle': new_tab(), 'url': url+name}
        browser.get(tabs[name]['url'])
    else:
        browser.switch_to.window(tabs[name]['window_handle'])

How to convert a Django QuerySet to a list

Why not just call list() on the Queryset?

answers_list = list(answers)

This will also evaluate the QuerySet/run the query. You can then remove/add from that list.

Can you do a partial checkout with Subversion?

I wrote a script to automate complex sparse checkouts.

#!/usr/bin/env python

'''
This script makes a sparse checkout of an SVN tree in the current working directory.

Given a list of paths in an SVN repository, it will:
1. Checkout the common root directory
2. Update with depth=empty for intermediate directories
3. Update with depth=infinity for the leaf directories
'''

import os
import getpass
import pysvn

__author__ = "Karl Ostmo"
__date__ = "July 13, 2011"

# =============================================================================

# XXX The os.path.commonprefix() function does not behave as expected!
# See here: http://mail.python.org/pipermail/python-dev/2002-December/030947.html
# and here: http://nedbatchelder.com/blog/201003/whats_the_point_of_ospathcommonprefix.html
# and here (what ever happened?): http://bugs.python.org/issue400788
from itertools import takewhile
def allnamesequal(name):
    return all(n==name[0] for n in name[1:])

def commonprefix(paths, sep='/'):
    bydirectorylevels = zip(*[p.split(sep) for p in paths])
    return sep.join(x[0] for x in takewhile(allnamesequal, bydirectorylevels))

# =============================================================================
def getSvnClient(options):

    password = options.svn_password
    if not password:
        password = getpass.getpass('Enter SVN password for user "%s": ' % options.svn_username)

    client = pysvn.Client()
    client.callback_get_login = lambda realm, username, may_save: (True, options.svn_username, password, True)
    return client

# =============================================================================
def sparse_update_with_feedback(client, new_update_path):
    revision_list = client.update(new_update_path, depth=pysvn.depth.empty)

# =============================================================================
def sparse_checkout(options, client, repo_url, sparse_path, local_checkout_root):

    path_segments = sparse_path.split(os.sep)
    path_segments.reverse()

    # Update the middle path segments
    new_update_path = local_checkout_root
    while len(path_segments) > 1:
        path_segment = path_segments.pop()
        new_update_path = os.path.join(new_update_path, path_segment)
        sparse_update_with_feedback(client, new_update_path)
        if options.verbose:
            print "Added internal node:", path_segment

    # Update the leaf path segment, fully-recursive
    leaf_segment = path_segments.pop()
    new_update_path = os.path.join(new_update_path, leaf_segment)

    if options.verbose:
        print "Will now update with 'recursive':", new_update_path
    update_revision_list = client.update(new_update_path)

    if options.verbose:
        for revision in update_revision_list:
            print "- Finished updating %s to revision: %d" % (new_update_path, revision.number)

# =============================================================================
def group_sparse_checkout(options, client, repo_url, sparse_path_list, local_checkout_root):

    if not sparse_path_list:
        print "Nothing to do!"
        return

    checkout_path = None
    if len(sparse_path_list) > 1:
        checkout_path = commonprefix(sparse_path_list)
    else:
        checkout_path = sparse_path_list[0].split(os.sep)[0]



    root_checkout_url = os.path.join(repo_url, checkout_path).replace("\\", "/")
    revision = client.checkout(root_checkout_url, local_checkout_root, depth=pysvn.depth.empty)

    checkout_path_segments = checkout_path.split(os.sep)
    for sparse_path in sparse_path_list:

        # Remove the leading path segments
        path_segments = sparse_path.split(os.sep)
        start_segment_index = 0
        for i, segment in enumerate(checkout_path_segments):
            if segment == path_segments[i]:
                start_segment_index += 1
            else:
                break

        pruned_path = os.sep.join(path_segments[start_segment_index:])
        sparse_checkout(options, client, repo_url, pruned_path, local_checkout_root)

# =============================================================================
if __name__ == "__main__":

    from optparse import OptionParser
    usage = """%prog  [path2] [more paths...]"""

    default_repo_url = "http://svn.example.com/MyRepository"
    default_checkout_path = "sparse_trunk"

    parser = OptionParser(usage)
    parser.add_option("-r", "--repo_url", type="str", default=default_repo_url, dest="repo_url", help='Repository URL (default: "%s")' % default_repo_url)
    parser.add_option("-l", "--local_path", type="str", default=default_checkout_path, dest="local_path", help='Local checkout path (default: "%s")' % default_checkout_path)

    default_username = getpass.getuser()
    parser.add_option("-u", "--username", type="str", default=default_username, dest="svn_username", help='SVN login username (default: "%s")' % default_username)
    parser.add_option("-p", "--password", type="str", dest="svn_password", help="SVN login password")

    parser.add_option("-v", "--verbose", action="store_true", default=False, dest="verbose", help="Verbose output")
    (options, args) = parser.parse_args()

    client = getSvnClient(options)
    group_sparse_checkout(
        options,
        client,
        options.repo_url,
        map(os.path.relpath, args),
        options.local_path)

Android: Scale a Drawable or background image?

The Below code make the bitmap perfectly with same size of the imageview. Get the bitmap image height and width and then calculate the new height and width with the help of imageview's parameters. That give you required image with best aspect ratio.

int bwidth=bitMap1.getWidth();
int bheight=bitMap1.getHeight();
int swidth=imageView_location.getWidth();
int sheight=imageView_location.getHeight();
new_width=swidth;
new_height = (int) Math.floor((double) bheight *( (double) new_width / (double) bwidth));
Bitmap newbitMap = Bitmap.createScaledBitmap(bitMap1,new_width,new_height, true);
imageView_location.setImageBitmap(newbitMap)

What size should apple-touch-icon.png be for iPad and iPhone?

The relevant documentation on Apple's site, Specifying a Webpage Icon for Web Clip.

There is no need to put anything in the head of your document. If no icons are specified using a link element, the website root directory is searched for icons with the apple-touch-icon or apple-touch-icon-precomposed prefix.

For example, if the appropriate icon size for the device is 57 x 57, the system searches for filenames in the following order:

  • apple-touch-icon-57x57-precomposed.png
  • apple-touch-icon-57x57.png
  • apple-touch-icon-precomposed.png
  • apple-touch-icon.png

Can I use Objective-C blocks as properties?

Hello, Swift

Complementing what @Francescu answered.

Adding extra parameters:

func test(function:String -> String, param1:String, param2:String) -> String
{
    return function("test"+param1 + param2)
}

func funcStyle(s:String) -> String
{
    return "FUNC__" + s + "__FUNC"
}
let resultFunc = test(funcStyle, "parameter 1", "parameter 2")

let blockStyle:(String) -> String = {s in return "BLOCK__" + s + "__BLOCK"}
let resultBlock = test(blockStyle, "parameter 1", "parameter 2")

let resultAnon = test({(s:String) -> String in return "ANON_" + s + "__ANON" }, "parameter 1", "parameter 2")


println(resultFunc)
println(resultBlock)
println(resultAnon)

How to add new line into txt file

var Line = textBox1.Text + "," + textBox2.Text;

File.AppendAllText(@"C:\Documents\m2.txt", Line + Environment.NewLine);

Java converting Image to BufferedImage

One way to handle this is to create a new BufferedImage, and tell it's graphics object to draw your scaled image into the new BufferedImage:

final float FACTOR  = 4f;
BufferedImage img = ImageIO.read(new File("graphic.png"));
int scaleX = (int) (img.getWidth() * FACTOR);
int scaleY = (int) (img.getHeight() * FACTOR);
Image image = img.getScaledInstance(scaleX, scaleY, Image.SCALE_SMOOTH);
BufferedImage buffered = new BufferedImage(scaleX, scaleY, TYPE);
buffered.getGraphics().drawImage(image, 0, 0 , null);

That should do the trick without casting.

Adding a slide effect to bootstrap dropdown

here is my solution for slide & fade effect:

   // Add slideup & fadein animation to dropdown
   $('.dropdown').on('show.bs.dropdown', function(e){
      var $dropdown = $(this).find('.dropdown-menu');
      var orig_margin_top = parseInt($dropdown.css('margin-top'));
      $dropdown.css({'margin-top': (orig_margin_top + 10) + 'px', opacity: 0}).animate({'margin-top': orig_margin_top + 'px', opacity: 1}, 300, function(){
         $(this).css({'margin-top':''});
      });
   });
   // Add slidedown & fadeout animation to dropdown
   $('.dropdown').on('hide.bs.dropdown', function(e){
      var $dropdown = $(this).find('.dropdown-menu');
      var orig_margin_top = parseInt($dropdown.css('margin-top'));
      $dropdown.css({'margin-top': orig_margin_top + 'px', opacity: 1, display: 'block'}).animate({'margin-top': (orig_margin_top + 10) + 'px', opacity: 0}, 300, function(){
         $(this).css({'margin-top':'', display:''});
      });
   });

HTML5: Slider with two inputs possible?

No, the HTML5 range input only accepts one input. I would recommend you to use something like the jQuery UI range slider for that task.

Deleting a pointer in C++

There is a rule in C++, for every new there is a delete.

  1. Why won't the first case work? Seems the most straightforward use to use and delete a pointer? The error says the memory wasn't allocated but 'cout' returned an address.

new is never called. So the address that cout prints is the address of the memory location of myVar, or the value assigned to myPointer in this case. By writing:

myPointer = &myVar;

you say:

myPointer = The address of where the data in myVar is stored

  1. On the second example the error is not being triggered but doing a cout of the value of myPointer still returns a memory address?

It returns an address that points to a memory location that has been deleted. Because first you create the pointer and assign its value to myPointer, second you delete it, third you print it. So unless you assign another value to myPointer, the deleted address will remain.

  1. Does #3 really work? Seems to work to me, the pointer is no longer storing an address, is this the proper way to delete a pointer?

NULL equals 0, you delete 0, so you delete nothing. And it's logic that it prints 0 because you did:

myPointer = NULL;

which equals:

myPointer = 0;

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

You could simply have: var result = (str == "true").

Is there a way to take the first 1000 rows of a Spark Dataframe?

The method you are looking for is .limit.

Returns a new Dataset by taking the first n rows. The difference between this function and head is that head returns an array while limit returns a new Dataset.

Example usage:

df.limit(1000)

Why do I need to override the equals and hashCode methods in Java?

Java puts a rule that

"If two objects are equal using Object class equals method, then the hashcode method should give the same value for these two objects."

So, if in our class we override equals() we should override hashcode() method also to follow this rule. Both methods, equals() and hashcode(), are used in Hashtable, for example, to store values as key-value pairs. If we override one and not the other, there is a possibility that the Hashtable may not work as we want, if we use such object as a key.

Timestamp Difference In Hours for PostgreSQL

extract(hour from age(now(),links.created)) gives you a floor-rounded count of the hour difference.

MySQL pivot table query with dynamic columns

I have a slightly different way of doing this than the accepted answer. This way you can avoid using GROUP_CONCAT which has a limit of 1024 characters and will not work if you have a lot of fields.

SET @sql = '';
SELECT
    @sql := CONCAT(@sql,if(@sql='','',', '),temp.output)
FROM
(
    SELECT
      DISTINCT
        CONCAT(
         'MAX(IF(pa.fieldname = ''',
          fieldname,
          ''', pa.fieldvalue, NULL)) AS ',
          fieldname
        ) as output
    FROM
        product_additional
) as temp;

SET @sql = CONCAT('SELECT p.id
                    , p.name
                    , p.description, ', @sql, ' 
                   FROM product p
                   LEFT JOIN product_additional AS pa 
                    ON p.id = pa.id
                   GROUP BY p.id');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

CodeIgniter PHP Model Access "Unable to locate the model you have specified"

You can give whatever name you want.

Styles guides are recommendations and not musts.

But you have to care to use everywhere the same name.

For example for Test_Model you have to:

Class Name

        class Test_Model extends CI_Model

File Name

        Test_Model.php

Load Model

        $this->load->model('Test_Model');

Use Model

        $this->Test_Model

To avoid using hard coding strings you can load model like this:

        $this->load->model(Test_Model::class);

Calculate MD5 checksum for a file

I know this question was already answered, but this is what I use:

using (FileStream fStream = File.OpenRead(filename)) {
    return GetHash<MD5>(fStream)
}

Where GetHash:

public static String GetHash<T>(Stream stream) where T : HashAlgorithm {
    StringBuilder sb = new StringBuilder();

    MethodInfo create = typeof(T).GetMethod("Create", new Type[] {});
    using (T crypt = (T) create.Invoke(null, null)) {
        byte[] hashBytes = crypt.ComputeHash(stream);
        foreach (byte bt in hashBytes) {
            sb.Append(bt.ToString("x2"));
        }
    }
    return sb.ToString();
}

Probably not the best way, but it can be handy.

Prevent Caching in ASP.NET MVC for specific actions using an attribute

To ensure that JQuery isn't caching the results, on your ajax methods, put the following:

$.ajax({
    cache: false
    //rest of your ajax setup
});

Or to prevent caching in MVC, we created our own attribute, you could do the same. Here's our code:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class NoCacheAttribute : ActionFilterAttribute
{
    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
        filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);
        filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
        filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        filterContext.HttpContext.Response.Cache.SetNoStore();

        base.OnResultExecuting(filterContext);
    }
}

Then just decorate your controller with [NoCache]. OR to do it for all you could just put the attribute on the class of the base class that you inherit your controllers from (if you have one) like we have here:

[NoCache]
public class ControllerBase : Controller, IControllerBase

You can also decorate some of the actions with this attribute if you need them to be non-cacheable, instead of decorating the whole controller.

If your class or action didn't have NoCache when it was rendered in your browser and you want to check it's working, remember that after compiling the changes you need to do a "hard refresh" (Ctrl+F5) in your browser. Until you do so, your browser will keep the old cached version, and won't refresh it with a "normal refresh" (F5).

How to properly set the 100% DIV height to match document/window height?

html, body {
    height:100%;
}
#wrapper {
    min-height:100%;
}

How to add an Android Studio project to GitHub

You need to create the project on GitHub first. After that go to the project directory and run in terminal:

git init
git remote add origin https://github.com/xxx/yyy.git
git add .
git commit -m "first commit"
git push -u origin master

how to remove the dotted line around the clicked a element in html

Its simple try below code --

a{
outline: medium none !important;
}

If happy cheers! Good day

How to solve SyntaxError on autogenerated manage.py?

We have to create a virtual environment inside the project, not outside the project.. Then it will solve..

How to add anything in <head> through jquery/javascript?

jQuery

$('head').append( ... );

JavaScript:

document.getElementsByTagName('head')[0].appendChild( ... );

fastest way to export blobs from table into individual files

I tried using a CLR function and it was more than twice as fast as BCP. Here's my code.

Original Method:

SET @bcpCommand = 'bcp "SELECT blobcolumn FROM blobtable WHERE ID = ' + CAST(@FileID AS VARCHAR(20)) + '" queryout "' + @FileName + '" -T -c'
EXEC master..xp_cmdshell @bcpCommand

CLR Method:

declare @file varbinary(max) = (select blobcolumn from blobtable WHERE ID = @fileid)
declare @filepath nvarchar(4000) = N'c:\temp\' + @FileName
SELECT Master.dbo.WriteToFile(@file, @filepath, 0)

C# Code for the CLR function

using System;
using System.Data;
using System.Data.SqlTypes;
using System.IO;
using Microsoft.SqlServer.Server;

namespace BlobExport
{
    public class Functions
    {
      [SqlFunction]
      public static SqlString WriteToFile(SqlBytes binary, SqlString path, SqlBoolean append)
      {        
        try
        {
          if (!binary.IsNull && !path.IsNull && !append.IsNull)
          {         
            var dir = Path.GetDirectoryName(path.Value);           
            if (!Directory.Exists(dir))              
              Directory.CreateDirectory(dir);            
              using (var fs = new FileStream(path.Value, append ? FileMode.Append : FileMode.OpenOrCreate))
            {
                byte[] byteArr = binary.Value;
                for (int i = 0; i < byteArr.Length; i++)
                {
                    fs.WriteByte(byteArr[i]);
                };
            }
            return "SUCCESS";
          }
          else
             "NULL INPUT";
        }
        catch (Exception ex)
        {          
          return ex.Message;
        }
      }
    }
}

Non-static variable cannot be referenced from a static context

It is ClassLoader responsible to load the class files.Let's see what happens when we write our own classes.

Example 1:

class StaticTest {

      static int a;
      int b;
      int c;
}

Now we can see that class "StaticTest" has 3 fields.But actually there is no existence of b,c member variable.But why ???. OK Lest's see. Here b,c are instance variable.Since instance variable gets the memory at the time of object creation. So here b,c are not getting any memory yet. That's why there is no existence of b,c. So There is only existence of a. For ClassLoader it has only one information about a. ClassLoader yet not recognize b,c because it's object not instantiated yet.

Let's see another example: Example 2:

class StaticTest {

      public void display() {
          System.out.println("Static Test");
      }


      public static void main(String []cmd) {

             display();       
      }

}

Now if we try to compile this code compiler will give CE error. CE: non-static method display() cannot be referenced from a static context.

Now For ClassLoader it looks like:

class StaticTest {

      public static void main(String []cmd) {

             display();       
      }

}

In Example 2 CE error is because we call non static method from a static context. So it is not possible for ClassLoader to recognize method display() at compile time.So compile time error is occurred.

How do you make strings "XML safe"?

By either escaping those characters with htmlspecialchars, or, perhaps more appropriately, using a library for building XML documents, such as DOMDocument or XMLWriter.

Another alternative would be to use CDATA sections, but then you'd have to look out for occurrences of ]]>.

Take also into consideration that that you must respect the encoding you define for the XML document (by default UTF-8).

Android: adbd cannot run as root in production builds

The problem is that, even though your phone is rooted, the 'adbd' server on the phone does not use root permissions. You can try to bypass these checks or install a different adbd on your phone or install a custom kernel/distribution that includes a patched adbd.

Or, a much easier solution is to use 'adbd insecure' from chainfire which will patch your adbd on the fly. It's not permanent, so you have to run it before starting up the adb server (or else set it to run every boot). You can get the app from the google play store for a couple bucks:

https://play.google.com/store/apps/details?id=eu.chainfire.adbd&hl=en

Or you can get it for free, the author has posted a free version on xda-developers:

http://forum.xda-developers.com/showthread.php?t=1687590

Install it to your device (copy it to the device and open the apk file with a file manager), run adb insecure on the device, and finally kill the adb server on your computer:

% adb kill-server

And then restart the server and it should already be root.

WPF: Grid with column/row margin/padding?

You could use something like this:

<Style TargetType="{x:Type DataGridCell}">
  <Setter Property="Padding" Value="4" />
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type DataGridCell}">
        <Border Padding="{TemplateBinding Padding}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True">
          <ContentPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
        </Border>
      </ControlTemplate>
    </Setter.Value>
  </Setter>

Or if you don't need the TemplateBindings:

<Style TargetType="{x:Type DataGridCell}">
   <Setter Property="Template">
      <Setter.Value>
          <ControlTemplate TargetType="{x:Type DataGridCell}">
              <Border Padding="4">
                  <ContentPresenter />
              </Border>
          </ControlTemplate>
      </Setter.Value>
  </Setter>
</Style>

Cannot connect to SQL Server named instance from another SQL Server

Your test cases where you cannot connect with "ServerName\Instance" but ARE able to connect to the server via "ServerName,Port" is what happens when you VPN into a network with Microsoft VPN. (I had this issue). For my VPN Issue I simply use the static port numbers to get around it.

This is appearently due to VPN not forwarding UDP Packets, allowing only TCP Connections.

In your case your firewall or security settings or antivirus or whatever may be blocking UDP.

I would suggest you check your firewall setting to specifically allow for UDP.

Browser Artical

On startup, SQL Server Browser starts and claims UDP port 1434. SQL Server Browser reads the registry, identifies all SQL Server instances on the computer, and notes the ports and named pipes that they use. When a server has two or more network cards, SQL Server Browser will return all ports enabled for SQL Server. SQL Server 2005 and SQL Server Browser support ipv6 and ipv4.

When SQL Server 2000 and SQL Server 2005 clients request SQL Server resources, the client network library sends a UDP message to the server using port 1434. SQL Server Browser responds with the TCP/IP port or named pipe of the requested instance. The network library on the client application then completes the connection by sending a request to the server using the port or named pipe of the desired instance.

Using a Firewall

To communicate with the SQL Server Browser service on a server behind a firewall, open UDP port 1434 in addition to the TCP port used by SQL Server (for example, 1433).

Java: Replace all ' in a string with \'

You can use apache's commons-text library (instead of commons-lang):

Example code:

org.apache.commons.text.StringEscapeUtils.escapeJava(escapedString);

Dependency:

compile 'org.apache.commons:commons-text:1.8'

OR

<dependency>
   <groupId>org.apache.commons</groupId>
   <artifactId>commons-text</artifactId>
   <version>1.8</version>
</dependency>

how to set default method argument values?

If your arguments are the same type you could use varargs:

public int something(int... args) {
    int a = 0;
    int b = 0;
    if (args.length > 0) {
      a = args[0];
    }
    if (args.length > 1) {
      b = args[1];
    }
    return a + b
}

but this way you lose the semantics of the individual arguments, or

have a method overloaded which relays the call to the parametered version

public int something() {
  return something(1, 2);
}

or if the method is part of some kind of initialization procedure, you could use the builder pattern instead:

class FoodBuilder {
   int saltAmount;
   int meatAmount;
   FoodBuilder setSaltAmount(int saltAmount) {
       this.saltAmount = saltAmount;
       return this;
   }
   FoodBuilder setMeatAmount(int meatAmount) {
       this.meatAmount = meatAmount;
       return this;
   }
   Food build() {
       return new Food(saltAmount, meatAmount);
   }
}

Food f = new FoodBuilder().setSaltAmount(10).build();
Food f2 = new FoodBuilder().setSaltAmount(10).setMeatAmount(5).build();

Then work with the Food object

int doSomething(Food f) {
    return f.getSaltAmount() + f.getMeatAmount();
}

The builder pattern allows you to add/remove parameters later on and you don't need to create new overloaded methods for them.

console.log showing contents of array object

console.log does not produce any message box. I don't think it is available in any version of IE (nor Firefox) without the addition of firebug or some equivalent.

It is however available in Safari and Chrome. Since you mention Chrome I'll use that for my example.

You'll need to open your window and its developer window counterpart. you can do this by right clicking any element on the page and selecting "Inspect element". your window will be divided in two parts, the developer part being the bottom. in the division between the two parts is a bar with buttons and the rightmost button there is labeled "console". You'll need to click that to switch to the console tab. Press F12 for developer tools in most browsers on Windows, command + shift + I on macOS.

Once there, you will be able to interact with whatever page is loaded on top through javascript from that console, and any messages you console.log will be displayed there.

How do you iterate through every file/directory recursively in standard C++?

In addition to the above mentioned boost::filesystem you may want to examine wxWidgets::wxDir and Qt::QDir.

Both wxWidgets and Qt are open source, cross platform C++ frameworks.

wxDir provides a flexible way to traverse files recursively using Traverse() or a simpler GetAllFiles() function. As well you can implement the traversal with GetFirst() and GetNext() functions (I assume that Traverse() and GetAllFiles() are wrappers that eventually use GetFirst() and GetNext() functions).

QDir provides access to directory structures and their contents. There are several ways to traverse directories with QDir. You can iterate over the directory contents (including sub-directories) with QDirIterator that was instantiated with QDirIterator::Subdirectories flag. Another way is to use QDir's GetEntryList() function and implement a recursive traversal.

Here is sample code (taken from here # Example 8-5) that shows how to iterate over all sub directories.

#include <qapplication.h>
#include <qdir.h>
#include <iostream>

int main( int argc, char **argv )
{
    QApplication a( argc, argv );
    QDir currentDir = QDir::current();

    currentDir.setFilter( QDir::Dirs );
    QStringList entries = currentDir.entryList();
    for( QStringList::ConstIterator entry=entries.begin(); entry!=entries.end(); ++entry) 
    {
         std::cout << *entry << std::endl;
    }
    return 0;
}

Python module os.chmod(file, 664) does not change the permission to rw-rw-r-- but -w--wx----

Using the stat.* bit masks does seem to me the most portable and explicit way of doing this. But on the other hand, I often forget how best to handle that. So, here's an example of masking out the 'group' and 'other' permissions and leaving 'owner' permissions untouched. Using bitmasks and subtraction is a useful pattern.

import os
import stat
def chmodme(pn):
    """Removes 'group' and 'other' perms. Doesn't touch 'owner' perms."""
    mode = os.stat(pn).st_mode
    mode -= (mode & (stat.S_IRWXG | stat.S_IRWXO))
    os.chmod(pn, mode)

How to get current relative directory of your Makefile?

Solution found here : https://sourceforge.net/p/ipt-netflow/bugs-requests-patches/53/

The solution is : $(CURDIR)

You can use it like that :

CUR_DIR = $(CURDIR)

## Start :
start:
    cd $(CUR_DIR)/path_to_folder

How to concatenate two strings to build a complete path

The POSIX standard mandates that multiple / are treated as a single / in a file name. Thus //dir///subdir////file is the same as /dir/subdir/file.

As such concatenating a two strings to build a complete path is a simple as:

full_path="$part1/$part2"

How can I specify system properties in Tomcat configuration on startup?

(Update: If I could delete this answer I would, although since it's accepted, I can't. I'm updating the description to provide better guidance and discourage folks from using the poor practice I outlined in the original answer).

You can specify these parameters via context or environment parameters, such as in context.xml. See the sections titled "Context Parameters" and "Environment Entries" on this page:

http://tomcat.apache.org/tomcat-5.5-doc/config/context.html

As @netjeff points out, these values will be available via the Context.lookup(String) method and not as System parameters.

Another way to do specify these values is to define variables inside of the web.xml file of the web application you're deploying (see below). As @Roberto Lo Giacco points out, this is generally considered a poor practice since a deployed artifact should not be environment specific. However, below is the configuration snippet if you really want to do this:

<env-entry>
    <env-entry-name>SMTP_PASSWORD</env-entry-name>
    <env-entry-type>java.lang.String</env-entry-type>
    <env-entry-value>abc123ftw</env-entry-value>
</env-entry>

How to convert array to SimpleXML

function array2xml(array $data, SimpleXMLElement $object = null, $oldNodeName = 'item')
{
    if (is_null($object)) $object = new SimpleXMLElement('<root/>');
    $isNumbered = true;
    $idx = 0;
    foreach ($data as $key => $x)
        if (is_string($key) || ($idx++ != $key + 0))
            $isNumbered = false;
    foreach ($data as $key => $value)
    {   
        $attribute = preg_match('/^[0-9]/', $key . '') ? $key : null;
        $key = (is_string($key) && !preg_match('/^[0-9]/', $key . '')) ? $key : preg_replace('/s$/', '', $oldNodeName);
        if (is_array($value))
        {
            $new_object = $object->addChild($key);
            if (!$isNumbered && !is_null($attribute)) $new_object->addAttribute('id', $attribute);
            array2xml($value, $new_object, $key);
        }
        else
        {
            if (is_bool($value)) $value = $value ? 'true' : 'false';
            $node = $object->addChild($key, htmlspecialchars($value));
            if (!$isNumbered && !is_null($attribute) && !isset($node->attributes()->id))
                $node->addAttribute('id', $attribute);
        }
    }
    return $object;
}

This function returns for example a list of <obj>...</obj><obj>...</obj> XML tags for numeric indexes.

Input:

    array(
    'people' => array(
        'dog',
        'cat',
        'life' => array(
            'gum',
            'shoe',
        ),
        'fish',
    ),
    array('yeah'),
)

Output:

<root>
    <people>
        <people>dog</people>
        <people>cat</people>
        <life>
            <life>gum</life>
            <life>shoe</life>
        </life>
        <people>fish</people>
        <people>
            <people>yeah</people>
        </people>
    </people>
</root>

This should satisfy all common needs. Maybe you may change the 3rd line to:

$key = is_string($key) ? $key : $oldNodeName . '_' . $key;

or if you are working with plurals ending with s:

$key = is_string($key) ? $key : preg_replace('/s$/', '', $oldNodeName);

how to create 100% vertical line in css

Use an absolutely positioned pseudo element:

ul:after {
  content: '';
  width: 0;
  height: 100%;
  position: absolute;
  border: 1px solid black;
  top: 0;
  left: 100px;
}

Demo

Git: copy all files in a directory from another branch

If there are no spaces in paths, and you are interested, like I was, in files of specific extension only, you can use

git checkout otherBranch -- $(git ls-tree --name-only -r otherBranch | egrep '*.java')

What is a web service endpoint?

Updated answer, from Peter in comments :

This is de "old terminology", use directally the WSDL2 "endepoint" definition (WSDL2 translated "port" to "endpoint").


Maybe you find an answer in this document : http://www.w3.org/TR/wsdl.html

A WSDL document defines services as collections of network endpoints, or ports. In WSDL, the abstract definition of endpoints and messages is separated from their concrete network deployment or data format bindings. This allows the reuse of abstract definitions: messages, which are abstract descriptions of the data being exchanged, and port types which are abstract collections of operations. The concrete protocol and data format specifications for a particular port type constitutes a reusable binding. A port is defined by associating a network address with a reusable binding, and a collection of ports define a service. Hence, a WSDL document uses the following elements in the definition of network services:

  • Types– a container for data type definitions using some type system (such as XSD).
  • Message– an abstract, typed definition of the data being communicated.
  • Operation– an abstract description of an action supported by the service.
  • Port Type–an abstract set of operations supported by one or more endpoints.
  • Binding– a concrete protocol and data format specification for a particular port type.
  • Port– a single endpoint defined as a combination of a binding and a network address.
  • Service– a collection of related endpoints.

http://www.ehow.com/info_12212371_definition-service-endpoint.html

The endpoint is a connection point where HTML files or active server pages are exposed. Endpoints provide information needed to address a Web service endpoint. The endpoint provides a reference or specification that is used to define a group or family of message addressing properties and give end-to-end message characteristics, such as references for the source and destination of endpoints, and the identity of messages to allow for uniform addressing of "independent" messages. The endpoint can be a PC, PDA, or point-of-sale terminal.

How to calculate percentage when old value is ZERO

There is no rate of growth from 0 to any other number. That is to say, there is no percentage of increase from zero to greater than zero and there is no percentage of decrease from zero to less than zero (a negative number). What you have to decide is what to put as an output when this situation happens. Here are two possibilities I am comfortable with:

  1. Any time you have to show a rate of increase from zero, output the infinity symbol (8). That's Alt + 236 on your number pad, in case you're wondering. You could also use negative infinity (-8) for a negative growth rate from zero.
  2. Output a statement such as "[Increase/Decrease] From Zero" or something along those lines.

Unfortunately, if you need the growth rate for further calculations, the above options will not work, but, on the other hand, any number would give your following calculations incorrect data any way so the point is moot. You'd need to update your following calculations to account for this eventuality.

As an aside, the ((New-Old)/Old) function will not work when your new and old values are both zero. You should create an initial check to see if both values are zero and, if they are, output zero percent as the growth rate.

Connecting to local SQL Server database using C#

If you use SQL authentication, use this:

using System.Data.SqlClient;

SqlConnection conn = new SqlConnection();
conn.ConnectionString = 
     "Data Source=.\SQLExpress;" + 
     "User Instance=true;" + 
     "User Id=UserName;" + 
     "Password=Secret;" + 
     "AttachDbFilename=|DataDirectory|Database1.mdf;"
conn.Open();

If you use Windows authentication, use this:

using System.Data.SqlClient;
SqlConnection conn = new SqlConnection();
conn.ConnectionString = 
     "Data Source=.\SQLExpress;" + 
     "User Instance=true;" + 
     "Integrated Security=true;" + 
     "AttachDbFilename=|DataDirectory|Database1.mdf;"
conn.Open();

Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine

There is indeed no 64 bit version of Jet - and no plans (apparently) to produce one.

You might be able to use the ACE 64 bit driver: http://www.microsoft.com/en-us/download/details.aspx?displaylang=en&id=23734

  • but I have no idea how that would work if you need to go back to Jet for your 32 bit apps.

However, you may be able to switch the project to 32bit in the Express version (I haven't tried and don't have 2008 installed in any flavour anymore)

Maybe it's time to scrap Access databases altogether, bite the bullet and go for SQL server instead?

Structs data type in php?

A public class is one option, if you want something more encapsulated you can use an abstract/anonymous class combination. My favorite part is that autocomplete still works (for PhpStorm) for this but I don't have a public class sitting around.

<?php

final class MyParentClass
{
    /**
     * @return MyStruct[]
     */
    public function getData(): array
    {
        return array(
            $this->createMyObject("One", 1.0, new DateTime("now")),
            $this->createMyObject("Two", 2.0, new DateTime("tommorow"))
        );
    }

    private function createMyObject(string $description, float $magnitude, DateTime $timeStamp): MyStruct
    {
        return new class(func_get_args()) extends MyStruct {
            protected function __construct(array $args)
            {
                $this->description = $args[0];
                $this->magnitude = $args[1];
                $this->timeStamp = $args[2];
            }
        };
    }
}

abstract class MyStruct
{
    public string $description;
    public float $magnitude;
    public DateTime $timeStamp;
}

Apache gives me 403 Access Forbidden when DocumentRoot points to two different drives

For Apache 2.4.2: I was getting 403: Forbidden continuously when I was trying to access WAMP on my Windows 7 desktop from my iPhone on WiFi. On one blog, I found the solution - add Require all granted after Allow all in the <Directory> section. So this is how my <Directory> section looks like inside <VirtualHost>

<Directory "C:/wamp/www">
    Options Indexes FollowSymLinks MultiViews Includes ExecCGI
    AllowOverride All
    Order Allow,Deny
    Allow from all
    Require all granted
</Directory>

How do I find an element that contains specific text in Selenium WebDriver (Python)?

//* will be looking for any HTML tag. Where if some text is common for Button and div tag and if //* is categories it will not work as expected. If you need to select any specific then You can get it by declaring HTML Element tag. Like:

driver.find_element_by_xpath("//div[contains(text(),'Add User')]")
driver.find_element_by_xpath("//button[contains(text(),'Add User')]")

Getting rid of bullet points from <ul>

I had the same extreme irritating problem myself since the script did not take any notice of my styelsheet. So I wrote:

<ul style="list-style-type: none;">

That did not work. So, in addition, I wrote:

<li style="list-style-type: none;">

Voila! it worked!

docker run <IMAGE> <MULTIPLE COMMANDS>

You can also pipe commands inside Docker container, bash -c "<command1> | <command2>" for example:

docker run img /bin/bash -c "ls -1 | wc -l"

But, without invoking the shell in the remote the output will be redirected to the local terminal.

Setting the value of checkbox to true or false with jQuery

UPDATED: Using prop instead of attr

 <input type="checkbox" name="vehicle" id="vehicleChkBox" value="FALSE"/>

 $('#vehicleChkBox').change(function(){
     cb = $(this);
     cb.val(cb.prop('checked'));
 });

OUT OF DATE:

Here is the jsfiddle

<input type="checkbox" name="vehicle" id="vehicleChkBox" value="FALSE" />

$('#vehicleChkBox').change(function(){
     if($(this).attr('checked')){
          $(this).val('TRUE');
     }else{
          $(this).val('FALSE');
     }
});

How can I run an EXE program from a Windows Service using C#?

First, we are going to create a Windows Service that runs under the System account. This service will be responsible for spawning an interactive process within the currently active User’s Session. This newly created process will display a UI and run with full admin rights. When the first User logs on to the computer, this service will be started and will be running in Session0; however the process that this service spawns will be running on the desktop of the currently logged on User. We will refer to this service as the LoaderService.

Next, the winlogon.exe process is responsible for managing User login and logout procedures. We know that every User who logs on to the computer will have a unique Session ID and a corresponding winlogon.exe process associated with their Session. Now, we mentioned above, the LoaderService runs under the System account. We also confirmed that each winlogon.exe process on the computer runs under the System account. Because the System account is the owner of both the LoaderService and the winlogon.exe processes, our LoaderService can copy the access token (and Session ID) of the winlogon.exe process and then call the Win32 API function CreateProcessAsUser to launch a process into the currently active Session of the logged on User. Since the Session ID located within the access token of the copied winlogon.exe process is greater than 0, we can launch an interactive process using that token.

Try this one. Subverting Vista UAC in Both 32 and 64 bit Architectures

error while loading shared libraries: libncurses.so.5:

If you are absolutely sure that libncurses, aka ncurses, is installed, as in you've done a successful 'ls' of the library, then perhaps you are running a 64 bit Linux operating system and only have the 64 bit libncurses installed, when the program that is running (adb) is 32 bit.

If so, a 32 bit program can't link to a 64 bit library (and won't located it anyway), so you might have to install libcurses, or ncurses (32 bit version). Likewise, if you are running a 64 bit adb, perhaps your ncurses is 32 bit (a possible but less likely scenario).

How to Create Multiple Where Clause Query Using Laravel Eloquent?

Without a real example, it is difficult to make a recommendation. However, I've never needed to use that many WHERE clauses in a query and it may indicate a problem with the structure of your data.

It may be helpful for you to learn about data normalization: http://en.wikipedia.org/wiki/Third_normal_form

Calling stored procedure from another stored procedure SQL Server

First of all, if table2's idProduct is an identity, you cannot insert it explicitly until you set IDENTITY_INSERT on that table

SET IDENTITY_INSERT table2 ON;

before the insert.

So one of two, you modify your second stored and call it with only the parameters productName and productDescription and then get the new ID

EXEC test2 'productName', 'productDescription'
SET @newID = SCOPE_IDENTIY()

or you already have the ID of the product and you don't need to call SCOPE_IDENTITY() and can make the insert on table1 with that ID

Getting "type or namespace name could not be found" but everything seems ok?

In my case I went into the solution properties and made sure "Build" was checked in the Configuration for both projects. My main project didn't have it checked.

enter image description here

Check if value exists in column in VBA

Just to modify scott's answer to make it a function:

Function FindFirstInRange(FindString As String, RngIn As Range, Optional UseCase As Boolean = True, Optional UseWhole As Boolean = True) As Variant

    Dim LookAtWhat As Integer

    If UseWhole Then LookAtWhat = xlWhole Else LookAtWhat = xlPart

    With RngIn
        Set FindFirstInRange = .Find(What:=FindString, _
                                     After:=.Cells(.Cells.Count), _
                                     LookIn:=xlValues, _
                                     LookAt:=LookAtWhat, _
                                     SearchOrder:=xlByRows, _
                                     SearchDirection:=xlNext, _
                                     MatchCase:=UseCase)

        If FindFirstInRange Is Nothing Then FindFirstInRange = False

    End With

End Function

This returns FALSE if the value isn't found, and if it's found, it returns the range.

You can optionally tell it to be case-sensitive, and/or to allow partial-word matches.

I took out the TRIM because you can add that beforehand if you want to.

An example:

MsgBox FindFirstInRange(StringToFind, Range("2:2"), TRUE, FALSE).Address

That does a case-sensitive, partial-word search on the 2nd row and displays a box with the address. The following is the same search, but a whole-word search that is not case-sensitive:

MsgBox FindFirstInRange(StringToFind, Range("2:2")).Address

You can easily tweak this function to your liking or change it from a Variant to to a boolean, or whatever, to speed it up a little.

Do note that VBA's Find is sometimes slower than other methods like brute-force looping or Match, so don't assume that it's the fastest just because it's native to VBA. It's more complicated and flexible, which also can make it not always as efficient. And it has some funny quirks to look out for, like the "Object variable or with block variable not set" error.

Can regular expressions be used to match nested patterns?

YES

...assuming that there is some maximum number of nestings you'd be happy to stop at.

Let me explain.


@torsten-marek is right that a regular expression cannot check for nested patterns like this, BUT it is possible to define a nested regex pattern which will allow you to capture nested structures like this up to some maximum depth. I created one to capture EBNF-style comments (try it out here), like:

(* This is a comment (* this is nested inside (* another level! *) hey *) yo *)

The regex (for single-depth comments) is the following:

m{1} = \(+\*+(?:[^*(]|(?:\*+[^)*])|(?:\(+[^*(]))*\*+\)+

This could easily be adapted for your purposes by replacing the \(+\*+ and \*+\)+ with { and } and replacing everything in between with a simple [^{}]:

p{1} = \{(?:[^{}])*\}

(Here's the link to try that out.)

To nest, just allow this pattern within the block itself:

p{2} = \{(?:(?:p{1})|(?:[^{}]))*\}
  ...or...
p{2} = \{(?:(?:\{(?:[^{}])*\})|(?:[^{}]))*\}

To find triple-nested blocks, use:

p{3} = \{(?:(?:p{2})|(?:[^{}]))*\}
  ...or...
p{3} = \{(?:(?:\{(?:(?:\{(?:[^{}])*\})|(?:[^{}]))*\})|(?:[^{}]))*\}

A clear pattern has emerged. To find comments nested to a depth of N, simply use the regex:

p{N} = \{(?:(?:p{N-1})|(?:[^{}]))*\}

  where N > 1 and
  p{1} = \{(?:[^{}])*\}

A script could be written to recursively generate these regexes, but that's beyond the scope of what I need this for. (This is left as an exercise for the reader. )

How do I declare and initialize an array in Java?

There are two main ways to make an array:

This one, for an empty array:

int[] array = new int[n]; // "n" being the number of spaces to allocate in the array

And this one, for an initialized array:

int[] array = {1,2,3,4 ...};

You can also make multidimensional arrays, like this:

int[][] array2d = new int[x][y]; // "x" and "y" specify the dimensions
int[][] array2d = { {1,2,3 ...}, {4,5,6 ...} ...};

Python3 integer division

Try this:

a = 1
b = 2
int_div  = a // b

Bulk package updates using Conda

You want conda update --all.

conda search --outdated will show outdated packages, and conda update --all will update them (note that the latter will not update you from Python 2 to Python 3, but the former will show Python as being outdated if you do use Python 2).

Unsafe JavaScript attempt to access frame with URL

A solution could be to use a local file which retrieves the remote content

remoteInclude.php

<?php
$url = $_GET['url'];
$contents = file_get_contents($url);
echo $contents;

The HTML

<iframe frameborder="1" id="frametest" src="/remoteInclude.php?url=REMOTE_URL_HERE"></iframe>
<script>
    $("#frametest").load(function (){       
    var contents =$("#frametest").contents();
});

CSS: transition opacity on mouse-out?

You're applying transitions only to the :hover pseudo-class, and not to the element itself.

.item {   
  height:200px;
  width:200px;
  background:red; 
  -webkit-transition: opacity 1s ease-in-out;
  -moz-transition: opacity 1s ease-in-out;
  -ms-transition: opacity 1s ease-in-out;
  -o-transition: opacity 1s ease-in-out;
  transition: opacity 1s ease-in-out;
}

.item:hover {
  zoom: 1;
  filter: alpha(opacity=50);
  opacity: 0.5;
}

Demo: http://jsfiddle.net/7uR8z/6/

If you don't want the transition to affect the mouse-over event, but only mouse-out, you can turn transitions off for the :hover state :

.item:hover {
  -webkit-transition: none;
  -moz-transition: none;
  -ms-transition: none;
  -o-transition: none;
  transition: none;
  zoom: 1;
  filter: alpha(opacity=50);
  opacity: 0.5;
}

Demo: http://jsfiddle.net/7uR8z/3/

Smart way to truncate long strings

Here are my solutions with word boundary.

_x000D_
_x000D_
let s = "At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."
let s_split = s.split(/\s+/);
let word_count = 0;
let result = "";
//1
for(let i = 0; word_count < 100; i++){
  word_count += s_split[i].length+1;
  result += (s_split[i] + " ");
}
console.log(result);
// 2
word_count = 0;
result = s_split.reduce((x,y)=>{
  word_count+=(y.length+1);
  if(word_count>=100) return x;
  else return x+" "+y;}, "").substring(1);
console.log(result);
_x000D_
_x000D_
_x000D_

How to replace sql field value

It depends on what you need to do. You can use replace since you want to replace the value:

select replace(email, '.com', '.org')
from yourtable

Then to UPDATE your table with the new ending, then you would use:

update yourtable
set email = replace(email, '.com', '.org')

You can also expand on this by checking the last 4 characters of the email value:

update yourtable
set email = replace(email, '.com', '.org')
where right(email, 4) = '.com'

However, the issue with replace() is that .com can be will in other locations in the email not just the last one. So you might want to use substring() the following way:

update yourtable
set email = substring(email, 1, len(email) -4)+'.org'
where right(email, 4) = '.com';

See SQL Fiddle with Demo

Using substring() will return the start of the email value, without the final .com and then you concatenate the .org to the end. This prevents the replacement of .com elsewhere in the string.

Alternatively you could use stuff(), which allows you to do both deleting and inserting at the same time:

update yourtable
set email = stuff(email, len(email) - 3, 4, '.org')
where right(email, 4) = '.com';

This will delete 4 characters at the position of the third character before the last one (which is the starting position of the final .com) and insert .org instead.

See SQL Fiddle with Demo for this method as well.

When to use CouchDB over MongoDB and vice versa

The answers above all over complicate the story.

  1. If you plan to have a mobile component, or need desktop users to work offline and then sync their work to a server you need CouchDB.
  2. If your code will run only on the server then go with MongoDB

That's it. Unless you need CouchDB's (awesome) ability to replicate to mobile and desktop devices, MongoDB has the performance, community and tooling advantage at present.

How to check if an array element exists?

You can use isset() for this very thing.

$myArr = array("Name" => "Jonathan");
print (isset($myArr["Name"])) ? "Exists" : "Doesn't Exist" ;

SOAP or REST for Web Services?

An old question but still relevant today....due to so many developers in the enterprise space still using it.

My work involves designing and developing IoT (Internet of Things) solutions. Which includes developing code for small embedded devices that communicate with the Cloud.

It is clear REST is now widely accepted and useful, and pretty much the defacto standard for the web, even Microsoft has REST support included throughout Azure. If I needed to rely on SOAP I could not do what I need to do, as is just too big, bulky and annoying for small embedded devices.

REST is simple and clean and small. Making it ideal for small embedded devices. I always scream when I am working with a web developer who sends me a WSDLs. As I will have to begin an education campaign about why this just isn't going to work and why they are going to have to learn REST.

How do Python functions handle the types of the parameters that you pass in?

I have implemented a wrapper if anyone would like to specify variable types.

import functools
    
def type_check(func):

    @functools.wraps(func)
    def check(*args, **kwargs):
        for i in range(len(args)):
            v = args[i]
            v_name = list(func.__annotations__.keys())[i]
            v_type = list(func.__annotations__.values())[i]
            error_msg = 'Variable `' + str(v_name) + '` should be type ('
            error_msg += str(v_type) + ') but instead is type (' + str(type(v)) + ')'
            if not isinstance(v, v_type):
                raise TypeError(error_msg)

        result = func(*args, **kwargs)
        v = result
        v_name = 'return'
        v_type = func.__annotations__['return']
        error_msg = 'Variable `' + str(v_name) + '` should be type ('
        error_msg += str(v_type) + ') but instead is type (' + str(type(v)) + ')'
        if not isinstance(v, v_type):
                raise TypeError(error_msg)
        return result

    return check

Use it as:

@type_check
def test(name : str) -> float:
    return 3.0

@type_check
def test2(name : str) -> str:
    return 3.0

>> test('asd')
>> 3.0

>> test(42)
>> TypeError: Variable `name` should be type (<class 'str'>) but instead is type (<class 'int'>)

>> test2('asd')
>> TypeError: Variable `return` should be type (<class 'str'>) but instead is type (<class 'float'>)

EDIT

The code above does not work if any of the arguments' (or return's) type is not declared. The following edit can help, on the other hand, it only works for kwargs and does not check args.

def type_check(func):

    @functools.wraps(func)
    def check(*args, **kwargs):
        for name, value in kwargs.items():
            v = value
            v_name = name
            if name not in func.__annotations__:
                continue
                
            v_type = func.__annotations__[name]

            error_msg = 'Variable `' + str(v_name) + '` should be type ('
            error_msg += str(v_type) + ') but instead is type (' + str(type(v)) + ') '
            if not isinstance(v, v_type):
                raise TypeError(error_msg)

        result = func(*args, **kwargs)
        if 'return' in func.__annotations__:
            v = result
            v_name = 'return'
            v_type = func.__annotations__['return']
            error_msg = 'Variable `' + str(v_name) + '` should be type ('
            error_msg += str(v_type) + ') but instead is type (' + str(type(v)) + ')'
            if not isinstance(v, v_type):
                    raise TypeError(error_msg)
        return result

    return check

How can we run a test method with multiple parameters in MSTest?

It is unfortunately not supported in older versions of MSTest. Apparently there is an extensibility model and you can implement it yourself. Another option would be to use data-driven tests.

My personal opinion would be to just stick with NUnit though...

As of Visual Studio 2012, update 1, MSTest has a similar feature. See McAden's answer.

Why does the Google Play store say my Android app is incompatible with my own device?

I also had the same problem. I published an App in Test mode created with React Native 59. it wasn't compatible for certain tester. The message wasn't clear about why the app is not compatible , after i figured out that i restricted the app to be available only for certain country . that was the problem, but as i said the message wasn't clear. in Play Store WebApp the message is: "this app is not compatible with your device". in the mobile app the message "This app is not available in your country"

Sum across multiple columns with dplyr

If you want to sum certain columns only, I'd use something like this:

library(dplyr)
df=data.frame(
  x1=c(1,0,0,NA,0,1,1,NA,0,1),
  x2=c(1,1,NA,1,1,0,NA,NA,0,1),
  x3=c(0,1,0,1,1,0,NA,NA,0,1),
  x4=c(1,0,NA,1,0,0,NA,0,0,1),
  x5=c(1,1,NA,1,1,1,NA,1,0,1))
df %>% select(x3:x5) %>% rowSums(na.rm=TRUE) -> df$x3x5.total
head(df)

This way you can use dplyr::select's syntax.

Vagrant ssh authentication failure

for me, this was resolved by changing the permissions on .ssh folder in vagrant home directort (i.e. "~vagrant/.ssh"). I think I messed up the permissions when I was setting up ssh keys for my application.

It seems that 'authorized_keys' file must be 'rw' only for 'vagrant' user so "chmod 600 authorized_keys"; the same goes for the directory itself and its parent:

so:

chmod 600 authorized_keys
chmod 700 .
chmod 700 ..

It was only after I had all these permissions restored that vagrant ssh started to work again.

I think it's something to do with ssh security. It refuses to recognise certificates if they are any way accessible beyond the current user, so vagrants attempts to login are thus rejected.

Drop Down Menu/Text Field in one

I found this question and discussion very helpful and wanted to show the solution I ended up with. It is based on the answer given by @DevangRathod, but I used jQuery and made a couple tweaks to it, so wanted to show a fully commented sample to help anyone else working on something similar. I originally had been using the HTML5 data-list element, but was dissatisfied with that solution since it removes options from the drop down list that don't match text typed in the box. In my application, I wanted the full list to always be available.

Fully functional demo here: https://jsfiddle.net/abru77mm/

HTML:

<!-- 
Most style elements I left to the CSS file, but some are here.
Reason being that I am actually calculating my width dynamically
in my application so when I dynamically formulate this HTML, I
want the width and all the factors (such as padding and border
width and margin) that go into determining the proper widths to
be controlled by one piece of code, so those pieces are done in
the in-line style.  Otherwise I leave the styling to the CSS file.
-->
<div class="data-list-input" style="width:190px;">
  <select class="data-list-input" style="width:190px;">
    <option value="">&lt;Free Form Text&gt;</option>
    <option value="Male">Male</option>
    <option value="Female">Female</option>
    <!-- Note that though the select/option allows for a different
    display and internal value, there is no such distinction in the
    text box, so for all the options (except the "none" option) the
    value and content of the option should be identical. -->
  </select>
  <input class="data-list-input" style="width:160px;padding:4px 6px;border-width:1px;margin:0;" type="text" name="sex" required="required" value="">
</div>

JS:

jQuery(function() {
  //keep the focus on the input box so that the highlighting
  //I'm using doesn't give away the hidden select box to the user
  $('select.data-list-input').focus(function() {
    $(this).siblings('input.data-list-input').focus();
  });
  //when selecting from the select box, put the value in the input box
  $('select.data-list-input').change(function() {
    $(this).siblings('input.data-list-input').val($(this).val());
  });
  //When editing the input box, reset the select box setting to "free
  //form input". This is important to do so that you can reselect the
  //option you had selected if you want to.
  $('input.data-list-input').change(function() {
    $(this).siblings('select.data-list-input').val('');
  });
});

CSS:

div.data-list-input
{
    position: relative;
    height: 20px;
    display: inline-flex;
    padding: 5px 0 5px 0;
}
select.data-list-input
{
    position: absolute;
    top: 5px;
    left: 0px;
    height: 20px;
}
input.data-list-input
{
    position: absolute;
    top: 0px;
    left: 0px;
    height: 20px;
}

Any comments for improvement on my implementation welcome. Hope someone finds this helpful.

symbol(s) not found for architecture i386

Another situation that can cause this problem is if your code calls into C++, or is called by C++ code. I had a problem with my own .c file's utility function showing up as "symbol not found" when called from Obj-C. The fix was to change the file type: in Xcode 4, use the extended info pane to set the file type to "Objective-C++ Source"; in Xcode 3, use "Get Info" to change file type to "source.cpp.objcpp".

Set bootstrap modal body height by percentage

This should work for everyone, any screen resolutions:

.modal-body {
    max-height: calc(100vh - 143px);
    overflow-y: auto; }

First, count your modal header and footer height, in my case I have H4 heading so I have them on 141px, already counted default modal margin in 20px(top+bottom).

So that subtract 141px is the max-height for my modal height, for the better result there are both border top and bottom by 1px, for this, 143px will work perfectly.

In some case of styling you may like to use overflow-y: auto; instead of overflow-y: scroll;, try it.

Try it, and you get the best result in both computer or mobile devices. If you have a heading larger than H4, recount it see how much px you would like to subtract.

If you don't know what I am telling, just change the number of 143px, see what is the best result for your case.

Last, I'd suggest have it an inline CSS.

Getting the first and last day of a month, using a given DateTime object

For Persian culture

PersianCalendar pc = new PersianCalendar();            

var today = pc.GetDayOfMonth(DateTime.Now);
var firstDayOfMonth = pc.GetDayOfMonth(DateTime.Now.AddDays(-(today-1)));
var lastDayOfMonth = pc.GetDayOfMonth(DateTime.Now.AddMonths(1).AddDays(-today));            
Console.WriteLine("First day "+ firstDayOfMonth);
Console.WriteLine("Last day " + lastDayOfMonth);

FIFO class in Java

Not sure what you call FIFO these days since Queue is FILO, but when I was a student we used the Stack<E> with the simple push, pop, and a peek... It is really that simple, no need for complicating further with Queue and whatever the accepted answer suggests.

Get JSON Data from URL Using Android?

Don't know about android but in POJ I use

public final class MyJSONObject extends JSONObject {
    public MyJSONObject(URL url) throws IOException {
        super(getServerData(url));
    }
    static String getServerData(URL url) throws IOException {
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        BufferedReader ir = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String text = ir.lines().collect(Collectors.joining("\n"));
        return (text);
    }
}

Hashing a file in Python

import hashlib
user = input("Enter ")
h = hashlib.md5(user.encode())
h2 = h.hexdigest()
with open("encrypted.txt","w") as e:
    print(h2,file=e)


with open("encrypted.txt","r") as e:
    p = e.readline().strip()
    print(p)

Python: how to capture image from webcam on click using OpenCV

Here is a simple program that displays the camera feed in a cv2.namedWindow and will take a snapshot when you hit SPACE. It will also quit if you hit ESC.

import cv2

cam = cv2.VideoCapture(0)

cv2.namedWindow("test")

img_counter = 0

while True:
    ret, frame = cam.read()
    if not ret:
        print("failed to grab frame")
        break
    cv2.imshow("test", frame)

    k = cv2.waitKey(1)
    if k%256 == 27:
        # ESC pressed
        print("Escape hit, closing...")
        break
    elif k%256 == 32:
        # SPACE pressed
        img_name = "opencv_frame_{}.png".format(img_counter)
        cv2.imwrite(img_name, frame)
        print("{} written!".format(img_name))
        img_counter += 1

cam.release()

cv2.destroyAllWindows()

I think this should answer your question for the most part. If there is any line of it that you don't understand let me know and I'll add comments.

If you need to grab multiple images per press of the SPACE key, you will need an inner loop or perhaps just make a function that grabs a certain number of images.

Note that the key events are from the cv2.namedWindow so it has to have focus.

How can I use UserDefaults in Swift?

class UserDefaults_WorstPresidentName {
    static let key = "appname.worstPresidentName"

    static var value: String? {
        get {
            return UserDefaults.standard.string(forKey: key)
        }
        set {
            if newValue != nil {
                UserDefaults.standard.set(newValue, forKey: key)
            } else {
                UserDefaults.standard.removeObject(forKey: key)
            }
        }
    }
}

Make a table fill the entire window

Try using

<html style="height: 100%;">
    <body style="height: 100%;">
        <table style="height: 100%;">
        ...

in order to force all parents of the table element to expand over the available vertical space (which will eliminate the need to use absolute positioning).

Works in Firefox 28, IE 11 and Chromium 34 (and hence probably Google Chrome as well)

Source: http://www.dailycoding.com/posts/howtoset100tableheightinhtml.aspx

require_once :failed to open stream: no such file or directory

It says that the file C:\wamp\www\mysite\php\includes\dbconn.inc doesn't exist, so the error is, you're missing the file.

Swift Error: Editor placeholder in source file

Sometimes, XCode does not forget the line which had an "Editor Placeholder" even if you have replaced it with a value. Cut the portion of the code where XCode is complaining and paste the code back to the same place to make the error message go away. This worked for me.

How to make a cross-module variable?

I use this for a couple built-in primitive functions that I felt were really missing. One example is a find function that has the same usage semantics as filter, map, reduce.

def builtin_find(f, x, d=None):
    for i in x:
        if f(i):
            return i
    return d

import __builtin__
__builtin__.find = builtin_find

Once this is run (for instance, by importing near your entry point) all your modules can use find() as though, obviously, it was built in.

find(lambda i: i < 0, [1, 3, 0, -5, -10])  # Yields -5, the first negative.

Note: You can do this, of course, with filter and another line to test for zero length, or with reduce in one sort of weird line, but I always felt it was weird.

How to set Bullet colors in UL/LI html lists via CSS without using any images or span tags

I am adding my solution to this problem.

I don't want to use image and validator will punish you for using negative values in CSS, so I go this way:

ul          { list-style:none; padding:0; margin:0; }

li          { padding-left:0.75em; position:relative; }

li:before       { content:"•"; color:#e60000; position:absolute; left:0em; }

CS1617: Invalid option ‘6’ for /langversion; must be ISO-1, ISO-2, 3, 4, 5 or Default

I've updated the Microsoft.Net.Compilers to version 2.0 or higher

see this

How to make space between LinearLayout children?

Use LinearLayout.LayoutParams instead of MarginLayoutParams. Here's the documentation.

Get epoch for a specific date using Javascript

Number(new Date(2010, 6, 26))

Works the same way as things above. If you need seconds don't forget to / 1000

How do I create sql query for searching partial matches?

This may work as well.

SELECT * 
FROM myTable
WHERE CHARINDEX('mall', name) > 0
  OR CHARINDEX('mall', description) > 0

Jquery If radio button is checked

if($('#test2').is(':checked')) {
    $(this).append('stuff');
} 

Make: how to continue after a command fails?

To get make to actually ignore errors on a single line, you can simply suffix it with ; true, setting the return value to 0. For example:

rm .lambda .lambda_t .activity .activity_t_lambda 2>/dev/null; true

This will redirect stderr output to null, and follow the command with true (which always returns 0, causing make to believe the command succeeded regardless of what actually happened), allowing program flow to continue.

How to convert string to boolean in typescript Angular 4

I have been trying different values with JSON.parse(value) and it seems to do the work:

// true
Boolean(JSON.parse("true"));
Boolean(JSON.parse("1"));
Boolean(JSON.parse(1));
Boolean(JSON.parse(true));

// false
Boolean(JSON.parse("0")); 
Boolean(JSON.parse(0));
Boolean(JSON.parse("false"));
Boolean(JSON.parse(false));

Clear git local cache

All .idea files that are explicitly ignored are still showing up to commit

you have to remove them from the staging area

git rm --cached .idea

now you have to commit those changes and they will be ignored from this point on.
Once git start to track changes it will not "stop" tracking them even if they were added to the .gitignore file later on.

You must explicitly remove them and then commit your removal manually in order to fully ignore them.


enter image description here

enter image description here

git submodule tracking latest

Edit (2020.12.28): GitHub change default master branch to main branch since October 2020. See https://github.com/github/renaming


Update March 2013

Git 1.8.2 added the possibility to track branches.

"git submodule" started learning a new mode to integrate with the tip of the remote branch (as opposed to integrating with the commit recorded in the superproject's gitlink).

# add submodule to track master branch
git submodule add -b master [URL to Git repo];

# update your submodule
git submodule update --remote 

If you had a submodule already present you now wish would track a branch, see "how to make an existing submodule track a branch".

Also see Vogella's tutorial on submodules for general information on submodules.

Note:

git submodule add -b . [URL to Git repo];
                    ^^^

See git submodule man page:

A special value of . is used to indicate that the name of the branch in the submodule should be the same name as the current branch in the current repository.


See commit b928922727d6691a3bdc28160f93f25712c565f6:

submodule add: If --branch is given, record it in .gitmodules

This allows you to easily record a submodule.<name>.branch option in .gitmodules when you add a new submodule. With this patch,

$ git submodule add -b <branch> <repository> [<path>]
$ git config -f .gitmodules submodule.<path>.branch <branch>

reduces to

$ git submodule add -b <branch> <repository> [<path>]

This means that future calls to

$ git submodule update --remote ...

will get updates from the same branch that you used to initialize the submodule, which is usually what you want.

Signed-off-by: W. Trevor King [email protected]


Original answer (February 2012):

A submodule is a single commit referenced by a parent repo.
Since it is a Git repo on its own, the "history of all commits" is accessible through a git log within that submodule.

So for a parent to track automatically the latest commit of a given branch of a submodule, it would need to:

  • cd in the submodule
  • git fetch/pull to make sure it has the latest commits on the right branch
  • cd back in the parent repo
  • add and commit in order to record the new commit of the submodule.

gitslave (that you already looked at) seems to be the best fit, including for the commit operation.

It is a little annoying to make changes to the submodule due to the requirement to check out onto the correct submodule branch, make the change, commit, and then go into the superproject and commit the commit (or at least record the new location of the submodule).

Other alternatives are detailed here.

Python: "Indentation Error: unindent does not match any outer indentation level"

I am using gedit basic version that comes with Ubuntu 11.10. I had the same error. This is mainly caused when you mix spaces with tabs.

A good way to differentiate as to which lines have problem would be to go to: 1. edit 2. preferences 3. editor 4. check "automatic indentation" 5. increase the indentation to 12 or some big number

after doing the fifth step you will be able to see the lines of your code that are relly causing problem (these are the lines that have a mix of space and tab)

Make the entire code convention as just TAB or just SPACE (this has to be done manually line by line)

Hope this helps...

Android Studio and android.support.v4.app.Fragment: cannot resolve symbol

For me the cause of problem was broken class path:

Library Gradle: com.android.support:support-v4:28.0.0@aar has broken classes path:   
/Users/YOUR_USER/.gradle/caches/transforms-1/files-1.1/support-v4-28.0.0.aar/0f378acce70d3d38db494e7ae5aa6008/res

So only removing transforms-1 folder and further Gradle Sync helped.

Android video streaming example

Your problem is most likely with the video file, not the code. Your video is most likely not "safe for streaming". See where to place videos to stream android for more.

c# dictionary How to add multiple values for single key?

Update: check for existence using TryGetValue to do only one lookup in the case where you have the list:

List<int> list;

if (!dictionary.TryGetValue("foo", out list))
{
    list = new List<int>();
    dictionary.Add("foo", list);
}

list.Add(2);


Original: Check for existence and add once, then key into the dictionary to get the list and add to the list as normal:

var dictionary = new Dictionary<string, List<int>>();

if (!dictionary.ContainsKey("foo"))
    dictionary.Add("foo", new List<int>());

dictionary["foo"].Add(42);
dictionary["foo"].AddRange(oneHundredInts);

Or List<string> as in your case.

As an aside, if you know how many items you are going to add to a dynamic collection such as List<T>, favour the constructor that takes the initial list capacity: new List<int>(100);.

This will grab the memory required to satisfy the specified capacity upfront, instead of grabbing small chunks every time it starts to fill up. You can do the same with dictionaries if you know you have 100 keys.

Check if AJAX response data is empty/blank/null/undefined/0

$.ajax({
    type:"POST",
    url: "<?php echo admin_url('admin-ajax.php'); ?>",
    data: associated_buildsorprojects_form,
    success:function(data){
        // do console.log(data);
        console.log(data);
        // you'll find that what exactly inside data 
        // I do not prefer alter(data); now because, it does not 
        // completes requirement all the time 
        // After that you can easily put if condition that you do not want like
        // if(data != '')
        // if(data == null)
        // or whatever you want 
    },
    error: function(errorThrown){
        alert(errorThrown);
        alert("There is an error with AJAX!");
    }               
});

How can I make the Android emulator show the soft keyboard?

I found out how to do this on the Android emulator itself (Menu, "Settings" App - not the settings of the emulator outside). All you need to do is:

open settings app -> Language & Input -> Go to the "Keyboard & Input Methods -> click Default

This will bring up a Dialog in which case you can then disable the Hardware Keyboard by switching the hardware keyboard from on to off. This will disable the Hardware keyboard and enable the softkeyboard.

How to set "style=display:none;" using jQuery's attr method?

Based on the comment we are removing one property from style attribute.

Here this was not affect, but when more property are used within the style it helpful.

$('#msform').css('display', '')

After this we use

$("#msform").show();

What is the (function() { } )() construct in JavaScript?

No, this construct just creates a scope for naming. If you break it in parts you can see that you have an external

(...)();

That is a function invocation. Inside the parenthesis you have:

function() {}

That is an anonymous function. Everything that is declared with var inside the construct will be visible only inside the same construct and will not pollute the global namespace.

android.os.FileUriExposedException: file:///storage/emulated/0/test.txt exposed beyond app through Intent.getData()

Simply let it ignore the URI Exposure... Add it after on create

StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder(); StrictMode.setVmPolicy(builder.build()); 

How to remove CocoaPods from a project?

If you just want to remove one pod and keep others you may have installed, open the podfile in your app directory and delete the one you want to remove. Then navigate to your app directory using terminal and type:

pod update

This will remove the pod you removed from the podfile. You will see it has been removed in the terminal:

Analyzing dependencies
Removing FirebaseUI
Removing UICircularProgressRing

Note that this method will also pull any updates to the other pods in your podfile. You may or may not want that.

Range of values in C Int and Long 32 - 64 bits

A 32-bit unsigned int has a range from 0 to 4,294,967,295. 0 to 65535 would be a 16-bit unsigned.

An unsigned long long (and, on a 64-bit implementation, possibly also ulong and possibly uint as well) have a range (at least) from 0 to 18,446,744,073,709,551,615 (264-1). In theory it could be greater than that, but at least for now that's rare to nonexistent.

Index Error: list index out of range (Python)

Generally it means that you are providing an index for which a list element does not exist.

E.g, if your list was [1, 3, 5, 7], and you asked for the element at index 10, you would be well out of bounds and receive an error, as only elements 0 through 3 exist.

7-zip commandline

I've not looked into this but shooting from the hip I'd say that they dropped command line support in the portable. The reason people don't do much command line stuff in portable applications is that the OS (windows in your case) requires that executables be added to the %path% inclusion list.

If that requirement is not met using command line utilities is rather tedious.

7z -a .

would be

d:\portable\z7\z7 -a c:\to\archive\folder*.*

Typing that out for everything is why GUI's make sense with things like portable apps it (the app) can remember it's own location and handle that stuff for you and if you can't run it you know it's not attached.

If you really want the portable app to contain that though you can always install the full version and pull the required 7z.exe out and put it into the portable folder making sure it's in with the required dll's.

You'll have to set your path when you hit the shell after making sure it's attached.

http://www.redfernplace.com/software-projects/patheditor/ -- a good path editor (down) usefull if you have lots of path information 20+ get's hard to read.

http://www.softpedia.com/get/System/System-Miscellaneous/Path-Editor.shtml -- alternet source for path editor

It's not advisable to modify your system path for temproary "portable" drives though manualy do that by:

set path=%path%;"d:\portable\z7\";

when you run dos cmd.exe or http://sourceforge.net/p/conemu/home/Home/

The other answers address other problems better I'm not going to try..

http://www.codejacked.com/zip-up-files-from-the-command-line/ -- good reference for command line usage of z7 and z7a.

PS: sorry for the necro but I figured it needed a more direct answer to why (even if it's just speculative).

Ubuntu - Run command on start-up with "sudo"

Nice answers. You could also set Jobs (i.e., commands) with "Crontab" for more flexibility (which provides different options to run scripts, loggin the outputs, etc.), although it requires more time to be understood and set properly:

Using '@reboot' you can Run a command once, at startup.

Wrapping up: run $ sudo crontab -e -u root

And add a line at the end of the file with your command as follows:

@reboot sudo searchd

How do I parse a YAML file in Ruby?

I had the same problem but also wanted to get the content of the file (after the YAML front-matter).

This is the best solution I have found:

if (md = contents.match(/^(?<metadata>---\s*\n.*?\n?)^(---\s*$\n?)/m))
  self.contents = md.post_match
  self.metadata = YAML.load(md[:metadata])
end

Source and discussion: https://practicingruby.com/articles/tricks-for-working-with-text-and-files

Set size of HTML page and browser window

<html>
<head >
<title>Welcome</title>    
<style type="text/css">
#maincontainer 
{   
top:0px;
padding-top:0;
margin:auto; position:relative;
width:950px;
height:100%;
}
  </style>
  </head>
<body>
 <div id="maincontainer ">
 </div>
</body>
</html>

Java format yyyy-MM-dd'T'HH:mm:ss.SSSz to yyyy-mm-dd HH:mm:ss

java.time

We have new technology for this problem: the java.time framework built into Java 8 and later.

Your input string is in standard ISO 8601 format. That standard is used by default in the java.time classes for parsing/generating textual representations of date-time values.

OffsetDateTime odt = OffsetDateTime.parse( "2012-10-01T09:45:00.000+02:00" );

Your Question suggests you want to truncate to a whole second.

OffsetDateTime odtTruncatedToWholeSecond = odt.truncatedTo( ChronoUnit.SECONDS );

It seems you want to omit the offset and time zone info. The pre-defined formatter DateTimeFormatter.ISO_LOCAL_DATE_TIME does that.

And apparently you want to use a space in the middle rather than the standard T. You could define your own formatter for this, but I would just do a string manipulation to replace the T with a SPACE.

String output = odtTruncatedToWholeSecond.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME ).replace( "T" , " " );

Simply String Manipulations

As the comments on the Question suggest, strictly speaking you can accomplish your goal by working only with strings and not converting to any date-time objects. But I provide this Answer here assuming you may have other business logic to work with these date-time values.


Table of date-time types in Java, both modern and legacy


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

Table of which java.time library to use with which version of Java or Android

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

How to determine the version of the C++ standard used by the compiler?

Use __cplusplus as suggested. Only one note for Microsoft compiler, use Zc:__cplusplus compiler switch to enable __cplusplus

Source https://devblogs.microsoft.com/cppblog/msvc-now-correctly-reports-__cplusplus/

Setting paper size in FPDF

/*$mpdf = new mPDF('',    // mode - default ''
 '',    // format - A4, for example, default ''
 0,     // font size - default 0
 '',    // default font family
 15,    // margin_left
 15,    // margin right
 16,     // margin top
 16,    // margin bottom
 9,     // margin header
 9,     // margin footer
 'L');  // L - landscape, P - portrait*/

shift a std_logic_vector of n bit to right or left

Personally, I think the concatenation is the better solution. The generic implementation would be

entity shifter is
    generic (
        REGSIZE  : integer := 8);
    port(
        clk      : in  str_logic;
        Data_in  : in  std_logic;
        Data_out : out std_logic(REGSIZE-1 downto 0);
end shifter ;

architecture bhv of shifter is
    signal shift_reg : std_logic_vector(REGSIZE-1 downto 0) := (others<='0');
begin
    process (clk) begin
        if rising_edge(clk) then
            shift_reg <= shift_reg(REGSIZE-2 downto 0) & Data_in;
        end if;
    end process;
end bhv;
Data_out <= shift_reg;

Both will implement as shift registers. If you find yourself in need of more shift registers than you are willing to spend resources on (EG dividing 1000 numbers by 4) you might consider using a BRAM to store the values and a single shift register to contain "indices" that result in the correct shift of all the numbers.

Setting active profile and config location from command line in spring boot

I had to add this:

bootRun {
    String activeProfile =  System.properties['spring.profiles.active']
    String confLoc = System.properties['spring.config.location']
    systemProperty "spring.profiles.active", activeProfile
    systemProperty "spring.config.location", "file:$confLoc"
}

And now bootRun picks up the profile and config locations.

Thanks a lot @jst for the pointer.

How to display both icon and title of action inside ActionBar?

Follow these steps:

  1. Add the Action Bar instance in the Java Code final ActionBar actionBar = getActionBar();
  2. Enable the Home Display Option actionBar.setDisplayShowHomeEnabled(false);
  3. Add the following code in the respective activity's manifest file android:logo=@drawable/logo and android:label="@string/actionbar_text"

I think this will help you

How to send a stacktrace to log4j?

You can also get stack trace as string via ExceptionUtils.getStackTrace.

See: ExceptionUtils.java

I use it only for log.debug, to keep log.error simple.

How can I convert a string to an int in Python?

Don't use str() method directly in html instead use with y=x|string()

<div class="row">
    {% for x in range(photo_upload_count) %}
        {% with y=x|string() %}

    <div col-md-4 >
        <div class="col-md-12">
            <div class="card card-primary "  style="border:1px solid #000">
                <div class="card-body">
                    {% if data['profile_photo']!= None: %}
                        <img class="profile-user-img img-responsive" src="{{ data['photo_'+y] }}" width="200px" alt="User profile picture">
                    {% else: %}
                        <img class="profile-user-img img-responsive" src="static/img/user.png" width="200px" alt="User profile picture">
                    {% endif %}
                </div>
                <div class="card-footer text-center">
                    <a href="{{value}}edit_photo/{{ 'photo_'+y }}" class="btn btn-primary">Edit</a>
                </div>
            </div>
        </div>
    </div>
    {% endwith %}
    {% endfor %}
</div>

Open local folder from link

Only IE6-8 - there's an ActiveX workaround this local-files issue in JavaScript:

        function OpenImage(filePath)
        {
            var myshell = new ActiveXObject("WScript.shell");
            myshell.run(filePath, 1, true); 
        }

How to simulate target="_blank" in JavaScript

This might help

var link = document.createElementNS("http://www.w3.org/1999/xhtml", "a");
    link.href = 'http://www.google.com';
    link.target = '_blank';
    var event = new MouseEvent('click', {
        'view': window,
        'bubbles': false,
        'cancelable': true
    });
    link.dispatchEvent(event);

Test if string begins with a string?

The best methods are already given but why not look at a couple of other methods for fun? Warning: these are more expensive methods but do serve in other circumstances.

The expensive regex method and the css attribute selector with starts with ^ operator

Option Explicit

Public Sub test()

    Debug.Print StartWithSubString("ab", "abc,d")

End Sub

Regex:

Public Function StartWithSubString(ByVal substring As String, ByVal testString As String) As Boolean
    'required reference Microsoft VBScript Regular Expressions
    Dim re As VBScript_RegExp_55.RegExp
    Set re = New VBScript_RegExp_55.RegExp

    re.Pattern = "^" & substring

    StartWithSubString = re.test(testString)

End Function

Css attribute selector with starts with operator

Public Function StartWithSubString(ByVal substring As String, ByVal testString As String) As Boolean
    'required reference Microsoft HTML Object Library
    Dim html As MSHTML.HTMLDocument
    Set html = New MSHTML.HTMLDocument

    html.body.innerHTML = "<div test=""" & testString & """></div>"

    StartWithSubString = html.querySelectorAll("[test^=" & substring & "]").Length > 0

End Function

JavaScript replace/regex

Your regex pattern should have the g modifier:

var pattern = /[somepattern]+/g;

notice the g at the end. it tells the replacer to do a global replace.

Also you dont need to use the RegExp object you can construct your pattern as above. Example pattern:

var pattern = /[0-9a-zA-Z]+/g;

a pattern is always surrounded by / on either side - with modifiers after the final /, the g modifier being the global.

EDIT: Why does it matter if pattern is a variable? In your case it would function like this (notice that pattern is still a variable):

var pattern = /[0-9a-zA-Z]+/g;
repeater.replace(pattern, "1234abc");

But you would need to change your replace function to this:

this.markup = this.markup.replace(pattern, value);

What's the proper way to compare a String to an enum value?

Define enum:

public enum Gesture
{
    ROCK, PAPER, SCISSORS;
}

Define a method to check enum content:

private boolean enumContainsValue(String value)
{
    for (Gesture gesture : Gesture.values())
    {
        if (gesture.name().equals(value))
        {
            return true;
        }
    }

    return false;
}

And use it:

String gestureString = "PAPER";

if (enumContainsValue(gestureString))
{
    Gesture gestureId = Gesture.valueOf(gestureString);

    switch (gestureId)
    {
        case ROCK:
            Log.i("TAG", "ROCK");
            break;

        case PAPER:
            Log.i("TAG", "PAPER");
            break;

        case SCISSORS:
            Log.i("TAG", "SCISSORS");
            break;
    }
}

Upper memory limit?

You're reading the entire file into memory (line = u.readlines()) which will fail of course if the file is too large (and you say that some are up to 20 GB), so that's your problem right there.

Better iterate over each line:

for current_line in u:
    do_something_with(current_line)

is the recommended approach.

Later in your script, you're doing some very strange things like first counting all the items in a list, then constructing a for loop over the range of that count. Why not iterate over the list directly? What is the purpose of your script? I have the impression that this could be done much easier.

This is one of the advantages of high-level languages like Python (as opposed to C where you do have to do these housekeeping tasks yourself): Allow Python to handle iteration for you, and only collect in memory what you actually need to have in memory at any given time.

Also, as it seems that you're processing TSV files (tabulator-separated values), you should take a look at the csv module which will handle all the splitting, removing of \ns etc. for you.

How to create multiple page app using react

This is a broad question and there are multiple ways you can achieve this. In my experience, I've seen a lot of single page applications having an entry point file such as index.js. This file would be responsible for 'bootstrapping' the application and will be your entry point for webpack.

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import Application from './components/Application';

const root = document.getElementById('someElementIdHere');

ReactDOM.render(
  <Application />,
  root,
);

Your <Application /> component would contain the next pieces of your app. You've stated you want different pages and that leads me to believe you're using some sort of routing. That could be included into this component along with any libraries that need to be invoked on application start. react-router, redux, redux-saga, react-devtools come to mind. This way, you'll only need to add a single entry point into your webpack configuration and everything will trickle down in a sense.

When you've setup a router, you'll have options to set a component to a specific matched route. If you had a URL of /about, you should create the route in whatever routing package you're using and create a component of About.js with whatever information you need.

Most efficient way to remove special characters from string

Well, unless you really need to squeeze the performance out of your function, just go with what is easiest to maintain and understand. A regular expression would look like this:

For additional performance, you can either pre-compile it or just tell it to compile on first call (subsequent calls will be faster.)

public static string RemoveSpecialCharacters(string str)
{
    return Regex.Replace(str, "[^a-zA-Z0-9_.]+", "", RegexOptions.Compiled);
}

Amazon Linux: apt-get: command not found

Try to install your application by using yum command yum install application_name

How to consume REST in Java

Look at Jersey. Again, REST is all about the data. And a tutorial here

How can I create a dynamic button click event on a dynamic button?

The easier one for newbies:

Button button = new Button();
button.Click += new EventHandler(button_Click);

protected void button_Click (object sender, EventArgs e)
{
    Button button = sender as Button;
    // identify which button was clicked and perform necessary actions
}

Evaluating a mathematical expression in a string

Here's my solution to the problem without using eval. Works with Python2 and Python3. It doesn't work with negative numbers.

$ python -m pytest test.py

test.py

from solution import Solutions

class SolutionsTestCase(unittest.TestCase):
    def setUp(self):
        self.solutions = Solutions()

    def test_evaluate(self):
        expressions = [
            '2+3=5',
            '6+4/2*2=10',
            '3+2.45/8=3.30625',
            '3**3*3/3+3=30',
            '2^4=6'
        ]
        results = [x.split('=')[1] for x in expressions]
        for e in range(len(expressions)):
            if '.' in results[e]:
                results[e] = float(results[e])
            else:
                results[e] = int(results[e])
            self.assertEqual(
                results[e],
                self.solutions.evaluate(expressions[e])
            )

solution.py

class Solutions(object):
    def evaluate(self, exp):
        def format(res):
            if '.' in res:
                try:
                    res = float(res)
                except ValueError:
                    pass
            else:
                try:
                    res = int(res)
                except ValueError:
                    pass
            return res
        def splitter(item, op):
            mul = item.split(op)
            if len(mul) == 2:
                for x in ['^', '*', '/', '+', '-']:
                    if x in mul[0]:
                        mul = [mul[0].split(x)[1], mul[1]]
                    if x in mul[1]:
                        mul = [mul[0], mul[1].split(x)[0]]
            elif len(mul) > 2:
                pass
            else:
                pass
            for x in range(len(mul)):
                mul[x] = format(mul[x])
            return mul
        exp = exp.replace(' ', '')
        if '=' in exp:
            res = exp.split('=')[1]
            res = format(res)
            exp = exp.replace('=%s' % res, '')
        while '^' in exp:
            if '^' in exp:
                itm = splitter(exp, '^')
                res = itm[0] ^ itm[1]
                exp = exp.replace('%s^%s' % (str(itm[0]), str(itm[1])), str(res))
        while '**' in exp:
            if '**' in exp:
                itm = splitter(exp, '**')
                res = itm[0] ** itm[1]
                exp = exp.replace('%s**%s' % (str(itm[0]), str(itm[1])), str(res))
        while '/' in exp:
            if '/' in exp:
                itm = splitter(exp, '/')
                res = itm[0] / itm[1]
                exp = exp.replace('%s/%s' % (str(itm[0]), str(itm[1])), str(res))
        while '*' in exp:
            if '*' in exp:
                itm = splitter(exp, '*')
                res = itm[0] * itm[1]
                exp = exp.replace('%s*%s' % (str(itm[0]), str(itm[1])), str(res))
        while '+' in exp:
            if '+' in exp:
                itm = splitter(exp, '+')
                res = itm[0] + itm[1]
                exp = exp.replace('%s+%s' % (str(itm[0]), str(itm[1])), str(res))
        while '-' in exp:
            if '-' in exp:
                itm = splitter(exp, '-')
                res = itm[0] - itm[1]
                exp = exp.replace('%s-%s' % (str(itm[0]), str(itm[1])), str(res))

        return format(exp)

Changing the git user inside Visual Studio Code

There is a conflict between Visual Studio 2015 and Visual Studio Code for the git credentials. When i changed my credentials on VS 2015 VS Code let me push with the correct git ID.

Radio Buttons "Checked" Attribute Not Working

The jQuery documentation provides a detailed explanation for checked property vs attribute.

Accordingly, here is another way to retrieve selected radio button value

var accepted = $('input[name="Contact0_AmericanExpress"]:checked').val();

How can I solve "Non-static method xxx:xxx() should not be called statically in PHP 5.4?

I don't suggest you just hidding the stricts errors on your project. Intead, you should turn your method to static or try to creat a new instance of the object:

$var = new YourClass();
$var->method();

You can also use the new way to do the same since PHP 5.4:

(new YourClass)->method();

I hope it helps you!

Usage of @see in JavaDoc?

Yeah, it is quite vague.

You should use it whenever for readers of the documentation of your method it may be useful to also look at some other method. If the documentation of your methodA says "Works like methodB but ...", then you surely should put a link. An alternative to @see would be the inline {@link ...} tag:

/**
 * ...
 * Works like {@link #methodB}, but ...
 */

When the fact that methodA calls methodB is an implementation detail and there is no real relation from the outside, you don't need a link here.

CSS disable hover effect

Add the following to add hover effect on disabled button:

.buttonDisabled:hover
  {
    /*your code goes here*/     
  }

How to print jquery object/array

var arrofobject = [{"id":"197","category":"Damskie"},{"id":"198","category":"M\u0119skie"}];

$.each(arrofobject, function(index, val) {
    console.log(val.category);
});

How can I close a browser window without receiving the "Do you want to close this window" prompt?

_x000D_
_x000D_
window.open('', '_self', '').close();
_x000D_
_x000D_
_x000D_

Sorry a bit late here, but i found the solution, at least for my case. Tested on Safari 11.0.3 and Google Chrome 64.0.3282.167

How do implement a breadth first traversal?

It doesn't seem like you're asking for an implementation, so I'll try to explain the process.

Use a Queue. Add the root node to the Queue. Have a loop run until the queue is empty. Inside the loop dequeue the first element and print it out. Then add all its children to the back of the queue (usually going from left to right).

When the queue is empty every element should have been printed out.

Also, there is a good explanation of breadth first search on wikipedia: http://en.wikipedia.org/wiki/Breadth-first_search

apache ProxyPass: how to preserve original IP address

The answer of JasonW is fine. But since apache httpd 2.4.6 there is a alternative: mod_remoteip

All what you must do is:

  1. May be you must install the mod_remoteip package
  2. Enable the module:

    LoadModule remoteip_module modules/mod_remoteip.so
    
  3. Add the following to your apache httpd config. Note that you must add this line not into the configuration of the proxy server. You must add this to the configuration of the proxy target httpd server (the server behind the proxy):

    RemoteIPHeader X-Forwarded-For
    

See at http://httpd.apache.org/docs/trunk/mod/mod_remoteip.html for more informations and more options.

javascript createElement(), style problem

yourElement.setAttribute("style", "background-color:red; font-size:2em;");

Or you could write the element as pure HTML and use .innerHTML = [raw html code]... that's very ugly though.

In answer to your first question, first you use var myElement = createElement(...);, then you do document.body.appendChild(myElement);.

VBA: activating/selecting a worksheet/row/cell

This is just a sample code, but it may help you get on your way:

Public Sub testIt()
    Workbooks("Workbook2").Activate
    ActiveWorkbook.Sheets("Sheet2").Activate
    ActiveSheet.Range("B3").Select
    ActiveCell.EntireRow.Insert
End Sub

I am assuming that you can open the book (called Workbook2 in the example).


I think (but I'm not sure) you can squash all this in a single line of code:

    Workbooks("Workbook2").Sheets("Sheet2").Range("B3").EntireRow.Insert

This way you won't need to activate the workbook (or sheet or cell)... Obviously, the book has to be open.

Sending a file over TCP sockets in Python

Remove below code

s.send("Hello server!")

because your sending s.send("Hello server!") to server, so your output file is somewhat more in size.

ALTER COLUMN in sqlite

There's no ALTER COLUMN in sqlite.

I believe your only option is to:

  • Rename the table to a temporary name
  • Create a new table without the NOT NULL constraint
  • Copy the content of the old table to the new one
  • Remove the old table

This other Stackoverflow answer explains the process in details

jQuery exclude elements with certain class in selector

use this..

$(".content_box a:not('.button')")

Starting of Tomcat failed from Netbeans

This affects:

  • All versions of Tomcat starting from 8.5.3 onwards.
  • All versions of Netbeans up to 8.1 (It is fixed in Netbeans 8.2).

This is because Netbeans does not 'see' that tomcat is started, although it started just fine.

I have filed Bug #262749 with NetBeans.

Workaround

In the server.xml file, in the Connector element for HTTP/1.1, add the following attribute: server="Apache-Coyote/1.1".

Example:

<Connector
  connectionTimeout="20000"
  port="8080"
  protocol="HTTP/1.1"
  redirectPort="8443"
  server="Apache-Coyote/1.1"
/>

Cause

The reason for that is that prior to 8.5.3, the default was to set the server header as Apache-Coyote/1.1, while since 8.5.3 this default has now been changed to blank. Apparently Netbeans checks on this header.

Maybe in the future we can expect a fix in netbeans addressing this issue.

I was able to trace it back to a change in documentation.

Tomcat 8.5:

"Overrides the Server header for the http response. If set, the value for this attribute overrides any Server header set by a web application. If not set, any value specified by the application is used. If the application does not specify a value then no Server header is set."

Tomcat 8.0:

"Overrides the Server header for the http response. If set, the value for this attribute overrides the Tomcat default and any Server header set by a web application. If not set, any value specified by the application is used. If the application does not specify a value then Apache-Coyote/1.1 is used. Unless you are paranoid, you won't need this feature."

That explains the need for explicitly adding the server attribute since version 8.5.3.

How to fix Array indexOf() in JavaScript for Internet Explorer browsers

There is Mozilla official solution: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf

(function() {
    /**Array*/
    // Production steps of ECMA-262, Edition 5, 15.4.4.14
    // Reference: http://es5.github.io/#x15.4.4.14
    if (!Array.prototype.indexOf) {
        Array.prototype.indexOf = function(searchElement, fromIndex) {
            var k;
            // 1. Let O be the result of calling ToObject passing
            //    the this value as the argument.
            if (null === this || undefined === this) {
                throw new TypeError('"this" is null or not defined');
            }
            var O = Object(this);
            // 2. Let lenValue be the result of calling the Get
            //    internal method of O with the argument "length".
            // 3. Let len be ToUint32(lenValue).
            var len = O.length >>> 0;
            // 4. If len is 0, return -1.
            if (len === 0) {
                return -1;
            }
            // 5. If argument fromIndex was passed let n be
            //    ToInteger(fromIndex); else let n be 0.
            var n = +fromIndex || 0;
            if (Math.abs(n) === Infinity) {
                n = 0;
            }
            // 6. If n >= len, return -1.
            if (n >= len) {
                return -1;
            }
            // 7. If n >= 0, then Let k be n.
            // 8. Else, n<0, Let k be len - abs(n).
            //    If k is less than 0, then let k be 0.
            k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
            // 9. Repeat, while k < len
            while (k < len) {
                // a. Let Pk be ToString(k).
                //   This is implicit for LHS operands of the in operator
                // b. Let kPresent be the result of calling the
                //    HasProperty internal method of O with argument Pk.
                //   This step can be combined with c
                // c. If kPresent is true, then
                //    i.  Let elementK be the result of calling the Get
                //        internal method of O with the argument ToString(k).
                //   ii.  Let same be the result of applying the
                //        Strict Equality Comparison Algorithm to
                //        searchElement and elementK.
                //  iii.  If same is true, return k.
                if (k in O && O[k] === searchElement) {
                    return k;
                }
                k++;
            }
            return -1;
        };
    }
})();

What is PostgreSQL equivalent of SYSDATE from Oracle?

NOW() is the replacement of Oracle Sysdate in Postgres.

Try "Select now()", it will give you the system timestamp.

Eclipse memory settings when getting "Java Heap Space" and "Out of Memory"

There's a couple of different memory settings for good reason.

The eclipse memory setting is because Eclipse is a large java program. if you are going to have a huge amount of files open in a couple of projects, then you're going to want to give Eclipse more ram. This is an issue only on "enterprise" systems normally personal projects wont use that many file handles or interfaces.

The JRE setting is how much ram to allow the java runtime when you run your project. This is probably the one you want when you are running some memory hogging application. I've run mathematical projects that needed a few gigs of ram and had to really tell the JRE it was okay, the JVM kept assuming my program was in some leaky runaway state, but I was doing it on purpose, and had to tell JVM specifically what it was allowed to use.

Then Catalina's memory setting is for the application server Tomcat. That server needs memory for each application and concurrent users. This blends with the JRE number because your project might be a web application and I'm not sure which one needs the memory.

Plot a horizontal line using matplotlib

You can use plt.grid to draw a horizontal line.

import numpy as np
from matplotlib import pyplot as plt
from scipy.interpolate import UnivariateSpline
from matplotlib.ticker import LinearLocator

# your data here
annual = np.arange(1,21,1)
l = np.random.random(20)
spl = UnivariateSpline(annual,l)
xs = np.linspace(1,21,200)

# plot your data
plt.plot(xs,spl(xs),'b')

# horizental line?
ax = plt.axes()
# three ticks:
ax.yaxis.set_major_locator(LinearLocator(3))
# plot grids only on y axis on major locations
plt.grid(True, which='major', axis='y')

# show
plt.show()

random data plot example

If statement for strings in python?

Even once you fixed the mis-cased if and improper indentation in your code, it wouldn't work as you probably expected. To check a string against a set of strings, use in. Here's how you'd do it (and note that if is all lowercase and that the code within the if block is indented one level).

One approach:

if answer in ['y', 'Y', 'yes', 'Yes', 'YES']:
    print("this will do the calculation")

Another:

if answer.lower() in ['y', 'yes']:
    print("this will do the calculation")

How do I determine if my python shell is executing in 32bit or 64bit?

Open python console:

import platform
platform.architecture()[0]

it should display the '64bit' or '32bit' according to your platform.

Alternatively( in case of OS X binaries ):

import sys
sys.maxsize > 2**32 
# it should display True in case of 64bit and False in case of 32bit

How to select all and copy in vim?

@swpd's answer improved

I use , as a leader key and ,a shortcut does the trick

Add this line if you prefer ,a shortcut

map <Leader>a :%y+<CR> 

I use Ctrl y shortcut to copy

vmap <C-y> y:call system("xclip -i -selection clipboard", getreg("\""))<CR>:call system("xclip -i", getreg("\""))<CR>

And ,v to paste

nmap <Leader>v :call setreg("\"",system("xclip -o -selection clipboard"))<CR>p

Before using this you have to install xclip

$ sudo apt-get install xclip

Edit: When you use :%y+, it can be only pasted to Vim vim Ctrl+Insert shortcut. And

map <C-a> :%y+<Esc>

is not conflicting any settings in my Vimrc.

Moq, SetupGet, Mocking a property

But while mocking read-only properties means properties with getter method only you should declare it as virtual otherwise System.NotSupportedException will be thrown because it is only supported in VB as moq internally override and create proxy when we mock anything.

Rotating a Div Element in jQuery

yeah you're not going to have much luck i think. Typically across the 3 drawing methods the major browsers use (Canvas, SVG, VML), text support is poor, I believe. If you want to rotate an image, then it's all good, but if you've got mixed content with formatting and styles, probably not.

Check out RaphaelJS for a cross-browser drawing API.

Visual Studio 2017 - Git failed with a fatal error

I'm going to add a solution here that the previous answers have not already mentioned, but this is what fixed it for me.

  1. Navigate to C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\ and delete the Git folder.

  2. Make sure that there is no version of Git installed on your system, remove it by going to Control Panel ? Program and Features (TortoiseGit does not need to be removed from my experience, just native git installations).

  3. Open up the Visual Studio 2017 installer and untick "Git For Windows" in installation options.

  4. Head over to the Git website and install the latest version of Git for Windows.

  5. Go back into the Visual Studio installer and tick "Git for Windows" again. It will not download a new version even though it may look like it is. After that is done, your Git should be fine with VSTS and TF Explorer.

how to send multiple data with $.ajax() jquery

you can use FormData

take look at my snippet from MVC

var fd = new FormData();
fd.append("ProfilePicture", $("#mydropzone")[0].files[0]);// getting value from form feleds 
d.append("id", @(((User) Session["User"]).ID));// getting value from session

$.ajax({
    url: '@Url.Action("ChangeUserPicture", "User")',
    dataType: "json",
    data: fd,//here is your data
    processData: false,
    contentType: false,
    type: 'post',
    success: function(data) {},

SQL LEFT JOIN Subquery Alias

I recognize that the answer works and has been accepted but there is a much cleaner way to write that query. Tested on mysql and postgres.

SELECT wpoi.order_id As No_Commande
FROM  wp_woocommerce_order_items AS wpoi
LEFT JOIN wp_postmeta AS wpp ON wpoi.order_id = wpp.post_id 
                            AND wpp.meta_key = '_shipping_first_name'
WHERE  wpoi.order_id =2198 

MVC 4 client side validation not working

I finally solved this issue by including the necessary scripts directly in my .cshtml file, in this order:

<script src="/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="/Scripts/jquery.validate.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js"></script>

It's a bit off-topic, but I'm continually amazed by how often this sort of thing happens in Web programming, i.e. everything seems to be in place but some obscure tweak turns out to be necessary to get things going. Flimsy, flimsy, flimsy.

How should I copy Strings in Java?

Since strings are immutable, both versions are safe. The latter, however, is less efficient (it creates an extra object and in some cases copies the character data).

With this in mind, the first version should be preferred.

How to change the name of an iOS app?

In new versions of Xcode (Xcode 5 too) to change the name of the project follow this simple (detailed as possible) steps:

Note: In this example I'll change a hypothetical "Sample" name to a "Test" one.

  1. Click twice slowly on the project root in the project navigator and then it becomes editable.

    enter image description here

  2. Rename the project.

    enter image description here

  3. After pressing 'ENTER' the assistant will suggest you to automatically change all project-name-related entries and will allow you to de-select some of them, if you want.

    enter image description here

  4. Press 'RENAME' and Xcode will do the rest. In the meanwhile Xcode may ask you about the option of making a snapshot of the project (it is very recommendable to do so).

  5. In addition to renaming the project, you may want to rename the scheme so that it matches your new project name.

    enter image description here

  6. Repeat similar steps like 1 and 2, and press OK.

    enter image description here enter image description here

  7. That's it.

Another scenario ... The previous explanation was related to changing the project name, but chances are that you only need to change the display name that appears below the app icon in the home screen. These are the steps:

  1. In the "Supporting Files" group locate the info.plist (or related) file

  2. Locate the "Bundle display name" key and change the value to the new name.

    enter image description here

    enter image description here

  3. Delete the "old" app from the simulator or any other testing device.

  4. Clean and Rebuild your app again.

  5. That's it, you will now see the new app name in your home screen.

Recursive Lock (Mutex) vs Non-Recursive Lock (Mutex)

The difference between a recursive and non-recursive mutex has to do with ownership. In the case of a recursive mutex, the kernel has to keep track of the thread who actually obtained the mutex the first time around so that it can detect the difference between recursion vs. a different thread that should block instead. As another answer pointed out, there is a question of the additional overhead of this both in terms of memory to store this context and also the cycles required for maintaining it.

However, there are other considerations at play here too.

Because the recursive mutex has a sense of ownership, the thread that grabs the mutex must be the same thread that releases the mutex. In the case of non-recursive mutexes, there is no sense of ownership and any thread can usually release the mutex no matter which thread originally took the mutex. In many cases, this type of "mutex" is really more of a semaphore action, where you are not necessarily using the mutex as an exclusion device but use it as synchronization or signaling device between two or more threads.

Another property that comes with a sense of ownership in a mutex is the ability to support priority inheritance. Because the kernel can track the thread owning the mutex and also the identity of all the blocker(s), in a priority threaded system it becomes possible to escalate the priority of the thread that currently owns the mutex to the priority of the highest priority thread that is currently blocking on the mutex. This inheritance prevents the problem of priority inversion that can occur in such cases. (Note that not all systems support priority inheritance on such mutexes, but it is another feature that becomes possible via the notion of ownership).

If you refer to classic VxWorks RTOS kernel, they define three mechanisms:

  • mutex - supports recursion, and optionally priority inheritance. This mechanism is commonly used to protect critical sections of data in a coherent manner.
  • binary semaphore - no recursion, no inheritance, simple exclusion, taker and giver does not have to be same thread, broadcast release available. This mechanism can be used to protect critical sections, but is also particularly useful for coherent signalling or synchronization between threads.
  • counting semaphore - no recursion or inheritance, acts as a coherent resource counter from any desired initial count, threads only block where net count against the resource is zero.

Again, this varies somewhat by platform - especially what they call these things, but this should be representative of the concepts and various mechanisms at play.

Reading from text file until EOF repeats last line

Just follow closely the chain of events.

  • Grab 10
  • Grab 20
  • Grab 30
  • Grab EOF

Look at the second-to-last iteration. You grabbed 30, then carried on to check for EOF. You haven't reached EOF because the EOF mark hasn't been read yet ("binarically" speaking, its conceptual location is just after the 30 line). Therefore you carry on to the next iteration. x is still 30 from previous iteration. Now you read from the stream and you get EOF. x remains 30 and the ios::eofbit is raised. You output to stderr x (which is 30, just like in the previous iteration). Next you check for EOF in the loop condition, and this time you're out of the loop.

Try this:

while (true) {
    int x;
    iFile >> x;
    if( iFile.eof() ) break;
    cerr << x << endl;
}

By the way, there is another bug in your code. Did you ever try to run it on an empty file? The behaviour you get is for the exact same reason.

How to align an input tag to the center without specifying the width?

To have text-align:center work you need to add that style to the #siteInfo div or wrap the input in a paragraph and add text-align:center to the paragraph.

What does the following Oracle error mean: invalid column index

If that's a SQLException thrown by Java, it's most likely because you are trying to get or set a value from a ResultSet, but the index you are using isn't within the range.

For example, you might be trying to get the column at index 3 from the result set, but you only have two columns being returned from the SQL query.

How to return 2 values from a Java method?

You don't need to create your own class to return two different values. Just use a HashMap like this:

private HashMap<Toy, GameLevel> getToyAndLevelOfSpatial(Spatial spatial)
{
    Toy toyWithSpatial = firstValue;
    GameLevel levelToyFound = secondValue;

    HashMap<Toy,GameLevel> hm=new HashMap<>();
    hm.put(toyWithSpatial, levelToyFound);
    return hm;
}

private void findStuff()
{
    HashMap<Toy, GameLevel> hm = getToyAndLevelOfSpatial(spatial);
    Toy firstValue = hm.keySet().iterator().next();
    GameLevel secondValue = hm.get(firstValue);
}

You even have the benefit of type safety.

How could I put a border on my grid control in WPF?

I think your problem is that the margin should be specified in the border tag and not in the grid.

How to get value of Radio Buttons?

You can also use a Common Event for your RadioButtons, and you can use the Tag property to pass information to your string or you can use the Text Property if you want your string to hold the same value as the Text of your RadioButton.

Something like this.

private void radioButton_CheckedChanged(object sender, EventArgs e)
{
    if (((RadioButton)sender).Checked == true)
        sex = ((RadioButton)sender).Tag.ToString();
}

Rotating a two-dimensional array in Python

def ruota_orario(matrix):
   ruota=list(zip(*reversed(matrix)))
   return[list(elemento) for elemento in ruota]
def ruota_antiorario(matrix):
   ruota=list(zip(*reversed(matrix)))
   return[list(elemento)[::-1] for elemento in ruota][::-1]

Find empty or NaN entry in Pandas Dataframe

I've resorted to

df[ (df[column_name].notnull()) & (df[column_name]!=u'') ].index

lately. That gets both null and empty-string cells in one go.

Why doesn't Java offer operator overloading?

James Gosling likened designing Java to the following:

"There's this principle about moving, when you move from one apartment to another apartment. An interesting experiment is to pack up your apartment and put everything in boxes, then move into the next apartment and not unpack anything until you need it. So you're making your first meal, and you're pulling something out of a box. Then after a month or so you've used that to pretty much figure out what things in your life you actually need, and then you take the rest of the stuff -- forget how much you like it or how cool it is -- and you just throw it away. It's amazing how that simplifies your life, and you can use that principle in all kinds of design issues: not do things just because they're cool or just because they're interesting."

You can read the context of the quote here

Basically operator overloading is great for a class that models some kind of point, currency or complex number. But after that you start running out of examples fast.

Another factor was the abuse of the feature in C++ by developers overloading operators like '&&', '||', the cast operators and of course 'new'. The complexity resulting from combining this with pass by value and exceptions is well covered in the Exceptional C++ book.

Reverting single file in SVN to a particular revision

The best way is to:

svn merge -c -RevisionToUndo ^/trunk

This will undo all files of the revision than simply revert those file you don't like to undo. Don't forget the dash (-) as prefix for the revision.

svn revert File1 File2

Now commit the changes back.

Practical uses of git reset --soft?

A great reason to use 'git reset --soft <sha1>' is to move HEAD in a bare repo.

If you try to use the --mixed or --hard option, you'll get an error since you're trying to modify and working tree and/or index that does not exist.

Note: You will need to do this directly from the bare repo.

Note Again: You will need to make sure the branch you want to reset in the bare repo is the active branch. If not, follow VonC's answer on how to update the active branch in a bare repo when you have direct access to the repo.

Why is C so fast, and why aren't other languages as fast or faster?

C is not always faster.

C is slower than, for example Modern Fortran.

C is often slower than Java for some things. ( Especially after the JIT compiler has had a go at your code)

C lets pointer aliasing happen, which means some good optimizations are not possible. Particularly when you have multiple execution units, this causes data fetch stalls. Ow.

The assumption that pointer arithmetic works really causes slow bloated performance on some CPU families (PIC particularly!) It used to suck the big one on segmented x86.

Basically, when you get a vector unit, or a parallelizing compiler, C stinks and modern Fortran runs faster.

C programmer tricks like thunking ( modifying the executable on the fly) cause CPU prefetch stalls.

You get the drift ?

And our good friend, the x86, executes an instruction set that these days bears little relationship to the actual CPU architecture. Shadow registers, load-store optimizers, all in the CPU. So C is then close to the virtual metal. The real metal, Intel don't let you see. (Historically VLIW CPU's were a bit of a bust so, maybe that's no so bad.)

If you program in C on a high-performance DSP (maybe a TI DSP ?), the compiler has to do some tricky stuff to unroll the C across the multiple parallel execution units. So in that case C isn't close to the metal, but it is close to the compiler, which will do whole program optimization. Weird.

And finally, some CPUs (www.ajile.com) run Java bytecodes in hardware. C would a PITA to use on that CPU.

What's the valid way to include an image with no src?

I've found that using:

<img src="file://null">

will not make a request and validates correctly.

The browsers will simply block the access to the local file system.

But there might be an error displayed in console log in Chrome for example:

Not allowed to load local resource: file://null/

Typescript react - Could not find a declaration file for module ''react-materialize'. 'path/to/module-name.js' implicitly has an any type

All you need to do is run the below script. Then, remove/re-install the module that you want to use.

npm install --save @types/react-redux