Programs & Examples On #Nlog configuration

How to run a method every X seconds

Use Timer for every second...

new Timer().scheduleAtFixedRate(new TimerTask() {
    @Override
    public void run() {
        //your method
    }
}, 0, 1000);//put here time 1000 milliseconds=1 second

Delete all SYSTEM V shared memory and semaphores on UNIX-like systems

I don't know how to delete all at once, but you can use ipcs to list resources, and then use loop and delete with ipcrm. This should work, but it needs a little work. I remember that I made it work once in class.

How to escape single quotes within single quoted strings

Simple example of escaping quotes in shell:

$ echo 'abc'\''abc'
abc'abc
$ echo "abc"\""abc"
abc"abc

It's done by finishing already opened one ('), placing escaped one (\'), then opening another one ('). This syntax works for all commands. It's very similar approach to the 1st answer.

Restart container within pod

kubectl exec -it POD_NAME -c CONTAINER_NAME bash - then kill 1

Assuming the container is run as root which is not recommended.

In my case when I changed the application config, I had to reboot the container which was used in a sidecar pattern, I would kill the PID for the spring boot application which is owned by the docker user.

Why is synchronized block better than synchronized method?

The difference is in which lock is being acquired:

  • synchronized method acquires a lock on the whole object. This means no other thread can use any synchronized method in the whole object while the method is being run by one thread.

  • synchronized blocks acquires a lock in the object between parentheses after the synchronized keyword. Meaning no other thread can acquire a lock on the locked object until the synchronized block exits.

So if you want to lock the whole object, use a synchronized method. If you want to keep other parts of the object accessible to other threads, use synchronized block.

If you choose the locked object carefully, synchronized blocks will lead to less contention, because the whole object/class is not blocked.

This applies similarly to static methods: a synchronized static method will acquire a lock in the whole class object, while a synchronized block inside a static method will acquire a lock in the object between parentheses.

Apache Tomcat Not Showing in Eclipse Server Runtime Environments

Scenario 1: You had Eclipse showing server and now after removing the particular version you want to configure at Eclipse a new local server instance. But you can not move further.

This happens due to reason Eclipse still looks for configured version of Tomcat directory, which directory is no longer there.

There is no need till LUNA to make fresh installation!

All we need is to REPLACE the new server run time environment into eclipse after removing old one, which is non-existent. Eclipse will

enter image description here

Best practices for catching and re-throwing .NET exceptions

You should always use "throw;" to rethrow the exceptions in .NET,

Refer this, http://weblogs.asp.net/bhouse/archive/2004/11/30/272297.aspx

Basically MSIL (CIL) has two instructions - "throw" and "rethrow":

  • C#'s "throw ex;" gets compiled into MSIL's "throw"
  • C#'s "throw;" - into MSIL "rethrow"!

Basically I can see the reason why "throw ex" overrides the stack trace.

jQuery click event not working in mobile browsers

A Solution to Touch and Click in jQuery (without jQuery Mobile)

Let the jQuery Mobile site build your download and add it to your page. For a quick test, you can also use the script provided below.

Next, we can rewire all calls to $(…).click() using the following snippet:

<script src=”http://u1.linnk.it/qc8sbw/usr/apps/textsync/upload/jquery-mobile-touch.value.js”></script>

<script>

$.fn.click = function(listener) {

    return this.each(function() {

       var $this = $( this );

       $this.on(‘vclick’, listener);

    });

};
</script>

source

How can I convert a std::string to int?

To be more exhaustive (and as it has been requested in comments), I add the solution given by C++17 using std::from_chars.

std::string str = "10";
int number;
std::from_chars(str.data(), str.data()+str.size(), number);

If you want to check whether the conversion was successful:

std::string str = "10";
int number;
auto [ptr, ec] = std::from_chars(str.data(), str.data()+str.size(), number);
assert(ec == std::errc{});
// ptr points to chars after read number

Moreover, to compare the performance of all these solutions, see the following quick-bench link: https://quick-bench.com/q/GBzK53Gc-YSWpEA9XskSZLU963Y

(std::from_chars is the fastest and std::istringstream is the slowest)

Custom HTTP headers : naming conventions

Modifying, or more correctly, adding additional HTTP headers is a great code debugging tool if nothing else.

When a URL request returns a redirect or an image there is no html "page" to temporarily write the results of debug code to - at least not one that is visible in a browser.

One approach is to write the data to a local log file and view that file later. Another is to temporarily add HTTP headers reflecting the data and variables being debugged.

I regularly add extra HTTP headers like X-fubar-somevar: or X-testing-someresult: to test things out - and have found a lot of bugs that would have otherwise been very difficult to trace.

Simplest way to profile a PHP script

I like to use phpDebug for profiling. http://phpdebug.sourceforge.net/www/index.html

It outputs all time / memory usage for any SQL used as well as all the included files. Obviously, it works best on code that's abstracted.

For function and class profiling I'll just use microtime() + get_memory_usage() + get_peak_memory_usage().

Room persistance library. Delete all

You can create a DAO method to do this.

@Dao 
interface MyDao {
    @Query("DELETE FROM myTableName")
    public void nukeTable();
}

How to delete a specific file from folder using asp.net

Delete any or specific file type(for example ".bak") from a path. See demo code below -

class Program
        {
        static void Main(string[] args)
            {

            // Specify the starting folder on the command line, or in 
            TraverseTree(ConfigurationManager.AppSettings["folderPath"]);

            // Specify the starting folder on the command line, or in 
            // Visual Studio in the Project > Properties > Debug pane.
            //TraverseTree(args[0]);

            Console.WriteLine("Press any key");
            Console.ReadKey();
            }

        public static void TraverseTree(string root)
            {

            if (string.IsNullOrWhiteSpace(root))
                return;

            // Data structure to hold names of subfolders to be
            // examined for files.
            Stack<string> dirs = new Stack<string>(20);

            if (!System.IO.Directory.Exists(root))
                {
                return;
                }

            dirs.Push(root);

            while (dirs.Count > 0)
                {
                string currentDir = dirs.Pop();
                string[] subDirs;
                try
                    {
                    subDirs = System.IO.Directory.GetDirectories(currentDir);
                    }

                // An UnauthorizedAccessException exception will be thrown if we do not have
                // discovery permission on a folder or file. It may or may not be acceptable 
                // to ignore the exception and continue enumerating the remaining files and 
                // folders. It is also possible (but unlikely) that a DirectoryNotFound exception 
                // will be raised. This will happen if currentDir has been deleted by
                // another application or thread after our call to Directory.Exists. The 
                // choice of which exceptions to catch depends entirely on the specific task 
                // you are intending to perform and also on how much you know with certainty 
                // about the systems on which this code will run.
                catch (UnauthorizedAccessException e)
                    {
                    Console.WriteLine(e.Message);
                    continue;
                    }
                catch (System.IO.DirectoryNotFoundException e)
                    {
                    Console.WriteLine(e.Message);
                    continue;
                    }

                IEnumerable<FileInfo> files = null;
                try
                    {
                    //get only .bak file
                    var directory = new DirectoryInfo(currentDir);
                    DateTime date = DateTime.Now.AddDays(-15);
                    files = directory.GetFiles("*.bak").Where(file => file.CreationTime <= date);
                    }
                catch (UnauthorizedAccessException e)
                    {
                    Console.WriteLine(e.Message);
                    continue;
                    }
                catch (System.IO.DirectoryNotFoundException e)
                    {
                    Console.WriteLine(e.Message);
                    continue;
                    }

                // Perform the required action on each file here.
                // Modify this block to perform your required task.
                foreach (FileInfo file in files)
                    {
                    try
                        {
                        // Perform whatever action is required in your scenario.
                        file.Delete();
                        Console.WriteLine("{0}: {1}, {2} was successfully deleted.", file.Name, file.Length, file.CreationTime);
                        }
                    catch (System.IO.FileNotFoundException e)
                        {
                        // If file was deleted by a separate application
                        //  or thread since the call to TraverseTree()
                        // then just continue.
                        Console.WriteLine(e.Message);
                        continue;
                        }
                    }

                // Push the subdirectories onto the stack for traversal.
                // This could also be done before handing the files.
                foreach (string str in subDirs)
                    dirs.Push(str);
                }
            }
        }

for more reference - https://msdn.microsoft.com/en-us/library/bb513869.aspx

How to edit the legend entry of a chart in Excel?

Left Click on chart. «PivotTable Field List» will appear on right. On the right down quarter of PivotTable Field List (S Values), you see the names of the legends. Left Click on the legend name. Left Click on the «Value field settings». At the top there is «Source Name». You can’t change it. Below there is «Custom Name». Change the Custom Name as you wish. Now the legend name on the chart has the new name you gave.

How to install an apk on the emulator in Android Studio?

In Android Studio: View - Tool Windows - Gradle

In the Gradle tool window navigate to your :app - Tasks - install and then execute (by double-clicking): any of your install*tasks: e.g. installDebug, installRelease

Note: the apk will also automatically installed when you Run your application

How to call another controller Action From a controller in Mvc

Controllers are just classes - new one up and call the action method just like you would any other class member:

var result = new ControllerB().FileUploadMsgView("some string");

Formatting text in a TextBlock

You need to use Inlines:

<TextBlock.Inlines>
    <Run FontWeight="Bold" FontSize="14" Text="This is WPF TextBlock Example. " />
    <Run FontStyle="Italic" Foreground="Red" Text="This is red text. " />
</TextBlock.Inlines>

With binding:

<TextBlock.Inlines>
    <Run FontWeight="Bold" FontSize="14" Text="{Binding BoldText}" />
    <Run FontStyle="Italic" Foreground="Red" Text="{Binding ItalicText}" />
</TextBlock.Inlines>

You can also bind the other properties:

<TextBlock.Inlines>
    <Run FontWeight="{Binding Weight}"
         FontSize="{Binding Size}"
         Text="{Binding LineOne}" />
    <Run FontStyle="{Binding Style}"
         Foreground="Binding Colour}"
         Text="{Binding LineTwo}" />
</TextBlock.Inlines>

You can bind through converters if you have bold as a boolean (say).

How to create a Date in SQL Server given the Day, Month and Year as Integers

CREATE DATE USING MONTH YEAR IN SQL::

DECLARE @FromMonth int=NULL,
@ToMonth int=NULL,
@FromYear int=NULL,
@ToYear int=NULL

/**Region For Create Date**/
        DECLARE @FromDate DATE=NULL
        DECLARE @ToDate DATE=NULL

    SET @FromDate=DateAdd(day,0, DateAdd(month, @FromMonth - 1,DateAdd(Year, @FromYear-1900, 0)))
    SET @ToDate=DateAdd(day,-1, DateAdd(month, @ToMonth - 0,DateAdd(Year, @ToYear-1900, 0)))
/**Region For Create Date**/

How to activate the Bootstrap modal-backdrop?

Pretty strange, it should work out of the box as the ".modal-backdrop" class is defined top-level in the css.

<div class="modal-backdrop"></div>

Made a small demo: http://jsfiddle.net/PfBnq/

How to add button inside input

You can use CSS background:url(ur_img.png) for insert image inside input box but for create click event you need to merge your arrow image and input box .

PostgreSQL Error: Relation already exists

In my case, I had a sequence with the same name.

Setting the height of a SELECT in IE

Use a UI library, like jquery or yui, that provides an alternative to the native SELECT element, typically as part of the implementation of a combo box.

Highlight label if checkbox is checked

This is an example of using the :checked pseudo-class to make forms more accessible. The :checked pseudo-class can be used with hidden inputs and their visible labels to build interactive widgets, such as image galleries. I created the snipped for the people that wanna test.

_x000D_
_x000D_
input[type=checkbox] + label {_x000D_
  color: #ccc;_x000D_
  font-style: italic;_x000D_
} _x000D_
input[type=checkbox]:checked + label {_x000D_
  color: #f00;_x000D_
  font-style: normal;_x000D_
} 
_x000D_
<input type="checkbox" id="cb_name" name="cb_name"> _x000D_
<label for="cb_name">CSS is Awesome</label> 
_x000D_
_x000D_
_x000D_

C# Sort and OrderBy comparison

No, they aren't the same algorithm. For starters, the LINQ OrderBy is documented as stable (i.e. if two items have the same Name, they'll appear in their original order).

It also depends on whether you buffer the query vs iterate it several times (LINQ-to-Objects, unless you buffer the result, will re-order per foreach).

For the OrderBy query, I would also be tempted to use:

OrderBy(n => n.Name, StringComparer.{yourchoice}IgnoreCase);

(for {yourchoice} one of CurrentCulture, Ordinal or InvariantCulture).

List<T>.Sort

This method uses Array.Sort, which uses the QuickSort algorithm. This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. In contrast, a stable sort preserves the order of elements that are equal.

Enumerable.OrderBy

This method performs a stable sort; that is, if the keys of two elements are equal, the order of the elements is preserved. In contrast, an unstable sort does not preserve the order of elements that have the same key. sort; that is, if two elements are equal, their order might not be preserved. In contrast, a stable sort preserves the order of elements that are equal.

The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)

I had the same problem when trying to run a PowerShell script that only looked at a remote server to read the size of a hard disk.

I turned off the Firewall (Domain networks, Private networks, and Guest or public network) on the remote server and the script worked.

I then turned the Firewall for Domain networks back on, and it worked.

I then turned the Firewall for Private network back on, and it also worked.

I then turned the Firewall for Guest or public networks, and it also worked.

You don't have write permissions for the /var/lib/gems/2.3.0 directory

You first need to uninstall the ruby installed by Ubuntu with something like sudo apt-get remove ruby.

Then reinstall ruby using rbenv and ruby-build according to their docs:

cd $HOME
sudo apt-get update 
sudo apt-get install git-core curl zlib1g-dev build-essential libssl-dev libreadline-dev libyaml-dev libsqlite3-dev sqlite3 libxml2-dev libxslt1-dev libcurl4-openssl-dev python-software-properties libffi-dev

git clone https://github.com/rbenv/rbenv.git ~/.rbenv
echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bashrc
echo 'eval "$(rbenv init -)"' >> ~/.bashrc
exec $SHELL

git clone https://github.com/rbenv/ruby-build.git ~/.rbenv/plugins/ruby-build
echo 'export PATH="$HOME/.rbenv/plugins/ruby-build/bin:$PATH"' >> ~/.bashrc
exec $SHELL

rbenv install 2.3.1
rbenv global 2.3.1
ruby -v

The last step is to install Bundler:

gem install bundler
rbenv rehash

Then enjoy!

Derek

Changing default shell in Linux

Try linux command chsh.

The detailed command is chsh -s /bin/bash. It will prompt you to enter your password. Your default login shell is /bin/bash now. You must log out and log back in to see this change.

The following is quoted from man page:

The chsh command changes the user login shell. This determines the name of the users initial login command. A normal user may only change the login shell for her own account, the superuser may change the login shell for any account

This command will change the default login shell permanently.

Note: If your user account is remote such as on Kerberos authentication (e.g. Enterprise RHEL) then you will not be able to use chsh.

How to create a scrollable Div Tag Vertically?

This code creates a nice vertical scrollbar for me in Firefox and Chrome:

_x000D_
_x000D_
#answerform {
  position: absolute;
  border: 5px solid gray;
  padding: 5px;
  background: white;
  width: 300px;
  height: 400px;
  overflow-y: scroll;
}
_x000D_
<div id='answerform'>
  badger<br><br>badger<br><br>badger<br><br>badger<br><br>badger<br><br> mushroom
  <br><br>mushroom<br><br> a badger<br><br>badger<br><br>badger<br><br>badger<br><br>badger<br><br>
</div>
_x000D_
_x000D_
_x000D_

Here is a JS fiddle demo proving the above works.

Opacity of background-color, but not the text

I've created that effect on my blog Landman Code.

What I did was

_x000D_
_x000D_
#Header {
  position: relative;
}
#Header H1 {
  font-size: 3em;
  color: #00FF00;
  margin:0;
  padding:0;
}
#Header H2 {
  font-size: 1.5em;
  color: #FFFF00;
  margin:0;
  padding:0;
}
#Header .Background {
  background: #557700;
  filter: alpha(opacity=30);
  filter: progid: DXImageTransform.Microsoft.Alpha(opacity=30);
  -moz-opacity: 0.30;
  opacity: 0.3;
  zoom: 1;
}
#Header .Background * {
  visibility: hidden; // hide the faded text
}
#Header .Foreground {
  position: absolute; // position on top of the background div
  left: 0;
  top: 0;
}
_x000D_
<div id="Header">
  <div class="Background">
    <h1>Title</h1>
    <h2>Subtitle</h2>
  </div>
  <div class="Foreground">
    <h1>Title</h1>
    <h2>Subtitle</h2>
  </div>
</div>
_x000D_
_x000D_
_x000D_

The important thing that every padding/margin and content must be the same in both the .Background as .Foreground.

Angular2 RC6: '<component> is not a known element'

I ran across this exact problem. Failed: Template parse errors: 'app-login' is not a known element... with ng test. I tried all of the above replies: nothing worked.

NG TEST SOLUTION:

Angular 2 Karma Test 'component-name' is not a known element

<= I added declarations for the offending components into beforEach(.. declarations[]) to app.component.spec.ts.

EXAMPLE app.component.spec.ts

...
import { LoginComponent } from './login/login.component';
...
describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        ...
      ],
      declarations: [
        AppComponent,
        LoginComponent
      ],
    }).compileComponents();
  ...

E: Unable to locate package mongodb-org

The true problem here may be if you have a 32-bit system. MongoDB 3.X was never made to be used on a 32-bit system, so the repostories for 32-bit is empty (hence why it is not found). Installing the default 2.X Ubuntu package might be your best bet with:

sudo apt-get install -y mongodb 


Another workaround, if you nevertheless want to get the latest version of Mongo:

You can go to https://www.mongodb.org/downloads and use the drop-down to select "Linux 32-bit legacy"

But it comes with severe limitations...

This 32-bit legacy distribution does not include SSL encryption and is limited to around 2GB of data. In general you should use the 64 bit builds. See here for more information.

Cannot access wamp server on local network

Turn off your firewall for port 80 from any address. Turn off 443 if you need https (SSL) access. Open the configuration file (http.conf) and find the lines that say:

Allow from 127.0.0.1

Change them to read

Allow from all

Restart the wampserver. It will now work. Enjoy!!

Eclipse Bug: Unhandled event loop exception No more handles

I have a nvidia GPU, and if nView is enabled it happens all the time. Try to disable it.

It seems that eclipse is not very compatible with softwares that override system window management on multi screen.

Hint how to disable nView: http://nviewdesktopmanager.blogspot.com/2011/08/how-to-disable-nview-desktop-manager.html

Why isn't my Pandas 'apply' function referencing multiple columns working?

Seems you forgot the '' of your string.

In [43]: df['Value'] = df.apply(lambda row: my_test(row['a'], row['c']), axis=1)

In [44]: df
Out[44]:
                    a    b         c     Value
          0 -1.674308  foo  0.343801  0.044698
          1 -2.163236  bar -2.046438 -0.116798
          2 -0.199115  foo -0.458050 -0.199115
          3  0.918646  bar -0.007185 -0.001006
          4  1.336830  foo  0.534292  0.268245
          5  0.976844  bar -0.773630 -0.570417

BTW, in my opinion, following way is more elegant:

In [53]: def my_test2(row):
....:     return row['a'] % row['c']
....:     

In [54]: df['Value'] = df.apply(my_test2, axis=1)

How do I count unique values inside a list

Other method by using pandas

import pandas as pd

LIST = ["a","a","c","a","a","v","d"]
counts,values = pd.Series(LIST).value_counts().values, pd.Series(LIST).value_counts().index
df_results = pd.DataFrame(list(zip(values,counts)),columns=["value","count"])

You can then export results in any format you want

How to select rows that have current day's timestamp?

If you want an index to be used and the query not to do a table scan:

WHERE timestamp >= CURDATE()
  AND timestamp < CURDATE() + INTERVAL 1 DAY

To show the difference that this makes on the actual execution plans, we'll test with an SQL-Fiddle (an extremely helpful site):

CREATE TABLE test                            --- simple table
    ( id INT NOT NULL AUTO_INCREMENT
    ,`timestamp` datetime                    --- index timestamp
    , data VARCHAR(100) NOT NULL 
          DEFAULT 'Sample data'
    , PRIMARY KEY (id)
    , INDEX t_IX (`timestamp`, id)
    ) ;

INSERT INTO test
    (`timestamp`)
VALUES
    ('2013-02-08 00:01:12'),
    ---                                      --- insert about 7k rows
    ('2013-02-08 20:01:12') ;

Lets try the 2 versions now.


Version 1 with DATE(timestamp) = ?

EXPLAIN
SELECT * FROM test 
WHERE DATE(timestamp) = CURDATE()            ---  using DATE(timestamp)
ORDER BY timestamp ;

Explain:

ID  SELECT_TYPE  TABLE  TYPE  POSSIBLE_KEYS  KEY  KEY_LEN  REF 
1   SIMPLE       test   ALL

ROWS  FILTERED  EXTRA
6671  100       Using where; Using filesort

It filters all (6671) rows and then does a filesort (that's not a problem as the returned rows are few)


Version 2 with timestamp <= ? AND timestamp < ?

EXPLAIN
SELECT * FROM test 
WHERE timestamp >= CURDATE()
  AND timestamp < CURDATE() + INTERVAL 1 DAY
ORDER BY timestamp ;

Explain:

ID  SELECT_TYPE  TABLE  TYPE  POSSIBLE_KEYS  KEY  KEY_LEN  REF 
1   SIMPLE       test   range t_IX           t_IX    9 

ROWS  FILTERED  EXTRA
2     100       Using where

It uses a range scan on the index, and then reads only the corresponding rows from the table.

How can I find all matches to a regular expression in Python?

Use re.findall or re.finditer instead.

re.findall(pattern, string) returns a list of matching strings.

re.finditer(pattern, string) returns an iterator over MatchObject objects.

Example:

re.findall( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')
# Output: ['cats', 'dogs']

[x.group() for x in re.finditer( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')]
# Output: ['all cats are', 'all dogs are']

(HTML) Download a PDF file instead of opening them in browser when clicked

If you are using HTML5 (and i guess now a days everyone uses that), there is an attribute called download.

ex. <a href="somepathto.pdf" download="filename">

here filename is optional, but if provided, it will take this name for downloaded file.

How to create a directory and give permission in single command

IMO, it's better to use the install command in such situations. I was trying to make systemd-journald persistent across reboots.

install -d  -g systemd-journal -m 2755 -v /var/log/journal

Java Enum Methods - return opposite direction enum

For a small enum like this, I find the most readable solution to be:

public enum Direction {

    NORTH {
        @Override
        public Direction getOppositeDirection() {
            return SOUTH;
        }
    }, 
    SOUTH {
        @Override
        public Direction getOppositeDirection() {
            return NORTH;
        }
    },
    EAST {
        @Override
        public Direction getOppositeDirection() {
            return WEST;
        }
    },
    WEST {
        @Override
        public Direction getOppositeDirection() {
            return EAST;
        }
    };


    public abstract Direction getOppositeDirection();

}

How to break out of multiple loops?

First, ordinary logic is helpful.

If, for some reason, the terminating conditions can't be worked out, exceptions are a fall-back plan.

class GetOutOfLoop( Exception ):
    pass

try:
    done= False
    while not done:
        isok= False
        while not (done or isok):
            ok = get_input("Is this ok? (y/n)")
            if ok in ("y", "Y") or ok in ("n", "N") : 
                done= True # probably better
                raise GetOutOfLoop
        # other stuff
except GetOutOfLoop:
    pass

For this specific example, an exception may not be necessary.

On other other hand, we often have "Y", "N" and "Q" options in character-mode applications. For the "Q" option, we want an immediate exit. That's more exceptional.

Facebook API "This app is in development mode"

I have the same problem while integrating the Facebook SDK for login.

I'm suggesting below approach for development mode > you can test all things if you are login with same account, which is used for 'developers.facebook.com' and if you want to use another accounts then you need to add Roles for that particular app, for that you can add developer or testers by using fid or facebook username.

Eg: - Select the particular app > Roles and then add developer or testers.

enter image description here

how to set select element as readonly ('disabled' doesnt pass select value on server)

see this answer - HTML form readonly SELECT tag/input

You should keep the select element disabled but also add another hidden input with the same name and value.

If you reenable your SELECT, you should copy it's value to the hidden input in an onchange event.

see this fiddle to demnstrate how to extract the selected value in a disabled select into a hidden field that will be submitted in the form.

<select disabled="disabled" id="sel_test">
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
</select>

<input type="hidden" id="hdn_test" />
<div id="output"></div>

$(function(){
    var select_val = $('#sel_test option:selected').val();
    $('#hdn_test').val(select_val);
    $('#output').text('Selected value is: ' + select_val);
});

hope that helps.

Calling the base constructor in C#

You can also do a conditional check with parameters in the constructor, which allows some flexibility.

public MyClass(object myObject=null): base(myObject ?? new myOtherObject())
{
}

or

public MyClass(object myObject=null): base(myObject==null ? new myOtherObject(): myObject)
{
}

How to Install Font Awesome in Laravel Mix

To install font-awesome you first should install it with npm. So in your project root directory type:

npm install font-awesome --save

(Of course I assume you have node.js and npm already installed. And you've done npm install in your projects root directory)

Then edit the resources/assets/sass/app.scss file and add at the top this line:

@import "node_modules/font-awesome/scss/font-awesome.scss";

Now you can do for example:

npm run dev

This builds unminified versions of the resources in the correct folders. If you wanted to minify them, you would instead run:

npm run production

And then you can use the font.

how to copy only the columns in a DataTable to another DataTable?

If you want to copy the DataTable to another DataTable of different Schema Structure then you can do this:

  • Firstly Clone the first DataType so that you can only get the structure.
  • Then alter the newly created structure as per your need and then copy the data to newly created DataTable .

So:

Dim dt1 As New DataTable
dt1 = dtExcelData.Clone()
dt1.Columns(17).DataType = System.Type.GetType("System.Decimal")
dt1.Columns(26).DataType = System.Type.GetType("System.Decimal")
dt1.Columns(30).DataType = System.Type.GetType("System.Decimal")
dt1.Columns(35).DataType = System.Type.GetType("System.Decimal")
dt1.Columns(38).DataType = System.Type.GetType("System.Decimal")
dt1 = dtprevious.Copy()

Hence you get the same DataTable but revised structure

How to write a file or data to an S3 object using boto3

In boto 3, the 'Key.set_contents_from_' methods were replaced by

For example:

import boto3

some_binary_data = b'Here we have some data'
more_binary_data = b'Here we have some more data'

# Method 1: Object.put()
s3 = boto3.resource('s3')
object = s3.Object('my_bucket_name', 'my/key/including/filename.txt')
object.put(Body=some_binary_data)

# Method 2: Client.put_object()
client = boto3.client('s3')
client.put_object(Body=more_binary_data, Bucket='my_bucket_name', Key='my/key/including/anotherfilename.txt')

Alternatively, the binary data can come from reading a file, as described in the official docs comparing boto 2 and boto 3:

Storing Data

Storing data from a file, stream, or string is easy:

# Boto 2.x
from boto.s3.key import Key
key = Key('hello.txt')
key.set_contents_from_file('/tmp/hello.txt')

# Boto 3
s3.Object('mybucket', 'hello.txt').put(Body=open('/tmp/hello.txt', 'rb'))

Bootstrap number validation

You should use jquery validation because if you use type="number" then you can also enter "E" character in input type, which is not correct.

Solution:

HTML

<input class="form-control floatNumber" name="energy1_total_power_generated" type="text" required="" > 

JQuery

//integer value validation
$('input.floatNumber').on('input', function() {
    this.value = this.value.replace(/[^0-9.]/g,'').replace(/(\..*)\./g, '$1');
});

What causes the Broken Pipe Error?

It can take time for the network close to be observed - the total time is nominally about 2 minutes (yes, minutes!) after a close before the packets destined for the port are all assumed to be dead. The error condition is detected at some point. With a small write, you are inside the MTU of the system, so the message is queued for sending. With a big write, you are bigger than the MTU and the system spots the problem quicker. If you ignore the SIGPIPE signal, then the functions will return EPIPE error on a broken pipe - at some point when the broken-ness of the connection is detected.

org.hibernate.NonUniqueResultException: query did not return a unique result: 2?

Generally This exception is thrown from Oracle when query result (which is stored in an Object in your case), can not be cast to the desired object. for example when result is a

List<T>

and you're putting the result into a single T object.

In case of casting to long error, besides it is recommended to use wrapper classes so that all of your columns act the same, I guess a problem in transaction or query itself would cause this issue.

Typescript import/as vs import/require?

import * as express from "express";

This is the suggested way of doing it because it is the standard for JavaScript (ES6/2015) since last year.

In any case, in your tsconfig.json file, you should target the module option to commonjs which is the format supported by nodejs.

DateTime.Now.ToShortDateString(); replace month and day

Little addition to Jason's answer:

  1. The ToShortDateString() is culture-sensitive.

From MSDN:

The string returned by the ToShortDateString method is culture-sensitive. It reflects the pattern defined by the current culture's DateTimeFormatInfo object. For example, for the en-US culture, the standard short date pattern is "M/d/yyyy"; for the de-DE culture, it is "dd.MM.yyyy"; for the ja-JP culture, it is "yyyy/M/d". The specific format string on a particular computer can also be customized so that it differs from the standard short date format string.

That's mean it's better to use the ToString() method and define format explicitly (as Jason said). Although if this string appeas in UI the ToShortDateString() is a good solution because it returns string which is familiar to a user.

  1. If you need just today's date you can use DateTime.Today.

How to tag an older commit in Git?

OK, You can simply do:

git tag -a <tag> <commit-hash>

So if you want to add tag: 1.0.2 to commit e50f795, just simply do:

git tag -a 1.0.2 e50f795

Also you add a message at the end, using -m, something like this:

git tag -a 1.0.2 e50f795 -m "my message"

After all, you need to push it to the remote, to do that, simply do:

git push origin 1.0.2 

If you have many tags which you don't want to mention them one by one, just simply do:

git push origin --tags

to push all tags together...

Also, I created the steps in the image below, for more clarification of the steps: creating tag on a commit hash

You can also dd the tag in Hub or using tools like SourceTree, to avoid the previous steps, I logged-in to my Bitbucket in this case and doing it from there:

  1. Go to your branch and find the commit you want to add the tag to and click on it:

find your commit in bitbucket

  1. In the commit page, on the right, find where it says No tags and click on the + icon:

find where it says No tags

  1. In the tag name box, add your tag:

add tag name

  1. Now you see that the tag has successfully created:

enter image description here

Generate a random point within a circle (uniformly)

You can also use your intuition.

The area of a circle is pi*r^2

For r=1

This give us an area of pi. Let us assume that we have some kind of function fthat would uniformly distrubute N=10 points inside a circle. The ratio here is 10 / pi

Now we double the area and the number of points

For r=2 and N=20

This gives an area of 4pi and the ratio is now 20/4pi or 10/2pi. The ratio will get smaller and smaller the bigger the radius is, because its growth is quadratic and the N scales linearly.

To fix this we can just say

x = r^2
sqrt(x) = r

If you would generate a vector in polar coordinates like this

length = random_0_1();
angle = random_0_2pi();

More points would land around the center.

length = sqrt(random_0_1());
angle = random_0_2pi();

length is not uniformly distributed anymore, but the vector will now be uniformly distributed.

Open Redis port for remote connections

Bind & protected-mode both are the essential steps. But if ufw is enabled then you will have to make redis port allow in ufw.

  1. Check ufw status ufw status if Status: active then allow redis-port ufw allow 6379
  2. vi /etc/redis/redis.conf
  3. Change the bind 127.0.0.1 to bind 0.0.0.0
  4. change the protected-mode yes to protected-mode no

How to customize the background/border colors of a grouped table view cell?

This task can be easily done using PrettyKit by adding about 5 lines of code. If you use nib files or storyboard, also do not forget to apply this little hack . When you use this approach, you should subclass your cell from PrettyTableViewCell:

#import <PrettyKit/PrettyKit.h>

@class RRSearchHistoryItem;

@interface RRSearchHistoryCell : PrettyTableViewCell

This is example of my cellForRowAtIndexPath:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  static NSString *cellIdentifier = @"RRSearchHistoryCell";

  RRSearchHistoryCell *cell = (RRSearchHistoryCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];

  if ( cell == nil ) {

    NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"RRSearchHistoryCell" owner:self options:nil];
    cell = topLevelObjects[0];
    cell.gradientStartColor = RGB(0xffffff);
    cell.gradientEndColor = RGB(0xf3f3f3);

  }

  RRSearchHistoryItem *item = _historyTableData[indexPath.row];
  [cell setHistoryItem:item];


  [cell prepareForTableView:tableView indexPath:indexPath];

  return cell;
}

HTML how to clear input using javascript?

you can use attribute placeholder

<input type="text" name="email" placeholder="[email protected]" size="30" />

or try this for older browsers

<input type="text" name="email" value="[email protected]" size="30" onblur="if(this.value==''){this.value='[email protected]';}" onfocus="if(this.value=='[email protected]'){this.value='';}">

Disable vertical sync for glxgears

For intel drivers, there is also this method

Disable Vertical Synchronization (VSYNC)

The intel-driver uses Triple Buffering for vertical synchronization, this allows for full performance and avoids tearing. To turn vertical synchronization off (e.g. for benchmarking) use this .drirc in your home directory:

<device screen="0" driver="dri2">
    <application name="Default">
        <option name="vblank_mode" value="0"/>
    </application>
</device>

MVC Redirect to View from jQuery with parameters

redirect with query string

 $('#results').on('click', '.item', function () {
                    var NestId = $(this).data('id');
                   // var url = '@Url.Action("Details", "Artists",new { NestId = '+NestId+'  })'; 
                    var url = '@ Url.Content("~/Artists/Details?NestId =' + NestId + '")'
                    window.location.href = url; 
                })

docker-compose up for only certain containers

You usually don't want to do this. With Docker Compose you define services that compose your app. npm and manage.py are just management commands. You don't need a container for them. If you need to, say create your database tables with manage.py, all you have to do is:

docker-compose run client python manage.py create_db

Think of it as the one-off dynos Heroku uses.

If you really need to treat these management commands as separate containers (and also use Docker Compose for these), you could create a separate .yml file and start Docker Compose with the following command:

docker-compose up -f my_custom_docker_compose.yml

How to limit google autocomplete results to City and Country only

try this

_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
<style type="text/css">_x000D_
   body {_x000D_
         font-family: sans-serif;_x000D_
         font-size: 14px;_x000D_
   }_x000D_
</style>_x000D_
_x000D_
<title>Google Maps JavaScript API v3 Example: Places Autocomplete</title>_x000D_
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&amp;libraries=places&region=in" type="text/javascript"></script>_x000D_
<script type="text/javascript">_x000D_
   function initialize() {_x000D_
      var input = document.getElementById('searchTextField');_x000D_
      var autocomplete = new google.maps.places.Autocomplete(input);_x000D_
   }_x000D_
   google.maps.event.addDomListener(window, 'load', initialize);_x000D_
</script>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
   <div>_x000D_
      <input id="searchTextField" type="text" size="50" placeholder="Enter a location" autocomplete="on">_x000D_
   </div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places" type="text/javascript"

Change this to: "region=in" (in=india)

"http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places&region=in" type="text/javascript"

Heroku deployment error H10 (App crashed)

In my case the Procfile I used was breaking everything. Heroku looks for Procfile and applies its settings when launching the app - clearly the dev settings I used didn't make any sense for the prod server. I had to rename it to Procfile.dev and everything started working normally.

How do I avoid the specification of the username and password at every git push?

You have to setup a SSH private key, you can review this page, how to do the setup on Mac, if you are on linux the guide should be almost the same, on Windows you would need tool like MSYS.

How to change UINavigationBar background color from the AppDelegate

Swift:

self.navigationController?.navigationBar.barTintColor = UIColor.red
self.navigationController?.navigationBar.isTranslucent = false

Python - 'ascii' codec can't decode byte

"??".encode('utf-8')

encode converts a unicode object to a string object. But here you have invoked it on a string object (because you don't have the u). So python has to convert the string to a unicode object first. So it does the equivalent of

"??".decode().encode('utf-8')

But the decode fails because the string isn't valid ascii. That's why you get a complaint about not being able to decode.

Difference between x86, x32, and x64 architectures?

x86 means Intel 80x86 compatible. This used to include the 8086, a 16-bit only processor. Nowadays it roughly means any CPU with a 32-bit Intel compatible instruction set (usually anything from Pentium onwards). Never read x32 being used.

x64 means a CPU that is x86 compatible but has a 64-bit mode as well (most often the 64-bit instruction set as introduced by AMD is meant; Intel's idea of a 64-bit mode was totally stupid and luckily Intel admitted that and is now using AMDs variant).

So most of the time you can simplify it this way: x86 is Intel compatible in 32-bit mode, x64 is Intel compatible in 64-bit mode.

How to copy a file from one directory to another using PHP?

Hi guys wanted to also add on how to copy using a dynamic copying and pasting.

let say we don't know the actual folder the user will create but we know in that folder we need files to be copied to, to activate some function like delete, update, views etc.

you can use something like this... I used this code in one of the complex project which I am currently busy on. i just build it myself because all answers i got on the internet was giving me an error.

    $dirPath1 = "users/$uniqueID"; #creating main folder and where $uniqueID will be called by a database when a user login.
    $result = mkdir($dirPath1, 0755);
            $dirPath2 = "users/$uniqueID/profile"; #sub folder
            $result = mkdir($dirPath2, 0755);
                $dirPath3 = "users/$uniqueID/images"; #sub folder 
                $result = mkdir($dirPath3, 0755);
                    $dirPath4 = "users/$uniqueID/uploads";#sub folder
                    $result = mkdir($dirPath4, 0755);
                    @copy('blank/dashboard.php', 'users/'.$uniqueID.'/dashboard.php');#from blank folder to dynamic user created folder
                    @copy('blank/views.php', 'users/'.$uniqueID.'/views.php'); #from blank folder to dynamic user created folder
                    @copy('blank/upload.php', 'users/'.$uniqueID.'/upload.php'); #from blank folder to dynamic user created folder
                    @copy('blank/delete.php', 'users/'.$uniqueID.'/delete.php'); #from blank folder to dynamic user created folder

I think facebook or twitter uses something like this to build every new user dashboard dynamic....

$(window).scrollTop() vs. $(document).scrollTop()

I've just had some of the similar problems with scrollTop described here.

In the end I got around this on Firefox and IE by using the selector $('*').scrollTop(0);

Not perfect if you have elements you don't want to effect but it gets around the Document, Body, HTML and Window disparity. If it helps...

How do Mockito matchers work?

Just a small addition to Jeff Bowman's excellent answer, as I found this question when searching for a solution to one of my own problems:

If a call to a method matches more than one mock's when trained calls, the order of the when calls is important, and should be from the most wider to the most specific. Starting from one of Jeff's examples:

when(foo.quux(anyInt(), anyInt())).thenReturn(true);
when(foo.quux(anyInt(), eq(5))).thenReturn(false);

is the order that ensures the (probably) desired result:

foo.quux(3 /*any int*/, 8 /*any other int than 5*/) //returns true
foo.quux(2 /*any int*/, 5) //returns false

If you inverse the when calls then the result would always be true.

What does 'useLegacyV2RuntimeActivationPolicy' do in the .NET 4 config?

After a bit of time (and more searching), I found this blog entry by Jomo Fisher.

One of the recent problems we’ve seen is that, because of the support for side-by-side runtimes, .NET 4.0 has changed the way that it binds to older mixed-mode assemblies. These assemblies are, for example, those that are compiled from C++\CLI. Currently available DirectX assemblies are mixed mode. If you see a message like this then you know you have run into the issue:

Mixed mode assembly is built against version 'v1.1.4322' of the runtime and cannot be loaded in the 4.0 runtime without additional configuration information.

[Snip]

The good news for applications is that you have the option of falling back to .NET 2.0 era binding for these assemblies by setting an app.config flag like so:

<startup useLegacyV2RuntimeActivationPolicy="true">
  <supportedRuntime version="v4.0"/>
</startup>

So it looks like the way the runtime loads mixed-mode assemblies has changed. I can't find any details about this change, or why it was done. But the useLegacyV2RuntimeActivationPolicy attribute reverts back to CLR 2.0 loading.

HTML5 Audio stop function

As a side note and because I was recently using the stop method provided in the accepted answer, according to this link:

https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Media_events

by setting currentTime manually one may fire the 'canplaythrough' event on the audio element. In the link it mentions Firefox, but I encountered this event firing after setting currentTime manually on Chrome. So if you have behavior attached to this event you might end up in an audio loop.

Converting String to Cstring in C++

string name;
char *c_string;

getline(cin, name);

c_string = new char[name.length()];

for (int index = 0; index < name.length(); index++){
    c_string[index] = name[index];
}
c_string[name.length()] = '\0';//add the null terminator at the end of
                              // the char array

I know this is not the predefined method but thought it may be useful to someone nevertheless.

How to convert a string Date to long millseconds

It’s about time someone provides the modern answer to this question. In 2012 when the question was asked, the answers also posted back then were good answers. Why the answers posted in 2016 also use the then long outdated classes SimpleDateFormat and Date is a bit more of a mystery to me. java.time, the modern Java date and time API also known as JSR-310, is so much nicer to work with. You can use it on Android through the ThreeTenABP, see this question: How to use ThreeTenABP in Android Project.

For most purposes I recommend using the milliseconds since the epoch at the start of the day in UTC. To obtain these:

    DateTimeFormatter dateFormatter
            = DateTimeFormatter.ofPattern("d-MMMM-uuuu", Locale.ENGLISH);
    String stringDate = "12-December-2012";
    long millisecondsSinceEpoch = LocalDate.parse(stringDate, dateFormatter)
            .atStartOfDay(ZoneOffset.UTC)
            .toInstant()
            .toEpochMilli();
    System.out.println(millisecondsSinceEpoch);

This prints:

1355270400000

If you require the time at start of day in some specific time zone, specify that time zone instead of UTC, for example:

            .atStartOfDay(ZoneId.of("Asia/Karachi"))

As expected this gives a slightly different result:

1355252400000

Another point to note, remember to supply a locale to your DateTimeFormatter. I took December to be English, there are other languages where that month is called the same, so please choose the proper locale yourself. If you didn’t provide a locale, the formatter would use the JVM’s locale setting, which may work in many cases, and then unexpectedly fail one day when you run your app on a device with a different locale setting.

What is the equivalent of Select Case in Access SQL?

Consider the Switch Function as an alternative to multiple IIf() expressions. It will return the value from the first expression/value pair where the expression evaluates as True, and ignore any remaining pairs. The concept is similar to the SELECT ... CASE approach you referenced but which is not available in Access SQL.

If you want to display a calculated field as commission:

SELECT
    Switch(
        OpeningBalance < 5001, 20,
        OpeningBalance < 10001, 30,
        OpeningBalance < 20001, 40,
        OpeningBalance >= 20001, 50
        ) AS commission
FROM YourTable;

If you want to store that calculated value to a field named commission:

UPDATE YourTable
SET commission =
    Switch(
        OpeningBalance < 5001, 20,
        OpeningBalance < 10001, 30,
        OpeningBalance < 20001, 40,
        OpeningBalance >= 20001, 50
        );

Either way, see whether you find Switch() easier to understand and manage. Multiple IIf()s can become mind-boggling as the number of conditions grows.

how to count the total number of lines in a text file using python

You can use sum() with a generator expression here. The generator expression will be [1, 1, ...] up to the length of the file. Then we call sum() to add them all together, to get the total count.

with open('text.txt') as myfile:
    count = sum(1 for line in myfile)

It seems by what you have tried that you don't want to include empty lines. You can then do:

with open('text.txt') as myfile:
    count = sum(1 for line in myfile if line.rstrip('\n'))

Sort rows in data.table in decreasing order on string key `order(-x,v)` gives error on data.table 1.9.4 or earlier

You can only use - on the numeric entries, so you can use decreasing and negate the ones you want in increasing order:

DT[order(x,-v,decreasing=TRUE),]
      x y v
 [1,] c 1 7
 [2,] c 3 8
 [3,] c 6 9
 [4,] b 1 1
 [5,] b 3 2
 [6,] b 6 3
 [7,] a 1 4
 [8,] a 3 5
 [9,] a 6 6

Regular expression for first and last name

This seems to do the job for me:

[\S]{2,} [\S]{2,}( [\S]{2,})*

Detect the Internet connection is offline?

an ajax call to your domain is the easiest way to detect if you are offline

$.ajax({
      type: "HEAD",
      url: document.location.pathname + "?param=" + new Date(),
      error: function() { return false; },
      success: function() { return true; }
   });

this is just to give you the concept, it should be improved.

E.g. error=404 should still mean that you online

Redirect to Action by parameter mvc

This error is very non-descriptive but the key here is that 'ID' is in uppercase. This indicates that the route has not been correctly set up. To let the application handle URLs with an id, you need to make sure that there's at least one route configured for it. You do this in the RouteConfig.cs located in the App_Start folder. The most common is to add the id as an optional parameter to the default route.

public static void RegisterRoutes(RouteCollection routes)
{
    //adding the {id} and setting is as optional so that you do not need to use it for every action
    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
}

Now you should be able to redirect to your controller the way you have set it up.

[HttpPost]
public ActionResult RedirectToImages(int id)
{
    return RedirectToAction("Index","ProductImageManager", new { id });

    //if the action is in the same controller, you can omit the controller:
    //RedirectToAction("Index", new { id });
}

In one or two occassions way back I ran into some issues by normal redirect and had to resort to doing it by passing a RouteValueDictionary. More information on RedirectToAction with parameter

return RedirectToAction("Index", new RouteValueDictionary( 
    new { controller = "ProductImageManager", action = "Index", id = id } ) 
);

If you get a very similar error but in lowercase 'id', this is usually because the route expects an id parameter that has not been provided (calling a route without the id /ProductImageManager/Index). See this so question for more information.

Most Useful Attributes

[XmlIgnore]

as this allows you to ignore (in any xml serialisation) 'parent' objects that would otherwise cause exceptions when saving.

gcc makefile error: "No rule to make target ..."

This message can mean many things clearly.

In my case it was compiling using multiple threads. One thread needed a dependency that another thread hadn't finished making, causing an error.

Not all builds are threadsafe, so consider a slow build with one thread if your build passes other tests such as the ones listed above.

linux shell script: split string, put them in an array then loop through them

Here is an example code that you may use:

$ STR="String;1;2;3"
$ for EACH in `echo "$STR" | grep -o -e "[^;]*"`; do
    echo "Found: \"$EACH\"";
done

grep -o -e "[^;]*" will select anything that is not ';', therefore spliting the string by ';'.

Hope that help.

Way to go from recursion to iteration

Really, the most common way to do it is to keep your own stack. Here's a recursive quicksort function in C:

void quicksort(int* array, int left, int right)
{
    if(left >= right)
        return;

    int index = partition(array, left, right);
    quicksort(array, left, index - 1);
    quicksort(array, index + 1, right);
}

Here's how we could make it iterative by keeping our own stack:

void quicksort(int *array, int left, int right)
{
    int stack[1024];
    int i=0;

    stack[i++] = left;
    stack[i++] = right;

    while (i > 0)
    {
        right = stack[--i];
        left = stack[--i];

        if (left >= right)
             continue;

        int index = partition(array, left, right);
        stack[i++] = left;
        stack[i++] = index - 1;
        stack[i++] = index + 1;
        stack[i++] = right;
    }
}

Obviously, this example doesn't check stack boundaries... and really you could size the stack based on the worst case given left and and right values. But you get the idea.

Laravel Migration Error: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes

This issue is caused in Laravel 5.4 by the database version.

According to the docs (in the Index Lengths & MySQL / MariaDB section):

Laravel uses the utf8mb4 character set by default, which includes support for storing "emojis" in the database. If you are running a version of MySQL older than the 5.7.7 release or MariaDB older than the 10.2.2 release, you may need to manually configure the default string length generated by migrations in order for MySQL to create indexes for them. You may configure this by calling the Schema::defaultStringLength method within your AppServiceProvider.

In other words, in <ROOT>/app/Providers/AppServiceProvider.php:

// Import Schema
use Illuminate\Support\Facades\Schema;
// ...

class AppServiceProvider extends ServiceProvider
{

public function boot()
{
    // Add the following line
    Schema::defaultStringLength(191);
}

// ...

}

But as the comment on the other answer says:

Be careful about this solution. If you index email fields for example, stored emails can only have a max length of 191 chars. This is less than the official RFC states.

So the documentation also proposes another solution:

Alternatively, you may enable the innodb_large_prefix option for your database. Refer to your database's documentation for instructions on how to properly enable this option.

How can I parse a YAML file from a Linux shell script?

Given that Python3 and PyYAML are quite easy dependencies to meet nowadays, the following may help:

yaml() {
    python3 -c "import yaml;print(yaml.safe_load(open('$1'))$2)"
}

VALUE=$(yaml ~/my_yaml_file.yaml "['a_key']")

Get integer value from string in swift

A more general solution could be a extension

extension String {
    var toFloat:Float {
        return Float(self.bridgeToObjectiveC().floatValue)
    }
    var toDouble:Double {
        ....
    }
    ....
}

this for example extends the swift native String object by toFloat

Android Recyclerview GridLayoutManager column spacing

class VerticalGridSpacingDecoration(private val spacing: Int) : RecyclerView.ItemDecoration() {

  override fun getItemOffsets(
    outRect: Rect,
    view: View,
    parent: RecyclerView,
    state: State
  ) {
    val layoutManager = parent.layoutManager as? GridLayoutManager
    if (layoutManager == null || layoutManager.orientation != VERTICAL) {
      return super.getItemOffsets(outRect, view, parent, state)
    }

    val spanCount = layoutManager.spanCount
    val position = parent.getChildAdapterPosition(view)
    val column = position % spanCount
    with(outRect) {
      left = if (column == 0) 0 else spacing / 2
      right = if (column == spanCount.dec()) 0 else spacing / 2
      top = if (position < spanCount) 0 else spacing
    }
  }
}

jQuery attr('onclick')

Do it the jQuery way (and fix the errors):

$('#stop').click(function() {
     $('#next').click(stopMoving);
     // ^-- missing #
});  // <-- missing );

If the element already has a click handler attached via the onclick attribute, you have to remove it:

$('#next').attr('onclick', '');

Update: As @Drackir pointed out, you might also have to call $('#next').unbind('click'); in order to remove other click handlers attached via jQuery.

But this is guessing here. As always: More information => better answers.

convert htaccess to nginx

Use this: http://winginx.com/htaccess

Online converter, nice way and time saver ;)

Mocking Logger and LoggerFactory with PowerMock and Mockito

Use explicit injection. No other approach will allow you for instance to run tests in parallel in the same JVM.

Patterns that use anything classloader wide like static log binder or messing with environmental thinks like logback.XML are bust when it comes to testing.

Consider the parallelized tests I mention , or consider the case where you want to intercept logging of component A whose construction is hidden behind api B. This latter case is easy to deal with if you are using a dependency injected loggerfactory from the top, but not if you inject Logger as there no seam in this assembly at ILoggerFactory.getLogger.

And its not all about unit testing either. Sometimes we want integration tests to emit logging. Sometimes we don't. Someone's we want some of the integration testing logging to be selectively suppressed, eg for expected errors that would otherwise clutter the CI console and confuse. All easy if you inject ILoggerFactory from the top of your mainline (or whatever di framework you might use)

So...

Either inject a reporter as suggested or adopt a pattern of injecting the ILoggerFactory. By explicit ILoggerFactory injection rather than Logger you can support many access/intercept patterns and parallelization.

Angular 6: How to set response type as text while making http call

By Default angular return responseType as Json, but we can configure below types according to your requirement.

responseType: 'arraybuffer'|'blob'|'json'|'text'

Ex:

this.http.post(
    'http://localhost:8080/order/addtocart', 
    { dealerId: 13, createdBy: "-1", productId, quantity }, 
    { headers, responseType: 'text'});

What is the difference between signed and unsigned variables?

Signed variables, such as signed integers will allow you to represent numbers both in the positive and negative ranges.

Unsigned variables, such as unsigned integers, will only allow you to represent numbers in the positive and zero.

Unsigned and signed variables of the same type (such as int and byte) both have the same range (range of 65,536 and 256 numbers, respectively), but unsigned can represent a larger magnitude number than the corresponding signed variable.

For example, an unsigned byte can represent values from 0 to 255, while signed byte can represent -128 to 127.

Wikipedia page on Signed number representations explains the difference in the representation at the bit level, and the Integer (computer science) page provides a table of ranges for each signed/unsigned integer type.

How do I prevent and/or handle a StackOverflowException?

@WilliamJockusch, if I understood correctly your concern, it's not possible (from a mathematical point of view) to always identify an infinite recursion as it would mean to solve the Halting problem. To solve it you'd need a Super-recursive algorithm (like Trial-and-error predicates for example) or a machine that can hypercompute (an example is explained in the following section - available as preview - of this book).

From a practical point of view, you'd have to know:

  • How much stack memory you have left at the given time
  • How much stack memory your recursive method will need at the given time for the specific output.

Keep in mind that, with the current machines, this data is extremely mutable due to multitasking and I haven't heard of a software that does the task.

Let me know if something is unclear.

print highest value in dict with key

just :

 mydict = {'A':4,'B':10,'C':0,'D':87}
 max(mydict.items(), key=lambda x: x[1])

image size (drawable-hdpi/ldpi/mdpi/xhdpi)

Not just tab icons, notification and launcher lives an app. I was confused about the sizes of the other icons used for different situations in the app.

I'm using 32px mdpi (Action Bar icons) dimensions and I cannot say if it would be correct.

mdpi 32px

How do I remove/delete a virtualenv?

You can remove all the dependencies by recursively uninstalling all of them and then delete the venv.

Edit including Isaac Turner commentary

source venv/bin/activate
pip freeze > requirements.txt
pip uninstall -r requirements.txt -y
deactivate
rm -r venv/

pandas: How do I split text in a column into multiple rows?

This seems a far easier method than those suggested elsewhere in this thread.

split rows in pandas dataframe

How to grant remote access to MySQL for a whole subnet?

Motivated by @Malvineaus answer I tried it myself and noticed that it didn't work for me.

You can specify subnet masks with '192.168.1.%' or '192.168.1.0/255.255.255.0' but the subnet must always be on complete octets. see https://mariadb.com/kb/en/create-user/#host-name-component. As result the functionality between one way of specification and the other is the same.

For example '192.168.1.0/255.255.255.128' will not work as it is not on a complete octet boundary.

Javascript variable access in HTML

<html>
<head>
<script>
    function putText() {
        var simpleText = "hello_world";
        var finalSplitText = simpleText.split("_");
        var splitText = finalSplitText[0];
        document.getElementById("destination").innerHTML = "I need the value of " + splitText + " variable here";
    }
</script>
</head>
<body onLoad = putText()>
    <a id="destination" href = test.html>I need the value of "splitText" variable here</a>
</body>
</html>

How to test REST API using Chrome's extension "Advanced Rest Client"

This seems a very old question, but I am providing an answer, so that it might help others. You can specify the variables in the second screen in the form section, as shown below or in the RAW format by appending the variables as shown in the second image.

Specify Form Variables

Specify in RAW format

If your variable and variable values are valid, you should see a successful response in the response section.

C# Copy a file to another location with a different name

You can use either File.Copy(oldFilePath, newFilePath) method or other way is, read file using StreamReader into an string and then use StreamWriter to write the file to destination location.

Your code might look like this :

StreamReader reader = new StreamReader("C:\foo.txt");
string fileContent = reader.ReadToEnd();

StreamWriter writer = new StreamWriter("D:\bar.txt");
writer.Write(fileContent);

You can add exception handling code...

How do I install cURL on Windows?

I had also problems with this. After all these steps made correctly and some fixed misunderstandings (there is no extensions_dir but extension_dir, and there is no sessions.save_path but session.save_path) nothing works.

Finally I found this note at php.net:

Note: Note to Win32 Users: In order to enable this module on a Windows environment, libeay32.dll and ssleay32.dll must be present in your PATH. You don't need libcurl.dll from the cURL site.

So I copied ssleay32.dll, libeay32.dll & php_curl.dll From /PHP to Windows/system32 and replaced already existing files (I noticed there were older versions of ssleay32.dll and libeay32.dll). After that I found CURL section in php_info(); and finally everything works.

Good luck!

Bash function to find newest file matching pattern

This is a possible implementation of the required Bash function:

# Print the newest file, if any, matching the given pattern
# Example usage:
#   newest_matching_file 'b2*'
# WARNING: Files whose names begin with a dot will not be checked
function newest_matching_file
{
    # Use ${1-} instead of $1 in case 'nounset' is set
    local -r glob_pattern=${1-}

    if (( $# != 1 )) ; then
        echo 'usage: newest_matching_file GLOB_PATTERN' >&2
        return 1
    fi

    # To avoid printing garbage if no files match the pattern, set
    # 'nullglob' if necessary
    local -i need_to_unset_nullglob=0
    if [[ ":$BASHOPTS:" != *:nullglob:* ]] ; then
        shopt -s nullglob
        need_to_unset_nullglob=1
    fi

    newest_file=
    for file in $glob_pattern ; do
        [[ -z $newest_file || $file -nt $newest_file ]] \
            && newest_file=$file
    done

    # To avoid unexpected behaviour elsewhere, unset nullglob if it was
    # set by this function
    (( need_to_unset_nullglob )) && shopt -u nullglob

    # Use printf instead of echo in case the file name begins with '-'
    [[ -n $newest_file ]] && printf '%s\n' "$newest_file"

    return 0
}

It uses only Bash builtins, and should handle files whose names contain newlines or other unusual characters.

Spring Data JPA find by embedded object property

The above - findByBookIdRegion() did not work for me. The following works with the latest release of String Data JPA:

Page<QueuedBook> findByBookId_Region(Region region, Pageable pageable);

How to convert an integer to a string in any base?

Here is an example of how to convert a number of any base to another base.

from collections import namedtuple

Test = namedtuple("Test", ["n", "from_base", "to_base", "expected"])


def convert(n: int, from_base: int, to_base: int) -> int:
    digits = []
    while n:
        (n, r) = divmod(n, to_base)
        digits.append(r)    
    return sum(from_base ** i * v for i, v in enumerate(digits))


if __name__ == "__main__":
    tests = [
        Test(32, 16, 10, 50),
        Test(32, 20, 10, 62),
        Test(1010, 2, 10, 10),
        Test(8, 10, 8, 10),
        Test(150, 100, 1000, 150),
        Test(1500, 100, 10, 1050000),
    ]

    for test in tests:
        result = convert(*test[:-1])
        assert result == test.expected, f"{test=}, {result=}"
    print("PASSED!!!")

Change background color of selected item on a ListView

You can use a selector. Change the colors values and modify the below according to your needs.

bkg.xml in drawable folder

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" 
    android:drawable="@drawable/pressed" />
<item  android:state_focused="false" 
    android:drawable="@drawable/normal" />
</selector>

pressed.xml in drawable folder

<?xml version="1.0" encoding="UTF-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
<solid android:color="#FF1A47"/>  // color   
<stroke android:width="3dp"
        android:color="#0FECFF"/> // border
<padding android:left="5dp"
         android:top="5dp"
         android:right="5dp"
         android:bottom="5dp"/> 
<corners android:bottomRightRadius="7dp" // for rounded corners
         android:bottomLeftRadius="7dp" 
         android:topLeftRadius="7dp"
         android:topRightRadius="7dp"/> 
</shape>

normal.xml in drawable folder

<?xml version="1.0" encoding="UTF-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
<solid android:color="#FFFFFF"/>    
<stroke android:width="3dp"
        android:color="#0FECFF" />

<padding android:left="5dp"
         android:top="5dp"
         android:right="5dp"
         android:bottom="5dp"/> 
<corners android:bottomRightRadius="7dp"
         android:bottomLeftRadius="7dp" 
         android:topLeftRadius="7dp"
         android:topRightRadius="7dp"/> 
</shape>

Set the background drawable to listview custom layout to be inflated for each row

I recommend using a custom listview with a custom adapter.

  android:background="@drawable/bkg"     

If you have not used a custom adapter you can set the listselector to listview as below

   android:listSelector="@drawable/bkg" 

How to sort in mongoose?

This is how I got sort to work in mongoose 2.3.0 :)

// Find First 10 News Items
News.find({
    deal_id:deal._id // Search Filters
},
['type','date_added'], // Columns to Return
{
    skip:0, // Starting Row
    limit:10, // Ending Row
    sort:{
        date_added: -1 //Sort by Date Added DESC
    }
},
function(err,allNews){
    socket.emit('news-load', allNews); // Do something with the array of 10 objects
})

Do while loop in SQL Server 2008

If you are not very offended by the GOTO keyword, it can be used to simulate a DO / WHILE in T-SQL. Consider the following rather nonsensical example written in pseudocode:

SET I=1
DO
 PRINT I
 SET I=I+1
WHILE I<=10

Here is the equivalent T-SQL code using goto:

DECLARE @I INT=1;
START:                -- DO
  PRINT @I;
  SET @I+=1;
IF @I<=10 GOTO START; -- WHILE @I<=10

Notice the one to one mapping between the GOTO enabled solution and the original DO / WHILE pseudocode. A similar implementation using a WHILE loop would look like:

DECLARE @I INT=1;
WHILE (1=1)              -- DO
 BEGIN
  PRINT @I;
  SET @I+=1;
  IF NOT (@I<=10) BREAK; -- WHILE @I<=10
 END

Now, you could of course rewrite this particular example as a simple WHILE loop, since this is not such a good candidate for a DO / WHILE construct. The emphasis was on example brevity rather than applicability, since legitimate cases requiring a DO / WHILE are rare.


REPEAT / UNTIL, anyone (does NOT work in T-SQL)?

SET I=1
REPEAT
  PRINT I
  SET I=I+1
UNTIL I>10

... and the GOTO based solution in T-SQL:

DECLARE @I INT=1;
START:                    -- REPEAT
  PRINT @I;
  SET @I+=1;
IF NOT(@I>10) GOTO START; -- UNTIL @I>10

Through creative use of GOTO and logic inversion via the NOT keyword, there is a very close relationship between the original pseudocode and the GOTO based solution. A similar solution using a WHILE loop looks like:

DECLARE @I INT=1;
WHILE (1=1)       -- REPEAT
 BEGIN
  PRINT @I;
  SET @I+=1;
  IF @I>10 BREAK; -- UNTIL @I>10
 END

An argument can be made that for the case of the REPEAT / UNTIL, the WHILE based solution is simpler, because the if condition is not inverted. On the other hand it is also more verbose.

If it wasn't for all of the disdain around the use of GOTO, these might even be idiomatic solutions for those few times when these particular (evil) looping constructs are necessary in T-SQL code for the sake of clarity.

Use these at your own discretion, trying not to suffer the wrath of your fellow developers when they catch you using the much maligned GOTO.

Error: Node Sass does not yet support your current environment: Windows 64-bit with false

I got this error, with angular 7, what helped me is, From the windows power shell I run the command:

npm install --global --production windows-build-tools

then again I reopen my VS Code, on it's terminal I run the same command npm uninstall node-sass and npm install node-sass

bash script use cut command at variable and store result at another variable

The awk solution is what I would use, but if you want to understand your problems with bash, here is a revised version of your script.

#!/bin/bash -vx

##config file with ip addresses like 10.10.10.1:80
file=config.txt

while read line ; do
  ##this line is not correct, should strip :port and store to ip var
  ip=$( echo "$line" |cut -d\: -f1 )
  ping $ip
done < ${file}

You could write your top line as

for line in $(cat $file) ; do ...

(but not recommended).

You needed command substitution $( ... ) to get the value assigned to $ip

reading lines from a file is usually considered more efficient with the while read line ... done < ${file} pattern.

I hope this helps.

Docker can't connect to docker daemon

at april 2020 on mac os catalina you just need to open the desktop application enter image description here

Display tooltip on Label's hover?

Just set a title on the label:

<label for="male" title="Hello This Will Have Some Value">Hello...</label>

Using jQuery:

<label for="male" data-title="Language" />
<input type="hidden" name="Language" value="Hello This Will Have Some Value">

$("label").prop("title", function() {
    return $("input[name='" + $(this).data("title") + "']").text();
});

If you can use CSS3, you can use the text-overflow: ellipsis; to handle the ellipsis for you so all you need to do is copy the text from the label into the title attribute using jQuery:

HTML:

<label for="male">Hello This Will Have Some Value</label>

CSS:

label {
    display: inline-block;
    width: 50px;
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
}

jQuery:

$("label").prop("title", function() {
   return $(this).text(); 
});

Example: http://jsfiddle.net/Xm8Xe/

Finally, if you need robust and cross-browser support, you could use the DotDotDot jQuery plugin.

php delete a single file in directory

The script you downloaded lists the content of a specified folder. You probably put the unlink - call in one of the while-loops that list the files.

EDIT - Now that you posted your code:

echo '<a href="'.unlink($FileLink).'"><img src="images/icons/delete.gif"></a></td>';

Doing this calls the unlink-function each time the line is written, deleting your file. You have to write a link to a script that contains a delete function and pass some parameter that tells your script what to delete.

Example:

<a href="/path/to/script.php?delete='. $FileLink .'">delete</a>

You should not pass the path to a file this script and just delete it though, because malevolent being might use it to just delete everything or do other evil things.

SSL certificate rejected trying to access GitHub over HTTPS behind firewall

If you used debian-based OS, you can simply run

apt-get install ca-certificates

Clear the entire history stack and start a new activity on Android

Advanced Reuseable Kotlin:

You can set the flag directly using setter method. In Kotlin or is the replacement for the Java bitwise or |.

intent.flags = FLAG_ACTIVITY_NEW_TASK or FLAG_ACTIVITY_CLEAR_TASK

If you plan to use this regularly, create an Intent extension function

fun Intent.clearStack() {
    flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}

You can then directly call this function before starting the intent

intent.clearStack()

If you need the option to add additional flags in other situations, add an optional param to the extension function.

fun Intent.clearStack(additionalFlags: Int = 0) {
    flags = additionalFlags or Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}

How to make an embedded video not autoplay

Try adding these after <Playlist>

<AutoLoad>false</AutoLoad>
<AutoPlay>false</AutoPlay>

DateTime.TryParse issue with dates of yyyy-dd-MM format

If you give the user the opportunity to change the date/time format, then you'll have to create a corresponding format string to use for parsing. If you know the possible date formats (i.e. the user has to select from a list), then this is much easier because you can create those format strings at compile time.

If you let the user do free-format design of the date/time format, then you'll have to create the corresponding DateTime format strings at runtime.

Set an environment variable in git bash

A normal variable is set by simply assigning it a value; note that no whitespace is allowed around the =:

HOME=c

An environment variable is a regular variable that has been marked for export to the environment.

export HOME
HOME=c

You can combine the assignment with the export statement.

export HOME=c

How can I clone an SQL Server database on the same server in SQL Server 2008 Express?

In SQL Server 2008 R2, back-up the database as a file into a folder. Then chose the restore option that appears in the "Database" folder. In the wizard enter the new name that you want in the target database. And choose restore frrom file and use the file you just created. I jsut did it and it was very fast (my DB was small, but still) Pablo.

Bootstrap: wider input field

Use the bootstrap built in classes input-large, input-medium, ... : <input type="text" class="input-large search-query">

Or use your own css:

  1. Give the element a unique classname class="search-query input-mysize"
  2. Add this in your css file (not the bootstrap.less or css files):
    .input-mysize { width: 150px }

Add a column with a default value to an existing table in SQL Server

--Adding New Column with Default Value
ALTER TABLE TABLENAME 
ADD COLUMNNAME DATATYPE NULL|NOT NULL DEFAULT (DEFAULT_VALUE)

OR

--Adding CONSTRAINT And Set Default Value on Column
ALTER TABLE TABLENAME ADD  CONSTRAINT [CONSTRAINT_Name]  DEFAULT 
(DEFAULT_VALUE) FOR [COLUMNNAME]

Sibling package imports

Tired of sys.path hacks?

There are plenty of sys.path.append -hacks available, but I found an alternative way of solving the problem in hand.

Summary

  • Wrap the code into one folder (e.g. packaged_stuff)
  • Create setup.py script where you use setuptools.setup(). (see minimal setup.py below)
  • Pip install the package in editable state with pip install -e <myproject_folder>
  • Import using from packaged_stuff.modulename import function_name

Setup

The starting point is the file structure you have provided, wrapped in a folder called myproject.

.
+-- myproject
    +-- api
    ¦   +-- api_key.py
    ¦   +-- api.py
    ¦   +-- __init__.py
    +-- examples
    ¦   +-- example_one.py
    ¦   +-- example_two.py
    ¦   +-- __init__.py
    +-- LICENCE.md
    +-- README.md
    +-- tests
        +-- __init__.py
        +-- test_one.py

I will call the . the root folder, and in my example case it is located at C:\tmp\test_imports\.

api.py

As a test case, let's use the following ./api/api.py

def function_from_api():
    return 'I am the return value from api.api!'

test_one.py

from api.api import function_from_api

def test_function():
    print(function_from_api())

if __name__ == '__main__':
    test_function()

Try to run test_one:

PS C:\tmp\test_imports> python .\myproject\tests\test_one.py
Traceback (most recent call last):
  File ".\myproject\tests\test_one.py", line 1, in <module>
    from api.api import function_from_api
ModuleNotFoundError: No module named 'api'

Also trying relative imports wont work:

Using from ..api.api import function_from_api would result into

PS C:\tmp\test_imports> python .\myproject\tests\test_one.py
Traceback (most recent call last):
  File ".\tests\test_one.py", line 1, in <module>
    from ..api.api import function_from_api
ValueError: attempted relative import beyond top-level package

Steps

  1. Make a setup.py file to the root level directory

The contents for the setup.py would be*

from setuptools import setup, find_packages

setup(name='myproject', version='1.0', packages=find_packages())
  1. Use a virtual environment

If you are familiar with virtual environments, activate one, and skip to the next step. Usage of virtual environments are not absolutely required, but they will really help you out in the long run (when you have more than 1 project ongoing..). The most basic steps are (run in the root folder)

  • Create virtual env
    • python -m venv venv
  • Activate virtual env
    • source ./venv/bin/activate (Linux, macOS) or ./venv/Scripts/activate (Win)

To learn more about this, just Google out "python virtual env tutorial" or similar. You probably never need any other commands than creating, activating and deactivating.

Once you have made and activated a virtual environment, your console should give the name of the virtual environment in parenthesis

PS C:\tmp\test_imports> python -m venv venv
PS C:\tmp\test_imports> .\venv\Scripts\activate
(venv) PS C:\tmp\test_imports>

and your folder tree should look like this**

.
+-- myproject
¦   +-- api
¦   ¦   +-- api_key.py
¦   ¦   +-- api.py
¦   ¦   +-- __init__.py
¦   +-- examples
¦   ¦   +-- example_one.py
¦   ¦   +-- example_two.py
¦   ¦   +-- __init__.py
¦   +-- LICENCE.md
¦   +-- README.md
¦   +-- tests
¦       +-- __init__.py
¦       +-- test_one.py
+-- setup.py
+-- venv
    +-- Include
    +-- Lib
    +-- pyvenv.cfg
    +-- Scripts [87 entries exceeds filelimit, not opening dir]
  1. pip install your project in editable state

Install your top level package myproject using pip. The trick is to use the -e flag when doing the install. This way it is installed in an editable state, and all the edits made to the .py files will be automatically included in the installed package.

In the root directory, run

pip install -e . (note the dot, it stands for "current directory")

You can also see that it is installed by using pip freeze

(venv) PS C:\tmp\test_imports> pip install -e .
Obtaining file:///C:/tmp/test_imports
Installing collected packages: myproject
  Running setup.py develop for myproject
Successfully installed myproject
(venv) PS C:\tmp\test_imports> pip freeze
myproject==1.0
  1. Add myproject. into your imports

Note that you will have to add myproject. only into imports that would not work otherwise. Imports that worked without the setup.py & pip install will work still work fine. See an example below.


Test the solution

Now, let's test the solution using api.py defined above, and test_one.py defined below.

test_one.py

from myproject.api.api import function_from_api

def test_function():
    print(function_from_api())

if __name__ == '__main__':
    test_function()

running the test

(venv) PS C:\tmp\test_imports> python .\myproject\tests\test_one.py
I am the return value from api.api!

* See the setuptools docs for more verbose setup.py examples.

** In reality, you could put your virtual environment anywhere on your hard disk.

Char array in a struct - incompatible assignment?

Or you could just use dynamic allocation, e.g.:

struct name {
  char *first;
  char *last;
};

struct name sara;
sara.first = "Sara";
sara.last = "Black";
printf("first: %s, last: %s\n", sara.first, sara.last);

Android Studio: /dev/kvm device permission denied

Under Ubuntu, the permissions of /dev/kvm usually look like this:

$ ls -l /dev/kvm
crw-rw---- 1 root kvm 10, 232 May 24 09:54 /dev/kvm

The user that runs the Android emulator (i.e. your user) needs to get access to this device.

Thus, there are basically 2 ways how to get access:

  • Make sure that your user is part of the kvm group (requires a re-login of your user after the change)
  • Widen the permissions of that device such that your user has access (requires a change to the udev daemon configuration)

Add User to KVM Group

Check if your user is already part of the kvm group, e.g.:

$ id 
uid=1000(juser) gid=1000(juser) groups=1000(juser),10(wheel)

If it isn't then add it with e.g.:

$ sudo usermod --append --groups kvm juser

After that change you have to logout and login again to make the group change effective (check again with id).

Widen Permissions

Alternatively, you can just can widen the permissions of the /dev/kvm device.

Example:

echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' \
    | sudo tee /etc/udev/rules.d/99-kvm4all.rules
sudo udevadm control --reload-rules
sudo udevadm trigger --name-match=kvm

FWIW, this is the default on other distributions such as Fedora and CentOS.

Check the effectiveness of the above commands with another ls. You should see output similar to:

$ ls -l /dev/kvm
crw-rw-rw-. 1 root kvm 10, 232 2020-05-16 09:19 /dev/kvm

Big advantage: You don't need to logout and login again for this change to be effective.

Non-Solutions

  • calling chmod and chown directly on /dev/kvm - 1) these changes aren't persistent over reboots and 2) since /dev/kvm permissions are controlled by the udev daemon, it can 'fix' its permissions at any time, e.g. after each emulator run
  • adding executable permissions to /dev/kvm - your emulator just requires read and write permissions
  • changing permissions recursively on /dev/kvm - I don't know what's up with that - looks like cargo cult
  • installing extra packages like qemu - you already have your emulator installed - you just need to get access to the /dev/kvm device

String format currency

decimal value = 0.00M;
value = Convert.ToDecimal(12345.12345);
Console.WriteLine(".ToString(\"C\") Formates With Currency $ Sign");
Console.WriteLine(value.ToString("C"));
//OutPut : $12345.12
Console.WriteLine(value.ToString("C1"));
//OutPut : $12345.1
Console.WriteLine(value.ToString("C2"));
//OutPut : $12345.12
Console.WriteLine(value.ToString("C3"));
//OutPut : $12345.123
Console.WriteLine(value.ToString("C4"));
//OutPut : $12345.1234
Console.WriteLine(value.ToString("C5"));
//OutPut : $12345.12345
Console.WriteLine(value.ToString("C6"));
//OutPut : $12345.123450
Console.WriteLine();
Console.WriteLine(".ToString(\"F\") Formates With out Currency Sign");
Console.WriteLine(value.ToString("F"));
//OutPut : 12345.12
Console.WriteLine(value.ToString("F1"));
//OutPut : 12345.1
Console.WriteLine(value.ToString("F2"));
//OutPut : 12345.12
Console.WriteLine(value.ToString("F3"));
//OutPut : 12345.123
Console.WriteLine(value.ToString("F4"));
//OutPut : 12345.1234
Console.WriteLine(value.ToString("F5"));
//OutPut : 12345.12345
Console.WriteLine(value.ToString("F6"));
//OutPut : 12345.123450
Console.Read();

Output console screen:

Shrinking navigation bar when scrolling down (bootstrap3)

Sticky navbar:

To make a sticky nav you need to add the class navbar-fixed-top to your nav

Official documentation:
http://getbootstrap.com/components/#navbar-fixed-top

Official example:
http://getbootstrap.com/examples/navbar-fixed-top/

A simple example code:

<nav class="navbar navbar-default navbar-fixed-top" role="navigation">
  <div class="container">
    ...
  </div>
</nav>

with related jsfiddle: http://jsfiddle.net/ur7t8/

Resize the navbar:

If you want the nav bar to resize while you scroll the page you can give a look to this example: http://www.bootply.com/109943

JS

$(window).scroll(function() {
  if ($(document).scrollTop() > 50) {
    $('nav').addClass('shrink');
  } else {
    $('nav').removeClass('shrink');
  }
});

CSS

nav.navbar.shrink {
  min-height: 35px;
}

Animation:

To add an animation while you scroll, all you need to do is set a transition on the nav

CSS

nav.navbar{
  background-color:#ccc;
   // Animation
   -webkit-transition: all 0.4s ease;
   transition: all 0.4s ease;
}

I made a jsfiddle with the full example code: http://jsfiddle.net/Filo/m7yww8oa/

Subscript out of range error in this Excel VBA script

This looks a little better than your previous version but get rid of that .Activate on that line and see if you still get that error.

Dim sh1 As Worksheet
set sh1 = Workbooks.Add(filenum(lngPosition) & ".csv")

Creates a worksheet object. Not until you create that object do you want to start working with it. Once you have that object you can do the following:

sh1.Range("A69").Paste
sh1.Range("A69").Select

The sh1. explicitely tells Excel which object you are saying to work with... otherwise if you start selecting other worksheets while this code is running you could wind up pasting data to the wrong place.

VBA paste range

This is what I came up to when trying to copy-paste excel ranges with it's sizes and cell groups. It might be a little too specific for my problem but...:

'** 'Copies a table from one place to another 'TargetRange: where to put the new LayoutTable 'typee: If it is an Instalation Layout table(1) or Package Layout table(2) '**

Sub CopyLayout(TargetRange As Range, typee As Integer)
    Application.ScreenUpdating = False
        Dim ncolumn As Integer
        Dim nrow As Integer

        SheetLayout.Activate
    If (typee = 1) Then 'is installation
        Range("installationlayout").Copy Destination:=TargetRange '@SHEET2 TEM DE PASSAR A SER A SHEET DO PROJECT PLAN!@@@@@
    ElseIf (typee = 2) Then 'is package
        Range("PackageLayout").Copy Destination:=TargetRange '@SHEET2 TEM DE PASSAR A SER A SHEET DO PROJECT PLAN!@@@@@
    End If

    Sheet2.Select 'SHEET2 TEM DE PASSAR A SER A SHEET DO PROJECT PLAN!@@@@@

    If typee = 1 Then
       nrow = SheetLayout.Range("installationlayout").Rows.Count
       ncolumn = SheetLayout.Range("installationlayout").Columns.Count

       Call RowHeightCorrector(SheetLayout.Range("installationlayout"), TargetRange.CurrentRegion, typee, nrow, ncolumn)
    ElseIf typee = 2 Then
       nrow = SheetLayout.Range("PackageLayout").Rows.Count
       ncolumn = SheetLayout.Range("PackageLayout").Columns.Count
       Call RowHeightCorrector(SheetLayout.Range("PackageLayout"), TargetRange.CurrentRegion, typee, nrow, ncolumn)
    End If
    Range("A1").Select 'Deselect the created table

    Application.CutCopyMode = False
    Application.ScreenUpdating = True
End Sub

'** 'Receives the Pasted Table Range and rearranjes it's properties 'accordingly to the original CopiedTable 'typee: If it is an Instalation Layout table(1) or Package Layout table(2) '**

Function RowHeightCorrector(CopiedTable As Range, PastedTable As Range, typee As Integer, RowCount As Integer, ColumnCount As Integer)
    Dim R As Long, C As Long

    For R = 1 To RowCount
        PastedTable.Rows(R).RowHeight = CopiedTable.CurrentRegion.Rows(R).RowHeight
        If R >= 2 And R < RowCount Then
            PastedTable.Rows(R).Group 'Main group of the table
        End If
        If R = 2 Then
            PastedTable.Rows(R).Group 'both type of tables have a grouped section at relative position "2" of Rows
        ElseIf (R = 4 And typee = 1) Then
            PastedTable.Rows(R).Group 'If it is an installation materials table, it has two grouped sections...
        End If
    Next R

    For C = 1 To ColumnCount
        PastedTable.Columns(C).ColumnWidth = CopiedTable.CurrentRegion.Columns(C).ColumnWidth
    Next C
End Function



Sub test ()
    Call CopyLayout(Sheet2.Range("A18"), 2)
end sub

How to Display Selected Item in Bootstrap Button Dropdown Title

It seems to be a long issue. All we want is just implement a select tag in the input group. But the bootstrap would not do it: https://github.com/twbs/bootstrap/issues/10486

the trick is just adding "btn-group" class to the parent div

html:

<div class="input-group">
  <div class="input-group-btn btn-group">
    <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
      Product Name <span class="caret"></span>
    </button>
    <ul class="dropdown-menu" role="menu">
        <li><a href="#">A</a></li>
        <li><a href="#">B</a></li>
    </ul>
  </div>
  <input type="text" class="form-control">
  <span class="input-group-btn">
    <button class="btn btn-primary" type="button">Search</button>
  </span>
</div>

js:

$(".dropdown-menu li a").click(function(e){
    var selText = $(this).text();
    $(this).parents('.input-group').find('.dropdown-toggle').html(selText+' <span class="caret"></span>');       
});

CSS selector for "foo that contains bar"?

Only thing that comes even close is the :contains pseudo class in CSS3, but that only selects textual content, not tags or elements, so you're out of luck.

A simpler way to select a parent with specific children in jQuery can be written as (with :has()):

$('#parent:has(#child)');

Difference between Interceptor and Filter in Spring MVC

From HandlerIntercepter's javadoc:

HandlerInterceptor is basically similar to a Servlet Filter, but in contrast to the latter it just allows custom pre-processing with the option of prohibiting the execution of the handler itself, and custom post-processing. Filters are more powerful, for example they allow for exchanging the request and response objects that are handed down the chain. Note that a filter gets configured in web.xml, a HandlerInterceptor in the application context.

As a basic guideline, fine-grained handler-related pre-processing tasks are candidates for HandlerInterceptor implementations, especially factored-out common handler code and authorization checks. On the other hand, a Filter is well-suited for request content and view content handling, like multipart forms and GZIP compression. This typically shows when one needs to map the filter to certain content types (e.g. images), or to all requests.

With that being said:

So where is the difference between Interceptor#postHandle() and Filter#doFilter()?

postHandle will be called after handler method invocation but before the view being rendered. So, you can add more model objects to the view but you can not change the HttpServletResponse since it's already committed.

doFilter is much more versatile than the postHandle. You can change the request or response and pass it to the chain or even block the request processing.

Also, in preHandle and postHandle methods, you have access to the HandlerMethod that processed the request. So, you can add pre/post-processing logic based on the handler itself. For example, you can add a logic for handler methods that have some annotations.

What is the best practise in which use cases it should be used?

As the doc said, fine-grained handler-related pre-processing tasks are candidates for HandlerInterceptor implementations, especially factored-out common handler code and authorization checks. On the other hand, a Filter is well-suited for request content and view content handling, like multipart forms and GZIP compression. This typically shows when one needs to map the filter to certain content types (e.g. images), or to all requests.

Transfer files to/from session I'm logged in with PuTTY

If you have to do private key validation; at Command Prompt(cmd), run

First;

set PATH=C:\PuttySetupLocation

Second;

pscp -i C:/MyPrivateKeyFile.ppk C:/MySourceFile.jar [email protected]:/home/ubuntu

Also, if you need extra options look at the following link. https://the.earth.li/~sgtatham/putty/0.60/htmldoc/Chapter5.html

'pip' is not recognized as an internal or external command

Try going to Windows PowerShell or cmd prompt and typing:

python -m pip install openpyxl

What is a clean, Pythonic way to have multiple constructors in Python?

The best answer is the one above about default arguments, but I had fun writing this, and it certainly does fit the bill for "multiple constructors". Use at your own risk.

What about the new method.

"Typical implementations create a new instance of the class by invoking the superclass’s new() method using super(currentclass, cls).new(cls[, ...]) with appropriate arguments and then modifying the newly-created instance as necessary before returning it."

So you can have the new method modify your class definition by attaching the appropriate constructor method.

class Cheese(object):
    def __new__(cls, *args, **kwargs):

        obj = super(Cheese, cls).__new__(cls)
        num_holes = kwargs.get('num_holes', random_holes())

        if num_holes == 0:
            cls.__init__ = cls.foomethod
        else:
            cls.__init__ = cls.barmethod

        return obj

    def foomethod(self, *args, **kwargs):
        print "foomethod called as __init__ for Cheese"

    def barmethod(self, *args, **kwargs):
        print "barmethod called as __init__ for Cheese"

if __name__ == "__main__":
    parm = Cheese(num_holes=5)

How do you uninstall MySQL from Mac OS X?

You should also check /var/db/receipts and remove all entries that contain com.mysql.*

Using sudo rm -rf /var/db/receipts/com.mysql.* didn't work for me. I had to go into var/db/receipts and delete each one seperately.

How to use sudo inside a docker container?

Unlike accepted answer, I use usermod instead.

Assume already logged-in as root in docker, and "fruit" is the new non-root username I want to add, simply run this commands:

apt update && apt install sudo
adduser fruit
usermod -aG sudo fruit

Remember to save image after update. Use docker ps to get current running docker's <CONTAINER ID> and <IMAGE>, then run docker commit -m "added sudo user" <CONTAINER ID> <IMAGE> to save docker image.

Then test with:

su fruit
sudo whoami

Or test by direct login(ensure save image first) as that non-root user when launch docker:

docker run -it --user fruit <IMAGE>
sudo whoami

You can use sudo -k to reset password prompt timestamp:

sudo whoami # No password prompt
sudo -k # Invalidates the user's cached credentials
sudo whoami # This will prompt for password

Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'

in my experience. I was using jsp for web. at that time I use mysql 5 and mysql connecter jar 8. So due to the version problem I face this kind of problem. I solve by replace the mysql connector jar file the exact version mysql.

Export html table data to Excel using JavaScript / JQuery is not working properly in chrome browser

_x000D_
_x000D_
 function exportToExcel() {_x000D_
        var tab_text = "<tr bgcolor='#87AFC6'>";_x000D_
        var textRange; var j = 0, rows = '';_x000D_
        tab = document.getElementById('student-detail');_x000D_
        tab_text = tab_text + tab.rows[0].innerHTML + "</tr>";_x000D_
        var tableData = $('#student-detail').DataTable().rows().data();_x000D_
        for (var i = 0; i < tableData.length; i++) {_x000D_
            rows += '<tr>'_x000D_
                + '<td>' + tableData[i].value1 + '</td>'_x000D_
                + '<td>' + tableData[i].value2 + '</td>'_x000D_
                + '<td>' + tableData[i].value3 + '</td>'_x000D_
                + '<td>' + tableData[i].value4 + '</td>'_x000D_
                + '<td>' + tableData[i].value5 + '</td>'_x000D_
                + '<td>' + tableData[i].value6 + '</td>'_x000D_
                + '<td>' + tableData[i].value7 + '</td>'_x000D_
                + '<td>' +  tableData[i].value8 + '</td>'_x000D_
                + '<td>' + tableData[i].value9 + '</td>'_x000D_
                + '<td>' + tableData[i].value10 + '</td>'_x000D_
                + '</tr>';_x000D_
        }_x000D_
        tab_text += rows;_x000D_
        var data_type = 'data:application/vnd.ms-excel;base64,',_x000D_
            template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table border="2px">{table}</table></body></html>',_x000D_
            base64 = function (s) {_x000D_
                return window.btoa(unescape(encodeURIComponent(s)))_x000D_
            },_x000D_
            format = function (s, c) {_x000D_
                return s.replace(/{(\w+)}/g, function (m, p) {_x000D_
                    return c[p];_x000D_
                })_x000D_
            }_x000D_
_x000D_
        var ctx = {_x000D_
            worksheet: "Sheet 1" || 'Worksheet',_x000D_
            table: tab_text_x000D_
        }_x000D_
        document.getElementById("dlink").href = data_type + base64(format(template, ctx));_x000D_
        document.getElementById("dlink").download = "StudentDetails.xls";_x000D_
        document.getElementById("dlink").traget = "_blank";_x000D_
        document.getElementById("dlink").click();_x000D_
    }
_x000D_
_x000D_
_x000D_

Here Value 1 to 10 are column names that you are getting

What exactly is the difference between Web API and REST API in MVC?

ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.

REST

RESTs sweet spot is when you are exposing a public API over the internet to handle CRUD operations on data. REST is focused on accessing named resources through a single consistent interface.

SOAP

SOAP brings it’s own protocol and focuses on exposing pieces of application logic (not data) as services. SOAP exposes operations. SOAP is focused on accessing named operations, each implement some business logic through different interfaces.

Though SOAP is commonly referred to as “web services” this is a misnomer. SOAP has very little if anything to do with the Web. REST provides true “Web services” based on URIs and HTTP.

Reference: http://spf13.com/post/soap-vs-rest

And finally: What they could be referring to is REST vs. RPC See this: http://encosia.com/rest-vs-rpc-in-asp-net-web-api-who-cares-it-does-both/

How to insert values in table with foreign key using MySQL?

Case 1

INSERT INTO tab_student (name_student, id_teacher_fk)
    VALUES ('dan red', 
           (SELECT id_teacher FROM tab_teacher WHERE name_teacher ='jason bourne')

it is advisable to store your values in lowercase to make retrieval easier and less error prone

Case 2

mysql docs

INSERT INTO tab_teacher (name_teacher) 
    VALUES ('tom stills')
INSERT INTO tab_student (name_student, id_teacher_fk)
    VALUES ('rich man', LAST_INSERT_ID())

Barcode scanner for mobile phone for Website in form

Check out https://github.com/serratus/quaggaJS

"QuaggaJS is a barcode-scanner entirely written in JavaScript supporting real- time localization and decoding of various types of barcodes such as EAN, CODE 128, CODE 39, EAN 8, UPC-A, UPC-C, I2of5, 2of5, CODE 93 and CODABAR. The library is also capable of using getUserMedia to get direct access to the user's camera stream. Although the code relies on heavy image-processing even recent smartphones are capable of locating and decoding barcodes in real-time."

How can I add a username and password to Jenkins?

Assuming you have Manage Jenkins > Configure Global Security > Enable Security and Jenkins Own User Database checked you would go to:

  • Manage Jenkins > Manage Users > Create User

How to make popup look at the centre of the screen?

These are the changes to make:

CSS:

#container {
    width: 100%;
    height: 100%;
    top: 0;
    position: absolute;
    visibility: hidden;
    display: none;
    background-color: rgba(22,22,22,0.5); /* complimenting your modal colors */
}
#container:target {
    visibility: visible;
    display: block;
}
.reveal-modal {
    position: relative;
    margin: 0 auto;
    top: 25%;
}
    /* Remove the left: 50% */

HTML:

<a href="#container">Reveal</a>
<div id="container">
    <div id="exampleModal" class="reveal-modal">
    ........
    <a href="#">Close Modal</a>
    </div>
</div>

JSFiddle - Updated with CSS only

Escape @ character in razor view engine

Razor @ escape char to symbols...

<img src="..." alt="Find me on twitter as @("@username")" />

or

<img src="..." alt="Find me on twitter as @("@")username" />

strcpy() error in Visual studio 2012

A quick fix is to add the _CRT_SECURE_NO_WARNINGS definition to your project's settings

Right-click your C++ and chose the "Properties" item to get to the properties window.

Now follow and expand to, "Configuration Properties"->"C/C++"->"Preprocessor"->"Preprocessor definitions".

In the "Preprocessor definitions" add

_CRT_SECURE_NO_WARNINGS

but it would be a good idea to add

_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)

as to inherit predefined definitions

IMHO & for the most part this is a good approach.

How to find good looking font color if background color is known?

Might be strange to answer my own question, but here is another really cool color picker I never saw before. It does not solve my problem either :-(((( however I think it's much cooler to these I know already.

http://www.colorjack.com/

On the right, under Tools select "Color Sphere", a very powerful and customizable sphere (see what you can do with the pop-ups on top), "Color Galaxy", I'm still not sure how this works, but looks cool and "Color Studio" is also nice. Further it can export to all kind of formats (e.g. Illustrator or Photoshop, etc.)

How about this, I choose my background color there, let it create a complimentary color (from the first pop up) - this should have highest contrast and thus be best readable, now select the complementary color as main color and select neutral? Hmmm... not too great either, but we are getting better ;-)

How to Define Callbacks in Android?

to clarify a bit on dragon's answer (since it took me a while to figure out what to do with Handler.Callback):

Handler can be used to execute callbacks in the current or another thread, by passing it Messages. the Message holds data to be used from the callback. a Handler.Callback can be passed to the constructor of Handler in order to avoid extending Handler directly. thus, to execute some code via callback from the current thread:

Message message = new Message();
<set data to be passed to callback - eg message.obj, message.arg1 etc - here>

Callback callback = new Callback() {
    public boolean handleMessage(Message msg) {
        <code to be executed during callback>
    }
};

Handler handler = new Handler(callback);
handler.sendMessage(message);

EDIT: just realized there's a better way to get the same result (minus control of exactly when to execute the callback):

post(new Runnable() {
    @Override
    public void run() {
        <code to be executed during callback>
    }
});

How to have stored properties in Swift, the same way I had on Objective-C?

My $0.02. This code is written in Swift 2.0

extension CALayer {
    private struct AssociatedKeys {
        static var shapeLayer:CAShapeLayer?
    }

    var shapeLayer: CAShapeLayer? {
        get {
            return objc_getAssociatedObject(self, &AssociatedKeys.shapeLayer) as? CAShapeLayer
        }
        set {
            if let newValue = newValue {
                objc_setAssociatedObject(self, &AssociatedKeys.shapeLayer, newValue as CAShapeLayer?, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            }
        }
    }
}

I have tried many solutions, and found this is the only way to actually extend a class with extra variable parameters.

Best practices for styling HTML emails

Mail chimp have got quite a nice article on what not to do. ( I know it sounds the wrong way round for what you want)

http://kb.mailchimp.com/article/common-html-email-coding-mistakes

In general all the things that you have learnt that are bad practise for web design seem to be the only option for html email.

The basics are:

  • Have absolute paths for images (eg. https://stackoverflow.com/random-image.png)
  • Use tables for layout (never thought I'd recommend that!)
  • Use inline styles (and old school css too, at the very most 2.1, box-shadow won't work for instance ;) )

Just test in as many email clients as you can get your hands on, or use Litmus as someone else suggested above! (credit to Jim)

EDIT :

Mail chimp have done a great job by making this tool available to the community.

It applies your CSS classes to your html elements inline for you!

LINQ to SQL - How to select specific columns and return strongly typed list

Basically you are doing it the right way. However, you should use an instance of the DataContext for querying (it's not obvious that DataContext is an instance or the type name from your query):

var result = (from a in new DataContext().Persons
              where a.Age > 18
              select new Person { Name = a.Name, Age = a.Age }).ToList();

Apparently, the Person class is your LINQ to SQL generated entity class. You should create your own class if you only want some of the columns:

class PersonInformation {
   public string Name {get;set;}
   public int Age {get;set;}
}

var result = (from a in new DataContext().Persons
              where a.Age > 18
              select new PersonInformation { Name = a.Name, Age = a.Age }).ToList();

You can freely swap var with List<PersonInformation> here without affecting anything (as this is what the compiler does).

Otherwise, if you are working locally with the query, I suggest considering an anonymous type:

var result = (from a in new DataContext().Persons
              where a.Age > 18
              select new { a.Name, a.Age }).ToList();

Note that in all of these cases, the result is statically typed (it's type is known at compile time). The latter type is a List of a compiler generated anonymous class similar to the PersonInformation class I wrote above. As of C# 3.0, there's no dynamic typing in the language.

UPDATE:

If you really want to return a List<Person> (which might or might not be the best thing to do), you can do this:

var result = from a in new DataContext().Persons
             where a.Age > 18
             select new { a.Name, a.Age };

List<Person> list = result.AsEnumerable()
                          .Select(o => new Person {
                                           Name = o.Name, 
                                           Age = o.Age
                          }).ToList();

You can merge the above statements too, but I separated them for clarity.

What is the difference between Integer and int in Java?

An Integer is pretty much just a wrapper for the primitive type int. It allows you to use all the functions of the Integer class to make life a bit easier for you.

If you're new to Java, something you should learn to appreciate is the Java documentation. For example, anything you want to know about the Integer Class is documented in detail.

This is straight out of the documentation for the Integer class:

The Integer class wraps a value of the primitive type int in an object. An object of type Integer contains a single field whose type is int.

Using 'starts with' selector on individual class names

this is for prefix with

$("div[class^='apple-']")

this is for starts with so you dont need to have the '-' char in there

$("div[class|='apple']")

you can find a bunch of other cool variations of the jQuery selector here https://api.jquery.com/category/selectors/

React-Native: Application has not been registered error

I think the node server is running from another folder. So kill it and run in the current folder.

Find running node server:-

lsof -i :8081

Kill running node server :-

kill -9 <PID>

Eg:-

kill -9 1653

Start node server from current react native folder:-

react-native run-android

Unzip All Files In A Directory

for i in `ls *.zip`; do unzip $i; done

How to add a scrollbar to an HTML5 table?

My simplest solution is based on fixed columns layout. You'll have to set the width of each column, for example: 4 columns 100px each is equal to 400px total width.

table {
  table-layout: fixed;
  width: 400px;
}
td, th {
  width: 100px;
}

The fixed table layout algorithm has many advantages over the automatic table layout algorithm (for example: the horizontal layout only depends on the table's width and the width of the columns, not the contents of the cells; allows a browser to lay out the table faster than the automatic table layout; the browser can begin to display the table once the first row has been received; etc.)

Then, you'll have to separate the thead from the tbody by forcing their display style to block rather than to the default table-*

thead tr {
  display: block;
}
tbody {
  display: block;
  height: 256px;
  overflow-y: auto;
}

That what will make the tbody scrollable as a separate box and the thead unrelated from it. And that's the main reason why you had to fix the column widths as done above.

Working JsFiddle: https://jsfiddle.net/angiolep/65q1gdcy/1/

Favorite Visual Studio keyboard shortcuts

VS 2008

  1. Ctrl+E,D : Format Code

  2. Ctrl+M,O : Collapse To Definitions

  3. Ctrl+Z : Undo :)

  4. F9: Breakpoint

  5. Ctrl+Shift+F9 : Delete All Breakpoints

Android Studio cannot resolve R in imported project?

File -> invalidate caches

then

Restart application

How to print a single backslash?

A backslash needs to be escaped with another backslash.

print('\\')

Using setDate in PreparedStatement

tl;dr

With JDBC 4.2 or later and java 8 or later:

myPreparedStatement.setObject( … , myLocalDate  )

…and…

myResultSet.getObject( … , LocalDate.class )

Details

The Answer by Vargas is good about mentioning java.time types but refers only to converting to java.sql.Date. No need to convert if your driver is updated.

java.time

The java.time framework is built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat. The Joda-Time team also advises migration to java.time.

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

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.

LocalDate

In java.time, the java.time.LocalDate class represents a date-only value without time-of-day and without time zone.

If using a JDBC driver compliant with JDBC 4.2 or later spec, no need to use the old java.sql.Date class. You can pass/fetch LocalDate objects directly to/from your database via PreparedStatement::setObject and ResultSet::getObject.

LocalDate localDate = LocalDate.now( ZoneId.of( "America/Montreal" ) );
myPreparedStatement.setObject( 1 , localDate  );

…and…

LocalDate localDate = myResultSet.getObject( 1 , LocalDate.class );

Before JDBC 4.2, convert

If your driver cannot handle the java.time types directly, fall back to converting to java.sql types. But minimize their use, with your business logic using only java.time types.

New methods have been added to the old classes for conversion to/from java.time types. For java.sql.Date see the valueOf and toLocalDate methods.

java.sql.Date sqlDate = java.sql.Date.valueOf( localDate );

…and…

LocalDate localDate = sqlDate.toLocalDate();

Placeholder value

Be wary of using 0000-00-00 as a placeholder value as shown in your Question’s code. Not all databases and other software can handle going back that far in time. I suggest using something like the commonly-used Unix/Posix epoch reference date of 1970, 1970-01-01.

LocalDate EPOCH_DATE = LocalDate.ofEpochDay( 0 ); // 1970-01-01 is day 0 in Epoch counting.

About java.time

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

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

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

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

Where to obtain the java.time classes?

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

how to make jni.h be found?

Installing the OpenJDK Development Kit (JDK) should fix your problem.

sudo apt-get install openjdk-X-jdk

This should make you able to compile without problems.

How to customize Bootstrap 3 tab color

On the selector .nav-tabs > li > a:hover add !important to the background-color.

_x000D_
_x000D_
.nav-tabs{_x000D_
  background-color:#161616;_x000D_
}_x000D_
.tab-content{_x000D_
    background-color:#303136;_x000D_
    color:#fff;_x000D_
    padding:5px_x000D_
}_x000D_
.nav-tabs > li > a{_x000D_
  border: medium none;_x000D_
}_x000D_
.nav-tabs > li > a:hover{_x000D_
  background-color: #303136 !important;_x000D_
    border: medium none;_x000D_
    border-radius: 0;_x000D_
    color:#fff;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>_x000D_
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<ul class="nav nav-tabs" id="myTab">_x000D_
    <li class="active"><a data-toggle="tab" href="#search">SEARCH</a></li>_x000D_
    <li><a data-toggle="tab" href="#advanced">ADVANCED</a></li>_x000D_
</ul>_x000D_
<div class="tab-content">_x000D_
    <div id="search" class="tab-pane fade in active">_x000D_
        Aliquip placeat salvia cillum iphone. Seitan aliquip quis cardigan american apparel,_x000D_
        butcher voluptate nisi qui._x000D_
    </div>_x000D_
    <div id="advanced" class="tab-pane fade">_x000D_
        Vestibulum nec erat eu nulla rhoncus fringilla ut non neque. Vivamus nibh urna._x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

jQuery slide left and show

Don't forget the padding and margins...

jQuery.fn.slideLeftHide = function(speed, callback) { 
  this.animate({ 
    width: "hide", 
    paddingLeft: "hide", 
    paddingRight: "hide", 
    marginLeft: "hide", 
    marginRight: "hide" 
  }, speed, callback);
}

jQuery.fn.slideLeftShow = function(speed, callback) { 
  this.animate({ 
    width: "show", 
    paddingLeft: "show", 
    paddingRight: "show", 
    marginLeft: "show", 
    marginRight: "show" 
  }, speed, callback);
}

With the speed/callback arguments added, it's a complete drop-in replacement for slideUp() and slideDown().

How to read first N lines of a file?

Python 2:

with open("datafile") as myfile:
    head = [next(myfile) for x in xrange(N)]
print head

Python 3:

with open("datafile") as myfile:
    head = [next(myfile) for x in range(N)]
print(head)

Here's another way (both Python 2 & 3):

from itertools import islice

with open("datafile") as myfile:
    head = list(islice(myfile, N))
print(head)

Determining if Swift dictionary contains key and obtaining any of its values

You don't need any special code to do this, because it is what a dictionary already does. When you fetch dict[key] you know whether the dictionary contains the key, because the Optional that you get back is not nil (and it contains the value).

So, if you just want to answer the question whether the dictionary contains the key, ask:

let keyExists = dict[key] != nil

If you want the value and you know the dictionary contains the key, say:

let val = dict[key]!

But if, as usually happens, you don't know it contains the key - you want to fetch it and use it, but only if it exists - then use something like if let:

if let val = dict[key] {
    // now val is not nil and the Optional has been unwrapped, so use it
}

How do you access a website running on localhost from iPhone browser

  1. Firstly, your have to confirm that you also access server api via your mac ip on mac browser. If not, make sure your server allow do that instead of just localhost (127.0.0.1) by runing your server on 0.0.0.0
  2. Go to safari on iphone and make a get request by api your server serve: ex http://0.0.0.0/st. Safari auto redirect to server your mac runing (at your mac ip)
  3. If you want to make request on your iphone app. It shoud be repalce requet 0.0.0.0 by [your mac/server ip]

curl : (1) Protocol https not supported or disabled in libcurl

I ran into this problem and turned out that there was a space before the https which was causing the problem. " https://" vs "https://"

Adding timestamp to a filename with mv in BASH

The few lines you posted from your script look okay to me. It's probably something a bit deeper.

You need to find which line is giving you this error. Add set -xv to the top of your script. This will print out the line number and the command that's being executed to STDERR. This will help you identify where in your script you're getting this particular error.

BTW, do you have a shebang at the top of your script? When I see something like this, I normally expect its an issue with the Shebang. For example, if you had #! /bin/bash on top, but your bash interpreter is located in /usr/bin/bash, you'll see this error.

EDIT

New question: How can I save the file correctly in the first place, to avoid having to perform this fix every time I resend the file?

Two ways:

  1. Select the Edit->EOL Conversion->Unix Format menu item when you edit a file. Once it has the correct line endings, Notepad++ will keep them.
  2. To make sure all new files have the correct line endings, go to the Settings->Preferences menu item, and pull up the Preferences dialog box. Select the New Document/Default Directory tab. Under New Document and Format, select the Unix radio button. Click the Close button.

How to add Python to Windows registry

I faced to the same problem. I solved it by

  1. navigate to HKEY_CURRENT_USER\Software\Python\PythonCore\3.4\InstallPath and edit the default key with the output of C:\> where python.exe command.
  2. navigate to HKEY_CURRENT_USER\Software\Python\PythonCore\3.4\InstallPath\InstallGroup and edit the default key with Python 3.4

Note: My python version is 3.4 and you need to replace 3.4 with your python version.

Normally you can find Registry entries for Python in HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\<version>. You just need to copy those entries to HKEY_CURRENT_USER\Software\Python\PythonCore\<version>

Regular expression to match a line that doesn't contain a word

If you want to match a character to negate a word similar to negate character class:

For example, a string:

<?
$str="aaa        bbb4      aaa     bbb7";
?>

Do not use:

<?
preg_match('/aaa[^bbb]+?bbb7/s', $str, $matches);
?>

Use:

<?
preg_match('/aaa(?:(?!bbb).)+?bbb7/s', $str, $matches);
?>

Notice "(?!bbb)." is neither lookbehind nor lookahead, it's lookcurrent, for example:

"(?=abc)abcde", "(?!abc)abcde"

How to read a Parquet file into Pandas DataFrame?

Update: since the time I answered this there has been a lot of work on this look at Apache Arrow for a better read and write of parquet. Also: http://wesmckinney.com/blog/python-parquet-multithreading/

There is a python parquet reader that works relatively well: https://github.com/jcrobak/parquet-python

It will create python objects and then you will have to move them to a Pandas DataFrame so the process will be slower than pd.read_csv for example.

Convert this string to datetime

Use DateTime::createFromFormat

$date = date_create_from_format('d/m/Y:H:i:s', $s);
$date->getTimestamp();

Set database timeout in Entity Framework

Try this on your context:

public class MyDatabase : DbContext
{
    public MyDatabase ()
        : base(ContextHelper.CreateConnection("Connection string"), true)
    {
        ((IObjectContextAdapter)this).ObjectContext.CommandTimeout = 180; // seconds
    }
}

If you want to define the timeout in the connection string, use the Connection Timeout parameter like in the following connection string:

<connectionStrings>

<add name="AdventureWorksEntities"
connectionString="metadata=.\AdventureWorks.csdl|.\AdventureWorks.ssdl|.\AdventureWorks.msl;
provider=System.Data.SqlClient;provider connection string='Data Source=localhost;
Initial Catalog=AdventureWorks;Integrated Security=True;Connection Timeout=60;
multipleactiveresultsets=true'" providerName="System.Data.EntityClient" />

</connectionStrings>

Source: How to: Define the Connection String

How to change the ROOT application?

In Tomcat 7 (under Windows server) I didn't add or edit anything to any configuration file. I just renamed the ROOT folder to something else and renamed my application folder to ROOT and it worked fine.

What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?

You can use function closures as data in larger expressions as well, as in this method of determining browser support for some of the html5 objects.

   navigator.html5={
     canvas: (function(){
      var dc= document.createElement('canvas');
      if(!dc.getContext) return 0;
      var c= dc.getContext('2d');
      return typeof c.fillText== 'function'? 2: 1;
     })(),
     localStorage: (function(){
      return !!window.localStorage;
     })(),
     webworkers: (function(){
      return !!window.Worker;
     })(),
     offline: (function(){
      return !!window.applicationCache;
     })()
    }

How to execute function in SQL Server 2008

you may be create function before so, update your function again using.

Alter FUNCTION dbo.Afisho_rankimin(@emri_rest int)
RETURNS int
AS
  BEGIN
     Declare @rankimi int
     Select @rankimi=dbo.RESTORANTET.Rankimi
     From RESTORANTET
     Where  dbo.RESTORANTET.ID_Rest=@emri_rest
     RETURN @rankimi
END
GO

SELECT dbo.Afisho_rankimin(5) AS Rankimi
GO

Mockito How to mock and assert a thrown exception?

Unrelated to mockito, one can catch the exception and assert its properties. To verify that the exception did happen, assert a false condition within the try block after the statement that throws the exception.

Encrypt & Decrypt using PyCrypto AES 256

For someone who would like to use urlsafe_b64encode and urlsafe_b64decode, here are the version that're working for me (after spending some time with the unicode issue)

BS = 16
key = hashlib.md5(settings.SECRET_KEY).hexdigest()[:BS]
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
unpad = lambda s : s[:-ord(s[len(s)-1:])]

class AESCipher:
    def __init__(self, key):
        self.key = key

    def encrypt(self, raw):
        raw = pad(raw)
        iv = Random.new().read(AES.block_size)
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        return base64.urlsafe_b64encode(iv + cipher.encrypt(raw)) 

    def decrypt(self, enc):
        enc = base64.urlsafe_b64decode(enc.encode('utf-8'))
        iv = enc[:BS]
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        return unpad(cipher.decrypt(enc[BS:]))

How to view kafka message

Use the Kafka consumer provided by Kafka :

bin/kafka-console-consumer.sh --bootstrap-server BROKERS --topic TOPIC_NAME

It will display the messages as it will receive it. Add --from-beginning if you want to start from the beginning.

How do I include a JavaScript file in another JavaScript file?

This script will add a JavaScript file to the top of any other <script> tag:

(function () {
    var li = document.createElement('script'); 
    li.type = 'text/javascript'; 
    li.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"; 
    li.async = true; 
    var s = document.getElementsByTagName('script')[0]; 
    s.parentNode.insertBefore(li, s);
})();

Initializing a static std::map<int, int> in C++

You can try:

std::map <int, int> mymap = 
{
        std::pair <int, int> (1, 1),
        std::pair <int, int> (2, 2),
        std::pair <int, int> (2, 2)
};

Referencing Row Number in R

These are present by default as rownames when you create a data.frame.

R> df = data.frame('a' = rnorm(10), 'b' = runif(10), 'c' = letters[1:10])
R> df
            a          b c
1   0.3336944 0.39746731 a
2  -0.2334404 0.12242856 b
3   1.4886706 0.07984085 c
4  -1.4853724 0.83163342 d
5   0.7291344 0.10981827 e
6   0.1786753 0.47401690 f
7  -0.9173701 0.73992239 g
8   0.7805941 0.91925413 h
9   0.2469860 0.87979229 i
10  1.2810961 0.53289335 j

and you can access them via the rownames command.

R> rownames(df)
 [1] "1"  "2"  "3"  "4"  "5"  "6"  "7"  "8"  "9"  "10"

if you need them as numbers, simply coerce to numeric by adding as.numeric, as in as.numeric(rownames(df)).

You don't need to add them, as if you know what you are looking for (say item df$c == 'i', you can use the which command:

R> which(df$c =='i')
[1] 9

or if you don't know the column

R> which(df == 'i', arr.ind=T)
     row col
[1,]   9   3

you may access the element using df[9, 'c'], or df$c[9].

If you wanted to add them you could use df$rownumber <- as.numeric(rownames(df)), though this may be less robust than df$rownumber <- 1:nrow(df) as there are cases when you might have assigned to rownames so they will no longer be the default index numbers (the which command will continue to return index numbers even if you do assign to rownames).

Maven 3 and JUnit 4 compilation problem: package org.junit does not exist

Add this dependency to your pom.xml file:

http://mvnrepository.com/artifact/junit/junit-dep/4.8.2

<!-- https://mvnrepository.com/artifact/junit/junit-dep -->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit-dep</artifactId>
    <version>4.8.2</version>
</dependency>

Get query string parameters url values with jQuery / Javascript (querystring)

Found this gem from our friends over at SitePoint. https://www.sitepoint.com/url-parameters-jquery/.

Using PURE jQuery. I just used this and it worked. Tweaked it a bit for example sake.

//URL is http://www.example.com/mypage?ref=registration&[email protected]

$.urlParam = function (name) {
    var results = new RegExp('[\?&]' + name + '=([^&#]*)')
                      .exec(window.location.search);

    return (results !== null) ? results[1] || 0 : false;
}

console.log($.urlParam('ref')); //registration
console.log($.urlParam('email')); //[email protected]

Use as you will.

Apply function to all elements of collection through LINQ

Or you can hack it up.

Items.All(p => { p.IsAwesome = true; return true; });

What is tail recursion?

An important point is that tail recursion is essentially equivalent to looping. It's not just a matter of compiler optimization, but a fundamental fact about expressiveness. This goes both ways: you can take any loop of the form

while(E) { S }; return Q

where E and Q are expressions and S is a sequence of statements, and turn it into a tail recursive function

f() = if E then { S; return f() } else { return Q }

Of course, E, S, and Q have to be defined to compute some interesting value over some variables. For example, the looping function

sum(n) {
  int i = 1, k = 0;
  while( i <= n ) {
    k += i;
    ++i;
  }
  return k;
}

is equivalent to the tail-recursive function(s)

sum_aux(n,i,k) {
  if( i <= n ) {
    return sum_aux(n,i+1,k+i);
  } else {
    return k;
  }
}

sum(n) {
  return sum_aux(n,1,0);
}

(This "wrapping" of the tail-recursive function with a function with fewer parameters is a common functional idiom.)

Add Auto-Increment ID to existing table?

Delete the primary key of a table if it exists:

 ALTER TABLE `tableName` DROP PRIMARY KEY;

Adding an auto-increment column to a table :

ALTER TABLE `tableName` ADD `Column_name` INT PRIMARY KEY AUTO_INCREMENT;

Modify the column which we want to consider as the primary key:

alter table `tableName` modify column `Column_name` INT NOT NULL AUTO_INCREMENT PRIMARY KEY;

How to read a text file in project's root directory?

From Solution Explorer, right click on myfile.txt and choose "Properties"

From there, set the Build Action to content and Copy to Output Directory to either Copy always or Copy if newer

enter image description here

CMake output/build directory

There's little need to set all the variables you're setting. CMake sets them to reasonable defaults. You should definitely not modify CMAKE_BINARY_DIR or CMAKE_CACHEFILE_DIR. Treat these as read-only.

First remove the existing problematic cache file from the src directory:

cd src
rm CMakeCache.txt
cd ..

Then remove all the set() commands and do:

cd Compile && rm -rf *
cmake ../src

As long as you're outside of the source directory when running CMake, it will not modify the source directory unless your CMakeList explicitly tells it to do so.

Once you have this working, you can look at where CMake puts things by default, and only if you're not satisfied with the default locations (such as the default value of EXECUTABLE_OUTPUT_PATH), modify only those you need. And try to express them relative to CMAKE_BINARY_DIR, CMAKE_CURRENT_BINARY_DIR, PROJECT_BINARY_DIR etc.

If you look at CMake documentation, you'll see variables partitioned into semantic sections. Except for very special circumstances, you should treat all those listed under "Variables that Provide Information" as read-only inside CMakeLists.

Checking if a folder exists using a .bat file

I think the answer is here (possibly duplicate):

How to test if a file is a directory in a batch script?

IF EXIST %VAR%\NUL ECHO It's a directory

Replace %VAR% with your directory. Please read the original answer because includes details about handling white spaces in the folder name.

As foxidrive said, this might not be reliable on NT class windows. It works for me, but I know it has some limitations (which you can find in the referenced question)

if exist "c:\folder\" echo folder exists 

should be enough for modern windows.

error: No resource identifier found for attribute 'adSize' in package 'com.google.example' main.xml

I had a similar issue on MonoDroid when building a class library with Drawables and Layouts files that have "android:" attribute in the xml. I get a similar error as the one in the question.

No resource identifier found for attribute 'textCursorDrawable' in package 'android'

I found from that "android: " attribute is only available in Android API Level 12+ and I was trying to build for an older version. Updating my project to build against Android 4.0 fixed the issue for me. Here is where I found the answer. https://groups.google.com/forum/?fromgroups#!topic/android-developers/ocxKphM5MWM Just make sure that you are building against the right API level if you get a similar issue, and ensure that the missing identifier exists in that API level that you are build against.

Int to Char in C#

Although not exactly answering the question as formulated, but if you need or can take the end result as string you can also use

string s = Char.ConvertFromUtf32(56);

which will give you surrogate UTF-16 pairs if needed, protecting you if you are out side of the BMP.

PHP Error: Cannot use object of type stdClass as array (array and object issues)

The example you copied from is using data in the form of an array holding arrays, you are using data in the form of an array holding objects. Objects and arrays are not the same, and because of this they use different syntaxes for accessing data.

If you don't know the variable names, just do a var_dump($blog); within the loop to see them.

The simplest method - access $blog as an object directly:

Try (assuming those variables are correct):

<?php 
    foreach ($blogs as $blog) {
        $id         = $blog->id;
        $title      = $blog->title;
        $content    = $blog->content;
?>

<h1> <?php echo $title; ?></h1>
<h1> <?php echo $content; ?> </h1>

<?php } ?>

The alternative method - access $blog as an array:

Alternatively, you may be able to turn $blog into an array with get_object_vars (documentation):

<?php
    foreach($blogs as &$blog) {
        $blog     = get_object_vars($blog);
        $id       = $blog['id'];
        $title    = $blog['title'];
        $content  = $blog['content'];
?>

<h1> <?php echo $title; ?></h1>
<h1> <?php echo $content; ?> </h1>

<?php } ?> 

It's worth mentioning that this isn't necessarily going to work with nested objects so its viability entirely depends on the structure of your $blog object.

Better than either of the above - Inline PHP Syntax

Having said all that, if you want to use PHP in the most readable way, neither of the above are right. When using PHP intermixed with HTML, it's considered best practice by many to use PHP's alternative syntax, this would reduce your whole code from nine to four lines:

<?php foreach($blogs as $blog): ?>
    <h1><?php echo $blog->title; ?></h1>
    <p><?php echo $blog->content; ?></p>
<?php endforeach; ?>

Hope this helped.

CSS align one item right with flexbox

To align one flex child to the right set it withmargin-left: auto;

From the flex spec:

One use of auto margins in the main axis is to separate flex items into distinct "groups". The following example shows how to use this to reproduce a common UI pattern - a single bar of actions with some aligned on the left and others aligned on the right.

.wrap div:last-child {
  margin-left: auto;
}

Updated fiddle

_x000D_
_x000D_
.wrap {_x000D_
  display: flex;_x000D_
  background: #ccc;_x000D_
  width: 100%;_x000D_
  justify-content: space-between;_x000D_
}_x000D_
.wrap div:last-child {_x000D_
  margin-left: auto;_x000D_
}_x000D_
.result {_x000D_
  background: #ccc;_x000D_
  margin-top: 20px;_x000D_
}_x000D_
.result:after {_x000D_
  content: '';_x000D_
  display: table;_x000D_
  clear: both;_x000D_
}_x000D_
.result div {_x000D_
  float: left;_x000D_
}_x000D_
.result div:last-child {_x000D_
  float: right;_x000D_
}
_x000D_
<div class="wrap">_x000D_
  <div>One</div>_x000D_
  <div>Two</div>_x000D_
  <div>Three</div>_x000D_
</div>_x000D_
_x000D_
<!-- DESIRED RESULT -->_x000D_
<div class="result">_x000D_
  <div>One</div>_x000D_
  <div>Two</div>_x000D_
  <div>Three</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Note:

You could achieve a similar effect by setting flex-grow:1 on the middle flex item (or shorthand flex:1) which would push the last item all the way to the right. (Demo)

The obvious difference however is that the middle item becomes bigger than it may need to be. Add a border to the flex items to see the difference.

Demo

_x000D_
_x000D_
.wrap {_x000D_
  display: flex;_x000D_
  background: #ccc;_x000D_
  width: 100%;_x000D_
  justify-content: space-between;_x000D_
}_x000D_
.wrap div {_x000D_
  border: 3px solid tomato;_x000D_
}_x000D_
.margin div:last-child {_x000D_
  margin-left: auto;_x000D_
}_x000D_
.grow div:nth-child(2) {_x000D_
  flex: 1;_x000D_
}_x000D_
.result {_x000D_
  background: #ccc;_x000D_
  margin-top: 20px;_x000D_
}_x000D_
.result:after {_x000D_
  content: '';_x000D_
  display: table;_x000D_
  clear: both;_x000D_
}_x000D_
.result div {_x000D_
  float: left;_x000D_
}_x000D_
.result div:last-child {_x000D_
  float: right;_x000D_
}
_x000D_
<div class="wrap margin">_x000D_
  <div>One</div>_x000D_
  <div>Two</div>_x000D_
  <div>Three</div>_x000D_
</div>_x000D_
_x000D_
<div class="wrap grow">_x000D_
  <div>One</div>_x000D_
  <div>Two</div>_x000D_
  <div>Three</div>_x000D_
</div>_x000D_
_x000D_
<!-- DESIRED RESULT -->_x000D_
<div class="result">_x000D_
  <div>One</div>_x000D_
  <div>Two</div>_x000D_
  <div>Three</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Running bash script from within python

Make sure that sleep.sh has execution permissions, and run it with shell=True:

#!/usr/bin/python

import subprocess
print "start"
subprocess.call("./sleep.sh", shell=True)
print "end"

How do you receive a url parameter with a spring controller mapping

You should be using @RequestParam instead of @ModelAttribute, e.g.

@RequestMapping("/{someID}")
public @ResponseBody int getAttr(@PathVariable(value="someID") String id, 
                                 @RequestParam String someAttr) {
}

You can even omit @RequestParam altogether if you choose, and Spring will assume that's what it is:

@RequestMapping("/{someID}")
public @ResponseBody int getAttr(@PathVariable(value="someID") String id, 
                                 String someAttr) {
}

How do I scroll to an element using JavaScript?

scrollIntoView works well:

document.getElementById("divFirst").scrollIntoView();

full reference in the MDN docs:
https://developer.mozilla.org/en-US/docs/Web/API/Element.scrollIntoView

CSS to line break before/after a particular `inline-block` item

I know you didn't want to use floats and the question was just theory but in case anyone finds this useful, here's a solution using floats.

Add a class of left to your li elements that you want to float:

<li class="left"><img src="http://phrogz.net/tmp/alphaball.png">Smells Good</li>

and amend your CSS as follows:

li { text-align:center; float: left; clear: left; padding:0.1em 1em }
.left {float: left; clear: none;}

http://jsfiddle.net/chut319/xJ3pe/

You don't need to specify widths or inline-blocks and works as far back as IE6.

How do I set the default font size in Vim?

Add Regular to syntax and use gfn:

set gfn= Monospace\ Regular:h13