Programs & Examples On #Windows live id

How to print a query string with parameter values when using Hibernate

Change hibernate.cfg.xml to:

<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="use_sql_comments">true</property>

Include log4j and below entries in "log4j.properties":

log4j.logger.org.hibernate=INFO, hb
log4j.logger.org.hibernate.SQL=DEBUG
log4j.logger.org.hibernate.type=TRACE

log4j.appender.hb=org.apache.log4j.ConsoleAppender
log4j.appender.hb.layout=org.apache.log4j.PatternLayout

How can I trim beginning and ending double quotes from a string?

Matcher m = Pattern.compile("^\"(.*)\"$").matcher(value);
String strUnquoted = value;
if (m.find()) {
    strUnquoted = m.group(1);
}

How to hide element label by element id in CSS?

If you give the label an ID, like this:

<label for="foo" id="foo_label">

Then this would work:

#foo_label { display: none;}

Your other options aren't really cross-browser friendly, unless javascript is an option. The CSS3 selector, not as widely supported looks like this:

[for="foo"] { display: none;}

How can I write maven build to add resources to classpath?

If you place anything in src/main/resources directory, then by default it will end up in your final *.jar. If you are referencing it from some other project and it cannot be found on a classpath, then you did one of those two mistakes:

  1. *.jar is not correctly loaded (maybe typo in the path?)
  2. you are not addressing the resource correctly, for instance: /src/main/resources/conf/settings.properties is seen on classpath as classpath:conf/settings.properties

How to split (chunk) a Ruby array into parts of X elements?

Take a look at Enumerable#each_slice:

foo.each_slice(3).to_a
#=> [["1", "2", "3"], ["4", "5", "6"], ["7", "8", "9"], ["10"]]

how to create a cookie and add to http response from inside my service layer?

Following @Aravind's answer with more details

@RequestMapping("/myPath.htm")
public ModelAndView add(HttpServletRequest request, HttpServletResponse response) throws Exception{
    myServiceMethodSettingCookie(request, response);        //Do service call passing the response
    return new ModelAndView("CustomerAddView");
}

// service method
void myServiceMethodSettingCookie(HttpServletRequest request, HttpServletResponse response){
    final String cookieName = "my_cool_cookie";
    final String cookieValue = "my cool value here !";  // you could assign it some encoded value
    final Boolean useSecureCookie = false;
    final int expiryTime = 60 * 60 * 24;  // 24h in seconds
    final String cookiePath = "/";

    Cookie cookie = new Cookie(cookieName, cookieValue);

    cookie.setSecure(useSecureCookie);  // determines whether the cookie should only be sent using a secure protocol, such as HTTPS or SSL

    cookie.setMaxAge(expiryTime);  // A negative value means that the cookie is not stored persistently and will be deleted when the Web browser exits. A zero value causes the cookie to be deleted.

    cookie.setPath(cookiePath);  // The cookie is visible to all the pages in the directory you specify, and all the pages in that directory's subdirectories

    response.addCookie(cookie);
}

Related docs:

http://docs.oracle.com/javaee/7/api/javax/servlet/http/Cookie.html

http://docs.spring.io/spring-security/site/docs/3.0.x/reference/springsecurity.html

Android: how to make keyboard enter button say "Search" and handle its click?

In Kotlin

evLoginPassword.setOnEditorActionListener { _, actionId, _ ->
    if (actionId == EditorInfo.IME_ACTION_DONE) {
        doTheLoginWork()
    }
    true
}

Partial Xml Code

 <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
       <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"

            android:layout_marginBottom="8dp"
            android:layout_marginTop="8dp"
            android:paddingLeft="24dp"
            android:paddingRight="24dp">

            <EditText
                android:id="@+id/evLoginUserEmail"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/email"
                android:inputType="textEmailAddress"
                android:textColor="@color/black_54_percent" />
        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="8dp"
            android:layout_marginTop="8dp"
            android:paddingLeft="24dp"
            android:paddingRight="24dp">

            <EditText
                android:id="@+id/evLoginPassword"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/password"
                android:inputType="textPassword"
                android:imeOptions="actionDone"
                android:textColor="@color/black_54_percent" />
        </android.support.design.widget.TextInputLayout>
</LinearLayout>

Updating Python on Mac

I was having the same problem, but then after a bit of research I tried

brew install python3 && cp /usr/local/bin/python3 /usr/local/bin/python

in terminal

A warning message will pop-up saying that python 3.7.0. is already installed but it's not linked so type the command brew link python and hit enter and hope things work right for you

How to silence output in a Bash script?

Try with:

myprogram &>/dev/null

to get no output

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

Changing the space between each item in Bootstrap navbar

Just remember that modifying the padding or margins on any bootstrap grid elements is likely to create overflowing elements at some point at lower screen-widths.

If that happens just remember to use CSS media queries and only include the margins at screen-widths that can handle it.

In keeping with the mobile-first approach of the framework you are working within (bootstrap) it is better to add the padding at widths which can handle it, rather than excluding it at widths which can't.

@media (min-width: 992px){
    .navbar li {
        margin-left : 1em;
        margin-right : 1em;
    }
}

Creating a new empty branch for a new project

Make an empty new branch like this:

true | git mktree | xargs git commit-tree | xargs git branch proj-doc

If your proj-doc files are already in a commit under a single subdir you can make the new branch this way:

git commit-tree thatcommit:path/to/dir | xargs git branch proj-doc

which might be more convenient than git branch --orphan if that would leave you with a lot of git rm and git mving to do.

Try

git branch --set-upstream proj-doc origin/proj-doc

and see if that helps with your fetching-too-much problem. Also if you really only want to fetch a single branch it's safest to just specify it on the commandline.

Current date without time

If you need exact your example, you should add format to ToString()

    string test = DateTime.ParseExact(DateTime.Now.ToString("dd.MM.yyyy"), "dd.MM.yyyy", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd");

But it's better to use straight formatting:

    string test = DateTime.Now.ToString("yyyy-MM-dd")

How open PowerShell as administrator from the run window

The easiest way to open an admin Powershell window in Windows 10 (and Windows 8) is to add a "Windows Powershell (Admin)" option to the "Power User Menu". Once this is done, you can open an admin powershell window via Win+X,A or by right-clicking on the start button and selecting "Windows Powershell (Admin)":

[Windows 10/Windows 8 Power User menu with "Windows Powershell (Admin)

Here's where you replace the "Command Prompt" option with a "Windows Powershell" option:

[Taskbar and Start Menu Properties: "Replace Command Prompt With Windows Powershell"

Javascript require() function giving ReferenceError: require is not defined

By default require() is not a valid function in client side javascript. I recommend you look into require.js as this does extend the client side to provide you with that function.

How to convert a Scikit-learn dataset to a Pandas dataset?

import pandas as pd
from sklearn.datasets import load_iris
iris = load_iris()
X = iris['data']
y = iris['target']
iris_df = pd.DataFrame(X, columns = iris['feature_names'])
iris_df.head()

"Unable to get the VLookup property of the WorksheetFunction Class" error

I was having the same problem. It seems that passing Me.ComboBox1.Value as an argument for the Vlookup function is causing the issue. What I did was assign this value to a double and then put it into the Vlookup function.

Dim x As Double
x = Me.ComboBox1.Value
Me.TextBox1.Value = Application.WorksheetFunction.VLookup(x, Worksheets("Sheet3").Range("Names"), 2, False) 

Or, for a shorter method, you can just convert the type within the Vlookup function using Cdbl(<Value>).

So it would end up being

Me.TextBox1.Value = Application.WorksheetFunction.VLookup(Cdbl(Me.ComboBox1.Value), Worksheets("Sheet3").Range("Names"), 2, False) 

Strange as it may sound, it works for me.

Hope this helps.

Bulk Insert to Oracle using .NET

To follow up on Theo's suggestion with my findings (apologies - I don't currently have enough reputation to post this as a comment)

First, this is how to use several named parameters:

String commandString = "INSERT INTO Users (Name, Desk, UpdateTime) VALUES (:Name, :Desk, :UpdateTime)";
using (OracleCommand command = new OracleCommand(commandString, _connection, _transaction))
{
    command.Parameters.Add("Name", OracleType.VarChar, 50).Value = strategy;
    command.Parameters.Add("Desk", OracleType.VarChar, 50).Value = deskName ?? OracleString.Null;
    command.Parameters.Add("UpdateTime", OracleType.DateTime).Value = updated;
    command.ExecuteNonQuery();
}

However, I saw no variation in speed between:

  • constructing a new commandString for each row (String.Format)
  • constructing a now parameterized commandString for each row
  • using a single commandString and changing the parameters

I'm using System.Data.OracleClient, deleting and inserting 2500 rows inside a transaction

Can I exclude some concrete urls from <url-pattern> inside <filter-mapping>?

I also Had to filter based on the URL pattern(/{servicename}/api/stats/)in java code .

if (path.startsWith("/{servicename}/api/statistics/")) {
validatingAuthToken(((HttpServletRequest) request).getHeader("auth_token"));
filterChain.doFilter(request, response);            
}

But its bizarre, that servlet doesn't support url pattern other than (/*), This should be a very common case for servlet API's !

Error: could not find function "%>%"

the following can be used:

 install.packages("data.table")
 library(data.table)

How do I set the visibility of a text box in SSRS using an expression?

Switch your false and true returns? I think if you put those as a function in the visibility area, then false will show it and true will not show it.

JSON response parsing in Javascript to get key/value pair

var yourobj={
"c":{
    "a":[{"name":"cable - black","value":2},{"name":"case","value":2}]
    },
"o":{
    "v":[{"name":"over the ear headphones - white/purple","value":1}]
},
"l":{
    "e":[{"name":"lens cleaner","value":1}]
},
"h":{
    "d":[{"name":"hdmi cable","value":1},
         {"name":"hdtv essentials (hdtv cable setup)","value":1},
         {"name":"hd dvd \u0026 blue-ray disc lens cleaner","value":1}]
}}
  • first of all it's a good idea to get organized
  • top level reference must be a more convenient name other that a..v... etc
  • in o.v,o.i.e no need for the array [] because it is one json entry

my solution

var obj = [];
for(n1 in yourjson)
    for(n1_1 in yourjson[n])
        for(n1_2 in yourjson[n][n1_1])
            obj[n1_2[name]] = n1_2[value];

Approved code

for(n1 in yourobj){
    for(n1_1 in yourobj[n1]){
    for(n1_2 in yourobj[n1][n1_1]){
            for(n1_3 in yourobj[n1][n1_1][n1_2]){
      obj[yourobj[n1][n1_1][n1_2].name]=yourobj[n1][n1_1][n1_2].value;
            }
    }
 }
}
console.log(obj);

result

*You should use distinguish accessorizes when using [] method or dot notation

proove

How many socket connections possible?

I achieved 1600k concurrent idle socket connections, and at the same time 57k req/s on a Linux desktop (16G RAM, I7 2600 CPU). It's a single thread http server written in C with epoll. Source code is on github, a blog here.

Edit:

I did 600k concurrent HTTP connections (client & server) on both the same computer, with JAVA/Clojure . detail info post, HN discussion: http://news.ycombinator.com/item?id=5127251

The cost of a connection(with epoll):

  • application need some RAM per connection
  • TCP buffer 2 * 4k ~ 10k, or more
  • epoll need some memory for a file descriptor, from epoll(7)

Each registered file descriptor costs roughly 90 bytes on a 32-bit kernel, and roughly 160 bytes on a 64-bit kernel.

Subtract days, months, years from a date in JavaScript

This is a pure-function which takes a passed-in starting date, building on Phil's answer:

function deltaDate(input, days, months, years) {
    return new Date(
      input.getFullYear() + years, 
      input.getMonth() + months, 
      Math.min(
        input.getDate() + days,
        new Date(input.getFullYear() + years, input.getMonth() + months + 1, 0).getDate()
      )
    );
}

e.g. writes the date one month ago to the console log:

console.log(deltaDate(new Date(), 0, -1, 0));

e.g. subtracts a month from March 30, 2020:

console.log(deltaDate(new Date(2020, 2, 30), 0, -1, 0)); // Feb 29, 2020

Note that this works even if you go past the end of the month or year.

Update: As the example above shows, this has been updated to handle variances in the number of days in a month.

Returning the product of a list

I am surprised no-one has suggested using itertools.accumulate with operator.mul. This avoids using reduce, which is different for Python 2 and 3 (due to the functools import required for Python 3), and moreover is considered un-pythonic by Guido van Rossum himself:

from itertools import accumulate
from operator import mul

def prod(lst):
    for value in accumulate(lst, mul):
        pass
    return value

Example:

prod([1,5,4,3,5,6])
# 1800

JS - window.history - Delete a state

There is no way to delete or read the past history.

You could try going around it by emulating history in your own memory and calling history.pushState everytime window popstate event is emitted (which is proposed by the currently accepted Mike's answer), but it has a lot of disadvantages that will result in even worse UX than not supporting the browser history at all in your dynamic web app, because:

  • popstate event can happen when user goes back ~2-3 states to the past
  • popstate event can happen when user goes forward

So even if you try going around it by building virtual history, it's very likely that it can also lead into a situation where you have blank history states (to which going back/forward does nothing), or where that going back/forward skips some of your history states totally.

grep without showing path/file:line

Just replace -H with -h. Check man grep for more details on options

find . -name '*.bar' -exec grep -hn FOO {} \;

How do I display image in Alert/confirm box in Javascript?

Alert boxes in JavaScript can only display pure text. You could use a JavaScript library like jQuery to display a modal instead?

This might be useful: http://jqueryui.com/dialog/

You can do it like this:

<!doctype html>

<html lang="en">
<head>
  <meta charset="utf-8" />
  <title>jQuery UI Dialog - Default functionality</title>
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
  <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
  <script>
  body {
    font-family: "Trebuchet MS", "Helvetica", "Arial",  "Verdana", "sans-serif";
    font-size: 62.5%;
}

  </script>
  <script>
  $(function() {
    $( "#dialog" ).dialog();
  });
  </script>
</head>
<body>

<div id="dialog" title="Basic dialog">
  <p>Image:</p>
  <img src="http://placehold.it/50x50" alt="Placeholder Image" />

</div>


</body>
</html>

Check if an element contains a class in JavaScript?

in which element is currently the class '.bar' ? Here is another solution but it's up to you.

var reg = /Image/g, // regexp for an image element
query = document.querySelector('.bar'); // returns [object HTMLImageElement]
query += this.toString(); // turns object into a string

if (query.match(reg)) { // checks if it matches
  alert('the class .bar is attached to the following Element:\n' + query);
}

jsfiddle demo

Of course this is only a lookup for 1 simple element <img>(/Image/g) but you can put all in an array like <li> is /LI/g, <ul> = /UL/g etc.

Switch firefox to use a different DNS than what is in the windows.host file

What about having different names for your dev and prod servers? That should avoid any confusions and you'd not have to edit the hosts file every time.

How do I correctly upgrade angular 2 (npm) to the latest version?

If you want to install/upgrade all packages to the latest version and you are running windows you can use this in powershell.exe:

foreach($package in @("animations","common","compiler","core","forms","http","platform-browser","platform-browser-dynamic","router")) {
    npm install @angular/$package@latest -E
}

If you also use the cli, you can do this:

foreach($package in @('animations','common','compiler','core','forms','http','platform-browser','platform-browser-dynamic','router', 'cli','compiler-cli')){
    iex "npm install @angular/$package@latest -E $(If($('cli','compiler-cli').Contains($package)){'-D'})";
}

This will save the packages exact (-E), and the cli packages in devDependencies (-D)

PHP, pass array through POST

There are two things to consider: users can modify forms, and you need to secure against Cross Site Scripting (XSS).

XSS

XSS is when a user enters HTML into their input. For example, what if a user submitted this value?:

" /><script type="text/javascript" src="http://example.com/malice.js"></script><input value="

This would be written into your form like so:

<input type="hidden" name="prova[]" value="" /><script type="text/javascript" src="http://example.com/malice.js"></script><input value=""/>

The best way to protect against this is to use htmlspecialchars() to secure your input. This encodes characters such as < into &lt;. For example:

<input type="hidden" name="prova[]" value="<?php echo htmlspecialchars($array); ?>"/>

You can read more about XSS here: https://www.owasp.org/index.php/XSS

Form Modification

If I were on your site, I could use Chrome's developer tools or Firebug to modify the HTML of your page. Depending on what your form does, this could be used maliciously.

I could, for example, add extra values to your array, or values that don't belong in the array. If this were a file system manager, then I could add files that don't exist or files that contain sensitive information (e.g.: replace myfile.jpg with ../index.php or ../db-connect.php).

In short, you always need to check your inputs later to make sure that they make sense, and only use safe inputs in forms. A File ID (a number) is safe, because you can check to see if the number exists, then extract the filename from a database (this assumes that your database contains validated input). A File Name isn't safe, for the reasons described above. You must either re-validate the filename or else I could change it to anything.

What is the use of rt.jar file in java?

rt.jar contains all of the compiled class files for the base Java Runtime environment. You should not be messing with this jar file.

For MacOS it is called classes.jar and located under /System/Library/Frameworks/<java_version>/Classes . Same not messing with it rule applies there as well :).

http://javahowto.blogspot.com/2006/05/what-does-rtjar-stand-for-in.html

Add another class to a div

In the DOM, the class of an element is just each class separated by a space. You would just need to implement the parsing logic to insert / remove the classes as necesary.

I wonder though... why wouldn't you want to use jQuery? It makes this kind of problem trivially easy.

IPhone/IPad: How to get screen width programmatically?

CGRect screen = [[UIScreen mainScreen] bounds];
CGFloat width = CGRectGetWidth(screen);
//Bonus height.
CGFloat height = CGRectGetHeight(screen);

Possible to change where Android Virtual Devices are saved?

Another way to specify ANDROID_SDK_HOME without messing around with environment variables (especially when using ec2) is simply create a shortcut of eclipse and add the following as target

C:\Windows\System32\cmd.exe /C "setx ANDROID_SDK_HOME YOUR AVD PATH /M & YOUR ECLIPSE.EXE PATH"

This will set ANDROID_SDK_HOME as system variable whenever you launch eclipse.

HTH Paul

Need to remove href values when printing in Chrome

To hide Page url .

use media="print" in style tage example :

<style type="text/css" media="print">
            @page {
                size: auto;   /* auto is the initial value */
                margin: 0;  /* this affects the margin in the printer settings */
            }
            @page { size: portrait; }
</style>

If you want to remove links :

@media print {
   a[href]:after {
      visibility: hidden !important;
   }
}

Execute SQL script from command line

You can do like this

sqlcmd -S <server Name> -U sa -P sapassword -i inputquery_file_name -o outputfile_name

From your command prompt run sqlcmd /? to get all the options you can use with sqlcmd utility

Multiple HttpPost method in Web API controller

use:

routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

it's not a RESTful approach anymore, but you can now call your actions by name (rather than let the Web API automatically determine one for you based on the verb) like this:

[POST] /api/VTRouting/TSPRoute

[POST] /api/VTRouting/Route

Contrary to popular belief, there is nothing wrong with this approach, and it's not abusing Web API. You can still leverage on all the awesome features of Web API (delegating handlers, content negotiation, mediatypeformatters and so on) - you just ditch the RESTful approach.

How to resolve this JNI error when trying to run LWJGL "Hello World"?

A CLASSPATH entry is either a directory at the head of a package hierarchy of .class files, or a .jar file. If you're expecting ./lib to include all the .jar files in that directory, it won't. You have to name them explicitly.

how to create a window with two buttons that will open a new window

You add your ActionListener twice to button. So correct your code for button2 to

  JButton button2 = new JButton("hello agin2");
  panel.add(button2);
  button2.addActionListener (new Action2());//note the button2 here instead of button

Furthermore, perform your Swing operations on the correct thread by using EventQueue.invokeLater

CodeIgniter Active Record not equal

This should work (which you have tried)

$this->db->where_not_in('emailsToCampaigns.campaignId', $campaignId);

How do I do logging in C# without using 3rd party libraries?

If you want your own custom Error Logging you can easily write your own code. I'll give you a snippet from one of my projects.

public void SaveLogFile(object method, Exception exception)
{
    string location = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\FolderName\";
    try
    {
        //Opens a new file stream which allows asynchronous reading and writing
        using (StreamWriter sw = new StreamWriter(new FileStream(location + @"log.txt", FileMode.Append, FileAccess.Write, FileShare.ReadWrite)))
        {
            //Writes the method name with the exception and writes the exception underneath
            sw.WriteLine(String.Format("{0} ({1}) - Method: {2}", DateTime.Now.ToShortDateString(), DateTime.Now.ToShortTimeString(), method.ToString()));
            sw.WriteLine(exception.ToString()); sw.WriteLine("");
        }
    }
    catch (IOException)
    {
        if (!File.Exists(location + @"log.txt"))
        {
            File.Create(location + @"log.txt");
        }
    }
}

Then to actually write to the error log just write (q being the caught exception)

SaveLogFile(MethodBase.GetCurrentMethod(), `q`);

Split files using tar, gz, zip, or bzip2

You can use the split command with the -b option:

split -b 1024m file.tar.gz

It can be reassembled on a Windows machine using @Joshua's answer.

copy /b file1 + file2 + file3 + file4 filetogether

Edit: As @Charlie stated in the comment below, you might want to set a prefix explicitly because it will use x otherwise, which can be confusing.

split -b 1024m "file.tar.gz" "file.tar.gz.part-"

// Creates files: file.tar.gz.part-aa, file.tar.gz.part-ab, file.tar.gz.part-ac, ...

Edit: Editing the post because question is closed and the most effective solution is very close to the content of this answer:

# create archives
$ tar cz my_large_file_1 my_large_file_2 | split -b 1024MiB - myfiles_split.tgz_
# uncompress
$ cat myfiles_split.tgz_* | tar xz

This solution avoids the need to use an intermediate large file when (de)compressing. Use the tar -C option to use a different directory for the resulting files. btw if the archive consists from only a single file, tar could be avoided and only gzip used:

# create archives
$ gzip -c my_large_file | split -b 1024MiB - myfile_split.gz_
# uncompress
$ cat myfile_split.gz_* | gunzip -c > my_large_file

For windows you can download ported versions of the same commands or use cygwin.

Getting query parameters from react-router hash fragment

You may get the following error while creating an optimized production build when using query-string module.

Failed to minify the code from this file: ./node_modules/query-string/index.js:8

To overcome this, kindly use the alternative module called stringquery which does the same process well without any issues while running the build.

import querySearch from "stringquery";

var query = querySearch(this.props.location.search);

Copy data into another table

Simple way if new table does not exist and you want to make a copy of old table with everything then following works in SQL Server.

SELECT * INTO NewTable FROM OldTable

Excluding files/directories from Gulp task

Quick answer

On src, you can always specify files to ignore using "!".

Example (you want to exclude all *.min.js files on your js folder and subfolder:

gulp.src(['js/**/*.js', '!js/**/*.min.js'])

You can do it as well for individual files.

Expanded answer:

Extracted from gulp documentation:

gulp.src(globs[, options])

Emits files matching provided glob or an array of globs. Returns a stream of Vinyl files that can be piped to plugins.

glob refers to node-glob syntax or it can be a direct file path.

So, looking to node-glob documentation we can see that it uses the minimatch library to do its matching.

On minimatch documentation, they point out the following:

if the pattern starts with a ! character, then it is negated.

And that is why using ! symbol will exclude files / directories from a gulp task

How do you post to an iframe?

This function creates a temporary form, then send data using jQuery :

function postToIframe(data,url,target){
    $('body').append('<form action="'+url+'" method="post" target="'+target+'" id="postToIframe"></form>');
    $.each(data,function(n,v){
        $('#postToIframe').append('<input type="hidden" name="'+n+'" value="'+v+'" />');
    });
    $('#postToIframe').submit().remove();
}

target is the 'name' attr of the target iFrame, and data is a JS object :

data={last_name:'Smith',first_name:'John'}

How to format numbers as currency string?

Numeral.js - a js library for easy number formatting by @adamwdraper

numeral(23456.789).format('$0,0.00'); // = "$23,456.79"

Matplotlib connect scatterplot points with line - Python

In addition to what provided in the other answers, the keyword "zorder" allows one to decide the order in which different objects are plotted vertically. E.g.:

plt.plot(x,y,zorder=1) 
plt.scatter(x,y,zorder=2)

plots the scatter symbols on top of the line, while

plt.plot(x,y,zorder=2)
plt.scatter(x,y,zorder=1)

plots the line over the scatter symbols.

See, e.g., the zorder demo

What is the difference between a "line feed" and a "carriage return"?

Since I can not comment because of not having enough reward points I have to answer to correct answer given by @Burhan Khalid.
In very layman language Enter key press is combination of carriage return and line feed.
Carriage return points the cursor to the beginning of the line horizontly and Line feed shifts the cursor to the next line vertically.Combination of both gives you new line(\n) effect.
Reference - https://en.wikipedia.org/wiki/Carriage_return#Computers

Unable to Resolve Module in React Native App

In my case I needed to import using an extended file path

i.e:

WRONG: import MyComponent from "componentFolder/myComponent";

RIGHT: import MyComponent from "../myAppFolder/componentFolder/myComponent";

Both of these showed no Typescript errors, but only the bottom one worked.

Understanding the Gemfile.lock file

in regards to the exclamation mark I just found out it's on gems fetched via :git, e.g.

gem "foo", :git => "[email protected]:company/foo.git"

Disabled href tag

Here are various ways to disable the a tag :

<a >Link Text</a> remove the href from your anchor tag
<a href=”javascript:void(0)”/>Link text</a> put javascript:void(0) in href
<a href="/" onclick="return false;">Link text</a> using return false

As there is no disabled attributes for anchor tag. If you want to stop anchor tag behavior inside a jQuery function than you can use the the below line in the start of the function :

$( "a" ).click(function( e ) {
e.preventDefault();
$( "<div>" )
.append( "default " + e.type + " prevented" )
.appendTo( "#log" );
});

event.preventDefault()

Load Image from javascript

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

<span class="spanloader">

    <span>set Loading Image Image</span>


</span>

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


<script type="text/javascript">

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

</script>

Direct download from Google Drive using Google Drive API

Update as of August 2020:

This is what worked for me recently -

Upload your file and get a shareable link which anyone can see(Change permission from "Restricted" to "Anyone with the Link" in the share link options)

Then run:

 SHAREABLE_LINK=<google drive shareable link>
 curl -L https://drive.google.com/uc\?id\=$(echo $SHAREABLE_LINK | cut -f6 -d"/")

Two HTML tables side by side, centered on the page

The problem is that the DIV that should center your tables has no width defined. By default, DIVs are block elements and take up the entire width of their parent - in this case the entire document (propagating through the #outer DIV), so the automatic margin style has no effect.

For this technique to work, you simply have to set the width of the div that has margin:auto to anything but "auto" or "inherit" (either a fixed pixel value or a percentage).

jQuery: If this HREF contains

It doesn't work because it's syntactically nonsensical. You simply can't do that in JavaScript like that.

You can, however, use jQuery:

  if ($(this).is('[href$=?]'))

You can also just look at the "href" value:

  if (/\?$/.test(this.href))

How to access remote server with local phpMyAdmin client?

Follow this blog post. You can do it very easily. https://wadsashika.wordpress.com/2015/01/06/manage-remote-mysql-database-locally-using-phpmyadmin/

The file config.inc.php contains the configuration settings for your phpMyAdmin installation. It uses an array to store sets of config options for every server it can connect to and by default there is only one, your own machine, or localhost. In order to connect to another server, you would have to add another set of config options to the config array. You have to edit this configuration file.

First open config.inc.php file held in phpMyAdmin folder. In wamp server, you can find it in wamp\apps\phpmyadmin folder. Then add following part to that file.

$i++;
$cfg['Servers'][$i]['host']          = 'hostname/Ip Adress';
$cfg['Servers'][$i]['port']          = '';
$cfg['Servers'][$i]['socket']        = '';
$cfg['Servers'][$i]['connect_type']  = 'tcp';
$cfg['Servers'][$i]['extension']     = 'mysql';
$cfg['Servers'][$i]['compress']      = FALSE;
$cfg['Servers'][$i]['auth_type']     = 'config';
$cfg['Servers'][$i]['user']          = 'username';
$cfg['Servers'][$i]['password']      = 'password';

Let’s see what is the meaning of this variables.

$i++ :- Incrementing variable for each server
$cfg[‘Servers’][$i][‘host’] :- Server host name or IP adress
$cfg[‘Servers’][$i][‘port’] :- MySQL port (Leave a blank for default port. Default MySQL port is 3306)
$cfg[‘Servers’][$i][‘socket’] :- Path to the socket (Leave a blank for default socket)
$cfg[‘Servers’][$i][‘connect_type’] :- How to connect to MySQL server (‘tcp’ or ‘socket’)
$cfg[‘Servers’][$i][‘extension’] :- php MySQL extension to use (‘mysql’ or ‘msqli’)
$cfg[‘Servers’][$i][‘compress’] :- Use compressed protocol for the MySQL connection (requires PHP >= 4.3.0)
$cfg[‘Servers’][$i][‘auth_type’] :- Method of Authentication
$cfg[‘Servers’][$i][‘username’] :- Username to the MySQL database in remote server
$cfg[‘Servers’][$i][‘password’] :- Password to the MySQL database int he remote server

After adding this configuration part, restart you server and now your phpMyAdmin home page will change and it will show a field to select the server.

Now you can select you server and access your remote database by entering username and password for that database.

How to prevent caching of my Javascript file?

<script src="test.js?random=<?php echo uniqid(); ?>"></script>

EDIT: Or you could use the file modification time so that it's cached on the client.

<script src="test.js?random=<?php echo filemtime('test.js'); ?>"></script>

How to access the SMS storage on Android?

You are going to need to call the SmsManager class. You are probably going to need to use the STATUS_ON_ICC_READ constant and maybe put what you get there into your apps local db so that you can keep track of what you have already read vs the new stuff for your app to parse through. BUT bear in mind that you have to declare the use of the class in your manifest, so users will see that you have access to their SMS called out in the permissions dialogue they get when they install. Seeing SMS access is unusual and could put some users off. Good luck.

Here is the link that goes into depth on the Sms Manager

Best practice for partial updates in a RESTful service

Check out http://www.odata.org/

It defines the MERGE method, so in your case it would be something like this:

MERGE /customer/123

<customer>
   <status>DISABLED</status>
</customer>

Only the status property is updated and the other values are preserved.

Python: most idiomatic way to convert None to empty string?

Use short circuit evaluation:

s = a or '' + b or ''

Since + is not a very good operation on strings, better use format strings:

s = "%s%s" % (a or '', b or '')

Add regression line equation and R^2 on graph

Another option would be to create a custom function generating the equation using dplyr and broom libraries:

get_formula <- function(model) {
  
  broom::tidy(model)[, 1:2] %>%
    mutate(sign = ifelse(sign(estimate) == 1, ' + ', ' - ')) %>% #coeff signs
    mutate_if(is.numeric, ~ abs(round(., 2))) %>% #for improving formatting
    mutate(a = ifelse(term == '(Intercept)', paste0('y ~ ', estimate), paste0(sign, estimate, ' * ', term))) %>%
    summarise(formula = paste(a, collapse = '')) %>%
    as.character
  
}

lm(y ~ x, data = df) -> model
get_formula(model)
#"y ~ 6.22 + 3.16 * x"

scales::percent(summary(model)$r.squared, accuracy = 0.01) -> r_squared

Now we need to add the text to the plot:

p + 
  geom_text(x = 20, y = 300,
            label = get_formula(model),
            color = 'red') +
  geom_text(x = 20, y = 285,
            label = r_squared,
            color = 'blue')

plot

What is the difference between a 'closure' and a 'lambda'?

A lambda is just an anonymous function - a function defined with no name. In some languages, such as Scheme, they are equivalent to named functions. In fact, the function definition is re-written as binding a lambda to a variable internally. In other languages, like Python, there are some (rather needless) distinctions between them, but they behave the same way otherwise.

A closure is any function which closes over the environment in which it was defined. This means that it can access variables not in its parameter list. Examples:

def func(): return h
def anotherfunc(h):
   return func()

This will cause an error, because func does not close over the environment in anotherfunc - h is undefined. func only closes over the global environment. This will work:

def anotherfunc(h):
    def func(): return h
    return func()

Because here, func is defined in anotherfunc, and in python 2.3 and greater (or some number like this) when they almost got closures correct (mutation still doesn't work), this means that it closes over anotherfunc's environment and can access variables inside of it. In Python 3.1+, mutation works too when using the nonlocal keyword.

Another important point - func will continue to close over anotherfunc's environment even when it's no longer being evaluated in anotherfunc. This code will also work:

def anotherfunc(h):
    def func(): return h
    return func

print anotherfunc(10)()

This will print 10.

This, as you notice, has nothing to do with lambdas - they are two different (although related) concepts.

Calculating frames per second in a game

Good answers here. Just how you implement it is dependent on what you need it for. I prefer the running average one myself "time = time * 0.9 + last_frame * 0.1" by the guy above.

however I personally like to weight my average more heavily towards newer data because in a game it is SPIKES that are the hardest to squash and thus of most interest to me. So I would use something more like a .7 \ .3 split will make a spike show up much faster (though it's effect will drop off-screen faster as well.. see below)

If your focus is on RENDERING time, then the .9.1 split works pretty nicely b/c it tend to be more smooth. THough for gameplay/AI/physics spikes are much more of a concern as THAT will usually what makes your game look choppy (which is often worse than a low frame rate assuming we're not dipping below 20 fps)

So, what I would do is also add something like this:

#define ONE_OVER_FPS (1.0f/60.0f)
static float g_SpikeGuardBreakpoint = 3.0f * ONE_OVER_FPS;
if(time > g_SpikeGuardBreakpoint)
    DoInternalBreakpoint()

(fill in 3.0f with whatever magnitude you find to be an unacceptable spike) This will let you find and thus solve FPS issues the end of the frame they happen.

How do I get the last day of a month?

Substract a day from the first of next month:

DateTime lastDay = new DateTime(MyDate.Year,MyDate.Month+1,1).AddDays(-1);

Also, in case you need it to work for December too:

DateTime lastDay = new DateTime(MyDate.Year,MyDate.Month,1).AddMonths(1).AddDays(-1);

How do you auto format code in Visual Studio?

(I know, I know, and old thread :P)

If you are using Jetbrains Resharper - the easiest way to format you code is to use the CTRL + ALT + ENTER shortcut (Reformat code)

Cannot get Kerberos service ticket: KrbException: Server not found in Kerberos database (7)

You would be surprised if I told you that I received this error when the UPN search was not returning any entry, meaning the user is not found, instead of getting a clear indication that the query returned no items.

So I recommend revising your query part or using AdExplorer to make sure that the users/groups you are looking for are reachable by the query you are using (depending on what you are using as an attribute for search sAMAccount, userPrincipalName, CN, DN).

Please note this can also happen when the AD you are connecting to is trying to find that user in another AD instance that your machine could not reach as part of your connections settings to that initial AD instance.

params.put(Context.REFERRAL, "follow");

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.

if var == False

var = False
if not var: print 'learnt stuff'

How to mention C:\Program Files in batchfile

While createting the bat file, you can easly avoid the space. If you want to mentioned "program files "folder in batch file.

Do following steps:

1. Type c: then press enter

2. cd program files

3. cd "choose your own folder name"

then continue as you wish.

This way you can create batch file and you can mention program files folder.

Check if a variable is of function type

Underscore.js uses a more elaborate but highly performant test:

_.isFunction = function(obj) {
  return !!(obj && obj.constructor && obj.call && obj.apply);
};

See: http://jsperf.com/alternative-isfunction-implementations

EDIT: updated tests suggest that typeof might be faster, see http://jsperf.com/alternative-isfunction-implementations/4

Populating Spring @Value during Unit Test

Since Spring 4.1 you could set up property values just in code by using org.springframework.test.context.TestPropertySource annotation on Unit Tests class level. You could use this approach even for injecting properties into dependent bean instances

For example

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = FooTest.Config.class)
@TestPropertySource(properties = {
    "some.bar.value=testValue",
})
public class FooTest {

  @Value("${some.bar.value}")
  String bar;

  @Test
  public void testValueSetup() {
    assertEquals("testValue", bar);
  }


  @Configuration
  static class Config {

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertiesResolver() {
        return new PropertySourcesPlaceholderConfigurer();
    }

  }

}

Note: It's necessary to have instance of org.springframework.context.support.PropertySourcesPlaceholderConfigurer in Spring context

Edit 24-08-2017: If you are using SpringBoot 1.4.0 and later you could initialize tests with @SpringBootTest and @SpringBootConfiguration annotations. More info here

In case of SpringBoot we have following code

@SpringBootTest
@SpringBootConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@TestPropertySource(properties = {
    "some.bar.value=testValue",
})
public class FooTest {

  @Value("${some.bar.value}")
  String bar;

  @Test
  public void testValueSetup() {
    assertEquals("testValue", bar);
  }

}

Bootstrap modal z-index

The modal dialog can be positioned on top by overriding its z-index property:

.modal.fade {
  z-index: 10000000 !important;
}

How to disable Django's CSRF validation?

@WoooHaaaa some third party packages use 'django.middleware.csrf.CsrfViewMiddleware' middleware. for example i use django-rest-oauth and i have problem like you even after disabling those things. maybe these packages responded to your request like my case, because you use authentication decorator and something like this.

Why Is Subtracting These Two Times (in 1927) Giving A Strange Result?

You've encountered a local time discontinuity:

When local standard time was about to reach Sunday, 1. January 1928, 00:00:00 clocks were turned backward 0:05:52 hours to Saturday, 31. December 1927, 23:54:08 local standard time instead

This is not particularly strange and has happened pretty much everywhere at one time or another as timezones were switched or changed due to political or administrative actions.

How to Select Columns in Editors (Atom,Notepad++, Kate, VIM, Sublime, Textpad,etc) and IDEs (NetBeans, IntelliJ IDEA, Eclipse, Visual Studio, etc)

If you're using Nedit under Cygwin-X (or any platform for that matter), hold down the Ctrl key while selecting text with the left mouse.

Additionally, you can then drag the selected "box" around in an insert mode using the depressed left-mouse button or in overwrite mode by using Ctrl+left-mouse button.

Java String split removed empty values

From String.split() API Doc:

Splits this string around matches of the given regular expression. This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

Overloaded String.split(regex, int) is more appropriate for your case.

How to install Java 8 on Mac

If you have several Java versions on your machine and you want to choose it dynamically at runtime, i.e, in my case, I have two versions:

ls -la /Library/Java/JavaVirtualMachines
drwxr-xr-x  3 root  wheel    96B Nov 16  2014 jdk1.7.0_71.jdk/
drwxr-xr-x  3 root  wheel    96B Mar  1  2015 jdk1.8.0_31.jdk/

You can change them by modifying the /etc/profile content. Just add (or modify) the following two lines at the end of the file:

export JAVA_HOME=YOUR_JAVA_PATH/Contents/Home
export PATH=$JAVA_HOME/bin:$PATH

In my case, it should be like the following if I want to use:

Java 7:

export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.7.0_71.jdk/Contents/Home
export PATH=$JAVA_HOME/bin:$PATH

Java 8:

export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_31.jdk/Contents/Home
export PATH=$JAVA_HOME/bin:$PATH

After saving the file, please run source /etc/profile and it should work. Here are results when I use the first and second option accordingly:

Java 7:

java -version
java version "1.7.0_71"
Java(TM) SE Runtime Environment (build 1.7.0_71-b14)

Java 8:

java -version 
java version "1.8.0_31"
Java(TM) SE Runtime Environment (build 1.8.0_31-b13)

The process is similar if your java folder is located in different locations.

Import one schema into another new schema - Oracle

After you correct the possible dmp file problem, this is a way to ensure that the schema is remapped and imported appropriately. This will also ensure that the tablespace will change also, if needed:

impdp system/<password> SCHEMAS=user1 remap_schema=user1:user2 \
            remap_tablespace=user1:user2 directory=EXPORTDIR \
            dumpfile=user1.dmp logfile=E:\Data\user1.log

EXPORTDIR must be defined in oracle as a directory as the system user

create or replace directory EXPORTDIR as 'E:\Data';
grant read, write on directory EXPORTDIR to user2;

Using momentjs to convert date to epoch then back to date

http://momentjs.com/docs/#/displaying/unix-timestamp/

You get the number of unix seconds, not milliseconds!

You you need to multiply it with 1000 or using valueOf() and don't forget to use a formatter, since you are using a non ISO 8601 format. And if you forget to pass the formatter, the date will be parsed in the UTC timezone or as an invalid date.

moment("10/15/2014 9:00", "MM/DD/YYYY HH:mm").valueOf()

What is the difference between an annotated and unannotated tag?

Push annotated tags, keep lightweight local

man git-tag says:

Annotated tags are meant for release while lightweight tags are meant for private or temporary object labels.

And certain behaviors do differentiate between them in ways that this recommendation is useful e.g.:

  • annotated tags can contain a message, creator, and date different than the commit they point to. So you could use them to describe a release without making a release commit.

    Lightweight tags don't have that extra information, and don't need it, since you are only going to use it yourself to develop.

  • git push --follow-tags will only push annotated tags
  • git describe without command line options only sees annotated tags

Internals differences

  • both lightweight and annotated tags are a file under .git/refs/tags that contains a SHA-1

  • for lightweight tags, the SHA-1 points directly to a commit:

    git tag light
    cat .git/refs/tags/light
    

    prints the same as the HEAD's SHA-1.

    So no wonder they cannot contain any other metadata.

  • annotated tags point to a tag object in the object database.

    git tag -as -m msg annot
    cat .git/refs/tags/annot
    

    contains the SHA of the annotated tag object:

    c1d7720e99f9dd1d1c8aee625fd6ce09b3a81fef
    

    and then we can get its content with:

    git cat-file -p c1d7720e99f9dd1d1c8aee625fd6ce09b3a81fef
    

    sample output:

    object 4284c41353e51a07e4ed4192ad2e9eaada9c059f
    type commit
    tag annot
    tagger Ciro Santilli <[email protected]> 1411478848 +0200
    
    msg
    -----BEGIN PGP SIGNATURE-----
    Version: GnuPG v1.4.11 (GNU/Linux)
    
    <YOUR PGP SIGNATURE>
    -----END PGP SIGNAT
    

    And this is how it contains extra metadata. As we can see from the output, the metadata fields are:

    A more detailed analysis of the format is present at: What is the format of a git tag object and how to calculate its SHA?

Bonuses

  • Determine if a tag is annotated:

    git cat-file -t tag
    

    Outputs

    • commit for lightweight, since there is no tag object, it points directly to the commit
    • tag for annotated, since there is a tag object in that case
  • List only lightweight tags: How can I list all lightweight tags?

What is an "index out of range" exception, and how do I fix it?

Why does this error occur?

Because you tried to access an element in a collection, using a numeric index that exceeds the collection's boundaries.

The first element in a collection is generally located at index 0. The last element is at index n-1, where n is the Size of the collection (the number of elements it contains). If you attempt to use a negative number as an index, or a number that is larger than Size-1, you're going to get an error.

How indexing arrays works

When you declare an array like this:

var array = new int[6]

The first and last elements in the array are

var firstElement = array[0];
var lastElement = array[5];

So when you write:

var element = array[5];

you are retrieving the sixth element in the array, not the fifth one.

Typically, you would loop over an array like this:

for (int index = 0; index < array.Length; index++)
{
    Console.WriteLine(array[index]);
}

This works, because the loop starts at zero, and ends at Length-1 because index is no longer less than Length.

This, however, will throw an exception:

for (int index = 0; index <= array.Length; index++)
{
    Console.WriteLine(array[index]);
}

Notice the <= there? index will now be out of range in the last loop iteration, because the loop thinks that Length is a valid index, but it is not.

How other collections work

Lists work the same way, except that you generally use Count instead of Length. They still start at zero, and end at Count - 1.

for (int index = 0; i < list.Count; index++)
{
    Console.WriteLine(list[index]);
} 

However, you can also iterate through a list using foreach, avoiding the whole problem of indexing entirely:

foreach (var element in list)
{
    Console.WriteLine(element.ToString());
}

You cannot index an element that hasn't been added to a collection yet.

var list = new List<string>();
list.Add("Zero");
list.Add("One");
list.Add("Two");
Console.WriteLine(list[3]);  // Throws exception.

registerForRemoteNotificationTypes: is not supported in iOS 8.0 and later

As you described, you will need to use a different method based on different versions of iOS. If your team is using both Xcode 5 (which doesn't know about any iOS 8 selectors) and Xcode 6, then you will need to use conditional compiling as follows:

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
if ([application respondsToSelector:@selector(registerUserNotificationSettings:)]) {
    // use registerUserNotificationSettings
} else {
    // use registerForRemoteNotificationTypes:
}
#else
// use registerForRemoteNotificationTypes:
#endif

If you are only using Xcode 6, you can stick with just this:

if ([application respondsToSelector:@selector(registerUserNotificationSettings:)]) {
    // use registerUserNotificationSettings
} else {
    // use registerForRemoteNotificationTypes:
}

The reason is here is that the way you get notification permissions has changed in iOS 8. A UserNotification is a message shown to the user, whether from remote or from local. You need to get permission to show one. This is described in the WWDC 2014 video "What's New in iOS Notifications"

JavaFX FXML controller - constructor vs initialize method

The initialize method is called after all @FXML annotated members have been injected. Suppose you have a table view you want to populate with data:

class MyController { 
    @FXML
    TableView<MyModel> tableView; 

    public MyController() {
        tableView.getItems().addAll(getDataFromSource()); // results in NullPointerException, as tableView is null at this point. 
    }

    @FXML
    public void initialize() {
        tableView.getItems().addAll(getDataFromSource()); // Perfectly Ok here, as FXMLLoader already populated all @FXML annotated members. 
    }
}

Command line for looking at specific port

For port 80, the command would be : netstat -an | find "80" For port n, the command would be : netstat -an | find "n"

Here, netstat is the instruction to your machine

-a : Displays all connections and listening ports -n : Displays all address and instructions in numerical format (This is required because output from -a can contain machine names)

Then, a find command to "Pattern Match" the output of previous command.

How to make gradient background in android

Try with this :

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >

    <gradient
        android:angle="90"
        android:centerColor="#555994"
        android:endColor="#b5b6d2"
        android:startColor="#555994"
        android:type="linear" />

    <corners 
        android:radius="0dp"/>

</shape>

Why is Dictionary preferred over Hashtable in C#?

People are saying that a Dictionary is the same as a hash table.

This is not necessarily true. A hash table is one way to implement a dictionary. A typical one at that, and it may be the default one in .NET in the Dictionary class, but it's not by definition the only one.

You could equally well implement a dictionary using a linked list or a search tree, it just wouldn't be as efficient (for some metric of efficient).

How to debug an apache virtual host configuration?

I recently had some issues with a VirtualHost. I used a2ensite to enable a host but before running a restart (which would kill the server on fail) I ran

apache2ctl -S

Which gives you some info about what's going on with your virtual hosts. It's not perfect, but it helps.

Disable Logback in SpringBoot

Same problem for me.

enter image description here

If you are using log4j2

In the Spring boot 2.4.0

I resolve below,

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-logging</artifactId>
        </exclusion>
    </exclusions>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-log4j2</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-slf4j-impl</artifactId> <-- exclude this artifactId
        </exclusion>
    </exclusions>
</dependency>

After, Maven Build > Clean > Run

enter image description here

Work for me.

Store text file content line by line into array

You can use this code. This works very fast!

public String[] loadFileToArray(String fileName) throws IOException {
    String s = new String(Files.readAllBytes(Paths.get(fileName)));
    return Arrays.stream(s.split("\n")).toArray(String[]::new);
}

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

A 32-bit float has about 7 digits of precision and a 64-bit double has about 16 digits of precision

Long answer:

Floating-point numbers have three components:

  1. A sign bit, to determine if the number is positive or negative.
  2. An exponent, to determine the magnitude of the number.
  3. A fraction, which determines how far between two exponent values the number is. This is sometimes called “the significand, mantissa, or coefficient”

Essentially, this works out to sign * 2^exponent * (1 + fraction). The “size” of the number, it’s exponent, is irrelevant to us, because it only scales the value of the fraction portion. Knowing that log10(n) gives the number of digits of n,† we can determine the precision of a floating point number with log10(largest_possible_fraction). Because each bit in a float stores 2 possibilities, a binary number of n bits can store a number up to 2n - 1 (a total of 2n values where one of the values is zero). This gets a bit hairier, because it turns out that floating point numbers are stored with one less bit of fraction than they can use, because zeroes are represented specially and all non-zero numbers have at least one non-zero binary bit.‡

Combining this, the digits of precision for a floating point number is log10(2n), where n is the number of bits of the floating point number’s fraction. A 32-bit float has 24 bits of fraction for ˜7.22 decimal digits of precision, and a 64-bit double has 53 bits of fraction for ˜15.95 decimal digits of precision.

For more on floating point accuracy, you might want to read about the concept of a machine epsilon.


† For n = 1 at least — for other numbers your formula will look more like ?log10(|n|)? + 1.

‡ “This rule is variously called the leading bit convention, the implicit bit convention, or the hidden bit convention.” (Wikipedia)

Authenticate with GitHub using a token

This worked for me using ssh:

SettingsDeveloper settingsGenerate new token.

git remote set-url origin https://[APPLICATION]:[NEW TOKEN]@github.com/[ORGANISATION]/[REPO].git

NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equalsIgnoreCase(java.lang.String)' on a null object reference

This is the error line:

if (called_from.equalsIgnoreCase("add")) {  --->38th error line

This means that called_from is null. Simple check if it is null above:

String called_from = getIntent().getStringExtra("called");

if(called_from == null) {
    called_from = "empty string";
}
if (called_from.equalsIgnoreCase("add")) {
    // do whatever
} else {
    // do whatever
}

That way, if called_from is null, it'll execute the else part of your if statement.

Sequelize, convert entity to plain object

I have found a solution that works fine for nested model and array using native JavaScript functions.

var results = [{},{},...]; //your result data returned from sequelize query
var jsonString = JSON.stringify(results); //convert to string to remove the sequelize specific meta data

var obj = JSON.parse(jsonString); //to make plain json
// do whatever you want to do with obj as plain json

Set height of chart in Chart.js

He's right. If you want to stay with jQuery you could do this

var ctx = $('#myChart')[0];
ctx.height = 500;

or

var ctx = $('#myChart');
ctx.attr('height',500);

How do you install an APK file in the Android emulator?

Start the console (Windows XP), Run -> type cmd, and move to the platform-tools folder of SDK directory.

In case anyone wondering how to run cmd in platform-tools folder of SDK directory, if you are running a new enough version of Windows, follow the steps:

  1. Go to platform-tools through Windows Explorer.
  2. While holding shift right click and you will find the option "Open Command window here".
  3. Click on it and cmd will start in that folder.

enter image description here

Hope it helps

A CSS selector to get last visible div

Pure JS solution (eg. when you don't use jQuery or another framework to other things and don't want to download that just for this task):

<div>A</div>
<div>B</div>  
<div>C</div>  
<div style="display:none">D</div>
<div style="display:none">E</div>    

<script>
var divs = document.getElementsByTagName('div');
var last;

if (divs) {
    for (var i = 0; i < divs.length; i++) {
        if (divs[i].style.display != 'none') {
            last = divs[i];           
        }
    }
}

if (last) {
    last.style.background = 'red';
}
</script>

http://jsfiddle.net/uEeaA/90/

Using Server.MapPath in external C# Classes in ASP.NET

you can also use:

var path = System.Web.Hosting.HostingEnvironment.MapPath("~/App_Data/myfile.txt")

if

var path = Server.MapPath("~/App_Data");
var fullpath = Path.Combine(path , "myfile.txt");

is inaccessible

Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function but got: object

Don't get surprised by the list of answers for a single question. There are various causes for this issue;

For my case, the warning was

warning.js:33 Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in. Check your code at index.js:13.

Followed by the error

invariant.js:42 Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in.

I couldn't understand the error since it doesn't mention any method or file name. I was able to resolve only after looking at this warning, mentioned above.

I have the following line at the index.js.

<ConnectedRouter history={history}>

When I googled for the above error with the keyword "ConnectedRouter" I found the solution in a GitHub page.

The error is because, when we install react-router-redux package, by default we install this one. https://github.com/reactjs/react-router-redux but not the actual library.

To resolve this error, install the proper package by specifing the npm scope with @

npm install react-router-redux@next

You don't need to remove the wrongly installed package. It will be automatically overwritten.

Thank you.

PS: Even warning helps you. Don't neglect warning just looking at the error alone.

Monad in plain English? (For the OOP programmer with no FP background)

A monad is an array of functions

(Pst: an array of functions is just a computation).

Actually, instead of a true array (one function in one cell array) you have those functions chained by another function >>=. The >>= allows to adapt the results from function i to feed function i+1, perform calculations between them or, even, not to call function i+1.

The types used here are "types with context". This is, a value with a "tag". The functions being chained must take a "naked value" and return a tagged result. One of the duties of >>= is to extract a naked value out of its context. There is also the function "return", that takes a naked value and puts it with a tag.

An example with Maybe. Let's use it to store a simple integer on which make calculations.

-- a * b
multiply :: Int -> Int -> Maybe Int
multiply a b = return  (a*b)

-- divideBy 5 100 = 100 / 5
divideBy :: Int -> Int -> Maybe Int
divideBy 0 _ = Nothing -- dividing by 0 gives NOTHING
divideBy denom num = return (quot num denom) -- quotient of num / denom

-- tagged value
val1 = Just 160 

-- array of functions feeded with val1
array1 = val1 >>= divideBy 2  >>= multiply 3 >>= divideBy  4 >>= multiply 3

-- array of funcionts created with the do notation
-- equals array1 but for the feeded val1
array2 :: Int -> Maybe Int
array2 n = do
       v <- divideBy 2  n
       v <- multiply 3 v
       v <- divideBy 4 v
       v <- multiply 3 v
       return v

-- array of functions, 
-- the first >>= performs 160 / 0, returning Nothing
-- the second >>= has to perform Nothing >>= multiply 3 ....
-- and simply returns Nothing without calling multiply 3 ....
array3 = val1 >>= divideBy 0  >>= multiply 3 >>= divideBy  4 >>= multiply 3

main = do
     print array1
     print (array2 160)
     print array3

Just to show that monads are array of functions with helper operations, consider the equivalent to the above example, just using a real array of functions

type MyMonad = [Int -> Maybe Int] -- my monad as a real array of functions

myArray1 = [divideBy 2, multiply 3, divideBy 4, multiply 3]

-- function for the machinery of executing each function i with the result provided by function i-1
runMyMonad :: Maybe Int -> MyMonad -> Maybe Int
runMyMonad val [] = val
runMyMonad Nothing _ = Nothing
runMyMonad (Just val) (f:fs) = runMyMonad (f val) fs

And it would be used like this:

print (runMyMonad (Just 160) myArray1)

What’s the difference between Response.Write() andResponse.Output.Write()?

Response.write() don't give formatted output. The latter one allows you to write formatted output.

Response.write - it writes the text stream Response.output.write - it writes the HTTP Output Stream.

How to sort a Pandas DataFrame by index?

Slightly more compact:

df = pd.DataFrame([1, 2, 3, 4, 5], index=[100, 29, 234, 1, 150], columns=['A'])
df = df.sort_index()
print(df)

Note:

Getting value of HTML Checkbox from onclick/onchange events

Use this

<input type="checkbox" onclick="onClickHandler()" id="box" />

<script>
function onClickHandler(){
    var chk=document.getElementById("box").value;

    //use this value

}
</script>

What is the difference between Select and Project Operations

select just changes cardinality of the result table but project does change both degree of relation and cardinality.

What is the difference between null and undefined in JavaScript?

I want to add a very subtle difference between null and undefined which is good to know when you are trying to learn Vanilla JavaScript(JS) from ground up:

  • null is a reserved keyword in JS while undefined is a variable on the global object of the run-time environment you're in.

While writing code, this difference is not identifiable as both null and undefined are always used in RHS of a JavaScript statement. But when you use them in LHS of an expression then you can observe this difference easily. So JS interpreter interprets the below code as error:

var null = 'foo'

It gives below error:

Uncaught SyntaxError: Unexpected token null

While below code runs successfully although I won't recommend doing so in real life:

var undefined = 'bar'

This works because undefined is a variable on the global object (browser window object in case of client-side JS)

How to Join to first row

From SQL Server 2012 and onwards I think this will do the trick:

SELECT DISTINCT
    o.OrderNumber ,
    FIRST_VALUE(li.Quantity) OVER ( PARTITION BY o.OrderNumber ORDER BY li.Description ) AS Quantity ,
    FIRST_VALUE(li.Description) OVER ( PARTITION BY o.OrderNumber ORDER BY li.Description ) AS Description
FROM    Orders AS o
    INNER JOIN LineItems AS li ON o.OrderID = li.OrderID

Invalid use side-effecting operator Insert within a function

Disclaimer: This is not a solution, it is more of a hack to test out something. User-defined functions cannot be used to perform actions that modify the database state.

I found one way to make insert or update using sqlcmd.exe so you need just to replace the code inside @sql variable.

CREATE FUNCTION [dbo].[_tmp_func](@orderID NVARCHAR(50))
RETURNS INT
AS
BEGIN
DECLARE @sql varchar(4000), @cmd varchar(4000)
SELECT @sql = 'INSERT INTO _ord (ord_Code) VALUES (''' + @orderID + ''') '
SELECT @cmd = 'sqlcmd -S ' + @@servername +
              ' -d ' + db_name() + ' -Q "' + @sql + '"'
EXEC master..xp_cmdshell @cmd, 'no_output'
RETURN 1
END

Error : ORA-01704: string literal too long

Try to split the characters into multiple chunks like the query below and try:

Insert into table (clob_column) values ( to_clob( 'chunk 1' ) || to_clob( 'chunk 2' ) );

It worked for me.

How to show full object in Chrome console?

With modern browsers, console.log(functor) works perfectly (behaves the same was a console.dir).

Linear Layout and weight in Android

You have to write like this its Working for me

<LinearLayout
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:orientation="horizontal"
            android:weightSum="2">

         <Button
            android:text="Register"
            android:id="@+id/register"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="10dip"
            android:layout_weight="1" />

         <Button
            android:text="Not this time"
            android:id="@+id/cancel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="10dip"
            android:layout_weight="1" />

Awaiting multiple Tasks with different results

If you're using C# 7, you can use a handy wrapper method like this...

public static class TaskEx
{
    public static async Task<(T1, T2)> WhenAll<T1, T2>(Task<T1> task1, Task<T2> task2)
    {
        return (await task1, await task2);
    }
}

...to enable convenient syntax like this when you want to wait on multiple tasks with different return types. You'd have to make multiple overloads for different numbers of tasks to await, of course.

var (someInt, someString) = await TaskEx.WhenAll(GetIntAsync(), GetStringAsync());

However, see Marc Gravell's answer for some optimizations around ValueTask and already-completed tasks if you intend to turn this example into something real.

How to extract text from a string using sed?

sed doesn't recognize \d, use [[:digit:]] instead. You will also need to escape the + or use the -r switch (-E on OS X).

Note that [0-9] works as well for Arabic-Hindu numerals.

Android REST client, Sample?

EDIT 2 (October 2017):

It is 2017. Just use Retrofit. There is almost no reason to use anything else.

EDIT:

The original answer is more than a year and a half old at the time of this edit. Although the concepts presented in original answer still hold, as other answers point out, there are now libraries out there that make this task easier for you. More importantly, some of these libraries handle device configuration changes for you.

The original answer is retained below for reference. But please also take the time to examine some of the Rest client libraries for Android to see if they fit your use cases. The following is a list of some of the libraries I've evaluated. It is by no means intended to be an exhaustive list.


Original Answer:

Presenting my approach to having REST clients on Android. I do not claim it is the best though :) Also, note that this is what I came up with in response to my requirement. You might need to have more layers/add more complexity if your use case demands it. For example, I do not have local storage at all; because my app can tolerate loss of a few REST responses.

My approach uses just AsyncTasks under the covers. In my case, I "call" these Tasks from my Activity instance; but to fully account for cases like screen rotation, you might choose to call them from a Service or such.

I consciously chose my REST client itself to be an API. This means, that the app which uses my REST client need not even be aware of the actual REST URL's and the data format used.

The client would have 2 layers:

  1. Top layer: The purpose of this layer is to provide methods which mirror the functionality of the REST API. For example, you could have one Java method corresponding to every URL in your REST API (or even two - one for GETs and one for POSTs).
    This is the entry point into the REST client API. This is the layer the app would use normally. It could be a singleton, but not necessarily.
    The response of the REST call is parsed by this layer into a POJO and returned to the app.

  2. This is the lower level AsyncTask layer, which uses HTTP client methods to actually go out and make that REST call.

In addition, I chose to use a Callback mechanism to communicate the result of the AsyncTasks back to the app.

Enough of text. Let's see some code now. Lets take a hypothetical REST API URL - http://myhypotheticalapi.com/user/profile

The top layer might look like this:

   /**
 * Entry point into the API.
 */
public class HypotheticalApi{   
    public static HypotheticalApi getInstance(){
        //Choose an appropriate creation strategy.
    }
    
    /**
     * Request a User Profile from the REST server.
     * @param userName The user name for which the profile is to be requested.
     * @param callback Callback to execute when the profile is available.
     */
    public void getUserProfile(String userName, final GetResponseCallback callback){
        String restUrl = Utils.constructRestUrlForProfile(userName);
        new GetTask(restUrl, new RestTaskCallback (){
            @Override
            public void onTaskComplete(String response){
                Profile profile = Utils.parseResponseAsProfile(response);
                callback.onDataReceived(profile);
            }
        }).execute();
    }
    
    /**
     * Submit a user profile to the server.
     * @param profile The profile to submit
     * @param callback The callback to execute when submission status is available.
     */
    public void postUserProfile(Profile profile, final PostCallback callback){
        String restUrl = Utils.constructRestUrlForProfile(profile);
        String requestBody = Utils.serializeProfileAsString(profile);
        new PostTask(restUrl, requestBody, new RestTaskCallback(){
            public void onTaskComplete(String response){
                callback.onPostSuccess();
            }
        }).execute();
    }
}


/**
 * Class definition for a callback to be invoked when the response data for the
 * GET call is available.
 */
public abstract class GetResponseCallback{
    
    /**
     * Called when the response data for the REST call is ready. <br/>
     * This method is guaranteed to execute on the UI thread.
     * 
     * @param profile The {@code Profile} that was received from the server.
     */
    abstract void onDataReceived(Profile profile);
    
    /*
     * Additional methods like onPreGet() or onFailure() can be added with default implementations.
     * This is why this has been made and abstract class rather than Interface.
     */
}

/**
 * 
 * Class definition for a callback to be invoked when the response for the data 
 * submission is available.
 * 
 */
public abstract class PostCallback{
    /**
     * Called when a POST success response is received. <br/>
     * This method is guaranteed to execute on the UI thread.
     */
    public abstract void onPostSuccess();

}

Note that the app doesn't use the JSON or XML (or whatever other format) returned by the REST API directly. Instead, the app only sees the bean Profile.

Then, the lower layer (AsyncTask layer) might look like this:

/**
 * An AsyncTask implementation for performing GETs on the Hypothetical REST APIs.
 */
public class GetTask extends AsyncTask<String, String, String>{
    
    private String mRestUrl;
    private RestTaskCallback mCallback;
    
    /**
     * Creates a new instance of GetTask with the specified URL and callback.
     * 
     * @param restUrl The URL for the REST API.
     * @param callback The callback to be invoked when the HTTP request
     *            completes.
     * 
     */
    public GetTask(String restUrl, RestTaskCallback callback){
        this.mRestUrl = restUrl;
        this.mCallback = callback;
    }
    
    @Override
    protected String doInBackground(String... params) {
        String response = null;
        //Use HTTP Client APIs to make the call.
        //Return the HTTP Response body here.
        return response;
    }
    
    @Override
    protected void onPostExecute(String result) {
        mCallback.onTaskComplete(result);
        super.onPostExecute(result);
    }
}

    /**
     * An AsyncTask implementation for performing POSTs on the Hypothetical REST APIs.
     */
    public class PostTask extends AsyncTask<String, String, String>{
        private String mRestUrl;
        private RestTaskCallback mCallback;
        private String mRequestBody;
        
        /**
         * Creates a new instance of PostTask with the specified URL, callback, and
         * request body.
         * 
         * @param restUrl The URL for the REST API.
         * @param callback The callback to be invoked when the HTTP request
         *            completes.
         * @param requestBody The body of the POST request.
         * 
         */
        public PostTask(String restUrl, String requestBody, RestTaskCallback callback){
            this.mRestUrl = restUrl;
            this.mRequestBody = requestBody;
            this.mCallback = callback;
        }
        
        @Override
        protected String doInBackground(String... arg0) {
            //Use HTTP client API's to do the POST
            //Return response.
        }
        
        @Override
        protected void onPostExecute(String result) {
            mCallback.onTaskComplete(result);
            super.onPostExecute(result);
        }
    }
    
    /**
     * Class definition for a callback to be invoked when the HTTP request
     * representing the REST API Call completes.
     */
    public abstract class RestTaskCallback{
        /**
         * Called when the HTTP request completes.
         * 
         * @param result The result of the HTTP request.
         */
        public abstract void onTaskComplete(String result);
    }

Here's how an app might use the API (in an Activity or Service):

HypotheticalApi myApi = HypotheticalApi.getInstance();
        myApi.getUserProfile("techie.curious", new GetResponseCallback() {

            @Override
            void onDataReceived(Profile profile) {
                //Use the profile to display it on screen, etc.
            }
            
        });
        
        Profile newProfile = new Profile();
        myApi.postUserProfile(newProfile, new PostCallback() {
            
            @Override
            public void onPostSuccess() {
                //Display Success
            }
        });

I hope the comments are sufficient to explain the design; but I'd be glad to provide more info.

Use a list of values to select rows from a pandas dataframe

You can use isin method:

In [1]: df = pd.DataFrame({'A': [5,6,3,4], 'B': [1,2,3,5]})

In [2]: df
Out[2]:
   A  B
0  5  1
1  6  2
2  3  3
3  4  5

In [3]: df[df['A'].isin([3, 6])]
Out[3]:
   A  B
1  6  2
2  3  3

And to get the opposite use ~:

In [4]: df[~df['A'].isin([3, 6])]
Out[4]:
   A  B
0  5  1
3  4  5

How can I run another application within a panel of my C# program?

I don't know if this is still the recommended thing to use but the "Object Linking and Embedding" framework allows you to embed certain objects/controls directly into your application. This will probably only work for certain applications, I'm not sure if Notepad is one of them. For really simple things like notepad, you'll probably have an easier time just working with the text box controls provided by whatever medium you're using (e.g. WinForms).

Here's a link to OLE info to get started:

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

HTML input textbox with a width of 100% overflows table cells

With some Javascript you can get the exact width of the containing TD and then assign that directly to the input element.

The following is raw javascript but jQuery would make it cleaner...

var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++)
{
    var el = inputs[i];
    if (el.style.width == '100%')
    {
        var pEl = el.parentNode;  // Assumes the parent node is the TD...
        el.style.width = pEl.offsetWidth;
    }
}

The issues with this solution are:

1) If you have your inputs contained in another element such as a SPAN then you will need loop up and find the TD because elements like SPANs will wrap the input and show its size rather then being limited to the size of the TD.

2) If you have padding or margins added at different levels then you might have to explicitly subtract that from [pEl.offsetWidth]. Depending on your HTML structure that can be calculated.

3) If the table columns are sized dynamically then changing the size of one element will cause the table to reflow in some browsers and you might get a stepped effect as you sequentially "fix" the input sizes. The solution is to assign specific widths to the column either as percentages or pixels OR collect the new widths and set them after. See the code below..

var inputs = document.getElementsByTagName('input');
var newSizes = [];
for (var i = 0; i < inputs.length; i++)
{
    var el = inputs[i];
    if (el.style.width == '100%')
    {
        var pEl = el.parentNode;  // Assumes the parent node is the TD...
        newSizes.push( { el: el, width: pEl.offsetWidth });
    }
}

// Set the sizes AFTER to avoid stepping...
for (var i = 0; i < newSizes.length; i++)
{
    newSizes[i].el.style.width = newSizes[i].width;
}

How to convert a String to CharSequence?

CharSequence is an interface and String is its one of the implementations other than StringBuilder, StringBuffer and many other.

So, just as you use InterfaceName i = new ItsImplementation(), you can use CharSequence cs = new String("string") or simply CharSequence cs = "string";

Equivalent to AssemblyInfo in dotnet core/csproj

I do the following for my .NET Standard 2.0 projects.

Create a Directory.Build.props file (e.g. in the root of your repo) and move the properties to be shared from the .csproj file to this file.

MSBuild will pick it up automatically and apply them to the autogenerated AssemblyInfo.cs.

They also get applied to the nuget package when building one with dotnet pack or via the UI in Visual Studio 2017.

See https://docs.microsoft.com/en-us/visualstudio/msbuild/customize-your-build

Example:

<Project>
    <PropertyGroup>
        <Company>Some company</Company>
        <Copyright>Copyright © 2020</Copyright>
        <AssemblyVersion>1.0.0.1</AssemblyVersion>
        <FileVersion>1.0.0.1</FileVersion>
        <Version>1.0.0.1</Version>
        <!-- ... -->
    </PropertyGroup>
</Project>

How to check for null/empty/whitespace values with a single test?

SELECT column_name from table_name
WHERE RTRIM(ISNULL(column_name, '')) LIKE ''

ISNULL(column_name, '') will return '' if column_name is NULL, otherwise it will return column_name.

UPDATE

In Oracle, you can use NVL to achieve the same results.

SELECT column_name from table_name
WHERE RTRIM(NVL(column_name, '')) LIKE ''

What is the best way to get all the divisors of a number?

My solution via generator function is:

def divisor(num):
    for x in range(1, num + 1):
        if num % x == 0:
            yield x
    while True:
        yield None

Uninstall mongoDB from ubuntu

Sometimes this works;

sudo apt-get install mongodb-org --fix-missing --fix-broken
sudo apt-get autoremove mongodb-org --fix-missing --fix-broken

ERROR 1452: Cannot add or update a child row: a foreign key constraint fails

You must delete data in the child table which does not have any corresponding foreign key value to the parent table primary key .Or delete all data from the child table then insert new data having the same foreign key value as the primary key in the parent table . That should work . Here also a youtube video

Send file via cURL from form POST in PHP

For my the @ symbol did not work, so I do some research and found this way and it work for me, I hope this help you.

    $target_url = "http://server:port/xxxxx.php";           
    $fname = 'file.txt';   
    $cfile = new CURLFile(realpath($fname));

        $post = array (
                  'file' => $cfile
                  );    

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $target_url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");   
    curl_setopt($ch, CURLOPT_HTTPHEADER,array('Content-Type: multipart/form-data'));
    curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);   
    curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);  
    curl_setopt($ch, CURLOPT_TIMEOUT, 100);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

    $result = curl_exec ($ch);

    if ($result === FALSE) {
        echo "Error sending" . $fname .  " " . curl_error($ch);
        curl_close ($ch);
    }else{
        curl_close ($ch);
        echo  "Result: " . $result;
    }   

Removing index column in pandas when reading a csv

One thing that i do is df=df.reset_index() then df=df.drop(['index'],axis=1)

Saving ssh key fails

Your method should work fine on a Mac, but on Windows, two additional steps are necessary.

  1. Create a new folder in the desired location and name it ".ssh." (note the closing dot - this will vanish, but is required to create a folder beginning with ".")
  2. When prompted, use the file path format C:/Users/NAME/.ssh/id_rsa (note no closing dot on .ssh).

Saving the id_rsa key in this location should solve the permission error.

How to get the <html> tag HTML with JavaScript / jQuery?

In addition to some of the other answers, you could also access the HTML element via:

var htmlEl = document.body.parentNode;

Then you could get the inner HTML content:

var inner = htmlEl.innerHTML;

Doing so this way seems to be marginally faster. If you are just obtaining the HTML element, however, document.body.parentNode seems to be quite a bit faster.

After you have the HTML element, you can mess with the attributes with the getAttribute and setAttribute methods.

For the DOCTYPE, you could use document.doctype, which was elaborated upon in this question.

How to Upload Image file in Retrofit 2

@Multipart
@POST("user/updateprofile")
Observable<ResponseBody> updateProfile(@Part("user_id") RequestBody id,
                                       @Part("full_name") RequestBody fullName,
                                       @Part MultipartBody.Part image,
                                       @Part("other") RequestBody other);

//pass it like this
File file = new File("/storage/emulated/0/Download/Corrections 6.jpg");
RequestBody requestFile =
        RequestBody.create(MediaType.parse("multipart/form-data"), file);

// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part body =
        MultipartBody.Part.createFormData("image", file.getName(), requestFile);

// add another part within the multipart request
RequestBody fullName = 
        RequestBody.create(MediaType.parse("multipart/form-data"), "Your Name");

service.updateProfile(id, fullName, body, other);

Look at the way I am passing the multipart and string params. Hope this will help you!

Get integer value from string in swift

above answer didnt help me as my string value was "700.00"

with Swift 2.2 this works for me

let myString = "700.00"
let myInt = (myString as NSString).integerValue

I passed myInt to NSFormatterClass

let formatter = NSNumberFormatter()
formatter.numberStyle = .CurrencyStyle
formatter.maximumFractionDigits = 0

let priceValue = formatter.stringFromNumber(myInt!)!

//Now priceValue is ? 700

Thanks to this blog post.

How can I get session id in php and show it?

In the PHP file first you need to register the session

 <? session_start();
     $_SESSION['id'] = $userData['user_id'];?>

And in each page of your php application you can retrive the session id

 <? session_start()
    id =  $_SESSION['id'];
   ?>

Serial Port (RS -232) Connection in C++

Please take a look here:

1) You can use this with Windows (incl. MinGW) as well as Linux. Alternative you can only use the code as an example.

2) Step-by-step tutorial how to use serial ports on windows

3) You can use this literally on MinGW

Here's some very, very simple code (without any error handling or settings):

#include <windows.h>

/* ... */


// Open serial port
HANDLE serialHandle;

serialHandle = CreateFile("\\\\.\\COM1", GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);

// Do some basic settings
DCB serialParams = { 0 };
serialParams.DCBlength = sizeof(serialParams);

GetCommState(serialHandle, &serialParams);
serialParams.BaudRate = baudrate;
serialParams.ByteSize = byteSize;
serialParams.StopBits = stopBits;
serialParams.Parity = parity;
SetCommState(serialHandle, &serialParams);

// Set timeouts
COMMTIMEOUTS timeout = { 0 };
timeout.ReadIntervalTimeout = 50;
timeout.ReadTotalTimeoutConstant = 50;
timeout.ReadTotalTimeoutMultiplier = 50;
timeout.WriteTotalTimeoutConstant = 50;
timeout.WriteTotalTimeoutMultiplier = 10;

SetCommTimeouts(serialHandle, &timeout);

Now you can use WriteFile() / ReadFile() to write / read bytes. Don't forget to close your connection:

CloseHandle(serialHandle);

ADB - Android - Getting the name of the current activity

If you want to filter out only your app's activities currently running/paused, you can use this command:

adb shell dumpsys activity activities | grep 'Hist #' | grep 'YOUR_PACKAGE_NAME'

For example:

adb shell dumpsys activity activities | grep 'Hist #' | grep 'com.supercell.clashroyale'

The output will be something like:

* Hist #2: ActivityRecord{26ba44b u10 com.supercell.clashroyale/StartActivity t27770}
* Hist #1: ActivityRecord{2f3a0236 u10 com.supercell.clashroyale/SomeActivity t27770}
* Hist #0: ActivityRecord{20bbb4ae u10 com.supercell.clashroyale/OtherActivity t27770}

Do notice that the output shows the actual stack of activities i.e. the topmost activity is the one that is currently being displayed.

Convert string to boolean in C#

You must use some of the C # conversion systems:

string to boolean: True to true

string str = "True";
bool mybool = System.Convert.ToBoolean(str);

boolean to string: true to True

bool mybool = true;
string str = System.Convert.ToString(mybool);

//or

string str = mybool.ToString();

bool.Parse expects one parameter which in this case is str, even .

Convert.ToBoolean expects one parameter.

bool.TryParse expects two parameters, one entry (str) and one out (result).

If TryParse is true, then the conversion was correct, otherwise an error occurred

string str = "True";
bool MyBool = bool.Parse(str);

//Or

string str = "True";
if(bool.TryParse(str, out bool result))
{
   //Correct conversion
}
else
{
     //Incorrect, an error has occurred
}

What is the difference between task and thread?

In computer science terms, a Task is a future or a promise. (Some people use those two terms synonymously, some use them differently, nobody can agree on a precise definition.) Basically, a Task<T> "promises" to return you a T, but not right now honey, I'm kinda busy, why don't you come back later?

A Thread is a way of fulfilling that promise. But not every Task needs a brand-new Thread. (In fact, creating a thread is often undesirable, because doing so is much more expensive than re-using an existing thread from the thread pool. More on that in a moment.) If the value you are waiting for comes from the filesystem or a database or the network, then there is no need for a thread to sit around and wait for the data when it can be servicing other requests. Instead, the Task might register a callback to receive the value(s) when they're ready.

In particular, the Task does not say why it is that it takes such a long time to return the value. It might be that it takes a long time to compute, or it might that it takes a long time to fetch. Only in the former case would you use a Thread to run a Task. (In .NET, threads are freaking expensive, so you generally want to avoid them as much as possible and really only use them if you want to run multiple heavy computations on multiple CPUs. For example, in Windows, a thread weighs 12 KiByte (I think), in Linux, a thread weighs as little as 4 KiByte, in Erlang/BEAM even just 400 Byte. In .NET, it's 1 MiByte!)

Android: how to draw a border to a LinearLayout

Do you really need to do that programmatically?

Just considering the title: You could use a ShapeDrawable as android:background…

For example, let's define res/drawable/my_custom_background.xml as:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
  <corners
      android:radius="2dp"
      android:topRightRadius="0dp"
      android:bottomRightRadius="0dp"
      android:bottomLeftRadius="0dp" />
  <stroke
      android:width="1dp"
      android:color="@android:color/white" />
</shape>

and define android:background="@drawable/my_custom_background".

I've not tested but it should work.

Update:

I think that's better to leverage the xml shape drawable resource power if that fits your needs. With a "from scratch" project (for android-8), define res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/border"
    android:padding="10dip" >
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Hello World, SOnich"
        />
    [... more TextView ...]
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Hello World, SOnich"
        />
</LinearLayout>

and a res/drawable/border.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
   <stroke
        android:width="5dip"
        android:color="@android:color/white" />
</shape>

Reported to work on a gingerbread device. Note that you'll need to relate android:padding of the LinearLayout to the android:width shape/stroke's value. Please, do not use @android:color/white in your final application but rather a project defined color.

You could apply android:background="@drawable/border" android:padding="10dip" to each of the LinearLayout from your provided sample.

As for your other posts related to display some circles as LinearLayout's background, I'm playing with Inset/Scale/Layer drawable resources (see Drawable Resources for further information) to get something working to display perfect circles in the background of a LinearLayout but failed at the moment…

Your problem resides clearly in the use of getBorder.set{Width,Height}(100);. Why do you do that in an onClick method?

I need further information to not miss the point: why do you do that programmatically? Do you need a dynamic behavior? Your input drawables are png or ShapeDrawable is acceptable? etc.

To be continued (maybe tomorrow and as soon as you provide more precisions on what you want to achieve)…

"Unknown class <MyClass> in Interface Builder file" error at runtime

Per Apple Documentation

For 64-bit and iPhone OS applications, there is a linker bug that prevents -ObjC from loading objects files from static libraries that contain only categories and no classes. The workaround is to use the -all_load or -force_load flags.

In short add -all_load to "other linker" flags in your "Build Settings" and you should be good.

http://developer.apple.com/library/mac/qa/qa1490/_index.html

Cancel a UIView animation?

Simplest way to stop all animations on a particular view, immediately, is this:

Link the project to QuartzCore.framework. At the start of your code:

#import <QuartzCore/QuartzCore.h>

Now, when you want to stop all animations on a view dead in their tracks, say this:

[CATransaction begin];
[theView.layer removeAllAnimations];
[CATransaction commit];

The middle line would work all by itself, but there's a delay until the runloop finishes (the "redraw moment"). To prevent that delay, wrap the command in an explicit transaction block as shown. This works provided no other changes have been performed on this layer in the current runloop.

json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190)

This error can also show up if there are parts in your string that json.loads() does not recognize. An in this example string, an error will be raised at character 27 (char 27).

string = """[{"Item1": "One", "Item2": False}, {"Item3": "Three"}]"""

My solution to this would be to use the string.replace() to convert these items to a string:

import json

string = """[{"Item1": "One", "Item2": False}, {"Item3": "Three"}]"""

string = string.replace("False", '"False"')

dict_list = json.loads(string)

How to uncompress a tar.gz in another directory

You can use for loop to untar multiple .tar.gz files to another folder. The following code will take /destination/folder/path as an argument to the script and untar all .tar.gz files present at the current location in /destination/folder/path.

if [ $# -ne 1 ];
 then
 echo "invalid argument/s"
 echo "Usage: ./script-file-name.sh /target/directory"
 exit 0
fi
for file in *.tar.gz
do
    tar -zxvf "$file" --directory $1
done

Node - was compiled against a different Node.js version using NODE_MODULE_VERSION 51

I had a similar problem with robotjs. There were some deprecated code that required node v11, but I had already compiled electron code on v12. So I got basically the same error. Nothing here worked as I was basically trying to rebuild electron and my other dependencies into node v11 from v12.

Here is what I did (part of this is based on chitzui's answer, credit where credit is due):

  • Back up package.json
  • completely delete the node_modules folder
  • completely delete package_lock.json
  • delete package.json (will reinit later)
  • Close any open editors and other cmd windows that are in the project's directory.
  • run npm init to reinit package, then missing data with old backed up package.json
  • run npm i
  • fixed :)

Hope this helps.

How to read xml file contents in jQuery and display in html elements?

You can use $.each()

Suppose your xml is

<Cloudtags><id>1</id></Cloudtags><Cloudtags><id>2</id></Cloudtags><Cloudtags><id>3</id></Cloudtags>

In your Ajax success

success: function (xml) {
    $(xml).find('Cloudtags').each(function(){// your outer tag of xml
         var id = $(this).find("id").text(); // 
    });
}

For your case

success: function (xml) {
        $(xml).find('person').each(function(){// your outer tag of xml
             var name = $(this).find("name").text(); // 
             var age = $(this).find("age").text();
        });
    }

Difference between EXISTS and IN in SQL?

The Exists keyword evaluates true or false, but IN keyword compare all value in the corresponding sub query column. Another one Select 1 can be use with Exists command. Example:

SELECT * FROM Temp1 where exists(select 1 from Temp2 where conditions...)

But IN is less efficient so Exists faster.

Split string into array of characters?

You can just assign the string to a byte array (the reverse is also possible). The result is 2 numbers for each character, so Xmas converts to a byte array containing {88,0,109,0,97,0,115,0}
or you can use StrConv

Dim bytes() as Byte
bytes = StrConv("Xmas", vbFromUnicode)

which will give you {88,109,97,115} but in that case you cannot assign the byte array back to a string.
You can convert the numbers in the byte array back to characters using the Chr() function

Convert a space delimited string to list

try

states.split()

it returns the list

['Alaska',
 'Alabama',
 'Arkansas',
 'American',
 'Samoa',
 'Arizona',
 'California',
 'Colorado']

and this returns the random element of the list

import random
random.choice(states.split())

split statement parses the string and returns the list, by default it's divided into the list by spaces, if you specify the string it's divided by this string, so for example

states.split('Ari')

returns

['Alaska Alabama Arkansas American Samoa ', 'zona California Colorado']

Btw, list is in python interpretated with [] brackets instead of {} brackets, {} brackets are used for dictionaries, you can read more on this here

I see you are probably new to python, so I'd give you some advice how to use python's great documentation

Almost everything you need can be found here You can use also python included documentation, open python console and write help() If you don't know what to do with some object, I'd install ipython, write statement and press Tab, great tool which helps you with interacting with the language

I just wrote this here to show that python is great tool also because it's great documentation and it's really powerful to know this

git stash and git pull

When you have changes on your working copy, from command line do:

git stash 

This will stash your changes and clear your status report

git pull

This will pull changes from upstream branch. Make sure it says fast-forward in the report. If it doesn't, you are probably doing an unintended merge

git stash pop

This will apply stashed changes back to working copy and remove the changes from stash unless you have conflicts. In the case of conflict, they will stay in stash so you can start over if needed.

if you need to see what is in your stash

git stash list

Create comma separated strings C#?

You could override your object's ToString() method:

public override string ToString ()
{
    return string.Format ("{0},{1},{2}", this.number, this.id, this.whatever);
}

Convert Base64 string to an image file?

$datetime = date("Y-m-d h:i:s");
$timestamp = strtotime($datetime);
$image = $_POST['image'];
$imgdata = base64_decode($image);
$f = finfo_open();
$mime_type = finfo_buffer($f, $imgdata, FILEINFO_MIME_TYPE);
$temp=explode('/',$mime_type);
$path = "uploads/$timestamp.$temp[1]";
file_put_contents($path,base64_decode($image));
echo "Successfully Uploaded->>> $timestamp.$temp[1]";

This will be enough for image processing. Special thanks to Mr. Dev Karan Sharma

Print multiple arguments in Python

Use f-string:

print(f'Total score for {name} is {score}')

Or

Use .format:

print("Total score for {} is {}".format(name, score))

Convert an NSURL to an NSString

You can use any one way

NSString *string=[NSString stringWithFormat:@"%@",url1];

or

NSString *str=[url1 absoluteString];

NSLog(@"string :: %@",string);

string :: file:///var/containers/Bundle/Application/E2D7570B-D5A6-45A0-8EAAA1F7476071FE/RemoDuplicateMedia.app/loading_circle_animation.gif

NSLog(@"str :: %@", str);

str :: file:///var/containers/Bundle/Application/E2D7570B-D5A6-45A0-8EAA-A1F7476071FE/RemoDuplicateMedia.app/loading_circle_animation.gif

Byte[] to InputStream or OutputStream

output = new ByteArrayOutputStream();
...
input = new ByteArrayInputStream( output.toByteArray() )

What is the difference between connection and read timeout for sockets?

These are timeout values enforced by JVM for TCP connection establishment and waiting on reading data from socket.

If the value is set to infinity, you will not wait forever. It simply means JVM doesn't have timeout and OS will be responsible for all the timeouts. However, the timeouts on OS may be really long. On some slow network, I've seen timeouts as long as 6 minutes.

Even if you set the timeout value for socket, it may not work if the timeout happens in the native code. We can reproduce the problem on Linux by connecting to a host blocked by firewall or unplugging the cable on switch.

The only safe approach to handle TCP timeout is to run the connection code in a different thread and interrupt the thread when it takes too long.

How do I get unique elements in this array?

You can just use the method uniq. Assuming your array is ary, call:

ary.uniq{|x| x.user_id}

and this will return a set with unique user_ids.

Apache POI Excel - how to configure columns to be expanded?

I use below simple solution:

This is your workbook and sheet:

XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("YOUR Workshhet");

then add data to your sheet with columns and rows. Once done with adding data to sheet write following code to autoSizeColumn width.

for (int columnIndex = 0; columnIndex < 15; columnIndex++) {
                    sheet.autoSizeColumn(columnIndex);
                }

Here, instead 15, you add the number of columns in your sheet.

Hope someone helps this.

Is it possible to get a list of files under a directory of a website? How?

There are only two ways to find a web page: through a link or by listing the directory.

Usually, web servers disable directory listing, so if there is really no link to the page, then it cannot be found.

BUT: information about the page may get out in ways you don't expect. For example, if a user with Google Toolbar visits your page, then Google may know about the page, and it can appear in its index. That will be a link to your page.

Redirect with CodeIgniter

Here is .htacess file that hide index file

#RewriteEngine on
#RewriteCond $1 !^(index\.php|images|robots\.txt)
#RewriteRule ^(.*)$ /index.php/$1 [L]

<IfModule mod_rewrite.c>
        RewriteEngine On
        RewriteBase /

        # Removes index.php from ExpressionEngine URLs
        RewriteCond %{THE_REQUEST} ^GET.*index\.php [NC]
        RewriteCond %{REQUEST_URI} !/system/.* [NC]
        RewriteRule (.*?)index\.php/*(.*) /$1$2 [R=301,NE,L]

        # Directs all EE web requests through the site index file
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>

Using NULL in C++?

Assuming that you don't have a library or system header that defines NULL as for example (void*)0 or (char*)0 it's fine. I always tend to use 0 myself as it is by definition the null pointer. In c++0x you'll have nullptr available so the question won't matter as much anymore.

Video file formats supported in iPhone

Short answer: H.264 MPEG (MP4)

Long answer from Apple.com:

Video formats supported: H.264 video, up to 1.5 Mbps, 640 by 480 pixels, 30 frames per second,

Low-Complexity version of the H.264 Baseline Profile with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats; H.264 video, up to 2.5 Mbps, 640 by 480 pixels, 30 frames per second,

Baseline Profile up to Level 3.0 with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats; MPEG-4 video, up to 2.5 Mbps, 640 by 480 pixels, 30 frames per second,

Simple Profile with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats

http://www.apple.com/iphone/specs.html

Model backing a DB Context has changed; Consider Code First Migrations

To solve this error write the the following code in Application_Start() Method in Global.asax.cs file

Database.SetInitializer<MyDbContext>(null);

Sleep function in ORACLE

There is a good article on this topic: PL/SQL: Sleep without using DBMS_LOCK that helped me out. I used Option 2 wrapped in a custom package. Proposed solutions are:

Option 1: APEX_UTIL.sleep

If APEX is installed you can use the procedure “PAUSE” from the publicly available package APEX_UTIL.

Example – “Wait 5 seconds”:

SET SERVEROUTPUT ON ;
BEGIN
    DBMS_OUTPUT.PUT_LINE('Start ' || to_char(SYSDATE, 'YYYY-MM-DD HH24:MI:SS'));
    APEX_UTIL.PAUSE(5);
    DBMS_OUTPUT.PUT_LINE('End   ' || to_char(SYSDATE, 'YYYY-MM-DD HH24:MI:SS'));
END;
/

Option 2: java.lang.Thread.sleep

An other option is the use of the method “sleep” from the Java class “Thread”, which you can easily use through providing a simple PL/SQL wrapper procedure:

Note: Please remember, that “Thread.sleep” uses milliseconds!

--- create ---
CREATE OR REPLACE PROCEDURE SLEEP (P_MILLI_SECONDS IN NUMBER) 
AS LANGUAGE JAVA NAME 'java.lang.Thread.sleep(long)';

--- use ---
SET SERVEROUTPUT ON ;
BEGIN
    DBMS_OUTPUT.PUT_LINE('Start ' || to_char(SYSDATE, 'YYYY-MM-DD HH24:MI:SS'));
    SLEEP(5 * 1000);
    DBMS_OUTPUT.PUT_LINE('End   ' || to_char(SYSDATE, 'YYYY-MM-DD HH24:MI:SS'));
END;
/

Correct way to quit a Qt program?

//How to Run App

bool ok = QProcess::startDetached("C:\\TTEC\\CozxyLogger\\CozxyLogger.exe");
qDebug() <<  "Run = " << ok;


//How to Kill App

system("taskkill /im CozxyLogger.exe /f");
qDebug() << "Close";

example

PostgreSQL IF statement

Just to help if anyone stumble on this question like me, if you want to use if in PostgreSQL, you use "CASE"

select 
    case
        when stage = 1 then 'running'
        when stage = 2 then 'done'
        when stage = 3 then 'stopped'
    else 
        'not running'
    end as run_status from processes

What exactly are iterator, iterable, and iteration?

Iterables have a __iter__ method that instantiates a new iterator every time.

Iterators implement a __next__ method that returns individual items, and a __iter__ method that returns self .

Therefore, iterators are also iterable, but iterables are not iterators.

Luciano Ramalho, Fluent Python.

How to implement one-to-one, one-to-many and many-to-many relationships while designing tables?

One to one (1-1) relationship: This is relationship between primary & foreign key (primary key relating to foreign key only one record). this is one to one relationship.

One to Many (1-M) relationship: This is also relationship between primary & foreign keys relationships but here primary key relating to multiple records (i.e. Table A have book info and Table B have multiple publishers of one book).

Many to Many (M-M): Many to many includes two dimensions, explained fully as below with sample.

-- This table will hold our phone calls.
CREATE TABLE dbo.PhoneCalls
(
   ID INT IDENTITY(1, 1) NOT NULL,
   CallTime DATETIME NOT NULL DEFAULT GETDATE(),
   CallerPhoneNumber CHAR(10) NOT NULL
)
-- This table will hold our "tickets" (or cases).
CREATE TABLE dbo.Tickets
(
   ID INT IDENTITY(1, 1) NOT NULL,
   CreatedTime DATETIME NOT NULL DEFAULT GETDATE(),
   Subject VARCHAR(250) NOT NULL,
   Notes VARCHAR(8000) NOT NULL,
   Completed BIT NOT NULL DEFAULT 0
)
-- This table will link a phone call with a ticket.
CREATE TABLE dbo.PhoneCalls_Tickets
(
   PhoneCallID INT NOT NULL,
   TicketID INT NOT NULL
)

Session variables in ASP.NET MVC

There are 3 ways to do it.

  1. You can directly access HttpContext.Current.Session

  2. You can Mock HttpContextBase

  3. Create a extension method for HttpContextBase

I prefer 3rd way.This link is good reference.

Get/Set HttpContext Session Methods in BaseController vs Mocking HttpContextBase to create Get/Set methods

'uint32_t' identifier not found error

There is an implementation available at the msinttypes project page - "This project fills the absence of stdint.h and inttypes.h in Microsoft Visual Studio".

I don't have experience with this implementation, but I've seen it recommended by others on SO.

Getting vertical gridlines to appear in line plot in matplotlib

According to matplotlib documentation, The signature of the Axes class grid() method is as follows:

Axes.grid(b=None, which='major', axis='both', **kwargs)
Turn the axes grids on or off.

which can be ‘major’ (default), ‘minor’, or ‘both’ to control whether major tick grids, minor tick grids, or both are affected.

axis can be ‘both’ (default), ‘x’, or ‘y’ to control which set of gridlines are drawn.

So in order to show grid lines for both the x axis and y axis, we can use the the following code:

ax = plt.gca()
ax.grid(which='major', axis='both', linestyle='--')

This method gives us finer control over what to show for grid lines.

How to install JQ on Mac by command-line?

You can install any application/packages with brew on mac. If you want to know the exact command just search your package on https://brewinstall.org and you will get the set of commands needed to install that package.

First open terminal and install brew

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" < /dev/null 2> /dev/null

Now Install jq

brew install jq

Show percent % instead of counts in charts of categorical variables

Note that if your variable is continuous, you will have to use geom_histogram(), as the function will group the variable by "bins".

df <- data.frame(V1 = rnorm(100))

ggplot(df, aes(x = V1)) +  
  geom_histogram(aes(y = 100*(..count..)/sum(..count..))) 

# if you use geom_bar(), with factor(V1), each value of V1 will be treated as a
# different category. In this case this does not make sense, as the variable is 
# really continuous. With the hp variable of the mtcars (see previous answer), it 
# worked well since hp was not really continuous (check unique(mtcars$hp)), and one 
# can want to see each value of this variable, and not to group it in bins.
ggplot(df, aes(x = factor(V1))) +  
  geom_bar(aes(y = (..count..)/sum(..count..))) 

How to install Ruby 2.1.4 on Ubuntu 14.04

update ubuntu:

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

Install rvm, which manages the ruby versions:

to install rvm use the following command.

 \curl -sSL https://get.rvm.io | bash -s stable
 source ~/.bash_profile
 rvm install ruby-2.1.4

Check ruby versions installed and in use:

rvm list
rvm use --default ruby-2.1.4

RecyclerView expand/collapse items

For this, just needed simple lines not complicated

in your onBindViewHolder method add below code

final boolean isExpanded = position==mExpandedPosition;
holder.details.setVisibility(isExpanded?View.VISIBLE:View.GONE);
holder.itemView.setActivated(isExpanded);
holder.itemView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        mExpandedPosition = isExpanded ? -1:position;
        notifyItemChanged(position);
    }
});

mExpandedPosition is an int global variable initialized to -1

For those who want only one item expanded and others get collapsed. Use this

first declare a global variable with previousExpandedPosition = -1

then

    final boolean isExpanded = position==mExpandedPosition;
    holder.details.setVisibility(isExpanded?View.VISIBLE:View.GONE);
    holder.itemView.setActivated(isExpanded);

    if (isExpanded)
       previousExpandedPosition = position;

    holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mExpandedPosition = isExpanded ? -1:position;
            notifyItemChanged(previousExpandedPosition);
            notifyItemChanged(position);
        }
    });

Done!!!. Simple and humble .. :)

How can I get all the request headers in Django?

Starting from Django 2.2, you can use request.headers to access the HTTP headers. From the documentation on HttpRequest.headers:

A case insensitive, dict-like object that provides access to all HTTP-prefixed headers (plus Content-Length and Content-Type) from the request.

The name of each header is stylized with title-casing (e.g. User-Agent) when it’s displayed. You can access headers case-insensitively:

>>> request.headers
{'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6', ...}

>>> 'User-Agent' in request.headers
True
>>> 'user-agent' in request.headers
True

>>> request.headers['User-Agent']
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)
>>> request.headers['user-agent']
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)

>>> request.headers.get('User-Agent')
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)
>>> request.headers.get('user-agent')
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)

To get all headers, you can use request.headers.keys() or request.headers.items().

Trusting all certificates with okHttp

SSLSocketFactory does not expose its X509TrustManager, which is a field that OkHttp needs to build a clean certificate chain. This method instead must use reflection to extract the trust manager. Applications should prefer to call sslSocketFactory(SSLSocketFactory, X509TrustManager), which avoids such reflection.

Source: OkHttp documentation

OkHttpClient.Builder builder = new OkHttpClient.Builder();

builder.sslSocketFactory(sslContext.getSocketFactory(),
    new X509TrustManager() {
        @Override
        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return new java.security.cert.X509Certificate[]{};
        }
    });

Node.js - How to send data from html to express

I'd like to expand on Obertklep's answer. In his example it is an NPM module called body-parser which is doing most of the work. Where he puts req.body.name, I believe he/she is using body-parser to get the contents of the name attribute(s) received when the form is submitted.

If you do not want to use Express, use querystring which is a built-in Node module. See the answers in the link below for an example of how to use querystring.

It might help to look at this answer, which is very similar to your quest.

Error with multiple definitions of function

This problem happens because you are calling fun.cpp instead of fun.hpp. So c++ compiler finds func.cpp definition twice and throws this error.

Change line 3 of your main.cpp file, from #include "fun.cpp" to #include "fun.hpp" .

Does "display:none" prevent an image from loading?

HTML5 <picture> tag will help you to resolve the right image source depending on the screen width

Apparently the browsers behaviour hasn't changed much over the past 5 years and many would still download the hidden images, even if there was a display: none property set on them.

Even though there's a media queries workaround, it could only be useful when the image was set as a background in the CSS.

While I was thinking that there's just a JS solution to the problem (lazy load, picturefill, etc.), it appeared that there's a nice pure HTML solution that comes out of the box with HTML5.

And that is the <picture> tag.

Here's how MDN describes it:

The HTML <picture> element is a container used to specify multiple <source> elements for a specific <img> contained in it. The browser will choose the most suitable source according to the current layout of the page (the constraints of the box the image will appear in) and the device it will be displayed on (e.g. a normal or hiDPI device.)

And here's how to use it:

<picture>
 <source srcset="mdn-logo-wide.png" media="(min-width: 600px)">
 <img src="mdn-logo-narrow.png" alt="MDN">
</picture>

The logic behind

The browser would load the source of the img tag, only if none of the media rules applies. When the <picture> element is not supported by the browser, it will again fallback to showing the img tag.

Normally you'd put the smallest image as the source of the <img> and thus not load the heavy images for larger screens. Vice versa, if a media rule applies, the source of the <img> will not be downloaded, instead it will download the url's contents of the corresponding <source> tag.

Only pitfall here is that if the element is not supported by the browser, it will only load the small image. On the other hand in 2017 we ought to think and code in the mobile first approach.

And before someone got too exited, here's the current browser support for <picture>:

Desktop browsers

Desktop browsers support

Mobile browsers

Mobile browsers support

More about the browser support you can find on Can I use.

The good thing is that html5please's sentence is to use it with a fallback. And I personally intend to take their advise.

More about the tag you can find in the W3C's specification. There's a disclaimer there, which I find important to mention:

The picture element is somewhat different from the similar-looking video and audio elements. While all of them contain source elements, the source element’s src attribute has no meaning when the element is nested within a picture element, and the resource selection algorithm is different. As well, the picture element itself does not display anything; it merely provides a context for its contained img element that enables it to choose from multiple URLs.

So what it says is that it only helps you improve the performance when loading an image, by providing some context to it.

And you can still use some CSS magic in order to hide the image on small devices:

<style>
  picture { display: none; }

  @media (min-width: 600px) {
    picture {
      display: block;
    }
  }
</style>

<picture>
 <source srcset="the-real-image-source" media="(min-width: 600px)">
 <img src="a-1x1-pixel-image-that-will-be-hidden-in-the-css" alt="MDN">
</picture>

Thus the browser will not display the actual image and will only download the 1x1 pixel image (which can be cached if you use it more than once). Be aware, though, that if the <picture> tag is not supported by the browser, even on descktop screens the actual image won't be displayed (so you'll definitely need a polyfill backup there).

How do I remove the horizontal scrollbar in a div?

If you don't have anything overflowing horizontally, you can also just use

overflow: auto;

and it will only show scrollbars when needed.

See The CSS Overflow Property

"Char cannot be dereferenced" error

If Character.isLetter(ch) looks a bit wordy/ugly you can use a static import.

import static java.lang.Character.*;


if(isLetter(ch)) {

} else if(isDigit(ch)) {

} 

Navigate to another page with a button in angular 2

Having the router link on the button seems to work fine for me:

<button class="nav-link" routerLink="/" (click)="hideMenu()">
     <i class="fa fa-home"></i> 
     <span>Home</span>
</button>

Big-oh vs big-theta

Bonus: why do people seemingly always use big-oh when talking informally?

Because in big-oh, this loop:

for i = 1 to n do
    something in O(1) that doesn't change n and i and isn't a jump

is O(n), O(n^2), O(n^3), O(n^1423424). big-oh is just an upper bound, which makes it easier to calculate because you don't have to find a tight bound.

The above loop is only big-theta(n) however.

What's the complexity of the sieve of eratosthenes? If you said O(n log n) you wouldn't be wrong, but it wouldn't be the best answer either. If you said big-theta(n log n), you would be wrong.

Get MIME type from filename extension

For ASP.NET or other

The options were changed a bit in ASP.NET Core, here they are (credits):

  • new FileExtensionContentTypeProvider().TryGetContentType(fileName, out contentType); (vNext only)
    • Never tested, but looks like you can officially expand the mime types list via the exposed Mappings property.
  • Use the MimeTypes NuGet package
  • Copy the MimeMappings file from the reference source of the .NET Framework

For .NET Framework >= 4.5:

Use the System.Web.MimeMapping.GetMimeMapping method, that is part of the BCL in .NET Framework 4.5:

string mimeType = MimeMapping.GetMimeMapping(fileName);

If you need to add custom mappings you probably can use reflection to add mappings to the BCL MimeMapping class, it uses a custom dictionary that exposes this method, so you should invoke the following to add mappings (never tested tho, but should prob. work).

Anyway, when using reflection to add MIME types, be aware that since you're accessing a private field, its name might change or even be totally removed, so you should be extra cautious and add double checks and provide fail safe action for every step.

MimeMapping._mappingDictionary.AddMapping(string fileExtension, string mimeType)

Set selected radio from radio group with a value

With the help of the attribute selector you can select the input element with the corresponding value. Then you have to set the attribute explicitly, using .attr:

var value = 5;
$("input[name=mygroup][value=" + value + "]").attr('checked', 'checked');

Since jQuery 1.6, you can also use the .prop method with a boolean value (this should be the preferred method):

$("input[name=mygroup][value=" + value + "]").prop('checked', true);

Remember you first need to remove checked attribute from any of radio buttons under one radio buttons group only then you will be able to add checked property / attribute to one of the radio button in that radio buttons group.

Code To Remove Checked Attribute from all radio buttons of one radio button group -

$('[name="radioSelectionName"]').removeAttr('checked');

"Large data" workflows using pandas

I recently came across a similar issue. I found simply reading the data in chunks and appending it as I write it in chunks to the same csv works well. My problem was adding a date column based on information in another table, using the value of certain columns as follows. This may help those confused by dask and hdf5 but more familiar with pandas like myself.

def addDateColumn():
"""Adds time to the daily rainfall data. Reads the csv as chunks of 100k 
   rows at a time and outputs them, appending as needed, to a single csv. 
   Uses the column of the raster names to get the date.
"""
    df = pd.read_csv(pathlist[1]+"CHIRPS_tanz.csv", iterator=True, 
                     chunksize=100000) #read csv file as 100k chunks

    '''Do some stuff'''

    count = 1 #for indexing item in time list 
    for chunk in df: #for each 100k rows
        newtime = [] #empty list to append repeating times for different rows
        toiterate = chunk[chunk.columns[2]] #ID of raster nums to base time
        while count <= toiterate.max():
            for i in toiterate: 
                if i ==count:
                    newtime.append(newyears[count])
            count+=1
        print "Finished", str(chunknum), "chunks"
        chunk["time"] = newtime #create new column in dataframe based on time
        outname = "CHIRPS_tanz_time2.csv"
        #append each output to same csv, using no header
        chunk.to_csv(pathlist[2]+outname, mode='a', header=None, index=None)

Calculate days between two Dates in Java 8

Here you go:

public class DemoDate {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();
        System.out.println("Current date: " + today);

        //add 1 month to the current date
        LocalDate date2 = today.plus(1, ChronoUnit.MONTHS);
        System.out.println("Next month: " + date2);

        // Put latest date 1st and old date 2nd in 'between' method to get -ve date difference
        long daysNegative = ChronoUnit.DAYS.between(date2, today);
        System.out.println("Days : "+daysNegative);

        // Put old date 1st and new date 2nd in 'between' method to get +ve date difference
        long datePositive = ChronoUnit.DAYS.between(today, date2);
        System.out.println("Days : "+datePositive);
    }
}

How to use PowerShell select-string to find more than one pattern in a file?

To search for multiple matches in each file, we can sequence several Select-String calls:

Get-ChildItem C:\Logs |
  where { $_ | Select-String -Pattern 'VendorEnquiry' } |
  where { $_ | Select-String -Pattern 'Failed' } |
  ...

At each step, files that do not contain the current pattern will be filtered out, ensuring that the final list of files contains all of the search terms.

Rather than writing out each Select-String call manually, we can simplify this with a filter to match multiple patterns:

filter MultiSelect-String( [string[]]$Patterns ) {
  # Check the current item against all patterns.
  foreach( $Pattern in $Patterns ) {
    # If one of the patterns does not match, skip the item.
    $matched = @($_ | Select-String -Pattern $Pattern)
    if( -not $matched ) {
      return
    }
  }

  # If all patterns matched, pass the item through.
  $_
}

Get-ChildItem C:\Logs | MultiSelect-String 'VendorEnquiry','Failed',...


Now, to satisfy the "Logtime about 11:30 am" part of the example would require finding the log time corresponding to each failure entry. How to do this is highly dependent on the actual structure of the files, but testing for "about" is relatively simple:

function AboutTime( [DateTime]$time, [DateTime]$target, [TimeSpan]$epsilon ) {
  $time -le ($target + $epsilon) -and $time -ge ($target - $epsilon)
}

PS> $epsilon = [TimeSpan]::FromMinutes(5)
PS> $target = [DateTime]'11:30am'
PS> AboutTime '11:00am' $target $epsilon
False
PS> AboutTime '11:28am' $target $epsilon
True
PS> AboutTime '11:35am' $target $epsilon
True

What are the safe characters for making URLs?

From an SEO perspective, hyphens are preferred over underscores. Convert to lowercase, remove all apostrophes, then replace all non-alphanumeric strings of characters with a single hyphen. Trim excess hyphens off the start and finish.

How do I overload the square-bracket operator in C#?

For CLI C++ (compiled with /clr) see this MSDN link.

In short, a property can be given the name "default":

ref class Class
{
 public:
  property System::String^ default[int i]
  {
    System::String^ get(int i) { return "hello world"; }
  }
};

How to check if a row exists in MySQL? (i.e. check if an email exists in MySQL)

There are multiple ways to check if a value exists in the database. Let me demonstrate how this can be done properly with PDO and mysqli.

PDO

PDO is the simpler option. To find out whether a value exists in the database you can use prepared statement and fetchColumn(). There is no need to fetch any data so we will only fetch 1 if the value exists.

<?php

// Connection code. 
$options = [
    \PDO::ATTR_ERRMODE            => \PDO::ERRMODE_EXCEPTION,
    \PDO::ATTR_EMULATE_PREPARES   => false,
];
$pdo = new \PDO('mysql:host=localhost;port=3306;dbname=test;charset=utf8mb4', 'testuser', 'password', $options);

// Prepared statement
$stmt = $pdo->prepare('SELECT 1 FROM tblUser WHERE email=?');
$stmt->execute([$_POST['email']]);
$exists = $stmt->fetchColumn(); // either 1 or null

if ($exists) {
    echo 'Email exists in the database.';
} else {
    // email doesn't exist yet
}

For more examples see: How to check if email exists in the database?

MySQLi

As always mysqli is a little more cumbersome and more restricted, but we can follow a similar approach with prepared statement.

<?php

// Connection code
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new \mysqli('localhost', 'testuser', 'password', 'test');
$mysqli->set_charset('utf8mb4');

// Prepared statement
$stmt = $mysqli->prepare('SELECT 1 FROM tblUser WHERE email=?');
$stmt->bind_param('s', $_POST['email']);
$stmt->execute();
$exists = (bool) $stmt->get_result()->fetch_row(); // Get the first row from result and cast to boolean

if ($exists) {
    echo 'Email exists in the database.';
} else {
    // email doesn't exist yet
}

Instead of casting the result row(which might not even exist) to boolean, you can also fetch COUNT(1) and read the first item from the first row using fetch_row()[0]

For more examples see: How to check whether a value exists in a database using mysqli prepared statements

Minor remarks

  • If someone suggests you to use mysqli_num_rows(), don't listen to them. This is a very bad approach and could lead to performance issues if misused.
  • Don't use real_escape_string(). This is not meant to be used as a protection against SQL injection. If you use prepared statements correctly you don't need to worry about any escaping.
  • If you want to check if a row exists in the database before you try to insert a new one, then it is better not to use this approach. It is better to create a unique key in the database and let it throw an exception if a duplicate value exists.

Why are unnamed namespaces used and what are their benefits?

Having something in an anonymous namespace means it's local to this translation unit (.cpp file and all its includes) this means that if another symbol with the same name is defined elsewhere there will not be a violation of the One Definition Rule (ODR).

This is the same as the C way of having a static global variable or static function but it can be used for class definitions as well (and should be used rather than static in C++).

All anonymous namespaces in the same file are treated as the same namespace and all anonymous namespaces in different files are distinct. An anonymous namespace is the equivalent of:

namespace __unique_compiler_generated_identifer0x42 {
    ...
}
using namespace __unique_compiler_generated_identifer0x42;

Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

Had an similar issue embeding youtube chat and I figure it out. Maybe there is a similar solution for similar problem.

Refused to display 'https://www.youtube.com/live_chat?v=yDc9BonIXXI&embed_domain=your.domain.web' in a frame because it set 'X-Frame-Options' to 'sameorigin'

My webpage works with www and without it. So to make it work you need to make sure you load the one that is listed on the embed_domain= value... Maybe there is a variable your missing to tell where to embed your iframe. To fix my problem had to write a script to detect the right webpage and execute proper iframe embed domain name.

<iframe src='https://www.youtube.com/live_chat?v=yDc9BonIXXI&embed_domain=your.domain.web' width="100%" height="600" frameborder='no' scrolling='no'></iframe>

or

<iframe src='https://www.youtube.com/live_chat?v=yDc9BonIXXI&embed_domain=www.your.domain.web' width="100%" height="600" frameborder='no' scrolling='no'></iframe>

Understand you are not using iframes, but still there may be some variable you need to add to your syntax to tell it where the script is going to be used.

How can I access Oracle from Python?

Note if you are using pandas you can access it in following way:

import pandas as pd
import cx_Oracle
conn= cx_Oracle.connect('username/pwd@host:port/service_name')
try:
    query = '''
         SELECT * from dual
             '''
    df = pd.read_sql(con = conn, sql = query)
finally:
    conn.close()
df.head()

How do I open workbook programmatically as read-only?

Check out the language reference:

http://msdn.microsoft.com/en-us/library/aa195811(office.11).aspx

expression.Open(FileName, UpdateLinks, ReadOnly, Format, Password, WriteResPassword, IgnoreReadOnlyRecommended, Origin, Delimiter, Editable, Notify, Converter, AddToMru, Local, CorruptLoad)

How do I remove the old history from a git repository?

I needed to read several answers and some other info to understand what I was doing.

1. Ignore everything older than a certain commit

The file .git/info/grafts can define fake parents for a commit. A line with just a commit id, says that the commit doesn't have a parent. If we wanted to say that we care only about the last 2000 commits, we can type:

git rev-parse HEAD~2000 > .git/info/grafts

git rev-parse gives us the commit id of the 2000th parent of the current commit. The above command will overwrite the grafts file if present. Check if it's there first.

2. Rewrite the Git history (optional)

If you want to make this grafted fake parent a real one, then run:

git filter-branch -- --all

It will change all commit ids. Every copy of this repository needs to be updated forcefully.

3. Clean up disk space

I didn't done step 2, because I wanted my copy to stay compatible with the upstream. I just wanted to save some disk space. In order to forget all the old commits:

git prune
git gc

Alternative: shallow copies

If you have a shallow copy of another repository and just want to save some disk space, you can update .git/shallow. But be careful that nothing is pointing at a commit from before. So you could run something like this:

git fetch --prune
git rev-parse HEAD~2000 > .git/shallow
git prune
git gc

The entry in shallow works like a graft. But be careful not to use grafts and shallow at the same time. At least, don't have the same entries in there, it will fail.

If you still have some old references (tags, branches, remote heads) that point to older commits, they won't be cleaned up and you won't save more disk space.

How to validate email id in angularJs using ng-pattern

According to the answer of @scx ,I created a validation for GUI

app.directive('validateEmail', function() {
  var EMAIL_REGEXP = /^[_a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
  return {
    link: function(scope, elm) {
      elm.on("keyup",function(){
            var isMatchRegex = EMAIL_REGEXP.test(elm.val());
            if( isMatchRegex&& elm.hasClass('warning') || elm.val() == ''){
              elm.removeClass('warning');
            }else if(isMatchRegex == false && !elm.hasClass('warning')){
              elm.addClass('warning');
            }
      });
    }
  }
});

And simply add :

css

.warning{
   border:1px solid red;
 }

html

<input type='email' validate-email name='email' id='email' ng-model='email' required>

Count frequency of words in a list and sort by frequency

use this

from collections import Counter
list1=['apple','egg','apple','banana','egg','apple']
counts = Counter(list1)
print(counts)
# Counter({'apple': 3, 'egg': 2, 'banana': 1})

How do I fix "for loop initial declaration used outside C99 mode" GCC error?

Jihene Stambouli answered OP question most directly... Question was; why does

for(int i = low; i <= high; ++i)
{
    res = runalg(i);
    if (res > highestres)
    {
        highestres = res;
    }
}

produce the error;

3np1.c:15: error: 'for' loop initial declaration used outside C99 mode

for which the answer is

for(int i = low...

should be

int i;
for (i=low...