Programs & Examples On #Foswiki

Foswiki is an Enterprise Open Source Data Wiki Engine that allows the _end_ users to not only write prose style wiki content, but create applications using the macro language, define data schemas and queries on that data.

Laravel 4 with Sentry 2 add user to a group on Registration

Somehow, where you are using Sentry, you're not using its Facade, but the class itself. When you call a class through a Facade you're not really using statics, it's just looks like you are.

Do you have this:

use Cartalyst\Sentry\Sentry; 

In your code?

Ok, but if this line is working for you:

$user = $this->sentry->register(array(     'username' => e($data['username']),     'email' => e($data['email']),      'password' => e($data['password'])     )); 

So you already have it instantiated and you can surely do:

$adminGroup = $this->sentry->findGroupById(5); 

How do I enable EF migrations for multiple contexts to separate databases?

I just bumped into the same problem and I used the following solution (all from Package Manager Console)

PM> Enable-Migrations -MigrationsDirectory "Migrations\ContextA" -ContextTypeName MyProject.Models.ContextA
PM> Enable-Migrations -MigrationsDirectory "Migrations\ContextB" -ContextTypeName MyProject.Models.ContextB

This will create 2 separate folders in the Migrations folder. Each will contain the generated Configuration.cs file. Unfortunately you still have to rename those Configuration.cs files otherwise there will be complaints about having two of them. I renamed my files to ConfigA.cs and ConfigB.cs

EDIT: (courtesy Kevin McPheat) Remember when renaming the Configuration.cs files, also rename the class names and constructors /EDIT

With this structure you can simply do

PM> Add-Migration -ConfigurationTypeName ConfigA
PM> Add-Migration -ConfigurationTypeName ConfigB

Which will create the code files for the migration inside the folder next to the config files (this is nice to keep those files together)

PM> Update-Database -ConfigurationTypeName ConfigA
PM> Update-Database -ConfigurationTypeName ConfigB

And last but not least those two commands will apply the correct migrations to their corrseponding databases.

EDIT 08 Feb, 2016: I have done a little testing with EF7 version 7.0.0-rc1-16348

I could not get the -o|--outputDir option to work. It kept on giving Microsoft.Dnx.Runtime.Common.Commandline.CommandParsingException: Unrecognized command or argument

However it looks like the first time an migration is added it is added into the Migrations folder, and a subsequent migration for another context is automatically put into a subdolder of migrations.

The original names ContextA seems to violate some naming conventions so I now use ContextAContext and ContextBContext. Using these names you could use the following commands: (note that my dnx still works from the package manager console and I do not like to open a separate CMD window to do migrations)

PM> dnx ef migrations add Initial -c "ContextAContext"
PM> dnx ef migrations add Initial -c "ContextBContext"

This will create a model snapshot and a initial migration in the Migrations folder for ContextAContext. It will create a folder named ContextB containing these files for ContextBContext

I manually added a ContextA folder and moved the migration files from ContextAContext into that folder. Then I renamed the namespace inside those files (snapshot file, initial migration and note that there is a third file under the initial migration file ... designer.cs). I had to add .ContextA to the namespace, and from there the framework handles it automatically again.

Using the following commands would create a new migration for each context

PM>  dnx ef migrations add Update1 -c "ContextAContext"
PM>  dnx ef migrations add Update1 -c "ContextBContext"

and the generated files are put in the correct folders.

Get selected option text with JavaScript

Try options

_x000D_
_x000D_
function myNewFunction(sel) {_x000D_
  alert(sel.options[sel.selectedIndex].text);_x000D_
}
_x000D_
<select id="box1" onChange="myNewFunction(this);">_x000D_
  <option value="98">dog</option>_x000D_
  <option value="7122">cat</option>_x000D_
  <option value="142">bird</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

How to have click event ONLY fire on parent DIV, not children?

If the e.target is the same element as this, you've not clicked on a descendant.

_x000D_
_x000D_
$('.foobar').on('click', function(e) {_x000D_
  if (e.target !== this)_x000D_
    return;_x000D_
  _x000D_
  alert( 'clicked the foobar' );_x000D_
});
_x000D_
.foobar {_x000D_
  padding: 20px; background: yellow;_x000D_
}_x000D_
span {_x000D_
  background: blue; color: white; padding: 8px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div class='foobar'> .foobar (alert) _x000D_
  <span>child (no alert)</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to initialize a static array?

Nope, no difference. It's just syntactic sugar. Arrays.asList(..) creates an additional list.

How to create a drop-down list?

Spinner xml:

<Spinner
      android:id="@+id/spinner"
      android:layout_width="wrap_content"
      android:layout_height="match_parent" />

java:

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener{

    private Spinner spinner;
    private static final String[] paths = {"item 1", "item 2", "item 3"};

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

        spinner = (Spinner)findViewById(R.id.spinner);
        ArrayAdapter<String>adapter = new ArrayAdapter<String>(MainActivity.this,
                android.R.layout.simple_spinner_item,paths);

        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(this);

    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {

        switch (position) {
            case 0:
                // Whatever you want to happen when the first item gets selected
                break;
            case 1:
                // Whatever you want to happen when the second item gets selected
                break;
            case 2:
                // Whatever you want to happen when the thrid item gets selected
                break;

        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
            // TODO Auto-generated method stub
        }

}

Detect if a page has a vertical scrollbar?

Let's bring this question back from the dead ;) There is a reason Google doesn't give you a simple solution. Special cases and browser quirks affect the calculation, and it is not as trivial as it seems to be.

Unfortunately, there are problems with the solutions outlined here so far. I don't mean to disparage them at all - they are great starting points and touch on all the key properties needed for a more robust approach. But I wouldn't recommend copying and pasting the code from any of the other answers because

  • they don't capture the effect of positioned content in a way that is reliable cross-browser. The answers which are based on body size miss this entirely (the body is not the offset parent of such content unless it is positioned itself). And those answers checking $( document ).width() and .height() fall prey to jQuery's buggy detection of document size.
  • Relying on window.innerWidth, if the browser supports it, makes your code fail to detect scroll bars in mobile browsers, where the width of the scroll bar is generally 0. They are just shown temporarily as an overlay and don't take up space in the document. Zooming on mobile also becomes a problem that way (long story).
  • The detection can be thrown off when people explicitly set the overflow of both the html and body element to non-default values (what happens then is a little involved - see this description).
  • In most answers, body padding, borders or margins are not detected and distort the results.

I have spent more time than I would have imagined on a finding a solution that "just works" (cough). The algorithm I have come up with is now part of a plugin, jQuery.isInView, which exposes a .hasScrollbar method. Have a look at the source if you wish.

In a scenario where you are in full control of the page and don't have to deal with unknown CSS, using a plugin may be overkill - after all, you know which edge cases apply, and which don't. However, if you need reliable results in an unknown environment, then I don't think the solutions outlined here will be enough. You are better off using a well-tested plugin - mine or anybody elses.

How to generate xsd from wsdl

Once I found an xsd link on the top of the wsdl. Like this wsdl example from the web, you can see a link xsd1. The server has to be running to see it.

<?xml version="1.0"?>
<definitions name="StockQuote"
             targetNamespace="http://example.com/stockquote.wsdl"
             xmlns:tns="http://example.com/stockquote.wsdl"
             xmlns:xsd1="http://example.com/stockquote.xsd"
             xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
             xmlns="http://schemas.xmlsoap.org/wsdl/">

Run exe file with parameters in a batch file

This should work:

start "" "c:\program files\php\php.exe" D:\mydocs\mp\index.php param1 param2

The start command interprets the first argument as a window title if it contains spaces. In this case, that means start considers your whole argument a title and sees no command. Passing "" (an empty title) as the first argument to start fixes the problem.

Comparing two strings, ignoring case in C#

I'd venture that the safest is to use String.Equals to mitigate against the possibility that val is null.

Run AVD Emulator without Android Studio

Assuming you've got Android Studio installed, and SDK in your PATH, it's:

emulator -avd avd_name

To get a list of AVD names, run:

emulator -list-avds

Source: https://developer.android.com/studio/run/emulator-commandline.html

PHP XML Extension: Not installed

In Centos

 sudo yum install php-xml

and restart apache

sudo service httpd restart

Trying to get the average of a count resultset

You just can put your query as a subquery:

SELECT avg(count)
  FROM 
    (
    SELECT COUNT (*) AS Count
      FROM Table T
     WHERE T.Update_time =
               (SELECT MAX (B.Update_time )
                  FROM Table B
                 WHERE (B.Id = T.Id))
    GROUP BY T.Grouping
    ) as counts

Edit: I think this should be the same:

SELECT count(*) / count(distinct T.Grouping)
  FROM Table T
 WHERE T.Update_time =
           (SELECT MAX (B.Update_time)
              FROM Table B
             WHERE (B.Id = T.Id))

Bootstrap 3 Horizontal Divider (not in a dropdown)

As I found the default Bootstrap <hr/> size unsightly, here's some simple HTML and CSS to balance out the element visually:

HTML:

<hr class="half-rule"/>

CSS:

.half-rule { 
    margin-left: 0;
    text-align: left;
    width: 50%;
 }

PHP Array to JSON Array using json_encode();

If you don't specify indexes on your initial array, you get the regular numric ones. Arrays must have some form of unique index

Android: ProgressDialog.show() crashes with getApplicationContext

For Activities shown within TabActivities use getParent()

final AlertDialog.Builder builder = new AlertDialog.Builder(getParent());

instead of

final AlertDialog.Builder builder = new AlertDialog.Builder(this);

error: RPC failed; curl transfer closed with outstanding read data remaining

These steps worked for me:using git:// instead of https://

How can I convert a date to GMT?

Although it looks logical, the accepted answer is incorrect because JavaScript dates don't work like that.

It's super important to note here that the numerical value of a date (i.e., new Date()-0 or Date.now()) in JavaScript is always measured as millseconds since the epoch which is a timezone-free quantity based on a precise exact instant in the history of the universe. You do not need to add or subtract anything to the numerical value returned from Date() to convert the numerical value into a timezone, because the numerical value has no timezone. If it did have a timezone, everything else in JavaScript dates wouldn't work.

Timezones, leap years, leap seconds, and all of the other endlessly complicated adjustments to our local times and dates, are based on this consistent and unambiguous numerical value, not the other way around.

Here are examples of how the numerical value of a date (provided to the date constructor) is independent of timezone:

In Central Standard Time:

new Date(0);
// Wed Dec 31 1969 18:00:00 GMT-0600 (CST)

In Anchorage, Alaska:

new Date(0);
// Wed Dec 31 1969 15:00:00 GMT-0900 (AHST)

In Paris, France:

new Date(0);
// Thu Jan 01 1970 01:00:00 GMT+0100 (CET)

It is critical to observe that in ALL cases, based on the timezone-free epoch offset of zero milliseconds, the resulting time is identical. 1 am in Paris, France is the exact same moment as 3 pm the day before in Anchorage, Alaska, which is the exact same moment as 6 pm in Chicago, Illinois.

For this reason, the accepted answer on this page is incorrect. Observe:

// Create a date.
   date = new Date();
// Fri Jan 27 2017 18:16:35 GMT-0600 (CST)


// Observe the numerical value of the date.
   date.valueOf();
// 1485562595732
// n.b. this value has no timezone and does not need one!!


// Observe the incorrectly "corrected" numerical date value.
   date.valueOf() + date.getTimezoneOffset() * 60000;
// 1485584195732


// Try out the incorrectly "converted" date string.
   new Date(date.valueOf() + date.getTimezoneOffset() * 60000);
// Sat Jan 28 2017 00:16:35 GMT-0600 (CST)

/* Not the correct result even within the same script!!!! */

If you have a date string in another timezone, no conversion to the resulting object created by new Date("date string") is needed. Why? JavaScript's numerical value of that date will be the same regardless of its timezone. JavaScript automatically goes through amazingly complicated procedures to extract the original number of milliseconds since the epoch, no matter what the original timezone was.

The bottom line is that plugging a textual date string x into the new Date(x) constructor will automatically convert from the original timezone, whatever that might be, into the timezone-free epoch milliseconds representation of time which is the same regardless of any timezone. In your actual application, you can choose to display the date in any timezone that you want, but do NOT add/subtract to the numerical value of the date in order to do so. All the conversion already happened at the instant the date object was created. The timezone isn't even there anymore, because the date object is instantiated using a precisely-defined and timezone-free sense of time.

The timezone only begins to exist again when the user of your application is considered. The user does have a timezone, so you simply display that timezone to the user. But this also happens automatically.

Let's consider a couple of the dates in your original question:

   date1 = new Date("Fri Jan 20 2012 11:51:36 GMT-0300");
// Fri Jan 20 2012 08:51:36 GMT-0600 (CST)


   date2 = new Date("Fri Jan 20 2012 11:51:36 GMT-0300")
// Fri Jan 20 2012 08:51:36 GMT-0600 (CST)

The console already knows my timezone, and so it has automatically shown me what those times mean to me.

And if you want to know the time in GMT/UTC representation, also no conversion is needed! You don't change the time at all. You simply display the UTC string of the time:

    date1.toUTCString();
// "Fri, 20 Jan 2012 14:51:36 GMT"

Code that is written to convert timezones numerically using the numerical value of a JavaScript date is almost guaranteed to fail. Timezones are way too complicated, and that's why JavaScript was designed so that you didn't need to.

How to delete a certain row from mysql table with same column values?

Best way to design table is add one temporary row as auto increment and keep as primary key. So we can avoid such above issues.

CSS / HTML Navigation and Logo on same line

Try this CSS:

body {
  margin: 0;
  padding: 0;
}

.logo {
  float: left;
}
/* ~~ Top Navigation Bar ~~ */

#navigation-container {
  width: 1200px;
  margin: 0 auto;
  height: 70px;
}

.navigation-bar {
  background-color: #352d2f;
  height: 70px;
  width: 100%;
}

#navigation-container img {
  float: left;
}

#navigation-container ul {
  padding: 0px;
  margin: 0px;
  text-align: center;
  display:inline-block;
}

#navigation-container li {
  list-style-type: none;
  padding: 0px;
  height: 24px;
  margin-top: 4px;
  margin-bottom: 4px;
  display: inline;
}

#navigation-container li a {
  color: white;
  font-size: 16px;
  font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
  text-decoration: none;
  line-height: 70px;
  padding: 5px 15px;
  opacity: 0.7;
}

#menu {
  float: right;
}

MySQL WHERE IN ()

Your query translates to

SELECT * FROM table WHERE id='1' or id='2' or id='3' or id='4';

It will only return the results that match it.


One way of solving it avoiding the complexity would be, chaning the datatype to SET. Then you could use, FIND_IN_SET

SELECT * FROM table WHERE FIND_IN_SET('1', id);

How to make asynchronous HTTP requests in PHP

Symfony HttpClient is asynchronous https://symfony.com/doc/current/components/http_client.html.

For example you can

use Symfony\Component\HttpClient\HttpClient;

$client = HttpClient::create();
$response1 = $client->request('GET', 'https://website1');
$response2 = $client->request('GET', 'https://website1');
$response3 = $client->request('GET', 'https://website1');
//these 3 calls with return immediately
//but the requests will fire to the website1 webserver

$response1->getContent(); //this will block until content is fetched
$response2->getContent(); //same 
$response3->getContent(); //same

How to check the version of GitLab?

cd /opt/gitlab

cat version-manifest.txt

Example:

gitlab-ctl 6.8.2-omnibus
gitlab-rails v6.8.2

Current gitlab version is 6.8.2

Screenshot of the console

mysql_config not found when installing mysqldb python interface

I had the same problem. I solved it by following this tutorial to install Python with python3-dev on Ubuntu 16.04:

sudo apt-get update
sudo apt-get -y upgrade
sudo apt-get install -y python3-pip
sudo apt-get install build-essential libssl-dev libffi-dev python3-dev

And now you can set up your virtual environment:

sudo apt-get install -y python3-venv
pyvenv my_env
source my_env/bin/activate

Resource leak: 'in' is never closed

// An InputStream which is typically connected to keyboard input of console programs

Scanner in= new Scanner(System.in);

above line will invoke Constructor of Scanner class with argument System.in, and will return a reference to newly constructed object.

It is connected to a Input Stream that is connected to Keyboard, so now at run-time you can take user input to do required operation.

//Write piece of code 

To remove the memory leak -

in.close();//write at end of code.

What to use now Google News API is deprecated?

Looks like you might have until the end of 2013 before they officially close it down. http://groups.google.com/group/google-ajax-search-api/browse_thread/thread/6aaa1b3529620610/d70f8eec3684e431?lnk=gst&q=news+api#d70f8eec3684e431

Also, it sounds like they are building a replacement... but it's going to cost you.

I'd say, go to a different service. I think bing has a news API.

You might enjoy (or not) reading: http://news.ycombinator.com/item?id=1864625

What is an alternative to execfile in Python 3?

This one is better, since it takes the globals and locals from the caller:

import sys
def execfile(filename, globals=None, locals=None):
    if globals is None:
        globals = sys._getframe(1).f_globals
    if locals is None:
        locals = sys._getframe(1).f_locals
    with open(filename, "r") as fh:
        exec(fh.read()+"\n", globals, locals)

Conda version pip install -r requirements.txt --target ./lib

You can run conda install --file requirements.txt instead of the loop, but there is no target directory in conda install. conda install installs a list of packages into a specified conda environment.

Spring RequestMapping for controllers that produce and consume JSON

As of Spring 4.2.x, you can create custom mapping annotations, using @RequestMapping as a meta-annotation. So:

Is there a way to produce a "composite/inherited/aggregated" annotation with default values for consumes and produces, such that I could instead write something like:

@JSONRequestMapping(value = "/foo", method = RequestMethod.POST)

Yes, there is such a way. You can create a meta annotation like following:

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@RequestMapping(consumes = "application/json", produces = "application/json")
public @interface JsonRequestMapping {
    @AliasFor(annotation = RequestMapping.class, attribute = "value")
    String[] value() default {};

    @AliasFor(annotation = RequestMapping.class, attribute = "method")
    RequestMethod[] method() default {};

    @AliasFor(annotation = RequestMapping.class, attribute = "params")
    String[] params() default {};

    @AliasFor(annotation = RequestMapping.class, attribute = "headers")
    String[] headers() default {};

    @AliasFor(annotation = RequestMapping.class, attribute = "consumes")
    String[] consumes() default {};

    @AliasFor(annotation = RequestMapping.class, attribute = "produces")
    String[] produces() default {};
}

Then you can use the default settings or even override them as you want:

@JsonRequestMapping(method = POST)
public String defaultSettings() {
    return "Default settings";
}

@JsonRequestMapping(value = "/override", method = PUT, produces = "text/plain")
public String overrideSome(@RequestBody String json) {
    return json;
}

You can read more about AliasFor in spring's javadoc and github wiki.

Wampserver icon not going green fully, mysql services not starting up?

This happened to me today. Since I had not changed my system setting since yesterday, I assumed it's predominantly a mysql issue on the system. I managed to fix it in the following way.

  1. Open wampserver's mysql log file. This will contain information on why the service threw and error and exited prematurely.

  2. In my case, the mysql service failed to start because it could not read a certain tablespace. The specific tablespace was indicated in the log.

  3. Failure to read such a file could be because of file permissions or the file being broken. In such a case, mysql stops executing in order to avoid damaging a tablespace file that may be linked to a database you need. Usually, if you have a backup of the database, then it is safe to simply delete this problematic file and restore the database once your mysql service is started again.

  4. If you do not have a database backup then you could force the mysql instance to run a recovery by enabling the option in your my.cnf / my.ini file.

innodb_force_recovery = 1

This forces the instance to run the crash recovery.

NOTE: installing a new instance of mysql does not necessarily mean that your databases shall be retained. I suggest you run a nightly backup of your databases if you are working on huge projects.

How to get line count of a large file cheaply in Python?

Simple method:

1)

>>> f = len(open("myfile.txt").readlines())
>>> f

430

2)

>>> f = open("myfile.txt").read().count('\n')
>>> f
430
>>>

3)

num_lines = len(list(open('myfile.txt')))

Skip first line(field) in loop using CSV file?

csvreader.next() Return the next row of the reader’s iterable object as a list, parsed according to the current dialect.

How to use ConcurrentLinkedQueue?

The ConcurentLinkedQueue is a very efficient wait/lock free implementation (see the javadoc for reference), so not only you don't need to synchronize, but the queue will not lock anything, thus being virtually as fast as a non synchronized (not thread safe) one.

How to change the color of a CheckBox?

you can create your own xml in drawable and use this as android:background="@drawable/your_xml"

in that you can give border corner everything

<item>
    <shape>
        <gradient

            android:endColor="#fff"
            android:startColor="#fff"/>
        <corners
            android:radius="2dp"/>
        <stroke
            android:width="15dp"
            android:color="#0013669e"/>

    </shape>
</item>

How to replace url parameter with javascript/jquery?

The following solution combines other answers and handles some special cases:

  • The parameter does not exist in the original url
  • The parameter is the only parameter
  • The parameter is first or last
  • The new parameter value is the same as the old
  • The url ends with a ? character
  • \b ensures another parameter ending with paramName won't be matched

Solution:

function replaceUrlParam(url, paramName, paramValue)
{
    if (paramValue == null) {
        paramValue = '';
    }
    var pattern = new RegExp('\\b('+paramName+'=).*?(&|#|$)');
    if (url.search(pattern)>=0) {
        return url.replace(pattern,'$1' + paramValue + '$2');
    }
    url = url.replace(/[?#]$/,'');
    return url + (url.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue;
}

Known limitations:

Selected value for JSP drop down using JSTL

I think above examples are correct. but you dont' really need to set

request.setAttribute("selectedDept", selectedDept);

you can reuse that info from JSTL, just do something like this..

<!DOCTYPE html>
<html lang="en">
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<head>
    <script src="../js/jquery-1.8.1.min.js"></script>
</head>
<body>
    <c:set var="authors" value="aaa,bbb,ccc,ddd,eee,fff,ggg" scope="application" />
    <c:out value="Before : ${param.Author}"/>
    <form action="TestSelect.action">
        <label>Author
            <select id="Author" name="Author">
                <c:forEach items="${fn:split(authors, ',')}" var="author">
                    <option value="${author}" ${author == param.Author ? 'selected' : ''}>${author}</option>
                </c:forEach>
            </select>
        </label>
        <button type="submit" value="submit" name="Submit"></button>
        <Br>
        <c:out value="After :   ${param.Author}"/>
    </form>
</body>
</html>

How can multiple rows be concatenated into one in Oracle without creating a stored procedure?

From Oracle 11gR2, the LISTAGG clause should do the trick:

SELECT question_id,
       LISTAGG(element_id, ',') WITHIN GROUP (ORDER BY element_id)
FROM YOUR_TABLE
GROUP BY question_id;

Beware if the resulting string is too big (more than 4000 chars for a VARCHAR2, for instance): from version 12cR2, we can use ON OVERFLOW TRUNCATE/ERROR to deal with this issue.

How to sort an array of associative arrays by value of a given key in PHP?

try this:

$prices = array_column($inventory, 'price');
array_multisort($prices, SORT_DESC, $inventory);
print_r($inventory);

How can Perl's print add a newline by default?

If you're stuck with pre-5.10, then the solutions provided above will not fully replicate the say function. For example

sub say { print @_, "\n"; }

Will not work with invocations such as

say for @arr;

or

for (@arr) {
    say;
}

... because the above function does not act on the implicit global $_ like print and the real say function.

To more closely replicate the perl 5.10+ say you want this function

sub say {
    if (@_) { print @_, "\n"; }
    else { print $_, "\n"; }
}

Which now acts like this

my @arr = qw( alpha beta gamma );
say @arr;
# OUTPUT
# alphabetagamma
#
say for @arr;
# OUTPUT
# alpha
# beta
# gamma
#

The say builtin in perl6 behaves a little differently. Invoking it with say @arr or @arr.say will not just concatenate the array items, but instead prints them separated with the list separator. To replicate this in perl5 you would do this

sub say {
    if (@_) { print join($", @_) . "\n"; }
    else { print $_ . "\n"; }
}

$" is the global list separator variable, or if you're using English.pm then is is $LIST_SEPARATOR

It will now act more like perl6, like so

say @arr;
# OUTPUT
# alpha beta gamma
#

Are lists thread-safe?

To clarify a point in Thomas' excellent answer, it should be mentioned that append() is thread safe.

This is because there is no concern that data being read will be in the same place once we go to write to it. The append() operation does not read data, it only writes data to the list.

How to reset AUTO_INCREMENT in MySQL?

Best way is remove the field with AI and add it again with AI, works for all tables

jQuery - how to write 'if not equal to' (opposite of ==)

if ("one" !== 1 )

would evaluate as true, the string "one" is not equal to the number 1

How to select a single child element using jQuery?

You can target the first child element with just using CSS selector with jQuery:

$(this).children('img:nth-child(1)');

If you want to target the second child element just change 1 to 2:

$(this).children('img:nth-child(2)');

and so on..

if you want to target more elements, you can use a for loop:

for (i = 1; i <= $(this).children().length; i++) {
    let childImg =  $(this).children("img:nth-child("+ i +")");
    // Do stuff...
}

Sql error on update : The UPDATE statement conflicted with the FOREIGN KEY constraint

This was the solution for me:

-- Check how it is now
select * from patient
select * from patient_address

-- Alter your DB
alter table patient_address nocheck constraint FK__patient_a__id_no__27C3E46E
update patient 
set id_no='7008255601088'
where id_no='8008255601088'

alter table patient_address nocheck constraint FK__patient_a__id_no__27C3E46E
update patient_address 
set id_no='7008255601088'
where id_no='8008255601088'

-- Check how it is now
select * from patient
select * from patient_address

Including non-Python files with setup.py

Figured out a workaround: I renamed my lgpl2.1_license.txt to lgpl2.1_license.txt.py, and put some triple quotes around the text. Now I don't need to use the data_files option nor to specify any absolute paths. Making it a Python module is ugly, I know, but I consider it less ugly than specifying absolute paths.

Get value of Span Text

You need to change your code as below:

<html>
<body>

<span id="span_Id">Click the button to display the content.</span>

<button onclick="displayDate()">Click Me</button>

<script>
function displayDate() {
   var span_Text = document.getElementById("span_Id").innerText;
   alert (span_Text);
}
</script>
</body>
</html>

How do I update/upsert a document in Mongoose?

I needed to update/upsert a document into one collection, what I did was to create a new object literal like this:

notificationObject = {
    user_id: user.user_id,
    feed: {
        feed_id: feed.feed_id,
        channel_id: feed.channel_id,
        feed_title: ''
    }
};

composed from data that I get from somewhere else in my database and then call update on the Model

Notification.update(notificationObject, notificationObject, {upsert: true}, function(err, num, n){
    if(err){
        throw err;
    }
    console.log(num, n);
});

this is the ouput that I get after running the script for the first time:

1 { updatedExisting: false,
    upserted: 5289267a861b659b6a00c638,
    n: 1,
    connectionId: 11,
    err: null,
    ok: 1 }

And this is the output when I run the script for the second time:

1 { updatedExisting: true, n: 1, connectionId: 18, err: null, ok: 1 }

I'm using mongoose version 3.6.16

How to create a DataTable in C# and how to add rows?

You have to add datarows to your datatable for this.

// Creates a new DataRow with the same schema as the table.
DataRow dr = dt.NewRow();

// Fill the values
dr["Name"] = "Name";
dr["Marks"] = "Marks";

// Add the row to the rows collection
dt.Rows.Add ( dr );

Perl regular expression (using a variable as a search string with Perl operator characters included)

Use \Q to autoescape any potentially problematic characters in your variable.

if($text_to_search =~ m/\Q$search_string/) print "wee";

Cookie blocked/not saved in IFRAME in Internet Explorer

I know it's a bit late to put my contribution on this subject but I lost so many hours that maybe this answer will help somebody.

I was trying to call a third party cookie on my site and of course it was not working on Internet Explorer 10, even at a low security level... don't ask me why. In the iframe I was calling a read_cookie.php (echo $_COOKIE) with ajax.

And I don't know why I was incapable of setting the P3P policy to solve the problem...

During my search I saw something about getting the cookie in JSON working. I don't even try because I thought that if the cookie won't pass through an iframe, it will not pass any more through an array...

Guess what, it does! So if you json_encode your cookie then decode after your ajax request, you'll get it!

Maybe there is something I missed and if I did, all my apologies, but i never saw something so stupid. Block third party cookies for security, why not, but let it pass if encoded? Where is the security now?

I hope this post will help somebody and again, if I missed something and I'm dumb, please educate me!

How can I remove all objects but one from the workspace in R?

let's think in different way, what if we wanna remove a group? try this,

 rm(list=ls()[grep("xxx",ls())]) 

I personally don't like too many tables, variables on my screen, yet I can't avoid using them. So I name the temporary things starting with "xxx", so I can remove them after it is no longer used.

Android: adbd cannot run as root in production builds

For those who rooted the Android device with Magisk, you can install adb_root from https://github.com/evdenis/adb_root. Then adb root can run smoothly.

What is `related_name` used for in Django?

To add to existing answer - related name is a must in case there 2 FKs in the model that point to the same table. For example in case of Bill of material

@with_author 
class BOM(models.Model): 
    name = models.CharField(max_length=200,null=True, blank=True)
    description = models.TextField(null=True, blank=True)
    tomaterial =  models.ForeignKey(Material, related_name = 'tomaterial')
    frommaterial =  models.ForeignKey(Material, related_name = 'frommaterial')
    creation_time = models.DateTimeField(auto_now_add=True, blank=True)
    quantity = models.DecimalField(max_digits=19, decimal_places=10)

So when you will have to access this data you only can use related name

 bom = material.tomaterial.all().order_by('-creation_time')

It is not working otherwise (at least I was not able to skip the usage of related name in case of 2 FK's to the same table.)

How do I format date value as yyyy-mm-dd using SSIS expression builder?

Looks like you created a separate question. I was answering your other question How to change flat file source using foreach loop container in an SSIS package? with the same answer. Anyway, here it is again.

Create two string data type variables namely DirPath and FilePath. Set the value C:\backup\ to the variable DirPath. Do not set any value to the variable FilePath.

Variables

Select the variable FilePath and select F4 to view the properties. Set the EvaluateAsExpression property to True and set the Expression property as @[User::DirPath] + "Source" + (DT_STR, 4, 1252) DATEPART("yy" , GETDATE()) + "-" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("mm" , GETDATE()), 2) + "-" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("dd" , GETDATE()), 2)

Expression

Datagridview full row selection but get single cell value

Simplest code is DataGridView1.SelectedCells(column_index).Value

As an example, for the first selected cell:

DataGridView1.SelectedCells(0).Value

SVN change username

Based on Ingo Kegel's solution I created a "small" bash script to change the username in all subfolders. Remember to:

  1. Change <NEW_USERNAME> to the new username.
  2. Change <OLD_USERNAME> to the current username (if you currently have no username set, simply remove <OLD_USERNAME>@).

In the code below the svn command is only printed out (not executed). To have the svn command executed, simply remove the echo and whitespace in front of it (just above popd).

for d in */ ; \
do echo $d ; pushd $d ; \
url=$(svn info | grep "URL: svn") ; \
url=$(echo ${url#"URL: "}) ; \
newurl=$(echo $url | sed "s/svn+ssh:\/\/<OLD_USERNAME>@/svn+ssh:\/\/<NEW_USERNAME>@/") ; \
echo "Old url: "$url ; echo "New url: "$newurl ; \
echo svn relocate $url $newurl ; \
popd ; \
done

Hope you find it useful!

invalid_grant trying to get oAuth token from google

There is a undocumented timeout between when you first redirect the user to the google authentication page (and get back a code), and when you take the returned code and post it to the token url. It works fine for me with the actual google supplied client_id as opposed to an "undocumented email address". I just needed to start the process again.

MySQL SELECT WHERE datetime matches day (and not necessarily time)

SELECT * FROM table where Date(col) = 'date'

What is the difference between git clone and checkout?

Simply git checkout have 2 uses

  1. Switching between existing local branches like git checkout <existing_local_branch_name>
  2. Create a new branch from current branch using flag -b. Suppose if you are at master branch then git checkout -b <new_feature_branch_name> will create a new branch with the contents of master and switch to newly created branch

You can find more options at the official site

How to list records with date from the last 10 days?

Yes this does work in PostgreSQL (assuming the column "date" is of datatype date) Why don't you just try it?

The standard ANSI SQL format would be:

SELECT Table.date 
FROM Table 
WHERE date > current_date - interval '10' day;

I prefer that format as it makes things easier to read (but it is the same as current_date - 10).

Does Hive have a String split function?

Another interesting usecase for split in Hive is when, for example, a column ipname in the table has a value "abc11.def.ghft.com" and you want to pull "abc11" out:

SELECT split(ipname,'[\.]')[0] FROM tablename;

Quickest way to convert XML to JSON in Java

To convert XML File in to JSON include the following dependency

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20140107</version>
</dependency>

and you can Download Jar from Maven Repository here. Then implement as:

String soapmessageString = "<xml>yourStringURLorFILE</xml>";
JSONObject soapDatainJsonObject = XML.toJSONObject(soapmessageString);
System.out.println(soapDatainJsonObject);

Error handling in getJSON calls

I was faced with this same issue, but rather than creating callbacks for a failed request, I simply returned an error with the json data object.

If possible, this seems like the easiest solution. Here's a sample of the Python code I used. (Using Flask, Flask's jsonify f and SQLAlchemy)

try:
    snip = Snip.query.filter_by(user_id=current_user.get_id(), id=snip_id).first()
    db.session.delete(snip)
    db.session.commit()
    return jsonify(success=True)
except Exception, e:
    logging.debug(e)
    return jsonify(error="Sorry, we couldn't delete that clip.")

Then you can check on Javascript like this;

$.getJSON('/ajax/deleteSnip/' + data_id,
    function(data){
    console.log(data);
    if (data.success === true) {
       console.log("successfully deleted snip");
       $('.snippet[data-id="' + data_id + '"]').slideUp();
    }
    else {
       //only shows if the data object was returned
    }
});

Are there any disadvantages to always using nvarchar(MAX)?

Think of it as just another safety level. You can design your table without foreign key relationships - perfectly valid - and ensure existence of associated entities entirely on the business layer. However, foreign keys are considered good design practice because they add another constraint level in case something messes up on the business layer. Same goes for field size limitation and not using varchar MAX.

Return only string message from Spring MVC 3 Controller

Annotate your method in controller with @ResponseBody:

@RequestMapping(value="/controller", method=GET)
@ResponseBody
public String foo() {
    return "Response!";
}

From: 15.3.2.6 Mapping the response body with the @ResponseBody annotation:

The @ResponseBody annotation [...] can be put on a method and indicates that the return type should be written straight to the HTTP response body (and not placed in a Model, or interpreted as a view name).

How can I disable a specific LI element inside a UL?

Using CSS3: http://www.w3schools.com/cssref/sel_nth-child.asp

If that's not an option for any reason, you could try giving the list items classes:

<ul>
<li class="one"></li>
<li class="two"></li>
<li class="three"></li>
...
</ul>

Then in your css:

li.one{display:none}/*hide first li*/
li.three{display:none}/*hide third li*/

How to load specific image from assets with Swift

You cannot load images directly with @2x or @3x, system selects appropriate image automatically, just specify the name using UIImage:

UIImage(named: "green-square-Retina")

jquery input select all on focus

This version works on ios and also fixes standard drag-to-select on windows chrome

var srcEvent = null;

$("input[type=text],input[type=number]")

    .mousedown(function (event) {
        srcEvent = event;
    })

    .mouseup(function (event) {
        var delta = Math.abs(event.clientX - srcEvent.clientX) 
                  + Math.abs(event.clientY - srcEvent.clientY);

        var threshold = 2;
        if (delta <= threshold) {
                   try {
                        // ios likes this but windows-chrome does not on number fields
                        $(this)[0].selectionStart = 0;
                        $(this)[0].selectionEnd = 1000;
                    } catch (e) {
                        // windows-chrome likes this
                        $(this).select();
                    }
        }
    });

http://jsfiddle.net/Zx2sc/2/

JavaScript REST client Library

jQuery has JSON-REST plugin with REST style of URI parameter templates. According to its description example of using is the followin: $.Read("/{b}/{a}", { a:'foo', b:'bar', c:3 }) becomes a GET to "/bar/foo?c=3".

What is the OR operator in an IF statement

The OR operator is a double pipe:

||

So it looks like:

if (this || that) 
{
  //do the other thing
}

EDIT: The reason that your updated attempt isn't working is because the logical operators must separate valid C# expressions. Expressions have operands and operators and operators have an order of precedence.

In your case, the == operator is evaluated first. This means your expression is being evaluated as (title == "User greeting") || "User name". The || gets evaluated next. Since || requires each operand to be a boolean expression, it fails, because your operands are strings.

Using two separate boolean expressions will ensure that your || operator will work properly.

title == "User greeting" || title == "User name"

How to create cross-domain request?

In my experience the plugins worked with http but not with the latest httpClient. Also, configuring the CORS respsonse headers on the server wasn't really an option. So, I created a proxy.conf.json file to act as a proxy server.

Read more about this here: https://github.com/angular/angular-cli/blob/master/docs/documentation/stories/proxy.md

below is my prox.conf.json file

{
  "/posts": {
    "target": "https://example.com",
    "secure": true,
    "pathRewrite": {
    "^/posts": ""
  },
    "changeOrigin": true
  }
}

I placed the proxy.conf.json file right next the the package.json file in the same directory

then I modified the start command in the package.json file like below

"start": "ng serve --proxy-config proxy.conf.json"

now, the http call from my app component is as follows

return this._http.get('/posts/pictures?method=GetPictures')
.subscribe((returnedStuff) => {
  console.log(returnedStuff);
});

Lastly to run my app, I'd have to use npm start or ng serve --proxy-config proxy.conf.json

Bootstrap table without stripe / borders

Using Bootstrap 3.2.0 I had problem with Brett Henderson solution (borders were always there), so I improved it:

HTML

<table class="table table-borderless">

CSS

.table-borderless > tbody > tr > td,
.table-borderless > tbody > tr > th,
.table-borderless > tfoot > tr > td,
.table-borderless > tfoot > tr > th,
.table-borderless > thead > tr > td,
.table-borderless > thead > tr > th {
    border: none;
}

javascript close current window

Should be

<input type="button" class="btn btn-success"
                       style="font-weight: bold;display: inline;"
                       value="Close"
                       onclick="closeMe()">
<script>
function closeMe()
{
    window.opener = self;
    window.close();
}
</script>

MongoDB: How to find out if an array field contains an element?

It seems like the $in operator would serve your purposes just fine.

You could do something like this (pseudo-query):

if (db.courses.find({"students" : {"$in" : [studentId]}, "course" : courseId }).count() > 0) {
  // student is enrolled in class
}

Alternatively, you could remove the "course" : courseId clause and get back a set of all classes the student is enrolled in.

How to select records without duplicate on just one field in SQL?

In MySQL a special column function GROUP_CONCAT can be used:

SELECT GROUP_CONCAT(COLUMN_NAME)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'computers' AND
    TABLE_NAME='Laptop' AND
    COLUMN_NAME NOT IN ('code')
ORDER BY ORDINAL_POSITION;

It should be mentioned that the information schema in MySQL covers all database server, not certain databases. That is why if different databases contains tables with identical names, search condition of the WHERE clause should specify the schema name: TABLE_SCHEMA='computers'.

Strings are concatenated with the CONCAT function in MySQL. The final solution of our problem can be expressed in MySQL as:

SELECT CONCAT('SELECT ',
(SELECT GROUP_CONCAT(COLUMN_NAME)
 FROM INFORMATION_SCHEMA.COLUMNS
 WHERE TABLE_SCHEMA='computers' AND
    TABLE_NAME='Laptop' AND
        COLUMN_NAME NOT IN ('code')
 ORDER BY ORDINAL_POSITION
), ' FROM Laptop');

http://www.sql-ex.ru/help/select20.php

What is code coverage and how do YOU measure it?

Just remember, having "100% code-coverage" doesn't mean everything is tested completely - while it means every line of code is tested, it doesn't mean they are tested under every (common) situation..

I would use code-coverage to highlight bits of code that I should probably write tests for. For example, if whatever code-coverage tool shows myImportantFunction() isn't executed while running my current unit-tests, they should probably be improved.

Basically, 100% code-coverage doesn't mean your code is perfect. Use it as a guide to write more comprehensive (unit-)tests.

JavaScript: Is there a way to get Chrome to break on all errors?

Just about any error will throw an exceptions. The only errors I can think of that wouldn't work with the "pause on exceptions" option are syntax errors, which happen before any of the code gets executed, so there's no place to pause anyway and none of the code will run.

Apparently, Chrome won't pause on the exception if it's inside a try-catch block though. It only pauses on uncaught exceptions. I don't know of any way to change it.

If you just need to know what line the exception happened on (then you could set a breakpoint if the exception is reproducible), the Error object given to the catch block has a stack property that shows where the exception happened.

What was the strangest coding standard rule that you were forced to follow?

Although this wasn't at a job, we had a massive project for a class in college. One of the requirements was commenting every line of code in our application -- regardless of what it did... and each line had to be specific e.g.

int x=0; //declare variable x and assign it to 0

We weren't allowed to do this:

int x, y, z = 0; //declare and assign to 0

As it wasn't detailed enough. And that's not even following the naming conventions forced upon us.

Needless to say we spent a few hours going back through the code...

use std::fill to populate vector with increasing numbers

You should use std::iota algorithm (defined in <numeric>):

  std::vector<int> ivec(100);
  std::iota(ivec.begin(), ivec.end(), 0); // ivec will become: [0..99]

Because std::fill just assigns the given fixed value to the elements in the given range [n1,n2). And std::iota fills the given range [n1, n2) with sequentially increasing values, starting with the initial value and then using ++value.You can also use std::generate as an alternative.

Don't forget that std::iota is C++11 STL algorithm. But a lot of modern compilers support it e.g. GCC, Clang and VS2012 : http://msdn.microsoft.com/en-us/library/vstudio/jj651033.aspx

P.S. This function is named after the integer function ? from the programming language APL, and signifies a Greek letter iota. I speculate that originally in APL this odd name was chosen because it resembles an “integer” (even though in mathematics iota is widely used to denote the imaginary part of a complex number).

onchange file input change img src and change image color

Try with this code, you will get the image preview while uploading

<input type='file' id="upload" onChange="readURL(this);"/>
<img id="img" src="#" alt="your image" />

 function readURL(input){
 var ext = input.files[0]['name'].substring(input.files[0]['name'].lastIndexOf('.') + 1).toLowerCase();
if (input.files && input.files[0] && (ext == "gif" || ext == "png" || ext == "jpeg" || ext == "jpg")) 
    var reader = new FileReader();
    reader.onload = function (e) {
        $('#img').attr('src', e.target.result);
    }

    reader.readAsDataURL(input.files[0]);
}else{
     $('#img').attr('src', '/assets/no_preview.png');
}
}

Error: Could not create the Java Virtual Machine Mac OSX Mavericks

There can be one more reason for such behavior - you delete current working directory.

For example:

# in terminal #1
cd /home/user/myJavaApp

# in terminal #2
rm -rf /home/user/myJavaApp

# in terminal #1
java -jar myJar.jar

Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.

jQuery equivalent to Prototype array.last()

with slice():

var a = [1,2,3,4];
var lastEl = a.slice(-1)[0]; // 4
// a is still [1,2,3,4]

with pop();

var a = [1,2,3,4];
var lastEl = a.pop(); // 4
// a is now [1,2,3]

see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array for more information

Differences between TCP sockets and web sockets, one more time

WebSocket is basically an application protocol (with reference to the ISO/OSI network stack), message-oriented, which makes use of TCP as transport layer.

The idea behind the WebSocket protocol consists of reusing the established TCP connection between a Client and Server. After the HTTP handshake the Client and Server start speaking WebSocket protocol by exchanging WebSocket envelopes. HTTP handshaking is used to overcome any barrier (e.g. firewalls) between a Client and a Server offering some services (usually port 80 is accessible from anywhere, by anyone). Client and Server can switch over speaking HTTP in any moment, making use of the same TCP connection (which is never released).

Behind the scenes WebSocket rebuilds the TCP frames in consistent envelopes/messages. The full-duplex channel is used by the Server to push updates towards the Client in an asynchronous way: the channel is open and the Client can call any futures/callbacks/promises to manage any asynchronous WebSocket received message.

To put it simply, WebSocket is a high level protocol (like HTTP itself) built on TCP (reliable transport layer, on per frame basis) that makes possible to build effective real-time application with JS Clients (previously Comet and long-polling techniques were used to pull updates from the Server before WebSockets were implemented. See Stackoverflow post: Differences between websockets and long polling for turn based game server ).

What is the correct way to represent null XML elements?

The documentation in the w3 link

http://www.w3.org/TR/REC-xml/#sec-starttags

says that this are the recomended forms.

<test></test>
<test/>

The attribute mentioned in the other answer is validation mechanism and not a representation of state. Please refer to the http://www.w3.org/TR/xmlschema-1/#xsi_nil

XML Schema: Structures introduces a mechanism for signaling that an element should be accepted as ·valid· when it has no content despite a content type which does not require or even necessarily allow empty content. An element may be ·valid· without content if it has the attribute xsi:nil with the value true. An element so labeled must be empty, but can carry attributes if permitted by the corresponding complex type.

To clarify this answer: Content

  <Book>
    <!--Invalid construct since the element attribute xsi:nil="true" signal that the element must be empty-->
    <BuildAttributes HardCover="true" Glued="true" xsi:nil="true">
      <anotherAttribute name="Color">Blue</anotherAttribute>
    </BuildAttributes>
    <Index></Index>
    <pages>
      <page pageNumber="1">Content</page>            
    </pages>
    <!--Missing ISBN number could be confusing and misguiding since its not present-->
  </Book>
</Books>

How to convert rdd object to dataframe in spark

Note: This answer was originally posted here

I am posting this answer because I would like to share additional details about the available options that I did not find in the other answers


To create a DataFrame from an RDD of Rows, there are two main options:

1) As already pointed out, you could use toDF() which can be imported by import sqlContext.implicits._. However, this approach only works for the following types of RDDs:

  • RDD[Int]
  • RDD[Long]
  • RDD[String]
  • RDD[T <: scala.Product]

(source: Scaladoc of the SQLContext.implicits object)

The last signature actually means that it can work for an RDD of tuples or an RDD of case classes (because tuples and case classes are subclasses of scala.Product).

So, to use this approach for an RDD[Row], you have to map it to an RDD[T <: scala.Product]. This can be done by mapping each row to a custom case class or to a tuple, as in the following code snippets:

val df = rdd.map({ 
  case Row(val1: String, ..., valN: Long) => (val1, ..., valN)
}).toDF("col1_name", ..., "colN_name")

or

case class MyClass(val1: String, ..., valN: Long = 0L)
val df = rdd.map({ 
  case Row(val1: String, ..., valN: Long) => MyClass(val1, ..., valN)
}).toDF("col1_name", ..., "colN_name")

The main drawback of this approach (in my opinion) is that you have to explicitly set the schema of the resulting DataFrame in the map function, column by column. Maybe this can be done programatically if you don't know the schema in advance, but things can get a little messy there. So, alternatively, there is another option:


2) You can use createDataFrame(rowRDD: RDD[Row], schema: StructType) as in the accepted answer, which is available in the SQLContext object. Example for converting an RDD of an old DataFrame:

val rdd = oldDF.rdd
val newDF = oldDF.sqlContext.createDataFrame(rdd, oldDF.schema)

Note that there is no need to explicitly set any schema column. We reuse the old DF's schema, which is of StructType class and can be easily extended. However, this approach sometimes is not possible, and in some cases can be less efficient than the first one.

Facebook API error 191

UPDATE:
To answer the API Error Code: 191
The redirect_uri should be equal (or relative) to the Site URL.
enter image description here

Tip: Use base URLs instead of full URLs pointing to specific pages.

NOT RECOMMENDED: For example, if you use www.mydomain.com/fb/test.html as your Site URL and having www.mydomain.com/fb/secondPage.html as redirect_uri this will give you the 191 error.

RECOMMENDED: So instead have your Site URL set to a base URL like: www.mydomain.com/ OR www.mydomain.com/fb/.


I went through the Facebook Python sample application today, and I was shocked it was stating clearly that you can use http://localhost:8080/ as Site URL if you are developing locally:

Configure the Site URL, and point it to your Web Server. If you're developing locally, you can use http://localhost:8080/

While I was sure you can't do that, based on my own experience (very old test though) it seems that you actually CAN test your Facebook application locally!

So I picked up an old application of mine and edited its name, Site URL and Canvas URL: Site URL: http://localhost:80/fblocal/

I downloaded the latest Facebook PHP-SDK and threw it in my xampp/htdocs/fblocal/ folder.

But I got the same error as yours! I noticed that XAMPP is doing an automatic redirection to http://localhost/fblocal/ so I changed the setting to simply http://localhost/fblocal/ and the error was gone BUT I had to remove the application (from privacy settings) and re-install my application and here are the results:
alt text

After that, asked for the publish_stream permission, and I was able to publish to my profile (using the PHP-SDK):

$user = $facebook->getUser();
if ($user) {
    try {
        $post = $facebook->api('/me/feed', 'post', array('message'=>'Hello World, from localhost!'));
    } catch (FacebookApiException $e) {
        error_log($e);
        $user = null;
    }
}

Results: alt text

How to define several include path in Makefile

You need to use -I with each directory. But you can still delimit the directories with whitespace if you use (GNU) make's foreach:

INC=$(DIR1) $(DIR2) ...
INC_PARAMS=$(foreach d, $(INC), -I$d)

How can I perform static code analysis in PHP?

See Semantic Designs' CloneDR, a "clone detection" tool that finds copy/paste/edited code.

It will find exact and near miss code fragments, in spite of white space, comments and even variable renamings. A sample detection report for PHP can be found at the website. (I'm the author.)

Can't compare naive and aware datetime.now() <= challenge.datetime_end

It is working form me. Here I am geeting the table created datetime and adding 10 minutes on the datetime. later depending on the current time, Expiry Operations are done.

from datetime import datetime, time, timedelta
import pytz

Added 10 minutes on database datetime

table_datetime = '2019-06-13 07:49:02.832969' (example)

# Added 10 minutes on database datetime
# table_datetime = '2019-06-13 07:49:02.832969' (example)

table_expire_datetime = table_datetime + timedelta(minutes=10 )

# Current datetime
current_datetime = datetime.now()


# replace the timezone in both time
expired_on = table_expire_datetime.replace(tzinfo=utc)
checked_on = current_datetime.replace(tzinfo=utc)


if expired_on < checked_on:
    print("Time Crossed)
else:
    print("Time not crossed ")

It worked for me.

Are querystring parameters secure in HTTPS (HTTP + SSL)?

I disagree with the advice given here - even the reference for the accepted answer concludes:

You can of course use query string parameters with HTTPS, but don’t use them for anything that could present a security problem. For example, you could safely use them to identity part numbers or types of display like ‘accountview’ or ‘printpage’, but don’t use them for passwords, credit card numbers or other pieces of information that should not be publicly available.

So, no they aren't really safe...!

CSS Div stretch 100% page height

Use position absolute. Note that this isn't how we are generally used to using position absolute which requires manually laying things out or having floating dialogs. This will automatically stretch when you resize the window or the content. I believe that this requires standards mode but will work in IE6 and above.

Just replace the div with id 'thecontent' with your content (the specified height there is just for illustration, you don't have to specify a height on the actual content.

<div style="position: relative; width: 100%;">
      <div style="position: absolute; left: 0px; right: 33%; bottom: 0px; top: 0px; background-color: blue; width: 33%;" id="navbar">nav bar</div>
      <div style="position: relative; left: 33%; width: 66%; background-color: yellow;" id="content">
         <div style="height: 10000px;" id="thecontent"></div>
      </div>
</div>

The way that this works is that the outer div acts as a reference point for the nav bar. The outer div is stretched out by the content of the 'content' div. The nav bar uses absolute positioning to stretch itself out to the height of its parent. For the horizontal alignment we make the content div offset itself by the same width of the navbar.

This is made much easier with CSS3 flex box model, but that's not available in IE yet and has some of it's own quirks.

Double precision floating values in Python?

Python's built-in float type has double precision (it's a C double in CPython, a Java double in Jython). If you need more precision, get NumPy and use its numpy.float128.

how to get the ipaddress of a virtual box running on local machine

Login to virtual machine use below command to check ip address. (anyone will work)

  1. ifconfig
  2. ip addr show

If you used NAT for your virtual machine settings(your machine ip will be 10.0.2.15), then you have to use port forwarding to connect to machine. IP address will be 127.0.0.1

If you used bridged networking/Host only networking, then you will have separate Ip address. Use that IP address to connect virtual machine

Fastest way to count number of occurrences in a Python list

Combination of lambda and map function can also do the job:

list_ = ['a', 'b', 'b', 'c']
sum(map(lambda x: x=="b", list_))
:2

How can I convert a comma-separated string to an array?

The split() method is used to split a string into an array of substrings, and returns the new array.

var array = string.split(',');

Errors in pom.xml with dependencies (Missing artifact...)

This is a very late answer,but this might help.I went to this link and searched for ojdbc8(I was trying to add jdbc oracle driver) When clicked on the result , a note was displayed like this:

enter image description here

I clicked the link in the note and the correct dependency was mentioned like below enter image description here

CSS: stretching background image to 100% width and height of screen?

You need to set the height of html to 100%

body {
    background-image:url("../images/myImage.jpg");
    background-repeat: no-repeat;
    background-size: 100% 100%;
}
html {
    height: 100%
}

http://jsfiddle.net/8XUjP/

jQuery UI Dialog with ASP.NET button postback

The exact solution is;

$("#dialogDiv").dialog({ other options...,
    open: function (type, data) {
        $(this).parent().appendTo("form");
    }
});

Laravel 5.2 redirect back with success message

You should remove web middleware from routes.php. Adding web middleware manually causes session and request related problems in Laravel 5.2.27 and higher.

If it didn't help (still, keep routes.php without web middleware), you can try little bit different approach:

return redirect()->back()->with('message', 'IT WORKS!');

Displaying message if it exists:

@if(session()->has('message'))
    <div class="alert alert-success">
        {{ session()->get('message') }}
    </div>
@endif

Convert laravel object to array

UPDATE since version 5.4 of Laravel it is no longer possible.

You can change your db config, like @Varun suggested, or if you want to do it just in this very case, then:

DB::setFetchMode(PDO::FETCH_ASSOC);

// then
DB::table(..)->get(); // array of arrays instead of objects

// of course to revert the fetch mode you need to set it again
DB::setFetchMode(PDO::FETCH_CLASS);

For New Laravel above 5.4 (Ver > 5.4) see https://laravel.com/docs/5.4/upgrade fetch mode section

Event::listen(StatementPrepared::class, function ($event) {
    $event->statement->setFetchMode(...);
});

How to format a floating number to fixed width in Python

I needed something similar for arrays. That helped me

some_array_rounded=np.around(some_array, 5)

Git diff -w ignore whitespace only at start & end of lines

For end of line use:

git diff --ignore-space-at-eol

Instead of what are you using currently:

git diff -w (--ignore-all-space)

For start of line... you are out of luck if you want a built in solution.

However, if you don't mind getting your hands dirty there's a rather old patch floating out there somewhere that adds support for "--ignore-space-at-sol".

R color scatter plot points based on values

Best thing to do here is to add a column to the data object to represent the point colour. Then update sections of it by filtering.

data<- read.table('sample_data.txtt', header=TRUE, row.name=1)
# Create new column filled with default colour
data$Colour="black"
# Set new column values to appropriate colours
data$Colour[data$col_name2>=3]="red"
data$Colour[data$col_name2<=1]="blue"
# Plot all points at once, using newly generated colours
plot(data$col_name1,data$col_name2, ylim=c(0,5), col=data$Colour, ylim=c(0,10))

It should be clear how to adapt this for plots with more colours & conditions.

Make XAMPP / Apache serve file outside of htdocs folder

Solution to allow Apache 2 to host websites outside of htdocs:

Underneath the "DocumentRoot" directive in httpd.conf, you should see a directory block. Replace this directory block with:

<Directory />
    Options FollowSymLinks
    AllowOverride All
    Allow from all
</Directory> 

REMEMBER NOT TO USE THIS CONFIGURATION IN A REAL ENVIRONMENT

How can I apply a border only inside a table?

this should work:

table {
 border:0;
}

table td, table th {
    border: 1px solid black;
    border-collapse: collapse;
}

edit:

i just tried it, no table border. but if i set a table border it is eliminated by the border-collapse.

this is the testfile:

<html>
<head>
<style type="text/css">
table {
    border-collapse: collapse;
    border-spacing: 0;
}


table {
    border: 0;
}
table td, table th {
    border: 1px solid black;
}


</style>
</head>
<body>
<table>
    <tr>
        <th>Heading 1</th>
        <th>Heading 2</th>
    </tr>
    <tr>
        <td>Cell (1,1)</td>
        <td>Cell (1,2)</td>
    </tr>
    <tr>
        <td>Cell (2,1)</td>
        <td>Cell (2,2)</td>
    </tr>
    <tr>
        <td>Cell (3,1)</td>
        <td>Cell (3,2)</td>
    </tr>
</table>

</body>
</html>

How to convert JSON object to JavaScript array?

This will solve the problem:

const json_data = {"2013-01-21":1,"2013-01-22":7};

const arr = Object.keys(json_data).map((key) => [key, json_data[key]]);

console.log(arr);

Or using Object.entries() method:

console.log(Object.entries(json_data));

In both the cases, output will be:

/* output: 
[['2013-01-21', 1], ['2013-01-22', 7]]
*/

How to clear gradle cache?

Gradle cache is located at

  • On Windows: %USERPROFILE%\.gradle\caches
  • On Mac / UNIX: ~/.gradle/caches/

You can browse to these directory and manually delete it or run

rm -rf $HOME/.gradle/caches/

on UNIX system. Run this command will also force to download dependencies.


UPDATE

Clear the Android build cache of current project

NOTE: Android Studio's File > Invalidate Caches / Restart doesn't clear the Android build cache, so you'll have to clean it separately.

On Windows:

gradlew cleanBuildCache

On Mac or UNIX:

./gradlew cleanBuildCache

Create directories using make file

Or, KISS.

DIRS=build build/bins

... 

$(shell mkdir -p $(DIRS))

This will create all the directories after the Makefile is parsed.

What is a "web service" in plain English?

An operating system provides a GUI (and CLI) that you can interact with. It also provides an API that you can interact with programmatically.

Similarly, a website provides HTML pages that you can interact with and may also provide an API that offers the same information and operations programmatically. Or those services may only be available via an API with no associated user interface.

Sending email with gmail smtp with codeigniter email library

send html email via codeiginater

    $this->load->library('email');
    $this->load->library('parser');



    $this->email->clear();
    $config['mailtype'] = "html";
    $this->email->initialize($config);
    $this->email->set_newline("\r\n");
    $this->email->from('[email protected]', 'Website');
    $list = array('[email protected]', '[email protected]');
    $this->email->to($list);
    $data = array();
    $htmlMessage = $this->parser->parse('messages/email', $data, true);
    $this->email->subject('This is an email test');
    $this->email->message($htmlMessage);



    if ($this->email->send()) {
        echo 'Your email was sent, thanks chamil.';
    } else {
        show_error($this->email->print_debugger());
    }

How to get the month name in C#?

    private string MonthName(int m)
    {
        string res;
        switch (m)
        {
            case 1:
                res="Ene";
                break;
            case 2:
                res = "Feb";
                break;
            case 3:
                res = "Mar";
                break;
            case 4:
                res = "Abr";
                break;
            case 5:
                res = "May";
                break;
            case 6:
                res = "Jun";
                break;
            case 7:
                res = "Jul";
                break;
            case 8:
                res = "Ago";
                break;
            case 9:
                res = "Sep";
                break;
            case 10:
                res = "Oct";
                break;
            case 11:
                res = "Nov";
                break;
            case 12:
                res = "Dic";
                break;
            default:
                res = "Nulo";
                break;
        }
        return res;
    }

how we add or remove readonly attribute from textbox on clicking radion button in cakephp using jquery?

You could use prop as well. Check the following code below.

$(document).ready(function(){

   $('.staff_on_site').click(function(){

     var rBtnVal = $(this).val();

     if(rBtnVal == "yes"){
         $("#no_of_staff").prop("readonly", false); 
     }
     else{ 
         $("#no_of_staff").prop("readonly", true); 
     }
   });
});

How to display JavaScript variables in a HTML page without document.write

there are different ways of doing this. one way would be to write a script retrieving a command. like so:

var name="kieran";
document.write=(name);

or we could use the default JavaScript way to print it.

var name="kieran";
document.getElementById("output").innerHTML=name;

and the html code would be: 

<p id="output"></p>

i hope this helped :)

What is the difference between #import and #include in Objective-C?

If you are familiar with C++ and macros, then

#import "Class.h" 

is similar to

{
#pragma once

#include "class.h"
}

which means that your Class will be loaded only once when your app runs.

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

Easiest way to do this in VBA is to create a function that takes in an array, your new amount of rows, and new amount of columns.

Run the below function to copy in all of the old data back to the array after it has been resized.

 function dynamic_preserve(array1, num_rows, num_cols)

        dim array2 as variant

        array2 = array1

        reDim array1(1 to num_rows, 1 to num_cols)

        for i = lbound(array2, 1) to ubound(array2, 2)

               for j = lbound(array2,2) to ubound(array2,2)

                      array1(i,j) = array2(i,j)

               next j

        next i

        dynamic_preserve = array1

end function

Get the previous month's first and last day dates in c#

An approach using extension methods:

class Program
{
    static void Main(string[] args)
    {
        DateTime t = DateTime.Now;

        DateTime p = t.PreviousMonthFirstDay();
        Console.WriteLine( p.ToShortDateString() );

        p = t.PreviousMonthLastDay();
        Console.WriteLine( p.ToShortDateString() );


        Console.ReadKey();
    }
}


public static class Helpers
{
    public static DateTime PreviousMonthFirstDay( this DateTime currentDate )
    {
        DateTime d = currentDate.PreviousMonthLastDay();

        return new DateTime( d.Year, d.Month, 1 );
    }

    public static DateTime PreviousMonthLastDay( this DateTime currentDate )
    {
        return new DateTime( currentDate.Year, currentDate.Month, 1 ).AddDays( -1 );
    }
}

See this link http://www.codeplex.com/fluentdatetime for some inspired DateTime extensions.

How can I run specific migration in laravel

use this command php artisan migrate --path=/database/migrations/my_migration.php it worked for me..

Jackson and generic type reference

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

JsonMarshallerUnmarshaller<T> {
    T targetClass;

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

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

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

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

        return null ;
    }  
}

How to get sp_executesql result into a variable?

DECLARE @vi INT
DECLARE @vQuery NVARCHAR(1000)

SET @vQuery = N'SELECT @vi= COUNT(*) FROM <TableName>'

EXEC SP_EXECUTESQL 
        @Query  = @vQuery
      , @Params = N'@vi INT OUTPUT'
      , @vi = @vi OUTPUT

SELECT @vi

Building and running app via Gradle and Android Studio is slower than via Eclipse

To run Android envirorment on low configuration machine.

  1. Close the uncessesory web tabs in browser
  2. For Antivirus users, exclude the build folder which is auto generated
  3. Android studio have 1.2 Gb default heap can decrease to 512 MB Help > Edit custom VM options studio.vmoptions -Xmx512m Layouts performace will be speed up

  4. For Gradle one of the core component in Android studio Mkae sure like right now 3.0beta is latest one

Below tips can affect the code quality so please use with cautions:

  1. Studio contain Power safe Mode when turned on it will close background operations that lint , code complelitions and so on.

  2. You can run manually lintcheck when needed ./gradlew lint

  3. Most of are using Android emulators on average it consume 2 GB RAM so if possible use actual Android device these will reduce your resource load on your computer. Alternatively you can reduce the RAM of the emulator and it will automatically reduce the virtual memory consumption on your computer. you can find this in virtual device configuration and advance setting.

  4. Gradle offline mode is a feature for bandwidth limited users to disable the downloading of build dependencies. It will reduce the background operation that will help to increase the performance of Android studio.

  5. Android studio offers an optimization to compile multiple modules in parallel. On low RAM machines this feature will likely have a negative impact on the performance. You can disable it in the compiler settings dialog.

What's the difference between StaticResource and DynamicResource in WPF?

What is the main difference. Like memory or performance implications

The difference between static and dynamic resources comes when the underlying object changes. If your Brush defined in the Resources collection were accessed in code and set to a different object instance, Rectangle will not detect this change.

Static Resources retrieved once by referencing element and used for the lifetime of the resources. Whereas, DynamicResources retrieve every time they are used.

The downside of Dynamic resources is that they tend to decrease application performance.

Are there rules in WPF like "brushes are always static" and "templates are always dynamic" etc.?

The best practice is to use Static Resources unless there is a specific reason like you want to change resource in the code behind dynamically. Another example of instance in which you would want t to use dynamic resoruces include when you use the SystemBrushes, SystenFonts and System Parameters.

jquery toggle slide from left to right and back

Hide #categories initially

#categories {
    display: none;
}

and then, using JQuery UI, animate the Menu slowly

var duration = 'slow';

$('#cat_icon').click(function () {
    $('#cat_icon').hide(duration, function() {
        $('#categories').show('slide', {direction: 'left'}, duration);});
});
$('.panel_title').click(function () {
    $('#categories').hide('slide', {direction: 'left'}, duration, function() {
        $('#cat_icon').show(duration);});
});

JSFiddle

You can use any time in milliseconds as well

var duration = 2000;

If you want to hide on class='panel_item' too, select both panel_title and panel_item

$('.panel_title,.panel_item').click(function () {
    $('#categories').hide('slide', {direction: 'left'}, duration, function() {
        $('#cat_icon').show(duration);});
});

JSFiddle

HTML anchor link - href and onclick both?

If the link should only change the location if the function run is successful, then do onclick="return runMyFunction();" and in the function you would return true or false.

If you just want to run the function, and then let the anchor tag do its job, simply remove the return false statement.

As a side note, you should probably use an event handler instead, as inline JS isn't a very optimal way of doing things.

How to reset a timer in C#?

I just assigned a new value to the timer:

mytimer.Change(10000, 0); // reset to 10 seconds

It works fine for me.

at the top of the code define the timer: System.Threading.Timer myTimer;

if (!active)
    myTimer = new Timer(new TimerCallback(TimerProc));

myTimer.Change(10000, 0);
active = true;

private void TimerProc(object state)
{
    // The state object is the Timer object.
    var t = (Timer)state;

    t.Dispose();
    Console.WriteLine("The timer callback executes.");
    active = false;
    
    // Action to do when timer is back to zero
}

-bash: export: `=': not a valid identifier

Try to surround the path with quotes, and remove the spaces

export PYTHONPATH="/home/user/my_project":$PYTHONPATH

And don't forget to preserve previous content suffixing by :$PYTHONPATH (which is the value of the variable)

Execute the following command to check everything is configured correctly:

echo $PYTHONPATH

How do I ignore files in Subversion?

  1. open you use JetBrains Product(i.e. Pycharm)
  2. then click the 'commit' button on the top toolbar or use shortcut 'ctrl + k' screenshot_toolbar
  3. on the commit interface, move your unwanted files to another change list as follows. screenshot_commit_change
  4. next time you can only commit default change list.

How to empty a list?

it turns out that with python 2.5.2, del l[:] is slightly slower than l[:] = [] by 1.1 usec.

$ python -mtimeit "l=list(range(1000))" "b=l[:];del b[:]"
10000 loops, best of 3: 29.8 usec per loop
$ python -mtimeit "l=list(range(1000))" "b=l[:];b[:] = []"
10000 loops, best of 3: 28.7 usec per loop
$ python -V
Python 2.5.2

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

Removing the following lines from web.config solved my problem. Note that in this project I didn't use WebApi components. So for others this solution may not work as expected.

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

Javascript: how to validate dates in format MM-DD-YYYY?

function isValidDate(date)
{
    var matches = /^(\d{1,2})[-\/](\d{1,2})[-\/](\d{4})$/.exec(date);
    if (matches == null) return false;
    var d = matches[2];
    var m = matches[1] - 1;
    var y = matches[3];
    var composedDate = new Date(y, m, d);
    return composedDate.getDate() == d &&
            composedDate.getMonth() == m &&
            composedDate.getFullYear() == y;
}
console.log(isValidDate('10-12-1961'));
console.log(isValidDate('12/11/1961'));
console.log(isValidDate('02-11-1961'));
console.log(isValidDate('12/01/1961'));
console.log(isValidDate('13-11-1961'));
console.log(isValidDate('11-31-1961'));
console.log(isValidDate('11-31-1061'));

It works. (Tested with Firebug, hence the console.log().)

Access denied; you need (at least one of) the SUPER privilege(s) for this operation

Full Solution

All the above solutions are fine. And here I'm gonna combine all the solutions so that it should work for all the situations.

  1. Fixed DEFINER

For Linux and Mac

sed -i old 's/\DEFINER\=`[^`]*`@`[^`]*`//g' file.sql

For Windows
download atom or notepad++, open your dump sql file with atom or notepad++, press Ctrl+F
search the word DEFINER, and remove the line DEFINER=admin@% (or may be little different for you) from everywhere and save the file.
As for example
before removing that line: CREATE DEFINER=admin@% PROCEDURE MyProcedure
After removing that line: CREATE PROCEDURE MyProcedure

  1. Remove the 3 lines Remove all these 3 lines from the dump file. You can use sed command or open the file in Atom editor and search for each line and then remove the line.
    Example: Open Dump2020.sql in Atom, Press ctrl+F, search SET @@SESSION.SQL_LOG_BIN= 0, remove that line.
SET @@SESSION.SQL_LOG_BIN= 0;
SET @@GLOBAL.GTID_PURGED=/*!80000 '+'*/ '';
SET @@SESSION.SQL_LOG_BIN = @MYSQLDUMP_TEMP_LOG_BIN;
  1. There an issue with your generated file You might face some issue if your generated dump.sql file is not proper. But here, I'm not gonna explain how to generate a dump file. But you can ask me (_)

Executors.newCachedThreadPool() versus Executors.newFixedThreadPool()

If you look at the source code, you will see, they are calling ThreadPoolExecutor. internally and setting their properties. You can create your one to have a better control of your requirement.

public static ExecutorService newFixedThreadPool(int nThreads) {
   return new ThreadPoolExecutor(nThreads, nThreads,0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}

public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
}

Reading a file line by line in Go

import (
     "bufio"
     "os"
)

var (
    reader = bufio.NewReader(os.Stdin)
)

func ReadFromStdin() string{
    result, _ := reader.ReadString('\n')
    witl := result[:len(result)-1]
    return witl
}

Here is an example with function ReadFromStdin() it's like fmt.Scan(&name) but its takes all strings with blank spaces like: "Hello My Name Is ..."

var name string = ReadFromStdin()

println(name)

Why does Git tell me "No such remote 'origin'" when I try to push to origin?

The following simple steps help me:

First, initialize the repository to work with Git, so that any file changes are tracked:

git init

Then, check that the remote repository that you want to associate with the alias origin exists, if not create it in git first.

$ git ls-remote https://github.com/repo-owner/repo-name.git/

If it exists, associate it with the remote "origin":

git remote add origin https://github.com:/repo-owner/repo-name.git

and check to which URL, the remote "origin" belongs to by using git remote -v:

$ git remote -v
origin  https://github.com:/repo-owner/repo-name.git (fetch)
origin  https://github.com:/repo-owner/repo-name.git (push)

Next, verify if your origin is properly aliased as follows:

$ cat ./.git/config
:
[remote "origin"]
        url = https://github.com:/repo-owner/repo-name.git
        fetch = +refs/heads/*:refs/remotes/origin/*
:

You need to see this section [remote "origin"]. You can consider to use GitHub Desktop available for both Windows and MacOS, which help me to automatically populate the missing section/s in ~./git/config file OR you can manually add it, not great, but hey it works!

[Optional]
You might also want to change the origin alias to make it more intuitive, especially if you are working with multiple origin:

git remote rename origin mynewalias

or even remove it:

git remote rm origin

Finally, on your first push, if you want master in that repository to be your default upstream. you may want to add the -u parameter

git add .
git commit -m 'First commit'
git push -u origin master

Pandas DataFrame column to list

You can use the Series.to_list method.

For example:

import pandas as pd

df = pd.DataFrame({'a': [1, 3, 5, 7, 4, 5, 6, 4, 7, 8, 9],
                   'b': [3, 5, 6, 2, 4, 6, 7, 8, 7, 8, 9]})

print(df['a'].to_list())

Output:

[1, 3, 5, 7, 4, 5, 6, 4, 7, 8, 9]

To drop duplicates you can do one of the following:

>>> df['a'].drop_duplicates().to_list()
[1, 3, 5, 7, 4, 6, 8, 9]
>>> list(set(df['a'])) # as pointed out by EdChum
[1, 3, 4, 5, 6, 7, 8, 9]

Fatal error: Maximum execution time of 300 seconds exceeded

In Codeignitor version 3.0.x the system/core/Codeigniter.php do not contain the time constraint as well as inserting

ini_set('MAX_EXECUTION_TIME', -1);  

will not work since codeignitor will override that with its own function set_time_limit() . So either you have to delete that function from codeignitor or simply you can insert

set_time_limit('1000');

in the beginning of the php file if you wanna change that to 1000 seconds. Set the time to 0 (zero) if you want to run it as long as it want.

How to compare strings in sql ignoring case?

You can use:

select * from your_table where upper(your_column) like '%ANGEL%'

Otherwise, you can use:

select * from your_table where upper(your_column) = 'ANGEL'

Which will be more efficient if you are looking for a match with no additional characters before or after your_column field as Gary Ray suggested in his comments.

How do you run `apt-get` in a dockerfile behind a proxy?

A slight alternative to the answer provided by @Reza Farshi (which works better in my case) is to write the proxy settings out to /etc/apt/apt.conf using echo via the Dockerfile e.g.:

FROM ubuntu:16.04

RUN echo "Acquire::http::proxy \"$HTTP_PROXY\";\nAcquire::https::proxy \"$HTTPS_PROXY\";" > /etc/apt/apt.conf

# Test that we can now retrieve packages via 'apt-get'
RUN apt-get update

The advantage of this approach is that the proxy addresses can be passed in dynamically at image build time, rather than having to copy the settings file over from the host.

e.g.

docker build --build-arg HTTP_PROXY=http://<host>:<port> --build-arg HTTPS_PROXY=http://<host>:<port> .

as per docker build docs.

How to select where ID in Array Rails ActiveRecord without exception

Update: This answer is more relevant for Rails 4.x

Do this:

current_user.comments.where(:id=>[123,"456","Michael Jackson"])

The stronger side of this approach is that it returns a Relation object, to which you can join more .where clauses, .limit clauses, etc., which is very helpful. It also allows non-existent IDs without throwing exceptions.

The newer Ruby syntax would be:

current_user.comments.where(id: [123, "456", "Michael Jackson"])

Converting Date and Time To Unix Timestamp

Using a date picker to get date and a time picker I get two variables, this is how I put them together in unixtime format and then pull them out...

let datetime = oDdate+' '+oDtime;
let unixtime = Date.parse(datetime)/1000;
console.log('unixtime:',unixtime);

to prove it:

let milliseconds = unixtime * 1000;
dateObject = new Date(milliseconds);
console.log('dateObject:',dateObject);

enjoy!

Order by in Inner Join

In SQL, the order of the output is not defined unless you specify it in the ORDER BY clause.

Try this:

SELECT  *
FROM    one
JOIN    two
ON      one.one_name = two.one_name
ORDER BY
        one.id

Refresh Fragment at reload

To refresh the fragment accepted answer will not work on Nougat and above version. To make it work on all os you can do following.

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        fragmentManager.beginTransaction().detach(this).commitNow();
        fragmentManager.beginTransaction().attach(this).commitNow();
    } else {
        fragmentManager.beginTransaction().detach(this).attach(this).commit();
    }

What is the cleanest way to disable CSS transition effects temporarily?

Short Answer

Use this CSS:

.notransition {
  -webkit-transition: none !important;
  -moz-transition: none !important;
  -o-transition: none !important;
  transition: none !important;
}

Plus either this JS (without jQuery)...

someElement.classList.add('notransition'); // Disable transitions
doWhateverCssChangesYouWant(someElement);
someElement.offsetHeight; // Trigger a reflow, flushing the CSS changes
someElement.classList.remove('notransition'); // Re-enable transitions

Or this JS with jQuery...

$someElement.addClass('notransition'); // Disable transitions
doWhateverCssChangesYouWant($someElement);
$someElement[0].offsetHeight; // Trigger a reflow, flushing the CSS changes
$someElement.removeClass('notransition'); // Re-enable transitions

... or equivalent code using whatever other library or framework you're working with.

Explanation

This is actually a fairly subtle problem.

First up, you probably want to create a 'notransition' class that you can apply to elements to set their *-transition CSS attributes to none. For instance:

.notransition {
  -webkit-transition: none !important;
  -moz-transition: none !important;
  -o-transition: none !important;
  transition: none !important;
}

(Minor aside - note the lack of an -ms-transition in there. You don't need it. The first version of Internet Explorer to support transitions at all was IE 10, which supported them unprefixed.)

But that's just style, and is the easy bit. When you come to try and use this class, you'll run into a trap. The trap is that code like this won't work the way you might naively expect:

// Don't do things this way! It doesn't work!
someElement.classList.add('notransition')
someElement.style.height = '50px' // just an example; could be any CSS change
someElement.classList.remove('notransition')

Naively, you might think that the change in height won't be animated, because it happens while the 'notransition' class is applied. In reality, though, it will be animated, at least in all modern browsers I've tried. The problem is that the browser is caching the styling changes that it needs to make until the JavaScript has finished executing, and then making all the changes in a single reflow. As a result, it does a reflow where there is no net change to whether or not transitions are enabled, but there is a net change to the height. Consequently, it animates the height change.

You might think a reasonable and clean way to get around this would be to wrap the removal of the 'notransition' class in a 1ms timeout, like this:

// Don't do things this way! It STILL doesn't work!
someElement.classList.add('notransition')
someElement.style.height = '50px' // just an example; could be any CSS change
setTimeout(function () {someElement.classList.remove('notransition')}, 1);

but this doesn't reliably work either. I wasn't able to make the above code break in WebKit browsers, but on Firefox (on both slow and fast machines) you'll sometimes (seemingly at random) get the same behaviour as using the naive approach. I guess the reason for this is that it's possible for the JavaScript execution to be slow enough that the timeout function is waiting to execute by the time the browser is idle and would otherwise be thinking about doing an opportunistic reflow, and if that scenario happens, Firefox executes the queued function before the reflow.

The only solution I've found to the problem is to force a reflow of the element, flushing the CSS changes made to it, before removing the 'notransition' class. There are various ways to do this - see here for some. The closest thing there is to a 'standard' way of doing this is to read the offsetHeight property of the element.

One solution that actually works, then, is

someElement.classList.add('notransition'); // Disable transitions
doWhateverCssChangesYouWant(someElement);
someElement.offsetHeight; // Trigger a reflow, flushing the CSS changes
someElement.classList.remove('notransition'); // Re-enable transitions

Here's a JS fiddle that illustrates the three possible approaches I've described here (both the one successful approach and the two unsuccessful ones): http://jsfiddle.net/2uVAA/131/

How do I print a list of "Build Settings" in Xcode project?

In case you would like to read/check your Target Build Settings in runtime using code, here is the way:

1) Add a Run Script:

cp ${PROJECT_FILE_PATH}/project.pbxproj ${CONFIGURATION_BUILD_DIR}/${EXECUTABLE_NAME}.app/BuildSetting.pbxproj 

It will copy the Target Build Settings file into your Main Bundle (will be called BuildSetting.pbxproj).

2) You can now check the contents of that file at any time in code:

NSString *thePathString = [[NSBundle mainBundle] pathForResource:@"BuildSetting" ofType:@"pbxproj"];
NSDictionary *theDictionary = [NSDictionary dictionaryWithContentsOfFile:thePathString];

jQuery won't parse my JSON from AJAX query

If returning an array works and returning a single object doesn't, you might also try returning your single object as an array containing that single object:

[ { title: "One", key: "1" } ]

that way you are returning a consistent data structure, an array of objects, no matter the data payload.

i see that you've tried wrapping your single object in "parenthesis", and suggest this with example because of course JavaScript treats [ .. ] differently than ( .. )

Import .bak file to a database in SQL server

Instead of choosing Restore Database..., select Restore Files and Filegroups...

Then enter a database name, select your .bak file path as the source, check the restore checkbox, and click Ok. If the .bak file is valid, it will work.

(The SQL Server restore option names are not intuitive for what should a very simple task.)

Using ffmpeg to change framerate

To the best of my knowledge you can't do this with ffmpeg without re-encoding. I had a 24fps file I wanted at 25fps to match some other material I was working with. I used the command ffmpeg -i inputfile -r 25 outputfile which worked perfectly with a webm,matroska input and resulted in an h264, matroska output utilizing encoder: Lavc56.60.100

You can accomplish the same thing at 6fps but as you noted the duration will not change (which in most cases is a good thing as otherwise you will lose audio sync). If this doesn't fit your requirements I suggest that you try this answer although my experience has been that it still re-encodes the output file.

For the best frame accuracy you are still better off decoding to raw streams as previously suggested. I use a script for this as reproduced below:

#!/bin/bash
#This script will decompress all files in the current directory, video to huffyuv and audio to PCM
#unsigned 8-bit and place the output #in an avi container to ease frame accurate editing.
for f in *
do
ffmpeg -i "$f" -c:v huffyuv -c:a pcm_u8 "$f".avi
done

Clearly this script expects all files in the current directory to be media files but can easily be changed to restrict processing to a specific extension of your choosing. Be aware that your file size will increase by a rather large factor when you decompress into raw streams.

How to embed fonts in HTML?

No, there isn't a decent solution for body type, unless you're willing to cater only to those with bleeding-edge browsers.

Microsoft has WEFT, their own proprietary font-embedding technology, but I haven't heard it talked about in years, and I know no one who uses it.

I get by with sIFR for display type (headlines, titles of blog posts, etc.) and using one of the less-worn-out web-safe fonts for body type (like Trebuchet MS). If you're bored with all the web-safe fonts, you're probably defining the term too narrowly — look at this matrix of stock fonts that ship with major OSes and chances are you'll be able to find a font cascade that will catch nearly all web users.

For instance: font-family: "Lucida Grande", "Verdana", sans-serif is a common font cascade; OS X comes with Lucida Grande, but those with Windows will get Verdana, a web-safe font with letters of similar size and shape to Lucida Grande. Linux users will also get Verdana if they've installed the web-safe fonts package that exists in most distros' package managers, or else they'll fall back to an ordinary sans-serif.

How do you install and run Mocha, the Node.js testing module? Getting "mocha: command not found" after install

since npm 5.2.0, there's a new command "npx" included with npm that makes this much simpler, if you run:

npx mocha <args>

Note: the optional args are forwarded to the command being executed (mocha in this case)

this will automatically pick the executable "mocha" command from your locally installed mocha (always add it as a dev dependency to ensure the correct one is always used by you and everyone else).

Be careful though that if you didn't install mocha, this command will automatically fetch and use latest version, which is great for some tools (like scaffolders for example), but might not be the most recommendable for certain dependencies where you might want to pin to a specific version.

You can read more on npx here


Now, if instead of invoking mocha directly, you want to define a custom npm script, an alias that might invoke other npm binaries...

you don't want your library tests to fail depending on the machine setup (mocha as global, global mocha version, etc), the way to use the local mocha that works cross-platform is:

node node_modules/.bin/mocha

npm puts aliases to all the binaries in your dependencies on that special folder. Finally, npm will add node_modules/.bin to the PATH automatically when running an npm script, so in your package.json you can do just:

"scripts": {
  "test": "mocha"
}

and invoke it with

npm test

How do I Sort a Multidimensional Array in PHP

Multiple row sorting using a closure

Here's another approach using uasort() and an anonymous callback function (closure). I've used that function regularly. PHP 5.3 required – no more dependencies!

/**
 * Sorting array of associative arrays - multiple row sorting using a closure.
 * See also: http://the-art-of-web.com/php/sortarray/
 *
 * @param array $data input-array
 * @param string|array $fields array-keys
 * @license Public Domain
 * @return array
 */
function sortArray( $data, $field ) {
    $field = (array) $field;
    uasort( $data, function($a, $b) use($field) {
        $retval = 0;
        foreach( $field as $fieldname ) {
            if( $retval == 0 ) $retval = strnatcmp( $a[$fieldname], $b[$fieldname] );
        }
        return $retval;
    } );
    return $data;
}

/* example */
$data = array(
    array( "firstname" => "Mary", "lastname" => "Johnson", "age" => 25 ),
    array( "firstname" => "Amanda", "lastname" => "Miller", "age" => 18 ),
    array( "firstname" => "James", "lastname" => "Brown", "age" => 31 ),
    array( "firstname" => "Patricia", "lastname" => "Williams", "age" => 7 ),
    array( "firstname" => "Michael", "lastname" => "Davis", "age" => 43 ),
    array( "firstname" => "Sarah", "lastname" => "Miller", "age" => 24 ),
    array( "firstname" => "Patrick", "lastname" => "Miller", "age" => 27 )
);

$data = sortArray( $data, 'age' );
$data = sortArray( $data, array( 'lastname', 'firstname' ) );

Prevent line-break of span element

Put this in your CSS:

white-space:nowrap;

Get more information here: http://www.w3.org/wiki/CSS/Properties/white-space

white-space

The white-space property declares how white space inside the element is handled.

Values

normal This value directs user agents to collapse sequences of white space, and break lines as necessary to fill line boxes.

pre This value prevents user agents from collapsing sequences of white space. Lines are only broken at newlines in the source, or at occurrences of "\A" in generated content.

nowrap This value collapses white space as for 'normal', but suppresses line breaks within text.

pre-wrap This value prevents user agents from collapsing sequences of white space. Lines are broken at newlines in the source, at occurrences of "\A" in generated content, and as necessary to fill line boxes.

pre-line This value directs user agents to collapse sequences of white space. Lines are broken at newlines in the source, at occurrences of "\A" in generated content, and as necessary to fill line boxes.

inherit Takes the same specified value as the property for the element's parent.

What does "app.run(host='0.0.0.0') " mean in Flask

To answer to your second question. You can just hit the IP address of the machine that your flask app is running, e.g. 192.168.1.100 in a browser on different machine on the same network and you are there. Though, you will not be able to access it if you are on a different network. Firewalls or VLans can cause you problems with reaching your application. If that computer has a public IP, then you can hit that IP from anywhere on the planet and you will be able to reach the app. Usually this might impose some configuration, since most of the public servers are behind some sort of router or firewall.

how to parse JSONArray in android

Here is a better way for doing it. Hope this helps

protected void onPostExecute(String result) {
                Log.v(TAG + " result);


                if (!result.equals("")) {

                    // Set up variables for API Call
                    ArrayList<String> list = new ArrayList<String>();

                    try {
                        JSONArray jsonArray = new JSONArray(result);

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

                            list.add(jsonArray.get(i).toString());

                        }//end for
                    } catch (JSONException e) {
                        Log.e(TAG, "onPostExecute > Try > JSONException => " + e);
                        e.printStackTrace();
                    }


                    adapter = new ArrayAdapter<String>(ListViewData.this, android.R.layout.simple_list_item_1, android.R.id.text1, list);
                    listView.setAdapter(adapter);
                    listView.setOnItemClickListener(new OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                            // ListView Clicked item index
                            int itemPosition = position;

                            // ListView Clicked item value
                            String itemValue = (String) listView.getItemAtPosition(position);

                            // Show Alert
                            Toast.makeText( ListViewData.this, "Position :" + itemPosition + "  ListItem : " + itemValue, Toast.LENGTH_LONG).show();
                        }
                    });

                    adapter.notifyDataSetChanged();
...

Convert file: Uri to File in Android

For folks that are here looking for a solution for images in particular here it is.

private Bitmap getBitmapFromUri(Uri contentUri) {
        String path = null;
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(contentUri, projection, null, null, null);
        if (cursor.moveToFirst()) {
            int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            path = cursor.getString(columnIndex);
        }
        cursor.close();
        Bitmap bitmap = BitmapFactory.decodeFile(path);
        return bitmap;
    }

403 - Forbidden: Access is denied. ASP.Net MVC

Are you hosting the site on iis? if so make sure the account your website runs under has access to local file system?

Straight from msdn .....

The Network Service account has Read and Execute permissions on the IIS server root folder by default. The IIS server root folder is named Wwwroot. This means that an ASP.NET application deployed inside the root folder already has Read and Execute permissions to its application folders. However, if your ASP.NET application needs to use files or folders in other locations, you must specifically enable access.

To provide access to an ASP.NET application running as Network Service, you must grant access to the Network Service account.

To grant read, write, and modify permissions to a specific file

  • In Windows Explorer, locate and select the required file.
  • Right-click the file, and then click Properties.
  • In the Properties dialog box, click the Security tab.
  • On the Security tab, examine the list of users. If the Network Service
  • account is not listed, add it.
  • In the Properties dialog box, click the Network Service user name, and in the Permissions for NETWORK SERVICE section, select the Read, Write, and Modify permissions.
  • Click Apply, and then click OK.

Click here for more

Difference between .on('click') vs .click()

I think, the difference is in usage patterns.

I would prefer .on over .click because the former can use less memory and work for dynamically added elements.

Consider the following html:

<html>
    <button id="add">Add new</button>
    <div id="container">
        <button class="alert">alert!</button>
    </div>
</html>

where we add new buttons via

$("button#add").click(function() {
    var html = "<button class='alert'>Alert!</button>";
    $("button.alert:last").parent().append(html);
});

and want "Alert!" to show an alert. We can use either "click" or "on" for that.


When we use click

$("button.alert").click(function() {
    alert(1);
});

with the above, a separate handler gets created for every single element that matches the selector. That means

  1. many matching elements would create many identical handlers and thus increase memory footprint
  2. dynamically added items won't have the handler - ie, in the above html the newly added "Alert!" buttons won't work unless you rebind the handler.

When we use .on

$("div#container").on('click', 'button.alert', function() {
    alert(1);
});

with the above, a single handler for all elements that match your selector, including the ones created dynamically.


...another reason to use .on

As Adrien commented below, another reason to use .on is namespaced events.

If you add a handler with .on("click", handler) you normally remove it with .off("click", handler) which will remove that very handler. Obviously this works only if you have a reference to the function, so what if you don't ? You use namespaces:

$("#element").on("click.someNamespace", function() { console.log("anonymous!"); });

with unbinding via

$("#element").off("click.someNamespace");

Passing data between view controllers

You can create a push segue from the source viewcontroller to the destination viewcontroller and give an identifier name like below.

Enter image description here

You have to perform a segue from didselectRowAt like this.

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    performSegue(withIdentifier: "segue", sender: self)
}

And you can pass the array of the selected item from the below function.

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let index = CategorytableView.indexPathForSelectedRow
    let indexNumber = index?.row
    print(indexNumber!)
    let VC = segue.destination as! AddTransactionVC
    VC.val = CategoryData[indexNumber!] . // Here you can pass the entire array instead of an array element.
}

And you have to check the value in viewdidload of destination viewcontroller and then store it into the database.

override func viewDidLoad{
    if val != ""{
        btnSelectCategory.setTitle(val, for: .normal)
    }
}

Thread Safe C# Singleton Pattern

Jeffrey Richter recommends following:



    public sealed class Singleton
    {
        private static readonly Object s_lock = new Object();
        private static Singleton instance = null;
    
        private Singleton()
        {
        }
    
        public static Singleton Instance
        {
            get
            {
                if(instance != null) return instance;
                Monitor.Enter(s_lock);
                Singleton temp = new Singleton();
                Interlocked.Exchange(ref instance, temp);
                Monitor.Exit(s_lock);
                return instance;
            }
        }
    }

How to delete a file or folder?

For deleting files:

os.unlink(path, *, dir_fd=None)

or

os.remove(path, *, dir_fd=None)

Both functions are semantically same. This functions removes (deletes) the file path. If path is not a file and it is directory, then exception is raised.

For deleting folders:

shutil.rmtree(path, ignore_errors=False, onerror=None)

or

os.rmdir(path, *, dir_fd=None)

In order to remove whole directory trees, shutil.rmtree() can be used. os.rmdir only works when the directory is empty and exists.

For deleting folders recursively towards parent:

os.removedirs(name)

It remove every empty parent directory with self until parent which has some content

ex. os.removedirs('abc/xyz/pqr') will remove the directories by order 'abc/xyz/pqr', 'abc/xyz' and 'abc' if they are empty.

For more info check official doc: os.unlink , os.remove, os.rmdir , shutil.rmtree, os.removedirs

TypeError: ObjectId('') is not JSON serializable

This is how I've recently fixed the error

    @app.route('/')
    def home():
        docs = []
        for doc in db.person.find():
            doc.pop('_id') 
            docs.append(doc)
        return jsonify(docs)

Use tab to indent in textarea

Every input an textarea element has a onkeydown event. In the event handler you can prevent the default reaction of the tab key by using event.preventDefault() whenever event.keyCode is 9.

Then put a tab sign in the right position:

function allowTab(input)
{
    input.addEventListener("keydown", function(event)
    {
        if(event.keyCode == 9)
        {
            event.preventDefault();

            var input = event.target;

            var str = input.value;
            var _selectionStart = input.selectionStart;
            var _selectionEnd = input.selectionEnd;

            str = str.substring(0, _selectionStart) + "\t" + str.substring(_selectionEnd, str.length);
            _selectionStart++;

            input.value = str;
            input.selectionStart = _selectionStart;
            input.selectionEnd = _selectionStart;
        }
    });
}

window.addEventListener("load", function(event)
{
    allowTab(document.querySelector("textarea"));
});

html

<textarea></textarea>

SQL Server - calculate elapsed time between two datetime stamps in HH:MM:SS format

Use the DATEDIFF to return value in milliseconds, seconds, minutes, hours, ...

DATEDIFF(interval, date1, date2)

interval REQUIRED - The time/date part to return. Can be one of the following values:

year, yyyy, yy = Year
quarter, qq, q = Quarter
month, mm, m = month
dayofyear = Day of the year
day, dy, y = Day
week, ww, wk = Week
weekday, dw, w = Weekday
hour, hh = hour
minute, mi, n = Minute
second, ss, s = Second
millisecond, ms = Millisecond

date1, date2 REQUIRED - The two dates to calculate the difference between

What are the dark corners of Vim your mom never told you about?

gg=G

Corrects indentation for entire file. I was missing my trusty <C-a><C-i> in Eclipse but just found out vim handles it nicely.

Update a column in MySQL

UPDATE table1 SET col_a = 'newvalue'

Add a WHERE condition if you want to only update some of the rows.

Regex (grep) for multi-line search needed

I am not very good in grep. But your problem can be solved using AWK command. Just see

awk '/select/,/from/' *.sql

The above code will result from first occurence of select till first sequence of from. Now you need to verify whether returned statements are having customername or not. For this you can pipe the result. And can use awk or grep again.

How to install Python package from GitHub?

To install Python package from github, you need to clone that repository.

git clone https://github.com/jkbr/httpie.git

Then just run the setup.py file from that directory,

sudo python setup.py install

Responsive Bootstrap Jumbotron Background Image

The simplest way is to set the background-size CSS property to cover:

.jumbotron {
  background-image: url("../img/jumbotron_bg.jpg");
  background-size: cover;
}

bash: pip: command not found

Avoiding sudo:

python <(curl https://bootstrap.pypa.io/get-pip.py) --user
echo 'export "PATH=$HOME/Library/Python/2.7/bin:$PATH"' >> ~/.bash_profile

From:

http://www.pip-command-not-found.com

PHP - print all properties of an object

for knowing the object properties var_dump(object) is the best way. It will show all public, private and protected properties associated with it without knowing the class name.

But in case of methods, you need to know the class name else i think it's difficult to get all associated methods of the object.

uppercase first character in a variable with bash

What if the first character is not a letter (but a tab, a space, and a escaped double quote)? We'd better test it until we find a letter! So:

S='  \"ó foo bar\"'
N=0
until [[ ${S:$N:1} =~ [[:alpha:]] ]]; do N=$[$N+1]; done
#F=`echo ${S:$N:1} | tr [:lower:] [:upper:]`
#F=`echo ${S:$N:1} | sed -E -e 's/./\u&/'` #other option
F=`echo ${S:$N:1}
F=`echo ${F} #pure Bash solution to "upper"
echo "$F"${S:(($N+1))} #without garbage
echo '='${S:0:(($N))}"$F"${S:(($N+1))}'=' #garbage preserved

Foo bar
= \"Foo bar=

How to create new folder?

You can create a folder with os.makedirs()
and use os.path.exists() to see if it already exists:

newpath = r'C:\Program Files\arbitrary' 
if not os.path.exists(newpath):
    os.makedirs(newpath)

If you're trying to make an installer: Windows Installer does a lot of work for you.

CSS to stop text wrapping under image

If you want the margin-left to work on a span element you'll need to make it display: inline-block or display:block as well.

How to make a class property?

As far as I can tell, there is no way to write a setter for a class property without creating a new metaclass.

I have found that the following method works. Define a metaclass with all of the class properties and setters you want. IE, I wanted a class with a title property with a setter. Here's what I wrote:

class TitleMeta(type):
    @property
    def title(self):
        return getattr(self, '_title', 'Default Title')

    @title.setter
    def title(self, title):
        self._title = title
        # Do whatever else you want when the title is set...

Now make the actual class you want as normal, except have it use the metaclass you created above.

# Python 2 style:
class ClassWithTitle(object):
    __metaclass__ = TitleMeta
    # The rest of your class definition...

# Python 3 style:
class ClassWithTitle(object, metaclass = TitleMeta):
    # Your class definition...

It's a bit weird to define this metaclass as we did above if we'll only ever use it on the single class. In that case, if you're using the Python 2 style, you can actually define the metaclass inside the class body. That way it's not defined in the module scope.

How to create and handle composite primary key in JPA

Key class:

@Embeddable
@Access (AccessType.FIELD)
public class EntryKey implements Serializable {

    public EntryKey() {
    }

    public EntryKey(final Long id, final Long version) {
        this.id = id;
        this.version = version;
    }

    public Long getId() {
        return this.id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Long getVersion() {
        return this.version;
    }

    public void setVersion(Long version) {
        this.version = version;
    }

    public boolean equals(Object other) {
        if (this == other)
            return true;
        if (!(other instanceof EntryKey))
            return false;
        EntryKey castOther = (EntryKey) other;
        return id.equals(castOther.id) && version.equals(castOther.version);
    }

    public int hashCode() {
        final int prime = 31;
        int hash = 17;
        hash = hash * prime + this.id.hashCode();
        hash = hash * prime + this.version.hashCode();
        return hash;
    }

    @Column (name = "ID")
    private Long id;
    @Column (name = "VERSION")
    private Long operatorId;
}

Entity class:

@Entity
@Table (name = "YOUR_TABLE_NAME")
public class Entry implements Serializable {

    @EmbeddedId
    public EntryKey getKey() {
        return this.key;
    }

    public void setKey(EntryKey id) {
        this.id = id;
    }

    ...

    private EntryKey key;
    ...
}

How can I duplicate it with another Version?

You can detach entity which retrieved from provider, change the key of Entry and then persist it as a new entity.

Server cannot set status after HTTP headers have been sent IIS7.5

I apologize, but I'm adding my 2 cents to the thread just in case anyone has the same problem.

  • I used Forms Authentication in my MVC app
  • But some controller-actions were "anonymous" i.e. allowed to non-authenticated users
  • Sometimes in those actions I would still want users to be redirected to the login form under some condition
  • to do that - I have this in my action method: return new HttpStatusCodeResult(401) - and ASP.NET is super nice to detect this, and it redirects the user to the login page! Magic, right? It even has the proper ReturnUrl parameter etc.

But you see where I'm getting here? I return 401. And ASP.NET redirects the user. Which is essentially returns 302. One status code is replaced with another.

And some IIS servers (just some!) throw this exception. Some don't. - I don't have it on my test serevr, only on my production server (ain't it always the case right o_O)

I know my answer is essentially repeating what's already said here, but sometimes it's just hard to figure out where this overwriting happens exactly.

Find and replace with sed in directory and sub directories

Since there are also macOS folks reading this one (as I did), the following code worked for me (on 10.14)

egrep -rl '<pattern>' <dir> | xargs -I@ sed -i '' 's/<arg1>/<arg2>/g' @

All other answers using -i and -e do not work on macOS.

Source

How to solve "The specified service has been marked for deletion" error

Deleting registry keys as suggested above got my service stuck in the stopping state. The following procedure worked for me:

open task manager > select services tab > select the service > right click and select "go to process" > right click on the process and select End process

Service should be gone after that

SQL Server Group By Month

Restrict the dimension of the NVARCHAR to 7, supplied to CONVERT to show only "YYYY-MM"

SELECT CONVERT(NVARCHAR(7),PaymentDate,120) [Month], SUM(Amount) [TotalAmount]
FROM Payments
GROUP BY CONVERT(NVARCHAR(7),PaymentDate,120)
ORDER BY [Month]

What is __future__ in Python used for and how/when to use it, and how it works

When you do

from __future__ import whatever

You're not actually using an import statement, but a future statement. You're reading the wrong docs, as you're not actually importing that module.

Future statements are special -- they change how your Python module is parsed, which is why they must be at the top of the file. They give new -- or different -- meaning to words or symbols in your file. From the docs:

A future statement is a directive to the compiler that a particular module should be compiled using syntax or semantics that will be available in a specified future release of Python. The future statement is intended to ease migration to future versions of Python that introduce incompatible changes to the language. It allows use of the new features on a per-module basis before the release in which the feature becomes standard.

If you actually want to import the __future__ module, just do

import __future__

and then access it as usual.

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

something.innerHTML += 'add whatever you want';

it worked for me. I added a button to an input text using this solution

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

Limit is very simple, example limit first 50 rows

val df_subset = data.limit(50)

eloquent laravel: How to get a row count from a ->get()

Answer has been updated

count is a Collection method. The query builder returns an array. So in order to get the count, you would just count it like you normally would with an array:

$wordCount = count($wordlist);

If you have a wordlist model, then you can use Eloquent to get a Collection and then use the Collection's count method. Example:

$wordlist = Wordlist::where('id', '<=', $correctedComparisons)->get();
$wordCount = $wordlist->count();

There is/was a discussion on having the query builder return a collection here: https://github.com/laravel/framework/issues/10478

However as of now, the query builder always returns an array.

Edit: As linked above, the query builder now returns a collection (not an array). As a result, what JP Foster was trying to do initially will work:

$wordlist = \DB::table('wordlist')->where('id', '<=', $correctedComparisons)
            ->get();
$wordCount = $wordlist->count();

However, as indicated by Leon in the comments, if all you want is the count, then querying for it directly is much faster than fetching an entire collection and then getting the count. In other words, you can do this:

// Query builder
$wordCount = \DB::table('wordlist')->where('id', '<=', $correctedComparisons)
            ->count();

// Eloquent
$wordCount = Wordlist::where('id', '<=', $correctedComparisons)->count();

Sorting objects by property values

javascript has the sort function which can take another function as parameter - that second function is used to compare two elements.

Example:

cars = [

    {
        name: "Honda",
        speed: 80
    },

    {
        name: "BMW",
        speed: 180
    },

    {
        name: "Trabi",
        speed: 40
    },

    {
        name: "Ferrari",
        speed: 200
    }
]


cars.sort(function(a, b) { 
    return a.speed - b.speed;
})

for(var i in cars)
    document.writeln(cars[i].name) // Trabi Honda BMW Ferrari 

ok, from your comment i see that you're using the word 'sort' in a wrong sense. In programming "sort" means "put things in a certain order", not "arrange things in groups". The latter is much simpler - this is just how you "sort" things in the real world

  • make two empty arrays ("boxes")
  • for each object in your list, check if it matches the criteria
  • if yes, put it in the first "box"
  • if no, put it in the second "box"

HAProxy redirecting http to https (ssl)

frontend unsecured *:80
    mode http
    redirect location https://foo.bar.com

Order by multiple columns with Doctrine

In Doctrine 2.x you can't pass multiple order by using doctrine 'orderBy' or 'addOrderBy' as above examples. Because, it automatically adds the 'ASC' at the end of the last column name when you left the second parameter blank, such as in the 'orderBy' function.

For an example ->orderBy('a.fist_name ASC, a.last_name ASC') will output SQL something like this 'ORDER BY first_name ASC, last_name ASC ASC'. So this is SQL syntax error. Simply because default of the orderBy or addOrderBy is 'ASC'.

To add multiple order by's you need to use 'add' function. And it will be like this.

->add('orderBy','first_name ASC, last_name ASC'). This will give you the correctly formatted SQL.

More info on add() function. https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/query-builder.html#low-level-api

Hope this helps. Cheers!

What is the best way to tell if a character is a letter or number in Java without using regexes?

 import java.util.Scanner;
 public class v{
 public static void main(String args[]){
 Scanner in=new Scanner(System.in);
    String str;
    int l;
    int flag=0;
    System.out.println("Enter the String:");
    str=in.nextLine();
    str=str.toLowerCase();
    str=str.replaceAll("\\s","");
    char[] ch=str.toCharArray();
    l=str.length();
    for(int i=0;i<l;i++){
        if ((ch[i] >= 'a' && ch[i]<= 'z') || (ch[i] >= 'A' && ch[i] <= 'Z')){
        flag=0;
        }
        else

        flag++;
        break;
        } 
if(flag==0)
    System.out.println("Onlt char");


}
}

Find column whose name contains a specific string

You also can use this code:

spike_cols =[x for x in df.columns[df.columns.str.contains('spike')]]

Combine two columns of text in pandas dataframe

def madd(x):
    """Performs element-wise string concatenation with multiple input arrays.

    Args:
        x: iterable of np.array.

    Returns: np.array.
    """
    for i, arr in enumerate(x):
        if type(arr.item(0)) is not str:
            x[i] = x[i].astype(str)
    return reduce(np.core.defchararray.add, x)

For example:

data = list(zip([2000]*4, ['q1', 'q2', 'q3', 'q4']))
df = pd.DataFrame(data=data, columns=['Year', 'quarter'])
df['period'] = madd([df[col].values for col in ['Year', 'quarter']])

df

    Year    quarter period
0   2000    q1  2000q1
1   2000    q2  2000q2
2   2000    q3  2000q3
3   2000    q4  2000q4

JSON: why are forward slashes escaped?

JSON doesn't require you to do that, it allows you to do that. It also allows you to use "\u0061" for "A", but it's not required. Allowing \/ helps when embedding JSON in a <script> tag, which doesn't allow </ inside strings, like Seb points out.

Some of Microsoft's ASP.NET Ajax/JSON API's use this loophole to add extra information, e.g., a datetime will be sent as "\/Date(milliseconds)\/". (Yuck)

How to debug stored procedures with print statements?

try using:

RAISERROR('your message here!!!',0,1) WITH NOWAIT

you could also try switching to "Results to Text" it is just a few icons to the right of "Execute" on the default tool bar.

With both of the above in place, and you still you do not see the messages, make sure you are running the same server/database/owner version of the procedure that you are editing. Make sure you are hitting the RAISERROR command, make it the first command inside the procedure.

If all else fails, you could create a table:

create table temp_log (RowID int identity(1,1) primary key not null
                      , MessageValue varchar(255))

then:

INSERT INTO temp_log VALUES ('Your message here')

then after running the procedure (provided no rollbacks) just select the table.

Trusting all certificates using HttpClient over HTTPS

There a many answers above but I wasn't able to get any of them working correctly (with my limited time), so for anyone else in the same situation you can try the code below which worked perfectly for my java testing purposes:

    public static HttpClient wrapClient(HttpClient base) {
    try {
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {
            public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException { }

            public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException { }

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        ctx.init(null, new TrustManager[]{tm}, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx);
        ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm = base.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", ssf, 443));
        return new DefaultHttpClient(ccm, base.getParams());
    } catch (Exception ex) {
        return null;
    }
}

and call like:

DefaultHttpClient baseClient = new DefaultHttpClient();
HttpClient httpClient = wrapClient(baseClient );

Reference: http://tech.chitgoks.com/2011/04/24/how-to-avoid-javax-net-ssl-sslpeerunverifiedexception-peer-not-authenticated-problem-using-apache-httpclient/

TypeScript: Interfaces vs Types

As of TypeScript 3.2 (Nov 2018), the following is true:

enter image description here

Sort a two dimensional array based on one column

Assuming your array contains strings, you can use the following:

String[] data = new String[] { 
    "2009.07.25 20:24 Message A",
    "2009.07.25 20:17 Message G",
    "2009.07.25 20:25 Message B",
    "2009.07.25 20:30 Message D",
    "2009.07.25 20:01 Message F",
    "2009.07.25 21:08 Message E",
    "2009.07.25 19:54 Message R"
};

Arrays.sort(data, new Comparator<String>() {
    @Override
    public int compare(String s1, String s2) {
        String t1 = s1.substring(0, 16); // date/time of s1
        String t2 = s2.substring(0, 16); // date/time of s2
        return t1.compareTo(t2);
    }
});

If you have a two-dimensional array, the solution is also very similar:

String[][] data = new String[][] { 
        { "2009.07.25 20:17", "Message G" },
        { "2009.07.25 20:25", "Message B" },
        { "2009.07.25 20:30", "Message D" },
        { "2009.07.25 20:01", "Message F" },
        { "2009.07.25 21:08", "Message E" },
        { "2009.07.25 19:54", "Message R" }
};

Arrays.sort(data, new Comparator<String[]>() {
    @Override
    public int compare(String[] s1, String[] s2) {
        String t1 = s1[0];
        String t2 = s2[0];
        return t1.compareTo(t2);
    }
});

Kill a postgresql session/connection

Open PGadmin see if there is any query page open, close all query page and disconnect the PostgresSQL server and Connect it again and try delete/drop option.This helped me.

How do I delete from multiple tables using INNER JOIN in SQL server

To build upon John Gibb's answer, for deleting a set of data in two tables with a FK relationship:

--*** To delete from tblMain which JOINs to (has a FK of) tblReferredTo's PK  
--       i.e.  ON tblMain.Refer_FK = tblReferredTo.ID
--*** !!! If you're CERTAIN that no other rows anywhere also refer to the 
--      specific rows in tblReferredTo !!!
BEGIN TRAN;

    --*** Keep the ID's from tblReferredTo when we DELETE from tblMain
    DECLARE @tblDeletedRefs TABLE ( ID INT );
    --*** DELETE from the referring table first
    DELETE FROM tblMain 
    OUTPUT DELETED.Refer_FK INTO @tblDeletedRefs  -- doesn't matter that this isn't DISTINCT, the following DELETE still works.
    WHERE ..... -- be careful if filtering, what if other rows 
                --   in tblMain (or elsewhere) also point to the tblReferredTo rows?

    --*** Now we can remove the referred to rows, even though tblMain no longer refers to them.
    DELETE tblReferredTo
    FROM   tblReferredTo INNER JOIN @tblDeletedRefs Removed  
            ON tblReferredTo.ID = Removed.ID;

COMMIT TRAN;

how to extract only the year from the date in sql server 2008?

Simply use

SELECT DATEPART(YEAR, SomeDateColumn)

It will return the portion of a DATETIME type that corresponds to the option you specify. SO DATEPART(YEAR, GETDATE()) would return the current year.

Can pass other time formatters instead of YEAR like

  • DAY
  • MONTH
  • SECOND
  • MILLISECOND
  • ...etc.

How do I redirect users after submit button click?

use

window.location.replace("login.php");

or simply window.location("login.php");

It is better than using window.location.href =, because replace() does not put the originating page in the session history, meaning the user won't get stuck in a never-ending back-button fiasco. If you want to simulate someone clicking on a link, use location.href. If you want to simulate an HTTP redirect, use location.replace.