Programs & Examples On #Treegrid

A graphical user interface element that presents data in tree view.

Django values_list vs values

You can get the different values with:

set(Article.objects.values_list('comment_id', flat=True))

Generating matplotlib graphs without a running X server

@Neil's answer is one (perfectly valid!) way of doing it, but you can also simply call matplotlib.use('Agg') before importing matplotlib.pyplot, and then continue as normal.

E.g.

import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(range(10))
fig.savefig('temp.png')

You don't have to use the Agg backend, as well. The pdf, ps, svg, agg, cairo, and gdk backends can all be used without an X-server. However, only the Agg backend will be built by default (I think?), so there's a good chance that the other backends may not be enabled on your particular install.

Alternately, you can just set the backend parameter in your .matplotlibrc file to automatically have matplotlib.pyplot use the given renderer.

Style the first <td> column of a table differently

The :nth-child() and :nth-of-type() pseudo-classes allows you to select elements with a formula.

The syntax is :nth-child(an+b), where you replace a and b by numbers of your choice.

For instance, :nth-child(3n+1) selects the 1st, 4th, 7th etc. child.

td:nth-child(3n+1) {  
  /* your stuff here */
}

:nth-of-type() works the same, except that it only considers element of the given type ( in the example).

Sort ArrayList of custom Objects by property

Since Date implements Comparable, it has a compareTo method just like String does.

So your custom Comparator could look like this:

public class CustomComparator implements Comparator<MyObject> {
    @Override
    public int compare(MyObject o1, MyObject o2) {
        return o1.getStartDate().compareTo(o2.getStartDate());
    }
}

The compare() method must return an int, so you couldn't directly return a boolean like you were planning to anyway.

Your sorting code would be just about like you wrote:

Collections.sort(Database.arrayList, new CustomComparator());

A slightly shorter way to write all this, if you don't need to reuse your comparator, is to write it as an inline anonymous class:

Collections.sort(Database.arrayList, new Comparator<MyObject>() {
    @Override
    public int compare(MyObject o1, MyObject o2) {
        return o1.getStartDate().compareTo(o2.getStartDate());
    }
});

Since

You can now write the last example in a shorter form by using a lambda expression for the Comparator:

Collections.sort(Database.arrayList, 
                        (o1, o2) -> o1.getStartDate().compareTo(o2.getStartDate()));

And List has a sort(Comparator) method, so you can shorten this even further:

Database.arrayList.sort((o1, o2) -> o1.getStartDate().compareTo(o2.getStartDate()));

This is such a common idiom that there's a built-in method to generate a Comparator for a class with a Comparable key:

Database.arrayList.sort(Comparator.comparing(MyObject::getStartDate));

All of these are equivalent forms.

How to add percent sign to NSString

The accepted answer doesn't work for UILocalNotification. For some reason, %%%% (4 percent signs) or the unicode character '\uFF05' only work for this.

So to recap, when formatting your string you may use %%. However, if your string is part of a UILocalNotification, use %%%% or \uFF05.

How do I load an HTTP URL with App Transport Security enabled in iOS 9?

Compiling answers given by @adurdin and @User

Add followings to your info.plist & change localhost.com with your corresponding domain name, you can add multiple domains as well:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
    <key>NSExceptionDomains</key>
    <dict>
        <key>localhost.com</key>
        <dict>
            <key>NSIncludesSubdomains</key>
            <false/>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <false/>
            <key>NSExceptionRequiresForwardSecrecy</key>
            <true/>
            <key>NSExceptionMinimumTLSVersion</key>
            <string>TLSv1.2</string>
            <key>NSThirdPartyExceptionAllowsInsecureHTTPLoads</key>
            <false/>
            <key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
            <true/>
            <key>NSThirdPartyExceptionMinimumTLSVersion</key>
            <string>TLSv1.2</string>
            <key>NSRequiresCertificateTransparency</key>
            <false/>
        </dict>
    </dict>
</dict>
</plist>

You info.plist must looks like this:

enter image description here

Abstract methods in Java

The error message tells the exact reason: "abstract methods cannot have a body".

They can only be defined in abstract classes and interfaces (interface methods are implicitly abstract!) and the idea is, that the subclass implements the method.

Example:

 public abstract class AbstractGreeter {
   public abstract String getHelloMessage();

   public void sayHello() {
     System.out.println(getHelloMessage());
   }
 }

 public class FrenchGreeter extends AbstractGreeter{

   // we must implement the abstract method
   @Override
   public String getHelloMessage() {
     return "bonjour";
   }
 }

What size should TabBar images be?

According to the latest Apple Human Interface Guidelines:

In portrait orientation, tab bar icons appear above tab titles. In landscape orientation, the icons and titles appear side-by-side. Depending on the device and orientation, the system displays either a regular or compact tab bar. Your app should include custom tab bar icons for both sizes.

enter image description here

enter image description here

I suggest you to use the above link to understand the full concept. Because apple update it's document in regular interval

Command-line Tool to find Java Heap Size and Memory Used (Linux)?

If using jrockit try the jrcmd command line tool. For example:

$ jrcmd 5127 print_memusage
5127:
Total mapped                  1074596KB           (reserved=3728KB)
-              Java heap       786432KB           (reserved=0KB)
-              GC tables        26316KB          
-          Thread stacks        13452KB           (#threads=34)
-          Compiled code         9856KB           (used=9761KB)
-               Internal          840KB          
-                     OS        15036KB          
-                  Other       146632KB          
-        Java class data        75008KB           (malloced=74861KB #103221 in 18709 classes)
- Native memory tracking         1024KB           (malloced=102KB #8)

For more commands, like heap_diagnostics, use "jrcmd help" to list them.

https://blogs.oracle.com/jrockit/entry/why_is_my_jvm_process_larger_t

How to lock specific cells but allow filtering and sorting

This is a very old, but still very useful thread. I came here recently with the same issue. I suggest protecting the sheet when appropriate and unprotecting it when the filter row (eg Row 1) is selected. My solution doesn't use password protection - I don't need it (its a safeguard, not a security feature). I can't find an event handler that recognizes selection of a filter button - so I gave the instruction to my users to first select the filter cell then click the filter button. Here's what I advocate, (I only change protection if it needs to be changed, that may or may not save time - I don't know, but it "feels" right):

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
  Const FilterRow = 1
  Dim c As Range
  Dim NotFilterRow As Boolean
  Dim oldstate As Boolean
  Dim ws As Worksheet
  Set ws = ActiveSheet
  oldstate = ws.ProtectContents
  NotFilterRow = False
  For Each c In Target.Cells
     NotFilterRow = c.Row <> FilterRow
     If NotFilterRow Then Exit For
  Next c
  If NotFilterRow <> oldstate Then
     If NotFilterRow Then
        ws.Protect
     Else
        ws.Unprotect
     End If
  End If
  Set ws = Nothing
End Sub

An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode

The 2nd option is the one you want.

In your web.config, make sure these keys exist:

<configuration>
    <system.webServer>
        <validation validateIntegratedModeConfiguration="false"/>
    </system.webServer>
</configuration>

How to set a timer in android

Probably Timerconcept

new CountDownTimer(40000, 1000) { //40000 milli seconds is total time, 1000 milli seconds is time interval

 public void onTick(long millisUntilFinished) {
  }
  public void onFinish() {
 }
}.start();

or

Method 2 ::

Program the timer

Add a new variable of int named time. Set it to 0. Add the following code to onCreate function in MainActivity.java.

//Declare the timer
Timer t = new Timer();
//Set the schedule function and rate
t.scheduleAtFixedRate(new TimerTask() {

    @Override
    public void run() {
        //Called each time when 1000 milliseconds (1 second) (the period parameter)
    }

},
//Set how long before to start calling the TimerTask (in milliseconds)
0,
//Set the amount of time between each execution (in milliseconds)
1000);

Go into the run method and add the following code.

//We must use this function in order to change the text view text
runOnUiThread(new Runnable() {

    @Override
    public void run() {
        TextView tv = (TextView) findViewById(R.id.main_timer_text);
        tv.setText(String.valueOf(time));
        time += 1;
    }

});

Loop inside React JSX

Here is a sample from React doc:JavaScript Expressions as Children

function Item(props) {
  return <li>{props.message}</li>;
}

function TodoList() {
  const todos = ['finish doc', 'submit pr', 'nag dan to review'];
  return (
    <ul>
      {todos.map((message) => <Item key={message} message={message} />)}
    </ul>
  );
}

as your case, I suggest writing like this:

function render() {
  return (
    <tbody>
      {numrows.map((roe, index) => <ObjectRow key={index} />)}
    </tbody>
  );
}

Please notice the Key is very important, because React use Key to differ data in array.

React js change child component's state from parent component

You can use the createRef to change the state of the child component from the parent component. Here are all the steps.

  1. Create a method to change the state in the child component.

    2 - Create a reference for the child component in parent component using React.createRef().

    3 - Attach reference with the child component using ref={}.

    4 - Call the child component method using this.yor-reference.current.method.

Parent component


class ParentComponent extends Component {
constructor()
{
this.changeChild=React.createRef()
}
  render() {
    return (
      <div>
        <button onClick={this.changeChild.current.toggleMenu()}>
          Toggle Menu from Parent
        </button>
        <ChildComponent ref={this.changeChild} />
      </div>
    );
  }
}

Child Component


class ChildComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      open: false;
    }
  }

  toggleMenu=() => {
    this.setState({
      open: !this.state.open
    });
  }

  render() {
    return (
      <Drawer open={this.state.open}/>
    );
  }
}



Warning: Null value is eliminated by an aggregate or other SET operation in Aqua Data Studio

You want to put the ISNULL inside of the COUNT function, not outside:

Not GOOD: ISNULL(COUNT(field), 0)

GOOD: COUNT(ISNULL(field, 0))

How to write/update data into cells of existing XLSX workbook using xlsxwriter in python

Quote from xlsxwriter module documentation:

This module cannot be used to modify or write to an existing Excel XLSX file.

If you want to modify existing xlsx workbook, consider using openpyxl module.

See also:

Definition of "downstream" and "upstream"

Upstream (as related to) Tracking

The term upstream also has some unambiguous meaning as comes to the suite of GIT tools, especially relative to tracking

For example :

   $git rev-list --count --left-right "@{upstream}"...HEAD
   >4   12

will print (the last cached value of) the number of commits behind (left) and ahead (right) of your current working branch, relative to the (if any) currently tracking remote branch for this local branch. It will print an error message otherwise:

    >error: No upstream branch found for ''
  • As has already been said, you may have any number of remotes for one local repository, for example, if you fork a repository from github, then issue a 'pull request', you most certainly have at least two: origin (your forked repo on github) and upstream (the repo on github you forked from). Those are just interchangeable names, only the 'git@...' url identifies them.

Your .git/configreads :

   [remote "origin"]
       fetch = +refs/heads/*:refs/remotes/origin/*
       url = [email protected]:myusername/reponame.git
   [remote "upstream"]
       fetch = +refs/heads/*:refs/remotes/upstream/*
       url = [email protected]:authorname/reponame.git
  • On the other hand, @{upstream}'s meaning for GIT is unique :

it is 'the branch' (if any) on 'said remote', which is tracking the 'current branch' on your 'local repository'.

It's the branch you fetch/pull from whenever you issue a plain git fetch/git pull, without arguments.

Let's say want to set the remote branch origin/master to be the tracking branch for the local master branch you've checked out. Just issue :

   $ git branch --set-upstream  master origin/master
   > Branch master set up to track remote branch master from origin.

This adds 2 parameters in .git/config :

   [branch "master"]
       remote = origin
       merge = refs/heads/master

now try (provided 'upstream' remote has a 'dev' branch)

   $ git branch --set-upstream  master upstream/dev
   > Branch master set up to track remote branch dev from upstream.

.git/config now reads:

   [branch "master"]
       remote = upstream
       merge = refs/heads/dev

git-push(1) Manual Page :

   -u
   --set-upstream

For every branch that is up to date or successfully pushed, add upstream (tracking) reference, used by argument-less git-pull(1) and other commands. For more information, see branch.<name>.merge in git-config(1).

git-config(1) Manual Page :

   branch.<name>.merge

Defines, together with branch.<name>.remote, the upstream branch for the given branch. It tells git fetch/git pull/git rebase which branch to merge and can also affect git push (see push.default). \ (...)

   branch.<name>.remote

When in branch < name >, it tells git fetch and git push which remote to fetch from/push to. It defaults to origin if no remote is configured. origin is also used if you are not on any branch.

Upstream and Push (Gotcha)

take a look at git-config(1) Manual Page

   git config --global push.default upstream
   git config --global push.default tracking  (deprecated)

This is to prevent accidental pushes to branches which you’re not ready to push yet.

JQuery wait for page to finish loading before starting the slideshow?

did you try this ?

$("#yourdiv").load(url, function(){ 

         your functions goes here !!!

}); 

How to get object size in memory?

Unmanaged object:

  • Marshal.SizeOf(object yourObj);

Value Types:

  • sizeof(object val)

Managed object:

How to vertically align a html radio button to it's label?

there are several way, one i would prefer is using a table in html. you can add two coloum three rows table and place the radio buttons and lable.

<table border="0">

<tr>
  <td><input type="radio" name="sex" value="1"></td>
  <td>radio1</td>

</tr>
<tr>
  <td><input type="radio" name="sex" value="2"></td>
  <td>radio2</td>

</tr>
</table>

Read file from line 2 or skip header row

f = open(fname).readlines()
firstLine = f.pop(0) #removes the first line
for line in f:
    ...

Difference between using Makefile and CMake to compile the code

Make (or rather a Makefile) is a buildsystem - it drives the compiler and other build tools to build your code.

CMake is a generator of buildsystems. It can produce Makefiles, it can produce Ninja build files, it can produce KDEvelop or Xcode projects, it can produce Visual Studio solutions. From the same starting point, the same CMakeLists.txt file. So if you have a platform-independent project, CMake is a way to make it buildsystem-independent as well.

If you have Windows developers used to Visual Studio and Unix developers who swear by GNU Make, CMake is (one of) the way(s) to go.

I would always recommend using CMake (or another buildsystem generator, but CMake is my personal preference) if you intend your project to be multi-platform or widely usable. CMake itself also provides some nice features like dependency detection, library interface management, or integration with CTest, CDash and CPack.

Using a buildsystem generator makes your project more future-proof. Even if you're GNU-Make-only now, what if you later decide to expand to other platforms (be it Windows or something embedded), or just want to use an IDE?

List of strings to one string

If you use .net 4.0 you can use a sorter way:

String.Join<string>(String.Empty, los);

How to change the color of text in javafx TextField?

If you are designing your Javafx application using SceneBuilder then use -fx-text-fill(if not available as option then write it in style input box) as style and give the color you want,it will change the text color of your Textfield.

I came here for the same problem and solved it in this way.

Docker: Multiple Dockerfiles in project

Use docker-compose and multiple Dockerfile in separate directories

Don't rename your Dockerfile to Dockerfile.db or Dockerfile.web, it may not be supported by your IDE and you will lose syntax highlighting.

As Kingsley Uchnor said, you can have multiple Dockerfile, one per directory, which represent something you want to build.

I like to have a docker folder which holds each applications and their configuration. Here's an example project folder hierarchy for a web application that has a database.

docker-compose.yml
docker
+-- web
¦   +-- Dockerfile
+-- db
    +-- Dockerfile

docker-compose.yml example:

version: '3'
services:
  web:
    # will build ./docker/web/Dockerfile
    build: ./docker/web
    ports:
     - "5000:5000"
    volumes:
     - .:/code
  db:
    # will build ./docker/db/Dockerfile
    build: ./docker/db
    ports:
      - "3306:3306"
  redis:
    # will use docker hub's redis prebuilt image from here:
    # https://hub.docker.com/_/redis/
    image: "redis:alpine"

docker-compose command line usage example:

# The following command will create and start all containers in the background
# using docker-compose.yml from current directory
docker-compose up -d

# get help
docker-compose --help

In case you need files from previous folders when building your Dockerfile

You can still use the above solution and place your Dockerfile in a directory such as docker/web/Dockerfile, all you need is to set the build context in your docker-compose.yml like this:

version: '3'
services:
  web:
    build:
      context: .
      dockerfile: ./docker/web/Dockerfile
    ports:
     - "5000:5000"
    volumes:
     - .:/code

This way, you'll be able to have things like this:

config-on-root.ini
docker-compose.yml
docker
+-- web
    +-- Dockerfile
    +-- some-other-config.ini

and a ./docker/web/Dockerfile like this:

FROM alpine:latest

COPY config-on-root.ini /
COPY docker/web/some-other-config.ini /

Here are some quick commands from tldr docker-compose. Make sure you refer to official documentation for more details.

Animate a custom Dialog

I meet the same problem,but ,at last I solve the problem by followed way

((ViewGroup)dialog.getWindow().getDecorView())
.getChildAt(0).startAnimation(AnimationUtils.loadAnimation(
context,android.R.anim.slide_in_left));

Matplotlib scatter plot with different text at each data point

Python 3.6+:

coordinates = [('a',1,2), ('b',3,4), ('c',5,6)]
for x in coordinates: plt.annotate(x[0], (x[1], x[2]))

How to check identical array in most efficient way?

You could compare String representations so:

array1.toString() == array2.toString()
array1.toString() !== array3.toString()

but that would also make

array4 = ['1',2,3,4,5]

equal to array1 if that matters to you

Use of Finalize/Dispose method in C#

Dispose pattern:

public abstract class DisposableObject : IDisposable
{
    public bool Disposed { get; private set;}      

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    ~DisposableObject()
    {
        Dispose(false);
    }

    private void Dispose(bool disposing)
    {
        if (!Disposed)
        {
            if (disposing)
            {
                DisposeManagedResources();
            }

            DisposeUnmanagedResources();
            Disposed = true;
        }
    }

    protected virtual void DisposeManagedResources() { }
    protected virtual void DisposeUnmanagedResources() { }
}

Example of inheritance:

public class A : DisposableObject
{
    public Component components_a { get; set; }
    private IntPtr handle_a;

    protected override void DisposeManagedResources()
    {
        try
        {
          Console.WriteLine("A_DisposeManagedResources");
          components_a.Dispose();
          components_a = null;
        }
        finally
        { 
          base.DisposeManagedResources();
        }
    }

    protected override void DisposeUnmanagedResources()
    {
        try
        {
          Console.WriteLine("A_DisposeUnmanagedResources");
          CloseHandle(handle_a);
          handle_a = IntPtr.Zero;
        }
        finally
        { 
          base.DisposeUnmanagedResources();
        }
    }
}

public class B : A
{
    public Component components_b { get; set; }
    private IntPtr handle_b;

    protected override void DisposeManagedResources()
    {
        try
        {
          Console.WriteLine("B_DisposeManagedResources");
          components_b.Dispose();
          components_b = null;
        }
        finally
        { 
          base.DisposeManagedResources();
        }
    }

    protected override void DisposeUnmanagedResources()
    {
        try
        {
          Console.WriteLine("B_DisposeUnmanagedResources");
          CloseHandle(handle_b);
          handle_b = IntPtr.Zero;
        }
        finally
        { 
          base.DisposeUnmanagedResources();
        }
    }
}

Why is "using namespace std;" considered bad practice?

It's case by case. We want to minimize the "total cost of ownership" of the software over its lifespan. Stating "using namespace std" has some costs, but not using it also has a cost in legibility.

People correctly point out that when using it, when the standard library introduces new symbols and definitions, your code ceases to compile, and you may be forced to rename variables. And yet this is probably good long-term, since future maintainers will be momentarily confused or distracted if you're using a keyword for some surprising purpose.

You don't want to have a template called vector, say, which isn't the vector known by everyone else. And the number of new definitions thus introduced in the C++ library is small enough it may simply not come up. There is a cost to having to do this kind of change, but the cost is not high and is offset by the clarity gained by not using std symbol names for other purposes.

Given the number of classes, variables, and functions, stating std:: on every one might fluff up your code by 50% and make it harder to get your head around. An algorithm or step in a method that could be taken in on one screenful of code now requires scrolling back and forth to follow. This is a real cost. Arguably it may not be a high cost, but people who deny it even exists are inexperienced, dogmatic, or simply wrong.

I'd offer the following rules:

  1. std is different from all other libraries. It is the one library everyone basically needs to know, and in my view is best thought of as part of the language. Generally speaking there is an excellent case for using namespace std even if there isn't for other libraries.

  2. Never force the decision onto the author of a compilation unit (a .cpp file) by putting this using in a header. Always defer the decision to the compilation unit author. Even in a project that has decided to use using namespace std everywhere may fine a few modules that are best handled as exceptions to that rule.

  3. Even though the namespace feature lets you have many modules with symbols defined the same, it's going to be confusing to do so. Keep the names different to the extent possible. Even if not using the namespace feature, if you have a class named foo and std introduces a class named foo, it's probably better long-run to rename your class anyway.

  4. An alternative to using namespaces is to manually namespace symbols by prefixing them. I have two libraries I've used for decades, both starting as C libraries, actually, where every symbol is prefixed with "AK" or "SCWin". Generally speaking, this is like avoiding the "using" construct, but you don't write the twin colons. AK::foo() is instead AKFoo(). It makes code 5-10% denser and less verbose, and the only downside is that you'll be in big trouble if you have to use two such libraries that have the same prefixing. Note the X Window libraries are excellent in this regard, except they forgot to do so with a few #defines: TRUE and FALSE should have been XTRUE and XFALSE, and this set up a namespace clash with Sybase or Oracle that likewise used TRUE and FALSE with different values! (ASCII 0 and 1 in the case of the database!) One special advantage of this is that it applies seemlessly to preprocessor definitions, whereas the C++ using/namespace system doesn't handle them. A nice benefit of this is that it gives an organic slope from being part of a project to eventually being a library. In a large application of mine, all window classes are prefixed Win, all signal-processing modules Mod, and so on. There's little chance of any of these being reused so there's no practical benefit to making each group into a library, but it makes obvious in a few seconds how the project breaks into sub-projects.

What is the difference between Select and Project Operations

Project will effects Columns in the table while Select effects the Rows. on other hand Project is use to select the columns with specefic properties rather than Select the all of columns data

How do I print part of a rendered HTML page in JavaScript?

I would go about it somewhat like this:

<html>
    <head>
        <title>Print Test Page</title>
        <script>
            printDivCSS = new String ('<link href="myprintstyle.css" rel="stylesheet" type="text/css">')
            function printDiv(divId) {
                window.frames["print_frame"].document.body.innerHTML=printDivCSS + document.getElementById(divId).innerHTML;
                window.frames["print_frame"].window.focus();
                window.frames["print_frame"].window.print();
            }
        </script>
    </head>

    <body>
        <h1><b><center>This is a test page for printing</center></b><hr color=#00cc00 width=95%></h1>
        <b>Div 1:</b> <a href="javascript:printDiv('div1')">Print</a><br>
        <div id="div1">This is the div1's print output</div>
        <br><br>
        <b>Div 2:</b> <a href="javascript:printDiv('div2')">Print</a><br>
        <div id="div2">This is the div2's print output</div>
        <br><br>
        <b>Div 3:</b> <a href="javascript:printDiv('div3')">Print</a><br>
        <div id="div3">This is the div3's print output</div>
        <iframe name="print_frame" width="0" height="0" frameborder="0" src="about:blank"></iframe>
    </body>
</html>

QED symbol in latex

You can use \blacksquare ¦:

When creating TeX, Knuth provided the symbol ¦ (solid black square), also called by mathematicians tombstone or Halmos symbol (after Paul Halmos, who pioneered its use as an equivalent of Q.E.D.). The tombstone is sometimes open: ? (hollow black square).

Attach the Source in Eclipse of a jar

Go back in to where you added the jar. I believe its the libraries tab, I don't have Eclipse open but that sounds right. to the left of the jar file you added there should be an arrow pointing right, click that and 3 or 4 options expand, one of them being the source file of the library. Click on that and click edit(I think you can also double click it) then locate the file or folder on your hard disk, you probably have to click apply or okay and you're good to go, same with javadoc and i think the last one is native libraries. I don't pay much attention when I'm in there anymore if you couldn't tell. That's what you were asking, right?

Bootstrap 3: Offset isn't working?

Which version of bootstrap are you using? The early versions of Bootstrap 3 (3.0, 3.0.1) didn't work with this functionality.

col-md-offset-0 should be working as seen in this bootstrap example found here (http://getbootstrap.com/css/#grid-responsive-resets):

<div class="row">
   <div class="col-sm-5 col-md-6">.col-sm-5 .col-md-6</div>
   <div class="col-sm-5 col-sm-offset-2 col-md-6 col-md-offset-0">.col-sm-5 .col-sm-offset-2 .col-md-6 .col-md-offset-0</div>
</div>

How to extract year and month from date in PostgreSQL without using to_char() function?

1st Option

date_trunc('month', timestamp_column)::date

It will maintain the date format with all months starting at day one.

Example:

2016-08-01
2016-09-01
2016-10-01
2016-11-01
2016-12-01
2017-01-01

2nd Option

to_char(timestamp_column, 'YYYY-MM')

This solution proposed by @yairchu worked fine in my case. I really wanted to discard 'day' info.

How do I declare and assign a variable on a single line in SQL

Here goes:

DECLARE @var nvarchar(max) = 'Man''s best friend';

You will note that the ' is escaped by doubling it to ''.

Since the string delimiter is ' and not ", there is no need to escape ":

DECLARE @var nvarchar(max) = '"My Name is Luca" is a great song';

The second example in the MSDN page on DECLARE shows the correct syntax.

Regular expression "^[a-zA-Z]" or "[^a-zA-Z]"

There is a difference.

When the ^ character appears outside of [] matches the beginning of the line (or string). When the ^ character appears inside the [], it matches any character not appearing inside the [].

How to watch for form changes in Angular

To complete a bit more previous great answers, you need to be aware that forms leverage observables to detect and handle value changes. It's something really important and powerful. Both Mark and dfsq described this aspect in their answers.

Observables allow not only to use the subscribe method (something similar to the then method of promises in Angular 1). You can go further if needed to implement some processing chains for updated data in forms.

I mean you can specify at this level the debounce time with the debounceTime method. This allows you to wait for an amount of time before handling the change and correctly handle several inputs:

this.form.valueChanges
    .debounceTime(500)
    .subscribe(data => console.log('form changes', data));

You can also directly plug the processing you want to trigger (some asynchronous one for example) when values are updated. For example, if you want to handle a text value to filter a list based on an AJAX request, you can leverage the switchMap method:

this.textValue.valueChanges
    .debounceTime(500)
    .switchMap(data => this.httpService.getListValues(data))
    .subscribe(data => console.log('new list values', data));

You even go further by linking the returned observable directly to a property of your component:

this.list = this.textValue.valueChanges
    .debounceTime(500)
    .switchMap(data => this.httpService.getListValues(data))
    .subscribe(data => console.log('new list values', data));

and display it using the async pipe:

<ul>
  <li *ngFor="#elt of (list | async)">{{elt.name}}</li>
</ul>

Just to say that you need to think the way to handle forms differently in Angular2 (a much more powerful way ;-)).

Hope it helps you, Thierry

TypeError: only length-1 arrays can be converted to Python scalars while plot showing

dataframe['column'].squeeze() should solve this. It basically changes the dataframe column to a list.

How can I force WebKit to redraw/repaint to propagate style changes?

I tried morewry answer but it does not work for me. I had trouble to have the same clientWidth with safari comparing to others browsers and this code solved the problem:

var get_safe_value = function(elm,callback){
    var sty = elm.style
    sty.transform = "translateZ(1px)";
    var ret = callback(elm)//you can get here the value you want
    sty.transform = "";
    return ret
}
// for safari to have the good clientWidth
var $fBody = document.body //the element you need to fix
var clientW = get_safe_value($fBody,function(elm){return $fBody.clientWidth})

It is really strange because if I try again to get the clientWidth after get_safe_value, I obtain a bad value with safari, the getter has to be between sty.transform = "translateZ(1px)"; and sty.transform = "";

The other solution that works definitively is

var $fBody = document.body //the element you need to fix
$fBody.style.display = 'none';
var temp = $.body.offsetHeight;
$fBody.style.display = ""
temp = $.body.offsetHeight;

var clientW = $fBody.clientWidth

The problem is that you lose focus and scroll states.

Setting Spring Profile variable

For Eclipse, setting -Dspring.profiles.active variable in the VM arguments would do the trick.

Go to

Right Click Project --> Run as --> Run Configurations --> Arguments

And add your -Dspring.profiles.active=dev in the VM arguments

If list index exists, do X

Could it be more useful for you to use the length of the list len(n) to inform your decision rather than checking n[i] for each possible length?

SQL Server query to find all current database names

Here is a query for showing all databases in one Sql engine

Select * from Sys.Databases

SQL MERGE statement to update data

UPDATE ed
SET ed.kWh = ted.kWh
FROM energydata ed
INNER JOIN temp_energydata ted ON ted.webmeterID = ed.webmeterID

Android dex gives a BufferOverflowException when building

Same problem here. Reverted to build tools 18.1.1, restarted Eclipse and that fixed it.

How to sleep the thread in node.js without affecting other threads?

If you are referring to the npm module sleep, it notes in the readme that sleep will block execution. So you are right - it isn't what you want. Instead you want to use setTimeout which is non-blocking. Here is an example:

setTimeout(function() {
  console.log('hello world!');
}, 5000);

For anyone looking to do this using es7 async/await, this example should help:

const snooze = ms => new Promise(resolve => setTimeout(resolve, ms));

const example = async () => {
  console.log('About to snooze without halting the event loop...');
  await snooze(1000);
  console.log('done!');
};

example();

How do I reverse an int array in Java?

Here is a simple implementation, to reverse array of any type, plus full/partial support.

import java.util.logging.Logger;

public final class ArrayReverser {
 private static final Logger LOGGER = Logger.getLogger(ArrayReverser.class.getName());

 private ArrayReverser () {

 }

 public static <T> void reverse(T[] seed) {
    reverse(seed, 0, seed.length);
 }

 public static <T> void reverse(T[] seed, int startIndexInclusive, int endIndexExclusive) {
    if (seed == null || seed.length == 0) {
        LOGGER.warning("Nothing to rotate");
    }
    int start = startIndexInclusive < 0 ? 0 : startIndexInclusive;
    int end = Math.min(seed.length, endIndexExclusive) - 1;
    while (start < end) {
        swap(seed, start, end);
        start++;
        end--;
    }
}

 private static <T> void swap(T[] seed, int start, int end) {
    T temp =  seed[start];
    seed[start] = seed[end];
    seed[end] = temp;
 }  

}

Here is the corresponding Unit Test

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

import org.junit.Before;
import org.junit.Test;

public class ArrayReverserTest {
private Integer[] seed;

@Before
public void doBeforeEachTestCase() {
    this.seed = new Integer[]{1,2,3,4,5,6,7,8};
}

@Test
public void wholeArrayReverse() {
    ArrayReverser.<Integer>reverse(seed);
    assertThat(seed[0], is(8));
}

 @Test
 public void partialArrayReverse() {
    ArrayReverser.<Integer>reverse(seed, 1, 5);
    assertThat(seed[1], is(5));
 }
}

PHP - count specific array values

You can do this with array_keys and count.

$array = array("blue", "red", "green", "blue", "blue");
echo count(array_keys($array, "blue"));

Output:

3

Use JAXB to create Object from XML String

If you already have the xml, and comes more than one attribute, you can handle it as follows:

String output = "<ciudads><ciudad><idCiudad>1</idCiudad>
<nomCiudad>BOGOTA</nomCiudad></ciudad><ciudad><idCiudad>6</idCiudad>
<nomCiudad>Pereira</nomCiudad></ciudads>";
DocumentBuilder db = DocumentBuilderFactory.newInstance()
    .newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(output));

Document doc = db.parse(is);
NodeList nodes = ((org.w3c.dom.Document) doc)
    .getElementsByTagName("ciudad");

for (int i = 0; i < nodes.getLength(); i++) {           
    Ciudad ciudad = new Ciudad();
    Element element = (Element) nodes.item(i);

    NodeList name = element.getElementsByTagName("idCiudad");
    Element element2 = (Element) name.item(0);
    ciudad.setIdCiudad(Integer
        .valueOf(getCharacterDataFromElement(element2)));

    NodeList title = element.getElementsByTagName("nomCiudad");
    element2 = (Element) title.item(0);
    ciudad.setNombre(getCharacterDataFromElement(element2));

    ciudades.getPartnerAccount().add(ciudad);
}
}

for (Ciudad ciudad1 : ciudades.getPartnerAccount()) {
System.out.println(ciudad1.getIdCiudad());
System.out.println(ciudad1.getNombre());
}

the method getCharacterDataFromElement is

public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;

return cd.getData();
}
return "";
}

How to move Jenkins from one PC to another

Sometimes we may not have access to a Jenkins machine to copy a folder directly into another Jenkins instance. So I wrote a menu driven utility which uses Jenkins REST API calls to install plugins and jobs from one Jenkins instance to another.

For plugin migration:

  1. GET request: {SOURCE_JENKINS_SERVER}/pluginManager/api/json?depth=1 will get you the list of plugins installed with their version.
  2. You can send a POST request with the following parameters to install these plugins.

    final_url=`{DESTINATION_JENKINS_SERVER}/pluginManager/installNecessaryPlugins`
    
    data=`<jenkins><install plugin="{PLUGIN_NAME}@latest"/></jenkins>` (where, latest will fetch the latest version of the plugin_name)
    
    auth=`(destination_jenkins_username, destination_jenkins_password)`
    
    header=`{crumb_field:crumb_value,"Content-Type":"application/xml”}` (where crumb_field=Jenkins-Crumb and get crumb value using API call {DESTINATION_JENKINS_SERVER}/crumbIssuer/api/json
    

For job migration:

  1. You can get the list of jobs installed on {SOURCE_JENKINS_URL} using a REST call, {SOURCE_JENKINS_URL}/view/All/api/json
  2. Then you can get each job config.xml file from the jobs on {SOURCE_JENKINS_URL} using the job URL {SOURCE_JENKINS_URL}/job/{JOB_NAME}.
  3. Use this config.xml file to POST the content of the XML file on {DESTINATION_JENKINS_URL} and that will create a job on {DESTINATION_JENKINS_URL}.

I have created a menu-driven utility in Python which asks the user to start plugin or Jenkins migration and uses Jenkins REST API calls to do it.

You can refer the JenkinsMigration.docx from this URL

Hex to ascii string conversion

you need to take 2 (hex) chars at the same time... then calculate the int value and after that make the char conversion like...

char d = (char)intValue;

do this for every 2chars in the hex string

this works if the string chars are only 0-9A-F:

#include <stdio.h>
#include <string.h>

int hex_to_int(char c){
        int first = c / 16 - 3;
        int second = c % 16;
        int result = first*10 + second;
        if(result > 9) result--;
        return result;
}

int hex_to_ascii(char c, char d){
        int high = hex_to_int(c) * 16;
        int low = hex_to_int(d);
        return high+low;
}

int main(){
        const char* st = "48656C6C6F3B";
        int length = strlen(st);
        int i;
        char buf = 0;
        for(i = 0; i < length; i++){
                if(i % 2 != 0){
                        printf("%c", hex_to_ascii(buf, st[i]));
                }else{
                        buf = st[i];
                }
        }
}

What is the advantage of using heredoc in PHP?

Heredoc's are a great alternative to quoted strings because of increased readability and maintainability. You don't have to escape quotes and (good) IDEs or text editors will use the proper syntax highlighting.

A very common example: echoing out HTML from within PHP:

$html = <<<HTML
  <div class='something'>
    <ul class='mylist'>
      <li>$something</li>
      <li>$whatever</li>
      <li>$testing123</li>
    </ul>
  </div>
HTML;

// Sometime later
echo $html;

It is easy to read and easy to maintain.

The alternative is echoing quoted strings, which end up containing escaped quotes and IDEs aren't going to highlight the syntax for that language, which leads to poor readability and more difficulty in maintenance.

Updated answer for Your Common Sense

Of course you wouldn't want to see an SQL query highlighted as HTML. To use other languages, simply change the language in the syntax:

$sql = <<<SQL
       SELECT * FROM table
SQL;

Import CSV file into SQL Server

The best, quickest and easiest way to resolve the comma in data issue is to use Excel to save a comma separated file after having set Windows' list separator setting to something other than a comma (such as a pipe). This will then generate a pipe (or whatever) separated file for you that you can then import. This is described here.

What is path of JDK on Mac ?

Have a look and see if the the JDK is at:

Library/Java/JavaVirtualMachines/ Or /System/Library/Java/JavaVirtualMachines/

Check this earlier SO post: JDK on OSX 10.7 Lion

Fastest way to get the first n elements of a List into an Array

Assumption:

list - List<String>

Using Java 8 Streams,

  • to get first N elements from a list into a list,

    List<String> firstNElementsList = list.stream().limit(n).collect(Collectors.toList());

  • to get first N elements from a list into an Array,

    String[] firstNElementsArray = list.stream().limit(n).collect(Collectors.toList()).toArray(new String[n]);

How to fix the error; 'Error: Bootstrap tooltips require Tether (http://github.hubspot.com/tether/)'

Install tether via npm like below

npm install tether --save-dev

then add tether to your html above bootstrap like below

<script src="node_modules/tether/dist/js/tether.min.js"></script>
<script src="jspm_packages/github/twbs/[email protected]/js/bootstrap.js"></script>

align textbox and text/labels in html?

you can do a multi div layout like this

<div class="fieldcontainer">
    <div class="label"></div>
    <div class="field"></div>
</div>

where .fieldcontainer { clear: both; } .label { float: left; width: ___ } .field { float: left; }

Or, I actually prefer tables for forms like this. This is very much tabular data and it comes out very clean. Both will work though.

CSS: Center block, but align contents to the left

Reposting the working answer from the other question: How to horizontally center a floating element of a variable width?

Assuming the element which is floated and will be centered is a div with an id="content" ...

<body>
<div id="wrap">
   <div id="content">
   This will be centered
   </div>
</div>
</body>

And apply the following CSS

#wrap {
    float: left;
    position: relative;
    left: 50%;
}

#content {
    float: left;
    position: relative;
    left: -50%;
}

Here is a good reference regarding that http://dev.opera.com/articles/view/35-floats-and-clearing/#centeringfloats

Use a.any() or a.all()

This should also work and is a closer answer to what is asked in the question:

for i in range(len(x)):
    if valeur.item(i) <= 0.6:
        print ("this works")
    else:   
        print ("valeur is too high")

How to concatenate multiple column values into a single column in Panda dataframe

Just wanted to make a time comparison for both solutions (for 30K rows DF):

In [1]: df = DataFrame({'foo':['a','b','c'], 'bar':[1, 2, 3], 'new':['apple', 'banana', 'pear']})

In [2]: big = pd.concat([df] * 10**4, ignore_index=True)

In [3]: big.shape
Out[3]: (30000, 3)

In [4]: %timeit big.apply(lambda x:'%s_%s_%s' % (x['bar'],x['foo'],x['new']),axis=1)
1 loop, best of 3: 881 ms per loop

In [5]: %timeit big['bar'].astype(str)+'_'+big['foo']+'_'+big['new']
10 loops, best of 3: 44.2 ms per loop

a few more options:

In [6]: %timeit big.ix[:, :-1].astype(str).add('_').sum(axis=1).str.cat(big.new)
10 loops, best of 3: 72.2 ms per loop

In [11]: %timeit big.astype(str).add('_').sum(axis=1).str[:-1]
10 loops, best of 3: 82.3 ms per loop

UTF-8, UTF-16, and UTF-32

  • UTF-8 is variable 1 to 4 bytes.

  • UTF-16 is variable 2 or 4 bytes.

  • UTF-32 is fixed 4 bytes.

Note: UTF-8 can take 1 to 6 bytes with latest convention: https://lists.gnu.org/archive/html/help-flex/2005-01/msg00030.html

Printing a java map Map<String, Object> - How?

There is a get method in HashMap:

for (String keys : objectSet.keySet())  
{
   System.out.println(keys + ":"+ objectSet.get(keys));
}

Object of custom type as dictionary key

You override __hash__ if you want special hash-semantics, and __cmp__ or __eq__ in order to make your class usable as a key. Objects who compare equal need to have the same hash value.

Python expects __hash__ to return an integer, returning Banana() is not recommended :)

User defined classes have __hash__ by default that calls id(self), as you noted.

There is some extra tips from the documentation.:

Classes which inherit a __hash__() method from a parent class but change the meaning of __cmp__() or __eq__() such that the hash value returned is no longer appropriate (e.g. by switching to a value-based concept of equality instead of the default identity based equality) can explicitly flag themselves as being unhashable by setting __hash__ = None in the class definition. Doing so means that not only will instances of the class raise an appropriate TypeError when a program attempts to retrieve their hash value, but they will also be correctly identified as unhashable when checking isinstance(obj, collections.Hashable) (unlike classes which define their own __hash__() to explicitly raise TypeError).

cordova run with ios error .. Error code 65 for command: xcodebuild with args:

I must add :

I had the same problem, it was coming from the fact that my teammate had a different version of cordova, and commited plugins on the repo with his version.

For all cordova plugins, I had to :

cordova plugin rm <plugin-name> 
cordova plugin add <plugin-name>

And ask my teammate to update his cordova to match my version

Run batch file from Java code

Your code is fine, but the problem is inside the batch file.

You have to show the content of the bat file, your problem is in the paths inside the bat file.

OS X Framework Library not loaded: 'Image not found'

I experienced that problem only when running on real device (iPhone SE). On simulator project worked as expected.

I did try all fixes from this very thread and from here. None of those worked for me.

For me problem was solved after restarting iPhone (sic!).

I did:

  • clean build folder,
  • clean derived data,
  • delete app from device,
  • reboot device

And it finally works. :)

If every other solution fails don't forget to try it out.

Cannot download Docker images behind a proxy

To configure Docker to work with a proxy you need to add the HTTPS_PROXY / HTTP_PROXY environment variable to the Docker sysconfig file (/etc/sysconfig/docker).

Depending on if you use init.d or the services tool you need to add the "export" statement (due to Debian Bug report logs - #767441. Examples in /etc/default/docker are misleading regarding the supported syntax):

HTTPS_PROXY="https://<user>:<password>@<proxy-host>:<proxy-port>"
HTTP_PROXY="https://<user>:<password>@<proxy-host>:<proxy-port>"
export HTTP_PROXY="https://<user>:<password>@<proxy-host>:<proxy-port>"
export HTTPS_PROXY="https://<user>:<password>@<proxy-host>:<proxy-port>"

The Docker repository (Docker Hub) only supports HTTPS. To get Docker working with SSL intercepting proxies you have to add the proxy root certificate to the systems trust store.

For CentOS, copy the file to /etc/pki/ca-trust/source/anchors/ and update the CA trust store and restart the Docker service.

If your proxy uses NTLMv2 authentication - you need to use intermediate proxies like Cntlm to bridge the authentication. This blog post explains it in detail.

Export to csv in jQuery

Just try the following coding...very simple to generate CSV with the values of HTML Tables. No browser issues will come

<!DOCTYPE html>
<html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>        
        <script src="http://www.csvscript.com/dev/html5csv.js"></script>
<script>
$(document).ready(function() {

 $('table').each(function() {
    var $table = $(this);

    var $button = $("<button type='button'>");
    $button.text("Export to CSV");
    $button.insertAfter($table);

    $button.click(function() {     
         CSV.begin('table').download('Export.csv').go();
    });
  });  
})

</script>
    </head>
<body>
<div id='PrintDiv'>
<table style="width:100%">
  <tr>
    <td>Jill</td>
    <td>Smith</td>      
    <td>50</td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td>        
    <td>94</td>
  </tr>
  <tr>
    <td>John</td>
    <td>Doe</td>        
    <td>80</td>
  </tr>
</table>
</div>
</body>
</html>

How to use makefiles in Visual Studio?

Makefiles and build files are about automating your build. If you use a script like MSBuild or NAnt, you can build your project or solution directly from command line. This in turn makes it possible to automate the build, have it run by a build server.

Besides building your solution it is typical that a build script includes task to run unit tests, report code coverage and complexity and more.

What is the difference between synchronous and asynchronous programming (in node.js)

The difference between these two approaches is as follows:

Synchronous way: It waits for each operation to complete, after that only it executes the next operation. For your query: The console.log() command will not be executed until & unless the query has finished executing to get all the result from Database.

Asynchronous way: It never waits for each operation to complete, rather it executes all operations in the first GO only. The result of each operation will be handled once the result is available. For your query: The console.log() command will be executed soon after the Database.Query() method. While the Database query runs in the background and loads the result once it is finished retrieving the data.

Use cases

  1. If your operations are not doing very heavy lifting like querying huge data from DB then go ahead with Synchronous way otherwise Asynchronous way.

  2. In Asynchronous way you can show some Progress indicator to the user while in background you can continue with your heavy weight works. This is an ideal scenario for GUI apps.

Why Anaconda does not recognize conda command?

Same problem with Anaconda running on Ubuntu 15.10. I closed the terminal and opened a new window and it worked fine.

Installing RubyGems in Windows

I use scoop as command-liner installer for Windows... scoop rocks!
The quick answer (use PowerShell):

PS C:\Users\myuser> scoop install ruby

Longer answer:

Just searching for ruby:

PS C:\Users\myuser> scoop search ruby
'main' bucket:
    jruby (9.2.7.0)
    ruby (2.6.3-1)

'versions' bucket:
    ruby19 (1.9.3-p551)
    ruby24 (2.4.6-1)
    ruby25 (2.5.5-1)

Check the installation info :

PS C:\Users\myuser> scoop info ruby
Name: ruby
Version: 2.6.3-1
Website: https://rubyinstaller.org
Manifest:
  C:\Users\myuser\scoop\buckets\main\bucket\ruby.json
Installed: No
Environment: (simulated)
  GEM_HOME=C:\Users\myuser\scoop\apps\ruby\current\gems
  GEM_PATH=C:\Users\myuser\scoop\apps\ruby\current\gems
  PATH=%PATH%;C:\Users\myuser\scoop\apps\ruby\current\bin
  PATH=%PATH%;C:\Users\myuser\scoop\apps\ruby\current\gems\bin

Output from installation:

PS C:\Users\myuser> scoop install ruby
Updating Scoop...
Updating 'extras' bucket...
Installing 'ruby' (2.6.3-1) [64bit]
rubyinstaller-2.6.3-1-x64.7z (10.3 MB) [============================= ... ===========] 100%
Checking hash of rubyinstaller-2.6.3-1-x64.7z ... ok.
Extracting rubyinstaller-2.6.3-1-x64.7z ... done.
Linking ~\scoop\apps\ruby\current => ~\scoop\apps\ruby\2.6.3-1
Persisting gems
Running post-install script...
Fetching rake-12.3.3.gem
Successfully installed rake-12.3.3
Parsing documentation for rake-12.3.3
Installing ri documentation for rake-12.3.3
Done installing documentation for rake after 1 seconds
1 gem installed
'ruby' (2.6.3-1) was installed successfully!
Notes
-----
Install MSYS2 via 'scoop install msys2' and then run 'ridk install' to install the toolchain!
'ruby' suggests installing 'msys2'.
PS C:\Users\myuser>

Searching for UUIDs in text with regex

@ivelin: UUID can have capitals. So you'll either need to toLowerCase() the string or use:

[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}

Would have just commented this but not enough rep :)

How to show Error & Warning Message Box in .NET/ How to Customize MessageBox

Try details: use any option..

    MessageBox.Show("your message",
    "window title", 
    MessageBoxButtons.OK, 
    MessageBoxIcon.Warning // for Warning  
    //MessageBoxIcon.Error // for Error 
    //MessageBoxIcon.Information  // for Information
    //MessageBoxIcon.Question // for Question
   );

WITH (NOLOCK) vs SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

WITH (NOLOCK) is a hint on a table level. Setting the transaction isolation level to READ_UNCOMMITTED with affect the connection. The difference is in terms of scope. See READUNCOMMITTED and NOLOCK in the SQL Server documentation here:

http://technet.microsoft.com/en-us/library/ms187373.aspx

For TRANSACTION ISOLATION LEVEL: http://technet.microsoft.com/en-us/library/ms173763.aspx

How to get the first 2 letters of a string in Python?

In general, you can the characters of a string from i until j with string[i:j]. string[:2] is shorthand for string[0:2]. This works for arrays as well.

Learn about python's slice notation at the official tutorial

phpMyAdmin allow remote users

Replace the contents of the first <directory> tag.

Remove:

<Directory /usr/share/phpMyAdmin/>
 <IfModule mod_authz_core.c>
  # Apache 2.4
  <RequireAny>
    Require ip 127.0.0.1
    Require ip ::1
  </RequireAny>
 </IfModule>
 <IfModule !mod_authz_core.c>
  # Apache 2.2
  Order Deny,Allow
  Deny from All
  Allow from 127.0.0.1
  Allow from ::1
 </IfModule>
</Directory>

And place this instead:

<Directory /usr/share/phpMyAdmin/>
 Order allow,deny
 Allow from all
</Directory>

Don't forget to restart Apache afterwards.

How to include quotes in a string

Use escape characters for example this code:

var message = "I want to learn \"c#\"";
Console.WriteLine(message);

will output:

I want to learn "c#"

Rounding up to next power of 2

next = pow(2, ceil(log(x)/log(2)));

This works by finding the number you'd have raise 2 by to get x (take the log of the number, and divide by the log of the desired base, see wikipedia for more). Then round that up with ceil to get the nearest whole number power.

This is a more general purpose (i.e. slower!) method than the bitwise methods linked elsewhere, but good to know the maths, eh?

asp.net mvc @Html.CheckBoxFor

Html.CheckBoxFor expects a Func<TModel, bool> as the first parameter. Therefore your lambda must return a bool, you are currently returning an instance of List<Checkboxes>:

model => model.EmploymentType

You need to iterate over the List<Checkboxes> to output each checkbox:

@for (int i = 0; i < Model.EmploymentType.Count; i++)
{
    @Html.HiddenFor(m => m.EmploymentType[i].Text)
    @Html.CheckBoxFor(m => m.EmploymentType[i].Checked, 
              new { id = string.Format("employmentType_{0}", i) })
}

How to format number of decimal places in wpf using style/template?

You should use the StringFormat on the Binding. You can use either standard string formats, or custom string formats:

<TextBox Text="{Binding Value, StringFormat=N2}" />
<TextBox Text="{Binding Value, StringFormat={}{0:#,#.00}}" />

Note that the StringFormat only works when the target property is of type string. If you are trying to set something like a Content property (typeof(object)), you will need to use a custom StringFormatConverter (like here), and pass your format string as the ConverterParameter.

Edit for updated question

So, if your ViewModel defines the precision, I'd recommend doing this as a MultiBinding, and creating your own IMultiValueConverter. This is pretty annoying in practice, to go from a simple binding to one that needs to be expanded out to a MultiBinding, but if the precision isn't known at compile time, this is pretty much all you can do. Your IMultiValueConverter would need to take the value, and the precision, and output the formatted string. You'd be able to do this using String.Format.

However, for things like a ContentControl, you can much more easily do this with a Style:

<Style TargetType="{x:Type ContentControl}">
    <Setter Property="ContentStringFormat" 
            Value="{Binding Resolution, StringFormat=N{0}}" />
</Style>

Any control that exposes a ContentStringFormat can be used like this. Unfortunately, TextBox doesn't have anything like that.

Get week number (in the year) from a date PHP

To get Correct Week Count for Date 2018-12-31 Please use below Code

$day_count = date('N',strtotime('2018-12-31'));
$week_count = date('W',strtotime('2018-12-31'));    


if($week_count=='01' && date('m',strtotime('2018-12-31'))==12){
    $yr_count = date('y',strtotime('2018-12-31')) + 1;
}else{
    $yr_count = date('y',strtotime('2018-12-31'));
}

Vertical Alignment of text in a table cell

If you are using Bootstrap, please add the following customised style setting for your table:

.table>tbody>tr>td, 
.table>tbody>tr>th, 
.table>tfoot>tr>td, 
.table>tfoot>tr>th, 
.table>thead>tr>td, 
.table>thead>tr>th {
      vertical-align: middle;
 }

How to get data from observable in angular2

You need to subscribe to the observable and pass a callback that processes emitted values

this.myService.getConfig().subscribe(val => console.log(val));

Java - sending HTTP parameters via POST method easily

I took Boann's answer and used it to create a more flexible query string builder that supports lists and arrays, just like php's http_build_query method:

public static byte[] httpBuildQueryString(Map<String, Object> postsData) throws UnsupportedEncodingException {
    StringBuilder postData = new StringBuilder();
    for (Map.Entry<String,Object> param : postsData.entrySet()) {
        if (postData.length() != 0) postData.append('&');

        Object value = param.getValue();
        String key = param.getKey();

        if(value instanceof Object[] || value instanceof List<?>)
        {
            int size = value instanceof Object[] ? ((Object[])value).length : ((List<?>)value).size();
            for(int i = 0; i < size; i++)
            {
                Object val = value instanceof Object[] ? ((Object[])value)[i] : ((List<?>)value).get(i);
                if(i>0) postData.append('&');
                postData.append(URLEncoder.encode(key + "[" + i + "]", "UTF-8"));
                postData.append('=');            
                postData.append(URLEncoder.encode(String.valueOf(val), "UTF-8"));
            }
        }
        else
        {
            postData.append(URLEncoder.encode(key, "UTF-8"));
            postData.append('=');            
            postData.append(URLEncoder.encode(String.valueOf(value), "UTF-8"));
        }
    }
    return postData.toString().getBytes("UTF-8");
}

How can I disable notices and warnings in PHP within the .htaccess file?

It is probably not the best thing to do. You need to at least check out your PHP error log for things going wrong ;)

# PHP error handling for development servers
php_flag display_startup_errors off
php_flag display_errors off
php_flag html_errors off
php_flag log_errors on
php_flag ignore_repeated_errors off
php_flag ignore_repeated_source off
php_flag report_memleaks on
php_flag track_errors on
php_value docref_root 0
php_value docref_ext 0
php_value error_log /home/path/public_html/domain/PHP_errors.log
php_value error_reporting -1
php_value log_errors_max_len 0

how to read certain columns from Excel using Pandas - Python

parse_cols is deprecated, use usecols instead

that is:

df = pd.read_excel(file_loc, index_col=None, na_values=['NA'], usecols = "A,C:AA")

Redirecting from cshtml page

This clearly is a bad case of controller logic in a view. It would be better to do this in a controller and return the desired view.

[ChildActionOnly]
public ActionResult Results() 
{
    EnumerableRowCollection<DataRow> custs = ViewBag.Customers;
    bool anyRows = custs.Any();

    if(anyRows == false)
    {
        return View("NoResults");
    }
    else
    {
        return View("OtherView");
    }
}

Modify NoResults.cshtml to a Partial.

And call this as a Partial view in the parent view

@Html.Partial("Results")

You might have to pass the Customer collection as a model to the Result action or in a ViewDataDictionary due to reasons explained here: Can't access ViewBag in a partial view in ASP.NET MVC3

The ChildActionOnly attribute will make sure you cannot go to this page by navigating and that this view must be rendered as a partial, thus by a parent view. cfr: Using ChildActionOnly in MVC

Using Eloquent ORM in Laravel to perform search of database using LIKE

If you need to frequently use LIKE, you can simplify the problem a bit. A custom method like () can be created in the model that inherits the Eloquent ORM:

public  function scopeLike($query, $field, $value){
        return $query->where($field, 'LIKE', "%$value%");
}

So then you can use this method in such way:

User::like('name', 'Tomas')->get();

jQuery: load txt file and insert into div

You can use jQuery load method to get the contents and insert into an element.

Try this:

$(document).ready(function() {
        $("#lesen").click(function() {
                $(".text").load("helloworld.txt");
    }); 
}); 

You, can also add a call back to execute something once the load process is complete

e.g:

$(document).ready(function() {
    $("#lesen").click(function() {
        $(".text").load("helloworld.txt", function(){
            alert("Done Loading");
        });
   }); 
}); 

Initializing a struct to 0

See §6.7.9 Initialization:

21 If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

So, yes both of them work. Note that in C99 a new way of initialization, called designated initialization can be used too:

myStruct _m1 = {.c2 = 0, .c1 = 1};

How to display table data more clearly in oracle sqlplus

If you mean you want to see them like this:

WORKPLACEID NAME       ADDRESS        TELEPHONE
----------- ---------- -------------- ---------
          1 HSBC       Nugegoda Road      43434
          2 HNB Bank   Colombo Road      223423

then in SQL Plus you can set the column widths like this (for example):

column name format a10
column address format a20
column telephone format 999999999

You can also specify the line size and page size if necessary like this:

set linesize 100 pagesize 50

You do this by typing those commands into SQL Plus before running the query. Or you can put these commands and the query into a script file e.g. myscript.sql and run that. For example:

column name format a10
column address format a20
column telephone format 999999999

select name, address, telephone
from mytable;

Composer could not find a composer.json

Simple solution is install via this command :

curl -sS https://getcomposer.org/installer | sudo php -- --install-dir=/usr/local/bin --filename=composer

To install package it's very simple :

 composer global require "phpunit/php-invoker=1.1.*"

Ref : composer web site.

Best approach to remove time part of datetime in SQL Server

CAST(round(cast(getdate()as real),0,1) AS datetime)

This method does not use string function. Date is basically a real datatype with digits before decimal are fraction of a day.

this I guess will be faster than a lot.

Parsing JSON string in Java

See my comment. You need to include the full org.json library when running as android.jar only contains stubs to compile against.

In addition, you must remove the two instances of extra } in your JSON data following longitude.

   private final static String JSON_DATA =
     "{" 
   + "  \"geodata\": [" 
   + "    {" 
   + "      \"id\": \"1\"," 
   + "      \"name\": \"Julie Sherman\","                  
   + "      \"gender\" : \"female\"," 
   + "      \"latitude\" : \"37.33774833333334\"," 
   + "      \"longitude\" : \"-121.88670166666667\""
   + "    }," 
   + "    {" 
   + "      \"id\": \"2\"," 
   + "      \"name\": \"Johnny Depp\","          
   + "      \"gender\" : \"male\"," 
   + "      \"latitude\" : \"37.336453\"," 
   + "      \"longitude\" : \"-121.884985\""
   + "    }" 
   + "  ]" 
   + "}"; 

Apart from that, geodata is in fact not a JSONObject but a JSONArray.

Here is the fully working and tested corrected code:

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class ShowActivity {


  private final static String JSON_DATA =
     "{" 
   + "  \"geodata\": [" 
   + "    {" 
   + "      \"id\": \"1\"," 
   + "      \"name\": \"Julie Sherman\","                  
   + "      \"gender\" : \"female\"," 
   + "      \"latitude\" : \"37.33774833333334\"," 
   + "      \"longitude\" : \"-121.88670166666667\""
   + "    }," 
   + "    {" 
   + "      \"id\": \"2\"," 
   + "      \"name\": \"Johnny Depp\","          
   + "      \"gender\" : \"male\"," 
   + "      \"latitude\" : \"37.336453\"," 
   + "      \"longitude\" : \"-121.884985\""
   + "    }" 
   + "  ]" 
   + "}"; 

  public static void main(final String[] argv) throws JSONException {
    final JSONObject obj = new JSONObject(JSON_DATA);
    final JSONArray geodata = obj.getJSONArray("geodata");
    final int n = geodata.length();
    for (int i = 0; i < n; ++i) {
      final JSONObject person = geodata.getJSONObject(i);
      System.out.println(person.getInt("id"));
      System.out.println(person.getString("name"));
      System.out.println(person.getString("gender"));
      System.out.println(person.getDouble("latitude"));
      System.out.println(person.getDouble("longitude"));
    }
  }
}

Here's the output:

C:\dev\scrap>java -cp json.jar;. ShowActivity
1
Julie Sherman
female
37.33774833333334
-121.88670166666667
2
Johnny Depp
male
37.336453
-121.884985

The breakpoint will not currently be hit. No symbols have been loaded for this document in a Silverlight application

Debug - > Attach to process ->
choose Debug these code types: option ->
select Managed v3.5, v3.0, v2.0 or Managed v4.5, v4.0 enter image description here

Align inline-block DIVs to top of container element

You need to add a vertical-align property to your two child div's.

If .small is always shorter, you need only apply the property to .small. However, if either could be tallest then you should apply the property to both .small and .big.

.container{ 
    border: 1px black solid;
    width: 320px;
    height: 120px;    
}

.small{
    display: inline-block;
    width: 40%;
    height: 30%;
    border: 1px black solid;
    background: aliceblue; 
    vertical-align: top;   
}

.big {
    display: inline-block;
    border: 1px black solid;
    width: 40%;
    height: 50%;
    background: beige; 
    vertical-align: top;   
}

Vertical align affects inline or table-cell box's, and there are a large nubmer of different values for this property. Please see https://developer.mozilla.org/en-US/docs/Web/CSS/vertical-align for more details.

Cannot find JavaScriptSerializer in .Net 4.0

  1. Right click References and do Add Reference, then from Assemblies->Framework select System.Web.Extensions.
  2. Now you should be able to add the following to your class file:
    using System.Web.Script.Serialization;

How to insert a data table into SQL Server database table?

public bool BulkCopy(ExcelToSqlBo objExcelToSqlBo, DataTable dt, SqlConnection conn, SqlTransaction tx)
{
    int check = 0;
    bool result = false;
    string getInsert = "";
    try
    {
        if (dt.Rows.Count > 0)
        {
            foreach (DataRow dr in dt.Rows)
            {
                if (dr != null)
                {
                    if (check == 0)
                    {
                        getInsert = "INSERT INTO [tblTemp]([firstName],[lastName],[Father],[Mother],[Category]" +
                                ",[sub_1],[sub_LG2])"+
                                " select '" + dr[0].ToString() + "','" + dr[1].ToString() + "','" + dr[2].ToString() + "','" + dr[3].ToString() + "','" + dr[4].ToString().Trim() + "','" + dr[5].ToString().Trim() + "','" + dr[6].ToString();

                        check += 1;
                    }
                    else
                    {
                        getInsert += " UNION ALL ";

                        getInsert += " select  '" + dr[0].ToString() + "','" + dr[1].ToString() + "','" + dr[2].ToString() + "','" + dr[3].ToString() + "','" + dr[4].ToString().Trim() + "','" + dr[5].ToString().Trim() + "','" + dr[6].ToString() ;

                        check++;
                    }
                }
            }
            result = common.ExecuteNonQuery(getInsert, DatabasesName, conn, tx);
        }
        else
        {
            throw new Exception("No row for insertion");
        }
        dt.Dispose();
    }
    catch (Exception ex)
    {
        dt.Dispose();
        throw new Exception("Please attach file in Proper format.");
    }
    return result;
} 

Best C++ Code Formatter/Beautifier

AStyle can be customized in great detail for C++ and Java (and others too)

This is a source code formatting tool.


clang-format is a powerful command line tool bundled with the clang compiler which handles even the most obscure language constructs in a coherent way.

It can be integrated with Visual Studio, Emacs, Vim (and others) and can format just the selected lines (or with git/svn to format some diff).

It can be configured with a variety of options listed here.

When using config files (named .clang-format) styles can be per directory - the closest such file in parent directories shall be used for a particular file.

Styles can be inherited from a preset (say LLVM or Google) and can later override different options

It is used by Google and others and is production ready.


Also look at the project UniversalIndentGUI. You can experiment with several indenters using it: AStyle, Uncrustify, GreatCode, ... and select the best for you. Any of them can be run later from a command line.


Uncrustify has a lot of configurable options. You'll probably need Universal Indent GUI (in Konstantin's reply) as well to configure it.

JSLint is suddenly reporting: Use the function form of "use strict"

Add a file .jslintrc (or .jshintrc in the case of jshint) at the root of your project with the following content:

{
    "node": true
}

How to take screenshot of a div with JavaScript?

<script src="/assets/backend/js/html2canvas.min.js"></script>


<script>
    $("#download").on('click', function(){
        html2canvas($("#printform"), {
            onrendered: function (canvas) {
                var url = canvas.toDataURL();

                var triggerDownload = $("<a>").attr("href", url).attr("download", getNowFormatDate()+"????????.jpeg").appendTo("body");
                triggerDownload[0].click();
                triggerDownload.remove();
            }
        });
    })
</script>

quotation

How to run a .awk file?

Put the part from BEGIN....END{} inside a file and name it like my.awk.

And then execute it like below:

awk -f my.awk life.csv >output.txt

Also I see a field separator as ,. You can add that in the begin block of the .awk file as FS=","

Count occurrences of a char in a string using Bash

also check this out, for example we wanna count t

echo "test" | awk -v RS='t' 'END{print NR-1}'

or in python

python -c 'print "this is for test".count("t")'

or even better, we can make our script dynamic with awk

echo 'test' | awk '{for (i=1 ; i<=NF ; i++) array[$i]++ } END{ for (char in array) print char,array[char]}' FS=""

in this case output is like this :

e 1
s 1
t 2

Difference between single and double quotes in Bash

Since this is the de facto answer when dealing with quotes in bash, I'll add upon one more point missed in the answers above, when dealing with the arithmetic operators in the shell.

The bash shell supports two ways do arithmetic operation, one defined by the built-in let command and the $((..)) operator. The former evaluates an arithmetic expression while the latter is more of a compound statement.

It is important to understand that the arithmetic expression used with let undergoes word-splitting, pathname expansion just like any other shell commands. So proper quoting and escaping needs to be done.

See this example when using let

let 'foo = 2 + 1'
echo $foo
3

Using single quotes here is absolutely fine here, as there is no need for variable expansions here, consider a case of

bar=1
let 'foo = $bar + 1'

would fail miserably, as the $bar under single quotes would not expand and needs to be double-quoted as

let 'foo = '"$bar"' + 1'

This should be one of the reasons, the $((..)) should always be considered over using let. Because inside it, the contents aren't subject to word-splitting. The previous example using let can be simply written as

(( bar=1, foo = bar + 1 ))

Always remember to use $((..)) without single quotes

Though the $((..)) can be used with double-quotes, there is no purpose to it as the result of it cannot contain a content that would need the double-quote. Just ensure it is not single quoted.

printf '%d\n' '$((1+1))'
-bash: printf: $((1+1)): invalid number
printf '%d\n' $((1+1))
2
printf '%d\n' "$((1+1))"
2

May be in some special cases of using the $((..)) operator inside a single quoted string, you need to interpolate quotes in a way that the operator either is left unquoted or under double quotes. E.g. consider a case, when you are tying to use the operator inside a curl statement to pass a counter every time a request is made, do

curl http://myurl.com --data-binary '{"requestCounter":'"$((reqcnt++))"'}'

Notice the use of nested double-quotes inside, without which the literal string $((reqcnt++)) is passed to requestCounter field.

Laravel Eloquent - Get one Row

You can also use this

$user = User::whereEmail($email)->first();

Remove the string on the beginning of an URL

Another way:

Regex.Replace(urlString, "www.(.+)", "$1");

PHP mPDF save file as PDF

Try this:

$mpdf->Output('my_filename.pdf','D'); 

because:

D - means Download
F - means File-save only

How do I access command line arguments in Python?

If you call it like this: $ python myfile.py var1 var2 var3

import sys

var1 = sys.argv[1]
var2 = sys.argv[2]
var3 = sys.argv[3]

Similar to arrays you also have sys.argv[0] which is always the current working directory.

How to delete a file from SD card?

Recursively delete all children of the file ...

public static void DeleteRecursive(File fileOrDirectory) {
    if (fileOrDirectory.isDirectory()) {
        for (File child : fileOrDirectory.listFiles()) {
            DeleteRecursive(child);
        }
    }

    fileOrDirectory.delete();
}

Call a method of a controller from another controller using 'scope' in AngularJS

Each controller has it's own scope(s) so that's causing your issue.

Having two controllers that want access to the same data is a classic sign that you want a service. The angular team recommends thin controllers that are just glue between views and services. And specifically- "services should hold shared state across controllers".

Happily, there's a nice 15-minute video describing exactly this (controller communication via services): video

One of the original author's of Angular, Misko Hevery, discusses this recommendation (of using services in this situation) in his talk entitled Angular Best Practices (skip to 28:08 for this topic, although I very highly recommended watching the whole talk).

You can use events, but they are designed just for communication between two parties that want to be decoupled. In the above video, Misko notes how they can make your app more fragile. "Most of the time injecting services and doing direct communication is preferred and more robust". (Check out the above link starting at 53:37 to hear him talk about this)

Swift - How to convert String to Double

As of Swift 1.1, you can directly pass String to const char * parameter.

import Foundation

let str = "123.4567"
let num = atof(str) // -> 123.4567

atof("123.4567fubar") // -> 123.4567

If you don't like deprecated atof:

strtod("765.4321", nil) // -> 765.4321

One caveat: the behavior of conversion is different from NSString.doubleValue.

atof and strtod accept 0x prefixed hex string:

atof("0xffp-2") // -> 63.75
atof("12.3456e+2") // -> 1,234.56
atof("nan") // -> (not a number)
atof("inf") // -> (+infinity)

If you prefer .doubleValue behavior, we can still use CFString bridging:

let str = "0xff"
atof(str)                      // -> 255.0
strtod(str, nil)               // -> 255.0
CFStringGetDoubleValue(str)    // -> 0.0
(str as NSString).doubleValue  // -> 0.0

How to check if running in Cygwin, Mac or Linux?

I guess the uname answer is unbeatable, mainly in terms of cleanliness.

Although it takes a ridiculous time to execute, I found that testing for specific files presence also gives me good and quicker results, since I'm not invoking an executable:

So,

[ -f /usr/bin/cygwin1.dll ] && echo Yep, Cygwin running

just uses a quick Bash file presence check. As I'm on Windows right now, I can't tell you any specific files for Linuxes and Mac OS X from my head, but I'm pretty sure they do exist. :-)

How to check the input is an integer or not in Java?

        String input = "";
        int inputInteger = 0;
        BufferedReader br    = new BufferedReader(new InputStreamReader (System.in));

        System.out.println("Enter the radious: ");
        try {
            input = br.readLine();
            inputInteger = Integer.parseInt(input);
        } catch (NumberFormatException e) {
            System.out.println("Please Enter An Integer");
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        float area = (float) (3.14*inputInteger*inputInteger);
        System.out.println("Area = "+area);

javac option to compile all java files under a given directory recursively

javac command does not follow a recursive compilation process, so you have either specify each directory when running command, or provide a text file with directories you want to include:

javac -classpath "${CLASSPATH}" @java_sources.txt

How do I push to GitHub under a different username?

git add .
git commit -m "initial commit"
git config --local credential.helper ""
git push https://github.com/youraccount/repo.git --all

After this push command, a username password prompt will be opened.

jQuery to remove an option from drop down list, given option's text/value

Many people had difficulty in using this keyword when we have iteration of Drop-downs with same elements but different values or say as Multi line data in USER INTERFACE. : Here is the code snippet : $(this).find('option[value=yourvalue]');

Hope you got this.

Batch File: ( was unexpected at this time

You are getting that error because when the param1 if statements are evaluated, param is always null due to being scoped variables without delayed expansion.

When parentheses are used, all the commands and variables within those parentheses are expanded. And at that time, param1 has no value making the if statements invalid. When using delayed expansion, the variables are only expanded when the command is actually called.

Also I recommend using if not defined command to determine if a variable is set.

@echo off
setlocal EnableExtensions EnableDelayedExpansion
cls
title ~USB Wizard~
echo What do you want to do?
echo 1.Enable/Disable USB Storage Devices.
echo 2.Enable/Disable Writing Data onto USB Storage.
echo 3.~Yet to come~.

set "a=%globalparam1%"
goto :aCheck
:aPrompt
set /p "a=Enter Choice: "
:aCheck
if not defined a goto :aPrompt
echo %a%

IF "%a%"=="2" (
    title USB WRITE LOCK
    echo What do you want to do?
    echo 1.Apply USB Write Protection
    echo 2.Remove USB Write Protection

    ::param1
    set "param1=%globalparam2%"
    goto :param1Check
    :param1Prompt
    set /p "param1=Enter Choice: "
    :param1Check
    if not defined param1 goto :param1Prompt
    echo !param1!

    if "!param1!"=="1" (
        REG ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\StorageDevicePolicies\ /v WriteProtect /t REG_DWORD /d 00000001 
        echo USB Write is Locked!
    )
    if "!param1!"=="2" (
        REG ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\StorageDevicePolicies\ /v WriteProtect /t REG_DWORD /d 00000000
        echo USB Write is Unlocked! 
    )
)
pause
endlocal

SQLSTATE[HY000] [1698] Access denied for user 'root'@'localhost'

These steps worked for me on several Systems using Ubuntu 16.04, Apache 2.4, MariaDB, PDO

  1. log into MYSQL as root

    mysql -u root
    
  2. Grant privileges. To a new user execute:

    CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password';
    GRANT ALL PRIVILEGES ON *.* TO 'newuser'@'localhost';
    FLUSH PRIVILEGES;
    

    UPDATE for Google Cloud Instances

    MySQL on Google Cloud seem to require an alternate command (mind the backticks).

    GRANT ALL PRIVILEGES ON `%`.* TO 'newuser'@'localhost';
    
  3. bind to all addresses:

    The easiest way is to comment out the line in your /etc/mysql/mariadb.conf.d/50-server.cnf or /etc/mysql/mysql.conf.d/mysqld.cnf file, depending on what system you are running:

    #bind-address = 127.0.0.1 
    
  4. exit mysql and restart mysql

    exit
    service mysql restart
    

By default it binds only to localhost, but if you comment the line it binds to all interfaces it finds. Commenting out the line is equivalent to bind-address=*.

To check the binding of mysql service execute as root:

netstat -tupan | grep mysql

How to set a Javascript object values dynamically?

You could also create something that would be similar to a value object (vo);

SomeModelClassNameVO.js;

function SomeModelClassNameVO(name,id) {
    this.name = name;
    this.id = id;
}

Than you can just do;

   var someModelClassNameVO = new someModelClassNameVO('name',1);
   console.log(someModelClassNameVO.name);

Textfield with only bottom border

Probably a duplicate of this post: A customized input text box in html/html5

_x000D_
_x000D_
input {_x000D_
  border: 0;_x000D_
  outline: 0;_x000D_
  background: transparent;_x000D_
  border-bottom: 1px solid black;_x000D_
}
_x000D_
<input></input>
_x000D_
_x000D_
_x000D_

WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

The exception indicates a problem with the unobtrusive JavaScript validation mode. This issue is not Sitefinity specific and occurs in any standard ASP.NET applications when the project targets .NET 4.5 framework and the pre-4.5 validation is not enabled in the web.config file.

Open the web.config file and make sure that there is a ValidationSettings:UnobtrusiveValidationMode in the app settings:

<appSettings>
  <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>

How to write a PHP ternary operator

Since this would be a common task I would suggest wrapping a switch/case inside of a function call.

function getVocationName($vocation){
    switch($vocation){
        case 1: return "Sorcerer";
        case 2: return 'Druid';
        case 3: return 'Paladin';
        case 4: return 'Knight';
        case 5: return 'Master Sorcerer';
        case 6: return 'Elder Druid';
        case 7: return 'Royal Paladin';
        default: return 'Elite Knight';
    }
}

echo getVocationName($result->vocation);

Recursively counting files in a Linux directory

Since filenames in UNIX may contain newlines (yes, newlines), wc -l might count too many files. I would print a dot for every file and then count the dots:

find DIR_NAME -type f -printf "." | wc -c

XML serialization in Java?

Worth mentioning that since version 1.4, Java had the classes java.beans.XMLEncoder and java.beans.XMLDecoder. These classes perform XML encoding which is at least very comparable to XML Serialization and in some circumstances might do the trick for you.

If your class sticks to the JavaBeans specification for its getters and setters, this method is straightforward to use and you don't need a schema. With the following caveats:

  • As with normal Java serialization
    • coding and decoding run over a InputStream and OutputStream
    • the process uses the familar writeObject and readObject methods
  • In contrast to normal Java serialization
    • the encoding but also decoding causes constructors and initializers to be invoked
    • encoding and decoding work regardless if your class implements Serializable or not
    • transient modifiers are not taken into account
    • works only for public classes, that have public constructors

For example, take the following declaration:

public class NPair {
  public NPair() { }
  int number1 = 0;
  int number2 = 0;
  public void setNumber1(int value) { number1 = value;}
  public int getNumber1() { return number1; }
  public void setNumber2(int value) { number2 = value; }
  public int getNumber2() {return number2;}
}

Executing this code:

NPair fe = new NPair();
fe.setNumber1(12);
fe.setNumber2(13);
FileOutputStream fos1 = new FileOutputStream("d:\\ser.xml");
java.beans.XMLEncoder xe1 = new java.beans.XMLEncoder(fos1);
xe1.writeObject(fe);
xe1.close();

Would result in the following file:

<?xml version="1.0" encoding="UTF-8"?>
<java version="1.7.0_02" class="java.beans.XMLDecoder">
 <object class="NPair">
  <void property="number1">
   <int>12</int>
  </void>
  <void property="number2">
   <int>13</int>
  </void>
 </object>
</java>

How to include header files in GCC search path?

Try gcc -c -I/home/me/development/skia sample.c.

How to find difference between two Joda-Time DateTimes in minutes

Something like...

Minutes.minutesBetween(getStart(), getEnd()).getMinutes();

Inserting a string into a list without getting split into characters

You have to add another list:

list[:0]=['foo']

What's the shebang/hashbang (#!) in Facebook and new Twitter URLs for?

I always assumed the ! just indicated that the hash fragment that followed corresponded to a URL, with ! taking the place of the site root or domain. It could be anything, in theory, but it seems the Google AJAX Crawling API likes it this way.

The hash, of course, just indicates that no real page reload is occurring, so yes, it’s for AJAX purposes. Edit: Raganwald does a lovely job explaining this in more detail.

how to convert an RGB image to numpy array?

load the image by using following syntax:-

from keras.preprocessing import image

X_test=image.load_img('four.png',target_size=(28,28),color_mode="grayscale"); #loading image and then convert it into grayscale and with it's target size 
X_test=image.img_to_array(X_test); #convert image into array

Global variables in c#.net

I second jdk's answer: any public static member of any class of your application can be considered as a "global variable".

However, do note that this is an ASP.NET application, and as such, it's a multi-threaded context for your global variables. Therefore, you should use some locking mechanism when you update and/or read the data to/from these variables. Otherwise, you might get your data in a corrupted state.

How to grep Git commit diffs or contents for a certain word?

One more way/syntax to do it is: git log -S "word"
Like this you can search for example git log -S "with whitespaces and stuff @/#ü !"

jQuery .css("margin-top", value) not updating in IE 8 (Standards mode)

The correct format for IE8 is:

  $("#ActionBox").css({ 'margin-top': '10px' });  

with this work.

Recursion in Python? RuntimeError: maximum recursion depth exceeded while calling a Python object

That's the error you get when a function makes too many recursive calls to itself. It might be doing this because the base case is never met (and therefore it gets stuck in an infinite loop) or just by making an large number of calls to itself. You could replace the recursive calls with while loops.

How to fix "Incorrect string value" errors?

If you happen to process the value with some string function before saving, make sure the function can properly handle multibyte characters. String functions that cannot do that and are, say, attempting to truncate might split one of the single multibyte characters in the middle, and that can cause such string error situations.

In PHP for instance, you would need to switch from substr to mb_substr.

How to handle windows file upload using Selenium WebDriver?

Double the backslashes in the path, like this:

driver.findElement(browsebutton).sendKeys("C:\\Users\\Desktop\\Training\\Training.jpg");

<ng-container> vs <template>

The documentation (https://angular.io/guide/template-syntax#!#star-template) gives the following example. Say we have template code like this:

<hero-detail *ngIf="currentHero" [hero]="currentHero"></hero-detail>

Before it will be rendered, it will be "de-sugared". That is, the asterix notation will be transcribed to the notation:

<template [ngIf]="currentHero">
  <hero-detail [hero]="currentHero"></hero-detail>
</template>

If 'currentHero' is truthy this will be rendered as

<hero-detail> [...] </hero-detail>

But what if you want an conditional output like this:

<h1>Title</h1><br>
<p>text</p>

.. and you don't want the output be wrapped in a container.

You could write the de-sugared version directly like so:

<template [ngIf]="showContent">
  <h1>Title</h1>
  <p>text</p><br>
</template>

And this will work fine. However, now we need ngIf to have brackets [] instead of an asterix *, and this is confusing (https://github.com/angular/angular.io/issues/2303)

For that reason a different notation was created, like so:

<ng-container *ngIf="showContent"><br>
  <h1>Title</h1><br>
  <p>text</p><br>
</ng-container>

Both versions will produce the same results (only the h1 and p tag will be rendered). The second one is preferred because you can use *ngIf like always.

spring autowiring with unique beans: Spring expected single matching bean but found 2

If I'm not mistaken, the default bean name of a bean declared with @Component is the name of its class its first letter in lower-case. This means that

@Component
public class SuggestionService {

declares a bean of type SuggestionService, and of name suggestionService. It's equivalent to

@Component("suggestionService")
public class SuggestionService {

or to

<bean id="suggestionService" .../>

You're redefining another bean of the same type, but with a different name, in the XML:

<bean id="SuggestionService" class="com.hp.it.km.search.web.suggestion.SuggestionService">
    ...
</bean>

So, either specify the name of the bean in the annotation to be SuggestionService, or use the ID suggestionService in the XML (don't forget to also modify the <ref> element, or to remove it, since it isn't needed). In this case, the XML definition will override the annotation definition.

windows batch file rename

Use REN Command

Ren is for rename

ren ( where the file is located ) ( the new name )

example

ren C:\Users\&username%\Desktop\aaa.txt bbb.txt

it will change aaa.txt to bbb.txt

Your code will be :

ren (file located)AAA_a001.jpg a001.AAA.jpg

ren (file located)BBB_a002.jpg a002.BBB.jpg

ren (file located)CCC_a003.jpg a003.CCC.jpg

and so on

IT WILL NOT WORK IF THERE IS SPACES!

Hope it helps :D

How to include another XHTML in XHTML using JSF 2.0 Facelets?

<ui:include>

Most basic way is <ui:include>. The included content must be placed inside <ui:composition>.

Kickoff example of the master page /page.xhtml:

<!DOCTYPE html>
<html lang="en"
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://xmlns.jcp.org/jsf/core"
    xmlns:h="http://xmlns.jcp.org/jsf/html"
    xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
    <h:head>
        <title>Include demo</title>
    </h:head>
    <h:body>
        <h1>Master page</h1>
        <p>Master page blah blah lorem ipsum</p>
        <ui:include src="/WEB-INF/include.xhtml" />
    </h:body>
</html>

The include page /WEB-INF/include.xhtml (yes, this is the file in its entirety, any tags outside <ui:composition> are unnecessary as they are ignored by Facelets anyway):

<ui:composition 
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://xmlns.jcp.org/jsf/core"
    xmlns:h="http://xmlns.jcp.org/jsf/html"
    xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
    <h2>Include page</h2>
    <p>Include page blah blah lorem ipsum</p>
</ui:composition>
  

This needs to be opened by /page.xhtml. Do note that you don't need to repeat <html>, <h:head> and <h:body> inside the include file as that would otherwise result in invalid HTML.

You can use a dynamic EL expression in <ui:include src>. See also How to ajax-refresh dynamic include content by navigation menu? (JSF SPA).


<ui:define>/<ui:insert>

A more advanced way of including is templating. This includes basically the other way round. The master template page should use <ui:insert> to declare places to insert defined template content. The template client page which is using the master template page should use <ui:define> to define the template content which is to be inserted.

Master template page /WEB-INF/template.xhtml (as a design hint: the header, menu and footer can in turn even be <ui:include> files):

<!DOCTYPE html>
<html lang="en"
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://xmlns.jcp.org/jsf/core"
    xmlns:h="http://xmlns.jcp.org/jsf/html"
    xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
    <h:head>
        <title><ui:insert name="title">Default title</ui:insert></title>
    </h:head>
    <h:body>
        <div id="header">Header</div>
        <div id="menu">Menu</div>
        <div id="content"><ui:insert name="content">Default content</ui:insert></div>
        <div id="footer">Footer</div>
    </h:body>
</html>

Template client page /page.xhtml (note the template attribute; also here, this is the file in its entirety):

<ui:composition template="/WEB-INF/template.xhtml"
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://xmlns.jcp.org/jsf/core"
    xmlns:h="http://xmlns.jcp.org/jsf/html"
    xmlns:ui="http://xmlns.jcp.org/jsf/facelets">

    <ui:define name="title">
        New page title here
    </ui:define>

    <ui:define name="content">
        <h1>New content here</h1>
        <p>Blah blah</p>
    </ui:define>
</ui:composition>

This needs to be opened by /page.xhtml. If there is no <ui:define>, then the default content inside <ui:insert> will be displayed instead, if any.


<ui:param>

You can pass parameters to <ui:include> or <ui:composition template> by <ui:param>.

<ui:include ...>
    <ui:param name="foo" value="#{bean.foo}" />
</ui:include>
<ui:composition template="...">
    <ui:param name="foo" value="#{bean.foo}" />
    ...
</ui:composition >

Inside the include/template file, it'll be available as #{foo}. In case you need to pass "many" parameters to <ui:include>, then you'd better consider registering the include file as a tagfile, so that you can ultimately use it like so <my:tagname foo="#{bean.foo}">. See also When to use <ui:include>, tag files, composite components and/or custom components?

You can even pass whole beans, methods and parameters via <ui:param>. See also JSF 2: how to pass an action including an argument to be invoked to a Facelets sub view (using ui:include and ui:param)?


Design hints

The files which aren't supposed to be publicly accessible by just entering/guessing its URL, need to be placed in /WEB-INF folder, like as the include file and the template file in above example. See also Which XHTML files do I need to put in /WEB-INF and which not?

There doesn't need to be any markup (HTML code) outside <ui:composition> and <ui:define>. You can put any, but they will be ignored by Facelets. Putting markup in there is only useful for web designers. See also Is there a way to run a JSF page without building the whole project?

The HTML5 doctype is the recommended doctype these days, "in spite of" that it's a XHTML file. You should see XHTML as a language which allows you to produce HTML output using a XML based tool. See also Is it possible to use JSF+Facelets with HTML 4/5? and JavaServer Faces 2.2 and HTML5 support, why is XHTML still being used.

CSS/JS/image files can be included as dynamically relocatable/localized/versioned resources. See also How to reference CSS / JS / image resource in Facelets template?

You can put Facelets files in a reusable JAR file. See also Structure for multiple JSF projects with shared code.

For real world examples of advanced Facelets templating, check the src/main/webapp folder of Java EE Kickoff App source code and OmniFaces showcase site source code.

How can I exclude a directory from Visual Studio Code "Explore" tab?

There's this Explorer Exclude extension that exactly does this. https://marketplace.visualstudio.com/items?itemName=RedVanWorkshop.explorer-exclude-vscode-extension

It adds an option to hide current folder/file to the right click menu. It also adds a vertical tab Hidden Items to explorer menu where you can see currently hidden files & folders and can toggle them easily.


enter image description here

Double quotes within php script echo

You can just forgo the quotes for alphanumeric attributes:

echo "<font color=red> XHTML is not a thing anymore. </font>";
echo "<div class=editorial-note> There, I said it. </div>";

Is perfectly valid in HTML, and though still shunned, absolutely en vogue since HTML5.

CAVEATS

Simple way to sort strings in the (case sensitive) alphabetical order

If you don't want to add a dependency on Guava (per Michael's answer) then this comparator is equivalent:

private static Comparator<String> ALPHABETICAL_ORDER = new Comparator<String>() {
    public int compare(String str1, String str2) {
        int res = String.CASE_INSENSITIVE_ORDER.compare(str1, str2);
        if (res == 0) {
            res = str1.compareTo(str2);
        }
        return res;
    }
};

Collections.sort(list, ALPHABETICAL_ORDER);

And I think it is just as easy to understand and code ...

The last 4 lines of the method can written more concisely as follows:

        return (res != 0) ? res : str1.compareTo(str2);

How to add meta tag in JavaScript

Try

_x000D_
_x000D_
document.head.innerHTML += '<meta http-equiv="X-UA-..." content="IE=edge">'
_x000D_
_x000D_
_x000D_

How to ftp with a batch file?

You can use PowerShell as well; this is what I did. As I needed to download a file based on a pattern I dynamically created a command file and then let ftp do the rest.

I used basic PowerShell commands. I did not need to download any additional components. I first checked if the requisite number of files existed. If they I invoked the FTP the second time with an Mget. I run this from a Windows Server 2008 connecting to a Windows XP remote server.

function make_ftp_command_file($p_file_pattern,$mget_flag)
{
    # This function dynamically prepares the FTP file.
    # The file needs to be prepared daily because the
    # pattern changes daily.
    # PowerShell default encoding is Unicode.
    # Unicode command files are not compatible with FTP so
    # we need to make sure we create an ASCII file.

    write-output "USER" | out-file -filepath C:\fc.txt -encoding ASCII
    write-output "ftpusername" | out-file -filepath C:\fc.txt -encoding ASCII -Append
    write-output "password" | out-file -filepath C:\fc.txt -encoding ASCII -Append
    write-output "ASCII" | out-file -filepath C:\fc.txt -encoding ASCII -Append
    If ($mget_flag -eq "Y")
    {
        write-output "prompt" | out-file -filepath C:\fc.txt -encoding ASCII -Append
        write-output "mget $p_file_pattern" | out-file -filepath C:\fc.txt -encoding ASCII -Append
    }
    else
    {
        write-output "ls $p_file_pattern" | out-file -filepath C:\fc.txt -encoding ASCII -Append
    }

    write-output quit | out-file -filepath C:\fc.txt -encoding ASCII -Append
}


###########################  Init Section ###############################
$yesterday = (get-date).AddDays(-1)
$yesterday_fmt = date $yesterday -format "yyyyMMdd"
$file_pattern = "BRAE_GE_*" + $yesterday_fmt + "*.csv"
$file_log = $yesterday_fmt + ".log"

echo  $file_pattern
echo  $file_log


############################## Main Section ############################
# Change location to folder where the files need to be downloaded
cd c:\remotefiles

# Dynamically create the FTP Command to get a list of files from
# the remote servers
echo "Call function that creates a FTP Command "
make_ftp_command_file $file_pattern N


#echo "Connect to remote site via FTP"
# Connect to Remote Server and get file listing
ftp -n -v -s:C:\Clover\scripts\fc.txt 10.129.120.31 > C:\logs\$file_log

$matches=select-string -pattern "BRAE_GE_[A-Z][A-Z]*" C:\logs\$file_log

# Check if the required number of Files available for download
if ($matches.count -eq 36)
{
    # Create the FTP command file

    # This time the command file has an mget rather than an ls
    make_ftp_command_file $file_pattern Y

    # Change directory if not done so
    cd c:\remotefiles

    # Invoke ftp with newly created command file
    ftp -n -v -s:C:\Clover\scripts\fc.txt 10.129.120.31 > C:\logs\$file_log
}
else
{
    echo "The full set of files is not available"
}

auto create database in Entity Framework Core

If you want both of EnsureCreated and Migrate use this code:

     using (var context = new YourDbContext())
            {
                if (context.Database.EnsureCreated())
                {
                    //auto migration when database created first time

                    //add migration history table

                    string createEFMigrationsHistoryCommand = $@"
USE [{context.Database.GetDbConnection().Database}];
SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
CREATE TABLE [dbo].[__EFMigrationsHistory](
    [MigrationId] [nvarchar](150) NOT NULL,
    [ProductVersion] [nvarchar](32) NOT NULL,
 CONSTRAINT [PK___EFMigrationsHistory] PRIMARY KEY CLUSTERED 
(
    [MigrationId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY];
";
                    context.Database.ExecuteSqlRaw(createEFMigrationsHistoryCommand);

                    //insert all of migrations
                    var dbAssebmly = context.GetType().GetAssembly();
                    foreach (var item in dbAssebmly.GetTypes())
                    {
                        if (item.BaseType == typeof(Migration))
                        {
                            string migrationName = item.GetCustomAttributes<MigrationAttribute>().First().Id;
                            var version = typeof(Migration).Assembly.GetName().Version;
                            string efVersion = $"{version.Major}.{version.Minor}.{version.Build}";
                            context.Database.ExecuteSqlRaw("INSERT INTO __EFMigrationsHistory(MigrationId,ProductVersion) VALUES ({0},{1})", migrationName, efVersion);
                        }
                    }
                }
                context.Database.Migrate();
            }

run a python script in terminal without the python command

There are three parts:

  1. Add a 'shebang' at the top of your script which tells how to execute your script
  2. Give the script 'run' permissions.
  3. Make the script in your PATH so you can run it from anywhere.

Adding a shebang

You need to add a shebang at the top of your script so the shell knows which interpreter to use when parsing your script. It is generally:

#!path/to/interpretter

To find the path to your python interpretter on your machine you can run the command:

which python

This will search your PATH to find the location of your python executable. It should come back with a absolute path which you can then use to form your shebang. Make sure your shebang is at the top of your python script:

#!/usr/bin/python

Run Permissions

You have to mark your script with run permissions so that your shell knows you want to actually execute it when you try to use it as a command. To do this you can run this command:

chmod +x myscript.py

Add the script to your path

The PATH environment variable is an ordered list of directories that your shell will search when looking for a command you are trying to run. So if you want your python script to be a command you can run from anywhere then it needs to be in your PATH. You can see the contents of your path running the command:

echo $PATH

This will print out a long line of text, where each directory is seperated by a semicolon. Whenever you are wondering where the actual location of an executable that you are running from your PATH, you can find it by running the command:

which <commandname>

Now you have two options: Add your script to a directory already in your PATH, or add a new directory to your PATH. I usually create a directory in my user home directory and then add it the PATH. To add things to your path you can run the command:

export PATH=/my/directory/with/pythonscript:$PATH

Now you should be able to run your python script as a command anywhere. BUT! if you close the shell window and open a new one, the new one won't remember the change you just made to your PATH. So if you want this change to be saved then you need to add that command at the bottom of your .bashrc or .bash_profile

What is the difference between 'E', 'T', and '?' for Java generics?

The most commonly used type parameter names are:

E - Element (used extensively by the Java Collections Framework)
K - Key
N - Number
T - Type
V - Value
S,U,V etc. - 2nd, 3rd, 4th types

You'll see these names used throughout the Java SE API

What is reflection and why is it useful?

Not every language supports reflection, but the principles are usually the same in languages that support it.

Reflection is the ability to "reflect" on the structure of your program. Or more concrete. To look at the objects and classes you have and programmatically get back information on the methods, fields, and interfaces they implement. You can also look at things like annotations.

It's useful in a lot of situations. Everywhere you want to be able to dynamically plug in classes into your code. Lots of object relational mappers use reflection to be able to instantiate objects from databases without knowing in advance what objects they're going to use. Plug-in architectures is another place where reflection is useful. Being able to dynamically load code and determine if there are types there that implement the right interface to use as a plugin is important in those situations.

Get the system date and split day, month and year

You can split date month year from current date as follows:

DateTime todaysDate = DateTime.Now.Date;

Day:

int day = todaysDate.Day;

Month:

int month = todaysDate.Month;

Year:

int year = todaysDate.Year;

Javascript: Call a function after specific time period

Execute function FetchData() once after 1000 milliseconds:

setTimeout(FetchData,1000);

Execute function FetchData() repeatedly every 1000 milliseconds:

setInterval(FetchData,1000);

How do I convert an integer to binary in JavaScript?

A solution i'd go with that's fine for 32-bits, is the code the end of this answer, which is from developer.mozilla.org(MDN), but with some lines added for A)formatting and B)checking that the number is in range.

Some suggested x.toString(2) which doesn't work for negatives, it just sticks a minus sign in there for them, which is no good.

Fernando mentioned a simple solution of (x>>>0).toString(2); which is fine for negatives, but has a slight issue when x is positive. It has the output starting with 1, which for positive numbers isn't proper 2s complement.

Anybody that doesn't understand the fact of positive numbers starting with 0 and negative numbers with 1, in 2s complement, could check this SO QnA on 2s complement. What is “2's Complement”?

A solution could involve prepending a 0 for positive numbers, which I did in an earlier revision of this answer. And one could accept sometimes having a 33bit number, or one could make sure that the number to convert is within range -(2^31)<=x<2^31-1. So the number is always 32bits. But rather than do that, you can go with this solution on mozilla.org

Patrick's answer and code is long and apparently works for 64-bit, but had a bug that a commenter found, and the commenter fixed patrick's bug, but patrick has some "magic number" in his code that he didn't comment about and has forgotten about and patrick no longer fully understands his own code / why it works.

Annan had some incorrect and unclear terminology but mentioned a solution by developer.mozilla.org https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators This works for 32-bit numbers.

The code is pretty compact, a function of three lines.

But I have added a regex to format the output in groups of 8 bits. Based on How to print a number with commas as thousands separators in JavaScript (I just amended it from grouping it in 3s right to left and adding commas, to grouping in 8s right to left, and adding spaces)

And, while mozilla made a comment about the size of nMask(the number fed in)..that it has to be in range, they didn't test for or throw an error when the number is out of range, so i've added that.

I'm not sure why they named their parameter 'nMask' but i'll leave that as is.

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators

_x000D_
_x000D_
function createBinaryString(nMask) {_x000D_
  // nMask must be between -2147483648 and 2147483647_x000D_
  if (nMask > 2**31-1) _x000D_
     throw "number too large. number shouldn't be > 2**31-1"; //added_x000D_
  if (nMask < -1*(2**31))_x000D_
     throw "number too far negative, number shouldn't be < 2**31" //added_x000D_
  for (var nFlag = 0, nShifted = nMask, sMask = ''; nFlag < 32;_x000D_
       nFlag++, sMask += String(nShifted >>> 31), nShifted <<= 1);_x000D_
  sMask=sMask.replace(/\B(?=(.{8})+(?!.))/g, " ") // added_x000D_
  return sMask;_x000D_
}_x000D_
_x000D_
_x000D_
console.log(createBinaryString(-1))    // "11111111 11111111 11111111 11111111"_x000D_
console.log(createBinaryString(1024))  // "00000000 00000000 00000100 00000000"_x000D_
console.log(createBinaryString(-2))    // "11111111 11111111 11111111 11111110"_x000D_
console.log(createBinaryString(-1024)) // "11111111 11111111 11111100 00000000"
_x000D_
_x000D_
_x000D_

push() a two-dimensional array

You have some errors in your code:

  1. Use myArray[i].push( 0 ); to add a new column. Your code (myArray[i][j].push(0);) would work in a 3-dimensional array as it tries to add another element to an array at position [i][j].
  2. You only expand (col-d)-many columns in all rows, even in those, which haven't been initialized yet and thus have no entries so far.

One correct, although kind of verbose version, would be the following:

var r = 3; //start from rows 3

var rows = 8;
var cols = 7;

// expand to have the correct amount or rows
for( var i=r; i<rows; i++ ) {
  myArray.push( [] );
}

// expand all rows to have the correct amount of cols
for (var i = 0; i < rows; i++)
{
    for (var j =  myArray[i].length; j < cols; j++)
    {
        myArray[i].push(0);
    }
}

Bootstrap 4 File Input

Solution based on @Elnoor answer, but working with multiple file upload form input and without the "fakepath hack":

HTML:

<div class="custom-file">
    <input id="logo" type="file" class="custom-file-input" multiple>
    <label for="logo" class="custom-file-label text-truncate">Choose file...</label>
</div>

JS:

$('input[type="file"]').on('change', function () {
    let filenames = [];
    let files = document.getElementById('health_claim_file_form_files').files;

    for (let i in files) {
        if (files.hasOwnProperty(i)) {
            filenames.push(files[i].name);
        }
    }

    $(this).next('.custom-file-label').addClass("selected").html(filenames.join(',    '));
});

Android: How to overlay a bitmap and draw over a bitmap?

If the purpose is to obtain a bitmap, this is very simple:

Canvas canvas = new Canvas();
canvas.setBitmap(image);
canvas.drawBitmap(image2, new Matrix(), null);

In the end, image will contain the overlap of image and image2.

Get the string value from List<String> through loop for display

As I understand your question..

From Java List class you have to methods add(E e) and get(int position).

add(E e)

Appends the specified element to the end of this list (optional operation).

get(int index)

Returns the element at the specified position in this list.

Example:

List<String> myString = new ArrayList<String>();

// How you add your data in string list
myString.add("Test 1");
myString.add("Test 2");
myString.add("Test 3");
myString.add("Test 4");

// retrieving data from string list array in for loop
for (int i=0;i < myString.size();i++)
{
  Log.i("Value of element "+i,myString.get(i));
}

But efficient way to iterate thru loop

for (String value : myString)
{
  Log.i("Value of element ",value);
}

Difference between __getattr__ vs __getattribute__

In reading through Beazley & Jones PCB, I have stumbled on an explicit and practical use-case for __getattr__ that helps answer the "when" part of the OP's question. From the book:

"The __getattr__() method is kind of like a catch-all for attribute lookup. It's a method that gets called if code tries to access an attribute that doesn't exist." We know this from the above answers, but in PCB recipe 8.15, this functionality is used to implement the delegation design pattern. If Object A has an attribute Object B that implements many methods that Object A wants to delegate to, rather than redefining all of Object B's methods in Object A just to call Object B's methods, define a __getattr__() method as follows:

def __getattr__(self, name):
    return getattr(self._b, name)

where _b is the name of Object A's attribute that is an Object B. When a method defined on Object B is called on Object A, the __getattr__ method will be invoked at the end of the lookup chain. This would make code cleaner as well, since you do not have a list of methods defined just for delegating to another object.

No connection string named 'MyEntities' could be found in the application config file

As you surmise, it is to do with the connection string being in app.config of the class library.

Copy the entry from the class app.config to the container's app.config or web.config file

Check/Uncheck checkbox with JavaScript

I would like to note, that setting the 'checked' attribute to a non-empty string leads to a checked box.

So if you set the 'checked' attribute to "false", the checkbox will be checked. I had to set the value to the empty string, null or the boolean value false in order to make sure the checkbox was not checked.

Encoding as Base64 in Java

In Java 8 it can be done as: Base64.getEncoder().encodeToString(string.getBytes(StandardCharsets.UTF_8))

Here is a short, self-contained complete example:

import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class Temp {
    public static void main(String... args) throws Exception {
        final String s = "old crow medicine show";
        final byte[] authBytes = s.getBytes(StandardCharsets.UTF_8);
        final String encoded = Base64.getEncoder().encodeToString(authBytes);
        System.out.println(s + " => " + encoded);
    }
}

Output:

old crow medicine show => b2xkIGNyb3cgbWVkaWNpbmUgc2hvdw==

How to make an element in XML schema optional?

Try this

<xs:element name="description" type="xs:string" minOccurs="0" maxOccurs="1" />

if you want 0 or 1 "description" elements, Or

<xs:element name="description" type="xs:string" minOccurs="0" maxOccurs="unbounded" />

if you want 0 to infinity number of "description" elements.

How to reenable event.preventDefault?

With async actions (timers, ajax) you can override the property isDefaultPrevented like this:

$('a').click(function(evt){
  e.preventDefault();

  // in async handler (ajax/timer) do these actions:
  setTimeout(function(){
    // override prevented flag to prevent jquery from discarding event
    evt.isDefaultPrevented = function(){ return false; }
    // retrigger with the exactly same event data
    $(this).trigger(evt);
  }, 1000);
}

This is most complete way of retriggering the event with the exactly same data.

How to upload a file from Windows machine to Linux machine using command lines via PuTTy?

Use putty. Put install directory path in environment values (PATH), and restart your PC if required.

Open cmd (command prompt) and type

C:/> pscp "C:\Users/gsjha/Desktop/example.txt" user@host:/home/

It'll be copied to the system.

What is the precise meaning of "ours" and "theirs" in git?

I suspect you're confused here because it's fundamentally confusing. To make things worse, the whole ours/theirs stuff switches roles (becomes backwards) when you are doing a rebase.

Ultimately, during a git merge, the "ours" branch refers to the branch you're merging into:

git checkout merge-into-ours

and the "theirs" branch refers to the (single) branch you're merging:

git merge from-theirs

and here "ours" and "theirs" makes some sense, as even though "theirs" is probably yours anyway, "theirs" is not the one you were on when you ran git merge.

While using the actual branch name might be pretty cool, it falls apart in more complex cases. For instance, instead of the above, you might do:

git checkout ours
git merge 1234567

where you're merging by raw commit-ID. Worse, you can even do this:

git checkout 7777777    # detach HEAD
git merge 1234567       # do a test merge

in which case there are no branch names involved!

I think it's little help here, but in fact, in gitrevisions syntax, you can refer to an individual path in the index by number, during a conflicted merge

git show :1:README
git show :2:README
git show :3:README

Stage #1 is the common ancestor of the files, stage #2 is the target-branch version, and stage #3 is the version you are merging from.


The reason the "ours" and "theirs" notions get swapped around during rebase is that rebase works by doing a series of cherry-picks, into an anonymous branch (detached HEAD mode). The target branch is the anonymous branch, and the merge-from branch is your original (pre-rebase) branch: so "--ours" means the anonymous one rebase is building while "--theirs" means "our branch being rebased".


As for the gitattributes entry: it could have an effect: "ours" really means "use stage #2" internally. But as you note, it's not actually in place at the time, so it should not have an effect here ... well, not unless you copy it into the work tree before you start.

Also, by the way, this applies to all uses of ours and theirs, but some are on a whole file level (-s ours for a merge strategy; git checkout --ours during a merge conflict) and some are on a piece-by-piece basis (-X ours or -X theirs during a -s recursive merge). Which probably does not help with any of the confusion.

I've never come up with a better name for these, though. And: see VonC's answer to another question, where git mergetool introduces yet more names for these, calling them "local" and "remote"!

R adding days to a date

Just use

 as.Date("2001-01-01") + 45

from base R, or date functionality in one of the many contributed packages. My RcppBDT package wraps functionality from Boost Date_Time including things like 'date of third Wednesday' in a given month.

Edit: And egged on by @Andrie, here is a bit more from RcppBDT (which is mostly a test case for Rcpp modules, really).

R> library(RcppBDT)
Loading required package: Rcpp
R> 
R> str(bdt)
Reference class 'Rcpp_date' [package ".GlobalEnv"] with 0 fields
 and 42 methods, of which 31 are possibly relevant:
   addDays, finalize, fromDate, getDate, getDay, getDayOfWeek, getDayOfYear, 
   getEndOfBizWeek, getEndOfMonth, getFirstDayOfWeekAfter,
   getFirstDayOfWeekInMonth, getFirstOfNextMonth, getIMMDate, getJulian, 
   getLastDayOfWeekBefore, getLastDayOfWeekInMonth, getLocalClock, getModJulian,
   getMonth, getNthDayOfWeek, getUTC, getWeekNumber, getYear, initialize, 
   setEndOfBizWeek, setEndOfMonth, setFirstOfNextMonth, setFromLocalClock,
   setFromUTC, setIMMDate, subtractDays
R> bdt$fromDate( as.Date("2001-01-01") )
R> bdt$addDays( 45 )
R> print(bdt)
[1] "2001-02-15"
R> 

Table Naming Dilemma: Singular vs. Plural Names

As others have mentioned here, conventions should be a tool for adding to the ease of use and readability. Not as a shackle or a club to torture developers.

That said, my personal preference is to use singular names for both tables and columns. This probably comes from my programming background. Class names are generally singular unless they are some sort of collection. In my mind I am storing or reading individual records in the table in question, so singular makes sense to me.

This practice also allows me to reserve plural table names for those that store many-to-many relationships between my objects.

I try to avoid reserved words in my table and column names, as well. In the case in question here it makes more sense to go counter to the singular convention for Users to avoid the need to encapsulate a table that uses the reserved word of User.

I like using prefixes in a limited manner (tbl for table names, sp_ for proc names, etc), though many believe this adds clutter. I also prefer CamelBack names to underscores because I always end up hitting the + instead of _ when typing the name. Many others disagree.

Here is another good link for naming convention guidelines: http://www.xaprb.com/blog/2008/10/26/the-power-of-a-good-sql-naming-convention/

Remember that the most important factor in your convention is that it make sense to the people interacting with the database in question. There is no "One Ring to Rule Them All" when it comes to naming conventions.

-XX:MaxPermSize with or without -XX:PermSize

If you're doing some performance tuning it's often recommended to set both -XX:PermSize and -XX:MaxPermSize to the same value to increase JVM efficiency.

Here is some information:

  1. Support for large page heap on x86 and amd64 platforms
  2. Java Support for Large Memory Pages
  3. Setting the Permanent Generation Size

You can also specify -XX:+CMSClassUnloadingEnabled to enable class unloading option if you are using CMS GC. It may help to decrease the probability of Java.lang.OutOfMemoryError: PermGen space

How to drop SQL default constraint without knowing its name?

Useful for some columns that had multiple default constraints or check constraints created:

Modified https://stackoverflow.com/a/16359095/206730 script

Note: this script is for sys.check_constraints

declare @table_name nvarchar(128)
declare @column_name nvarchar(128)
declare @constraint_name nvarchar(128)
declare @constraint_definition nvarchar(512)

declare @df_name nvarchar(128)
declare @cmd nvarchar(128) 

PRINT 'DROP CONSTRAINT [Roles2016.UsersCRM].Estado'

declare constraints cursor for 
 select t.name TableName, c.name ColumnName, d.name ConstraintName, d.definition ConstraintDefinition
 from sys.tables t   
 join sys.check_constraints d  on d.parent_object_id = t.object_id  
 join sys.columns c  on c.object_id = t.object_id      
 and c.column_id = d.parent_column_id
 where t.name = N'Roles2016.UsersCRM' and c.name = N'Estado'

open constraints
fetch next from constraints into @table_name , @column_name, @constraint_name, @constraint_definition
while @@fetch_status = 0
BEGIN
    print 'CONSTRAINT: ' + @constraint_name
    select @cmd = 'ALTER TABLE [' + @table_name +  '] DROP CONSTRAINT [' +  @constraint_name + ']'
    print @cmd
    EXEC sp_executeSQL @cmd;

  fetch next from constraints into @table_name , @column_name, @constraint_name, @constraint_definition
END

close constraints 
deallocate constraints

Android - SMS Broadcast receiver

Your broadcast receiver must specify android:exported="true" to receive broadcasts created outside your own application. My broadcast receiver is defined in the manifest as follows:

<receiver
    android:name=".IncomingSmsBroadcastReceiver"
    android:enabled="true"
    android:exported="true" >
    <intent-filter>
        <action android:name="android.provider.Telephony.SMS_RECEIVED" />
    </intent-filter>
</receiver>

As noted below, exported="true" is the default, so you can omit this line. I've left it in so that the discussion comments make sense.

AngularJS : Initialize service with asynchronous data

I had the same problem: I love the resolve object, but that only works for the content of ng-view. What if you have controllers (for top-level nav, let's say) that exist outside of ng-view and which need to be initialized with data before the routing even begins to happen? How do we avoid mucking around on the server-side just to make that work?

Use manual bootstrap and an angular constant. A naiive XHR gets you your data, and you bootstrap angular in its callback, which deals with your async issues. In the example below, you don't even need to create a global variable. The returned data exists only in angular scope as an injectable, and isn't even present inside of controllers, services, etc. unless you inject it. (Much as you would inject the output of your resolve object into the controller for a routed view.) If you prefer to thereafter interact with that data as a service, you can create a service, inject the data, and nobody will ever be the wiser.

Example:

//First, we have to create the angular module, because all the other JS files are going to load while we're getting data and bootstrapping, and they need to be able to attach to it.
var MyApp = angular.module('MyApp', ['dependency1', 'dependency2']);

// Use angular's version of document.ready() just to make extra-sure DOM is fully 
// loaded before you bootstrap. This is probably optional, given that the async 
// data call will probably take significantly longer than DOM load. YMMV.
// Has the added virtue of keeping your XHR junk out of global scope. 
angular.element(document).ready(function() {

    //first, we create the callback that will fire after the data is down
    function xhrCallback() {
        var myData = this.responseText; // the XHR output

        // here's where we attach a constant containing the API data to our app 
        // module. Don't forget to parse JSON, which `$http` normally does for you.
        MyApp.constant('NavData', JSON.parse(myData));

        // now, perform any other final configuration of your angular module.
        MyApp.config(['$routeProvider', function ($routeProvider) {
            $routeProvider
              .when('/someroute', {configs})
              .otherwise({redirectTo: '/someroute'});
          }]);

        // And last, bootstrap the app. Be sure to remove `ng-app` from your index.html.
        angular.bootstrap(document, ['NYSP']);
    };

    //here, the basic mechanics of the XHR, which you can customize.
    var oReq = new XMLHttpRequest();
    oReq.onload = xhrCallback;
    oReq.open("get", "/api/overview", true); // your specific API URL
    oReq.send();
})

Now, your NavData constant exists. Go ahead and inject it into a controller or service:

angular.module('MyApp')
    .controller('NavCtrl', ['NavData', function (NavData) {
        $scope.localObject = NavData; //now it's addressable in your templates 
}]);

Of course, using a bare XHR object strips away a number of the niceties that $http or JQuery would take care of for you, but this example works with no special dependencies, at least for a simple get. If you want a little more power for your request, load up an external library to help you out. But I don't think it's possible to access angular's $http or other tools in this context.

(SO related post)

Is there a Python caching library?

Try redis, it is one of the cleanest and easiest solutions for applications to share data in a atomic way or if you have got some web server platform. Its very easy to setup, you will need a python redis client http://pypi.python.org/pypi/redis

What is the difference between char * const and const char *?

I remember from Czech book about C: read the declaration that you start with the variable and go left. So for

char * const a;

you can read as: "a is variable of type constant pointer to char",

char const * a;

you can read as: "a is a pointer to constant variable of type char. I hope this helps.

Bonus:

const char * const a;

You will read as a is constant pointer to constant variable of type char.

Pytorch reshape tensor dimension

Assume the following code:

import torch
import numpy as np
a = torch.tensor([1, 2, 3, 4, 5])

The following three calls have the exact same effect:

res_1 = a.unsqueeze(0)
res_2 = a.view(1, 5)
res_3 = a[np.newaxis,:]
res_1.shape == res_2.shape == res_3.shape == (1,5)  # Returns true

Notice that for any of the resulting tensors, if you modify the data in them, you are also modifying the data in a, because they don't have a copy of the data, but reference the original data in a.

res_1[0,0] = 2
a[0] == res_1[0,0] == 2  # Returns true

The other way of doing it would be using the resize_ in place operation:

a.shape == res_1.shape  # Returns false
a.reshape_((1, 5))
a.shape == res_1.shape # Returns true

Be careful of using resize_ or other in-place operation with autograd. See the following discussion: https://pytorch.org/docs/stable/notes/autograd.html#in-place-operations-with-autograd

Print a variable in hexadecimal in Python

Use

print " ".join("0x%s"%my_string[i:i+2] for i in range(0, len(my_string), 2))

like this:

>>> my_string = "deadbeef"
>>> print " ".join("0x%s"%my_string[i:i+2] for i in range(0, len(my_string), 2))
0xde 0xad 0xbe 0xef
>>>

On an unrelated side note ... using string as a variable name even as an example variable name is very bad practice.

iframe to Only Show a Certain Part of the Page

<div style="border: 2px solid #D5CC5A; overflow: hidden; margin: 15px auto; max-width: 575px;">

Read contents of a local file into a variable in Rails

I think you should consider using IO.binread("/path/to/file") if you have a recent ruby interpreter (i.e. >= 1.9.2)

You could find IO class documentation here http://www.ruby-doc.org/core-2.1.2/IO.html

How to show all rows by default in JQuery DataTable

Use:

$('#example').dataTable({
    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]
    ],
    iDisplayLength: -1
});

Or if using 1.10+

$('#example').dataTable({
    paging: false
});

The option you should use is iDisplayLength:

$('#adminProducts').dataTable({
  'iDisplayLength': 100
});

$('#table').DataTable({
   "lengthMenu": [ [5, 10, 25, 50, -1], [5, 10, 25, 50, "All"] ]
});

It will Load by default all entries.

$('#example').dataTable({
    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]
    ],
    iDisplayLength: -1
});

Or if using 1.10+

$('#example').dataTable({
    paging: false
});

If you want to load by default 25 not all do this.

$('#example').dataTable({
    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]
    ],
});

Very simple log4j2 XML configuration file using Console and File appender

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
        </Console>
        <File name="MyFile" fileName="all.log" immediateFlush="false" append="false">
            <PatternLayout pattern="%d{yyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
        </File>
    </Appenders>
    <Loggers>
        <Root level="debug">
            <AppenderRef ref="Console" />
            <AppenderRef ref="MyFile"/>
        </Root>
    </Loggers>
</Configuration>

Notes:

  • Put the following content in your configuration file.
  • Name the configuration file log4j2.xml
  • Put the log4j2.xml in a folder which is in the class-path (i.e. your source folder "src")
  • Use Logger logger = LogManager.getLogger(); to initialize your logger
  • I did set the immediateFlush="false" since this is better for SSD lifetime. If you need the log right away in your log-file remove the parameter or set it to true

How to make a simple popup box in Visual C#?

In Visual Studio 2015 (community edition), System.Windows.Forms is not available and hence we can't use MessageBox.Show("text").

Use this Instead:

var Msg = new MessageDialog("Some String here", "Title of Message Box");    
await Msg.ShowAsync();

Note: Your function must be defined async to use above await Msg.ShowAsync().

How do I ignore files in Subversion?

You can also set a global ignore pattern in SVN's configuration file.

Convert NVARCHAR to DATETIME in SQL Server 2008

what about this

--// Convert NVARCHAR to DATETIME
DECLARE @date DATETIME = (SELECT convert(DATETIME, '2013-08-29 13:55:48', 120))
--// Convert DATETIME to custom NVARCHAR FORMAT
SELECT 
RIGHT('00'+ CAST(DAY(@date) AS NVARCHAR),2) + '-' +
RIGHT('00'+ CAST(MONTH(@date) AS NVARCHAR),2) + '-' + 
CAST(YEAR(@date) AS NVARCHAR) + ' ' + 
CAST(CONVERT(TIME,@date) AS NVARCHAR)

result: '29-08-2013 13:55:48.0000000'

How to pass multiple parameters from ajax to mvc controller?

  var data = JSON.stringify
            ({
            'StrContactDetails': Details,
            'IsPrimary': true
            })

What is the difference between <p> and <div>?

<p> represents a paragraph and <div> represents a 'division', I suppose the main difference is that divs are semantically 'meaningless', where as a <p> is supposed to represent something relating to the text itself.

You wouldn't want to have nested <p>s for example, since that wouldn't make much semantic sense (except in the sense of quotations) Whereas people use nested <div>s for page layout.

According to Wikipedia

In HTML, the span and div elements are used where parts of a document cannot be semantically described by other HTML elements.

importing jar libraries into android-studio

If the code for your jar library is on GitHub then importing into Android Studio is easy with JitPack.

Your will just need to add the repository to build.gradle:

allprojects{
 repositories {
    jcenter()
    maven { url "https://jitpack.io" }
 }
}

and then the library's GitHub repository as a dependency:

dependencies {
    // ...
    compile 'com.github.YourUsername:LibraryRepo:ReleaseTag'
}

JitPack acts as a maven repository and can be used like Maven Central. The nice thing is that you don't have to upload the jar manually. Behind the scenes JitPack will check out the code from GitHub and compile it. Therefore it works only if the repo has a build file in it (build.gradle).

There is also a guide on how to prepare an Android project.

TypeError: Can't convert 'int' object to str implicitly

You cannot concatenate a string with an int. You would need to convert your int to a string using the str function, or use formatting to format your output.

Change: -

print("Ok. Your balance is now at " + balanceAfterStrength + " skill points.")

to: -

print("Ok. Your balance is now at {} skill points.".format(balanceAfterStrength))

or: -

print("Ok. Your balance is now at " + str(balanceAfterStrength) + " skill points.")

or as per the comment, use , to pass different strings to your print function, rather than concatenating using +: -

print("Ok. Your balance is now at ", balanceAfterStrength, " skill points.")

How to use npm with node.exe?

Search all .npmrc file in your system.

Please verify that the path you have given is correct. If not please remove the incorrect path.

Formatting struct timespec

You can pass the tv_sec parameter to some of the formatting function. Have a look at gmtime, localtime(). Then look at snprintf.

Parse an URL in JavaScript

This should fix a few edge-cases in kobe's answer:

function getQueryParam(url, key) {
  var queryStartPos = url.indexOf('?');
  if (queryStartPos === -1) {
    return;
  }
  var params = url.substring(queryStartPos + 1).split('&');
  for (var i = 0; i < params.length; i++) {
    var pairs = params[i].split('=');
    if (decodeURIComponent(pairs.shift()) == key) {
      return decodeURIComponent(pairs.join('='));
    }
  }
}

getQueryParam('http://example.com/form_image_edit.php?img_id=33', 'img_id');
// outputs "33"

Using python's mock patch.object to change the return value of a method called within another method

There are two ways you can do this; with patch and with patch.object

Patch assumes that you are not directly importing the object but that it is being used by the object you are testing as in the following

#foo.py
def some_fn():
    return 'some_fn'

class Foo(object):
    def method_1(self):
        return some_fn()
#bar.py
import foo
class Bar(object):
    def method_2(self):
        tmp = foo.Foo()
        return tmp.method_1()
#test_case_1.py
import bar
from mock import patch

@patch('foo.some_fn')
def test_bar(mock_some_fn):
    mock_some_fn.return_value = 'test-val-1'
    tmp = bar.Bar()
    assert tmp.method_2() == 'test-val-1'
    mock_some_fn.return_value = 'test-val-2'
    assert tmp.method_2() == 'test-val-2'

If you are directly importing the module to be tested, you can use patch.object as follows:

#test_case_2.py
import foo
from mock import patch

@patch.object(foo, 'some_fn')
def test_foo(test_some_fn):
    test_some_fn.return_value = 'test-val-1'
    tmp = foo.Foo()
    assert tmp.method_1() == 'test-val-1'
    test_some_fn.return_value = 'test-val-2'
    assert tmp.method_1() == 'test-val-2'

In both cases some_fn will be 'un-mocked' after the test function is complete.

Edit: In order to mock multiple functions, just add more decorators to the function and add arguments to take in the extra parameters

@patch.object(foo, 'some_fn')
@patch.object(foo, 'other_fn')
def test_foo(test_other_fn, test_some_fn):
    ...

Note that the closer the decorator is to the function definition, the earlier it is in the parameter list.

MySQL fails on: mysql "ERROR 1524 (HY000): Plugin 'auth_socket' is not loaded"

You can try these some steps:

Stop Mysql Service 1st sudo /etc/init.d/mysql stop

Login as root without password sudo mysqld_safe --skip-grant-tables &

After login mysql terminal you should need execute commands more:

use mysql;

UPDATE mysql.user SET authentication_string=PASSWORD('solutionclub3@*^G'), plugin='mysql_native_password' WHERE User='root';

flush privileges;

sudo mysqladmin -u root -p -S /var/run/mysqld/mysqld.sock shutdown

After you restart your mysql server If you still facing error you must visit : Reset MySQL 5.7 root password Ubuntu 16.04

ES6 exporting/importing in index file

Simply:

// Default export (recommended)
export {default} from './MyClass' 

// Default export with alias
export {default as d1} from './MyClass' 

// In >ES7, it could be
export * from './MyClass'

// In >ES7, with alias
export * as d1 from './MyClass'

Or by functions names :

// export by function names
export { funcName1, funcName2, …} from './MyClass'

// export by aliases
export { funcName1 as f1, funcName2 as f2, …} from './MyClass'

More infos: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export

Read binary file as string in Ruby

how about some open/close safety.

string = File.open('file.txt', 'rb') { |file| file.read }

Xcode 9 error: "iPhone has denied the launch request"

Just tick "Automatically manage signing" in General -> Signing properties of the Target. It will create Development provisioning profile for you and running on the device will work.

How to update TypeScript to latest version with npm?

Open command prompt (cmd.exe/git bash)

Recommended:

npm install -g typescript@latest

or

yarn global add typescript@latest  // if you use yarn package manager

This will install the latest typescript version if not already installed, otherwise it will update the current installation to the latest version.

And then verify which version is installed:

tsc -v

enter image description here


If you have typescript already installed you could also use the following command to update to latest version, but as commentators have reported and I confirm it that the following command does not update to latest (as of now [ Feb 10 '17])!

npm update -g typescript@latest

libclntsh.so.11.1: cannot open shared object file.

For the benefit of anyone else coming here by far the best thing to do is to update cx_Oracle to the latest version (6+). This version does not need LD_LIBRARY_PATH set at all.

How to format strings in Java

Take a look at String.format. Note, however, that it takes format specifiers similar to those of C's printf family of functions -- for example:

String.format("Hello %s, %d", "world", 42);

Would return "Hello world, 42". You may find this helpful when learning about the format specifiers. Andy Thomas-Cramer was kind enough to leave this link in a comment below, which appears to point to the official spec. The most commonly used ones are:

  • %s - insert a string
  • %d - insert a signed integer (decimal)
  • %f - insert a real number, standard notation

This is radically different from C#, which uses positional references with an optional format specifier. That means that you can't do things like:

String.format("The {0} is repeated again: {0}", "word");

... without actually repeating the parameter passed to printf/format. (see The Scrum Meister's comment below)


If you just want to print the result directly, you may find System.out.printf (PrintStream.printf) to your liking.

How do I install Python 3 on an AWS EC2 instance?

On Debian derivatives such as Ubuntu, use apt. Check the apt repository for the versions of Python available to you. Then, run a command similar to the following, substituting the correct package name:

sudo apt-get install python3

On Red Hat and derivatives, use yum. Check the yum repository for the versions of Python available to you. Then, run a command similar to the following, substituting the correct package name:

sudo yum install python36

On SUSE and derivatives, use zypper. Check the repository for the versions of Python available to you. Then. run a command similar to the following, substituting the correct package name:

sudo zypper install python3