Programs & Examples On #Notice

PHP How to fix Notice: Undefined variable:

Xampp I guess you're using MySQL.

mysql_fetch_array($result);  

And make sure $result is not empty.

Notice: Trying to get property of non-object error

@Balamanigandan your Original Post :- PHP Notice: Trying to get property of non-object error

Your are trying to access the Null Object. From AngularJS your are not passing any Objects instead you are passing the $_GET element. Try by using $_GET['uid'] instead of $objData->token

Junit test case for database insert method with DAO and web service

This is one sample dao test using junit in spring project.

import java.util.List;

import junit.framework.Assert;

import org.jboss.tools.example.springmvc.domain.Member;
import org.jboss.tools.example.springmvc.repo.MemberDao;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:test-context.xml",
"classpath:/META-INF/spring/applicationContext.xml"})
@Transactional
@TransactionConfiguration(defaultRollback=true)
public class MemberDaoTest
{
    @Autowired
    private MemberDao memberDao;

    @Test
    public void testFindById()
    {
        Member member = memberDao.findById(0l);

        Assert.assertEquals("John Smith", member.getName());
        Assert.assertEquals("[email protected]", member.getEmail());
        Assert.assertEquals("2125551212", member.getPhoneNumber());
        return;
    }

    @Test
    public void testFindByEmail()
    {
        Member member = memberDao.findByEmail("[email protected]");

        Assert.assertEquals("John Smith", member.getName());
        Assert.assertEquals("[email protected]", member.getEmail());
        Assert.assertEquals("2125551212", member.getPhoneNumber());
        return;
    }

    @Test
    public void testRegister()
    {
        Member member = new Member();
        member.setEmail("[email protected]");
        member.setName("Jane Doe");
        member.setPhoneNumber("2125552121");

        memberDao.register(member);
        Long id = member.getId();
        Assert.assertNotNull(id);

        Assert.assertEquals(2, memberDao.findAllOrderedByName().size());
        Member newMember = memberDao.findById(id);

        Assert.assertEquals("Jane Doe", newMember.getName());
        Assert.assertEquals("[email protected]", newMember.getEmail());
        Assert.assertEquals("2125552121", newMember.getPhoneNumber());
        return;
    }

    @Test
    public void testFindAllOrderedByName()
    {
        Member member = new Member();
        member.setEmail("[email protected]");
        member.setName("Jane Doe");
        member.setPhoneNumber("2125552121");
        memberDao.register(member);

        List<Member> members = memberDao.findAllOrderedByName();
        Assert.assertEquals(2, members.size());
        Member newMember = members.get(0);

        Assert.assertEquals("Jane Doe", newMember.getName());
        Assert.assertEquals("[email protected]", newMember.getEmail());
        Assert.assertEquals("2125552121", newMember.getPhoneNumber());
        return;
    }
}

Why do I get "Procedure expects parameter '@statement' of type 'ntext/nchar/nvarchar'." when I try to use sp_executesql?

I had missed another tiny detail: I forgot the brackets "(100)" behind NVARCHAR.

No notification sound when sending notification from firebase in android

do like this

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {

    //codes..,.,,

    Uri sound= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        builder.setSound(sound);

}

Access parent DataContext from DataTemplate

You can use RelativeSource to find the parent element, like this -

Binding="{Binding Path=DataContext.CurveSpeedMustBeSpecified, 
RelativeSource={RelativeSource AncestorType={x:Type local:YourParentElementType}}}"

See this SO question for more details about RelativeSource.

Heroku "psql: FATAL: remaining connection slots are reserved for non-replication superuser connections"

See Heroku “psql: FATAL: remaining connection slots are reserved for non-replication superuser connections”:

Heroku sometimes has a problem with database load balancing.

André Laszlo, markshiz and me all reported dealing with that in comments on the question.

To save you the support call, here's the response I got from Heroku Support for a similar issue:

Hello,

One of the limitations of the hobby tier databases is unannounced maintenance. Many hobby databases run on a single shared server, and we will occasionally need to restart that server for hardware maintenance purposes, or migrate databases to another server for load balancing. When that happens, you'll see an error in your logs or have problems connecting. If the server is restarting, it might take 15 minutes or more for the database to come back online.

Most apps that maintain a connection pool (like ActiveRecord in Rails) can just open a new connection to the database. However, in some cases an app won't be able to reconnect. If that happens, you can heroku restart your app to bring it back online.

This is one of the reasons we recommend against running hobby databases for critical production applications. Standard and Premium databases include notifications for downtime events, and are much more performant and stable in general. You can use pg:copy to migrate to a standard or premium plan.

If this continues, you can try provisioning a new database (on a different server) with heroku addons:add, then use pg:copy to move the data. Keep in mind that hobby tier rules apply to the $9 basic plan as well as the free database.

Thanks, Bradley

Extension gd is missing from your system - laravel composer Update

Using Manjaro(Arch) Linux:

$ sudo pacman -S php-gd

In file /etc/php/php-ini, add the line:

extension=gd.so

How to assign name for a screen?

As already stated, screen -S SESSIONTITLE works for starting a session with a title (SESSIONTITLE), but if you start a session and later decide to change its title. This can be accomplished by using the default key bindings:

Ctrl+a, A

Which prompts:

Set windows title to:SESSIONTITLE

Change SESSIONTITLE by backspacing and typing in the desired title. To confirm the name change and list all titles.

Ctrl+a, "

$(window).height() vs $(document).height

you need know what it is mean about document and window.

  1. The window object represents an open window in a browser.click here
  2. The Document object is the root of a document tree.click here

Multiple SQL joins

 SELECT
 B.Title, B.Edition, B.Year, B.Pages, B.Rating     --from Books
, C.Category                                        --from Categories
, P.Publisher                                       --from Publishers
, W.LastName                                        --from Writers

FROM Books B

JOIN Categories_Books CB ON B._ISBN = CB._Books_ISBN
JOIN Categories_Books CB ON CB.__Categories_Category_ID = C._CategoryID
JOIN Publishers P ON B.PublisherID = P._Publisherid
JOIN Writers_Books WB ON B._ISBN = WB._Books_ISBN
JOIN Writers W ON WB._Writers_WriterID = W._WriterID

How to add \newpage in Rmarkdown in a smart way?

In the initialization chunk I define a function

pagebreak <- function() {
  if(knitr::is_latex_output())
    return("\\newpage")
  else
    return('<div style="page-break-before: always;" />')
}

In the markdown part where I want to insert a page break, I type

`r pagebreak()`

Set scroll position

You can use window.scrollTo(), like this:

window.scrollTo(0, 0); // values are x,y-offset

How to determine whether code is running in DEBUG / RELEASE build?

zitao xiong's answer is pretty close to what I use; I also include the file name (by stripping off the path of FILE).

#ifdef DEBUG
    #define NSLogDebug(format, ...) \
    NSLog(@"<%s:%d> %s, " format, \
    strrchr("/" __FILE__, '/') + 1, __LINE__, __PRETTY_FUNCTION__, ## __VA_ARGS__)
#else
    #define NSLogDebug(format, ...)
#endif

How to trim a string to N chars in Javascript?

Little late... I had to respond. This is the simplest way.

_x000D_
_x000D_
// JavaScript_x000D_
function fixedSize_JS(value, size) {_x000D_
  return value.padEnd(size).substring(0, size);_x000D_
}_x000D_
_x000D_
// JavaScript (Alt)_x000D_
var fixedSize_JSAlt = function(value, size) {_x000D_
  return value.padEnd(size).substring(0, size);_x000D_
}_x000D_
_x000D_
// Prototype (preferred)_x000D_
String.prototype.fixedSize = function(size) {_x000D_
  return this.padEnd(size).substring(0, size);_x000D_
}_x000D_
_x000D_
// Overloaded Prototype_x000D_
function fixedSize(value, size) {_x000D_
  return value.fixedSize(size);_x000D_
}_x000D_
_x000D_
// usage_x000D_
console.log('Old school JS -> "' + fixedSize_JS('test (30 characters)', 30) + '"');_x000D_
console.log('Semi-Old school JS -> "' + fixedSize_JSAlt('test (10 characters)', 10) + '"');_x000D_
console.log('Prototypes (Preferred) -> "' + 'test (25 characters)'.fixedSize(25) + '"');_x000D_
console.log('Overloaded Prototype (Legacy support) -> "' + fixedSize('test (15 characters)', 15) + '"');
_x000D_
_x000D_
_x000D_

Step by step. .padEnd - Guarentees the length of the string

"The padEnd() method pads the current string with a given string (repeated, if needed) so that the resulting string reaches a given length. The padding is applied from the end (right) of the current string. The source for this interactive example is stored in a GitHub repository." source: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

.substring - limits to the length you need

If you choose to add ellipses, append them to the output.

I gave 4 examples of common JavaScript usages. I highly recommend using the String prototype with Overloading for legacy support. It makes it much easier to implement and change later.

Android YouTube app Play Video Intent

Try this,

WebView webview = new WebView(this); 

String htmlString = 
    "<html> <body> <embed src=\"youtube link\"; type=application/x-shockwave-flash width="+widthOfDevice+" height="+heightOfDevice+"> </embed> </body> </html>";

webview.loadData(htmlString ,"text/html", "UTF-8");

DataSet panel (Report Data) in SSRS designer is gone

If you are using BIDS with SQL 2008 R2 you can only get the "Report Data" menu by clicking inside the actual report layout itself.

  1. Click inside the actual report layout.

  2. Now select "View" from the main menu bar.

  3. Now select "Report Data" which is the last item.

What is a Python egg?

Note: Egg packaging has been superseded by Wheel packaging.

Same concept as a .jar file in Java, it is a .zip file with some metadata files renamed .egg, for distributing code as bundles.

Specifically: The Internal Structure of Python Eggs

A "Python egg" is a logical structure embodying the release of a specific version of a Python project, comprising its code, resources, and metadata. There are multiple formats that can be used to physically encode a Python egg, and others can be developed. However, a key principle of Python eggs is that they should be discoverable and importable. That is, it should be possible for a Python application to easily and efficiently find out what eggs are present on a system, and to ensure that the desired eggs' contents are importable.

The .egg format is well-suited to distribution and the easy uninstallation or upgrades of code, since the project is essentially self-contained within a single directory or file, unmingled with any other projects' code or resources. It also makes it possible to have multiple versions of a project simultaneously installed, such that individual programs can select the versions they wish to use.

How can I check if a directory exists in a Bash shell script?

In kind of a ternary form,

[ -d "$directory" ] && echo "exist" || echo "not exist"

And with test:

test -d "$directory" && echo "exist" || echo "not exist"

Convert time span value to format "hh:mm Am/Pm" using C#

Doing some piggybacking off existing answers here:

public static string ToShortTimeSafe(this TimeSpan timeSpan)
{
    return new DateTime().Add(timeSpan).ToShortTimeString();
} 

public static string ToShortTimeSafe(this TimeSpan? timeSpan)
{
    return timeSpan == null ? string.Empty : timeSpan.Value.ToShortTimeSafe();
}

How to find the UpgradeCode and ProductCode of an installed application in Windows 7

You can use the MsiEnumProductsEx and MsiGetProductInfoEx methods to enumerate all the installed applications on your system and match the data to your application

Can I use return value of INSERT...RETURNING in another INSERT?

table_ex

id default nextval('table_id_seq'::regclass),

camp1 varchar

camp2 varchar

INSERT INTO table_ex(camp1,camp2) VALUES ('xxx','123') RETURNING id 

Update data on a page without refreshing

In general, if you don't know how something works, look for an example which you can learn from.

For this problem, consider this DEMO

You can see loading content with AJAX is very easily accomplished with jQuery:

$(function(){
    // don't cache ajax or content won't be fresh
    $.ajaxSetup ({
        cache: false
    });
    var ajax_load = "<img src='http://automobiles.honda.com/images/current-offers/small-loading.gif' alt='loading...' />";

    // load() functions
    var loadUrl = "http://fiddle.jshell.net/deborah/pkmvD/show/";
    $("#loadbasic").click(function(){
        $("#result").html(ajax_load).load(loadUrl);
    });

// end  
});

Try to understand how this works and then try replicating it. Good luck.

You can find the corresponding tutorial HERE

Update

Right now the following event starts the ajax load function:

$("#loadbasic").click(function(){
        $("#result").html(ajax_load).load(loadUrl);
    });

You can also do this periodically: How to fire AJAX request Periodically?

(function worker() {
  $.ajax({
    url: 'ajax/test.html', 
    success: function(data) {
      $('.result').html(data);
    },
    complete: function() {
      // Schedule the next request when the current one's complete
      setTimeout(worker, 5000);
    }
  });
})();

I made a demo of this implementation for you HERE. In this demo, every 2 seconds (setTimeout(worker, 2000);) the content is updated.

You can also just load the data immediately:

$("#result").html(ajax_load).load(loadUrl);

Which has THIS corresponding demo.

Register comdlg32.dll gets Regsvr32: DllRegisterServer entry point was not found

comdlg32.dll is not a COM DLL and cannot be registered.

One way to confirm this for yourself is to run this command:

dumpbin /exports comdlg32.dll

You'll see that comdlg32.dll doesn't contain a DllRegisterServer method. Hence RegSvr32.exe won't work.

That's your answer.


ComDlg32.dll is a a system component. (exists in both c:\windows\system32 and c:\windows\syswow64) Trying to replace it or override any registration with an older version could corrupt the rest of Windows.


I can help more, but I need to know what MSComDlg.CommonDialog is. What does it do and how is it supposed to work? And what version of ComDlg32.dll are you trying to register (and where did you get it)?

Rename Files and Directories (Add Prefix)

If you have Ruby(1.9+)

ruby -e 'Dir["*"].each{|x| File.rename(x,"PRE_"+x) }'

Bootstrap 4 datapicker.js not included

Most of bootstrap datepickers as I write this answer are rather buggy when included in Bootstrap 4. In my view the least code adding solution is a jQuery plugin. I used this one https://plugins.jquery.com/datetimepicker/ - you can see its usage here: https://xdsoft.net/jqplugins/datetimepicker/ It sure is not as smooth as the whole BS interface, but it only requires its css and js files along with jQuery which is already included in bootstrap.

How To Set Text In An EditText

If you want to set text at design time in xml file just simple android:text="username" add this property.

<EditText
    android:id="@+id/edtUsername"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="username"/>

If you want to set text programmatically in Java

EditText edtUsername = findViewById(R.id.edtUsername);
edtUsername.setText("username");

and in kotlin same like java using getter/setter

edtUsername.setText("username")

But if you want to use .text from principle then

edtUsername.text = Editable.Factory.getInstance().newEditable("username")

because of EditText.text requires an editable at firstplace not String

Git error on commit after merge - fatal: cannot do a partial commit during a merge

git commit -i -m 'merge message' didn't work for me. It said:

fatal: No paths with --include/--only does not make sense.

FWIW, I got here via this related question because I was getting this message:

fatal: You have not concluded your merge (MERGE_HEAD exists).

I also tried mergetool, which said No files need merging. Very confusing! So the MERGE_HEAD is not in a file that needs merging-??

Finally, I used this trick to add only the modified files (did not want to add all the files in my tree, since I have some I want to keep untracked):

git ls-files -m | xargs git add

Then I was finally (!) able to commit and push up. It sure would be nice if git gave you better hints about what to do in these situations.

How do I make a dictionary with multiple keys to one value?

Your example creates multiple key: value pairs if using fromkeys. If you don't want this, you can use one key and create an alias for the key. For example if you are using a register map, your key can be the register address and the alias can be register name. That way you can perform read/write operations on the correct register.

>>> mydict = {}
>>> mydict[(1,2)] = [30, 20]
>>> alias1 = (1,2)
>>> print mydict[alias1]
[30, 20]
>>> mydict[(1,3)] = [30, 30]
>>> print mydict
{(1, 2): [30, 20], (1, 3): [30, 30]}
>>> alias1 in mydict
True

Error: stray '\240' in program

I got the same error when I just copied the complete line but when I rewrite the code again i.e. instead of copy-paste, writing it completely then the error was no longer present.

Conclusion: There might be some unacceptable words to the language got copied giving rise to this error.

Python Remove last char from string and return it

Not only is it the preferred way, it's the only reasonable way. Because strings are immutable, in order to "remove" a char from a string you have to create a new string whenever you want a different string value.

You may be wondering why strings are immutable, given that you have to make a whole new string every time you change a character. After all, C strings are just arrays of characters and are thus mutable, and some languages that support strings more cleanly than C allow mutable strings as well. There are two reasons to have immutable strings: security/safety and performance.

Security is probably the most important reason for strings to be immutable. When strings are immutable, you can't pass a string into some library and then have that string change from under your feet when you don't expect it. You may wonder which library would change string parameters, but if you're shipping code to clients you can't control their versions of the standard library, and malicious clients may change out their standard libraries in order to break your program and find out more about its internals. Immutable objects are also easier to reason about, which is really important when you try to prove that your system is secure against particular threats. This ease of reasoning is especially important for thread safety, since immutable objects are automatically thread-safe.

Performance is surprisingly often better for immutable strings. Whenever you take a slice of a string, the Python runtime only places a view over the original string, so there is no new string allocation. Since strings are immutable, you get copy semantics without actually copying, which is a real performance win.

Eric Lippert explains more about the rationale behind immutable of strings (in C#, not Python) here.

How to override application.properties during production in Spring-Boot?

I have found the following has worked for me:

java -jar my-awesome-java-prog.jar --spring.config.location=file:/path-to-config-dir/

with file: added.

LATE EDIT

Of course, this command line is never run as it is in production.

Rather I have

  • [possibly several layers of] shell scripts in source control with place holders for all parts of the command that could change (name of the jar, path to config...)
  • ansible deployment scripts that will deploy the shell scripts and replace the place holders by the actual value.

How can I see the request headers made by curl when sending a request to the server?

curl -s -v -o/dev/null -H "Testheader: test" http://www.example.com

You could also use -I option if you want to send a HEAD request and not a GET request.

Forcing to download a file using PHP

Configure your server to send the file with the media type application/octet-stream.

How to handle ListView click in Android

Suppose ListView object is lv, do the following-

lv.setClickable(true);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

  @Override
  public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {

    Object o = lv.getItemAtPosition(position);
    /* write you handling code like...
    String st = "sdcard/";
    File f = new File(st+o.toString());
    // do whatever u want to do with 'f' File object
    */  
  }
});

Spring Boot how to hide passwords in properties file

In additional to the popular K8s, jasypt or vault solutions, there's also Karmahostage. It enables you to do:

@EncryptedValue("${application.secret}")
private String application;

It works the same way jasypt does, but encryption happens on a dedicated saas solution, with a more fine-grained ACL model attached to it.

How to remove duplicate values from an array in PHP

Here I've created a second empty array and used for loop with the first array which is having duplicates. It will run as many time as the count of the first array. Then compared with the position of the array with the first array and matched that it has this item already or not by using in_array. If not then it'll add that item to second array with array_push.

$a = array(1,2,3,1,3,4,5);
$count = count($a);
$b = [];
for($i=0; $i<$count; $i++){
    if(!in_array($a[$i], $b)){
        array_push($b, $a[$i]);
    }
}
print_r ($b);

Using Keras & Tensorflow with AMD GPU

One can use AMD GPU via the PlaidML Keras backend.

Fastest: PlaidML is often 10x faster (or more) than popular platforms (like TensorFlow CPU) because it supports all GPUs, independent of make and model. PlaidML accelerates deep learning on AMD, Intel, NVIDIA, ARM, and embedded GPUs.

Easiest: PlaidML is simple to install and supports multiple frontends (Keras and ONNX currently)

Free: PlaidML is completely open source and doesn't rely on any vendor libraries with proprietary and restrictive licenses.

For most platforms, getting started with accelerated deep learning is as easy as running a few commands (assuming you have Python (v2 or v3) installed):

virtualenv plaidml
source plaidml/bin/activate
pip install plaidml-keras plaidbench

Choose which accelerator you'd like to use (many computers, especially laptops, have multiple):

plaidml-setup

Next, try benchmarking MobileNet inference performance:

plaidbench keras mobilenet

Or, try training MobileNet:

plaidbench --batch-size 16 keras --train mobilenet

To use it with keras set

os.environ["KERAS_BACKEND"] = "plaidml.keras.backend"

For more information

https://github.com/plaidml/plaidml

https://github.com/rstudio/keras/issues/205#issuecomment-348336284

How can I set a dynamic model name in AngularJS?

To make the answer provided by @abourget more complete, the value of scopeValue[field] in the following line of code could be undefined. This would result in an error when setting subfield:

<textarea ng-model="scopeValue[field][subfield]"></textarea>

One way of solving this problem is by adding an attribute ng-focus="nullSafe(field)", so your code would look like the below:

<textarea ng-focus="nullSafe(field)" ng-model="scopeValue[field][subfield]"></textarea>

Then you define nullSafe( field ) in a controller like the below:

$scope.nullSafe = function ( field ) {
  if ( !$scope.scopeValue[field] ) {
    $scope.scopeValue[field] = {};
  }
};

This would guarantee that scopeValue[field] is not undefined before setting any value to scopeValue[field][subfield].

Note: You can't use ng-change="nullSafe(field)" to achieve the same result because ng-change happens after the ng-model has been changed, which would throw an error if scopeValue[field] is undefined.

Change value of input and submit form in JavaScript

No. When your input type is submit, you should have an onsubmit event declared in the markup and then do the changes you want. Meaning, have an onsubmit defined in your form tag.

Otherwise change the input type to a button and then define an onclick event for that button.

What is the difference between "word-break: break-all" versus "word-wrap: break-word" in CSS

There's a huge difference. break-all is basically unusable for rendering readable text.

Let's say you've got the string This is a text from an old magazine in a container which only fits 6 chars per row.

word-break: break-all

This i
s a te
xt fro
m an o
ld mag
azine

As you can see the result is awful. break-all will try to fit as many chararacters into each row as possible, it will even split a 2 letter word like "is" onto 2 rows! It's ridiculous. This is why break-all is rarely ever used.

word-wrap: break-word

This
is a
text
from
an old
magazi
ne

break-word will only break words which are too long to ever fit the container (like "magazine", which is 8 chars, and the container only fits 6 chars). It will never break words that could fit the container in their entirety, instead it will push them to a new line.

_x000D_
_x000D_
<div style="width: 100px; border: solid 1px black; font-family: monospace;">_x000D_
  <h1 style="word-break: break-all;">This is a text from an old magazine</h1>_x000D_
  <hr>_x000D_
  <h1 style="word-wrap: break-word;">This is a text from an old magazine</h1>_x000D_
</div
_x000D_
_x000D_
_x000D_

How to output only captured groups with sed?

Give up and use Perl

Since sed does not cut it, let's just throw the towel and use Perl, at least it is LSB while grep GNU extensions are not :-)

  • Print the entire matching part, no matching groups or lookbehind needed:

    cat <<EOS | perl -lane 'print m/\d+/g'
    a1 b2
    a34 b56
    EOS
    

    Output:

    12
    3456
    
  • Single match per line, often structured data fields:

    cat <<EOS | perl -lape 's/.*?a(\d+).*/$1/g'
    a1 b2
    a34 b56
    EOS
    

    Output:

    1
    34
    

    With lookbehind:

    cat <<EOS | perl -lane 'print m/(?<=a)(\d+)/'
    a1 b2
    a34 b56
    EOS
    
  • Multiple fields:

    cat <<EOS | perl -lape 's/.*?a(\d+).*?b(\d+).*/$1 $2/g'
    a1 c0 b2 c0
    a34 c0 b56 c0
    EOS
    

    Output:

    1 2
    34 56
    
  • Multiple matches per line, often unstructured data:

    cat <<EOS | perl -lape 's/.*?a(\d+)|.*/$1 /g'
    a1 b2
    a34 b56 a78 b90
    EOS
    

    Output:

    1 
    34 78
    

    With lookbehind:

    cat EOS<< | perl -lane 'print m/(?<=a)(\d+)/g'
    a1 b2
    a34 b56 a78 b90
    EOS
    

    Output:

    1
    3478
    

Angular: Cannot Get /

See this answer here. You need to redirect all routes that Node is not using to Angular:

app.get('*', function(req, res) {
  res.sendfile('./server/views/index.html')
})

File Upload In Angular?

Since the code sample is a bit outdated I thought I'd share a more recent approach, using Angular 4.3 and the new(er) HttpClient API, @angular/common/http

export class FileUpload {

@ViewChild('selectedFile') selectedFileEl;

uploadFile() {
let params = new HttpParams();

let formData = new FormData();
formData.append('upload', this.selectedFileEl.nativeElement.files[0])

const options = {
    headers: new HttpHeaders().set('Authorization', this.loopBackAuth.accessTokenId),
    params: params,
    reportProgress: true,
    withCredentials: true,
}

this.http.post('http://localhost:3000/api/FileUploads/fileupload', formData, options)
.subscribe(
    data => {
        console.log("Subscribe data", data);
    },
    (err: HttpErrorResponse) => {
        console.log(err.message, JSON.parse(err.error).error.message);
    }
)
.add(() => this.uploadBtn.nativeElement.disabled = false);//teardown
}

Default nginx client_max_body_size

You have to increase client_max_body_size in nginx.conf file. This is the basic step. But if your backend laravel then you have to do some changes in the php.ini file as well. It depends on your backend. Below I mentioned file location and condition name.

sudo vim /etc/nginx/nginx.conf.

After open the file adds this into HTTP section.

client_max_body_size 100M;

Is there an upper bound to BigInteger?

The first maximum you would hit is the length of a String which is 231-1 digits. It's much smaller than the maximum of a BigInteger but IMHO it loses much of its value if it can't be printed.

how to remove multiple columns in r dataframe?

@Ahmed Elmahy following approach should help you out, when you have got a vector of column names you want to remove from your dataframe:

test_df <- data.frame(col1 = c("a", "b", "c", "d", "e"), col2 = seq(1, 5), col3 = rep(3, 5))
rm_col <- c("col2")
test_df[, !(colnames(test_df) %in% rm_col), drop = FALSE]

All the best, ExploreR

How to draw checkbox or tick mark in GitHub Markdown table?

Here is what I have that helps you and others about markdown checkbox table. Enjoy!

| Projects | Operating Systems | Programming Languages   | CAM/CAD Programs | Microcontrollers and Processors | 
|---------------------------------- |---------------|---------------|----------------|-----------|
| <ul><li>[ ] Blog </li></ul>       | <ul><li>[ ] CentOS</li></ul>        | <ul><li>[ ] Python </li></ul> | <ul><li>[ ] AutoCAD Electrical </li></ul> | <ul><li>[ ] Arduino </li></ul> |
| <ul><li>[ ] PyGame</li></ul>   | <ul><li>[ ] Fedora </li></ul>       | <ul><li>[ ] C</li></ul> | <ul><li>[ ] 3DsMax </li></ul> |<ul><li>[ ] Raspberry Pi </li></ul> |
| <ul><li>[ ] Server Info Display</li></ul>| <ul><li>[ ] Ubuntu</li></ul> | <ul><li>[ ] C++ </li></ul> | <ul><li>[ ] Adobe AfterEffects </li></ul> |<ul><li>[ ]  </li></ul> |
| <ul><li>[ ] Twitter Subs Bot </li></ul> | <ul><li>[ ] ROS </li></ul>    | <ul><li>[ ] C# </li></ul> | <ul><li>[ ] Adobe Illustrator </li></ul> |<ul><li>[ ]  </li></ul> |

UIScrollView not scrolling

I found that with this AutoLayout issue... if I just make the ViewController use UIView instead of UIScrollView for the class... then just add a UIScrollView myself... that it works.

Check if a string has white space

Your regex won't match anything, as it is. You definitely need to remove the quotes -- the "/" characters are sufficient.

/^\s+$/ is checking whether the string is ALL whitespace:

  • ^ matches the start of the string.
  • \s+ means at least 1, possibly more, spaces.
  • $ matches the end of the string.

Try replacing the regex with /\s/ (and no quotes)

Xcode 7 error: "Missing iOS Distribution signing identity for ..."

Apple has made following changes so download new certificate developer.apple.com

renewed certificate and place it as below screen shots .In the keychain as below screen shots click on system and then certificate. Delete the expired certificate . Then drag and drop the AppleWWDRCA.cer that you downloaded from above link

Apple Worldwide Developer Relations Intermediate Certificate Expiration

To help protect customers and developers, we require that all third party apps, passes for Apple Wallet, Safari Extensions, Safari Push Notifications, and App Store purchase receipts are signed by a trusted certificate authority. The Apple Worldwide Developer Relations Certificate Authority issues the certificates you use to sign your software for Apple devices, allowing our systems to confirm that your software is delivered to users as intended and has not been modified.

The Apple Worldwide Developer Relations Certification Intermediate Certificate expires soon and we've issued a renewed certificate that must be included when signing all new Apple Wallet Passes, push packages for Safari Push Notifications, and Safari Extensions starting February 14, 2016.

While most developers and users will not be affected by the certificate change, we recommend that all developers download and install the renewed certificate on their development systems and servers as a best practice. All apps will remain available on the App Store for iOS, Mac, and Apple TV.

Since different methods can be used for validating receipts and delivering remote notifications, we recommend that you test your services to ensure no implementation-specific issues exist. Your apps may experience receipt verification failure if the receipt checking code makes incorrect assumptions about the certificate. Make sure that your code adheres to the Receipt Validation Programming Guide and resolve all receipt validation issues before February 14, 2016.

enter image description here

How to delete from a table where ID is in a list of IDs?

Your question almost spells the SQL for this:

DELETE FROM table WHERE id IN (1, 4, 6, 7)

Add Items to Columns in a WPF ListView

Solution With Less XAML and More C#

If you define the ListView in XAML:

<ListView x:Name="listView"/>

Then you can add columns and populate it in C#:

public Window()
{
    // Initialize
    this.InitializeComponent();

    // Add columns
    var gridView = new GridView();
    this.listView.View = gridView;
    gridView.Columns.Add(new GridViewColumn { 
        Header = "Id", DisplayMemberBinding = new Binding("Id") });
    gridView.Columns.Add(new GridViewColumn { 
        Header = "Name", DisplayMemberBinding = new Binding("Name") });

    // Populate list
    this.listView.Items.Add(new MyItem { Id = 1, Name = "David" });
}

See definition of MyItem below.

Solution With More XAML and less C#

However, it's easier to define the columns in XAML (inside the ListView definition):

<ListView x:Name="listView">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Id" DisplayMemberBinding="{Binding Id}"/>
            <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}"/>
        </GridView>
    </ListView.View>
</ListView>

And then just populate the list in C#:

public Window()
{
    // Initialize
    this.InitializeComponent();

    // Populate list
    this.listView.Items.Add(new MyItem { Id = 1, Name = "David" });
}

See definition of MyItem below.

MyItem Definition

MyItem is defined like this:

public class MyItem
{
    public int Id { get; set; }

    public string Name { get; set; }
}

How do I sum values in a column that match a given condition using pandas?

The essential idea here is to select the data you want to sum, and then sum them. This selection of data can be done in several different ways, a few of which are shown below.

Boolean indexing

Arguably the most common way to select the values is to use Boolean indexing.

With this method, you find out where column 'a' is equal to 1 and then sum the corresponding rows of column 'b'. You can use loc to handle the indexing of rows and columns:

>>> df.loc[df['a'] == 1, 'b'].sum()
15

The Boolean indexing can be extended to other columns. For example if df also contained a column 'c' and we wanted to sum the rows in 'b' where 'a' was 1 and 'c' was 2, we'd write:

df.loc[(df['a'] == 1) & (df['c'] == 2), 'b'].sum()

Query

Another way to select the data is to use query to filter the rows you're interested in, select column 'b' and then sum:

>>> df.query("a == 1")['b'].sum()
15

Again, the method can be extended to make more complicated selections of the data:

df.query("a == 1 and c == 2")['b'].sum()

Note this is a little more concise than the Boolean indexing approach.

Groupby

The alternative approach is to use groupby to split the DataFrame into parts according to the value in column 'a'. You can then sum each part and pull out the value that the 1s added up to:

>>> df.groupby('a')['b'].sum()[1]
15

This approach is likely to be slower than using Boolean indexing, but it is useful if you want check the sums for other values in column a:

>>> df.groupby('a')['b'].sum()
a
1    15
2     8

How to pass parameters to $http in angularjs?

We can use input data to pass it as a parameter in the HTML file w use ng-model to bind the value of input field.

<input type="text" placeholder="Enter your Email" ng-model="email" required>

<input type="text" placeholder="Enter your password " ng-model="password" required> 

and in the js file w use $scope to access this data:

$scope.email="";
$scope.password="";

Controller function will be something like that:

 var app = angular.module('myApp', []);

    app.controller('assignController', function($scope, $http) {
      $scope.email="";
      $scope.password="";

      $http({
        method: "POST",
        url: "http://localhost:3000/users/sign_in",
        params: {email: $scope.email, password: $scope.password}

      }).then(function mySuccess(response) {
          // a string, or an object, carrying the response from the server.
          $scope.myRes = response.data;
          $scope.statuscode = response.status;

        }, function myError(response) {
          $scope.myRes = response.statusText;
      });
    });

Angularjs - Pass argument to directive

<button my-directive="push">Push to Go</button>

app.directive("myDirective", function() {
    return {
        restrict : "A",
         link: function(scope, elm, attrs) {
                elm.bind('click', function(event) {

                    alert("You pressed button: " + event.target.getAttribute('my-directive'));
                });
        }
    };
});

here is what I did

I'm using directive as html attribute and I passed parameter as following in my HTML file. my-directive="push" And from the directive I retrieved it from the Mouse-click event object. event.target.getAttribute('my-directive').

How to read a file into vector in C++?

Your loop is wrong:

for (int i=0; i=((Main.size())-1); i++) {

Try this:

for (int i=0; i < Main.size(); i++) {

Also, a more idiomatic way of reading numbers into a vector and writing them to stdout is something along these lines:

#include <iostream>
#include <iterator>
#include <fstream>
#include <vector>
#include <algorithm> // for std::copy

int main()
{
  std::ifstream is("numbers.txt");
  std::istream_iterator<double> start(is), end;
  std::vector<double> numbers(start, end);
  std::cout << "Read " << numbers.size() << " numbers" << std::endl;

  // print the numbers to stdout
  std::cout << "numbers read in:\n";
  std::copy(numbers.begin(), numbers.end(), 
            std::ostream_iterator<double>(std::cout, " "));
  std::cout << std::endl;

}

although you should check the status of the ifstream for read errors.

How to run binary file in Linux

Or, the file is of a filetype and/or architecture that you just cannot run with your hardware and/or there is also no fallback binfmt_misc entry to handle the particular format in some other way. Use file(1) to determine.

How to embed an autoplaying YouTube video in an iframe?

The embedded code of youtube has autoplay off by default. Simply add autoplay=1at the end of "src" attribute. For example:

<iframe src="http://www.youtube.com/embed/xzvScRnF6MU?autoplay=1" width="960" height="447" frameborder="0" allowfullscreen></iframe>

Best way to get child nodes

Just to add to the other answers, there are still noteworthy differences here, specifically when dealing with <svg> elements.

I have used both .childNodes and .children and have preferred working with the HTMLCollection delivered by the .children getter.

Today however, I ran into issues with IE/Edge failing when using .children on an <svg>. While .children is supported in IE on basic HTML elements, it isn't supported on document/document fragments, or SVG elements.

For me, I was able to simply grab the needed elements via .childNodes[n] because I don't have extraneous text nodes to worry about. You may be able to do the same, but as mentioned elsewhere above, don't forget that you may run into unexpected elements.

Hope this is helpful to someone scratching their head trying to figure out why .children works elsewhere in their js on modern IE and fails on document or SVG elements.

Calculating number of full months between two dates in SQL

I know this is an old question, but as long as the dates are >= 01-Jan-1753 I use:

DATEDIFF(MONTH, DATEADD(DAY,-DAY(@Start)+1,@Start),DATEADD(DAY,-DAY(@Start)+1,@End))

NumPy array initialization (fill with identical values)

NumPy 1.8 introduced np.full(), which is a more direct method than empty() followed by fill() for creating an array filled with a certain value:

>>> np.full((3, 5), 7)
array([[ 7.,  7.,  7.,  7.,  7.],
       [ 7.,  7.,  7.,  7.,  7.],
       [ 7.,  7.,  7.,  7.,  7.]])

>>> np.full((3, 5), 7, dtype=int)
array([[7, 7, 7, 7, 7],
       [7, 7, 7, 7, 7],
       [7, 7, 7, 7, 7]])

This is arguably the way of creating an array filled with certain values, because it explicitly describes what is being achieved (and it can in principle be very efficient since it performs a very specific task).

How to run SQL script in MySQL?

Very likely, you just need to change the slash/blackslash: from

 \home\sivakumar\Desktop\test.sql

to

 /home/sivakumar/Desktop/test.sql

So the command would be:

source /home/sivakumar/Desktop/test.sql

How to click an element in Selenium WebDriver using JavaScript

Not sure OP answer was really answered.

var driver = new webdriver.Builder().usingServer('serverAddress').withCapabilities({'browserName': 'firefox'}).build();

driver.get('http://www.google.com');
driver.findElement(webdriver.By.id('gbqfb')).click();

Deleting specific rows from DataTable

If you delete an item from a collection, that collection has been changed and you can't continue to enumerate through it.

Instead, use a For loop, such as:

for(int i = dtPerson.Rows.Count-1; i >= 0; i--)
{
    DataRow dr = dtPerson.Rows[i];
    if (dr["name"] == "Joe")
        dr.Delete();
}
dtPerson.AcceptChanges();

Note that you are iterating in reverse to avoid skipping a row after deleting the current index.

Laravel blade check empty foreach

This is my best solution if I understood the question well:

Use of $object->first() method to run the code inside if statement once, that is when on the first loop. The same concept is true with $object->last().

    @if($object->first())
        <div class="panel user-list">
          <table id="myCustomTable" class="table table-hover">
              <thead>
                  <tr>
                     <th class="col-email">Email</th>
                  </tr>
              </thead>
              <tbody>
    @endif

    @foreach ($object as $data)
        <tr class="gradeX">
           <td class="col-name"><strong>{{ $data->email }}</strong></td>
        </tr>
    @endforeach

    @if($object->last())
                </tbody>
            </table>
        </div>
    @endif

What is Android keystore file, and what is it used for?

The answer I would provide is that a keystore file is to authenticate yourself to anyone who is asking. It isn't restricted to just signing .apk files, you can use it to store personal certificates, sign data to be transmitted and a whole variety of authentication.

In terms of what you do with it for Android and probably what you're looking for since you mention signing apk's, it is your certificate. You are branding your application with your credentials. You can brand multiple applications with the same key, in fact, it is recommended that you use one certificate to brand multiple applications that you write. It easier to keep track of what applications belong to you.

I'm not sure what you mean by implications. I suppose it means that no one but the holder of your certificate can update your application. That means that if you release it into the wild, lose the cert you used to sign the application, then you cannot release updates so keep that cert safe and backed up if need be.

But apart from signing apks to release into the wild, you can use it to authenticate your device to a server over SSL if you so desire, (also Android related) among other functions.

How to select current date in Hive SQL

Yes... I am using Hue 3.7.0 - The Hadoop UI and to get current date/time information we can use below commands in Hive:

SELECT from_unixtime(unix_timestamp()); --/Selecting Current Time stamp/

SELECT CURRENT_DATE; --/Selecting Current Date/

SELECT CURRENT_TIMESTAMP; --/Selecting Current Time stamp/

However, in Impala you will find that only below command is working to get date/time details:

SELECT from_unixtime(unix_timestamp()); --/Selecting Current Timestamp /

Hope it resolves your query :)

How to insert blank lines in PDF?

You can also use

document.add(new Paragraph());
document.add(new Paragraph());

before seperator if you are using either it is fine.

Problems after upgrading to Xcode 10: Build input file cannot be found

I had a similar issue after upgrading to a new swift version recently. Moving files around caused my xcode project to reference items that were no longer in the project directory giving me the Error Code Build Input File Not Found.

In my situation I somehow had multiple files/images that were being referenced as described below:enter image description here

In the image above.

  • Navigate to your Targets page.
  • Then Click on the Build Phases tab on the top.
  • Scroll Down to Copy Bundle Resources
  • Find the affected files and remove them. (hit delete on them or select them and hit the minus button )

It was in here that I somehow had multiple files and images that were being referenced from other folders and the build would fail as they could no longer find them. And I could not find them either! or how Xcode was still referencing them

I hope this helps someone else !

What's the difference between an argument and a parameter?

According to Joseph's Alabahari book "C# in a Nutshell" (C# 7.0, p. 49) :

static void Foo (int x)
{
    x = x + 1; // When you're talking in context of this method x is parameter
    Console.WriteLine (x);
}
static void Main()
{
    Foo (8); // an argument of 8. 
             // When you're talking from the outer scope point of view
}

In some human languages (afaik Italian, Russian) synonyms are widely used for these terms.

  • parameter = formal parameter
  • argument = actual parameter

In my university professors use both kind of names.

libstdc++.so.6: cannot open shared object file: No such file or directory

For Fedora use:

yum install libstdc++44.i686

You can find out which versions are supported by running:

yum list all | grep libstdc | grep i686

Reverse HashMap keys and values in Java

Apache commons collections library provides a utility method for inversing the map. You can use this if you are sure that the values of myHashMap are unique

org.apache.commons.collections.MapUtils.invertMap(java.util.Map map)

Sample code

HashMap<String, Character> reversedHashMap = MapUtils.invertMap(myHashMap) 

How to convert integer to char in C?

A char in C is already a number (the character's ASCII code), no conversion required.

If you want to convert a digit to the corresponding character, you can simply add '0':

c = i +'0';

The '0' is a character in the ASCll table.

How do I convert array of Objects into one Object in JavaScript?

You're probably looking for something like this:

_x000D_
_x000D_
// original_x000D_
var arr = [ _x000D_
  {key : '11', value : '1100', $$hashKey : '00X' },_x000D_
  {key : '22', value : '2200', $$hashKey : '018' }_x000D_
];_x000D_
_x000D_
//convert_x000D_
var result = {};_x000D_
for (var i = 0; i < arr.length; i++) {_x000D_
  result[arr[i].key] = arr[i].value;_x000D_
}_x000D_
_x000D_
console.log(result);
_x000D_
_x000D_
_x000D_

Printing reverse of any String without using any predefined function?

This is the simplest solution:

System.out.print("egaugnal detatneiro tcejbo si avaj");

How can I zoom an HTML element in Firefox and Opera?

try this code to zoom the whole page in fireFox

-moz-transform: scale(2);

if I am using this code, the whole page scaled with y and x scroll not properly zoom

so Sorry to say fireFox not working well using "-moz-transform: scale(2);"

**

Simply you can't zoom your page using css in fireFox

**

What is the difference between a .cpp file and a .h file?

Others have already offered good explanations, but I thought I should clarify the differences between the various extensions:

  Source Files for C: .c
  Header Files for C: .h

  Source Files for C++: .cpp
  Header Files for C++: .hpp

Of course, as it has already been pointed out, these are just conventions. The compiler doesn't actually pay any attention to them - it's purely for the benefit of the coder.

How to use graphics.h in codeblocks?

  • Open the file graphics.h using either of Sublime Text Editor or Notepad++,from the include folder where you have installed Codeblocks.
  • Goto line no 302
  • Delete the line and paste int left=0, int top=0, int right=INT_MAX, int bottom=INT_MAX, in that line.
  • Save the file and start Coding.

How to convert a Kotlin source file to a Java source file

As @louis-cad mentioned "Kotlin source -> Java's byte code -> Java source" is the only solution so far.

But I would like to mention the way, which I prefer: using Jadx decompiler for Android.

It allows to see the generates code for closures and, as for me, resulting code is "cleaner" then one from IntelliJ IDEA decompiler.

Normally when I need to see Java source code of any Kotlin class I do:

  • Generate apk: ./gradlew assembleDebug
  • Open apk using Jadx GUI: jadx-gui ./app/build/outputs/apk/debug/app-debug.apk

In this GUI basic IDE functionality works: class search, click to go declaration. etc.

Also all the source code could be saved and then viewed using other tools like IntelliJ IDEA.

Change span text?

document.getElementById("serverTime").innerHTML = ...;

Declare a const array

This is a way to do what you want:

using System;
using System.Collections.ObjectModel;
using System.Collections.Generic;

public ReadOnlyCollection<string> Titles { get { return new List<string> { "German", "Spanish", "Corrects", "Wrongs" }.AsReadOnly();}}

It is very similar to doing a readonly array.

android get real path by Uri.getPath()

This is what I do:

Uri selectedImageURI = data.getData();
imageFile = new File(getRealPathFromURI(selectedImageURI));

and:

private String getRealPathFromURI(Uri contentURI) {
    String result;
    Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
    if (cursor == null) { // Source is Dropbox or other similar local file path
        result = contentURI.getPath();
    } else { 
        cursor.moveToFirst(); 
        int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); 
        result = cursor.getString(idx);
        cursor.close();
    }
    return result;
}

NOTE: managedQuery() method is deprecated, so I am not using it.

Last edit: Improvement. We should close cursor!!

Can't bind to 'dataSource' since it isn't a known property of 'table'

  • Angular Core v6.0.2,
  • Angular Material, v6.0.2,
  • Angular CLI v6.0.0 (globally v6.1.2)

I had this issue when running ng test, so to fix it, I added to my xyz.component.spec.ts file:

import { MatTableModule } from '@angular/material';

And added it to imports section in TestBed.configureTestingModule({}):

beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [ ReactiveFormsModule, HttpClientModule, RouterTestingModule, MatTableModule ],
      declarations: [ BookComponent ],
      schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
    })
    .compileComponents();
}));

css3 text-shadow in IE9

As IE9 does not support CSS3 text-shadow, I would just use the filter property for IE instead. Live example: http://jsfiddle.net/dmM2S/

text-shadow:1px 1px 1px red; /* CSS3 */

can be replaced with

filter: Shadow(Color=red, Direction=130, Strength=1); /* IE Proprietary Filter*/

You can get the results to be very similar.

Array slices in C#

Arrays are enumerable, so your foo already is an IEnumerable<byte> itself. Simply use LINQ sequence methods like Take() to get what you want out of it (don't forget to include the Linq namespace with using System.Linq;):

byte[] foo = new byte[4096];

var bar = foo.Take(41);

If you really need an array from any IEnumerable<byte> value, you could use the ToArray() method for that. That does not seem to be the case here.

Convert Pixels to Points

Height lines converted into points and pixel (my own formula). Here is an example with a manual entry of 213.67 points in the Row Height field:

213.67  Manual Entry    
  0.45  Add 0.45    
214.12  Subtotal    
213.75  Round to a multiple of 0.75 
213.00  Subtract 0.75 provides manual entry converted by Excel  
284.00  Divide by 0.75 gives the number of pixels of height

Here the manual entry of 213.67 points gives 284 pixels.
Here the manual entry of 213.68 points gives 285 pixels.

(Why 0.45? I do not know but it works.)

Python: SyntaxError: keyword can't be an expression

Using the Elastic search DSL API, you may hit the same error with

s = Search(using=client, index="my-index") \
    .query("match", category.keyword="Musician")

You can solve it by doing:

s = Search(using=client, index="my-index") \
    .query({"match": {"category.keyword":"Musician/Band"}})

MongoError: connect ECONNREFUSED 127.0.0.1:27017

You probably need to continue running your DB process (by running mongod) while running your node server.

How to use environment variables in docker compose

Use .env file to define dynamic values in docker-compse.yml. Be it port or any other value.

Sample docker-compose:

testcore.web:
       image: xxxxxxxxxxxxxxx.dkr.ecr.ap-northeast-2.amazonaws.com/testcore:latest
       volumes: 
            - c:/logs:c:/logs
       ports:
            - ${TEST_CORE_PORT}:80
       environment:
            - CONSUL_URL=http://${CONSUL_IP}:8500 
            - HOST=${HOST_ADDRESS}:${TEST_CORE_PORT}

Inside .env file you can define the value of these variables:

CONSUL_IP=172.31.28.151
HOST_ADDRESS=172.31.16.221
TEST_CORE_PORT=10002

Regex replace (in Python) - a simpler way?

The short version is that you cannot use variable-width patterns in lookbehinds using Python's re module. There is no way to change this:

>>> import re
>>> re.sub("(?<=foo)bar(?=baz)", "quux", "foobarbaz")
'fooquuxbaz'
>>> re.sub("(?<=fo+)bar(?=baz)", "quux", "foobarbaz")

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    re.sub("(?<=fo+)bar(?=baz)", "quux", string)
  File "C:\Development\Python25\lib\re.py", line 150, in sub
    return _compile(pattern, 0).sub(repl, string, count)
  File "C:\Development\Python25\lib\re.py", line 241, in _compile
    raise error, v # invalid expression
error: look-behind requires fixed-width pattern

This means that you'll need to work around it, the simplest solution being very similar to what you're doing now:

>>> re.sub("(fo+)bar(?=baz)", "\\1quux", "foobarbaz")
'fooquuxbaz'
>>>
>>> # If you need to turn this into a callable function:
>>> def replace(start, replace, end, replacement, search):
        return re.sub("(" + re.escape(start) + ")" + re.escape(replace) + "(?=" + re.escape + ")", "\\1" + re.escape(replacement), search)

This doesn't have the elegance of the lookbehind solution, but it's still a very clear, straightforward one-liner. And if you look at what an expert has to say on the matter (he's talking about JavaScript, which lacks lookbehinds entirely, but many of the principles are the same), you'll see that his simplest solution looks a lot like this one.

PHP remove all characters before specific string

Considering

$string="We have www/audio path where the audio files are stored";  //Considering the string like this

Either you can use

strstr($string, 'www/audio');

Or

$expStr=explode("www/audio",$string);
$resultString="www/audio".$expStr[1];

Http Post request with content type application/x-www-form-urlencoded not working in Spring

Remove @ResponseBody annotation from your use parameters in method. Like this;

   @Autowired
    ProjectService projectService;

    @RequestMapping(path = "/add", method = RequestMethod.POST)
    public ResponseEntity<Project> createNewProject(Project newProject){
        Project project = projectService.save(newProject);

        return new ResponseEntity<Project>(project,HttpStatus.CREATED);
    }

Copy Files from Windows to the Ubuntu Subsystem

You should be able to access your windows system under the /mnt directory. For example inside of bash, use this to get to your pictures directory:

cd /mnt/c/Users/<ubuntu.username>/Pictures

Hope this helps!

This IP, site or mobile application is not authorized to use this API key

Disable both direction api and geocoding api and re-enable.

it works for only 5-10 seconds and than automatically disabled itself.

it means you have only 5-10 sec to test you assignment.

Erase the current printed console line

under windows 10 one can use VT100 style by activating the VT100 mode in the current console to use escape sequences as follow :

#include <windows.h>
#include <iostream>

#define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
#define DISABLE_NEWLINE_AUTO_RETURN  0x0008

int main(){

  // enabling VT100 style in current console
  DWORD l_mode;
  HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
  GetConsoleMode(hStdout,&l_mode)
  SetConsoleMode( hStdout, l_mode |
            ENABLE_VIRTUAL_TERMINAL_PROCESSING |
            DISABLE_NEWLINE_AUTO_RETURN );

  // create a waiting loop with changing text every seconds
  while(true) {
    // erase current line and go to line begining 
    std::cout << "\x1B[2K\r";
    std::cout << "wait a second .";
    Sleep(1);
    std::cout << "\x1B[2K\r";
    std::cout << "wait a second ..";
    Sleep(1);
    std::cout << "\x1B[2K\r";
    std::cout << "wait a second ...";
    Sleep(1);
    std::cout << "\x1B[2K\r";
    std::cout << "wait a second ....";
 }

}

see following link : windows VT100

What are the differences between the urllib, urllib2, urllib3 and requests module?

To get the content of a url:

try: # Try importing requests first.
    import requests
except ImportError: 
    try: # Try importing Python3 urllib
        import urllib.request
    except AttributeError: # Now importing Python2 urllib
        import urllib


def get_content(url):
    try:  # Using requests.
        return requests.get(url).content # Returns requests.models.Response.
    except NameError:  
        try: # Using Python3 urllib.
            with urllib.request.urlopen(index_url) as response:
                return response.read() # Returns http.client.HTTPResponse.
        except AttributeError: # Using Python3 urllib.
            return urllib.urlopen(url).read() # Returns an instance.

It's hard to write Python2 and Python3 and request dependencies code for the responses because they urlopen() functions and requests.get() function return different types:

  • Python2 urllib.request.urlopen() returns a http.client.HTTPResponse
  • Python3 urllib.urlopen(url) returns an instance
  • Request request.get(url) returns a requests.models.Response

"SDK Platform Tools component is missing!"

The latest version of the Android SDK ships with two different applications: an SDK Manager and an AVD Manager rather than one single app that was valid when this question was originally asked.

My particular problem was unrelated to the other suggestions. I'm on a network at the moment where HTTPS traffic is mostly disallowed. In order to install the Android Platform Tools I needed to turn on the option to "Force https://... sources to be fetched using http://..." and then this allowed me to install the other tools.

How to find rows in one table that have no corresponding row in another table

select tableA.id from tableA left outer join tableB on (tableA.id = tableB.id)
where tableB.id is null
order by tableA.id desc 

If your db knows how to do index intersections, this will only touch the primary key index

Sleep for milliseconds

#include <windows.h>

Syntax:

Sleep (  __in DWORD dwMilliseconds   );

Usage:

Sleep (1000); //Sleeps for 1000 ms or 1 sec

How to make the corners of a button round?

Create a xml file in drawable folder like below

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" android:padding="10dp">
    <!-- you can use any color you want I used here gray color-->
    <solid android:color="#ABABAB"/> 
    <corners android:radius="10dp"/>
</shape>

Apply this as background to button you want make corners round.

Or you can use separate radius for every corner like below

android:bottomRightRadius="10dp"
android:bottomLeftRadius="10dp"
android:topLeftRadius="10dp"
android:topRightRadius="10dp"

SQL Server tables: what is the difference between @, # and ##?

CREATE TABLE #t

Creates a table that is only visible on and during that CONNECTION the same user who creates another connection will not be able to see table #t from the other connection.

CREATE TABLE ##t

Creates a temporary table visible to other connections. But the table is dropped when the creating connection is ended.

Use jQuery to scroll to the bottom of a div with lots of text

please refer : .scrollTop(), You can give a try to the solution here : http://jsfiddle.net/y430ovjt/

_x000D_
_x000D_
$(function() {_x000D_
  var wtf    = $('#scroll');_x000D_
  var height = wtf[0].scrollHeight;_x000D_
  wtf.scrollTop(height);_x000D_
});
_x000D_
 #scroll {_x000D_
   width: 200px;_x000D_
   height: 300px;_x000D_
   overflow-y: scroll;_x000D_
 }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="scroll">_x000D_
    <br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/> <center><b>Voila!! You have already reached the bottom :)<b></center>_x000D_
</div>
_x000D_
_x000D_
_x000D_


Edit : for the people who are looking for a nice little animation with scrolling : http://jsfiddle.net/o98zbx8j

_x000D_
_x000D_
$(function() {_x000D_
  var height = 0;_x000D_
_x000D_
  function scroll(height, ele) {_x000D_
    this.stop().animate({_x000D_
      scrollTop: height_x000D_
    }, 1000, function() {_x000D_
      var dir = height ? "top" : "bottom";_x000D_
      $(ele).html("scroll to " + dir).attr({_x000D_
        id: dir_x000D_
      });_x000D_
    });_x000D_
  };_x000D_
  var wtf = $('#scroll');_x000D_
  $("#bottom, #top").click(function() {_x000D_
    height = height < wtf[0].scrollHeight ? wtf[0].scrollHeight : 0;_x000D_
    scroll.call(wtf, height, this);_x000D_
  });_x000D_
});
_x000D_
#scroll {_x000D_
  width: 300px;_x000D_
  height: 200px;_x000D_
  overflow-y: scroll;_x000D_
}_x000D_
#bottom,_x000D_
#top {_x000D_
  font-size: 12px;_x000D_
  cursor: pointer;_x000D_
  min-width: 50px;_x000D_
  padding: 5px;_x000D_
  border: 2px solid #0099f9;_x000D_
  border-radius: 5px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<span id="bottom">scroll to bottom</span>_x000D_
<br />_x000D_
<br />_x000D_
<br />_x000D_
<div id="scroll">_x000D_
  <center><b>There's Plenty of Room at the Top, seriously?</b>_x000D_
  </center>_x000D_
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam at enim dignissim, eleifend eros at, lobortis sem. Mauris vel erat felis. Proin quis convallis neque, quis molestie augue. Vestibulum aliquam elit sit amet venenatis eleifend. Donec dapibus_x000D_
    mauris ac lorem mattis pulvinar. Curabitur cursus elit commodo tellus bibendum, ut euismod nisi luctus. Pellentesque id magna nunc. Nam luctus nisi sapien, ac porta sem ultrices vitae. Suspendisse aliquet eleifend nunc, in mattis tellus dapibus rutrum._x000D_
    Nullam a sem venenatis, suscipit lorem eu, facilisis leo. Nunc eget eleifend magna. Curabitur dictum dui in massa vestibulum sagittis. Mauris sodales neque at tincidunt feugiat. Curabitur iaculis purus nec tortor elementum pulvinar. Donec non mattis_x000D_
    augue.</p>_x000D_
_x000D_
  <p>Integer sit amet iaculis nulla. Cras vehicula nunc eu leo aliquet, et convallis erat aliquet. Aenean tempor faucibus justo, porta blandit felis semper at. Maecenas auctor nibh sit amet tellus consectetur, et varius velit iaculis. Phasellus convallis_x000D_
    lacinia dapibus. Praesent tempus nunc elit, id volutpat tellus sagittis commodo. Vestibulum ultrices quam vel congue viverra. Integer varius diam quis tempor consequat. Integer pulvinar neque lorem, eu lobortis augue pharetra vel. Praesent ornare_x000D_
    lacus quis nisi fermentum dignissim. Curabitur hendrerit augue eu interdum interdum.</p>_x000D_
_x000D_
  <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Etiam a ex non dolor rutrum suscipit vitae sit amet nibh. Donec pulvinar odio non ultrices dignissim. Quisque in risus lobortis, accumsan ante et, pellentesque_x000D_
    erat. Quisque ultricies tortor sed tortor venenatis posuere. Integer convallis nunc ut tellus sagittis, et imperdiet erat volutpat. Sed non maximus augue. Sed mattis ipsum sed sem rutrum, at mollis ligula facilisis. Etiam fringilla hendrerit mi eu_x000D_
    molestie. Etiam semper feugiat nunc, eu pellentesque metus porta pretium. Duis tempor neque ut libero scelerisque euismod. Vivamus molestie, quam a mattis scelerisque, dolor turpis accumsan quam, a cursus sem quam at ex. Suspendisse congue elit quis_x000D_
    sem scelerisque commodo.</p>_x000D_
_x000D_
  <p>Ut eu odio at urna hendrerit ullamcorper. Nulla ut turpis molestie diam aliquet luctus. Curabitur dignissim tellus ut porta sagittis. Vivamus ut erat ut neque consequat interdum. Duis vitae risus eget arcu pulvinar venenatis. Maecenas erat arcu, hendrerit_x000D_
    id tortor ut, viverra elementum nibh. Nam quis metus sit amet lacus rhoncus porttitor ac non ipsum. Nullam lacus dui, tempus sed elementum ut, venenatis eget ipsum. Quisque blandit maximus enim eu porta.</p>_x000D_
_x000D_
  <p>Donec mollis diam eros, eu ultrices magna sollicitudin vitae. Nullam quam sapien, elementum a metus nec, facilisis scelerisque nulla. Praesent lobortis nisi ac leo laoreet, quis molestie ipsum porta. Suspendisse aliquet in velit eu ullamcorper. Maecenas_x000D_
    auctor, mi ut viverra elementum, metus turpis commodo orci, eu commodo erat dolor malesuada arcu. Fusce condimentum augue</p>_x000D_
  <center><b>Voila!! You have reached the bottom, already! :)</b>_x000D_
  </center>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to a convert a date to a number and back again in MATLAB

Use DATESTR

>> datestr(40189)
ans =
12-Jan-0110

Unfortunately, Excel starts counting at 1-Jan-1900. Find out how to convert serial dates from Matlab to Excel by using DATENUM

>> datenum(2010,1,11)
ans =
      734149
>> datenum(2010,1,11)-40189
ans =
      693960
>> datestr(40189+693960)
ans =
11-Jan-2010

In other words, to convert any serial Excel date, call

datestr(excelSerialDate + 693960)

EDIT

To get the date in mm/dd/yyyy format, call datestr with the specified format

excelSerialDate = 40189;
datestr(excelSerialDate + 693960,'mm/dd/yyyy')
ans =
01/11/2010

Also, if you want to get rid of the leading zero for the month, you can use REGEXPREP to fix things

excelSerialDate = 40189;
regexprep(datestr(excelSerialDate + 693960,'mm/dd/yyyy'),'^0','')
ans =
1/11/2010

Permission denied: /var/www/abc/.htaccess pcfg_openfile: unable to check htaccess file, ensure it is readable?

If it gets into the selinux arena you've got a much more complicated issue. It's not a good idea to remove the selinux protection but to embrace it and use the tools that were designed to manage it.

If you are serving content out of /var/www/abc, you can verify the selinux permissions with a Z appended to the normal ls -l command. i.e. ls -laZ will give the selinux context.

To add a directory to be served by selinux you can use the semanage command like this. This will change the label on /var/www/abc to httpd_sys_content_t

semanage fcontext -a -t httpd_sys_content_t /var/www/abc

this will update the label for /var/www/abc

restorecon /var/www/abc 

This answer was taken from unixmen and modified to fit this question. I had been searching for this answer for a while and finally found it so felt like I needed to share somewhere. Hope it helps someone.

how to read value from string.xml in android?

Details

  • Android Studio 3.1.4
  • Kotlin version: 1.2.60

Task

  • single line use
  • minimum code
  • use suggestions from the compiler

Step 1. Application()

Get link to the context of you application

class MY_APPLICATION_NAME: Application() {

    companion object {
        private lateinit var instance: MY_APPLICATION_NAME

        fun getAppContext(): Context = instance.applicationContext
    }

    override fun onCreate() {
        instance = this
        super.onCreate()
    }

}

Step 2. Add int extension

inline fun Int.toLocalizedString(): String = MY_APPLICATION_NAME.getAppContext().resources.getString(this)

Usage

strings.xml

<resources>
    <!-- .......  -->
    <string name="no_internet_connection">No internet connection</string>
    <!-- .......  -->
</resources>

Get string value:

val errorMessage = R.string.no_internet_connection.toLocalizedString()

Results

enter image description here enter image description here

How to redirect verbose garbage collection output to a file?

To add to the above answers, there's a good article: Useful JVM Flags – Part 8 (GC Logging) by Patrick Peschlow.

A brief excerpt:

The flag -XX:+PrintGC (or the alias -verbose:gc) activates the “simple” GC logging mode

By default the GC log is written to stdout. With -Xloggc:<file> we may instead specify an output file. Note that this flag implicitly sets -XX:+PrintGC and -XX:+PrintGCTimeStamps as well.

If we use -XX:+PrintGCDetails instead of -XX:+PrintGC, we activate the “detailed” GC logging mode which differs depending on the GC algorithm used.

With -XX:+PrintGCTimeStamps a timestamp reflecting the real time passed in seconds since JVM start is added to every line.

If we specify -XX:+PrintGCDateStamps each line starts with the absolute date and time.

How to auto-size an iFrame?

Here is a dead simple solution that works on every browser and with cross domains:

First, this works on the concept that if the html page containing the iframe is set to a height of 100% and the iframe is styled using css to have a height of 100%, then css will automatically size everything to fit.

Here is the code:

<head>
<style type="text/css"> 
html {height:100%}
body {
margin:0;
height:100%;
overflow:hidden
}
</style>
</head>

<body>
<iframe allowtransparency=true frameborder=0 id=rf sandbox="allow-same-origin allow-forms allow-scripts" scrolling=auto src="http://www.externaldomain.com/" style="width:100%;height:100%"></iframe>
</body>

'JSON' is undefined error in JavaScript in Internet Explorer

Maybe it is not what you are looking for, but I had a similar problem and i solved it including JSON 2 to my application:

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

Other browsers natively implements JSON but IE < 8 (also IE 8 compatibility mode) does not, that's why you need to include it.

Here is a related question: JSON on IE6 (IE7)

UPDATE

the JSON parser has been updated so you should use the new one: http://bestiejs.github.io/json3/

Creating composite primary key in SQL Server

How about this:

ALTER TABLE dbo.testRequest
ADD CONSTRAINT PK_TestRequest 
PRIMARY KEY (wardNo, BHTNo, TestID) 

How to format a date using ng-model?

I've created a simple directive to enable standard input[type="date"] form elements to work correctly with AngularJS ~1.2.16.

Look here: https://github.com/betsol/angular-input-date

And here's the demo: http://jsfiddle.net/F2LcY/1/

Mergesort with Python

A little late the the party, but I figured I'd throw my hat in the ring as my solution seems to run faster than OP's (on my machine, anyway):

# [Python 3]
def merge_sort(arr):
    if len(arr) < 2:
        return arr
    half = len(arr) // 2
    left = merge_sort(arr[:half])
    right = merge_sort(arr[half:])
    out = []
    li = ri = 0  # index of next element from left, right halves
    while True:
        if li >= len(left):  # left half is exhausted
            out.extend(right[ri:])
            break
        if ri >= len(right): # right half is exhausted
            out.extend(left[li:])
            break
        if left[li] < right[ri]:
            out.append(left[li])
            li += 1
        else:
            out.append(right[ri])
            ri += 1
    return out

This doesn't have any slow pop()s, and once one of the half-arrays is exhausted, it immediately extends the other one onto the output array rather than starting a new loop.

I know it's machine dependent, but for 100,000 random elements (above merge_sort() vs. Python built-in sorted()):

merge sort: 1.03605 seconds
Python sort: 0.045 seconds
Ratio merge / Python sort: 23.0229

How to select a single child element using jQuery?

I think what you want to do is this:

$(this).children('img').eq(0);

this will give you a jquery object containing the first img element, whereas

$(this).children('img')[0];

will give you the img element itself.

How to select label for="XYZ" in CSS?

If the label immediately follows a specified input element:

input#example + label { ... }
input:checked + label { ... }

Why is json_encode adding backslashes?

This happens because the JSON format uses ""(Quotes) and anything in between these quotes is useful information (either key or the data).

Suppose your data was : He said "This is how it is done". Then the actual data should look like "He said \"This is how it is done\".".

This ensures that the \" is treated as "(Quotation mark) and not as JSON formatting. This is called escape character.

This usually happens when one tries to encode an already JSON encoded data, which is a common way I have seen this happen.

Try this

$arr = ['This is a sample','This is also a "sample"']; echo json_encode($arr);

OUTPUT:

["This is a sample","This is also a \"sample\""]

Custom Adapter for List View

A more compact example of a custom adapter (using list array as my data):

class MyAdapter extends ArrayAdapter<Object> {
    public ArrayAdapter(Context context, List<MyObject> objectList) {
        super(context, R.layout.my_list_item, R.id.textViewTitle, objectList.toArray());
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View row = super.getView(position, convertView, parent);
        TextView title = (TextView) row.findViewById(R.id.textViewTitle);
        ImageView icon = (ImageView) row.findViewById(R.id.imageViewAccessory);
        MyObject obj = (MyObject) getItem(position);
        icon.setImageBitmap( ... );
        title.setText(obj.name);
        return row;
    }
}

And this is how to use it:

List<MyObject> objectList = ...
MyAdapter adapter = new MyAdapter(this.getActivity(), objectList);
listView.setAdapter(adapter);

How does PHP 'foreach' actually work?

As per the documentation provided by PHP manual.

On each iteration, the value of the current element is assigned to $v and the internal
array pointer is advanced by one (so on the next iteration, you'll be looking at the next element).

So as per your first example:

$array = ['foo'=>1];
foreach($array as $k=>&$v)
{
   $array['bar']=2;
   echo($v);
}

$array have only single element, so as per the foreach execution, 1 assign to $v and it don't have any other element to move pointer

But in your second example:

$array = ['foo'=>1, 'bar'=>2];
foreach($array as $k=>&$v)
{
   $array['baz']=3;
   echo($v);
}

$array have two element, so now $array evaluate the zero indices and move the pointer by one. For first iteration of loop, added $array['baz']=3; as pass by reference.

How to check for palindrome using Python logic

There is much easier way I just found. It's only 1 line.

is_palindrome = word.find(word[::-1])

Retrieving a Foreign Key value with django-rest-framework serializers

This solution is better because of no need to define the source model. But the name of the serializer field should be the same as the foreign key field name

class ItemSerializer(serializers.ModelSerializer):
    category = serializers.SlugRelatedField(read_only=True, slug_field='title')

    class Meta:
        model = Item
        fields = ('id', 'name', 'category')

Cannot make a static reference to the non-static method fxn(int) from the type Two

You cannot refer non-static members from a static method.

Non-Static members (like your fxn(int y)) can be called only from an instance of your class.

Example:

You can do this:

       public class A
       {
           public   int fxn(int y) {
              y = 5;
              return y;
          }
       }


  class Two {
public static void main(String[] args) {
    int x = 0;
    A a = new A();
    System.out.println("x = " + x);
    x = a.fxn(x);
    System.out.println("x = " + x);
}

or you can declare you method as static.

Django download a file

If you hafe upload your file in media than:

media
example-input-file.txt

views.py

def download_csv(request):    
    file_path = os.path.join(settings.MEDIA_ROOT, 'example-input-file.txt')    
    if os.path.exists(file_path):    
        with open(file_path, 'rb') as fh:    
            response = HttpResponse(fh.read(), content_type="application/vnd.ms-excel")    
            response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path)    
            return response

urls.py

path('download_csv/', views.download_csv, name='download_csv'),

download.html

a href="{% url 'download_csv' %}" download=""

How can I calculate the time between 2 Dates in typescript

In order to calculate the difference you have to put the + operator,

that way typescript converts the dates to numbers.

+new Date()- +new Date("2013-02-20T12:01:04.753Z")

From there you can make a formula to convert the difference to minutes or hours.

Calling another method java GUI

I'm not sure what you're trying to do, but here's something to consider: c(); won't do anything. c is an instance of the class checkbox and not a method to be called. So consider this:

public class FirstWindow extends JFrame {      public FirstWindow() {         checkbox c = new checkbox();         c.yourMethod(yourParameters); // call the method you made in checkbox     } }  public class checkbox extends JFrame {      public checkbox(yourParameters) {          // this is the constructor method used to initialize instance variables     }      public void yourMethod() // doesn't have to be void     {         // put your code here     } } 

How to strip all whitespace from string

import re
re.sub(' ','','strip my spaces')

How to show a confirm message before delete?

function del_confirm(msg,url)
        {
            if(confirm(msg))
            {
                window.location.href=url
            }
            else
            {
                false;
            }

        }



<a  onclick="del_confirm('Are you Sure want to delete this record?','<filename>.php?action=delete&id=<?<id> >')"href="#"></a>

Docker - Bind for 0.0.0.0:4000 failed: port is already allocated

I've had same problem with docker-compose:

  1. Killed docker-proxy processe .
  2. Restart docker
  3. Start docker-compose again.

org.springframework.beans.factory.BeanCreationException: Error creating bean with name

you need to add jar file in your build path..

commons-dbcp-1.1-RC2.jar

or any version of that..!!!!

ADDED : also make sure you have commons-pool-1.1.jar too in your build path.

ADDED: sorry saw complete list of jar late... may be version clashes might be there.. better check out..!!! just an assumption.

Fastest way to count number of occurrences in a Python list

You can convert list in string with elements seperated by space and split it based on number/char to be searched..

Will be clean and fast for large list..

>>>L = [2,1,1,2,1,3]
>>>strL = " ".join(str(x) for x in L)
>>>strL
2 1 1 2 1 3
>>>count=len(strL.split(" 1"))-1
>>>count
3

What is the difference between ng-if and ng-show/ng-hide

To note, a thing that happened to me now: ng-show does hide the content via css, yes, but it resulted in strange glitches in div's supposed to be buttons.

I had a card with two buttons on the bottom and depending on the actual state one is exchanged with an third, example edit button with new entry. Using ng-show=false to hide the left one(present first in the file) it happened that the following button ended up with the right border outside of the card. ng-if fixes that by not including the code at all. (Just checked here if there are some hidden surprises using ng-if instead of ng-show)

How can I send large messages with Kafka (over 15MB)?

One key thing to remember that message.max.bytes attribute must be in sync with the consumer's fetch.message.max.bytes property. the fetch size must be at least as large as the maximum message size otherwise there could be situation where producers can send messages larger than the consumer can consume/fetch. It might worth taking a look at it.
Which version of Kafka you are using? Also provide some more details trace that you are getting. is there some thing like ... payload size of xxxx larger than 1000000 coming up in the log?

java.lang.NoClassDefFoundError in junit

  1. Right click your project in Package Explorer > click Properties
  2. go to Java Build Path > Libraries tab
  3. click on 'Add Library' button
  4. select JUnit
  5. click Next.
  6. select in dropdown button JUnit4 or other new versions.
  7. click finish.
  8. Then Ok.

Iterate through DataSet

foreach (DataTable table in dataSet.Tables)
{
    foreach (DataRow row in table.Rows)
    {
        foreach (object item in row.ItemArray)
        {
            // read item
        }
    }
}

Or, if you need the column info:

foreach (DataTable table in dataSet.Tables)
{
    foreach (DataRow row in table.Rows)
    {
        foreach (DataColumn column in table.Columns)
        {
            object item = row[column];
            // read column and item
        }
    }
}

NSPhotoLibraryUsageDescription key must be present in Info.plist to use camera roll

i faced the same issue few days earlier for my IONIC 4 Project. when i uploaded my IPA, i got this warnings from App Store Connect.

enter image description here

I fixed the "Missing Purpose String in info.plist" issue, by the following steps. hope it will also work for you.

  1. Goto your "info.plist" file.

enter image description here

  1. Find this key, called Privacy - Photo Library Usage Description. if it's not present there, add a new one and it's value, like below image.

enter image description here

Thanks.

OS specific instructions in CMAKE: How to?

In General

You can detect and specify variables for several operating systems like that:

Detect Microsoft Windows

if(WIN32)
    # for Windows operating system in general
endif()

Or:

if(MSVC OR MSYS OR MINGW)
    # for detecting Windows compilers
endif()

Detect Apple MacOS

if(APPLE)
    # for MacOS X or iOS, watchOS, tvOS (since 3.10.3)
endif()

Detect Unix and Linux

if(UNIX AND NOT APPLE)
    # for Linux, BSD, Solaris, Minix
endif()

Your specific linker issue

To solve your issue with the Windows-specific wsock32 library, just remove it from other systems, like that:

if(WIN32)
    target_link_libraries(${PROJECT_NAME} bioutils wsock32)
else
    target_link_libraries(${PROJECT_NAME} bioutils)
endif()

sequelize findAll sort order in nodejs

You can accomplish this in a very back-handed way with the following code:

exports.getStaticCompanies = function () {
    var ids = [46128, 2865, 49569, 1488, 45600, 61991, 1418, 61919, 53326, 61680]
    return Company.findAll({
        where: {
            id: ids
        },
        attributes: ['id', 'logo_version', 'logo_content_type', 'name', 'updated_at'],
        order: sequelize.literal('(' + ids.map(function(id) {
            return '"Company"."id" = \'' + id + '\'');
        }).join(', ') + ') DESC')
    });
};

This is somewhat limited because it's got very bad performance characteristics past a few dozen records, but it's acceptable at the scale you're using.

This will produce a SQL query that looks something like this:

[...] ORDER BY ("Company"."id"='46128', "Company"."id"='2865', "Company"."id"='49569', [...])

How to implement drop down list in flutter?

For anyone interested to implement a DropDown of custom class you can follow the bellow steps.

  1. Suppose you have a class called Language with the following code and a static method which returns a List<Language>

    class Language {
      final int id;
      final String name;
      final String languageCode;
    
      const Language(this.id, this.name, this.languageCode);
    
    
    }
    
     const List<Language> getLanguages = <Language>[
            Language(1, 'English', 'en'),
            Language(2, '?????', 'fa'),
            Language(3, '????', 'ps'),
         ];
    
  2. Anywhere you want to implement a DropDown you can import the Language class first use it as follow

        DropdownButton(
            underline: SizedBox(),
            icon: Icon(
                        Icons.language,
                        color: Colors.white,
                        ),
            items: getLanguages.map((Language lang) {
            return new DropdownMenuItem<String>(
                            value: lang.languageCode,
                            child: new Text(lang.name),
                          );
                        }).toList(),
    
            onChanged: (val) {
                          print(val);
                       },
          )
    

Ruby replace string with captured regex pattern

def get_code(str)
  str.sub(/^(Z_.*): .*/, '\1')
end
get_code('Z_foo: bar!') # => "Z_foo"

Eloquent - where not equal to

Or like this:

Code::whereNotIn('to_be_used_by_user_id', [2])->get();

How to check if a Docker image with a specific tag exist locally?

You can use like the following:

[ ! -z $(docker images -q someimage:sometag) ] || echo "does not exist"

Or:

[ -z $(docker images -q someimage:sometag) ] || echo "already exists"

How to change background color of cell in table using java script

document.getElementById('id1').bgColor = '#00FF00';

seems to work. I don't think .style.backgroundColor does.

Delete all rows in a table based on another table

While the OP doesn't want to use an 'in' statement, in reply to Ankur Gupta, this was the easiest way I found to delete the records in one table which didn't exist in another table, in a one to many relationship:

DELETE
FROM Table1 as t1
WHERE ID_Number NOT IN
(SELECT ID_Number FROM Table2 as t2)

Worked like a charm in Access 2016, for me.

Disable Required validation attribute under certain circumstances

You can remove all validation off a property with the following in your controller action.

ModelState.Remove<ViewModel>(x => x.SomeProperty);

@Ian's comment regarding MVC5

The following is still possible

ModelState.Remove("PropertyNameInModel");

Bit annoying that you lose the static typing with the updated API. You could achieve something similar to the old way by creating an instance of HTML helper and using NameExtensions Methods.

XAMPP - Apache could not start - Attempting to start Apache service

when i run xampp control panel normal:

enter image description here

I had been run

I can’t start apache So, I will run it with administrator:

enter image description here

I can run apache

How to create a simple checkbox in iOS?

On iOS there is the switch UI component instead of a checkbox, look into the UISwitch class. The property on (boolean) can be used to determine the state of the slider and about the saving of its state: That depends on how you save your other stuff already, its just saving a boolean value.

How to initailize byte array of 100 bytes in java with all 0's

A new byte array will automatically be initialized with all zeroes. You don't have to do anything.

The more general approach to initializing with other values, is to use the Arrays class.

import java.util.Arrays;

byte[] bytes = new byte[100];
Arrays.fill( bytes, (byte) 1 );

How to Clear Console in Java?

Try this code

import java.io.IOException;

public class CLS {
    public static void main(String... arg) throws IOException, InterruptedException {
        new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
    }
}

Now when the Java process is connected to a console, it will clear the console.

Entity Framework is Too Slow. What are my options?

The fact of the matter is that products such as Entity Framework will ALWAYS be slow and inefficient, because they are executing lot more code.

I also find it silly that people are suggesting that one should optimize LINQ queries, look at the SQL generated, use debuggers, pre-compile, take many extra steps, etc. i.e. waste a lot of time. No one says - Simplify! Everyone wants to comlicate things further by taking even more steps (wasting time).

A common sense approach would be not to use EF or LINQ at all. Use plain SQL. There is nothing wrong with it. Just because there is herd mentality among programmers and they feel the urge to use every single new product out there, does not mean that it is good or it will work. Most programmers think if they incorporate every new piece of code released by a large company, it is making them a smarter programmer; not true at all. Smart programming is mostly about how to do more with less headaches, uncertainties, and in the least amount of time. Remember - Time! That is the most important element, so try to find ways not to waste it on solving problems in bad/bloated code written simply to conform with some strange so called 'patterns'

Relax, enjoy life, take a break from coding and stop using extra features, code, products, 'patterns'. Life is short and the life of your code is even shorter, and it is certainly not rocket science. Remove layers such as LINQ, EF and others, and your code will run efficiently, will scale, and yes, it will still be easy to maintain. Too much abstraction is a bad 'pattern'.

And that is the solution to your problem.

How to play only the audio of a Youtube video using HTML 5?

This may be an old post but people could still be searching for this so here you go:

<div style="position:relative;width:267px;height:25px;overflow:hidden;">
<div style="position:absolute;top:-276px;left:-5px">
<iframe width="300" height="300" 
  src="https://www.youtube.com/embed/youtubeID?rel=0">
</iframe>
</div>
</div>

Multiple dex files define Landroid/support/v4/accessibilityservice/AccessibilityServiceInfoCompat

If you have imported your project from Eclipse.

1. The select project 
2. Go to File -> **Project Structure**
3. Select app in **module** section on left hand panel
4. Select **Dependency** tab
5. Your able to see jars you have added in eclipse project for v4 and v13.
6. Remove that jar by clicking on minus sign at bottom after selection
7. Click on Plus sign select **Library Dependency** 
8. Choose V4 and V13 if added
9. Press Ok and Clean and Rebuild your project

The scenario I have faced after importing Eclipse project to Android studio.

Hope this helps..

How to use target in location.href

If you are using an <a/> to trigger the report, you can try this approach. Instead of attempting to spawn a new window when window.open() fails, make the default scenario to open a new window via target (and prevent it if window.open() succeeds).

HTML

<a href="http://my/url" target="_blank" id="myLink">Link</a>

JS

var spawn = function (e) {
    try {
        window.open(this.href, "","width=1002,height=700,location=0,menubar=0,scrollbars=1,status=1,resizable=0")
        e.preventDefault(); // Or: return false;
    } catch(e) {
    // Allow the default event handler to take place
    }
}

document.getElementById("myLink").onclick = spawn;

Python 3.2 Unable to import urllib2 (ImportError: No module named urllib2)

    import urllib2

Traceback (most recent call last):

File "", line 1, in

    import urllib2

ImportError: No module named 'urllib2' So urllib2 has been been replaced by the package : urllib.request.

Here is the PEP link (Python Enhancement Proposals )

http://www.python.org/dev/peps/pep-3108/#urllib-package

so instead of urllib2 you can now import urllib.request and then use it like this:

    >>>import urllib.request

    >>>urllib.request.urlopen('http://www.placementyogi.com')

Original Link : http://placementyogi.com/articles/python/importerror-no-module-named-urllib2-in-python-3-x

Php header location redirect not working

Try this, Add @ob_start() function in top of the page,

if ((isset($_POST['cancel'])) && ($_POST['cancel'] == 'cancel'))
{
    header('Location: page1.php');
    exit();
}

Why is NULL undeclared?

NULL isn't a native part of the core C++ language, but it is part of the standard library. You need to include one of the standard header files that include its definition. #include <cstddef> or #include <stddef.h> should be sufficient.

The definition of NULL is guaranteed to be available if you include cstddef or stddef.h. It's not guaranteed, but you are very likely to get its definition included if you include many of the other standard headers instead.

Javascript/jQuery detect if input is focused

Did you try:

$(this).is(':focus');

Take a look at Using jQuery to test if an input has focus it features some more examples

How to change text color of simple list item

I realize this question is a bit old but here's a really simple solution that was missing. You don't need to create a custom ListView or even a custom layout.

Just create an anonymous subclass of ArrayAdapter and override getView(). Let super.getView() handle all the heavy lifting. Since simple_list_item_1 is just a text view you can customize it (e.g. set textColor) and then return it.

Here's an example from one of my apps. I'm displaying a list of recent locations and I want all occurrences of "Current Location" to be blue and the rest white.

ListView listView = (ListView) this.findViewById(R.id.listView);
listView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, MobileMuni.getBookmarkStore().getRecentLocations()) {
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        TextView textView = (TextView) super.getView(position, convertView, parent);

        String currentLocation = RouteFinderBookmarksActivity.this.getResources().getString(R.string.Current_Location);
        int textColor = textView.getText().toString().equals(currentLocation) ? R.color.holo_blue : R.color.text_color_btn_holo_dark;
        textView.setTextColor(RouteFinderBookmarksActivity.this.getResources().getColor(textColor));

        return textView;
    }
});

How to obtain the start time and end time of a day?

public static Date beginOfDay(Date date) {
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);

    return cal.getTime();
}

public static Date endOfDay(Date date) {
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    cal.set(Calendar.HOUR_OF_DAY, 23);
    cal.set(Calendar.MINUTE, 59);
    cal.set(Calendar.SECOND, 59);
    cal.set(Calendar.MILLISECOND, 999);

    return cal.getTime();
}

VBA for clear value in specific range of cell and protected cell from being wash away formula

Not sure its faster with VBA - the fastest way to do it in the normal Excel programm would be:

  1. Ctrl-G
  2. A1:X50 Enter
  3. Delete

Unless you have to do this very often, entering and then triggering the VBAcode is more effort.

And in case you only want to delete formulas or values, you can insert Ctrl-G, Alt-S to select Goto Special and here select Formulas or Values.

rails 3.1.0 ActionView::Template::Error (application.css isn't precompiled)

You probably have a syntax error in the css you are using.

Run this command

$ bundle exec rake assets:precompile RAILS_ENV=development --trace

It will give the exception, fixed that and you are all done.

Thanks

Selecting the last value of a column

Similar answer to caligari's answer, but we can tidy it up by just specifying the full column range:

=INDEX(G2:G, COUNT(G2:G))

Python dictionary: Get list of values for list of keys

reduce(lambda x,y: mydict.get(y) and x.append(mydict[y]) or x, mykeys,[])

incase there are keys not in dict.

How to Consolidate Data from Multiple Excel Columns All into One Column

You didn't mention if you are using Excel 2003 or 2007, but you may run into an issue with the # of rows in Excel 2003 being capped at 65,536. If you are using 2007, the limit is 1,048,576.

Also, can I ask what your end goal is for your analysis? If you need to perform many statistical calculations on your data, I would recommend moving out of the Excel environment into something that is more directly suited for data manipulation and analysis, such as R.

There are a variety of options for connecting R to Excel, including

  1. RExcel
  2. RODBC
  3. Other options in the R manual

Regardless of what you choose to use to move data in/out of R, the code to change from wide to long format is pretty trivial. I enjoy the melt() function from the reshape package. That code would look like:

library(reshape)
#Fake data, 4 columns, 20k rows
df <- data.frame(foo = rnorm(20000)
    , bar = rlnorm(20000)
    , fee = rnorm(20000)
    , fie = rlnorm(20000)
)
#Create new object with 1 column, 80k rows
df.m <- melt(df)

From there, you can perform any number of statistical or graphing operations. If you use the RExcel plugin above, you can fire all of this up and run it within Excel itself. The R community is very active and can help address any and all questions you may encounter.

Good luck!

Simulating a click in jQuery/JavaScript on a link

Just

$("#your_item").trigger("click");

using .trigger() you can simulate many type of events, just passing it as the parameter.

How can I run code on a background thread on Android?

IF you need to:

  1. execute code on a background Thread

  2. execute code that DOES NOT touch/update the UI

  3. execute (short) code which will take at most a few seconds to complete

THEN use the following clean and efficient pattern which uses AsyncTask:

AsyncTask.execute(new Runnable() {
   @Override
   public void run() {
      //TODO your background code
   }
});

Handling warning for possible multiple enumeration of IEnumerable

If you only need to check the first element you can peek on it without iterating the whole collection:

public List<object> Foo(IEnumerable<object> objects)
{
    object firstObject;
    if (objects == null || !TryPeek(ref objects, out firstObject))
        throw new ArgumentException();

    var list = DoSomeThing(firstObject);
    var secondList = DoSomeThingElse(objects);
    list.AddRange(secondList);

    return list;
}

public static bool TryPeek<T>(ref IEnumerable<T> source, out T first)
{
    if (source == null)
        throw new ArgumentNullException(nameof(source));

    IEnumerator<T> enumerator = source.GetEnumerator();
    if (!enumerator.MoveNext())
    {
        first = default(T);
        source = Enumerable.Empty<T>();
        return false;
    }

    first = enumerator.Current;
    T firstElement = first;
    source = Iterate();
    return true;

    IEnumerable<T> Iterate()
    {
        yield return firstElement;
        using (enumerator)
        {
            while (enumerator.MoveNext())
            {
                yield return enumerator.Current;
            }
        }
    }
}

"starting Tomcat server 7 at localhost has encountered a prob"

Method 1:

  • type localhost:8080 in your browser to know which process is taking 8080 port
  • uninstall that program

Method 2:

re-install the apache tomcat BUT during installation change the port number. Watch carefully the installation process

Python Git Module experiences?

Here's a really quick implementation of "git status":

import os
import string
from subprocess import *

repoDir = '/Users/foo/project'

def command(x):
    return str(Popen(x.split(' '), stdout=PIPE).communicate()[0])

def rm_empty(L): return [l for l in L if (l and l!="")]

def getUntracked():
    os.chdir(repoDir)
    status = command("git status")
    if "# Untracked files:" in status:
        untf = status.split("# Untracked files:")[1][1:].split("\n")
        return rm_empty([x[2:] for x in untf if string.strip(x) != "#" and x.startswith("#\t")])
    else:
        return []

def getNew():
    os.chdir(repoDir)
    status = command("git status").split("\n")
    return [x[14:] for x in status if x.startswith("#\tnew file:   ")]

def getModified():
    os.chdir(repoDir)
    status = command("git status").split("\n")
    return [x[14:] for x in status if x.startswith("#\tmodified:   ")]

print("Untracked:")
print( getUntracked() )
print("New:")
print( getNew() )
print("Modified:")
print( getModified() )

Which HTML elements can receive focus?

Here I have a CSS-selector based on bobince's answer to select any focusable HTML element:

  a[href]:not([tabindex='-1']),
  area[href]:not([tabindex='-1']),
  input:not([disabled]):not([tabindex='-1']),
  select:not([disabled]):not([tabindex='-1']),
  textarea:not([disabled]):not([tabindex='-1']),
  button:not([disabled]):not([tabindex='-1']),
  iframe:not([tabindex='-1']),
  [tabindex]:not([tabindex='-1']),
  [contentEditable=true]:not([tabindex='-1'])
  {
      /* your CSS for focusable elements goes here */
  }

or a little more beautiful in SASS:

a[href],
area[href],
input:not([disabled]),
select:not([disabled]),
textarea:not([disabled]),
button:not([disabled]),
iframe,
[tabindex],
[contentEditable=true]
{
    &:not([tabindex='-1'])
    {
        /* your SCSS for focusable elements goes here */
    }
}

I've added it as an answer, because that was, what I was looking for, when Google redirected me to this Stackoverflow question.

EDIT: There is one more selector, which is focusable:

[contentEditable=true]

However, this is used very rarely.

getContext is not a function

I got the same error because I had accidentally used <div> instead of <canvas> as the element on which I attempt to call getContext.

Inline <style> tags vs. inline css properties

I agree with the majority view that external stylesheets are the prefered method.

However, here are some practical exceptions:

  • Dynamic background images. CSS stylesheets are static files so you need to use an inline style to add a dynamic (from a database, CMS etc...) background-image style.

  • If an element needs to be hidden when the page loads, using an external stylesheet for this is not practical, since there will always be some delay before the stylesheet is processed and the element will be visible until that happens. style="display: none;" is the best way to achieve this.

  • If an application is going to give the user fine control over a particular CSS value, e.g. text color, then it may be necessary to add this to inline style elements or in-page <style></style> blocks. E.g. style="color:#{{ page.color }}", or <style> p.themed { color: #{{ page.color }}; }</style>

How do I get the fragment identifier (value after hash #) from a URL?

It's very easy. Try the below code

$(document).ready(function(){
  var hashValue = location.hash.replace(/^#/, '');  
  //do something with the value here  
});

Working with INTERVAL and CURDATE in MySQL

I usually use

DATE_ADD(CURDATE(), INTERVAL - 1 MONTH)

Which is almost same as Pekka's but this way you can control your INTERVAL to be negative or positive...

jquery animate .css

Just use .animate() instead of .css() (with a duration if you want), like this:

$('#hfont1').hover(function() {
    $(this).animate({"color":"#efbe5c","font-size":"52pt"}, 1000);
}, function() {
    $(this).animate({"color":"#e8a010","font-size":"48pt"}, 1000);
});

You can test it here. Note though, you need either the jQuery color plugin, or jQuery UI included to animate the color. In the above, the duration is 1000ms, you can change it, or just leave it off for the default 400ms duration.

What does "use strict" do in JavaScript, and what is the reasoning behind it?

JavaScript “strict” mode was introduced in ECMAScript 5.

(function() {
  "use strict";
  your code...
})();

Writing "use strict"; at the very top of your JS file turns on strict syntax checking. It does the following tasks for us:

  1. shows an error if you try to assign to an undeclared variable

  2. stops you from overwriting key JS system libraries

  3. forbids some unsafe or error-prone language features

use strict also works inside of individual functions. It is always a better practice to include use strict in your code.

Browser compatibility issue: The "use" directives are meant to be backwards-compatible. Browsers that do not support them will just see a string literal that isn't referenced further. So, they will pass over it and move on.

Change fill color on vector asset in Android Studio

if you look to support old version pre lolipop

use the same xml code with some changes

instead of normal ImageView --> AppCompatImageView

instead of android:src --> app:srcCompat

here is example

<android.support.v7.widget.AppCompatImageView
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:id="@+id/button"
        app:srcCompat="@drawable/ic_more_vert_24dp"
        android:tint="@color/primary" />

dont forget update your gradle as @ Sayooj Valsan mention

// Gradle Plugin 2.0+  
 android {  
   defaultConfig {  
     vectorDrawables.useSupportLibrary = true  
   }  
 }  

 compile 'com.android.support:design:23.4.0'

Notice To any one use vector dont ever ever never give your vector reference to color like this one android:fillColor="@color/primary" give its hex value .

Move branch pointer to different commit without checkout

git branch -f <branch-name> [<new-tip-commit>]

If new-tip-commit is omitted it defaults to the current commit.

How to convert a Binary String to a base 10 integer in Java

For me I got NumberFormatException when trying to deal with the negative numbers. I used the following for the negative and positive numbers.

System.out.println(Integer.parseUnsignedInt("11111111111111111111111111110111", 2));      

Output : -9

How to trim a string after a specific character in java

You can use:

result = result.split("\n")[0];

How to read the output from git diff?

@@ -1,2 +3,4 @@ part of the diff

This part took me a while to understand, so I've created a minimal example.

The format is basically the same the diff -u unified diff.

For instance:

diff -u <(seq 16) <(seq 16 | grep -Ev '^(2|3|14|15)$')

Here we removed lines 2, 3, 14 and 15. Output:

@@ -1,6 +1,4 @@
 1
-2
-3
 4
 5
 6
@@ -11,6 +9,4 @@
 11
 12
 13
-14
-15
 16

@@ -1,6 +1,4 @@ means:

  • -1,6 means that this piece of the first file starts at line 1 and shows a total of 6 lines. Therefore it shows lines 1 to 6.

    1
    2
    3
    4
    5
    6
    

    - means "old", as we usually invoke it as diff -u old new.

  • +1,4 means that this piece of the second file starts at line 1 and shows a total of 4 lines. Therefore it shows lines 1 to 4.

    + means "new".

    We only have 4 lines instead of 6 because 2 lines were removed! The new hunk is just:

    1
    4
    5
    6
    

@@ -11,6 +9,4 @@ for the second hunk is analogous:

  • on the old file, we have 6 lines, starting at line 11 of the old file:

    11
    12
    13
    14
    15
    16
    
  • on the new file, we have 4 lines, starting at line 9 of the new file:

    11
    12
    13
    16
    

    Note that line 11 is the 9th line of the new file because we have already removed 2 lines on the previous hunk: 2 and 3.

Hunk header

Depending on your git version and configuration, you can also get a code line next to the @@ line, e.g. the func1() { in:

@@ -4,7 +4,6 @@ func1() {

This can also be obtained with the -p flag of plain diff.

Example: old file:

func1() {
    1;
    2;
    3;
    4;
    5;
    6;
    7;
    8;
    9;
}

If we remove line 6, the diff shows:

@@ -4,7 +4,6 @@ func1() {
     3;
     4;
     5;
-    6;
     7;
     8;
     9;

Note that this is not the correct line for func1: it skipped lines 1 and 2.

This awesome feature often tells exactly to which function or class each hunk belongs, which is very useful to interpret the diff.

How the algorithm to choose the header works exactly is discussed at: Where does the excerpt in the git diff hunk header come from?

python .replace() regex

No. Regular expressions in Python are handled by the re module.

article = re.sub(r'(?is)</html>.+', '</html>', article)

In general:

text_after = re.sub(regex_search_term, regex_replacement, text_before)

How to create an Excel File with Nodejs?

Using fs package we can create excel/CSV file from JSON data.

Step 1: Store JSON data in a variable (here it is in jsn variable).

Step 2: Create empty string variable(here it is data).

Step 3: Append every property of jsn to string variable data, while appending put '\t' in-between 2 cells and '\n' after completing the row.

Code:

var fs = require('fs');

var jsn = [{
    "name": "Nilesh",
    "school": "RDTC",
    "marks": "77"
   },{
    "name": "Sagar",
    "school": "RC",
    "marks": "99.99"
   },{
    "name": "Prashant",
    "school": "Solapur",
    "marks": "100"
 }];

var data='';
for (var i = 0; i < jsn.length; i++) {
    data=data+jsn[i].name+'\t'+jsn[i].school+'\t'+jsn[i].marks+'\n';
 }
fs.appendFile('Filename.xls', data, (err) => {
    if (err) throw err;
    console.log('File created');
 });

Output

Can't compare naive and aware datetime.now() <= challenge.datetime_end

So the way I would solve this problem is to make sure the two datetimes are in the right timezone.

I can see that you are using datetime.now() which will return the systems current time, with no tzinfo set.

tzinfo is the information attached to a datetime to let it know what timezone it is in. If you are using naive datetime you need to be consistent through out your system. I would highly recommend only using datetime.utcnow()

seeing as somewhere your are creating datetime that have tzinfo associated with them, what you need to do is make sure those are localized (has tzinfo associated) to the correct timezone.

Take a look at Delorean, it makes dealing with this sort of thing much easier.

Gerrit error when Change-Id in commit messages are missing

You might be an admin doing a one-off push directly into refs/changes/<change_number>.

For example, once a commit without Change-Id landed into Subversion, you pull it out of Subversion using git-svn, and you'd like to archive it as a Gerrit patchset into a Gerrit change.

If so, you can go to project settings page (http://[installation-path]/#/admin/projects/[project-id]) and temporarily change "Require Change-Id in commit message" value to False.

Don't forget to afterwards change it back to Inherit or True!

Restoring Nuget References?

I have to agree with @Juri that the vastly popular answer by jmfenoll is not complete. In the case of broken references, I submit that most of the time you do not want to update to the latest package, but only fix your references to the current versions that you happen to be using. And Juri provided a handy function Sync-References to do just that.

But we can go just a bit further, allowing the flexibility to filter by project as well as package:

function Sync-References([string]$PackageId, [string]$ProjectName) {
    get-project -all | 
    Where-Object { $_.name -match $ProjectName } |
    ForEach-Object {
        $proj = $_ ;
        Write-Output ('Project: ' + $proj.name)
        Get-Package -project $proj.name |
        Where-Object { $_.id -match $PackageId } |
        ForEach-Object { 
            Write-Output ('Package: ' + $_.id)
            uninstall-package -projectname $proj.name -id $_.id -version $_.version -RemoveDependencies -force
            install-package -projectname $proj.name -id $_.id -version $_.version
        }
    }
}

Multiplication on command line terminal

If you like python and have an option to install a package, you can use this utility that I made.

# install pythonp
python -m pip install pythonp

pythonp "5*5"
25

pythonp "1 / (1+math.exp(0.5))"
0.3775406687981454

# define a custom function and pass it to another higher-order function
pythonp "n=10;functools.reduce(lambda x,y:x*y, range(1,n+1))"     
3628800

How to call a VbScript from a Batch File without opening an additional command prompt

If you want to fix vbs associations type

regsvr32 vbscript.dll
regsvr32 jscript.dll
regsvr32 wshext.dll
regsvr32 wshom.ocx
regsvr32 wshcon.dll
regsvr32 scrrun.dll

Also if you can't use vbs due to management then convert your script to a vb.net program which is designed to be easy, is easy, and takes 5 minutes.

Big difference is functions and subs are both called using brackets rather than just functions.

So the compilers are installed on all computers with .NET installed.

See this article here on how to make a .NET exe. Note the sample is for a scripting host. You can't use this, you have to put your vbs code in as .NET code.

How can I convert a VBScript to an executable (EXE) file?

Moving from JDK 1.7 to JDK 1.8 on Ubuntu

Add the repository and update apt-get:

sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update

Install Java8 and set it as default:

sudo apt-get install oracle-java8-set-default

Check version:

java -version

Initial bytes incorrect after Java AES/CBC decryption

In this answer I choose to approach the "Simple Java AES encrypt/decrypt example" main theme and not the specific debugging question because I think this will profit most readers.

This is a simple summary of my blog post about AES encryption in Java so I recommend reading through it before implementing anything. I will however still provide a simple example to use and give some pointers what to watch out for.

In this example I will choose to use authenticated encryption with Galois/Counter Mode or GCM mode. The reason is that in most case you want integrity and authenticity in combination with confidentiality (read more in the blog).

AES-GCM Encryption/Decryption Tutorial

Here are the steps required to encrypt/decrypt with AES-GCM with the Java Cryptography Architecture (JCA). Do not mix with other examples, as subtle differences may make your code utterly insecure.

1. Create Key

As it depends on your use-case, I will assume the simplest case: a random secret key.

SecureRandom secureRandom = new SecureRandom();
byte[] key = new byte[16];
secureRandom.nextBytes(key);
SecretKey secretKey = SecretKeySpec(key, "AES");

Important:

2. Create the Initialization Vector

An initialization vector (IV) is used so that the same secret key will create different cipher texts.

byte[] iv = new byte[12]; //NEVER REUSE THIS IV WITH SAME KEY
secureRandom.nextBytes(iv);

Important:

3. Encrypt with IV and Key

final Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
GCMParameterSpec parameterSpec = new GCMParameterSpec(128, iv); //128 bit auth tag length
cipher.init(Cipher.ENCRYPT_MODE, secretKey, parameterSpec);
byte[] cipherText = cipher.doFinal(plainText);

Important:

  • use 16 byte / 128 bit authentication tag (used to verify integrity/authenticity)
  • the authentication tag will be automatically appended to the cipher text (in the JCA implementation)
  • since GCM behaves like a stream cipher, no padding is required
  • use CipherInputStream when encrypting large chunks of data
  • want additional (non-secret) data checked if it was changed? You may want to use associated data with cipher.updateAAD(associatedData); More here.

3. Serialize to Single Message

Just append IV and ciphertext. As stated above, the IV doesn't need to be secret.

ByteBuffer byteBuffer = ByteBuffer.allocate(iv.length + cipherText.length);
byteBuffer.put(iv);
byteBuffer.put(cipherText);
byte[] cipherMessage = byteBuffer.array();

Optionally encode with Base64 if you need a string representation. Either use Android's or Java 8's built-in implementation (do not use Apache Commons Codec - it's an awful implementation). Encoding is used to "convert" byte arrays to string representation to make it ASCII safe e.g.:

String base64CipherMessage = Base64.getEncoder().encodeToString(cipherMessage);

4. Prepare Decryption: Deserialize

If you have encoded the message, first decode it to byte array:

byte[] cipherMessage = Base64.getDecoder().decode(base64CipherMessage)

Important:

5. Decrypt

Initialize the cipher and set the same parameters as with the encryption:

final Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
//use first 12 bytes for iv
AlgorithmParameterSpec gcmIv = new GCMParameterSpec(128, cipherMessage, 0, 12);
cipher.init(Cipher.DECRYPT_MODE, secretKey, gcmIv);
//use everything from 12 bytes on as ciphertext
byte[] plainText = cipher.doFinal(cipherMessage, 12, cipherMessage.length - 12);

Important:

  • don't forget to add associated data with cipher.updateAAD(associatedData); if you added it during encryption.

A working code snippet can be found in this gist.


Note that most recent Android (SDK 21+) and Java (7+) implementations should have AES-GCM. Older versions may lack it. I still choose this mode, since it is easier to implement in addition to being more efficient compared to similar mode of Encrypt-then-Mac (with e.g. AES-CBC + HMAC). See this article on how to implement AES-CBC with HMAC.

Getting data from selected datagridview row and which event?

Simple solution would be as below. This is improvement of solution from vale.

private void dgMapTable_SelectionChanged(object sender, EventArgs e) 
{
    int active_map=0;
    if(dgMapTable.SelectedRows.Count>0)
        active_map = dgMapTable.SelectedRows[0].Index;
    // User code if required Process_ROW(active_map);
}

Note for other reader, for above code to work FullRowSelect selection mode for datagridview should be used. You may extend this to give message if more than two rows selected.

Can I write native iPhone apps using Python?

The only significant "external" language for iPhone development that I'm aware of with semi-significant support in terms of frameworks and compatibility is MonoTouch, a C#/.NET environment for developing on the iPhone.

In a javascript array, how do I get the last 5 elements, excluding the first element?

You can call:

arr.slice(Math.max(arr.length - 5, 1))

If you don't want to exclude the first element, use

arr.slice(Math.max(arr.length - 5, 0))

How to install pip3 on Windows?

On Windows pip3 should be in the Scripts path of your Python installation:

C:\path\to\python\Scripts\pip3

Use:

where python

to find out where your Python executable(s) is/are located. The result should look like this:

C:\path\to\python\python.exe

or:

C:\path\to\python\python3.exe

You can check if pip3 works with this absolute path:

C:\path\to\python\Scripts\pip3

if yes, add C:\path\to\python\Scripts to your environmental variable PATH .

Java verify void method calls n times with Mockito

The necessary method is Mockito#verify:

public static <T> T verify(T mock,
                           VerificationMode mode)

mock is your mocked object and mode is the VerificationMode that describes how the mock should be verified. Possible modes are:

verify(mock, times(5)).someMethod("was called five times");
verify(mock, never()).someMethod("was never called");
verify(mock, atLeastOnce()).someMethod("was called at least once");
verify(mock, atLeast(2)).someMethod("was called at least twice");
verify(mock, atMost(3)).someMethod("was called at most 3 times");
verify(mock, atLeast(0)).someMethod("was called any number of times"); // useful with captors
verify(mock, only()).someMethod("no other method has been called on the mock");

You'll need these static imports from the Mockito class in order to use the verify method and these verification modes:

import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.atMost;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.only;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

So in your case the correct syntax will be:

Mockito.verify(mock, times(4)).send()

This verifies that the method send was called 4 times on the mocked object. It will fail if it was called less or more than 4 times.


If you just want to check, if the method has been called once, then you don't need to pass a VerificationMode. A simple

verify(mock).someMethod("was called once");

would be enough. It internally uses verify(mock, times(1)).someMethod("was called once");.


It is possible to have multiple verification calls on the same mock to achieve a "between" verification. Mockito doesn't support something like this verify(mock, between(4,6)).someMethod("was called between 4 and 6 times");, but we can write

verify(mock, atLeast(4)).someMethod("was called at least four times ...");
verify(mock, atMost(6)).someMethod("... and not more than six times");

instead, to get the same behaviour. The bounds are included, so the test case is green when the method was called 4, 5 or 6 times.

How can I remove a specific item from an array?

A friend was having issues in Internet Explorer 8 and showed me what he did. I told him it was wrong, and he told me he got the answer here. The current top answer will not work in all browsers (Internet Explorer 8 for example), and it will only remove the first occurrence of the item.

Remove ALL instances from an array

function array_remove_index_by_value(arr, item)
{
 for (var i = arr.length; i--;)
 {
  if (arr[i] === item) {arr.splice(i, 1);}
 }
}

It loops through the array backwards (since indices and length will change as items are removed) and removes the item if it's found. It works in all browsers.

Get decimal portion of a number with JavaScript

A good option is to transform the number into a string and then split it.

// Decimal number
let number = 3.2;

// Convert it into a string
let string = number.toString();

// Split the dot
let array = string.split('.');

// Get both numbers
// The '+' sign transforms the string into a number again
let firstNumber  = +array[0]; // 3
let secondNumber = +array[1]; // 2

In one line of code

let [firstNumber, secondNumber] = [+number.toString().split('.')[0], +number.toString().split('.')[1]];

How in node to split string by newline ('\n')?

Try splitting on a regex like /\r?\n/ to be usable by both Windows and UNIX systems.

> "a\nb\r\nc".split(/\r?\n/)
[ 'a', 'b', 'c' ]

In Node.js, how do I "include" functions from my other files?

Like you are having a file abc.txt and many more?

Create 2 files: fileread.js and fetchingfile.js, then in fileread.js write this code:

function fileread(filename) {
    var contents= fs.readFileSync(filename);
        return contents;
    }

    var fs = require("fs");  // file system

    //var data = fileread("abc.txt");
    module.exports.fileread = fileread;
    //data.say();
    //console.log(data.toString());
}

In fetchingfile.js write this code:

function myerror(){
    console.log("Hey need some help");
    console.log("type file=abc.txt");
}

var ags = require("minimist")(process.argv.slice(2), { string: "file" });
if(ags.help || !ags.file) {
    myerror();
    process.exit(1);
}
var hello = require("./fileread.js");
var data = hello.fileread(ags.file);  // importing module here 
console.log(data.toString());

Now, in a terminal: $ node fetchingfile.js --file=abc.txt

You are passing the file name as an argument, moreover include all files in readfile.js instead of passing it.

Thanks

How to Check if value exists in a MySQL database

For Exact Match

"SELECT * FROM yourTable WHERE city = 'c7'"

For Pattern / Wildcard Search

"SELECT * FROM yourTable WHERE city LIKE '%c7%'"

Of course you can change '%c7%' to '%c7' or 'c7%' depending on how you want to search it. For exact match, use first query example.

PHP

$result = mysql_query("SELECT * FROM yourTable WHERE city = 'c7'");
$matchFound = mysql_num_rows($result) > 0 ? 'yes' : 'no';
echo $matchFound;

You can also use if condition there.

How to make code wait while calling asynchronous calls like Ajax

Why didn't it work for you using Deferred Objects? Unless I misunderstood something this may work for you.

/* AJAX success handler */
var echo = function() {
    console.log('Pass1');
};

var pass = function() {
  $.when(
    /* AJAX requests */
    $.post("/echo/json/", { delay: 1 }, echo),
    $.post("/echo/json/", { delay: 2 }, echo),
    $.post("/echo/json/", { delay: 3 }, echo)
  ).then(function() {
    /* Run after all AJAX */
    console.log('Pass2');
  });
};?

See it here.


UPDATE

Based on your input it seems what your quickest alternative is to use synchronous requests. You can set the property async to false in your $.ajax requests to make them blocking. This will hang your browser until the request is finished though.

Notice I don't recommend this and I still consider you should fix your code in an event-based workflow to not depend on it.

Adding space/padding to a UILabel

Full and correct solution which works in all cases, including stack views, dynamic cells, dynamic number of lines, collection views, animated padding, every character count, and every other situation.

Padding a UILabel, full solution. Updated for 2021.

It turns out there are three things that must be done.

1. Must call textRect#forBounds with the new smaller size

2. Must override drawText with the new smaller size

3. If a dynamically sized cell, must adjust intrinsicContentSize

In the typical example below, the text unit is in a table view, stack view or similar construction, which gives it a fixed width. In the example we want padding of 60,20,20,24.

Thus, we take the "existing" intrinsicContentSize and actually add 80 to the height.

To repeat ...

You have to literally "get" the height calculated "so far" by the engine, and change that value.

I find that process confusing, but, that is how it works. For me, Apple should expose a call named something like "preliminary height calculation".

Secondly we have to actually use the textRect#forBounds call with our new smaller size.

So in textRect#forBounds we first make the size smaller and then call super.

Alert! You must call super after, not before!

If you carefully investigate all the attempts and discussion on this page, that is the exact problem.

Notice some solutions "seem to usually work". This is indeed the exact reason - confusingly you must "call super afterwards", not before.

If you call super "in the wrong order", it usually works, but fails for certain specific text lengths.

Here is an exact visual example of "incorrectly doing super first":

enter image description here

Notice the 60,20,20,24 margins are correct BUT the size calculation is actually wrong, because it was done with the "super first" pattern in textRect#forBounds.

Fixed:

Only now does the textRect#forBounds engine know how to do the calculation properly:

enter image description here

Finally!

Again, in this example the UILabel is being used in the typical situation where width is fixed. So in intrinsicContentSize we have to "add" the overall extra height we want. (You don't need to "add" in any way to the width, that would be meaningless as it is fixed.)

Then in textRect#forBounds you get the bounds "suggested so far" by autolayout, you subtract your margins, and only then call again to the textRect#forBounds engine, that is to say in super, which will give you a result.

Finally and simply in drawText you of course draw in that same smaller box.

Phew!

let UIEI = UIEdgeInsets(top: 60, left: 20, bottom: 20, right: 24) // as desired

override var intrinsicContentSize:CGSize {
    numberOfLines = 0       // don't forget!
    var s = super.intrinsicContentSize
    s.height = s.height + UIEI.top + UIEI.bottom
    s.width = s.width + UIEI.left + UIEI.right
    return s
}

override func drawText(in rect:CGRect) {
    let r = rect.inset(by: UIEI)
    super.drawText(in: r)
}

override func textRect(forBounds bounds:CGRect,
                           limitedToNumberOfLines n:Int) -> CGRect {
    let b = bounds
    let tr = b.inset(by: UIEI)
    let ctr = super.textRect(forBounds: tr, limitedToNumberOfLines: 0)
    // that line of code MUST be LAST in this function, NOT first
    return ctr
}

Once again. Note that the answers on this and other QA that are "almost" correct suffer the problem in the first image above - the "super is in the wrong place". You must force the size bigger in intrinsicContentSize and then in textRect#forBounds you must first shrink the first-suggestion bounds and then call super.

Summary: you must "call super last" in textRect#forBounds

That's the secret.

Note that you do not need to and should not need to additionally call invalidate, sizeThatFits, needsLayout or any other forcing call. A correct solution should work properly in the normal autolayout draw cycle.

Table is marked as crashed and should be repaired

When I got this error:

#145 - Table '.\engine\phpbb3_posts' is marked as crashed and should be repaired

I ran this command in PhpMyAdmin to fix it:

REPAIR TABLE phpbb3_posts;

Inserting multiple rows in a single SQL query?

If you are inserting into a single table, you can write your query like this (maybe only in MySQL):

INSERT INTO table1 (First, Last)
VALUES
    ('Fred', 'Smith'),
    ('John', 'Smith'),
    ('Michael', 'Smith'),
    ('Robert', 'Smith');