Programs & Examples On #Precompute

What algorithms compute directions from point A to point B on a map?

I see what's up with the maps in the OP:

Look at the route with the intermediate point specified: The route goes slightly backwards due to that road that isn't straight.

If their algorithm won't backtrack it won't see the shorter route.

Find number of decimal places in decimal value regardless of culture

Most people here seem to be unaware that decimal considers trailing zeroes as significant for storage and printing.

So 0.1m, 0.10m and 0.100m may compare as equal, they are stored differently (as value/scale 1/1, 10/2 and 100/3, respectively), and will be printed as 0.1, 0.10 and 0.100, respectively, by ToString().

As such, the solutions that report "too high a precision" are actually reporting the correct precision, on decimal's terms.

In addition, math-based solutions (like multiplying by powers of 10) will likely be very slow (decimal is ~40x slower than double for arithmetic, and you don't want to mix in floating-point either because that's likely to introduce imprecision). Similarly, casting to int or long as a means of truncating is error-prone (decimal has a much greater range than either of those - it's based around a 96-bit integer).

While not elegant as such, the following will likely be one of the fastest way to get the precision (when defined as "decimal places excluding trailing zeroes"):

public static int PrecisionOf(decimal d) {
  var text = d.ToString(System.Globalization.CultureInfo.InvariantCulture).TrimEnd('0');
  var decpoint = text.IndexOf('.');
  if (decpoint < 0)
    return 0;
  return text.Length - decpoint - 1;
}

The invariant culture guarantees a '.' as decimal point, trailing zeroes are trimmed, and then it's just a matter of seeing of how many positions remain after the decimal point (if there even is one).

Edit: changed return type to int

CSS Vertical align does not work with float

Vertical alignment doesn't work with floated elements, indeed. That's because float lifts the element from the normal flow of the document. You might want to use other vertical aligning techniques, like the ones based on transform, display: table, absolute positioning, line-height, js (last resort maybe) or even the plain old html table (maybe the first choice if the content is actually tabular). You'll find that there's a heated debate on this issue.

However, this is how you can vertically align YOUR 3 divs:

.wrap{
    width: 500px;
    overflow:hidden;    
    background: pink;
}

.left {
    width: 150px;       
    margin-right: 10px;
    background: yellow;  
    display:inline-block;
    vertical-align: middle; 
}

.left2 {
    width: 150px;    
    margin-right: 10px;
    background: aqua; 
    display:inline-block;
    vertical-align: middle; 
}

.right{
    width: 150px;
    background: orange;
    display:inline-block;
    vertical-align: middle; 
}

Not sure why you needed both fixed width, display: inline-block and floating.

bash: Bad Substitution

Your script syntax is valid bash and good.

Possible causes for the failure:

  1. Your bash is not really bash but ksh or some other shell which doesn't understand bash's parameter substitution. Because your script looks fine and works with bash. Do ls -l /bin/bash and check it's really bash and not sym-linked to some other shell.

  2. If you do have bash on your system, then you may be executing your script the wrong way like: ksh script.sh or sh script.sh (and your default shell is not bash). Since you have proper shebang, if you have bash ./script.sh or bash ./script.sh should be fine.

Powershell folder size of folders without listing Subdirectories

from sysinternals.com with du.exe or du64.exe -l 1 . or 2 levels down: **du -l 2 c:**

Much shorter than Linux though ;)

Cannot assign requested address using ServerSocket.socketBind

As other people have pointed out, it is most likely related to another process using port 9999. On Windows, run the command:

netstat -a -n | grep "LIST"

And it should list anything there that's hogging the port. Of course you'll then have to go and manually kill those programs in Task Manager. If this still doesn't work, replace the line:

serverSocket = new ServerSocket(9999);

With:

InetAddress locIP = InetAddress.getByName("192.168.1.20");
serverSocket = new ServerSocket(9999, 0, locIP);

Of course replace 192.168.1.20 with your actual IP address, or use 127.0.0.1.

How to set a default value for an existing column

This will work in SQL Server:

ALTER TABLE Employee ADD CONSTRAINT DF_SomeName DEFAULT N'SANDNES' FOR CityBorn;

How to pass arguments within docker-compose?

Now docker-compose supports variable substitution.

Compose uses the variable values from the shell environment in which docker-compose is run. For example, suppose the shell contains POSTGRES_VERSION=9.3 and you supply this configuration in your docker-compose.yml file:

db:
  image: "postgres:${POSTGRES_VERSION}"

When you run docker-compose up with this configuration, Compose looks for the POSTGRES_VERSION environment variable in the shell and substitutes its value in. For this example, Compose resolves the image to postgres:9.3 before running the configuration.

How to convert string to Title Case in Python?

Why not use title Right from the docs:

>>> "they're bill's friends from the UK".title()
"They'Re Bill'S Friends From The Uk"

If you really wanted PascalCase you can use this:

>>> ''.join(x for x in 'make IT pascal CaSe'.title() if not x.isspace())
'MakeItPascalCase'

How to obtain the location of cacerts of the default java installation?

Under Linux, to find the location of $JAVA_HOME:

readlink -f /usr/bin/java | sed "s:bin/java::"

the cacerts are under lib/security/cacerts:

$(readlink -f /usr/bin/java | sed "s:bin/java::")lib/security/cacerts

Under mac OS X , to find $JAVA_HOME run:

/usr/libexec/java_home

the cacerts are under Home/lib/security/cacerts:

$(/usr/libexec/java_home)/lib/security/cacerts

UPDATE (OS X with JDK)

above code was tested on computer without JDK installed. With JDK installed, as pR0Ps said, it's at

$(/usr/libexec/java_home)/jre/lib/security/cacerts

Pure JavaScript: a function like jQuery's isNumeric()

isFinite(String(n)) returns true for n=0 or '0', '1.1' or 1.1,

but false for '1 dog' or '1,2,3,4', +- Infinity and any NaN values.

T-SQL Substring - Last 3 Characters

if you want to specifically find strings which ends with desired characters then this would help you...

select * from tablename where col_name like '%190'

How can I check if a checkbox is checked?

remember is undefined … and the checked property is a boolean not a number.

function validate(){
    var remember = document.getElementById('remember');
    if (remember.checked){
        alert("checked") ;
    }else{
        alert("You didn't check it! Let me check it for you.")
    }
}

CSS "color" vs. "font-color"

I know this is an old post but as MisterZimbu stated, the color property is defining the values of other properties, as the border-color and, with CSS3, of currentColor.

currentColor is very handy if you want to use the font color for other elements (as the background or custom checkboxes and radios of inner elements for example).

Example:

_x000D_
_x000D_
.element {_x000D_
  color: green;_x000D_
  background: red;_x000D_
  display: block;_x000D_
  width: 200px;_x000D_
  height: 200px;_x000D_
  padding: 0;_x000D_
  margin: 0;_x000D_
}_x000D_
_x000D_
.innerElement1 {_x000D_
  border: solid 10px;_x000D_
  display: inline-block;_x000D_
  width: 60px;_x000D_
  height: 100px;_x000D_
  margin: 10px;_x000D_
}_x000D_
_x000D_
.innerElement2 {_x000D_
  background: currentColor;_x000D_
  display: inline-block;_x000D_
  width: 60px;_x000D_
  height: 100px;_x000D_
  margin: 10px;_x000D_
}
_x000D_
<div class="element">_x000D_
  <div class="innerElement1"></div>_x000D_
  <div class="innerElement2"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to stop mongo DB in one command

Windows

In PowerShell, it's: Stop-Service MongoDB

Then to start it again: Start-Service MongoDB

To verify whether it's started, run: net start | findstr MongoDB.

Note: Above assumes MongoDB is registered as a service.

PHP cURL not working - WAMP on Windows 7 64 bit

Well, just uninstall WAMP 64-bit and go with the 32-bit version. It worked in my case.

How do I create a new column from the output of pandas groupby().sum()?

How do I create a new column with Groupby().Sum()?

There are two ways - one straightforward and the other slightly more interesting.


Everybody's Favorite: GroupBy.transform() with 'sum'

@Ed Chum's answer can be simplified, a bit. Call DataFrame.groupby rather than Series.groupby. This results in simpler syntax.

# The setup.
df[['Date', 'Data3']]

         Date  Data3
0  2015-05-08      5
1  2015-05-07      8
2  2015-05-06      6
3  2015-05-05      1
4  2015-05-08     50
5  2015-05-07    100
6  2015-05-06     60
7  2015-05-05    120

df.groupby('Date')['Data3'].transform('sum')

0     55
1    108
2     66
3    121
4     55
5    108
6     66
7    121
Name: Data3, dtype: int64 

It's a tad faster,

df2 = pd.concat([df] * 12345)

%timeit df2['Data3'].groupby(df['Date']).transform('sum')
%timeit df2.groupby('Date')['Data3'].transform('sum')

10.4 ms ± 367 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
8.58 ms ± 559 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Unconventional, but Worth your Consideration: GroupBy.sum() + Series.map()

I stumbled upon an interesting idiosyncrasy in the API. From what I tell, you can reproduce this on any major version over 0.20 (I tested this on 0.23 and 0.24). It seems like you consistently can shave off a few milliseconds of the time taken by transform if you instead use a direct function of GroupBy and broadcast it using map:

df.Date.map(df.groupby('Date')['Data3'].sum())

0     55
1    108
2     66
3    121
4     55
5    108
6     66
7    121
Name: Date, dtype: int64

Compare with

df.groupby('Date')['Data3'].transform('sum')

0     55
1    108
2     66
3    121
4     55
5    108
6     66
7    121
Name: Data3, dtype: int64

My tests show that map is a bit faster if you can afford to use the direct GroupBy function (such as mean, min, max, first, etc). It is more or less faster for most general situations upto around ~200 thousand records. After that, the performance really depends on the data.

(Left: v0.23, Right: v0.24)

Nice alternative to know, and better if you have smaller frames with smaller numbers of groups. . . but I would recommend transform as a first choice. Thought this was worth sharing anyway.

Benchmarking code, for reference:

import perfplot

perfplot.show(
    setup=lambda n: pd.DataFrame({'A': np.random.choice(n//10, n), 'B': np.ones(n)}),
    kernels=[
        lambda df: df.groupby('A')['B'].transform('sum'),
        lambda df:  df.A.map(df.groupby('A')['B'].sum()),
    ],
    labels=['GroupBy.transform', 'GroupBy.sum + map'],
    n_range=[2**k for k in range(5, 20)],
    xlabel='N',
    logy=True,
    logx=True
)

Using Font Awesome icon for bullet points, with a single list item element

Solution:

http://jsfiddle.net/VR2hP/

ul li:before {    
    font-family: 'FontAwesome';
    content: '\f067';
    margin:0 5px 0 -15px;
    color: #f00;
}

Here's a blog post which explains this technique in-depth.

Subtracting 1 day from a timestamp date

Use the INTERVAL type to it. E.g:

--yesterday
SELECT NOW() - INTERVAL '1 DAY';

--Unrelated to the question, but PostgreSQL also supports some shortcuts:
SELECT 'yesterday'::TIMESTAMP, 'tomorrow'::TIMESTAMP, 'allballs'::TIME;

Then you can do the following on your query:

SELECT 
    org_id,
    count(accounts) AS COUNT,
    ((date_at) - INTERVAL '1 DAY') AS dateat
FROM 
    sourcetable
WHERE 
    date_at <= now() - INTERVAL '130 DAYS'
GROUP BY 
    org_id,
    dateat;


TIPS

Tip 1

You can append multiple operands. E.g.: how to get last day of current month?

SELECT date_trunc('MONTH', CURRENT_DATE) + INTERVAL '1 MONTH - 1 DAY';

Tip 2

You can also create an interval using make_interval function, useful when you need to create it at runtime (not using literals):

SELECT make_interval(days => 10 + 2);
SELECT make_interval(days => 1, hours => 2);
SELECT make_interval(0, 1, 0, 5, 0, 0, 0.0);


More info:

Date/Time Functions and Operators

datatype-datetime (Especial values).

Angular directive how to add an attribute to the element?

You can try this:

<div ng-app="app">
    <div ng-controller="AppCtrl">
        <a my-dir ng-repeat="user in users" ng-click="fxn()">{{user.name}}</a>
    </div>
</div>

<script>
var app = angular.module('app', []);

function AppCtrl($scope) {
        $scope.users = [{ name: 'John', id: 1 }, { name: 'anonymous' }];
        $scope.fxn = function () {
            alert('It works');
        };
    }

app.directive("myDir", function ($compile) {
    return {
        scope: {ngClick: '='}
    };
});
</script>

What is Dependency Injection?

I know there are already many answers, but I found this very helpful: http://tutorials.jenkov.com/dependency-injection/index.html

No Dependency:

public class MyDao {

  protected DataSource dataSource = new DataSourceImpl(
    "driver", "url", "user", "password");

  //data access methods...
  public Person readPerson(int primaryKey) {...}     
}

Dependency:

public class MyDao {

  protected DataSource dataSource = null;

  public MyDao(String driver, String url, String user, String password) {
    this.dataSource = new DataSourceImpl(driver, url, user, password);
  }

  //data access methods...
  public Person readPerson(int primaryKey) {...}
}

Notice how the DataSourceImpl instantiation is moved into a constructor. The constructor takes four parameters which are the four values needed by the DataSourceImpl. Though the MyDao class still depends on these four values, it no longer satisfies these dependencies itself. They are provided by whatever class creating a MyDao instance.

MySQL Error: : 'Access denied for user 'root'@'localhost'

  1. Open & Edit /etc/my.cnf or /etc/mysql/my.cnf, depending on your distro.
  2. Add skip-grant-tables under [mysqld]
  3. Restart Mysql
  4. You should be able to login to mysql now using the below command mysql -u root -p
  5. Run mysql> flush privileges;
  6. Set new password by ALTER USER 'root'@'localhost' IDENTIFIED BY 'NewPassword';
  7. Go back to /etc/my.cnf and remove/comment skip-grant-tables
  8. Restart Mysql
  9. Now you will be able to login with the new password mysql -u root -p

how to align all my li on one line?

Here is what you want. In this case you do not want the list items to be treated as blocks that can wrap.

li{display:inline}
ul{overflow:hidden}

Java array assignment (multiple values)

If you know the values at compile time you can do :

float[] values = {0.1f, 0.2f, 0.3f};

There is no way to do that if values are variables in runtime.

Python: Figure out local timezone

Here's a slightly more concise version of @vbem's solution:

from datetime import datetime as dt

dt.utcnow().astimezone().tzinfo

The only substantive difference is that I replaced datetime.datetime.now(datetime.timezone.utc) with datetime.datetime.utcnow(). For brevity, I also aliased datetime.datetime as dt.

For my purposes, I want the UTC offset in seconds. Here's what that looks like:

dt.utcnow().astimezone().utcoffset().total_seconds()

Java: How to insert CLOB into oracle database

For this purpose you need to make the connection result set

ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE

Connection con=null;
//initialize connection variable to connect to your database...
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
String query="Select MYCLOB from TABLE_NAME for update";
con.setAutoCommit(false);
ResultSet resultset=stmt.executeQuery(query);


if(resultset.next()){
oracle.sql.CLOB    clobnew = ((OracleResultSet) rss).getCLOB("MYCLOB");
PrintWriter pw = new PrintWriter(clobnew.getCharacterOutputStream() );
BufferedReader br = new BufferedReader( new FileReader( new File("filename.xml") ) );
String  lineIn = null;
while( ( lineIn = br.readLine() ) != null )
      pw.println( lineIn );
      pw.close();
      br.close();
}

con.setAutoCommit(true);
con.commit();
}

Note: its important that you add the phrase for update at the end of the query that is written to select the row...

Follow the above code to insert the XML file

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

what I'd call a hack, but given that you're only processing hour values, you can do

 hour=08
 echo $(( ${hour#0} +1 ))
 9
 hour=10 
 echo $(( ${hour#0} +1))
 11

with little risk.

IHTH.

How to deal with the URISyntaxException

I had this exception in the case of a test for checking some actual accessed URLs by users.

And the URLs are sometime contains an illegal-character and hang by this error.

So I make a function to encode only the characters in the URL string like this.

String encodeIllegalChar(String uriStr,String enc)
  throws URISyntaxException,UnsupportedEncodingException {
  String _uriStr = uriStr;
  int retryCount = 17;
  while(true){
     try{
       new URI(_uriStr);
       break;
     }catch(URISyntaxException e){
       String reason = e.getReason();
       if(reason == null ||
         !(
          reason.contains("in path") ||
          reason.contains("in query") ||
          reason.contains("in fragment")
         )
       ){
         throw e;
       }
       if(0 > retryCount--){
         throw e;
       }
       String input = e.getInput();
       int idx = e.getIndex();
       String illChar = String.valueOf(input.charAt(idx));
       _uriStr = input.replace(illChar,URLEncoder.encode(illChar,enc));
     }
  }
  return _uriStr;
}

test:

String q =  "\\'|&`^\"<>)(}{][";
String url = "http://test.com/?q=" + q + "#" + q;
String eic = encodeIllegalChar(url,'UTF-8');
System.out.println(String.format("  original:%s",url));
System.out.println(String.format("   encoded:%s",eic));
System.out.println(String.format("   uri-obj:%s",new URI(eic)));
System.out.println(String.format("re-decoded:%s",URLDecoder.decode(eic)));

How can I enable Assembly binding logging?

  1. Create a new Application Pool

  2. Go to the Advanced Settings of this application pool

  3. Set the Enable 32-Bit Application to True

  4. Point your web application to use this new Pool

Screenshot (IIS-ApplicationPool)

Why does configure say no C compiler found when GCC is installed?

I had the same issue with mind. I tried using sudo apt-get install build-essential It still won't work. I simply created a hardlink to the gcc-x binary in the /usr/bin/ folder. sudo ls /usr/bin/gcc-x /usr/bin/gcc

That worked for me!

How can you get the Manifest Version number from the App's (Layout) XML variables?

Late to the game, but you can do it without @string/xyz by using ?android:attr

    <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="?android:attr/versionName"
     />
    <!-- or -->
    <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="?android:attr/versionCode"
     />

How to remove the default link color of the html hyperlink 'a' tag?

.cancela,.cancela:link,.cancela:visited,.cancela:hover,.cancela:focus,.cancela:active{
    color: inherit;
    text-decoration: none;
}

I felt it necessary to post the above class definition, many of the answers on SO miss some of the states

How to download a Nuget package without nuget.exe or Visual Studio extension?

To obtain the current stable version of the NuGet package use:

https://www.nuget.org/api/v2/package/{packageID}

Repeat-until or equivalent loop in Python

REPEAT
    ...
UNTIL cond

Is equivalent to

while True:
    ...
    if cond:
        break

What is the difference between public, private, and protected?

The mentioned keywords are access modifiers and help us implement Encapsulation (or information hiding). They tell the compiler which other classes should have access to the field or method being defined.

private - Only the current class will have access to the field or method.

protected - Only the current class and subclasses (and sometimes also same-package classes) of this class will have access to the field or method.

public - Any class can refer to the field or call the method.

How do I fit an image (img) inside a div and keep the aspect ratio?

Try CSS:

img {
  object-fit: cover;
  height: 48px;
}

Delete duplicate elements from an array

var arr = [1,2,2,3,4,5,5,5,6,7,7,8,9,10,10];

function squash(arr){
    var tmp = [];
    for(var i = 0; i < arr.length; i++){
        if(tmp.indexOf(arr[i]) == -1){
        tmp.push(arr[i]);
        }
    }
    return tmp;
}

console.log(squash(arr));

Working Example http://jsfiddle.net/7Utn7/

Compatibility for indexOf on old browsers

How can I detect Internet Explorer (IE) and Microsoft Edge using JavaScript?

For me better this:

var uA = window.navigator.userAgent,
    onlyIEorEdge = /msie\s|trident\/|edge\//i.test(uA) && !!( document.uniqueID || window.MSInputMethodContext),
    checkVersion = (onlyIEorEdge && +(/(edge\/|rv:|msie\s)([\d.]+)/i.exec(uA)[2])) || NaN;

Go run: http://output.jsbin.com/solicul/1/ o http://jsfiddle.net/Webnewbie/apa1nvu8/

Why doesn't adding CORS headers to an OPTIONS route allow browsers to access my API?

To answer your main question, the CORS spec only requires the OPTIONS call to precede the POST or GET if the POST or GET has any non-simple content or headers in it.

Content-Types that require a CORS pre-flight request (the OPTIONS call) are any Content-Type except the following:

  1. application/x-www-form-urlencoded
  2. multipart/form-data
  3. text/plain

Any other Content-Types apart from those listed above will trigger a pre-flight request.

As for Headers, any Request Headers apart from the following will trigger a pre-flight request:

  1. Accept
  2. Accept-Language
  3. Content-Language
  4. Content-Type
  5. DPR
  6. Save-Data
  7. Viewport-Width
  8. Width

Any other Request Headers will trigger the pre-flight request.

So, you could add a custom header such as: x-Trigger: CORS, and that should trigger the pre-flight request and hit the OPTIONS block.

See MDN Web API Reference - CORS Preflighted requests

Why not use tables for layout in HTML?

In the past, screen readers and other accessibility software had a difficult time handling tables in an efficient fashion. To some extent, this became handled in screen readers by the reader switching between a "table" mode and a "layout" mode based on what it saw inside the table. This was often wrong, and so the users had to manually switch the mode when navigating through tables. In any case, the large, often highly nested tables were, and to a large extent, are still very difficult to navigate through using a screen reader.

The same is true when divs or other block-level elements are used to recreate tables and are highly nested. The purpose of divs is to be used as a fomating and layout element, and as such, are intended used to hold similar information, and lay it out on the screen for visual users. When a screen reader encounters a page, it often ignores any layout information, both CSS based, as well as html attribute based(This isn't true for all screen readers, but for the most popular ones, like JAWS, Windows Eyes, and Orca for Linux it is).

To this end, tabular data, that is to say data that makes logical sense to be ordered in two or more dimensions, with some sort of headers, is best placed in tables, and use divs to manage the layout of content on the page. (another way to think of what "tabular data" is is to try to draw it in graph form...if you can't, it likely is not best represented in a table)

Finally, with a table-based layout, in order to achieve a fine-grained control of the position of elements on the page, highly nested tables are often used. This has two effects: 1.) Increased code size for each page - Since navigation and common structure is often done with the tables, the same code is sent over the network for each request, whereas a div/css based layout pulls the css file over once, and then uses less wordy divs. 2.) Highly nested tables take much longer for the client's browser to render, leading to slightly slower load times.

In both cases, the increase in "last mile" bandwidth, as well as much faster personal computers mitigates these factors, but none-the-less, they still are existing issues for many sites.

With all of this in mind, as others have said, tables are easier, because they are more grid-oriented, allowing for less thought. If the site in question is not expected to be around long, or will not be maintained, it might make sense to do what is easiest, because it might be the most cost effective. However, if the anticipated userbase might include a substantial portion of handicapped individuals, or if the site will be maintained by others for a long time, spending the time up front to do things in a concise, accessible way may payoff more in the end.

How to Implement DOM Data Binding in JavaScript

Things have changed a lot in the last 7 years, we have native web components in most browsers now. IMO the core of the problem is sharing state between elements, once you have that its trivial to update the ui when state changes and vice versa.

To share data between elements you can create a StateObserver class, and extend your web components from that. A minimal implementation looks something like this:

_x000D_
_x000D_
// create a base class to handle state_x000D_
class StateObserver extends HTMLElement {_x000D_
 constructor () {_x000D_
   super()_x000D_
    StateObserver.instances.push(this)_x000D_
  }_x000D_
 stateUpdate (update) {_x000D_
   StateObserver.lastState = StateObserver.state_x000D_
    StateObserver.state = update_x000D_
    StateObserver.instances.forEach((i) => {_x000D_
     if (!i.onStateUpdate) return_x000D_
     i.onStateUpdate(update, StateObserver.lastState)_x000D_
    })_x000D_
  }_x000D_
}_x000D_
_x000D_
StateObserver.instances = []_x000D_
StateObserver.state = {}_x000D_
StateObserver.lastState = {}_x000D_
_x000D_
// create a web component which will react to state changes_x000D_
class CustomReactive extends StateObserver {_x000D_
 onStateUpdate (state, lastState) {_x000D_
   if (state.someProp === lastState.someProp) return_x000D_
    this.innerHTML = `input is: ${state.someProp}`_x000D_
  }_x000D_
}_x000D_
customElements.define('custom-reactive', CustomReactive)_x000D_
_x000D_
class CustomObserved extends StateObserver {_x000D_
 connectedCallback () {_x000D_
   this.querySelector('input').addEventListener('input', (e) => {_x000D_
     this.stateUpdate({ someProp: e.target.value })_x000D_
    })_x000D_
  }_x000D_
}_x000D_
customElements.define('custom-observed', CustomObserved)
_x000D_
<custom-observed>_x000D_
  <input>_x000D_
</custom-observed>_x000D_
<br />_x000D_
<custom-reactive></custom-reactive>
_x000D_
_x000D_
_x000D_

fiddle here

I like this approach because:

  • no dom traversal to find data- properties
  • no Object.observe (deprecated)
  • no Proxy (which provides a hook but no communication mechanism anyway)
  • no dependencies, (other than a polyfill depending on your target browsers)
  • it's reasonably centralised & modular... describing state in html, and having listeners everywhere would get messy very quickly.
  • it's extensible. This basic implementation is 20 lines of code, but you could easily build up some convenience, immutability, and state shape magic to make it easier to work with.

std::string to float or double

The C++ 11 way is to use std::stod and std::to_string. Both work in Visual Studio 11.

Getting file size in Python?

Try

os.path.getsize(filename)

It should return the size of a file, reported by os.stat().

Python: Pandas pd.read_excel giving ImportError: Install xlrd >= 0.9.0 for Excel support

Please make sure your python or python3 can see xlrd installation. I had a situation where python3.5 and python3.7 were installed in two different locations. While xlrd was installed with python3.5, I was using python3 (from python3.7 dir) to run my script and got the same error reported above. When I used the correct python (viz. python3.5 dir) to run my script, I was able to read the excel spread sheet without a problem.

How do I get the difference between two Dates in JavaScript?

If using moment.js, there is a simpler solution, which will give you the difference in days in one single line of code.

moment(endDate).diff(moment(beginDate), 'days');

Additional details can be found in the moment.js page

Cheers, Miguel

Oracle Date TO_CHAR('Month DD, YYYY') has extra spaces in it

try this:-

select to_char(to_date('01/10/2017','dd/mm/yyyy'),'fmMonth fmDD,YYYY') from dual;

select to_char(sysdate,'fmMonth fmDD,YYYY') from dual;

HTML5 Form Input Pattern Currency Format

The best we could come up with is this:

^\\$?(([1-9](\\d*|\\d{0,2}(,\\d{3})*))|0)(\\.\\d{1,2})?$

I realize it might seem too much, but as far as I can test it matches anything that a human eye would accept as valid currency value and weeds out everything else.

It matches these:

1 => true
1.00 => true
$1 => true
$1000 => true
0.1 => true
1,000.00 => true
$1,000,000 => true
5678 => true

And weeds out these:

1.001 => false
02.0 => false
22,42 => false
001 => false
192.168.1.2 => false
, => false
.55 => false
2000,000 => false

Correct way to create rounded corners in Twitter Bootstrap

With bootstrap4 you can easily do it like this :-

class="rounded" 

or

class="rounded-circle"

Scala how can I count the number of occurrences in a list

A somewhat cleaner version of one of the other answers is:

val s = Seq("apple", "oranges", "apple", "banana", "apple", "oranges", "oranges")

s.groupBy(identity).mapValues(_.size)

giving a Map with a count for each item in the original sequence:

Map(banana -> 1, oranges -> 3, apple -> 3)

The question asks how to find the count of a specific item. With this approach, the solution would require mapping the desired element to its count value as follows:

s.groupBy(identity).mapValues(_.size)("apple")

How do I use cascade delete with SQL Server?

Use something like

ALTER TABLE T2
ADD CONSTRAINT fk_employee
FOREIGN KEY (employeeID)
REFERENCES T1 (employeeID)
ON DELETE CASCADE;

Fill in the correct column names and you should be set. As mark_s correctly stated, if you have already a foreign key constraint in place, you maybe need to delete the old one first and then create the new one.

Detect iPhone/iPad purely by css

This is how I handle iPhone (and similar) devices [not iPad]:

In my CSS file:

@media only screen and (max-width: 480px), only screen and (max-device-width: 480px) {
   /* CSS overrides for mobile here */
}

In the head of my HTML document:

<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no">

How to check if a number is a power of 2

bool IsPowerOfTwo(ulong x)
{
    return x > 0 && (x & (x - 1)) == 0;
}

List of <p:ajax> events

Unfortunatelly, Ajax events are poorly documented and I haven't found any comprehensive list. For example, User Guide v. 3.5 lists itemChange event for p:autoComplete, but forgets to mention change event.

If you want to find out which events are supported:

  1. Download and unpack primefaces source jar
  2. Find the JavaScript file, where your component is defined (for example, most form components such as SelectOneMenu are defined in forms.js)
  3. Search for this.cfg.behaviors references

For example, this section is responsible for launching toggleSelect event in SelectCheckboxMenu component:

fireToggleSelectEvent: function(checked) {
    if(this.cfg.behaviors) {
        var toggleSelectBehavior = this.cfg.behaviors['toggleSelect'];

        if(toggleSelectBehavior) {
            var ext = {
                params: [{name: this.id + '_checked', value: checked}]
            }
        }

        toggleSelectBehavior.call(this, null, ext);
    }
},

ERROR: Google Maps API error: MissingKeyMapError

All Google Maps JavaScript API applications require authentication( API KEY )

  1. Go to https://developers.google.com/maps/documentation/javascript/get-api-key.
  2. Login with Google Account
  3. Click on Get a key button 3 Select or create a project
  4. Click on Enable API ( Google Maps API)
  5. Copy YOUR API KEY in your Project: <script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=(Paste YOUR API KEY)"></script>

How can I start an interactive console for Perl?

I use the command line as a console:

$ perl -e 'print "JAPH\n"'

Then I can use my bash history to get back old commands. This does not preserve state, however.

This form is most useful when you want to test "one little thing" (like when answering Perl questions). Often, I find these commands get scraped verbatim into a shell script or makefile.

Is JavaScript's "new" keyword considered harmful?

I think "new" adds clarity to the code. And clarity is worth everything. Good to know there are pitfalls, but avoiding them by avoiding clarity doesn't seem like the way for me.

IEnumerable vs List - What to Use? How do they work?

IEnumerable describes behavior, while List is an implementation of that behavior. When you use IEnumerable, you give the compiler a chance to defer work until later, possibly optimizing along the way. If you use ToList() you force the compiler to reify the results right away.

Whenever I'm "stacking" LINQ expressions, I use IEnumerable, because by only specifying the behavior I give LINQ a chance to defer evaluation and possibly optimize the program. Remember how LINQ doesn't generate the SQL to query the database until you enumerate it? Consider this:

public IEnumerable<Animals> AllSpotted()
{
    return from a in Zoo.Animals
           where a.coat.HasSpots == true
           select a;
}

public IEnumerable<Animals> Feline(IEnumerable<Animals> sample)
{
    return from a in sample
           where a.race.Family == "Felidae"
           select a;
}

public IEnumerable<Animals> Canine(IEnumerable<Animals> sample)
{
    return from a in sample
           where a.race.Family == "Canidae"
           select a;
}

Now you have a method that selects an initial sample ("AllSpotted"), plus some filters. So now you can do this:

var Leopards = Feline(AllSpotted());
var Hyenas = Canine(AllSpotted());

So is it faster to use List over IEnumerable? Only if you want to prevent a query from being executed more than once. But is it better overall? Well in the above, Leopards and Hyenas get converted into single SQL queries each, and the database only returns the rows that are relevant. But if we had returned a List from AllSpotted(), then it may run slower because the database could return far more data than is actually needed, and we waste cycles doing the filtering in the client.

In a program, it may be better to defer converting your query to a list until the very end, so if I'm going to enumerate through Leopards and Hyenas more than once, I'd do this:

List<Animals> Leopards = Feline(AllSpotted()).ToList();
List<Animals> Hyenas = Canine(AllSpotted()).ToList();

Regular Expression to match only alphabetic characters

If you need to include non-ASCII alphabetic characters, and if your regex flavor supports Unicode, then

\A\pL+\z

would be the correct regex.

Some regex engines don't support this Unicode syntax but allow the \w alphanumeric shorthand to also match non-ASCII characters. In that case, you can get all alphabetics by subtracting digits and underscores from \w like this:

\A[^\W\d_]+\z

\A matches at the start of the string, \z at the end of the string (^ and $ also match at the start/end of lines in some languages like Ruby, or if certain regex options are set).

How can I count the occurrences of a list item?

l2=[1,"feto",["feto",1,["feto"]],['feto',[1,2,3,['feto']]]]
count=0
 def Test(l):   
        global count 
        if len(l)==0:
             return count
        count=l.count("feto")
        for i in l:
             if type(i) is list:
                count+=Test(i)
        return count   
    print(Test(l2))

this will recursive count or search for the item in the list even if it in list of lists

How can I stop Chrome from going into debug mode?

I have made it working...

Please follow the highlighted mark in the attached image.

Enter image description here

Mongoose: findOneAndUpdate doesn't return updated document

If you want to return the altered document you need to set the option {new:true} API reference you can use Cat.findOneAndUpdate(conditions, update, options, callback) // executes

Taken by the official Mongoose API http://mongoosejs.com/docs/api.html#findoneandupdate_findOneAndUpdate you can use the following parameters

A.findOneAndUpdate(conditions, update, options, callback) // executes
A.findOneAndUpdate(conditions, update, options)  // returns Query
A.findOneAndUpdate(conditions, update, callback) // executes
A.findOneAndUpdate(conditions, update)           // returns Query
A.findOneAndUpdate()                             // returns Query

Another implementation thats is not expressed in the official API page and is what I prefer to use is the Promise base implementation that allow you to have .catch where you can deal with all your various error there.

    let cat: catInterface = {
        name: "Naomi"
    };

    Cat.findOneAndUpdate({age:17}, cat,{new: true}).then((data) =>{
        if(data === null){
            throw new Error('Cat Not Found');
        }
        res.json({ message: 'Cat updated!' })
        console.log("New cat data", data);
    }).catch( (error) => {
        /*
            Deal with all your errors here with your preferred error handle middleware / method
         */
        res.status(500).json({ message: 'Some Error!' })
        console.log(error);
    });

Laravel view not found exception

Create the index.blade.php file in the views folder, that should be all

data type not understood

Try:

mmatrix = np.zeros((nrows, ncols))

Since the shape parameter has to be an int or sequence of ints

http://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html

Otherwise you are passing ncols to np.zeros as the dtype.

How to combine multiple inline style objects?

You can use the spread operator:

 <button style={{...styles.panel.button,...styles.panel.backButton}}>Back</button

Remove json element

You can try to delete the JSON as follows:

var bleh = {first: '1', second: '2', third:'3'}

alert(bleh.first);

delete bleh.first;

alert(bleh.first);

Alternatively, you can also pass in the index to delete an attribute:

delete bleh[1];

However, to understand some of the repercussions of using deletes, have a look here

How can I have two fixed width columns with one flexible column in the center?

Instead of using width (which is a suggestion when using flexbox), you could use flex: 0 0 230px; which means:

  • 0 = don't grow (shorthand for flex-grow)
  • 0 = don't shrink (shorthand for flex-shrink)
  • 230px = start at 230px (shorthand for flex-basis)

which means: always be 230px.

See fiddle, thanks @TylerH

Oh, and you don't need the justify-content and align-items here.

img {
    max-width: 100%;
}
#container {
    display: flex;
    x-justify-content: space-around;
    x-align-items: stretch;
    max-width: 1200px;
}
.column.left {
    width: 230px;
    flex: 0 0 230px;
}
.column.right {
    width: 230px;
    flex: 0 0 230px;
    border-left: 1px solid #eee;
}
.column.center {
    border-left: 1px solid #eee;
}

Why does calling sumr on a stream with 50 tuples not complete

sumr is implemented in terms of foldRight:

 final def sumr(implicit A: Monoid[A]): A = F.foldRight(self, A.zero)(A.append) 

foldRight is not always tail recursive, so you can overflow the stack if the collection is too long. See Why foldRight and reduceRight are NOT tail recursive? for some more discussion of when this is or isn't true.

Detecting arrow key presses in JavaScript

Arrow keys are only triggered by onkeydown, not onkeypress.

The keycodes are:

  • left = 37
  • up = 38
  • right = 39
  • down = 40

iOS for VirtualBox

VirtualBox is a virtualizer, not an emulator. (The name kinda gives it away.) I.e. it can only virtualize a CPU that is actually there, not emulate one that isn't. In particular, VirtualBox can only virtualize x86 and AMD64 CPUs. iOS only runs on ARM CPUs.

How to disable a link using only CSS?

One way you could do this with CSS, would be to set a CSS on a wrapping div that you set to disappear and something else takes it's place.

E.g.:

<div class="disabled">
    <a class="toggleLink" href="wherever">blah</a>
    <span class="toggleLink">blah</span
</div>

With a CSS like

.disabled a.toggleLink { display: none; }
span.toggleLink { display: none; }
.disabled span.toggleLink { display: inline; }

To actually turn off the a you'll have to replace it's click event or href, as described by others.

PS: Just to clarify I'd consider this a fairly untidy solution, and for SEO it's not the best either, but I believe it's the best with purely CSS.

Pretty Printing JSON with React

The 'react-json-view' provides solution rendering json string.

import ReactJson from 'react-json-view';
<ReactJson src={my_important_json} theme="monokai" />

Excel VBA Run-time error '13' Type mismatch

For future readers:

This function was abending in Run-time error '13': Type mismatch

Function fnIsNumber(Value) As Boolean
  fnIsNumber = Evaluate("ISNUMBER(0+""" & Value & """)")
End Function

In my case, the function was failing when it ran into a #DIV/0! or N/A value.

To solve it, I had to do this:

Function fnIsNumber(Value) As Boolean
   If CStr(Value) = "Error 2007" Then '<===== This is the important line
      fnIsNumber = False
   Else
      fnIsNumber = Evaluate("ISNUMBER(0+""" & Value & """)")
   End If
End Function

How do the major C# DI/IoC frameworks compare?

Disclaimer: As of early 2015, there is a great comparison of IoC Container features from Jimmy Bogard, here is a summary:

Compared Containers:

  • Autofac
  • Ninject
  • Simple Injector
  • StructureMap
  • Unity
  • Windsor

The scenario is this: I have an interface, IMediator, in which I can send a single request/response or a notification to multiple recipients:

public interface IMediator 
{ 
    TResponse Send<TResponse>(IRequest<TResponse> request);

    Task<TResponse> SendAsync<TResponse>(IAsyncRequest<TResponse> request);

    void Publish<TNotification>(TNotification notification)
        where TNotification : INotification;

    Task PublishAsync<TNotification>(TNotification notification)
        where TNotification : IAsyncNotification; 
}

I then created a base set of requests/responses/notifications:

public class Ping : IRequest<Pong>
{
    public string Message { get; set; }
}
public class Pong
{
    public string Message { get; set; }
}
public class PingAsync : IAsyncRequest<Pong>
{
    public string Message { get; set; }
}
public class Pinged : INotification { }
public class PingedAsync : IAsyncNotification { }

I was interested in looking at a few things with regards to container support for generics:

  • Setup for open generics (registering IRequestHandler<,> easily)
  • Setup for multiple registrations of open generics (two or more INotificationHandlers)

Setup for generic variance (registering handlers for base INotification/creating request pipelines) My handlers are pretty straightforward, they just output to console:

public class PingHandler : IRequestHandler<Ping, Pong> { /* Impl */ }
public class PingAsyncHandler : IAsyncRequestHandler<PingAsync, Pong> { /* Impl */ }

public class PingedHandler : INotificationHandler<Pinged> { /* Impl */ }
public class PingedAlsoHandler : INotificationHandler<Pinged> { /* Impl */ }
public class GenericHandler : INotificationHandler<INotification> { /* Impl */ }

public class PingedAsyncHandler : IAsyncNotificationHandler<PingedAsync> { /* Impl */ }
public class PingedAlsoAsyncHandler : IAsyncNotificationHandler<PingedAsync> { /* Impl */ }

Autofac

var builder = new ContainerBuilder();
builder.RegisterSource(new ContravariantRegistrationSource());
builder.RegisterAssemblyTypes(typeof (IMediator).Assembly).AsImplementedInterfaces();
builder.RegisterAssemblyTypes(typeof (Ping).Assembly).AsImplementedInterfaces();
  • Open generics: yes, implicitly
  • Multiple open generics: yes, implicitly
  • Generic contravariance: yes, explicitly

Ninject

var kernel = new StandardKernel();
kernel.Components.Add<IBindingResolver, ContravariantBindingResolver>();
kernel.Bind(scan => scan.FromAssemblyContaining<IMediator>()
    .SelectAllClasses()
    .BindDefaultInterface());
kernel.Bind(scan => scan.FromAssemblyContaining<Ping>()
    .SelectAllClasses()
    .BindAllInterfaces());
kernel.Bind<TextWriter>().ToConstant(Console.Out);
  • Open generics: yes, implicitly
  • Multiple open generics: yes, implicitly
  • Generic contravariance: yes, with user-built extensions

Simple Injector

var container = new Container();
var assemblies = GetAssemblies().ToArray();
container.Register<IMediator, Mediator>();
container.Register(typeof(IRequestHandler<,>), assemblies);
container.Register(typeof(IAsyncRequestHandler<,>), assemblies);
container.RegisterCollection(typeof(INotificationHandler<>), assemblies);
container.RegisterCollection(typeof(IAsyncNotificationHandler<>), assemblies);
  • Open generics: yes, explicitly
  • Multiple open generics: yes, explicitly
  • Generic contravariance: yes, implicitly (with update 3.0)

StructureMap

var container = new Container(cfg =>
{
    cfg.Scan(scanner =>
    {
        scanner.AssemblyContainingType<Ping>();
        scanner.AssemblyContainingType<IMediator>();
        scanner.WithDefaultConventions();
        scanner.AddAllTypesOf(typeof(IRequestHandler<,>));
        scanner.AddAllTypesOf(typeof(IAsyncRequestHandler<,>));
        scanner.AddAllTypesOf(typeof(INotificationHandler<>));
        scanner.AddAllTypesOf(typeof(IAsyncNotificationHandler<>));
    });
});
  • Open generics: yes, explicitly
  • Multiple open generics: yes, explicitly
  • Generic contravariance: yes, implicitly

Unity

container.RegisterTypes(AllClasses.FromAssemblies(typeof(Ping).Assembly),
   WithMappings.FromAllInterfaces,
   GetName,
   GetLifetimeManager);

/* later down */

static bool IsNotificationHandler(Type type)
{
    return type.GetInterfaces().Any(x => x.IsGenericType && (x.GetGenericTypeDefinition() == typeof(INotificationHandler<>) || x.GetGenericTypeDefinition() == typeof(IAsyncNotificationHandler<>)));
}

static LifetimeManager GetLifetimeManager(Type type)
{
    return IsNotificationHandler(type) ? new ContainerControlledLifetimeManager() : null;
}

static string GetName(Type type)
{
    return IsNotificationHandler(type) ? string.Format("HandlerFor" + type.Name) : string.Empty;
}
  • Open generics: yes, implicitly
  • Multiple open generics: yes, with user-built extension
  • Generic contravariance: derp

Windsor

var container = new WindsorContainer();
container.Register(Classes.FromAssemblyContaining<IMediator>().Pick().WithServiceAllInterfaces());
container.Register(Classes.FromAssemblyContaining<Ping>().Pick().WithServiceAllInterfaces());
container.Kernel.AddHandlersFilter(new ContravariantFilter());
  • Open generics: yes, implicitly
  • Multiple open generics: yes, implicitly
  • Generic contravariance: yes, with user-built extension

The term "Add-Migration" is not recognized

I ran into the same issue. Most of my projects had the same thing in tools.

"tools": {
    "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final"
}

This worked fine on all but one project. I changed the entry in tools to

"tools": {
    "Microsoft.EntityFrameworkCore.Tools": {
    "version": "1.0.0-preview2-final",
    "type": "build"
  }
}

And then ran dotnet restore. After the restore completed, Add-Migration worked normally.

What exactly is Apache Camel?

There are lot of frameworks that facilitates us for messaging and solving problems in messaging. One such product is Apache Camel.

Most of the common problems have proven solutions called as design patterns. The design pattern for messaging is Enterprise Integration patterns(EIPs) which are well explained here. Apache camel help us to implement our solution using the EIPs.

The strength of an integration framework is its ability to facilitate us through EIPs or other patterns,number of transports and components and ease of development on which Apache camel stands on the top of the list

Each of the Frameworks has its own advantages Some of the special features of Apache camel are the following.

  1. It provides the coding to be in many DSLs namely Java DSL and Spring xml based DSL , which are popular.
  2. Easy use and simple to use.
  3. Fuse IDE is a product that helps you to code through UI

How to convert JSON data into a Python object

While searching for a solution, I've stumbled upon this blog post: https://blog.mosthege.net/2016/11/12/json-deserialization-of-nested-objects/

It uses the same technique as stated in previous answers but with a usage of decorators. Another thing I found useful is the fact that it returns a typed object at the end of deserialisation

class JsonConvert(object):
    class_mappings = {}

    @classmethod
    def class_mapper(cls, d):
        for keys, cls in clsself.mappings.items():
            if keys.issuperset(d.keys()):   # are all required arguments present?
                return cls(**d)
        else:
            # Raise exception instead of silently returning None
            raise ValueError('Unable to find a matching class for object: {!s}'.format(d))

    @classmethod
    def complex_handler(cls, Obj):
        if hasattr(Obj, '__dict__'):
            return Obj.__dict__
        else:
            raise TypeError('Object of type %s with value of %s is not JSON serializable' % (type(Obj), repr(Obj)))

    @classmethod
    def register(cls, claz):
        clsself.mappings[frozenset(tuple([attr for attr,val in cls().__dict__.items()]))] = cls
        return cls

    @classmethod
    def to_json(cls, obj):
        return json.dumps(obj.__dict__, default=cls.complex_handler, indent=4)

    @classmethod
    def from_json(cls, json_str):
        return json.loads(json_str, object_hook=cls.class_mapper)

Usage:

@JsonConvert.register
class Employee(object):
    def __init__(self, Name:int=None, Age:int=None):
        self.Name = Name
        self.Age = Age
        return

@JsonConvert.register
class Company(object):
    def __init__(self, Name:str="", Employees:[Employee]=None):
        self.Name = Name
        self.Employees = [] if Employees is None else Employees
        return

company = Company("Contonso")
company.Employees.append(Employee("Werner", 38))
company.Employees.append(Employee("Mary"))

as_json = JsonConvert.to_json(company)
from_json = JsonConvert.from_json(as_json)
as_json_from_json = JsonConvert.to_json(from_json)

assert(as_json_from_json == as_json)

print(as_json_from_json)

How to do one-liner if else statement?

A very similar construction is available in the language

**if <statement>; <evaluation> {
   [statements ...]
} else {
   [statements ...]
}*

*

i.e.

if path,err := os.Executable(); err != nil {
   log.Println(err)
} else {
   log.Println(path)
}

connecting MySQL server to NetBeans

  1. Download XAMPP
  2. Run XAMPP server. Click on Start button in front of MY SQL. Now you can see that color is changed to green. Now, Click on Admin.The new browser window will be open. Copy the link from browser and paste to the Admin properties as shown in below. Set path in the admin properties of database connection. Click on OK. Now your database is connected. enter image description here

Simple PHP form: Attachment to email (code golf)

This article "How to create PHP based email form with file attachment" presents step-by-step instructions how to achieve your requirement.

Quote:

This article shows you how to create a PHP based email form that supports file attachment. The article will also show you how to validate the type and size of the uploaded file.

It consists of the following steps:

  • The HTML form with file upload box
  • Getting the uploaded file in the PHP script
  • Validating the size and extension of the uploaded file
  • Copy the uploaded file
  • Sending the Email

The entire example code can be downloaded here

C# get and set properties for a List Collection

Your setters are strange, which is why you may be seeing a problem.

First, consider whether you even need these setters - if so, they should take a List<string>, not just a string:

set
{
    _subHead = value;
}

These lines:

newSec.subHead.Add("test string");

Are calling the getter and then call Add on the returned List<string> - the setter is not invoked.

Is it possible to append Series to rows of DataFrame without making a list first?

Try using this command. See the example given below:

Before image

df.loc[len(df)] = ['Product 9',99,9.99,8.88,1.11]

df

After Image

How do I collapse sections of code in Visual Studio Code for Windows?

With JavaScript:

//#region REGION_NAME
   ...code here
//#endregion

How to set only time part of a DateTime variable in C#

Use the constructor that allows you to specify the year, month, day, hours, minutes, and seconds:

var dateNow = DateTime.Now;
var date = new DateTime(dateNow.Year, dateNow.Month, dateNow.Day, 4, 5, 6);

Links in <select> dropdown options

You can use this code:

<select id="menu" name="links" size="1" onchange="window.location.href=this.value;">
    <option value="URL">Book</option>
    <option value="URL">Pen</option>
    <option value="URL">Read</option>
    <option value="URL">Apple</option>
</select>

How to write palindrome in JavaScript

Alternative solution for using Array.prototype.every()

function palindrome(str) {
  return str.split('').every((char, index) => {
     return char === str[str.length - index - 1];
  });
}

Error : Program type already present: android.support.design.widget.CoordinatorLayout$Behavior

Important Update

Android support libraries will not be updated after 28.0.0. According to Support Library Release Notes -

This will be the last feature release under the android.support packaging, and developers are encouraged to migrate to AndroidX 1.0.0.

So use AndroidX support libraries instead. In your case design library is now available in material package.

dependencies {
    implementation 'com.google.android.material:material:1.0.0' // instead of design
    implementation 'androidx.appcompat:appcompat:1.0.2' // instead of support-v7
}

I have put latest versions in dependency, you can check latest version here at read time.

Useful Posts :

  1. AndroidX introduction & integration
  2. Learn about Jetifier (engine behind AndroidX migration)
  3. Some Do's and Dont's

What are the advantages of NumPy over regular Python lists?

All have highlighted almost all major differences between numpy array and python list, I will just brief them out here:

  1. Numpy arrays have a fixed size at creation, unlike python lists (which can grow dynamically). Changing the size of ndarray will create a new array and delete the original.

  2. The elements in a Numpy array are all required to be of the same data type (we can have the heterogeneous type as well but that will not gonna permit you mathematical operations) and thus will be the same size in memory

  3. Numpy arrays are facilitated advances mathematical and other types of operations on large numbers of data. Typically such operations are executed more efficiently and with less code than is possible using pythons build in sequences

Div height 100% and expands to fit content

Old question, but in my case i found using position:fixed solved it for me. My situation might have been a little different though. I had an overlayed semi transparent div with a loading animation in it that I needed displayed while the page was loading. So using height:auto / 100% or min-height: 100% both filled the window but not the off-screen area. Using position:fixed made this overlay scroll with the user, so it always covered the visible area and kept my preloading animation centred on the screen.

Focusable EditText inside ListView

I just found another solution. I believe it's more a hack than a solution but it works on android 2.3.7 and android 4.3 (I've even tested that good old D-pad)

init your webview as usual and add this: (thanks Michael Bierman)

listView.setItemsCanFocus(true);

During the getView call:

editText.setOnFocusChangeListener(
    new OnFocusChangeListener(View view,boolean hasFocus){
        view.post(new Runnable() {
            @Override
            public void run() {
                view.requestFocus();
                view.requestFocusFromTouch();
            }
     });

Python update a key in dict if it doesn't exist

Since Python 3.9 you can use the merge operator | to merge two dictionaries. The dict on the right takes precedence:

new_dict = old_dict | { key: val }

For example:

new_dict = { 'a': 1, 'b': 2 } | { 'b': 42 }

print(new_dict} # {'a': 1, 'b': 42}

Note: this creates a new dictionary with the updated values.

How to see PL/SQL Stored Function body in Oracle

You can also use DBMS_METADATA:

select dbms_metadata.get_ddl('FUNCTION', 'FGETALGOGROUPKEY', 'PADCAMPAIGN') 
from dual

Get the directory from a file path in java (android)

I have got solution on this after 4 days, Please note following points while giving path to File class in Android(Java):

  1. Use path for internal storage String path="/storage/sdcard0/myfile.txt";
  2. path="/storage/sdcard1/myfile.txt";
  3. mention permissions in Manifest file.

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

  4. First check file length for confirmation.
  5. Check paths in ES File Explorer regarding sdcard0 & sdcard1 is this same or else......

e.g.

File file=new File(path);
long=file.length();//in Bytes

How can I align text directly beneath an image?

You can use HTML5 <figcaption>:

<figure>
  <img src="img.jpg" alt="my img"/>
  <figcaption> Your text </figcaption>
</figure>

Working example.

Getting the name of the currently executing method

Most answers here seems wrong.

    public static String getCurrentMethod() {
            return getCurrentMethod(1);
    }
    public static String getCurrentMethod(int skip) {
            return Thread.currentThread().getStackTrace()[1 + 1 + skip].getMethodName();
    }

Example:

    public static void main(String[] args) {
            aaa();
    }

    public static void aaa() {
            System.out.println("aaa  -> "  + getCurrentMethod( ) );
            System.out.println("aaa  -> "  + getCurrentMethod(0) );
            System.out.println("main -> "  + getCurrentMethod(1) );
    }

Outputs:

aaa  -> aaa
aaa  -> aaa
main -> main

How do you use variables in a simple PostgreSQL script?

DO $$
DECLARE  
   a integer := 10;  
   b integer := 20;  
   c integer;  
BEGIN  
   c := a + b;
    RAISE NOTICE'Value of c: %', c;
END $$;

Remove git mapping in Visual Studio 2015

NoGit extension simply hides the problem, by turning off the Git source control provider each time the solution is loaded. It does this job for every solution that is loaded in Visual Studio.

I solved by opening another project and removing the Git repository from the Local Git Repositories, as Chris C. suggested (View > Team Explorer > Local Git Repositories, select the repository that has to be removed and click Remove). Then I removed .git folder from the project path, as suggested by helix. Reopened the project and finally Git integration was gone!

document.getElementById().value and document.getElementById().checked not working for IE

The code you pasted should work... There must be something else we are not seeing here.

Check this out. Working for me fine on IE7. When you submit you will see the variable passed in the URL.

How to resolve javax.mail.AuthenticationFailedException issue?

This error is from google security... This Can Be Resolved by Enabling Less Secure .

Go To This Link : "https://www.google.com/settings/security/lesssecureapps" and Make "TURN ON" then your application runs For Sure.

substring of an entire column in pandas dataframe

I needed to convert a single column of strings of form nn.n% to float. I needed to remove the % from the element in each row. The attend data frame has two columns.

attend.iloc[:,1:2]=attend.iloc[:,1:2].applymap(lambda x: float(x[:-1]))

Its an extenstion to the original answer. In my case it takes a dataframe and applies a function to each value in a specific column. The function removes the last character and converts the remaining string to float.

Use Async/Await with Axios in React.js

Async/Await with axios 

  useEffect(() => {     
    const getData = async () => {  
      await axios.get('your_url')  
      .then(res => {  
        console.log(res)  
      })  
      .catch(err => {  
        console.log(err)  
      });  
    }  
    getData()  
  }, [])

Optional Parameters in Go?

No -- neither. Per the Go for C++ programmers docs,

Go does not support function overloading and does not support user defined operators.

I can't find an equally clear statement that optional parameters are unsupported, but they are not supported either.

How to pretty print XML from Java?

I saw one answer using Scala, so here is another one in Groovy, just in case someone finds it interesting. The default indentation is 2 steps, XmlNodePrinter constructor can be passed another value as well.

def xml = "<tag><nested>hello</nested></tag>"
def stringWriter = new StringWriter()
def node = new XmlParser().parseText(xml);
new XmlNodePrinter(new PrintWriter(stringWriter)).print(node)
println stringWriter.toString()

Usage from Java if groovy jar is in classpath

  String xml = "<tag><nested>hello</nested></tag>";
  StringWriter stringWriter = new StringWriter();
  Node node = new XmlParser().parseText(xml);
  new XmlNodePrinter(new PrintWriter(stringWriter)).print(node);
  System.out.println(stringWriter.toString());

How to import data from one sheet to another

VLookup

You can do it with a simple VLOOKUP formula. I've put the data in the same sheet, but you can also reference a different worksheet. For the price column just change the last value from 2 to 3, as you are referencing the third column of the matrix "A2:C4". VLOOKUP example

External Reference

To reference a cell of the same Workbook use the following pattern:

<Sheetname>!<Cell>

Example:

Table1!A1

To reference a cell of a different Workbook use this pattern:

[<Workbook_name>]<Sheetname>!<Cell>

Example:

[MyWorkbook]Table1!A1

PHP find difference between two datetimes

Sorry my previous answer was wrong. If you are trying to take total elapsed time between time and timeout in the format Y-m-d H:i:s format, take diff between timeout and time in using DateTime object and format it as '%y-%m-%d %H:%i:%s'.

Return value using String result=Command.ExecuteScalar() error occurs when result returns null

Value is not null, but DBNull.Value.

object value = cmd.ExecuteScalar();
if(value == DBNull.Value)

How do you add an action to a button programmatically in xcode

try this:

first write this in your .h file of viewcontroller

UIButton *btn;

Now write this in your .m file of viewcontrollers viewDidLoad.

btn=[[UIButton alloc]initWithFrame:CGRectMake(50, 20, 30, 30)];
[btn setBackgroundColor:[UIColor orangeColor]];
//adding action programatically
[btn addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];

write this outside viewDidLoad method in .m file of your view controller

- (IBAction)btnClicked:(id)sender
{
   //Write a code you want to execute on buttons click event
}

Return in Scala

Use case match for early return purpose. It will force you to declare all return branches explicitly, preventing the careless mistake of forgetting to write return somewhere.

php mysqli_connect: authentication method unknown to the client [caching_sha2_password]

Now you can upgrade to PHP7.4 and MySQL will go with caching_sha2_password by default, so default MySQL installation will work with mysqli_connect No configuration required.

shell script. how to extract string using regular expressions

Using bash regular expressions:

re="http://([^/]+)/"
if [[ $name =~ $re ]]; then echo ${BASH_REMATCH[1]}; fi

Edit - OP asked for explanation of syntax. Regular expression syntax is a large topic which I can't explain in full here, but I will attempt to explain enough to understand the example.

re="http://([^/]+)/"

This is the regular expression stored in a bash variable, re - i.e. what you want your input string to match, and hopefully extract a substring. Breaking it down:

  • http:// is just a string - the input string must contain this substring for the regular expression to match
  • [] Normally square brackets are used say "match any character within the brackets". So c[ao]t would match both "cat" and "cot". The ^ character within the [] modifies this to say "match any character except those within the square brackets. So in this case [^/] will match any character apart from "/".
  • The square bracket expression will only match one character. Adding a + to the end of it says "match 1 or more of the preceding sub-expression". So [^/]+ matches 1 or more of the set of all characters, excluding "/".
  • Putting () parentheses around a subexpression says that you want to save whatever matched that subexpression for later processing. If the language you are using supports this, it will provide some mechanism to retrieve these submatches. For bash, it is the BASH_REMATCH array.
  • Finally we do an exact match on "/" to make sure we match all the way to end of the fully qualified domain name and the following "/"

Next, we have to test the input string against the regular expression to see if it matches. We can use a bash conditional to do that:

if [[ $name =~ $re ]]; then
    echo ${BASH_REMATCH[1]}
fi

In bash, the [[ ]] specify an extended conditional test, and may contain the =~ bash regular expression operator. In this case we test whether the input string $name matches the regular expression $re. If it does match, then due to the construction of the regular expression, we are guaranteed that we will have a submatch (from the parentheses ()), and we can access it using the BASH_REMATCH array:

  • Element 0 of this array ${BASH_REMATCH[0]} will be the entire string matched by the regular expression, i.e. "http://www.google.com/".
  • Subsequent elements of this array will be subsequent results of submatches. Note you can have multiple submatch () within a regular expression - The BASH_REMATCH elements will correspond to these in order. So in this case ${BASH_REMATCH[1]} will contain "www.google.com", which I think is the string you want.

Note that the contents of the BASH_REMATCH array only apply to the last time the regular expression =~ operator was used. So if you go on to do more regular expression matches, you must save the contents you need from this array each time.

This may seem like a lengthy description, but I have really glossed over several of the intricacies of regular expressions. They can be quite powerful, and I believe with decent performance, but the regular expression syntax is complex. Also regular expression implementations vary, so different languages will support different features and may have subtle differences in syntax. In particular escaping of characters within a regular expression can be a thorny issue, especially when those characters would have an otherwise different meaning in the given language.


Note that instead of setting the $re variable on a separate line and referring to this variable in the condition, you can put the regular expression directly into the condition. However in bash 3.2, the rules were changed regarding whether quotes around such literal regular expressions are required or not. Putting the regular expression in a separate variable is a straightforward way around this, so that the condition works as expected in all bash versions that support the =~ match operator.

Passing array in GET for a REST call

I think it's a better practice to serialize your REST call parameters, usually by JSON-encoding them:

/appointments?users=[id1,id2]

or even:

/appointments?params={users:[id1,id2]}

Then you un-encode them on the server. This is going to give you more flexibility in the long run.

Just make sure to URLEncode the params as well before you send them!

MySQL Error 1264: out of range value for column

You can also change the data type to bigInt and it will solve your problem, it's not a good practice to keep integers as strings unless needed. :)

ALTER TABLE T_PERSON MODIFY mobile_no BIGINT;

How to display svg icons(.svg files) in UI using React Component?

if you have .svg or an image locally. first you have to install the loader needed for svg and file-loader for images. Then you have to import your icon or image first for example:

import logo from './logos/myLogo.svg' ;
import image from './images/myimage.png';

const temp = (
     <div>
         <img src={logo} />
         <img src={image} />
     </div>
);

ReactDOM.render(temp,document.getElementByID("app"));

Happy Coding :")

resources from react website and worked for me after many searches: https://create-react-app.dev/docs/adding-images-fonts-and-files/

How do I rename a repository on GitHub?

  1. open this url (https://github.com/) from your browser

  2. Go to repositories at the Right end of the page

  3. Open the link of repository that you want to rename

  4. click Settings (you will find in the Navigation bar)

  5. At the top you will find a box Called (Repository name) where you write the new name

  6. Press Rename

UTF-8 problems while reading CSV file with fgetcsv

Try this:

<?php
$handle = fopen ("specialchars.csv","r");
echo '<table border="1"><tr><td>First name</td><td>Last name</td></tr><tr>';
while ($data = fgetcsv ($handle, 1000, ";")) {
        $data = array_map("utf8_encode", $data); //added
        $num = count ($data);
        for ($c=0; $c < $num; $c++) {
            // output data
            echo "<td>$data[$c]</td>";
        }
        echo "</tr><tr>";
}
?>

How to take complete backup of mysql database using mysqldump command line utility

I am using MySQL 5.5.40. This version has the option --all-databases

mysqldump -u<username> -p<password> --all-databases --events > /tmp/all_databases__`date +%d_%b_%Y_%H_%M_%S`.sql

This command will create a complete backup of all databases in MySQL server to file named to current date-time.

How to select <td> of the <table> with javascript?

There begin to appear some answers that assume you want to get all <td> elements from #table. If so, the simplest cross-browser way how to do this is document.getElementById('table').getElementsByTagName('td'). This works because getElementsByTagName doesn't return only immediate children. No loops are needed.

How do I validate a date string format in python?

I think the full validate function should look like this:

from datetime import datetime

def validate(date_text):
    try:
        if date_text != datetime.strptime(date_text, "%Y-%m-%d").strftime('%Y-%m-%d'):
            raise ValueError
        return True
    except ValueError:
        return False

Executing just

datetime.strptime(date_text, "%Y-%m-%d") 

is not enough because strptime method doesn't check that month and day of the month are zero-padded decimal numbers. For example

datetime.strptime("2016-5-3", '%Y-%m-%d')

will be executed without errors.

Calling Javascript from a html form

You can either use javascript url form with

<form action="javascript:handleClick()">

Or use onSubmit event handler

<form onSubmit="return handleClick()">

In the later form, if you return false from the handleClick it will prevent the normal submision procedure. Return true if you want the browser to follow normal submision procedure.

Your onSubmit event handler in the button also fails because of the Javascript: part

EDIT: I just tried this code and it works:

<html>
  <head>
    <script type="text/javascript">

      function handleIt() {
        alert("hello");
      }

    </script>
  </head>

<body>
    <form name="myform" action="javascript:handleIt()">
      <input name="Submit"  type="submit" value="Update"/>
    </form>
</body>
</html>

Calculate date from week number

Week 1 is defined as being the week that starts on a Monday and contains the first Thursday of the year.

Web.Config Debug/Release

To make the transform work in development (using F5 or CTRL + F5) I drop ctt.exe (https://ctt.codeplex.com/) in the packages folder (packages\ConfigTransform\ctt.exe).

Then I register a pre- or post-build event in Visual Studio...

$(SolutionDir)packages\ConfigTransform\ctt.exe source:"$(ProjectDir)connectionStrings.config" transform:"$(ProjectDir)connectionStrings.$(ConfigurationName).config" destination:"$(ProjectDir)connectionStrings.config"
$(SolutionDir)packages\ConfigTransform\ctt.exe source:"$(ProjectDir)web.config" transform:"$(ProjectDir)web.$(ConfigurationName).config" destination:"$(ProjectDir)web.config"

For the transforms I use SlowCheeta VS extension (https://visualstudiogallery.msdn.microsoft.com/69023d00-a4f9-4a34-a6cd-7e854ba318b5).

How to work on UAC when installing XAMPP

Just go to start > type search box uac press enter > you will see 'Change user account control settings' > down the you will see never notify. Click on OK. And you are done.

Can we set a Git default to fetch all tags during a remote pull?

You should be able to accomplish this by adding a refspec for tags to your local config. Concretely:

[remote "upstream"]
    url = <redacted>
    fetch = +refs/heads/*:refs/remotes/upstream/*
    fetch = +refs/tags/*:refs/tags/*

Add leading zeroes/0's to existing Excel values to certain length

Even this will work nicely

REPT(0,2-LEN(F2)&F2

where 2 is total number of digits, for 0 ~ 9 -> it will display 00 to 09 rest nothing will be added.

Solving Quadratic Equation

How about accepting complex roots as solutions?

import math

# User inserting the values of a, b and c

a = float(input("Insert coefficient a: "))
b = float(input("Insert coefficient b: "))
c = float(input("Insert coefficient c: "))

discriminant = b**2 - 4 * a * c

if discriminant >= 0:
    x_1=(-b+math.sqrt(discriminant))/2*a
    x_2=(-b-math.sqrt(discriminant))/2*a
else:
    x_1= complex((-b/(2*a)),math.sqrt(-discriminant)/(2*a))
    x_2= complex((-b/(2*a)),-math.sqrt(-discriminant)/(2*a))

if discriminant > 0:
    print("The function has two distinct real roots: ", x_1, " and ", x_2)
elif discriminant == 0:
    print("The function has one double root: ", x_1)
else:
    print("The function has two complex (conjugate) roots: ", x_1, " and ", x_2)

Get final URL after curl is redirected

Can you try with it?

#!/bin/bash 
LOCATION=`curl -I 'http://your-domain.com/url/redirect?r=something&a=values-VALUES_FILES&e=zip' | perl -n -e '/^Location: (.*)$/ && print "$1\n"'` 
echo "$LOCATION"

Note: when you execute the command curl -I http://your-domain.com have to use single quotes in the command like curl -I 'http://your-domain.com'

Getting min and max Dates from a pandas dataframe

min(df['some_property'])
max(df['some_property'])

The built-in functions work well with Pandas Dataframes.

Get Last Part of URL PHP

One liner: $page_path = end(explode('/', trim($_SERVER['REQUEST_URI'], '/')));

Get URI, trim slashes, convert to array, grab last part

long long int vs. long int vs. int64_t in C++

Do you want to know if a type is the same type as int64_t or do you want to know if something is 64 bits? Based on your proposed solution, I think you're asking about the latter. In that case, I would do something like

template<typename T>
bool is_64bits() { return sizeof(T) * CHAR_BIT == 64; } // or >= 64

How to find duplicate records in PostgreSQL

From "Find duplicate rows with PostgreSQL" here's smart solution:

select * from (
  SELECT id,
  ROW_NUMBER() OVER(PARTITION BY column1, column2 ORDER BY id asc) AS Row
  FROM tbl
) dups
where 
dups.Row > 1

What ports does RabbitMQ use?

What ports is RabbitMQ using?

Default: 5672, the manual has the answer. It's defined in the RABBITMQ_NODE_PORT variable.

https://www.rabbitmq.com/configure.html#define-environment-variables

The number might be differently if changed by someone in the rabbitmq configuration file:

vi /etc/rabbitmq/rabbitmq-env.conf

Ask the computer to tell you:

sudo nmap -p 1-65535 localhost

Starting Nmap 5.51 ( http://nmap.org ) at 2014-09-19 13:50 EDT
Nmap scan report for localhost (127.0.0.1)
Host is up (0.00041s latency).
PORT      STATE         SERVICE
443/tcp   open          https
5672/tcp  open          amqp
15672/tcp open  unknown
35102/tcp open  unknown
59440/tcp open  unknown

Oh look, 5672, and 15672

Use netstat:

netstat -lntu
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address               Foreign Address             State
tcp        0      0 0.0.0.0:15672               0.0.0.0:*                   LISTEN
tcp        0      0 0.0.0.0:55672               0.0.0.0:*                   LISTEN
tcp        0      0 :::5672                     :::*                        LISTEN

Oh look 5672.

use lsof:

eric@dev ~$ sudo lsof -i | grep beam
beam.smp  21216    rabbitmq   17u  IPv4 33148214      0t0  TCP *:55672 (LISTEN)
beam.smp  21216    rabbitmq   18u  IPv4 33148219      0t0  TCP *:15672 (LISTEN)

use nmap from a different machine, find out if 5672 is open:

sudo nmap -p 5672 10.0.1.71
Starting Nmap 5.51 ( http://nmap.org ) at 2014-09-19 13:19 EDT
Nmap scan report for 10.0.1.71
Host is up (0.00011s latency).
PORT     STATE SERVICE
5672/tcp open  amqp
MAC Address: 0A:40:0E:8C:75:6C (Unknown)    
Nmap done: 1 IP address (1 host up) scanned in 0.13 seconds

Try to connect to a port manually with telnet, 5671 is CLOSED:

telnet localhost 5671
Trying 127.0.0.1...
telnet: connect to address 127.0.0.1: Connection refused

Try to connect to a port manually with telnet, 5672 is OPEN:

telnet localhost 5672
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.

Check your firewall:

sudo cat /etc/sysconfig/iptables  

It should tell you what ports are made open:

-A INPUT -p tcp -m tcp --dport 5672 -j ACCEPT

Reapply your firewall:

sudo service iptables restart
iptables: Setting chains to policy ACCEPT: filter          [  OK  ]
iptables: Flushing firewall rules:                         [  OK  ]
iptables: Unloading modules:                               [  OK  ]
iptables: Applying firewall rules:                         [  OK  ]

Set folder browser dialog start location

In my case, it was an accidental double escaping.

this works:

SelectedPath = @"C:\Program Files\My Company\My product";

this doesn't:

SelectedPath = @"C:\\Program Files\\My Company\\My product";

Read only the first line of a file?

Lots of other answers here, but to answer precisely the question you asked (before @MarkAmery went and edited the original question and changed the meaning):

>>> f = open('myfile.txt')
>>> data = f.read()
>>> # I'm assuming you had the above before asking the question
>>> first_line = data.split('\n', 1)[0]

In other words, if you've already read in the file (as you said), and have a big block of data in memory, then to get the first line from it efficiently, do a split() on the newline character, once only, and take the first element from the resulting list.

Note that this does not include the \n character at the end of the line, but I'm assuming you don't want it anyway (and a single-line file may not even have one). Also note that although it's pretty short and quick, it does make a copy of the data, so for a really large blob of memory you may not consider it "efficient". As always, it depends...

How do I print the content of httprequest request?

You can print the request type using:

request.getMethod();

You can print all the headers as mentioned here:

Enumeration<String> headerNames = request.getHeaderNames();
while(headerNames.hasMoreElements()) {
  String headerName = headerNames.nextElement();
  System.out.println("Header Name - " + headerName + ", Value - " + request.getHeader(headerName));
}

To print all the request params, use this:

Enumeration<String> params = request.getParameterNames(); 
while(params.hasMoreElements()){
 String paramName = params.nextElement();
 System.out.println("Parameter Name - "+paramName+", Value - "+request.getParameter(paramName));
}

request is the instance of HttpServletRequest

You can beautify the outputs as you desire.

Upgrading PHP in XAMPP for Windows?

I have upgraded to php7.2 from php5.6

Steps which I followed.

  1. Download PHP binary from here. I have downloaded VC15 x86 Thread Safe Zip file.
  2. Created a backup of xampp/php folder.
  3. Extract all the contents of zip file to xampp/php folder.
  4. Copied php.ini (as I have modified it before and I want my configuration back, if you were using default one then skip this step.)
  5. Edit below file

C:\xampp\apache\conf\extra\http-xampp.conf

5.1. Replace

LoadFile "C:/xampp/php/php5ts.dll"

LoadFile "C:/xampp/php/libpq.dll"

LoadModule php5_module "C:/xampp/php/php5apache2_4.dll"

to

LoadFile "C:/xampp/php/php7ts.dll"

LoadFile "C:/xampp/php/libpq.dll"

LoadModule php7_module "C:/xampp/php/php7apache2_4.dll"

  1. Restart Apache

C++, copy set to vector

set<T> s;
//....
vector<T> v;
v.assign(s.begin(), s.end());

Javascript : get <img> src and set as variable?

How about this for instance :

var youtubeimgsrc = document.getElementById("youtubeimg").getAttribute('src');

Bash array with spaces in elements

I think the issue might be partly with how you're accessing the elements. If I do a simple for elem in $FILES, I experience the same issue as you. However, if I access the array through its indices, like so, it works if I add the elements either numerically or with escapes:

for ((i = 0; i < ${#FILES[@]}; i++))
do
    echo "${FILES[$i]}"
done

Any of these declarations of $FILES should work:

FILES=(2011-09-04\ 21.43.02.jpg
2011-09-05\ 10.23.14.jpg
2011-09-09\ 12.31.16.jpg
2011-09-11\ 08.43.12.jpg)

or

FILES=("2011-09-04 21.43.02.jpg"
"2011-09-05 10.23.14.jpg"
"2011-09-09 12.31.16.jpg"
"2011-09-11 08.43.12.jpg")

or

FILES[0]="2011-09-04 21.43.02.jpg"
FILES[1]="2011-09-05 10.23.14.jpg"
FILES[2]="2011-09-09 12.31.16.jpg"
FILES[3]="2011-09-11 08.43.12.jpg"

EF Migrations: Rollback last applied migration?

Update-Database –TargetMigration:"Your migration name"

For this problem I suggest this link:

https://elegantcode.com/2012/04/12/entity-framework-migrations-tips/

Error in <my code> : object of type 'closure' is not subsettable

I had this issue was trying to remove a ui element inside an event reactive:

myReactives <- eventReactive(input$execute, {
    ... # Some other long running function here
    removeUI(selector = "#placeholder2")
})

I was getting this error, but not on the removeUI element line, it was in the next observer after for some reason. Taking the removeUI method out of the eventReactive and placing it somewhere else removed this error for me.

What causes "Unable to access jarfile" error?

I was trying this:

After giving the file read, write, execute priviledges:

chmod 777 java-repl.jar

alias jr="java -jar $HOME/Dev/java-repl/java-repl.jar"

Unable to access bla bla..., this was on Mac OS though

So I tried this:

alias jr="cd $HOME/Dev/java-repl/ && java -jar java-repl.jar"

"Prevent saving changes that require the table to be re-created" negative effects

Yes, there are negative effects from this:

If you script out a change blocked by this flag you get something like the script below (all i am turning the ID column in Contact into an autonumbered IDENTITY column, but the table has dependencies). Note potential errors that can occur while the following is running:

  1. Even microsoft warns that this may cause data loss (that comment is auto-generated)!
  2. for a period of time, foreign keys are not enforced.
  3. if you manually run this in ssms and the ' EXEC('INSERT INTO ' fails, and you let the following statements run (which they do by default, as they are split by 'go') then you will insert 0 rows, then drop the old table.
  4. if this is a big table, the runtime of the insert can be large, and the transaction is holding a schema modification lock, so blocks many things.

--

/* To prevent any potential data loss issues, you should review this script in detail before running it outside the context of the database designer.*/

BEGIN TRANSACTION
GO
ALTER TABLE raw.Contact
    DROP CONSTRAINT fk_Contact_AddressType
GO
ALTER TABLE ref.ContactpointType SET (LOCK_ESCALATION = TABLE)
GO
COMMIT
BEGIN TRANSACTION
GO
ALTER TABLE raw.Contact
    DROP CONSTRAINT fk_contact_profile
GO
ALTER TABLE raw.Profile SET (LOCK_ESCALATION = TABLE)
GO
COMMIT
BEGIN TRANSACTION
GO
CREATE TABLE raw.Tmp_Contact
    (
    ContactID int NOT NULL IDENTITY (1, 1),
    ProfileID int NOT NULL,
    AddressType char(2) NOT NULL,
    ContactText varchar(250) NULL
    )  ON [PRIMARY]
GO
ALTER TABLE raw.Tmp_Contact SET (LOCK_ESCALATION = TABLE)
GO
SET IDENTITY_INSERT raw.Tmp_Contact ON
GO
IF EXISTS(SELECT * FROM raw.Contact)
     EXEC('INSERT INTO raw.Tmp_Contact (ContactID, ProfileID, AddressType, ContactText)
        SELECT ContactID, ProfileID, AddressType, ContactText FROM raw.Contact WITH (HOLDLOCK TABLOCKX)')
GO
SET IDENTITY_INSERT raw.Tmp_Contact OFF
GO
ALTER TABLE raw.PostalAddress
    DROP CONSTRAINT fk_AddressProfile
GO
ALTER TABLE raw.MarketingFlag
    DROP CONSTRAINT fk_marketingflag_contact
GO
ALTER TABLE raw.Phones
    DROP CONSTRAINT fk_phones_contact
GO
DROP TABLE raw.Contact
GO
EXECUTE sp_rename N'raw.Tmp_Contact', N'Contact', 'OBJECT' 
GO
ALTER TABLE raw.Contact ADD CONSTRAINT
    Idx_Contact_1 PRIMARY KEY CLUSTERED 
    (
    ProfileID,
    ContactID
    ) 

GO
ALTER TABLE raw.Contact ADD CONSTRAINT
    Idx_Contact UNIQUE NONCLUSTERED 
    (
    ProfileID,
    ContactID
    ) 

GO
CREATE NONCLUSTERED INDEX idx_Contact_0 ON raw.Contact
    (
    AddressType
    ) 
GO
ALTER TABLE raw.Contact ADD CONSTRAINT
    fk_contact_profile FOREIGN KEY
    (
    ProfileID
    ) REFERENCES raw.Profile
    (
    ProfileID
    ) ON UPDATE  NO ACTION 
     ON DELETE  NO ACTION 

GO
ALTER TABLE raw.Contact ADD CONSTRAINT
    fk_Contact_AddressType FOREIGN KEY
    (
    AddressType
    ) REFERENCES ref.ContactpointType
    (
    ContactPointTypeCode
    ) ON UPDATE  NO ACTION 
     ON DELETE  NO ACTION 

GO
COMMIT
BEGIN TRANSACTION
GO
ALTER TABLE raw.Phones ADD CONSTRAINT
    fk_phones_contact FOREIGN KEY
    (
    ProfileID,
    PhoneID
    ) REFERENCES raw.Contact
    (
    ProfileID,
    ContactID
    ) ON UPDATE  NO ACTION 
     ON DELETE  NO ACTION 

GO
ALTER TABLE raw.Phones SET (LOCK_ESCALATION = TABLE)
GO
COMMIT
BEGIN TRANSACTION
GO
ALTER TABLE raw.MarketingFlag ADD CONSTRAINT
    fk_marketingflag_contact FOREIGN KEY
    (
    ProfileID,
    ContactID
    ) REFERENCES raw.Contact
    (
    ProfileID,
    ContactID
    ) ON UPDATE  NO ACTION 
     ON DELETE  NO ACTION 

GO
ALTER TABLE raw.MarketingFlag SET (LOCK_ESCALATION = TABLE)
GO
COMMIT
BEGIN TRANSACTION
GO
ALTER TABLE raw.PostalAddress ADD CONSTRAINT
    fk_AddressProfile FOREIGN KEY
    (
    ProfileID,
    AddressID
    ) REFERENCES raw.Contact
    (
    ProfileID,
    ContactID
    ) ON UPDATE  NO ACTION 
     ON DELETE  NO ACTION 

GO
ALTER TABLE raw.PostalAddress SET (LOCK_ESCALATION = TABLE)
GO
COMMIT

Making HTTP Requests using Chrome Developer tools

_x000D_
_x000D_
$.post(_x000D_
    'dom/data-home.php',_x000D_
    {_x000D_
    type : "home", id : "0"_x000D_
    },function(data){_x000D_
        console.log(data)_x000D_
    })
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Enabling WiFi on Android Emulator

Apparently it does not and I didn't quite expect it would. HOWEVER Ivan brings up a good possibility that has escaped Android people.

What is the purpose of an emulator? to EMULATE, right? I don't see why for testing purposes -provided the tester understands the limitations- the emulator might not add a Wifi emulator.

It could for example emulate WiFi access by using the underlying internet connection of the host. Obviously testing WPA/WEP differencess would not make sense but at least it could toggle access via WiFi.

Or some sort of emulator plugin where there would be a base WiFi emulator that would emulate WiFi access via the underlying connection but then via configuration it could emulate WPA/WEP by providing a list of fake WiFi networks and their corresponding fake passwords that would be matched against a configurable list of credentials.

After all the idea is to do initial testing on the emulator and then move on to the actual device.

How do I make an Event in the Usercontrol and have it handled in the Main Form?

you can do like this.....the below example shows text box(user control) value changed

   // Declare a delegate 
public delegate void ValueChangedEventHandler(object sender, ValueChangedEventArgs e);
public partial class SampleUserControl : TextBox 
{    
    public SampleUserControl() 
    { 
        InitializeComponent(); 
    }

    // Declare an event 
    public event ValueChangedEventHandler ValueChanged;

    protected virtual void OnValueChanged(ValueChangedEventArgs e) 
    { 
        if (ValueChanged != null) 
            ValueChanged(this,e); 
    }    
    private void SampleUserControl_TextChanged(object sender, EventArgs e) 
    { 
        TextBox tb  = (TextBox)sender; 
        int value; 
        if (!int.TryParse(tb.Text, out value)) 
            value = 0; 
        // Raise the event 
       OnValueChanged( new ValueChangedEventArgs(value)); 
    }    
}

Generating a random hex color code with PHP

$rand = str_pad(dechex(rand(0x000000, 0xFFFFFF)), 6, 0, STR_PAD_LEFT);
echo('#' . $rand);

You can change rand() in for mt_rand() if you want, and you can put strtoupper() around the str_pad() to make the random number look nicer (although it’s not required).

It works perfectly and is way simpler than all the other methods described here :)

Changing three.js background to transparent or other color

I found that when I created a scene via the three.js editor, I not only had to use the correct answer's code (above), to set up the renderer with an alpha value and the clear color, I had to go into the app.json file and find the "Scene" Object's "background" attribute and set it to: "background: null".

The export from Three.js editor had it originally set to "background": 0

How to call a shell script from python code?

The subprocess module will help you out.

Blatantly trivial example:

>>> import subprocess
>>> subprocess.call(['sh', './test.sh']) # Thanks @Jim Dennis for suggesting the []
0 
>>> 

Where test.sh is a simple shell script and 0 is its return value for this run.

Lock down Microsoft Excel macro

Generate a protected application for Mac or Windows from your Excel spreadsheet using OfficeProtect with either AppProtect or QuickLicense/AddLicense. There is a demonstation video called "Protect Excel Spreedsheet" at www.excelsoftware.com/videos.

Select mysql query between date?

You can use now() like:

Select data from tablename where datetime >= "01-01-2009 00:00:00" and datetime <= now();

Does React Native styles support gradients?

React Native hasn't provided the gradient color yet. But still, you can do it with a nmp package called react-native-linear-gradient or you can click here for more info

  1. npm install react-native-linear-gradient --save
  2. use import LinearGradient from 'react-native-linear-gradient'; in your application file
  3.         <LinearGradient colors={['#4c669f', '#3b5998', '#192f6a']}>
              <Text>
                Your Text Here
              </Text>
            </LinearGradient> 

Ionic 2: Cordova is not available. Make sure to include cordova.js or run in a device/simulator (running in emulator)

This is quite late but anyone going through the same problem might benefit from this answer.First try to add browser by running below command ionic platform add browser and then run command ionic run browser.

which is the difference between ionic serve and ionic run browser?

Ionic serve - runs your app as a website (meaning it doesn't have any Cordova capabilities). Ionic run browser - runs your app in the Cordova browser platform, which will inject cordova.js and any plugins that have browser capabilities

You can refer this link to know more difference between ionic serve and ionic run browser command

Update

From Ionic 3 this command has been changed. Use the command below instead;

ionic cordova platform add browser

ionic cordova run browser

You can find out which version of ionic you are using by running: ionic --version

Export to CSV using jQuery and html

I am not sure if the above CSV generation code is so great as it appears to skip th cells and also did not appear to allow for commas in the value. So here is my CSV generation code that might be useful.

It does assume you have the $table variable which is a jQuery object (eg. var $table = $('#yourtable');)

$rows = $table.find('tr');

var csvData = "";

for(var i=0;i<$rows.length;i++){
                var $cells = $($rows[i]).children('th,td'); //header or content cells

                for(var y=0;y<$cells.length;y++){
                    if(y>0){
                      csvData += ",";
                    }
                    var txt = ($($cells[y]).text()).toString().trim();
                    if(txt.indexOf(',')>=0 || txt.indexOf('\"')>=0 || txt.indexOf('\n')>=0){
                        txt = "\"" + txt.replace(/\"/g, "\"\"") + "\"";
                    }
                    csvData += txt;
                }
                csvData += '\n';
 }

Babel command not found

I had the same issue. Deleted the nodemodules folder and opened command prompt as administrator and then ran npm install.

All packages installed fine.

How can I determine the type of an HTML element in JavaScript?

nodeName is the attribute you are looking for. For example:

var elt = document.getElementById('foo');
console.log(elt.nodeName);

Note that nodeName returns the element name capitalized and without the angle brackets, which means that if you want to check if an element is an <div> element you could do it as follows:

elt.nodeName == "DIV"

While this would not give you the expected results:

elt.nodeName == "<div>"

Inline IF Statement in C#

You may define your enum like so and use cast where needed

public enum MyEnum
{
    VariablePeriods = 1,
    FixedPeriods = 2
}

Usage

public class Entity
{
    public MyEnum Property { get; set; }
}

var returnedFromDB = 1;
var entity = new Entity();
entity.Property = (MyEnum)returnedFromDB;

How to store Configuration file and read it using React

You can use the dotenv package no matter what setup you use. It allows you to create a .env in your project root and specify your keys like so

REACT_APP_SERVER_PORT=8000

In your applications entry file your just call dotenv(); before accessing the keys like so

process.env.REACT_APP_SERVER_PORT

onclick open window and specific size

Anyone looking for a quick Vue file component, here you go:

// WindowUrl.vue

<template>
    <a :href="url" :class="classes" @click="open">
        <slot></slot>
    </a>
</template>

<script>
    export default {
        props: {
            url: String,
            width: String,
            height: String,
            classes: String,
        },
        methods: {
            open(e) {
                // Prevent the link from opening on the parent page.
                e.preventDefault();

                window.open(
                    this.url,
                    'targetWindow',
                    `toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=yes,width=${this.width},height=${this.height}`
                );
            }
        }
    }
</script>

Usage:

<window-url url="/print/shipping" class="btn btn-primary" height="250" width="250">
    Print Shipping Label
</window-url>

MongoDB Aggregation: How to get total records count?

I did it this way:

db.collection.aggregate([
     { $match : { score : { $gt : 70, $lte : 90 } } },
     { $group: { _id: null, count: { $sum: 1 } } }
] ).map(function(record, index){
        print(index);
 });

The aggregate will return the array so just loop it and get the final index .

And other way of doing it is:

var count = 0 ;
db.collection.aggregate([
{ $match : { score : { $gt : 70, $lte : 90 } } },
{ $group: { _id: null, count: { $sum: 1 } } }
] ).map(function(record, index){
        count++
 }); 
print(count);

How can I use the $index inside a ng-repeat to enable a class and show a DIV?

As johnnyynnoj mentioned ng-repeat creates a new scope. I would in fact use a function to set the value. See plunker

JS:

$scope.setSelected = function(selected) {
  $scope.selected = selected;
}

HTML:

{{ selected }}

<ul>
  <li ng-class="{current: selected == 100}">
     <a href ng:click="setSelected(100)">ABC</a>
  </li>
  <li ng-class="{current: selected == 101}">
     <a href ng:click="setSelected(101)">DEF</a>
  </li>
  <li ng-class="{current: selected == $index }" 
      ng-repeat="x in [4,5,6,7]">
     <a href ng:click="setSelected($index)">A{{$index}}</a>
  </li>
</ul>

<div  
  ng:show="selected == 100">
  100        
</div>
<div  
  ng:show="selected == 101">
  101        
</div>
<div ng-repeat="x in [4,5,6,7]" 
  ng:show="selected == $index">
  {{ $index }}        
</div>

Still Reachable Leak detected by Valgrind

There is more than one way to define "memory leak". In particular, there are two primary definitions of "memory leak" that are in common usage among programmers.

The first commonly used definition of "memory leak" is, "Memory was allocated and was not subsequently freed before the program terminated." However, many programmers (rightly) argue that certain types of memory leaks that fit this definition don't actually pose any sort of problem, and therefore should not be considered true "memory leaks".

An arguably stricter (and more useful) definition of "memory leak" is, "Memory was allocated and cannot be subsequently freed because the program no longer has any pointers to the allocated memory block." In other words, you cannot free memory that you no longer have any pointers to. Such memory is therefore a "memory leak". Valgrind uses this stricter definition of the term "memory leak". This is the type of leak which can potentially cause significant heap depletion, especially for long lived processes.

The "still reachable" category within Valgrind's leak report refers to allocations that fit only the first definition of "memory leak". These blocks were not freed, but they could have been freed (if the programmer had wanted to) because the program still was keeping track of pointers to those memory blocks.

In general, there is no need to worry about "still reachable" blocks. They don't pose the sort of problem that true memory leaks can cause. For instance, there is normally no potential for heap exhaustion from "still reachable" blocks. This is because these blocks are usually one-time allocations, references to which are kept throughout the duration of the process's lifetime. While you could go through and ensure that your program frees all allocated memory, there is usually no practical benefit from doing so since the operating system will reclaim all of the process's memory after the process terminates, anyway. Contrast this with true memory leaks which, if left unfixed, could cause a process to run out of memory if left running long enough, or will simply cause a process to consume far more memory than is necessary.

Probably the only time it is useful to ensure that all allocations have matching "frees" is if your leak detection tools cannot tell which blocks are "still reachable" (but Valgrind can do this) or if your operating system doesn't reclaim all of a terminating process's memory (all platforms which Valgrind has been ported to do this).

How can I get the nth character of a string?

You would do:

char c = str[1];

Or even:

char c = "Hello"[1];

edit: updated to find the "E".

PHP Deprecated: Methods with the same name

As mentioned in the error, the official manual and the comments:

Replace

public function TSStatus($host, $queryPort)

with

public function __construct($host, $queryPort)

How to execute python file in linux

You have to add a shebang. A shebang is the first line of the file. Its what the system is looking for in order to execute a file.

It should look like that :

#!/usr/bin/env python

or the real path

#!/usr/bin/python

You should also check the file have the right to be execute. chmod +x file.py

As Fabian said, take a look to Wikipedia : Wikipedia - Shebang (en)

Using C++ filestreams (fstream), how can you determine the size of a file?

Don't use tellg to determine the exact size of the file. The length determined by tellg will be larger than the number of characters can be read from the file.

From stackoverflow question tellg() function give wrong size of file? tellg does not report the size of the file, nor the offset from the beginning in bytes. It reports a token value which can later be used to seek to the same place, and nothing more. (It's not even guaranteed that you can convert the type to an integral type.). For Windows (and most non-Unix systems), in text mode, there is no direct and immediate mapping between what tellg returns and the number of bytes you must read to get to that position.

If it is important to know exactly how many bytes you can read, the only way of reliably doing so is by reading. You should be able to do this with something like:

#include <fstream>
#include <limits>

ifstream file;
file.open(name,std::ios::in|std::ios::binary);
file.ignore( std::numeric_limits<std::streamsize>::max() );
std::streamsize length = file.gcount();
file.clear();   //  Since ignore will have set eof.
file.seekg( 0, std::ios_base::beg );

How to use 'git pull' from the command line?

One more option is to add the path of the privatekey file like this in terminal:

ssh-add "path to the privatekeyfile"

and then execute the pull command

How do I import a .sql file in mysql database using PHP?

As we all know MySQL was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0 ref so I have converted accepted answer to mysqli.

<?php
// Name of the file
$filename = 'db.sql';
// MySQL host
$mysql_host = 'localhost';
// MySQL username
$mysql_username = 'root';
// MySQL password
$mysql_password = '123456';
// Database name
$mysql_database = 'mydb';

$connection = mysqli_connect($mysql_host,$mysql_username,$mysql_password,$mysql_database) or die(mysqli_error($connection));

// Temporary variable, used to store current query
$templine = '';
// Read in entire file
$lines = file($filename);
// Loop through each line
foreach ($lines as $line)
{
// Skip it if it's a comment
if (substr($line, 0, 2) == '--' || $line == '')
    continue;

// Add this line to the current segment
$templine .= $line;
// If it has a semicolon at the end, it's the end of the query
if (substr(trim($line), -1, 1) == ';')
{
    // Perform the query
    mysqli_query($connection,$templine) or print('Error performing query \'<strong>' . $templine . '\': ' . mysqli_error($connection) . '<br /><br />');
    // Reset temp variable to empty
    $templine = '';
}
}
 echo "Tables imported successfully";
?>

Creating a Facebook share button with customized url, title and image

Crude, but it works on our system:

<div class="block-share spread-share p-t-md">
  <a href="http://www.facebook.com/share.php?u=http://www.voteleavetakecontrol.org/our_affiliates&title=Farmers+for+Britain+have+made+the+sensible+decision+to+Vote+Leave.+Be+part+of+a+better+future+for+us+all.+Please+share!" 
     target="_blank">
    <button class="btn btn-social btn-facebook">
      <span class="icon icon-facebook">
      </span> 
      Share on Facebook
    </button>
  </a>

  <a href="https://www.facebook.com/FarmersForBritain" target="_blank">
    <button class="btn btn-social btn-facebook">
      <span class="icon icon-facebook">
      </span>
      Like  on Facebook
    </button>
  </a>
</div>

insert data from one table to another in mysql

You can use INSERT...SELECT syntax. Note that you can quote '1' directly in the SELECT part.

INSERT INTO mt_magazine_subscription ( 
      magazine_subscription_id, 
      subscription_name, 
      magazine_id, 
      status ) 
SELECT magazine_subscription_id, 
       subscription_name, 
       magazine_id, 
       '1'
FROM tbl_magazine_subscription
ORDER BY magazine_subscription_id ASC 

PHP read and write JSON from file

This should work for you to get the contents of list.txt file

$headers = array('http'=>array('method'=>'GET','header'=>'Content: type=application/json \r\n'.'$agent \r\n'.'$hash'));

$context=stream_context_create($headers);

$str = file_get_contents("list.txt",FILE_USE_INCLUDE_PATH,$context);

$str=utf8_encode($str);

$str=json_decode($str,true);

print_r($str);

How to export the Html Tables data into PDF using Jspdf

Just follow these steps i can assure pdf file will be generated

    <html>
    <head>

    <title>Exporting table data to pdf Example</title>


    <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.3.js"></script>
    <script type="text/javascript" src="js/jspdf.js"></script>
    <script type="text/javascript" src="js/from_html.js"></script>
    <script type="text/javascript" src="js/split_text_to_size.js"></script>
    <script type="text/javascript" src="js/standard_fonts_metrics.js"></script>
    <script type="text/javascript" src="js/cell.js"></script>
    <script type="text/javascript" src="js/FileSaver.js"></script>


    <script type="text/javascript">
        $(document).ready(function() {

            $("#exportpdf").click(function() {
                var pdf = new jsPDF('p', 'pt', 'ledger');
                // source can be HTML-formatted string, or a reference
                // to an actual DOM element from which the text will be scraped.
                source = $('#yourTableIdName')[0];

                // we support special element handlers. Register them with jQuery-style 
                // ID selector for either ID or node name. ("#iAmID", "div", "span" etc.)
                // There is no support for any other type of selectors 
                // (class, of compound) at this time.
                specialElementHandlers = {
                    // element with id of "bypass" - jQuery style selector
                    '#bypassme' : function(element, renderer) {
                        // true = "handled elsewhere, bypass text extraction"
                        return true
                    }
                };
                margins = {
                    top : 80,
                    bottom : 60,
                    left : 60,
                    width : 522
                };
                // all coords and widths are in jsPDF instance's declared units
                // 'inches' in this case
                pdf.fromHTML(source, // HTML string or DOM elem ref.
                margins.left, // x coord
                margins.top, { // y coord
                    'width' : margins.width, // max width of content on PDF
                    'elementHandlers' : specialElementHandlers
                },

                function(dispose) {
                    // dispose: object with X, Y of the last line add to the PDF 
                    //          this allow the insertion of new lines after html
                    pdf.save('fileNameOfGeneretedPdf.pdf');
                }, margins);
            });

        });
    </script>
    </head>
    <body>
    <div id="yourTableIdName">
        <table style="width: 1020px;font-size: 12px;" border="1">
            <thead>
                <tr align="left">
                    <th>Country</th>
                    <th>State</th>
                    <th>City</th>
                </tr>
            </thead>


            <tbody>

                <tr align="left">
                    <td>India</td>
                    <td>Telangana</td>
                    <td>Nirmal</td>
                </tr>
<tr align="left">
                    <td>India</td>
                    <td>Telangana</td>
                    <td>Nirmal</td>
                </tr><tr align="left">
                    <td>India</td>
                    <td>Telangana</td>
                    <td>Nirmal</td>
                </tr><tr align="left">
                    <td>India</td>
                    <td>Telangana</td>
                    <td>Nirmal</td>
                </tr><tr align="left">
                    <td>India</td>
                    <td>Telangana</td>
                    <td>Nirmal</td>
                </tr><tr align="left">
                    <td>India</td>
                    <td>Telangana</td>
                    <td>Nirmal</td>
                </tr><tr align="left">
                    <td>India</td>
                    <td>Telangana</td>
                    <td>Nirmal</td>
                </tr>
            </tbody>
        </table></div>

        <input type="button" id="exportpdf" value="Download PDF">


    </body>

    </html>

Output:

Html file output: html output

Pdf file output: pdf output

Class name does not name a type in C++

The solution to my problem today was slightly different that the other answers here.

In my case, the problem was caused by a missing close bracket (}) at the end of one of the header files in the include chain.

Essentially, what was happening was that A was including B. Because B was missing a } somewhere in the file, the definitions in B were not correctly found in A.

At first I thought I have circular dependency and added the forward declaration B. But then it started complaining about the fact that something in B was an incomplete type. That's how I thought of double checking the files for syntax errors.

How do I initialize a dictionary of empty lists in Python?

You could use this:

data[:1] = ['hello']

List of foreign keys and the tables they reference in Oracle DB

If you need all the foreign keys of the user then use the following script

SELECT a.constraint_name, a.table_name, a.column_name,  c.owner, 
       c_pk.table_name r_table_name,  b.column_name r_column_name
  FROM user_cons_columns a
  JOIN user_constraints c ON a.owner = c.owner
       AND a.constraint_name = c.constraint_name
  JOIN user_constraints c_pk ON c.r_owner = c_pk.owner
       AND c.r_constraint_name = c_pk.constraint_name
  JOIN user_cons_columns b ON C_PK.owner = b.owner
       AND  C_PK.CONSTRAINT_NAME = b.constraint_name AND b.POSITION = a.POSITION     
 WHERE c.constraint_type = 'R'

based on Vincent Malgrat code

How do I include image files in Django templates?

I do understand, that your question was about files stored in MEDIA_ROOT, but sometimes it can be possible to store content in static, when you are not planning to create content of that type anymore.
May be this is a rare case, but anyway - if you have a huge amount of "pictures of the day" for your site - and all these files are on your hard drive?

In that case I see no contra to store such a content in STATIC.
And all becomes really simple:

static

To link to static files that are saved in STATIC_ROOT Django ships with a static template tag. You can use this regardless if you're using RequestContext or not.

{% load static %} <img src="{% static "images/hi.jpg" %}" alt="Hi!" />

copied from Official django 1.4 documentation / Built-in template tags and filters

Select rows with same id but different value in another column

This is an old question yet I find that I also need a solution for this from time to time. The previous answers are all good and works well, I just personally prefer using CTE, for example:

DECLARE @T TABLE (ARIDNR INT, LIEFNR varchar(5)) --table variable for loading sample data
INSERT INTO @T (ARIDNR, LIEFNR) VALUES (1,'A'),(2,'A'),(3,'A'),(1,'B'),(2,'B'); --add your sample data to it
WITH duplicates AS --the CTE portion to find the duplicates
(
    SELECT ARIDNR FROM @T GROUP BY ARIDNR HAVING COUNT(*) > 1
)
SELECT t.* FROM @T t --shows results from main table
INNER JOIN duplicates d on t.ARIDNR = d.ARIDNR --where the main table can be joined to the duplicates CTE

Yields the following results:

1|A
1|B
2|B
2|A

Unable to Connect to GitHub.com For Cloning

You can make git replace the protocol for you

git config --global url."https://".insteadOf git://

See more at SO Bower install using only https?

What's the meaning of exception code "EXC_I386_GPFLT"?

In my case the error was thrown in Xcode when running an app on the iOS simulator. While I cannot answer the specific question "what the error means", I can say what helped me, maybe it also helps others.

The solution for me was to Erase All Content and Settings in the simulator and to Clean Build Folder... in Xcode.

Sorting a tab delimited file

You need to put an actual tab character after the -t\ and to do that in a shell you hit ctrl-v and then the tab character. Most shells I've used support this mode of literal tab entry.

Beware, though, because copying and pasting from another place generally does not preserve tabs.

Which version of Python do I have installed?

If you are already in a REPL window and don't see the welcome message with the version number, you can use help() to see the major and minor version:

>>>help()
Welcome to Python 3.6's help utility!
...

How to compare two JSON have the same properties without order?

In VueJs function you can use this as well... A working solution using recursion. Base credits Samadhan Sakhale

     check_objects(obj1, obj2) {
            try {
                var flag = true;

                if (Object.keys(obj1).length == Object.keys(obj2).length) {
                    for (let key in obj1) {

                        if(typeof (obj1[key]) != typeof (obj2[key]))
                        {
                            return false;
                        }

                        if (obj1[key] == obj2[key]) {
                            continue;
                        }

                        else if(typeof (obj1[key]) == typeof (new Object()))
                        {
                            if(!this.check_objects(obj1[key], obj2[key])) {
                                return false;
                            }
                        }
                        else {
                            return false;
                        }
                    }
                }
                else {
                    return false
                }
            }
            catch {

                return false;
            }

            return flag;
        },

Can we pass parameters to a view in SQL?

If you don't want to use a function, you can use something like this

-- VIEW
CREATE VIEW [dbo].[vwPharmacyProducts]
AS
SELECT     PharmacyId, ProductId
FROM         dbo.Stock
WHERE     (TotalQty > 0)

-- Use of view inside a stored procedure
CREATE PROCEDURE [dbo].[usp_GetProductByFilter]
(   @pPharmacyId int ) AS

IF @pPharmacyId = 0 BEGIN SET @pPharmacyId = NULL END

SELECT  P.[ProductId], P.[strDisplayAs] FROM [Product] P
WHERE (P.[bDeleted] = 0)
    AND (P.[ProductId] IN (Select vPP.ProductId From vwPharmacyProducts vPP
                           Where vPP.PharmacyId = @pPharmacyId)
                       OR @pPharmacyId IS NULL
        )

Hope it will help

How to change button text or link text in JavaScript?

Change .text to .textContent to get/set the text content.

Or since you're dealing with a single text node, use .firstChild.data in the same manner.

Also, let's make sensible use of a variable, and enjoy some code reduction and eliminate redundant DOM selection by caching the result of getElementById.

function toggleText(button_id) 
{
   var el = document.getElementById(button_id);
   if (el.firstChild.data == "Lock") 
   {
       el.firstChild.data = "Unlock";
   }
   else 
   {
     el.firstChild.data = "Lock";
   }
}

Or even more compact like this:

function toggleText(button_id)  {
   var text = document.getElementById(button_id).firstChild;
   text.data = text.data == "Lock" ? "Unlock" : "Lock";
}

convert xml to java object using jaxb (unmarshal)

Tests

On the Tests class we will add an @XmlRootElement annotation. Doing this will let your JAXB implementation know that when a document starts with this element that it should instantiate this class. JAXB is configuration by exception, this means you only need to add annotations where your mapping differs from the default. Since the testData property differs from the default mapping we will use the @XmlElement annotation. You may find the following tutorial helpful: http://wiki.eclipse.org/EclipseLink/Examples/MOXy/GettingStarted

package forum11221136;

import javax.xml.bind.annotation.*;

@XmlRootElement
public class Tests {

    TestData testData;

    @XmlElement(name="test-data")
    public TestData getTestData() {
        return testData;
    }

    public void setTestData(TestData testData) {
        this.testData = testData;
    }

}

TestData

On this class I used the @XmlType annotation to specify the order in which the elements should be ordered in. I added a testData property that appeared to be missing. I also used an @XmlElement annotation for the same reason as in the Tests class.

package forum11221136;

import java.util.List;
import javax.xml.bind.annotation.*;

@XmlType(propOrder={"title", "book", "count", "testData"})
public class TestData {
    String title;
    String book;
    String count;
    List<TestData> testData;

    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getBook() {
        return book;
    }
    public void setBook(String book) {
        this.book = book;
    }
    public String getCount() {
        return count;
    }
    public void setCount(String count) {
        this.count = count;
    }
    @XmlElement(name="test-data")
    public List<TestData> getTestData() {
        return testData;
    }
    public void setTestData(List<TestData> testData) {
        this.testData = testData;
    }
}

Demo

Below is an example of how to use the JAXB APIs to read (unmarshal) the XML and populate your domain model and then write (marshal) the result back to XML.

package forum11221136;

import java.io.File;
import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Tests.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        File xml = new File("src/forum11221136/input.xml");
        Tests tests = (Tests) unmarshaller.unmarshal(xml);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(tests, System.out);
    }

}

JavaScript - Hide a Div at startup (load)

Use css style to hide the div.

#selector { display: none; }

or Use it like below,

CSS:

.hidden { display: none; }

HTML

<div id="blah" class="hidden"><!-- div content --></div>

and in jQuery

 $(function () {
     $('#blah').removeClass('hidden');
 });

Apply function to pandas groupby

As of Pandas version 0.22, there exists also an alternative to apply: pipe, which can be considerably faster than using apply (you can also check this question for more differences between the two functionalities).

For your example:

df = pd.DataFrame({"my_label": ['A','B','A','C','D','D','E']})

  my_label
0        A
1        B
2        A
3        C
4        D
5        D
6        E

The apply version

df.groupby('my_label').apply(lambda grp: grp.count() / df.shape[0])

gives

          my_label
my_label          
A         0.285714
B         0.142857
C         0.142857
D         0.285714
E         0.142857

and the pipe version

df.groupby('my_label').pipe(lambda grp: grp.size() / grp.size().sum())

yields

my_label
A    0.285714
B    0.142857
C    0.142857
D    0.285714
E    0.142857

So the values are identical, however, the timings differ quite a lot (at least for this small dataframe):

%timeit df.groupby('my_label').apply(lambda grp: grp.count() / df.shape[0])
100 loops, best of 3: 5.52 ms per loop

and

%timeit df.groupby('my_label').pipe(lambda grp: grp.size() / grp.size().sum())
1000 loops, best of 3: 843 µs per loop

Wrapping it into a function is then also straightforward:

def get_perc(grp_obj):
    gr_size = grp_obj.size()
    return gr_size / gr_size.sum()

Now you can call

df.groupby('my_label').pipe(get_perc)

yielding

my_label
A    0.285714
B    0.142857
C    0.142857
D    0.285714
E    0.142857

However, for this particular case, you do not even need a groupby, but you can just use value_counts like this:

df['my_label'].value_counts(sort=False) / df.shape[0]

yielding

A    0.285714
C    0.142857
B    0.142857
E    0.142857
D    0.285714
Name: my_label, dtype: float64

For this small dataframe it is quite fast

%timeit df['my_label'].value_counts(sort=False) / df.shape[0]
1000 loops, best of 3: 770 µs per loop

As pointed out by @anmol, the last statement can also be simplified to

df['my_label'].value_counts(sort=False, normalize=True)

What is a simple command line program or script to backup SQL server databases?

Microsoft's answer to backing up all user databases on SQL Express is here:

The process is: copy, paste, and execute their code (see below. I've commented some oddly non-commented lines at the top) as a query on your database server. That means you should first install the SQL Server Management Studio (or otherwise connect to your database server with SSMS). This code execution will create a stored procedure on your database server.

Create a batch file to execute the stored procedure, then use Task Scheduler to schedule a periodic (e.g. nightly) run of this batch file. My code (that works) is a slightly modified version of their first example:

sqlcmd -S .\SQLEXPRESS -E -Q "EXEC sp_BackupDatabases @backupLocation='E:\SQLBackups\', @backupType='F'" 

This worked for me, and I like it. Each time you run it, new backup files are created. You'll need to devise a method of deleting old backup files on a routine basis. I already have a routine that does that sort of thing, so I'll keep a couple of days' worth of backups on disk (long enough for them to get backed up by my normal backup routine), then I'll delete them. In other words, I'll always have a few days' worth of backups on hand without having to restore from my backup system.

I'll paste Microsoft's stored procedure creation script below:

--// Copyright © Microsoft Corporation.  All Rights Reserved.
--// This code released under the terms of the
--// Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.)

USE [master] 
GO 

/****** Object:  StoredProcedure [dbo].[sp_BackupDatabases] ******/ 

SET ANSI_NULLS ON 
GO 

SET QUOTED_IDENTIFIER ON 
GO 

 
-- ============================================= 
-- Author: Microsoft 
-- Create date: 2010-02-06
-- Description: Backup Databases for SQLExpress
-- Parameter1: databaseName 
-- Parameter2: backupType F=full, D=differential, L=log
-- Parameter3: backup file location
-- =============================================

CREATE PROCEDURE [dbo].[sp_BackupDatabases]  
            @databaseName sysname = null,
            @backupType CHAR(1),
            @backupLocation nvarchar(200) 
AS 

       SET NOCOUNT ON; 

            DECLARE @DBs TABLE
            (
                  ID int IDENTITY PRIMARY KEY,
                  DBNAME nvarchar(500)
            )
           
             -- Pick out only databases which are online in case ALL databases are chosen to be backed up

             -- If specific database is chosen to be backed up only pick that out from @DBs

            INSERT INTO @DBs (DBNAME)
            SELECT Name FROM master.sys.databases
            where state=0
            AND name=@DatabaseName
            OR @DatabaseName IS NULL
            ORDER BY Name

 
           -- Filter out databases which do not need to backed up
 
           IF @backupType='F'
                  BEGIN
                  DELETE @DBs where DBNAME IN ('tempdb','Northwind','pubs','AdventureWorks')
                  END
            ELSE IF @backupType='D'
                  BEGIN
                  DELETE @DBs where DBNAME IN ('tempdb','Northwind','pubs','master','AdventureWorks')
                  END
            ELSE IF @backupType='L'
                  BEGIN
                  DELETE @DBs where DBNAME IN ('tempdb','Northwind','pubs','master','AdventureWorks')
                  END
            ELSE
                  BEGIN
                  RETURN
                  END
           

            -- Declare variables

            DECLARE @BackupName varchar(100)
            DECLARE @BackupFile varchar(100)
            DECLARE @DBNAME varchar(300)
            DECLARE @sqlCommand NVARCHAR(1000) 
        DECLARE @dateTime NVARCHAR(20)
            DECLARE @Loop int                  
                       
            -- Loop through the databases one by one

            SELECT @Loop = min(ID) FROM @DBs
       WHILE @Loop IS NOT NULL
      BEGIN
 
-- Database Names have to be in [dbname] format since some have - or _ in their name

      SET @DBNAME = '['+(SELECT DBNAME FROM @DBs WHERE ID = @Loop)+']'


-- Set the current date and time n yyyyhhmmss format

      SET @dateTime = REPLACE(CONVERT(VARCHAR, GETDATE(),101),'/','') + '_' +  REPLACE(CONVERT(VARCHAR, GETDATE(),108),':','')  
 

-- Create backup filename in path\filename.extension format for full,diff and log backups

      IF @backupType = 'F'
            SET @BackupFile = @backupLocation+REPLACE(REPLACE(@DBNAME, '[',''),']','')+ '_FULL_'+ @dateTime+ '.BAK'
      ELSE IF @backupType = 'D'
            SET @BackupFile = @backupLocation+REPLACE(REPLACE(@DBNAME, '[',''),']','')+ '_DIFF_'+ @dateTime+ '.BAK'
      ELSE IF @backupType = 'L'
            SET @BackupFile = @backupLocation+REPLACE(REPLACE(@DBNAME, '[',''),']','')+ '_LOG_'+ @dateTime+ '.TRN'
 

-- Provide the backup a name for storing in the media

      IF @backupType = 'F'
            SET @BackupName = REPLACE(REPLACE(@DBNAME,'[',''),']','') +' full backup for '+ @dateTime

      IF @backupType = 'D'
            SET @BackupName = REPLACE(REPLACE(@DBNAME,'[',''),']','') +' differential backup for '+ @dateTime

      IF @backupType = 'L'
            SET @BackupName = REPLACE(REPLACE(@DBNAME,'[',''),']','') +' log backup for '+ @dateTime


-- Generate the dynamic SQL command to be executed

       IF @backupType = 'F' 
                  BEGIN
               SET @sqlCommand = 'BACKUP DATABASE ' +@DBNAME+  ' TO DISK = '''+@BackupFile+ ''' WITH INIT, NAME= ''' +@BackupName+''', NOSKIP, NOFORMAT'
                  END

       IF @backupType = 'D'
                  BEGIN
               SET @sqlCommand = 'BACKUP DATABASE ' +@DBNAME+  ' TO DISK = '''+@BackupFile+ ''' WITH DIFFERENTIAL, INIT, NAME= ''' +@BackupName+''', NOSKIP, NOFORMAT'        
                  END

       IF @backupType = 'L' 
                  BEGIN
               SET @sqlCommand = 'BACKUP LOG ' +@DBNAME+  ' TO DISK = '''+@BackupFile+ ''' WITH INIT, NAME= ''' +@BackupName+''', NOSKIP, NOFORMAT'        
                  END
 

-- Execute the generated SQL command

       EXEC(@sqlCommand)

 
-- Goto the next database

SELECT @Loop = min(ID) FROM @DBs where ID>@Loop
 

END?

How can I convert a .py to .exe for Python?

Python 3.6 is supported by PyInstaller.

Open a cmd window in your Python folder (open a command window and use cd or while holding shift, right click it on Windows Explorer and choose 'Open command window here'). Then just enter

pip install pyinstaller

And that's it.

The simplest way to use it is by entering on your command prompt

pyinstaller file_name.py

For more details on how to use it, take a look at this question.

&& (AND) and || (OR) in IF statements

No, it will not be evaluated. And this is very useful. For example, if you need to test whether a String is not null or empty, you can write:

if (str != null && !str.isEmpty()) {
  doSomethingWith(str.charAt(0));
}

or, the other way around

if (str == null || str.isEmpty()) {
  complainAboutUnusableString();
} else {
  doSomethingWith(str.charAt(0));
}

If we didn't have 'short-circuits' in Java, we'd receive a lot of NullPointerExceptions in the above lines of code.

Best way to check if a Data Table has a null value in it

I will do like....

(!DBNull.Value.Equals(dataSet.Tables[6].Rows[0]["_id"]))

How to find largest objects in a SQL Server database?

I've found this query also very helpful in SqlServerCentral, here is the link to original post

Sql Server largest tables

  select name=object_schema_name(object_id) + '.' + object_name(object_id)
, rows=sum(case when index_id < 2 then row_count else 0 end)
, reserved_kb=8*sum(reserved_page_count)
, data_kb=8*sum( case 
     when index_id<2 then in_row_data_page_count + lob_used_page_count + row_overflow_used_page_count 
     else lob_used_page_count + row_overflow_used_page_count 
    end )
, index_kb=8*(sum(used_page_count) 
    - sum( case 
           when index_id<2 then in_row_data_page_count + lob_used_page_count + row_overflow_used_page_count 
        else lob_used_page_count + row_overflow_used_page_count 
        end )
     )    
, unused_kb=8*sum(reserved_page_count-used_page_count)
from sys.dm_db_partition_stats
where object_id > 1024
group by object_id
order by 
rows desc   

In my database they gave different results between this query and the 1st answer.

Hope somebody finds useful

right click context menu for datagridview

Follow the steps:

  1. Create a context menu like: Sample context menu

  2. User needs to right click on the row to get this menu. We need to handle the _MouseClick event and _CellMouseDown event.

selectedBiodataid is the variable that contains the selected row information.

Here is the code:

private void dgrdResults_MouseClick(object sender, MouseEventArgs e)
{   
    if (e.Button == System.Windows.Forms.MouseButtons.Right)
    {                      
        contextMenuStrip1.Show(Cursor.Position.X, Cursor.Position.Y);
    }   
}

private void dgrdResults_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
    //handle the row selection on right click
    if (e.Button == MouseButtons.Right)
    {
        try
        {
            dgrdResults.CurrentCell = dgrdResults.Rows[e.RowIndex].Cells[e.ColumnIndex];
            // Can leave these here - doesn't hurt
            dgrdResults.Rows[e.RowIndex].Selected = true;
            dgrdResults.Focus();

            selectedBiodataId = Convert.ToInt32(dgrdResults.Rows[e.RowIndex].Cells[1].Value);
        }
        catch (Exception)
        {

        }
    }
}

and the output would be:

Final output

Should I use window.navigate or document.location in JavaScript?

I'd go with window.location = "http://...";. I've been coding cross-browser JavaScript for a few years, and I've never experienced problems using this approach.

window.navigate and window.location.href seems a bit odd to me.

How do I test if a recordSet is empty? isNull?

If Not temp_rst1 Is Nothing Then ...

How to recognize swipe in all 4 directions

Looks like things have changed lately. In XCode 7.2 the following approach works:

override func viewDidLoad() {
    super.viewDidLoad()

    let swipeGesture = UISwipeGestureRecognizer(target: self, action: "handleSwipe:")
    swipeGesture.direction = [.Down, .Up]
    self.view.addGestureRecognizer(swipeGesture)
}

func handleSwipe(sender: UISwipeGestureRecognizer) {
    print(sender.direction)
}

Tested in Simulator on iOS 8.4 and 9.2 and on actual device on 9.2.

Or, using mlcollard's handy extension here:

let swipeGesture = UISwipeGestureRecognizer() {
    print("Gesture recognized !")
}

swipeGesture.direction = [.Down, .Up]
self.view.addGestureRecognizer(swipeGesture)

php exec command (or similar) to not wait for result

I know this question has been answered but the answers i found here didn't work for my scenario ( or for Windows ).

I am using windows 10 laptop with PHP 7.2 in Xampp v3.2.4.

$command = 'php Cron.php send_email "'. $id .'"';
if ( substr(php_uname(), 0, 7) == "Windows" )
{
    //windows
    pclose(popen("start /B " . $command . " 1> temp/update_log 2>&1 &", "r"));
}
else
{
    //linux
    shell_exec( $command . " > /dev/null 2>&1 &" );
}

This worked perfectly for me.

I hope it will help someone with windows. Cheers.

Rails: How do I create a default value for attributes in Rails activerecord's model?

You can set a default option for the column in the migration

....
add_column :status, :string, :default => "P"
....

OR

You can use a callback, before_save

class Task < ActiveRecord::Base
  before_save :default_values
  def default_values
    self.status ||= 'P' # note self.status = 'P' if self.status.nil? might be safer (per @frontendbeauty)
  end
end