Programs & Examples On #Asp.net routing

ASP.NET routing enables you to use URLs that do not have to map to specific files in a Web site in both ASP.NET MVC and ASP.NET Webforms.

How to remove from a map while iterating it?

The C++20 draft contains the convenience function std::erase_if.

So you can use that function to do it as a one-liner.

std::map<K, V> map_obj;
//calls needs_removing for each element and erases it, if true was reuturned
std::erase_if(map_obj,needs_removing);
//if you need to pass only part of the key/value pair
std::erase_if(map_obj,[](auto& kv){return needs_removing(kv.first);});

How to delete $_POST variable upon pressing 'Refresh' button on browser with PHP?

I can see this is an old thread, just thought I'd give my 2cents. Not sure if it would fit every scenario, but this is the method I've been successfully using for a number of years:

session_start();
if($_POST == $_SESSION['oldPOST']) $_POST = array(); else $_SESSION['oldPOST'] = $_POST;

Doesn't really delete POST-ed values from the browser, but as far as your php script below these lines is concerned, there is no more POST variables.

What does "-ne" mean in bash?

"not equal" So in this case, $RESULT is tested to not be equal to zero.

However, the test is done numerically, not alphabetically:

n1 -ne n2     True if the integers n1 and n2 are not algebraically equal.

compared to:

s1 != s2      True if the strings s1 and s2 are not identical.

How do I delete unpushed git commits?

If you want to move that commit to another branch, get the SHA of the commit in question

git rev-parse HEAD

Then switch the current branch

git checkout other-branch

And cherry-pick the commit to other-branch

git cherry-pick <sha-of-the-commit>

How do we update URL or query strings using javascript/jQuery without reloading the page?

You can use :

window.history.pushState('obj', 'newtitle', newUrlWithQueryString)

Get image dimensions

You can use the getimagesize function like this:

list($width, $height) = getimagesize('path to image');
echo "width: " . $width . "<br />";
echo "height: " .  $height;

Installing J2EE into existing eclipse IDE

For Mars (Eclipse 4.5) and WTP 3.7 use this link. http://download.eclipse.org/webtools/repository/mars/

  1. In Eclipse select Help - Install New Software.
  2. In the "Work with:" text box place the above link.
  3. Press Enter.
  4. Select the WTP version you need (3.7.0 or 3.7.1 as of today) & follow the prompts.

Undefined columns selected when subsetting data frame

You want rows where that condition is true so you need a comma:

data[data$Ozone > 14, ]

What's the difference between JavaScript and JScript?

Jscript is a .NET language similar to C#, with the same capabilities and access to all the .NET functions.

JavaScript is run on the ASP Classic server. Use Classic ASP to run the same JavaScript that you have on the Client (excluding HTML5 capabilities). I only have one set of code this way for most of my code.

I run .ASPX JScript when I require Image and Binary File functions, (among many others) that are not in Classic ASP. This code is unique for the server, but extremely powerful.

It says that TypeError: document.getElementById(...) is null

I got the same error. In my case I had multiple div with same id in a page. I renamed the another id of the div used and fixed the issue.

So confirm whether the element:

  • exists with id
  • doesn't have duplicate with id
  • confirm whether the script is called

Multi-Column Join in Hibernate/JPA Annotations

Hibernate is not going to make it easy for you to do what you are trying to do. From the Hibernate documentation:

Note that when using referencedColumnName to a non primary key column, the associated class has to be Serializable. Also note that the referencedColumnName to a non primary key column has to be mapped to a property having a single column (other cases might not work). (emphasis added)

So if you are unwilling to make AnEmbeddableObject the Identifier for Bar then Hibernate is not going to lazily, automatically retrieve Bar for you. You can, of course, still use HQL to write queries that join on AnEmbeddableObject, but you lose automatic fetching and life cycle maintenance if you insist on using a multi-column non-primary key for Bar.

How can I query for null values in entity framework?

If you prefer using method (lambda) syntax as I do, you could do the same thing like this:

var result = new TableName();

using(var db = new EFObjectContext)
{
    var query = db.TableName;

    query = value1 == null 
        ? query.Where(tbl => tbl.entry1 == null) 
        : query.Where(tbl => tbl.entry1 == value1);

    query = value2 == null 
        ? query.Where(tbl => tbl.entry2 == null) 
        : query.Where(tbl => tbl.entry2 == value2);

    result = query
        .Select(tbl => tbl)
        .FirstOrDefault();

   // Inspect the value of the trace variable below to see the sql generated by EF
   var trace = ((ObjectQuery<REF_EQUIPMENT>) query).ToTraceString();

}

return result;

Including one C source file in another?

I thought I'd share a situation where my team decided to include .c files. Our archicture largely consists of modules that are decoupled through a message system. These message handlers are public, and call many local static worker functions to do their work. The problem came about when trying to get coverage for our unit test cases, as the only way to exercise this private implementation code was indirectly through the public message interface. With some worker functions knee-deep in the stack, this turned out to be a nightmare to achieve proper coverage.

Including the .c files gave us a way to reach the cog in the machine we were interesting in testing.

ImportError: no module named win32api

The following should work:

pip install pywin32

But it didn't for me. I fixed this by downloading and installing the exe from here:

https://github.com/mhammond/pywin32/releases

Tomcat Server not starting with in 45 seconds

Folks, I had this same problem and tried raising the timeout, deleting the server and creating again and did not work. I was running Eclipse Kepler in Linux. The solution proposed by @Phoenix is what worked for me:

Window -> Preferences -> General -> Network Connections

Set Active Providers in manual and then configure or not the proxy. I had this option in "Native".

Then I realized I had the variable http_proxy set. It was set in the ~/.bashrc file. This environment variable is the culprit of many problems.

Once I set http_proxy to empty

export http_proxy=

to check it:

echo $http_proxy

I was able to leave option "Active Provider" in "Native" and solve the timeout problem. This is useful because Eclipse adopts the native configuration, in case you change it often.

In my case, where I had configured http_proxy in ~./bashrc, I had to close Eclipse and even log out and log in again.

R barplot Y-axis scale too short

Simplest solution seems to be specifying the ylim range. Here is some code to do this automatically (left default, right - adjusted):

# default y-axis
barplot(dat, beside=TRUE)

# automatically adjusted y-axis
barplot(dat, beside=TRUE, ylim=range(pretty(c(0, dat))))

img

The trick is to use pretty() which returns a list of interval breaks covering all values of the provided data. It guarantees that the maximum returned value is 1) a round number 2) greater than maximum value in the data.

In the example 0 was also added pretty(c(0, dat)) which makes sure that axis starts from 0.

How to set a DateTime variable in SQL Server 2008?

First of all - use single quotes around your date literals!

Second of all, I would strongly recommend always using the ISO-8601 date format - this works regardless of what your locale, regional or language settings are on your SQL Server.

The ISO-8601 format is either:

  • YYYYMMDD for dates only (e.g. 20110825 for the 25th of August, 2011)
  • YYYY-MM-DDTHH:MM:SS for dates and time (e.g. 2011-08-25T14:15:00 for 25th of AUgust, 14:15/2:15pm in the afternoon)

How to add a list item to an existing unordered list?

This would do it:

$("#header ul").append('<li><a href="/user/messages"><span class="tab">Message Center</span></a></li>');

Two things:

  • You can just append the <li> to the <ul> itself.
  • You need to use the opposite type of quotes than what you're using in your HTML. So since you're using double quotes in your attributes, surround the code with single quotes.

Convert integers to strings to create output filenames at run time

A much easier solution IMHO ...................

character(len=8) :: fmt ! format descriptor

fmt = '(I5.5)' ! an integer of width 5 with zeros at the left

i1= 59

write (x1,fmt) i1 ! converting integer to string using a 'internal file'

filename='output'//trim(x1)//'.dat'

! ====> filename: output00059.dat

set option "selected" attribute from dynamic created option

This works in FF, IE9

var x = document.getElementById("country").children[2];
x.setAttribute("selected", "selected");

Remove background drawable programmatically in Android

setBackgroundResource(0) is the best option. From the documentation:

Set the background to a given resource. The resource should refer to a Drawable object or 0 to remove the background.

It works everywhere, because it's since API 1.

setBackground was added much later, in API 16, so it will not work if your minSdkVersion is lower than 16.

Appending values to dictionary in Python

It sounds as if you are trying to setup a list of lists as each value in the dictionary. Your initial value for each drug in the dict is []. So assuming that you have list1 that you want to append to the list for 'MORPHINE' you should do:

drug_dictionary['MORPHINE'].append(list1)

You can then access the various lists in the way that you want as drug_dictionary['MORPHINE'][0] etc.

To traverse the lists stored against key you would do:

for listx in drug_dictionary['MORPHINE'] :
  do stuff on listx

SQL selecting rows by most recent date with two unique columns

SELECT chargeId, chargeType, MAX(serviceMonth) AS serviceMonth 
FROM invoice
GROUP BY chargeId, chargeType

How to run code after some delay in Flutter?

Just adding more description over the above answers

The Timer functionality works with below duration time also:

const Duration(
      {int days = 0,
      int hours = 0,
      int minutes = 0,
      int seconds = 0,
      int milliseconds = 0,
      int microseconds = 0})

Example:

  Timer(Duration(seconds: 3), () {
    print("print after every 3 seconds");
  });

Calling a function from a string in C#

This code works in my console .Net application
class Program
{
    static void Main(string[] args)
    {
        string method = args[0]; // get name method
        CallMethod(method);
    }
    
    public static void CallMethod(string method)
    {
        try
        {
            Type type = typeof(Program);
            MethodInfo methodInfo = type.GetMethod(method);
            methodInfo.Invoke(method, null);
        }
        catch(Exception ex)
        {
            Console.WriteLine("Error: " + ex.Message);
            Console.ReadKey();
        }
    }
    
    public static void Hello()
    {
        string a = "hello world!";
        Console.WriteLine(a);
        Console.ReadKey();
    }
}

jQuery pass more parameters into callback

$(document).on('click','[action=register]',function(){
    registerSocket(registerJSON(),registerDone,second($(this)));
});

function registerSocket(dataFn,doneFn,second){
                 $.ajax({
                       type:'POST',
                       url: "http://localhost:8080/store/public/register",
                       contentType: "application/json; charset=utf-8",
                       dataType: "json",
                       data:dataFn
                 }).done ([doneFn,second])
                   .fail(function(err){
                            console.log("AJAX failed: " + JSON.stringify(err, null, 2));
                        });
}

function registerDone(data){
    console.log(JSON.stringify(data));
}
function second(element){
    console.log(element);
}

Secondary way :

function socketWithParam(url,dataFn,doneFn,param){
  $.ajax({
    type:'POST',
    url:url,
    contentType: "application/json; charset=utf-8",
    headers: { 'Authorization': 'Bearer '+localStorage.getItem('jwt')},
    data:dataFn
    }).done(function(data){
      doneFn(data,param);
    })
    .fail(function(err,status,xhr){
    console.log("AJAX failed: " + JSON.stringify(err, null, 2));
    });
}

$(document).on('click','[order-btn]',function(){
  socketWithParam(url,fakeDataFn(),orderDetailDone,secondParam);
});

function orderDetailDone(data,param){
  -- to do something --
}

VBA copy cells value and format

Found this on OzGrid courtesy of Mr. Aaron Blood - simple direct and works.

Code:
Cells(1, 3).Copy Cells(1, 1)
Cells(1, 1).Value = Cells(1, 3).Value

However, I kinda suspect you were just providing us with an oversimplified example to ask the question. If you just want to copy formats from one range to another it looks like this...

Code:
Cells(1, 3).Copy
    Cells(1, 1).PasteSpecial (xlPasteFormats)
    Application.CutCopyMode = False

Android: I lost my android key store, what should I do?

Brute Force is the only way!

Here is a script that helped me out:

https://code.google.com/p/android-keystore-password-recover/wiki/HowTo

Using a list of 5-10 possible words from memory, it recovered my password in <1 sec.

Batch - Echo or Variable Not Working

Dont use spaces:

SET @var="GREG"
::instead of SET @var = "GREG"
ECHO %@var%
PAUSE

jQuery: Load Modal Dialog Contents via Ajax

$(function ()    {
    $('<div>').dialog({
        modal: true,
        open: function ()
        {
            $(this).load('Sample.htm');
        },         
        height: 400,
        width: 400,
        title: 'Dynamically Loaded Page'
    });
});

http://www.devcurry.com/2010/06/load-page-dynamically-inside-jquery-ui.html

android: how to change layout on button click?

  Button btnDownload = (Button) findViewById(R.id.DownloadView);
  Button btnApp = (Button) findViewById(R.id.AppView);

  btnDownload.setOnClickListener(handler);
  btnApp.setOnClickListener(handler);

  View.OnClickListener handler = new View.OnClickListener(){

  public void onClick(View v) {

    if(v==btnDownload){ 
            // doStuff
            Intent intentMain = new Intent(CurrentActivity.this , 
                                           SecondActivity.class);
            CurrentActivity.this.startActivity(intentMain);
            Log.i("Content "," Main layout ");
    }

    if(v==btnApp){ 
            // doStuff
            Intent intentApp = new Intent(CurrentActivity.this, 
                                          ThirdActivity.class);

            CurrentActivity.this.startActivity(intentApp);

            Log.i("Content "," App layout ");

    }
   }
  };

Note : and then you should declare all your activities in the manifest .xml file like this :

<activity android:name=".SecondActivity" ></activity>
<activity android:name=".ThirdActivity" ></activity>

EDIT : update this part of Code :) :

@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);// Add THIS LINE

    setContentView(R.layout.app);

    TextView tv = (TextView) this.findViewById(R.id.thetext);
    tv.setText("App View yo!?\n");
}

NB : check this (Broken link) Tutorial About How To Switch Between Activities.

Adding 'serial' to existing column in Postgres

TL;DR

Here's a version where you don't need a human to read a value and type it out themselves.

CREATE SEQUENCE foo_a_seq OWNED BY foo.a;
SELECT setval('foo_a_seq', coalesce(max(a), 0) + 1, false) FROM foo;
ALTER TABLE foo ALTER COLUMN a SET DEFAULT nextval('foo_a_seq'); 

Another option would be to employ the reusable Function shared at the end of this answer.


A non-interactive solution

Just adding to the other two answers, for those of us who need to have these Sequences created by a non-interactive script, while patching a live-ish DB for instance.

That is, when you don't wanna SELECT the value manually and type it yourself into a subsequent CREATE statement.

In short, you can not do:

CREATE SEQUENCE foo_a_seq
    START WITH ( SELECT max(a) + 1 FROM foo );

... since the START [WITH] clause in CREATE SEQUENCE expects a value, not a subquery.

Note: As a rule of thumb, that applies to all non-CRUD (i.e.: anything other than INSERT, SELECT, UPDATE, DELETE) statements in pgSQL AFAIK.

However, setval() does! Thus, the following is absolutely fine:

SELECT setval('foo_a_seq', max(a)) FROM foo;

If there's no data and you don't (want to) know about it, use coalesce() to set the default value:

SELECT setval('foo_a_seq', coalesce(max(a), 0)) FROM foo;
--                         ^      ^         ^
--                       defaults to:       0

However, having the current sequence value set to 0 is clumsy, if not illegal.
Using the three-parameter form of setval would be more appropriate:

--                                             vvv
SELECT setval('foo_a_seq', coalesce(max(a), 0) + 1, false) FROM foo;
--                                                  ^   ^
--                                                is_called

Setting the optional third parameter of setval to false will prevent the next nextval from advancing the sequence before returning a value, and thus:

the next nextval will return exactly the specified value, and sequence advancement commences with the following nextval.

— from this entry in the documentation

On an unrelated note, you also can specify the column owning the Sequence directly with CREATE, you don't have to alter it later:

CREATE SEQUENCE foo_a_seq OWNED BY foo.a;

In summary:

CREATE SEQUENCE foo_a_seq OWNED BY foo.a;
SELECT setval('foo_a_seq', coalesce(max(a), 0) + 1, false) FROM foo;
ALTER TABLE foo ALTER COLUMN a SET DEFAULT nextval('foo_a_seq'); 

Using a Function

Alternatively, if you're planning on doing this for multiple columns, you could opt for using an actual Function.

CREATE OR REPLACE FUNCTION make_into_serial(table_name TEXT, column_name TEXT) RETURNS INTEGER AS $$
DECLARE
    start_with INTEGER;
    sequence_name TEXT;
BEGIN
    sequence_name := table_name || '_' || column_name || '_seq';
    EXECUTE 'SELECT coalesce(max(' || column_name || '), 0) + 1 FROM ' || table_name
            INTO start_with;
    EXECUTE 'CREATE SEQUENCE ' || sequence_name ||
            ' START WITH ' || start_with ||
            ' OWNED BY ' || table_name || '.' || column_name;
    EXECUTE 'ALTER TABLE ' || table_name || ' ALTER COLUMN ' || column_name ||
            ' SET DEFAULT nextVal(''' || sequence_name || ''')';
    RETURN start_with;
END;
$$ LANGUAGE plpgsql VOLATILE;

Use it like so:

INSERT INTO foo (data) VALUES ('asdf');
-- ERROR: null value in column "a" violates not-null constraint

SELECT make_into_serial('foo', 'a');
INSERT INTO foo (data) VALUES ('asdf');
-- OK: 1 row(s) affected

Know relationships between all the tables of database in SQL Server

My solution is based on @marc_s solution, i just concatenated columns in cases that a constraint is based on more than one column:

SELECT
   FK.[name] AS ForeignKeyConstraintName
  ,SCHEMA_NAME(FT.schema_id) + '.' + FT.[name] AS ForeignTable
  ,STUFF(ForeignColumns.ForeignColumns, 1, 2, '') AS ForeignColumns
  ,SCHEMA_NAME(RT.schema_id) + '.' + RT.[name] AS ReferencedTable
  ,STUFF(ReferencedColumns.ReferencedColumns, 1, 2, '') AS ReferencedColumns
FROM
  sys.foreign_keys FK
  INNER JOIN sys.tables FT
  ON FT.object_id = FK.parent_object_id
  INNER JOIN sys.tables RT
  ON RT.object_id = FK.referenced_object_id
  CROSS APPLY
  (
    SELECT
      ', ' + iFC.[name] AS [text()]
    FROM
      sys.foreign_key_columns iFKC
      INNER JOIN sys.columns iFC
      ON iFC.object_id = iFKC.parent_object_id
        AND iFC.column_id = iFKC.parent_column_id
    WHERE
      iFKC.constraint_object_id = FK.object_id
    ORDER BY
      iFC.[name]
    FOR XML PATH('')
  ) ForeignColumns (ForeignColumns)
  CROSS APPLY
  (
    SELECT
      ', ' + iRC.[name]AS [text()]
    FROM
      sys.foreign_key_columns iFKC
      INNER JOIN sys.columns iRC
      ON iRC.object_id = iFKC.referenced_object_id
        AND iRC.column_id = iFKC.referenced_column_id
    WHERE
      iFKC.constraint_object_id = FK.object_id
    ORDER BY
      iRC.[name]
    FOR XML PATH('')
  ) ReferencedColumns (ReferencedColumns)

How do you access the matched groups in a JavaScript regular expression?

You can access capturing groups like this:

_x000D_
_x000D_
var myString = "something format_abc";_x000D_
var myRegexp = /(?:^|\s)format_(.*?)(?:\s|$)/g;_x000D_
var match = myRegexp.exec(myString);_x000D_
console.log(match[1]); // abc
_x000D_
_x000D_
_x000D_

And if there are multiple matches you can iterate over them:

_x000D_
_x000D_
var myString = "something format_abc";_x000D_
var myRegexp = /(?:^|\s)format_(.*?)(?:\s|$)/g;_x000D_
match = myRegexp.exec(myString);_x000D_
while (match != null) {_x000D_
  // matched text: match[0]_x000D_
  // match start: match.index_x000D_
  // capturing group n: match[n]_x000D_
  console.log(match[0])_x000D_
  match = myRegexp.exec(myString);_x000D_
}
_x000D_
_x000D_
_x000D_

Edit: 2019-09-10

As you can see the way to iterate over multiple matches was not very intuitive. This lead to the proposal of the String.prototype.matchAll method. This new method is expected to ship in the ECMAScript 2020 specification. It gives us a clean API and solves multiple problems. It has been started to land on major browsers and JS engines as Chrome 73+ / Node 12+ and Firefox 67+.

The method returns an iterator and is used as follows:

_x000D_
_x000D_
const string = "something format_abc";_x000D_
const regexp = /(?:^|\s)format_(.*?)(?:\s|$)/g;_x000D_
const matches = string.matchAll(regexp);_x000D_
    _x000D_
for (const match of matches) {_x000D_
  console.log(match);_x000D_
  console.log(match.index)_x000D_
}
_x000D_
_x000D_
_x000D_

As it returns an iterator, we can say it's lazy, this is useful when handling particularly large numbers of capturing groups, or very large strings. But if you need, the result can be easily transformed into an Array by using the spread syntax or the Array.from method:

function getFirstGroup(regexp, str) {
  const array = [...str.matchAll(regexp)];
  return array.map(m => m[1]);
}

// or:
function getFirstGroup(regexp, str) {
  return Array.from(str.matchAll(regexp), m => m[1]);
}

In the meantime, while this proposal gets more wide support, you can use the official shim package.

Also, the internal workings of the method are simple. An equivalent implementation using a generator function would be as follows:

function* matchAll(str, regexp) {
  const flags = regexp.global ? regexp.flags : regexp.flags + "g";
  const re = new RegExp(regexp, flags);
  let match;
  while (match = re.exec(str)) {
    yield match;
  }
}

A copy of the original regexp is created; this is to avoid side-effects due to the mutation of the lastIndex property when going through the multple matches.

Also, we need to ensure the regexp has the global flag to avoid an infinite loop.

I'm also happy to see that even this StackOverflow question was referenced in the discussions of the proposal.

Build Android Studio app via command line

there are two build types to build your application using the Gradle build settings: one for debugging your application — debug — and one for building your final package for release — release mode.

Building in Debug Mode

  • First Navigate to Android studio project Root folder using CMD enter image description here

  • run this command gradlew.bat assembleDebug

  • Output window look like this enter image description here

Build signed apk in Release Mode

  • Edit the build.gradle file to build your project in release mode:

    android {
    ...
    defaultConfig { ... }
    signingConfigs {
        release {
            storeFile file("myreleasekey.keystore")
            storePassword "password"
            keyAlias "MyReleaseKey"
            keyPassword "password"
        }
    }
    buildTypes {
        release {
            ...
            signingConfig signingConfigs.release
        }
    }}
    

enter image description here

  • run this command gradlew.bat assembleRelease

Done.Good Luck!

How to sort dates from Oldest to Newest in Excel?

Convert text to date format via the "Data" tab.

Highlight the relevant section and then select from the top menu Data> Datat Tools > Text to Column (depending on your version).

Choose the "Delimited" option.

Toggle through the Delimiter options until the entry appears in the desired format, and select "Next".

Under the Data format, select Date (DMY)

Select "finish" and the issue should be resolved.

How to change maven logging level to display only warning and errors?

You can achieve this with MAVEN_OPTS, for example
MAVEN_OPTS=-Dorg.slf4j.simpleLogger.defaultLogLevel=warn mvn clean

Rather than putting the system property directly on the command line. (At least for maven 3.3.1.)

Consider using ~/.mavenrc for setting MAVEN_OPTS if you would like logging changed for your login across all maven invocations.

What causing this "Invalid length for a Base-64 char array"

My guess is that something is either encoding or decoding too often - or that you've got text with multiple lines in.

Base64 strings have to be a multiple of 4 characters in length - every 4 characters represents 3 bytes of input data. Somehow, the view state data being passed back by ASP.NET is corrupted - the length isn't a multiple of 4.

Do you log the user agent when this occurs? I wonder whether it's a badly-behaved browser somewhere... another possibility is that there's a proxy doing naughty things. Likewise try to log the content length of the request, so you can see whether it only happens for large requests.

A potentially dangerous Request.Path value was detected from the client (*)

When dealing with Uniform Resource Locator(URL) s there are certain syntax standards, in this particular situation we are dealing with Reserved Characters.

As up to RFC 3986, Reserved Characters may (or may not) be defined as delimiters by the generic syntax, by each scheme-specific syntax, or by the implementation-specific syntax of a URI's dereferencing algorithm; And asterisk(*) is a Reserved Character.

The best practice is to use Unreserved Characters in URLs or you can try encoding it.

Keep digging :

HTTP GET Request in Node.js Express

Check out httpreq: it's a node library I created because I was frustrated there was no simple http GET or POST module out there ;-)

Authentication failed for https://xxx.visualstudio.com/DefaultCollection/_git/project

If you wish to use GIT CLI and not interact with the build in GIT wrappers in Visual Studio you need to enable Alternate Authentication Credentials

How?

Open your account (VS Online account) 
-> click on your name on the top right 
-> My Profile
-> Credentials.

and set it up.


enter image description here

enter image description here

Reset par to the default values at startup

Use below script to get back to normal 1 plot:

par(mfrow = c(1,1))

Is there any way to call a function periodically in JavaScript?

Since you want the function to be executed periodically, use setInterval

How to calculate number of days between two dates

If you are using moment.js you can do it easily.

var start = moment("2018-03-10", "YYYY-MM-DD");
var end = moment("2018-03-15", "YYYY-MM-DD");

//Difference in number of days
moment.duration(start.diff(end)).asDays();

//Difference in number of weeks
moment.duration(start.diff(end)).asWeeks();

If you want to find difference between a given date and current date in number of days (ignoring time), make sure to remove time from moment object of current date as below

moment().startOf('day')

To find difference between a given date and current date in number of days

var given = moment("2018-03-10", "YYYY-MM-DD");
var current = moment().startOf('day');

//Difference in number of days
moment.duration(given.diff(current)).asDays();

How can I put an icon inside a TextInput in React Native?

you can also do something more specific like that based on Anthony Artemiew's response:

<View style={globalStyles.searchSection}>
                    <TextInput
                        style={globalStyles.input}
                        placeholder="Rechercher"
                        onChangeText={(searchString) => 
                       {this.setState({searchString})}}
                        underlineColorAndroid="transparent"
                    />
                     <Ionicons onPress={()=>console.log('Recherche en cours...')} style={globalStyles.searchIcon} name="ios-search" size={30} color="#1764A5"/>

 </View>

Style:

 searchSection: {
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#fff',
        borderRadius:50,
        marginLeft:35,
        width:340,
        height:40,
        margin:25
    },
    searchIcon: {
        padding: 10,
    },
    input: {
        flex: 1,
        paddingTop: 10,
        paddingRight: 10,
        paddingBottom: 10,
        paddingLeft: 0,
        marginLeft:10,
        borderTopLeftRadius:50,
        borderBottomLeftRadius:50,
        backgroundColor: '#fff',
        color: '#424242',
    },

Revert to a commit by a SHA hash in Git?

It reverts the said commit, that is, adds the commit opposite to it. If you want to checkout an earlier revision, you do:

git checkout 56e05fced214c44a37759efa2dfc25a65d8ae98d

How to create image slideshow in html?

  1. Set var step=1 as global variable by putting it above the function call
  2. put semicolons

It will look like this

<head>
<script type="text/javascript">
var image1 = new Image()
image1.src = "images/pentagg.jpg"
var image2 = new Image()
image2.src = "images/promo.jpg"
</script>
</head>
<body>
<p><img src="images/pentagg.jpg" width="500" height="300" name="slide" /></p>
<script type="text/javascript">
        var step=1;
        function slideit()
        {
            document.images.slide.src = eval("image"+step+".src");
            if(step<2)
                step++;
            else
                step=1;
            setTimeout("slideit()",2500);
        }
        slideit();
</script>
</body>

jquery how to catch enter key and change event to tab

Here is what I've been using:

$("[tabindex]").addClass("TabOnEnter");
$(document).on("keypress", ".TabOnEnter", function (e) {
 //Only do something when the user presses enter
     if (e.keyCode == 13) {
          var nextElement = $('[tabindex="' + (this.tabIndex + 1) + '"]');
          console.log(this, nextElement);
           if (nextElement.length)
                nextElement.focus()
           else
                $('[tabindex="1"]').focus();
      }
});

Pays attention to the tabindex and is not specific to the form but to the whole page.

Note live has been obsoleted by jQuery, now you should be using on

Creating a Menu in Python

def my_add_fn():
   print "SUM:%s"%sum(map(int,raw_input("Enter 2 numbers seperated by a space").split()))

def my_quit_fn():
   raise SystemExit

def invalid():
   print "INVALID CHOICE!"

menu = {"1":("Sum",my_add_fn),
        "2":("Quit",my_quit_fn)
       }
for key in sorted(menu.keys()):
     print key+":" + menu[key][0]

ans = raw_input("Make A Choice")
menu.get(ans,[None,invalid])[1]()

how to add script inside a php code?

You mean JavaScript? Just output it like anything else in the page:

<script type="text/javascript">
  <?php echo "alert('message');"; ?>
</script>

If want PHP to generate a custom message for the alert dialog, then basically you want to write your JavaScript as usual in the HTML, but insert PHP echo statements in the middle of your JavaScript where you want the messages, like:

<script type="text/javascript">
  alert('<?php echo $custom_message; ?>');
</script>

Or you could even do something like this:

<script type="text/javascript">
  var alertMsg = '<?php echo $custom_message; ?>';
  alert(alertMsg);
</script>

Basically, think about where in your JavaScript you want PHP to generate dynamic output and just put an echo statement there.

Hide password with "•••••••" in a textField

For SwiftUI, try

TextField ("Email", text: $email)
    .textFieldStyle(RoundedBorderTextFieldStyle()).padding()
SecureField ("Password", text: $password)
    .textFieldStyle(RoundedBorderTextFieldStyle()).padding()

How to run ssh-add on windows?

If you are trying to setup a key for using git with ssh, there's always an option to add a configuration for the identity file.

vi ~/.ssh/config

Host example.com
IdentityFile ~/.ssh/example_key

Get month and year from date cells Excel

Please try something like:

=IF(LEN(C1)>10,VALUE(LEFT(C1,FIND(" ",C1,8))),IF(ISTEXT(C1),DATE(RIGHT(C1,4),MID(C1,4,2),LEFT(C1,2)),C1))  

You seem to have three main possible scenarios:

  1. Space-separated date with time as text (eg as A1 below)
  2. Hyphen-separated date as text (eg as A2 below)
  3. Formatted date index (as A4 and A5 below)

ColumnA below is formatted General and ColumnB as Date (my default setting). ColumnC also as date but with custom formatting to suit the appearances mentioned in your question.
A clue as to whether or not text format is the left or right alignment of the cells’ contents.

I am suggesting separate treatment for each of the above three main cases, so use =IF to differentiate them.

Case #1

This is longer than any of the others, so can be distinguished as having a length greater than say 10 characters, with =LEN.
In this case we want all but the last six characters but for added flexibility (for instance, in case the time element included seconds) I have chosen to count from the left rather than from the right. The problem then is that the month names may vary in length, so I have chosen to look for the space that immediately follows the year to indicate the limit for the relevant number of characters.

This with =FIND which looks for a space (" ") in C1, starting with the eighth character within C1 counting from the left, on the assumption that for this case days will be expressed as two characters and months as three or more.

Since =LEFT is a string function it returns a string, but this can be converted to a value with=VALUE.

So

=VALUE(LEFT(C1,FIND(" ",C1,8))) 

returns 40671 in this example – in Excel’s 1900 date system the date serial number for May 5, 2011.

Case #2

If the length of C1 is not greater than 10 characters, we still need to distinguish between a text entry or a value entry which I have chosen to do with =ISTEXT and, where the if condition is TRUE (as for C2) apply =DATE which takes three parameters, here provided by:

=RIGHT(C2,4)  

Takes the last four characters of C2, hence 2011 in this example.

=MID(C2,4,2) 

Starting at the fourth character, takes the next two characters of C2, hence 05 in this example (representing May).

=LEFT(C2,2))  

Takes the first two characters of C2, hence 08 in this example (representing the 8th day of the month). Date is not a text function so does not need to be wrapped in =VALUE.

Taken together

=DATE(RIGHT(C2,4),MID(C2,4,2),LEFT(C2,2)) 

also returns 40671 in this example, but from different input from Case #1.

Case #3

Is simple because already a date serial number, so just

=C2  

is sufficient.


Put the above together to cover all three cases in a single formula:

=IF(LEN(C1)>10,VALUE(LEFT(C1,FIND(" ",C1,8))),IF(ISTEXT(C1),DATE(RIGHT(C1,4),MID(C1,4,2),LEFT(C1,2)),C1))  

as applied in ColumnF (formatted to suit OP) or in General format (to show values are integers) in ColumnH:

SO23928568 example

Skip first couple of lines while reading lines in Python file

Use a slice, like below:

with open('yourfile.txt') as f:
    lines_after_17 = f.readlines()[17:]

If the file is too big to load in memory:

with open('yourfile.txt') as f:
    for _ in range(17):
        next(f)
    for line in f:
        # do stuff

Is it possible to move/rename files in Git and maintain their history?

I make moving the files and then do

git add -A

which put in the sataging area all deleted/new files. Here git realizes that the file is moved.

git commit -m "my message"
git push

I do not know why but this works for me.

How to call a SOAP web service on Android

If you can, go for JSON. Android comes with the complete org.json package

How can I convert an image into a Base64 string?

If you're doing this on Android, here's a helper copied from the React Native codebase:

import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import android.util.Base64;
import android.util.Base64OutputStream;
import android.util.Log;

// You probably don't want to do this with large files
// (will allocate a large string and can cause an OOM crash).
private String readFileAsBase64String(String path) {
  try {
    InputStream is = new FileInputStream(path);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Base64OutputStream b64os = new Base64OutputStream(baos, Base64.DEFAULT);
    byte[] buffer = new byte[8192];
    int bytesRead;
    try {
      while ((bytesRead = is.read(buffer)) > -1) {
        b64os.write(buffer, 0, bytesRead);
      }
      return baos.toString();
    } catch (IOException e) {
      Log.e(TAG, "Cannot read file " + path, e);
      // Or throw if you prefer
      return "";
    } finally {
      closeQuietly(is);
      closeQuietly(b64os); // This also closes baos
    }
  } catch (FileNotFoundException e) {
    Log.e(TAG, "File not found " + path, e);
    // Or throw if you prefer
    return "";
  }
}

private static void closeQuietly(Closeable closeable) {
  try {
    closeable.close();
  } catch (IOException e) {
  }
}

Conditional Count on a field

Using COUNT instead of SUM removes the requirement for an ELSE statement:

SELECT jobId, jobName,
    COUNT(CASE WHEN Priority=1 THEN 1 END) AS Priority1,
    COUNT(CASE WHEN Priority=2 THEN 1 END) AS Priority2,
    COUNT(CASE WHEN Priority=3 THEN 1 END) AS Priority3,
    COUNT(CASE WHEN Priority=4 THEN 1 END) AS Priority4,
    COUNT(CASE WHEN Priority=5 THEN 1 END) AS Priority5
FROM TableName
GROUP BY jobId, jobName

Servlet Mapping using web.xml

It allows servlets to have multiple servlet mappings:

<servlet>
    <servlet-name>Servlet1</servlet-name>
    <servlet-path>foo.Servlet</servlet-path>
</servlet>
<servlet-mapping>
    <servlet-name>Servlet1</servlet-name>
    <url-pattern>/enroll</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>Servlet1</servlet-name>
    <url-pattern>/pay</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>Servlet1</servlet-name>
    <url-pattern>/bill</url-pattern>
</servlet-mapping>

It allows filters to be mapped on the particular servlet:

<filter-mapping>
    <filter-name>Filter1</filter-name>
    <servlet-name>Servlet1</servlet-name>
</filter-mapping>

Your proposal would support neither of them. Note that the web.xml is read and parsed only once during application's startup, not on every HTTP request as you seem to think.

Since Servlet 3.0, there's the @WebServlet annotation which minimizes this boilerplate:

@WebServlet("/enroll")
public class Servlet1 extends HttpServlet {

See also:

How can I clone a private GitLab repository?

You might need a ~/.ssh/config:

Host gitlab.YOURDOMAIN.DOMAIN
    Port 1111
    IdentityFile ~/.ssh/id_rsa

and then you can use git clone git@DOMAINandREPOSITORY. This means you always use the user git.

Read file As String

The code finally used is the following from:

http://www.java2s.com/Code/Java/File-Input-Output/ConvertInputStreamtoString.htm

public static String convertStreamToString(InputStream is) throws Exception {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
      sb.append(line).append("\n");
    }
    reader.close();
    return sb.toString();
}

public static String getStringFromFile (String filePath) throws Exception {
    File fl = new File(filePath);
    FileInputStream fin = new FileInputStream(fl);
    String ret = convertStreamToString(fin);
    //Make sure you close all streams.
    fin.close();        
    return ret;
}

T-SQL - function with default parameters

With user defined functions, you have to declare every parameter, even if they have a default value.

The following would execute successfully:

IF dbo.CheckIfSFExists( 23, default ) = 0
    SET @retValue = 'bla bla bla;

write() versus writelines() and concatenated strings

Actually, I think the problem is that your variable "lines" is bad. You defined lines as a tuple, but I believe that write() requires a string. All you have to change is your commas into pluses (+).

nl = "\n"
lines = line1+nl+line2+nl+line3+nl
textdoc.writelines(lines)

should work.

Cropping images in the browser BEFORE the upload

The Pixastic library does exactly what you want. However, it will only work on browsers that have canvas support. For those older browsers, you'll either need to:

  1. supply a server-side fallback, or
  2. tell the user that you're very sorry, but he'll need to get a more modern browser.

Of course, option #2 isn't very user-friendly. However, if your intent is to provide a pure client-only tool and/or you can't support a fallback back-end cropper (e.g. maybe you're writing a browser extension or offline Chrome app, or maybe you can't afford a decent hosting provider that provides image manipulation libraries), then it's probably fair to limit your user base to modern browsers.

EDIT: If you don't want to learn Pixastic, I have added a very simple cropper on jsFiddle here. It should be possible to modify and integrate and use the drawCroppedImage function with Jcrop.

Launch Pycharm from command line (terminal)

open /Applications/PyCharm\ CE.app/ opens up the primary Pycharm Dialogue box to choose the project..

worked for me with macOS 10.13.6 & Pycharm 2018.1

How to connect a Windows Mobile PDA to Windows 10

Here is the answer: Download the "Windows Mobile Device Center" for your machine type, likely 64bit.
http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=3182

Before you run the install, change the compatibility settings to 'Windows 7'. Then install it... Then run it: You'll find it under 'WMDC'.. Your device should now recognize, when plugged in, mine did!

What is the difference between T(n) and O(n)?

Short explanation:

If an algorithm is of T(g(n)), it means that the running time of the algorithm as n (input size) gets larger is proportional to g(n).

If an algorithm is of O(g(n)), it means that the running time of the algorithm as n gets larger is at most proportional to g(n).

Normally, even when people talk about O(g(n)) they actually mean T(g(n)) but technically, there is a difference.


More technically:

O(n) represents upper bound. T(n) means tight bound. O(n) represents lower bound.

f(x) = T(g(x)) iff f(x) = O(g(x)) and f(x) = O(g(x))

Basically when we say an algorithm is of O(n), it's also O(n2), O(n1000000), O(2n), ... but a T(n) algorithm is not T(n2).

In fact, since f(n) = T(g(n)) means for sufficiently large values of n, f(n) can be bound within c1g(n) and c2g(n) for some values of c1 and c2, i.e. the growth rate of f is asymptotically equal to g: g can be a lower bound and and an upper bound of f. This directly implies f can be a lower bound and an upper bound of g as well. Consequently,

f(x) = T(g(x)) iff g(x) = T(f(x))

Similarly, to show f(n) = T(g(n)), it's enough to show g is an upper bound of f (i.e. f(n) = O(g(n))) and f is a lower bound of g (i.e. f(n) = O(g(n)) which is the exact same thing as g(n) = O(f(n))). Concisely,

f(x) = T(g(x)) iff f(x) = O(g(x)) and g(x) = O(f(x))


There are also little-oh and little-omega (?) notations representing loose upper and loose lower bounds of a function.

To summarize:

f(x) = O(g(x)) (big-oh) means that the growth rate of f(x) is asymptotically less than or equal to to the growth rate of g(x).

f(x) = O(g(x)) (big-omega) means that the growth rate of f(x) is asymptotically greater than or equal to the growth rate of g(x)

f(x) = o(g(x)) (little-oh) means that the growth rate of f(x) is asymptotically less than the growth rate of g(x).

f(x) = ?(g(x)) (little-omega) means that the growth rate of f(x) is asymptotically greater than the growth rate of g(x)

f(x) = T(g(x)) (theta) means that the growth rate of f(x) is asymptotically equal to the growth rate of g(x)

For a more detailed discussion, you can read the definition on Wikipedia or consult a classic textbook like Introduction to Algorithms by Cormen et al.

Change first commit of project with Git?

As mentioned by ecdpalma below, git 1.7.12+ (August 2012) has enhanced the option --root for git rebase:

"git rebase [-i] --root $tip" can now be used to rewrite all the history leading to "$tip" down to the root commit.

That new behavior was initially discussed here:

I personally think "git rebase -i --root" should be made to just work without requiring "--onto" and let you "edit" even the first one in the history.
It is understandable that nobody bothered, as people are a lot less often rewriting near the very beginning of the history than otherwise.

The patch followed.


(original answer, February 2010)

As mentioned in the Git FAQ (and this SO question), the idea is:

  1. Create new temporary branch
  2. Rewind it to the commit you want to change using git reset --hard
  3. Change that commit (it would be top of current HEAD, and you can modify the content of any file)
  4. Rebase branch on top of changed commit, using:

    git rebase --onto <tmp branch> <commit after changed> <branch>`
    

The trick is to be sure the information you want to remove is not reintroduced by a later commit somewhere else in your file. If you suspect that, then you have to use filter-branch --tree-filter to make sure the content of that file does not contain in any commit the sensible information.

In both cases, you end up rewriting the SHA1 of every commit, so be careful if you have already published the branch you are modifying the contents of. You probably shouldn’t do it unless your project isn’t yet public and other people haven’t based work off the commits you’re about to rewrite.

Rails 3 migrations: Adding reference column?

For Rails 4

The generator accepts column type as references (also available as belongs_to).

This migration will create a user_id column and appropriate index:

$ rails g migration AddUserRefToProducts user:references 

generates:

class AddUserRefToProducts < ActiveRecord::Migration
  def change
    add_reference :products, :user, index: true
  end
end

http://guides.rubyonrails.org/active_record_migrations.html#creating-a-standalone-migration

For Rails 3

Helper is called references (also available as belongs_to).

This migration will create a category_id column of the appropriate type. Note that you pass the model name, not the column name. Active Record adds the _id for you.

change_table :products do |t|
  t.references :category
end

If you have polymorphic belongs_to associations then references will add both of the columns required:

change_table :products do |t|
  t.references :attachment, :polymorphic => {:default => 'Photo'}
end

Will add an attachment_id column and a string attachment_type column with a default value of Photo.

http://guides.rubyonrails.org/v3.2.21/migrations.html#creating-a-standalone-migration

How to restore a SQL Server 2012 database to SQL Server 2008 R2?

NOTE, SOME OF THE ABOVE ANSWERS ARE MASSIVELY OUT-OF-DATE! THIS CAN BE DONE AND ALL WITHIN SQL SERVER MANAGEMENT STUDIO (SQL MS)


There are numerous methods you can adopt to "downgrade" a database, but one I have found recently and that I believe was not found in early releases of SQL MS 2012, is the Copy Database Wizard. Here is how you can copy a database from a 2012 server instance to a 2008 R2 instance:

  1. In the 2012 instance, right click on the database you want to copy/"downgrade" and select "Tasks" > "Copy Database...".

  2. "Welcome to the Copy Database Wizard" click [Next].

  3. "Select a Source Server": Set the "Source server" as the 2012 instance (or the higher version server instance), and set the appropriate authentication. click [Next]. [Note. the Server Agent services must be running]

  4. "Select a Destination Server:" Set the "Destination server" as the 2008 R2 (or lower version instance), and set the appropriate authentication. click [Next]. [Note. the Server Agent services must be running]

  5. "Select the Transfer Method" For the sake of this example, select "Use the SQL Management Object method", click [Next].

  6. Select to move or copy the required databases, click [Next].

  7. Configure the destination database path and logical names etc. Select the required option for if the database exists. Click [Next].

  8. Configure the integration services package, click [Next].

  9. For this example, select the "Run Immediately" option for "Schedule the Package" options, click [Next].

  10. "Complete the Wizard", click [Finish] to execute the package and create the "downgraded" database.

You are done, happy days. :]


Another method I found was the SQL Database Migration Wizard which was created by Microsoft and which I think (I don't know) that the wizard above was created from. Get it here http://sqlazuremw.codeplex.com/. To use this package to migrate a databases from SQL Server 20012 to 2008 R2, you can do the following:

Note. Microsoft have now removed SQLAzureMW from Codeplex. I have personally made it available here

  1. Run SQLAzureMW.exe.

  2. Select the Analyse/Migrate radio button from the right hand side of the main window.

  3. Select the Target Server as “SQL Database latest service version (V12)”. Click [Next].

  4. Connect to the SQL Server 2012 instance. Server name for my machine is “VAIOE\SQLSERVER2012”, use Windows authentication, select “Master DB (list all databases)” from the database options and “Save Login Information”. Click [Connect].

  5. Select the required database to migrate [use GVH Report database for now]. Click [Next].

  6. Select “Script all database objects”.

  7. Click [Advance] and change the following options:

a. Under General set “Target Server” to “SQL Server”.

b. Under “Table/View Options” set “Script Table / Data” to “Table Schema with Data”. Set “Database Engine Stored Procedures” to “True”. Set “Security Functions”, “Security Stored Procedures” and “System Functions” to “True”.

Click [OK]. Click [Next].

  1. Review your selections. Click [Next].

  2. You will be prompted “Ready to Generate Script?”, click [Yes]. This will start the script generation. Once this is done, click [Next].

  3. Now you will get another connection dialog. This time select the database on the target server (the SQL Server 2008 R2 instance). Select Master database so you get a choice of target DB. Click [Connect].

  4. Now, it is likely that you want to migrate into a new database, so click [Create Database].

  5. Enter a database target name and leave the “Collation” as the “”, this does not concern us. Click [Create Database]. Click [Next].

  6. You will now be prompted “Execute script against destination server?”, click [Yes].

  7. This will now go off and do loads of stuff, setting up the schema using the generated script, but unlike the previous method we found, the data is bulk loaded using BCP, which is blazingly fast. All of this is also done internally, so no generation of massive .sql script files etc.

  8. Click [Exit].

You are done. Now if you open up Management Studio and connect to both the SQL Server 2012 and 2008 R2 instances we have just worked with you can see that the schema for the 2012 source database matches the target database which was just created.


The two processes above are almost identical and provide the same functionality. I would not perform the latter unless you specifically need to migrate to Azure or method 1 fails for you.

I hope this helps someone out.

Passing multiple values for same variable in stored procedure

Your stored procedure is designed to accept a single parameter, Arg1List. You can't pass 4 parameters to a procedure that only accepts one.

To make it work, the code that calls your procedure will need to concatenate your parameters into a single string of no more than 3000 characters and pass it in as a single parameter.

Export and import table dump (.sql) using pgAdmin

follow he steps. in pgadmin

host-DataBase-Schemas- public (click right) CREATE script- open file -(choose xxx.sql) , then click over the option execute query write result to file -export data file ok- then click in save.its all. it work to me.

note: error in version command script enter image description herede sql over pgadmin can be search, example: http://www.forosdelweb.com/f21/campo-tipo-datetime-postgresql-245389/

enter image description here

How to use timer in C?

Here's a solution I used (it needs #include <time.h>):

int msec = 0, trigger = 10; /* 10ms */
clock_t before = clock();

do {
  /*
   * Do something to busy the CPU just here while you drink a coffee
   * Be sure this code will not take more than `trigger` ms
   */

  clock_t difference = clock() - before;
  msec = difference * 1000 / CLOCKS_PER_SEC;
  iterations++;
} while ( msec < trigger );

printf("Time taken %d seconds %d milliseconds (%d iterations)\n",
  msec/1000, msec%1000, iterations);

Homebrew install specific version of formula?

There's now a much easier way to install an older version of a formula that you'd previously installed. Simply use

brew switch [formula] [version]

For instance, I alternate regularly between Node.js 0.4.12 and 0.6.5:

brew switch node 0.4.12
brew switch node 0.6.5

Since brew switch just changes the symlinks, it's very fast. See further documentation on the Homebrew Wiki under External Commands.

LINQ Joining in C# with multiple conditions

Your and should be a && in the where clause.

where epl.DepartAirportAfter >  sd.UTCDepartureTime 
and epl.ArriveAirportBy > sd.UTCArrivalTime

should be

where epl.DepartAirportAfter >  sd.UTCDepartureTime 
&& epl.ArriveAirportBy > sd.UTCArrivalTime

What's the opposite of 'make install', i.e. how do you uninstall a library in Linux?

If you have a manifest file which lists all the files that were installed with make install you can run this command which I have from another answer:

cat install_manifest.txt | xargs echo rm | sh

If you have sudo make install you will need to add a sudo to your uninstall:

cat install_manifest.txt | xargs echo sudo rm | sh

Creating and Naming Worksheet in Excel VBA

Are you using an error handler? If you're ignoring errors and try to name a sheet the same as an existing sheet or a name with invalid characters, it could be just skipping over that line. See the CleanSheetName function here

http://www.dailydoseofexcel.com/archives/2005/01/04/naming-a-sheet-based-on-a-cell/

for a list of invalid characters that you may want to check for.

Update

Other things to try: Fully qualified references, throwing in a Doevents, code cleaning. This code qualifies your Sheets reference to ThisWorkbook (you can change it to ActiveWorkbook if that suits). It also adds a thousand DoEvents (stupid overkill, but if something's taking a while to get done, this will allow it to - you may only need one DoEvents if this actually fixes anything).

Dim WS As Worksheet
Dim i As Long

With ThisWorkbook
    Set WS = .Worksheets.Add(After:=.Sheets(.Sheets.Count))
End With

For i = 1 To 1000
    DoEvents
Next i

WS.Name = txtSheetName.Value

Finally, whenever I have a goofy VBA problem that just doesn't make sense, I use Rob Bovey's CodeCleaner. It's an add-in that exports all of your modules to text files then re-imports them. You can do it manually too. This process cleans out any corrupted p-code that's hanging around.

Android: Center an image

Technically both answers above are correct, but since you are setting your ImageView to fill_parent instead of wrap_content, the image within is not centered, but the ImageView itself is.

Give your ImageView the attributes:

android:scaleType="centerInside"
android:gravity="center"

The scaleType is really only necessary in this case if the image exceeds the size of the ImageView. You may also want different scaleTypes. In conclusion, android:gravity is what you're looking for in this case, but if your ImageView is set to wrap_content, you should set the ImageView's gravity (android:layout_gravity) to be centered within the parent.

HTML: how to make 2 tables with different CSS

Of course it is!

Give them both an id and set up the CSS accordingly:

#table1
{
    CSS for table1
}


#table2
{
    CSS for table2
}

From io.Reader to string in Go

func copyToString(r io.Reader) (res string, err error) {
    var sb strings.Builder
    if _, err = io.Copy(&sb, r); err == nil {
        res = sb.String()
    }
    return
}

How to customize the back button on ActionBar

The "up" affordance indicator is provided by a drawable specified in the homeAsUpIndicator attribute of the theme. To override it with your own custom version it would be something like this:

<style name="Theme.MyFancyTheme" parent="android:Theme.Holo">
    <item name="android:homeAsUpIndicator">@drawable/my_fancy_up_indicator</item>
</style>

If you are supporting pre-3.0 with your application be sure you put this version of the custom theme in values-v11 or similar.

How to iterate over a std::map full of strings in C++

Your main problem is that you are calling a method called first() in the iterator. What you are meant to do is use the property called first:

...append(iter->first) rather than ...append(iter->first())

As a matter of style, you shouldn't be using new to create that string.

std::string something::toString() 
{
        std::map<std::string, std::string>::iterator iter;
        std::string strToReturn; //This is no longer on the heap

        for (iter = table.begin(); iter != table.end(); ++iter) {
           strToReturn.append(iter->first); //Not a method call
           strToReturn.append("=");
           strToReturn.append(iter->second);
           //....
           // Make sure you don't modify table here or the iterators will not work as you expect
        }
        //...
        return strToReturn;
}

edit: facildelembrar pointed out (in the comments) that in modern C++ you can now rewrite the loop

for (auto& item: table) {
    ...
}

"The system cannot find the file specified" when running C++ program

I came across this problem and none of these solution worked 100%

In addition to ReturnVoid's answer which suggested the change

Project Properties -> Linker -> Output file -> $(OutDir)$(TargetName)$(TargetExt)

I needed to changed

Project Properties -> C/C++ -> Debug Information Format -> /Zi

This field was blank for me, changing the contents to /Zi (or /Z7 or /ZI if those are the formats you want to use) allowed me to debug

How do I iterate over an NSArray?

The three ways are:

        //NSArray
    NSArray *arrData = @[@1,@2,@3,@4];

    // 1.Classical
    for (int i=0; i< [arrData count]; i++){
        NSLog(@"[%d]:%@",i,arrData[i]);
    }

    // 2.Fast iteration
    for (id element in arrData){
        NSLog(@"%@",element);
    }

    // 3.Blocks
    [arrData enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
         NSLog(@"[%lu]:%@",idx,obj);
         // Set stop to YES in case you want to break the iteration
    }];
  1. Is the fastest way in execution, and 3. with autocompletion forget about writing iteration envelope.

Pandas: drop a level from a multi-level column index?

I have struggled with this problem since I don’t know why my droplevel() function does not work. Work through several and learn that ‘a’ in your table is columns name and ‘b’, ‘c’ are index. Do like this will help

df.columns.name = None
df.reset_index() #make index become label

What is the PHP syntax to check "is not null" or an empty string?

Null OR an empty string?

if (!empty($user)) {}

Use empty().


After realizing that $user ~= $_POST['user'] (thanks matt):

var uservariable='<?php 
    echo ((array_key_exists('user',$_POST)) || (!empty($_POST['user']))) ? $_POST['user'] : 'Empty Username Input';
?>';

Why Python 3.6.1 throws AttributeError: module 'enum' has no attribute 'IntFlag'?

Installing version 1.1.8 of enum34 worked for me.

I was able to fix this by adding enum34 = "==1.1.8" to pyproject.toml. Apparently enum34 had a feature in v1.1.8 that avoided this error, but this regressed in v1.1.9+. This is just a workaround though. The better solution would be for packages to use environment markers so you don't have to install enum34 at all unless needed.

Source: https://github.com/python-poetry/poetry/issues/1122

AltGr key not working, instead I have to use Ctrl+AltGr

I found a solution for my problem while writing my question !

Going into my remote session i tried two key combinations, and it solved the problem on my Desktop : Alt+Enter and Ctrl+Enter (i don't know which one solved the problem though)

I tried to reproduce the problem, but i couldn't... but i'm almost sure it's one of the key combinations described in the question above (since i experienced this problem several times)

So it seems the problem comes from the use of RDP (windows7 and 8)

Update 2017: Problem occurs on Windows 10 aswell.

How to compile and run a C/C++ program on the Android system

if you have installed NDK succesfully then start with it sample application

http://developer.android.com/sdk/ndk/overview.html#samples

if you are interested another ways of this then may this will help

http://shareprogrammingtips.blogspot.com/2018/07/cross-compile-cc-based-programs-and-run.html

I also want to know is it possible to push the compiled binary into android device or AVD and run using the terminal of the android device or AVD?

here you can see NestedVM

NestedVM provides binary translation for Java Bytecode. This is done by having GCC compile to a MIPS binary which is then translated to a Java class file. Hence any application written in C, C++, Fortran, or any other language supported by GCC can be run in 100% pure Java with no source changes.


Example: Cross compile Hello world C program and run it on android

How to extract base URL from a string in JavaScript?

To get the origin of any url, including paths within a website (/my/path) or schemaless (//example.com/my/path), or full (http://example.com/my/path) I put together a quick function.

In the snippet below, all three calls should log https://stacksnippets.net.

_x000D_
_x000D_
function getOrigin(url)_x000D_
{_x000D_
  if(/^\/\//.test(url))_x000D_
  { // no scheme, use current scheme, extract domain_x000D_
    url = window.location.protocol + url;_x000D_
  }_x000D_
  else if(/^\//.test(url))_x000D_
  { // just path, use whole origin_x000D_
    url = window.location.origin + url;_x000D_
  }_x000D_
  return url.match(/^([^/]+\/\/[^/]+)/)[0];_x000D_
}_x000D_
_x000D_
console.log(getOrigin('https://stacksnippets.net/my/path'));_x000D_
console.log(getOrigin('//stacksnippets.net/my/path'));_x000D_
console.log(getOrigin('/my/path'));
_x000D_
_x000D_
_x000D_

Format cell color based on value in another sheet and cell

Here is my own solution for restoring the original colors when copying certain highly formatted sheets or templates to a new spreadsheet.. it copies all data directly, so it only works if you need to copy a sheet, not only apply colors to a different sheet with different data:

copy the original format workbook by ctrl + g and selecting the appropriate range

paste it into the new work sheet, colors will be all changed

with the destination still highlighted, right click and go to "Paste special" and select "All using source theme", then repeat the paste special, only with "Values" this time, and it should be identical to the original sheet you copied

Android SDK location should not contain whitespace, as this cause problems with NDK tools

It is possible to make a symbolic link from e.g. C:\Android\sdk to the actual location of the sdk (which contains whitespaces), and refer to this symbolic link from within Android Studio as the location of the SDK. I have, however, not tried whether NDK will work with such a setup, even though Android Studio stops giving this warning about whitespaces.

What JSON library to use in Scala?

Play released its module for dealing with JSON independently from Play Framework, Play WS

Made a blog post about that, check it out at http://pedrorijo.com/blog/scala-json/

Using case classes, and Play WS (already included in Play Framework) you case convert between json and case classes with a simple one-liner implicit

case class User(username: String, friends: Int, enemies: Int, isAlive: Boolean)

object User {
  implicit val userJsonFormat = Json.format[User]
}

Delete from a table based on date

You could use:

DELETE FROM tableName
where your_date_column < '2009-01-01';

but Keep in mind that the above is really

DELETE FROM tableName
    where your_date_column < '2009-01-01 00:00:00';

Not

 DELETE FROM tableName
        where your_date_column < '2009-01-01 11:59';

Changing route doesn't scroll to top in the new page

This code worked great for me .. I hope it will also work great for you .. All you have to do is just inject $anchorScroll to your run block and apply listener function to the rootScope like I have done in the below example ..

 angular.module('myAngularApp')
.run(function($rootScope, Auth, $state, $anchorScroll){
    $rootScope.$on("$locationChangeSuccess", function(){
        $anchorScroll();
    });

Here's the calling order of Angularjs Module:

  1. app.config()
  2. app.run()
  3. directive's compile functions (if they are found in the dom)
  4. app.controller()
  5. directive's link functions (again, if found)

RUN BLOCK get executed after the injector is created and are used to kickstart the application.. it means when you redirected to the new route view ,the listener in the run block calls the

$anchorScroll()

and you can now see the scroll starts to the top with the new routed view :)

Calculating how many minutes there are between two times

In your quesion code you are using TimeSpan.FromMinutes incorrectly. Please see the MSDN Documentation for TimeSpan.FromMinutes, which gives the following method signature:

public static TimeSpan FromMinutes(double value)

hence, the following code won't compile

var intMinutes = TimeSpan.FromMinutes(varTime); // won't compile

Instead, you can use the TimeSpan.TotalMinutes property to perform this arithmetic. For instance:

TimeSpan varTime = (DateTime)varFinish - (DateTime)varValue; 
double fractionalMinutes = varTime.TotalMinutes;
int wholeMinutes = (int)fractionalMinutes;

How to disable horizontal scrolling of UIScrollView?

Introduced in iOS 11 is a new property on UIScrollView

var contentLayoutGuide: UILayoutGuide

The documentation states that you:

Use this layout guide when you want to create Auto Layout constraints related to the content area of a scroll view.

Along with any other Autolayout constraints that you might be adding you will want to constrain the widthAnchor of the UIScrollView's contentLayoutGuide to be the same size as the "frame". You can use the frameLayoutGuide (also introduced in iOS 11) or any external width (such as your superView's.)

example:

NSLayoutConstraint.activate([
  scrollView.contentLayoutGuide.widthAnchor.constraint(equalTo: self.widthAnchor)
])

Documentation: https://developer.apple.com/documentation/uikit/uiscrollview/2865870-contentlayoutguide

How can I enter latitude and longitude in Google Maps?

First is latitude, second longitude. Different than many constructors in mapbox.

Here are examples of formats that work:

  • Degrees, minutes, and seconds (DMS): 41°24'12.2"N 2°10'26.5"E
  • Degrees and decimal minutes (DMM): 41 24.2028, 2 10.4418
  • Decimal degrees (DD): 41.40338, 2.17403

Tips for formatting your coordinates

  • Use the degree symbol instead of “d”.
  • Use periods as decimals, not commas.
    • Incorrect: 41,40338, 2,17403.
    • Correct: 41.40338, 2.17403.
  • List your latitude coordinates before longitude coordinates.
  • Check that the first number in your latitude coordinate is between -90 and 90 and the first number in your longitude coordinate is between -180 and 180.

https://support.google.com/maps/answer/18539

align textbox and text/labels in html?

you can do a multi div layout like this

<div class="fieldcontainer">
    <div class="label"></div>
    <div class="field"></div>
</div>

where .fieldcontainer { clear: both; } .label { float: left; width: ___ } .field { float: left; }

Or, I actually prefer tables for forms like this. This is very much tabular data and it comes out very clean. Both will work though.

Spring-Security-Oauth2: Full authentication is required to access this resource

setting management.security.enabled=false in application.properties resolved the issue for me.

How to make HTTP Post request with JSON body in Swift

a combination of several answers found in my attempt to not use 3rd party frameworks like Alamofire.

    let body: [String: Any] = ["provider": "Google", "email": "[email protected]"]
    let api_url = "https://erics.es/p/u"
    let url = URL(string: api_url)!
    var request = URLRequest(url: url)

    do {
        let jsonData = try JSONSerialization.data(withJSONObject: body, options: .prettyPrinted)
        request.httpBody = jsonData
    } catch let e {
        print(e)
    }

    request.httpMethod = HTTPMethod.post.rawValue
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")

    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {
            print(error?.localizedDescription ?? "No data")
            return
        }
        let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
        if let responseJSON = responseJSON as? [String: Any] {
            print(responseJSON)
        }
    }

    task.resume()

You need to install postgresql-server-dev-X.Y for building a server-side extension or libpq-dev for building a client-side application

You must setup postgresql-server-dev-X.Y, where X.Y. your's servers version, and it will install libpq-dev and other servers variables at modules for server side developing. In my case it was

apt-get install postgresql-server-dev-9.5

Reading package lists... Done Building dependency tree Reading state information... Done The following packages were automatically installed and are no longer required: libmysqlclient18 mysql-common Use 'apt-get autoremove' to remove them. The following extra packages will be installed:
libpq-dev Suggested packages: postgresql-doc-10 The following NEW packages will be installed: libpq-dev postgresql-server-dev-9.5

In your's case

sudo apt-get install postgresql-server-dev-X.Y
sudo apt-get install python-psycopg2

Listen for key press in .NET console app

From the video curse Building .NET Console Applications in C# by Jason Roberts at http://www.pluralsight.com

We could do following to have multiple running process

  static void Main(string[] args)
    {
        Console.CancelKeyPress += (sender, e) =>
        {

            Console.WriteLine("Exiting...");
            Environment.Exit(0);
        };

        Console.WriteLine("Press ESC to Exit");

        var taskKeys = new Task(ReadKeys);
        var taskProcessFiles = new Task(ProcessFiles);

        taskKeys.Start();
        taskProcessFiles.Start();

        var tasks = new[] { taskKeys };
        Task.WaitAll(tasks);
    }

    private static void ProcessFiles()
    {
        var files = Enumerable.Range(1, 100).Select(n => "File" + n + ".txt");

        var taskBusy = new Task(BusyIndicator);
        taskBusy.Start();

        foreach (var file in files)
        {
            Thread.Sleep(1000);
            Console.WriteLine("Procesing file {0}", file);
        }
    }

    private static void BusyIndicator()
    {
        var busy = new ConsoleBusyIndicator();
        busy.UpdateProgress();
    }

    private static void ReadKeys()
    {
        ConsoleKeyInfo key = new ConsoleKeyInfo();

        while (!Console.KeyAvailable && key.Key != ConsoleKey.Escape)
        {

            key = Console.ReadKey(true);

            switch (key.Key)
            {
                case ConsoleKey.UpArrow:
                    Console.WriteLine("UpArrow was pressed");
                    break;
                case ConsoleKey.DownArrow:
                    Console.WriteLine("DownArrow was pressed");
                    break;

                case ConsoleKey.RightArrow:
                    Console.WriteLine("RightArrow was pressed");
                    break;

                case ConsoleKey.LeftArrow:
                    Console.WriteLine("LeftArrow was pressed");
                    break;

                case ConsoleKey.Escape:
                    break;

                default:
                    if (Console.CapsLock && Console.NumberLock)
                    {
                        Console.WriteLine(key.KeyChar);
                    }
                    break;
            }
        }
    }
}

internal class ConsoleBusyIndicator
{
    int _currentBusySymbol;

    public char[] BusySymbols { get; set; }

    public ConsoleBusyIndicator()
    {
        BusySymbols = new[] { '|', '/', '-', '\\' };
    }
    public void UpdateProgress()
    {
        while (true)
        {
            Thread.Sleep(100);
            var originalX = Console.CursorLeft;
            var originalY = Console.CursorTop;

            Console.Write(BusySymbols[_currentBusySymbol]);

            _currentBusySymbol++;

            if (_currentBusySymbol == BusySymbols.Length)
            {
                _currentBusySymbol = 0;
            }

            Console.SetCursorPosition(originalX, originalY);
        }
    }

Tomcat 8 throwing - org.apache.catalina.webresources.Cache.getResource Unable to add the resource

This isn’t a solution in the sense that it doesn’t resolve the conditions which cause the message to appear in the logs, but the message can be suppressed by appending the following to conf/logging.properties:

org.apache.catalina.webresources.Cache.level = SEVERE

This filters out the “Unable to add the resource” logs, which are at level WARNING.

In my view a WARNING is not necessarily an error that needs to be addressed, but rather can be ignored if desired.

Java Multithreading concept and join() method

join() is a instance method of java.lang.Thread class which we can use join() method to ensure all threads that started from main must end in order in which they started and also main should end in last. In other words waits for this thread to die.

Exception: join() method throws InterruptedException.

Thread state: When join() method is called on thread it goes from running to waiting state. And wait for thread to die.

synchronized block: Thread need not to acquire object lock before calling join() method i.e. join() method can be called from outside synchronized block.

Waiting time: join(): Waits for this thread to die.

public final void join() throws InterruptedException;

This method internally calls join(0). And timeout of 0 means to wait forever;

join(long millis) – synchronized method Waits at most millis milliseconds for this thread to die. A timeout of 0 means to wait forever.

public final synchronized void join(long millis)
    throws InterruptedException;

public final synchronized void join(long millis, int nanos)
    throws InterruptedException;

Example of join method

class MyThread implements Runnable {
     public void run() {
           String threadName = Thread.currentThread().getName();
           Printer.print("run() method of "+threadName);
           for(int i=0;i<4;i++){
                Printer.print("i="+i+" ,Thread="+threadName);
           }         
     }
}

public class TestJoin {
     public static void main(String...args) throws InterruptedException {
           Printer.print("start main()...");

           MyThread runnable = new MyThread();
           Thread thread1=new Thread(runnable);
           Thread thread2=new Thread(runnable);

           thread1.start();
           thread1.join();

           thread2.start();
           thread2.join();

           Printer.print("end main()");
     }
}

class Printer {
     public static void print(String str) {
           System.out.println(str);
     }
}

Output:
     start main()...
     run() method of Thread-0
     i=0 ,Thread=Thread-0
     i=1 ,Thread=Thread-0
     i=2 ,Thread=Thread-0
     i=3 ,Thread=Thread-0
     run() method of Thread-1
     i=0 ,Thread=Thread-1
     i=1 ,Thread=Thread-1
     i=2 ,Thread=Thread-1
     i=3 ,Thread=Thread-1
     end main()

Note: calling thread1.join() made main thread to wait until Thread-1 dies.

Let’s check a program to use join(long millis)

First, join(1000) will be called on Thread-1, but once 1000 millisec are up, main thread can resume and start thread2 (main thread won’t wait for Thread-1 to die).

class MyThread implements Runnable {
     public void run() {
           String threadName = Thread.currentThread().getName();
           Printer.print("run() method of "+threadName);
           for(int i=0;i<4;i++){
                try {
                     Thread.sleep(500);
                } catch (InterruptedException e) {
                     e.printStackTrace();
                }
                Printer.print("i="+i+" ,Thread="+threadName);
           }         
     }
}

public class TestJoin {
     public static void main(String...args) throws InterruptedException {
           Printer.print("start main()...");

           MyThread runnable = new MyThread();
           Thread thread1=new Thread(runnable);
           Thread thread2=new Thread(runnable);

           thread1.start();

           // once 1000 millisec are up,
           // main thread can resume and start thread2.
           thread1.join(1000);

           thread2.start();
           thread2.join();

           Printer.print("end main()");
     }
}

class Printer {
     public static void print(String str) {
           System.out.println(str);
     }
}

Output:
     start main()...
     run() method of Thread-0
     i=0 ,Thread=Thread-0
     run() method of Thread-1
     i=1 ,Thread=Thread-0
     i=2 ,Thread=Thread-0
     i=0 ,Thread=Thread-1
     i=1 ,Thread=Thread-1
     i=3 ,Thread=Thread-0
     i=2 ,Thread=Thread-1
     i=3 ,Thread=Thread-1
     end main()

For more information see my blog:

http://javaexplorer03.blogspot.in/2016/05/join-method-in-java.html

What is console.log in jQuery?

it will print log messages in your developer console (firebug/webkit dev tools/ie dev tools)

QUERY syntax using cell reference

none of the above answers worked for me. This one did:

=QUERY(Copy!A1:AP, "select AP, E, F, AO where AP="&E1&" ",1)

Specify JDK for Maven to use

Seems that maven now gives a solution here : Compiling Sources Using A Different JDK

Let's say your JAVA_HOME points to JDK7 (which will run maven processes)

Your pom.xml could be :

<build>
    <plugins>
        <!-- we want JDK 1.6 source and binary compatiblility -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>1.6</source>
                <target>1.6</target>
            </configuration>
        </plugin>
        <!-- ... -->
        <!-- we want sources to be processed by a specific 1.6 javac -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
              <verbose>true</verbose>
              <fork>true</fork>
              <executable>${JAVA_1_6_HOME}/bin/javac</executable>
              <compilerVersion>1.3</compilerVersion>
            </configuration>
        </plugin>
    </plugins>
</build>

If your developpers just add (and customize) the following lines in their settings.xml, your pom will be platform independant :

<settings>
  [...]
  <profiles>
    [...]
    <profile>
      <id>compiler</id>
        <properties>
          <JAVA_1_4_HOME>C:\Program Files\Java\j2sdk1.4.2_09</JAVA_1_4_HOME>
          <JAVA_1_6_HOME>C:\Program Files\Java\j2sdk1.6.0_18</JAVA_1_6_HOME>
        </properties>
    </profile>
  </profiles>
  [...]
  <activeProfiles>
    <activeProfile>compiler</activeProfile>
  </activeProfiles>
</settings>

Could not load file or assembly 'System.Net.Http.Formatting' or one of its dependencies. The system cannot find the path specified

As originally suggested in a comment by GeoMac and documented on NuGet's docs the following worked for me when none of the other answers worked:

Tools / NuGet Package Manager / Package Manager Console

Update-Package -ProjectName MyProjectName -reinstall

What is your single most favorite command-line trick using Bash?

To be able to quickly edit a shell script you know is in your $PATH (do not try with ls...):

function viscr { vi $(which $*); }

Catch browser's "zoom" event in JavaScript

Although this is a 9 yr old question, the problem persists!

I have been detecting resize while excluding zoom in a project, so I edited my code to make it work to detect both resize and zoom exclusive from one another. It works most of the time, so if most is good enough for your project, then this should be helpful! It detects zooming 100% of the time in what I've tested so far. The only issue is that if the user gets crazy (ie. spastically resizing the window) or the window lags it may fire as a zoom instead of a window resize.

It works by detecting a change in window.outerWidth or window.outerHeight as window resizing while detecting a change in window.innerWidth or window.innerHeight independent from window resizing as a zoom.

_x000D_
_x000D_
//init object to store window properties_x000D_
var windowSize = {_x000D_
  w: window.outerWidth,_x000D_
  h: window.outerHeight,_x000D_
  iw: window.innerWidth,_x000D_
  ih: window.innerHeight_x000D_
};_x000D_
_x000D_
window.addEventListener("resize", function() {_x000D_
  //if window resizes_x000D_
  if (window.outerWidth !== windowSize.w || window.outerHeight !== windowSize.h) {_x000D_
    windowSize.w = window.outerWidth; // update object with current window properties_x000D_
    windowSize.h = window.outerHeight;_x000D_
    windowSize.iw = window.innerWidth;_x000D_
    windowSize.ih = window.innerHeight;_x000D_
    console.log("you're resizing"); //output_x000D_
  }_x000D_
  //if the window doesn't resize but the content inside does by + or - 5%_x000D_
  else if (window.innerWidth + window.innerWidth * .05 < windowSize.iw ||_x000D_
    window.innerWidth - window.innerWidth * .05 > windowSize.iw) {_x000D_
    console.log("you're zooming")_x000D_
    windowSize.iw = window.innerWidth;_x000D_
  }_x000D_
}, false);
_x000D_
_x000D_
_x000D_

Note: My solution is like KajMagnus's, but this has worked better for me.

What is the purpose of Android's <merge> tag in XML layouts?

To have a more in-depth knowledge of what's happening, I created the following example. Have a look at the activity_main.xml and content_profile.xml files.

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <include layout="@layout/content_profile" />

</LinearLayout>

content_profile.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Howdy" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Hi there" />

</LinearLayout>

In here, the entire layout file when inflated looks like this.

<LinearLayout>
    <LinearLayout>
        <TextView />
        <TextView />
    </LinearLayout>
</LinearLayout>

See that there is a LinearLayout inside the parent LinearLayout which doesn't serve any purpose and is redundant. A look at the layout through Layout Inspector tool clearly explains this.

enter image description here

content_profile.xml after updating the code to use merge instead of a ViewGroup like LinearLayout.

<merge xmlns:android="http://schemas.android.com/apk/res/android">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Howdy" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Hi there" />

</merge>

Now our layout looks like this

<LinearLayout>
    <TextView />
    <TextView />
</LinearLayout>

Here we see that the redundant LinearLayout ViewGroup is removed. Now Layout Inspector tool gives the following layout hierarchy.

enter image description here

So always try to use merge when your parent layout can position your child layouts, or more precisely use merge when you understand that there is going to be a redundant view group in the hierarchy.

Best practice when adding whitespace in JSX

If the goal is to seperate two elements, you can use CSS like below:

A<span style={{paddingLeft: '20px'}}>B</span>

Create a git patch from the uncommitted changes in the current working directory

I like:

git format-patch HEAD~<N>

where <N> is number of last commits to save as patches.

The details how to use the command are in the DOC

UPD
Here you can find how to apply them then.

UPD For those who did not get the idea of format-patch
Add alias:

git config --global alias.make-patch '!bash -c "cd ${GIT_PREFIX};git add .;git commit -m ''uncommited''; git format-patch HEAD~1; git reset HEAD~1"'

Then at any directory of your project repository run:

git make-patch

This command will create 0001-uncommited.patch at your current directory. Patch will contain all the changes and untracked files that are visible to next command:

git status .

how to display data values on Chart.js

Following this good answer, I'd use these options for a bar chart:

var chartOptions = {
    animation: false,
    responsive : true,
    tooltipTemplate: "<%= value %>",
    tooltipFillColor: "rgba(0,0,0,0)",
    tooltipFontColor: "#444",
    tooltipEvents: [],
    tooltipCaretSize: 0,
    onAnimationComplete: function()
    {
        this.showTooltip(this.datasets[0].bars, true);
    }
};

window.myBar = new Chart(ctx1).Bar(chartData, chartOptions);

Bar Chart

This still uses the tooltip system and his advantages (automatic positionning, templating, ...) but hiding the decorations (background color, caret, ...)

What is unexpected T_VARIABLE in PHP?

It could be some other line as well. PHP is not always that exact.

Probably you are just missing a semicolon on previous line.

How to reproduce this error, put this in a file called a.php:

<?php
  $a = 5
  $b = 7;        // Error happens here.
  print $b;
?>

Run it:

eric@dev ~ $ php a.php

PHP Parse error:  syntax error, unexpected T_VARIABLE in
/home/el/code/a.php on line 3

Explanation:

The PHP parser converts your program to a series of tokens. A T_VARIABLE is a Token of type VARIABLE. When the parser processes tokens, it tries to make sense of them, and throws errors if it receives a variable where none is allowed.

In the simple case above with variable $b, the parser tried to process this:

$a = 5 $b = 7;

The PHP parser looks at the $b after the 5 and says "that is unexpected".

Could not extract response: no suitable HttpMessageConverter found for response type

Since you return to the client just String and its content type == 'text/plain', there is no any chance for default converters to determine how to convert String response to the FFSampleResponseHttp object.

The simple way to fix it:

  • remove expected-response-type from <int-http:outbound-gateway>
  • add to the replyChannel1 <json-to-object-transformer>

Otherwise you should write your own HttpMessageConverter to convert the String to the appropriate object.

To make it work with MappingJackson2HttpMessageConverter (one of default converters) and your expected-response-type, you should send your reply with content type = 'application/json'.

If there is a need, just add <header-enricher> after your <service-activator> and before sending a reply to the <int-http:inbound-gateway>.

So, it's up to you which solution to select, but your current state doesn't work, because of inconsistency with default configuration.

UPDATE

OK. Since you changed your server to return FfSampleResponseHttp object as HTTP response, not String, just add contentType = 'application/json' header before sending the response for the HTTP and MappingJackson2HttpMessageConverter will do the stuff for you - your object will be converted to JSON and with correct contentType header.

From client side you should come back to the expected-response-type="com.mycompany.MyChannel.model.FFSampleResponseHttp" and MappingJackson2HttpMessageConverter should do the stuff for you again.

Of course you should remove <json-to-object-transformer> from you message flow after <int-http:outbound-gateway>.

Programmatically trigger "select file" dialog box

If you're looking to have your own button to upload a file instead of using <input type="file" />, you can do something like:

<input id="myInput" type="file" style="visibility:hidden" />
<input type="button" value="Show Dialog" onclick="$('#myInput').click();" />

Note that I used visibility: hidden, instead of display: none. You cannot call the click event on a non-displayed file input.

How do I POST JSON data with cURL?

You can use Postman with its intuitive GUI to assemble your cURL command.

  1. Install and Start Postman
  2. Type in your URL, Post Body, Request Headers etc. pp.
  3. Click on Code
  4. Select cURL from the drop-down list
  5. copy & paste your cURL command

Note: There are several options for automated request generation in the drop-down list, which is why I thought my post was neccessary in the first place.

Tkinter module not found on Ubuntu

If you are using Ubuntu 18.04 along with Python 3.6, then pip or pip3 won't help. You need to install tkinter using following command:

sudo apt-get install python3-tk

How to invoke a Linux shell command from Java

Use ProcessBuilder to separate commands and arguments instead of spaces. This should work regardless of shell used:

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class Test {

    public static void main(final String[] args) throws IOException, InterruptedException {
        //Build command 
        List<String> commands = new ArrayList<String>();
        commands.add("/bin/cat");
        //Add arguments
        commands.add("/home/narek/pk.txt");
        System.out.println(commands);

        //Run macro on target
        ProcessBuilder pb = new ProcessBuilder(commands);
        pb.directory(new File("/home/narek"));
        pb.redirectErrorStream(true);
        Process process = pb.start();

        //Read output
        StringBuilder out = new StringBuilder();
        BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line = null, previous = null;
        while ((line = br.readLine()) != null)
            if (!line.equals(previous)) {
                previous = line;
                out.append(line).append('\n');
                System.out.println(line);
            }

        //Check result
        if (process.waitFor() == 0) {
            System.out.println("Success!");
            System.exit(0);
        }

        //Abnormal termination: Log command parameters and output and throw ExecutionException
        System.err.println(commands);
        System.err.println(out.toString());
        System.exit(1);
    }
}

How to escape JSON string?

I use System.Web.HttpUtility.JavaScriptStringEncode

string quoted = HttpUtility.JavaScriptStringEncode(input);

Jackson and generic type reference

'JavaType' works !! I was trying to unmarshall (deserialize) a List in json String to ArrayList java Objects and was struggling to find a solution since days.
Below is the code that finally gave me solution. Code:

JsonMarshallerUnmarshaller<T> {
    T targetClass;

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

        AnnotationIntrospector introspector = new JacksonAnnotationIntrospector();
        mapper.getDeserializationConfig()
            .withAnnotationIntrospector(introspector);

        mapper.getSerializationConfig()
            .withAnnotationIntrospector(introspector);
        JavaType type = mapper.getTypeFactory().
            constructCollectionType(
                ArrayList.class, 
                targetclass.getClass());

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

        return null ;
    }  
}

How to skip the OPTIONS preflight request?

setting the content-type to undefined would make javascript pass the header data As it is , and over writing the default angular $httpProvider header configurations. Angular $http Documentation

$http({url:url,method:"POST", headers:{'Content-Type':undefined}).then(success,failure);

How to serve .html files with Spring

Java configuration for html files (in this case index.html):

@Configuration
@EnableWebMvc
public class DispatcherConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        registry.addResourceHandler("/index.html").addResourceLocations("/index.html");
    }

}

undefined reference to boost::system::system_category() when compiling

When I had this, problem, the cause was the ordering of the libraries. To fix it, I put libboost_system last:

g++ mingw/timer1.o -o mingw/timer1.exe  -L/usr/local/boost_1_61_0/stage/lib \
    -lboost_timer-mgw53-mt-1_61 \
    -lboost_chrono-mgw53-mt-1_61 \
    -lboost_system-mgw53-mt-1_61

This was on mingw with gcc 5.3 and boost 1.61.0 with a simple timer example.

Replace single quotes in SQL Server

You could use char(39)

insert into my_table values('hi, my name'+char(39)+'s tim.')

Or in this case:

Replace(@strip,char(39),'')

LINQ to read XML

A couple of plain old foreach loops provides a clean solution:

foreach (XElement level1Element in XElement.Load("data.xml").Elements("level1"))
{
    result.AppendLine(level1Element.Attribute("name").Value);

    foreach (XElement level2Element in level1Element.Elements("level2"))
    {
        result.AppendLine("  " + level2Element.Attribute("name").Value);
    }
}

TypeLoadException says 'no implementation', but it is implemented

I encountered this when I renamed a project (and the assembly name), which was depended upon by an ASP.NET project. Types in the web project implemented interfaces in the dependent assembly. Despite executing Clean Solution from the Build menu, the assembly with the previous name remained in the bin folder, and when my web project executed

var types = AppDomain.CurrentDomain.
   GetAssemblies().
   ToList().
   SelectMany( s => s.GetTypes() /* exception thrown in this call */ )
;

the above exception was thrown, complaining that interface methods in the implementing web types were not actually implemented. Manually deleting the assembly in the web project's bin folder resolved the problem.

SELECT FOR UPDATE with SQL Server

You have to deal with the exception at commit time and repeat the transaction.

Regex, every non-alphanumeric character except white space or colon

Try this:

[^a-zA-Z0-9 :]

JavaScript example:

"!@#$%* ABC def:123".replace(/[^a-zA-Z0-9 :]/g, ".")

See a online example:

http://jsfiddle.net/vhMy8/

T-SQL loop over query results

DECLARE @id INT
DECLARE @name NVARCHAR(100)
DECLARE @getid CURSOR

SET @getid = CURSOR FOR
SELECT table.id,
       table.name
FROM   table

WHILE 1=1
BEGIN

    FETCH NEXT
    FROM @getid INTO @id, @name
    IF @@FETCH_STATUS < 0 BREAK

    EXEC stored_proc @varName=@id, @otherVarName='test', @varForName=@name

END

CLOSE @getid
DEALLOCATE @getid

How to add elements of a Java8 stream into an existing List

Erik Allik already gave very good reasons, why you will most likely not want to collect elements of a stream into an existing List.

Anyway, you can use the following one-liner, if you really need this functionality.

But as Stuart Marks explains in his answer, you should never do this, if the streams might be parallel streams - use at your own risk...

list.stream().collect(Collectors.toCollection(() -> myExistingList));

How does the keyword "use" work in PHP and can I import classes with it?

use doesn't include anything. It just imports the specified namespace (or class) to the current scope

If you want the classes to be autoloaded - read about autoloading

How to set focus on a view when a layout is created and displayed?

You can start by adding android:windowSoftInputMode to your activity in AndroidManifest.xml file.

<activity android:name="YourActivity"
          android:windowSoftInputMode="stateHidden" />

This will make the keyboard to not show, but EditText is still got focus. To solve that, you can set android:focusableInTouchmode and android:focusable to true on your root view.

<LinearLayout android:orientation="vertical"
              android:focusable="true"
              android:focusableInTouchMode="true"
              ...
              >
    <EditText
         ...
       />
    <TextView
         ...
       />
    <Button
         ...
       />
</LinearLayout>

The code above will make sure that RelativeLayout is getting focus instead of EditText

How to decrypt hash stored by bcrypt

# Maybe you search this ??
For example in my case I use Symfony 4.4 (PHP).
If you want to update User, you need to insert the User password 
encrypted and test with the current Password not encrypted to verify 
if it's the same User. 

For example :

public function updateUser(Request $req)
      {
         $entityManager = $this->getDoctrine()->getManager();
         $repository = $entityManager->getRepository(User::class);
         $user = $repository->find($req->get(id)); /// get User from your DB

         if($user == null){
            throw  $this->createNotFoundException('User don't exist!!', $user);
         }
         $password_old_encrypted = $user->getPassword();//in your DB is always encrypted.
         $passwordToUpdate = $req->get('password'); // not encrypted yet from request.

         $passwordToUpdateEncrypted = password_hash($passwordToUpdate , PASSWORD_DEFAULT);

          ////////////VERIFY IF IT'S THE SAME PASSWORD
         $isPass = password_verify($passwordToUpdateEncrypted , $password_old_encrypted );

         if($isPass === false){ // failure
            throw  $this->createNotFoundException('Your password it's not verify', null);
         }

        return $isPass; //// true!! it's the same password !!!

      }

SqlDataAdapter vs SqlDataReader

The Fill function uses a DataReader internally. If your consideration is "Which one is more efficient?", then using a DataReader in a tight loop that populates a collection record-by-record, is likely to be the same load on the system as using DataAdapter.Fill.

(System.Data.dll, System.Data.Common.DbDataAdapter, FillInternal.)

How to change text color and console color in code::blocks?

An Easy Approach...

system("Color F0");

Letter Represents Background Color while the number represents the text color.

0 = Black

1 = Blue

2 = Green

3 = Aqua

4 = Red

5 = Purple

6 = Yellow

7 = White

8 = Gray

9 = Light Blue

A = Light Green

B = Light Aqua

C = Light Red

D = Light Purple

E = Light Yellow

F = Bright White

HTML Input - already filled in text

You seem to look for the input attribute value, "the initial value of the control"?

<input type="text" value="Morlodenhof 7" />

https://developer.mozilla.org/de/docs/Web/HTML/Element/Input#attr-value

How to position two elements side by side using CSS

you can simple use some div to make a container and the display: flex; to make the content appear side-by-side like this:

CSS

.splitscreen {
    display:flex;
}
.splitscreen .left {
    flex: 1;
}
.splitscreen .right {
    flex: 1;
}

HTML

<div class="splitscreen">
    <div class="left">
        <!-- content -->
    </div>

    <div class="right">
        <!-- content -->
    </div>
</div>

using flex you say who will use more space on the screen.

Sonar properties files

Do the build job on Jenkins first without Sonar configured. Then add Sonar, and run a build job again. Should fix the problem

Why is "cursor:pointer" effect in CSS not working

I have the same issue, when I close the chrome window popup browser inspector its working fine for me.

Attempt to set a non-property-list object as an NSUserDefaults

https://developer.apple.com/reference/foundation/userdefaults

A default object must be a property list—that is, an instance of (or for collections, a combination of instances of): NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary.

If you want to store any other type of object, you should typically archive it to create an instance of NSData. For more details, see Preferences and Settings Programming Guide.

Android - Handle "Enter" in an EditText

Kotlin solution to react to enter press using Lambda expression:

        editText.setOnKeyListener { _, keyCode, event ->
            if(keyCode == KeyEvent.KEYCODE_ENTER && event.action==KeyEvent.ACTION_DOWN){
            //react to enter press here
            }
            true
        }

not doing the additional check for the type of event will cause this listener to be called twice when pressed once (once for ACTION_DOWN, once for ACTION_UP)

Getting visitors country from their IP

There is a well-maintained flat-file version of the ip->country database maintained by the Perl community at CPAN

Access to those files does not require a dataserver, and the data itself is roughly 515k

Higemaru has written a PHP wrapper to talk to that data: php-ip-country-fast

Setting max width for body using Bootstrap

In responsive.less, you can comment out the line that imports responsive-1200px-min.less.

// Large desktops

@import "responsive-1200px-min.less";

Like so:

// Large desktops

// @import "responsive-1200px-min.less";

How to copy a string of std::string type in C++?

Caesar's solution is the best in my opinion, but if you still insist to use the strcpy function, then after you have your strings ready:

string a = "text";
string b = "image";

You can try either:

strcpy(a.data(), b.data());

or

strcpy(a.c_str(), b.c_str());

Just call either the data() or c_str() member functions of the std::string class, to get the char* pointer of the string object.

The strcpy() function doesn't have overload to accept two std::string objects as parameters. It has only one overload to accept two char* pointers as parameters.

Both data and c_str return what does strcpy() want exactly.

Using HTML5/JavaScript to generate and save a file

When testing the "ahref" method, I found that the web developer tools of Firefox and Chrome gets confused. I needed to restart the debugging after the a.click() was issued. Same happened with the FileSaver (it uses the same ahref method to actually make the saving). To work around it, I created new temporary window, added the element a into that and clicked it there.

    function download_json(dt) {
        var csv = ' var data = ';
        csv += JSON.stringify(dt, null, 3);

        var uricontent = 'data:application/octet-stream,' + encodeURI(csv);

        var newwin = window.open( "", "_blank" );
        var elem = newwin.document.createElement('a');
        elem.download = "database.js";
        elem.href = uricontent;
        elem.click();
        setTimeout(function(){ newwin.close(); }, 3000);
        
    }

Effective way to find any file's Encoding

Check this.

UDE

This is a port of Mozilla Universal Charset Detector and you can use it like this...

public static void Main(String[] args)
{
    string filename = args[0];
    using (FileStream fs = File.OpenRead(filename)) {
        Ude.CharsetDetector cdet = new Ude.CharsetDetector();
        cdet.Feed(fs);
        cdet.DataEnd();
        if (cdet.Charset != null) {
            Console.WriteLine("Charset: {0}, confidence: {1}", 
                 cdet.Charset, cdet.Confidence);
        } else {
            Console.WriteLine("Detection failed.");
        }
    }
}

how to set textbox value in jquery

try

subtotal.value= 5 // some value

_x000D_
_x000D_
proc = async function(x,y) {_x000D_
  let url = "https://server.test-cors.org/server?id=346169&enable=true&status=200&credentials=false&methods=GET&" // some url working in snippet_x000D_
  _x000D_
  let r= await(await fetch(url+'&prodid=' + x + '&qbuys=' + y)).json(); // return json-object_x000D_
  console.log(r);_x000D_
  _x000D_
  subtotal.value= r.length; // example value from json_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<form name="yoh" method="get"> _x000D_
Product id: <input type="text" id="pid"  value=""><br/>_x000D_
_x000D_
Quantity to buy:<input type="text" id="qtytobuy"  value="" onkeyup="proc(pid.value, this.value);"></br>_x000D_
_x000D_
Subtotal:<input type="text" name="subtotal" id="subtotal"  value=""></br>_x000D_
<div id="compz"></div>_x000D_
_x000D_
</form>
_x000D_
_x000D_
_x000D_

How to mock void methods with Mockito

First of all: you should always import mockito static, this way the code will be much more readable (and intuitive):

import static org.mockito.Mockito.*;

For partial mocking and still keeping original functionality on the rest mockito offers "Spy".

You can use it as follows:

private World world = spy(new World());

To eliminate a method from being executed you could use something like this:

doNothing().when(someObject).someMethod(anyObject());

to give some custom behaviour to a method use "when" with an "thenReturn":

doReturn("something").when(this.world).someMethod(anyObject());

For more examples please find the excellent mockito samples in the doc.

Configure DataSource programmatically in Spring Boot

You can use DataSourceBuilder if you are using jdbc starter. Also, in order to override the default autoconfiguration bean you need to mark your bean as a @Primary

In my case I have properties starting with datasource.postgres prefix.

E.g

@ConfigurationProperties(prefix = "datasource.postgres")
@Bean
@Primary
public DataSource dataSource() {
    return DataSourceBuilder
        .create()
        .build();
}

If it is not feasible for you, then you can use

@Bean
@Primary
public DataSource dataSource() {
    return DataSourceBuilder
        .create()
        .username("")
        .password("")
        .url("")
        .driverClassName("")
        .build();
}

How do you handle multiple submit buttons in ASP.NET MVC Framework?

When using ajax forms, we can use ActionLinks with POST HttpMethod and serialize the form in the AjaxOptions.OnBegin event.

Let's say you have two actions, InsertAction and UpdateAction:

<form>
    @Html.Hidden("SomeField", "SomeValue")

    @Ajax.ActionLink(
        "Insert",
        "InsertAction",
        null,
        new AjaxOptions { 
            OnBegin = "OnBegin", 
            UpdateTargetId = "yourDiv", 
            HttpMethod = "POST" })
    @Ajax.ActionLink(
        "Update",
        "UpdateAction",
        null,
        new AjaxOptions { 
            OnBegin = "OnBegin", 
            UpdateTargetId = "yourDiv", 
            HttpMethod = "POST" })
</form>

Javascript

function OnBegin(xhr, settings) {
    settings.data = $("form").serialize();
}

Nesting queries in SQL

Query below should help you achieve what you want.

select scountry, headofstate from data 
where data.scountry like 'a%'and ttlppl>=100000

C++ Redefinition Header Files (winsock2.h)

I've run into the same issue and here is what I have discovered so far:

From this output fragment -

c:\program files\microsoft sdks\windows\v6.0a\include\ws2def.h(91) : warning C4005: 'AF_IPX' : macro redefinition
c:\program files\microsoft sdks\windows\v6.0a\include\winsock.h(460) : see previous definition of 'AF_IPX'

-It appears that both ws2def.h and winsock.h have been included in your solution.

If you look at the file ws2def.h it starts with the following comment -

/*++

Copyright (c) Microsoft Corporation. All rights reserved.

Module Name:

    ws2def.h

Abstract:

    This file contains the core definitions for the Winsock2
    specification that can be used by both user-mode and 
    kernel mode modules.

    This file is included in WINSOCK2.H. User mode applications
    should include WINSOCK2.H rather than including this file
    directly. This file can not be included by a module that also
    includes WINSOCK.H.

Environment:

    user mode or kernel mode

--*/

Pay attention to the last line - "This file can not be included by a module that also includes WINSOCK.H"

Still trying to rectify the problem without making changes to the code.

Let me know if this makes sense.

Using AJAX to pass variable to PHP and retrieve those using AJAX again

No need to use second ajax function, you can get it back on success inside a function, another issue here is you don't know when the first ajax call finished, then, even if you use SESSION you may not get it within second AJAX call.

SO, I recommend using one AJAX call and get the value with success.

example: in first ajax call

    $.ajax({
        url: 'ajax.php', //This is the current doc
        type: "POST",
        data: ({name: 145}),
        success: function(data){
            console.log(data);
            alert(data);
            //or if the data is JSON
            var jdata = jQuery.parseJSON(data);
        }
    }); 

Activity, AppCompatActivity, FragmentActivity, and ActionBarActivity: When to Use Which?

Since the name is likely to change in future versions of Android (currently the latest is AppCompatActivity but it will probably change at some point), I believe a good thing to have is a class Activity that extends AppCompatActivity and then all your activities extend from that one. If tomorrow, they change the name to AppCompatActivity2 for instance you will have to change it just in one place.

Breaking/exit nested for in vb.net

For i As Integer = 0 To 100
    bool = False
    For j As Integer = 0 To 100
        If check condition Then
            'if condition match
            bool = True
            Exit For 'Continue For
        End If
    Next
    If bool = True Then Continue For
Next

Convert base class to derived class

You can implement the conversion yourself, but I would not recommend that. Take a look at the Decorator Pattern if you want to do this in order to extend the functionality of an existing object.

What is the python "with" statement designed for?

  1. I believe this has already been answered by other users before me, so I only add it for the sake of completeness: the with statement simplifies exception handling by encapsulating common preparation and cleanup tasks in so-called context managers. More details can be found in PEP 343. For instance, the open statement is a context manager in itself, which lets you open a file, keep it open as long as the execution is in the context of the with statement where you used it, and close it as soon as you leave the context, no matter whether you have left it because of an exception or during regular control flow. The with statement can thus be used in ways similar to the RAII pattern in C++: some resource is acquired by the with statement and released when you leave the with context.

  2. Some examples are: opening files using with open(filename) as fp:, acquiring locks using with lock: (where lock is an instance of threading.Lock). You can also construct your own context managers using the contextmanager decorator from contextlib. For instance, I often use this when I have to change the current directory temporarily and then return to where I was:

    from contextlib import contextmanager
    import os
    
    @contextmanager
    def working_directory(path):
        current_dir = os.getcwd()
        os.chdir(path)
        try:
            yield
        finally:
            os.chdir(current_dir)
    
    with working_directory("data/stuff"):
        # do something within data/stuff
    # here I am back again in the original working directory
    

    Here's another example that temporarily redirects sys.stdin, sys.stdout and sys.stderr to some other file handle and restores them later:

    from contextlib import contextmanager
    import sys
    
    @contextmanager
    def redirected(**kwds):
        stream_names = ["stdin", "stdout", "stderr"]
        old_streams = {}
        try:
            for sname in stream_names:
                stream = kwds.get(sname, None)
                if stream is not None and stream != getattr(sys, sname):
                    old_streams[sname] = getattr(sys, sname)
                    setattr(sys, sname, stream)
            yield
        finally:
            for sname, stream in old_streams.iteritems():
                setattr(sys, sname, stream)
    
    with redirected(stdout=open("/tmp/log.txt", "w")):
         # these print statements will go to /tmp/log.txt
         print "Test entry 1"
         print "Test entry 2"
    # back to the normal stdout
    print "Back to normal stdout again"
    

    And finally, another example that creates a temporary folder and cleans it up when leaving the context:

    from tempfile import mkdtemp
    from shutil import rmtree
    
    @contextmanager
    def temporary_dir(*args, **kwds):
        name = mkdtemp(*args, **kwds)
        try:
            yield name
        finally:
            shutil.rmtree(name)
    
    with temporary_dir() as dirname:
        # do whatever you want
    

Full Page <iframe>

Here's the working code. Works in desktop and mobile browsers. hope it helps. thanks for everyone responding.

<!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>
        <title>Test Layout</title>
        <style type="text/css">
            body, html
            {
                margin: 0; padding: 0; height: 100%; overflow: hidden;
            }

            #content
            {
                position:absolute; left: 0; right: 0; bottom: 0; top: 0px; 
            }
        </style>
    </head>
    <body>
        <div id="content">
            <iframe width="100%" height="100%" frameborder="0" src="http://cnn.com" />
        </div>
    </body>
</html>

Java: Multiple class declarations in one file

You can have as many classes as you wish like this

public class Fun {
    Fun() {
        System.out.println("Fun constructor");
    }
    void fun() {
        System.out.println("Fun mathod");
    }
    public static void main(String[] args) {
        Fun fu = new Fun();
        fu.fun();
        Fen fe = new Fen();
        fe.fen();
        Fin fi = new Fin();
        fi.fin();
        Fon fo = new Fon();
        fo.fon();
        Fan fa = new Fan();
        fa.fan();
        fa.run();
    }
}

class Fen {
    Fen() {
        System.out.println("fen construuctor");

    }
    void fen() {
        System.out.println("Fen method");
    }
}

class Fin {
    void fin() {
        System.out.println("Fin method");
    }
}

class Fon {
    void fon() {
        System.out.println("Fon method");
    } 
}

class Fan {
    void fan() {
        System.out.println("Fan method");
    }
    public void run() {
        System.out.println("run");
    }
}

HttpClient does not exist in .net 4.0: what can I do?

I've used HttpClient in .NET 4.0 applications on numerous occasions. If you are familiar with NuGet, you can do an Install-Package Microsoft.Net.Http to add it to your project. See the link below for further details.

http://nuget.org/packages/Microsoft.Net.Http

CSS fixed width in a span

Unfortunately inline elements (or elements having display:inline) ignore the width property. You should use floating divs instead:

<style type="text/css">
div.f1 { float: left; width: 20px; }
div.f2 { float: left; }
div.f3 { clear: both; }
</style>

<div class="f1"></div><div class="f2">The Lazy dog</div><div class="f3"></div>
<div class="f1">AND</div><div class="f2">The Lazy cat</div><div class="f3"></div>
<div class="f1">OR</div><div class="f2">The active goldfish</div><div class="f3"></div>

Now I see you need to use spans and lists, so we need to rewrite this a little bit:

<html><head>
<style type="text/css">
        span.f1 { display: block; float: left; clear: left; width: 60px; }
    li { list-style-type: none; }
    </style>

</head><body>
<ul>
<li><span class="f1">&nbsp;</span>The lazy dog.</li>
<li><span class="f1">AND</span> The lazy cat.</li>
<li><span class="f1">OR</span> The active goldfish.</li>
</ul>
</body>
</html>

IE11 meta element Breaks SVG

I figured it out! The page was rendering using IE8 mode... had

<meta http-equiv="X-UA-Compatible" content="IE=8">

in the header... changed it to

<meta http-equiv="X-UA-Compatible" content="IE=9">

9 and it worked!

How to get sp_executesql result into a variable?

DECLARE @tab AS TABLE (col1 VARCHAR(10), col2 varchar(10)) 
INSERT into @tab EXECUTE  sp_executesql N'
SELECT 1 AS col1, 2 AS col2
UNION ALL
SELECT 1 AS col1, 2 AS col2
UNION ALL
SELECT 1 AS col1, 2 AS col2'

SELECT * FROM @tab

MySQL Workbench: "Can't connect to MySQL server on 127.0.0.1' (10061)" error

To connect to a new server, you click on home + add new connection. Put IP or webserver URL in new connection.

how to create

Set QLineEdit to accept only numbers

You could also set an inputMask:

QLineEdit.setInputMask("9")

This allows the user to type only one digit ranging from 0 to 9. Use multiple 9's to allow the user to enter multiple numbers. See also the complete list of characters that can be used in an input mask.

(My answer is in Python, but it should not be hard to transform it to C++)

installing vmware tools: location of GCC binary?

Install prerequisites VMware Tools for LinuxOS:

If you have RHEL/CentOS:

yum install perl gcc make kernel-headers kernel-devel -y

If you have Ubuntu/Debian:

sudo apt-get -y install linux-headers-server build-essential
  • build-essential, also install: dpkg-dev, g++, gcc, lib6-dev, libc-dev, make

Extracted from: http://www.sysadmit.com/2016/01/vmware-tools-linux-instalar-requisitos.html

How to use sys.exit() in Python

In tandem with what Pedro Fontez said a few replies up, you seemed to never call the sys module initially, nor did you manage to stick the required () at the end of sys.exit:

so:

import sys

and when finished:

sys.exit()

How to find the Windows version from the PowerShell command line

Since you have access to the .NET library, you could access the OSVersion property of the System.Environment class to get this information. For the version number, there is the Version property.

For example,

PS C:\> [System.Environment]::OSVersion.Version

Major  Minor  Build  Revision
-----  -----  -----  --------
6      1      7601   65536

Details of Windows versions can be found here.

Creating an iframe with given HTML dynamically

The URL approach will only work for small HTML fragements. The more solid approach is to generate an object URL from a blob and use it as a source of the dynamic iframe.

const html = '<html>...</html>';
const iframe = document.createElement('iframe');
const blob = new Blob([html], {type: 'text/html'});
iframe.src = window.URL.createObjectURL(blob);
document.body.appendChild(iframe);

Paused in debugger in chrome?

Really silly issue that I ran into that led me here with the debugger; command.: "debugger;" has a watch set on it.

It caused a page that just said debugger; to appear between every page load.

The way to disable it is to just right-click said Watch and click "Delete watch expression".

Case insensitive 'in'

Usually (in oop at least) you shape your object to behave the way you want. name in USERNAMES is not case insensitive, so USERNAMES needs to change:

class NameList(object):
    def __init__(self, names):
        self.names = names

    def __contains__(self, name): # implements `in`
        return name.lower() in (n.lower() for n in self.names)

    def add(self, name):
        self.names.append(name)

# now this works
usernames = NameList(USERNAMES)
print someone in usernames

The great thing about this is that it opens the path for many improvements, without having to change any code outside the class. For example, you could change the self.names to a set for faster lookups, or compute the (n.lower() for n in self.names) only once and store it on the class and so on ...

Create zip file and ignore directory structure

Somewhat related - I was looking for a solution to do the same for directories. Unfortunately the -j option does not work for this :(

Here is a good solution on how to get it done: https://superuser.com/questions/119649/avoid-unwanted-path-in-zip-file

ReDim Preserve to a Multi-Dimensional Array in Visual Basic 6

Function Redim2d(ByRef Mtx As Variant, ByVal QtyColumnToAdd As Integer)
    ReDim Preserve Mtx(LBound(Mtx, 1) To UBound(Mtx, 1), LBound(Mtx, 2) To UBound(Mtx, 2) + QtyColumnToAdd)
End Function

'Main Code
sub Main ()
    Call Redim2d(MtxR8Strat, 1)  'Add one column
end sub

'OR
sub main2()
    QtyColumnToAdd = 1 'Add one column
    ReDim Preserve Mtx(LBound(Mtx, 1) To UBound(Mtx, 1), LBound(Mtx, 2) To UBound(Mtx, 2) + QtyColumnToAdd)
end sub

Pythonic way to print list items

I think this is the most convenient if you just want to see the content in the list:

myList = ['foo', 'bar']
print('myList is %s' % str(myList))

Simple, easy to read and can be used together with format string.

How to convert Hexadecimal #FFFFFF to System.Drawing.Color

Remove the '#' and do

Color c = Color.FromArgb(int.Parse("#FFFFFF".Replace("#",""),
                         System.Globalization.NumberStyles.AllowHexSpecifier));

How to select rows in a DataFrame between two values, in Python Pandas?

Instead of this

df = df[(99 <= df['closing_price'] <= 101)]

You should use this

df = df[(df['closing_price']>=99 ) & (df['closing_price']<=101)]

We have to use NumPy's bitwise Logic operators |, &, ~, ^ for compounding queries. Also, the parentheses are important for operator precedence.

For more info, you can visit the link :Comparisons, Masks, and Boolean Logic

Cannot attach the file *.mdf as database

Take a look at this: Entity Framework don't create database

I would try giving the database a different name. Sometimes you can run into problems with SQL Express when trying to create a database with the same name a second time. There is a way to fix this using SQL Server Management Studio but it's generally easier to just use a different database name.

Edit This answer was accepted because it confirms the bug and the workaround used by OP (renaming database could help). I totally agree that renaming the database is not really an acceptable way, and does not totally solve the issue. Unfortunatly I didn't check the other ways to really solve it in SSMS.

How to add a button dynamically in Android?

In mainactivity.xml write:

<Button
    android:id="@+id/search"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Search" 
    android:visibility="invisible"/>

In main.java write:

Button buttonSearch;
buttonSearch = (Button)findViewById(R.id.search);
buttonSearch.setVisibility(View.VISIBLE);

Why use the params keyword?

No need to create overload methods, just use one single method with params as shown below

// Call params method with one to four integer constant parameters.
//
int sum0 = addTwoEach();
int sum1 = addTwoEach(1);
int sum2 = addTwoEach(1, 2);
int sum3 = addTwoEach(3, 3, 3);
int sum4 = addTwoEach(2, 2, 2, 2);

Who sets response content-type in Spring MVC (@ResponseBody)

if you decide to fix this problem through the following configuration:

<mvc:annotation-driven>
  <mvc:message-converters register-defaults="true">
    <bean class="org.springframework.http.converter.StringHttpMessageConverter">
      <property name="supportedMediaTypes" value = "text/plain;charset=UTF-8" />
    </bean>
  </mvc:message-converters>
</mvc:annotation-driven>

you should confirm that there should only one mvc:annotation-driven tag in all your *.xml file. otherwise, the configuration may not be effective.

Generate a Hash from string in Javascript

SubtleCrypto.digest

I’m not utilizing a server-side language so I can’t do it that way.

Are you sure you can’t do it that way?

Did you forget you’re using Javascript, the language ever-evolving?

Try SubtleCrypto. It supports SHA-1, SHA-128, SHA-256, and SHA-512 hash functions.


_x000D_
_x000D_
async function hash(message/*: string */) {_x000D_
 const text_encoder = new TextEncoder;_x000D_
 const data = text_encoder.encode(message);_x000D_
 const message_digest = await window.crypto.subtle.digest("SHA-512", data);_x000D_
 return message_digest;_x000D_
} // -> ArrayBuffer_x000D_
_x000D_
function in_hex(data/*: ArrayBuffer */) {_x000D_
 const octets = new Uint8Array(data);_x000D_
 const hex = [].map.call(octets, octet => octet.toString(16).padStart(2, "0")).join("");_x000D_
 return hex;_x000D_
} // -> string_x000D_
_x000D_
(async function demo() {_x000D_
 console.log(in_hex(await hash("Thanks for the magic.")));_x000D_
})();
_x000D_
_x000D_
_x000D_

How should I resolve java.lang.IllegalArgumentException: protocol = https host = null Exception?

This code seems completely unnecessary:

String serverURLS = getRecipientURL(message);

serverURLS = "https:\\\\abc.my.domain.com:55555\\update";

if (serverURLS != null){
    serverURL = new URL(serverURLS);
}
  1. serverURLS is assigned the result of getRecipientURL(message)
  2. Then immediately you overwrite the value of serverURLS, making the previous statement a dead store
  3. Then, because if (serverURLS != null) evaluates to true, since you just assigned the variable a value in the preceding statement, you assign a value to serverURL. It is impossible for if (serverURLS != null) to evaluate to false!
  4. You never actually use the variable serverURLS beyond the previous line of code.

You could replace all of this with just:

serverURL = new URL("https:\\\\abc.my.domain.com:55555\\update");

onclick event function in JavaScript

<script>
//$(document).ready(function () {
function showcontent() {
        document.getElementById("demo22").innerHTML = "Hello World";
}
//});// end of ready function
</script>

I had the same problem where onclick function calls would not work. I had included the function inside the usual "$(document).ready(function(){});" block used to wrap jquery scripts. Commenting this block out solved the problem.

Cookie blocked/not saved in IFRAME in Internet Explorer

I was investigating this problem with regard to login-off via Azure Access Control Services, and wasn't able to connect head and tails of anything.

Then, stumbled over this post https://blogs.msdn.microsoft.com/ieinternals/2011/03/10/beware-cookie-sharing-in-cross-zone-scenarios/

In short, IE doesn't share cookies across zones (eg. Internet vs. Trusted sites).

So, if your IFrame target and html page are in different zone's P3P won't help with anything.

Angular.js ng-repeat filter by property having one of multiple values (OR of values)

Best way to do this is to use a function:

<div ng-repeat="product in products | filter: myFilter">

$scope.myFilter = function (item) { 
    return item === 'red' || item === 'blue'; 
};

Alternatively, you can use ngHide or ngShow to dynamically show and hide elements based on a certain criteria.

How to capitalize the first letter of a String in Java?

Set the string to lower case, then set the first Letter to upper like this:

    userName = userName.toLowerCase();

then to capitalise the first letter:

    userName = userName.substring(0, 1).toUpperCase() + userName.substring(1).toLowerCase();

substring is just getting a piece of a larger string, then we are combining them back together.

Uploading into folder in FTP?

The folder is part of the URL you set when you create request: "ftp://www.contoso.com/test.htm". If you use "ftp://www.contoso.com/wibble/test.htm" then the file will be uploaded to a folder named wibble.

You may need to first use a request with Method = WebRequestMethods.Ftp.MakeDirectory to make the wibble folder if it doesn't already exist.

How to get selected option using Selenium WebDriver with Java

You should be able to get the text using getText() (for the option element you got using getFirstSelectedOption()):

Select select = new Select(driver.findElement(By.xpath("//select")));
WebElement option = select.getFirstSelectedOption();
String defaultItem = option.getText();
System.out.println(defaultItem );

Use HTML5 to resize an image before upload

If some of you, like me, encounter orientation problems I have combined the solutions here with a exif orientation fix

https://gist.github.com/SagiMedina/f00a57de4e211456225d3114fd10b0d0

Cannot open include file 'afxres.h' in VC2010 Express

Had similar issue but the message was shown when I tried to open a project solution. What worked for me was:

TOOLS -> Import and Export Settings...-> Reset all settings

Is Tomcat running?

$ sudo netstat -lpn |grep :8080

To check the port number

$ ps -aef|grep tomcat

Is any tomcat is running under the server.

tsssinfotech-K53U infotech # ps -aef|grep tomcat

root 9586 9567 0 11:35 pts/6 00:00:00 grep --colour=auto tomcat

Edit a commit message in SourceTree Windows (already pushed to remote)

If the comment message includes non-English characters, using method provided by user456814, those characters will be replaced by question marks. (tested under sourcetree Ver2.5.5.0)

So I have to use the following method.

CAUTION: if the commit has been pulled by other members, changes below might cause chaos for them.

Step1: In the sourcetree main window, locate your repo tab, and click the "terminal" button to open the git command console.

Step2:

[Situation A]: target commit is the latest one.

1) In the git command console, input

git commit --amend -m "new comment message"

2) If the target commit has been pushed to remote, you have to push again by force. In the git command console, input

git push --force

[Situation B]: target commit is not the latest one.

1) In the git command console, input

git rebase -i HEAD~n

It is to squash the latest n commits. e.g. if you want to edit the message before the last one, n is 2. This command will open a vi window, the first word of each line is "pick", and you change the "pick" to "reword" for the line you want to edit. Then, input :wq to save&quit that vi window. Now, a new vi window will be open, in this window you input your new message. Also use :wq to save&quit.

2) If the target commit has been pushed to remote, you have to push again by force. In the git command console, input

git push --force


Finally: In the sourcetree main window, Press F5 to refresh.

I want to execute shell commands from Maven's pom.xml

The problem here is that I don't know what is expected. With your current setup, invoking the plugin on the command line would just work:

$ mvn exec:exec
[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] Building Q3491937
[INFO]    task-segment: [exec:exec]
[INFO] ------------------------------------------------------------------------
[INFO] [exec:exec {execution: default-cli}]
[INFO] laptop
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ------------------------------------------------------------------------
...

The global configuration is used, the hostname command is executed (laptop is my hostname). In other words, the plugin works as expected.

Now, if you want a plugin to get executed as part of the build, you have to bind a goal on a specific phase. For example, to bind it on compile:

  <plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <version>1.1.1</version>
    <executions>
      <execution>
        <id>some-execution</id>
        <phase>compile</phase>
        <goals>
          <goal>exec</goal>
        </goals>
      </execution>
    </executions>
    <configuration>
      <executable>hostname</executable>
    </configuration>
  </plugin>

And then:

$ mvn compile
[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] Building Q3491937
[INFO]    task-segment: [compile]
[INFO] ------------------------------------------------------------------------
[INFO] [resources:resources {execution: default-resources}]
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /home/pascal/Projects/Q3491937/src/main/resources
[INFO] [compiler:compile {execution: default-compile}]
[INFO] Nothing to compile - all classes are up to date
[INFO] [exec:exec {execution: some-execution}]
[INFO] laptop
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ------------------------------------------------------------------------
...

Note that you can specify a configuration inside an execution.

java.lang.NoClassDefFoundError: org/apache/http/client/HttpClient

What could be the possible cause of this exception?

You may not have appropriate Jar in your class path.

How it could be removed?

By putting HTTPClient jar in your class path. If it's a webapp, copy Jar into WEB-INF/lib if it's standalone, make sure you have this jar in class path or explicitly set using -cp option

as the doc says,

Thrown if the Java Virtual Machine or a ClassLoader instance tries to load in the definition of a class (as part of a normal method call or as part of creating a new instance using the new expression) and no definition of the class could be found.

The searched-for class definition existed when the currently executing class was compiled, but the definition can no longer be found.

Edit:
If you are using a dependency management like Maven/Gradle (see the answer below) or SBT please use it to bring the httpclient jar for you.

How to pass event as argument to an inline event handler in JavaScript?

Since inline events are executed as functions you can simply use arguments.

<p id="p" onclick="doSomething.apply(this, arguments)">

and

function doSomething(e) {
  if (!e) e = window.event;
  // 'e' is the event.
  // 'this' is the P element
}

The 'event' that is mentioned in the accepted answer is actually the name of the argument passed to the function. It has nothing to do with the global event.