Programs & Examples On #Yahoo finance

PLEASE NOTE : THIS API HAS BEEN DISCONTINUED BY YAHOO. Yahoo! Finance is a service from Yahoo! that provides financial information. It is the top financial news and research website in the United States.

Download history stock prices automatically from yahoo finance in python

It's trivial when you know how:

import yfinance as yf
df = yf.download('CVS', '2015-01-01')
df.to_csv('cvs-health-corp.csv')

If you wish to plot it:

import finplot as fplt
fplt.candlestick_ochl(df[['Open','Close','High','Low']])
fplt.show()

enter image description here

How to get a complete list of ticker symbols from Yahoo Finance?

I have been researching this for a few days, following endless leads that got close, but not quite, to what I was after.

My need is for a simple list of 'symbol, sector, industry'. I'm working in Java and don't want to use any platform native code.

It seems that most other data, like quotes, etc., is readily available.

Finally, followed a suggestion to look at 'finviz.com'. Looks like just the ticket. Try using the following:

http://finviz.com/export.ashx?v=111&t=aapl,cat&o=ticker This comes back as lines, csv style, with a header row, ordered by ticker symbol. You can keep adding tickers. In code, you can read the stream. Or you can let the browser ask you whether to open or save the file.

http://finviz.com/export.ashx?v=111&&o=ticker Same csv style, but pulls all available symbols (a lot, across global exchanges)

Replace 'export' with 'screener' and the data will show up in the browser.

There are many more options you can use, one for every screener element on the site.

So far, this is the most powerful and convenient programmatic way to get the few pieces of data I couldn't otherwise seem to easily get. And, it looks like this site could well be a single source for most of what you might need other than real- or near-real-time quotes.

Yahoo Finance API

IMHO the best place to find this information is: http://code.google.com/p/yahoo-finance-managed/

I used to use the "gummy-stuff" too but then I found this page which is far more organized and full of easy to use examples. I am using it now to get the data in CSV files and use the files in my C++/Qt project.

No found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations:

I missed to add

@Controller("userBo") into UserBoImpl class.

The solution for this is adding this controller into Impl class.

What does "collect2: error: ld returned 1 exit status" mean?

Try running task manager to determine if your program is still running.

If it is running then stop it and run it again. the [Error] ld returned 1 exit status will not come back

How to compare 2 dataTables

You would need to loop through the rows of each table, and then through each column within that loop to compare individual values.

There's a code sample here: http://canlu.blogspot.com/2009/05/how-to-compare-two-datatables-in-adonet.html

Custom Authentication in ASP.Net-Core

I would like to add something to brilliant @AmiNadimi answer for everyone who going implement his solution in .NET Core 3:

First of all, you should change signature of SignIn method in UserManager class from:

public async void SignIn(HttpContext httpContext, UserDbModel user, bool isPersistent = false)

to:

public async Task SignIn(HttpContext httpContext, UserDbModel user, bool isPersistent = false)

It's because you should never use async void, especially if you work with HttpContext. Source: Microsoft Docs

The last, but not least, your Configure() method in Startup.cs should contains app.UseAuthorization and app.UseAuthentication in proper order:

if (env.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}
else
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseAuthentication();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
});

Convert string to Date in java

GregorianCalendar date;

CharSequence dateForMart = android.text.format.DateFormat.format("yyyy-MM-dd", date);

Toast.makeText(LogmeanActivity.this,dateForMart,Toast.LENGTH_LONG).show();

How do you change the datatype of a column in SQL Server?

The syntax to modify a column in an existing table in SQL Server (Transact-SQL) is:

ALTER TABLE table_name
    ALTER COLUMN column_name column_type;

For example:

ALTER TABLE employees
    ALTER COLUMN last_name VARCHAR(75) NOT NULL;

This SQL Server ALTER TABLE example will modify the column called last_name to be a data type of VARCHAR(75) and force the column to not allow null values.

see here

HTML/CSS - Adding an Icon to a button

You could add a span before the link with a specific class like so:

<div class="btn btn_red"><span class="icon"></span><a href="#">Crimson</a><span></span></div>

And then give that a specific width and a background image just like you are doing with the button itself.

.btn span.icon {
    background: url(imgs/icon.png) no-repeat;
    float: left;
    width: 10px;
    height: 40px;
}

I am no CSS guru but off the top of my head I think that should work.

Namenode not getting started

If you facing this issue after rebooting the system, Then below steps will work fine

For workaround.

1) format the namenode: bin/hadoop namenode -format

2) start all processes again:bin/start-all.sh

For Perm fix: -

1) go to /conf/core-site.xml change fs.default.name to your custom one.

2) format the namenode: bin/hadoop namenode -format

3) start all processes again:bin/start-all.sh

Selecting one row from MySQL using mysql_* API

Try with mysql_fetch_assoc .It will returns an associative array of strings that corresponds to the fetched row, or FALSE if there are no more rows. Furthermore, you have to add LIMIT 1 if you really expect single row.

$result = mysql_query("SELECT option_value FROM wp_10_options WHERE option_name='homepage' LIMIT 1");
$row = mysql_fetch_assoc($result);
echo $row['option_value'];

Send SMTP email using System.Net.Mail via Exchange Online (Office 365)

Fixed a few typos in the working code above:

MailMessage msg = new MailMessage();
msg.To.Add(new MailAddress("[email protected]", "SomeOne"));
msg.From = new MailAddress("[email protected]", "You");
msg.Subject = "This is a Test Mail";
msg.Body = "This is a test message using Exchange OnLine";
msg.IsBodyHtml = true;

SmtpClient client = new SmtpClient();
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("your user name", "your password");
client.Port = 587; // You can use Port 25 if 587 is blocked (mine is!)
client.Host = "smtp.office365.com";
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl = true;
try
{
    client.Send(msg);
    lblText.Text = "Message Sent Succesfully";
}
catch (Exception ex)
{
    lblText.Text = ex.ToString();
}

I have two web applications using the above code and both work fine without any trouble.

How to re-index all subarray elements of a multidimensional array?

PHP native function exists for this. See http://php.net/manual/en/function.reset.php

Simply do this: mixed reset ( array &$array )

How can I remove jenkins completely from linux

First - stop Jenkins service:

sudo service jenkins stop

Next - delete:

sudo apt-get remove --purge jenkins

If you used separate server for Jenkins, some GCP or AWS - just delete this server. Here is a video how to uninstall Jenkins from GCP Compute Engine https://youtu.be/D2HUFAc_Trw

When and where to use GetType() or typeof()?

typeof is applied to a name of a type or generic type parameter known at compile time (given as identifier, not as string). GetType is called on an object at runtime. In both cases the result is an object of the type System.Type containing meta-information on a type.

Example where compile-time and run-time types are equal

string s = "hello";

Type t1 = typeof(string);
Type t2 = s.GetType();

t1 == t2 ==> true

Example where compile-time and run-time types are different

object obj = "hello";

Type t1 = typeof(object); // ==> object
Type t2 = obj.GetType();  // ==> string!

t1 == t2 ==> false

i.e., the compile time type (static type) of the variable obj is not the same as the runtime type of the object referenced by obj.


Testing types

If, however, you only want to know whether mycontrol is a TextBox then you can simply test

if (mycontrol is TextBox)

Note that this is not completely equivalent to

if (mycontrol.GetType() == typeof(TextBox))    

because mycontrol could have a type that is derived from TextBox. In that case the first comparison yields true and the second false! The first and easier variant is OK in most cases, since a control derived from TextBox inherits everything that TextBox has, probably adds more to it and is therefore assignment compatible to TextBox.

public class MySpecializedTextBox : TextBox
{
}

MySpecializedTextBox specialized = new MySpecializedTextBox();
if (specialized is TextBox)       ==> true

if (specialized.GetType() == typeof(TextBox))        ==> false

Casting

If you have the following test followed by a cast and T is nullable ...

if (obj is T) {
    T x = (T)obj; // The casting tests, whether obj is T again!
    ...
}

... you can change it to ...

T x = obj as T;
if (x != null) {
    ...
}

Testing whether a value is of a given type and casting (which involves this same test again) can both be time consuming for long inheritance chains. Using the as operator followed by a test for null is more performing.

Starting with C# 7.0 you can simplify the code by using pattern matching:

if (obj is T t) {
    // t is a variable of type T having a non-null value.
    ...
}

Btw.: this works for value types as well. Very handy for testing and unboxing. Note that you cannot test for nullable value types:

if (o is int? ni) ===> does NOT compile!

This is because either the value is null or it is an int. This works for int? o as well as for object o = new Nullable<int>(x);:

if (o is int i) ===> OK!

I like it, because it eliminates the need to access the Nullable<T>.Value property.

How to send authorization header with axios

Try this :

axios.get(
    url,
    {headers: {
        "name" : "value"
      }
    }
  )
  .then((response) => {
      var response = response.data;
    },
    (error) => {
      var status = error.response.status
    }
  );

Determine if JavaScript value is an "integer"?

Try this:

if(Math.floor(id) == id && $.isNumeric(id)) 
  alert('yes its an int!');

$.isNumeric(id) checks whether it's numeric or not
Math.floor(id) == id will then determine if it's really in integer value and not a float. If it's a float parsing it to int will give a different result than the original value. If it's int both will be the same.

How to map a composite key with JPA and Hibernate?

You need to use @EmbeddedId:

@Entity
class Time {
    @EmbeddedId
    TimeId id;

    String src;
    String dst;
    Integer distance;
    Integer price;
}

@Embeddable
class TimeId implements Serializable {
    Integer levelStation;
    Integer confPathID;
}

Accessing constructor of an anonymous class

It doesn't make any sense to have a named overloaded constructor in an anonymous class, as there would be no way to call it, anyway.

Depending on what you are actually trying to do, just accessing a final local variable declared outside the class, or using an instance initializer as shown by Arne, might be the best solution.

how to remove "," from a string in javascript

If you need a number greater than 999,999.00 you will have a problem.
These are only good for numbers less than 1 million, 1,000,000.
They only remove 1 or 2 commas.

Here the script that can remove up to 12 commas:

function uncomma(x) {
  var string1 = x;
  for (y = 0; y < 12; y++) {
    string1 = string1.replace(/\,/g, '');
  }
  return string1;
}

Modify that for loop if you need bigger numbers.

How to save a Seaborn plot into a file

The suggested solutions are incompatible with Seaborn 0.8.1

giving the following errors because the Seaborn interface has changed:

AttributeError: 'AxesSubplot' object has no attribute 'fig'
When trying to access the figure

AttributeError: 'AxesSubplot' object has no attribute 'savefig'
when trying to use the savefig directly as a function

The following calls allow you to access the figure (Seaborn 0.8.1 compatible):

swarm_plot = sns.swarmplot(...)
fig = swarm_plot.get_figure()
fig.savefig(...) 

as seen previously in this answer.

UPDATE: I have recently used PairGrid object from seaborn to generate a plot similar to the one in this example. In this case, since GridPlot is not a plot object like, for example, sns.swarmplot, it has no get_figure() function. It is possible to directly access the matplotlib figure by

fig = myGridPlotObject.fig

Like previously suggested in other posts in this thread.

@synthesize vs @dynamic, what are the differences?

As others have said, in general you use @synthesize to have the compiler generate the getters and/ or settings for you, and @dynamic if you are going to write them yourself.

There is another subtlety not yet mentioned: @synthesize will let you provide an implementation yourself, of either a getter or a setter. This is useful if you only want to implement the getter for some extra logic, but let the compiler generate the setter (which, for objects, is usually a bit more complex to write yourself).

However, if you do write an implementation for a @synthesize'd accessor it must still be backed by a real field (e.g., if you write -(int) getFoo(); you must have an int foo; field). If the value is being produce by something else (e.g. calculated from other fields) then you have to use @dynamic.

Bind class toggle to window scroll event

Maybe this can help :)

Controller

$scope.scrollevent = function($e){
   // Your code
}

Html

<div scroll scroll-event="scrollevent">//scrollable content</div>

Or

<body scroll scroll-event="scrollevent">//scrollable content</body>

Directive

.directive("scroll", function ($window) {
   return {
      scope: {
         scrollEvent: '&'
      },
      link : function(scope, element, attrs) {
        $("#"+attrs.id).scroll(function($e) { scope.scrollEvent != null ?  scope.scrollEvent()($e) : null })
      }
   }
})

How to get span tag inside a div in jQuery and assign a text?

Try this:

$("#message span").text("hello world!");

See it in your code!

function Errormessage(txt) {
    var m = $("#message");

    // set text before displaying message
    m.children("span").text(txt);

    // bind close listener
    m.children("a.close-notify").click(function(){
      m.fadeOut("slow");
    });

    // display message
    m.fadeIn("slow");
}

Use sed to replace all backslashes with forward slashes

sed can perform text transformations on input stream from a file or from a pipeline. Example:

echo 'C:\foo\bar.xml' | sed 's/\\/\//g'

gets

C:/foo/bar.xml

jQuery: Get height of hidden element in jQuery

You are confuising two CSS styles, the display style and the visibility style.

If the element is hidden by setting the visibility css style, then you should be able to get the height regardless of whether or not the element is visible or not as the element still takes space on the page.

If the element is hidden by changing the display css style to "none", then the element doesn't take space on the page, and you will have to give it a display style which will cause the element to render in some space, at which point, you can get the height.

How to get an ASP.NET MVC Ajax response to redirect to new page instead of inserting view into UpdateTargetId?

The behavior you're trying to produce is not really best done using AJAX. AJAX would be best used if you wanted to only update a portion of the page, not completely redirect to some other page. That defeats the whole purpose of AJAX really.

I would suggest to just not use AJAX with the behavior you're describing.

Alternatively, you could try using jquery Ajax, which would submit the request and then you specify a callback when the request completes. In the callback you could determine if it failed or succeeded, and redirect to another page on success. I've found jquery Ajax to be much easier to use, especially since I'm already using the library for other things anyway.

You can find documentation about jquery ajax here, but the syntax is as follows:

jQuery.ajax( options )  

jQuery.get( url, data, callback, type)

jQuery.getJSON( url, data, callback )

jQuery.getScript( url, callback )

jQuery.post( url, data, callback, type)

Using helpers in model: how do I include helper dependencies?

If you want to use a the my_helper_method inside a model, you can write:

ApplicationController.helpers.my_helper_method

Open and write data to text file using Bash?

If you are using variables, you can use

first_var="Hello"
second_var="How are you"

If you want to concat both string and write it to file, then use below

echo "${first_var} - ${second_var}" > ./file_name.txt

Your file_name.txt content will be "Hello - How are you"

Where should I put the log4j.properties file?

My IDE is NetBeans. I put log4j.property file as shown in the pictures

Root

project's root folder

Web

web folder

WEB-INF

WEB-INF folder

To use this property file you should to write this code:

package example;

import java.io.File;
import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.Logger;
import javax.servlet.*;
public class test {

public static ServletContext context;
static Logger log = Logger.getLogger("example/test");

public test() {

        String homeDir = context.getRealPath("/");
        File propertiesFile = new File(homeDir, "WEB-INF/log4j.properties");
        PropertyConfigurator.configure(propertiesFile.toString());
        log.info("This is a test");
    }
}

You can define static ServletContext context from another JSP file. Example:

test.context = getServletContext(); 
test sample = new test(); 

Now you can use log4j.property file in your projects.

Import Error: No module named numpy

pip3 may not refer to the python3 you use. run python3 -m pip install numpy instead.

Can a JSON value contain a multiline string

Not pretty good solution, but you can try the hjson tool. It allows you to write text multi-lined in editor and then converts it to the proper valid JSON format.

Note: it adds '\n' characters for the new lines, but you can simply delete them in any text editor with the "Replace all.." function.

How can I create a text box for a note in markdown?

The following methods work on GitHub, on GitLab... and on Stackoverflow, which now uses CommonMark!


> One-Line Box made with Blockquote

One-Line Box made with Blockquote


`One-Line Box made with Backticks`

One-Line Box made with Backticks


```
Box made with Triple Backticks
```

Box made with Triple Backticks  


~ ~ ~
Box made with Triple Tildes
(remove the spaces between the tildes to make this work)
~ ~ ~

Box made with Triple Tildes


Box made with Four Spaces at the start of each line:

    “Sometimes we must let go of our pride and do what is requested of us.”
    Padmé Amidala


... or use horizontal lines?

Three dashes (---) make a horizontal line:


Note: “ Your focus determines your reality.” – Qui-Gon Jinn.


For more configurations, I strongly advise the excellent GitLab Markdown Guide.
You can also check the less detailed GitHub basic formatting syntax.
You can compare Markdown implementations using Babelmark.

Useful hints :

  • to force a newline, put two spaces at the end of the line;

  • to escape special characters, use \.

not:first-child selector

div li~li {
    color: red;
}

Supports IE7

How to declare a local variable in Razor?

Not a direct answer to OP's problem, but it may help you too. You can declare a local variable next to some html inside a scope without trouble.

@foreach (var item in Model.Stuff)
{
    var file = item.MoreStuff.FirstOrDefault();

    <li><a href="@item.Source">@file.Name</a></li>
}

SQL Server Insert Example

Here are 4 ways to insert data into a table.

  1. Simple insertion when the table column sequence is known.

    INSERT INTO Table1 VALUES (1,2,...)

  2. Simple insertion into specified columns of the table.

    INSERT INTO Table1(col2,col4) VALUES (1,2)

  3. Bulk insertion when...

    1. You wish to insert every column of Table2 into Table1
    2. You know the column sequence of Table2
    3. You are certain that the column sequence of Table2 won't change while this statement is being used (perhaps you the statement will only be used once).

    INSERT INTO Table1 {Column sequence} SELECT * FROM Table2

  4. Bulk insertion of selected data into specified columns of Table2.

.

INSERT INTO Table1 (Column1,Column2 ....)
    SELECT Column1,Column2...
       FROM Table2

Why is volatile needed in C?

volatile tells the compiler that your variable may be changed by other means, than the code that is accessing it. e.g., it may be a I/O-mapped memory location. If this is not specified in such cases, some variable accesses can be optimised, e.g., its contents can be held in a register, and the memory location not read back in again.

I want to execute shell commands from Maven's pom.xml

Solved. The problem is, executable is working in a different way in Linux. If you want to run an .sh file, you should add the exec-maven-plugin to the <plugins> section of your pom.xml file.

<plugin>
  <artifactId>exec-maven-plugin</artifactId>
  <version>3.0.0</version>
  <groupId>org.codehaus.mojo</groupId>
  <executions>
    <execution>
      <!-- Run our version calculation script -->
      <id>Renaming build artifacts</id>
      <phase>package</phase>
      <goals>
        <goal>exec</goal>
      </goals>
      <configuration>
        <executable>bash</executable>
        <commandlineArgs>handleResultJars.sh</commandlineArgs>
      </configuration>
    </execution>
  </executions>
</plugin>

How to declare an ArrayList with values?

The Guava library contains convenience methods for creating lists and other collections which makes this much prettier than using the standard library classes.

Example:

ArrayList<String> list = newArrayList("a", "b", "c");

(This assumes import static com.google.common.collect.Lists.newArrayList;)

How do you change the server header returned by nginx?

Are you asking about the Server header value in the response? You can try changing that with an add_header directive, but I'm not sure if it'll work. http://wiki.codemongers.com/NginxHttpHeadersModule

Remove empty array elements

For multidimensional array

$data = array_map('array_filter', $data);
$data = array_filter($data);

Does Python support short-circuiting?

Yes. Try the following in your python interpreter:

and

>>>False and 3/0
False
>>>True and 3/0
ZeroDivisionError: integer division or modulo by zero

or

>>>True or 3/0
True
>>>False or 3/0
ZeroDivisionError: integer division or modulo by zero

Error: "Could Not Find Installable ISAM"

I used this to update a excel 12 xlsx file

        System.Data.OleDb.OleDbConnection MyConnection;
        System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand();
        MyConnection = new System.Data.OleDb.OleDbConnection("provider=Microsoft.ACE.OLEDB.12.0;Data Source='D:\\Programming\\Spreadsheet-Current.xlsx';Extended Properties='Excel 12.0;HDR=YES;';");
        MyConnection.Open();
        myCommand.Connection = MyConnection;
        string sql = "Update [ArticlesV2$] set [ID]='Test' where [ActualPageId]=114";// 
        myCommand.CommandText = sql;
        myCommand.ExecuteNonQuery();
        MyConnection.Close();

How to send an email with Gmail as provider using Python?

There is a gmail API now, which lets you send email, read email and create drafts via REST. Unlike the SMTP calls, it is non-blocking which can be a good thing for thread-based webservers sending email in the request thread (like python webservers). The API is also quite powerful.

  • Of course, email should be handed off to a non-webserver queue, but it's nice to have options.

It's easiest to setup if you have Google Apps administrator rights on the domain, because then you can give blanket permission to your client. Otherwise you have to fiddle with OAuth authentication and permission.

Here is a gist demonstrating it:

https://gist.github.com/timrichardson/1154e29174926e462b7a

Sorting using Comparator- Descending order (User defined classes)

You can do the descending sort of a user-defined class this way overriding the compare() method,

Collections.sort(unsortedList,new Comparator<Person>() {
    @Override
    public int compare(Person a, Person b) {
        return b.getName().compareTo(a.getName());
    }
});

Or by using Collection.reverse() to sort descending as user Prince mentioned in his comment.

And you can do the ascending sort like this,

Collections.sort(unsortedList,new Comparator<Person>() {
    @Override
    public int compare(Person a, Person b) {
        return a.getName().compareTo(b.getName());
    }
});

Replace the above code with a Lambda expression(Java 8 onwards) we get concise:

Collections.sort(personList, (Person a, Person b) -> b.getName().compareTo(a.getName()));

As of Java 8, List has sort() method which takes Comparator as parameter(more concise) :

personList.sort((a,b)->b.getName().compareTo(a.getName()));

Here a and b are inferred as Person type by lambda expression.

How to set default font family in React Native?

That works for me: Add Custom Font in React Native

download your fonts and place them in assets/fonts folder, add this line in package.json

 "rnpm": {
"assets": ["assets/fonts/Sarpanch"]}

then open terminal and run this command: react-native link

Now your are good to go. For more detailed step. visit the link above mentioned

How to get certain commit from GitHub project

If you want to go with any certain commit or want to code of any certain commit then you can use below command:

git checkout <BRANCH_NAME>
git reset --hard  <commit ID which code you want>
git push --force

Example:

 git reset --hard fbee9dd 
 git push --force

How do I find the length of an array?

std::vector has a method size() which returns the number of elements in the vector.

(Yes, this is tongue-in-cheek answer)

Programmatically scroll a UIScrollView

scrollView.setContentOffset(CGPoint(x: y, y: x), animated: true)

Hyper-V: Create shared folder between host and guest with internal network

Share Files, Folders or Drives Between Host and Hyper-V Virtual Machine

Prerequisites

  1. Ensure that Enhanced session mode settings are enabled on the Hyper-V host.

    Start Hyper-V Manager, and in the Actions section, select "Hyper-V Settings".

    hyper-v-settings

    Make sure that enhanced session mode is allowed in the Server section. Then, make sure that the enhanced session mode is available in the User section.

    use-enhanced-session-mode

  2. Enable Hyper-V Guest Services for your virtual machine

    Right-click on Virtual Machine > Settings. Select the Integration Services in the left-lower corner of the menu. Check Guest Service and click OK.

    enable-guest-services

Steps to share devices with Hyper-v virtual machine:

  1. Start a virtual machine and click Show Options in the pop-up windows.

    connect-to-vm

    Or click "Edit Session Settings..." in the Actions panel on the right

    edit-session-sessions

    It may only appear when you're (able to get) connected to it. If it doesn't appear try Starting and then Connecting to the VM while paying close attention to the panel in the Hyper-V Manager.

  2. View local resources. Then, select the "More..." menu.

    click-more

  3. From there, you can choose which devices to share. Removable drives are especially useful for file sharing.

    choose-the-devices-that-you-want-to-use

  4. Choose to "Save my settings for future connections to this virtual machine".

    save-my-settings-for-future-connections-to-this-vm

  5. Click Connect. Drive sharing is now complete, and you will see the shared drive in this PC > Network Locations section of Windows Explorer after using the enhanced session mode to sigh to the VM. You should now be able to copy files from a physical machine and paste them into a virtual machine, and vice versa.

    shared-drives-from-local-pc

Source (and for more info): Share Files, Folders or Drives Between Host and Hyper-V Virtual Machine

What is the suggested way to install brew, node.js, io.js, nvm, npm on OS X?

I agree with noa -- if you need to have multiple versions of node, io.js then brew is not the appropriate solution.

You can help beta-test io.js support in nvm: https://github.com/creationix/nvm/pull/616

If you just want io.js and are not switching versions, then you can install the binary distribution of io.js from https://iojs.org/dist/v1.0.2/iojs-v1.0.2-darwin-x64.tar.gz ; that includes npm and you will not need nvm if you are not switching versions.

Remember to update npm after installing: sudo npm install -g npm@latest

Column standard deviation R

The general idea is to sweep the function across. You have many options, one is apply():

R> set.seed(42)
R> M <- matrix(rnorm(40),ncol=4)
R> apply(M, 2, sd)
[1] 0.835449 1.630584 1.156058 1.115269
R> 

Create a user with all privileges in Oracle

There are 2 differences:

2 methods creating a user and granting some privileges to him

create user userName identified by password;
grant connect to userName;

and

grant connect to userName identified by password;

do exactly the same. It creates a user and grants him the connect role.

different outcome

resource is a role in oracle, which gives you the right to create objects (tables, procedures, some more but no views!). ALL PRIVILEGES grants a lot more of system privileges.

To grant a user all privileges run you first snippet or

grant all privileges to userName identified by password;

What is ModelState.IsValid valid for in ASP.NET MVC in NerdDinner?

ModelState.IsValid tells you if any model errors have been added to ModelState.

The default model binder will add some errors for basic type conversion issues (for example, passing a non-number for something which is an "int"). You can populate ModelState more fully based on whatever validation system you're using.

The sample DataAnnotations model binder will fill model state with validation errors taken from the DataAnnotations attributes on your model.

Python 2: AttributeError: 'list' object has no attribute 'strip'

This should be what you want:

[x for y in l for x in y.split(";")]

output:

['Facebook', 'Google+', 'MySpace', 'Apple', 'Android']

How to remove item from array by value?

Please do not use the variant with delete - it makes a hole in the array as it does not re-index the elements after the deleted item.

> Array.prototype.remove=function(v){
...     delete this[this.indexOf(v)]
... };
[Function]
> var myarray=["3","24","55","2"];
undefined
> myarray.remove("55");
undefined
> myarray
[ '3', '24', , '2' ]

How to link html pages in same or different folders?

Also, this will go up a directory and then back down to another subfolder.

<a href = "../subfolder/page.html">link</a>

To go up multiple directories you can do this.

<a href = "../../page.html">link</a>

To go the root, I use this

<a href = "~/page.html">link</a>

Best Practices for Custom Helpers in Laravel 5

First create helpers.php inside App\Http directory. Then add the following code inside the composer.json

"autoload": {
        "classmap": [
            "database"
        ],
        "files": [
            "app/Http/helpers.php"
        ],
        "psr-4": {
            "App\\": "app/"
        }
    },

Next run the following command

composer dump-autoload

Now you can define your custom function inside the helpers.php file.

How to communicate between iframe and the parent site?

Use event.source.window.postMessage to send back to sender.

From Iframe

window.top.postMessage('I am Iframe', '*')
window.onmessage = (event) => {
    if (event.data === 'GOT_YOU_IFRAME') {
        console.log('Parent received successfully.')
    }
}

Then from parent say back.

window.onmessage = (event) => {
    event.source.window.postMessage('GOT_YOU_IFRAME', '*')
}

What values for checked and selected are false?

There are no values that will cause the checkbox to be unchecked. If the checked attribute exists, the checkbox will be checked regardless of what value you set it to.

_x000D_
_x000D_
<input type="checkbox" checked />_x000D_
<input type="checkbox" checked="" />_x000D_
<input type="checkbox" checked="checked" />_x000D_
<input type="checkbox" checked="unchecked" />_x000D_
<input type="checkbox" checked="true" />_x000D_
<input type="checkbox" checked="false" />_x000D_
<input type="checkbox" checked="on" />_x000D_
<input type="checkbox" checked="off" />_x000D_
<input type="checkbox" checked="1" />_x000D_
<input type="checkbox" checked="0" />_x000D_
<input type="checkbox" checked="yes" />_x000D_
<input type="checkbox" checked="no" />_x000D_
<input type="checkbox" checked="y" />_x000D_
<input type="checkbox" checked="n" />
_x000D_
_x000D_
_x000D_

Renders everything checked in all modern browsers (FF3.6, Chrome 10, IE8).

How to create batch file in Windows using "start" with a path and command with spaces

Escaping the path with apostrophes is correct, but the start command takes a parameter containing the title of the new window. This parameter is detected by the surrounding apostrophes, so your application is not executed.

Try something like this:

start "Dummy Title" "c:\path with spaces\app.exe" param1 "param with spaces"

How to style readonly attribute with CSS?

There are a few ways to do this.

The first is the most widely used. It works on all major browsers.

input[readonly] {
 background-color: #dddddd;
}

While the one above will select all inputs with readonly attached, this one below will select only what you desire. Make sure to replace demo with whatever input type you want.

input[type="demo"]:read-only {
 background-color: #dddddd;
}

This is an alternate to the first, but it's not used a whole lot:

input:read-only {
 background-color: #dddddd;
}

The :read-only selector is supported in Chrome, Opera, and Safari. Firefox uses :-moz-read-only. IE doesn't support the :read-only selector.

You can also use input[readonly="readonly"], but this is pretty much the same as input[readonly], from my experience.

S3 Static Website Hosting Route All Paths to Index.html

There are few problems with the S3/Redirect based approach mentioned by others.

  1. Mutliple redirects happen as your app's paths are resolved. For example: www.myapp.com/path/for/test gets redirected as www.myapp.com/#/path/for/test
  2. There is a flicker in the url bar as the '#' comes and goes due the action of your SPA framework.
  3. The seo is impacted because - 'Hey! Its google forcing his hand on redirects'
  4. Safari support for your app goes for a toss.

The solution is:

  1. Make sure you have the index route configured for your website. Mostly it is index.html
  2. Remove routing rules from S3 configurations
  3. Put a Cloudfront in front of your S3 bucket.
  4. Configure error page rules for your Cloudfront instance. In the error rules specify:

    • Http error code: 404 (and 403 or other errors as per need)
    • Error Caching Minimum TTL (seconds) : 0
    • Customize response: Yes
    • Response Page Path : /index.html
    • HTTP Response Code: 200

      1. For SEO needs + making sure your index.html does not cache, do the following:
    • Configure an EC2 instance and setup an nginx server.

    • Assign a public ip to your EC2 instance.
    • Create an ELB that has the EC2 instance you created as an instance
    • You should be able to assign the ELB to your DNS.
    • Now, configure your nginx server to do the following things: Proxy_pass all requests to your CDN (for index.html only, serve other assets directly from your cloudfront) and for search bots, redirect traffic as stipulated by services like Prerender.io

I can help in more details with respect to nginx setup, just leave a note. Have learnt it the hard way.

Once the cloud front distribution update. Invalidate your cloudfront cache once to be in the pristine mode. Hit the url in the browser and all should be good.

OnClick vs OnClientClick for an asp:CheckBox?

You can assign function to all checkboxes then ask for confirmation inside of it. If they choose yes, checkbox is allowed to be changed if no it remains unchanged.

In my case I am also using ASP .Net checkbox inside a repeater (or grid) with Autopostback="True" attribute, so on server side I need to compare the value submitted vs what's currently in db in order to know what confirmation value they chose and update db only if it was "yes".

$(document).ready(function () {
    $('input[type=checkbox]').click(function(){                
        var areYouSure = confirm('Are you sure you want make this change?');
        if (areYouSure) {
            $(this).prop('checked', this.checked);
        } else {
            $(this).prop('checked', !this.checked);
        }
    });
}); 


<asp:CheckBox ID="chk" AutoPostBack="true" onCheckedChanged="chk_SelectedIndexChanged" runat="server" Checked='<%#Eval("FinancialAid") %>' />

protected void chk_SelectedIndexChanged(Object sender, EventArgs e)
{
    using (myDataContext db = new myDataDataContext())
    {
        CheckBox chk = (CheckBox)sender;
        RepeaterItem row = (RepeaterItem) chk.NamingContainer;            
        var studentID = ((Label) row.FindControl("lblID")).Text;
        var z = (from b in db.StudentApplicants
        where b.StudentID == studentID
        select b).FirstOrDefault();                
        if(chk != null && chk.Checked != z.FinancialAid){
            z.FinancialAid = chk.Checked;                
            z.ModifiedDate = DateTime.Now;
            db.SubmitChanges();
            BindGrid();
        }
        gvData.DataBind();
    }
}

How to output only captured groups with sed?

Sed has up to nine remembered patterns but you need to use escaped parentheses to remember portions of the regular expression.

See here for examples and more detail

What is a 'NoneType' object?

NoneType is simply the type of the None singleton:

>>> type(None)
<type 'NoneType'>

From the latter link above:

None

The sole value of the type NoneType. None is frequently used to represent the absence of a value, as when default arguments are not passed to a function. Assignments to None are illegal and raise a SyntaxError.

In your case, it looks like one of the items you are trying to concatenate is None, hence your error.

seek() function?

For strings, forget about using WHENCE: use f.seek(0) to position at beginning of file and f.seek(len(f)+1) to position at the end of file. Use open(file, "r+") to read/write anywhere in a file. If you use "a+" you'll only be able to write (append) at the end of the file regardless of where you position the cursor.

How to find the 'sizeof' (a pointer pointing to an array)?

For dynamic arrays (malloc or C++ new) you need to store the size of the array as mentioned by others or perhaps build an array manager structure which handles add, remove, count, etc. Unfortunately C doesn't do this nearly as well as C++ since you basically have to build it for each different array type you are storing which is cumbersome if you have multiple types of arrays that you need to manage.

For static arrays, such as the one in your example, there is a common macro used to get the size, but it is not recommended as it does not check if the parameter is really a static array. The macro is used in real code though, e.g. in the Linux kernel headers although it may be slightly different than the one below:

#if !defined(ARRAY_SIZE)
    #define ARRAY_SIZE(x) (sizeof((x)) / sizeof((x)[0]))
#endif

int main()
{
    int days[] = {1,2,3,4,5};
    int *ptr = days;
    printf("%u\n", ARRAY_SIZE(days));
    printf("%u\n", sizeof(ptr));
    return 0;
}

You can google for reasons to be wary of macros like this. Be careful.

If possible, the C++ stdlib such as vector which is much safer and easier to use.

Javascript return number of days,hours,minutes,seconds between two dates

my solution is not as clear as that, but I put it as another example

_x000D_
_x000D_
console.log(duration('2019-07-17T18:35:25.235Z', '2019-07-20T00:37:28.839Z'));_x000D_
_x000D_
function duration(t0, t1){_x000D_
    let d = (new Date(t1)) - (new Date(t0));_x000D_
    let weekdays     = Math.floor(d/1000/60/60/24/7);_x000D_
    let days         = Math.floor(d/1000/60/60/24 - weekdays*7);_x000D_
    let hours        = Math.floor(d/1000/60/60    - weekdays*7*24            - days*24);_x000D_
    let minutes      = Math.floor(d/1000/60       - weekdays*7*24*60         - days*24*60         - hours*60);_x000D_
    let seconds      = Math.floor(d/1000          - weekdays*7*24*60*60      - days*24*60*60      - hours*60*60      - minutes*60);_x000D_
    let milliseconds = Math.floor(d               - weekdays*7*24*60*60*1000 - days*24*60*60*1000 - hours*60*60*1000 - minutes*60*1000 - seconds*1000);_x000D_
    let t = {};_x000D_
    ['weekdays', 'days', 'hours', 'minutes', 'seconds', 'milliseconds'].forEach(q=>{ if (eval(q)>0) { t[q] = eval(q); } });_x000D_
    return t;_x000D_
}
_x000D_
_x000D_
_x000D_

How can I get all a form's values that would be submitted without submitting

Depending on the type of input types you're using on your form, you should be able to grab them using standard jQuery expressions.

Example:

// change forms[0] to the form you're trying to collect elements from...  or remove it, if you need all of them
var input_elements = $("input, textarea", document.forms[0]);

Check out the documentation for jQuery expressions on their site for more info: http://docs.jquery.com/Core/jQuery#expressioncontext

show distinct column values in pyspark dataframe: python

you could do

distinct_column = 'somecol' 

distinct_column_vals = df.select(distinct_column).distinct().collect()
distinct_column_vals = [v[distinct_column] for v in distinct_column_vals]

How to hash a string into 8 digits?

Just to complete JJC answer, in python 3.5.3 the behavior is correct if you use hashlib this way:

$ python3 -c '
import hashlib
hash_object = hashlib.sha256(b"Caroline")
hex_dig = hash_object.hexdigest()
print(hex_dig)
'
739061d73d65dcdeb755aa28da4fea16a02b9c99b4c2735f2ebfa016f3e7fded
$ python3 -c '
import hashlib
hash_object = hashlib.sha256(b"Caroline")
hex_dig = hash_object.hexdigest()
print(hex_dig)
'
739061d73d65dcdeb755aa28da4fea16a02b9c99b4c2735f2ebfa016f3e7fded

$ python3 -V
Python 3.5.3

Excel VBA Password via Hex Editor

New version, now you also have the GC= try to replace both DPB and GC with those

DPB="DBD9775A4B774B77B4894C77DFE8FE6D2CCEB951E8045C2AB7CA507D8F3AC7E3A7F59012A2" GC="BAB816BBF4BCF4BCF4"

password will be "test"

Laravel - check if Ajax request

You are using the wrong Request class. If you want to use the Facade like: Request::ajax() you have to import this class:

use Illuminate\Support\Facades\Request;

And not Illumiante\Http\Request


Another solution would be injecting an instance of the real request class:

public function index(Request $request){
    if($request->ajax()){
        return "AJAX";
    }

(Now here you have to import Illuminate\Http\Request)

How to Ping External IP from Java Android

Pink ip Address

  public static int pingHost(String host, int timeout) throws IOException,
        InterruptedException {
    Runtime runtime = Runtime.getRuntime();
    timeout /= 1000;
    String cmd = "ping -c 1 -W " + timeout + " " + host;
    Process proc = runtime.exec(cmd);
    Log.d(TAG, cmd);
    proc.waitFor();
    int exit = proc.exitValue();
    return exit;
}
   Ping a host and return an int value of 0 or 1 or 2 0=success, 1=fail,
   * 2=error

jQuery loop over JSON result from AJAX Success?

If you use Fire Fox, just open up a console (use F12 key) and try out this:

var a = [
 {"TEST1":45,"TEST2":23,"TEST3":"DATA1"},
 {"TEST1":46,"TEST2":24,"TEST3":"DATA2"},
 {"TEST1":47,"TEST2":25,"TEST3":"DATA3"}
];

$.each (a, function (bb) {
    console.log (bb);
    console.log (a[bb]);
    console.log (a[bb].TEST1);
});

hope it helps

Refresh image with a new one at the same url

I've seen a lot of variation in answers for how to do this, so I thought I'd summarize them here (plus add a 4th method of my own invention):


(1) Add a unique cache-busting query parameter to the URL, such as:

newImage.src = "image.jpg?t=" + new Date().getTime();

Pros: 100% reliable, quick & easy to understand and implement.

Cons: Bypasses caching altogether, meaning unnecessary delays and bandwidth use whenever the image doesn't change between views. Will potentially fill browser cache (and any intermediate caches) with many, many copies of exactly the same image! Also, requires modifying image URL.

When to use: Use when image is constantly changing, such as for a live webcam feed. If you use this method, make sure to serve the images themselves with Cache-control: no-cache HTTP headers!!! (Often this can be set up using a .htaccess file). Otherwise you'll be progressively filling caches up with old versions of the image!


(2) Add query parameter to the URL that changes only when the file does, e.g.:

echo '<img src="image.jpg?m=' . filemtime('image.jpg') . '">';

(That's PHP server-side code, but the important point here is just that a ?m=[file last-modified time] querystring is appended to the filename).

Pros: 100% reliable, quick & easy to understand and implement, and preserves caching advantages perfectly.

Cons: Requires modifying the image URL. Also, a little more work for the server - it has to get access to the file-last-modified time. Also, requires server-side information, so not suitable for a purely client-side-only solution to check for a refreshed image.

When to use: When you want to cache images, but may need to update them at the server end from time to time without changing the filename itself. AND when you can easily ensure that the correct querystring is added to every image instance in your HTML.


(3) Serve your images with the header Cache-control: max-age=0, must-revalidate, and add a unique memcache-busting fragment identifier to the URL, such as:

newImage.src = "image.jpg#" + new Date().getTime();

The idea here is that the cache-control header puts images in the browser cache, but immediately markes them stale, so that and every time they are re-displayed the browser must check with the server to see if they've changed. This ensures that the browser's HTTP cache always returns the latest copy of the image. However, browsers will often re-use an in-memory copy of an image if they have one, and not even check their HTTP cache in that case. To prevent this, a fragment identifier is used: Comparison of in-memory image src's includes the fragment identifier, but it gets stripped of before querying the HTTP cache. (So, e.g., image.jpg#A and image.jpg#B might both be displayed from the image.jpg entry in the browser's HTTP cache, but image.jpg#B would never be displayed using in-memory retained image data from when image.jpg#A was last displayed).

Pros: Makes proper use of HTTP caching mechanisms, and uses cached images if they haven't changed. Works for servers that choke on a querystring added to a static image URL (since servers never see fragment identifiers - they're for the browsers' own use only).

Cons: Relies on somewhat dubious (or at least poorly documented) behaviour of browsers, in regard to images with fragment identifiers in their URLs (However, I've tested this successfully in FF27, Chrome33, and IE11). Does still send a revalidation request to the server for every image view, which may be overkill if images only change rarely and/or latency is a big issue (since you need to wait for the revalidation response even when the cached image is still good). Requires modifying image URLs.

When to use: Use when images may change frequently, or need to be refreshed intermittently by the client without server-side script involvement, but where you still want the advantage of caching. For example, polling a live webcam that updates an image irregularly every few minutes. Alternatively, use instead of (1) or (2) if your server doesn't allow querystrings on static image URLs.


(4) Forcibly refresh a particular image using Javascript, by first loading it into a hidden <iframe> and then calling location.reload(true) on the iframe's contentWindow.

The steps are:

  • Load the image to be refreshed into a hidden iframe. This is just a setup step - it can be done long in advance the actual refresh, if desired. It doesn't even matter if the image fails to load at this stage!

  • Once that's done, blank out all copies of that image on your page(s) or anywhere in any DOM nodes (even off-page ones stored in javascript variables). This is necessary because the browser may otherwise display the image from a stale in-memory copy (IE11 especially does this): You need to ensure all in-memory copies are cleared, before refreshing the HTTP cache. If other javascript code is running asynchronously, you may also need to prevent that code from creating new copies of the to-be-refreshed image in the meantime.

  • Call iframe.contentWindow.location.reload(true). The true forces a cache bypass, reloading directly from the server and overwriting the existing cached copy.

  • Once it's finished re-loading, restore the blanked images. They should now display the fresh version from the server!

For same-domain images, you can load the image into the iframe directly. For cross-domain images, you have to instead load a HTML page from your domain that contains the image in an <img> tag, otherwise you'll get an "Access Denied" error when trying to call iframe.contentWindow.reload(...).

Pros: Works just like the image.reload() function you wish the DOM had! Allows images to by cached normally (even with in-the-future expiry dates if you want them, thus avoiding frequent revalidation). Allows you to refresh a particular image without altering the URLs for that image on the current page, or on any other pages, using only client-side code.

Cons: Relies on Javascript. Not 100% guaranteed to work properly in every browser (I've tested this successfully in FF27, Chrome33, and IE11 though). Very complicated relative to the other methods.

When to use: When you have a collection of basically static images that you'd like cached, but you still need to be able to update them occasionally and get immediate visual feedback that the update took place. (Especially when just refreshing the whole browser page wouldn't work, as in some web apps built on AJAX for example). And when methods (1)-(3) aren't feasible because (for whatever reason) you can't change all the URLs that might potentially display the image you need to have updated. (Note that using those 3 methods the image will be refreshed, but if another page then tries to displays that image without the appropriate querystring or fragment identifier, it may show an older version instead).

The details of implementing this in a fairy robust and flexible manner are given below:

Let's assume your website contains a blank 1x1 pixel .gif at the URL path /img/1x1blank.gif, and also has the following one-line PHP script (only required for applying forced refresh to cross-domain images, and can be rewritten in any server-side scripting language, of course) at the URL path /echoimg.php:

<img src="<?=htmlspecialchars(@$_GET['src'],ENT_COMPAT|ENT_HTML5,'UTF-8')?>">

Then, here's a realistic implementation of how you might do all this in Javascript. It looks a bit complicated, but there's a lot of comments, and the important function is just forceImgReload() - the first two just blank and un-blank images, and should be designed to work efficiently with your own HTML, so code them as works best for you; much of the complications in them may be unnecessary for your website:

// This function should blank all images that have a matching src, by changing their src property to /img/1x1blank.gif.
// ##### You should code the actual contents of this function according to your page design, and what images there are on them!!! #####
// Optionally it may return an array (or other collection or data structure) of those images affected.
// This can be used by imgReloadRestore() to restore them later, if that's an efficient way of doing it (otherwise, you don't need to return anything).
// NOTE that the src argument here is just passed on from forceImgReload(), and MAY be a relative URI;
// However, be aware that if you're reading the src property of an <img> DOM object, you'll always get back a fully-qualified URI,
// even if the src attribute was a relative one in the original HTML.  So watch out if trying to compare the two!
// NOTE that if your page design makes it more efficient to obtain (say) an image id or list of ids (of identical images) *first*, and only then get the image src,
// you can pass this id or list data to forceImgReload() along with (or instead of) a src argument: just add an extra or replacement parameter for this information to
// this function, to imgReloadRestore(), to forceImgReload(), and to the anonymous function returned by forceImgReload() (and make it overwrite the earlier parameter variable from forceImgReload() if truthy), as appropriate.
function imgReloadBlank(src)
{
  // ##### Everything here is provisional on the way the pages are designed, and what images they contain; what follows is for example purposes only!
  // ##### For really simple pages containing just a single image that's always the one being refreshed, this function could be as simple as just the one line:
  // ##### document.getElementById("myImage").src = "/img/1x1blank.gif";

  var blankList = [],
      fullSrc = /* Fully qualified (absolute) src - i.e. prepend protocol, server/domain, and path if not present in src */,
      imgs, img, i;

  for each (/* window accessible from this one, i.e. this window, and child frames/iframes, the parent window, anything opened via window.open(), and anything recursively reachable from there */)
  {
    // get list of matching images:
    imgs = theWindow.document.body.getElementsByTagName("img");
    for (i = imgs.length; i--;) if ((img = imgs[i]).src===fullSrc)  // could instead use body.querySelectorAll(), to check both tag name and src attribute, which would probably be more efficient, where supported
    {
      img.src = "/img/1x1blank.gif";  // blank them
      blankList.push(img);            // optionally, save list of blanked images to make restoring easy later on
    }
  }

  for each (/* img DOM node held only by javascript, for example in any image-caching script */) if (img.src===fullSrc)
  {
    img.src = "/img/1x1blank.gif";   // do the same as for on-page images!
    blankList.push(img);
  }

  // ##### If necessary, do something here that tells all accessible windows not to create any *new* images with src===fullSrc, until further notice,
  // ##### (or perhaps to create them initially blank instead and add them to blankList).
  // ##### For example, you might have (say) a global object window.top.blankedSrces as a propery of your topmost window, initially set = {}.  Then you could do:
  // #####
  // #####     var bs = window.top.blankedSrces;
  // #####     if (bs.hasOwnProperty(src)) bs[src]++; else bs[src] = 1;
  // #####
  // ##### And before creating a new image using javascript, you'd first ensure that (blankedSrces.hasOwnProperty(src)) was false...
  // ##### Note that incrementing a counter here rather than just setting a flag allows for the possibility that multiple forced-reloads of the same image are underway at once, or are overlapping.

  return blankList;   // optional - only if using blankList for restoring back the blanked images!  This just gets passed in to imgReloadRestore(), it isn't used otherwise.
}




// This function restores all blanked images, that were blanked out by imgReloadBlank(src) for the matching src argument.
// ##### You should code the actual contents of this function according to your page design, and what images there are on them, as well as how/if images are dimensioned, etc!!! #####
function imgReloadRestore(src,blankList,imgDim,loadError);
{
  // ##### Everything here is provisional on the way the pages are designed, and what images they contain; what follows is for example purposes only!
  // ##### For really simple pages containing just a single image that's always the one being refreshed, this function could be as simple as just the one line:
  // ##### document.getElementById("myImage").src = src;

  // ##### if in imgReloadBlank() you did something to tell all accessible windows not to create any *new* images with src===fullSrc until further notice, retract that setting now!
  // ##### For example, if you used the global object window.top.blankedSrces as described there, then you could do:
  // #####
  // #####     var bs = window.top.blankedSrces;
  // #####     if (bs.hasOwnProperty(src)&&--bs[src]) return; else delete bs[src];  // return here means don't restore until ALL forced reloads complete.

  var i, img, width = imgDim&&imgDim[0], height = imgDim&&imgDim[1];
  if (width) width += "px";
  if (height) height += "px";

  if (loadError) {/* If you want, do something about an image that couldn't load, e.g: src = "/img/brokenImg.jpg"; or alert("Couldn't refresh image from server!"); */}

  // If you saved & returned blankList in imgReloadBlank(), you can just use this to restore:

  for (i = blankList.length; i--;)
  {
    (img = blankList[i]).src = src;
    if (width) img.style.width = width;
    if (height) img.style.height = height;
  }
}




// Force an image to be reloaded from the server, bypassing/refreshing the cache.
// due to limitations of the browser API, this actually requires TWO load attempts - an initial load into a hidden iframe, and then a call to iframe.contentWindow.location.reload(true);
// If image is from a different domain (i.e. cross-domain restrictions are in effect, you must set isCrossDomain = true, or the script will crash!
// imgDim is a 2-element array containing the image x and y dimensions, or it may be omitted or null; it can be used to set a new image size at the same time the image is updated, if applicable.
// if "twostage" is true, the first load will occur immediately, and the return value will be a function
// that takes a boolean parameter (true to proceed with the 2nd load (including the blank-and-reload procedure), false to cancel) and an optional updated imgDim.
// This allows you to do the first load early... for example during an upload (to the server) of the image you want to (then) refresh.
function forceImgReload(src, isCrossDomain, imgDim, twostage)
{
  var blankList, step = 0,                                // step: 0 - started initial load, 1 - wait before proceeding (twostage mode only), 2 - started forced reload, 3 - cancelled
      iframe = window.document.createElement("iframe"),   // Hidden iframe, in which to perform the load+reload.
      loadCallback = function(e)                          // Callback function, called after iframe load+reload completes (or fails).
      {                                                   // Will be called TWICE unless twostage-mode process is cancelled. (Once after load, once after reload).
        if (!step)  // initial load just completed.  Note that it doesn't actually matter if this load succeeded or not!
        {
          if (twostage) step = 1;  // wait for twostage-mode proceed or cancel; don't do anything else just yet
          else { step = 2; blankList = imgReloadBlank(src); iframe.contentWindow.location.reload(true); }  // initiate forced-reload
        }
        else if (step===2)   // forced re-load is done
        {
          imgReloadRestore(src,blankList,imgDim,(e||window.event).type==="error");    // last parameter checks whether loadCallback was called from the "load" or the "error" event.
          if (iframe.parentNode) iframe.parentNode.removeChild(iframe);
        }
      }
  iframe.style.display = "none";
  window.parent.document.body.appendChild(iframe);    // NOTE: if this is done AFTER setting src, Firefox MAY fail to fire the load event!
  iframe.addEventListener("load",loadCallback,false);
  iframe.addEventListener("error",loadCallback,false);
  iframe.src = (isCrossDomain ? "/echoimg.php?src="+encodeURIComponent(src) : src);  // If src is cross-domain, script will crash unless we embed the image in a same-domain html page (using server-side script)!!!
  return (twostage
    ? function(proceed,dim)
      {
        if (!twostage) return;
        twostage = false;
        if (proceed)
        {
          imgDim = (dim||imgDim);  // overwrite imgDim passed in to forceImgReload() - just in case you know the correct img dimensions now, but didn't when forceImgReload() was called.
          if (step===1) { step = 2; blankList = imgReloadBlank(src); iframe.contentWindow.location.reload(true); }
        }
        else
        {
          step = 3;
          if (iframe.contentWindow.stop) iframe.contentWindow.stop();
          if (iframe.parentNode) iframe.parentNode.removeChild(iframe);
        }
      }
    : null);
}

Then, to force a refresh of an image located on the same domain as your page, you can just do:

forceImgReload("myimage.jpg");

To refresh an image from somewhere else (cross-domain):

forceImgReload("http://someother.server.com/someimage.jpg", true);

A more advanced application might be to reload an image after uploading a new version to your server, preparing the initial stage of the reload process simultaneous with the upload, to minimize the visible reload delay to the user. If you're doing the upload via AJAX, and the server is returning a very simple JSON array [success, width, height] then your code might look something like this:

// fileForm is a reference to the form that has a the <input typ="file"> on it, for uploading.
// serverURL is the url at which the uploaded image will be accessible from, once uploaded.
// The response from uploadImageToServer.php is a JSON array [success, width, height]. (A boolean and two ints).
function uploadAndRefreshCache(fileForm, serverURL)
{
  var xhr = new XMLHttpRequest(),
      proceedWithImageRefresh = forceImgReload(serverURL, false, null, true);
  xhr.addEventListener("load", function(){ var arr = JSON.parse(xhr.responseText); if (!(arr&&arr[0])) { proceedWithImageRefresh(false); doSomethingOnUploadFailure(...); } else { proceedWithImageRefresh(true,[arr[1],ar[2]]); doSomethingOnUploadSuccess(...); }});
  xhr.addEventListener("error", function(){ proceedWithImageRefresh(false); doSomethingOnUploadError(...); });
  xhr.addEventListener("abort", function(){ proceedWithImageRefresh(false); doSomethingOnUploadAborted(...); });
  // add additional event listener(s) to track upload progress for graphical progress bar, etc...
  xhr.open("post","uploadImageToServer.php");
  xhr.send(new FormData(fileForm));
}

A final note: Although this topic is about images, it potentially applies to other kinds of files or resources also. For example, preventing the use of stale script or css files, or perhaps even refreshing updated PDF documents (using (4) only if set up to open in-browser). Method (4) might require some changes to the above javascript, in these cases.

Convert object string to JSON

Douglas Crockford has a converter, but I'm not sure it will help with bad JSON to good JSON.

https://github.com/douglascrockford/JSON-js

Passing arguments to angularjs filters

Actually you can pass a parameter ( http://docs.angularjs.org/api/ng.filter:filter ) and don't need a custom function just for this. If you rewrite your HTML as below it'll work:

<div ng:app>
 <div ng-controller="HelloCntl">
 <ul>
    <li ng-repeat="friend in friends | filter:{name:'!Adam'}">
        <span>{{friend.name}}</span>
        <span>{{friend.phone}}</span>
    </li>
 </ul>
 </div>
</div>

http://jsfiddle.net/ZfGx4/59/

How to open this .DB file?

You can use a tool like the TrIDNet - File Identifier to look for the Magic Number and other telltales, if the file format is in it's database it may tell you what it is for.

However searching the definitions did not turn up anything for the string "FLDB", but it checks more than magic numbers so it is worth a try.

If you are using Linux File is a command that will do a similar task.

The other thing to try is if you have access to the program that generated this file, there may be DLL's or EXE's from the database software that may contain meta information about the dll's creator which could give you a starting point for looking for software that can read the file outside of the program that originally created the .db file.

How to access pandas groupby dataframe by key

I was looking for a way to sample a few members of the GroupBy obj - had to address the posted question to get this done.

create groupby object based on some_key column

grouped = df.groupby('some_key')

pick N dataframes and grab their indices

sampled_df_i  = random.sample(grouped.indices, N)

grab the groups

df_list  = map(lambda df_i: grouped.get_group(df_i), sampled_df_i)

optionally - turn it all back into a single dataframe object

sampled_df = pd.concat(df_list, axis=0, join='outer')

file_put_contents: Failed to open stream, no such file or directory

There is definitly a problem with the destination folder path.

Your above error message says, it wants to put the contents to a file in the directory /files/grantapps/, which would be beyond your vhost, but somewhere in the system (see the leading absolute slash )

You should double check:

  • Is the directory /home/username/public_html/files/grantapps/ really present.
  • Contains your loop and your file_put_contents-Statement the absolute path /home/username/public_html/files/grantapps/

Making text bold using attributed string in swift

Usage:

let label = UILabel()
label.attributedText =
    NSMutableAttributedString()
        .bold("Address: ")
        .normal(" Kathmandu, Nepal\n\n")
        .orangeHighlight(" Email: ")
        .blackHighlight(" [email protected] ")
        .bold("\n\nCopyright: ")
        .underlined(" All rights reserved. 2020.")

Result:

enter image description here

Here is a neat way to make a combination of bold and normal texts in a single label plus some other bonus methods.

Extension: Swift 5.*

extension NSMutableAttributedString {
    var fontSize:CGFloat { return 14 }
    var boldFont:UIFont { return UIFont(name: "AvenirNext-Bold", size: fontSize) ?? UIFont.boldSystemFont(ofSize: fontSize) }
    var normalFont:UIFont { return UIFont(name: "AvenirNext-Regular", size: fontSize) ?? UIFont.systemFont(ofSize: fontSize)}
    
    func bold(_ value:String) -> NSMutableAttributedString {
        
        let attributes:[NSAttributedString.Key : Any] = [
            .font : boldFont
        ]
        
        self.append(NSAttributedString(string: value, attributes:attributes))
        return self
    }
    
    func normal(_ value:String) -> NSMutableAttributedString {
        
        let attributes:[NSAttributedString.Key : Any] = [
            .font : normalFont,
        ]
        
        self.append(NSAttributedString(string: value, attributes:attributes))
        return self
    }
    /* Other styling methods */
    func orangeHighlight(_ value:String) -> NSMutableAttributedString {
        
        let attributes:[NSAttributedString.Key : Any] = [
            .font :  normalFont,
            .foregroundColor : UIColor.white,
            .backgroundColor : UIColor.orange
        ]
        
        self.append(NSAttributedString(string: value, attributes:attributes))
        return self
    }
    
    func blackHighlight(_ value:String) -> NSMutableAttributedString {
        
        let attributes:[NSAttributedString.Key : Any] = [
            .font :  normalFont,
            .foregroundColor : UIColor.white,
            .backgroundColor : UIColor.black
            
        ]
        
        self.append(NSAttributedString(string: value, attributes:attributes))
        return self
    }
    
    func underlined(_ value:String) -> NSMutableAttributedString {
        
        let attributes:[NSAttributedString.Key : Any] = [
            .font :  normalFont,
            .underlineStyle : NSUnderlineStyle.single.rawValue
            
        ]
        
        self.append(NSAttributedString(string: value, attributes:attributes))
        return self
    }
}

Note: If compiler is missing UIFont/UIColor, replace them with NSFont/NSColor.

Calling functions in a DLL from C++

There are many ways to do this but I think one of the easiest options is to link the application to the DLL at link time and then use a definition file to define the symbols to be exported from the DLL.

CAVEAT: The definition file approach works bests for undecorated symbol names. If you want to export decorated symbols then it is probably better to NOT USE the definition file approach.

Here is an simple example on how this is done.

Step 1: Define the function in the export.h file.

int WINAPI IsolatedFunction(const char *title, const char *test);

Step 2: Define the function in the export.cpp file.

#include <windows.h>

int WINAPI IsolatedFunction(const char *title, const char *test)
{
    MessageBox(0, title, test, MB_OK);
    return 1;
}

Step 3: Define the function as an export in the export.def defintion file.

EXPORTS    IsolatedFunction          @1

Step 4: Create a DLL project and add the export.cpp and export.def files to this project. Building this project will create an export.dll and an export.lib file.

The following two steps link to the DLL at link time. If you don't want to define the entry points at link time, ignore the next two steps and use the LoadLibrary and GetProcAddress to load the function entry point at runtime.

Step 5: Create a Test application project to use the dll by adding the export.lib file to the project. Copy the export.dll file to ths same location as the Test console executable.

Step 6: Call the IsolatedFunction function from within the Test application as shown below.

#include "stdafx.h"

// get the function prototype of the imported function
#include "../export/export.h"

int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     int       nCmdShow)
{
    // call the imported function found in the dll
    int result = IsolatedFunction("hello", "world");

    return 0;
}

How can I create objects while adding them into a vector?

To answer the first part of your question, you must create an object of type Player before you can use it. When you say push_back(Player), it means "add the Player class to the vector", not "add an object of type Player to the vector" (which is what you meant).

You can create the object on the stack like this:

Player player;
vectorOfGamers.push_back(player);    // <-- name of variable, not type

Or you can even create a temporary object inline and push that (it gets copied when it's put in the vector):

vectorOfGamers.push_back(Player());    // <-- parentheses create a "temporary"

To answer the second part, you can create a vector of the base type, which will allow you to push back objects of any subtype; however, this won't work as expected:

vector<Gamer> gamers;
gamers.push_back(Dealer());    // Doesn't work properly!

since when the dealer object is put into the vector, it gets copied as a Gamer object -- this means only the Gamer part is copied effectively "slicing" the object. You can use pointers, however, since then only the pointer would get copied, and the object is never sliced:

vector<Gamer*> gamers;
gamers.push_back(new Dealer());    // <-- Allocate on heap with `new`, since we
                                   // want the object to persist while it's
                                   // pointed to

Initialize class fields in constructor or at declaration?

In Java, an initializer with the declaration means the field is always initialized the same way, regardless of which constructor is used (if you have more than one) or the parameters of your constructors (if they have arguments), although a constructor might subsequently change the value (if it is not final). So using an initializer with a declaration suggests to a reader that the initialized value is the value that the field has in all cases, regardless of which constructor is used and regardless of the parameters passed to any constructor. Therefore use an initializer with the declaration only if, and always if, the value for all constructed objects is the same.

How to debug SSL handshake using cURL?

openssl s_client -connect 127.0.0.1:6379 -state
CONNECTED(00000003)
SSL_connect:before SSL initialization
SSL_connect:SSLv3/TLS write client hello

Reading a text file and splitting it into single words in python

As supplementary, if you are reading a vvvvery large file, and you don't want read all of the content into memory at once, you might consider using a buffer, then return each word by yield:

def read_words(inputfile):
    with open(inputfile, 'r') as f:
        while True:
            buf = f.read(10240)
            if not buf:
                break

            # make sure we end on a space (word boundary)
            while not str.isspace(buf[-1]):
                ch = f.read(1)
                if not ch:
                    break
                buf += ch

            words = buf.split()
            for word in words:
                yield word
        yield '' #handle the scene that the file is empty

if __name__ == "__main__":
    for word in read_words('./very_large_file.txt'):
        process(word)

How to check Grants Permissions at Run-Time?

Try this for Check Run-Time Permission:

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

    checkRunTimePermission();
}

Check run time permission:

private void checkRunTimePermission() {
    String[] permissionArrays = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        requestPermissions(permissionArrays, 11111);
    } else {
         // if already permition granted
        // PUT YOUR ACTION (Like Open cemara etc..)
    }
}

Handle Permission result:

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    boolean openActivityOnce = true;
    boolean openDialogOnce = true;
    if (requestCode == 11111) {
        for (int i = 0; i < grantResults.length; i++) {
            String permission = permissions[i];

            isPermitted = grantResults[i] == PackageManager.PERMISSION_GRANTED;

            if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
                // user rejected the permission
                boolean showRationale = shouldShowRequestPermissionRationale(permission);
                if (!showRationale) {
                    //execute when 'never Ask Again' tick and permission dialog not show
                } else {
                    if (openDialogOnce) {
                        alertView();
                    }
                }
            }
        }

        if (isPermitted)
            if (isPermissionFromGallery)
                openGalleryFragment();
    }
}

Set custom alert:

private void alertView() {
    AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity(), R.style.MyAlertDialogStyle);

    dialog.setTitle("Permission Denied")
            .setInverseBackgroundForced(true)
            //.setIcon(R.drawable.ic_info_black_24dp)
            .setMessage("Without those permission the app is unable to save your profile. App needs to save profile image in your external storage and also need to get profile image from camera or external storage.Are you sure you want to deny this permission?")

            .setNegativeButton("I'M SURE", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialoginterface, int i) {
                    dialoginterface.dismiss();
                }
            })
            .setPositiveButton("RE-TRY", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialoginterface, int i) {
                    dialoginterface.dismiss();
                    checkRunTimePermission();

                }
            }).show();
}

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

There is a package called eclipse-cdt in the Ubuntu 12.10 repositories, this is what you want. If you haven't got g++ already, you need to install that as well, so all you need is:

sudo apt-get install eclipse eclipse-cdt g++

Whether you messed up your system with your previous installation attempts depends heavily on how you did it. If you did it the safe way for trying out new packages not from repositories (i.e., only installed in your home folder, no sudos blindly copied from installation manuals...) you're definitely fine. Otherwise, you may well have thousands of stray files all over your file system now. In that case, run all uninstall scripts you can find for the things you installed, then install using apt-get and hope for the best.

PHP form - on submit stay on same page

You can use the # action in a form action:

<?php
    if(isset($_POST['SubmitButton'])){ // Check if form was submitted

        $input = $_POST['inputText']; // Get input text
        $message = "Success! You entered: " . $input;
    }
?>

<html>
    <body>
        <form action="#" method="post">
            <?php echo $message; ?>
            <input type="text" name="inputText"/>
            <input type="submit" name="SubmitButton"/>
        </form>
    </body>
</html>

C# DataTable.Select() - How do I format the filter criteria to include null?

Try this

myDataTable.Select("[Name] is NULL OR [Name] <> 'n/a'" )

Edit: Relevant sources:

Recommended way to save uploaded files in a servlet application

Store it anywhere in an accessible location except of the IDE's project folder aka the server's deploy folder, for reasons mentioned in the answer to Uploaded image only available after refreshing the page:

  1. Changes in the IDE's project folder does not immediately get reflected in the server's work folder. There's kind of a background job in the IDE which takes care that the server's work folder get synced with last updates (this is in IDE terms called "publishing"). This is the main cause of the problem you're seeing.

  2. In real world code there are circumstances where storing uploaded files in the webapp's deploy folder will not work at all. Some servers do (either by default or by configuration) not expand the deployed WAR file into the local disk file system, but instead fully in the memory. You can't create new files in the memory without basically editing the deployed WAR file and redeploying it.

  3. Even when the server expands the deployed WAR file into the local disk file system, all newly created files will get lost on a redeploy or even a simple restart, simply because those new files are not part of the original WAR file.

It really doesn't matter to me or anyone else where exactly on the local disk file system it will be saved, as long as you do not ever use getRealPath() method. Using that method is in any case alarming.

The path to the storage location can in turn be definied in many ways. You have to do it all by yourself. Perhaps this is where your confusion is caused because you somehow expected that the server does that all automagically. Please note that @MultipartConfig(location) does not specify the final upload destination, but the temporary storage location for the case file size exceeds memory storage threshold.

So, the path to the final storage location can be definied in either of the following ways:

  • Hardcoded:

      File uploads = new File("/path/to/uploads");
    
  • Environment variable via SET UPLOAD_LOCATION=/path/to/uploads:

      File uploads = new File(System.getenv("UPLOAD_LOCATION"));
    
  • VM argument during server startup via -Dupload.location="/path/to/uploads":

      File uploads = new File(System.getProperty("upload.location"));
    
  • *.properties file entry as upload.location=/path/to/uploads:

      File uploads = new File(properties.getProperty("upload.location"));
    
  • web.xml <context-param> with name upload.location and value /path/to/uploads:

      File uploads = new File(getServletContext().getInitParameter("upload.location"));
    
  • If any, use the server-provided location, e.g. in JBoss AS/WildFly:

      File uploads = new File(System.getProperty("jboss.server.data.dir"), "uploads");
    

Either way, you can easily reference and save the file as follows:

File file = new File(uploads, "somefilename.ext");

try (InputStream input = part.getInputStream()) {
    Files.copy(input, file.toPath());
}

Or, when you want to autogenerate an unique file name to prevent users from overwriting existing files with coincidentally the same name:

File file = File.createTempFile("somefilename-", ".ext", uploads);

try (InputStream input = part.getInputStream()) {
    Files.copy(input, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
}

How to obtain part in JSP/Servlet is answered in How to upload files to server using JSP/Servlet? and how to obtain part in JSF is answered in How to upload file using JSF 2.2 <h:inputFile>? Where is the saved File?

Note: do not use Part#write() as it interprets the path relative to the temporary storage location defined in @MultipartConfig(location).

See also:

ParseError: not well-formed (invalid token) using cElementTree

What helped me with that error was Juan's answer - https://stackoverflow.com/a/20204635/4433222 But wasn't enough - after struggling I found out that an XML file needs to be saved with UTF-8 without BOM encoding.

The solution wasn't working for "normal" UTF-8.

How to create an Observable from static data similar to http one in Angular?

This way you can create Observable from data, in my case I need to maintain shopping cart:

service.ts

export class OrderService {
    cartItems: BehaviorSubject<Array<any>> = new BehaviorSubject([]);
    cartItems$ = this.cartItems.asObservable();

    // I need to maintain cart, so add items in cart

    addCartData(data) {
        const currentValue = this.cartItems.value; // get current items in cart
        const updatedValue = [...currentValue, data]; // push new item in cart

        if(updatedValue.length) {
          this.cartItems.next(updatedValue); // notify to all subscribers
        }
      }
}

Component.ts

export class CartViewComponent implements OnInit {
    cartProductList: any = [];
    constructor(
        private order: OrderService
    ) { }

    ngOnInit() {
        this.order.cartItems$.subscribe(items => {
            this.cartProductList = items;
        });
    }
}

Most efficient T-SQL way to pad a varchar on the left to a certain length?

I liked vnRocks solution, here it is in the form of a udf

create function PadLeft(
      @String varchar(8000)
     ,@NumChars int
     ,@PadChar char(1) = ' ')
returns varchar(8000)
as
begin
    return stuff(@String, 1, 0, replicate(@PadChar, @NumChars - len(@String)))
end

window.open with headers

As the best anwser have writed using XMLHttpResponse except window.open, and I make the abstracts-anwser as a instance.

The main Js file is download.js Download-JS

 // var download_url = window.BASE_URL+ "/waf/p1/download_rules";
    var download_url = window.BASE_URL+ "/waf/p1/download_logs_by_dt";
    function download33() {
        var sender_data = {"start_time":"2018-10-9", "end_time":"2018-10-17"};
        var x=new XMLHttpRequest();
        x.open("POST", download_url, true);
        x.setRequestHeader("Content-type","application/json");
//        x.setRequestHeader("Access-Control-Allow-Origin", "*");
        x.setRequestHeader("Authorization", "JWT " + localStorage.token );
        x.responseType = 'blob';
        x.onload=function(e){download(x.response, "test211.zip", "application/zip" ); }
        x.send( JSON.stringify(sender_data) ); // post-data
    }

Downloading a picture via urllib and python

Using urllib, you can get this done instantly.

import urllib.request

opener=urllib.request.build_opener()
opener.addheaders=[('User-Agent','Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1941.0 Safari/537.36')]
urllib.request.install_opener(opener)

urllib.request.urlretrieve(URL, "images/0.jpg")

RegEx: Grabbing values between quotation marks

Peculiarly, none of these answers produce a regex where the returned match is the text inside the quotes, which is what is asked for. MA-Madden tries but only gets the inside match as a captured group rather than the whole match. One way to actually do it would be :

(?<=(["']\b))(?:(?=(\\?))\2.)*?(?=\1)

Examples for this can be seen in this demo https://regex101.com/r/Hbj8aP/1

The key here is the the positive lookbehind at the start (the ?<= ) and the positive lookahead at the end (the ?=). The lookbehind is looking behind the current character to check for a quote, if found then start from there and then the lookahead is checking the character ahead for a quote and if found stop on that character. The lookbehind group (the ["']) is wrapped in brackets to create a group for whichever quote was found at the start, this is then used at the end lookahead (?=\1) to make sure it only stops when it finds the corresponding quote.

The only other complication is that because the lookahead doesn't actually consume the end quote, it will be found again by the starting lookbehind which causes text between ending and starting quotes on the same line to be matched. Putting a word boundary on the opening quote (["']\b) helps with this, though ideally I'd like to move past the lookahead but I don't think that is possible. The bit allowing escaped characters in the middle I've taken directly from Adam's answer.

Node.js: How to read a stream into a buffer?

in ts, [].push(bufferPart) is not compatible;

so:

getBufferFromStream(stream: Part | null): Promise<Buffer> {
    if (!stream) {
        throw 'FILE_STREAM_EMPTY';
    }
    return new Promise(
        (r, j) => {
            let buffer = Buffer.from([]);
            stream.on('data', buf => {
               buffer = Buffer.concat([buffer, buf]);
            });
            stream.on('end', () => r(buffer));
            stream.on('error', j);
        }
    );
}

How to parse a CSV file using PHP

I love this

        $data = str_getcsv($CsvString, "\n"); //parse the rows
        foreach ($data as &$row) {
            $row = str_getcsv($row, "; or , or whatever you want"); //parse the items in rows 
            $this->debug($row);
        }

in my case I am going to get a csv through web services, so in this way I don't need to create the file. But if you need to parser with a file, it's only necessary to pass as string

How to add parameters into a WebRequest?

I have a feeling that the username and password that you are sending should be part of the Authorization Header. So the code below shows you how to create the Base64 string of the username and password. I also included an example of sending the POST data. In my case it was a phone_number parameter.

string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(_username + ":" + _password));

HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(Request);
webRequest.Headers.Add("Authorization", string.Format("Basic {0}", credentials));
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = WebRequestMethods.Http.Post;
webRequest.AllowAutoRedirect = true;
webRequest.Proxy = null;

string data = "phone_number=19735559042"; 
byte[] dataStream = Encoding.UTF8.GetBytes(data);

request.ContentLength = dataStream.Length;
Stream newStream = webRequest.GetRequestStream();
newStream.Write(dataStream, 0, dataStream.Length);
newStream.Close();

HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader streamreader = new StreamReader(stream);
string s = streamreader.ReadToEnd();

Removing elements from an array in C

You don't really want to be reallocing memory every time you remove something. If you know the rough size of your deck then choose an appropriate size for your array and keep a pointer to the current end of the list. This is a stack.

If you don't know the size of your deck, and think it could get really big as well as keeps changing size, then you will have to do something a little more complex and implement a linked-list.

In C, you have two simple ways to declare an array.

  1. On the stack, as a static array

    int myArray[16]; // Static array of 16 integers
    
  2. On the heap, as a dynamically allocated array

    // Dynamically allocated array of 16 integers
    int* myArray = calloc(16, sizeof(int));
    

Standard C does not allow arrays of either of these types to be resized. You can either create a new array of a specific size, then copy the contents of the old array to the new one, or you can follow one of the suggestions above for a different abstract data type (ie: linked list, stack, queue, etc).

How to fetch FetchType.LAZY associations with JPA and Hibernate in a Spring Controller

You can do the same like this:

@Override
public FaqQuestions getFaqQuestionById(Long questionId) {
    session = sessionFactory.openSession();
    tx = session.beginTransaction();
    FaqQuestions faqQuestions = null;
    try {
        faqQuestions = (FaqQuestions) session.get(FaqQuestions.class,
                questionId);
        Hibernate.initialize(faqQuestions.getFaqAnswers());

        tx.commit();
        faqQuestions.getFaqAnswers().size();
    } finally {
        session.close();
    }
    return faqQuestions;
}

Just use faqQuestions.getFaqAnswers().size()nin your controller and you will get the size if lazily intialised list, without fetching the list itself.

Spring Boot application in eclipse, the Tomcat connector configured to listen on port XXXX failed to start

Issue: It's because either you are not stopping your application or the application is already somehow running on the same port somehow.

Solution, Before starting it another time, the earlier application needs to be killed and the port needs to be freed up.

Depending on your platform you can run the below commands to stop the application,

on windows

netstat -anp | find "your application port number"` --> find PID

taskkill /F /PID

on Linux,

netstat -ntpl | grep "your application port number"

kill pid // pid you will get from previous command

on Mac OS

lsof -n -iTCP:"port number"

kill pid //pid you will get from previous command

How can I transition height: 0; to height: auto; using CSS?

The max-height solution from Jake works well, if the hard-coded max-height value supplied is not much bigger than the real height (because otherwise there are undesirable delays and timing problems). On the other hand if the hard-coded value accidentially is not bigger than the real height the element won't open up completely.

The following CSS only solution also requires a hard-coded size that should be bigger than most of the occurring real sizes. However this solution also works if the real size is in some situations bigger than the hard-coded size. In that event the transition might jump a bit, but it will never leave a partially visible element. So this solution could also be used for unknown content, e.g. from a database, where you just know that the content is usually not bigger than x pixels, but there are exceptions.

Idea is to use a negative value for margin-bottom (or margin-top for a slightly diffenrent animation) and to place the content element into a middle element with overflow:hidden. The negative margin of the content element so reduces the height of the middle element.

The following code uses a transition on margin-bottom from -150px to 0px. This alone works fine as long as the content element is not higher than 150px. In addition it uses a transition on max-height for the middle element from 0px to 100%. This finally hides the middle element if the content element is higher than 150px. For max-height the transition is just used to delay its application by a second when closing, not for a smooth visiual effect ( and therefore it can run from 0px to 100%).

CSS:

.content {
  transition: margin-bottom 1s ease-in;
  margin-bottom: -150px;
}
.outer:hover .middle .content {
  transition: margin-bottom 1s ease-out;
  margin-bottom: 0px
}
.middle {
  overflow: hidden;
  transition: max-height .1s ease 1s;
  max-height: 0px
}
.outer:hover .middle {
  transition: max-height .1s ease 0s;
  max-height: 100%
}

HTML:

<div class="outer">
  <div class="middle">
    <div class="content">
      Sample Text
      <br> Sample Text
      <br> Sample Text
      <div style="height:150px">Sample Test of height 150px</div>
      Sample Text
    </div>
  </div>
  Hover Here
</div>

The value for margin bottom should be negative and as close as possible to the real height of the content element. If it('s absoute value) is bigger there are similar delay and timing problems as with the max-height solutions, which however can be limited as long as the hard coded size is not much bigger than the real one. If the absolute value for margin-bottom is smaller than the real height the tansition jumps a bit. In any case after the transition the content element is either fully displayed or fully removed.

For more details see my blog post http://www.taccgl.org/blog/css_transition_display.html#combined_height

How to add a single item to a Pandas Series

Here is another thought n for appending multiple items in one line without changing the name of series. However, this may be not as efficient as the other answer.

>>> df = pd.Series(np.random.random(5), name='random')
>>> df

0    0.363885
1    0.402623
2    0.450449
3    0.172917
4    0.983481
Name: random, dtype: float64


>>> df.to_frame().T.assign(a=3, b=2, c=5).squeeze()

0    0.363885
1    0.402623
2    0.450449
3    0.172917
4    0.983481
a    3.000000
b    2.000000
c    5.000000
Name: random, dtype: float64

jQuery each loop in table row

In jQuery just use:

$('#tblOne > tbody  > tr').each(function() {...code...});

Using the children selector (>) you will walk over all the children (and not all descendents), example with three rows:

$('table > tbody  > tr').each(function(index, tr) { 
   console.log(index);
   console.log(tr);
});

Result:

0
<tr>
1 
<tr>
2
<tr>

In VanillaJS you can use document.querySelectorAll() and walk over the rows using forEach()

[].forEach.call(document.querySelectorAll('#tblOne > tbody  > tr'), function(index, tr) {
    /* console.log(index); */
    /* console.log(tr); */
});

Abort a git cherry-pick?

You can do the following

git cherry-pick --abort

From the git cherry-pick docs

--abort  

Cancel the operation and return to the pre-sequence state.

UICollectionView Set number of columns

Updated to Swift 5+ iOS 13

Collectionview Estimate Size must be none

enter image description here

Declare margin for cell

let margin: CGFloat = 10

In viewDidLoad configure minimumInteritemSpacing, minimumLineSpacing, sectionInset

 guard let collectionView = docsColl, let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout else { return }

    flowLayout.minimumInteritemSpacing = margin
    flowLayout.minimumLineSpacing = margin
    flowLayout.sectionInset = UIEdgeInsets(top: margin, left: margin, bottom: margin, right: margin)

UICollectionViewDataSource method sizeForItemAt

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    let noOfCellsInRow = 2   //number of column you want
    let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
    let totalSpace = flowLayout.sectionInset.left
        + flowLayout.sectionInset.right
        + (flowLayout.minimumInteritemSpacing * CGFloat(noOfCellsInRow - 1))

    let size = Int((collectionView.bounds.width - totalSpace) / CGFloat(noOfCellsInRow))
    return CGSize(width: size, height: size)
}

jQuery - on change input text

The jQuery documentation says this "It is also displayed [the handler execution result] if you change the text in the field and then click away. If the field loses focus without the contents having changed, though, the event is not triggered.".

Try the keyup and keydown events, like this:

$("#kat").keydown(function(){ 
   alert("Hello");
});

Null check in VB

Change your Ands to AndAlsos

A standard And will test both expressions. If comp.Container is Nothing, then the second expression will raise a NullReferenceException because you're accessing a property on a null object.

AndAlso will short-circuit the logical evaluation. If comp.Container is Nothing, then the 2nd expression will not be evaluated.

Get IPv4 addresses from Dns.GetHostEntry()

To find all valid address list this is the code I have used

public static IEnumerable<string> GetAddresses()
{
      var host = Dns.GetHostEntry(Dns.GetHostName());
      return (from ip in host.AddressList where ip.AddressFamily == AddressFamily.lo select ip.ToString()).ToList();
}

Disabling Warnings generated via _CRT_SECURE_NO_DEPRECATE

i work on a multi platform project, so i can't use _s function and i don't want pollute my code with visual studio specific code.
my solution is disable the warning 4996 on the visual studio project. go to Project -> Properties -> Configuration properties -> C/C++ -> Advanced -> Disable specific warning add the value 4996.
if you use also the mfc and/or atl library (not my case) define before include mfc _AFX_SECURE_NO_DEPRECATE and before include atl _ATL_SECURE_NO_DEPRECATE.
i use this solution across visual studio 2003 and 2005.

p.s. if you use only visual studio the secure template overloads could be a good solution.

How does one set up the Visual Studio Code compiler/debugger to GCC?

Just wanted to add that if you want to debug stuff, you should compile with debug information before you debug, otherwise the debugger won't work. So, in g++ you need to do g++ -g source.cpp. The -g flag means that the compiler will insert debugging information into your executable, so that you can run gdb on it.

How to loop through a directory recursively to delete files with certain extensions

There is no reason to pipe the output of find into another utility. find has a -delete flag built into it.

find /tmp -name '*.pdf' -or -name '*.doc' -delete

How to preserve aspect ratio when scaling image using one (CSS) dimension in IE6?

Well, I can think of a CSS hack that will resolve this issue.

You could add the following line in your CSS file:

* html .blog_list div.postbody img { width:75px; height: SpecifyHeightHere; } 

The above code will only be seen by IE6. The aspect ratio won't be perfect, but you could make it look somewhat normal. If you really wanted to make it perfect, you would need to write some javascript that would read the original picture width, and set the ratio accordingly to specify a height.

Proper way to make HTML nested list?

I prefer option two because it clearly shows the list item as the possessor of that nested list. I would always lean towards semantically sound HTML.

What does `unsigned` in MySQL mean and when to use it?

MySQL says:

All integer types can have an optional (nonstandard) attribute UNSIGNED. Unsigned type can be used to permit only nonnegative numbers in a column or when you need a larger upper numeric range for the column. For example, if an INT column is UNSIGNED, the size of the column's range is the same but its endpoints shift from -2147483648 and 2147483647 up to 0 and 4294967295.

When do I use it ?

Ask yourself this question: Will this field ever contain a negative value?
If the answer is no, then you want an UNSIGNED data type.

A common mistake is to use a primary key that is an auto-increment INT starting at zero, yet the type is SIGNED, in that case you’ll never touch any of the negative numbers and you are reducing the range of possible id's to half.

How to copy directories in OS X 10.7.3?

Is there something special with that directory or are you really just asking how to copy directories?

Copy recursively via CLI:

cp -R <sourcedir> <destdir>

If you're only seeing the files under the sourcedir being copied (instead of sourcedir as well), that's happening because you kept the trailing slash for sourcedir:

cp -R <sourcedir>/ <destdir>

The above only copies the files and their directories inside of sourcedir. Typically, you want to include the directory you're copying, so drop the trailing slash:

cp -R <sourcedir> <destdir>

How do I discover memory usage of my application in Android?

Yes, you can get memory info programmatically and decide whether to do memory intensive work.

Get VM Heap Size by calling:

Runtime.getRuntime().totalMemory();

Get Allocated VM Memory by calling:

Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();

Get VM Heap Size Limit by calling:

Runtime.getRuntime().maxMemory()

Get Native Allocated Memory by calling:

Debug.getNativeHeapAllocatedSize();

I made an app to figure out the OutOfMemoryError behavior and monitor memory usage.

https://play.google.com/store/apps/details?id=net.coocood.oomresearch

You can get the source code at https://github.com/coocood/oom-research

How to change MySQL timezone in a database connection using Java?

Is there a way we can get the list of supported timeZone from MySQL ? ex - serverTimezone=America/New_York. That can solve many such issue. I believe every time you need to specify the correct time zone from the Application irrespective of the DB TimeZone.

Spring Boot how to hide passwords in properties file

You can use Jasypt to encrypt properties, so you could have your property like this:

db.password=ENC(XcBjfjDDjxeyFBoaEPhG14wEzc6Ja+Xx+hNPrJyQT88=)

Jasypt allows you to encrypt your properties using different algorithms, once you get the encrypted property you put inside the ENC(...). For instance, you can encrypt this way through Jasypt using the terminal:

encrypted-pwd$ java -cp ~/.m2/repository/org/jasypt/jasypt/1.9.2/jasypt-1.9.2.jar  org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI input="contactspassword" password=supersecretz algorithm=PBEWithMD5AndDES

----ENVIRONMENT-----------------

Runtime: Oracle Corporation Java HotSpot(TM) 64-Bit Server VM 24.45-b08



----ARGUMENTS-------------------

algorithm: PBEWithMD5AndDES
input: contactspassword
password: supersecretz



----OUTPUT----------------------

XcBjfjDDjxeyFBoaEPhG14wEzc6Ja+Xx+hNPrJyQT88=

To easily configure it with Spring Boot you can use its starter jasypt-spring-boot-starter with group ID com.github.ulisesbocchio

Keep in mind, that you will need to start your application using the same password you used to encrypt the properties. So, you can start your app this way:

mvn -Djasypt.encryptor.password=supersecretz spring-boot:run

Or using the environment variable (thanks to spring boot relaxed binding):

export JASYPT_ENCRYPTOR_PASSWORD=supersecretz
mvn spring-boot:run

You can check below link for more details:

https://www.ricston.com/blog/encrypting-properties-in-spring-boot-with-jasypt-spring-boot/

To use your encrypted properties in your app just use it as usual, use either method you like (Spring Boot wires the magic, anyway the property must be of course in the classpath):

Using @Value annotation

@Value("${db.password}")
private String password;

Or using Environment

@Autowired
private Environment environment;

public void doSomething(Environment env) {
    System.out.println(env.getProperty("db.password"));
}

Update: for production environment, to avoid exposing the password in the command line, since you can query the processes with ps, previous commands with history, etc etc. You could:

  • Create a script like this: touch setEnv.sh
  • Edit setEnv.sh to export the JASYPT_ENCRYPTOR_PASSWORD variable

    #!/bin/bash

    export JASYPT_ENCRYPTOR_PASSWORD=supersecretz

  • Execute the file with . setEnv.sh
  • Run the app in background with mvn spring-boot:run &
  • Delete the file setEnv.sh
  • Unset the previous environment variable with: unset JASYPT_ENCRYPTOR_PASSWORD

How to export dataGridView data Instantly to Excel on button click?

The Best is use use closedxml.codeplex.com Library.Refer it @https://closedxml.codeplex.com/wikipage?title=Adding%20DataTable%20as%20Worksheet&referringTitle=Documentation

var wb = new ClosedXML.Excel.XLWorkbook();
DataTable dt = GetTheDataTable();//Refer documentation


wb.Worksheets.Add(dt);

Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=\"FileName.xlsx\"");

using (var ms = new System.IO.MemoryStream()) {
    wb.SaveAs(ms);
    ms.WriteTo(Response.OutputStream);
    ms.Close();
}

Response.End();

TypeError: unhashable type: 'dict', when dict used as a key for another dict

From the error, I infer that referenceElement is a dictionary (see repro below). A dictionary cannot be hashed and therefore cannot be used as a key to another dictionary (or itself for that matter!).

>>> d1, d2 = {}, {}
>>> d1[d2] = 1
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: unhashable type: 'dict'

You probably meant either for element in referenceElement.keys() or for element in json['referenceElement'].keys(). With more context on what types json and referenceElement are and what they contain, we will be able to better help you if neither solution works.

How do I get the current GPS location programmatically in Android?

You can find the location either by GPS_PROVIDER or NETWORK_PROVIDER.

Overview of location services in Android.

Here is one example which try to find the location using GPS. If your GPS is not available then try to use network for find the location.

GPSTracker.java

 public class GPSTracker extends Service implements LocationListener {

    private final Context mContext;

    // Flag for GPS status
    boolean isGPSEnabled = false;

    // Flag for network status
    boolean isNetworkEnabled = false;

    // Flag for GPS status
    boolean canGetLocation = false;

    Location location; // Location
    double latitude; // Latitude
    double longitude; // Longitude

    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

    // Declaring a Location Manager
    protected LocationManager locationManager;

    public GPSTracker(Context context) {
        this.mContext = context;
        getLocation();
    }

    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);

            // Getting GPS status
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);

            // Getting network status
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {
                // No network provider is enabled
            } else {
                this.canGetLocation = true;
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
                // If GPS enabled, get latitude/longitude using GPS Services
                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        return location;
    }


    /**
     * Stop using GPS listener
     * Calling this function will stop using GPS in your app.
     * */
    public void stopUsingGPS(){
        if(locationManager != null){
            locationManager.removeUpdates(GPSTracker.this);
        }
    }


    /**
     * Function to get latitude
     * */
    public double getLatitude(){
        if(location != null){
            latitude = location.getLatitude();
        }

        // return latitude
        return latitude;
    }


    /**
     * Function to get longitude
     * */
    public double getLongitude(){
        if(location != null){
            longitude = location.getLongitude();
        }

        // return longitude
        return longitude;
    }

    /**
     * Function to check GPS/Wi-Fi enabled
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }


    /**
     * Function to show settings alert dialog.
     * On pressing the Settings button it will launch Settings Options.
     * */
    public void showSettingsAlert(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        // Setting Dialog Title
        alertDialog.setTitle("GPS is settings");

        // Setting Dialog Message
        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

        // On pressing the Settings button.
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });

        // On pressing the cancel button
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }


    @Override
    public void onLocationChanged(Location location) {
    }


    @Override
    public void onProviderDisabled(String provider) {
    }


    @Override
    public void onProviderEnabled(String provider) {
    }


    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }


    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
}

Activity -AndroidGPSTrackingActivity.java

    public class AndroidGPSTrackingActivity extends Activity {

    Button btnShowLocation;

    // GPSTracker class
    GPSTracker gps;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        btnShowLocation = (Button) findViewById(R.id.btnShowLocation);

        // Show location button click event
        btnShowLocation.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // Create class object
                gps = new GPSTracker(AndroidGPSTrackingActivity.this);

                // Check if GPS enabled
                if(gps.canGetLocation()) {

                    double latitude = gps.getLatitude();
                    double longitude = gps.getLongitude();

                    // \n is for new line
                    Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
                } else {
                    // Can't get location.
                    // GPS or network is not enabled.
                    // Ask user to enable GPS/network in settings.
                    gps.showSettingsAlert();
                }
            }
        });
    }
}

Layout- main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button android:id="@+id/btnShowLocation"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Location"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"/>
</RelativeLayout>

AndroidManifest.xml

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

How to generate components in a specific folder with Angular CLI?

Use 'ng generate component ./target_directory/Component_Name'

How do I initialize Kotlin's MutableList to empty MutableList?

Various forms depending on type of List, for Array List:

val myList = mutableListOf<Kolory>() 
// or more specifically use the helper for a specific list type
val myList = arrayListOf<Kolory>()

For LinkedList:

val myList = linkedListOf<Kolory>()
// same as
val myList: MutableList<Kolory> = linkedListOf()

For other list types, will be assumed Mutable if you construct them directly:

val myList = ArrayList<Kolory>()
// or
val myList = LinkedList<Kolory>()

This holds true for anything implementing the List interface (i.e. other collections libraries).

No need to repeat the type on the left side if the list is already Mutable. Or only if you want to treat them as read-only, for example:

val myList: List<Kolory> = ArrayList()

Flask at first run: Do not use the development server in a production environment

When running the python file, you would normally do this

python app.py
This will display these messages.

To avoid these messsages. Inside the CLI (Command Line Interface), run these commands.

export FLASK_APP=app.py
export FLASK_RUN_HOST=127.0.0.1
export FLASK_ENV=development
export FLASK_DEBUG=0
flask run

This should work perfectlly. :) :)

Node.js: get path from the request

A more modern solution that utilises the URL WebAPI:

(req, res) => {
  const { pathname } = new URL(req.url || '', `https://${req.headers.host}`)
}

Apache won't follow symlinks (403 Forbidden)

For anyone having trouble after upgrading to 14.04 https://askubuntu.com/questions/452042/why-is-my-apache-not-working-after-upgrading-to-ubuntu-14-04 as root changed before upgrade = /var/www after upgrade = /var/www/html

Service has zero application (non-infrastructure) endpoints

One crucial thing to remember for those working with a Console application to host the WCF service is that the Web.config file in the WCF project is completely ignored. If your system.serviceModel configuration is there, then you need to move that section of config to the App.config of your Console project.

This is in addition to the answers concerning ensuring the namespace is specified in the right places.

cURL POST command line on WINDOWS RESTful service

Another Alternative for the command line that is easier than fighting with quotation marks is to put the json into a file, and use the @ prefix of curl parameters, e.g. with the following in json.txt:

{ "syncheader" : {
    "servertimesync" : "20131126121749",
    "deviceid" : "testDevice"
  }
}

then in my case I issue:

curl localhost:9000/sync -H "Content-type:application/json" -X POST -d @json.txt

Keeps the json more readable too.

Prevent users from submitting a form by hitting Enter

I think it's well covered with all the answers, but if you are using a button with some JavaScript validation code you could just set the form's onkeypress for Enter to call your submit as expected:

<form method="POST" action="..." onkeypress="if(event.keyCode == 13) mySubmitFunction(this); return false;">

The onkeypress JS could be whatever you need to do. There's no need for a larger, global change. This is especially true if you're not the one coding the app from scratch, and you've been brought into fix someone else's web site without tearing it apart and re-testing it.

PHP - syntax error, unexpected T_CONSTANT_ENCAPSED_STRING

When you're working with strings in PHP you'll need to pay special attention to the formation, using " or '

$string = 'Hello, world!';
$string = "Hello, world!";

Both of these are valid, the following is not:

$string = "Hello, world';

You must also note that ' inside of a literal started with " will not end the string, and vice versa. So when you have a string which contains ', it is generally best practice to use double quotation marks.

$string = "It's ok here";

Escaping the string is also an option

$string = 'It\'s ok here too';

More information on this can be found within the documentation

Array initialization syntax when not in a declaration

Why is this blocked by Java?

You'd have to ask the Java designers. There might be some subtle grammatical reason for the restriction. Note that some of the array creation / initialization constructs were not in Java 1.0, and (IIRC) were added in Java 1.1.

But "why" is immaterial ... the restriction is there, and you have to live with it.

I know how to work around it, but from time to time it would be simpler.

You can write this:

AClass[] array;
...
array = new AClass[]{object1, object2};

Print a list of space-separated elements in Python 3

You can apply the list as separate arguments:

print(*L)

and let print() take care of converting each element to a string. You can, as always, control the separator by setting the sep keyword argument:

>>> L = [1, 2, 3, 4, 5]
>>> print(*L)
1 2 3 4 5
>>> print(*L, sep=', ')
1, 2, 3, 4, 5
>>> print(*L, sep=' -> ')
1 -> 2 -> 3 -> 4 -> 5

Unless you need the joined string for something else, this is the easiest method. Otherwise, use str.join():

joined_string = ' '.join([str(v) for v in L])
print(joined_string)
# do other things with joined_string

Note that this requires manual conversion to strings for any non-string values in L!

What does it mean to "program to an interface"?

The specific example I used to give to students is that they should write

List myList = new ArrayList(); // programming to the List interface

instead of

ArrayList myList = new ArrayList(); // this is bad

These look exactly the same in a short program, but if you go on to use myList 100 times in your program you can start to see a difference. The first declaration ensures that you only call methods on myList that are defined by the List interface (so no ArrayList specific methods). If you've programmed to the interface this way, later on you can decide that you really need

List myList = new TreeList();

and you only have to change your code in that one spot. You already know that the rest of your code doesn't do anything that will be broken by changing the implementation because you programmed to the interface.

The benefits are even more obvious (I think) when you're talking about method parameters and return values. Take this for example:

public ArrayList doSomething(HashMap map);

That method declaration ties you to two concrete implementations (ArrayList and HashMap). As soon as that method is called from other code, any changes to those types probably mean you're going to have to change the calling code as well. It would be better to program to the interfaces.

public List doSomething(Map map);

Now it doesn't matter what kind of List you return, or what kind of Map is passed in as a parameter. Changes that you make inside the doSomething method won't force you to change the calling code.

Fitting polynomial model to data in R

Which model is the "best fitting model" depends on what you mean by "best". R has tools to help, but you need to provide the definition for "best" to choose between them. Consider the following example data and code:

x <- 1:10
y <- x + c(-0.5,0.5)

plot(x,y, xlim=c(0,11), ylim=c(-1,12))

fit1 <- lm( y~offset(x) -1 )
fit2 <- lm( y~x )
fit3 <- lm( y~poly(x,3) )
fit4 <- lm( y~poly(x,9) )
library(splines)
fit5 <- lm( y~ns(x, 3) )
fit6 <- lm( y~ns(x, 9) )

fit7 <- lm( y ~ x + cos(x*pi) )

xx <- seq(0,11, length.out=250)
lines(xx, predict(fit1, data.frame(x=xx)), col='blue')
lines(xx, predict(fit2, data.frame(x=xx)), col='green')
lines(xx, predict(fit3, data.frame(x=xx)), col='red')
lines(xx, predict(fit4, data.frame(x=xx)), col='purple')
lines(xx, predict(fit5, data.frame(x=xx)), col='orange')
lines(xx, predict(fit6, data.frame(x=xx)), col='grey')
lines(xx, predict(fit7, data.frame(x=xx)), col='black')

Which of those models is the best? arguments could be made for any of them (but I for one would not want to use the purple one for interpolation).

Traverse a list in reverse order in Python

Assuming task is to find last element that satisfies some condition in a list (i.e. first when looking backwards), I'm getting following numbers:

>>> min(timeit.repeat('for i in xrange(len(xs)-1,-1,-1):\n    if 128 == xs[i]: break', setup='xs, n = range(256), 0', repeat=8))
4.6937971115112305
>>> min(timeit.repeat('for i in reversed(xrange(0, len(xs))):\n    if 128 == xs[i]: break', setup='xs, n = range(256), 0', repeat=8))
4.809093952178955
>>> min(timeit.repeat('for i, x in enumerate(reversed(xs), 1):\n    if 128 == x: break', setup='xs, n = range(256), 0', repeat=8))
4.931743860244751
>>> min(timeit.repeat('for i, x in enumerate(xs[::-1]):\n    if 128 == x: break', setup='xs, n = range(256), 0', repeat=8))
5.548468112945557
>>> min(timeit.repeat('for i in xrange(len(xs), 0, -1):\n    if 128 == xs[i - 1]: break', setup='xs, n = range(256), 0', repeat=8))
6.286104917526245
>>> min(timeit.repeat('i = len(xs)\nwhile 0 < i:\n    i -= 1\n    if 128 == xs[i]: break', setup='xs, n = range(256), 0', repeat=8))
8.384078979492188

So, the ugliest option xrange(len(xs)-1,-1,-1) is the fastest.

Prepend text to beginning of string

EcmaScript 2017 added special functions to string prototype for that. padStart and padEnd are two new methods available in JavaScript string prototype object. As their name implies, they allow for formatting a string by adding padding characters at the start or the end. (Not supported by IE11 and lower)

var mystr = "Doe";
mystr = mystr.padStart('John ');

How to get a web page's source code from Java

URL yahoo = new URL("http://www.yahoo.com/");
BufferedReader in = new BufferedReader(
            new InputStreamReader(
            yahoo.openStream()));

String inputLine;

while ((inputLine = in.readLine()) != null)
    System.out.println(inputLine);

in.close();

How can I add a volume to an existing Docker container?

Unfortunately the switch option to mount a volume is only found in the run command.

docker run --help

-v, --volume list Bind mount a volume (default [])

There is a way you can work around this though so you won't have to reinstall the applications you've already set up on your container.

  1. Export your container docker container export -o ./myimage.docker mycontainer
  2. Import as an image docker import ./myimage.docker myimage
  3. Then docker run -i -t -v /somedir --name mycontainer myimage /bin/bash

Verifying a specific parameter with Moq

If the verification logic is non-trivial, it will be messy to write a large lambda method (as your example shows). You could put all the test statements in a separate method, but I don't like to do this because it disrupts the flow of reading the test code.

Another option is to use a callback on the Setup call to store the value that was passed into the mocked method, and then write standard Assert methods to validate it. For example:

// Arrange
MyObject saveObject;
mock.Setup(c => c.Method(It.IsAny<int>(), It.IsAny<MyObject>()))
        .Callback<int, MyObject>((i, obj) => saveObject = obj)
        .Returns("xyzzy");

// Act
// ...

// Assert
// Verify Method was called once only
mock.Verify(c => c.Method(It.IsAny<int>(), It.IsAny<MyObject>()), Times.Once());
// Assert about saveObject
Assert.That(saveObject.TheProperty, Is.EqualTo(2));

Remove useless zero digits from decimals in PHP

Strange, when I get a number out of database with a "float" type and if my number is ex. 10000 when I floatval it, it becomes 1.

$number = $ad['price_month']; // 1000 from the database with a float type
echo floatval($number);
Result : 1

I've tested all the solutions above but didn't work.

How can I alter a primary key constraint using SQL syntax?

Performance wise there is no point to keep non clustered indexes during this as they will get re-updated on drop and create. If it is a big data set you should consider renaming the table (if possible , any security settings on it?), re-creating an empty table with the correct keys migrate all data there. You have to make sure you have enough space for this.

Is the Scala 2.8 collections library a case of "the longest suicide note in history"?

Don't know Scala at all, however a few weeks ago I could not read Clojure. Now I can read most of it, but can not write anything yet beyond the most simplistic examples. I suspect Scala is no different. You need a good book or course depending on how you learn. Just reading the map declaration above, I got maybe 1/3 of it.

I believe the bigger problems are not the syntax of these languages, but adopting and internalizing the paradigms that make them usable in everyday production code. For me Java was not a huge leap from C++, which was not a huge leap from C, which was not a leap at all from Pascal, nor Basic etc... But coding in a functional language like Clojure is a huge leap (for me anyway). I guess in Scala you can code in Java style or Scala style. But in Clojure you will create quite the mess trying to keep your imperative habits from Java.

How do I decompile a .NET EXE into readable C# source code?

Reflector and the File Disassembler add-in from Denis Bauer. It actually produces source projects from assemblies, where Reflector on its own only displays the disassembled source.

ADDED: My latest favourite is JetBrains' dotPeek.

JavaScript error: "is not a function"

I received this error when I copied a class object using JSON.parse and JSON.stringify() which removed the function like:

class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
  // Method
  calcArea() {
    return this.height * this.width;
  }
}

const square = new Rectangle(10, 10);

console.log('area of square: ', square.calcArea());

const squareCopy = JSON.parse(JSON.stringify(square));

// Will throw an exception since calcArea() is no longer function 
console.log('area of square copy: ', squareCopy.calcArea());

Ajax call Into MVC Controller- Url Issue

you have an type error in example of code. You forget curlybracket after success

$.ajax({
 type: "POST",
 url: '@Url.Action("Search","Controller")',
 data: "{queryString:'" + searchVal + "'}",
 contentType: "application/json; charset=utf-8",
 dataType: "html",
 success: function (data) {
     alert("here" + data.d.toString());
 }
})

;

Redirect to external URI from ASP.NET MVC controller

Maybe the solution someone is looking for is this:

Response.Redirect("/Sucesso")

This work when used in the View as well.

Setting Remote Webdriver to run tests in a remote computer using Java

You have to install a Selenium Server (a Hub) and register your remote WebDriver to it. Then, your client will talk to the Hub which will find a matching WebDriver to execute your test.

You can have a look at here for more information.

Validating with an XML schema in Python

I am assuming you mean using XSD files. Surprisingly there aren't many python XML libraries that support this. lxml does however. Check Validation with lxml. The page also lists how to use lxml to validate with other schema types.

Delete from a table based on date

Delete data that is 30 days and older

   DELETE FROM Table
   WHERE DateColumn < GETDATE()- 30

How to simulate POST request?

This should help if you need a publicly exposed website but you're on a dev pc. Also to answer (I can't comment yet): "How do I post to an internal only running development server with this? – stryba "

NGROK creates a secure public URL to a local webserver on your development machine (Permanent URLs available for a fee, temporary for free).
1) Run ngrok.exe to open command line (on desktop)
2) Type ngrok.exe http 80 to start a tunnel,
3) test by browsing to the displayed web address which will forward and display the local default 80 page on your dev pc

Then use some of the tools recommended above to POST to your ngrok site ('https://xxxxxx.ngrok.io') to test your local code.

https://ngrok.com/

How can I delete a query string parameter in JavaScript?

Here a solution that:

  1. uses URLSearchParams (no difficult to understand regex)
  2. updates the URL in the search bar without reload
  3. maintains all other parts of the URL (e.g. hash)
  4. removes superflous ? in query string if the last parameter was removed
function removeParam(paramName) {
    let searchParams = new URLSearchParams(window.location.search);
    searchParams.delete(paramName);
    if (history.replaceState) {
        let searchString = searchParams.toString().length > 0 ? '?' + searchParams.toString() : '';
        let newUrl = window.location.protocol + "//" + window.location.host + window.location.pathname +  searchString + window.location.hash;
        history.replaceState(null, '', newUrl);
    }
}

Note: as pointed out in other answers URLSearchParams is not supported in IE, so use a polyfill.

Trigger change() event when setting <select>'s value with val() function

I separate it, and then use an identity comparison to dictate what is does next.

$("#selectField").change(function(){
  if(this.value === 'textValue1'){ $(".contentClass1").fadeIn(); }
  if(this.value === 'textValue2'){ $(".contentclass2").fadeIn(); }
});

Random "Element is no longer attached to the DOM" StaleElementReferenceException

In Java 8 you can use very simple method for that:

private Object retryUntilAttached(Supplier<Object> callable) {
    try {
        return callable.get();
    } catch (StaleElementReferenceException e) {
        log.warn("\tTrying once again");
        return retryUntilAttached(callable);
    }
}

How to use XMLReader in PHP?

For xml formatted with attributes...

data.xml:

<building_data>
<building address="some address" lat="28.902914" lng="-71.007235" />
<building address="some address" lat="48.892342" lng="-75.0423423" />
<building address="some address" lat="58.929753" lng="-79.1236987" />
</building_data>

php code:

$reader = new XMLReader();

if (!$reader->open("data.xml")) {
    die("Failed to open 'data.xml'");
}

while($reader->read()) {
  if ($reader->nodeType == XMLReader::ELEMENT && $reader->name == 'building') {
    $address = $reader->getAttribute('address');
    $latitude = $reader->getAttribute('lat');
    $longitude = $reader->getAttribute('lng');
}

$reader->close();

How to declare strings in C

Strings in C are represented as arrays of characters.

char *p = "String";

You are declaring a pointer that points to a string stored some where in your program (modifying this string is undefined behavior) according to the C programming language 2 ed.

char p2[] = "String";

You are declaring an array of char initialized with the string "String" leaving to the compiler the job to count the size of the array.

char p3[5] = "String";

You are declaring an array of size 5 and initializing it with "String". This is an error be cause "String" don't fit in 5 elements.

char p3[7] = "String"; is the correct declaration ('\0' is the terminating character in c strings).

http://c-faq.com/~scs/cclass/notes/sx8.html

Difference between string and text in rails?

Use string for shorter field, like names, address, phone, company

Use Text for larger content, comments, content, paragraphs.

My general rule, if it's something that is more than one line, I typically go for text, if it's a short 2-6 words, I go for string.

The official rule is 255 for a string. So, if your string is more than 255 characters, go for text.

Grab a segment of an array in Java without creating a new array on heap

Disclaimer: This answer does not conform to the constraints of the question:

I don't want to have to create a new byte array in the heap memory just to do that.

(Honestly, I feel my answer is worthy of deletion. The answer by @unique72 is correct. Imma let this edit sit for a bit and then I shall delete this answer.)


I don't know of a way to do this directly with arrays without additional heap allocation, but the other answers using a sub-list wrapper have additional allocation for the wrapper only – but not the array – which would be useful in the case of a large array.

That said, if one is looking for brevity, the utility method Arrays.copyOfRange() was introduced in Java 6 (late 2006?):

byte [] a = new byte [] {0, 1, 2, 3, 4, 5, 6, 7};

// get a[4], a[5]

byte [] subArray = Arrays.copyOfRange(a, 4, 6);

Difference between filter and filter_by in SQLAlchemy

It is a syntax sugar for faster query writing. Its implementation in pseudocode:

def filter_by(self, **kwargs):
    return self.filter(sql.and_(**kwargs))

For AND you can simply write:

session.query(db.users).filter_by(name='Joe', surname='Dodson')

btw

session.query(db.users).filter(or_(db.users.name=='Ryan', db.users.country=='England'))

can be written as

session.query(db.users).filter((db.users.name=='Ryan') | (db.users.country=='England'))

Also you can get object directly by PK via get method:

Users.query.get(123)
# And even by a composite PK
Users.query.get(123, 321)

When using get case its important that object can be returned without database request from identity map which can be used as cache(associated with transaction)

Python script header


I'd suggest 3 things in the beginning of your script:

First, as already being said use environment:

#!/usr/bin/env python

Second, set your encoding:

# -*- coding: utf-8 -*-

Third, set some doc string:

"""This is a awesome
    python script!"""

And for sure I would use " " (4 spaces) for ident.
Final header will look like:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""This is a awesome
        python script!"""


Best wishes and happy coding.

Is it a good idea to index datetime field in mysql?

Here author performed tests showed that integer unix timestamp is better than DateTime. Note, he used MySql. But I feel no matter what DB engine you use comparing integers are slightly faster than comparing dates so int index is better than DateTime index. Take T1 - time of comparing 2 dates, T2 - time of comparing 2 integers. Search on indexed field takes approximately O(log(rows)) time because index based on some balanced tree - it may be different for different DB engines but anyway Log(rows) is common estimation. (if you not use bitmask or r-tree based index). So difference is (T2-T1)*Log(rows) - may play role if you perform your query oftenly.

How to access a preexisting collection with Mongoose?

Something else that was not obvious, to me at least, was that the when using Mongoose's third parameter to avoid replacing the actual collection with a new one with the same name, the new Schema(...) is actually only a placeholder, and doesn't interfere with the exisitng schema so

var User = mongoose.model('User', new Schema({ url: String, text: String, id: Number}, { collection : 'users' }));   // collection name;
User.find({}, function(err, data) { console.log(err, data, data.length);});

works fine and returns all fields - even if the actual (remote) Schema contains none of these fields. Mongoose will still want it as new Schema(...), and a variable almost certainly won't hack it.

Negative matching using grep (match lines that do not contain foo)

grep -v is your friend:

grep --help | grep invert  

-v, --invert-match select non-matching lines

Also check out the related -L (the complement of -l).

-L, --files-without-match only print FILE names containing no match

$_SERVER['HTTP_REFERER'] missing

You can and should never assume that $_SERVER['HTTP_REFERER'] will be present.

If you control the previous page, you can pass the URL as a parameter "site.com/page2.php?prevUrl=".urlencode("site.com/page1.php").

If you don't control the page, then there is nothing you can do.

Fitting a density curve to a histogram in R

Dirk has explained how to plot the density function over the histogram. But sometimes you might want to go with the stronger assumption of a skewed normal distribution and plot that instead of density. You can estimate the parameters of the distribution and plot it using the sn package:

> sn.mle(y=c(rep(65, times=5), rep(25, times=5), rep(35, times=10), rep(45, times=4)))
$call
sn.mle(y = c(rep(65, times = 5), rep(25, times = 5), rep(35, 
    times = 10), rep(45, times = 4)))

$cp
    mean     s.d. skewness 
41.46228 12.47892  0.99527 

Skew-normal distributed data plot

This probably works better on data that is more skew-normal:

Another skew-normal plot

How can I change the thickness of my <hr> tag

I believe the best achievement for styling <hr> tag is as follow:

hr {
color:#ddd;
background-color:
#ddd; height:1px;
border:none;
max-width:100%;
}

And for the HTML code just add: <hr>.

COUNT(*) vs. COUNT(1) vs. COUNT(pk): which is better?

Asked and answered before...

Books on line says "COUNT ( { [ [ ALL | DISTINCT ] expression ] | * } )"

"1" is a non-null expression so it's the same as COUNT(*). The optimiser recognises it as trivial so gives the same plan. A PK is unique and non-null (in SQL Server at least) so COUNT(PK) = COUNT(*)

This is a similar myth to EXISTS (SELECT * ... or EXISTS (SELECT 1 ...

And see the ANSI 92 spec, section 6.5, General Rules, case 1

        a) If COUNT(*) is specified, then the result is the cardinality
          of T.

        b) Otherwise, let TX be the single-column table that is the
          result of applying the <value expression> to each row of T
          and eliminating null values. If one or more null values are
          eliminated, then a completion condition is raised: warning-
          null value eliminated in set function.

Excel Calculate the date difference from today from a cell of "7/6/2012 10:26:42"

DAYS(start_date,end_date):

For example:

DAYS(A1,TODAY())

How can I export the schema of a database in PostgreSQL?

If you only want the create tables, then you can do pg_dump -s databasename | awk 'RS="";/CREATE TABLE[^;]*;/'

get index of DataTable column with name

Try this:

int index = row.Table.Columns["ColumnName"].Ordinal;

How do disable paging by swiping with finger in ViewPager but still be able to swipe programmatically?

Overriding only onTouchEvent and onInterceptTouchEvent is not sufficient in case you have ViewPager itself inside another ViewPager. Child ViewPager would steal horizontal scroll touch events from parent ViewPager unless it is positioned on its first / last page.

To make this setup work properly you need to override also the canScrollHorizontally method.

See LockableViewPager implementation below.

public class LockableViewPager extends ViewPager {

    private boolean swipeLocked;

    public LockableViewPager(Context context) {
        super(context);
    }

    public LockableViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public boolean getSwipeLocked() {
        return swipeLocked;
    }

    public void setSwipeLocked(boolean swipeLocked) {
        this.swipeLocked = swipeLocked;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return !swipeLocked && super.onTouchEvent(event);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        return !swipeLocked && super.onInterceptTouchEvent(event);
    }

    @Override
    public boolean canScrollHorizontally(int direction) {
        return !swipeLocked && super.canScrollHorizontally(direction);
    }

}

How to advance to the next form input when the current input has a value?

If you have jQuery UI this little function allows basic tabbing

handlePseudoTab(direction) {
    if (!document.hasFocus() || !document.activeElement) {
        return;
    }
    const focusList = $(":focusable", $yourHTMLElement);
    const i = focusList.index(document.activeElement);
    if (i < 0) {
        focusList[0].focus(); // nothing is focussed so go to list item 0
    } else if (direction === 'next' && i + 1 < focusList.length) {
        focusList[i + 1].focus(); // advance one
    } else if (direction === 'prev' && i - 1 > -1) {
        focusList[i - 1].focus(); // go back one
    }
}

How to save username and password in Git?

After going over dozens of SO posts, blogs, etc, I tried out every method, and this is what I came up with. It covers EVERYTHING.

The Vanilla DevOps Git Credentials & Private Packages Cheatsheet

These are all the ways and tools by which you can securely authenticate git to clone a repository without an interactive password prompt.

  • SSH Public Keys
    • SSH_ASKPASS
  • API Access Tokens
    • GIT_ASKPASS
    • .gitconfig insteadOf
    • .gitconfig [credential]
    • .git-credentials
    • .netrc
  • Private Packages (for Free)
    • node / npm package.json
    • python / pip / eggs requirements.txt
    • ruby gems Gemfile
    • golang go.mod

The Silver Bullet

Want Just Works™? This is the magic silver bullet.

Get your Access Token (see the section in the cheatsheet if you need the Github or Gitea instructions for that) and set it in an environment variable (both for local dev and deployment):

MY_GIT_TOKEN=xxxxxxxxxxxxxxxx

For Github, copy and run these lines verbatim:

git config --global url."https://api:[email protected]/".insteadOf "https://github.com/"
git config --global url."https://ssh:[email protected]/".insteadOf "ssh://[email protected]/"
git config --global url."https://git:[email protected]/".insteadOf "[email protected]:"

Congrats, now any automated tool cloning git repositories won't be obstructed by a password prompt, whether using https or either style of ssh url.

Not using Github?

For other platforms (Gitea, Github, Bitbucket), just change the URL. Don't change the usernames (although arbitrary, they're needed for distinct config entries).

Compatibility

This works locally in MacOS, Linux, Windows (in Bash), Docker, CircleCI, Heroku, Akkeris, etc.

More Info

See the ".gitconfig insteadOf" section of the cheatsheet.

Security

See the "Security" section of the cheatsheet.

An efficient way to Base64 encode a byte array?

You could use the String Convert.ToBase64String(byte[]) to encode the byte array into a base64 string, then Byte[] Convert.FromBase64String(string) to convert the resulting string back into a byte array.

creating a table in ionic

the issue of too long content @beenotung can be resolved by this css class :

.col{
  max-width :20% !important;
}

example fork from @jpoveda

Python speed testing - Time Difference - milliseconds

start = datetime.now() 

#code for which response time need to be measured.

end = datetime.now()
dif = end - start
dif_micro = dif.microseconds # time in microseconds
dif_millis = dif.microseconds / 1000 # time in millisseconds

Excel VBA function to print an array to the workbook

On the same theme as other answers, keeping it simple

Sub PrintArray(Data As Variant, Cl As Range)
    Cl.Resize(UBound(Data, 1), UBound(Data, 2)) = Data
End Sub


Sub Test()
    Dim MyArray() As Variant

    ReDim MyArray(1 To 3, 1 To 3) ' make it flexible

    ' Fill array
    '  ...

    PrintArray MyArray, ActiveWorkbook.Worksheets("Sheet1").[A1]
End Sub

Get JSON data from external URL and display it in a div as plain text

To display the Json data using Robin Hartman code. You need to add, the below line.

The code he gave gives you Object, object. this code retrieves the data in a better way.

result.innerText =JSON.stringify(data);

What is the difference between Numpy's array() and asarray() functions?

The difference can be demonstrated by this example:

  1. generate a matrix

    >>> A = numpy.matrix(numpy.ones((3,3)))
    >>> A
    matrix([[ 1.,  1.,  1.],
            [ 1.,  1.,  1.],
            [ 1.,  1.,  1.]])
    
  2. use numpy.array to modify A. Doesn't work because you are modifying a copy

    >>> numpy.array(A)[2]=2
    >>> A
    matrix([[ 1.,  1.,  1.],
            [ 1.,  1.,  1.],
            [ 1.,  1.,  1.]])
    
  3. use numpy.asarray to modify A. It worked because you are modifying A itself

    >>> numpy.asarray(A)[2]=2
    >>> A
    matrix([[ 1.,  1.,  1.],
            [ 1.,  1.,  1.],
            [ 2.,  2.,  2.]])
    

Hope this helps!

Bash command to sum a column of numbers

Use a for loop to iterate over your file …

sum=0; for x in `cat <your-file>`; do let sum+=x; done; echo $sum

How to search JSON tree with jQuery

Once you have the JSON loaded into a JavaScript object, it's no longer a jQuery problem but is now a JavaScript problem. In JavaScript you could for instance write a search such as:

var people = myJson["people"];
var persons = people["person"];
for(var i=0; i < persons.length; ++i) {
    var person_i = persons[i];
    if(person_i["name"] == mySearchForName) {
        // found ! do something with 'person_i'.
        break;
    }
}
// not found !

A formula to copy the values from a formula to another column

Copy the cell. Paste special as link. Will update with original. No formula though.

Include an SVG (hosted on GitHub) in MarkDown

rawgit.com solves this problem nicely. For each request, it retrieves the appropriate document from GitHub and, crucially, serves it with the correct Content-Type header.

What is the difference between Multiple R-squared and Adjusted R-squared in a single-variate least squares regression?

Note that, in addition to number of predictive variables, the Adjusted R-squared formula above also adjusts for sample size. A small sample will give a deceptively large R-squared.

Ping Yin & Xitao Fan, J. of Experimental Education 69(2): 203-224, "Estimating R-squared shrinkage in multiple regression", compares different methods for adjusting r-squared and concludes that the commonly-used ones quoted above are not good. They recommend the Olkin & Pratt formula.

However, I've seen some indication that population size has a much larger effect than any of these formulas indicate. I am not convinced that any of these formulas are good enough to allow you to compare regressions done with very different sample sizes (e.g., 2,000 vs. 200,000 samples; the standard formulas would make almost no sample-size-based adjustment). I would do some cross-validation to check the r-squared on each sample.

What is the function of the push / pop instructions used on registers in x86 assembly?

Pushing and popping registers are behind the scenes equivalent to this:

push reg   <= same as =>      sub  $8,%rsp        # subtract 8 from rsp
                              mov  reg,(%rsp)     # store, using rsp as the address

pop  reg    <= same as=>      mov  (%rsp),reg     # load, using rsp as the address
                              add  $8,%rsp        # add 8 to the rsp

Note this is x86-64 At&t syntax.

Used as a pair, this lets you save a register on the stack and restore it later. There are other uses, too.

Django set field value after a form is initialized

If you have initialized the form like this

form = CustomForm()

then the correct way as of Jan 2019, is to use .initial to replace the data. This will replace the data in the intial dict that goes along with the form. It also works if you have initialized using some instance such as form = CustomForm(instance=instance)

To replace data in the form, you need to

form.initial['Email'] = GetEmailString()

Generalizing this it would be,

form.initial['field_name'] = new_value

How to ensure that there is a delay before a service is started in systemd?

The systemd way to do this is to have the process "talk back" when it's setup somehow, like by opening a socket or sending a notification (or a parent script exiting). Which is of course not always straight-forward especially with third party stuff :|

You might be able to do something inline like

ExecStart=/bin/bash -c '/bin/start_cassandra &; do_bash_loop_waiting_for_it_to_come_up_here'

or a script that does the same. Or put do_bash_loop_waiting_for_it_to_come_up_here in an ExecStartPost

Or create a helper .service that waits for it to come up, so the helper service depends on cassandra, and waits for it to come up, then your other process can depend on the helper service.

(May want to increase TimeoutStartSec from the default 90s as well)

How to display two digits after decimal point in SQL Server

select cast(your_float_column as decimal(10,2))
from your_table

decimal(10,2) means you can have a decimal number with a maximal total precision of 10 digits. 2 of them after the decimal point and 8 before.
The biggest possible number would be 99999999.99

Sql Query to list all views in an SQL Server 2005 database

Necromancing.

Since you said ALL views, technically, all answers to date are WRONG.
Here is how to get ALL views:

SELECT 
     sch.name AS view_schema 
    ,sysv.name AS view_name 
    ,ISNULL(sysm.definition, syssm.definition) AS view_definition 
    ,create_date 
    ,modify_date 
FROM sys.all_views AS sysv 

INNER JOIN sys.schemas AS sch 
    ON sch.schema_id = sysv.schema_id 

LEFT JOIN sys.sql_modules AS sysm 
    ON sysm.object_id = sysv.object_id 

LEFT JOIN sys.system_sql_modules AS syssm 
    ON syssm.object_id = sysv.object_id 

-- INNER JOIN sys.objects AS syso ON syso.object_id = sysv.object_id 

WHERE (1=1) 
AND (sysv.type = 'V') -- seems unnecessary, but who knows
-- AND sch.name = 'INFORMATION_SCHEMA' 
/*
AND sysv.is_ms_shipped = 0  
AND NOT EXISTS 
(
    SELECT * FROM sys.extended_properties AS syscrap
    WHERE syscrap.major_id = sysv.object_id
    AND syscrap.minor_id = 0 
    AND syscrap.class = 1 
    AND syscrap.name = N'microsoft_database_tools_support' 
)  
*/

ORDER BY 
     view_schema 
    ,view_name 

Copy all values in a column to a new column in a pandas dataframe

Following up on these solutions, here is some helpful code illustrating :

#
# Copying columns in pandas without slice warning
#
import numpy as np
df = pd.DataFrame(np.random.randn(10, 3), columns=list('ABC'))

#
# copies column B into new column D
df.loc[:,'D'] = df['B']
print df

#
# creates new column 'E' with values -99
# 
# But copy command replaces those where 'B'>0 while others become NaN (not copied)
df['E'] = -99
print df
df['E'] = df[df['B']>0]['B'].copy()
print df

#
# creates new column 'F' with values -99
# 
# Copy command only overwrites values which meet criteria 'B'>0
df['F']=-99
df.loc[df['B']>0,'F'] = df[df['B']>0]['B'].copy()
print df

Expected response code 220 but got code "", with message "" in Laravel

In my case I had to set the

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=465           <<<<<<<------------------------- (FOCUS THIS)
MAIL_USERNAME=<<your email address>>
MAIL_PASSWORD=<<app password>>

MAIL_ENCRYPTION= ssl    <<<<<<<------------------------- (FOCUS THIS)

to work it.. Might be useful. Rest of the code was same as @Sid said.

And I think that editing both environment file and app/config/mail.php is unnecessary. Just use one method.

Edit as per the comment by @Zan

If you need to enable tls protection use following settings.

MAIL_PORT=587
MAIL_ENCRYPTION= tls  

See here for some other gmail settings

.NET Format a string with fixed spaces

As of Visual Studio 2015 you can also do this with Interpolated Strings (its a compiler trick, so it doesn't matter which version of the .net framework you target).

string value = "String goes here";
string txt1 = $"{value,20}";
string txt2 = $"{value,-20}";

How to set the focus for a particular field in a Bootstrap modal, once it appears

Bootstrap modal show event

$('#modal-content').on('show.bs.modal', function() {
$("#txtname").focus();

})