Programs & Examples On #Updatedate

How to combine GROUP BY, ORDER BY and HAVING

Steps for Using Group by,Having By and Order by...

Select Attitude ,count(*) from Person
group by person
HAving PersonAttitude='cool and friendly'
Order by PersonName.

Convert array into csv

My solution requires the array be formatted differently than provided in the question:

<?
    $data = array(
        array( 'row_1_col_1', 'row_1_col_2', 'row_1_col_3' ),
        array( 'row_2_col_1', 'row_2_col_2', 'row_2_col_3' ),
        array( 'row_3_col_1', 'row_3_col_2', 'row_3_col_3' ),
    );
?>

We define our function:

<?
    function outputCSV($data) {
        $outputBuffer = fopen("php://output", 'w');
        foreach($data as $val) {
            fputcsv($outputBuffer, $val);
        }
        fclose($outputBuffer);
    }
?>

Then we output our data as a CSV:

<?
    $filename = "example";

    header("Content-type: text/csv");
    header("Content-Disposition: attachment; filename={$filename}.csv");
    header("Pragma: no-cache");
    header("Expires: 0");

    outputCSV($data);
?>

I have used this with several projects, and it works well. I should note that the outputCSV code is more clever than I am, so I am sure I am not the original author. Unfortunately I have lost track of where I got it, so I can't give the credit to whom it is due.

Detect the Internet connection is offline?

 if(navigator.onLine){
  alert('online');
 } else {
  alert('offline');
 }

Save a file in json format using Notepad++

You can save it as .txt and change it manually using a mouse click and your keyboard. OR, when saving the file:

  • choose All types(*.*) in the Save as type field.
  • type filename.json in File name field

What's the difference between a method and a function?

A function is a mathematical concept. For example:

f(x,y) = sin(x) + cos(y)

says that function f() will return the sin of the first parameter added to the cosine of the second parameter. It's just math. As it happens sin() and cos() are also functions. A function has another property: all calls to a function with the same parameters, should return the same result.

A method, on the other hand, is a function that is related to an object in an object-oriented language. It has one implicit parameter: the object being acted upon (and it's state).

So, if you have an object Z with a method g(x), you might see the following:

Z.g(x) = sin(x) + cos(Z.y)

In this case, the parameter x is passed in, the same as in the function example earlier. However, the parameter to cos() is a value that lives inside the object Z. Z and the data that lives inside it (Z.y) are implicit parameters to Z's g() method.

Multiple commands on a single line in a Windows batch file

Can be achieved also with scriptrunner

ScriptRunner.exe -appvscript demoA.cmd arg1 arg2 -appvscriptrunnerparameters -wait -timeout=30 -rollbackonerror -appvscript demoB.ps1 arg3 arg4 -appvscriptrunnerparameters -wait -timeout=30 

Which also have some features as rollback , timeout and waiting.

Parse XLSX with Node and create json

Improved Version of "Josh Marinacci" answer , it will read beyond Z column (i.e. AA1).

var XLSX = require('xlsx');
var workbook = XLSX.readFile('test.xlsx');
var sheet_name_list = workbook.SheetNames;
sheet_name_list.forEach(function(y) {
    var worksheet = workbook.Sheets[y];
    var headers = {};
    var data = [];
    for(z in worksheet) {
        if(z[0] === '!') continue;
        //parse out the column, row, and value
        var tt = 0;
        for (var i = 0; i < z.length; i++) {
            if (!isNaN(z[i])) {
                tt = i;
                break;
            }
        };
        var col = z.substring(0,tt);
        var row = parseInt(z.substring(tt));
        var value = worksheet[z].v;

        //store header names
        if(row == 1 && value) {
            headers[col] = value;
            continue;
        }

        if(!data[row]) data[row]={};
        data[row][headers[col]] = value;
    }
    //drop those first two rows which are empty
    data.shift();
    data.shift();
    console.log(data);
});

How to use JavaScript with Selenium WebDriver Java

You need to run this command in the top-level directory of a Selenium SVN repository checkout.

HttpContext.Current.User.Identity.Name is Empty

The browser will only detect your username if the IIS server is on the same domain and the security settings within your group policy allow it.

Otherwise you will have to provide it with credentials, but if it is not on the same domain, it will not be able to authenticate you.

Set Focus After Last Character in Text Box

Chris Coyier has a mini jQuery plugin for this which works perfectly well: http://css-tricks.com/snippets/jquery/move-cursor-to-end-of-textarea-or-input/

It uses setSelectionRange if supported, else has a solid fallback.

jQuery.fn.putCursorAtEnd = function() {
  return this.each(function() {
    $(this).focus()
    // If this function exists...
    if (this.setSelectionRange) {
      // ... then use it (Doesn't work in IE)
      // Double the length because Opera is inconsistent about whether a carriage return is one character or two. Sigh.
      var len = $(this).val().length * 2;
      this.setSelectionRange(len, len);
    } else {
      // ... otherwise replace the contents with itself
      // (Doesn't work in Google Chrome)
      $(this).val($(this).val());
    }
    // Scroll to the bottom, in case we're in a tall textarea
    // (Necessary for Firefox and Google Chrome)
    this.scrollTop = 999999;
  });
};

Then you can just do:

input.putCursorAtEnd();

Android Location Providers - GPS or Network Provider?

GPS is generally more accurate than network but sometimes GPS is not available, therefore you might need to switch between the two.

A good start might be to look at the android dev site. They had a section dedicated to determining user location and it has all the code samples you need.

http://developer.android.com/guide/topics/location/obtaining-user-location.html

Why is my JavaScript function sometimes "not defined"?

My guess is, somehow the document is not fully loaded by the time the method is called. Have your code executing after the document is ready event.

Stop setInterval call in JavaScript

Use setTimeOut to stop the interval after some time.

var interVal = setInterval(function(){console.log("Running")  }, 1000);
 setTimeout(function (argument) {
    clearInterval(interVal);
 },10000);

WPF Timer Like C# Timer

you can also use

using System.Timers;
using System.Threading;

how to query child objects in mongodb

Assuming your "states" collection is like:

{"name" : "Spain", "cities" : [ { "name" : "Madrid" }, { "name" : null } ] }
{"name" : "France" }

The query to find states with null cities would be:

db.states.find({"cities.name" : {"$eq" : null, "$exists" : true}});

It is a common mistake to query for nulls as:

db.states.find({"cities.name" : null});

because this query will return all documents lacking the key (in our example it will return Spain and France). So, unless you are sure the key is always present you must check that the key exists as in the first query.

How to "pull" from a local branch into another one?

If you are looking for a brand new pull from another branch like from local to master you can follow this.

git commit -m "Initial Commit"
git add .
git pull --rebase git_url
git push origin master

SQL to find the number of distinct values in a column

select count(distinct(column_name)) AS columndatacount from table_name where somecondition=true

You can use this query, to count different/distinct data. Thanks

Scatter plot with error bars

I put together start to finish code of a hypothetical experiment with ten measurement replicated three times. Just for fun with the help of other stackoverflowers. Thank you... Obviously loops are an option as applycan be used but I like to see what happens.

#Create fake data
x <-rep(1:10, each =3)
y <- rnorm(30, mean=4,sd=1)

#Loop to get standard deviation from data
sd.y = NULL
for(i in 1:10){
  sd.y[i] <- sd(y[(1+(i-1)*3):(3+(i-1)*3)])
}
sd.y<-rep(sd.y,each = 3)

#Loop to get mean from data
mean.y = NULL
for(i in 1:10){
  mean.y[i] <- mean(y[(1+(i-1)*3):(3+(i-1)*3)])
}
mean.y<-rep(mean.y,each = 3)

#Put together the data to view it so far
data <- cbind(x, y, mean.y, sd.y)

#Make an empty matrix to fill with shrunk data
data.1 = matrix(data = NA, nrow=10, ncol = 4)
colnames(data.1) <- c("X","Y","MEAN","SD")

#Loop to put data into shrunk format
for(i in 1:10){
  data.1[i,] <- data[(1+(i-1)*3),]
}

#Create atomic vectors for arrows
x <- data.1[,1]
mean.exp <- data.1[,3]
sd.exp <- data.1[,4]

#Plot the data
plot(x, mean.exp, ylim = range(c(mean.exp-sd.exp,mean.exp+sd.exp)))
abline(h = 4)
arrows(x, mean.exp-sd.exp, x, mean.exp+sd.exp, length=0.05, angle=90, code=3)

Xcode stops working after set "xcode-select -switch"

You should be pointing it towards the Developer directory, not the Xcode application bundle. Run this:

sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer

With recent versions of Xcode, you can go to Xcode ? Preferences… ? Locations and pick one of the options for Command Line Tools to set the location.

S3 Static Website Hosting Route All Paths to Index.html

You can now do this with Lambda@Edge to rewrite the paths

Here is a working lambda@Edge function:

  1. Create a new Lambda function, but use one of the pre-existing Blueprints instead of a blank function.
  2. Search for “cloudfront” and select cloudfront-response-generation from the search results.
  3. After creating the function, replace the content with the below. I also had to change the node runtime to 10.x because cloudfront didn't support node 12 at the time of writing.
'use strict';
exports.handler = (event, context, callback) => {

    // Extract the request from the CloudFront event that is sent to Lambda@Edge 
    var request = event.Records[0].cf.request;

    // Extract the URI from the request
    var olduri = request.uri;

    // Match any '/' that occurs at the end of a URI. Replace it with a default index
    var newuri = olduri.replace(/\/$/, '\/index.html');

    // Log the URI as received by CloudFront and the new URI to be used to fetch from origin
    console.log("Old URI: " + olduri);
    console.log("New URI: " + newuri);

    // Replace the received URI with the URI that includes the index page
    request.uri = newuri;

    return callback(null, request);
};

In your cloudfront behaviors, you'll edit them to add a call to that lambda function on "Viewer Request" enter image description here

Full Tutorial: https://aws.amazon.com/blogs/compute/implementing-default-directory-indexes-in-amazon-s3-backed-amazon-cloudfront-origins-using-lambdaedge/

command/usr/bin/codesign failed with exit code 1- code sign error

I was having the issue after select the deny when it asks for permission

After some search I got it fixed by restarting the system.

Clearing <input type='file' /> using jQuery

Easy: you wrap a <form> around the element, call reset on the form, then remove the form using .unwrap(). Unlike the .clone() solutions otherwise in this thread, you end up with the same element at the end (including custom properties that were set on it).

Tested and working in Opera, Firefox, Safari, Chrome and IE6+. Also works on other types of form elements, with the exception of type="hidden".

_x000D_
_x000D_
window.reset = function(e) {
  e.wrap('<form>').closest('form').get(0).reset();
  e.unwrap();
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form>
  <input id="file" type="file">
  <br>
  <input id="text" type="text" value="Original">
</form>

<button onclick="reset($('#file'))">Reset file</button>
<button onclick="reset($('#text'))">Reset text</button>
_x000D_
_x000D_
_x000D_

JSFiddle

As Timo notes below, if you have the buttons to trigger the reset of the field inside of the <form>, you must call .preventDefault() on the event to prevent the <button> from triggering a submit.


EDIT

Does not work in IE 11 due to an unfixed bug. The text (file name) is cleared on the input, but its File list remains populated.

Convert a python 'type' object to a string

Using str()

 typeOfOneAsString=str(type(1))

How to redirect a URL path in IIS?

Taken from Microsoft Technet.

Redirecting Web Sites in IIS 6.0 (IIS 6.0)


When a browser requests a page or program on your Web site, the Web server locates the page identified by the URL and returns it to the browser. When you move a page on your Web site, you can't always correct all of the links that refer to the old URL of the page. To make sure that browsers can find the page at the new URL, you can instruct the Web server to redirect the browser to the new URL.

You can redirect requests for files in one directory to a different directory, to a different Web site, or to another file in a different directory. When the browser requests the file at the original URL, the Web server instructs the browser to request the page by using the new URL.

Important

You must be a member of the Administrators group on the local computer to perform the following procedure or procedures. As a security best practice, log on to your computer by using an account that is not in the Administrators group, and then use the runas command to run IIS Manager as an administrator. At a command prompt, type runas /user:Administrative_AccountName "mmc %systemroot%\system32\inetsrv\iis.msc".

Procedures

To redirect requests to another Web site or directory


  1. In IIS Manager, expand the local computer, right-click the Web site or directory you want to redirect, and click Properties.

  2. Click the Home Directory, Virtual Directory, or Directory tab.

  3. Under The content for this source should come from, click A redirection to a URL.

  4. In the Redirect to box, type the URL of the destination directory or Web site. For example, to redirect all requests for files in the Catalog directory to the NewCatalog directory, type /NewCatalog.

To redirect all requests to a single file


  1. In IIS Manager, expand the local computer, right-click the Web site or directory you want to redirect, and click Properties.

  2. Click the Home Directory, Virtual Directory, or Directory tab.

  3. Under The content for this source should come from, click A redirection to a URL.

  4. In the Redirect to box, type the URL of the destination file.

  5. Select the The exact URL entered above check box to prevent the Web server from appending the original file name to the destination URL.

    You can use wildcards and redirect variables in the destination URL to precisely control how the original URL is translated into the destination URL.

    You can also use the redirect method to redirect all requests for files in a particular directory to a program. Generally, you should pass any parameters from the original URL to the program, which you can do by using redirect variables.

    To redirect requests to a program


  6. In IIS Manager, expand the local computer, right-click the Web site or directory you want to redirect, and click Properties.

  7. Click the Home Directory, Virtual Directory, or Directory tab.

  8. Under The content for this source should come from, click A redirection to a URL.

    In the Redirect to box, type the URL of the program, including any redirect variables needed to pass parameters to the program. For example, to redirect all requests for scripts in a Scripts directory to a logging program that records the requested URL and any parameters passed with the URL, type /Scripts/Logger.exe?URL=$V+PARAMS=$P. $V and $P are redirect variables.

  9. Select the The exact URL entered above check box to prevent the Web server from appending the original file name to the destination URL.

Nginx location priority

It fires in this order.

  1. = (exactly)

    location = /path

  2. ^~ (forward match)

    location ^~ /path

  3. ~ (regular expression case sensitive)

    location ~ /path/

  4. ~* (regular expression case insensitive)

    location ~* .(jpg|png|bmp)

  5. /

    location /path

How do I tell Spring Boot which main class to use for the executable jar?

If you're using spring-boot-starter-parent in your pom, you simply add the following to your pom:

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

Then do your mvn package.

See this Spring docs page.

A very important aspect here is to mention that the directory structure has to be src/main/java/nameofyourpackage

Best practices for SQL varchar column length

In a sense you're right, although anything lower than 2^8 characters will still register as a byte of data.

If you account for the base character that leaves anything with a VARCHAR < 255 as consuming the same amount of space.

255 is a good baseline definition unless you particularly wish to curtail excessive input.

XSL substring and indexOf

I want to select the text of a string that is located after the occurrence of substring

You could use:

substring-after($string,$match)

If you want a subtring of the above with some length then use:

substring(substring-after($string,$match),1,$length)

But problems begin if there is no ocurrence of the matching substring... So, if you want a substring with specific length located after the occurrence of a substring, or from the whole string if there is no match, you could use:

substring(substring-after($string,substring-before($string,$match)),
          string-length($match) * contains($string,$match) + 1,
          $length) 

catch forEach last iteration

The 2018 ES6+ ANSWER IS:

    const arr = [1, 2, 3];

    arr.forEach((val, key, arr) => {
      if (Object.is(arr.length - 1, key)) {
        // execute last item logic
        console.log(`Last callback call at index ${key} with value ${val}` ); 
      }
    });

Generate random numbers following a normal distribution in C/C++

If you're using C++11, you can use std::normal_distribution:

#include <random>

std::default_random_engine generator;
std::normal_distribution<double> distribution(/*mean=*/0.0, /*stddev=*/1.0);

double randomNumber = distribution(generator);

There are many other distributions you can use to transform the output of the random number engine.

Testing if a checkbox is checked with jQuery

// use ternary operators
$("#ans").is(':checked') ? 1 : 0;

HTML CSS Invisible Button

HTML

<input type="button">

CSS

input[type=button]{
 background:transparent;
 border:0;
}

Lua string to int

here is what you should put

local stringnumber = "10"
local a = tonumber(stringnumber)
print(a + 10)

output:

20

@RequestParam vs @PathVariable

Both the annotations behave exactly in same manner.

Only 2 special characters '!' and '@' are accepted by the annotations @PathVariable and @RequestParam.

To check and confirm the behavior I have created a spring boot application that contains only 1 controller.

 @RestController 
public class Controller 
{
    @GetMapping("/pvar/{pdata}")
    public @ResponseBody String testPathVariable(@PathVariable(name="pdata") String pathdata)
    {
        return pathdata;
    }

    @GetMapping("/rpvar")
    public @ResponseBody String testRequestParam(@RequestParam("param") String paramdata)
    {
        return paramdata;
    }
}

Hitting following Requests I got the same response:

  1. localhost:7000/pvar/!@#$%^&*()_+-=[]{}|;':",./<>?
  2. localhost:7000/rpvar?param=!@#$%^&*()_+-=[]{}|;':",./<>?

!@ was received as response in both the requests

LINQ query to return a Dictionary<string, string>

Look at the ToLookup and/or ToDictionary extension methods.

Python: Is there an equivalent of mid, right, and left from BASIC?

You can use this method also it will act like that

thadari=[1,2,3,4,5,6]

#Front Two(Left)
print(thadari[:2])
[1,2]

#Last Two(Right)# edited
print(thadari[-2:])
[5,6]

#mid
mid = len(thadari) //2

lefthalf = thadari[:mid]
[1,2,3]
righthalf = thadari[mid:]
[4,5,6]

Hope it will help

Programmatically get own phone number in iOS

Using Private API you can get user phone number on the following way:

extern NSString* CTSettingCopyMyPhoneNumber();


+(NSString *) phoneNumber {
NSString *phone = CTSettingCopyMyPhoneNumber();

return phone;
}

Also include CoreTelephony.framework to your project.

Parsing JSON Array within JSON Object

This could be an answer to your question:

JSONArray msg1 = (JSONArray) json.get("source");
for(int i = 0; i < msg1.length(); i++){
  String name = msg1.getString("name");
  int age     = msg1.getInt("age");
}

How to align two elements on the same line without changing HTML

#element1 {float:left;}
#element2 {padding-left : 20px; float:left;}

fiddle : http://jsfiddle.net/sKqZJ/

or

#element1 {float:left;}
#element2 {margin-left : 20px;float:left;}

fiddle : http://jsfiddle.net/sKqZJ/1/

or

#element1 {padding-right : 20px; float:left;}
#element2 {float:left;}

fiddle : http://jsfiddle.net/sKqZJ/2/

or

#element1 {margin-right : 20px; float:left;}
#element2 {float:left;}

fiddle : http://jsfiddle.net/sKqZJ/3/

reference : The Difference Between CSS Margins and Padding

Iterating each character in a string using Python

Even easier:

for c in "test":
    print c

how to set ASPNETCORE_ENVIRONMENT to be considered for publishing an asp.net core application?

This is how we can set it in run-time:

public class Program
{
    public static void Main(string[] args)
    {
        Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "Development");

        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .Build();
}

How to get controls in WPF to fill available space?

There are also some properties you can set to force a control to fill its available space when it would otherwise not do so. For example, you can say:

HorizontalContentAlignment="Stretch"

... to force the contents of a control to stretch horizontally. Or you can say:

HorizontalAlignment="Stretch"

... to force the control itself to stretch horizontally to fill its parent.

Select2 doesn't work when embedded in a bootstrap modal

Ok, I've got it to work.

change

<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    <h3 id="myModalLabel">Panel</h3>
  </div>
  <div class="modal-body" style="max-height: 800px">

to

<div id="myModal" class="modal hide fade" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    <h3 id="myModalLabel">Panel</h3>
  </div>
  <div class="modal-body" style="max-height: 800px">

(remove tabindex="-1" from modal)

builder for HashMap

You can use the fluent API in Eclipse Collections:

Map<String, Integer> map = Maps.mutable.<String, Integer>empty()
        .withKeyValue("a", 1)
        .withKeyValue("b", 2);

Assert.assertEquals(Maps.mutable.with("a", 1, "b", 2), map);

Here's a blog with more detail and examples.

Note: I am a committer for Eclipse Collections.

Know relationships between all the tables of database in SQL Server

This stored procedure will provide you with a hierarchical tree of relationship. Based on this article from Technet. It will also optionally provide you a query for reading or deleting all the related data.

IF OBJECT_ID('GetForeignKeyRelations','P') IS NOT NULL 
    DROP PROC GetForeignKeyRelations 
GO 

CREATE PROC GetForeignKeyRelations 
@Schemaname Sysname = 'dbo' 
,@Tablename Sysname 
,@WhereClause NVARCHAR(2000) = '' 
,@GenerateDeleteScripts bit  = 0  
,@GenerateSelectScripts bit  = 0 

AS 

SET NOCOUNT ON 

DECLARE @fkeytbl TABLE 
( 
ReferencingObjectid        int NULL 
,ReferencingSchemaname  Sysname NULL 
,ReferencingTablename   Sysname NULL  
,ReferencingColumnname  Sysname NULL 
,PrimarykeyObjectid     int  NULL 
,PrimarykeySchemaname   Sysname NULL 
,PrimarykeyTablename    Sysname NULL 
,PrimarykeyColumnname   Sysname NULL 
,Hierarchy              varchar(max) NULL 
,level                  int NULL 
,rnk                    varchar(max) NULL 
,Processed                bit default 0  NULL 
); 



 WITH fkey (ReferencingObjectid,ReferencingSchemaname,ReferencingTablename,ReferencingColumnname 
            ,PrimarykeyObjectid,PrimarykeySchemaname,PrimarykeyTablename,PrimarykeyColumnname,Hierarchy,level,rnk) 
    AS 
    ( 
        SELECT                   
                               soc.object_id 
                              ,scc.name 
                              ,soc.name 
                              ,convert(sysname,null) 
                              ,convert(int,null) 
                              ,convert(sysname,null) 
                              ,convert(sysname,null) 
                              ,convert(sysname,null) 
                              ,CONVERT(VARCHAR(MAX), scc.name + '.' + soc.name  ) as Hierarchy 
                              ,0 as level 
                              ,rnk=convert(varchar(max),soc.object_id) 
        FROM SYS.objects soc 
        JOIN sys.schemas scc 
          ON soc.schema_id = scc.schema_id 
       WHERE scc.name =@Schemaname 
         AND soc.name =@Tablename 
      UNION ALL 
      SELECT                   sop.object_id 
                              ,scp.name 
                              ,sop.name 
                              ,socp.name 
                              ,soc.object_id 
                              ,scc.name 
                              ,soc.name 
                              ,socc.name 
                              ,CONVERT(VARCHAR(MAX), f.Hierarchy + ' --> ' + scp.name + '.' + sop.name ) as Hierarchy 
                              ,f.level+1 as level 
                              ,rnk=f.rnk + '-' + convert(varchar(max),sop.object_id) 
        FROM SYS.foreign_key_columns sfc 
        JOIN Sys.Objects sop 
          ON sfc.parent_object_id = sop.object_id 
        JOIN SYS.columns socp 
          ON socp.object_id = sop.object_id 
         AND socp.column_id = sfc.parent_column_id 
        JOIN sys.schemas scp 
          ON sop.schema_id = scp.schema_id 
        JOIN SYS.objects soc 
          ON sfc.referenced_object_id = soc.object_id 
        JOIN SYS.columns socc 
          ON socc.object_id = soc.object_id 
         AND socc.column_id = sfc.referenced_column_id 
        JOIN sys.schemas scc 
          ON soc.schema_id = scc.schema_id 
        JOIN fkey f 
          ON f.ReferencingObjectid = sfc.referenced_object_id 
        WHERE ISNULL(f.PrimarykeyObjectid,0) <> f.ReferencingObjectid 
      ) 

     INSERT INTO @fkeytbl 
     (ReferencingObjectid,ReferencingSchemaname,ReferencingTablename,ReferencingColumnname 
            ,PrimarykeyObjectid,PrimarykeySchemaname,PrimarykeyTablename,PrimarykeyColumnname,Hierarchy,level,rnk) 
     SELECT ReferencingObjectid,ReferencingSchemaname,ReferencingTablename,ReferencingColumnname 
            ,PrimarykeyObjectid,PrimarykeySchemaname,PrimarykeyTablename,PrimarykeyColumnname,Hierarchy,level,rnk 
       FROM fkey 

        SELECT F.Relationshiptree 
         FROM 
        ( 
        SELECT DISTINCT Replicate('------',Level) + CASE LEVEL WHEN 0 THEN '' ELSE '>' END +  ReferencingSchemaname + '.' + ReferencingTablename 'Relationshiptree' 
               ,RNK 
          FROM @fkeytbl 
          ) F 
        ORDER BY F.rnk ASC 

------------------------------------------------------------------------------------------------------------------------------- 
-- Generate the Delete / Select script 
------------------------------------------------------------------------------------------------------------------------------- 

    DECLARE @Sql VARCHAR(MAX) 
    DECLARE @RnkSql VARCHAR(MAX) 

    DECLARE @Jointables TABLE 
    ( 
    ID INT IDENTITY 
    ,Object_id int 
    ) 

    DECLARE @ProcessTablename SYSNAME 
    DECLARE @ProcessSchemaName SYSNAME 

    DECLARE @JoinConditionSQL VARCHAR(MAX) 
    DECLARE @Rnk VARCHAR(MAX) 
    DECLARE @OldTablename SYSNAME 

    IF @GenerateDeleteScripts = 1 or @GenerateSelectScripts = 1  
    BEGIN 

          WHILE EXISTS ( SELECT 1 
                           FROM @fkeytbl 
                          WHERE Processed = 0 
                            AND level > 0 ) 
          BEGIN 

            SELECT @ProcessTablename = '' 
            SELECT @Sql                 = '' 
            SELECT @JoinConditionSQL = '' 
            SELECT @OldTablename     = '' 


            SELECT TOP 1 @ProcessTablename = ReferencingTablename 
                  ,@ProcessSchemaName  = ReferencingSchemaname 
                  ,@Rnk = RNK  
              FROM @fkeytbl 
             WHERE Processed = 0 
              AND level > 0  
             ORDER BY level DESC 


            SELECT @RnkSql ='SELECT ' + REPLACE (@rnk,'-',' UNION ALL SELECT ')  

            DELETE FROM @Jointables 

            INSERT INTO @Jointables 
            EXEC(@RnkSql) 

            IF @GenerateDeleteScripts = 1 
                SELECT @Sql = 'DELETE [' + @ProcessSchemaName + '].[' + @ProcessTablename + ']' + CHAR(10) + ' FROM [' + @ProcessSchemaName + '].[' + @ProcessTablename + ']' + CHAR(10) 

            IF @GenerateSelectScripts = 1 
                SELECT @Sql = 'SELECT  [' + @ProcessSchemaName + '].[' + @ProcessTablename + '].*' + CHAR(10) + ' FROM [' + @ProcessSchemaName + '].[' + @ProcessTablename + ']' + CHAR(10) 

            SELECT @JoinConditionSQL = @JoinConditionSQL  
                                           + CASE  
                                             WHEN @OldTablename <> f.PrimarykeyTablename THEN  'JOIN ['  + f.PrimarykeySchemaname  + '].[' + f.PrimarykeyTablename + '] ' + CHAR(10) + ' ON ' 
                                             ELSE ' AND '  
                                             END 
                                           + ' ['  + f.PrimarykeySchemaname  + '].[' + f.PrimarykeyTablename + '].[' + f.PrimarykeyColumnname + '] =  ['  + f.ReferencingSchemaname  + '].[' + f.ReferencingTablename + '].[' + f.ReferencingColumnname + ']' + CHAR(10)  
                     , @OldTablename = CASE  
                                         WHEN @OldTablename <> f.PrimarykeyTablename THEN  f.PrimarykeyTablename 
                                         ELSE @OldTablename 
                                         END 

                  FROM @fkeytbl f 
                  JOIN @Jointables j 
                    ON f.Referencingobjectid  = j.Object_id 
                 WHERE charindex(f.rnk + '-',@Rnk + '-') <> 0 
                   AND F.level > 0 
                 ORDER BY J.ID DESC 

            SELECT @Sql = @Sql +  @JoinConditionSQL 

            IF LTRIM(RTRIM(@WhereClause)) <> ''  
                SELECT @Sql = @Sql + ' WHERE (' + @WhereClause + ')' 

            PRINT @SQL 
            PRINT CHAR(10) 

            UPDATE @fkeytbl 
               SET Processed = 1 
             WHERE ReferencingTablename = @ProcessTablename 
               AND rnk = @Rnk 

          END 

          IF @GenerateDeleteScripts = 1 
            SELECT @Sql = 'DELETE FROM [' + @Schemaname + '].[' + @Tablename + ']' 

          IF @GenerateSelectScripts = 1 
            SELECT @Sql = 'SELECT * FROM [' + @Schemaname + '].[' + @Tablename + ']' 

          IF LTRIM(RTRIM(@WhereClause)) <> ''  
                SELECT @Sql = @Sql  + ' WHERE ' + @WhereClause 

         PRINT @SQL 
     END 

SET NOCOUNT OFF 


go 

PHP shorthand for isset()?

PHP 7.4+; with the null coalescing assignment operator

$var ??= '';

PHP 7.0+; with the null coalescing operator

$var = $var ?? '';

PHP 5.3+; with the ternary operator shorthand

isset($var) ?: $var = '';

Or for all/older versions with isset:

$var = isset($var) ? $var : '';

or

!isset($var) && $var = '';

Limit the height of a responsive image with css

The trick is to add both max-height: 100%; and max-width: 100%; to .container img. Example CSS:

.container {
  width: 300px;
  border: dashed blue 1px;
}

.container img {
  max-height: 100%;
  max-width: 100%;
}

In this way, you can vary the specified width of .container in whatever way you want (200px or 10% for example), and the image will be no larger than its natural dimensions. (You could specify pixels instead of 100% if you didn't want to rely on the natural size of the image.)

Here's the whole fiddle: http://jsfiddle.net/KatieK/Su28P/1/

Can't change table design in SQL Server 2008

The answer is on the MSDN site:

The Save (Not Permitted) dialog box warns you that saving changes is not permitted because the changes you have made require the listed tables to be dropped and re-created.

The following actions might require a table to be re-created:

  • Adding a new column to the middle of the table
  • Dropping a column
  • Changing column nullability
  • Changing the order of the columns
  • Changing the data type of a column

EDIT 1:

Additional useful informations from here:

To change the Prevent saving changes that require the table re-creation option, follow these steps:

  1. Open SQL Server Management Studio (SSMS).
  2. On the Tools menu, click Options.
  3. In the navigation pane of the Options window, click Designers.
  4. Select or clear the Prevent saving changes that require the table re-creation check box, and then click OK.

Note If you disable this option, you are not warned when you save the table that the changes that you made have changed the metadata structure of the table. In this case, data loss may occur when you save the table.

Risk of turning off the "Prevent saving changes that require table re-creation" option

Although turning off this option can help you avoid re-creating a table, it can also lead to changes being lost. For example, suppose that you enable the Change Tracking feature in SQL Server 2008 to track changes to the table. When you perform an operation that causes the table to be re-created, you receive the error message that is mentioned in the "Symptoms" section. However, if you turn off this option, the existing change tracking information is deleted when the table is re-created. Therefore, we recommend that you do not work around this problem by turning off the option.

Settings, screen shot

CSS fixed width in a span

In an ideal world you'd achieve this simply using the following css

<style type="text/css">

span {
  display: inline-block;
  width: 50px;
}

</style>

This works on all browsers apart from FF2 and below.

Firefox 2 and lower don't support this value. You can use -moz-inline-box, but be aware that it's not the same as inline-block, and it may not work as you expect in some situations.

Quote taken from quirksmode

How to do a SOAP wsdl web services call from the command line

For Windows users looking for a PowerShell alternative, here it is (using POST). I've split it up onto multiple lines for readability.

$url = 'https://sandbox.mediamind.com/Eyeblaster.MediaMind.API/V2/AuthenticationService.svc'
$headers = @{
    'Content-Type' = 'text/xml';
    'SOAPAction' = 'http://api.eyeblaster.com/IAuthenticationService/ClientLogin'
}
$envelope = @'
    <Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/">
        <Body>
            <yourEnvelopeContentsHere/>
        </Body>
    </Envelope>
'@     # <--- This line must not be indented

Invoke-WebRequest -Uri $url -Headers $headers -Method POST -Body $envelope

How to use linux command line ftp with a @ sign in my username?

A more complete answer would be it is not possible with ftp(at least the ftp program installed on centos 6).

Since you wanted an un-attended process, "pts"'s answer will work fine.

Do the unattended upload with curl instead of ftp:

curl -u user:password -T file ftp://server/dir/file

%40 doesn't appear to work.

[~]# ftp domain.com
ftp: connect: Connection refused
ftp> quit
[~]# ftp some_user%[email protected]
ftp: some_user%[email protected]: Name or service not known
ftp> quit

All I've got is to open the ftp program and use the domain and enter the user when asked. Usually, a password is required anyway, so the interactive nature probably isn't problematic.

[~]# ftp domain.com
Connected to domain.com (173.254.13.235).
220---------- Welcome to Pure-FTPd [privsep] [TLS] ----------
220-You are user number 2 of 1000 allowed.
220-Local time is now 02:47. Server port: 21.
220-This is a private system - No anonymous login
220-IPv6 connections are also welcome on this server.
220 You will be disconnected after 15 minutes of inactivity.
Name (domain.com:user): [email protected]
331 User [email protected] OK. Password required
Password:
230 OK. Current restricted directory is /
Remote system type is UNIX.
Using binary mode to transfer files.

Set equal width of columns in table layout in Android

Change android:stretchColumns value to *.

Value 0 means stretch the first column. Value 1 means stretch the second column and so on.

Value * means stretch all the columns.

How to plot a function curve in R

plot has a plot.function method

plot(eq, 1, 1000)

Or

curve(eq, 1, 1000)

How to change column width in DataGridView?

Set the "AutoSizeColumnsMode" property to "Fill".. By default it is set to 'NONE'. Now columns will be filled across the DatagridView. Then you can set the width of other columns accordingly.

DataGridView1.Columns[0].Width=100;// The id column 
DataGridView1.Columns[1].Width=200;// The abbrevation columln
//Third Colulmns 'description' will automatically be resized to fill the remaining 
//space

How to define two fields "unique" as couple

There is a simple solution for you called unique_together which does exactly what you want.

For example:

class MyModel(models.Model):
  field1 = models.CharField(max_length=50)
  field2 = models.CharField(max_length=50)

  class Meta:
    unique_together = ('field1', 'field2',)

And in your case:

class Volume(models.Model):
  id = models.AutoField(primary_key=True)
  journal_id = models.ForeignKey(Journals, db_column='jid', null=True, verbose_name = "Journal")
  volume_number = models.CharField('Volume Number', max_length=100)
  comments = models.TextField('Comments', max_length=4000, blank=True)

  class Meta:
    unique_together = ('journal_id', 'volume_number',)

Fade In on Scroll Down, Fade Out on Scroll Up - based on element position in window

The reason your attempt wasn't working, is because the two animations (fade-in and fade-out) were working against each other.

Right before an object became visible, it was still invisible and so the animation for fading-out would run. Then, the fraction of a second later when that same object had become visible, the fade-in animation would try to run, but the fade-out was still running. So they would work against each other and you would see nothing.

Eventually the object would become visible (most of the time), but it would take a while. And if you would scroll down by using the arrow-button at the button of the scrollbar, the animation would sort of work, because you would scroll using bigger increments, creating less scroll-events.


Enough explanation, the solution (JS, CSS, HTML):

_x000D_
_x000D_
$(window).on("load",function() {_x000D_
  $(window).scroll(function() {_x000D_
    var windowBottom = $(this).scrollTop() + $(this).innerHeight();_x000D_
    $(".fade").each(function() {_x000D_
      /* Check the location of each desired element */_x000D_
      var objectBottom = $(this).offset().top + $(this).outerHeight();_x000D_
      _x000D_
      /* If the element is completely within bounds of the window, fade it in */_x000D_
      if (objectBottom < windowBottom) { //object comes into view (scrolling down)_x000D_
        if ($(this).css("opacity")==0) {$(this).fadeTo(500,1);}_x000D_
      } else { //object goes out of view (scrolling up)_x000D_
        if ($(this).css("opacity")==1) {$(this).fadeTo(500,0);}_x000D_
      }_x000D_
    });_x000D_
  }).scroll(); //invoke scroll-handler on page-load_x000D_
});
_x000D_
.fade {_x000D_
  margin: 50px;_x000D_
  padding: 50px;_x000D_
  background-color: lightgreen;_x000D_
  opacity: 1;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>_x000D_
_x000D_
<div>_x000D_
  <div class="fade">Fade In 01</div>_x000D_
  <div class="fade">Fade In 02</div>_x000D_
  <div class="fade">Fade In 03</div>_x000D_
  <div class="fade">Fade In 04</div>_x000D_
  <div class="fade">Fade In 05</div>_x000D_
  <div class="fade">Fade In 06</div>_x000D_
  <div class="fade">Fade In 07</div>_x000D_
  <div class="fade">Fade In 08</div>_x000D_
  <div class="fade">Fade In 09</div>_x000D_
  <div class="fade">Fade In 10</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_ (fiddle: http://jsfiddle.net/eLwex993/2/)

  • I wrapped the fade-codeline in an if-clause: if ($(this).css("opacity")==0) {...}. This makes sure the object is only faded in when the opacity is 0. Same goes for fading out. And this prevents the fade-in and fade-out from working against each other, because now there's ever only one of the two running at one time on an object.
  • I changed .animate() to .fadeTo(). It's jQuery's specialized function for opacity, a lot shorter to write and probably lighter than animate.
  • I changed .position() to .offset(). This always calculates relative to the body, whereas position is relative to the parent. For your case I believe offset is the way to go.
  • I changed $(window).height() to $(window).innerHeight(). The latter is more reliable in my experience.
  • Directly after the scroll-handler, I invoke that handler once on page-load with $(window).scroll();. Now you can give all desired objects on the page the .fade class, and objects that should be invisible at page-load, will be faded out immediately.
  • I removed #container from both HTML and CSS, because (at least for this answer) it isn't necessary. (I thought maybe you needed the height:2000px because you used .position() instead of .offset(), otherwise I don't know. Feel free of course to leave it in your code.)

UPDATE

If you want opacity values other than 0 and 1, use the following code:

_x000D_
_x000D_
$(window).on("load",function() {_x000D_
  function fade(pageLoad) {_x000D_
    var windowBottom = $(window).scrollTop() + $(window).innerHeight();_x000D_
    var min = 0.3;_x000D_
    var max = 0.7;_x000D_
    var threshold = 0.01;_x000D_
    _x000D_
    $(".fade").each(function() {_x000D_
      /* Check the location of each desired element */_x000D_
      var objectBottom = $(this).offset().top + $(this).outerHeight();_x000D_
      _x000D_
      /* If the element is completely within bounds of the window, fade it in */_x000D_
      if (objectBottom < windowBottom) { //object comes into view (scrolling down)_x000D_
        if ($(this).css("opacity")<=min+threshold || pageLoad) {$(this).fadeTo(500,max);}_x000D_
      } else { //object goes out of view (scrolling up)_x000D_
        if ($(this).css("opacity")>=max-threshold || pageLoad) {$(this).fadeTo(500,min);}_x000D_
      }_x000D_
    });_x000D_
  } fade(true); //fade elements on page-load_x000D_
  $(window).scroll(function(){fade(false);}); //fade elements on scroll_x000D_
});
_x000D_
.fade {_x000D_
  margin: 50px;_x000D_
  padding: 50px;_x000D_
  background-color: lightgreen;_x000D_
  opacity: 1;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>_x000D_
_x000D_
<div>_x000D_
  <div class="fade">Fade In 01</div>_x000D_
  <div class="fade">Fade In 02</div>_x000D_
  <div class="fade">Fade In 03</div>_x000D_
  <div class="fade">Fade In 04</div>_x000D_
  <div class="fade">Fade In 05</div>_x000D_
  <div class="fade">Fade In 06</div>_x000D_
  <div class="fade">Fade In 07</div>_x000D_
  <div class="fade">Fade In 08</div>_x000D_
  <div class="fade">Fade In 09</div>_x000D_
  <div class="fade">Fade In 10</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_ (fiddle: http://jsfiddle.net/eLwex993/3/)

  • I added a threshold to the if-clause, see explanation below.
  • I created variables for the threshold and for min/max at the start of the function. In the rest of the function these variables are referenced. This way, if you ever want to change the values again, you only have to do it in one place.
  • I also added || pageLoad to the if-clause. This was necessary to make sure all objects are faded to the correct opacity on page-load. pageLoad is a boolean that is send along as an argument when fade() is invoked.
    I had to put the fade-code inside the extra function fade() {...}, in order to be able to send along the pageLoad boolean when the scroll-handler is invoked.
    I did't see any other way to do this, if anyone else does, please leave a comment.

Explanation:
The reason the code in your fiddle didn't work, is because the actual opacity values are always a little off from the value you set it to. So if you set the opacity to 0.3, the actual value (in this case) is 0.300000011920929. That's just one of those little bugs you have to learn along the way by trail and error. That's why this if-clause won't work: if ($(this).css("opacity") == 0.3) {...}.

I added a threshold, to take that difference into account: == 0.3 becomes <= 0.31.
(I've set the threshold to 0.01, this can be changed of course, just as long as the actual opacity will fall between the set value and this threshold.)

The operators are now changed from == to <= and >=.


UPDATE 2:

If you want to fade the elements based on their visible percentage, use the following code:

_x000D_
_x000D_
$(window).on("load",function() {_x000D_
  function fade(pageLoad) {_x000D_
    var windowTop=$(window).scrollTop(), windowBottom=windowTop+$(window).innerHeight();_x000D_
    var min=0.3, max=0.7, threshold=0.01;_x000D_
    _x000D_
    $(".fade").each(function() {_x000D_
      /* Check the location of each desired element */_x000D_
      var objectHeight=$(this).outerHeight(), objectTop=$(this).offset().top, objectBottom=$(this).offset().top+objectHeight;_x000D_
      _x000D_
      /* Fade element in/out based on its visible percentage */_x000D_
      if (objectTop < windowTop) {_x000D_
        if (objectBottom > windowTop) {$(this).fadeTo(0,min+((max-min)*((objectBottom-windowTop)/objectHeight)));}_x000D_
        else if ($(this).css("opacity")>=min+threshold || pageLoad) {$(this).fadeTo(0,min);}_x000D_
      } else if (objectBottom > windowBottom) {_x000D_
        if (objectTop < windowBottom) {$(this).fadeTo(0,min+((max-min)*((windowBottom-objectTop)/objectHeight)));}_x000D_
        else if ($(this).css("opacity")>=min+threshold || pageLoad) {$(this).fadeTo(0,min);}_x000D_
      } else if ($(this).css("opacity")<=max-threshold || pageLoad) {$(this).fadeTo(0,max);}_x000D_
    });_x000D_
  } fade(true); //fade elements on page-load_x000D_
  $(window).scroll(function(){fade(false);}); //fade elements on scroll_x000D_
});
_x000D_
.fade {_x000D_
  margin: 50px;_x000D_
  padding: 50px;_x000D_
  background-color: lightgreen;_x000D_
  opacity: 1;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>_x000D_
_x000D_
<div>_x000D_
  <div class="fade">Fade In 01</div>_x000D_
  <div class="fade">Fade In 02</div>_x000D_
  <div class="fade">Fade In 03</div>_x000D_
  <div class="fade">Fade In 04</div>_x000D_
  <div class="fade">Fade In 05</div>_x000D_
  <div class="fade">Fade In 06</div>_x000D_
  <div class="fade">Fade In 07</div>_x000D_
  <div class="fade">Fade In 08</div>_x000D_
  <div class="fade">Fade In 09</div>_x000D_
  <div class="fade">Fade In 10</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_ (fiddle: http://jsfiddle.net/eLwex993/5/)

What is the difference between display: inline and display: inline-block?

splattne's answer probably covered most of everything so I won't repeat the same thing, but: inline and inline-block behave differently with the direction CSS property.

Within the next snippet you see one two (in order) is rendered, like it does in LTR layouts. I suspect the browser here auto-detected the English part as LTR text and rendered it from left to right.

_x000D_
_x000D_
body {_x000D_
  text-align: right;_x000D_
  direction: rtl;_x000D_
}_x000D_
_x000D_
h2 {_x000D_
  display: block; /* just being explicit */_x000D_
}_x000D_
_x000D_
span {_x000D_
  display: inline;_x000D_
}
_x000D_
<h2>_x000D_
  ??? ????? ????_x000D_
  <span>one</span>_x000D_
  <span>two</span>_x000D_
</h2>
_x000D_
_x000D_
_x000D_

However, if I go ahead and set display to inline-block, the browser appears to respect the direction property and render the elements from right to left in order, so that two one is rendered.

_x000D_
_x000D_
body {_x000D_
  text-align: right;_x000D_
  direction: rtl;_x000D_
}_x000D_
_x000D_
h2 {_x000D_
  display: block; /* just being explicit */_x000D_
}_x000D_
_x000D_
span {_x000D_
  display: inline-block;_x000D_
}
_x000D_
<h2>_x000D_
  ??? ????? ????_x000D_
  <span>one</span>_x000D_
  <span>two</span>_x000D_
</h2>
_x000D_
_x000D_
_x000D_

I don't know if there are any other quirks to this, I only found about this empirically on Chrome.

Select All as default value for Multivalue parameter

Using dataset with default values is one way, but you must use query for Available values and for Default Values, if values are hard coded in Available values tab, then you must define default values as expressions. Pictures should explain everything

Create Parameter (if not automaticly created)

Create Parameter

Define values - wrong way example

Define values - wrong way

Define values - correct way example

Define values - correct way

Set default values - you must define all default values reflecting available values to make "Select All" by default, if you won't define all only those defined will be selected by default.

Set default values

The Result

The result

One picture for Data type: Int

One picture for Data type Int

Quick easy way to migrate SQLite3 to MySQL?

I've just gone through this process, and there's a lot of very good help and information in this Q/A, but I found I had to pull together various elements (plus some from other Q/As) to get a working solution in order to successfully migrate.

However, even after combining the existing answers, I found that the Python script did not fully work for me as it did not work where there were multiple boolean occurrences in an INSERT. See here why that was the case.

So, I thought I'd post up my merged answer here. Credit goes to those that have contributed elsewhere, of course. But I wanted to give something back, and save others time that follow.

I'll post the script below. But firstly, here's the instructions for a conversion...

I ran the script on OS X 10.7.5 Lion. Python worked out of the box.

To generate the MySQL input file from your existing SQLite3 database, run the script on your own files as follows,

Snips$ sqlite3 original_database.sqlite3 .dump | python ~/scripts/dump_for_mysql.py > dumped_data.sql

I then copied the resulting dumped_sql.sql file over to a Linux box running Ubuntu 10.04.4 LTS where my MySQL database was to reside.

Another issue I had when importing the MySQL file was that some unicode UTF-8 characters (specifically single quotes) were not being imported correctly, so I had to add a switch to the command to specify UTF-8.

The resulting command to input the data into a spanking new empty MySQL database is as follows:

Snips$ mysql -p -u root -h 127.0.0.1 test_import --default-character-set=utf8 < dumped_data.sql

Let it cook, and that should be it! Don't forget to scrutinise your data, before and after.

So, as the OP requested, it's quick and easy, when you know how! :-)

As an aside, one thing I wasn't sure about before I looked into this migration, was whether created_at and updated_at field values would be preserved - the good news for me is that they are, so I could migrate my existing production data.

Good luck!

UPDATE

Since making this switch, I've noticed a problem that I hadn't noticed before. In my Rails application, my text fields are defined as 'string', and this carries through to the database schema. The process outlined here results in these being defined as VARCHAR(255) in the MySQL database. This places a 255 character limit on these field sizes - and anything beyond this was silently truncated during the import. To support text length greater than 255, the MySQL schema would need to use 'TEXT' rather than VARCHAR(255), I believe. The process defined here does not include this conversion.


Here's the merged and revised Python script that worked for my data:

#!/usr/bin/env python

import re
import fileinput

def this_line_is_useless(line):
    useless_es = [
        'BEGIN TRANSACTION',
        'COMMIT',
        'sqlite_sequence',
        'CREATE UNIQUE INDEX',        
        'PRAGMA foreign_keys=OFF'
        ]
    for useless in useless_es:
        if re.search(useless, line):
            return True

def has_primary_key(line):
    return bool(re.search(r'PRIMARY KEY', line))

searching_for_end = False
for line in fileinput.input():
    if this_line_is_useless(line): continue

    # this line was necessary because ''); was getting
    # converted (inappropriately) to \');
    if re.match(r".*, ''\);", line):
        line = re.sub(r"''\);", r'``);', line)

    if re.match(r'^CREATE TABLE.*', line):
        searching_for_end = True

    m = re.search('CREATE TABLE "?([A-Za-z_]*)"?(.*)', line)
    if m:
        name, sub = m.groups()
        line = "DROP TABLE IF EXISTS %(name)s;\nCREATE TABLE IF NOT EXISTS `%(name)s`%(sub)s\n"
        line = line % dict(name=name, sub=sub)
        line = line.replace('AUTOINCREMENT','AUTO_INCREMENT')
        line = line.replace('UNIQUE','')
        line = line.replace('"','')
    else:
        m = re.search('INSERT INTO "([A-Za-z_]*)"(.*)', line)
        if m:
            line = 'INSERT INTO %s%s\n' % m.groups()
            line = line.replace('"', r'\"')
            line = line.replace('"', "'")
            line = re.sub(r"(?<!')'t'(?=.)", r"1", line)
            line = re.sub(r"(?<!')'f'(?=.)", r"0", line)

    # Add auto_increment if it's not there since sqlite auto_increments ALL
    # primary keys
    if searching_for_end:
        if re.search(r"integer(?:\s+\w+)*\s*PRIMARY KEY(?:\s+\w+)*\s*,", line):
            line = line.replace("PRIMARY KEY", "PRIMARY KEY AUTO_INCREMENT")
        # replace " and ' with ` because mysql doesn't like quotes in CREATE commands

    # And now we convert it back (see above)
    if re.match(r".*, ``\);", line):
        line = re.sub(r'``\);', r"'');", line)

    if searching_for_end and re.match(r'.*\);', line):
        searching_for_end = False

    if re.match(r"CREATE INDEX", line):
        line = re.sub('"', '`', line)

    print line,

HTML CSS How to stop a table cell from expanding

Simply set the max-width attribute to 280px like this:

<td align="left" valign="top" style="overflow:hidden;" nowrap="nowrap" max-width="280px" width="280px">

This will solve your problem.

How to convert numbers between hexadecimal and decimal

Hex to Decimal Conversion

Convert.ToInt32(number, 16);

Decimal to Hex Conversion

int.Parse(number, System.Globalization.NumberStyles.HexNumber)

For more details Check this article

In ASP.NET MVC: All possible ways to call Controller Action Method from a Razor View

Method 1 : Using jQuery Ajax Get call (partial page update).

Suitable for when you need to retrieve jSon data from database.

Controller's Action Method

[HttpGet]
public ActionResult Foo(string id)
{
    var person = Something.GetPersonByID(id);
    return Json(person, JsonRequestBehavior.AllowGet);
}

Jquery GET

function getPerson(id) {
    $.ajax({
        url: '@Url.Action("Foo", "SomeController")',
        type: 'GET',
        dataType: 'json',
        // we set cache: false because GET requests are often cached by browsers
        // IE is particularly aggressive in that respect
        cache: false,
        data: { id: id },
        success: function(person) {
            $('#FirstName').val(person.FirstName);
            $('#LastName').val(person.LastName);
        }
    });
}

Person class

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Method 2 : Using jQuery Ajax Post call (partial page update).

Suitable for when you need to do partial page post data into database.

Post method is also same like above just replace [HttpPost] on Action method and type as post for jquery method.

For more information check Posting JSON Data to MVC Controllers Here

Method 3 : As a Form post scenario (full page update).

Suitable for when you need to save or update data into database.

View

@using (Html.BeginForm("SaveData","ControllerName", FormMethod.Post))
{        
    @Html.TextBoxFor(model => m.Text)
    
    <input type="submit" value="Save" />
}

Action Method

[HttpPost]
public ActionResult SaveData(FormCollection form)
    {
        // Get movie to update
        return View();
   }

Method 4 : As a Form Get scenario (full page update).

Suitable for when you need to Get data from database

Get method also same like above just replace [HttpGet] on Action method and FormMethod.Get for View's form method.

I hope this will help to you.

MySQL INNER JOIN select only one row from second table

@John Woo's answer helped me solve a similar problem. I've improved upon his answer by setting the correct ordering as well. This has worked for me:

SELECT  a.*, c.*
FROM users a 
    INNER JOIN payments c
        ON a.id = c.user_ID
    INNER JOIN (
        SELECT user_ID, MAX(date) as maxDate FROM
        (
            SELECT user_ID, date
            FROM payments
            ORDER BY date DESC
        ) d
        GROUP BY user_ID
    ) b ON c.user_ID = b.user_ID AND
           c.date = b.maxDate
WHERE a.package = 1

I'm not sure how efficient this is, though.

Merging arrays with the same keys

Two entries in an array can't share a key, you'll need to change the key for the duplicate

Clearfix with twitter bootstrap

clearfix should contain the floating elements but in your html you have added clearfix only after floating right that is your pull-right so you should do like this:

<div class="clearfix">
  <div id="sidebar">
    <ul>
      <li>A</li>
      <li>A</li>
      <li>C</li>
      <li>D</li>
      <li>E</li>
      <li>F</li>
      <li>...</li>
      <li>Z</li>
    </ul>
  </div>
  <div id="main">
    <div>
      <div class="pull-right">
        <a>RIGHT</a>
      </div>
    </div>
  <div>MOVED BELOW Z</div>
</div>

see this demo


Happy to know you solved the problem by setting overflow properties. However this is also good idea to clear the float. Where you have floated your elements you could add overflow: hidden; as you have done in your main.

Convert row names into first column

Alternatively, you can create a new dataframe (or overwrite the current one, as the example below) so you do not need to use of any external package. However this way may not be efficient with huge dataframes.

df <- data.frame(names = row.names(df), df)

How to display a content in two-column layout in LaTeX?

You can import a csv file to this website(https://www.tablesgenerator.com/latex_tables) and click copy to clipboard.

Scroll event listener javascript

Is there a js listener for when a user scrolls in a certain textbox that can be used?

DOM L3 UI Events spec gave the initial definition but is considered obsolete.

To add a single handler you can do:

  let isTicking;
  const debounce = (callback, evt) => {
    if (isTicking) return;
    requestAnimationFrame(() => {
      callback(evt);
      isTicking = false;
    });
    isTicking = true;
  };
  const handleScroll = evt => console.log(evt, window.scrollX, window.scrollY);
  document.defaultView.onscroll = evt => debounce(handleScroll, evt);

For multiple handlers or, if preferable for style reasons, you may use addEventListener as opposed to assigning your handler to onscroll as shown above.

If using something like _.debounce from lodash you could probably get away with:

const handleScroll = evt => console.log(evt, window.scrollX, window.scrollY);
document.defaultView.onscroll = evt => _.debounce(() => handleScroll(evt));

Review browser compatibility and be sure to test on some actual devices before calling it done.

How to put a symbol above another in LaTeX?

Use \overset{above}{main} in math mode. In your case, \overset{a}{\#}.

How to edit my Excel dropdown list?

Attribute_Brands is a named range that should contain your list items. Use the drop down to the left of the formula bar to jump to the named range, then edit it. If you add or remove items you will need to adjust the range the named range covers.

UNIX nonblocking I/O: O_NONBLOCK vs. FIONBIO

I believe fcntl() is a POSIX function. Where as ioctl() is a standard UNIX thing. Here is a list of POSIX io. ioctl() is a very kernel/driver/OS specific thing, but i am sure what you use works on most flavors of Unix. some other ioctl() stuff might only work on certain OS or even certain revs of it's kernel.

gcloud command not found - while installing Google Cloud SDK

The cause of my installation failure:

  • I am running a zsh terminal and the install.sh inserts path.bash.inc into my .bash_profile

fix:

  1. cd [whereever]/google-cloud-sdk && ./install.sh
  2. vi ~/.bash_profile
  3. replace all instances of path.bash.inc with path.zsh.inc

os config:

  • macOS Catalina
  • zsh

ref:

How can I exclude multiple folders using Get-ChildItem -exclude?

VertigoRay, in his answer, explained that -Exclude works only at the leaf level of a path (for a file the filename with path stripped out; for a sub-directory the directory name with path stripped out). So it looks like -Exclude cannot be used to specify a directory (eg "bin") and exclude all the files and sub-directories within that directory.

Here's a function to exclude files and sub-directories of one or more directories (I know this is not directly answering the question but I thought it might be useful in getting around the limitations of -Exclude):

$rootFolderPath = 'C:\Temp\Test'
$excludeDirectories = ("bin", "obj");

function Exclude-Directories
{
    process
    {
        $allowThrough = $true
        foreach ($directoryToExclude in $excludeDirectories)
        {
            $directoryText = "*\" + $directoryToExclude
            $childText = "*\" + $directoryToExclude + "\*"
            if (($_.FullName -Like $directoryText -And $_.PsIsContainer) `
                -Or $_.FullName -Like $childText)
            {
                $allowThrough = $false
                break
            }
        }
        if ($allowThrough)
        {
            return $_
        }
    }
}

Clear-Host

Get-ChildItem $rootFolderPath -Recurse `
    | Exclude-Directories

For a directory tree:

C:\Temp\Test\
|
+?SomeFolder\
|  |
|  +?bin (file without extension)
|
+?MyApplication\
  |
  +?BinFile.txt
  +?FileA.txt
  +?FileB.txt
  |
  +?bin\
    |
    +?Debug\
      |
      +?SomeFile.txt

The result is:

C:\Temp\Test\
|
+?SomeFolder\
|  |
|  +?bin (file without extension)
|
+?MyApplication\
  |
  +?BinFile.txt
  +?FileA.txt
  +?FileB.txt

It excludes the bin\ sub-folder and all its contents but does not exclude files Bin.txt or bin (file named "bin" without an extension).

Color different parts of a RichTextBox string

Using Selection in WPF, aggregating from several other answers, no other code is required (except Severity enum and GetSeverityColor function)

 public void Log(string msg, Severity severity = Severity.Info)
    {
        string ts = "[" + DateTime.Now.ToString("HH:mm:ss") + "] ";
        string msg2 = ts + msg + "\n";
        richTextBox.AppendText(msg2);

        if (severity > Severity.Info)
        {
            int nlcount = msg2.ToCharArray().Count(a => a == '\n');
            int len = msg2.Length + 3 * (nlcount)+2; //newlines are longer, this formula works fine
            TextPointer myTextPointer1 = richTextBox.Document.ContentEnd.GetPositionAtOffset(-len);
            TextPointer myTextPointer2 = richTextBox.Document.ContentEnd.GetPositionAtOffset(-1);

            richTextBox.Selection.Select(myTextPointer1,myTextPointer2);
            SolidColorBrush scb = new SolidColorBrush(GetSeverityColor(severity));
            richTextBox.Selection.ApplyPropertyValue(TextElement.BackgroundProperty, scb);

        }

        richTextBox.ScrollToEnd();
    }

javascript close current window

I suggest to put id to the input, and close the window by callback function as the following:

<input id="close_window" type="button" class="btn btn-success"
                   style="font-weight: bold;display: inline;"
                   value="Close">

The callback function as the following:

<script>
   $('#close_window').on('click', function(){
      window.opener = self;
      window.close();
   });
</script>

I think sometimes onclick doesn't work, check the following answer also.

Showing the stack trace from a running Python application

If you're on a Linux system, use the awesomeness of gdb with Python debug extensions (can be in python-dbg or python-debuginfo package). It also helps with multithreaded applications, GUI applications and C modules.

Run your program with:

$ gdb -ex r --args python <programname>.py [arguments]

This instructs gdb to prepare python <programname>.py <arguments> and run it.

Now when you program hangs, switch into gdb console, press Ctr+C and execute:

(gdb) thread apply all py-list

See example session and more info here and here.

How to remove all numbers from string?

For Western Arabic numbers (0-9):

$words = preg_replace('/[0-9]+/', '', $words);

For all numerals including Western Arabic (e.g. Indian):

$words = '????';
$words = preg_replace('/\d+/u', '', $words);
var_dump($words); // string(0) ""
  • \d+ matches multiple numerals.
  • The modifier /u enables unicode string treatment. This modifier is important, otherwise the numerals would not match.

Add image to layout in ruby on rails

When using the new ruby, the image folder will go to asset folder on folder app

after placing your images in image folder, use

<%=image_tag("example_image.png", alt: "Example Image")%>

Scheduling recurring task in Android

I am not sure but as per my knowledge I share my views. I always accept best answer if I am wrong .

Alarm Manager

The Alarm Manager holds a CPU wake lock as long as the alarm receiver's onReceive() method is executing. This guarantees that the phone will not sleep until you have finished handling the broadcast. Once onReceive() returns, the Alarm Manager releases this wake lock. This means that the phone will in some cases sleep as soon as your onReceive() method completes. If your alarm receiver called Context.startService(), it is possible that the phone will sleep before the requested service is launched. To prevent this, your BroadcastReceiver and Service will need to implement a separate wake lock policy to ensure that the phone continues running until the service becomes available.

Note: The Alarm Manager is intended for cases where you want to have your application code run at a specific time, even if your application is not currently running. For normal timing operations (ticks, timeouts, etc) it is easier and much more efficient to use Handler.

Timer

timer = new Timer();

    timer.scheduleAtFixedRate(new TimerTask() {

        synchronized public void run() {

            \\ here your todo;
            }

        }, TimeUnit.MINUTES.toMillis(1), TimeUnit.MINUTES.toMillis(1));

Timer has some drawbacks that are solved by ScheduledThreadPoolExecutor. So it's not the best choice

ScheduledThreadPoolExecutor.

You can use java.util.Timer or ScheduledThreadPoolExecutor (preferred) to schedule an action to occur at regular intervals on a background thread.

Here is a sample using the latter:

ScheduledExecutorService scheduler =
    Executors.newSingleThreadScheduledExecutor();

scheduler.scheduleAtFixedRate
      (new Runnable() {
         public void run() {
            // call service
         }
      }, 0, 10, TimeUnit.MINUTES);

So I preferred ScheduledExecutorService

But Also think about that if the updates will occur while your application is running, you can use a Timer, as suggested in other answers, or the newer ScheduledThreadPoolExecutor. If your application will update even when it is not running, you should go with the AlarmManager.

The Alarm Manager is intended for cases where you want to have your application code run at a specific time, even if your application is not currently running.

Take note that if you plan on updating when your application is turned off, once every ten minutes is quite frequent, and thus possibly a bit too power consuming.

Printing without newline (print 'a',) prints a space, how to remove?

Python 3.x:

for i in range(20):
    print('a', end='')

Python 2.6 or 2.7:

from __future__ import print_function
for i in xrange(20):
    print('a', end='')

Call a stored procedure with parameter in c#

public void myfunction(){
        try
        {
            sqlcon.Open();
            SqlCommand cmd = new SqlCommand("sp_laba", sqlcon);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.ExecuteNonQuery();
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            sqlcon.Close();
        }
}

What is the purpose of meshgrid in Python / NumPy?

Short answer

The purpose of meshgrid is to help remplace Python loops (slow interpreted code) by vectorized operations within C NumPy library.

Borrowed from this site.

enter image description here

x = np.arange(-4, 4, 0.25)
y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(x, y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)

meshgrid is used to create pairs of coordinates between -4 and +4 with .25 increments in each direction X and Y. Each pair is then used to find R, and Z from it. This way of preparing "a grid" of coordinates is frequently used in plotting 3D surfaces, or coloring 2D surfaces.


Details: Python for-loop vs NumPy vector operation

To take a more simple example, let's say we have two sequences of values,

a = [2,7,9,20]    
b = [1,6,7,9]    ?

and we want to perform an operation on each possible pair of values, one taken from the first list, one taken from the second list. We also want to store the result. For example, let's say we want to get the sum of the values for each possible pair.

Slow and laborious method

c = []    
for i in range(len(b)):    
    row = []    
    for j in range(len(a)):    
        row.append (a[j] + b[i])
    c.append (row)    
print (c)

Result:

[[3, 8, 10, 21],
 [8, 13, 15, 26],
 [9, 14, 16, 27],
 [11, 16, 18, 29]]

Python is interpreted, these loops are relatively slow to execute.

Fast and easy method

meshgrid is intended to remove the loops from the code. It returns two arrays (i and j below) which can be combined to scan all the existing pairs like this:

i,j = np.meshgrid (a,b)    
c = i + j    
print (c)

Result:

[[ 3  8 10 21]
 [ 8 13 15 26]
 [ 9 14 16 27]
 [11 16 18 29]]

Meshgrid under the hood

The two arrays prepared by meshgrid are:

(array([[ 2,  7,  9, 20],
        [ 2,  7,  9, 20],
        [ 2,  7,  9, 20],
        [ 2,  7,  9, 20]]),

 array([[1, 1, 1, 1],
        [6, 6, 6, 6],
        [7, 7, 7, 7],
        [9, 9, 9, 9]]))

These arrays are created by repeating the values provided. One contains the values in identical rows, the other contains the other values in identical columns. The number of rows and column is determined by the number of elements in the other sequence.

The two arrays created by meshgrid are therefore shape compatible for a vector operation. Imagine x and y sequences in the code at the top of page having a different number of elements, X and Y resulting arrays will be shape compatible anyway, not requiring any broadcast.

Origin

numpy.meshgrid comes from MATLAB, like many other NumPy functions. So you can also study the examples from MATLAB to see meshgrid in use, the code for the 3D plotting looks the same in MATLAB.

Python dict how to create key or append an element to key?

You can use defaultdict in collections.

An example from doc:

s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
d = defaultdict(list)
for k, v in s:
    d[k].append(v)

how I can show the sum of in a datagridview column?

Use LINQ if you can.

  label1.Text =  dataGridView1.Rows.Cast<DataGridViewRow>()
                                   .AsEnumerable()
                                   .Sum(x => int.Parse(x.Cells[1].Value.ToString()))
                                   .ToString();

Get div tag scroll position using JavaScript

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function scollPos() {
            var div = document.getElementById("myDiv").scrollTop;
            document.getElementById("pos").innerHTML = div;
        }
    </script>
</head>
<body>
    <form id="form1">
    <div id="pos">
    </div>
    <div id="myDiv" style="overflow: auto; height: 200px; width: 200px;" onscroll="scollPos();">
        Place some large content here
    </div>
    </form>
</body>
</html>

Bootstrap control with multiple "data-toggle"

Not yet. However, it has been suggested that someone add this feature one day.

The following bootstrap Github issue shows a perfect example of what you are wishing for. It is possible- but not without writing your own workaround code at this stage though.

Check it out... :-)

https://github.com/twitter/bootstrap/issues/7011

What is an Endpoint?

API stands for Application Programming Interface. It is a way for your application to interact with other applications via an endpoint. Conversely, you can build out an API for your application that is available for other developers to utilize/connect to via HTTP methods, which are RESTful. Representational State Transfer (REST):

  • GET: Retrieve data from an API endpoint.
  • PUT: Update data via an API - similar to POST but more about updating info.
  • POST: Send data to an API.
  • DELETE: Remove data from given API.

How do you normalize a file path in Bash?

Try realpath. Below is the source in its entirety, hereby donated to the public domain.

// realpath.c: display the absolute path to a file or directory.
// Adam Liss, August, 2007
// This program is provided "as-is" to the public domain, without express or
// implied warranty, for any non-profit use, provided this notice is maintained.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <libgen.h>   
#include <limits.h>

static char *s_pMyName;
void usage(void);

int main(int argc, char *argv[])
{
    char
        sPath[PATH_MAX];


    s_pMyName = strdup(basename(argv[0]));

    if (argc < 2)
        usage();

    printf("%s\n", realpath(argv[1], sPath));
    return 0;
}    

void usage(void)
{
    fprintf(stderr, "usage: %s PATH\n", s_pMyName);
    exit(1);
}

Regular Expression for password validation

There seems to be a lot of confusion here. The answers I see so far don't correctly enforce the 1+ number/1+ lowercase/1+ uppercase rule, meaning that passwords like abc123, 123XYZ, or AB*&^# would still be accepted. Preventing all-lowercase, all-caps, or all-digits is not enough; you have to enforce the presence of at least one of each.

Try the following:

^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,15}$

If you also want to require at least one special character (which is probably a good idea), try this:

^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^\da-zA-Z]).{8,15}$

The .{8,15} can be made more restrictive if you wish (for example, you could change it to \S{8,15} to disallow whitespace), but remember that doing so will reduce the strength of your password scheme.

I've tested this pattern and it works as expected. Tested on ReFiddle here: http://refiddle.com/110


Edit: One small note, the easiest way to do this is with 3 separate regexes and the string's Length property. It's also easier to read and maintain, so do it that way if you have the option. If this is for validation rules in markup, though, you're probably stuck with a single regex.

How do I URl encode something in Node.js?

You can use JavaScript's encodeURIComponent:

encodeURIComponent('select * from table where i()')

giving

'select%20*%20from%20table%20where%20i()'

Set angular scope variable in markup

You can set values from html like this. I don't think there is a direct solution from angular yet.

 <div style="visibility: hidden;">{{activeTitle='home'}}</div>

Save and retrieve image (binary) from SQL Server using Entity Framework 6

Convert the image to a byte[] and store that in the database.


Add this column to your model:

public byte[] Content { get; set; }

Then convert your image to a byte array and store that like you would any other data:

public byte[] ImageToByteArray(System.Drawing.Image imageIn)
{
    using(var ms = new MemoryStream())
    {
        imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);

        return ms.ToArray();
    }
}

public Image ByteArrayToImage(byte[] byteArrayIn)
{
     using(var ms = new MemoryStream(byteArrayIn))
     {
         var returnImage = Image.FromStream(ms);

         return returnImage;
     }
}

Source: Fastest way to convert Image to Byte array

var image = new ImageEntity()
{
   Content = ImageToByteArray(image)
};

_context.Images.Add(image);
_context.SaveChanges();

When you want to get the image back, get the byte array from the database and use the ByteArrayToImage and do what you wish with the Image

This stops working when the byte[] gets to big. It will work for files under 100Mb

How can I format bytes a cell in Excel as KB, MB, GB etc?

I use CDH hadoop and when I export excel report, I have two problems;

1) convert Linux date to excel date,
For that, add an empty column next to date column lets say the top row is B4, paste below formula and drag the BLACK "+" all the way to your last day at the end of the column. Then hide the original column

=(((B4/1000/60)/60)/24)+DATE(1970|1|1)+(-5/24)

2) Convert disk size from byte to TB, GB, and MB
the best formula for that is this

[>999999999999]# ##0.000,,,," TB";[>999999999]# ##0.000,,," GB";# ##0.000,," MB"

it will give you values with 3 decimals just format cells --> Custom and paste the above code there

how to run two commands in sudo?

The above answers won't let you quote inside the quotes. This solution will:

sudo -su nobody umask 0000 \; mkdir -p "$targetdir"

Both the umask command and the mkdir-command runs in with the 'nobody' user.

Programmatically add new column to DataGridView

Add new column to DataTable and use column Expression property to set your Status expression.

Here you can find good example: DataColumn.Expression Property

DataTable and DataColumn Expressions in ADO.NET - Calculated Columns

UPDATE

Code sample:

DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("colBestBefore", typeof(DateTime)));
dt.Columns.Add(new DataColumn("colStatus", typeof(string)));

dt.Columns["colStatus"].Expression = String.Format("IIF(colBestBefore < #{0}#, 'Ok','Not ok')", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

dt.Rows.Add(DateTime.Now.AddDays(-1));
dt.Rows.Add(DateTime.Now.AddDays(1));
dt.Rows.Add(DateTime.Now.AddDays(2));
dt.Rows.Add(DateTime.Now.AddDays(-2));

demoGridView.DataSource = dt;

UPDATE #2

dt.Columns["colStatus"].Expression = String.Format("IIF(CONVERT(colBestBefore, 'System.DateTime') < #{0}#, 'Ok','Not ok')", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

Opening a SQL Server .bak file (Not restoring!)

The only workable solution is to restore the .bak file. The contents and the structure of those files are not documented and therefore, there's really no way (other than an awful hack) to get this to work - definitely not worth your time and the effort!

The only tool I'm aware of that can make sense of .bak files without restoring them is Red-Gate SQL Compare Professional (and the accompanying SQL Data Compare) which allow you to compare your database structure against the contents of a .bak file. Red-Gate tools are absolutely marvelous - highly recommended and well worth every penny they cost!

And I just checked their web site - it does seem that you can indeed restore a single table from out of a .bak file with SQL Compare Pro ! :-)

What is the use of "object sender" and "EventArgs e" parameters?

EventArgs e is a parameter called e that contains the event data, see the EventArgs MSDN page for more information.

Object Sender is a parameter called Sender that contains a reference to the control/object that raised the event.

Event Arg Class: http://msdn.microsoft.com/en-us/library/system.eventargs.aspx

Example:

protected void btn_Click (object sender, EventArgs e){
   Button btn = sender as Button;
   btn.Text = "clicked!";
}

Edit: When Button is clicked, the btn_Click event handler will be fired. The "object sender" portion will be a reference to the button which was clicked

How to Turn Off Showing Whitespace Characters in Visual Studio IDE

In Visual Studio 2010 the key sequence CTRL+E, S will also toggle display of whitespace characters.

Removing legend on charts with chart.js v2

The options object can be added to the chart when the new Chart object is created.

var chart1 = new Chart(canvas, {
    type: "pie",
    data: data,
    options: {
         legend: {
            display: false
         },
         tooltips: {
            enabled: false
         }
    }
});

Do sessions really violate RESTfulness?

HTTP transaction, basic access authentication, is not suitable for RBAC, because basic access authentication uses the encrypted username:password every time to identify, while what is needed in RBAC is the Role the user wants to use for a specific call. RBAC does not validate permissions on username, but on roles.

You could tric around to concatenate like this: usernameRole:password, but this is bad practice, and it is also inefficient because when a user has more roles, the authentication engine would need to test all roles in concatenation, and that every call again. This would destroy one of the biggest technical advantages of RBAC, namely a very quick authorization-test.

So that problem cannot be solved using basic access authentication.

To solve this problem, session-maintaining is necessary, and that seems, according to some answers, in contradiction with REST.

That is what I like about the answer that REST should not be treated as a religion. In complex business cases, in healthcare, for example, RBAC is absolutely common and necessary. And it would be a pity if they would not be allowed to use REST because all REST-tools designers would treat REST as a religion.

For me there are not many ways to maintain a session over HTTP. One can use cookies, with a sessionId, or a header with a sessionId.

If someone has another idea I will be glad to hear it.

jQuery issue - #<an Object> has no method

For anyone else arriving at this question:

I was performing the most simple jQuery, trying to hide an element:

('#fileselection').hide();

and I was getting the same type of error, "Uncaught TypeError: Object #fileselection has no method 'hide'

Of course, now it is obvious, but I just left off the jQuery indicator '$'. The code should have been:

$('#fileselection').hide();

This fixes the no-brainer problem. I hope this helps someone save a few minutes debugging!

join on multiple columns

The other queries are all going base on any ONE of the conditions qualifying and it will return a record... if you want to make sure the BOTH columns of table A are matched, you'll have to do something like...

select 
      tA.Col1,
      tA.Col2,
      tB.Val
   from
      TableA tA
         join TableB tB
            on  ( tA.Col1 = tB.Col1 OR tA.Col1 = tB.Col2 )
            AND ( tA.Col2 = tB.Col1 OR tA.Col2 = tB.Col2 )

jQuery slide left and show

And if you want to vary the speed and include callbacks simply add them like this :

        jQuery.fn.extend({
            slideRightShow: function(speed,callback) {
                return this.each(function() {
                    $(this).show('slide', {direction: 'right'}, speed, callback);
                });
            },
            slideLeftHide: function(speed,callback) {
                return this.each(function() {
                    $(this).hide('slide', {direction: 'left'}, speed, callback);
                });
            },
            slideRightHide: function(speed,callback) {
                return this.each(function() {  
                    $(this).hide('slide', {direction: 'right'}, speed, callback);
                });
            },
            slideLeftShow: function(speed,callback) {
                return this.each(function() {
                    $(this).show('slide', {direction: 'left'}, speed, callback);
                });
            }
        });

array.select() in javascript

Array.filter is not implemented in many browsers,It is better to define this function if it does not exist.

The source code for Array.prototype is posted in MDN

if (!Array.prototype.filter)
{
  Array.prototype.filter = function(fun /*, thisp */)
  {
    "use strict";

    if (this == null)
      throw new TypeError();

    var t = Object(this);
    var len = t.length >>> 0;
    if (typeof fun != "function")
      throw new TypeError();

    var res = [];
    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in t)
      {
        var val = t[i]; // in case fun mutates this
        if (fun.call(thisp, val, i, t))
          res.push(val);
      }
    }

    return res;
  };
}

see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter for more details

How to close activity and go back to previous activity in android

This closes the entire application:

this.finish();

CodeIgniter: "Unable to load the requested class"

If you're using a linux server for your application then it is necessary to use lowercase file name and class name to avoid this issue.

Ex.

Filename: csvsample.php

class csvsample {

}

How to convert signed to unsigned integer in python

Assuming:

  1. You have 2's-complement representations in mind; and,
  2. By (unsigned long) you mean unsigned 32-bit integer,

then you just need to add 2**32 (or 1 << 32) to the negative value.

For example, apply this to -1:

>>> -1
-1
>>> _ + 2**32
4294967295L
>>> bin(_)
'0b11111111111111111111111111111111'

Assumption #1 means you want -1 to be viewed as a solid string of 1 bits, and assumption #2 means you want 32 of them.

Nobody but you can say what your hidden assumptions are, though. If, for example, you have 1's-complement representations in mind, then you need to apply the ~ prefix operator instead. Python integers work hard to give the illusion of using an infinitely wide 2's complement representation (like regular 2's complement, but with an infinite number of "sign bits").

And to duplicate what the platform C compiler does, you can use the ctypes module:

>>> import ctypes
>>> ctypes.c_ulong(-1)  # stuff Python's -1 into a C unsigned long
c_ulong(4294967295L)
>>> _.value
4294967295L

C's unsigned long happens to be 4 bytes on the box that ran this sample.

Replace negative values in an numpy array

And yet another possibility:

In [2]: a = array([1, 2, 3, -4, 5])

In [3]: where(a<0, 0, a)
Out[3]: array([1, 2, 3, 0, 5])

When to choose mouseover() and hover() function?

You can try it out http://api.jquery.com/mouseover/ on the jQuery doc page. It's a nice little, interactive demo that makes it very clear and you can actually see for yourself.

In short, you'll notice that a mouse over event occurs on an element when you are over it - coming from either its child OR parent element, but a mouse enter event only occurs when the mouse moves from the parent element to the element.

Configure nginx with multiple locations with different root folders on subdomain

The Location directive system is

Like you want to forward all request which start /static and your data present in /var/www/static

So a simple method is separated last folder from full path , that means

Full path : /var/www/static

Last Path : /static and First path : /var/www

location <lastPath> {
    root <FirstPath>;
}

So lets see what you did mistake and what is your solutions

Your Mistake :

location /static {
    root /web/test.example.com/static;
}

Your Solutions :

location /static {
    root /web/test.example.com;
}

How to create materialized views in SQL Server?

You might need a bit more background on what a Materialized View actually is. In Oracle these are an object that consists of a number of elements when you try to build it elsewhere.

An MVIEW is essentially a snapshot of data from another source. Unlike a view the data is not found when you query the view it is stored locally in a form of table. The MVIEW is refreshed using a background procedure that kicks off at regular intervals or when the source data changes. Oracle allows for full or partial refreshes.

In SQL Server, I would use the following to create a basic MVIEW to (complete) refresh regularly.

First, a view. This should be easy for most since views are quite common in any database Next, a table. This should be identical to the view in columns and data. This will store a snapshot of the view data. Then, a procedure that truncates the table, and reloads it based on the current data in the view. Finally, a job that triggers the procedure to start it's work.

Everything else is experimentation.

INSTALL_FAILED_UPDATE_INCOMPATIBLE when I try to install compiled .apk on device

I just renamed the package and it worked for me.

Or if you are using Ionic, you could delete the application and try again, this happens when ionic detects that the app you are deploying is not coming from the same build. It often happen when you change from pc.

How to cast an object in Objective-C

Casting for inclusion is just as important as casting for exclusion for a C++ programmer. Type casting is not the same as with RTTI in the sense that you can cast an object to any type and the resulting pointer will not be nil.

Zsh: Conda/Pip installs command not found

Simply copy your Anaconda bin directory and paste it at the bottom of ~/.zshrc.

For me the path is /home/theorangeguy/miniconda3/bin, so I ran:

echo ". /home/theorangeguy/miniconda3/bin" >> ~/.zshrc

This edited the ~/.zshrc. Now do:

source ~/.zshrc

It worked like a charm.

How to manage a redirect request after a jQuery Ajax call

The solution that was eventually implemented was to use a wrapper for the callback function of the Ajax call and in this wrapper check for the existence of a specific element on the returned HTML chunk. If the element was found then the wrapper executed a redirection. If not, the wrapper forwarded the call to the actual callback function.

For example, our wrapper function was something like:

function cbWrapper(data, funct){
    if($("#myForm", data).length > 0)
        top.location.href="login.htm";//redirection
    else
        funct(data);
}

Then, when making the Ajax call we used something like:

$.post("myAjaxHandler", 
       {
        param1: foo,
        param2: bar
       },
       function(data){
           cbWrapper(data, myActualCB);
       }, 
       "html"
);

This worked for us because all Ajax calls always returned HTML inside a DIV element that we use to replace a piece of the page. Also, we only needed to redirect to the login page.

How to cd into a directory with space in the name?

To change to a directory with spaces on the name you just have to type like this:

cd My\ Documents

Hit enter and you will be good

Drop unused factor levels in a subsetted data frame

Here's another way, which I believe is equivalent to the factor(..) approach:

> df <- data.frame(let=letters[1:5], num=1:5)
> subdf <- df[df$num <= 3, ]

> subdf$let <- subdf$let[ , drop=TRUE]

> levels(subdf$let)
[1] "a" "b" "c"

What does 'IISReset' do?

You can find more information about which services it affects on the Microsoft docs.

Array length in angularjs returns undefined

use:

$scope.users.length;

Instead of:

$scope.users.lenght;

And next time "spell-check" your code.

How can I force a long string without any blank to be wrapped?

My way to go (when there is no appropiate way to insert special chars) via CSS:

-ms-word-break: break-all;
word-break: break-all;
word-break: break-word;
-webkit-hyphens: auto;
-moz-hyphens: auto;
-ms-hyphens: auto;
hyphens: auto;

As found here: http://kenneth.io/blog/2012/03/04/word-wrapping-hypernation-using-css/ with some additional research to be found there.

Android Studio drawable folders

Actually you have selected Android from the tab change it to project.

Steps

enter image description here

Then you will found all folders.

enter image description here

Revert to a commit by a SHA hash in Git?

This might work:

git checkout 56e05f
echo ref: refs/heads/master > .git/HEAD
git commit

How to set the custom border color of UIView programmatically?

In Swift 4 you can set the border color and width to UIControls using below code.

let yourColor : UIColor = UIColor( red: 0.7, green: 0.3, blue:0.1, alpha: 1.0 )
yourControl.layer.masksToBounds = true
yourControl.layer.borderColor = yourColor.CGColor
yourControl.layer.borderWidth = 1.0

< Swift 4, You can set UIView's border width and border color using the below code.

yourView.layer.borderWidth = 1

yourView.layer.borderColor = UIColor.red.cgColor

What's the difference between a 302 and a 307 redirect?

Flowchart

  • 301: permanent redirect: the URL is old and should be replaced. Browsers will cache this.
    Example usage: URL moved from /register-form.html to signup-form.html.
    The method will change to GET, as per RFC 7231: "For historical reasons, a user agent MAY change the request method from POST to GET for the subsequent request."
  • 302: temporary redirect. Only use for HTTP/1.0 clients. This status code should not change the method, but browsers did it anyway. The RFC says: "Many pre-HTTP/1.1 user agents do not understand [303]. When interoperability with such clients is a concern, the 302 status code may be used instead, since most user agents react to a 302 response as described here for 303." Of course, some clients may implement it according to the spec, so if interoperability with such ancient clients is not a real concern, 303 is better for consistent results.
  • 303: temporary redirect, changing the method to GET.
    Example usage: if the browser sent POST to /register.php, then now load (GET) /success.html.
  • 307: temporary redirect, repeating the request identically.
    Example usage: if the browser sent a POST to /register.php, then this tells it to redo the POST at /signup.php.
  • 308: permanent redirect, repeating the request identically. Where 307 is the "no method change" counterpart of 303, this 308 status is the "no method change" counterpart of 301.

RFC 7231 (from 2014) is very readable and not overly verbose. If you want to know the exact answer, it's a recommended read. Some other answers use RFC 2616 from 1999, but nothing changed.

RFC 7238 specifies the 308 status. It is considered experimental, but it was already supported by all major browsers in 2016.

How to diff one file to an arbitrary version in Git?

To see what was changed in a file in the last commit:

git diff HEAD~1 path/to/file

You can change the number (~1) to the n-th commit which you want to diff with.

Sorting a vector in descending order

What about this?

std::sort(numbers.begin(), numbers.end());
std::reverse(numbers.begin(), numbers.end());

In jQuery, what's the best way of formatting a number to 2 decimal places?

If you're doing this to several fields, or doing it quite often, then perhaps a plugin is the answer.
Here's the beginnings of a jQuery plugin that formats the value of a field to two decimal places.
It is triggered by the onchange event of the field. You may want something different.

<script type="text/javascript">

    // mini jQuery plugin that formats to two decimal places
    (function($) {
        $.fn.currencyFormat = function() {
            this.each( function( i ) {
                $(this).change( function( e ){
                    if( isNaN( parseFloat( this.value ) ) ) return;
                    this.value = parseFloat(this.value).toFixed(2);
                });
            });
            return this; //for chaining
        }
    })( jQuery );

    // apply the currencyFormat behaviour to elements with 'currency' as their class
    $( function() {
        $('.currency').currencyFormat();
    });

</script>   
<input type="text" name="one" class="currency"><br>
<input type="text" name="two" class="currency">

Efficiently replace all accented characters in a string?

Answer os Crisalin is almost perfect. Just improved the performance to avoid create new RegExp on each run.

var normalizeConversions = [
    { regex: new RegExp('ä|æ|?', 'g'), clean: 'ae' },
    { regex: new RegExp('ö|œ', 'g'), clean: 'oe' },
    { regex: new RegExp('ü', 'g'), clean: 'ue' },
    { regex: new RegExp('Ä', 'g'), clean: 'Ae' },
    { regex: new RegExp('Ü', 'g'), clean: 'Ue' },
    { regex: new RegExp('Ö', 'g'), clean: 'Oe' },
    { regex: new RegExp('À|Á|Â|Ã|Ä|Å|?|A|A|A|A', 'g'), clean: 'A' },
    { regex: new RegExp('à|á|â|ã|å|?|a|a|a|a|ª', 'g'), clean: 'a' },
    { regex: new RegExp('Ç|C|C|C|C', 'g'), clean: 'C' },
    { regex: new RegExp('ç|c|c|c|c', 'g'), clean: 'c' },
    { regex: new RegExp('Ð|D|Ð', 'g'), clean: 'D' },
    { regex: new RegExp('ð|d|d', 'g'), clean: 'd' },
    { regex: new RegExp('È|É|Ê|Ë|E|E|E|E|E', 'g'), clean: 'E' },
    { regex: new RegExp('è|é|ê|ë|e|e|e|e|e', 'g'), clean: 'e' },
    { regex: new RegExp('G|G|G|G', 'g'), clean: 'G' },
    { regex: new RegExp('g|g|g|g', 'g'), clean: 'g' },
    { regex: new RegExp('H|H', 'g'), clean: 'H' },
    { regex: new RegExp('h|h', 'g'), clean: 'h' },
    { regex: new RegExp('Ì|Í|Î|Ï|I|I|I|I|I|I', 'g'), clean: 'I' },
    { regex: new RegExp('ì|í|î|ï|i|i|i|i|i|i', 'g'), clean: 'i' },
    { regex: new RegExp('J', 'g'), clean: 'J' },
    { regex: new RegExp('j', 'g'), clean: 'j' },
    { regex: new RegExp('K', 'g'), clean: 'K' },
    { regex: new RegExp('k', 'g'), clean: 'k' },
    { regex: new RegExp('L|L|L|?|L', 'g'), clean: 'L' },
    { regex: new RegExp('l|l|l|?|l', 'g'), clean: 'l' },
    { regex: new RegExp('Ñ|N|N|N', 'g'), clean: 'N' },
    { regex: new RegExp('ñ|n|n|n|?', 'g'), clean: 'n' },
    { regex: new RegExp('Ò|Ó|Ô|Õ|O|O|O|O|O|Ø|?', 'g'), clean: 'O' },
    { regex: new RegExp('ò|ó|ô|õ|o|o|o|o|o|ø|?|º', 'g'), clean: 'o' },
    { regex: new RegExp('R|R|R', 'g'), clean: 'R' },
    { regex: new RegExp('r|r|r', 'g'), clean: 'r' },
    { regex: new RegExp('S|S|S|Š', 'g'), clean: 'S' },
    { regex: new RegExp('s|s|s|š|?', 'g'), clean: 's' },
    { regex: new RegExp('T|T|T', 'g'), clean: 'T' },
    { regex: new RegExp('t|t|t', 'g'), clean: 't' },
    { regex: new RegExp('Ù|Ú|Û|U|U|U|U|U|U|U|U|U|U|U|U', 'g'), clean: 'U' },
    { regex: new RegExp('ù|ú|û|u|u|u|u|u|u|u|u|u|u|u|u', 'g'), clean: 'u' },
    { regex: new RegExp('Ý|Ÿ|Y', 'g'), clean: 'Y' },
    { regex: new RegExp('ý|ÿ|y', 'g'), clean: 'y' },
    { regex: new RegExp('W', 'g'), clean: 'W' },
    { regex: new RegExp('w', 'g'), clean: 'w' },
    { regex: new RegExp('Z|Z|Ž', 'g'), clean: 'Z' },
    { regex: new RegExp('z|z|ž', 'g'), clean: 'z' },
    { regex: new RegExp('Æ|?', 'g'), clean: 'AE' },
    { regex: new RegExp('ß', 'g'), clean: 'ss' },
    { regex: new RegExp('?', 'g'), clean: 'IJ' },
    { regex: new RegExp('?', 'g'), clean: 'ij' },
    { regex: new RegExp('Œ', 'g'), clean: 'OE' },
    { regex: new RegExp('ƒ', 'g'), clean: 'f' }
];

Usage:

function(str){
    normalizeConversions.forEach(function(normalizeEntry){
        str = str.replace(normalizeEntry.regex, normalizeEntry.clean);
    });
    return str;
};

What is the regular expression to allow uppercase/lowercase (alphabetical characters), periods, spaces and dashes only?

The regex you're looking for is ^[A-Za-z.\s_-]+$

  • ^ asserts that the regular expression must match at the beginning of the subject
  • [] is a character class - any character that matches inside this expression is allowed
  • A-Z allows a range of uppercase characters
  • a-z allows a range of lowercase characters
  • . matches a period rather than a range of characters
  • \s matches whitespace (spaces and tabs)
  • _ matches an underscore
  • - matches a dash (hyphen); we have it as the last character in the character class so it doesn't get interpreted as being part of a character range. We could also escape it (\-) instead and put it anywhere in the character class, but that's less clear
  • + asserts that the preceding expression (in our case, the character class) must match one or more times
  • $ Finally, this asserts that we're now at the end of the subject

When you're testing regular expressions, you'll likely find a tool like regexpal helpful. This allows you to see your regular expression match (or fail to match) your sample data in real time as you write it.

Prolog "or" operator, query

Just another viewpoint. Performing an "or" in Prolog can also be done with the "disjunct" operator or semi-colon:

registered(X, Y) :-
    X = ct101; X = ct102; X = ct103.

For a fuller explanation:

Predicate control in Prolog

What is the difference between DTR/DSR and RTS/CTS flow control?

An important difference is that some UARTs (16550 notably) will stop receiving characters immediately if their host instructs them to set DSR to be inactive. In contrast, characters will still be received if CTS is inactive. I believe that the intention here is that DSR indicates that the device is no longer listening and so sending any further characters is pointless, while CTS indicates that a buffer is getting full; the latter allows for a certain amount of 'skid' where the flow control line changed state between the DTE sampling it and the next character being transmitted. In (relatively) later devices that support a hardware FIFO it's possible that a number of characters could be transmitted after the DCE has set CTS to be inactive.

How to terminate a window in tmux?

While you asked how to kill a window resp. pane, I often wouldn't want to kill it but simply to get it back to a working state (the layout of panes is of importance to me, killing a pane destroys it so I must recreate it); tmux provides the respawn commands to that effect: respawn-pane resp. respawn-window. Just that people like me may find this solution here.

How to open Emacs inside Bash

It can be useful also to add the option --no-desktop to avoid launching several buffers saved.

How can I split a shell command over multiple lines when using an IF statement?

For Windows/WSL/Cygwin etc users:

Make sure that your line endings are standard Unix line feeds, i.e. \n (LF) only.

Using Windows line endings \r\n (CRLF) line endings will break the command line break.


This is because having \ at the end of a line with Windows line ending translates to \ \r \n.
As Mark correctly explains above:

The line-continuation will fail if you have whitespace after the backslash and before the newline.

This includes not just space () or tabs (\t) but also the carriage return (\r).

Why does JPA have a @Transient annotation?

As others have said, @Transient is used to mark fields which shouldn't be persisted. Consider this short example:

public enum Gender { MALE, FEMALE, UNKNOWN }

@Entity
public Person {
    private Gender g;
    private long id;

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    public long getId() { return id; }
    public void setId(long id) { this.id = id; }

    public Gender getGender() { return g; }    
    public void setGender(Gender g) { this.g = g; }

    @Transient
    public boolean isMale() {
        return Gender.MALE.equals(g);
    }

    @Transient
    public boolean isFemale() {
        return Gender.FEMALE.equals(g);
    }
}

When this class is fed to the JPA, it persists the gender and id but doesn't try to persist the helper boolean methods - without @Transient the underlying system would complain that the Entity class Person is missing setMale() and setFemale() methods and thus wouldn't persist Person at all.

Access mysql remote database from command line

  1. try telnet 3306. If it doesn't open connection, either there is a firewall setting or the server isn't listening (or doesn't work).

  2. run netstat -an on server to see if server is up.

  3. It's possible that you don't allow remote connections.

    See http://www.cyberciti.biz/tips/how-do-i-enable-remote-access-to-mysql-database-server.html

Why can't DateTime.ParseExact() parse "9/1/2009" using "M/d/yyyy"

Try

Date.ParseExact("9/1/2009", "M/d/yyyy", new CultureInfo("en-US"))

CSS Classes & SubClasses

kR105 wrote:

you can also have two classes within an element like this

<div class = "item1 item2 item3"></div

I can't see the value of this, since by the principle of cascading styles, the last one takes precedence. For example, if in my earlier example I changed the HTML to read

 <div class="box1 box2"> Hello what is my color? </div>

the box's border and text would be blue, since .box2's style assigns these values.

Also in my earlier post I should have emphasized that adding selectors as I did is not the same as creating a subclass within a class (the first solution in this thread), though the effect is similar.

CAML query with nested ANDs and ORs for multiple fields

You can try U2U Query Builder http://www.u2u.net/res/Tools/CamlQueryBuilder.aspx you can use their API U2U.SharePoint.CAML.Server.dll and U2U.SharePoint.CAML.Client.dll

I didn't use them but I'm sure it will help you achieving your task.

How to loop and render elements in React.js without an array of objects to map?

Updated: As of React > 0.16

Render method does not necessarily have to return a single element. An array can also be returned.

var indents = [];
for (var i = 0; i < this.props.level; i++) {
  indents.push(<span className='indent' key={i}></span>);
}
return indents;

OR

return this.props.level.map((item, index) => (
    <span className="indent" key={index}>
        {index}
    </span>
));

Docs here explaining about JSX children


OLD:

You can use one loop instead

var indents = [];
for (var i = 0; i < this.props.level; i++) {
  indents.push(<span className='indent' key={i}></span>);
}
return (
   <div>
    {indents}
    "Some text value"
   </div>
);

You can also use .map and fancy es6

return (
   <div>
    {this.props.level.map((item, index) => (
       <span className='indent' key={index} />
    ))}
    "Some text value"
   </div>
);

Also, you have to wrap the return value in a container. I used div in the above example

As the docs say here

Currently, in a component's render, you can only return one node; if you have, say, a list of divs to return, you must wrap your components within a div, span or any other component.

Is it possible to animate scrollTop with jQuery?

I was having issues where the animation was always starting from the top of the page after a page refresh in the other examples.

I fixed this by not animating the css directly but rather calling window.scrollTo(); on each step:

$({myScrollTop:window.pageYOffset}).animate({myScrollTop:300}, {
  duration: 600,
  easing: 'swing',
  step: function(val) {
    window.scrollTo(0, val);
  }
});

This also gets around the html vs body issue as it's using cross-browser JavaScript.

Have a look at http://james.padolsey.com/javascript/fun-with-jquerys-animate/ for more information on what you can do with jQuery's animate function.

How to print pthread_t

if pthread_t is just a number; this would be the easiest.

int get_tid(pthread_t tid)
{
    assert_fatal(sizeof(int) >= sizeof(pthread_t));

    int * threadid = (int *) (void *) &tid;
    return *threadid;
}

How do MySQL indexes work?

Adding some visual representation to the list of answers. enter image description here

MySQL uses an extra layer of indirection: secondary index records point to primary index records, and the primary index itself holds the on-disk row locations. If a row offset changes, only the primary index needs to be updated.

Caveat: Disk data structure looks flat in the diagram but actually is a B+ tree.

Source: link

Rename multiple files in a folder, add a prefix (Windows)

Option 1: Using Windows PowerShell

Open the windows menu. Type: "PowerShell" and open the 'Windows PowerShell' command window.

Goto folder with desired files: e.g. cd "C:\house chores" Notice: address must incorporate quotes "" if there are spaces involved.

You can use 'dir' to see all the files in the folder. Using '|' will pipeline the output of 'dir' for the command that follows.

Notes: 'dir' is an alias of 'Get-ChildItem'. See: wiki: cmdlets. One can provide further functionality. e.g. 'dir -recurse' outputs all the files, folders and sub-folders.

What if I only want a range of files?

Instead of 'dir |' I can use:

dir | where-object -filterscript {($_.Name -ge 'DSC_20') -and ($_.Name -le 'DSC_31')} |

For batch-renaming with the directory name as a prefix:

dir | Rename-Item -NewName {$_.Directory.Name + " - " + $_.Name}

Option 2: Using Command Prompt

In the folder press shift+right-click : select 'open command-window here'

for %a in (*.*) do ren "%a" "prefix - %a"

If there are a lot of files, it might be good to add an '@echo off' command before this and an 'echo on' command at the end.

Executing JavaScript without a browser?

Main Answer

Yes, to answer your question, it is possible to use JavaScript as a "regular" scripting language from the command line, without a browser. Since others have not mentioned it yet, I see that it is worth mentioning:

On Debian-based systems (and this includes Ubuntu, Linux Mint, and aptosid/sidux, at least), besides the options of installing Rhino and others already mentioned, you have have other options:

  • Install the libmozjs-24-bin package, which will provide you with Mozilla's Spidermonkey engine on the command line as a simple js24, which can be used also as an interactive interpreter. (The 24 in the name means that it corresponds to version 24 of Firefox).

  • Install the libv8-dev package, which will provide you Google's V8 engine. It has, as one of its examples, the file /usr/share/doc/libv8-dev/examples/shell.cc.gz which you can uncompress and compile very simply (e.g., g++ -Os shell.cc -o shell -lv8).

  • Install the package nodejs and it will be available both as the executable nodejs and as an alternative (in the Debian-sense) to provide the js executable. JIT compilation is provided as a courtesy of V8.

  • Install the package libjavascriptcoregtk-3.0-bin and use WebKit's JavaScriptCore interpreter (jsc) as a regular interpreter from the command-line. And this is without needing to have access to a Mac. On many platforms (e.g., x86 and x86_64), this interpreter will come with a JIT compiler.

So, with almost no compilation you will have three of the heavy-weight JavaScript engines at your disposal.

Addendum

Once you have things installed, you can simply create files with the #!/usr/bin/js shebang line and things will just work:

$ cat foo.js 
#!/usr/bin/js

console.log("Hello, world!");
$ ls -lAF /usr/bin/js /etc/alternatives/js /usr/bin/nodejs
lrwxrwxrwx 1 root root      15 Jul 16 04:26 /etc/alternatives/js -> /usr/bin/nodejs*
lrwxrwxrwx 1 root root      20 Jul 16 04:26 /usr/bin/js -> /etc/alternatives/js*
-rwxr-xr-x 1 root root 1422004 Apr 28 20:31 /usr/bin/nodejs*
$ chmod a+x foo.js 
$ ./foo.js 
Hello, world!
$ js ./foo.js
Hello, world!
$

How to import Angular Material in project?

UPDATE for Angular 9.0.1

Since this version there is no barrel file for massive exports in the root index.d.ts. The assets imports should be:

import { NgModule } from '@angular/core';
import { MatCardModule } from '@angular/material/card';
import { MatButtonModule} from '@angular/material/button';
import { MatMenuModule } from '@angular/material/menu';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatIconModule } from '@angular/material/icon';

import {
  MatButtonModule,
  MatMenuModule,
  MatToolbarModule,
  MatIconModule,
  MatCardModule
} from '@angular/material';

@NgModule({
  imports: [
    MatButtonModule,
    MatMenuModule,
    MatToolbarModule,
    MatIconModule,
    MatCardModule
  ],
  exports: [
    MatButtonModule,
    MatMenuModule,
    MatToolbarModule,
    MatIconModule,
    MatCardModule
  ]
})
export class MaterialModule {}

source: @angular/material/index.d.ts' is not a module


MaterialModule was depreciated in version 2.0.0-beta.3 and it has been removed completely in version 2.0.0-beta.11. See this CHANGELOG for more details. Please go through the breaking changes.

Breaking changes

  • Angular Material now requires Angular 4.4.3 or greater
  • MaterialModule has been removed.
  • For beta.11, we've made the decision to deprecate the "md" prefix completely and use "mat" moving forward.

Please go through CHANGELOG we will get more answer!

Example shown below cmd

npm install --save @angular/material @angular/animations @angular/cdk
npm install --save angular/material2-builds angular/cdk-builds

Create file (material.module.ts) inside the 'app' folder

import { NgModule } from '@angular/core';

import {
  MatButtonModule,
  MatMenuModule,
  MatToolbarModule,
  MatIconModule,
  MatCardModule
} from '@angular/material';

@NgModule({
  imports: [
    MatButtonModule,
    MatMenuModule,
    MatToolbarModule,
    MatIconModule,
    MatCardModule
  ],
  exports: [
    MatButtonModule,
    MatMenuModule,
    MatToolbarModule,
    MatIconModule,
    MatCardModule
  ]
})
export class MaterialModule {}

import on app.module.ts

import { MaterialModule } from './material.module';

Your component html file

<div>
  <mat-toolbar color="primary">
    <span><mat-icon>mood</mat-icon></span>

    <span>Yay, Material in Angular 2!</span>

    <button mat-icon-button [mat-menu-trigger-for]="menu">
      <mat-icon>more_vert</mat-icon>
    </button>
  </mat-toolbar>
  <mat-menu x-position="before" #menu="matMenu">
    <button mat-menu-item>Option 1</button>
    <button mat-menu-item>Option 2</button>
  </mat-menu>

  <mat-card>
    <button mat-button>All</button>
    <button mat-raised-button>Of</button>
    <button mat-raised-button color="primary">The</button>
    <button mat-raised-button color="accent">Buttons</button>
  </mat-card>

  <span class="done">
    <button mat-fab>
      <mat-icon>check circle</mat-icon>
    </button>
  </span>
</div>

Add global css 'style.css'

@import 'https://fonts.googleapis.com/icon?family=Material+Icons';
@import '~@angular/material/prebuilt-themes/indigo-pink.css'; 

Your component css

body {
  margin: 0;
  font-family: Roboto, sans-serif;
}

mat-card {
  max-width: 80%;
  margin: 2em auto;
  text-align: center;
}

mat-toolbar-row {
  justify-content: space-between;
}

.done {
  position: fixed;
  bottom: 20px;
  right: 20px;
  color: white;
}

If any one didn't get output use below instruction

instead of above interface (material.module.ts) u can directly use below code also in the app.module.ts.

import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MdButtonModule, MdCardModule, MdMenuModule, MdToolbarModule, MdIconModule, MatAutocompleteModule, MatInputModule,MatFormFieldModule } from '@angular/material';

So this case u don't want to import

import { MaterialModule } from './material.module';

in the app.module.ts

How to find the nearest parent of a Git branch?

If you use Source Tree look at your commit details > Parents > then you'll see commit numbers underlined (links)

Hiding the R code in Rmarkdown/knit and just showing the results

Alternatively, you can also parse a standard markdown document (without code blocks per se) on the fly by the markdownreports package.

possible EventEmitter memory leak detected

Thanks to RLaaa for giving me an idea how to solve the real problem/root cause of the warning. Well in my case it was MySQL buggy code.

Providing you wrote a Promise with code inside like this:

pool.getConnection((err, conn) => {

  if(err) reject(err)

  const q = 'SELECT * from `a_table`'

  conn.query(q, [], (err, rows) => {

    conn.release()

    if(err) reject(err)

    // do something
  })

  conn.on('error', (err) => {

     reject(err)
  })
})

Notice there is a conn.on('error') listener in the code. That code literally adding listener over and over again depends on how many times you call the query. Meanwhile if(err) reject(err) does the same thing.

So I removed the conn.on('error') listener and voila... solved! Hope this helps you.

How can I obfuscate (protect) JavaScript?

Try this tool Javascript Obfuscator

I used it on my HTML5 game not only it reduced it size from 950KB to 150 but also made the source code unreadable closure compilers and minifiers are reversable I personally dont know how to reverse this obfuscation.

Is there a timeout for idle PostgreSQL connections?

Another option is set this value "tcp_keepalives_idle". Check more in documentation https://www.postgresql.org/docs/10/runtime-config-connection.html.

are there dictionaries in javascript like python?

I realize this is an old question, but it pops up in Google when you search for 'javascript dictionaries', so I'd like to add to the above answers that in ECMAScript 6, the official Map object has been introduced, which is a dictionary implementation:

var dict = new Map();
dict.set("foo", "bar");

//returns "bar"
dict.get("foo");

Unlike javascript's normal objects, it allows any object as a key:

var foo = {};
var bar = {};
var dict = new Map();
dict.set(foo, "Foo");
dict.set(bar, "Bar");

//returns "Bar"
dict.get(bar);

//returns "Foo"
dict.get(foo);

//returns undefined, as {} !== foo and {} !== bar
dict.get({});

How to retrieve available RAM from Windows command line?

Here is a pure Java solution actually:

public static long getFreePhysicalMemory()
{
    com.sun.management.OperatingSystemMXBean bean =
            (com.sun.management.OperatingSystemMXBean)
                    java.lang.management.ManagementFactory.getOperatingSystemMXBean();
    return bean.getFreePhysicalMemorySize();
}

Unsuccessful append to an empty NumPy array

Here's the result of running your code in Ipython. Note that result is a (2,0) array, 2 rows, 0 columns, 0 elements. The append produces a (2,) array. result[0] is (0,) array. Your error message has to do with trying to assign that 2 item array into a size 0 slot. Since result is dtype=float64, only scalars can be assigned to its elements.

In [65]: result=np.asarray([np.asarray([]),np.asarray([])])

In [66]: result
Out[66]: array([], shape=(2, 0), dtype=float64)

In [67]: result[0]
Out[67]: array([], dtype=float64)

In [68]: np.append(result[0],[1,2])
Out[68]: array([ 1.,  2.])

np.array is not a Python list. All elements of an array are the same type (as specified by the dtype). Notice also that result is not an array of arrays.

Result could also have been built as

ll = [[],[]]
result = np.array(ll)

while

ll[0] = [1,2]
# ll = [[1,2],[]]

the same is not true for result.

np.zeros((2,0)) also produces your result.

Actually there's another quirk to result.

result[0] = 1

does not change the values of result. It accepts the assignment, but since it has 0 columns, there is no place to put the 1. This assignment would work in result was created as np.zeros((2,1)). But that still can't accept a list.

But if result has 2 columns, then you can assign a 2 element list to one of its rows.

result = np.zeros((2,2))
result[0] # == [0,0]
result[0] = [1,2]

What exactly do you want result to look like after the append operation?

Insert line break inside placeholder attribute of a textarea?

Check out this solution with custom placeholder.

  • You get multiline placeholder that works in all browsers (including Firefox)
  • It is posible to customise placeholder as you want

Demo on fiddle.

_x000D_
_x000D_
$(document).on('input', '#textArea', function () {_x000D_
 _x000D_
        if ($('#textArea').val()) {_x000D_
            $('#placeholderDiv').hide();_x000D_
        } else {_x000D_
            $('#placeholderDiv').show();_x000D_
        }   _x000D_
});
_x000D_
#textAreaWrap {_x000D_
    position: relative;_x000D_
    background-color: white;_x000D_
}_x000D_
_x000D_
#textArea {_x000D_
    position: relative;_x000D_
    z-index: 1;_x000D_
    width: 350px;_x000D_
    height: 100px;_x000D_
    min-height: 100px;_x000D_
    padding: 6px 12px;_x000D_
    resize: vertical;_x000D_
    background-color: transparent;_x000D_
    /* When set background-color: transparent - Firefox  displays_x000D_
    unpleasant textarea border. Set border style to fix it.*/_x000D_
    border: 1px solid #a5a5a5;_x000D_
}_x000D_
_x000D_
#placeholderDiv {_x000D_
    position: absolute;_x000D_
    top: 0;_x000D_
    padding: 6px 13px;_x000D_
    color: #a5a5a5;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="textAreaWrap">_x000D_
    _x000D_
<textarea id="textArea"></textarea>_x000D_
_x000D_
<!-- Check here. If textarea has content -_x000D_
     set for this div attribute style="display: none;" -->_x000D_
<div id="placeholderDiv">Multiline textarea<br>_x000D_
                         placeholder<br>_x000D_
                         <br>_x000D_
                         that works in Firefox</div>_x000D_
    _x000D_
</div>
_x000D_
_x000D_
_x000D_

How to pass a value to razor variable from javascript variable?

But it would be possible if one were used in place of the variable in @html.Hidden field. As in this example.

@Html.Hidden("myVar", 0);

set the field per script:

<script>
function setMyValue(value) {
     $('#myVar').val(value);       
}
</script>

I hope I can at least offer no small Workaround.

Caused by: org.flywaydb.core.api.FlywayException: Validate failed. Migration Checksum mismatch for migration 2

I had the same issue and deleted the complete schema from the database, yet the issue remained.

I solved this by running the repair() command of flyway:

flyway.repair();

Alternatively with Flyway Maven plugin:

mvn flyway:repair

Maven plugin addition into pom.xml:

<plugin>
    <groupId>org.flywaydb</groupId>
    <artifactId>flyway-maven-plugin</artifactId>
    <version>5.2.4</version>
</plugin>

BTW: I did not find what exactly went wrong.

With Gradle (as per comment from Raf):

./gradlew flywayRepair

Xcode 6 Bug: Unknown class in Interface Builder file

I faced the problem when I ported the storyboard from Swift project to Objective-c project, noticing vvkuznetsov's answer, it turned out the two project using same identifier. I "Product -> Clean" and tap Enter key on the Module and Class text field. the issue went away.

How to print color in console using System.out.println?

Here are a list of colors in a Java class with public static fields

Usage

System.out.println(ConsoleColors.RED + "RED COLORED" +
ConsoleColors.RESET + " NORMAL");


Note Don't forget to use the RESET after printing as the effect will remain if it's not cleared


public class ConsoleColors {
    // Reset
    public static final String RESET = "\033[0m";  // Text Reset

    // Regular Colors
    public static final String BLACK = "\033[0;30m";   // BLACK
    public static final String RED = "\033[0;31m";     // RED
    public static final String GREEN = "\033[0;32m";   // GREEN
    public static final String YELLOW = "\033[0;33m";  // YELLOW
    public static final String BLUE = "\033[0;34m";    // BLUE
    public static final String PURPLE = "\033[0;35m";  // PURPLE
    public static final String CYAN = "\033[0;36m";    // CYAN
    public static final String WHITE = "\033[0;37m";   // WHITE

    // Bold
    public static final String BLACK_BOLD = "\033[1;30m";  // BLACK
    public static final String RED_BOLD = "\033[1;31m";    // RED
    public static final String GREEN_BOLD = "\033[1;32m";  // GREEN
    public static final String YELLOW_BOLD = "\033[1;33m"; // YELLOW
    public static final String BLUE_BOLD = "\033[1;34m";   // BLUE
    public static final String PURPLE_BOLD = "\033[1;35m"; // PURPLE
    public static final String CYAN_BOLD = "\033[1;36m";   // CYAN
    public static final String WHITE_BOLD = "\033[1;37m";  // WHITE

    // Underline
    public static final String BLACK_UNDERLINED = "\033[4;30m";  // BLACK
    public static final String RED_UNDERLINED = "\033[4;31m";    // RED
    public static final String GREEN_UNDERLINED = "\033[4;32m";  // GREEN
    public static final String YELLOW_UNDERLINED = "\033[4;33m"; // YELLOW
    public static final String BLUE_UNDERLINED = "\033[4;34m";   // BLUE
    public static final String PURPLE_UNDERLINED = "\033[4;35m"; // PURPLE
    public static final String CYAN_UNDERLINED = "\033[4;36m";   // CYAN
    public static final String WHITE_UNDERLINED = "\033[4;37m";  // WHITE

    // Background
    public static final String BLACK_BACKGROUND = "\033[40m";  // BLACK
    public static final String RED_BACKGROUND = "\033[41m";    // RED
    public static final String GREEN_BACKGROUND = "\033[42m";  // GREEN
    public static final String YELLOW_BACKGROUND = "\033[43m"; // YELLOW
    public static final String BLUE_BACKGROUND = "\033[44m";   // BLUE
    public static final String PURPLE_BACKGROUND = "\033[45m"; // PURPLE
    public static final String CYAN_BACKGROUND = "\033[46m";   // CYAN
    public static final String WHITE_BACKGROUND = "\033[47m";  // WHITE

    // High Intensity
    public static final String BLACK_BRIGHT = "\033[0;90m";  // BLACK
    public static final String RED_BRIGHT = "\033[0;91m";    // RED
    public static final String GREEN_BRIGHT = "\033[0;92m";  // GREEN
    public static final String YELLOW_BRIGHT = "\033[0;93m"; // YELLOW
    public static final String BLUE_BRIGHT = "\033[0;94m";   // BLUE
    public static final String PURPLE_BRIGHT = "\033[0;95m"; // PURPLE
    public static final String CYAN_BRIGHT = "\033[0;96m";   // CYAN
    public static final String WHITE_BRIGHT = "\033[0;97m";  // WHITE

    // Bold High Intensity
    public static final String BLACK_BOLD_BRIGHT = "\033[1;90m"; // BLACK
    public static final String RED_BOLD_BRIGHT = "\033[1;91m";   // RED
    public static final String GREEN_BOLD_BRIGHT = "\033[1;92m"; // GREEN
    public static final String YELLOW_BOLD_BRIGHT = "\033[1;93m";// YELLOW
    public static final String BLUE_BOLD_BRIGHT = "\033[1;94m";  // BLUE
    public static final String PURPLE_BOLD_BRIGHT = "\033[1;95m";// PURPLE
    public static final String CYAN_BOLD_BRIGHT = "\033[1;96m";  // CYAN
    public static final String WHITE_BOLD_BRIGHT = "\033[1;97m"; // WHITE

    // High Intensity backgrounds
    public static final String BLACK_BACKGROUND_BRIGHT = "\033[0;100m";// BLACK
    public static final String RED_BACKGROUND_BRIGHT = "\033[0;101m";// RED
    public static final String GREEN_BACKGROUND_BRIGHT = "\033[0;102m";// GREEN
    public static final String YELLOW_BACKGROUND_BRIGHT = "\033[0;103m";// YELLOW
    public static final String BLUE_BACKGROUND_BRIGHT = "\033[0;104m";// BLUE
    public static final String PURPLE_BACKGROUND_BRIGHT = "\033[0;105m"; // PURPLE
    public static final String CYAN_BACKGROUND_BRIGHT = "\033[0;106m";  // CYAN
    public static final String WHITE_BACKGROUND_BRIGHT = "\033[0;107m";   // WHITE
}

Visual Studio 2015 doesn't have cl.exe

In Visual Studio 2019 you can find cl.exe inside

32-BIT : C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.20.27508\bin\Hostx86\x86
64-BIT : C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.20.27508\bin\Hostx64\x64

Before trying to compile either run vcvars32 for 32-Bit compilation or vcvars64 for 64-Bit.

32-BIT : "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvars32.bat"
64-BIT : "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvars64.bat"

If you can't find the file or the directory, try going to C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC and see if you can find a folder with a version number. If you can't, then you probably haven't installed C++ through the Visual Studio Installation yet.

Is there a way to select sibling nodes?

There are a few ways to do it.

Either one of the following should do the trick.

// METHOD A (ARRAY.FILTER, STRING.INDEXOF)
var siblings = function(node, children) {
    siblingList = children.filter(function(val) {
        return [node].indexOf(val) != -1;
    });
    return siblingList;
}

// METHOD B (FOR LOOP, IF STATEMENT, ARRAY.PUSH)
var siblings = function(node, children) {
    var siblingList = [];
    for (var n = children.length - 1; n >= 0; n--) {
        if (children[n] != node) {
            siblingList.push(children[n]);
        }  
    }
    return siblingList;
}

// METHOD C (STRING.INDEXOF, ARRAY.SPLICE)
var siblings = function(node, children) {
   siblingList = children;
   index = siblingList.indexOf(node);
   if(index != -1) {
       siblingList.splice(index, 1);
   }
   return siblingList;
}

FYI: The jQuery code-base is a great resource for observing Grade A Javascript.

Here is an excellent tool that reveals the jQuery code-base in a very streamlined way. http://james.padolsey.com/jquery/

How to Run a jQuery or JavaScript Before Page Start to Load

Maybe you are using:

$(document).ready(function(){
   // Your code here
 });

Try this instead:

window.onload = function(){  }

Relative instead of Absolute paths in Excel VBA

if current directory of the operating system is the path of the workbook you are using, Workbooks.Open FileName:= "TRICATEndurance Summary.html" would suffice. if you are making calculations with the path, you can refer to current directory as . and then \ to tell the file is in that dir, and in case you have to change the os's current directory to your workbook's path, you can use ChDrive and ChDir to do so.

ChDrive ThisWorkbook.Path
ChDir ThisWorkbook.Path
Workbooks.Open FileName:= ".\TRICATEndurance Summary.html"

Loop Through Each HTML Table Column and Get the Data using jQuery

try this

    $("#mprDetailDataTable tr:gt(0)").each(function () {
        var this_row = $(this);
        var productId = $.trim(this_row.find('td:eq(0)').html());//td:eq(0) means first td of this row
        var product = $.trim(this_row.find('td:eq(1)').html())
        var Quantity = $.trim(this_row.find('td:eq(2)').html())
    });

form action with javascript

I always include the js files in the head of the html document and them in the action just call the javascript function. Something like this:

action="javascript:checkout()"

You try this?

Don't forget include the script reference in the html head.

I don't know cause of that works in firefox. Regards.

Passing multiple values for a single parameter in Reporting Services

I'm new to the site, and couldn't figure how to comment on a previous answer, which is what I feel this should be. I also couldn't up vote Jeff's post, which I believe gave me my answer. Anyways...

While I can see how some of the great posts, and subsequent tweaks, work, I only have read access to the database, so no UDF, SP or view-based solutions work for me. So Ed Harper's solution looked good, except for VenkateswarluAvula's comment that you can not pass a comma-separated string as a parameter into an WHERE IN clause and expect it to work as you need. But Jeff's solution to the ORACLE 10g fills that gap. I put those together with Russell Christopher's blog post at http://blogs.msdn.com/b/bimusings/archive/2007/05/07/how-do-you-set-select-all-as-the-default-for-multi-value-parameters-in-reporting-services.aspx and I have my solution:

Create your multi-select parameter MYPARAMETER using whatever source of available values (probably a dataset). In my case, the multi-select was from a bunch of TEXT entries, but I'm sure with some tweaking it would work with other types. If you want Select All to be the default position, set the same source as the default. This gives you your user interface, but the parameter created is not the parameter passed to my SQL.

Skipping ahead to the SQL, and Jeff's solution to the WHERE IN (@MYPARAMETER) problem, I have a problem all my own, in that 1 of the values ('Charge') appears in one of the other values ('Non Charge'), meaning the CHARINDEX might find a false-positive. I needed to search the parameter for the delimited value both before and after. This means I need to make sure the comma-separated list has a leading and trailling comma as well. And this is my SQL snippet:

where ...
and CHARINDEX(',' + pitran.LINEPROPERTYID + ',', @MYPARAMETER_LIST) > 0

The bit in the middle is to create another parameter (hidden in production, but not while developing) with:

  • A name of MYPARAMETER_LIST
  • A type of Text
  • A single available value of ="," + join(Parameters!MYPARAMETER.Value,",") + "," and a label that
    doesn't really matter (since it will not be displayed).
  • A default value exactly the same
  • Just to be sure, I set Always Refresh in both parameters' Advanced properties

It is this parameter which gets passed to SQL, which just happens to be a searchable string but which SQL handles like any piece of text.

I hope putting these fragments of answers together helps somebody find what they're looking for.

Android transparent status bar and actionbar

Just add these lines of code to your activity/fragment java file:

getWindow().setFlags(
    WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
    WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
);

AVD Manager - No system image installed for this target

Open your Android SDK Manager and ensure that you download/install a system image for the API level you are developing with.

What's causing my java.net.SocketException: Connection reset?

I know this thread is little old, but would like to add my 2 cents. We had the same "connection reset" error right after our one of the releases.

The root cause was, our apache server was brought down for deployment. All our third party traffic goes thru apache and we were getting connection reset error because of it being down.

HTTP response code for POST when resource already exists

I know it's been ages but I will leave an answer here which I see fit.

I think the best will be to use HTTP_306_RESERVED.

Bootstrap: How do I identify the Bootstrap version?

You can also check the bootstrap version via the javascript console in the browser:

$.fn.tooltip.Constructor.VERSION // => "3.3.7"

Credit: https://stackoverflow.com/a/43233731/1608226

Posting this here because I always come across this question when I forget to include JavaScript in the search and wind up on this question instead of the one above. If this helps you, be sure to upvote that answer as well.

Note: For older versions of bootstrap (less than 3 or so), you'll proably need to search the page's JavaScript or CSS files for the bootstrap version. Just came across this on an app using bootstrap 2.3.2. In this case, the (current) top answer is likely the correct one, you'll need to search the source code for the bootstrap find what version it uses. (Added 9/18/2020, though was in comment since 8/13/2020)

How to execute multiple commands in a single line

Googling gives me this:


Command A & Command B

Execute Command A, then execute Command B (no evaluation of anything)


Command A | Command B

Execute Command A, and redirect all its output into the input of Command B


Command A && Command B

Execute Command A, evaluate the errorlevel after running and if the exit code (errorlevel) is 0, only then execute Command B


Command A || Command B

Execute Command A, evaluate the exit code of this command and if it's anything but 0, only then execute Command B


How can I replace text with CSS?

I had better luck setting the font-size: 0 of the outer element, and the font-size of the :after selector to whatever I needed.

How to make correct date format when writing data to Excel

Try using

DateTime.ToOADate()

And putting that as a double in the cell. There could be issues with Excel on Mac Systems (it uses a different datetime-->double conversion), but it should work well for most cases.

Hope this helps.

Is there a concise way to iterate over a stream with indices in Java 8?

With a List you can try

List<String> strings = new ArrayList<>(Arrays.asList("First", "Second", "Third", "Fourth", "Fifth")); // An example list of Strings
strings.stream() // Turn the list into a Stream
    .collect(HashMap::new, (h, o) -> h.put(h.size(), o), (h, o) -> {}) // Create a map of the index to the object
        .forEach((i, o) -> { // Now we can use a BiConsumer forEach!
            System.out.println(String.format("%d => %s", i, o));
        });

Output:

0 => First
1 => Second
2 => Third
3 => Fourth
4 => Fifth

Android Fragment no view found for ID?

I had this problem (when building my UI in code) and it was caused by my ViewPager (that showed Fragments) not having an ID set, so I simply used pager.setID(id) and then it worked.

This page helped me figure that out.

How to get cumulative sum

Once the table is created -

select 
    A.id, A.SomeNumt, SUM(B.SomeNumt) as sum
    from @t A, @t B where A.id >= B.id
    group by A.id, A.SomeNumt

order by A.id

Get the client IP address using PHP

It also works fine for internal IP addresses:

 function get_client_ip()
 {
      $ipaddress = '';
      if (getenv('HTTP_CLIENT_IP'))
          $ipaddress = getenv('HTTP_CLIENT_IP');
      else if(getenv('HTTP_X_FORWARDED_FOR'))
          $ipaddress = getenv('HTTP_X_FORWARDED_FOR');
      else if(getenv('HTTP_X_FORWARDED'))
          $ipaddress = getenv('HTTP_X_FORWARDED');
      else if(getenv('HTTP_FORWARDED_FOR'))
          $ipaddress = getenv('HTTP_FORWARDED_FOR');
      else if(getenv('HTTP_FORWARDED'))
          $ipaddress = getenv('HTTP_FORWARDED');
      else if(getenv('REMOTE_ADDR'))
          $ipaddress = getenv('REMOTE_ADDR');
      else
          $ipaddress = 'UNKNOWN';

      return $ipaddress;
 }

Script to kill all connections to a database (More than RESTRICTED_USER ROLLBACK)

Little known: the GO sql statement can take an integer for the number of times to repeat previous command.

So if you:

ALTER DATABASE [DATABASENAME] SET SINGLE_USER
GO

Then:

USE [DATABASENAME]
GO 2000

This will repeat the USE command 2000 times, force deadlock on all other connections, and take ownership of the single connection. (Giving your query window sole access to do as you wish.)

Dictionary with list of strings as value

I'd wrap the dictionary in another class:

public class MyListDictionary
{

    private Dictionary<string, List<string>> internalDictionary = new Dictionary<string,List<string>>();

    public void Add(string key, string value)
    {
        if (this.internalDictionary.ContainsKey(key))
        {
            List<string> list = this.internalDictionary[key];
            if (list.Contains(value) == false)
            {
                list.Add(value);
            }
        }
        else
        {
            List<string> list = new List<string>();
            list.Add(value);
            this.internalDictionary.Add(key, list);
        }
    }

}

Are these methods thread safe?

It follows the convention that static methods should be thread-safe, but actually in v2 that static api is a proxy to an instance method on a default instance: in the case protobuf-net, it internally minimises contention points, and synchronises the internal state when necessary. Basically the library goes out of its way to do things right so that you can have simple code.

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

SelThroughJava's answer was very helpful I had to modify a bit to my code to be worked . I used https://mvnrepository.com/artifact/org.apache.poi/poi and https://mvnrepository.com/artifact/org.testng/testng as dependencies . Full code is given below with exact imports.

 import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;

    import org.apache.poi.hssf.usermodel.HSSFCell;
    import org.apache.poi.hssf.util.CellReference;
    import org.apache.poi.sl.usermodel.Sheet;
    import org.apache.poi.ss.usermodel.Cell;
    import org.apache.poi.ss.usermodel.CellType;
    import org.apache.poi.ss.usermodel.CellValue;
    import org.apache.poi.ss.usermodel.FormulaEvaluator;
    import org.apache.poi.ss.usermodel.Row;
    import org.apache.poi.ss.usermodel.Workbook;
    import org.apache.poi.ss.usermodel.WorkbookFactory;
    import org.apache.poi.xssf.usermodel.XSSFWorkbook;


    public class ReadExcelFormulaValue {

        private static final CellType NUMERIC = null;
        public static void main(String[] args) {
            try {
                readFormula();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        public static void readFormula() throws IOException {
            FileInputStream fis = new FileInputStream("C:eclipse-workspace\\sam-webdbriver-diaries\\resources\\tUser_WS.xls");
            org.apache.poi.ss.usermodel.Workbook workbook = WorkbookFactory.create(fis);
            org.apache.poi.ss.usermodel.Sheet sheet = workbook.getSheetAt(0);

            FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();

            CellReference cellReference = new CellReference("G2"); // pass the cell which contains the formula
            Row row = sheet.getRow(cellReference.getRow());
            Cell cell = row.getCell(cellReference.getCol());

            CellValue cellValue = evaluator.evaluate(cell);
            System.out.println("Cell type month  is "+cellValue.getCellTypeEnum());
            System.out.println("getNumberValue month is  "+cellValue.getNumberValue());     
          //  System.out.println("getStringValue "+cellValue.getStringValue());


            cellReference = new CellReference("H2"); // pass the cell which contains the formula
             row = sheet.getRow(cellReference.getRow());
             cell = row.getCell(cellReference.getCol());

            cellValue = evaluator.evaluate(cell);
            System.out.println("getNumberValue DAY is  "+cellValue.getNumberValue());    


        }

    }

Add placeholder text inside UITextView in Swift?

A simple and quick solution that works for me is:

@IBDesignable
class PlaceHolderTextView: UITextView {

    @IBInspectable var placeholder: String = "" {
         didSet{
             updatePlaceHolder()
        }
    }

    @IBInspectable var placeholderColor: UIColor = UIColor.gray {
        didSet {
            updatePlaceHolder()
        }
    }

    private var originalTextColor = UIColor.darkText
    private var originalText: String = ""

    private func updatePlaceHolder() {

        if self.text == "" || self.text == placeholder  {

            self.text = placeholder
            self.textColor = placeholderColor
            if let color = self.textColor {

                self.originalTextColor = color
            }
            self.originalText = ""
        } else {
            self.textColor = self.originalTextColor
            self.originalText = self.text
        }

    }

    override func becomeFirstResponder() -> Bool {
        let result = super.becomeFirstResponder()
        self.text = self.originalText
        self.textColor = self.originalTextColor
        return result
    }
    override func resignFirstResponder() -> Bool {
        let result = super.resignFirstResponder()
        updatePlaceHolder()

        return result
    }
}

Convert List to Pandas Dataframe Column

Example:

['Thanks You',
 'Its fine no problem',
 'Are you sure']

code block:

import pandas as pd
df = pd.DataFrame(lst)

Output:

    0
0   Thanks You
1   Its fine no problem
2   Are you sure

It is not recommended to remove the column names of the panda dataframe. but if you still want your data frame without header(as per the format you posted in the question) you can do this:

df = pd.DataFrame(lst)    
df.columns = ['']

Output will be like this:

0   Thanks You
1   Its fine no problem
2   Are you sure

or

df = pd.DataFrame(lst).to_string(header=False)

But the output will be a list instead of a dataframe:

0           Thanks You
1  Its fine no problem
2         Are you sure

Hope this helps!!

Chmod 777 to a folder and all contents

If you are going for a console command it would be:

chmod -R 777 /www/store. The -R (or --recursive) options make it recursive.

Or if you want to make all the files in the current directory have all permissions type:

chmod -R 777 ./

If you need more info about chmod command see: File permission

Android: Difference between Parcelable and Serializable?

The Serializable interface can be used the same way as the Parcelable one, resulting in (not much) better performances. Just overwrite those two methods to handle manual marshalling and unmarshalling process:

private void writeObject(java.io.ObjectOutputStream out)
    throws IOException
private void readObject(java.io.ObjectInputStream in)
    throws IOException, ClassNotFoundException

Still, it seems to me that when developing native Android, using the Android api is the way to go.

See :

How to remove only 0 (Zero) values from column in excel 2010

I selected columns that I want to delete 0 values then clicked DATA > FILTER. In column's header there is a filter icon appears. I clicked on that icon and selected only 0 values and clicked OK. Only 0 values becomes selected. Finally clear content OR use DELETE button. Problem Solved!

How to trim a string after a specific character in java

Try this:

String result = "34.1 -118.33\n<!--ABCDEFG-->";
result = result.substring(0, result.indexOf("\n"));

Where is body in a nodejs http.get response?

The data event is fired multiple times with 'chunks' of the body as they are downloaded and an end event when all chunks have been downloaded.

With Node supporting Promises now, I created a simple wrapper to return the concatenated chunks through a Promise:

const httpGet = url => {
  return new Promise((resolve, reject) => {
    http.get(url, res => {
      res.setEncoding('utf8');
      let body = ''; 
      res.on('data', chunk => body += chunk);
      res.on('end', () => resolve(body));
    }).on('error', reject);
  });
};

You can call it from an async function with:

const body = await httpGet('http://www.somesite.com');

SQL Error: ORA-12899: value too large for column

In my case I'm using C# OracleCommand with OracleParameter, and I set all the the parameters Size property to max length of each column, then the error solved.

OracleParameter parm1 = new OracleParameter();
param1.OracleDbType = OracleDbType.Varchar2;
param1.Value = "test1";
param1.Size = 8;

OracleParameter parm2 = new OracleParameter();
param2.OracleDbType = OracleDbType.Varchar2;
param2.Value = "test1";
param2.Size = 12;

Detect if a jQuery UI dialog box is open

If you read the docs.

$('#mydialog').dialog('isOpen')

This method returns a Boolean (true or false), not a jQuery object.

Aligning textviews on the left and right edges in Android layout

Use a RelativeLayout with layout_alignParentLeft and layout_alignParentRight:

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/RelativeLayout01" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"
    android:padding="10dp">

    <TextView 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true" 
        android:id="@+id/mytextview1"/>

    <TextView 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_alignParentRight="true" 
        android:id="@+id/mytextview2"/>

</RelativeLayout>

Also, you should probably be using dip (or dp) rather than sp in your layout. sp reflect text settings as well as screen density so they're usually only for sizing text items.

How to use mod operator in bash?

You must put your mathematical expressions inside $(( )).

One-liner:

for i in {1..600}; do wget http://example.com/search/link$(($i % 5)); done;

Multiple lines:

for i in {1..600}; do
    wget http://example.com/search/link$(($i % 5))
done

Difference between Console.Read() and Console.ReadLine()?

Console.Read() is used to read next charater from the standard input stream. When we want to read only the single character then use Console.Read().

Console.ReadLine() is used to read aline of characters from the standard input stream. when we want to read a line of characters use Console.ReadLine().

How to determine the longest increasing subsequence using dynamic programming?

Here is my Leetcode solution using Binary Search:->

class Solution:
    def binary_search(self,s,x):
        low=0
        high=len(s)-1
        flag=1
        while low<=high:
              mid=(high+low)//2
              if s[mid]==x:
                 flag=0
                 break
              elif s[mid]<x:
                  low=mid+1
              else:
                 high=mid-1
        if flag:
           s[low]=x
        return s

    def lengthOfLIS(self, nums: List[int]) -> int:
         if not nums:
            return 0
         s=[]
         s.append(nums[0])
         for i in range(1,len(nums)):
             if s[-1]<nums[i]:
                s.append(nums[i])
             else:
                 s=self.binary_search(s,nums[i])
         return len(s)

Difference between signature versions - V1 (Jar Signature) and V2 (Full APK Signature) while generating a signed APK in Android Studio?

It is written here that "By default, Android Studio 2.2 and the Android Plugin for Gradle 2.2 sign your app using both APK Signature Scheme v2 and the traditional signing scheme, which uses JAR signing."

As it seems that these new checkboxes appeared with Android 2.3, I understand that my previous versions of Android Studio (at least the 2.2) did sign with both signatures. So, to continue as I did before, I think that it is better to check both checkboxes.

EDIT March 31st, 2017 : submitted several apps with both signatures => no problem :)

Make absolute positioned div expand parent div height

"You either use fixed heights or you need to involve JS."

Here is the JS example:

---------- jQuery JS example--------------------

    function findEnvelopSizeOfAbsolutelyPositionedChildren(containerSelector){
        var maxX = $(containerSelector).width(), maxY = $(containerSelector).height();

        $(containerSelector).children().each(function (i){
            if (maxX < parseInt($(this).css('left')) + $(this).width()){
                maxX = parseInt($(this).css('left')) + $(this).width();
            }
            if (maxY < parseInt($(this).css('top')) + $(this).height()){
                maxY = parseInt($(this).css('top')) + $(this).height();
            }
        });
        return {
            'width': maxX,
            'height': maxY
        }
    }

    var specBodySize = findEnvelopSizeOfAbsolutelyPositionedSubDivs("#SpecBody");
    $("#SpecBody").width(specBodySize.width);
    $("#SpecBody").height(specBodySize.height);