Programs & Examples On #Actionviewhelper

Helper classes for [tag:actionview]

COUNT / GROUP BY with active record?

This code counts rows with date range:

Controller:

$this->load->model("YourModelName");
$data ['query'] = $this->YourModelName->get_report();

Model:

  public function get_report()
     {   
       $query = $this->db->query("SELECT  *
FROM   reservation WHERE arvdate <= '2016-7-20' AND  dptrdate >= '2016-10-25' ");
       return $query;
     }

where 'arvdate' and 'dptrdate' are two dates on database and 'reservation' is the table name.

View:

<?php
 echo $query->num_rows();
?>

This code is to return number of rows. To return table data, then use

$query->rows();
return $row->table_column_name;

C# guid and SQL uniqueidentifier

Here's a code snippet showing how to insert a GUID using a parameterised query:

    using(SqlConnection conn = new SqlConnection(connectionString))
    {
        conn.Open();
        using(SqlTransaction trans = conn.BeginTransaction())
        using (SqlCommand cmd = conn.CreateCommand())
        {
            cmd.Transaction = trans;
            cmd.CommandText = @"INSERT INTO [MYTABLE] ([GuidValue]) VALUE @guidValue;";
            cmd.Parameters.AddWithValue("@guidValue", Guid.NewGuid());
            cmd.ExecuteNonQuery();
            trans.Commit();
        }
    }

How to make a input field readonly with JavaScript?

document.getElementById("").readOnly = true

how to implement Interfaces in C++?

Interface are nothing but a pure abstract class in C++. Ideally this interface class should contain only pure virtual public methods and static const data. For example:

class InterfaceA
{
public:
  static const int X = 10;

  virtual void Foo() = 0;
  virtual int Get() const = 0;
  virtual inline ~InterfaceA() = 0;
};
InterfaceA::~InterfaceA () {}

Refreshing page on click of a button

<button type="button" onClick="refreshPage()">Close</button>

<script>
function refreshPage(){
    window.location.reload();
} 
</script>

or

<button type="button" onClick="window.location.reload();">Close</button>

Convert INT to DATETIME (SQL)

Try this:

select CONVERT(datetime, convert(varchar(10), 20120103))

Best way to store a key=>value array in JavaScript?

I know its late but it might be helpful for those that want other ways. Another way array key=>values can be stored is by using an array method called map(); (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) you can use arrow function too

 
    var countries = ['Canada','Us','France','Italy'];  
// Arrow Function
countries.map((value, key) => key+ ' : ' + value );
// Anonomous Function
countries.map(function(value, key){
return key + " : " + value;
});

Regex Email validation

I've created a FormValidationUtils class to validate email:

public static class FormValidationUtils
{
    const string ValidEmailAddressPattern = "^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$";

    public static bool IsEmailValid(string email)
    {
        var regex = new Regex(ValidEmailAddressPattern, RegexOptions.IgnoreCase);
        return regex.IsMatch(email);
    }
}

C# DLL config file

When using ConfigurationManager, I'm pretty sure it is loading the process/AppDomain configuration file (app.config / web.config). If you want to load a specific config file, you'll have to specifically ask for that file by name...

You could try:

var config = ConfigurationManager.OpenExeConfiguration("foo.dll");
config.ConnectionStrings. [etc]

What does -save-dev mean in npm install grunt --save-dev

--save-dev means "needed only when developing"

  • e.g. the final users using your package will not want/need/care about what testing suite you used; they will only want packages that are absolutely required to run your code in a production environment. This flag marks what is needed when developing vs production.

Generating a drop down list of timezones with PHP

In some projects it really doesn't make sense to have the detailed timezones of Africa, Europe or Pacific. So here is a short version

$timezoneTable = array(
    "-12" => "(GMT -12:00) Eniwetok, Kwajalein",
    "-11" => "(GMT -11:00) Midway Island, Samoa",
    "-10" => "(GMT -10:00) Hawaii",
    "-9" => "(GMT -9:00) Alaska",
    "-8" => "(GMT -8:00) Pacific Time (US &amp; Canada)",
    "-7" => "(GMT -7:00) Mountain Time (US &amp; Canada)",
    "-6" => "(GMT -6:00) Central Time (US &amp; Canada), Mexico City",
    "-5" => "(GMT -5:00) Eastern Time (US &amp; Canada), Bogota, Lima",
    "-4" => "(GMT -4:00) Atlantic Time (Canada), Caracas, La Paz",
    "-3.5" => "(GMT -3:30) Newfoundland",
    "-3" => "(GMT -3:00) Brazil, Buenos Aires, Georgetown",
    "-2" => "(GMT -2:00) Mid-Atlantic",
    "-1" => "(GMT -1:00) Azores, Cape Verde Islands",
    "0" => "(GMT) Western Europe Time, London, Lisbon, Casablanca",
    "1" => "(GMT +1:00) Brussels, Copenhagen, Madrid, Paris",
    "2" => "(GMT +2:00) Kaliningrad, South Africa",
    "3" => "(GMT +3:00) Baghdad, Riyadh, Moscow, St. Petersburg",
    "3.5" => "(GMT +3:30) Tehran",
    "4" => "(GMT +4:00) Abu Dhabi, Muscat, Baku, Tbilisi",
    "4.5" => "(GMT +4:30) Kabul",
    "5" => "(GMT +5:00) Ekaterinburg, Islamabad, Karachi, Tashkent",
    "5.5" => "(GMT +5:30) Bombay, Calcutta, Madras, New Delhi",
    "6" => "(GMT +6:00) Almaty, Dhaka, Colombo",
    "7" => "(GMT +7:00) Bangkok, Hanoi, Jakarta",
    "8" => "(GMT +8:00) Beijing, Perth, Singapore, Hong Kong",
    "9" => "(GMT +9:00) Tokyo, Seoul, Osaka, Sapporo, Yakutsk",
    "9.5" => "(GMT +9:30) Adelaide, Darwin",
    "10" => "(GMT +10:00) Eastern Australia, Guam, Vladivostok",
    "11" => "(GMT +11:00) Magadan, Solomon Islands, New Caledonia",
    "12" => "(GMT +12:00) Auckland, Wellington, Fiji, Kamchatka"
);

echo "<select>";
foreach ($timezoneTable as $k => $v){
    $sel = ($k==-5)?" selected":"";
    echo "<option value='".$k."'".$sel.">".$v."</option>";
}
echo "</select>" 

this will generate a select as below:

enter image description here

how do I check in bash whether a file was created more than x time ago?

Although ctime isn't technically the time of creation, it quite often is.

Since ctime it isn't affected by changes to the contents of the file, it's usually only updated when the file is created. And yes - I can hear you all screaming - it's also updated if you change the access permissions or ownership... but generally that's something that's done once, usually at the same time you put the file there.

Personally I always use mtime for everything, and I imagine that is what you want. But anyway... here's a rehash of Guss's "unattractive" bash, in an easy to use function.

#!/bin/bash
function age() {
   local filename=$1
   local changed=`stat -c %Y "$filename"`
   local now=`date +%s`
   local elapsed

   let elapsed=now-changed
   echo $elapsed
}

file="/"
echo The age of $file is $(age "$file") seconds.

Sys is undefined

In case none of the above works for you, and you happen to be overriding OnPreRenderComplete, make sure you call base.OnPreRenderComplete. My therapist is going to be happy to see me back

JavaScript open in a new window, not tab

You might try following function:

<script type="text/javascript">
function open(url)
{
  var popup = window.open(url, "_blank", "width=200, height=200") ;
  popup.location = URL;
}
</script>

The HTML code for execution:

<a href="#" onclick="open('http://www.google.com')">google search</a>

Best way to handle multiple constructors in Java

A slightly simplified answer:

public class Book
{
    private final String title;

    public Book(String title)
    {
      this.title = title;
    }

    public Book()
    {
      this("Default Title");
    }

    ...
}

How do you copy and paste into Git Bash

Yep, copy from somewhere else using ctrl+c and paste using INSERT. Work for me on Window 8.

align right in a table cell with CSS

What worked for me now is:

CSS:

.right {
  text-align: right;
  margin-right: 1em;
}

.left {
  text-align: left;
  margin-left: 1em;
}

HTML:

<table width="100%">
  <tbody>
    <tr>
      <td class="left">
        <input id="abort" type="submit" name="abort" value="Back">
        <input id="save" type="submit" name="save" value="Save">
      </td>
      <td class="right">
        <input id="delegate" type="submit" name="delegate" value="Delegate">
        <input id="unassign" type="submit" name="unassign" value="Unassign">
        <input id="complete" type="submit" name="complete" value="Complete">
      </td>
    </tr>
  </tbody>
</table>

See the following fiddle:

http://jsfiddle.net/Joysn/3u3SD/

How to redirect to Index from another controller?

You can use the following code:

return RedirectToAction("Index", "Home");

See RedirectToAction

How to reset db in Django? I get a command 'reset' not found error

For me this solved the problem.

heroku pg:reset DATABASE_URL

heroku run bash
>> Inside heroku bash
cd app_name && rm -rf migrations && cd ..
./manage.py makemigrations app_name
./manage.py migrate

JS: Failed to execute 'getComputedStyle' on 'Window': parameter is not of type 'Element'

The error message is pretty straightforward: getComputedStyle expects an Element as its first argument, and something else was passed to it.

If what you are really asking for is help with debugging your skin, you should make more of an effort to isolate the error.

Should MySQL have its timezone set to UTC?

The pros and cons are pretty much identical.It depends on whether you want this or not.

Be careful, if MySQL timezone differs from your system time (for instance PHP), comparing the time or printing to the user will involve some tinkering.

Convert SVG to PNG in Python

The answer is "pyrsvg" - a Python binding for librsvg.

There is an Ubuntu python-rsvg package providing it. Searching Google for its name is poor because its source code seems to be contained inside the "gnome-python-desktop" Gnome project GIT repository.

I made a minimalist "hello world" that renders SVG to a cairo surface and writes it to disk:

import cairo
import rsvg

img = cairo.ImageSurface(cairo.FORMAT_ARGB32, 640,480)

ctx = cairo.Context(img)

## handle = rsvg.Handle(<svg filename>)
# or, for in memory SVG data:
handle= rsvg.Handle(None, str(<svg data>))

handle.render_cairo(ctx)

img.write_to_png("svg.png")

Update: as of 2014 the needed package for Fedora Linux distribution is: gnome-python2-rsvg. The above snippet listing still works as-is.

Makefile If-Then Else and Loops

Conditional Forms

Simple

conditional-directive
text-if-true
endif

Moderately Complex

conditional-directive
text-if-true
else
text-if-false
endif

More Complex

conditional-directive
text-if-one-is-true
else
conditional-directive
text-if-true
else
text-if-false
endif
endif

Conditional Directives

If Equal Syntax

ifeq (arg1, arg2)
ifeq 'arg1' 'arg2'
ifeq "arg1" "arg2"
ifeq "arg1" 'arg2'
ifeq 'arg1' "arg2"

If Not Equal Syntax

ifneq (arg1, arg2)
ifneq 'arg1' 'arg2'
ifneq "arg1" "arg2"
ifneq "arg1" 'arg2'
ifneq 'arg1' "arg2"

If Defined Syntax

ifdef variable-name

If Not Defined Syntax

ifndef variable-name  

foreach Function

foreach Function Syntax

$(foreach var, list, text)  

foreach Semantics
For each whitespace separated word in "list", the variable named by "var" is set to that word and text is executed.

Checking Maven Version

Type the command mvn -version directly in your maven directory, you probably haven't added it to your PATH. Here are explained details of how to add maven to your PATH variable (I guess you use Windows because you are talking about CMD).

How do I add to the Windows PATH variable using setx? Having weird problems

I was having such trouble managing my computer labs when the %PATH% environment variable approached 1024 characters that I wrote a Powershell script to fix it.

You can download the code here: https://gallery.technet.microsoft.com/scriptcenter/Edit-and-shorten-PATH-37ef3189

You can also use it as a simple way to safely add, remove and parse PATH entries. Enjoy.

Google API for location, based on user IP address

Google already appends location data to all requests coming into GAE (see Request Header documentation for go, java, php and python). You should be interested X-AppEngine-Country, X-AppEngine-Region, X-AppEngine-City and X-AppEngine-CityLatLong headers.

An example looks like this:

X-AppEngine-Country:US
X-AppEngine-Region:ca
X-AppEngine-City:norwalk
X-AppEngine-CityLatLong:33.902237,-118.081733

How to get a path to a resource in a Java JAR file

if netclient.p is inside a JAR file, it won't have a path because that file is located inside other file. in that case, the best path you can have is really file:/path/to/jarfile/bot.jar!/config/netclient.p.

VC++ fatal error LNK1168: cannot open filename.exe for writing

I know this is an old question but thought I'd share how I resolved the issue.

If you're using Visual Studio and this error occurs, you can try to attach to process (CTRL+ALT+P) and find the "(program).exe" process. When you try to attach to it, an error will display stating that it failed to attach which removes the process from "running" (even though it's not...) You'll also be able to delete the (program).exe from your Debug folder.

Hope this helps someone! :)

How do I find the current directory of a batch file, and then use it for the path?

You can also do

 Pushd "%~dp0"

Which also takes running from a unc path into consideration.

div background color, to change onhover

To make the whole div act as a link, set the anchor tag as:

display: block

And set your height of the anchor tag to 100%. Then set a fixed height to your div tag. Then style your anchor tag like usual.

For example:

<html>
<head>
    <title>DIV Link</title>

    <style type="text/css">
    .link-container {
        border: 1px solid;
        width: 50%;
        height: 20px;
    }

    .link-container a {
        display: block;
        background: #c8c8c8;
        height: 100%;
        text-align: center;
    }

    .link-container a:hover {
        background: #f8f8f8;
    }

    </style>

</head>
<body>

    <div class="link-container">
        <a href="http://www.stackoverflow.com">Stack Overflow</a>
    </div>

    <div class="link-container">
        <a href="http://www.stackoverflow.com">Stack Overflow</a>
    </div>

</body> </html>

Good luck!

Subset dataframe by multiple logical conditions of rows to remove

data <- data[-which(data[,1] %in% c("b","d","e")),]

Check if a string contains a substring in SQL Server 2005, using a stored procedure

CHARINDEX() searches for a substring within a larger string, and returns the position of the match, or 0 if no match is found

if CHARINDEX('ME',@mainString) > 0
begin
    --do something
end

Edit or from daniels answer, if you're wanting to find a word (and not subcomponents of words), your CHARINDEX call would look like:

CHARINDEX(' ME ',' ' + REPLACE(REPLACE(@mainString,',',' '),'.',' ') + ' ')

(Add more recursive REPLACE() calls for any other punctuation that may occur)

How do I see which checkbox is checked?

I love short hands so:

$isChecked = isset($_POST['myCheckbox']) ? "yes" : "no";

Check if Cell value exists in Column, and then get the value of the NEXT Cell

After t.thielemans' answer, I worked that just

=VLOOKUP(A1, B:C, 2, FALSE) 

works fine and does what I wanted, except that it returns #N/A for non-matches; so it is suitable for the case where it is known that the value definitely exists in the look-up column.

Edit (based on t.thielemans' comment):

To avoid #N/A for non-matches, do:

=IFERROR(VLOOKUP(A1, B:C, 2, FALSE), "No Match")

Splitting String with delimiter

You can also do:

Integer a = '1182-2'.split('-')[0] as Integer
Integer b = '1182-2'.split('-')[1] as Integer

//a=1182 b=2

Should Jquery code go in header or footer?

Only load jQuery itself in the head, via CDN of course.

Why? In some scenarios you might include a partial template (e.g. ajax login form snippet) with embedded jQuery dependent code; if jQuery is loaded at page bottom, you get a "$ is not defined" error, nice.

There are ways to workaround this of course (such as not embedding any JS and appending to a load-at-bottom js bundle), but why lose the freedom of lazily loaded js, of being able to place jQuery dependent code anywhere you please? Javascript engine doesn't care where the code lives in the DOM so long as dependencies (like jQuery being loaded) are satisfied.

For your common/shared js files, yes, place them before </body>, but for the exceptions, where it really just makes sense application maintenance-wise to stick a jQuery dependent snippet or file reference right there at that point in the html, do so.

There is no performance hit loading jquery in the head; what browser on the planet does not already have jQuery CDN file in cache?

Much ado about nothing, stick jQuery in the head and let your js freedom reign.

Most efficient way to append arrays in C#?

Concatenating arrays is simple using linq extensions which come standard with .Net 4

Biggest thing to remember is that linq works with IEnumerable<T> objects, so in order to get an array back as your result then you must use the .ToArray() method at the end

Example of concatenating two byte arrays:

byte[] firstArray = {2,45,79,33};
byte[] secondArray = {55,4,7,81};
byte[] result = firstArray.Concat(secondArray).ToArray();

Adding a directory to the PATH environment variable in Windows

Handy if you are already in the directory you want to add to PATH:

set PATH=%PATH%;%CD%

It works with the standard Windows cmd, but not in PowerShell.

For PowerShell, the %CD% equivalent is [System.Environment]::CurrentDirectory.

Warning: A non-numeric value encountered

If non-numeric value encountered in your code try below one. The below code is converted to float.

$PlannedAmount = ''; // empty string ''

if(!is_numeric($PlannedAmount)) {
           $PlannedAmount = floatval($PlannedAmount);
 }

 echo $PlannedAmount; //output = 0

Flexbox: center horizontally and vertically

1 - Set CSS on parent div to display: flex;

2 - Set CSS on parent div to flex-direction: column;
Note that this will make all content within that div line up top to bottom. This will work best if the parent div only contains the child and nothing else.

3 - Set CSS on parent div to justify-content: center;

Here is an example of what the CSS will look like:

_x000D_
_x000D_
.parentDivClass {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
  justify-content: center;_x000D_
}
_x000D_
_x000D_
_x000D_

How to make all controls resize accordingly proportionally when window is maximized?

Just thought i'd share this with anyone who needs more clarity on how to achieve this:

myCanvas is a Canvas control and Parent to all other controllers. This code works to neatly resize to any resolution from 1366 x 768 upward. Tested up to 4k resolution 4096 x 2160

Take note of all the MainWindow property settings (WindowStartupLocation, SizeToContent and WindowState) - important for this to work correctly - WindowState for my user case requirement was Maximized

xaml

<Window x:Name="mainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:MyApp" 
    xmlns:ed="http://schemas.microsoft.com/expression/2010/drawing"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"
    x:Class="MyApp.MainWindow" 
     Title="MainWindow"  SizeChanged="MainWindow_SizeChanged"
    Width="1366" Height="768" WindowState="Maximized" WindowStartupLocation="CenterOwner" SizeToContent="WidthAndHeight">
  
    <Canvas x:Name="myCanvas" HorizontalAlignment="Left" Height="768" VerticalAlignment="Top" Width="1356">
        <Image x:Name="maxresdefault_1_1__jpg" Source="maxresdefault-1[1].jpg" Stretch="Fill" Opacity="0.6" Height="767" Canvas.Left="-6" Width="1366"/>

        <Separator Margin="0" Background="#FF302D2D" Foreground="#FF111010" Height="0" Canvas.Left="-811" Canvas.Top="148" Width="766"/>
        <Separator Margin="0" Background="#FF302D2D" Foreground="#FF111010" HorizontalAlignment="Right" Width="210" Height="0" Canvas.Left="1653" Canvas.Top="102"/>
        <Image x:Name="imgscroll" Source="BcaKKb47i[1].png" Stretch="Fill" RenderTransformOrigin="0.5,0.5" Height="523" Canvas.Left="-3" Canvas.Top="122" Width="580">
            <Image.RenderTransform>
                <TransformGroup>
                    <ScaleTransform/>
                    <SkewTransform/>
                    <RotateTransform Angle="89.093"/>
                    <TranslateTransform/>
                </TransformGroup>
            </Image.RenderTransform>
        </Image>

.cs

 private void MainWindow_SizeChanged(object sender, SizeChangedEventArgs e)
    {
        myCanvas.Width = e.NewSize.Width;
        myCanvas.Height = e.NewSize.Height;

        double xChange = 1, yChange = 1;

        if (e.PreviousSize.Width != 0)
            xChange = (e.NewSize.Width / e.PreviousSize.Width);

        if (e.PreviousSize.Height != 0)
            yChange = (e.NewSize.Height / e.PreviousSize.Height);

        ScaleTransform scale = new ScaleTransform(myCanvas.LayoutTransform.Value.M11 * xChange, myCanvas.LayoutTransform.Value.M22 * yChange);
        myCanvas.LayoutTransform = scale;
        myCanvas.UpdateLayout();
    }

Force "git push" to overwrite remote files

git push -f is a bit destructive because it resets any remote changes that had been made by anyone else on the team. A safer option is {git push --force-with-lease}.

What {--force-with-lease} does is refuse to update a branch unless it is the state that we expect; i.e. nobody has updated the branch upstream. In practice this works by checking that the upstream ref is what we expect, because refs are hashes, and implicitly encode the chain of parents into their value. You can tell {--force-with-lease} exactly what to check for, but by default will check the current remote ref. What this means in practice is that when Alice updates her branch and pushes it up to the remote repository, the ref pointing head of the branch will be updated. Now, unless Bob does a pull from the remote, his local reference to the remote will be out of date. When he goes to push using {--force-with-lease}, git will check the local ref against the new remote and refuse to force the push. {--force-with-lease} effectively only allows you to force-push if no-one else has pushed changes up to the remote in the interim. It's {--force} with the seatbelt on.

How to Load RSA Private Key From File

Two things. First, you must base64 decode the mykey.pem file yourself. Second, the openssl private key format is specified in PKCS#1 as the RSAPrivateKey ASN.1 structure. It is not compatible with java's PKCS8EncodedKeySpec, which is based on the SubjectPublicKeyInfo ASN.1 structure. If you are willing to use the bouncycastle library you can use a few classes in the bouncycastle provider and bouncycastle PKIX libraries to make quick work of this.

import java.io.BufferedReader;
import java.io.FileReader;
import java.security.KeyPair;
import java.security.Security;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;

// ...   

String keyPath = "mykey.pem";
BufferedReader br = new BufferedReader(new FileReader(keyPath));
Security.addProvider(new BouncyCastleProvider());
PEMParser pp = new PEMParser(br);
PEMKeyPair pemKeyPair = (PEMKeyPair) pp.readObject();
KeyPair kp = new JcaPEMKeyConverter().getKeyPair(pemKeyPair);
pp.close();
samlResponse.sign(Signature.getInstance("SHA1withRSA").toString(), kp.getPrivate(), certs);

Number of regex matches

If you always need to know the length, and you just need the content of the match rather than the other info, you might as well use re.findall. Otherwise, if you only need the length sometimes, you can use e.g.

matches = re.finditer(...)
...
matches = tuple(matches)

to store the iteration of the matches in a reusable tuple. Then just do len(matches).

Another option, if you just need to know the total count after doing whatever with the match objects, is to use

matches = enumerate(re.finditer(...))

which will return an (index, match) pair for each of the original matches. So then you can just store the first element of each tuple in some variable.

But if you need the length first of all, and you need match objects as opposed to just the strings, you should just do

matches = tuple(re.finditer(...))

How to get a Char from an ASCII Character Code in c#

You can simply write:

char c = (char) 2;

or

char c = Convert.ToChar(2);

or more complex option for ASCII encoding only

char[] characters = System.Text.Encoding.ASCII.GetChars(new byte[]{2});
char c = characters[0];

How to insert element into arrays at specific position?

array_slice() can be used to extract parts of the array, and the union array operator (+) can recombine the parts.

$res = array_slice($array, 0, 3, true) +
    array("my_key" => "my_value") +
    array_slice($array, 3, count($array)-3, true);

This example:

$array = array(
  'zero'  => '0',
  'one'   => '1',
  'two'   => '2',
  'three' => '3',
);
$res = array_slice($array, 0, 3, true) +
    array("my_key" => "my_value") +
    array_slice($array, 3, count($array) - 1, true) ;
print_r($res);

gives:

Array
(
    [zero] => 0
    [one] => 1
    [two] => 2
    [my_key] => my_value
    [three] => 3
)

How to center a window on the screen in Tkinter?

The simplest (but possibly inaccurate) method is to use tk::PlaceWindow, which takes the pathname of a toplevel window as an argument. The main window's pathname is .

import tkinter

root = tkinter.Tk()
root.eval('tk::PlaceWindow . center')

second_win = tkinter.Toplevel(root)
root.eval(f'tk::PlaceWindow {str(second_win)} center')

root.mainloop()

The problem

Simple solutions ignore the outermost frame with the title bar and the menu bar, which leads to a slight offset from being truly centered.

The solution

import tkinter  # Python 3

def center(win):
    """
    centers a tkinter window
    :param win: the main window or Toplevel window to center
    """
    win.update_idletasks()
    width = win.winfo_width()
    frm_width = win.winfo_rootx() - win.winfo_x()
    win_width = width + 2 * frm_width
    height = win.winfo_height()
    titlebar_height = win.winfo_rooty() - win.winfo_y()
    win_height = height + titlebar_height + frm_width
    x = win.winfo_screenwidth() // 2 - win_width // 2
    y = win.winfo_screenheight() // 2 - win_height // 2
    win.geometry('{}x{}+{}+{}'.format(width, height, x, y))
    win.deiconify()

if __name__ == '__main__':
    root = tkinter.Tk()
    root.attributes('-alpha', 0.0)
    menubar = tkinter.Menu(root)
    filemenu = tkinter.Menu(menubar, tearoff=0)
    filemenu.add_command(label="Exit", command=root.destroy)
    menubar.add_cascade(label="File", menu=filemenu)
    root.config(menu=menubar)
    frm = tkinter.Frame(root, bd=4, relief='raised')
    frm.pack(fill='x')
    lab = tkinter.Label(frm, text='Hello World!', bd=4, relief='sunken')
    lab.pack(ipadx=4, padx=4, ipady=4, pady=4, fill='both')
    center(root)
    root.attributes('-alpha', 1.0)
    root.mainloop()

With tkinter you always want to call the update_idletasks() method
directly before retrieving any geometry, to ensure that the values returned are accurate.

There are four methods that allow us to determine the outer-frame's dimensions.
winfo_rootx() will give us the window's top left x coordinate, excluding the outer-frame.
winfo_x() will give us the outer-frame's top left x coordinate.
Their difference is the outer-frame's width.

frm_width = win.winfo_rootx() - win.winfo_x()
win_width = win.winfo_width() + (2*frm_width)

The difference between winfo_rooty() and winfo_y() will be our title-bar / menu-bar's height.

titlebar_height = win.winfo_rooty() - win.winfo_y()
win_height = win.winfo_height() + (titlebar_height + frm_width)

You set the window's dimensions and the location with the geometry method. The first half of the geometry string is the window's width and height excluding the outer-frame,
and the second half is the outer-frame's top left x and y coordinates.

win.geometry(f'{width}x{height}+{x}+{y}')

You see the window move

One way to prevent seeing the window move across the screen is to use .attributes('-alpha', 0.0) to make the window fully transparent and then set it to 1.0 after the window has been centered. Using withdraw() or iconify() later followed by deiconify() doesn't seem to work well, for this purpose, on Windows 7. I use deiconify() as a trick to activate the window.


Making it optional

You might want to consider providing the user with an option to center the window, and not center by default; otherwise, your code can interfere with the window manager's functions. For example, xfwm4 has smart placement, which places windows side by side until the screen is full. It can also be set to center all windows, in which case you won't have the problem of seeing the window move (as addressed above).


Multiple monitors

If the multi-monitor scenario concerns you, then you can either look into the screeninfo project, or look into what you can accomplish with Qt (PySide2) or GTK (PyGObject), and then use one of those toolkits instead of tkinter. Combining GUI toolkits results in an unreasonably large dependency.

How to parse json string in Android?

Below is the link which guide in parsing JSON string in android.

http://www.ibm.com/developerworks/xml/library/x-andbene1/?S_TACT=105AGY82&S_CMP=MAVE

Also according to your json string code snippet must be something like this:-

JSONObject mainObject = new JSONObject(yourstring);

JSONObject universityObject = mainObject.getJSONObject("university");
JSONString name = universityObject.getString("name");  
JSONString url = universityObject.getString("url");

Following is the API reference for JSOnObject: https://developer.android.com/reference/org/json/JSONObject.html#getString(java.lang.String)

Same for other object.

What is the correct way to declare a boolean variable in Java?

Not only there is no need to declare it as false first, I would add few other improvements:

  • use boolean instead of Boolean (which can also be null for no reason)

  • assign during declaration:

    boolean isMatch = email1.equals(email2);
    
  • ...and use final keyword if you can:

    final boolean isMatch = email1.equals(email2);
    

Last but not least:

if (isMatch == true)

can be expressed as:

if (isMatch)

which renders the isMatch flag not that useful, inlining it might not hurt readability. I suggest looking for some better courses/tutorials out there...

Move the mouse pointer to a specific position?

Couldn't this simply be done by getting actual position of the mouse pointer then calculating and compensating sprite/scene mouse actions based off this compensation?

For instance you need the mouse pointer to be bottom center, but it sits top left; hide the cursor, use a shifted cursor image. Shift the cursor movement and map mouse input to match re-positioned cursor sprite (or 'control') clicks When/if bounds are hit, recalculate. If/when the cursor actually hits the point you want it to be, remove compensation.

Disclaimer, not a game developer.

In Java, how to find if first character in a string is upper case without regex

we can find upper case letter by using regular expression as well

private static void findUppercaseFirstLetterInString(String content) {
    Matcher m = Pattern
            .compile("([a-z])([a-z]*)", Pattern.CASE_INSENSITIVE).matcher(
                    content);
    System.out.println("Given input string : " + content);
    while (m.find()) {
        if (m.group(1).equals(m.group(1).toUpperCase())) {
            System.out.println("First Letter Upper case match found :"
                    + m.group());
        }
    }
}

for detailed example . please visit http://www.onlinecodegeek.com/2015/09/how-to-determines-if-string-starts-with.html

Android Call an method from another class

And, if you don't want to instantiate Class2, declare UpdateEmployee as static and call it like this:

Class2.UpdateEmployee();

However, you'll normally want to do what @parag said.

Django REST Framework: adding additional field to ModelSerializer

With the last version of Django Rest Framework, you need to create a method in your model with the name of the field you want to add. No need for @property and source='field' raise an error.

class Foo(models.Model):
    . . .
    def foo(self):
        return 'stuff'
    . . .

class FooSerializer(ModelSerializer):
    foo = serializers.ReadOnlyField()

    class Meta:
        model = Foo
        fields = ('foo',)

Can't create a docker image for COPY failed: stat /var/lib/docker/tmp/docker-builder error

I had to use the following command to start the build:

docker build .

Maven project.build.directory

You can find those maven properties in the super pom.

You find the jar here:

${M2_HOME}/lib/maven-model-builder-3.0.3.jar

Open the jar with 7-zip or some other archiver (or use the jar tool).

Navigate to

org/apache/maven/model

There you'll find the pom-4.0.0.xml.

It contains all those "short cuts":

<project>
    ...
    <build>
        <directory>${project.basedir}/target</directory>
        <outputDirectory>${project.build.directory}/classes</outputDirectory>
        <finalName>${project.artifactId}-${project.version}</finalName>
        <testOutputDirectory>${project.build.directory}/test-classes</testOutputDirectory>
        <sourceDirectory>${project.basedir}/src/main/java</sourceDirectory>
        <scriptSourceDirectory>src/main/scripts</scriptSourceDirectory>
        <testSourceDirectory>${project.basedir}/src/test/java</testSourceDirectory>
        <resources>
            <resource>
                <directory>${project.basedir}/src/main/resources</directory>
            </resource>
        </resources>
        <testResources>
            <testResource>
                <directory>${project.basedir}/src/test/resources</directory>
            </testResource>
        </testResources>
        ...
    </build>
    ...
</project>

Update

After some lobbying I am adding a link to the pom-4.0.0.xml. This allows you to see the properties without opening up the local jar file.

Appending an id to a list if not already present in a string

I agree with other answers that you are doing something weird here. You have a list containing a string with multiple entries that are themselves integers that you are comparing to an integer id.

This is almost surely not what you should be doing. You probably should be taking input and converting it to integers before storing in your list. You could do that with:

input = '350882 348521 350166\r\n'
list.append([int(x) for x in input.split()])

Then your test will pass. If you really are sure you don't want to do what you're currently doing, the following should do what you want, which is to not add the new id that already exists:

list = ['350882 348521 350166\r\n']
id = 348521
if id not in [int(y) for x in list for y in x.split()]:
    list.append(id)
print list

How can I split this comma-delimited string in Python?

You don't want regular expressions here.

s = "144,1231693144,26959535291011309493156476344723991336010898738574164086137773096960,26959535291011309493156476344723991336010898738574164086137773096960,1.00,4295032833,1563,2747941 288,1231823695,26959535291011309493156476344723991336010898738574164086137773096960,26959535291011309493156476344723991336010898738574164086137773096960,1.00,4295032833,909,4725008"

print s.split(',')

Gives you:

['144', '1231693144', '26959535291011309493156476344723991336010898738574164086137773096960', '26959535291011309493156476344723991336010898738574164086137773096960', '1.00
', '4295032833', '1563', '2747941 288', '1231823695', '26959535291011309493156476344723991336010898738574164086137773096960', '26959535291011309493156476344723991336010898
738574164086137773096960', '1.00', '4295032833', '909', '4725008']

IO Error: The Network Adapter could not establish the connection

I had the same problem, and this is how I fixed it. I was using the wrong port for my connection.

private final String DB_URL  = "jdbc:oracle:thin:@localhost:1521:orcll"; // 1521 my wrong port
  • go to your localhost
  • (my localhost address) : https://localhost:1158/em

  • login

    • user name
    • password
    • connect as --> normal
  • Below 'General' click on LISTENER_localhost

  • look at you port number
    • Net Address (ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1522)) Connect to port 1522
  • Edit you connection change port 1521 to 1522.

    • done

How to use WebRequest to POST some data and read response?

Here's what works for me. I'm sure it can be improved, so feel free to make suggestions or edit to make it better.

const string WEBSERVICE_URL = "http://localhost/projectname/ServiceName.svc/ServiceMethod";
//This string is untested, but I think it's ok.
string jsonData = "{ \"key1\" : \"value1\", \"key2\":\"value2\"  }"; 
try
{       
    var webRequest = System.Net.WebRequest.Create(WEBSERVICE_URL);
    if (webRequest != null)
    {
        webRequest.Method = "POST";
        webRequest.Timeout = 20000;
        webRequest.ContentType = "application/json";

    using (System.IO.Stream s = webRequest.GetRequestStream())
    {
        using (System.IO.StreamWriter sw = new System.IO.StreamWriter(s))
            sw.Write(jsonData);
    }

    using (System.IO.Stream s = webRequest.GetResponse().GetResponseStream())
    {
        using (System.IO.StreamReader sr = new System.IO.StreamReader(s))
        {
            var jsonResponse = sr.ReadToEnd();
            System.Diagnostics.Debug.WriteLine(String.Format("Response: {0}", jsonResponse));
        }
    }
}
}
catch (Exception ex)
{
    System.Diagnostics.Debug.WriteLine(ex.ToString());
}

How to check if a string is a number?

I need to do the same thing for a project I am currently working on. Here is how I solved things:

/* Prompt user for input */
printf("Enter a number: ");

/* Read user input */
char input[255]; //Of course, you can choose a different input size
fgets(input, sizeof(input), stdin);

/* Strip trailing newline */
size_t ln = strlen(input) - 1;
if( input[ln] == '\n' ) input[ln] = '\0';

/* Ensure that input is a number */
for( size_t i = 0; i < ln; i++){
    if( !isdigit(input[i]) ){
        fprintf(stderr, "%c is not a number. Try again.\n", input[i]);
        getInput(); //Assuming this is the name of the function you are using
        return;
    }
}

How to specify names of columns for x and y when joining in dplyr?

This feature has been added in dplyr v0.3. You can now pass a named character vector to the by argument in left_join (and other joining functions) to specify which columns to join on in each data frame. With the example given in the original question, the code would be:

left_join(test_data, kantrowitz, by = c("first_name" = "name"))

How to install JQ on Mac by command-line?

On a Mac, the "most efficient" way to install jq would probably be using homebrew, e.g.

brew install jq

If you want the development version, you could try:

brew install --HEAD jq

but this has various pre-requisites.

Detailed instructions are on the "Installation" page of the jq wiki: https://github.com/stedolan/jq/wiki/Installation

The same page also includes details regarding installation from source, and has notes on installing with MacPorts.

How to add new line into txt file

No new line:

File.AppendAllText("file.txt", DateTime.Now.ToString());

and then to get a new line after OK:

File.AppendAllText("file.txt", string.Format("{0}{1}", "OK", Environment.NewLine));

How do I apply a CSS class to Html.ActionLink in ASP.NET MVC?

deleted the c#... here is the vb.net

<%=Html.ActionLink("Home", "Index", "Home", New With {.class = "tab"}, Nothing)%>

UICollectionView Self Sizing Cells with Auto Layout

contentView anchor mystery:

In one bizarre case this

    contentView.translatesAutoresizingMaskIntoConstraints = false

would not work. Added four explicit anchors to the contentView and it worked.

class AnnoyingCell: UICollectionViewCell {
    
    @IBOutlet var word: UILabel!
    
    override init(frame: CGRect) {
        super.init(frame: frame); common() }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder); common() }
    
    private func common() {
        contentView.translatesAutoresizingMaskIntoConstraints = false
        
        NSLayoutConstraint.activate([
            contentView.leftAnchor.constraint(equalTo: leftAnchor),
            contentView.rightAnchor.constraint(equalTo: rightAnchor),
            contentView.topAnchor.constraint(equalTo: topAnchor),
            contentView.bottomAnchor.constraint(equalTo: bottomAnchor)
        ])
    }
}

and as usual

    estimatedItemSize = UICollectionViewFlowLayout.automaticSize

in YourLayout: UICollectionViewFlowLayout

Who knows? Might help someone.

Credit

https://www.vadimbulavin.com/collection-view-cells-self-sizing/

stumbled on to the tip there - never saw it anywhere else in all the 1000s articles on this.

How to make parent wait for all child processes to finish?

POSIX defines a function: wait(NULL);. It's the shorthand for waitpid(-1, NULL, 0);, which will suspends the execution of the calling process until any one child process exits. Here, 1st argument of waitpid indicates wait for any child process to end.

In your case, have the parent call it from within your else branch.

javascript setTimeout() not working

This line:

setTimeout(startTimer(), startInterval); 

You're invoking startTimer(). Instead, you need to pass it in as a function to be invoked, like so:

setTimeout(startTimer, startInterval);

Difference between string and text in rails?

The accepted answer is awesome, it properly explains the difference between string vs text (mostly the limit size in the database, but there are a few other gotchas), but I wanted to point out a small issue that got me through it as that answer didn't completely do it for me.

The max size :limit => 1 to 4294967296 didn't work exactly as put, I needed to go -1 from that max size. I'm storing large JSON blobs and they might be crazy huge sometimes.

Here's my migration with the larger value in place with the value MySQL doesn't complain about.

Note the 5 at the end of the limit instead of 6

class ChangeUserSyncRecordDetailsToText < ActiveRecord::Migration[5.1]
  def up
    change_column :user_sync_records, :details, :text, :limit => 4294967295
  end

  def down
    change_column :user_sync_records, :details, :string, :limit => 1000
  end
end

How to return an array from an AJAX call?

Have a look at json_encode (http://php.net/manual/en/function.json-encode.php). It is available as of PHP 5.2. Use the parameter dataType: 'json' to have it parsed for you. You'll have the Object as the first argument in success then. For further information have a look at the jQuery-documentation: http://api.jquery.com/jQuery.ajax/

Genymotion Android emulator - adb access?

My working solution is:

cd /opt/genymobile/genymotion/tools
./adb shell

You have to use its own adb tool.

Why does HTML think “chucknorris” is a color?

The rules for parsing colors on legacy attributes involves additional steps than those mentioned in existing answers. The truncate component to 2 digits part is described as:

  1. Discard all characters except the last 8
  2. Discard leading zeros one by one as long as all components have a leading zero
  3. Discard all characters except the first 2

Some examples:

oooFoooFoooF
000F 000F 000F                <- replace, pad and chunk
0F 0F 0F                      <- leading zeros truncated
0F 0F 0F                      <- truncated to 2 characters from right

oooFooFFoFFF
000F 00FF 0FFF                <- replace, pad and chunk
00F 0FF FFF                   <- leading zeros truncated
00 0F FF                      <- truncated to 2 characters from right

ABCooooooABCooooooABCoooooo
ABC000000 ABC000000 ABC000000 <- replace, pad and chunk
BC000000 BC000000 BC000000    <- truncated to 8 characters from left
BC BC BC                      <- truncated to 2 characters from right

AoCooooooAoCooooooAoCoooooo
A0C000000 A0C000000 A0C000000 <- replace, pad and chunk
0C000000 0C000000 0C000000    <- truncated to 8 characters from left
C000000 C000000 C000000       <- leading zeros truncated
C0 C0 C0                      <- truncated to 2 characters from right

Below is a partial implementation of the algorithm. It does not handle errors or cases where the user enters a valid color.

_x000D_
_x000D_
function parseColor(input) {_x000D_
  // todo: return error if input is ""_x000D_
  input = input.trim();_x000D_
  // todo: return error if input is "transparent"_x000D_
  // todo: return corresponding #rrggbb if input is a named color_x000D_
  // todo: return #rrggbb if input matches #rgb_x000D_
  // todo: replace unicode code points greater than U+FFFF with 00_x000D_
  if (input.length > 128) {_x000D_
    input = input.slice(0, 128);_x000D_
  }_x000D_
  if (input.charAt(0) === "#") {_x000D_
    input = input.slice(1);_x000D_
  }_x000D_
  input = input.replace(/[^0-9A-Fa-f]/g, "0");_x000D_
  while (input.length === 0 || input.length % 3 > 0) {_x000D_
    input += "0";_x000D_
  }_x000D_
  var r = input.slice(0, input.length / 3);_x000D_
  var g = input.slice(input.length / 3, input.length * 2 / 3);_x000D_
  var b = input.slice(input.length * 2 / 3);_x000D_
  if (r.length > 8) {_x000D_
    r = r.slice(-8);_x000D_
    g = g.slice(-8);_x000D_
    b = b.slice(-8);_x000D_
  }_x000D_
  while (r.length > 2 && r.charAt(0) === "0" && g.charAt(0) === "0" && b.charAt(0) === "0") {_x000D_
    r = r.slice(1);_x000D_
    g = g.slice(1);_x000D_
    b = b.slice(1);_x000D_
  }_x000D_
  if (r.length > 2) {_x000D_
    r = r.slice(0, 2);_x000D_
    g = g.slice(0, 2);_x000D_
    b = b.slice(0, 2);_x000D_
  }_x000D_
  return "#" + r.padStart(2, "0") + g.padStart(2, "0") + b.padStart(2, "0");_x000D_
}_x000D_
_x000D_
$(function() {_x000D_
  $("#input").on("change", function() {_x000D_
    var input = $(this).val();_x000D_
    var color = parseColor(input);_x000D_
    var $cells = $("#result tbody td");_x000D_
    $cells.eq(0).attr("bgcolor", input);_x000D_
    $cells.eq(1).attr("bgcolor", color);_x000D_
_x000D_
    var color1 = $cells.eq(0).css("background-color");_x000D_
    var color2 = $cells.eq(1).css("background-color");_x000D_
    $cells.eq(2).empty().append("bgcolor: " + input, "<br>", "getComputedStyle: " + color1);_x000D_
    $cells.eq(3).empty().append("bgcolor: " + color, "<br>", "getComputedStyle: " + color2);_x000D_
  });_x000D_
});
_x000D_
body { font: medium monospace; }_x000D_
input { width: 20em; }_x000D_
table { table-layout: fixed; width: 100%; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
_x000D_
<p><input id="input" placeholder="Enter color e.g. chucknorris"></p>_x000D_
<table id="result">_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>Left Color</th>_x000D_
      <th>Right Color</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td>&nbsp;</td>_x000D_
      <td>&nbsp;</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>&nbsp;</td>_x000D_
      <td>&nbsp;</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How to put a UserControl into Visual Studio toolBox

I found that the user control must have a parameterless constructor or it won't show up in the list. at least that was true in vs2005.

View markdown files offline

Geany has a plugin for markdown which does a fair job, giving you also a Markdown preview in the sidebar. It also runs on Linux, Mac OS X and Windows.

To use it, install geany, then install the package geany-plugin-markdown and select it from the plugin manager.

File 'app/hero.ts' is not a module error in the console, where to store interfaces files in directory structure with angular2?

For people getting the same error on stackblitz

You will find a Dependency tab on the left sidebar of the IDE. Just click the refresh button next to it and you will be good to go.


enter image description here

Bootstrap modal not displaying

Delete the data-target attribute from button type. Then add onClick="$('#your_modal_name').modal('show')" in the button tag. I hope it will work as I faced the same problem & I fixed the issue by calling the show class of modal via jQuery.

Run php script as daemon process

Another option is to use Upstart. It was originally developed for Ubuntu (and comes packaged with it by default), but is intended to be suitable for all Linux distros.

This approach is similar to Supervisord and daemontools, in that it automatically starts the daemon on system boot and respawns on script completion.

How to set it up:

Create a new script file at /etc/init/myphpworker.conf. Here is an example:

# Info
description "My PHP Worker"
author      "Jonathan"

# Events
start on startup
stop on shutdown

# Automatically respawn
respawn
respawn limit 20 5

# Run the script!
# Note, in this example, if your PHP script returns
# the string "ERROR", the daemon will stop itself.
script
    [ $(exec /usr/bin/php -f /path/to/your/script.php) = 'ERROR' ] && ( stop; exit 1; )
end script

Starting & stopping your daemon:

sudo service myphpworker start
sudo service myphpworker stop

Check if your daemon is running:

sudo service myphpworker status

Thanks

A big thanks to Kevin van Zonneveld, where I learned this technique from.

Appending the same string to a list of strings in Python

map seems like the right tool for the job to me.

my_list = ['foo', 'fob', 'faz', 'funk']
string = 'bar'
list2 = list(map(lambda orig_string: orig_string + string, my_list))

See this section on functional programming tools for more examples of map.

Delete all lines beginning with a # from a file

The opposite of Raymond's solution:

sed -n '/^#/!p'

"don't print anything, except for lines that DON'T start with #"

Anyway to prevent the Blue highlighting of elements in Chrome when clicking quickly?

I had similar issue with <input type="range" /> and I solved it with

-webkit-tap-highlight-color: transparent;

_x000D_
_x000D_
input[type="range"]{
  -webkit-tap-highlight-color: transparent;
}
_x000D_
 <input type="range" id="volume" name="demo"
         min="0" max="11">
  <label for="volume">Demo</label>
_x000D_
_x000D_
_x000D_

Python loop to run for certain amount of seconds

Simply You can do it

import time
delay=60*15    ###for 15 minutes delay 
close_time=time.time()+delay
while True:
      ##bla bla
      ###bla bla
     if time.time()>close_time
         break

Very simple C# CSV reader

You can try the some thing like the below LINQ snippet.

string[] allLines = File.ReadAllLines(@"E:\Temp\data.csv");

    var query = from line in allLines
                let data = line.Split(',')
                select new
                {
                    Device = data[0],
                    SignalStrength = data[1],
                    Location = data[2], 
                    Time = data[3],
                    Age = Convert.ToInt16(data[4])
                };

UPDATE: Over a period of time, things evolved. As of now, I would prefer to use this library http://www.aspnetperformance.com/post/LINQ-to-CSV-library.aspx

Convert string into integer in bash script - "Leading Zero" number error

Since hours are always positive, and always 2 digits, you can set a 1 in front of it and subtract 100:

echo $((1$hour+1-100))

which is equivalent to

echo $((1$hour-99))

Be sure to comment such gymnastics. :)

Update using LINQ to SQL

I found a workaround a week ago. You can use direct commands with "ExecuteCommand":

MDataContext dc = new MDataContext();
var flag = (from f in dc.Flags
                   where f.Code == Code
                   select f).First();
_refresh = Convert.ToBoolean(flagRefresh.Value);
if (_refresh)
{
    dc.ExecuteCommand("update Flags set value = 0 where code = {0}", Code);
}

In the ExecuteCommand statement, you can send the query directly, with the value for the specific record you want to update.

value = 0 --> 0 is the new value for the record;

code = {0} --> is the field where you will send the filter value;

Code --> is the new value for the field;

I hope this reference helps.

Auto-loading lib files in Rails 4

Though this does not directly answer the question, but I think it is a good alternative to avoid the question altogether.

To avoid all the autoload_paths or eager_load_paths hassle, create a "lib" or a "misc" directory under "app" directory. Place codes as you would normally do in there, and Rails will load files just like how it will load (and reload) model files.

Check if element is visible on screen

--- Shameless plug ---
I have added this function to a library I created vanillajs-browser-helpers: https://github.com/Tokimon/vanillajs-browser-helpers/blob/master/inView.js
-------------------------------

Well BenM stated, you need to detect the height of the viewport + the scroll position to match up with your top position. The function you are using is ok and does the job, though its a bit more complex than it needs to be.

If you don't use jQuery then the script would be something like this:

function posY(elm) {
    var test = elm, top = 0;

    while(!!test && test.tagName.toLowerCase() !== "body") {
        top += test.offsetTop;
        test = test.offsetParent;
    }

    return top;
}

function viewPortHeight() {
    var de = document.documentElement;

    if(!!window.innerWidth)
    { return window.innerHeight; }
    else if( de && !isNaN(de.clientHeight) )
    { return de.clientHeight; }
    
    return 0;
}

function scrollY() {
    if( window.pageYOffset ) { return window.pageYOffset; }
    return Math.max(document.documentElement.scrollTop, document.body.scrollTop);
}

function checkvisible( elm ) {
    var vpH = viewPortHeight(), // Viewport Height
        st = scrollY(), // Scroll Top
        y = posY(elm);
    
    return (y > (vpH + st));
}

Using jQuery is a lot easier:

function checkVisible( elm, evalType ) {
    evalType = evalType || "visible";

    var vpH = $(window).height(), // Viewport Height
        st = $(window).scrollTop(), // Scroll Top
        y = $(elm).offset().top,
        elementHeight = $(elm).height();

    if (evalType === "visible") return ((y < (vpH + st)) && (y > (st - elementHeight)));
    if (evalType === "above") return ((y < (vpH + st)));
}

This even offers a second parameter. With "visible" (or no second parameter) it strictly checks whether an element is on screen. If it is set to "above" it will return true when the element in question is on or above the screen.

See in action: http://jsfiddle.net/RJX5N/2/

I hope this answers your question.

-- IMPROVED VERSION--

This is a lot shorter and should do it as well:

function checkVisible(elm) {
  var rect = elm.getBoundingClientRect();
  var viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight);
  return !(rect.bottom < 0 || rect.top - viewHeight >= 0);
}

with a fiddle to prove it: http://jsfiddle.net/t2L274ty/1/

And a version with threshold and mode included:

function checkVisible(elm, threshold, mode) {
  threshold = threshold || 0;
  mode = mode || 'visible';

  var rect = elm.getBoundingClientRect();
  var viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight);
  var above = rect.bottom - threshold < 0;
  var below = rect.top - viewHeight + threshold >= 0;

  return mode === 'above' ? above : (mode === 'below' ? below : !above && !below);
}

and with a fiddle to prove it: http://jsfiddle.net/t2L274ty/2/

Python one-line "for" expression

Even array2.extend(array1) will work.

git-diff to ignore ^M

Is there an option like "treat ^M as newline when diffing" ?

There will be one with Git 2.16 (Q1 2018), as the "diff" family of commands learned to ignore differences in carriage return at the end of line.

See commit e9282f0 (26 Oct 2017) by Junio C Hamano (gitster).
Helped-by: Johannes Schindelin (dscho).
(Merged by Junio C Hamano -- gitster -- in commit 10f65c2, 27 Nov 2017)

diff: --ignore-cr-at-eol

A new option --ignore-cr-at-eol tells the diff machinery to treat a carriage-return at the end of a (complete) line as if it does not exist.

Just like other "--ignore-*" options to ignore various kinds of whitespace differences, this will help reviewing the real changes you made without getting distracted by spurious CRLF<->LF conversion made by your editor program.

How to get datas from List<Object> (Java)?

Do like this

List<Object[]> list = HQL.list(); // get your lsit here but in Object array

your query is : "SELECT houses.id, addresses.country, addresses.region,..."

for(Object[] obj : list){
String houseId = String.valueOf(obj[0]); // houseId is at first place in your query
String country = String.valueof(obj[1]); // country is at second and so on....
.......
}

this way you can get the mixed objects with ease, but you should know in advance at which place what value you are getting or you can just check by printing the values to know. sorry for the bad english I hope this help

Compare if BigDecimal is greater than zero

Possible better way:

if (value.signum() > 0)

signum returns -1, 0, or 1 as the value of this BigDecimal is negative, zero, or positive.

sys.stdin.readline() reads without prompt, returning 'nothing in between'

stdin.read(1)

will not return when you press one character - it will wait for '\n'. The problem is that the second character is buffered in standard input, and the moment you call another input - it will return immediately because it gets its input from buffer.

Ignore mapping one property with Automapper

From Jimmy Bogard: CreateMap<Foo, Bar>().ForMember(x => x.Blarg, opt => opt.Ignore());

It's in one of the comments at his blog.

how to run two commands in sudo?

For your command you also could refer to the following example:

sudo sh -c 'whoami; whoami'

psycopg2: insert multiple rows with one query

I've been using ant32's answer above for several years. However I've found that is thorws an error in python 3 because mogrify returns a byte string.

Converting explicitly to bytse strings is a simple solution for making code python 3 compatible.

args_str = b','.join(cur.mogrify("(%s,%s,%s,%s,%s,%s,%s,%s,%s)", x) for x in tup) 
cur.execute(b"INSERT INTO table VALUES " + args_str)

What is log4j's default log file dumping path

You have copy this sample code from Here,right?
now, as you can see there property file they have define, have you done same thing? if not then add below code in your project with property file for log4j

So the content of log4j.properties file would be as follows:

# Define the root logger with appender file
log = /usr/home/log4j
log4j.rootLogger = DEBUG, FILE

# Define the file appender
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=${log}/log.out

# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%m%n

make changes as per your requirement like log path

VARCHAR to DECIMAL

In MySQL

select convert( if( listPrice REGEXP '^[0-9]+$', listPrice, '0' ), DECIMAL(15, 3) ) from MyProduct WHERE 1

Print out the values of a (Mat) matrix in OpenCV C++

See the first answer to Accessing a matrix element in the "Mat" object (not the CvMat object) in OpenCV C++
Then just loop over all the elements in cout << M.at<double>(0,0); rather than just 0,0

Or better still with the C++ interface:

cv::Mat M;
cout << "M = " << endl << " "  << M << endl << endl;

How to transfer paid android apps from one google account to another google account

You will not be able to do that. You can download apps again to the same userid account on different devices, but you cannot transfer those licenses to other userids.

There is no way to do this programatically - I don't think you can do that practically (except for trying to call customer support at the Play Store).

Add an object to a python list

Is your problem similar to this:

l = [[0]] * 4
l[0][0] += 1
print l # prints "[[1], [1], [1], [1]]"

If so, you simply need to copy the objects when you store them:

import copy
l = [copy.copy(x) for x in [[0]] * 4]
l[0][0] += 1
print l # prints "[[1], [0], [0], [0]]"

The objects in question should implement a __copy__ method to copy objects. See the documentation for copy. You may also be interested in copy.deepcopy, which is there as well.

EDIT: Here's the problem:

arrayList = []
for x in allValues:
    result = model(x)
    arrayList.append(wM) # appends the wM object to the list
    wM.reset()           # clears  the wM object

You need to append a copy:

import copy
arrayList = []
for x in allValues:
    result = model(x)
    arrayList.append(copy.copy(wM)) # appends a copy to the list
    wM.reset()                      # clears the wM object

But I'm still confused as to where wM is coming from. Won't you just be copying the same wM object over and over, except clearing it after the first time so all the rest will be empty? Or does model() modify the wM (which sounds like a terrible design flaw to me)? And why are you throwing away result?

Does hosts file exist on the iPhone? How to change it?

It might exist, but you cannot change it on a non-jailbreaked iPhone.

Assuming that your development webserver is on a Mac, why don't you simply use its Bonjour name (e.g. MyMac.local.) instead of myrealwebserverontheinternet.com?

What is the Eclipse shortcut for "public static void main(String args[])"?

Type main and press and hold Ctrl and next press Space Space (double space) and select, it or pressenter to focus on main option.

This is fastest way.

What good are SQL Server schemas?

I don't see the benefit in aliasing out users tied to Schemas. Here is why....

Most people connect their user accounts to databases via roles initially, As soon as you assign a user to either the sysadmin, or the database role db_owner, in any form, that account is either aliased to the "dbo" user account, or has full permissions on a database. Once that occurs, no matter how you assign yourself to a scheme beyond your default schema (which has the same name as your user account), those dbo rights are assigned to those object you create under your user and schema. Its kinda pointless.....and just a namespace and confuses true ownership on those objects. Its poor design if you ask me....whomever designed it.

What they should have done is created "Groups", and thrown out schemas and role and just allow you to tier groups of groups in any combination you like, then at each tier tell the system if permissions are inherited, denied, or overwritten with custom ones. This would have been so much more intuitive and allowed DBA's to better control who the real owners are on those objects. Right now its implied in most cases the dbo default SQL Server user has those rights....not the user.

Set ImageView width and height programmatically?

If you need to set your width or height to match_parent (as big as its parent) or wrap_content (large enough to fit its own internal content), then ViewGroup.LayoutParams has this two constants:

imageView.setLayoutParams(
    new ViewGroup.LayoutParams(
        // or ViewGroup.LayoutParams.WRAP_CONTENT
        ViewGroup.LayoutParams.MATCH_PARENT,      
        // or ViewGroup.LayoutParams.WRAP_CONTENT,     
        ViewGroup.LayoutParams.MATCH_PARENT ) );

Or you can set them like in Hakem Zaied's answer:

imageView.getLayoutParams().width = ViewGroup.LayoutParams.MATCH_PARENT;
//...

How to make a simple popup box in Visual C#?

Why not make use of a tooltip?

private void ShowToolTip(object sender, string message)
{
  new ToolTip().Show(message, this, Cursor.Position.X - this.Location.X, Cursor.Position.Y - this.Location.Y, 1000);
}

The code above will show message for 1000 milliseconds (1 second) where you clicked.

To call it, you can use the following in your button click event:

ShowToolTip("Hello World");

Eclipse Problems View not showing Errors anymore

I experienced that problem with a MapReduce project. I closed the error window and never came back after doing what the other answers suggested.

Click on the bottom left -> Other -> Problems

enter image description here

Using npm behind corporate proxy .pac

From a little search on google the first thing I tried was this

npm config set registry http://registry.npmjs.org/
npm config set proxy "your proxy"
npm config set https-proxy "your proxy"

But still npm seemed to lose connection when trying to do "npm install"s. then I ran this line in command prompt and now I can use npm install

set NODE_TLS_REJECT_UNAUTHORIZED=0

How to "add existing frameworks" in Xcode 4?

In Project

  1. Select the project navigator
  2. Click on Build Phases
  3. Click on link binary with libraries
  4. Click on + Button and add your Frameworks

Adding rows to dataset

DataSet myDataset = new DataSet();

DataTable customers = myDataset.Tables.Add("Customers");

customers.Columns.Add("Name");
customers.Columns.Add("Age");

customers.Rows.Add("Chris", "25");

//Get data
DataTable myCustomers = myDataset.Tables["Customers"];
DataRow currentRow = null;
for (int i = 0; i < myCustomers.Rows.Count; i++)
{
    currentRow = myCustomers.Rows[i];
    listBox1.Items.Add(string.Format("{0} is {1} YEARS OLD", currentRow["Name"], currentRow["Age"]));    
}

How to get only time from date-time C#

Try this:

TimeSpan TodayTime = DateTime.Now.TimeOfDay;

How to show/hide JPanels in a JFrame?

If you want to hide panel on button click, write below code in JButton Action. I assume you want to hide jpanel1.

jpanel1.setVisible(false);

Difference between webdriver.Dispose(), .Close() and .Quit()

Selenium WebDriver

  1. WebDriver.Close() This method is used to close the current open window. It closes the current open window on which driver has focus on.

  2. WebDriver.Quit() This method is used to destroy the instance of WebDriver. It closes all Browser Windows associated with that driver and safely ends the session. WebDriver.Quit() calls Dispose.

  3. WebDriver.Dispose() This method closes all Browser windows and safely ends the session

Visual Studio Code PHP Intelephense Keep Showing Not Necessary Error

I had the same issue and the following seemed to have addressed the issue.

a) Updated to latest version 1.3.5 and re-enabled all the diagnosis settings.

I was still getting the messages

b) Added the vendor folder with the dependent libraries to the workspace

This seems to have solved the problem.

Reset select value to default

I have select box

<select id="my_select">
    <option value="a">a</option>
    <option value="b" selected="selected">b</option>
    <option value="c">c</option>
</select>

<div id="reset">
    reset
</div>

I have also reset button, here default (selected) value is "b", suppose I select "c" and after I need resert select box value to default, how to make this using Angular2?

Can "git pull --all" update all my local branches?

If refs/heads/master can be fast-forwarded to refs/remotes/foo/master, the output of

git merge-base refs/heads/master refs/remotes/foo/master

should return the SHA1 id that refs/heads/master points to. With this, you can put together a script that automatically updates all local branches that have had no diverting commits applied to them.

This little shell script (I called it git-can-ff) illustrates how it can be done.

#!/bin/sh

set -x

usage() {
    echo "usage: $(basename $0) <from-ref> <to-ref>" >&2
    exit 2
}

[ $# -ne 2 ] && usage

FROM_REF=$1
TO_REF=$2

FROM_HASH=$(git show-ref --hash $FROM_REF)
TO_HASH=$(git show-ref --hash $TO_REF)
BASE_HASH=$(git merge-base $FROM_REF $TO_REF)

if [ "$BASE_HASH" = "$FROM_HASH" -o \
     "$BASE_HASH" = "$FROM_REF" ]; then
    exit 0
else
    exit 1
fi

Android Viewpager as Image Slide Gallery

you can use custom gallery control.. check this https://github.com/kilaka/ImageViewZoom use galleryTouch class from this..

How to add column to numpy array

I add a new column with ones to a matrix array in this way:

Z = append([[1 for _ in range(0,len(Z))]], Z.T,0).T

Maybe it is not that efficient?

Youtube - downloading a playlist - youtube-dl

I have tried everything above, but none could solve my problem. I fixed it by updating the old version of youtube-dl to download playlist. To update it

sudo youtube-dl -U

or

youtube-dl -U

after you have successfully updated using the above command

youtube-dl -cit https://www.youtube.com/playlist?list=PLttJ4RON7sleuL8wDpxbKHbSJ7BH4vvCk

Representing null in JSON

According to the JSON spec, the outermost container does not have to be a dictionary (or 'object') as implied in most of the comments above. It can also be a list or a bare value (i.e. string, number, boolean or null). If you want to represent a null value in JSON, the entire JSON string (excluding the quotes containing the JSON string) is simply null. No braces, no brackets, no quotes. You could specify a dictionary containing a key with a null value ({"key1":null}), or a list with a null value ([null]), but these are not null values themselves - they are proper dictionaries and lists. Similarly, an empty dictionary ({}) or an empty list ([]) are perfectly fine, but aren't null either.

In Python:

>>> print json.loads('{"key1":null}')
{u'key1': None}
>>> print json.loads('[null]')
[None]
>>> print json.loads('[]')
[]
>>> print json.loads('{}')
{}
>>> print json.loads('null')
None

Convert XmlDocument to String

If you are using Windows.Data.Xml.Dom.XmlDocument version of XmlDocument (used in UWP apps for example), you can use yourXmlDocument.GetXml() to get the XML as a string.

extract date only from given timestamp in oracle sql

This format worked for me, for the mentioned date format i.e. MM/DD/YYYY

SELECT to_char(query_date,'MM/DD/YYYY') as query_date 
FROM QMS_INVOICE_TABLE;

Parsing a comma-delimited std::string

This is the simplest way, which I used a lot. It works for any one-character delimiter.

#include<bits/stdc++.h>
using namespace std;

int main() {
   string str;

   cin >> str;
   int temp;
   vector<int> result;
   char ch;
   stringstream ss(str);

   do
   {
       ss>>temp;
       result.push_back(temp);
   }while(ss>>ch);

   for(int i=0 ; i < result.size() ; i++)
       cout<<result[i]<<endl;

   return 0;
}

How to add an object to an array

obejct is clearly a typo. But both object and array need capital letters.

You can use short hands for new Array and new Object these are [] and {}

You can push data into the array using .push. This adds it to the end of the array. or you can set an index to contain the data.

function saveToArray() {
    var o = {};
    o.foo = 42;
    var arr = [];
    arr.push(o);
    return arr;
}

function other() {
    var arr = saveToArray();
    alert(arr[0]);
}

other();

jQuery - Increase the value of a counter when a button is clicked

Several of the suggestions above use global variables. This is not a good solution for the problem. The count is specific to one element, and you can use jQuery's data function to bind an item of data to an element:

$('#counter').data('count', 0);
$('#update').click(function(){
    $('#counter').html(function(){
        var $this = $(this),
            count = $this.data('count') + 1;

        $this.data('count', count);
        return count;
    });
});

Note also that this uses the callback syntax of html to make the code more fluent and fast.

Disable vertical scroll bar on div overflow: auto

This rules are compatible whit all browser:

body {overflow: hidden; }
body::-webkit-scrollbar { width: 0 !important; }
body { overflow: -moz-scrollbars-none; }
body { -ms-overflow-style: none; }

How do I parse a YAML file in Ruby?

I had the same problem but also wanted to get the content of the file (after the YAML front-matter).

This is the best solution I have found:

if (md = contents.match(/^(?<metadata>---\s*\n.*?\n?)^(---\s*$\n?)/m))
  self.contents = md.post_match
  self.metadata = YAML.load(md[:metadata])
end

Source and discussion: https://practicingruby.com/articles/tricks-for-working-with-text-and-files

How can I specify the default JVM arguments for programs I run from eclipse?

Yes, right click the project. Click Run as then Run Configurations. You can change the parameters passed to the JVM in the Arguments tab in the VM Arguments box.

That configuration can then be used as the default when running the project.

PHP - Insert date into mysql

$date=$year."-".$month."-".$day; 
$new_date=date('Y-m-d', strtotime($dob)); 
$status=0;  
$insert_date = date("Y-m-d H:i:s");  
$latest_insert_id=0; 

$insertSql="insert into participationDetail (formId,name,city,emailId,dob,mobile,status,social_media1,social_media2,visa_status,tnc_status,data,gender,insertDate)values('".$formid."','".$name."','".$city."','".$email."','".$new_date."','".$mobile."','".$status."','".$link1."','".$link2."','".$visa_check."','".$tnc_check."','".json_encode($detail_arr,JSON_HEX_APOS)."','".$gender."','".$insert_date."')";

How to justify a single flexbox item (override justify-content)

AFAIK there is no property for that in the specs, but here is a trick I’ve been using: set the container element ( the one with display:flex ) to justify-content:space-around Then add an extra element between the first and second item and set it to flex-grow:10 (or some other value that works with your setup)

Edit: if the items are tightly aligned it's a good idea to add flex-shrink: 10; to the extra element as well, so the layout will be properly responsive on smaller devices.

What is Dispatcher Servlet in Spring?

<?xml version='1.0' encoding='UTF-8' ?>
<!-- was: <?xml version="1.0" encoding="UTF-8"?> -->
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
               http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
    <context:component-scan base-package="com.demo" />
    <context:annotation-config />

    <mvc:annotation-driven />


    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:prefix="/WEB-INF/jsp/"
          p:suffix=".jsp" />

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="datasource" />
    </bean> 

          <bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />  
        <property name="url" value="jdbc:mysql://localhost:3306/employee" />
        <property name="username" value="username" />
        <property name="password" value="password" />
    </bean> 

</beans>

Get $_POST from multiple checkboxes

It's pretty simple. Pay attention and you'll get it right away! :)

You will create a html array, which will be then sent to php array. Your html code will look like this:

<input type="checkbox" name="check_list[1]" alt="Checkbox" value="checked">
<input type="checkbox" name="check_list[2]" alt="Checkbox" value="checked">
<input type="checkbox" name="check_list[3]" alt="Checkbox" value="checked">

Where [1] [2] [3] are the IDs of your messages, meaning that you will echo your $row['Report ID'] in their place.

Then, when you submit the form, your PHP array will look like this:

print_r($check_list)

[1] => checked [3] => checked

Depending on which were checked and which were not.

I'm sure you can continue from this point forward.

MySQL LIMIT on DELETE statement

DELETE t.* FROM test t WHERE t.name = 'foo' LIMIT 1

@Andre If I understood what you are asking, I think the only thing missing is the t.* before FROM.

How to add class active on specific li on user click with jQuery

Slightly off topic but having arrived here while developing an Angular2 app I would like to share that Angular2 automatically adds the class "router-link-active" to active router links such as this one:

<li><a [routerLink]="['Dashboard']">Dashboard</a></li>

You can therefore easily style such links using CSS:

.router-link-active {
    color: red;
}

What do $? $0 $1 $2 mean in shell script?

They are called the Positional Parameters.

3.4.1 Positional Parameters

A positional parameter is a parameter denoted by one or more digits, other than the single digit 0. Positional parameters are assigned from the shell’s arguments when it is invoked, and may be reassigned using the set builtin command. Positional parameter N may be referenced as ${N}, or as $N when N consists of a single digit. Positional parameters may not be assigned to with assignment statements. The set and shift builtins are used to set and unset them (see Shell Builtin Commands). The positional parameters are temporarily replaced when a shell function is executed (see Shell Functions).

When a positional parameter consisting of more than a single digit is expanded, it must be enclosed in braces.

How to iterate (keys, values) in JavaScript?

I think the fast and easy way is

Object.entries(event).forEach(k => {
    console.log("properties ... ", k[0], k[1]); });

just check the documentation https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries

SQL is null and = null

First is correct way of checking whether a field value is null while later won't work the way you expect it to because null is special value which does not equal anything, so you can't use equality comparison using = for it.

So when you need to check if a field value is null or not, use:

where x is null

instead of:

where x = null

Call a Subroutine from a different Module in VBA

Prefix the call with Module2 (ex. Module2.IDLE). I'm assuming since you asked this that you have IDLE defined multiple times in the project, otherwise this shouldn't be necessary.

center image in div with overflow hidden

you the have to corp your image from sides to hide it try this

3 Easy and Fast CSS Techniques for Faux Image Cropping | Css ...

one of the demo for the first way on the site above

try demo

i will do some reading on it too

How to create a showdown.js markdown extension

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

EDIT

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

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

I submitted a pull request to update this.

Insert into a MySQL table or update if exists

When using batch insert use the following syntax:

INSERT INTO TABLE (id, name, age) VALUES (1, "A", 19), (2, "B", 17), (3, "C", 22)
ON DUPLICATE KEY UPDATE
    name = VALUES (name),
    ...

Parse (split) a string in C++ using string delimiter (standard C++)

A very simple/naive approach:

vector<string> words_seperate(string s){
    vector<string> ans;
    string w="";
    for(auto i:s){
        if(i==' '){
           ans.push_back(w);
           w="";
        }
        else{
           w+=i;
        }
    }
    ans.push_back(w);
    return ans;
}

Or you can use boost library split function:

vector<string> result; 
boost::split(result, input, boost::is_any_of("\t"));

Or You can try TOKEN or strtok:

char str[] = "DELIMIT-ME-C++"; 
char *token = strtok(str, "-"); 
while (token) 
{ 
    cout<<token; 
    token = strtok(NULL, "-"); 
} 

Or You can do this:

char split_with=' ';
vector<string> words;
string token; 
stringstream ss(our_string);
while(getline(ss , token , split_with)) words.push_back(token);

MySQL foreign key constraints, cascade delete

If your cascading deletes nuke a product because it was a member of a category that was killed, then you've set up your foreign keys improperly. Given your example tables, you should have the following table setup:

CREATE TABLE categories (
    id int unsigned not null primary key,
    name VARCHAR(255) default null
)Engine=InnoDB;

CREATE TABLE products (
    id int unsigned not null primary key,
    name VARCHAR(255) default null
)Engine=InnoDB;

CREATE TABLE categories_products (
    category_id int unsigned not null,
    product_id int unsigned not null,
    PRIMARY KEY (category_id, product_id),
    KEY pkey (product_id),
    FOREIGN KEY (category_id) REFERENCES categories (id)
       ON DELETE CASCADE
       ON UPDATE CASCADE,
    FOREIGN KEY (product_id) REFERENCES products (id)
       ON DELETE CASCADE
       ON UPDATE CASCADE
)Engine=InnoDB;

This way, you can delete a product OR a category, and only the associated records in categories_products will die alongside. The cascade won't travel farther up the tree and delete the parent product/category table.

e.g.

products: boots, mittens, hats, coats
categories: red, green, blue, white, black

prod/cats: red boots, green mittens, red coats, black hats

If you delete the 'red' category, then only the 'red' entry in the categories table dies, as well as the two entries prod/cats: 'red boots' and 'red coats'.

The delete will not cascade any farther and will not take out the 'boots' and 'coats' categories.

comment followup:

you're still misunderstanding how cascaded deletes work. They only affect the tables in which the "on delete cascade" is defined. In this case, the cascade is set in the "categories_products" table. If you delete the 'red' category, the only records that will cascade delete in categories_products are those where category_id = red. It won't touch any records where 'category_id = blue', and it would not travel onwards to the "products" table, because there's no foreign key defined in that table.

Here's a more concrete example:

categories:     products:
+----+------+   +----+---------+
| id | name |   | id | name    |
+----+------+   +----+---------+
| 1  | red  |   | 1  | mittens |
| 2  | blue |   | 2  | boots   |
+---++------+   +----+---------+

products_categories:
+------------+-------------+
| product_id | category_id |
+------------+-------------+
| 1          | 1           | // red mittens
| 1          | 2           | // blue mittens
| 2          | 1           | // red boots
| 2          | 2           | // blue boots
+------------+-------------+

Let's say you delete category #2 (blue):

DELETE FROM categories WHERE (id = 2);

the DBMS will look at all the tables which have a foreign key pointing at the 'categories' table, and delete the records where the matching id is 2. Since we only defined the foreign key relationship in products_categories, you end up with this table once the delete completes:

+------------+-------------+
| product_id | category_id |
+------------+-------------+
| 1          | 1           | // red mittens
| 2          | 1           | // red boots
+------------+-------------+

There's no foreign key defined in the products table, so the cascade will not work there, so you've still got boots and mittens listed. There's just no 'blue boots' and no 'blue mittens' anymore.

How to make the overflow CSS property work with hidden as value

This worked for me

<div style="display: flex; position: absolute; width: 100%;">
  <div style="white-space: nowrap; overflow: hidden;text-overflow: ellipsis;">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi.
  </div>
</div>

Adding position:absolute to the parent container made it work.

PS: This is for anyone looking for a solution to dynamically truncating text.

EDIT: This was meant to be an answer for this question but since they are related and it could help someone on this question I shall also leave it here instead of deleting it.

Spring default behavior for lazy-init

When we use lazy-init="default" as an attribute in element, the container picks up the value specified by default-lazy-init="true|false" attribute of element and uses it as lazy-init="true|false".

If default-lazy-init attribute is not present in element than lazy-init="default" in element will behave as if lazy-init-"false".

PHP, pass array through POST

You could put it in the session:

session_start();
$_SESSION['array_name'] = $array_name;

Or if you want to send it via a form you can serialize it:

<input type='hidden' name='input_name' value="<?php echo htmlentities(serialize($array_name)); ?>" />

$passed_array = unserialize($_POST['input_name']);

Note that to work with serialized arrays, you need to use POST as the form's transmission method, as GET has a size limit somewhere around 1024 characters.

I'd use sessions wherever possible.

How to verify element present or visible in selenium 2 (Selenium WebDriver)

Here is my Java code for Selenium WebDriver. Write the following method and call it during assertion:

protected boolean isElementPresent(By by){
        try{
            driver.findElement(by);
            return true;
        }
        catch(NoSuchElementException e){
            return false;
        }
    }

how to access downloads folder in android?

If you're using a shell, the filepath to the Download (no "s") folder is

/storage/emulated/0/Download

.autocomplete is not a function Error

This is embarrassing but it held me up for a while so I figured I would post it here.

I did not have jQuery UI installed, only classic jQuery, which does not include autocomplete (apparently). Adding the following tags enabled autocomplete via jQuery UI.

<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">

and

<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

Of note, the HTML value autocomplete="off" for either the form or form block will prevent the brower from performing the method .autocomplete(), but will not block the jQuery UI function.

Drawing an SVG file on a HTML5 canvas

You can easily draw simple svgs onto a canvas by:

  1. Assigning the source of the svg to an image in base64 format
  2. Drawing the image onto a canvas

Note: The only drawback of the method is that it cannot draw images embedded in the svg. (see demo)

Demonstration:

(Note that the embedded image is only visible in the svg)

_x000D_
_x000D_
var svg = document.querySelector('svg');_x000D_
var img = document.querySelector('img');_x000D_
var canvas = document.querySelector('canvas');_x000D_
_x000D_
// get svg data_x000D_
var xml = new XMLSerializer().serializeToString(svg);_x000D_
_x000D_
// make it base64_x000D_
var svg64 = btoa(xml);_x000D_
var b64Start = 'data:image/svg+xml;base64,';_x000D_
_x000D_
// prepend a "header"_x000D_
var image64 = b64Start + svg64;_x000D_
_x000D_
// set it as the source of the img element_x000D_
img.src = image64;_x000D_
_x000D_
// draw the image onto the canvas_x000D_
canvas.getContext('2d').drawImage(img, 0, 0);
_x000D_
svg, img, canvas {_x000D_
  display: block;_x000D_
}
_x000D_
SVG_x000D_
_x000D_
<svg height="40">_x000D_
  <rect width="40" height="40" style="fill:rgb(255,0,255);" />_x000D_
  <image xlink:href="https://en.gravatar.com/userimage/16084558/1a38852cf33713b48da096c8dc72c338.png?size=20" height="20px" width="20px" x="10" y="10"></image>_x000D_
</svg>_x000D_
<hr/><br/>_x000D_
_x000D_
IMAGE_x000D_
<img/>_x000D_
<hr/><br/>_x000D_
   _x000D_
CANVAS_x000D_
<canvas></canvas>_x000D_
<hr/><br/>
_x000D_
_x000D_
_x000D_

How can I remove or replace SVG content?

Setting the id attribute when appending the svg element can also let d3 select so remove() later on this element by id :

var svg = d3.select("theParentElement").append("svg")
.attr("id","the_SVG_ID")
.attr("width",...

...

d3.select("#the_SVG_ID").remove();

How to search for an element in an stl list?

What you can do and what you should do are different matters.

If the list is very short, or you are only ever going to call find once then use the linear approach above.

However linear-search is one of the biggest evils I find in slow code, and consider using an ordered collection (set or multiset if you allow duplicates). If you need to keep a list for other reasons eg using an LRU technique or you need to maintain the insertion order or some other order, create an index for it. You can actually do that using a std::set of the list iterators (or multiset) although you need to maintain this any time your list is modified.

How to update/upgrade a package using pip?

The way is

pip install [package_name] --upgrade

or in short

pip install [package_name] -U

Using sudo will ask to enter your root password to confirm the action, but although common, is considered unsafe.

If you do not have a root password (if you are not the admin) you should probably work with virtualenv.

You can also use the user flag to install it on this user only.

pip install [package_name] --upgrade --user

Conditional formatting, entire row based

Use RC addressing. So, if I want the background color of Col B to depend upon the value in Col C and apply that from Rows 2 though 20:

Steps:

  1. Select R2C2 to R20C2

  2. Click on Conditional Formatting

  3. Select "Use a formula to determine what cells to format"

  4. Type in the formula: =RC[1] > 25

  5. Create the formatting you want (i.e. background color "yellow")

  6. Applies to: Make sure it says: =R2C2:R20C2

** Note that the "magic" takes place in step 4 ... using RC addressing to look at the value one column to the right of the cell being formatted. In this example, I am checking to see if the value of the cell one column to the right of the cell being formatting contains a value greater than 25 (note that you can put pretty much any formula here that returns a T/F value)

"java.lang.OutOfMemoryError : unable to create new native Thread"

To find which processes are creating threads try:

ps huH

I normally redirect output to a file and analysis the file offline (is thread count for each process is as expected or not)

How to go up a level in the src path of a URL in HTML?

Here is all you need to know about relative file paths:

  • Starting with / returns to the root directory and starts there

  • Starting with ../ moves one directory backward and starts there

  • Starting with ../../ moves two directories backward and starts there (and so on...)

  • To move forward, just start with the first sub directory and keep moving forward.

Click here for more details!

error: request for member '..' in '..' which is of non-class type

Foo foo2();

change to

Foo foo2;

You get the error because compiler thinks of

Foo foo2()

as of function declaration with name 'foo2' and the return type 'Foo'.

But in that case If we change to Foo foo2 , the compiler might show the error " call of overloaded ‘Foo()’ is ambiguous".

How to split a list by comma not space

kent$  echo "Hello,World,Questions,Answers,bash shell,script"|awk -F, '{for (i=1;i<=NF;i++)print $i}'
Hello
World
Questions
Answers
bash shell
script

SSRS Field Expression to change the background color of the Cell

=IIF(fields!column.value =Condition,"Red","Black")

Various ways to remove local Git changes

Use:

git checkout -- <file>

To discard the changes in the working directory.

Working with SQL views in Entity Framework Core

It is possible to scaffold a view. Just use -Tables the way you would to scaffold a table, only use the name of your view. E.g., If the name of your view is ‘vw_inventory’, then run this command in the Package Manager Console (substituting your own information for "My..."):

PM> Scaffold-DbContext "Server=MyServer;Database=MyDatabase;user id=MyUserId;password=MyPassword" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Temp -Tables vw_inventory

This command will create a model file and context file in the Temp directory of your project. You can move the model file into your models directory (remember to change the namespace name). You can copy what you need from the context file and paste it into the appropriate existing context file in your project.

Note: If you want to use your view in an integration test using a local db, you'll need to create the view as part of your db setup. If you’re going to use the view in more than one test, make sure to add a check for existence of the view. In this case, since the SQL ‘Create View’ statement is required to be the only statement in the batch, you’ll need to run the create view as dynamic Sql within the existence check statement. Alternatively you could run separate ‘if exists drop view…’, then ‘create view’ statements, but if multiple tests are running concurrently, you don’t want the view to be dropped if another test is using it. Example:

  void setupDb() {
    ...
    SomeDb.Command(db => db.Database.ExecuteSqlRaw(CreateInventoryView()));
    ...
  }
  public string CreateInventoryView() => @"
  IF OBJECT_ID('[dbo].[vw_inventory]') IS NULL
    BEGIN EXEC('CREATE VIEW [dbo].[vw_inventory] AS
       SELECT ...')
    END";

How do I declare an array of undefined or no initial size?

This can be done by using a pointer, and allocating memory on the heap using malloc. Note that there is no way to later ask how big that memory block is. You have to keep track of the array size yourself.

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

int main(int argc, char** argv)
{
  /* declare a pointer do an integer */
  int *data; 
  /* we also have to keep track of how big our array is - I use 50 as an example*/
  const int datacount = 50;
  data = malloc(sizeof(int) * datacount); /* allocate memory for 50 int's */
  if (!data) { /* If data == 0 after the call to malloc, allocation failed for some reason */
    perror("Error allocating memory");
    abort();
  }
  /* at this point, we know that data points to a valid block of memory.
     Remember, however, that this memory is not initialized in any way -- it contains garbage.
     Let's start by clearing it. */
  memset(data, 0, sizeof(int)*datacount);
  /* now our array contains all zeroes. */
  data[0] = 1;
  data[2] = 15;
  data[49] = 66; /* the last element in our array, since we start counting from 0 */
  /* Loop through the array, printing out the values (mostly zeroes, but even so) */
  for(int i = 0; i < datacount; ++i) {
    printf("Element %d: %d\n", i, data[i]);
  }
}

That's it. What follows is a more involved explanation of why this works :)

I don't know how well you know C pointers, but array access in C (like array[2]) is actually a shorthand for accessing memory via a pointer. To access the memory pointed to by data, you write *data. This is known as dereferencing the pointer. Since data is of type int *, then *data is of type int. Now to an important piece of information: (data + 2) means "add the byte size of 2 ints to the adress pointed to by data".

An array in C is just a sequence of values in adjacent memory. array[1] is just next to array[0]. So when we allocate a big block of memory and want to use it as an array, we need an easy way of getting the direct adress to every element inside. Luckily, C lets us use the array notation on pointers as well. data[0] means the same thing as *(data+0), namely "access the memory pointed to by data". data[2] means *(data+2), and accesses the third int in the memory block.

How to include a Font Awesome icon in React's render()

npm install --save font-awesome

import 'font-awesome/css/font-awesome.min.css';

then

<i className="fa fa-shopping-cart" style={{fontSize:24}}></i>  
        <span className="badge badge-danger" style={{position:"absolute", right:5, top:5}}>number of items in cart</span>

Storing WPF Image Resources

Yes, it is the right way.

You could use the image in the resource file just using the path:

<Image Source="..\Media\Image.png" />

You must set the build action of the image file to "Resource".

Can't get ScriptManager.RegisterStartupScript in WebControl nested in UpdatePanel to work

I try many things and finally found that the last parameter must be false and you must add <SCRIPT> tag to the java script :

string script = "< SCRIPT >alert('hello!');< /SCRIPT>";

ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), key, script, **false**);

Python urllib2 Basic Auth Problem

I would suggest that the current solution is to use my package urllib2_prior_auth which solves this pretty nicely (I work on inclusion to the standard lib.

sweet-alert display HTML code in text

As of 2018, the accepted answer is out-of-date:

Sweetalert is maintained, and you can solve the original question's issue with use of the content option.

How to recursively find the latest modified file in a directory?

This gives a sorted list:

find . -type f -ls 2>/dev/null | sort -M -k8,10 | head -n5

Reverse the order by placing a '-r' in the sort command. If you only want filenames, insert "awk '{print $11}' |" before '| head'

A beginner's guide to SQL database design

I started out with this article

http://en.tekstenuitleg.net/articles/software/database-design-tutorial/intro.html

It's pretty concise compared to reading an entire book and it explains the basics of database design (normalization, types of relationships) very well.

SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed

If you're using RVM on OS X, you probably need to run this:

rvm osx-ssl-certs update all

More information here: http://rvm.io/support/fixing-broken-ssl-certificates

And here is the full explanation: https://github.com/wayneeseguin/rvm/blob/master/help/osx-ssl-certs.md


Update

On Ruby 2.2, you may have to reinstall Ruby from source to fix this. Here's how (replace 2.2.3 with your Ruby version):

rvm reinstall 2.2.3 --disable-binary

Credit to https://stackoverflow.com/a/32363597/4353 and Ian Connor.

CSS class for pointer cursor

I usually just add the following custom CSS, the W3School example prepended with cursor-

_x000D_
_x000D_
.cursor-alias {cursor: alias;}_x000D_
.cursor-all-scroll {cursor: all-scroll;}_x000D_
.cursor-auto {cursor: auto;}_x000D_
.cursor-cell {cursor: cell;}_x000D_
.cursor-context-menu {cursor: context-menu;}_x000D_
.cursor-col-resize {cursor: col-resize;}_x000D_
.cursor-copy {cursor: copy;}_x000D_
.cursor-crosshair {cursor: crosshair;}_x000D_
.cursor-default {cursor: default;}_x000D_
.cursor-e-resize {cursor: e-resize;}_x000D_
.cursor-ew-resize {cursor: ew-resize;}_x000D_
.cursor-grab {cursor: -webkit-grab; cursor: grab;}_x000D_
.cursor-grabbing {cursor: -webkit-grabbing; cursor: grabbing;}_x000D_
.cursor-help {cursor: help;}_x000D_
.cursor-move {cursor: move;}_x000D_
.cursor-n-resize {cursor: n-resize;}_x000D_
.cursor-ne-resize {cursor: ne-resize;}_x000D_
.cursor-nesw-resize {cursor: nesw-resize;}_x000D_
.cursor-ns-resize {cursor: ns-resize;}_x000D_
.cursor-nw-resize {cursor: nw-resize;}_x000D_
.cursor-nwse-resize {cursor: nwse-resize;}_x000D_
.cursor-no-drop {cursor: no-drop;}_x000D_
.cursor-none {cursor: none;}_x000D_
.cursor-not-allowed {cursor: not-allowed;}_x000D_
.cursor-pointer {cursor: pointer;}_x000D_
.cursor-progress {cursor: progress;}_x000D_
.cursor-row-resize {cursor: row-resize;}_x000D_
.cursor-s-resize {cursor: s-resize;}_x000D_
.cursor-se-resize {cursor: se-resize;}_x000D_
.cursor-sw-resize {cursor: sw-resize;}_x000D_
.cursor-text {cursor: text;}_x000D_
.cursor-w-resize {cursor: w-resize;}_x000D_
.cursor-wait {cursor: wait;}_x000D_
.cursor-zoom-in {cursor: zoom-in;}_x000D_
.cursor-zoom-out {cursor: zoom-out;}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<button type="button" class="btn btn-success cursor-pointer">Sample Button</button>
_x000D_
_x000D_
_x000D_

JSP : JSTL's <c:out> tag

As said Will Wagner, in old version of jsp you should always use c:out to output dynamic text.

Moreover, using this syntax:

<c:out value="${person.name}">No name</c:out>

you can display the text "No name" when name is null.

remove all special characters in java

You can read the lines and replace all special characters safely this way.
Keep in mind that if you use \\W you will not replace underscores.

Scanner scan = new Scanner(System.in);

while(scan.hasNextLine()){
    System.out.println(scan.nextLine().replaceAll("[^a-zA-Z0-9]", ""));
}

Make browser window blink in task Bar

The only way I can think of doing this is by doing something like alert('you have a new message') when the message is received. This will flash the taskbar if the window is minimized, but it will also open a dialog box, which you may not want.

How to split a comma separated string and process in a loop using JavaScript

Try the following snippet:

var mystring = 'this,is,an,example';
var splits = mystring.split(",");
alert(splits[0]); // output: this

CMake error at CMakeLists.txt:30 (project): No CMAKE_C_COMPILER could be found

You can also make sure you are the sudo user and you have READ/WRITE access on the directory you are working. I had a similar problem on OS X, and I got it fixed just by entering in sudo mode.

file.delete() returns false even though file.exists(), file.canRead(), file.canWrite(), file.canExecute() all return true

It was pretty odd the trick that worked. The thing is when I have previously read the content of the file, I used BufferedReader. After reading, I closed the buffer.

Meanwhile I switched and now I'm reading the content using FileInputStream. Also after finishing reading I close the stream. And now it's working.

The problem is I don't have the explanation for this.

I don't know BufferedReader and FileOutputStream to be incompatible.

How to handle notification when app in background in Firebase

I feel like all the responses are incomplete but all of them have something that you need to process a notification that have data when your app is in background.

Follow these steps and you will be able to process your notifications when your app is in background.

1.Add an intent-filter like this:

<activity android:name=".MainActivity">
      <intent-filter>
           <action android:name=".MainActivity" />
           <category android:name="android.intent.category.DEFAULT" />
      </intent-filter>
</activity>

to an activity that you want to process the notification data.

  1. Send notifications with the next format:

    { 
     "notification" : {
            "click_action" : ".MainActivity", 
            "body" : "new Symulti update !", 
            "title" : "new Symulti update !", 
            "icon" : "ic_notif_symulti" }, 
     "data": { ... },
     "to" : "c9Vaa3ReGdk:APA91bH-AuXgg3lDN2WMcBrNhJZoFtYF9" }
    

The key here is add

"click_action" : ".MainActivity"

where .MainActivity is the activity with the intent-filter that you added in step 1.

  1. Get "data" info from notification in the onCreate of ".MainActivity":

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //get notification data info
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
           //bundle must contain all info sent in "data" field of the notification
        }
    }
    

And that should be all you need to do. I hope this helps somebody :)

How to compare if two structs, slices or maps are equal?

Here's how you'd roll your own function http://play.golang.org/p/Qgw7XuLNhb

func compare(a, b T) bool {
  if &a == &b {
    return true
  }
  if a.X != b.X || a.Y != b.Y {
    return false
  }
  if len(a.Z) != len(b.Z) || len(a.M) != len(b.M) {
    return false
  }
  for i, v := range a.Z {
    if b.Z[i] != v {
      return false
    }
  }
  for k, v := range a.M {
    if b.M[k] != v {
      return false
    }
  }
  return true
}

What to do with commit made in a detached head

Maybe not the best solution, (will rewrite history) but you could also do git reset --hard <hash of detached head commit>.

Force the origin to start at 0

In the latest version of ggplot2, this can be more easy.

p <- ggplot(mtcars, aes(wt, mpg))
p + geom_point()
p+ geom_point() + scale_x_continuous(expand = expansion(mult = c(0, 0))) + scale_y_continuous(expand = expansion(mult = c(0, 0)))

enter image description here

See ?expansion() for more details.

Adding integers to an int array

An array has a fixed length. You cannot 'add' to it. You define at the start how long it will be.

int[] num = new int[5];

This creates an array of integers which has 5 'buckets'. Each bucket contains 1 integer. To begin with these will all be 0.

num[0] = 1;
num[1] = 2;

The two lines above set the first and second values of the array to 1 and 2. Now your array looks like this:

[1,2,0,0,0]

As you can see you set values in it, you don't add them to the end.

If you want to be able to create a list of numbers which you add to, you should use ArrayList.

Reloading/refreshing Kendo Grid

The default/updated configuration/data of the widgets is set to automatically bind to an associated DataSource.

$('#GridId').data('kendoGrid').dataSource.read();
$('#GridId').data('kendoGrid').refresh();

Querying DynamoDB by date

Updated Answer There is no convenient way to do this using Dynamo DB Queries with predictable throughput. One (sub optimal) option is to use a GSI with an artificial HashKey & CreatedAt. Then query by HashKey alone and mention ScanIndexForward to order the results. If you can come up with a natural HashKey (say the category of the item etc) then this method is a winner. On the other hand, if you keep the same HashKey for all items, then it will affect the throughput mostly when when your data set grows beyond 10GB (one partition)

Original Answer: You can do this now in DynamoDB by using GSI. Make the "CreatedAt" field as a GSI and issue queries like (GT some_date). Store the date as a number (msecs since epoch) for this kind of queries.

Details are available here: Global Secondary Indexes - Amazon DynamoDB : http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GSI.html#GSI.Using

This is a very powerful feature. Be aware that the query is limited to (EQ | LE | LT | GE | GT | BEGINS_WITH | BETWEEN) Condition - Amazon DynamoDB : http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Condition.html

XPath Query: get attribute href from a tag

The answer shared by @mockinterface is correct. Although I would like to add my 2 cents to it.

If someone is using frameworks like scrapy the you will have to use /html/body//a[contains(@href,'com')][2]/@href along with get() like this:

response.xpath('//a[contains(@href,'com')][2]/@href').get()

What should be the package name of android app?

Package name is the reversed domain name, it is a unique name for each application on Playstore. You can't upload two apps with the same package name. You can check package name of the app from playstore url

https://play.google.com/store/apps/details?id=package_name

so you can easily check on playstore that this package name is in used by some other app or not before uploading it.

Cannot use Server.MapPath

Firt add a reference to System.web, if you don't have. Do that in the References folder.

You can then use Hosting.HostingEnvironment.MapPath(path);

What is a good regular expression to match a URL?

Regex if you want to ensure URL starts with HTTP/HTTPS:

https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)

If you do not require HTTP protocol:

[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)

To try this out see http://regexr.com?37i6s, or for a version which is less restrictive http://regexr.com/3e6m0.

Example JavaScript implementation:

_x000D_
_x000D_
var expression = /[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)?/gi;_x000D_
var regex = new RegExp(expression);_x000D_
var t = 'www.google.com';_x000D_
_x000D_
if (t.match(regex)) {_x000D_
  alert("Successful match");_x000D_
} else {_x000D_
  alert("No match");_x000D_
}
_x000D_
_x000D_
_x000D_

What does <> mean in excel?

It means "not equal to" (as in, the values in cells E37-N37 are not equal to "", or in other words, they are not empty.)

Separation of business logic and data access in django

Django employs a slightly modified kind of MVC. There's no concept of a "controller" in Django. The closest proxy is a "view", which tends to cause confusion with MVC converts because in MVC a view is more like Django's "template".

In Django, a "model" is not merely a database abstraction. In some respects, it shares duty with the Django's "view" as the controller of MVC. It holds the entirety of behavior associated with an instance. If that instance needs to interact with an external API as part of it's behavior, then that's still model code. In fact, models aren't required to interact with the database at all, so you could conceivable have models that entirely exist as an interactive layer to an external API. It's a much more free concept of a "model".

Using global variables between files?

I just came across this post and thought of posting my solution, just in case of anyone being in the same situation as me, where there are quite some files in the developed program, and you don't have the time to think through the whole import sequence of your modules (if you didn't think of that properly right from the start, such as I did).

In such cases, in the script where you initiate your global(s), simply code a class which says like:

class My_Globals:
  def __init__(self):
    self.global1 = "initial_value_1"
    self.global2 = "initial_value_2"
    ...

and then use, instead of the line in the script where you initiated your globals, instead of

global1 = "initial_value_1"

use

globals = My_Globals()

I was then able to retrieve / change the values of any of these globals via

globals.desired_global

in any script, and these changes were automatically also applied to all the other scripts using them. All worked now, by using the exact same import statements which previously failed, due to the problems mentioned in this post / discussion here. I simply thought of global object's properties being changing dynamically without the need of considering / changing any import logic, in comparison to simple importing of global variables, and that definitely was the quickest and easiest (for later access) approach to solve this kind of problem for me.

Passing data between view controllers

For SwiftUI

Think of @EnvironmentObject as a smarter, simpler way of using @ObservedObject on lots of views. Rather than creating some data in view A, then passing it to view B, then view C, then view D before finally using it, you can create it in view and put it into the environment so that views B, C, and D will automatically have access to it.

Note: Environment objects must be supplied by an ancestor view – if SwiftUI can’t find an environment object of the correct type you’ll get a crash. This applies for previews too, so be careful.

As an example, here’s an observable object that stores user settings:

class UserSettings: ObservableObject {
     @Published var score = 0
}

UILabel Align Text to center

N.B.: As per the UILabel class reference, as of iOS 6 this approach is now deprecated.

Simply use the textAlignment property to see the required alignment using one of the UITextAlignment values. (UITextAlignmentLeft, UITextAlignmentCenter or UITextAlignmentRight.)

e.g.: [myUILabel setTextAlignment:UITextAlignmentCenter];

See the UILabel Class Reference for more information.

Declaring static constants in ES6 classes?

Like https://stackoverflow.com/users/2784136/rodrigo-botti said, I think you're looking for Object.freeze(). Here's an example of a class with immutable statics:

class User {
  constructor(username, age) {
    if (age < User.minimumAge) {
      throw new Error('You are too young to be here!');
    }
    this.username = username;
    this.age = age;
    this.state = 'active';
  }
}

User.minimumAge = 16;
User.validStates = ['active', 'inactive', 'archived'];

deepFreeze(User);

function deepFreeze(value) {
  if (typeof value === 'object' && value !== null) {
    Object.freeze(value);
    Object.getOwnPropertyNames(value).forEach(property => {
      deepFreeze(value[property]);
    });
  }
  return value;
}

Get list from pandas DataFrame column headers

list(df.columns)

This gives you the list of column names of a data frame df.

Android SDK Manager Not Installing Components

In Mac OS X (tried with Android Studio), do the following in Terminal

cd /android/adt-bundle-mac-x86_64/sdk/tools 
sudo ./android sdk

This launches SDK manager as admin. Now update/install the packages from SDK manager and it'll work.

Invoking Java main method with parameters from Eclipse

If have spaces within your string argument, do the following:

Run > Run Configurations > Java Application > Arguments > Program arguments

  1. Enclose your string argument with quotes
  2. Separate each argument by space or new line

Checking if a website is up via Python

You can use httplib

import httplib
conn = httplib.HTTPConnection("www.python.org")
conn.request("HEAD", "/")
r1 = conn.getresponse()
print r1.status, r1.reason

prints

200 OK

Of course, only if www.python.org is up.

Inline for loop

What you are using is called a list comprehension in Python, not an inline for-loop (even though it is similar to one). You would write your loop as a list comprehension like so:

p = [q.index(v) if v in q else 99999 for v in vm]

When using a list comprehension, you do not call list.append because the list is being constructed from the comprehension itself. Each item in the list will be what is returned by the expression on the left of the for keyword, which in this case is q.index(v) if v in q else 99999. Incidentially, if you do use list.append inside a comprehension, then you will get a list of None values because that is what the append method always returns.

Can you detect "dragging" in jQuery?

$(".draggable")
.mousedown(function(e){
    $(this).on("mousemove",function(e){
        var p1 = { x: e.pageX, y: e.pageY };
        var p0 = $(this).data("p0") || p1;
        console.log("dragging from x:" + p0.x + " y:" + p0.y + "to x:" + p1.x + " y:" + p1.y);
        $(this).data("p0", p1);
    });
})
.mouseup(function(){
    $(this).off("mousemove");
});

This solution uses the "on" and "off" functions to bind an unbind a mousemove event (bind and unbind are deprecated). You can also detect the change in mouse x and y positions between two mousemove events.