Programs & Examples On #Nsapi

PHP Fatal error: Call to undefined function mssql_connect()

I have just tried to install that extension on my dev server.

First, make sure that the extension is correctly enabled. Your phpinfo() output doesn't seem complete.

If it is indeed installed properly, your phpinfo() should have a section that looks like this: enter image description here

If you do not get that section in your phpinfo(). Make sure that you are using the right version. There are both non-thread-safe and thread-safe versions of the extension.

Finally, check your extension_dir setting. By default it's this: extension_dir = "ext", for most of the time it works fine, but if it doesn't try: extension_dir = "C:\PHP\ext".

===========================================================================

EDIT given new info:

You are using the wrong function. mssql_connect() is part of the Mssql extension. You are using microsoft's extension, so use sqlsrv_connect(), for the API for the microsoft driver, look at SQLSRV_Help.chm which should be extracted to your ext directory when you extracted the extension.

vertical alignment of text element in SVG

After looking at the SVG Recommendation I've come to the understanding that the baseline properties are meant to position text relative to other text, especially when mixing different fonts and or languages. If you want to postion text so that it's top is at y then you need use dy = "y + the height of your text".

Negative list index?

List indexes of -x mean the xth item from the end of the list, so n[-1] means the last item in the list n. Any good Python tutorial should have told you this.

It's an unusual convention that only a few other languages besides Python have adopted, but it is extraordinarily useful; in any other language you'll spend a lot of time writing n[n.length-1] to access the last item of a list.

How to directly execute SQL query in C#?

Something like this should suffice, to do what your batch file was doing (dumping the result set as semi-colon delimited text to the console):

// sqlcmd.exe
// -S .\PDATA_SQLEXPRESS
// -U sa
// -P 2BeChanged!
// -d PDATA_SQLEXPRESS
// -s ; -W -w 100
// -Q "SELECT tPatCulIntPatIDPk, tPatSFirstname, tPatSName, tPatDBirthday  FROM  [dbo].[TPatientRaw] WHERE tPatSName = '%name%' "

DataTable dt            = new DataTable() ;
int       rows_returned ;

const string credentials = @"Server=(localdb)\.\PDATA_SQLEXPRESS;Database=PDATA_SQLEXPRESS;User ID=sa;Password=2BeChanged!;" ;
const string sqlQuery = @"
  select tPatCulIntPatIDPk ,
         tPatSFirstname    ,
         tPatSName         ,
         tPatDBirthday
  from dbo.TPatientRaw
  where tPatSName = @patientSurname
  " ;

using ( SqlConnection connection = new SqlConnection(credentials) )
using ( SqlCommand    cmd        = connection.CreateCommand() )
using ( SqlDataAdapter sda       = new SqlDataAdapter( cmd ) )
{
  cmd.CommandText = sqlQuery ;
  cmd.CommandType = CommandType.Text ;
  connection.Open() ;
  rows_returned = sda.Fill(dt) ;
  connection.Close() ;
}

if ( dt.Rows.Count == 0 )
{
  // query returned no rows
}
else
{

  //write semicolon-delimited header
  string[] columnNames = dt.Columns
                           .Cast<DataColumn>()
                           .Select( c => c.ColumnName )
                           .ToArray()
                           ;
  string   header      = string.Join("," , columnNames) ;
  Console.WriteLine(header) ;

  // write each row
  foreach ( DataRow dr in dt.Rows )
  {

    // get each rows columns as a string (casting null into the nil (empty) string
    string[] values = new string[dt.Columns.Count];
    for ( int i = 0 ; i < dt.Columns.Count ; ++i )
    {
      values[i] = ((string) dr[i]) ?? "" ; // we'll treat nulls as the nil string for the nonce
    }

    // construct the string to be dumped, quoting each value and doubling any embedded quotes.
    string data = string.Join( ";" , values.Select( s => "\""+s.Replace("\"","\"\"")+"\"") ) ;
    Console.WriteLine(values);

  }

}

to_string is not a member of std, says g++ (mingw)

If we use a template-light-solution (as shown above) like the following:

namespace std {
    template<typename T>
    std::string to_string(const T &n) {
        std::ostringstream s;
        s << n;
        return s.str();
    }
}

Unfortunately, we will have problems in some cases. For example, for static const members:

hpp

class A
{
public:

    static const std::size_t x = 10;

    A();
};

cpp

A::A()
{
    std::cout << std::to_string(x);
}

And linking:

CMakeFiles/untitled2.dir/a.cpp.o:a.cpp:(.rdata$.refptr._ZN1A1xE[.refptr._ZN1A1xE]+0x0): undefined reference to `A::x'
collect2: error: ld returned 1 exit status

Here is one way to solve the problem (add to the type size_t):

namespace std {
    std::string to_string(size_t n) {
        std::ostringstream s;
        s << n;
        return s.str();
    }
}

HTH.

How to connect to Mysql Server inside VirtualBox Vagrant?

Log in to your box with ssh [email protected] -p 2222 (password vagrant)

Then: sudo nano /etc/mysql/my.cnf and comment out the following lines with #

#skip-external-locking 
#bind-address

save it & exit

then: sudo service mysql restart

Then you can connect through SSH to your MySQL server.

What does the "+=" operator do in Java?

XOR operator rule =>

0 ^ 0 = 0
1 ^ 1 = 0
0 ^ 1 = 1
1 ^ 0 = 1

Binary representation of 4, 5 and 6 :

4 = 1 0 0 
5 = 1 0 1
6 = 1 1 0

now, perform XOR operation on 5 and 4:

     5 ^ 4 => 1  0  1   (5)
              1  0  0   (4)
            ----------
              0  0  1   => 1

Similarly,

5 ^ 5 => 1   0   1    (5)
         1   0   1    (5)
       ------------
         0   0   0   => (0)


5 ^ 6 => 1   0   1  (5)
         1   1   0  (6)
        -----------
         0   1   1  => 3

Under what conditions is a JSESSIONID created?

CORRECTION: Please vote for Peter Štibraný's answer - it is more correct and complete!

A "JSESSIONID" is the unique id of the http session - see the javadoc here. There, you'll find the following sentence

Session information is scoped only to the current web application (ServletContext), so information stored in one context will not be directly visible in another.

So when you first hit a site, a new session is created and bound to the SevletContext. If you deploy multiple applications, the session is not shared.

You can also invalidate the current session and therefore create a new one. e.g. when switching from http to https (after login), it is a very good idea, to create a new session.

Hope, this answers your question.

403 Access Denied on Tomcat 8 Manager App without prompting for user/password

<role rolename="tomcat"/>
  <role rolename="manager-gui"/>
  <role rolename="admin-gui"/>
  <role rolename="manager-script"/>
  <role rolename="manager-jmx"/>
  <user username="admin" password="admin" roles="tomcat,manager-gui,admin-gui,manager-script,manager-jmx"/>


Close all the session, once closed, ensure open the URL in incognito mode login again and it should start working

Is Google Play Store supported in avd emulators?

The Google Play Store is now officially preinstalled the Android Emulator. Make sure you are running the latest version of Android Studio 2.4. In the Android Studio AVD Manager choose a virtual device configuration that has the Google Play store icon next to it, and then select one of the system images that have the label "Google Play". See this release note: https://androidstudio.googleblog.com/2017/04/android-studio-24-preview-4-is-now.html

Android Studio AVD Manager with Google Play Store support

Changing CSS for last <li>

:last-child is CSS3 and has no IE support while :first-child is CSS2, I believe the following is the safe way to implement it using jquery

$('li').last().addClass('someClass');

Can a java lambda have more than 1 parameter?

For this case you could use interfaces from default library (java 1.8):

java.util.function.BiConsumer
java.util.function.BiFunction

There is a small (not the best) example of default method in interface:

default BiFunction<File, String, String> getFolderFileReader() {
    return (directory, fileName) -> {
        try {
            return FileUtils.readFile(directory, fileName);
        } catch (IOException e) {
            LOG.error("Unable to read file {} in {}.", fileName, directory.getAbsolutePath(), e);
        }
        return "";
    };
}}

How to find the Windows version from the PowerShell command line

This will give you the full version of Windows (including Revision/Build number) unlike all the solutions above:

(Get-ItemProperty -Path c:\windows\system32\hal.dll).VersionInfo.FileVersion

Result:

10.0.10240.16392 (th1_st1.150716-1608)

Escape a string in SQL Server so that it is safe to use in LIKE expression

Alternative escaping syntax:

LIKE Wildcard Literals

The JDBC driver supports the {escape 'escape character'} syntax for using LIKE clause wildcards as literals.

SELECT *
FROM tab
WHERE col LIKE 'a\_c' {escape '\'};

db<>fiddle demo

How can strip whitespaces in PHP's variable?

Any possible option is to use custom file wrapper for simulating variables as files. You can achieve it by using this:

1) First of all, register your wrapper (only once in file, use it like session_start()):

stream_wrapper_register('var', VarWrapper);

2) Then define your wrapper class (it is really fast written, not completely correct, but it works):

class VarWrapper {
  protected $pos = 0;
  protected $content;
  public function stream_open($path, $mode, $options, &$opened_path) {
    $varname = substr($path, 6);
    global $$varname;
    $this->content = $$varname;
    return true;
  }
  public function stream_read($count) {
    $s = substr($this->content, $this->pos, $count);
    $this->pos += $count;
    return $s;
  }
  public function stream_stat() {
    $f = fopen(__file__, 'rb');
    $a = fstat($f);
    fclose($f);
    if (isset($a[7])) $a[7] = strlen($this->content);
    return $a;
  }
}

3) Then use any file function with your wrapper on var:// protocol (you can use it for include, require etc. too):

global $__myVar;
$__myVar = 'Enter tags here';
$data = php_strip_whitespace('var://__myVar');

Note: Don't forget to have your variable in global scope (like global $__myVar)

Splitting templated C++ classes into .hpp/.cpp files--is it possible?

It is possible, as long as you know what instantiations you are going to need.

Add the following code at the end of stack.cpp and it'll work :

template class stack<int>;

All non-template methods of stack will be instantiated, and linking step will work fine.

How to use the TextWatcher class in Android?

A little bigger perspective of the solution:

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.yourlayout, container, false);
        View tv = v.findViewById(R.id.et1);
        ((TextView) tv).addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                 SpannableString contentText = new SpannableString(((TextView) tv).getText());
                 String contents = Html.toHtml(contentText).toString();
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                // TODO Auto-generated method stub
            }

            @Override
            public void afterTextChanged(Editable s) {

                // TODO Auto-generated method stub
            }
        });
        return v;
    }

This works for me, doing it my first time.

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysql.sock' (2)

Simple: run these codes:::

 1:: ls -lart/var/run/my*

   2::mkdir /var/run/mysqld

    3::touch /var/run/mysqld/mysqld.sock
    4:ls -lart /var/run/mysqld
    5::chown -R mysql /var/run/mysqld
    6::ls -lart /var/run/mysqld
REstart your mysql server

then finaly type mysql -u root or mysql -u root -p and press enter key. thanks

How to make a function wait until a callback has been called using node.js

That defeats the purpose of non-blocking IO -- you're blocking it when it doesn't need blocking :)

You should nest your callbacks instead of forcing node.js to wait, or call another callback inside the callback where you need the result of r.

Chances are, if you need to force blocking, you're thinking about your architecture wrong.

Gson: Directly convert String to JsonObject (no POJO)

Try to use getAsJsonObject() instead of a straight cast used in the accepted answer:

JsonObject o = new JsonParser().parse("{\"a\": \"A\"}").getAsJsonObject();

No Application Encryption Key Has Been Specified

Simply run this command:

php artisan key:generate

Two models in one view in ASP MVC 3

Just create a single view Model with all the needed information in it, normaly what I do is create a model for every view so I can be specific on every view, either that or make a parent model and inherit it. OR make a model which includes both the views.

Personally I would just add them into one model but thats the way I do it:

public class xViewModel
{
    public int PersonID { get; set; }
    public string PersonName { get; set; }
    public int OrderID { get; set; }
    public int TotalSum { get; set; }
}

@model project.Models.Home.xViewModel

@using(Html.BeginForm())
{
    @Html.EditorFor(x => x.PersonID)
    @Html.EditorFor(x => x.PersonName)
    @Html.EditorFor(x => x.OrderID)
    @Html.EditorFor(x => x.TotalSum)
}

OpenCV NoneType object has no attribute shape

I also face the same issue "OpenCV NoneType object has no attribute shape" and i solve this by changing the image location. I also use the PyCharm IDE. Currently my image location and class file in the same folder. enter image description here

ie8 var w= window.open() - "Message: Invalid argument."

I discovered the same problem and after reading the first answer that supposed the problem is caused by the window name, changed it : first to '_blank', which worked fine (both compatibility and regular view), then to the previous value, only minus the space in the value :) - also worked. IMO, the problem (or part of it) is caused by IE being unable to use a normal string value as the wname. Hope this helps if anybody runs into the same problem.

What characters do I need to escape in XML documents?

Escaping characters is different for tags and attributes.

For tags:

 < &lt;
 > &gt; (only for compatibility, read below)
 & &amp;

For attributes:

" &quot;
' &apos;

From Character Data and Markup:

The ampersand character (&) and the left angle bracket (<) must not appear in their literal form, except when used as markup delimiters, or within a comment, a processing instruction, or a CDATA section. If they are needed elsewhere, they must be escaped using either numeric character references or the strings " &amp; " and " &lt; " respectively. The right angle bracket (>) may be represented using the string " &gt; ", and must, for compatibility, be escaped using either " &gt; " or a character reference when it appears in the string " ]]> " in content, when that string is not marking the end of a CDATA section.

To allow attribute values to contain both single and double quotes, the apostrophe or single-quote character (') may be represented as " &apos; ", and the double-quote character (") as " &quot; ".

JavaScript replace/regex

In terms of pattern interpretation, there's no difference between the following forms:

  • /pattern/
  • new RegExp("pattern")

If you want to replace a literal string using the replace method, I think you can just pass a string instead of a regexp to replace.

Otherwise, you'd have to escape any regexp special characters in the pattern first - maybe like so:

function reEscape(s) {
    return s.replace(/([.*+?^$|(){}\[\]])/mg, "\\$1");
}

// ...

var re = new RegExp(reEscape(pattern), "mg");
this.markup = this.markup.replace(re, value);

How can I discard remote changes and mark a file as "resolved"?

git checkout has the --ours option to check out the version of the file that you had locally (as opposed to --theirs, which is the version that you pulled in). You can pass . to git checkout to tell it to check out everything in the tree. Then you need to mark the conflicts as resolved, which you can do with git add, and commit your work once done:

git checkout --ours .  # checkout our local version of all files
git add -u             # mark all conflicted files as merged
git commit             # commit the merge

Note the . in the git checkout command. That's very important, and easy to miss. git checkout has two modes; one in which it switches branches, and one in which it checks files out of the index into the working copy (sometimes pulling them into the index from another revision first). The way it distinguishes is by whether you've passed a filename in; if you haven't passed in a filename, it tries switching branches (though if you don't pass in a branch either, it will just try checking out the current branch again), but it refuses to do so if there are modified files that that would effect. So, if you want a behavior that will overwrite existing files, you need to pass in . or a filename in order to get the second behavior from git checkout.

It's also a good habit to have, when passing in a filename, to offset it with --, such as git checkout --ours -- <filename>. If you don't do this, and the filename happens to match the name of a branch or tag, Git will think that you want to check that revision out, instead of checking that filename out, and so use the first form of the checkout command.

I'll expand a bit on how conflicts and merging work in Git. When you merge in someone else's code (which also happens during a pull; a pull is essentially a fetch followed by a merge), there are few possible situations.

The simplest is that you're on the same revision. In this case, you're "already up to date", and nothing happens.

Another possibility is that their revision is simply a descendent of yours, in which case you will by default have a "fast-forward merge", in which your HEAD is just updated to their commit, with no merging happening (this can be disabled if you really want to record a merge, using --no-ff).

Then you get into the situations in which you actually need to merge two revisions. In this case, there are two possible outcomes. One is that the merge happens cleanly; all of the changes are in different files, or are in the same files but far enough apart that both sets of changes can be applied without problems. By default, when a clean merge happens, it is automatically committed, though you can disable this with --no-commit if you need to edit it beforehand (for instance, if you rename function foo to bar, and someone else adds new code that calls foo, it will merge cleanly, but produce a broken tree, so you may want to clean that up as part of the merge commit in order to avoid having any broken commits).

The final possibility is that there's a real merge, and there are conflicts. In this case, Git will do as much of the merge as it can, and produce files with conflict markers (<<<<<<<, =======, and >>>>>>>) in your working copy. In the index (also known as the "staging area"; the place where files are stored by git add before committing them), you will have 3 versions of each file with conflicts; there is the original version of the file from the ancestor of the two branches you are merging, the version from HEAD (your side of the merge), and the version from the remote branch.

In order to resolve the conflict, you can either edit the file that is in your working copy, removing the conflict markers and fixing the code up so that it works. Or, you can check out the version from one or the other sides of the merge, using git checkout --ours or git checkout --theirs. Once you have put the file into the state you want it, you indicate that you are done merging the file and it is ready to commit using git add, and then you can commit the merge with git commit.

Spring @Autowired and @Qualifier

@Autowired to autowire(or search) by-type
@Qualifier to autowire(or search) by-name
Other alternate option for @Qualifier is @Primary

@Component
@Qualifier("beanname")
public class A{}

public class B{

//Constructor
@Autowired  
public B(@Qualifier("beanname")A a){...} //  you need to add @autowire also 

//property
@Autowired
@Qualifier("beanname")
private A a;

}

//If you don't want to add the two annotations, we can use @Resource
public class B{

//property
@Resource(name="beanname")
private A a;

//Importing properties is very similar
@Value("${property.name}")  //@Value know how to interpret ${}
private String name;
}

more about @value

Detecting Back Button/Hash Change in URL

HTML5 has included a much better solution than using hashchange which is the HTML5 State Management APIs - https://developer.mozilla.org/en/DOM/Manipulating_the_browser_history - they allow you to change the url of the page, without needing to use hashes!

Though the HTML5 State Functionality is only available to HTML5 Browsers. So you probably want to use something like History.js which provides a backwards compatible experience to HTML4 Browsers (via hashes, but still supports data and titles as well as the replaceState functionality).

You can read more about it here: https://github.com/browserstate/History.js

How to export database schema in Oracle to a dump file

It depends on which version of Oracle? Older versions require exp (export), newer versions use expdp (data pump); exp was deprecated but still works most of the time.

Before starting, note that Data Pump exports to the server-side Oracle "directory", which is an Oracle symbolic location mapped in the database to a physical location. There may be a default directory (DATA_PUMP_DIR), check by querying DBA_DIRECTORIES:

  SQL> select * from dba_directories;

... and if not, create one

  SQL> create directory DATA_PUMP_DIR as '/oracle/dumps';
  SQL> grant all on directory DATA_PUMP_DIR to myuser;    -- DBAs dont need this grant

Assuming you can connect as the SYSTEM user, or another DBA, you can export any schema like so, to the default directory:

 $ expdp system/manager schemas=user1 dumpfile=user1.dpdmp

Or specifying a specific directory, add directory=<directory name>:

 C:\> expdp system/manager schemas=user1 dumpfile=user1.dpdmp directory=DUMPDIR

With older export utility, you can export to your working directory, and even on a client machine that is remote from the server, using:

 $ exp system/manager owner=user1 file=user1.dmp

Make sure the export is done in the correct charset. If you haven't setup your environment, the Oracle client charset may not match the DB charset, and Oracle will do charset conversion, which may not be what you want. You'll see a warning, if so, then you'll want to repeat the export after setting NLS_LANG environment variable so the client charset matches the database charset. This will cause Oracle to skip charset conversion.

Example for American UTF8 (UNIX):

 $ export NLS_LANG=AMERICAN_AMERICA.AL32UTF8

Windows uses SET, example using Japanese UTF8:

 C:\> set NLS_LANG=Japanese_Japan.AL32UTF8

More info on Data Pump here: http://docs.oracle.com/cd/B28359_01/server.111/b28319/dp_export.htm#g1022624

Python Save to file

You can use this function:

def saveListToFile(listname, pathtosave):
    file1 = open(pathtosave,"w") 
    for i in listname:
        file1.writelines("{}\n".format(i))    
    file1.close() 

# to save:
saveListToFile(list, path)

while ($row = mysql_fetch_array($result)) - how many loops are being performed?

It depends how many rows are returned in $results, and how many columns there are in $row?

Allowed characters in filename

On Windows OS create a file and give it a invalid character like \ in the filename. As a result you will get a popup with all the invalid characters in a filename.

enter image description here

How to get a substring between two strings in PHP?

If you have multiple recurrences from a single string and you have different [start] and [\end] pattern. Here's a function which output an array.

function get_string_between($string, $start, $end){
    $split_string       = explode($end,$string);
    foreach($split_string as $data) {
         $str_pos       = strpos($data,$start);
         $last_pos      = strlen($data);
         $capture_len   = $last_pos - $str_pos;
         $return[]      = substr($data,$str_pos+1,$capture_len);
    }
    return $return;
}

How to open a web page automatically in full screen mode

You can go fullscreen automatically by putting this code in:

var elem = document.documentElement; if (elem.requestFullscreen) { elem.requestFullscreen() }

demo: https://codepen.io/ConfidentCoding/pen/ewLyPX

note: does not always work for security reasons. but it works for me at least. does not work when inspecting and pasting the code.

Java; String replace (using regular expressions)?

private String removeScript(String content) {
    Pattern p = Pattern.compile("<script[^>]*>(.*?)</script>",
            Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
    return p.matcher(content).replaceAll("");
}

Powershell 2 copy-item which creates a folder if doesn't exist

function Copy-File ([System.String] $sourceFile, [System.String] $destinationFile, [Switch] $overWrite) {

    if ($sourceFile -notlike "filesystem::*") {
        $sourceFile = "filesystem::$sourceFile" 
    }

    if ($destinationFile -notlike "filesystem::*") {
        $destinationFile = "filesystem::$destinationFile" 
    }

    $destinationFolder = $destinationFile.Replace($destinationFile.Split("\")[-1],"")

    if (!(Test-Path -path $destinationFolder)) {
        New-Item $destinationFolder -Type Directory
    }

    try {
        Copy-Item -Path $sourceFile -Destination $destinationFile -Recurse -Force
        Return $true 
    } catch [System.IO.IOException] {
        # If overwrite enabled, then delete the item from the destination, and try again:
        if ($overWrite) {
            try {
                Remove-Item -Path $destinationFile -Recurse -Force        
                Copy-Item -Path $sourceFile -Destination $destinationFile -Recurse -Force 
                Return $true
            } catch {
                Write-Error -Message "[Copy-File] Overwrite error occurred!`n$_" -ErrorAction SilentlyContinue
                #$PSCmdlet.WriteError($Global:Error[0])
                Return $false
            }
        } else {
            Write-Error -Message "[Copy-File] File already exists!" -ErrorAction SilentlyContinue
            #$PSCmdlet.WriteError($Global:Error[0])
            Return $false
        }
    } catch {
        Write-Error -Message "[Copy-File] File move failed!`n$_" -ErrorAction SilentlyContinue
        #$PSCmdlet.WriteError($Global:Error[0]) 
        Return $false
    } 
}

How to get current location in Android

First you need to define a LocationListener to handle location changes.

private final LocationListener mLocationListener = new LocationListener() {
    @Override
    public void onLocationChanged(final Location location) {
        //your code here
    }
};

Then get the LocationManager and ask for location updates

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

    mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, LOCATION_REFRESH_TIME,
            LOCATION_REFRESH_DISTANCE, mLocationListener);
}

And finally make sure that you have added the permission on the Manifest,

For using only network based location use this one

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

For GPS based location, this one

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

How to redirect the output of a PowerShell to a file during its execution

Use:

Write "Stuff to write" | Out-File Outputfile.txt -Append

Convert string to number field

Within Crystal, you can do it by creating a formula that uses the ToNumber function. It might be a good idea to code for the possibility that the field might include non-numeric data - like so:

If NumericText ({field}) then ToNumber ({field}) else 0

Alternatively, you might find it easier to convert the field's datatype within the query used in the report.

registerForRemoteNotificationTypes: is not supported in iOS 8.0 and later

If all you need is the ios 8 code, this should do it.

 - (BOOL)application:(UIApplication *)application       didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
       [application registerUserNotificationSettings: [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound  | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge)  categories:nil]];

       [application registerForRemoteNotifications];
}

 return YES;
}

How to style child components from parent component's CSS file?

For assigning an element's class in a child component you can simply use an @Input string in the child's component and use it as an expression inside the template. Here is an example of something we did to change the icon and button type in a shared Bootstrap loading button component, without affecting how it was already used throughout the codebase:

app-loading-button.component.html (child)

<button class="btn {{additionalClasses}}">...</button>

app-loading-button.component.ts

@Input() additionalClasses: string;

parent.html

<app-loading-button additionalClasses="fa fa-download btn-secondary">...</app-loading-button>

Visual Studio 2017: Display method references

No luck with Code lens in Community editions.

Press Shift + F12 to find all references.

How to insert a new line in strings in Android

Try:

String str = "my string \n my other string";

When printed you will get:

my string
my other string

List append() in for loop

No need to re-assign.

a=[]
for i in range(5):    
    a.append(i)
a

Breaking out of nested loops

It has at least been suggested, but also rejected. I don't think there is another way, short of repeating the test or re-organizing the code. It is sometimes a bit annoying.

In the rejection message, Mr van Rossum mentions using return, which is really sensible and something I need to remember personally. :)

String to object in JS

Since JSON.parse() method requires the Object keys to be enclosed within quotes for it to work correctly, we would first have to convert the string into a JSON formatted string before calling JSON.parse() method.

_x000D_
_x000D_
var obj = '{ firstName:"John", lastName:"Doe" }';_x000D_
_x000D_
var jsonStr = obj.replace(/(\w+:)|(\w+ :)/g, function(matchedStr) {_x000D_
  return '"' + matchedStr.substring(0, matchedStr.length - 1) + '":';_x000D_
});_x000D_
_x000D_
obj = JSON.parse(jsonStr); //converts to a regular object_x000D_
_x000D_
console.log(obj.firstName); // expected output: John_x000D_
console.log(obj.lastName); // expected output: Doe
_x000D_
_x000D_
_x000D_

This would work even if the string has a complex object (like the following) and it would still convert correctly. Just make sure that the string itself is enclosed within single quotes.

_x000D_
_x000D_
var strObj = '{ name:"John Doe", age:33, favorites:{ sports:["hoops", "baseball"], movies:["star wars", "taxi driver"]  }}';_x000D_
_x000D_
var jsonStr = strObj.replace(/(\w+:)|(\w+ :)/g, function(s) {_x000D_
  return '"' + s.substring(0, s.length-1) + '":';_x000D_
});_x000D_
_x000D_
var obj = JSON.parse(jsonStr);_x000D_
console.log(obj.favorites.movies[0]); // expected output: star wars
_x000D_
_x000D_
_x000D_

Select current element in jQuery

You will find the siblings() and parent() methods useful here.

// assuming A1 is clicked
$('div a').click(function(e) {
    $(this); // A1
    $(this).parent(); // the div containing A1
    $(this).siblings(); // A2 and A3
});

Combining those methods with andSelf() will let you manipulate any combination of those elements you want.

Edit: The comment left by Mark regarding event delegation on Shog9's answer is a very good one. The easiest way to accomplish this in jQuery would be by using the live() method.

// assuming A1 is clicked
$('div a').live('click', function(e) {
    $(this); // A1
    $(this).parent(); // the div containing A1
    $(this).siblings(); // A2 and A3
});

I think it actually binds the event to the root element, but the effect is that same. Not only is it more flexible, it also improves performance in a lot of cases. Just be sure to read the documentation to avoid any gotchas.

Does JavaScript have the interface type (such as Java's 'interface')?

JavaScript Interfaces:

Though JavaScript does not have the interface type, it is often times needed. For reasons relating to JavaScript's dynamic nature and use of Prototypical-Inheritance, it is difficult to ensure consistent interfaces across classes -- however, it is possible to do so; and frequently emulated.

At this point, there are handfuls of particular ways to emulate Interfaces in JavaScript; variance on approaches usually satisfies some needs, while others are left unaddressed. Often times, the most robust approach is overly cumbersome and stymies the implementor (developer).

Here is an approach to Interfaces / Abstract Classes that is not very cumbersome, is explicative, keeps implementations inside of Abstractions to a minimum, and leaves enough room for dynamic or custom methodologies:

function resolvePrecept(interfaceName) {
    var interfaceName = interfaceName;
    return function curry(value) {
        /*      throw new Error(interfaceName + ' requires an implementation for ...');     */
        console.warn('%s requires an implementation for ...', interfaceName);
        return value;
    };
}

var iAbstractClass = function AbstractClass() {
    var defaultTo = resolvePrecept('iAbstractClass');

    this.datum1 = this.datum1 || defaultTo(new Number());
    this.datum2 = this.datum2 || defaultTo(new String());

    this.method1 = this.method1 || defaultTo(new Function('return new Boolean();'));
    this.method2 = this.method2 || defaultTo(new Function('return new Object();'));

};

var ConcreteImplementation = function ConcreteImplementation() {

    this.datum1 = 1;
    this.datum2 = 'str';

    this.method1 = function method1() {
        return true;
    };
    this.method2 = function method2() {
        return {};
    };

    //Applies Interface (Implement iAbstractClass Interface)
    iAbstractClass.apply(this);  // .call / .apply after precept definitions
};

Participants

Precept Resolver

The resolvePrecept function is a utility & helper function to use inside of your Abstract Class. Its job is to allow for customized implementation-handling of encapsulated Precepts (data & behavior). It can throw errors or warn -- AND -- assign a default value to the Implementor class.

iAbstractClass

The iAbstractClass defines the interface to be used. Its approach entails a tacit agreement with its Implementor class. This interface assigns each precept to the same exact precept namespace -- OR -- to whatever the Precept Resolver function returns. However, the tacit agreement resolves to a context -- a provision of Implementor.

Implementor

The Implementor simply 'agrees' with an Interface (iAbstractClass in this case) and applies it by the use of Constructor-Hijacking: iAbstractClass.apply(this). By defining the data & behavior above, and then hijacking the Interface's constructor -- passing Implementor's context to the Interface constructor -- we can ensure that Implementor's overrides will be added, and that Interface will explicate warnings and default values.

This is a very non-cumbersome approach which has served my team & I very well for the course of time and different projects. However, it does have some caveats & drawbacks.

Drawbacks

Though this helps implement consistency throughout your software to a significant degree, it does not implement true interfaces -- but emulates them. Though definitions, defaults, and warnings or errors are explicated, the explication of use is enforced & asserted by the developer (as with much of JavaScript development).

This is seemingly the best approach to "Interfaces in JavaScript", however, I would love to see the following resolved:

  • Assertions of return types
  • Assertions of signatures
  • Freeze objects from delete actions
  • Assertions of anything else prevalent or needed in the specificity of the JavaScript community

That said, I hope this helps you as much as it has my team and I.

How to check if a string starts with one of several prefixes?

When you say you tried to use OR, how exactly did you try and use it? In your case, what you will need to do would be something like so:

String newStr4 = strr.split("2012")[0];
if(newStr4.startsWith("Mon") || newStr4.startsWith("Tues")...)
str4.add(newStr4);

How to change xampp localhost to another folder ( outside xampp folder)?

On Linux Mint (Debian Based) go to /opt/lampp/etc/httpd.conf

Find YOUR_OWN_FILES_LOCATION to, of course, your files location.

DocumentRoot "YOUR_OWN_FILES_LOCATION"
<Directory "YOUR_OWN_FILES_LOCATION">
    #
    # Possible values for the Options directive are "None", "All",
    # or any combination of:
    #   Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
    #
    # Note that "MultiViews" must be named *explicitly* --- "Options All"
    # doesn't give it to you.
    #
    # The Options directive is both complicated and important.  Please see
    # http://httpd.apache.org/docs/trunk/mod/core.html#options
    # for more information.
    #
    #Options Indexes FollowSymLinks
    # XAMPP
    Options Indexes FollowSymLinks ExecCGI Includes

    #
    # AllowOverride controls what directives may be placed in .htaccess files.
    # It can be "All", "None", or any combination of the keywords:
    #   Options FileInfo AuthConfig Limit
    #
    #AllowOverride None
    # since XAMPP 1.4:
    AllowOverride All

    #
    # Controls who can get stuff from this server.
    #
    Require all granted
</Directory>

How to "perfectly" override a dict?

After trying out both of the top two suggestions, I've settled on a shady-looking middle route for Python 2.7. Maybe 3 is saner, but for me:

class MyDict(MutableMapping):
   # ... the few __methods__ that mutablemapping requires
   # and then this monstrosity
   @property
   def __class__(self):
       return dict

which I really hate, but seems to fit my needs, which are:

  • can override **my_dict
    • if you inherit from dict, this bypasses your code. try it out.
    • this makes #2 unacceptable for me at all times, as this is quite common in python code
  • masquerades as isinstance(my_dict, dict)
    • rules out MutableMapping alone, so #1 is not enough
    • I heartily recommend #1 if you don't need this, it's simple and predictable
  • fully controllable behavior
    • so I cannot inherit from dict

If you need to tell yourself apart from others, personally I use something like this (though I'd recommend better names):

def __am_i_me(self):
  return True

@classmethod
def __is_it_me(cls, other):
  try:
    return other.__am_i_me()
  except Exception:
    return False

As long as you only need to recognize yourself internally, this way it's harder to accidentally call __am_i_me due to python's name-munging (this is renamed to _MyDict__am_i_me from anything calling outside this class). Slightly more private than _methods, both in practice and culturally.

So far I have no complaints, aside from the seriously-shady-looking __class__ override. I'd be thrilled to hear of any problems that others encounter with this though, I don't fully understand the consequences. But so far I've had no problems whatsoever, and this allowed me to migrate a lot of middling-quality code in lots of locations without needing any changes.


As evidence: https://repl.it/repls/TraumaticToughCockatoo

Basically: copy the current #2 option, add print 'method_name' lines to every method, and then try this and watch the output:

d = LowerDict()  # prints "init", or whatever your print statement said
print '------'
splatted = dict(**d)  # note that there are no prints here

You'll see similar behavior for other scenarios. Say your fake-dict is a wrapper around some other datatype, so there's no reasonable way to store the data in the backing-dict; **your_dict will be empty, regardless of what every other method does.

This works correctly for MutableMapping, but as soon as you inherit from dict it becomes uncontrollable.


Edit: as an update, this has been running without a single issue for almost two years now, on several hundred thousand (eh, might be a couple million) lines of complicated, legacy-ridden python. So I'm pretty happy with it :)

Edit 2: apparently I mis-copied this or something long ago. @classmethod __class__ does not work for isinstance checks - @property __class__ does: https://repl.it/repls/UnitedScientificSequence

How to retrieve the current value of an oracle sequence without increment it?

The follows is often used:

select field_SQ.nextval from dual;
select field_SQ.currval from DUAL;

However the following is able to change the sequence to what you expected. The 1 can be an integer (negative or positive)

alter sequence field_SQ increment by 1 minvalue 0

Unix - copy contents of one directory to another

To make an exact copy, permissions, ownership, and all use "-a" with "cp". "-r" will copy the contents of the files but not necessarily keep other things the same.

cp -av Source/* Dest/

(make sure Dest/ exists first)

If you want to repeatedly update from one to the other or make sure you also copy all dotfiles, rsync is a great help:

rsync -av --delete Source/ Dest/

This is also "recoverable" in that you can restart it if you abort it while copying. I like "-v" because it lets you watch what is going on but you can omit it.

How to select Python version in PyCharm?

Quick Answer:

  • File --> Setting
  • In left side in project section --> Project interpreter
  • Select desired Project interpreter
  • Apply + OK

[NOTE]:

Tested on Pycharm 2018 and 2017.


Dynamic function name in javascript?

In recent engines, you can do

_x000D_
_x000D_
function nameFunction(name, body) {_x000D_
  return {[name](...args) {return body(...args)}}[name]_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
const x = nameFunction("wonderful function", (p) => p*2)_x000D_
console.log(x(9)) // => 18_x000D_
console.log(x.name) // => "wonderful function"
_x000D_
_x000D_
_x000D_

Ansible: deploy on multiple hosts in the same time

By default Ansible will attempt to run on all hosts in parallel. See these Ansible docs for details. You can also use the serial parameter to limit the number of parallel hosts you want to be processed at any given time, so if you want to have a playbook run on just one host at a time you can specify serial:1, etc.

Ansible is designed so that each task will be run on all hosts before continuing on to the next task. So if you have 3 tasks it will ensure task 1 runs on all your hosts first, then task 2 is run, then task 3 is run. See this section of the Ansible docs for more details on this.

Python variables as keys to dict

for i in ('apple', 'banana', 'carrot'):
    fruitdict[i] = locals()[i]

How to add an element to the beginning of an OrderedDict?

You have to make a new instance of OrderedDict. If your keys are unique:

d1=OrderedDict([("a",1),("b",2)])
d2=OrderedDict([("c",3),("d",99)])
both=OrderedDict(list(d2.items()) + list(d1.items()))
print(both)

#OrderedDict([('c', 3), ('d', 99), ('a', 1), ('b', 2)])

But if not, beware as this behavior may or may not be desired for you:

d1=OrderedDict([("a",1),("b",2)])
d2=OrderedDict([("c",3),("b",99)])
both=OrderedDict(list(d2.items()) + list(d1.items()))
print(both)

#OrderedDict([('c', 3), ('b', 2), ('a', 1)])

Python datetime - setting fixed hour and minute after using strptime to get day,month,year

If you have date as a datetime.datetime (or a datetime.date) instance and want to combine it via a time from a datetime.time instance, then you can use the classmethod datetime.datetime.combine:

import datetime
dt = datetime.datetime(2020, 7, 1)
t = datetime.time(12, 34)
combined = datetime.datetime.combine(dt.date(), t)

Can I set text box to readonly when using Html.TextBoxFor?

To make it read only

@Html.TextBoxFor(m=> m.Total, new {@class ="form-control", @readonly="true"})

To diable

@Html.TextBoxFor(m=> m.Total, new {@class ="form-control", @disabled="true"})

How to set environment via `ng serve` in Angular 6

This answer seems good.
however, it lead me towards an error as it resulted with
Configuration 'xyz' could not be found in project ...
error in build.
It is requierd not only to updated build configurations, but also serve ones.

So just to leave no confusions:

  1. --env is not supported in angular 6
  2. --env got changed into --configuration || -c (and is now more powerful)
  3. to manage various envs, in addition to adding new environment file, it is now required to do some changes in angular.json file:
    • add new configuration in the build { ... "build": "configurations": ... property
    • new build configuration may contain only fileReplacements part, (but more options are available)
    • add new configuration in the serve { ... "serve": "configurations": ... property
    • new serve configuration shall contain of browserTarget="your-project-name:build:staging"

Using CSS to insert text

Also check out the attr() function of the CSS content attribute. It outputs a given attribute of the element as a text node. Use it like so:

<div class="Owner Joe" />

div:before {
  content: attr(class);
}

Or even with the new HTML5 custom data attributes:

<div data-employeename="Owner Joe" />

div:before {
  content: attr(data-employeename);
}

WPF checkbox binding

This works for me (essential code only included, fill more for your needs):

In XAML a user control is defined:

<UserControl x:Class="Mockup.TestTab" ......>
    <!-- a checkbox somewhere within the control -->
    <!-- IsChecked is bound to Property C1 of the DataContext -->
    <CheckBox Content="CheckBox 1" IsChecked="{Binding C1, Mode=TwoWay}" />
</UserControl>

In code behind for UserControl

public partial class TestTab : UserControl
{
    public TestTab()
    {
        InitializeComponent();  // the standard bit

    // then we set the DataContex of TestTab Control to a MyViewModel object
    // this MyViewModel object becomes the DataContext for all controls
         // within TestTab ... including our CheckBox
         DataContext = new MyViewModel(....);
    }

}

Somewhere in solution class MyViewModel is defined

public class MyViewModel : INotifyPropertyChanged 
{
    public event PropertyChangedEventHandler PropertyChanged;
    private bool m_c1 = true;

    public bool C1 {
        get { return m_c1; }
        set {
            if (m_c1 != value) {
                m_c1 = value;
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs("C1"));
            }
        }
    }
}

Creating Scheduled Tasks

This works for me https://www.nuget.org/packages/ASquare.WindowsTaskScheduler/

It is nicely designed Fluent API.

//This will create Daily trigger to run every 10 minutes for a duration of 18 hours
SchedulerResponse response = WindowTaskScheduler
    .Configure()
    .CreateTask("TaskName", "C:\\Test.bat")
    .RunDaily()
    .RunEveryXMinutes(10)
    .RunDurationFor(new TimeSpan(18, 0, 0))
    .SetStartDate(new DateTime(2015, 8, 8))
    .SetStartTime(new TimeSpan(8, 0, 0))
    .Execute();

jquery select option click handler

you can attach a focus event to select

$('#select_id').focus(function() {
    console.log('Handler for .focus() called.');
});

How to get folder directory from HTML input type "file" or any other way?

You're most likely looking at using a flash/silverlight/activeX control. The <input type="file" /> control doesn't handle that.

If you don't mind the user selecting a file as a means to getting its directory, you may be able to bind to that control's change event then strip the filename portion and save the path somewhere--but that's about as good as it gets.

Keep in mind that webpages are designed to interact with servers. Nothing about providing a local directory to a remote server is "typical" (a server can't access it so why ask for it?); however files are a means to selectively passing information.

Spark RDD to DataFrame python

Try if that works

sc = spark.sparkContext

# Infer the schema, and register the DataFrame as a table.
schemaPeople = spark.createDataFrame(RddName)
schemaPeople.createOrReplaceTempView("RddName")

How to set cornerRadius for only top-left and top-right corner of a UIView?

Pay attention to the fact that if you have layout constraints attached to it, you must refresh this as follows in your UIView subclass:

override func layoutSubviews() {
    super.layoutSubviews()
    roundCorners(corners: [.topLeft, .topRight], radius: 3.0)
}

If you don't do that it won't show up.


And to round corners, use the extension:

extension UIView {
   func roundCorners(corners: UIRectCorner, radius: CGFloat) {
        let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
        let mask = CAShapeLayer()
        mask.path = path.cgPath
        layer.mask = mask
    }
}


Additional view controller case: Whether you can't or wouldn't want to subclass a view, you can still round a view. Do it from its view controller by overriding the viewWillLayoutSubviews() function, as follows:

class MyVC: UIViewController {
    /// The view to round the top-left and top-right hand corners
    let theView: UIView = {
        let v = UIView(frame: CGRect(x: 10, y: 10, width: 200, height: 200))
        v.backgroundColor = .red
        return v
    }()

    override func loadView() {
        super.loadView()
        view.addSubview(theView)
    }

    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()

        // Call the roundCorners() func right there.
        theView.roundCorners(corners: [.topLeft, .topRight], radius: 30)
    }
}

Compiling and Running Java Code in Sublime Text 2

By following the steps below, you will have 2 Build Systems in sublime - "JavaC" and "JavaC_Input".

"JavaC" would let you run code that doesn't require user input and display the results in sublime's terminal simulator, which is convenient and nice-looking. "JavaC_Input" lets you run code that requires user input in a separate terminal window, it's able to accept user input. You can also run non-input-requiring code in this build system, so if you don't mind the pop-up, you can just stick with this build system and don't switch. You switch between build systems from Tools -> Build System. And you compile&run code using ctrl+b.

Here are the steps to achieve this:

(note: Make sure you already have the basic setup of the java system: install JDK and set up correct CLASSPATH and PATH, I won't elaborate on this)

"JavaC" build system setup

1, Make a bat file with the following code, and save it under C:\Program Files\Java\jdk*\bin\ to keep everything together. Name the file "javacexec.bat".

@ECHO OFF
cd %~dp1
javac %~nx1
java %~n1

2, Then edit C:\Users\your_user_name\AppData\Roaming\Sublime Text 2\Packages\Java\JavaC.sublime-build (if there isn't any, create one), the contents will be

{
   "cmd": ["javacexec.bat", "$file"],
   "file_regex": "^(...*?):([0-9]*):?([0-9]*)",
   "selector": "source.java"
}

"JavaC_Input" build system setup

1, Install Cygwin [http://www.cygwin.com/]

2, Go to C:\Users\your_user_name\AppData\Roaming\Sublime Text 2\Packages\Java\, then create a file called "JavaC_Input.sublime-build" with the following content

{
"cmd": ["javacexec_input.bat", "$file"],
"file_regex": "^(...*?):([0-9]*):?([0-9]*)",
"selector": "source.java"
}

3, Make a bat file with the following code, and save it under C:\Program Files\Java\jdk*\bin\ to keep everything together. Name the file "javacexec_input.bat".

@echo off
javac  -Xlint:unchecked %~n1.java 
start cmd /k java -ea %~n1

How to capitalize the first letter in a String in Ruby

My version:

class String
    def upcase_first
        return self if empty?
        dup.tap {|s| s[0] = s[0].upcase }
    end
    def upcase_first!
        replace upcase_first
    end
end

['NASA title', 'MHz', 'sputnik'].map &:upcase_first  #=> ["NASA title", "MHz", "Sputnik"]

Check also:
https://www.rubydoc.info/gems/activesupport/5.0.0.1/String%3Aupcase_first
https://www.rubydoc.info/gems/activesupport/5.0.0.1/ActiveSupport/Inflector#upcase_first-instance_method

Regex match digits, comma and semicolon?

You almost have it, you just left out 0 and forgot the quantifier.

word.matches("^[0-9,;]+$")

Is there a null-coalescing (Elvis) operator or safe navigation operator in javascript?

2020 Update

JavaScript now has equivalents for both the Elvis Operator and the Safe Navigation Operator.


Safe Property Access

The optional chaining operator (?.) is currently a stage 4 ECMAScript proposal. You can use it today with Babel.

// `undefined` if either `a` or `b` are `null`/`undefined`. `a.b.c` otherwise.
const myVariable = a?.b?.c;

The logical AND operator (&&) is the "old", more-verbose way to handle this scenario.

const myVariable = a && a.b && a.b.c;

Providing a Default

The nullish coalescing operator (??) is currently a stage 4 ECMAScript proposal. You can use it today with Babel. It allows you to set a default value if the left-hand side of the operator is a nullary value (null/undefined).

const myVariable = a?.b?.c ?? 'Some other value';

// Evaluates to 'Some other value'
const myVariable2 = null ?? 'Some other value';

// Evaluates to ''
const myVariable3 = '' ?? 'Some other value';

The logical OR operator (||) is an alternative solution with slightly different behavior. It allows you to set a default value if the left-hand side of the operator is falsy. Note that the result of myVariable3 below differs from myVariable3 above.

const myVariable = a?.b?.c || 'Some other value';

// Evaluates to 'Some other value'
const myVariable2 = null || 'Some other value';

// Evaluates to 'Some other value'
const myVariable3 = '' || 'Some other value';

How to check that a JCheckBox is checked?

Use the isSelected method.

You can also use an ItemListener so you'll be notified when it's checked or unchecked.

Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)

I had to disable explicit_defaults_for_timestamp from my.cnf.

How to query nested objects?

Since there is a lot of confusion about queries MongoDB collection with sub-documents, I thought its worth to explain the above answers with examples:

First I have inserted only two objects in the collection namely: message as:

> db.messages.find().pretty()
{
    "_id" : ObjectId("5cce8e417d2e7b3fe9c93c32"),
    "headers" : {
        "From" : "[email protected]"
    }
}
{
    "_id" : ObjectId("5cce8eb97d2e7b3fe9c93c33"),
    "headers" : {
        "From" : "[email protected]",
        "To" : "[email protected]"
    }
}
>

So what is the result of query: db.messages.find({headers: {From: "[email protected]"} }).count()

It should be one because these queries for documents where headers equal to the object {From: "[email protected]"}, only i.e. contains no other fields or we should specify the entire sub-document as the value of a field.

So as per the answer from @Edmondo1984

Equality matches within sub-documents select documents if the subdocument matches exactly the specified sub-document, including the field order.

From the above statements, what is the below query result should be?

> db.messages.find({headers: {To: "[email protected]", From: "[email protected]"}  }).count()
0

And what if we will change the order of From and To i.e same as sub-documents of second documents?

> db.messages.find({headers: {From: "[email protected]", To: "[email protected]"}  }).count()
1

so, it matches exactly the specified sub-document, including the field order.

For using dot operator, I think it is very clear for every one. Let's see the result of below query:

> db.messages.find( { 'headers.From': "[email protected]" }  ).count()
2

I hope these explanations with the above example will make someone more clarity on find query with sub-documents.

Max size of URL parameters in _GET

Ok, it seems that some versions of PHP have a limitation of length of GET params:

Please note that PHP setups with the suhosin patch installed will have a default limit of 512 characters for get parameters. Although bad practice, most browsers (including IE) supports URLs up to around 2000 characters, while Apache has a default of 8000.

To add support for long parameters with suhosin, add suhosin.get.max_value_length = <limit> in php.ini

Source: http://www.php.net/manual/en/reserved.variables.get.php#101469

Best practice for localization and globalization of strings and labels

When you’re faced with a problem to solve (and frankly, who isn’t these days?), the basic strategy usually taken by we computer people is called “divide and conquer.” It goes like this:

  • Conceptualize the specific problem as a set of smaller sub-problems.
  • Solve each smaller problem.
  • Combine the results into a solution of the specific problem.

But “divide and conquer” is not the only possible strategy. We can also take a more generalist approach:

  • Conceptualize the specific problem as a special case of a more general problem.
  • Somehow solve the general problem.
  • Adapt the solution of the general problem to the specific problem.

- Eric Lippert

I believe many solutions already exist for this problem in server-side languages such as ASP.Net/C#.

I've outlined some of the major aspects of the problem

  • Issue: We need to load data only for the desired language

    Solution: For this purpose we save data to a separate files for each language

ex. res.de.js, res.fr.js, res.en.js, res.js(for default language)

  • Issue: Resource files for each page should be separated so we only get the data we need

    Solution: We can use some tools that already exist like https://github.com/rgrove/lazyload

  • Issue: We need a key/value pair structure to save our data

    Solution: I suggest a javascript object instead of string/string air. We can benefit from the intellisense from an IDE

  • Issue: General members should be stored in a public file and all pages should access them

    Solution: For this purpose I make a folder in the root of web application called Global_Resources and a folder to store global file for each sub folders we named it 'Local_Resources'

  • Issue: Each subsystems/subfolders/modules member should override the Global_Resources members on their scope

    Solution: I considered a file for each

Application Structure

root/
    Global_Resources/
        default.js
        default.fr.js
    UserManagementSystem/
        Local_Resources/
            default.js
            default.fr.js
            createUser.js
        Login.htm
        CreateUser.htm

The corresponding code for the files:

Global_Resources/default.js

var res = {
    Create : "Create",
    Update : "Save Changes",
    Delete : "Delete"
};

Global_Resources/default.fr.js

var res = {
    Create : "créer",
    Update : "Enregistrer les modifications",
    Delete : "effacer"
};

The resource file for the desired language should be loaded on the page selected from Global_Resource - This should be the first file that is loaded on all the pages.

UserManagementSystem/Local_Resources/default.js

res.Name = "Name";
res.UserName = "UserName";
res.Password = "Password";

UserManagementSystem/Local_Resources/default.fr.js

res.Name = "nom";
res.UserName = "Nom d'utilisateur";
res.Password = "Mot de passe";

UserManagementSystem/Local_Resources/createUser.js

// Override res.Create on Global_Resources/default.js
res.Create = "Create User"; 

UserManagementSystem/Local_Resources/createUser.fr.js

// Override Global_Resources/default.fr.js
res.Create = "Créer un utilisateur";

manager.js file (this file should be load last)

res.lang = "fr";

var globalResourcePath = "Global_Resources";
var resourceFiles = [];

var currentFile = globalResourcePath + "\\default" + res.lang + ".js" ;

if(!IsFileExist(currentFile))
    currentFile = globalResourcePath + "\\default.js" ;
if(!IsFileExist(currentFile)) throw new Exception("File Not Found");

resourceFiles.push(currentFile);

// Push parent folder on folder into folder
foreach(var folder in parent folder of current page)
{
    currentFile = folder + "\\Local_Resource\\default." + res.lang + ".js";

    if(!IsExist(currentFile))
        currentFile = folder + "\\Local_Resource\\default.js";
    if(!IsExist(currentFile)) throw new Exception("File Not Found");

    resourceFiles.push(currentFile);
}

for(int i = 0; i < resourceFiles.length; i++) { Load.js(resourceFiles[i]); }

// Get current page name
var pageNameWithoutExtension = "SomePage";

currentFile = currentPageFolderPath + pageNameWithoutExtension + res.lang + ".js" ;

if(!IsExist(currentFile))
    currentFile = currentPageFolderPath + pageNameWithoutExtension + ".js" ;
if(!IsExist(currentFile)) throw new Exception("File Not Found");

Hope it helps :)

What is the opposite of :hover (on mouse leave)?

Just add a transition to the element you are messing with. Be aware that there could be some effects when the page loads. Like if you made a border radius change, you will see it when the dom loads.

_x000D_
_x000D_
.element {_x000D_
  width: 100px;_x000D_
  transition: all ease-in-out 0.5s;_x000D_
}_x000D_
 _x000D_
 .element:hover {_x000D_
  width: 200px;_x000D_
    transition: all ease-in-out 0.5s;_x000D_
}
_x000D_
_x000D_
_x000D_

How to Code Double Quotes via HTML Codes

There is no difference, in browsers that you can find in the wild these days (that is, excluding things like Netscape 1 that you might find in a museum). There is no reason to suspect that any of them would be deprecated ever, especially since they are all valid in XML, in HTML 4.01, and in HTML5 CR.

There is no reason to use any of them, as opposite to using the Ascii quotation mark (") directly, except in the very special case where you have an attribute value enclosed in such marks and you would like to use the mark inside the value (e.g., title="Hello &quot;world&quot;"), and even then, there are almost always better options (like title='Hello "word"' or title="Hello “word”".

If you want to use “smart” quotation marks instead, then it’s a different question, and none of the constructs has anything to do with them. Some people expect notations like &quot; to produce “smart” quotes, but it is easy to see that they don’t; the notations unambiguously denote the Ascii quote ("), as used in computer languages.

PHP Curl And Cookies

Here you can find some useful info about cURL & cookies http://docstore.mik.ua/orelly/webprog/pcook/ch11_04.htm .

You can also use this well done method https://github.com/alixaxel/phunction/blob/master/phunction/Net.php#L89 like a function:

function CURL($url, $data = null, $method = 'GET', $cookie = null, $options = null, $retries = 3)
{
    $result = false;

    if ((extension_loaded('curl') === true) && (is_resource($curl = curl_init()) === true))
    {
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_FAILONERROR, true);
        curl_setopt($curl, CURLOPT_AUTOREFERER, true);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

        if (preg_match('~^(?:DELETE|GET|HEAD|OPTIONS|POST|PUT)$~i', $method) > 0)
        {
            if (preg_match('~^(?:HEAD|OPTIONS)$~i', $method) > 0)
            {
                curl_setopt_array($curl, array(CURLOPT_HEADER => true, CURLOPT_NOBODY => true));
            }

            else if (preg_match('~^(?:POST|PUT)$~i', $method) > 0)
            {
                if (is_array($data) === true)
                {
                    foreach (preg_grep('~^@~', $data) as $key => $value)
                    {
                        $data[$key] = sprintf('@%s', rtrim(str_replace('\\', '/', realpath(ltrim($value, '@'))), '/') . (is_dir(ltrim($value, '@')) ? '/' : ''));
                    }

                    if (count($data) != count($data, COUNT_RECURSIVE))
                    {
                        $data = http_build_query($data, '', '&');
                    }
                }

                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            }

            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, strtoupper($method));

            if (isset($cookie) === true)
            {
                curl_setopt_array($curl, array_fill_keys(array(CURLOPT_COOKIEJAR, CURLOPT_COOKIEFILE), strval($cookie)));
            }

            if ((intval(ini_get('safe_mode')) == 0) && (ini_set('open_basedir', null) !== false))
            {
                curl_setopt_array($curl, array(CURLOPT_MAXREDIRS => 5, CURLOPT_FOLLOWLOCATION => true));
            }

            if (is_array($options) === true)
            {
                curl_setopt_array($curl, $options);
            }

            for ($i = 1; $i <= $retries; ++$i)
            {
                $result = curl_exec($curl);

                if (($i == $retries) || ($result !== false))
                {
                    break;
                }

                usleep(pow(2, $i - 2) * 1000000);
            }
        }

        curl_close($curl);
    }

    return $result;
}

And pass this as $cookie parameter:

$cookie_jar = tempnam('/tmp','cookie');

Angular - POST uploaded file

your http service file:

import { Injectable } from "@angular/core";
import { ActivatedRoute, Router } from '@angular/router';
import { Http, Headers, Response, Request, RequestMethod, URLSearchParams, RequestOptions } from "@angular/http";
import {Observable} from 'rxjs/Rx';
import { Constants } from './constants';
declare var $: any;

@Injectable()
export class HttpClient {
  requestUrl: string;
  responseData: any;
  handleError: any;

  constructor(private router: Router, 
  private http: Http, 
  private constants: Constants, 
  ) {
    this.http = http;
  }

  postWithFile (url: string, postData: any, files: File[]) {

    let headers = new Headers();
    let formData:FormData = new FormData();
    formData.append('files', files[0], files[0].name);
    // For multiple files
    // for (let i = 0; i < files.length; i++) {
    //     formData.append(`files[]`, files[i], files[i].name);
    // }

    if(postData !=="" && postData !== undefined && postData !==null){
      for (var property in postData) {
          if (postData.hasOwnProperty(property)) {
              formData.append(property, postData[property]);
          }
      }
    }
    var returnReponse = new Promise((resolve, reject) => {
      this.http.post(this.constants.root_dir + url, formData, {
        headers: headers
      }).subscribe(
          res => {
            this.responseData = res.json();
            resolve(this.responseData);
          },
          error => {
            this.router.navigate(['/login']);
            reject(error);
          }
      );
    });
    return returnReponse;
  }
}

call your function (Component file):

onChange(event) {
    let file = event.srcElement.files;
    let postData = {field1:"field1", field2:"field2"}; // Put your form data variable. This is only example.
    this._service.postWithFile(this.baseUrl + "add-update",postData,file).then(result => {
        console.log(result);
    });
}

your html code:

<input type="file" class="form-control" name="documents" (change)="onChange($event)" [(ngModel)]="stock.documents" #documents="ngModel">

SELECT * FROM X WHERE id IN (...) with Dapper ORM

It is not necessary to add () in the WHERE clause as we do in a regular SQL. Because Dapper does that automatically for us. Here is the syntax:-

const string SQL = "SELECT IntegerColumn, StringColumn FROM SomeTable WHERE IntegerColumn IN @listOfIntegers";

var conditions = new { listOfIntegers };
    
var results = connection.Query(SQL, conditions);

How to select a node of treeview programmatically in c#?

Call the TreeView.OnAfterSelect() protected method after you programatically select the node.

Specify sudo password for Ansible

Very simple, and only add in the variable file:

Example:

$ vim group_vars/all

And add these:

Ansible_connection: ssh
Ansible_ssh_user: rafael
Ansible_ssh_pass: password123
Ansible_become_pass: password123

jquery .html() vs .append()

You can get the second method to achieve the same effect by:

var mySecondDiv = $('<div></div>');
$(mySecondDiv).find('div').attr('id', 'mySecondDiv');
$('#myDiv').append(mySecondDiv);

Luca mentioned that html() just inserts hte HTML which results in faster performance.

In some occassions though, you would opt for the second option, consider:

// Clumsy string concat, error prone
$('#myDiv').html("<div style='width:'" + myWidth + "'px'>Lorem ipsum</div>");

// Isn't this a lot cleaner? (though longer)
var newDiv = $('<div></div>');
$(newDiv).find('div').css('width', myWidth);
$('#myDiv').append(newDiv);

How to Save Console.WriteLine Output to Text File

do you want to write code for that or just use command-line feature 'command redirection' as follows:

app.exe >> output.txt

as demonstrated here: http://discomoose.org/2006/05/01/output-redirection-to-a-file-from-the-windows-command-line/ (Archived at archive.org)

EDIT: link dead, here's another example: http://pcsupport.about.com/od/commandlinereference/a/redirect-command-output-to-file.htm

accessing a docker container from another container

You will have to access db through the ip of host machine, or if you want to access it via localhost:1521, then run webserver like -

docker run --net=host --name oracle-wls wls-image:latest

See here

XmlWriter to Write to a String Instead of to a File

Guys don't forget to call xmlWriter.Close() and xmlWriter.Dispose() or else your string won't finish creating. It will just be an empty string

Free tool to Create/Edit PNG Images?

Inkscape is a vector drawing program that exports PNG images. So, you end up editing SVG documents and exporting them to PNGs. Inkscape is good if you're starting from scratch, but wouldn't be ideal if you just want to edit existing PNGs.

Note--Inkscape is open source and available for free on multiple platforms.

How to format background color using twitter bootstrap?

Bootstrap default "contextual backgrounds" helper classes to change the background color:

.bg-primary
.bg-default
.bg-info
.bg-warning
.bg-danger

If you need set custom background color then, you can write your own custom classes in style.css( a custom css file) example below

.bg-pink
{
  background-color: #CE6F9E;
}

How can I decrypt a password hash in PHP?

I need to decrypt a password. The password is crypted with password_hash function.

$password = 'examplepassword';
$crypted = password_hash($password, PASSWORD_DEFAULT);

Its not clear to me if you need password_verify, or you are trying to gain unauthorized access to the application or database. Other have talked about password_verify, so here's how you could gain unauthorized access. Its what bad guys often do when they try to gain access to a system.

First, create a list of plain text passwords. A plain text list can be found in a number of places due to the massive data breaches from companies like Adobe. Sort the list and then take the top 10,000 or 100,000 or so.

Second, create a list of digested passwords. Simply encrypt or hash the password. Based on your code above, it does not look like a salt is being used (or its a fixed salt). This makes the attack very easy.

Third, for each digested password in the list, perform a select in an attempt to find a user who is using the password:

$sql_script = 'select * from USERS where password="'.$digested_password.'"'

Fourth, profit.

So, rather than picking a user and trying to reverse their password, the bad guy picks a common password and tries to find a user who is using it. Odds are on the bad guy's side...

Because the bad guy does these things, it would behove you to not let users choose common passwords. In this case, take a look at ProCheck, EnFilter or Hyppocrates (et al). They are filtering libraries that reject bad passwords. ProCheck achieves very high compression, and can digest multi-million word password lists into a 30KB data file.

Possible to change where Android Virtual Devices are saved?

In my case, what I concerned about is the C: drive disk space. So what I did is copy the ".avd" folder(not file) to other drive, and leave the ".ini" file there but change it to point to the moved

How to check if a class inherits another class without instantiating it?

To check for assignability, you can use the Type.IsAssignableFrom method:

typeof(SomeType).IsAssignableFrom(typeof(Derived))

This will work as you expect for type-equality, inheritance-relationships and interface-implementations but not when you are looking for 'assignability' across explicit / implicit conversion operators.

To check for strict inheritance, you can use Type.IsSubclassOf:

typeof(Derived).IsSubclassOf(typeof(SomeType))

Removing nan values from an array

@jmetz's answer is probably the one most people need; however it yields a one-dimensional array, e.g. making it unusable to remove entire rows or columns in matrices.

To do so, one should reduce the logical array to one dimension, then index the target array. For instance, the following will remove rows which have at least one NaN value:

x = x[~numpy.isnan(x).any(axis=1)]

See more detail here.

PyTorch: How to get the shape of a Tensor as a list of int

Previous answers got you list of torch.Size Here is how to get list of ints

listofints = [int(x) for x in tensor.shape]

How do I get Month and Date of JavaScript in 2 digit format?

The best way to do this is to create your own simple formatter (as below):

getDate() returns the day of the month (from 1-31)
getMonth() returns the month (from 0-11) < zero-based, 0=January, 11=December
getFullYear() returns the year (four digits) < don't use getYear()

function formatDateToString(date){
   // 01, 02, 03, ... 29, 30, 31
   var dd = (date.getDate() < 10 ? '0' : '') + date.getDate();
   // 01, 02, 03, ... 10, 11, 12
   var MM = ((date.getMonth() + 1) < 10 ? '0' : '') + (date.getMonth() + 1);
   // 1970, 1971, ... 2015, 2016, ...
   var yyyy = date.getFullYear();

   // create the format you want
   return (dd + "-" + MM + "-" + yyyy);
}

How do I install Eclipse with C++ in Ubuntu 12.10 (Quantal Quetzal)?

http://www.eclipse.org/cdt/ ^Give that a try

I have not used the CDT for eclipse but I do use Eclipse Java for Ubuntu 12.04 and it works wonders.

Java synchronized method lock on object, or method?

From oracle documentation link

Making methods synchronized has two effects:

First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.

Second, when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all threads

Have a look at this documentation page to understand intrinsic locks and lock behavior.

This will answer your question: On same object x , you can't call x.addA() and x.addB() at same time when one of the synchronized methods execution is in progress.

Pandas read_csv low_memory and dtype options

I was facing a similar issue when processing a huge csv file (6 million rows). I had three issues:

  1. the file contained strange characters (fixed using encoding)
  2. the datatype was not specified (fixed using dtype property)
  3. Using the above I still faced an issue which was related with the file_format that could not be defined based on the filename (fixed using try .. except..)
    df = pd.read_csv(csv_file,sep=';', encoding = 'ISO-8859-1',
                     names=['permission','owner_name','group_name','size','ctime','mtime','atime','filename','full_filename'],
                     dtype={'permission':str,'owner_name':str,'group_name':str,'size':str,'ctime':object,'mtime':object,'atime':object,'filename':str,'full_filename':str,'first_date':object,'last_date':object})
    
    try:
        df['file_format'] = [Path(f).suffix[1:] for f in df.filename.tolist()]
    except:
        df['file_format'] = ''

Convert negative data into positive data in SQL Server

The best solution is: from positive to negative or from negative to positive

For negative:

SELECT ABS(a) * -1 AS AbsoluteA, ABS(b) * -1 AS AbsoluteB
FROM YourTable

For positive:

SELECT ABS(a) AS AbsoluteA, ABS(b)  AS AbsoluteB
FROM YourTable

Find package name for Android apps to use Intent to launch Market app from web

You can search the app online in the Google Play Store. When found, check the url, for example, https://play.google.com/store/apps/details?id=lutey.FTPServer&hl=en

The id parameter corresponds to the package name of the application. In the case of the url in the example, the package name is lutey.FTPServer.

Difference between add(), replace(), and addToBackStack()

Here is a picture that shows the difference between add() and replace()

enter image description here

So add() method keeps on adding fragments on top of the previous fragment in FragmentContainer.

While replace() methods clears all the previous Fragment from Containers and then add it in FragmentContainer.

What is addToBackStack

addtoBackStack method can be used with add() and replace methods. It serves a different purpose in Fragment API.

What is the purpose?

Fragment API unlike Activity API does not come with Back Button navigation by default. If you want to go back to the previous Fragment then the we use addToBackStack() method in Fragment. Let's understand both

Case 1:

getSupportFragmentManager()
            .beginTransaction()
            .add(R.id.fragmentContainer, fragment, "TAG")
            .addToBackStack("TAG")
            .commit();

enter image description here

Case 2:

getSupportFragmentManager()
            .beginTransaction()
            .add(R.id.fragmentContainer, fragment, "TAG")
            .commit();

enter image description here

How do I fix the npm UNMET PEER DEPENDENCY warning?

npm no longer installs peer dependencies so you need to install them manually, just do an npm install on the needed deps, and then try to install the main one again.


Reply to comment:

it's right in that message, it says which deps you're missing

UNMET PEER DEPENDENCY angular-animate@^1.5.0 +-- 
UNMET PEER DEPENDENCY angular-aria@^1.5.0 +-- [email protected] +
UNMET PEER DEPENDENCY angular-messages@^1.5.0 `-- [email protected]` 

So you need to npm install angular angular-animate angular-aria angular-material angular-messages mdi

Exception: Unexpected end of ZLIB input stream

You have to call close() on the GZIPOutputStream before you attempt to read it. The final bytes of the file will only be written when the file is actually closed. (This is irrespective of any explicit buffering in the output stack. The stream only knows to compress and write the last bytes when you tell it to close. A flush() probably won't help ... though calling finish() instead of close() should work. Look at the javadocs.)

Here's the correct code (in Java);

package test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GZipTest {

    public static void main(String[] args) throws
                FileNotFoundException, IOException {
        String name = "/tmp/test";
        GZIPOutputStream gz = new GZIPOutputStream(new FileOutputStream(name));
        gz.write(10);
        gz.close();       // Remove this to reproduce the reported bug
        System.out.println(new GZIPInputStream(new FileInputStream(name)).read());
    }
}

(I've not implemented resource management or exception handling / reporting properly as they are not relevant to the purpose of this code. Don't treat this as an example of "good code".)

What is the Swift equivalent to Objective-C's "@synchronized"?

You can sandwich statements between objc_sync_enter(obj: AnyObject?) and objc_sync_exit(obj: AnyObject?). The @synchronized keyword is using those methods under the covers. i.e.

objc_sync_enter(self)
... synchronized code ...
objc_sync_exit(self)

One-liner if statements, how to convert this if-else-statement

All you'd need in your case is:

return expression;

The reason why is that the expression itself evaluates to a boolean value of true or false, so it's redundant to have an if block (or even a ?: operator).

adding line break

C# 6+

In addition, since c#6 you can also use a static using statement for System.Environment.

So instead of Environment.NewLine, you can just write NewLine.

Concise and much easier on the eye, particularly when there are multiple instances ...

using static System.Environment;
   
FirmNames = "";
foreach (var item in FirmNameList)
{
    if (FirmNames != "")
    {
       FirmNames += ", " + NewLine;
    }
    FirmNames += item;
}

MySQL JDBC Driver 5.1.33 - Time Zone Issue

The above program will generate that time zone error.

After your database name you have to add this: ?useTimezone=true&serverTimezone=UTC. Once you have done your code will work fine.

Best of luck :)

How to enter newline character in Oracle?

begin   
   dbms_output.put_line( 'hello' ||chr(13) || chr(10) || 'world' );
end;

How can I remove the gloss on a select element in Safari on Mac?

If you inspect the User Agent StyleSheet of Chome, you'll find this

outline: -webkit-focus-ring-color auto 5px;

in short its outline property - make it None

that should remove the glow

ALTER table - adding AUTOINCREMENT in MySQL

ALTER TABLE tblcatalog
    CHANGE COLUMN id id INT(11) NOT NULL AUTO_INCREMENT FIRST;

How to check if a file exists in Ansible?

The stat module will do this as well as obtain a lot of other information for files. From the example documentation:

- stat: path=/path/to/something
  register: p

- debug: msg="Path exists and is a directory"
  when: p.stat.isdir is defined and p.stat.isdir

How to retrieve the first word of the output of a command in bash?

As perl incorporates awk's functionality this can be solved with perl too:

echo " word1 word2" | perl -lane 'print $F[0]'

Flask Value error view function did not return a response

The following does not return a response:

You must return anything like return afunction() or return 'a string'.

This can solve the issue

How do I change data-type of pandas data frame to string with a defined format?

I'm putting this in a new answer because no linebreaks / codeblocks in comments. I assume you want those nans to turn into a blank string? I couldn't find a nice way to do this, only do the ugly method:

s = pd.Series([1001.,1002.,None])
a = s.loc[s.isnull()].fillna('')
b = s.loc[s.notnull()].astype(int).astype(str)
result = pd.concat([a,b])

Select the first 10 rows - Laravel Eloquent

First you can use a Paginator. This is as simple as:

$allUsers = User::paginate(15);

$someUsers = User::where('votes', '>', 100)->paginate(15);

The variables will contain an instance of Paginator class. all of your data will be stored under data key.

Or you can do something like:

Old versions Laravel.

Model::all()->take(10)->get();

Newer version Laravel.

Model::all()->take(10);

For more reading consider these links:

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

The way it's often done is as follows:

  • allocate an array of some initial (fairly small) size;
  • read into this array, keeping track of how many elements you've read;
  • once the array is full, reallocate it, doubling the size and preserving (i.e. copying) the contents;
  • repeat until done.

I find that this pattern comes up pretty frequently.

What's interesting about this method is that it allows one to insert N elements into an empty array one-by-one in amortized O(N) time without knowing N in advance.

Graphviz: How to go from .dot to a graph?

You can also output your file in xdot format, then render it in a browser using canviz, a JavaScript library.

Canviz on code.google.com:

To see an example, there is a "Canviz Demo" link on the page above as of November 2, 2014.

How to find substring inside a string (or how to grep a variable)?

If you're using bash you can just say

if grep -q "$SOURCE" <<< "$LIST" ; then
    ...
fi

PyLint "Unable to import" error - how to set PYTHONPATH?

1) sys.path is a list.

2) The problem is sometimes the sys.path is not your virtualenv.path and you want to use pylint in your virtualenv

3) So like said, use init-hook (pay attention in ' and " the parse of pylint is strict)

[Master]
init-hook='sys.path = ["/path/myapps/bin/", "/path/to/myapps/lib/python3.3/site-packages/", ... many paths here])'

or

[Master]
init-hook='sys.path = list(); sys.path.append("/path/to/foo")'

.. and

pylint --rcfile /path/to/pylintrc /path/to/module.py

Bash Templating: How to build configuration files from templates with Bash?

Here's a modified perl script based on a few of the other answers:

perl -pe 's/([^\\]|^)\$\{([a-zA-Z_][a-zA-Z_0-9]*)\}/$1.$ENV{$2}/eg' -i template

Features (based on my needs, but should be easy to modify):

  • Skips escaped parameter expansions (e.g. \${VAR}).
  • Supports parameter expansions of the form ${VAR}, but not $VAR.
  • Replaces ${VAR} with a blank string if there is no VAR envar.
  • Only supports a-z, A-Z, 0-9 and underscore characters in the name (excluding digits in the first position).

iPhone: How to get current milliseconds?

[[NSDate date] timeIntervalSince1970];

It returns the number of seconds since epoch as a double. I'm almost sure you can access the milliseconds from the fractional part.

Display List in a View MVC

You are passing wrong mode to you view. Your view is looking for @model IEnumerable<Standings.Models.Teams> and you are passing var model = tm.Name.ToList(); name list. You have to pass list of Teams.

You have to pass following model

var model = new List<Teams>();

model.Add(new Teams { Name =  new List<string>(){"Sky","ABC"}});
model.Add(new Teams { Name =  new List<string>(){"John","XYZ"} });
return View(model);

css - position div to bottom of containing div

Add position: relative to .outside. (https://developer.mozilla.org/en-US/docs/CSS/position)

Elements that are positioned relatively are still considered to be in the normal flow of elements in the document. In contrast, an element that is positioned absolutely is taken out of the flow and thus takes up no space when placing other elements. The absolutely positioned element is positioned relative to nearest positioned ancestor. If a positioned ancestor doesn't exist, the initial container is used.

The "initial container" would be <body>, but adding the above makes .outside positioned.

Configure WAMP server to send email

Install Fake Sendmail (download sendmail.zip). Then configure C:\wamp\sendmail\sendmail.ini:

smtp_server=smtp.gmail.com
smtp_port=465
[email protected]
auth_password=your_password

The above will work against a Gmail account. And then configure php.ini:

sendmail_path = "C:\wamp\sendmail\sendmail.exe -t"

Now, restart Apache, and that is basically all you need to do.

python numpy ValueError: operands could not be broadcast together with shapes

Convert the arrays to matrices, and then perform the multiplication.

X = np.matrix(X)

y = np.matrix(y)

X*y

Get DataKey values in GridView RowCommand

On the Button:

CommandArgument='<%# Eval("myKey")%>'

On the Server Event

e.CommandArgument

How to truncate milliseconds off of a .NET DateTime

Here is an extension method based on a previous answer that will let you truncate to any resolution...

Usage:

DateTime myDateSansMilliseconds = myDate.Truncate(TimeSpan.TicksPerSecond);
DateTime myDateSansSeconds = myDate.Truncate(TimeSpan.TicksPerMinute)

Class:

public static class DateTimeUtils
{
    /// <summary>
    /// <para>Truncates a DateTime to a specified resolution.</para>
    /// <para>A convenient source for resolution is TimeSpan.TicksPerXXXX constants.</para>
    /// </summary>
    /// <param name="date">The DateTime object to truncate</param>
    /// <param name="resolution">e.g. to round to nearest second, TimeSpan.TicksPerSecond</param>
    /// <returns>Truncated DateTime</returns>
    public static DateTime Truncate(this DateTime date, long resolution)
    {
        return new DateTime(date.Ticks - (date.Ticks % resolution), date.Kind);
    }
}

Controller 'ngModel', required by directive '...', can't be found

I faced the same error, in my case I miss-spelled ng-model directive something like "ng-moel"

Wrong one: ng-moel="user.name" Right one: ng-model="user.name"

enter image description here

Call JavaScript function from C#

You can call javascript functions from c# using Jering.Javascript.NodeJS, an open-source library by my organization:

string javascriptModule = @"
module.exports = (callback, x, y) => {  // Module must export a function that takes a callback as its first parameter
    var result = x + y; // Your javascript logic
    callback(null /* If an error occurred, provide an error object or message */, result); // Call the callback when you're done.
}";

// Invoke javascript
int result = await StaticNodeJSService.InvokeFromStringAsync<int>(javascriptModule, args: new object[] { 3, 5 });

// result == 8
Assert.Equal(8, result);

The library supports invoking directly from .js files as well. Say you have file C:/My/Directory/exampleModule.js containing:

module.exports = (callback, message) => callback(null, message);

You can invoke the exported function:

string result = await StaticNodeJSService.InvokeFromFileAsync<string>("C:/My/Directory/exampleModule.js", args: new[] { "test" });

// result == "test"
Assert.Equal("test", result);

How to select an element by classname using jqLite?

Essentially, and as-noted by @kevin-b:

// find('#id')
angular.element(document.querySelector('#id'))

//find('.classname'), assumes you already have the starting elem to search from
angular.element(elem.querySelector('.classname'))

Note: If you're looking to do this from your controllers you may want to have a look at the "Using Controllers Correctly" section in the developers guide and refactor your presentation logic into appropriate directives (such as <a2b ...>).

How to sum the values of one column of a dataframe in spark/scala

Using spark sql query..just incase if it helps anyone!

import org.apache.spark.sql.SparkSession 
import org.apache.spark.SparkConf 
import org.apache.spark.sql.functions._ 
import org.apache.spark.SparkContext 
import java.util.stream.Collectors

val conf = new SparkConf().setMaster("local[2]").setAppName("test")
val spark = SparkSession.builder.config(conf).getOrCreate()
val df = spark.sparkContext.parallelize(Seq(1, 2, 3, 4, 5, 6, 7)).toDF()

df.createOrReplaceTempView("steps")
val sum = spark.sql("select  sum(steps) as stepsSum from steps").map(row => row.getAs("stepsSum").asInstanceOf[Long]).collect()(0)
println("steps sum = " + sum) //prints 28

Getting Database connection in pure JPA setup

Since the code suggested by @Pascal is deprecated as mentioned by @Jacob, I found this another way that works for me.

import org.hibernate.classic.Session;
import org.hibernate.connection.ConnectionProvider;
import org.hibernate.engine.SessionFactoryImplementor;

Session session = (Session) em.getDelegate();
SessionFactoryImplementor sfi = (SessionFactoryImplementor) session.getSessionFactory();
ConnectionProvider cp = sfi.getConnectionProvider();
Connection connection = cp.getConnection();

How to increase heap size of an android application?

Increasing Java Heap unfairly eats deficit mobile resurces. Sometimes it is sufficient to just wait for garbage collector and then resume your operations after heap space is reduced. Use this static method then.

How is TeamViewer so fast?

would take time to route through TeamViewer's servers (TeamViewer bypasses corporate Symmetric NATs by simply proxying traffic through their servers)

You'll find that TeamViewer rarely needs to relay traffic through their own servers. TeamViewer penetrates NAT and networks complicated by NAT using NAT traversal (I think it is UDP hole-punching, like Google's libjingle).

They do use their own servers to middle-man in order to do the handshake and connection set-up, but most of the time the relationship between client and server will be P2P (best case, when the hand-shake is successful). If NAT traversal fails, then TeamViewer will indeed relay traffic through its own servers.

I've only ever seen it do this when a client has been behind double-NAT, though.

javascript regex for password containing at least 8 characters, 1 number, 1 upper and 1 lowercase

Your regular expression should look like:

/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/

Here is an explanation:

/^
  (?=.*\d)          // should contain at least one digit
  (?=.*[a-z])       // should contain at least one lower case
  (?=.*[A-Z])       // should contain at least one upper case
  [a-zA-Z0-9]{8,}   // should contain at least 8 from the mentioned characters
$/

Parsing query strings on Android

Just for reference, this is what I've ended up with (based on URLEncodedUtils, and returning a Map).

Features:

  • it accepts the query string part of the url (you can use request.getQueryString())
  • an empty query string will produce an empty Map
  • a parameter without a value (?test) will be mapped to an empty List<String>

Code:

public static Map<String, List<String>> getParameterMapOfLists(String queryString) {
    Map<String, List<String>> mapOfLists = new HashMap<String, List<String>>();
    if (queryString == null || queryString.length() == 0) {
        return mapOfLists;
    }
    List<NameValuePair> list = URLEncodedUtils.parse(URI.create("http://localhost/?" + queryString), "UTF-8");
    for (NameValuePair pair : list) {
        List<String> values = mapOfLists.get(pair.getName());
        if (values == null) {
            values = new ArrayList<String>();
            mapOfLists.put(pair.getName(), values);
        }
        if (pair.getValue() != null) {
            values.add(pair.getValue());
        }
    }

    return mapOfLists;
}

A compatibility helper (values are stored in a String array just as in ServletRequest.getParameterMap()):

public static Map<String, String[]> getParameterMap(String queryString) {
    Map<String, List<String>> mapOfLists = getParameterMapOfLists(queryString);

    Map<String, String[]> mapOfArrays = new HashMap<String, String[]>();
    for (String key : mapOfLists.keySet()) {
        mapOfArrays.put(key, mapOfLists.get(key).toArray(new String[] {}));
    }

    return mapOfArrays;
}

c# Image resizing to different size while preserving aspect ratio

// This allows us to resize the image. It prevents skewed images and 
// also vertically long images caused by trying to maintain the aspect 
// ratio on images who's height is larger than their width

public void ResizeImage(string OriginalFile, string NewFile, int NewWidth, int MaxHeight, bool OnlyResizeIfWider)

{
    System.Drawing.Image FullsizeImage = System.Drawing.Image.FromFile(OriginalFile);

    // Prevent using images internal thumbnail
    FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
    FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);

    if (OnlyResizeIfWider)
    {
        if (FullsizeImage.Width <= NewWidth)
        {
            NewWidth = FullsizeImage.Width;
        }
    }

    int NewHeight = FullsizeImage.Height * NewWidth / FullsizeImage.Width;
    if (NewHeight > MaxHeight)
    {
        // Resize with height instead
        NewWidth = FullsizeImage.Width * MaxHeight / FullsizeImage.Height;
        NewHeight = MaxHeight;
    }

    System.Drawing.Image NewImage = FullsizeImage.GetThumbnailImage(NewWidth, NewHeight, null, IntPtr.Zero);

    // Clear handle to original file so that we can overwrite it if necessary
    FullsizeImage.Dispose();

    // Save resized picture
    NewImage.Save(NewFile);
}

Python3 integer division

Try this:

a = 1
b = 2
int_div  = a // b

Get ID of element that called a function

I'm surprised that nobody has mentioned the use of this in the event handler. It works automatically in modern browsers and can be made to work in other browsers. If you use addEventListener or attachEvent to install your event handler, then you can make the value of this automatically be assigned to the object the created the event.

Further, the user of programmatically installed event handlers allows you to separate javascript code from HTML which is often considered a good thing.

Here's how you would do that in your code in plain javascript:

Remove the onmouseover="zoom()" from your HTML and install the event handler in your javascript like this:

// simplified utility function to register an event handler cross-browser
function setEventHandler(obj, name, fn) {
    if (typeof obj == "string") {
        obj = document.getElementById(obj);
    }
    if (obj.addEventListener) {
        return(obj.addEventListener(name, fn));
    } else if (obj.attachEvent) {
        return(obj.attachEvent("on" + name, function() {return(fn.call(obj));}));
    }
}

function zoom() {
    // you can use "this" here to refer to the object that caused the event
    // this here will refer to the calling object (which in this case is the <map>)
    console.log(this.id);
    document.getElementById("preview").src="http://photos.smugmug.com/photos/344290962_h6JjS-Ti.jpg";
}

// register your event handler
setEventHandler("nose", "mouseover", zoom);

How to run Spring Boot web application in Eclipse itself?

Just run the main method which is in the class SampleWebJspApplication. Spring Boot will take care of all the rest (starting the embedded tomcat which will host your sample application).

How to tell a Mockito mock object to return something different the next time it is called?

For all who search to return something and then for another call throw exception:

when(mockFoo.someMethod())
        .thenReturn(obj1)
        .thenReturn(obj2)
        .thenThrow(new RuntimeException("Fail"));

or

when(mockFoo.someMethod())
        .thenReturn(obj1, obj2)
        .thenThrow(new RuntimeException("Fail"));

text flowing out of div

use overflow:auto it will give a scroller to your text within the div :).

Set focus on textbox in WPF

In XAML:

<StackPanel FocusManager.FocusedElement="{Binding ElementName=Box}">
   <TextBox Name="Box" />
</StackPanel>

Javascript: getFullyear() is not a function

You are overwriting the start date object with the value of a DOM Element with an id of Startdate.

This should work:

var start = new Date(document.getElementById('Stardate').value);

var y = start.getFullYear();

How to Update Date and Time of Raspberry Pi With out Internet

You will need to configure your Win7 PC as a Time Server, and then configure the RasPi to connect to it for NTP services.

Configure Win7 as authoritative time server. Configure RasPi time server lookup.

How to swap two variables in JavaScript

We are able to swap var like this :

var val1 =  117,
    val2 = 327;

val2 = val1-val2; 
console.log(val2);
val1 = val1-val2;
console.log(val1);
val2 = val1+val2;
console.log(val2);

Getting the name / key of a JToken with JSON.net

JToken is the base class for JObject, JArray, JProperty, JValue, etc. You can use the Children<T>() method to get a filtered list of a JToken's children that are of a certain type, for example JObject. Each JObject has a collection of JProperty objects, which can be accessed via the Properties() method. For each JProperty, you can get its Name. (Of course you can also get the Value if desired, which is another JToken.)

Putting it all together we have:

JArray array = JArray.Parse(json);

foreach (JObject content in array.Children<JObject>())
{
    foreach (JProperty prop in content.Properties())
    {
        Console.WriteLine(prop.Name);
    }
}

Output:

MobileSiteContent
PageContent

How to check if a user is logged in (how to properly use user.is_authenticated)?

Django 1.10+

Use an attribute, not a method:

if request.user.is_authenticated: # <-  no parentheses any more!
    # do something if the user is authenticated

The use of the method of the same name is deprecated in Django 2.0, and is no longer mentioned in the Django documentation.


Note that for Django 1.10 and 1.11, the value of the property is a CallableBool and not a boolean, which can cause some strange bugs. For example, I had a view that returned JSON

return HttpResponse(json.dumps({
    "is_authenticated": request.user.is_authenticated()
}), content_type='application/json') 

that after updated to the property request.user.is_authenticated was throwing the exception TypeError: Object of type 'CallableBool' is not JSON serializable. The solution was to use JsonResponse, which could handle the CallableBool object properly when serializing:

return JsonResponse({
    "is_authenticated": request.user.is_authenticated
})

Creating an index on a table variable

If Table variable has large data, then instead of table variable(@table) create temp table (#table).table variable doesn't allow to create index after insert.

 CREATE TABLE #Table(C1 int,       
  C2 NVarchar(100) , C3 varchar(100)
  UNIQUE CLUSTERED (c1) 
 ); 
  1. Create table with unique clustered index

  2. Insert data into Temp "#Table" table

  3. Create non clustered indexes.

     CREATE NONCLUSTERED INDEX IX1  ON #Table (C2,C3);
    

How can I control the width of a label tag?

label {
  width:200px;
  display: inline-block;
}

OR 

label {
  width:200px;
  display: inline-flex;
}

OR 

label {
  width:200px;
  display: inline-table;
}

Short circuit Array.forEach like calling break

Yes it is possible to continue and to exit of a forEach loop.

To continue, you can use return, the loop will continue but the current function will end.

To exit of the loop, you can set the third parameter to 0 length, set to empty array. The loop will not continue, the current function do, so you can use "return" to finish, like exit in a normal for loop...

This:

[1,2,3,4,5,6,7,8,9,10].forEach((a,b,c) => {
    console.log(a);
    if(b == 2){return;}
    if(b == 4){c.length = 0;return;}
    console.log("next...",b);
});

will print this:

1
next... 0
2
next... 1
3
4
next... 3
5

Is the ternary operator faster than an "if" condition in Java

Try to use switch case statement but normally it's not the performance bottleneck.

Are SSL certificates bound to the servers ip address?

The SSL certificates are going to be bound to hostname rather than IP if they are setup in the standard way. Hence why it works at one site rather than the other.

Even if the servers share the same hostname they may well have two different certificates and hence WebSphere will have a certificate trust issue as it won't be able to recognise the certificate on the second server as it is different to the first.

2D Euclidean vector rotations

you should remove the vars from the function:

x = x * cs - y * sn; // now x is something different than original vector x
y = x * sn + y * cs;

create new coordinates becomes, to avoid calculation of x before it reaches the second line:

px = x * cs - y * sn; 
py = x * sn + y * cs;

How do I change the background color with JavaScript?

Add this script element to your body element, changing the color as desired:

_x000D_
_x000D_
<body>_x000D_
  <p>Hello, World!</p>_x000D_
  <script type="text/javascript">_x000D_
     document.body.style.backgroundColor = "#ff0000";  // red_x000D_
  </script>_x000D_
</body>
_x000D_
_x000D_
_x000D_

How to free memory in Java?

No one seems to have mentioned explicitly setting object references to null, which is a legitimate technique to "freeing" memory you may want to consider.

For example, say you'd declared a List<String> at the beginning of a method which grew in size to be very large, but was only required until half-way through the method. You could at this point set the List reference to null to allow the garbage collector to potentially reclaim this object before the method completes (and the reference falls out of scope anyway).

Note that I rarely use this technique in reality but it's worth considering when dealing with very large data structures.

How to get the file extension in PHP?

No need to use string functions. You can use something that's actually designed for what you want: pathinfo():

$path = $_FILES['image']['name'];
$ext = pathinfo($path, PATHINFO_EXTENSION);

Add two numbers and display result in textbox with Javascript

_x000D_
_x000D_
var app = angular.module('myApp', []);_x000D_
app.controller('myCtrl', function($scope) {_x000D_
_x000D_
    $scope.minus = function() {     _x000D_
_x000D_
     var a = Number($scope.a || 0);_x000D_
            var b = Number($scope.b || 0);_x000D_
            $scope.sum1 = a-b;_x000D_
    // $scope.sum = $scope.sum1+1; _x000D_
    alert($scope.sum1);_x000D_
    }_x000D_
_x000D_
   $scope.add = function() {     _x000D_
_x000D_
     var c = Number($scope.c || 0);_x000D_
            var d = Number($scope.d || 0);_x000D_
            $scope.sum2 = c+d;_x000D_
    alert($scope.sum2);_x000D_
    }_x000D_
});
_x000D_
<head>_x000D_
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>_x000D_
   </head>_x000D_
<body>_x000D_
_x000D_
<div ng-app="myApp" ng-controller="myCtrl">_x000D_
     <h3>Using Double Negation</h3>_x000D_
_x000D_
    <p>First Number:_x000D_
        <input type="text" ng-model="a" />_x000D_
    </p>_x000D_
    <p>Second Number:_x000D_
        <input type="text" ng-model="b" />_x000D_
    </p>_x000D_
    <button id="minus" ng-click="minus()">Minus</button>_x000D_
    <!-- <p>Sum: {{ a - b }}</p>  -->_x000D_
 <p>Sum: {{ sum1 }}</p>_x000D_
_x000D_
    <p>First Number:_x000D_
        <input type="number" ng-model="c" />_x000D_
    </p>_x000D_
    <p>Second Number:_x000D_
        <input type="number" ng-model="d" />_x000D_
    </p>_x000D_
 <button id="minus" ng-click="add()">Add</button>_x000D_
    <p>Sum: {{ sum2 }}</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Join vs. sub-query

In most cases JOINs are faster than sub-queries and it is very rare for a sub-query to be faster.

In JOINs RDBMS can create an execution plan that is better for your query and can predict what data should be loaded to be processed and save time, unlike the sub-query where it will run all the queries and load all their data to do the processing.

The good thing in sub-queries is that they are more readable than JOINs: that's why most new SQL people prefer them; it is the easy way; but when it comes to performance, JOINS are better in most cases even though they are not hard to read too.

Exception: There is already an open DataReader associated with this Connection which must be closed first

The issue you are running into is that you are starting up a second MySqlCommand while still reading back data with the DataReader. The MySQL connector only allows one concurrent query. You need to read the data into some structure, then close the reader, then process the data. Unfortunately you can't process the data as it is read if your processing involves further SQL queries.

File changed listener in Java

Spring Integration provides a nice mechanism for watching Directories and files: http://static.springsource.org/spring-integration/reference/htmlsingle/#files. Pretty sure it's cross platform (I've used it on mac, linux, and windows).

How can I generate an HTML report for Junit results?

Junit xml format is used outside of Java/Maven/Ant word. Jenkins with http://wiki.jenkins-ci.org/display/JENKINS/xUnit+Plugin is a solution.

For the one shot solution I have found this tool that does the job: https://www.npmjs.com/package/junit-viewer

junit-viewer --results=surefire-reports --save=file_location.html

--results= is directory with xml files (test reports)

What is the point of WORKDIR on Dockerfile?

According to the documentation:

The WORKDIR instruction sets the working directory for any RUN, CMD, ENTRYPOINT, COPY and ADD instructions that follow it in the Dockerfile. If the WORKDIR doesn’t exist, it will be created even if it’s not used in any subsequent Dockerfile instruction.

Also, in the Docker best practices it recommends you to use it:

... you should use WORKDIR instead of proliferating instructions like RUN cd … && do-something, which are hard to read, troubleshoot, and maintain.

I would suggest to keep it.

I think you can refactor your Dockerfile to something like:

FROM node:latest
WORKDIR /usr/src/app
COPY package.json .
RUN npm install
COPY . ./
EXPOSE 3000
CMD [ “npm”, “start” ] 

How to disable Django's CSRF validation?

To disable CSRF for class based views the following worked for me.
Using django 1.10 and python 3.5.2

from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator

@method_decorator(csrf_exempt, name='dispatch')
class TestView(View):
    def post(self, request, *args, **kwargs):
        return HttpResponse('Hello world')

How many significant digits do floats and doubles have in java?

float: 32 bits (4 bytes) where 23 bits are used for the mantissa (about 7 decimal digits). 8 bits are used for the exponent, so a float can “move” the decimal point to the right or to the left using those 8 bits. Doing so avoids storing lots of zeros in the mantissa as in 0.0000003 (3 × 10-7) or 3000000 (3 × 107). There is 1 bit used as the sign bit.

double: 64 bits (8 bytes) where 52 bits are used for the mantissa (about 16 decimal digits). 11 bits are used for the exponent and 1 bit is the sign bit.

Since we are using binary (only 0 and 1), one bit in the mantissa is implicitly 1 (both float and double use this trick) when the number is non-zero.

Also, since everything is in binary (mantissa and exponents) the conversions to decimal numbers are usually not exact. Numbers like 0.5, 0.25, 0.75, 0.125 are stored exactly, but 0.1 is not. As others have said, if you need to store cents precisely, do not use float or double, use int, long, BigInteger or BigDecimal.

Sources:

http://en.wikipedia.org/wiki/Floating_point#IEEE_754:_floating_point_in_modern_computers

http://en.wikipedia.org/wiki/Binary64

http://en.wikipedia.org/wiki/Binary32

Temporarily change current working directory in bash to run a command

bash has a builtin

pushd SOME_PATH
run_stuff
...
...
popd 

How do you write to a folder on an SD card in Android?

Add Permission to Android Manifest

Add this WRITE_EXTERNAL_STORAGE permission to your applications manifest.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="your.company.package"
    android:versionCode="1"
    android:versionName="0.1">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <!-- ... -->
    </application>
    <uses-sdk android:minSdkVersion="7" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</manifest> 

Check availability of external storage

You should always check for availability first. A snippet from the official android documentation on external storage.

boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();

if (Environment.MEDIA_MOUNTED.equals(state)) {
    // We can read and write the media
    mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
    // We can only read the media
    mExternalStorageAvailable = true;
    mExternalStorageWriteable = false;
} else {
    // Something else is wrong. It may be one of many other states, but all we need
    //  to know is we can neither read nor write
    mExternalStorageAvailable = mExternalStorageWriteable = false;
}

Use a Filewriter

At last but not least forget about the FileOutputStream and use a FileWriter instead. More information on that class form the FileWriter javadoc. You'll might want to add some more error handling here to inform the user.

// get external storage file reference
FileWriter writer = new FileWriter(getExternalStorageDirectory()); 
// Writes the content to the file
writer.write("This\n is\n an\n example\n"); 
writer.flush();
writer.close();

OpenCV TypeError: Expected cv::UMat for argument 'src' - What is this?

Some dtype are not supported by specific OpenCV functions. For example inputs of dtype np.uint32 create this error. Try to convert the input to a supported dtype (e.g. np.int32 or np.float32)

How to check if a .txt file is in ASCII or UTF-8 format in Windows environment?

Open it in a hex editor and make sure that the first three bytes are a UTF8 BOM (EF BB BF)

What is the yield keyword used for in C#?

A list or array implementation loads all of the items immediately whereas the yield implementation provides a deferred execution solution.

In practice, it is often desirable to perform the minimum amount of work as needed in order to reduce the resource consumption of an application.

For example, we may have an application that process millions of records from a database. The following benefits can be achieved when we use IEnumerable in a deferred execution pull-based model:

  • Scalability, reliability and predictability are likely to improve since the number of records does not significantly affect the application’s resource requirements.
  • Performance and responsiveness are likely to improve since processing can start immediately instead of waiting for the entire collection to be loaded first.
  • Recoverability and utilisation are likely to improve since the application can be stopped, started, interrupted or fail. Only the items in progress will be lost compared to pre-fetching all of the data where only using a portion of the results was actually used.
  • Continuous processing is possible in environments where constant workload streams are added.

Here is a comparison between build a collection first such as a list compared to using yield.

List Example

    public class ContactListStore : IStore<ContactModel>
    {
        public IEnumerable<ContactModel> GetEnumerator()
        {
            var contacts = new List<ContactModel>();
            Console.WriteLine("ContactListStore: Creating contact 1");
            contacts.Add(new ContactModel() { FirstName = "Bob", LastName = "Blue" });
            Console.WriteLine("ContactListStore: Creating contact 2");
            contacts.Add(new ContactModel() { FirstName = "Jim", LastName = "Green" });
            Console.WriteLine("ContactListStore: Creating contact 3");
            contacts.Add(new ContactModel() { FirstName = "Susan", LastName = "Orange" });
            return contacts;
        }
    }

    static void Main(string[] args)
    {
        var store = new ContactListStore();
        var contacts = store.GetEnumerator();

        Console.WriteLine("Ready to iterate through the collection.");
        Console.ReadLine();
    }

Console Output
ContactListStore: Creating contact 1
ContactListStore: Creating contact 2
ContactListStore: Creating contact 3
Ready to iterate through the collection.

Note: The entire collection was loaded into memory without even asking for a single item in the list

Yield Example

public class ContactYieldStore : IStore<ContactModel>
{
    public IEnumerable<ContactModel> GetEnumerator()
    {
        Console.WriteLine("ContactYieldStore: Creating contact 1");
        yield return new ContactModel() { FirstName = "Bob", LastName = "Blue" };
        Console.WriteLine("ContactYieldStore: Creating contact 2");
        yield return new ContactModel() { FirstName = "Jim", LastName = "Green" };
        Console.WriteLine("ContactYieldStore: Creating contact 3");
        yield return new ContactModel() { FirstName = "Susan", LastName = "Orange" };
    }
}

static void Main(string[] args)
{
    var store = new ContactYieldStore();
    var contacts = store.GetEnumerator();

    Console.WriteLine("Ready to iterate through the collection.");
    Console.ReadLine();
}

Console Output
Ready to iterate through the collection.

Note: The collection wasn't executed at all. This is due to the "deferred execution" nature of IEnumerable. Constructing an item will only occur when it is really required.

Let's call the collection again and obverse the behaviour when we fetch the first contact in the collection.

static void Main(string[] args)
{
    var store = new ContactYieldStore();
    var contacts = store.GetEnumerator();
    Console.WriteLine("Ready to iterate through the collection");
    Console.WriteLine("Hello {0}", contacts.First().FirstName);
    Console.ReadLine();
}

Console Output
Ready to iterate through the collection
ContactYieldStore: Creating contact 1
Hello Bob

Nice! Only the first contact was constructed when the client "pulled" the item out of the collection.

How do you create nested dict in Python?

UPDATE: For an arbitrary length of a nested dictionary, go to this answer.

Use the defaultdict function from the collections.

High performance: "if key not in dict" is very expensive when the data set is large.

Low maintenance: make the code more readable and can be easily extended.

from collections import defaultdict

target_dict = defaultdict(dict)
target_dict[key1][key2] = val

SQL SELECT multi-columns INTO multi-variable

SELECT @variable1 = col1, @variable2 = col2
FROM table1

What's the difference between TRUNCATE and DELETE in SQL

DELETE

The DELETE command is used to remove rows from a table. A WHERE clause can be used to only remove some rows. If no WHERE condition is specified, all rows will be removed. After performing a DELETE operation you need to COMMIT or ROLLBACK the transaction to make the change permanent or to undo it. Note that this operation will cause all DELETE triggers on the table to fire.

TRUNCATE

TRUNCATE removes all rows from a table. The operation cannot be rolled back and no triggers will be fired. As such, TRUCATE is faster and doesn't use as much undo space as a DELETE.

DROP

The DROP command removes a table from the database. All the tables' rows, indexes and privileges will also be removed. No DML triggers will be fired. The operation cannot be rolled back.


DROP and TRUNCATE are DDL commands, whereas DELETE is a DML command. Therefore DELETE operations can be rolled back (undone), while DROP and TRUNCATE operations cannot be rolled back.

From: http://www.orafaq.com/faq/difference_between_truncate_delete_and_drop_commands

Git commit date

If you like to have the timestamp without the timezone but local timezone do

git log -1 --format=%cd --date=local

Which gives this depending on your location

Mon Sep 28 12:07:37 2015

JQuery Number Formatting

http://jquerypriceformat.com/#examples

https://github.com/flaviosilveira/Jquery-Price-Format

html input runing for live chance.

<input type="text" name="v7"  class="priceformat"/>
<input type="text" name="v8"  class="priceformat"/>


$('.priceformat').each(function( index ) {
    $(this).priceFormat({ prefix: '',  thousandsSeparator: '' });
});

//5000.00

//5.000,00

//5,000.00

sort csv by column

import operator
sortedlist = sorted(reader, key=operator.itemgetter(3), reverse=True)

or use lambda

sortedlist = sorted(reader, key=lambda row: row[3], reverse=True)

Plot mean and standard deviation

plt.errorbar can be used to plot x, y, error data (as opposed to the usual plt.plot)

import matplotlib.pyplot as plt
import numpy as np

x = np.array([1, 2, 3, 4, 5])
y = np.power(x, 2) # Effectively y = x**2
e = np.array([1.5, 2.6, 3.7, 4.6, 5.5])

plt.errorbar(x, y, e, linestyle='None', marker='^')

plt.show()

plt.errorbar accepts the same arguments as plt.plot with additional yerr and xerr which default to None (i.e. if you leave them blank it will act as plt.plot).

Example plot

Convert JS date time to MySQL datetime

A simple solution is send a timestamp to MySQL and let it do the conversion. Javascript uses timestamps in milliseconds whereas MySQL expects them to be in seconds - so a division by 1000 is needed:

// Current date / time as a timestamp:
let jsTimestamp = Date.now();

// **OR** a specific date / time as a timestamp:
jsTimestamp = new Date("2020-11-17 16:34:59").getTime();

// Adding 30 minutes (to answer the second part of the question):
jsTimestamp += 30 * 1000;

// Example query converting Javascript timestamp into a MySQL date
let sql = 'SELECT FROM_UNIXTIME(' + jsTimestamp + ' / 1000) AS mysql_date_time';

What does "commercial use" exactly mean?

If the usage of something is part of the process of you making money, then it's generally considered a commercial use. If the purpose of the site is to, through some means or another, directly or indirectly, make you money, then it's probably commercial use.

If, on the other hand, something is merely incidental (not part of the process of production/working, but instead simply tacked on to the side), there are potential grounds for it not to be considered commercial use.

VBA EXCEL Multiple Nested FOR Loops that Set two variable for expression

I can't get to your google docs file at the moment but there are some issues with your code that I will try to address while answering

Sub stituterangersNEW()
Dim t As Range
Dim x As Range
Dim dify As Boolean
Dim difx As Boolean
Dim time2 As Date
Dim time1 As Date

    'You said time1 doesn't change, so I left it in a singe cell.
    'If that is not correct, you will have to play with this some more.
    time1 = Range("A6").Value

    'Looping through each of our output cells.
    For Each t In Range("B7:E9") 'Change these to match your real ranges.

        'Looping through each departure date/time.
        '(Only one row in your example. This can be adjusted if needed.)
        For Each x In Range("B2:E2") 'Change these to match your real ranges.
            'Check to see if our dep time corresponds to
            'the matching column in our output
            If t.Column = x.Column Then
                'If it does, then check to see what our time value is
                If x > 0 Then
                    time2 = x.Value
                    'Apply the change to the output cell.
                    t.Value = time1 - time2
                    'Exit out of this loop and move to the next output cell.
                    Exit For
                End If
            End If
            'If the columns don't match, or the x value is not a time
            'then we'll move to the next dep time (x)
        Next x
    Next t

End Sub

EDIT

I changed you worksheet to play with (see above for the new Sub). This probably does not suite your needs directly, but hopefully it will demonstrate the conept behind what I think you want to do. Please keep in mind that this code does not follow all the coding best preactices I would recommend (e.g. validating the time is actually a TIME and not some random other data type).

     A                      B                   C                   D                  E
1    LOAD_NUMBER            1                   2                   3                  4
2    DEPARTURE_TIME_DATE    11/12/2011 19:30    11/12/2011 19:30    11/12/2011 19:30    11/12/2011 20:00                
4    Dry_Refrig 7585.1  0   10099.8 16700
6    1/4/2012 19:30

Using the sub I got this output:

    A           B             C             D             E
7   Friday      1272:00:00    1272:00:00    1272:00:00    1271:30:00
8   Saturday    1272:00:00    1272:00:00    1272:00:00    1271:30:00
9   Thursday    1272:00:00    1272:00:00    1272:00:00    1271:30:00

Smooth scroll without the use of jQuery

You can use a for loop with window.scrollTo and setTimeout to scroll smoothly with plain Javascript. To scroll to an element with my scrollToSmoothly function: scrollToSmoothly(elem.offsetTop) (assuming elem is a DOM element). You can use this to scroll smoothly to any y-position in the document.

function scrollToSmoothly(pos, time){
/*Time is only applicable for scrolling upwards*/
/*Code written by hev1*/
/*pos is the y-position to scroll to (in pixels)*/
     if(isNaN(pos)){
      throw "Position must be a number";
     }
     if(pos<0){
     throw "Position can not be negative";
     }
    var currentPos = window.scrollY||window.screenTop;
    if(currentPos<pos){
    var t = 10;
       for(let i = currentPos; i <= pos; i+=10){
       t+=10;
        setTimeout(function(){
        window.scrollTo(0, i);
        }, t/2);
      }
    } else {
    time = time || 2;
       var i = currentPos;
       var x;
      x = setInterval(function(){
         window.scrollTo(0, i);
         i -= 10;
         if(i<=pos){
          clearInterval(x);
         }
     }, time);
      }
}

Demo:

_x000D_
_x000D_
<button onClick="scrollToDiv()">Scroll To Element</button>_x000D_
<div style="margin: 1000px 0px; text-align: center;">Div element<p/>_x000D_
<button onClick="scrollToSmoothly(Number(0))">Scroll back to top</button>_x000D_
</div>_x000D_
<script>_x000D_
function scrollToSmoothly(pos, time){_x000D_
/*Time is only applicable for scrolling upwards*/_x000D_
/*Code written by hev1*/_x000D_
/*pos is the y-position to scroll to (in pixels)*/_x000D_
     if(isNaN(pos)){_x000D_
      throw "Position must be a number";_x000D_
     }_x000D_
     if(pos<0){_x000D_
     throw "Position can not be negative";_x000D_
     }_x000D_
    var currentPos = window.scrollY||window.screenTop;_x000D_
    if(currentPos<pos){_x000D_
    var t = 10;_x000D_
       for(let i = currentPos; i <= pos; i+=10){_x000D_
       t+=10;_x000D_
        setTimeout(function(){_x000D_
       window.scrollTo(0, i);_x000D_
        }, t/2);_x000D_
      }_x000D_
    } else {_x000D_
    time = time || 2;_x000D_
       var i = currentPos;_x000D_
       var x;_x000D_
      x = setInterval(function(){_x000D_
         window.scrollTo(0, i);_x000D_
         i -= 10;_x000D_
         if(i<=pos){_x000D_
          clearInterval(x);_x000D_
         }_x000D_
     }, time);_x000D_
      }_x000D_
}_x000D_
function scrollToDiv(){_x000D_
  var elem = document.querySelector("div");_x000D_
  scrollToSmoothly(elem.offsetTop);_x000D_
}_x000D_
</script>
_x000D_
_x000D_
_x000D_

How to print a two dimensional array?

If you know the maxValue (can be easily done if another iteration of the elements is not an issue) of the matrix, I find the following code more effective and generic.

    int numDigits = (int) Math.log10(maxValue) + 1;
    if (numDigits <= 1) {
        numDigits = 2;
    }
    StringBuffer buf = new StringBuffer();
    for (int i = 0; i < matrix.length; i++) {
        int[] row = matrix[i];
        for (int j = 0; j < row.length; j++) {
            int block = row[j];
            buf.append(String.format("%" + numDigits + "d", block));
            if (j >= row.length - 1) {
                buf.append("\n");
            }
        }
    }
    return buf.toString();

From inside of a Docker container, how do I connect to the localhost of the machine?

For Windows Machine :-

Run the below command to Expose docker port randomly during build time

$docker run -d --name MyWebServer -P mediawiki

enter image description here

enter image description here

In the above container list you can see the port assigned as 32768. Try accessing

localhost:32768 

You can see the mediawiki page

Call a python function from jinja2

I think jinja deliberately makes it difficult to run 'arbitrary' python within a template. It tries to enforce the opinion that less logic in templates is a good thing.

You can manipulate the global namespace within an Environment instance to add references to your functions. It must be done before you load any templates. For example:

from jinja2 import Environment, FileSystemLoader

def clever_function(a, b):
    return u''.join([b, a])

env = Environment(loader=FileSystemLoader('/path/to/templates'))
env.globals['clever_function'] = clever_function

How to use Greek symbols in ggplot2?

Here is a link to an excellent wiki that explains how to put greek symbols in ggplot2. In summary, here is what you do to obtain greek symbols

  1. Text Labels: Use parse = T inside geom_text or annotate.
  2. Axis Labels: Use expression(alpha) to get greek alpha.
  3. Facet Labels: Use labeller = label_parsed inside facet.
  4. Legend Labels: Use bquote(alpha == .(value)) in legend label.

You can see detailed usage of these options in the link

EDIT. The objective of using greek symbols along the tick marks can be achieved as follows

require(ggplot2);
data(tips);
p0 = qplot(sex, data = tips, geom = 'bar');
p1 = p0 + scale_x_discrete(labels = c('Female' = expression(alpha),
                                      'Male'   = expression(beta)));
print(p1);

For complete documentation on the various symbols that are available when doing this and how to use them, see ?plotmath.

How to force a component's re-rendering in Angular 2?

tx, found the workaround I needed:

  constructor(private zone:NgZone) {
    // enable to for time travel
    this.appStore.subscribe((state) => {
        this.zone.run(() => {
            console.log('enabled time travel');
        });
    });

running zone.run will force the component to re-render

INNER JOIN vs LEFT JOIN performance in SQL Server

There is one important scenario that can lead to an outer join being faster than an inner join that has not been discussed yet.

When using an outer join, the optimizer is always free to drop the outer joined table from the execution plan if the join columns are the PK of the outer table, and none of the outer table columns are referenced outside of the outer join itself. For example SELECT A.* FROM A LEFT OUTER JOIN B ON A.KEY=B.KEY and B.KEY is the PK for B. Both Oracle (I believe I was using release 10) and Sql Server (I used 2008 R2) prune table B from the execution plan.

The same is not necessarily true for an inner join: SELECT A.* FROM A INNER JOIN B ON A.KEY=B.KEY may or may not require B in the execution plan depending on what constraints exist.

If A.KEY is a nullable foreign key referencing B.KEY, then the optimizer cannot drop B from the plan because it must confirm that a B row exists for every A row.

If A.KEY is a mandatory foreign key referencing B.KEY, then the optimizer is free to drop B from the plan because the constraints guarantee the existence of the row. But just because the optimizer can drop the table from the plan, doesn't mean it will. SQL Server 2008 R2 does NOT drop B from the plan. Oracle 10 DOES drop B from the plan. It is easy to see how the outer join will out-perform the inner join on SQL Server in this case.

This is a trivial example, and not practical for a stand-alone query. Why join to a table if you don't need to?

But this could be a very important design consideration when designing views. Frequently a "do-everything" view is built that joins everything a user might need related to a central table. (Especially if there are naive users doing ad-hoc queries that do not understand the relational model) The view may include all the relevent columns from many tables. But the end users might only access columns from a subset of the tables within the view. If the tables are joined with outer joins, then the optimizer can (and does) drop the un-needed tables from the plan.

It is critical to make sure that the view using outer joins gives the correct results. As Aaronaught has said - you cannot blindly substitute OUTER JOIN for INNER JOIN and expect the same results. But there are times when it can be useful for performance reasons when using views.

One last note - I haven't tested the impact on performance in light of the above, but in theory it seems you should be able to safely replace an INNER JOIN with an OUTER JOIN if you also add the condition <FOREIGN_KEY> IS NOT NULL to the where clause.

Waiting for Target Device to Come Online

After trying almost all the solutions listed above, what finally worked for me was to create a new virtual device using a "Google APIs" image instead of a "Google Play" image.

Using Switch Statement to Handle Button Clicks

    XML CODE FOR TWO BUTTONS  
     <Button
            android:id="@+id/btn_save"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="SAVE"
            android:onClick="process"
            />
        <Button
            android:id="@+id/btn_show"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="SHOW"
            android:onClick="process"/> 

  Java Code
 <pre> public void process(View view) {
            switch (view.getId()){
                case R.id.btn_save:
                  //add your own code
                    break;
                case R.id.btn_show:
                   //add your own code
                    break;
            }</pre>

How do you create a daemon in Python?

80% of the time, when folks say "daemon", they only want a server. Since the question is perfectly unclear on this point, it's hard to say what the possible domain of answers could be. Since a server is adequate, start there. If an actual "daemon" is actually needed (this is rare), read up on nohup as a way to daemonize a server.

Until such time as an actual daemon is actually required, just write a simple server.

Also look at the WSGI reference implementation.

Also look at the Simple HTTP Server.

"Are there any additional things that need to be considered? " Yes. About a million things. What protocol? How many requests? How long to service each request? How frequently will they arrive? Will you use a dedicated process? Threads? Subprocesses? Writing a daemon is a big job.

Meaning of Choreographer messages in Logcat

In my case I have these messages when I show the sherlock action bar inderterminate progressbar. Since its not my library, I decided to hide the Choreographer outputs.

You can hide the Choreographer outputs onto the Logcat view, using this filter expression :

tag:^((?!Choreographer).*)$

I used a regex explained elsewhere : Regular expression to match a line that doesn't contain a word?

How to query values from xml nodes?

This works, been tested...

SELECT  n.c.value('OrganizationReportReferenceIdentifier[1]','varchar(128)') AS 'OrganizationReportReferenceNumber',  
        n.c.value('(OrganizationNumber)[1]','varchar(128)') AS 'OrganizationNumber'
FROM    Batches t
Cross   Apply RawXML.nodes('/GrobXmlFile/Grob/ReportHeader') n(c)  

Reading a date using DataReader

        /// <summary>
    /// Returns a new conContractorEntity instance filled with the DataReader's current record data
    /// </summary>
    protected virtual conContractorEntity GetContractorFromReader(IDataReader reader)
    {
        return new conContractorEntity()
        {
            ConId = reader["conId"].ToString().Length > 0 ? int.Parse(reader["conId"].ToString()) : 0,
            ConEmail = reader["conEmail"].ToString(),
            ConCopyAdr = reader["conCopyAdr"].ToString().Length > 0 ? bool.Parse(reader["conCopyAdr"].ToString()) : true,
            ConCreateTime = reader["conCreateTime"].ToString().Length > 0 ? DateTime.Parse(reader["conCreateTime"].ToString()) : DateTime.MinValue
        };
    }

OR

        /// <summary>
    /// Returns a new conContractorEntity instance filled with the DataReader's current record data
    /// </summary>
    protected virtual conContractorEntity GetContractorFromReader(IDataReader reader)
    {
        return new conContractorEntity()
        {
            ConId = GetValue<int>(reader["conId"]),
            ConEmail = reader["conEmail"].ToString(),
            ConCopyAdr = GetValue<bool>(reader["conCopyAdr"], true),
            ConCreateTime = GetValue<DateTime>(reader["conCreateTime"])
        };
    }

// Base methods
        protected T GetValue<T>(object obj)
    {
        if (typeof(DBNull) != obj.GetType())
        {
            return (T)Convert.ChangeType(obj, typeof(T));
        }
        return default(T);
    }

    protected T GetValue<T>(object obj, object defaultValue)
    {
        if (typeof(DBNull) != obj.GetType())
        {
            return (T)Convert.ChangeType(obj, typeof(T));
        }
        return (T)defaultValue;
    }

How to Convert Datetime to Date in dd/MM/yyyy format

Give a different alias

SELECT  Convert(varchar,A.InsertDate,103) as converted_Tran_Date from table as A
order by A.InsertDate