Programs & Examples On #Dreamhost

DreamHost is a Los Angeles-based web hosting, public cloud provider and domain name registrar.

Getting error while sending email through Gmail SMTP - "Please log in via your web browser and then try again. 534-5.7.14"

There are two ways to resolve this, and only one may work, depending on how you're accessing Google.

The first method is to authorize access for your IP or client machine using the https://accounts.google.com/DisplayUnlockCaptcha link. That can resolve authentication issues on client devices, like mobile or desktop apps. I would test this first, because it results in a lower overall decrease in account security.

If the above link doesn't work, it's because the session is being initiated by an app or device that is not associated with your particular location. Examples include:

  • An app that uses a remote server to retrieve data, like a web site or, in my case, other Google servers
  • A company mail server fetching mail on your behalf

In all such cases you have to use the https://www.google.com/settings/security/lesssecureapps link referenced above.

TLDR; check the captcha link first, and if it doesn't work, try the other one and enable less secure apps.

Reloading .env variables without restarting server (Laravel 5, shared hosting)

A short solution:

use Dotenv;

with(new Dotenv(app()->environmentPath(), app()->environmentFile()))->overload();
with(new LoadConfiguration())->bootstrap(app());

In my case I needed to re-establish database connection after altering .env programmatically, but it didn't work , If you get into this trouble try this

app('db')->purge($connection->getName()); 

after reloading .env , that's because Laravel App could have accessed the default connection before and the \Illuminate\Database\DatabaseManager needs to re-read config parameters.

How do I install soap extension?

They dont support it as in in they wont help you or be responsible for you hosing anything, but you can install custom extensions. To do so you need to first set up a local install of php 5, during that process you can compile in extensions you need or you can add them dynamically to the php.ini after the fact.

Is it possible to set async:false to $.getJSON call

Roll your own e.g.

function syncJSON(i_url, callback) {
  $.ajax({
    type: "POST",
    async: false,
    url: i_url,
    contentType: "application/json",
    dataType: "json",
    success: function (msg) { callback(msg) },
    error: function (msg) { alert('error : ' + msg.d); }
  });
}

syncJSON("/pathToYourResouce", function (msg) {
   console.log(msg);
})

What exactly is nullptr?

According to cppreference, nullptr is a keyword that:

denotes the pointer literal. It is a prvalue of type std::nullptr_t. There exist implicit conversions from nullptr to null pointer value of any pointer type and any pointer to member type. Similar conversions exist for any null pointer constant, which includes values of type std::nullptr_t as well as the macro NULL.

So nullptr is a value of a distinct type std::nullptr_t, not int. It implicitly converts to the null pointer value of any pointer type. This magic happens under the hood for you and you don't have to worry about its implementation. NULL, however, is a macro and it is an implementation-defined null pointer constant. It's often defined like this:

#define NULL 0

i.e. an integer.

This is a subtle but important difference, which can avoid ambiguity.

For example:

int i = NULL;     //OK
int i = nullptr;  //error
int* p = NULL;    //OK
int* p = nullptr; //OK

and when you have two function overloads like this:

void func(int x);   //1)
void func(int* x);  //2)

func(NULL) calls 1) because NULL is an integer. func(nullptr) calls 2) because nullptr converts implicitly to a pointer of type int*.

Also if you see a statement like this:

auto result = findRecord( /* arguments */ );

if (result == nullptr)
{
 ...
}

and you can't easily find out what findRecord returns, you can be sure that result must be a pointer type; nullptr makes this more readable.

In a deduced context, things work a little differently. If you have a template function like this:

template<typename T>
void func(T *ptr)
{
    ...
}

and you try to call it with nullptr:

func(nullptr);

you will get a compiler error because nullptr is of type nullptr_t. You would have to either explicitly cast nullptr to a specific pointer type or provide an overload/specialization for func with nullptr_t.


Advantages of using nulptr:
  • avoid ambiguity between function overloads
  • enables you to do template specialization
  • more secure, intuitive and expressive code, e.g. if (ptr == nullptr) instead of if (ptr == 0)

How can I read numeric strings in Excel cells as string (not numbers)?

I would much rather go the route of the wil's answer or Vinayak Dornala, unfortunately they effected my performance far to much. I went for a HACKY solution of implicit casting:

for (Row row : sheet){
String strValue = (row.getCell(numericColumn)+""); // hack
...

I don't suggest you do this, for my situation it worked because of the nature of how the system worked and I had a reliable file source.

Footnote: numericColumn Is an int which is generated from reading the header of the file processed.

Better naming in Tuple classes than "Item1", "Item2"

I think I would create a class but another alternative is output parameters.

public void GetOrderRelatedIds(out int OrderGroupId, out int OrderTypeId, out int OrderSubTypeId, out int OrderRequirementId)

Since your Tuple only contains integers you could represent it with a Dictionary<string,int>

var orderIds = new Dictionary<string, int> {
    {"OrderGroupId", 1},
    {"OrderTypeId", 2},
    {"OrderSubTypeId", 3},
    {"OrderRequirementId", 4}.
};

but I don't recommend that either.

Very simple C# CSV reader

First of all need to understand what is CSV and how to write it.

(Most of answers (all of them at the moment) do not use this requirements, that's why they all is wrong!)

  1. Every next string ( /r/n ) is next "table" row.
  2. "Table" cells is separated by some delimiter symbol.
  3. As delimiter can be used ANY symbol. Often this is \t or ,.
  4. Each cell possibly can contain this delimiter symbol inside of the cell (cell must to start with double quotes symbol and to have double quote in the end in this case)
  5. Each cell possibly can contains /r/n symbols inside of the cell (cell must to start with double quotes symbol and to have double quote in the end in this case)

Some time ago I had wrote simple class for CSV read/write based on standard Microsoft.VisualBasic.FileIO library. Using this simple class you will be able to work with CSV like with 2 dimensions array.

Simple example of using my library:

Csv csv = new Csv("\t");//delimiter symbol

csv.FileOpen("c:\\file1.csv");

var row1Cell6Value = csv.Rows[0][5];

csv.AddRow("asdf","asdffffff","5")

csv.FileSave("c:\\file2.csv");

You can find my class by the following link and investigate how it's written: https://github.com/ukushu/DataExporter

This library code is really fast in work and source code is really short.

PS: In the same time this solution will not work for unity.

PS2: Another solution is to work with library "LINQ-to-CSV". It must also work well. But it's will be bigger.

Load Image from javascript

<span>
    <img id="my_image" src="#" />
</span>

<span class="spanloader">

    <span>set Loading Image Image</span>


</span>

<input type="button" id="btnnext" value="Next" />


<script type="text/javascript">

    $('#btnnext').click(function () {
        $(".spanloader").hide();
        $("#my_image").attr("src", "1.jpg");
    });

</script>

Google drive limit number of download

Sure Google has a limit of downloads so that you don't abuse the system. These are the limits if you are using Gmail:

The following limits apply for Google Apps for Business or Education editions. Limits for domains during trial are lower. These limits may change without notice in order to protect Google’s infrastructure.

Bandwidth limits

Limit                          Per hour            Per day
Download via web client        750 MB              1250 MB
Upload via web client          300 MB              500 MB
POP and IMAP bandwidth limits

Limit                Per day
Download via IMAP    2500 MB
Download via POP     1250 MB
Upload via IMAP      500 MB

check out this link

Is ConfigurationManager.AppSettings available in .NET Core 2.0?

I know it's a bit too late, but maybe someone is looking for easy way to access appsettings in .net core app. in API constructor add the following:

public class TargetClassController : ControllerBase
{
    private readonly IConfiguration _config;

    public TargetClassController(IConfiguration config)
    {
        _config = config;
    }

    [HttpGet("{id:int}")]
    public async Task<ActionResult<DTOResponse>> Get(int id)
    {
        var config = _config["YourKeySection:key"];
    }
}

Bash: Syntax error: redirection unexpected

Another reason to the error may be if you are running a cron job that updates a subversion working copy and then has attempted to run a versioned script that was in a conflicted state after the update...

plot different color for different categorical levels using matplotlib

I usually do it using Seaborn which is built on top of matplotlib

import seaborn as sns
iris = sns.load_dataset('iris')
sns.scatterplot(x='sepal_length', y='sepal_width',
              hue='species', data=iris); 

Extract regression coefficient values

To answer your question, you can explore the contents of the model's output by saving the model as a variable and clicking on it in the environment window. You can then click around to see what it contains and what is stored where.

Another way is to type yourmodelname$ and select the components of the model one by one to see what each contains. When you get to yourmodelname$coefficients, you will see all of beta-, p, and t- values you desire.

How can I get stock quotes using Google Finance API?

This is no longer an active API for google, you can try Xignite, although they charge: http://www.xignite.com

Get current AUTO_INCREMENT value for any table

mysqli executable sample code:

<?php
    $db = new mysqli("localhost", "user", "password", "YourDatabaseName");
    if ($db->connect_errno) die ($db->connect_error);

    $table=$db->prepare("SHOW TABLE STATUS FROM YourDatabaseName");
    $table->execute();
    $sonuc = $table->get_result();
    while ($satir=$sonuc->fetch_assoc()){
        if ($satir["Name"]== "YourTableName"){
            $ai[$satir["Name"]]=$satir["Auto_increment"];
        }
    }
    $LastAutoIncrement=$ai["YourTableName"];
    echo $LastAutoIncrement;
?>  

jQuery plugin returning "Cannot read property of undefined"

The problem is that "i" is incremented, so by the time the click event is executed the value of i equals len. One possible solution is to capture the value of i inside a function:

var len = menuitems.length;
for (var i = 0; i < len; i++){
    (function(i) {
      $('<li/>',{
          'html':'<img src="'+menuitems[i].icon+'">'+menuitems[i].name,
          'click':function(){
              menuitems[i].action();
          },
          'class':o.itemClass
      }).appendTo('.'+o.listClass);
    })(i);
}

In the above sample, the anonymous function creates a new scope which captures the current value of i, so that when the click event is triggered the local variable is used instead of the i from the for loop.

jQuery post() with serialize and extra data

When you want to add a javascript object to the form data, you can use the following code

var data = {name1: 'value1', name2: 'value2'};
var postData = $('#my-form').serializeArray();
for (var key in data) {
    if (data.hasOwnProperty(key)) {
        postData.push({name:key, value:data[key]});
    }
}
$.post(url, postData, function(){});

Or if you add the method serializeObject(), you can do the following

var data = {name1: 'value1', name2: 'value2'};
var postData = $('#my-form').serializeObject();
$.extend(postData, data);
$.post(url, postData, function(){});

Disable elastic scrolling in Safari

I had solved it on iPad. Try, if it works also on OSX.

body, html { position: fixed; }

Works only if you have content smaller then screen or you are using some layout framework (Angular Material in my case).

In Angular Material it is great, that you will disable over-scroll effect of whole page, but inner sections <md-content> can be still scrollable.

What REALLY happens when you don't free after malloc?

What's the real result here?

Your program leaked the memory. Depending on your OS, it may have been recovered.

Most modern desktop operating systems do recover leaked memory at process termination, making it sadly common to ignore the problem, as can be seen by many other answers here.)

But you are relying on a safety feature you should not rely upon, and your program (or function) might run on a system where this behaviour does result in a "hard" memory leak, next time.

You might be running in kernel mode, or on vintage / embedded operating systems which do not employ memory protection as a tradeoff. (MMUs take up die space, memory protection costs additional CPU cycles, and it is not too much to ask from a programmer to clean up after himself).

You can use and re-use memory any way you like, but make sure you deallocated all resources before exiting.

How do I get logs from all pods of a Kubernetes replication controller?

Worked for me:

kubectl logs -n namespace -l app=label -c container

"VT-x is not available" when I start my Virtual machine

VT-x can normally be disabled/enabled in your BIOS.

When your PC is just starting up you should press DEL (or something) to get to the BIOS settings. There you'll find an option to enable VT-technology (or something).

What exactly is \r in C language?

It's Carriage Return. Source: http://msdn.microsoft.com/en-us/library/6aw8xdf2(v=vs.80).aspx

The following repeats the loop until the user has pressed the Return key.

while(ch!='\r')
{
  ch=getche();
}

php delete a single file in directory

<?php 
    if(isset($_GET['delete'])){
        $delurl=$_GET['delete'];
        unlink($delurl);
    }
?>
<?php
if ($handle = opendir('.')) {
    while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != "..") {
            echo "<a href=\"$entry\">$entry</a> | <a href=\"?delete=$entry\">Delete</a><br>";
        }
    }
    closedir($handle);
}
?>

This is It

JQuery .on() method with multiple event handlers to one selector

If you want to use the same function on different events the following code block can be used

$('input').on('keyup blur focus', function () {
   //function block
})

Passing arguments to JavaScript function from code-behind

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Call java script function on Code behind</title>
    <script  type="text/javascript">
    function abc()
    {
        var a=20;
        var b=30;
        alert("you enter"+a+":"+b);
    }
    </script>
</head>

cs code

protected void Page_Load(object sender, EventArgs e)
{
    TextBox2.Attributes.Add("onkeypress", "return abc();");
}

try this

Squash the first two commits in Git?

If you simply want to squash all commits into a single, initial commit, just reset the repository and amend the first commit:

git reset hash-of-first-commit
git add -A
git commit --amend

Git reset will leave the working tree intact, so everything is still there. So just add the files using git add commands, and amend the first commit with these changes. Compared to rebase -i you'll lose the ability to merge the git comments though.

Android ADB device offline, can't issue commands

Installed the latest android sdk.
Changed the USB port of the device.
Changed from MTP -> Charge only -> MTP.
It worked.

Spring Boot - Cannot determine embedded database driver class for database type NONE

Spring boot will look for datasoure properties in application.properties file.

Please define it in application.properties or yml file

application.properties

spring.datasource.url=xxx
spring.datasource.username=xxx
spring.datasource.password=xxx
spring.datasource.driver-class-name=xxx

If you need your own configuration you could set your own profile and use the datasource values while bean creation.

Create an ArrayList of unique values

Try checking for duplicates with a .contains() method on the ArrayList, before adding a new element.

It would look something like this

   if(!list.contains(data))
       list.add(data);

That should prevent duplicates in the list, as well as not mess up the order of elements, like people seem to look for.

How to sort an array of integers correctly

As sort method converts Array elements into string. So, below way also works fine with decimal numbers with array elements.

let productPrices = [10.33, 2.55, 1.06, 5.77];
console.log(productPrices.sort((a,b)=>a-b));

And gives you the expected result.

Return anonymous type results?

BreedId in the Dog table is obviously a foreign key to the corresponding row in the Breed table. If you've got your database set up properly, LINQ to SQL should automatically create an association between the two tables. The resulting Dog class will have a Breed property, and the Breed class should have a Dogs collection. Setting it up this way, you can still return IEnumerable<Dog>, which is an object that includes the breed property. The only caveat is that you need to preload the breed object along with dog objects in the query so they can be accessed after the data context has been disposed, and (as another poster has suggested) execute a method on the collection that will cause the query to be performed immediately (ToArray in this case):

public IEnumerable<Dog> GetDogs()
{
    using (var db = new DogDataContext(ConnectString))
    {
        db.LoadOptions.LoadWith<Dog>(i => i.Breed);
        return db.Dogs.ToArray();
    }

}

It is then trivial to access the breed for each dog:

foreach (var dog in GetDogs())
{
    Console.WriteLine("Dog's Name: {0}", dog.Name);
    Console.WriteLine("Dog's Breed: {0}", dog.Breed.Name);        
}

Executing Batch File in C#

Using CliWrap:

var result = await Cli.Wrap("foobar.bat").ExecuteBufferedAsync();

var exitCode = result.ExitCode;
var stdOut = result.StandardOutput;

How can a Javascript object refer to values in itself?

That's not a JSON object, that's a Javascript object created via object literal notation. (JSON is a textual notation for data exchange (more). If you're dealing with JavaScript source code, and not dealing with a string, you're not dealing with JSON.)

There's no way within the object initializer to refer to another key of the object being initialized, because there's no way to get a reference to the object being created until the initializer is finished. (There's no keyword akin to this or something for this situation.)

Guzzlehttp - How get the body of a response from Guzzle 6?

For get response in JSON format :

  1.$response = (string) $res->getBody();
      $response =json_decode($response); // Using this you can access any key like below
     
     $key_value = $response->key_name; //access key  

  2. $response = json_decode($res->getBody(),true);
     
     $key_value =   $response['key_name'];//access key

Replace specific text with a redacted version using Python

You can do it using named-entity recognition (NER). It's fairly simple and there are out-of-the-shelf tools out there to do it, such as spaCy.

NER is an NLP task where a neural network (or other method) is trained to detect certain entities, such as names, places, dates and organizations.

Example:

Sponge Bob went to South beach, he payed a ticket of $200!
I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.

Returns:

NER with spacy

Just be aware that this is not 100%!

Here are a little snippet for you to try out:

import spacy

phrases = ['Sponge Bob went to South beach, he payed a ticket of $200!', 'I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.']
nlp = spacy.load('en')
for phrase in phrases:
   doc = nlp(phrase)
   replaced = ""
   for token in doc:
      if token in doc.ents:
         replaced+="XXXX "
      else:
         replaced+=token.text+" "

Read more here: https://spacy.io/usage/linguistic-features#named-entities

You could, instead of replacing with XXXX, replace based on the entity type, like:

if ent.label_ == "PERSON":
   replaced += "<PERSON> "

Then:

import re, random

personames = ["Jack", "Mike", "Bob", "Dylan"]

phrase = re.replace("<PERSON>", random.choice(personames), phrase)

Git pull after forced update

This won't fix branches that already have the code you don't want in them (see below for how to do that), but if they had pulled some-branch and now want it to be clean (and not "ahead" of origin/some-branch) then you simply:

git checkout some-branch   # where some-branch can be replaced by any other branch
git branch base-branch -D  # where base-branch is the one with the squashed commits
git checkout -b base-branch origin/base-branch  # recreating branch with correct commits

Note: You can combine these all by putting && between them

Note2: Florian mentioned this in a comment, but who reads comments when looking for answers?

Note3: If you have contaminated branches, you can create new ones based off the new "dumb branch" and just cherry-pick commits over.

Ex:

git checkout feature-old  # some branch with the extra commits
git log                   # gives commits (write down the id of the ones you want)
git checkout base-branch  # after you have already cleaned your local copy of it as above
git checkout -b feature-new # make a new branch for your feature
git cherry-pick asdfasd   # where asdfasd is one of the commit ids you want
# repeat previous step for each commit id
git branch feature-old -D # delete the old branch

Now feature-new is your branch without the extra (possibly bad) commits!

Check whether a path is valid

You can try this code:

try
{
  Path.GetDirectoryName(myPath);
}
catch
{
  // Path is not valid
}

I'm not sure it covers all the cases...

How to initialize all the elements of an array to any specific value in java

You could do this if it's short:

int[] array = {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1};

but that gets bad for more than just a few.

Easier would be a for loop:

  int[] myArray = new int[10];
  for (int i = 0; i < array.length; i++)
       myArray[i] = -1;

Edit: I also like the Arrays.fill() option other people have mentioned.

jQuery: Check if special characters exists in string

If you really want to check for all those special characters, it's easier to use a regular expression:

var str = $('#Search').val();
if(/^[a-zA-Z0-9- ]*$/.test(str) == false) {
    alert('Your search string contains illegal characters.');
}

The above will only allow strings consisting entirely of characters on the ranges a-z, A-Z, 0-9, plus the hyphen an space characters. A string containing any other character will cause the alert.

Question mark and colon in JavaScript

Properly parenthesized for clarity, it is

hsb.s = (max != 0) ? (255 * delta / max) : 0;

meaning return either

  • 255*delta/max if max != 0
  • 0 if max == 0

HTTP POST with Json on Body - Flutter/Dart

I think many people have problems with Post 'Content-type': 'application / json' The problem here is parse data Map <String, dynamic> to json:

Hope the code below can help someone

Model:

class ConversationReq {
  String name = '';
  String description = '';
  String privacy = '';
  String type = '';
  String status = '';

  String role;
  List<String> members;
  String conversationType = '';

  ConversationReq({this.type, this.name, this.status, this.description, this.privacy, this.conversationType, this.role, this.members});

  Map<String, dynamic> toJson() {

    final Map<String, dynamic> data = new Map<String, dynamic>();

    data['name'] = this.name;
    data['description'] = this.description;
    data['privacy'] = this.privacy;
    data['type'] = this.type;

    data['conversations'] = [
      {
        "members": members,
        "conversationType": conversationType,
      }
    ];

    return data;
  }
}

Request:

createNewConversation(ConversationReq param) async {
    HeaderRequestAuth headerAuth = await getAuthHeader();
    var headerRequest = headerAuth.toJson();
/*
{
            'Content-type': 'application/json',
            'x-credential-session-token': xSectionToken,
            'x-user-org-uuid': xOrg,
          }
*/

    var bodyValue = param.toJson();

    var bodydata = json.encode(bodyValue);// important
    print(bodydata);

    final response = await http.post(env.BASE_API_URL + "xxx", headers: headerRequest, body: bodydata);

    print(json.decode(response.body));
    if (response.statusCode == 200) {
      // TODO
    } else {
      // If that response was not OK, throw an error.
      throw Exception('Failed to load ConversationRepo');
    }
  }

How do you store Java objects in HttpSession?

You are not adding the object to the session, instead you are adding it to the request.
What you need is:

HttpSession session = request.getSession();
session.setAttribute("MySessionVariable", param);

In Servlets you have 4 scopes where you can store data.

  1. Application
  2. Session
  3. Request
  4. Page

Make sure you understand these. For more look here

Rails select helper - Default selected value, how?

Its already explained, Will try to give an example

let the select list be

select_list = { eligible: 1, ineligible: 0 }

So the following code results in

<%= f.select :to_vote, select_list %>

<select name="to_vote" id="to_vote">
  <option value="1">eligible</option>
  <option value="0">ineligible</option>
</select>

So to make a option selected by default we have to use selected: value.

<%= f.select :to_vote, select_list, selected: select_list.can_vote? ? 1 : 0 %>

if can_vote? returns true it sets selected: 1 then the first value will be selected else second.

select name="driver[bca_aw_eligible]" id="driver_bca_aw_eligible">
  <option value="1">eligible</option>
  <option selected="selected" value="0">ineligible</option>
</select>

if the select options are just a array list instead of hast then the selected will be just the value to be selected for example if

select_list = [ 'eligible', 'ineligible' ]

now the selected will just take

<%= f.select :to_vote, select_list, selected: 'ineligible' %>

Why am I getting "Cannot Connect to Server - A network-related or instance-specific error"?

I resolved this problem by setting the project that makes use of Entity Framework as the start-up project and then run the "update-database" command.

Converting UTF-8 to ISO-8859-1 in Java - how to keep it as single byte

If you're dealing with character encodings other than UTF-16, you shouldn't be using java.lang.String or the char primitive -- you should only be using byte[] arrays or ByteBuffer objects. Then, you can use java.nio.charset.Charset to convert between encodings:

Charset utf8charset = Charset.forName("UTF-8");
Charset iso88591charset = Charset.forName("ISO-8859-1");

ByteBuffer inputBuffer = ByteBuffer.wrap(new byte[]{(byte)0xC3, (byte)0xA2});

// decode UTF-8
CharBuffer data = utf8charset.decode(inputBuffer);

// encode ISO-8559-1
ByteBuffer outputBuffer = iso88591charset.encode(data);
byte[] outputData = outputBuffer.array();

Improve subplot size/spacing with many subplots in matplotlib

Try using plt.tight_layout

As a quick example:

import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=4, ncols=4)
fig.tight_layout() # Or equivalently,  "plt.tight_layout()"

plt.show()

Without Tight Layout

enter image description here


With Tight Layout enter image description here

How to make matrices in Python?

you can do it short like this:

matrix = [["A, B, C, D, E"]*5]
print(matrix)


[['A, B, C, D, E', 'A, B, C, D, E', 'A, B, C, D, E', 'A, B, C, D, E', 'A, B, C, D, E']]

What is the { get; set; } syntax in C#?

They are the accessors for the public property Name.

You would use them to get/set the value of that property in an instance of Genre.

What is the difference between a token and a lexeme?

Token: The kind for (keywords,identifier,punctuation character, multi-character operators) is ,simply, a Token.

Pattern: A rule for formation of token from input characters.

Lexeme : Its a sequence of characters in SOURCE PROGRAM matched by a pattern for a token. Basically, its an element of Token.

Unexpected token }

You have endless loop in place:

function save() {
    var filename = id('filename').value;
    var name = id('name').value;
    var text = id('text').value;
    save(filename, name, text);
}

No idea what you're trying to accomplish with that endless loop but first of all get rid of it and see if things are working.

How do I print a double value with full precision using cout?

In C++20 you'll be able to use std::format to do this:

std::cout << std::format("{}", M_PI);

Output (assuming IEEE754 double):

3.141592653589793

The default floating-point format is the shortest decimal representation with a round-trip guarantee. The advantage of this method compared to the setprecision I/O manipulator is that it doesn't print unnecessary digits.

In the meantime you can use the {fmt} library, std::format is based on. {fmt} also provides the print function that makes this even easier and more efficient (godbolt):

fmt::print("{}", M_PI);

Disclaimer: I'm the author of {fmt} and C++20 std::format.

Run CRON job everyday at specific time

From cron manual http://man7.org/linux/man-pages/man5/crontab.5.html:

Lists are allowed. A list is a set of numbers (or ranges) separated by commas. Examples: "1,2,5,9", "0-4,8-12".

So in this case it would be:

30 10,14 * * *

How do I do a not equal in Django queryset filtering?

Watch out for lots of incorrect answers to this question!

Gerard's logic is correct, though it will return a list rather than a queryset (which might not matter).

If you need a queryset, use Q:

from django.db.models import Q
results = Model.objects.filter(Q(a=false) | Q(x=5))

Regex: Use start of line/end of line signs (^ or $) in different context

Just use look-arounds to solve this:

(?<=^|,)garp(?=$|,)

The difference with look-arounds and just regular groups are that with regular groups the comma would be part of the match, and with look-arounds it wouldn't. In this case it doesn't make a difference though.

How to deny access to a file in .htaccess

Within an htaccess file, the scope of the <Files> directive only applies to that directory (I guess to avoid confusion when rules/directives in the htaccess of subdirectories get applied superceding ones from the parent).

So you can have:

<Files "log.txt">  
  Order Allow,Deny
  Deny from all
</Files>

For Apache 2.4+, you'd use:

<Files "log.txt">  
  Require all denied
</Files>

In an htaccess file in your inscription directory. Or you can use mod_rewrite to sort of handle both cases deny access to htaccess file as well as log.txt:

RewriteRule /?\.htaccess$ - [F,L]

RewriteRule ^/?inscription/log\.txt$ - [F,L]

How to send a Post body in the HttpClient request in Windows Phone 8?

This depends on what content do you have. You need to initialize your requestMessage.Content property with new HttpContent. For example:

...
// Add request body
if (isPostRequest)
{
    requestMessage.Content = new ByteArrayContent(content);
}
...

where content is your encoded content. You also should include correct Content-type header.

UPDATE:

Oh, it can be even nicer (from this answer):

requestMessage.Content = new StringContent("{\"name\":\"John Doe\",\"age\":33}", Encoding.UTF8, "application/json");

Disable Copy or Paste action for text box?

Here is the updated fiddle.

$(document).ready(function(){
    $('#confirmEmail').bind("cut copy paste",function(e) {
        e.preventDefault();
    });
});

This will prevent cut copy paste on Confirm Email text box.

Hope it helps.

Open Windows Explorer and select a file

Check out this snippet:

Private Sub openDialog()
    Dim fd As Office.FileDialog

    Set fd = Application.FileDialog(msoFileDialogFilePicker)

   With fd

      .AllowMultiSelect = False

      ' Set the title of the dialog box.
      .Title = "Please select the file."

      ' Clear out the current filters, and add our own.
      .Filters.Clear
      .Filters.Add "Excel 2003", "*.xls"
      .Filters.Add "All Files", "*.*"

      ' Show the dialog box. If the .Show method returns True, the
      ' user picked at least one file. If the .Show method returns
      ' False, the user clicked Cancel.
      If .Show = True Then
        txtFileName = .SelectedItems(1) 'replace txtFileName with your textbox

      End If
   End With
End Sub

I think this is what you are asking for.

Unable to copy a file from obj\Debug to bin\Debug

I can confirm this bug exists in VS 2012 Update 2 also.

My work-around is to:

  1. Clean Solution (and do nothing else)
  2. Close all open documents/files in the solution
  3. Exit VS 2012
  4. Run VS 2012
  5. Build Solution

I don't know if this is relevant or not, but my project uses "Linked" in class files from other projects - it's a Silverlight 5 project and the only way to share a class that is .NET and SL compatible is to link the files.

Something to consider ... look for linked files across projects in a single solution.

`getchar()` gives the same output as the input string

According to the definition of getchar(), it reads a character from the standard input. Unfortunately stdin is mistaken for keyboard which might not be the case for getchar. getchar uses a buffer as stdin and reads a single character at a time. In your case since there is no EOF, the getchar and putchar are running multiple times and it looks to you as it the whole string is being printed out at a time. Make a small change and you will understand:

putchar(c);
printf("\n");     
c = getchar();

Now look at the output compared to the original code.

Another example that will explain you the concept of getchar and buffered stdin :

void main(){
int c;
printf("Enter character");
c = getchar();
putchar();
c = getchar();
putchar();
}

Enter two characters in the first case. The second time when getchar is running are you entering any character? NO but still putchar works.

This ultimately means there is a buffer and when ever you are typing something and click enter this goes and settles in the buffer. getchar uses this buffer as stdin.

Replacing a fragment with another fragment inside activity group

I change fragment dynamically in single line code
It is work in any SDK version and androidx
I use navigation as BottomNavigationView

    BottomNavigationView btn_nav;
    FragmentFirst fragmentFirst;
    FragmentSecond fragmentSecond;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        fragmentFirst = new FragmentFirst();
        fragmentSecond = new FragmentSecond ();
        changeFragment(fragmentFirst); // at first time load the fragmentFirst
        btn_nav = findViewById(R.id.bottomNav);
        btn_nav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
                switch(menuItem.getItemId()){
                    case R.id.menu_first_frag:
                        changeFragment(fragmentFirst); // change fragmentFirst
                        break;
                    case R.id.menu_second_frag:
                        changeFragment(fragmentSecond); // change fragmentSecond
                        break;
                        default:
                            Toast.makeText(SearchActivity.this, "Click on wrong bottom SORRY!", Toast.LENGTH_SHORT).show();
                }
                return true;
            }
        });
    }
public void changeFragment(Fragment fragment) {
        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_layout_changer, fragment).commit();
    }

Converting an integer to a hexadecimal string in Ruby

Here's another approach:

sprintf("%02x", 10).upcase

see the documentation for sprintf here: http://www.ruby-doc.org/core/classes/Kernel.html#method-i-sprintf

Django: multiple models in one template using forms

I currently have a workaround functional (it passes my unit tests). It is a good solution to my opinion when you only want to add a limited number of fields from other models.

Am I missing something here ?

class UserProfileForm(ModelForm):
    def __init__(self, instance=None, *args, **kwargs):
        # Add these fields from the user object
        _fields = ('first_name', 'last_name', 'email',)
        # Retrieve initial (current) data from the user object
        _initial = model_to_dict(instance.user, _fields) if instance is not None else {}
        # Pass the initial data to the base
        super(UserProfileForm, self).__init__(initial=_initial, instance=instance, *args, **kwargs)
        # Retrieve the fields from the user model and update the fields with it
        self.fields.update(fields_for_model(User, _fields))

    class Meta:
        model = UserProfile
        exclude = ('user',)

    def save(self, *args, **kwargs):
        u = self.instance.user
        u.first_name = self.cleaned_data['first_name']
        u.last_name = self.cleaned_data['last_name']
        u.email = self.cleaned_data['email']
        u.save()
        profile = super(UserProfileForm, self).save(*args,**kwargs)
        return profile

How to remove a branch locally?

I think (based on your comments) that I understand what you want to do: you want your local copy of the repository to have neither the ordinary local branch master, nor the remote-tracking branch origin/master, even though the repository you cloned—the github one—has a local branch master that you do not want deleted from the github version.

You can do this by deleting the remote-tracking branch locally, but it will simply come back every time you ask your git to synchronize your local repository with the remote repository, because your git asks their git "what branches do you have" and it says "I have master" so your git (re)creates origin/master for you, so that your repository has what theirs has.

To delete your remote-tracking branch locally using the command line interface:

git branch -d -r origin/master

but again, it will just come back on re-synchronizations. It is possible to defeat this as well (using remote.origin.fetch manipulation), but you're probably better off just being disciplined enough to not create or modify master locally.

how to overlap two div in css?

See demo here you need to introduce an additiona calss for second div

.overlap{
    top: -30px;
position: relative;
left: 30px;
}

How to find column names for all tables in all databases in SQL Server

user @KM say best Answer.

I Use This :

Declare @Table_Name VarChar(100) ,@Column_Name VarChar(100)
Set @Table_Name = ''
Set @Column_Name = ''

Select 
RowNumber = Row_Number() Over( PARTITION BY T.[Name] Order By T.[Name],C.column_id  ),
SCHEMA_NAME( T.schema_id ) As SchemaName ,  
T.[Name] As Table_Name ,
C.[Name] As Field_Name , 
sysType.name ,
C.max_length , C.is_nullable , C.is_identity , C.scale , C.precision  
From Sys.Tables As T
Left Join Sys.Columns As C On ( T.[Object_Id] = C.[Object_Id] )
Left Join sys.types As sysType On ( C.user_type_id = sysType.user_type_id )
Where ( Type = 'U' )
    And ( C.Name Like '%' + @Column_Name + '%' )  
    And ( T.Name Like '%' + @Table_Name + '%' ) 

How to take input in an array + PYTHON?

raw_input is your helper here. From documentation -

If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised.

So your code will basically look like this.

num_array = list()
num = raw_input("Enter how many elements you want:")
print 'Enter numbers in array: '
for i in range(int(num)):
    n = raw_input("num :")
    num_array.append(int(n))
print 'ARRAY: ',num_array

P.S: I have typed all this free hand. Syntax might be wrong but the methodology is correct. Also one thing to note is that, raw_input does not do any type checking, so you need to be careful...

How to add "Maven Managed Dependencies" library in build path eclipse?

You could also consider to maven-dependency-plugin to your pom:

<plugins>
... 
    <plugin> 
        <artifactId>maven-dependency-plugin</artifactId> 
            <executions> 
                <execution> 
                    <phase>process-resources</phase> 
                    <goals> 
                        <goal>copy-dependencies</goal> 
                    </goals> 
                    <configuration>   
                        <outputDirectory>${project.build.directory}/lib</outputDirectory> 
                    </configuration> 
                </execution> 
            </executions> 
    </plugin> 
...
</plugins>

Than you can run "mvn package" and maven will copy all needed dependencies to your_project_path/target/your_project_name/WEB-INF/lib/ directory. From there you can copy them to your project/lib dir and add as external jars (configuring your project settings buildpath)

How can you customize the numbers in an ordered list?

This code makes numbering style same as headers of li content.

<style>
    h4 {font-size: 18px}
    ol.list-h4 {counter-reset: item; padding-left:27px}
    ol.list-h4 > li {display: block}
    ol.list-h4 > li::before {display: block; position:absolute;  left:16px;  top:auto; content: counter(item)"."; counter-increment: item; font-size: 18px}
    ol.list-h4 > li > h4 {padding-top:3px}
</style>

<ol class="list-h4">
    <li>
        <h4>...</h4>
        <p>...</p> 
    </li>
    <li>...</li>
</ol>

How might I force a floating DIV to match the height of another floating DIV?

Wrap them in a containing div with the background color applied to it, and have a clearing div after the 'columns'.

<div style="background-color: yellow;">
  <div style="float: left;width: 65%;">column a</div>
  <div style="float: right;width: 35%;">column b</div>
  <div style="clear: both;"></div>
</div>

Updated to address some comments and my own thoughts:

This method works because its essentially a simplification of your problem, in this somewhat 'oldskool' method I put two columns in followed by an empty clearing element, the job of the clearing element is to tell the parent (with the background) this is where floating behaviour ends, this allows the parent to essentially render 0 pixels of height at the position of the clear, which will be whatever the highest priorly floating element is.

The reason for this is to ensure the parent element is as tall as the tallest column, the background is then set on the parent to give the appearance that both columns have the same height.

It should be noted that this technique is 'oldskool' because the better choice is to trigger this height calculation behaviour with something like clearfix or by simply having overflow: hidden on the parent element.

Whilst this works in this limited scenario, if you wish for each column to look visually different, or have a gap between them, then setting a background on the parent element won't work, there is however a trick to get this effect.

The trick is to add bottom padding to all columns, to the max amount of size you expect that could be the difference between the shortest and tallest column, if you can't work this out then pick a large figure, you then need to add a negative bottom margin of the same number.

You'll need overflow hidden on the parent object, but the result will be that each column will request to render this additional height suggested by the margin, but not actually request layout of that size (because the negative margin counters the calculation).

This will render the parent at the size of the tallest column, whilst allowing all the columns to render at their height + the size of bottom padding used, if this height is larger than the parent then the rest will simply clip off.

<div style="overflow: hidden;">
  <div style="background: blue;float: left;width: 65%;padding-bottom: 500px;margin-bottom: -500px;">column a<br />column a</div>
  <div style="background: red;float: right;width: 35%;padding-bottom: 500px;margin-bottom: -500px;">column b</div>
</div>

You can see an example of this technique on the bowers and wilkins website (see the four horizontal spotlight images the bottom of the page).

Insert multiple rows into single column

Another way to do this is with union:

INSERT INTO Data ( Col1 ) 
select 'hello'
union 
select 'world'

Entity Framework 6 Code first Default value

Hmm... I do DB first, and in that case, this is actually a lot easier. EF6 right? Just open your model, right click on the column you want to set a default for, choose properties, and you will see a "DefaultValue" field. Just fill that out and save. It will set up the code for you.

Your mileage may vary on code first though, I haven't worked with that.

The problem with a lot of other solutions, is that while they may work initially, as soon as you rebuild the model, it will throw out any custom code you inserted into the machine-generated file.

This method works by adding an extra property to the edmx file:

<EntityType Name="Thingy">
  <Property Name="Iteration" Type="Int32" Nullable="false" **DefaultValue="1"** />

And by adding the necessary code to the constructor:

public Thingy()
{
  this.Iteration = 1;

Testing if a checkbox is checked with jQuery

You can get value (true/false) by these two method

$("input[type='checkbox']").prop("checked");
$("input[type='checkbox']").is(":checked");

How to filter input type="file" dialog by specific file type?

See http://www.w3schools.com/tags/att_input_accept.asp:

The accept attribute is supported in all major browsers, except Internet Explorer and Safari. Definition and Usage

The accept attribute specifies the types of files that the server accepts (that can be submitted through a file upload).

Note: The accept attribute can only be used with <input type="file">.

Tip: Do not use this attribute as a validation tool. File uploads should be validated on the server.

Syntax <input accept="audio/*|video/*|image/*|MIME_type" />

Tip: To specify more than one value, separate the values with a comma (e.g. <input accept="audio/*,video/*,image/*" />.

Why is SQL server throwing this error: Cannot insert the value NULL into column 'id'?

I had a similar problem and upon looking into it, it was simply a field in the actual table missing id (id was empty/null) - meaning when you try to make the id field the primary key it will result in error because the table contains a row with null value for the primary key.

This could be the fix if you see a temp table associated with the error. I was using SQL Server Management Studio.

How to limit the number of selected checkboxes?

I did this today, the difference being I wanted to uncheck the oldest checkbox instead of stopping the user from checking a new one:

    let maxCheckedArray = [];
    let assessmentOptions = jQuery('.checkbox-fields').find('input[type="checkbox"]');
    assessmentOptions.on('change', function() {
        let checked = jQuery(this).prop('checked');
        if(checked) {
            maxCheckedArray.push(jQuery(this));
        }
        if(maxCheckedArray.length >= 3) {
            let old_item = maxCheckedArray.shift();
            old_item.prop('checked', false);
        }
    });

Redirecting to a new page after successful login

You could also provide a link to the page after login and have it auto redirect using javascript after 10 seconds.

How does one get started with procedural generation?

You should probably start with a little theory and simple examples such as the midpoint displacement algorithm. You should also learn a little about Perlin Noise if you are interested in generating graphics. I used this to get me started with my final year project on procedural generation.

Fractals are closely related to procedural generation.

Terragen and SpeedTree will show you some amazing possibilities of procedural generation.

Procedural generation is a technique that can be used in any language (it is definitely not restricted to procedural languages such as C, as it can be used in OO languages such as Java, and Logic languages such as Prolog). A good understanding of recursion in any language will strengthen your grasp of Procedural Generation.

As for 'serious' or non-game code, procedural generation techniques have been used to:

  • simulate the growth of cities in order to plan for traffic management
  • to simulate the growth of blood vessels
  • SpeedTree is used in movies and architectural presentations

Wrapping a react-router Link in an html button

While this will render in a web browser, beware that:
??Nesting an html button in an html a (or vice-versa) is not valid html ??. If you want to keep your html semantic to screen readers, use another approach.

Do wrapping in the reverse way and you get the original button with the Link attached. No CSS changes required.

 <Link to="/dashboard">
     <button type="button">
          Click Me!
     </button>
 </Link>

Here button is HTML button. It is also applicable to the components imported from third party libraries like Semantic-UI-React.

 import { Button } from 'semantic-ui-react'
 ... 
 <Link to="/dashboard">
     <Button style={myStyle}>
        <p>Click Me!</p>
     </Button>
 </Link>

phpMyAdmin mbstring error

just copy the php.ini file from C:\wamp\bin\apache\apache2.4.17\bin to C:\wamp\bin\apache\apache2.4.17\bin and then again restart apache server.. it will work fine.

How to convert a string to ASCII

Try Linq:

Result = string.Join("", input.ToCharArray().Where(x=> ((int)x) < 127));

This will filter out all non ascii characters. Now if you want an equivalent, try the following:

Result = string.Join("", System.Text.Encoding.ASCII.GetChars(System.Text.Encoding.ASCII.GetBytes(input.ToCharArray())));

How do you test that a Python function throws an exception?

You can use context manager to run the faulty function and assert it raises the exception with a certain message using assertRaisesMessage

with self.assertRaisesMessage(SomeException,'Some error message e.g 404 Not Found'):
    faulty_funtion()

How to check if a String contains any of some strings

You can use Regular Expressions

if(System.Text.RegularExpressions.IsMatch("a|b|c"))

String split on new line, tab and some number of spaces

>>> for line in s.splitlines():
...     line = line.strip()
...     if not line:continue
...     ary.append(line.split(":"))
...
>>> ary
[['Name', ' John Smith'], ['Home', ' Anytown USA'], ['Misc', ' Data with spaces'
]]
>>> dict(ary)
{'Home': ' Anytown USA', 'Misc': ' Data with spaces', 'Name': ' John Smith'}
>>>

When does a cookie with expiration time 'At end of session' expire?

When you use setcookie, you can either set the expiration time to 0 or simply omit the parametre - the cookie will then expire at the end of session (ie, when you close the browser).

How to display tables on mobile using Bootstrap?

After researching for almost 1 month i found the below code which is working very beautifully and 100% perfectly on my website. To check the preview how it is working you can check from the link. https://www.jobsedit.in/state-government-jobs/

CSS CODE-----

@media only screen and (max-width: 500px)  {
    .resp table  { 
        display: block ; 
    }   
    .resp th  { 
        position: absolute;
        top: -9999px;
        left: -9999px;
        display:block ;
    }   
     .resp tr { 
    border: 1px solid #ccc;
    display:block;
    }   
    .resp td  { 
        /* Behave  like a "row" */
        border: none;
        border-bottom: 1px solid #eee; 
        position: relative;
        width:100%;
        background-color:White;
        text-indent: 50%; 
        text-align:left;
        padding-left: 0px;
        display:block;      
    }
    .resp  td:nth-child(1)  {
        border: none;
        border-bottom: 1px solid #eee; 
        position: relative;
        font-size:20px;
        text-indent: 0%;
        text-align:center;
}   
    .resp td:before  { 
        /* Now like a table header */
        position: absolute;
        /* Top/left values mimic padding */
        top: 6px;
        left: 6px;
        width: 45%; 
        text-indent: 0%;
        text-align:left;
        white-space: nowrap;
        background-color:White;
        font-weight:bold;
    }
    /*
    Label the data
    */
    .resp td:nth-of-type(2):before  { content: attr(data-th) }
    .resp td:nth-of-type(3):before  { content: attr(data-th) }
    .resp td:nth-of-type(4):before  { content: attr(data-th) }
    .resp td:nth-of-type(5):before  { content: attr(data-th) }
    .resp td:nth-of-type(6):before  { content: attr(data-th) }
    .resp td:nth-of-type(7):before  { content: attr(data-th) }
    .resp td:nth-of-type(8):before  { content: attr(data-th) }
    .resp td:nth-of-type(9):before  { content: attr(data-th) }
    .resp td:nth-of-type(10):before  { content: attr(data-th) }
}

HTML CODE --

<table>
<tr>
<td data-th="Heading 1"></td>
<td data-th="Heading 2"></td>
<td data-th="Heading 3"></td>
<td data-th="Heading 4"></td>
<td data-th="Heading 5"></td>
</tr>
</table>

Is there any way to specify a suggested filename when using data: URI?

you can add a download attribute to the anchor element.

sample:

<a download="abcd.cer"
    href="data:application/stream;base64,MIIDhTC......">down</a>

TypeScript or JavaScript type casting

This is called type assertion in TypeScript, and since TypeScript 1.6, there are two ways to express this:

// Original syntax
var markerSymbolInfo = <MarkerSymbolInfo> symbolInfo;

// Newer additional syntax
var markerSymbolInfo = symbolInfo as MarkerSymbolInfo;

Both alternatives are functionally identical. The reason for introducing the as-syntax is that the original syntax conflicted with JSX, see the design discussion here.

If you are in a position to choose, just use the syntax that you feel more comfortable with. I personally prefer the as-syntax as it feels more fluent to read and write.

c# open file with default application and parameters

you can try with

Process process = new Process();
process.StartInfo.FileName = "yourProgram.exe";
process.StartInfo.Arguments = ..... //your parameters
process.Start();

Eclipse can't find / load main class

Standard troubleshooting steps for Eclipse should include deleting and re-importing the project at some point, which when I have dealt with this error has worked.

Creating executable files in Linux

No need to hack your editor, or switch editors.

Instead we can come up with a script to watch your development directories and chmod files as they're created. This is what I've done in the attached bash script. You probably want to read through the comments and edit the 'config' section as fits your needs, then I would suggest putting it in your $HOME/bin/ directory and adding its execution to your $HOME/.login or similar file. Or you can just run it from the terminal.

This script does require inotifywait, which comes in the inotify-tools package on Ubuntu,

sudo apt-get install inotify-tools

Suggestions/edits/improvements are welcome.

#!/usr/bin/env bash

# --- usage --- #
# Depends: 'inotifywait' available in inotify-tools on Ubuntu
# 
# Edit the 'config' section below to reflect your working directory, WORK_DIR,
# and your watched directories, WATCH_DIR. Each directory in WATCH_DIR will
# be logged by inotify and this script will 'chmod +x' any new files created
# therein. If SUBDIRS is 'TRUE' this script will watch WATCH_DIRS recursively.
# I recommend adding this script to your $HOME/.login or similar to have it
# run whenever you log into a shell, eg 'echo "watchdirs.sh &" >> ~/.login'.
# This script will only allow one instance of itself to run at a time.

# --- config --- #

WORK_DIR="$HOME/path/to/devel" # top working directory (for cleanliness?)
WATCH_DIRS=" \
    $WORK_DIR/dirA \
    $WORK_DIR/dirC \
    "                          # list of directories to watch
SUBDIRS="TRUE"                 # watch subdirectories too
NOTIFY_ARGS="-e create -q"     # watch for create events, non-verbose


# --- script starts here --- #
# probably don't need to edit beyond this point

# kill all previous instances of myself
SCRIPT="bash.*`basename $0`"
MATCHES=`ps ax | egrep $SCRIPT | grep -v grep | awk '{print $1}' | grep -v $$`
kill $MATCHES >& /dev/null

# set recursive notifications (for subdirectories)
if [ "$SUBDIRS" = "TRUE" ] ; then
    RECURSE="-r"
else
    RECURSE=""
fi

while true ; do
    # grab an event
    EVENT=`inotifywait $RECURSE $NOTIFY_ARGS $WATCH_DIRS`

    # parse the event into DIR, TAGS, FILE
    OLDIFS=$IFS ; IFS=" " ; set -- $EVENT
    E_DIR=$1
    E_TAGS=$2
    E_FILE=$3
    IFS=$OLDIFS

    # skip if it's not a file event or already executable (unlikely)
    if [ ! -f "$E_DIR$E_FILE" ] || [ -x "$E_DIR$E_FILE" ] ; then
        continue
    fi

    # set file executable
    chmod +x $E_DIR$E_FILE
done

How to list all dates between two dates

Create a stored procedure that does something like the following:

declare @startDate date;
declare @endDate date;

select @startDate = '20150528';
select @endDate = '20150531';

with dateRange as
(
  select dt = dateadd(dd, 1, @startDate)
  where dateadd(dd, 1, @startDate) < @endDate
  union all
  select dateadd(dd, 1, dt)
  from dateRange
  where dateadd(dd, 1, dt) < @endDate
)
select *
from dateRange

SQL Fiddle with demo.

Or better still create a calendar table and just select from that.

Expand a div to fill the remaining width

Pat - You are right. That's why this solution would satisfy both "dinosaurs" and contemporaries. :)

_x000D_
_x000D_
.btnCont {_x000D_
  display: table-layout;_x000D_
  width: 500px;_x000D_
}_x000D_
_x000D_
.txtCont {_x000D_
  display: table-cell;_x000D_
  width: 70%;_x000D_
  max-width: 80%;_x000D_
  min-width: 20%;_x000D_
}_x000D_
_x000D_
.subCont {_x000D_
  display: table-cell;_x000D_
  width: 30%;_x000D_
  max-width: 80%;_x000D_
  min-width: 20%;_x000D_
}
_x000D_
<div class="btnCont">_x000D_
  <div class="txtCont">_x000D_
    Long text that will auto adjust as it grows. The best part is that the width of the container would not go beyond 500px!_x000D_
  </div>_x000D_
  <div class="subCont">_x000D_
    This column as well as the entire container works like a table. Isn't Amazing!!!_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I process each letter of text using Javascript?

One more solution...

var strg= 'This is my string';
for(indx in strg){
  alert(strg[indx]);
}

Safely override C++ virtual functions

Your compiler may have a warning that it can generate if a base class function becomes hidden. If it does, enable it. That will catch const clashes and differences in parameter lists. Unfortunately this won't uncover a spelling error.

For example, this is warning C4263 in Microsoft Visual C++.

Convert integer to binary in C#

Your example has an integer expressed as a string. Let's say your integer was actually an integer, and you want to take the integer and convert it to a binary string.

int value = 8;
string binary = Convert.ToString(value, 2);

Which returns 1000.

Copying HTML code in Google Chrome's inspect element

This is bit tricky

Now a days most of website new techniques to save websites from scraping

1st Technique

Ctrl+U this will show you Page Source enter image description here

2nd Technique

This one is small hack if the website has ajax like functionality.

Just Hover the mouse key on inspect element untill whole screen becomes just right click then and copy element enter image description here

That's it you are good to go.

Best way to work with transactions in MS SQL Server Management Studio

The easisest thing to do is to wrap your code in a transaction, and then execute each batch of T-SQL code line by line.

For example,

Begin Transaction

         -Do some T-SQL queries here.

Rollback transaction -- OR commit transaction

If you want to incorporate error handling you can do so by using a TRY...CATCH BLOCK. Should an error occur you can then rollback the tranasction within the catch block.

For example:

USE AdventureWorks;
GO
BEGIN TRANSACTION;

BEGIN TRY
    -- Generate a constraint violation error.
    DELETE FROM Production.Product
    WHERE ProductID = 980;
END TRY
BEGIN CATCH
    SELECT 
        ERROR_NUMBER() AS ErrorNumber
        ,ERROR_SEVERITY() AS ErrorSeverity
        ,ERROR_STATE() AS ErrorState
        ,ERROR_PROCEDURE() AS ErrorProcedure
        ,ERROR_LINE() AS ErrorLine
        ,ERROR_MESSAGE() AS ErrorMessage;

    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION;
END CATCH;

IF @@TRANCOUNT > 0
    COMMIT TRANSACTION;
GO

See the following link for more details.

http://msdn.microsoft.com/en-us/library/ms175976.aspx

Hope this helps but please let me know if you need more details.

jQuery Call to WebService returns "No Transport" error

I too got this problem and all solutions given above either failed or were not applicable due to client webservice restrictions.

For this, I added an iframe in my page which resided in the client;s server. So when we post our data to the iframe and the iframe then posts it to the webservice. Hence the cross-domain referencing is eliminated.

We added a 2-way origin check to confirm only authorized page posts data to and from the iframe.

Hope it helps

<iframe style="display:none;" id='receiver' name="receiver" src="https://iframe-address-at-client-server">
 </iframe>

//send data to iframe
var hiddenFrame = document.getElementById('receiver').contentWindow;
hiddenFrame.postMessage(JSON.stringify(message), 'https://client-server-url');

//The iframe receives the data using the code:
window.onload = function () {
    var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
    var eventer = window[eventMethod];
    var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
    eventer(messageEvent, function (e) {
        var origin = e.origin;
        //if origin not in pre-defined list, break and return
        var messageFromParent = JSON.parse(e.data);
        var json = messageFromParent.data;

        //send json to web service using AJAX   
        //return the response back to source
        e.source.postMessage(JSON.stringify(aJAXResponse), e.origin);
    }, false);
}

Visual Studio 2010 always thinks project is out of date, but nothing has changed

Visual Studio 2013 -- "Forcing recompile of all source files due to missing PDB". I turned on detailed build output to locate the issue: I enabled "Detailed" build output under "Tools" ? "Projects and Solutions" ? "Build and Run".

I had several projects, all C++, I set the option for under project settings: (C/C++ ? Debug Information Format) to Program Database (/Zi) for the problem project. However, this did not stop the problem for that project. The problem came from one of the other C++ projects in the solution.

I set all C++ projects to "Program Database (/Zi)". This fixed the problem.

Again, the project reporting the problem was not the problem project. Try setting all projects to "Program Database (/Zi)" to fix the problem.

How to add an element at the end of an array?

As many others pointed out if you are trying to add a new element at the end of list then something like, array[array.length-1]=x; should do. But this will replace the existing element.

For something like continuous addition to the array. You can keep track of the index and go on adding elements till you reach end and have the function that does the addition return you the next index, which in turn will tell you how many more elements can fit in the array.

Of course in both the cases the size of array will be predefined. Vector can be your other option since you do not want arraylist, which will allow you all the same features and functions and additionally will take care of incrementing the size.

Coming to the part where you want StringBuffer to array. I believe what you are looking for is the getChars(int srcBegin, int srcEnd,char[] dst,int dstBegin) method. Look into it that might solve your doubts. Again I would like to point out that after managing to get an array out of it, you can still only replace the last existing element(character in this case).

converting CSV/XLS to JSON?

None of the existing solutions worked, so I quickly hacked together a script that would do the job. Also converts empty strings into nulls and and separates the header row for JSON. May need to be tuned depending on the CSV dialect and charset you have.

#!/usr/bin/python
import csv, json
csvreader = csv.reader(open('data.csv', 'rb'), delimiter='\t', quotechar='"')
data = []
for row in csvreader:
    r = []
    for field in row:
        if field == '': field = None
        else: field = unicode(field, 'ISO-8859-1')
        r.append(field)
    data.append(r)
jsonStruct = {
    'header': data[0],
    'data': data[1:]
}
open('data.json', 'wb').write(json.dumps(jsonStruct))

How to create a showdown.js markdown extension

In your last block you have a comma after 'lang', followed immediately with a function. This is not valid json.

EDIT

It appears that the readme was incorrect. I had to to pass an array with the string 'twitter'.

var converter = new Showdown.converter({extensions: ['twitter']}); converter.makeHtml('whatever @meandave2020'); // output "<p>whatever <a href="http://twitter.com/meandave2020">@meandave2020</a></p>" 

I submitted a pull request to update this.

Defining static const integer members in class definition

Bjarne Stroustrup's example in his C++ FAQ suggests you are correct, and only need a definition if you take the address.

class AE {
    // ...
public:
    static const int c6 = 7;
    static const int c7 = 31;
};

const int AE::c7;   // definition

int f()
{
    const int* p1 = &AE::c6;    // error: c6 not an lvalue
    const int* p2 = &AE::c7;    // ok
    // ...
}

He says "You can take the address of a static member if (and only if) it has an out-of-class definition". Which suggests it would work otherwise. Maybe your min function invokes addresses somehow behind the scenes.

How to export html table to excel using javascript

I would suggest using a different approach. Add a button on the webpage that will copy the content of the table to the clipboard, with TAB chars between columns and newlines between rows. This way the "paste" function in Excel should work correctly and your web application will also work with many browsers and on many operating systems (linux, mac, mobile) and users will be able to use the data also with other spreadsheets or word processing programs.

The only tricky part is to copy to the clipboard because many browsers are security obsessed on this. A solution is to prepare the data already selected in a textarea, and show it to the user in a modal dialog box where you tell the user to copy the text (some will need to type Ctrl-C, others Command-c, others will use a "long touch" or a popup menu).

It would be nicer to have a standard copy-to-clipboard function that possibly requests a user confirmation... but this is not the case, unfortunately.

Google Forms file upload complete example

Update: Google Forms can now upload files. This answer was posted before Google Forms had the capability to upload files.

This solution does not use Google Forms. This is an example of using an Apps Script Web App, which is very different than a Google Form. A Web App is basically a website, but you can't get a domain name for it. This is not a modification of a Google Form, which can't be done to upload a file.

NOTE: I did have an example of both the UI Service and HTML Service, but have removed the UI Service example, because the UI Service is deprecated.

NOTE: The only sandbox setting available is now IFRAME. I you want to use an onsubmit attribute in the beginning form tag: <form onsubmit="myFunctionName()">, it may cause the form to disappear from the screen after the form submission.

If you were using NATIVE mode, your file upload Web App may no longer be working. With NATIVE mode, a form submission would not invoke the default behavior of the page disappearing from the screen. If you were using NATIVE mode, and your file upload form is no longer working, then you may be using a "submit" type button. I'm guessing that you may also be using the "google.script.run" client side API to send data to the server. If you want the page to disappear from the screen after a form submission, you could do that another way. But you may not care, or even prefer to have the page stay on the screen. Depending upon what you want, you'll need to configure the settings and code a certain way.

If you are using a "submit" type button, and want to continue to use it, you can try adding event.preventDefault(); to your code in the submit event handler function. Or you'll need to use the google.script.run client side API.


A custom form for uploading files from a users computer drive, to your Google Drive can be created with the Apps Script HTML Service. This example requires writing a program, but I've provide all the basic code here.

This example shows an upload form with Google Apps Script HTML Service.

What You Need

  • Google Account
  • Google Drive
  • Google Apps Script - also called Google Script

Google Apps Script

There are various ways to end up at the Google Apps Script code editor.

I mention this because if you are not aware of all the possibilities, it could be a little confusing. Google Apps Script can be embedded in a Google Site, Sheets, Docs or Forms, or used as a stand alone app.

Apps Script Overview

This example is a "Stand Alone" app with HTML Service.

HTML Service - Create a web app using HTML, CSS and Javascript

Google Apps Script only has two types of files inside of a Project:

  • Script
  • HTML

Script files have a .gs extension. The .gs code is a server side code written in JavaScript, and a combination of Google's own API.

  • Copy and Paste the following code

  • Save It

  • Create the first Named Version

  • Publish it

  • Set the Permissions

    and you can start using it.

Start by:

  • Create a new Blank Project in Apps Script
  • Copy and Paste in this code:

Upload a file with HTML Service:

Code.gs file (Created by Default)

//For this to work, you need a folder in your Google drive named:
// 'For Web Hosting'
// or change the hard coded folder name to the name of the folder
// you want the file written to

function doGet(e) {
  return HtmlService.createTemplateFromFile('Form')
    .evaluate() // evaluate MUST come before setting the Sandbox mode
    .setTitle('Name To Appear in Browser Tab')
    .setSandboxMode();//Defaults to IFRAME which is now the only mode available
}

function processForm(theForm) {
  var fileBlob = theForm.picToLoad;
  
  Logger.log("fileBlob Name: " + fileBlob.getName())
  Logger.log("fileBlob type: " + fileBlob.getContentType())
  Logger.log('fileBlob: ' + fileBlob);

  var fldrSssn = DriveApp.getFolderById(Your Folder ID);
    fldrSssn.createFile(fileBlob);
    
  return true;
}

Create an html file:

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <h1 id="main-heading">Main Heading</h1>
    <br/>
    <div id="formDiv">

      <form id="myForm">
    
        <input name="picToLoad" type="file" /><br/>
        <input type="button" value="Submit" onclick="picUploadJs(this.parentNode)" />
          
      </form>
    </div>


  <div id="status" style="display: none">
  <!-- div will be filled with innerHTML after form submission. -->
  Uploading. Please wait...
</div>

</body>
<script>

function picUploadJs(frmData) {

  document.getElementById('status').style.display = 'inline';

  google.script.run
    .withSuccessHandler(updateOutput)
    .processForm(frmData)
};
  // Javascript function called by "submit" button handler,
  // to show results.
  
  function updateOutput() {
  
    var outputDiv = document.getElementById('status');
    outputDiv.innerHTML = "The File was UPLOADED!";
  }

</script>
</html>

This is a full working example. It only has two buttons and one <div> element, so you won't see much on the screen. If the .gs script is successful, true is returned, and an onSuccess function runs. The onSuccess function (updateOutput) injects inner HTML into the div element with the message, "The File was UPLOADED!"

  • Save the file, give the project a name
  • Using the menu: File, Manage Version then Save the first Version
  • Publish, Deploy As Web App then Update

When you run the Script the first time, it will ask for permissions because it's saving files to your drive. After you grant permissions that first time, the Apps Script stops, and won't complete running. So, you need to run it again. The script won't ask for permissions again after the first time.

The Apps Script file will show up in your Google Drive. In Google Drive you can set permissions for who can access and use the script. The script is run by simply providing the link to the user. Use the link just as you would load a web page.

Another example of using the HTML Service can be seen at this link here on StackOverflow:

File Upload with HTML Service

NOTES about deprecated UI Service:

There is a difference between the UI Service, and the Ui getUi() method of the Spreadsheet Class (Or other class) The Apps Script UI Service was deprecated on Dec. 11, 2014. It will continue to work for some period of time, but you are encouraged to use the HTML Service.

Google Documentation - UI Service

Even though the UI Service is deprecated, there is a getUi() method of the spreadsheet class to add custom menus, which is NOT deprecated:

Spreadsheet Class - Get UI method

I mention this because it could be confusing because they both use the terminology UI.

The UI method returns a Ui return type.

You can add HTML to a UI Service, but you can't use a <button>, <input> or <script> tag in the HTML with the UI Service.

Here is a link to a shared Apps Script Web App file with an input form:

Shared File - Contact Form

Loop through Map in Groovy?

Quite simple with a closure:

def map = [
           'iPhone':'iWebOS',
           'Android':'2.3.3',
           'Nokia':'Symbian',
           'Windows':'WM8'
           ]

map.each{ k, v -> println "${k}:${v}" }

html select only one checkbox in a group

Here is a simple HTML and JavaScript solution I prefer:

//js function to allow only checking of one weekday checkbox at a time:

function checkOnlyOne(b){

var x = document.getElementsByClassName('daychecks');
var i;

for (i = 0; i < x.length; i++) {
  if(x[i].value != b) x[i].checked = false;
}
}


Day of the week:
<input class="daychecks" onclick="checkOnlyOne(this.value);" type="checkbox" name="reoccur_weekday" value="Monday" />Mon&nbsp;&nbsp;&nbsp;
<input class="daychecks" onclick="checkOnlyOne(this.value);" type="checkbox" name="reoccur_weekday" value="Tuesday" />Tue&nbsp;&nbsp;&nbsp;
<input class="daychecks" onclick="checkOnlyOne(this.value);" type="checkbox" name="reoccur_weekday" value="Wednesday" />Wed&nbsp;&nbsp;&nbsp;
<input class="daychecks" onclick="checkOnlyOne(this.value);" type="checkbox" name="reoccur_weekday" value="Thursday" />Thu&nbsp;&nbsp;&nbsp;
<input class="daychecks" onclick="checkOnlyOne(this.value);" type="checkbox" name="reoccur_weekday" value="Friday" />Fri&nbsp;&nbsp;&nbsp;
<input class="daychecks" onclick="checkOnlyOne(this.value);" type="checkbox" name="reoccur_weekday" value="Saturday" />Sat&nbsp;&nbsp;&nbsp;
<input class="daychecks" onclick="checkOnlyOne(this.value);" type="checkbox" name="reoccur_weekday" value="Sunday" />Sun&nbsp;&nbsp;&nbsp;<br /><br />

How to set Spinner Default by its Value instead of Position?

this is how i did it:

String[] listAges = getResources().getStringArray(R.array.ages);

        // Creating adapter for spinner
        ArrayAdapter<String> dataAdapter =
                new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, listAges);

        // Drop down layout style - list view with radio button
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        // attaching data adapter to spinner
        spinner_age.getBackground().setColorFilter(ContextCompat.getColor(this, R.color.spinner_icon), PorterDuff.Mode.SRC_ATOP);
        spinner_age.setAdapter(dataAdapter);
        spinner_age.setSelection(0);
        spinner_age.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String item = parent.getItemAtPosition(position).toString();

                if(position > 0){
                    // get spinner value
                    Toast.makeText(parent.getContext(), "Age..." + item, Toast.LENGTH_SHORT).show();
                }else{
                    // show toast select gender
                    Toast.makeText(parent.getContext(), "none" + item, Toast.LENGTH_SHORT).show();
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

Cell Style Alignment on a range

  ExcelApp.Sheets[1].Range[ExcelApp.Sheets[1].Cells[1, 1], ExcelApp.Sheets[1].Cells[70, 15]].Cells.HorizontalAlignment =
                 Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;

This works fine for me.

Uncaught TypeError: Cannot set property 'onclick' of null

Try to put all your <script ...></script> tags before the </body> tag. Perhaps the js is trying to access an object of the DOM before it's built up.

What is the email subject length limit?

See RFC 2822, section 2.1.1 to start.

There are two limits that this standard places on the number of characters in a line. Each line of characters MUST be no more than 998 characters, and SHOULD be no more than 78 characters, excluding the CRLF.

As the RFC states later, you can work around this limit (not that you should) by folding the subject over multiple lines.

Each header field is logically a single line of characters comprising the field name, the colon, and the field body. For convenience however, and to deal with the 998/78 character limitations per line, the field body portion of a header field can be split into a multiple line representation; this is called "folding". The general rule is that wherever this standard allows for folding white space (not simply WSP characters), a CRLF may be inserted before any WSP. For example, the header field:

       Subject: This is a test

can be represented as:

       Subject: This
        is a test

The recommendation for no more than 78 characters in the subject header sounds reasonable. No one wants to scroll to see the entire subject line, and something important might get cut off on the right.

How to sort pandas data frame using values from several columns?

The dataframe.sort() method is - so my understanding - deprecated in pandas > 0.18. In order to solve your problem you should use dataframe.sort_values() instead:

f.sort_values(by=["c1","c2"], ascending=[False, True])

The output looks like this:

    c1  c2
    3   10
    2   15
    2   30
    2   100
    1   20

Check if url contains string with JQuery

use href with indexof

<script type="text/javascript">
 $(document).ready(function () {
   if(window.location.href.indexOf("added-to-cart=555") > -1) {
   alert("your url contains the added-to-cart=555");
  }
});
</script>

How do I avoid the "#DIV/0!" error in Google docs spreadsheet?

Wrapping the existing formula in IFERROR will not achieve:

the average of cells that contain non-zero, non-blank values.

I suggest trying:

=if(ArrayFormula(isnumber(K23:M23)),AVERAGEIF(K23:M23,"<>0"),"")

How do I use Access-Control-Allow-Origin? Does it just go in between the html head tags?

That is an HTTP header. You would configure your webserver or webapp to send this header ideally. Perhaps in htaccess or PHP.

Alternatively you might be able to use

<head>...<meta http-equiv="Access-Control-Allow-Origin" content="*">...</head>

I do not know if that would work. Not all HTTP headers can be configured directly in the HTML.

This works as an alternative to many HTTP headers, but see @EricLaw's comment below. This particular header is different.

Caveat

This answer is strictly about how to set headers. I do not know anything about allowing cross domain requests.

About HTTP Headers

Every request and response has headers. The browser sends this to the webserver

GET /index.htm HTTP/1.1

Then the headers

Host: www.example.com
User-Agent: (Browser/OS name and version information)
.. Additional headers indicating supported compression types and content types and other info

Then the server sends a response

Content-type: text/html
Content-length: (number of bytes in file (optional))
Date: (server clock)
Server: (Webserver name and version information)

Additional headers can be configured for example Cache-Control, it all depends on your language (PHP, CGI, Java, htaccess) and webserver (Apache, etc).

The cause of "bad magic number" error when loading a workspace and how to avoid it?

The magic number comes from UNIX-type systems where the first few bytes of a file held a marker indicating the file type.

This error indicates you are trying to load a non-valid file type into R. For some reason, R no longer recognizes this file as an R workspace file.

Extracting numbers from vectors of strings

We can also use str_extract from stringr

years<-c("20 years old", "1 years old")
as.integer(stringr::str_extract(years, "\\d+"))
#[1] 20  1

If there are multiple numbers in the string and we want to extract all of them, we may use str_extract_all which unlike str_extract returns all the macthes.

years<-c("20 years old and 21", "1 years old")
stringr::str_extract(years, "\\d+")
#[1] "20"  "1"

stringr::str_extract_all(years, "\\d+")

#[[1]]
#[1] "20" "21"

#[[2]]
#[1] "1"

What is Inversion of Control?

Inversion of control is an indicator for a shift of responsibility in the program.

There is an inversion of control every time when a dependency is granted ability to directly act on the caller's space.

The smallest IoC is passing a variable by reference, lets look at non-IoC code first:

function isVarHello($var) {
    return ($var === "Hello");
}

// Responsibility is within the caller
$word = "Hello";
if (isVarHello($word)) {
    $word = "World";
}

Let's now invert the control by shifting the responsibility of a result from the caller to the dependency:

function changeHelloToWorld(&$var) {
    // Responsibility has been shifted to the dependency
    if ($var === "Hello") {
        $var = "World";
    }
}

$word = "Hello";
changeHelloToWorld($word);

Here is another example using OOP:

<?php

class Human {
    private $hp = 0.5;

    function consume(Eatable $chunk) {
        // $this->chew($chunk);
        $chunk->unfoldEffectOn($this);
    }

    function incrementHealth() {
        $this->hp++;
    }
    function isHealthy() {}
    function getHungry() {}
    // ...
}

interface Eatable {
    public function unfoldEffectOn($body);
}

class Medicine implements Eatable {
    function unfoldEffectOn($human) {
        // The dependency is now in charge of the human.
        $human->incrementHealth();
        $this->depleted = true;
    }
}

$human = new Human();
$medicine = new Medicine();
if (!$human->isHealthy()) {
    $human->consume($medicine);   
}

var_dump($medicine);
var_dump($human);

*) Disclaimer: The real world human uses a message queue.

How to listen for changes to a MongoDB collection?

Since MongoDB 3.6 there will be a new notifications API called Change Streams which you can use for this. See this blog post for an example. Example from it:

cursor = client.my_db.my_collection.changes([
    {'$match': {
        'operationType': {'$in': ['insert', 'replace']}
    }},
    {'$match': {
        'newDocument.n': {'$gte': 1}
    }}
])

# Loops forever.
for change in cursor:
    print(change['newDocument'])

How to strip a specific word from a string?

A bit 'lazy' way to do this is to use startswith- it is easier to understand this rather regexps. However regexps might work faster, I haven't measured.

>>> papa = "papa is a good man"
>>> app = "app is important"
>>> strip_word = 'papa'
>>> papa[len(strip_word):] if papa.startswith(strip_word) else papa
' is a good man'
>>> app[len(strip_word):] if app.startswith(strip_word) else app
'app is important'

Is SQL syntax case sensitive?

My understanding is that the SQL standard calls for case-insensitivity. I don't believe any databases follow the standard completely, though.

MySQL has a configuration setting as part of its "strict mode" (a grab bag of several settings that make MySQL more standards-compliant) for case sensitive or insensitive table names. Regardless of this setting, column names are still case-insensitive, although I think it affects how the column-names are displayed. I believe this setting is instance-wide, across all databases within the RDBMS instance, although I'm researching today to confirm this (and hoping the answer is no).

I like how Oracle handles this far better. In straight SQL, identifiers like table and column names are case insensitive. However, if for some reason you really desire to get explicit casing, you can enclose the identifier in double-quotes (which are quite different in Oracle SQL from the single-quotes used to enclose string data). So:

SELECT fieldName
FROM tableName;

will query fieldname from tablename, but

SELECT "fieldName"
FROM "tableName";

will query fieldName from tableName.

I'm pretty sure you could even use this mechanism to insert spaces or other non-standard characters into an identifier.

In this situation if for some reason you found explicitly-cased table and column names desirable it was available to you, but it was still something I would highly caution against.

My convention when I used Oracle on a daily basis was that in code I would put all Oracle SQL keywords in uppercase and all identifiers in lowercase. In documentation I would put all table and column names in uppercase. It was very convenient and readable to be able to do this (although sometimes a pain to type so many capitals in code -- I'm sure I could've found an editor feature to help, here).

In my opinion MySQL is particularly bad for differing about this on different platforms. We need to be able to dump databases on Windows and load them into UNIX, and doing so is a disaster if the installer on Windows forgot to put the RDBMS into case-sensitive mode. (To be fair, part of the reason this is a disaster is our coders made the bad decision, long ago, to rely on the case-sensitivity of MySQL on UNIX.) The people who wrote the Windows MySQL installer made it really convenient and Windows-like, and it was great to move toward giving people a checkbox to say "Would you like to turn on strict mode and make MySQL more standards-compliant?" But it is very convenient for MySQL to differ so signficantly from the standard, and then make matters worse by turning around and differing from its own de facto standard on different platforms. I'm sure that on differing Linux distributions this may be further compounded, as packagers for different distros probably have at times incorporated their own preferred MySQL configuration settings.

Here's another SO question that gets into discussing if case-sensitivity is desirable in an RDBMS.

Django: TemplateSyntaxError: Could not parse the remainder

also happens when you use jinja templates (which have different syntax for calling object methods) and you forget to set it in settings.py

Multiple values in single-value context

Here's a generic helper function with assumption checking:

func assumeNoError(value interface{}, err error) interface{} {
    if err != nil {
        panic("error encountered when none assumed:" + err.Error())
    }
    return value
}

Since this returns as an interface{}, you'll generally need to cast it back to your function's return type.

For example, the OP's example called Get(1), which returns (Item, error).

item := assumeNoError(Get(1)).(Item)

The trick that makes this possible: Multi-values returned from one function call can be passed in as multi-variable arguments to another function.

As a special case, if the return values of a function or method g are equal in number and individually assignable to the parameters of another function or method f, then the call f(g(parameters_of_g)) will invoke f after binding the return values of g to the parameters of f in order.


This answer borrows heavily from existing answers, but none had provided a simple, generic solution of this form.

Converting 24 hour time to 12 hour time w/ AM & PM using Javascript

I noticed there is already an answer, but I wanted to share my own solution, using pure JavaScript:

function curTime(pm) {
  var dt = new Date();
  var hr = dt.getHours(), min = dt.getMinutes(), sec = dt.getSeconds();
  var time = (pm ? ((hr+11)%12+1) : (hr<10?'0':'')+hr)+":"+(min<10?'0':'')+min+":"+(sec<10?'0':'')+sec+(pm ? (hr>12 ? " PM" : " AM") : ""); 
  return time;
}

You can see it in action at https://jsfiddle.net/j2xk312m/3/ using the following code block:

(function() {

  function curTime(pm) {
    var dt = new Date();
    var hr = dt.getHours(), min = dt.getMinutes(), sec = dt.getSeconds();
    var time = (pm ? ((hr+11)%12+1) : (hr<10?'0':'')+hr)+":"+(min<10?'0':'')+min+":"+(sec<10?'0':'')+sec+(pm ? (hr>12 ? " PM" : " AM") : ""); 
    return time;
  }

  alert("12-hour Format:    "+curTime(true)+"\n24-hour Format:    "+curTime(false));

})();

How do I add 24 hours to a unix timestamp in php?

$time = date("H:i", strtotime($today . " +5 hours +30 minutes"));
//+5 hours +30 minutes     Time Zone +5:30 (Asia/Kolkata)

MySQL server has gone away - in exactly 60 seconds

Increasing SQL-Wait-Timeout worked for me in this case, try this:

mysql_query("SET @@session.wait_timeout=900", $link);

before you first "normal" SQL queries.

Convert a double to a QString

Check out the documentation

Quote:

QString provides many functions for converting numbers into strings and strings into numbers. See the arg() functions, the setNum() functions, the number() static functions, and the toInt(), toDouble(), and similar functions.

Excel VBA - select multiple columns not in sequential order

As a recorded macro.

range("A:A, B:B, D:D, E:E, G:G, H:H").select

WPF: Grid with column/row margin/padding?

As was stated before create a GridWithMargins class. Here is my working code example

public class GridWithMargins : Grid
{
    public Thickness RowMargin { get; set; } = new Thickness(10, 10, 10, 10);
    protected override Size ArrangeOverride(Size arrangeSize)
    {
        var basesize = base.ArrangeOverride(arrangeSize);

        foreach (UIElement child in InternalChildren)
        {
            var pos = GetPosition(child);
            pos.X += RowMargin.Left;
            pos.Y += RowMargin.Top;

            var actual = child.RenderSize;
            actual.Width -= (RowMargin.Left + RowMargin.Right);
            actual.Height -= (RowMargin.Top + RowMargin.Bottom);
            var rec = new Rect(pos, actual);
            child.Arrange(rec);
        }
        return arrangeSize;
    }

    private Point GetPosition(Visual element)
    {
        var posTransForm = element.TransformToAncestor(this);
        var areaTransForm = posTransForm.Transform(new Point(0, 0));
        return areaTransForm;
    }
}

Usage:

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfApplication1"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
    <Grid>
        <local:GridWithMargins ShowGridLines="True">
            <Grid.RowDefinitions>
                <RowDefinition />
                <RowDefinition />
                <RowDefinition />
                <RowDefinition />
                <RowDefinition />
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition />
                <ColumnDefinition />
                <ColumnDefinition />
            </Grid.ColumnDefinitions>
            <Rectangle Fill="Red" Grid.Row="0" Grid.Column="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
            <Rectangle Fill="Green" Grid.Row="1" Grid.Column="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
            <Rectangle Fill="Blue" Grid.Row="1" Grid.Column="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
        </local:GridWithMargins>
    </Grid>
</Window>

Setting DataContext in XAML in WPF

First of all you should create property with employee details in the Employee class:

public class Employee
{
    public Employee()
    {
        EmployeeDetails = new EmployeeDetails();
        EmployeeDetails.EmpID = 123;
        EmployeeDetails.EmpName = "ABC";
    }

    public EmployeeDetails EmployeeDetails { get; set; }
}

If you don't do that, you will create instance of object in Employee constructor and you lose reference to it.

In the XAML you should create instance of Employee class, and after that you can assign it to DataContext.

Your XAML should look like this:

<Window x:Class="SampleApplication.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525"
    xmlns:local="clr-namespace:SampleApplication"
   >
    <Window.Resources>
        <local:Employee x:Key="Employee" />
    </Window.Resources>
    <Grid DataContext="{StaticResource Employee}">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="200" />
        </Grid.ColumnDefinitions>

        <Label Grid.Row="0" Grid.Column="0" Content="ID:"/>
        <Label Grid.Row="1" Grid.Column="0" Content="Name:"/>
        <TextBox Grid.Column="1" Grid.Row="0" Margin="3" Text="{Binding EmployeeDetails.EmpID}" />
        <TextBox Grid.Column="1" Grid.Row="1" Margin="3" Text="{Binding EmployeeDetails.EmpName}" />
    </Grid>
</Window>

Now, after you created property with employee details you should binding by using this property:

Text="{Binding EmployeeDetails.EmpID}"

HttpContext.Current.Session is null when routing requests

Nice job! I've been having the exact same problem. Adding and removing the Session module worked perfectly for me too. It didn't however bring back by HttpContext.Current.User so I tried your little trick with the FormsAuth module and sure enough, that did it.

<remove name="FormsAuthentication" />
<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule"/>

How to wrap text around an image using HTML/CSS

With CSS Shapes you can go one step further than just float text around a rectangular image.

You can actually wrap text such that it takes the shape of the edge of the image or polygon that you are wrapping it around.

DEMO FIDDLE (Currently working on webkit - caniuse)

_x000D_
_x000D_
.oval {_x000D_
  width: 400px;_x000D_
  height: 250px;_x000D_
  color: #111;_x000D_
  border-radius: 50%;_x000D_
  text-align: center;_x000D_
  font-size: 90px;_x000D_
  float: left;_x000D_
  shape-outside: ellipse();_x000D_
  padding: 10px;_x000D_
  background-color: MediumPurple;_x000D_
  background-clip: content-box;_x000D_
}_x000D_
span {_x000D_
  padding-top: 70px;_x000D_
  display: inline-block;_x000D_
}
_x000D_
<div class="oval"><span>PHP</span>_x000D_
</div>_x000D_
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has_x000D_
  survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing_x000D_
  software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley_x000D_
  of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing_x000D_
  Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy_x000D_
  text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised_x000D_
  in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
_x000D_
_x000D_
_x000D_

Also, here is a good list apart article on CSS Shapes

How to rotate a div using jQuery

EDIT: Updated for jQuery 1.8

Since jQuery 1.8 browser specific transformations will be added automatically. jsFiddle Demo

var rotation = 0;

jQuery.fn.rotate = function(degrees) {
    $(this).css({'transform' : 'rotate('+ degrees +'deg)'});
    return $(this);
};

$('.rotate').click(function() {
    rotation += 5;
    $(this).rotate(rotation);
});

EDIT: Added code to make it a jQuery function.

For those of you who don't want to read any further, here you go. For more details and examples, read on. jsFiddle Demo.

var rotation = 0;

jQuery.fn.rotate = function(degrees) {
    $(this).css({'-webkit-transform' : 'rotate('+ degrees +'deg)',
                 '-moz-transform' : 'rotate('+ degrees +'deg)',
                 '-ms-transform' : 'rotate('+ degrees +'deg)',
                 'transform' : 'rotate('+ degrees +'deg)'});
    return $(this);
};

$('.rotate').click(function() {
    rotation += 5;
    $(this).rotate(rotation);
});

EDIT: One of the comments on this post mentioned jQuery Multirotation. This plugin for jQuery essentially performs the above function with support for IE8. It may be worth using if you want maximum compatibility or more options. But for minimal overhead, I suggest the above function. It will work IE9+, Chrome, Firefox, Opera, and many others.


Bobby... This is for the people who actually want to do it in the javascript. This may be required for rotating on a javascript callback.

Here is a jsFiddle.

If you would like to rotate at custom intervals, you can use jQuery to manually set the css instead of adding a class. Like this! I have included both jQuery options at the bottom of the answer.

HTML

<div class="rotate">
    <h1>Rotatey text</h1>
</div>

CSS

/* Totally for style */
.rotate {
    background: #F02311;
    color: #FFF;
    width: 200px;
    height: 200px;
    text-align: center;
    font: normal 1em Arial;
    position: relative;
    top: 50px;
    left: 50px;
}

/* The real code */
.rotated {
    -webkit-transform: rotate(45deg);  /* Chrome, Safari 3.1+ */
    -moz-transform: rotate(45deg);  /* Firefox 3.5-15 */
    -ms-transform: rotate(45deg);  /* IE 9 */
    -o-transform: rotate(45deg);  /* Opera 10.50-12.00 */
    transform: rotate(45deg);  /* Firefox 16+, IE 10+, Opera 12.10+ */
}

jQuery

Make sure these are wrapped in $(document).ready

$('.rotate').click(function() {
    $(this).toggleClass('rotated');
});

Custom intervals

var rotation = 0;
$('.rotate').click(function() {
    rotation += 5;
    $(this).css({'-webkit-transform' : 'rotate('+ rotation +'deg)',
                 '-moz-transform' : 'rotate('+ rotation +'deg)',
                 '-ms-transform' : 'rotate('+ rotation +'deg)',
                 'transform' : 'rotate('+ rotation +'deg)'});
});

Restart pods when configmap updates in Kubernetes?

https://github.com/kubernetes/helm/blob/master/docs/charts_tips_and_tricks.md#user-content-automatically-roll-deployments-when-configmaps-or-secrets-change

Often times configmaps or secrets are injected as configuration files in containers. Depending on the application a restart may be required should those be updated with a subsequent helm upgrade, but if the deployment spec itself didn't change the application keeps running with the old configuration resulting in an inconsistent deployment.

The sha256sum function can be used together with the include function to ensure a deployments template section is updated if another spec changes:

kind: Deployment
spec:
  template:
    metadata:
      annotations:
        checksum/config: {{ include (print $.Template.BasePath "/secret.yaml") . | sha256sum }}
[...]

In my case, for some reasons, $.Template.BasePath didn't work but $.Chart.Name does:

spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: admin-app
      annotations:
        checksum/config: {{ include (print $.Chart.Name "/templates/" $.Chart.Name "-configmap.yaml") . | sha256sum }}

C# Help reading foreign characters using StreamReader

for Arabic, I used Encoding.GetEncoding(1256). it is working good.

Entity Framework code-first: migration fails with update-database, forces unneccessary(?) add-migration

I understand this is a very old thread. However, wanted to share how I encountered the message in my scenario and in case it might help others

  1. I created an Add-Migration <Migration_name> on my local machine. Didn't run the update-database yet.
  2. Meanwhile, there were series of commits in parent branch that I must down merge. The merge also had a migration to it and when I fixed conflicts, I ended up having 2 migrations that are added to my project but are not executed via update-database.
  3. Now I don't use enable-migrations -force in my application. Rather my preferred way is execute the update-database -script command to control the target migrations I need.
  4. So, when I attempted the above command, I get the error in question.

My solution was to run update-database -Script -TargetMigration <migration_name_from_merge> and then my update-database -Script -TargetMigration <migration_name> which generated 2 scripts that I was able to run manually on my local db.

Needless to say above experience is on my local machine.

How can I make a CSS table fit the screen width?

If the table content is too wide (as in this example), there's nothing you can do other than alter the content to make it possible for the browser to show it in a more narrow format. Contrary to the earlier answers, setting width to 100% will have absolutely no effect if the content is too wide (as that link, and this one, demonstrate). Browsers already try to keep tables within the left and right margins if they can, and only resort to a horizontal scrollbar if they can't.

Some ways you can alter content to make a table more narrow:

  • Reduce the number of columns (perhaps breaking one megalithic table into multiple independent tables).
  • If you're using CSS white-space: nowrap on any of the content (or the old nowrap attribute, &nbsp;, a nobr element, etc.), see if you can live without them so the browser has the option of wrapping that content to keep the width down.
  • If you're using really wide margins, padding, borders, etc., try reducing their size (but I'm sure you thought of that).

If the table is too wide but you don't see a good reason for it (the content isn't that wide, etc.), you'll have to provide more information about how you're styling the table, the surrounding elements, etc. Again, by default the browser will avoid the scrollbar if it can.

List<T> OrderBy Alphabetical Order

If you mean an in-place sort (i.e. the list is updated):

people.Sort((x, y) => string.Compare(x.LastName, y.LastName));

If you mean a new list:

var newList = people.OrderBy(x=>x.LastName).ToList(); // ToList optional

Java serialization - java.io.InvalidClassException local class incompatible

This worked for me:

If you wrote your Serialized class object into a file, then made some changes to file and compiled it, and then you try to read an object, then this will happen.

So, write the necessary objects to file again if a class is modified and recompiled.

PS: This is NOT a solution; was meant to be a workaround.

in a "using" block is a SqlConnection closed on return or exception?

I wrote two using statements inside a try/catch block and I could see the exception was being caught the same way if it's placed within the inner using statement just as ShaneLS example.

     try
     {
       using (var con = new SqlConnection(@"Data Source=..."))
       {
         var cad = "INSERT INTO table VALUES (@r1,@r2,@r3)";

         using (var insertCommand = new SqlCommand(cad, con))
         {
           insertCommand.Parameters.AddWithValue("@r1", atxt);
           insertCommand.Parameters.AddWithValue("@r2", btxt);
           insertCommand.Parameters.AddWithValue("@r3", ctxt);
           con.Open();
           insertCommand.ExecuteNonQuery();
         }
       }
     }
     catch (Exception ex)
     {
       MessageBox.Show("Error: " + ex.Message, "UsingTest", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }

No matter where's the try/catch placed, the exception will be caught without issues.

Nested iframes, AKA Iframe Inception

I think the best way to reach your div:

var your_element=$('iframe#uploads').children('iframe').children('div#element');

It should work well.

Get restaurants near my location

Is this what you are looking for?

https://maps.googleapis.com/maps/api/place/search/xml?location=49.260691,-123.137784&radius=500&sensor=false&key=*PlacesAPIKey*&types=restaurant

types is optional

MySQL count occurrences greater than 2

To get a list of the words that appear more than once together with how often they occur, use a combination of GROUP BY and HAVING:

SELECT word, COUNT(*) AS cnt
FROM words
GROUP BY word
HAVING cnt > 1

To find the number of words in the above result set, use that as a subquery and count the rows in an outer query:

SELECT COUNT(*)
FROM
(
    SELECT NULL
    FROM words
    GROUP BY word
    HAVING COUNT(*) > 1
) T1

List All Google Map Marker Images

var pinIcon = new google.maps.MarkerImage(
    "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|00D900",
    null, /* size is determined at runtime */
    null, /* origin is 0,0 */
    null, /* anchor is bottom center of the scaled image */
    new google.maps.Size(12, 18)
);

unable to dequeue a cell with identifier Cell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard

I just met the same issue and see this post. For me it's because I forgot the set the identifier of cell, also as mentioned in other answers. What I want to say is that if you are using the storyboard to load custom cell we don't need to register the table view cell in code, which can cause other problems.

See this post for detail:

Custom table view cell: IBOutlet label is nil

Android Studio: Module won't show up in "Edit Configuration"

In my case the problem was with SDK license acceptance. The problem was solved by downloading proper SDK version and license acceptance via SDK Manager.

break out of if and foreach

foreach($equipxml as $equip) {
    $current_device = $equip->xpath("name");
    if ( $current_device[0] == $device ) {
        // found a match in the file            
        $nodeid = $equip->id;
        break;
    }
}

Simply use break. That will do it.

When do you use the "this" keyword?

Never. Ever. If you have variable shadowing, your naming conventions are on crack. I mean, really, no distinguishing naming for member variables? Facepalm

Getting attribute using XPath

you can use:

(//@lang)[1]

these means you get all attributes nodes with name equal to "lang" and get the first one.

How to re-index all subarray elements of a multidimensional array?

$array[9] = 'Apple';
$array[12] = 'Orange';
$array[5] = 'Peach';

$array = array_values($array);

through this function you can reset your array

$array[0] = 'Apple';
$array[1] = 'Orange';
$array[2] = 'Peach';

How to fix the error; 'Error: Bootstrap tooltips require Tether (http://github.hubspot.com/tether/)'

You should done my guideline:
1. Add bellow source into Gemfile

source 'https://rails-assets.org' do
  gem 'rails-assets-tether', '>= 1.1.0'
end
  1. Run command:

    bundle install

  2. Add this line after jQuery in application.js.

    //= require jquery
    //= require tether

  3. Restart rails server.

function to return a string in java

Your code is fine. There's no problem with returning Strings in this manner.

In Java, a String is a reference to an immutable object. This, coupled with garbage collection, takes care of much of the potential complexity: you can simply pass a String around without worrying that it would disapper on you, or that someone somewhere would modify it.

If you don't mind me making a couple of stylistic suggestions, I'd modify the code like so:

public String time_to_string(long t) // time in milliseconds
{
    if (t < 0)
    {
        return "-";
    }
    else
    {
        int secs = (int)(t/1000);
        int mins = secs/60;
        secs = secs - (mins * 60);
        return String.format("%d:%02d", mins, secs);
    }
}

As you can see, I've pushed the variable declarations as far down as I could (this is the preferred style in C++ and Java). I've also eliminated ans and have replaced the mix of string concatenation and String.format() with a single call to String.format().

How to find row number of a value in R code

Instead of 1:nrow(mydata_2) you can simply use the which() function: which(mydata_2[,4] == 1578)

Although as it was pointed out above, the 3rd column contains 1578, not the fourth: which(mydata_2[,3] == 1578)

Keyboard shortcut to clear cell output in Jupyter notebook

Just adding in for JupyterLab users. Ctrl, (advanced settings) and pasting the below in User References under keyboard shortcuts does the trick for me.

{
"shortcuts": [
        {
            "command": "notebook:hide-cell-outputs",
            "keys": [
                "H"
            ],
            "selector": ".jp-Notebook:focus"
        },
        {
            "command": "notebook:show-cell-outputs",
            "keys": [
                "Shift H"
            ],
            "selector": ".jp-Notebook:focus"
        }
    ]
}

Is it possible to append to innerHTML without destroying descendants' event listeners?

You could do it like this:

var anchors = document.getElementsByTagName('a'); 
var index_a = 0;
var uls = document.getElementsByTagName('UL'); 
window.onload=function()          {alert(anchors.length);};
for(var i=0 ; i<uls.length;  i++)
{
    lis = uls[i].getElementsByTagName('LI');
    for(var j=0 ;j<lis.length;j++)
    {
        var first = lis[j].innerHTML; 
        string = "<img src=\"http://g.etfv.co/" +  anchors[index_a++] + 
            "\"  width=\"32\" 
        height=\"32\" />   " + first;
        lis[j].innerHTML = string;
    }
}

How to retrieve GET parameters from JavaScript

Here I've made this code to transform the GET parameters into an object to use them more easily.

// Get Nav URL
function getNavUrl() {
    // Get URL
    return window.location.search.replace("?", "");
};

function getParameters(url) {
    // Params obj
    var params = {};
    // To lowercase
    url = url.toLowerCase();
    // To array
    url = url.split('&');

    // Iterate over URL parameters array
    var length = url.length;
    for(var i=0; i<length; i++) {
        // Create prop
        var prop = url[i].slice(0, url[i].search('='));
        // Create Val
        var value = url[i].slice(url[i].search('=')).replace('=', '');
        // Params New Attr
        params[prop] = value;
    }
    return params;
};

// Call of getParameters
console.log(getParameters(getNavUrl()));

Changing default startup directory for command prompt in Windows 7

changing shortcut under Windows System on 8.1 worked for me - another thing I found is that 'Start In:' WORKS when Advanced -> Run as admin is UNCHECKED, however, if CHECKED, it does not work

Change app language programmatically in Android

Alex Volovoy answer only works for me if it's in onCreate method of the activity.

The answer that works in all the methods is in another thread

Change language programmatically in Android

Here is the adaptation of the code



    Resources standardResources = getBaseContext().getResources();

    AssetManager assets = standardResources.getAssets();

    DisplayMetrics metrics = standardResources.getDisplayMetrics();

    Configuration config = new Configuration(standardResources.getConfiguration());

    config.locale = new Locale(languageToLoad);

    Resources defaultResources = new Resources(assets, metrics, config);

Hope that it helps.

Log4net rolling daily filename with date in the file name

The extended configuration section in a previous response with

 ...
 ...
 <rollingStyle value="Composite" />
 ...
 ...

listed works but I did not have to use

<staticLogFileName value="false" /> 

. I think the RollingAppender must (logically) ignore that setting since by definition the file gets rebuilt each day when the application restarts/reused. Perhaps it does matter for immediate rollover EVERY time the application starts.

What are ODEX files in Android?

The blog article is mostly right, but not complete. To have a full understanding of what an odex file does, you have to understand a little about how application files (APK) work.

Applications are basically glorified ZIP archives. The java code is stored in a file called classes.dex and this file is parsed by the Dalvik JVM and a cache of the processed classes.dex file is stored in the phone's Dalvik cache.

An odex is basically a pre-processed version of an application's classes.dex that is execution-ready for Dalvik. When an application is odexed, the classes.dex is removed from the APK archive and it does not write anything to the Dalvik cache. An application that is not odexed ends up with 2 copies of the classes.dex file--the packaged one in the APK, and the processed one in the Dalvik cache. It also takes a little longer to launch the first time since Dalvik has to extract and process the classes.dex file.

If you are building a custom ROM, it's a really good idea to odex both your framework JAR files and the stock apps in order to maximize the internal storage space for user-installed apps. If you want to theme, then simply deodex -> apply your theme -> reodex -> release.

To actually deodex, use small and baksmali:

https://github.com/JesusFreke/smali/wiki/DeodexInstructions

What is the difference between smoke testing and sanity testing?

Sanity testing

Sanity testing is the subset of regression testing and it is performed when we do not have enough time for doing testing.

Sanity testing is the surface level testing where QA engineer verifies that all the menus, functions, commands available in the product and project are working fine.


Example

For example, in a project there are 5 modules: Login Page, Home Page, User's Details Page, New User Creation and Task Creation.

Suppose we have a bug in the login page: the login page's username field accepts usernames which are shorter than 6 alphanumeric characters, and this is against the requirements, as in the requirements it is specified that the username should be at least 6 alphanumeric characters.

Now the bug is reported by the testing team to the developer team to fix it. After the developing team fixes the bug and passes the app to the testing team, the testing team also checks the other modules of the application in order to verify that the bug fix does not affect the functionality of the other modules. But keep one point always in mind: the testing team only checks the extreme functionality of the modules, it does not go deep to test the details because of the short time.


Sanity testing is performed after the build has cleared the smoke tests and has been accepted by QA team for further testing. Sanity testing checks the major functionality with finer details.

Sanity testing is performed when the development team needs to know quickly the state of the product after they have done changes in the code, or there is some controlled code changed in a feature to fix any critical issue, and stringent release time-frame does not allow complete regression testing.


Smoke testing

Smoke Testing is performed after a software build to ascertain that the critical functionalities of the program are working fine. It is executed "before" any detailed functional or regression tests are executed on the software build.

The purpose is to reject a badly broken application, so that the QA team does not waste time installing and testing the software application.

In smoke testing, the test cases chosen cover the most important functionalities or components of the system. The objective is not to perform exhaustive testing, but to verify that the critical functionalities of the system are working fine. For example, typical smoke tests would be:

  • verify that the application launches successfully,
  • Check that the GUI is responsive

What's the difference between OpenID and OAuth?

The explanation of the difference between OpenID, OAuth, OpenID Connect:

OpenID is a protocol for authentication while OAuth is for authorization. Authentication is about making sure that the guy you are talking to is indeed who he claims to be. Authorization is about deciding what that guy should be allowed to do.

In OpenID, authentication is delegated: server A wants to authenticate user U, but U's credentials (e.g. U's name and password) are sent to another server, B, that A trusts (at least, trusts for authenticating users). Indeed, server B makes sure that U is indeed U, and then tells to A: "ok, that's the genuine U".

In OAuth, authorization is delegated: entity A obtains from entity B an "access right" which A can show to server S to be granted access; B can thus deliver temporary, specific access keys to A without giving them too much power. You can imagine an OAuth server as the key master in a big hotel; he gives to employees keys which open the doors of the rooms that they are supposed to enter, but each key is limited (it does not give access to all rooms); furthermore, the keys self-destruct after a few hours.

To some extent, authorization can be abused into some pseudo-authentication, on the basis that if entity A obtains from B an access key through OAuth, and shows it to server S, then server S may infer that B authenticated A before granting the access key. So some people use OAuth where they should be using OpenID. This schema may or may not be enlightening; but I think this pseudo-authentication is more confusing than anything. OpenID Connect does just that: it abuses OAuth into an authentication protocol. In the hotel analogy: if I encounter a purported employee and that person shows me that he has a key which opens my room, then I suppose that this is a true employee, on the basis that the key master would not have given him a key which opens my room if he was not.

(source)

How is OpenID Connect different than OpenID 2.0?

OpenID Connect performs many of the same tasks as OpenID 2.0, but does so in a way that is API-friendly, and usable by native and mobile applications. OpenID Connect defines optional mechanisms for robust signing and encryption. Whereas integration of OAuth 1.0a and OpenID 2.0 required an extension, in OpenID Connect, OAuth 2.0 capabilities are integrated with the protocol itself.

(source)

OpenID connect will give you an access token plus an id token. The id token is a JWT and contains information about the authenticated user. It is signed by the identity provider and can be read and verified without accessing the identity provider.

In addition, OpenID connect standardizes quite a couple things that oauth2 leaves up to choice. for instance scopes, endpoint discovery, and dynamic registration of clients.

This makes it easier to write code that lets the user choose between multiple identity providers.

(source)

Google's OAuth 2.0

Google's OAuth 2.0 APIs can be used for both authentication and authorization. This document describes our OAuth 2.0 implementation for authentication, which conforms to the OpenID Connect specification, and is OpenID Certified. The documentation found in Using OAuth 2.0 to Access Google APIs also applies to this service. If you want to explore this protocol interactively, we recommend the Google OAuth 2.0 Playground.

(source)

What do the icons in Eclipse mean?

In eclipse help documentation, we can all icons information as follows. Common path for all eclipse versions except eclipse version:

enter image description here

https://help.eclipse.org/2019-09/index.jsp?nav=%2F1

How to copy file from HDFS to the local file system

1.- Remember the name you gave to the file and instead of using hdfs dfs -put. Use 'get' instead. See below.

$hdfs dfs -get /output-fileFolderName-In-hdfs

Split string into array of character strings

String str = "cat";
char[] cArray = str.toCharArray();

Vba macro to copy row from table if value in table meets condition

That is exactly what you do with an advanced filter. If it's a one shot, you don't even need a macro, it is available in the Data menu.

Sheets("Sheet1").Range("A1:D17").AdvancedFilter Action:=xlFilterCopy, _
    CriteriaRange:=Sheets("Sheet1").Range("G1:G2"), CopyToRange:=Range("A1:D1") _
    , Unique:=False

(Mac) -bash: __git_ps1: command not found

I was doing the course on Udacity for git hub and was having this same issue. Here is my final code that make is work correctly.

# Change command prompt
alias __git_ps1="git branch 2>/dev/null | grep '*' | sed 's/* \ .   (.*\)/(\1)/'"

if [ -f ~/.git-completion.bash ]; then
  source ~/.git-completion.bash
  export PS1='[\W]$(__git_ps1 "(%s)"): '
fi

source ~/.git-prompt.sh
export GIT_PS1_SHOWDIRTYSTATE=1
# '\u' adds the name of the current user to the prompt
# '\$(__git_ps1)' adds git-related stuff
# '\W' adds the name of the current directory
export PS1="$purple\u$green\$(__git_ps1)$blue \W $ $reset"

It works! https://i.stack.imgur.com/d0lvb.jpg

Android: How to turn screen on and off programmatically?

     WakeLock screenLock =    ((PowerManager)getSystemService(POWER_SERVICE)).newWakeLock(
    PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "TAG");
    screenLock.acquire();

  //later
  screenLock.release();

//User Manifest file

One line if/else condition in linux shell scripting

It's not a direct answer to the question but you could just use the OR-operator

( grep "#SystemMaxUse=" journald.conf > /dev/null && sed -i 's/\#SystemMaxUse=/SystemMaxUse=50M/g' journald.conf ) || echo "This file has been edited. You'll need to do it manually."

Are Git forks actually Git clones?

In simplest terms,

When you say you are forking a repository, you are basically creating a copy of the original repository under your GitHub ID in your GitHub account.

and

When you say you are cloning a repository, you are creating a local copy of the original repository in your system (PC/laptop) directly without having a copy in your GitHub account.

Convert .pem to .crt and .key

I was able to convert pem to crt using this:

openssl x509 -outform der -in your-cert.pem -out your-cert.crt

Differences between key, superkey, minimal superkey, candidate key and primary key

Superkey

A superkey is a combination of attributes that can be uniquely used to identify a 
database record. A table might have many superkeys.Candidate keys are a special subset
of superkeys that do not have any extraneous information in them.

Examples: Imagine a table with the fields <Name>, <Age>, <SSN> and <Phone Extension>.
This table has many possible superkeys. Three of these are <SSN>, <Phone Extension, Name>
and <SSN, Name>.Of those listed, only <SSN> is a **candidate key**, as the others
contain information not necessary to uniquely identify records.

How to select count with Laravel's fluent query builder?

$count = DB::table('category_issue')->count();

will give you the number of items.

For more detailed information check Fluent Query Builder section in beautiful Laravel Documentation.

How to concatenate a std::string and an int?

This problem can be done in many ways. I will show it in two ways:

  1. Convert the number to string using to_string(i).

  2. Using string streams.

    Code:

    #include <string>
    #include <sstream>
    #include <bits/stdc++.h>
    #include <iostream>
    using namespace std;
    
    int main() {
        string name = "John";
        int age = 21;
    
        string answer1 = "";
        // Method 1). string s1 = to_string(age).
    
        string s1=to_string(age); // Know the integer get converted into string
        // where as we know that concatenation can easily be done using '+' in C++
    
        answer1 = name + s1;
    
        cout << answer1 << endl;
    
        // Method 2). Using string streams
    
        ostringstream s2;
    
        s2 << age;
    
        string s3 = s2.str(); // The str() function will convert a number into a string
    
        string answer2 = "";  // For concatenation of strings.
    
        answer2 = name + s3;
    
        cout << answer2 << endl;
    
        return 0;
    }
    

React hooks useState Array

To expand on Ryan's answer:

Whenever setStateValues is called, React re-renders your component, which means that the function body of the StateSelector component function gets re-executed.

React docs:

setState() will always lead to a re-render unless shouldComponentUpdate() returns false.

Essentially, you're setting state with:

setStateValues(allowedState);

causing a re-render, which then causes the function to execute, and so on. Hence, the loop issue.

To illustrate the point, if you set a timeout as like:

  setTimeout(
    () => setStateValues(allowedState),
    1000
  )

Which ends the 'too many re-renders' issue.

In your case, you're dealing with a side-effect, which is handled with UseEffectin your component functions. You can read more about it here.

I didn't find "ZipFile" class in the "System.IO.Compression" namespace

Add System.IO.Compression.ZipFile as nuget reference it is working

Jackson with JSON: Unrecognized field, not marked as ignorable

As no one else has mentioned, thought I would...

Problem is your property in your JSON is called "wrapper" and your property in Wrapper.class is called "students".

So either...

  1. Correct the name of the property in either the class or JSON.
  2. Annotate your property variable as per StaxMan's comment.
  3. Annotate the setter (if you have one)

Working Soap client example

Yes, if you can acquire any WSDL file, then you can use SoapUI to create mock service of that service complete with unit test requests. I created an example of this (using Maven) that you can try out.

Is it possible to insert multiple rows at a time in an SQLite database?

If you use the Sqlite manager firefox plugin, it supports bulk inserts from INSERT SQL statements.

Infact it doesn't support this, but Sqlite Browser does (works on Windows, OS X, Linux)

What is float in Java?

Make it

float b= 3.6f;

A floating-point literal is of type float if it is suffixed with an ASCII letter F or f; otherwise its type is double and it can optionally be suffixed with an ASCII letter D or d

Close a MessageBox after several seconds

I know this question is 8 year old, however there was and is a better solution for this purpose. It's always been there, and still is: User32.dll!MessageBoxTimeout.

This is an undocumented function used by Microsoft Windows, and it does exactly what you want and even more. It supports different languages as well.

C# Import:

[DllImport("user32.dll", SetLastError = true)]
public static extern int MessageBoxTimeout(IntPtr hWnd, String lpText, String lpCaption, uint uType, Int16 wLanguageId, Int32 dwMilliseconds);

[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr GetForegroundWindow();

How to use it in C#:

uint uiFlags = /*MB_OK*/ 0x00000000 | /*MB_SETFOREGROUND*/  0x00010000 | /*MB_SYSTEMMODAL*/ 0x00001000 | /*MB_ICONEXCLAMATION*/ 0x00000030;

NativeFunctions.MessageBoxTimeout(NativeFunctions.GetForegroundWindow(), $"Kitty", $"Hello", uiFlags, 0, 5000);

Work smarter, not harder.

php - add + 7 days to date format mm dd, YYYY

onClose: function(selectedDate) {

    $("#dpTodate").datepicker("option", "minDate", selectedDate);
    var maxDate = new Date(selectedDate);

     maxDate.setDate(maxDate.getDate() + 6); //6 days extra in from date

     $("#dpTodate").datepicker("option", "maxDate", maxDate);
}

What are the most common naming conventions in C?

You know, I like to keep it simple, but clear... So here's what I use, in C:

  • Trivial Variables: i,n,c,etc... (Only one letter. If one letter isn't clear, then make it a Local Variable)
  • Local Variables: lowerCamelCase
  • Global Variables: g_lowerCamelCase
  • Const Variables: ALL_CAPS
  • Pointer Variables: add a p_ to the prefix. For global variables it would be gp_var, for local variables p_var, for const variables p_VAR. If far pointers are used then use an fp_ instead of p_.
  • Structs: ModuleCamelCase (Module = full module name, or a 2-3 letter abbreviation, but still in CamelCase.)
  • Struct Member Variables: lowerCamelCase
  • Enums: ModuleCamelCase
  • Enum Values: ALL_CAPS
  • Public Functions: ModuleCamelCase
  • Private Functions: CamelCase
  • Macros: CamelCase

I typedef my structs, but use the same name for both the tag and the typedef. The tag is not meant to be commonly used. Instead it's preferrable to use the typedef. I also forward declare the typedef in the public module header for encapsulation and so that I can use the typedef'd name in the definition.

Full struct Example:

typdef struct TheName TheName;
struct TheName{
    int var;
    TheName *p_link;
};

How to parseInt in Angular.js

Perform the operation inside the scope itself.

<script>
angular.controller('MyCtrl', function($scope, $window) {
$scope.num1= 0;
$scope.num2= 1;


  $scope.total = $scope.num1 + $scope.num2;

 });
</script>
<input type="text" ng-model="num1">
<input type="text" ng-model="num2">

Total: {{total}}

Converting Java file:// URL to File(...) path, platform independent, including UNC paths

For Java 8 the following method works:

  1. Form an URI from file URI string
  2. Create a file from the URI (not directly from URI string, absolute URI string are not paths)

Refer, below code snippet

    String fileURiString="file:///D:/etc/MySQL.txt";
    URI fileURI=new URI(fileURiString);
    File file=new File(fileURI);//File file=new File(fileURiString) - will generate exception

    FileInputStream fis=new FileInputStream(file);
    fis.close();

Pip freeze vs. pip list

When you are using a virtualenv, you can specify a requirements.txt file to install all the dependencies.

A typical usage:

$ pip install -r requirements.txt

The packages need to be in a specific format for pip to understand, which is

feedparser==5.1.3
wsgiref==0.1.2
django==1.4.2
...

That is the "requirements format".

Here, django==1.4.2 implies install django version 1.4.2 (even though the latest is 1.6.x). If you do not specify ==1.4.2, the latest version available would be installed.

You can read more in "Virtualenv and pip Basics", and the official "Requirements File Format" documentation.

Image vs zImage vs uImage

What is the difference between them?

Image: the generic Linux kernel binary image file.

zImage: a compressed version of the Linux kernel image that is self-extracting.

uImage: an image file that has a U-Boot wrapper (installed by the mkimage utility) that includes the OS type and loader information.
A very common practice (e.g. the typical Linux kernel Makefile) is to use a zImage file. Since a zImage file is self-extracting (i.e. needs no external decompressors), the wrapper would indicate that this kernel is "not compressed" even though it actually is.


Note that the author/maintainer of U-Boot considers the (widespread) use of using a zImage inside a uImage questionable:

Actually it's pretty stupid to use a zImage inside an uImage. It is much better to use normal (uncompressed) kernel image, compress it using just gzip, and use this as poayload for mkimage. This way U-Boot does the uncompresiong instead of including yet another uncompressor with each kernel image.

(quoted from https://lists.yoctoproject.org/pipermail/yocto/2013-October/016778.html)


Which type of kernel image do I have to use?

You could choose whatever you want to program for.
For economy of storage, you should probably chose a compressed image over the uncompressed one.
Beware that executing the kernel (presumably the Linux kernel) involves more than just loading the kernel image into memory. Depending on the architecture (e.g. ARM) and the Linux kernel version (e.g. with or without DTB), there are registers and memory buffers that may have to be prepared for the kernel. In one instance there was also hardware initialization that U-Boot performed that had to be replicated.

ADDENDUM

I know that u-boot needs a kernel in uImage format.

That is accurate for all versions of U-Boot which only have the bootm command.
But more recent versions of U-Boot could also have the bootz command that can boot a zImage.

Convert DataTable to IEnumerable<T>

Universal extension method for DataTable. May be somebody be interesting. Idea creating dynamic properties I take from another post: https://stackoverflow.com/a/15819760/8105226

    public static IEnumerable<dynamic> AsEnumerable(this DataTable dt)
    {
        List<dynamic> result = new List<dynamic>();
        Dictionary<string, object> d;
        foreach (DataRow dr in dt.Rows)
        {
            d = new Dictionary<string, object>();

            foreach (DataColumn dc in dt.Columns)
                d.Add(dc.ColumnName, dr[dc]);

            result.Add(GetDynamicObject(d));
        }
        return result.AsEnumerable<dynamic>();
    }

    public static dynamic GetDynamicObject(Dictionary<string, object> properties)
    {
        return new MyDynObject(properties);
    }

    public sealed class MyDynObject : DynamicObject
    {
        private readonly Dictionary<string, object> _properties;

        public MyDynObject(Dictionary<string, object> properties)
        {
            _properties = properties;
        }

        public override IEnumerable<string> GetDynamicMemberNames()
        {
            return _properties.Keys;
        }

        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            if (_properties.ContainsKey(binder.Name))
            {
                result = _properties[binder.Name];
                return true;
            }
            else
            {
                result = null;
                return false;
            }
        }

        public override bool TrySetMember(SetMemberBinder binder, object value)
        {
            if (_properties.ContainsKey(binder.Name))
            {
                _properties[binder.Name] = value;
                return true;
            }
            else
            {
                return false;
            }
        }
    }

How can I stop the browser back button using JavaScript?

<script src="~/main.js" type="text/javascript"></script>

<script type="text/javascript">
    window.history.forward();

    function noBack() {
        window.history.forward();
    }
</script>

file_get_contents() Breaks Up UTF-8 Characters

I am working with 35000 lines of data.

$f=fopen("veri1.txt","r");
$i=0;
while(!feof($f)){
    $i++;
    $line=mb_convert_encoding(fgets($f), 'HTML-ENTITIES', "UTF-8");
    echo $line;
}

This code convert my strange characters into normal.

How to continue the code on the next line in VBA

In VBA (and VB.NET) the line terminator (carriage return) is used to signal the end of a statement. To break long statements into several lines, you need to

Use the line-continuation character, which is an underscore (_), at the point at which you want the line to break. The underscore must be immediately preceded by a space and immediately followed by a line terminator (carriage return).

(From How to: Break and Combine Statements in Code)

In other words: Whenever the interpreter encounters the sequence <space>_<line terminator>, it is ignored and parsing continues on the next line. Note, that even when ignored, the line continuation still acts as a token separator, so it cannot be used in the middle of a variable name, for example. You also cannot continue a comment by using a line-continuation character.

To break the statement in your question into several lines you could do the following:

U_matrix(i, j, n + 1) = _
     k * b_xyt(xi, yi, tn) / (4 * hx * hy) * U_matrix(i + 1, j + 1, n) + _
     (k * (a_xyt(xi, yi, tn) / hx ^ 2 + d_xyt(xi, yi, tn) / (2 * hx)))

(Leading whitespaces are ignored.)

Passing an array as an argument to a function in C

You are not passing the array as copy. It is only a pointer pointing to the address where the first element of the array is in memory.

Run Function After Delay

$(document).ready(function() {

  // place this within dom ready function
  function showpanel() {     
    $(".navigation").hide();
    $(".page").children(".panel").fadeIn(1000);
 }

 // use setTimeout() to execute
 setTimeout(showpanel, 1000)

});

For more see here

Why use def main()?

"What does if __name__==“__main__”: do?" has already been answered.

Having a main() function allows you to call its functionality if you import the module. The main (no pun intended) benefit of this (IMHO) is that you can unit test it.

Populate one dropdown based on selection in another

Setup mine within a closure and with straight JavaScript, explanation provided in comments

_x000D_
_x000D_
(function() {_x000D_
_x000D_
  //setup an object fully of arrays_x000D_
  //alternativly it could be something like_x000D_
  //{"yes":[{value:sweet, text:Sweet}.....]}_x000D_
  //so you could set the label of the option tag something different than the name_x000D_
  var bOptions = {_x000D_
    "yes": ["sweet", "wohoo", "yay"],_x000D_
    "no": ["you suck!", "common son"]_x000D_
  };_x000D_
_x000D_
  var A = document.getElementById('A');_x000D_
  var B = document.getElementById('B');_x000D_
_x000D_
  //on change is a good event for this because you are guarenteed the value is different_x000D_
  A.onchange = function() {_x000D_
    //clear out B_x000D_
    B.length = 0;_x000D_
    //get the selected value from A_x000D_
    var _val = this.options[this.selectedIndex].value;_x000D_
    //loop through bOption at the selected value_x000D_
    for (var i in bOptions[_val]) {_x000D_
      //create option tag_x000D_
      var op = document.createElement('option');_x000D_
      //set its value_x000D_
      op.value = bOptions[_val][i];_x000D_
      //set the display label_x000D_
      op.text = bOptions[_val][i];_x000D_
      //append it to B_x000D_
      B.appendChild(op);_x000D_
    }_x000D_
  };_x000D_
  //fire this to update B on load_x000D_
  A.onchange();_x000D_
_x000D_
})();
_x000D_
<select id='A' name='A'>_x000D_
  <option value='yes' selected='selected'>yes_x000D_
  <option value='no'> no_x000D_
</select>_x000D_
<select id='B' name='B'>_x000D_
</select>
_x000D_
_x000D_
_x000D_

$(window).height() vs $(document).height

AFAIK $(window).height(); returns the height of your window and $(document).height(); returns the height of your document

Facebook api: (#4) Application request limit reached

The Facebook "Graph API Rate Limiting" docs says that an error with code #4 is an app level rate limit, which is different than user level rate limits. Although it doesn't give any exact numbers, it describes their app level rate-limit as:

This rate limiting is applied globally at the app level. Ads api calls are excluded.

  • Rate limiting happens real time on sliding window for past one hour.
  • Stats is collected for number of calls and queries made, cpu time spent, memory used for each app.
  • There is a limit for each resource multiplied by monthly active users of a given app.
  • When the app uses more than its allowed resources the error is thrown.
  • Error, Code: 4, Message: Application request limit reached

The docs also give recommendations for avoiding the rate limits. For app level limits, they are:

Recommendations:

  • Verify the error code (4) to confirm the throttling type.
  • Do not make burst of calls, spread out the calls throughout the day.
  • Do smart fetching of data (important data, non duplicated data, etc).
    • Real-time insights, make sure API calls are structured in a way that you can read insights for as many as Page posts as possible, with minimum number of requests.
    • Don't fetch users feed twice (in the case that two App users have a specific friend in common)
    • Don't fetch all user's friends feed in a row if the number of friends is more than 250. Separate the fetches over different days. As an option, fetch first the app user's news feed (me/home) in order to detect which friends are more important to the App user. Then, fetch those friends feeds first.
  • Consider to limit/filter the requests by using the following parameters: "since", "until", "limit"
  • For page related calls use realtime updates to subscribe to changes in data.
  • Field expansion allows ton "join" multiple graph queries into a single call.
  • Etags to check if the data querying has changed since the last check.
  • For page management developers who does not have massive user base, have the admins of the page to accept the app to increase the number of users.

Finally, the docs give the following informational tips:

  • Batching calls will not reduce the number of api calls.
  • Making parallel calls will not reduce the number of api calls.

Move textfield when keyboard appears swift

If you're like me, using Autolayout and not getting the keyboard when running the App on a simulator. This might be because Apple make you use the keyboard of you're computer as first Keyboard.

To make the keyboard from the device appear :

shift + cmd + K

Sounds stupid but I would have loved to find this answer 3 hours ago :)

Windows Explorer "Command Prompt Here"

I use StExBar, a Windows Explorer extension that gives you a command prompt button in explorer along with some other cool features (copy path, copy file name & more).

https://tools.stefankueng.com/StExBar.html

EDIT: I just found out (been using it for more than a year and did not know this) that Ctrl+M will do it with StExBar. How's that for fast!

How to call multiple JavaScript functions in onclick event?

ES6 React

<MenuItem
  onClick={() => {
    this.props.toggleTheme();
    this.handleMenuClose();
  }}
>