Programs & Examples On #Cx freeze

cx_Freeze is a set of scripts and modules for freezing Python scripts (.py) into executable files for Windows (.exe), Mac OS (.app), or Linux.

How do I use cx_freeze?

I'm really not sure what you're doing to get that error, it looks like you're trying to run cx_Freeze on its own, without arguments. So here is a short step-by-step guide on how to do it in windows (Your screenshot looks rather like the windows command line, so I'm assuming that's your platform)

  1. Write your setup.py file. Your script above looks correct so it should work, assuming that your script exists.

  2. Open the command line (Start -> Run -> "cmd")

  3. Go to the location of your setup.py file and run python setup.py build

Notes:

  1. There may be a problem with the name of your script. "Main.py" contains upper case letters, which might cause confusion since windows' file names are not case sensitive, but python is. My approach is to always use lower case for scripts to avoid any conflicts.

  2. Make sure that python is on your PATH (read http://docs.python.org/using/windows.html)1

  3. Make sure are are looking at the new cx_Freeze documentation. Google often seems to bring up the old docs.

Using Regular Expressions to Extract a Value in Java

Pattern p = Pattern.compile("(\\D+)(\\d+)(.*)");
Matcher m = p.matcher("this is your number:1234 thank you");
if (m.find()) {
    String someNumberStr = m.group(2);
    int someNumberInt = Integer.parseInt(someNumberStr);
}

How to use matplotlib tight layout with Figure?

Just call fig.tight_layout() as you normally would. (pyplot is just a convenience wrapper. In most cases, you only use it to quickly generate figure and axes objects and then call their methods directly.)

There shouldn't be a difference between the QtAgg backend and the default backend (or if there is, it's a bug).

E.g.

import matplotlib.pyplot as plt

#-- In your case, you'd do something more like:
# from matplotlib.figure import Figure
# fig = Figure()
#-- ...but we want to use it interactive for a quick example, so 
#--    we'll do it this way
fig, axes = plt.subplots(nrows=4, ncols=4)

for i, ax in enumerate(axes.flat, start=1):
    ax.set_title('Test Axes {}'.format(i))
    ax.set_xlabel('X axis')
    ax.set_ylabel('Y axis')

plt.show()

Before Tight Layout

enter image description here

After Tight Layout

import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=4, ncols=4)

for i, ax in enumerate(axes.flat, start=1):
    ax.set_title('Test Axes {}'.format(i))
    ax.set_xlabel('X axis')
    ax.set_ylabel('Y axis')

fig.tight_layout()

plt.show()

enter image description here

How to properly use unit-testing's assertRaises() with NoneType objects?

Complete snippet would look like the following. It expands @mouad's answer to asserting on error's message (or generally str representation of its args), which may be useful.

from unittest import TestCase


class TestNoneTypeError(TestCase):

  def setUp(self): 
    self.testListNone = None

  def testListSlicing(self):
    with self.assertRaises(TypeError) as ctx:
        self.testListNone[:1]
    self.assertEqual("'NoneType' object is not subscriptable", str(ctx.exception))

Simple JavaScript login form validation

<!DOCTYPE html>
<html>
<head>
<script>
function vali() {
var u=document.forms["myform"]["user"].value;
var p=document.forms["myform"]["pwd"].value;
if(u == p) {
alert("Welcome");
window.location="sec.html";
return false;
}
else
{
alert("Please Try again!");
return false;
}
}
</script>
</head>
<body>
<form method="post">
<fieldset style="width:35px;">  <legend>Login Here</legend>
<input type="text" name="user" placeholder="Username" required>
<br>
<input type="Password" name="pwd" placeholder="Password" required>
<br>
<input type="submit" name="submit" value="submit" onclick="return vali()">
</form>
</fieldset>
</html>

Getting text from td cells with jQuery

You can use .map: http://jsfiddle.net/9ndcL/1/.

// array of text of each td

var texts = $("td").map(function() {
    return $(this).text();
});

Is it possible to get the index you're sorting over in Underscore.js?

More generally, under most circumstances, underscore functions that take a list and argument as the first two arguments, provide access to the list index as the next to last argument to the iterator. This is an important distinction when it comes to the two underscore functions, _.reduce and _.reduceRight, that take 'memo' as their third argument -- in the case of these two the index will not be the second argument, but the third:

var destination = (function() {
    var fields = ['_333st', 'offroad', 'fbi'];
    return _.reduce(waybillInfo.destination.split(','), function(destination, segment, index) {
        destination[fields[index]] = segment;
        return destination;
    }, {});
})();

console.log(destination);            
/*
_333st: "NYARFTW  TX"
fbi: "FTWUP"
offroad: "UP"

The following is better of course but not demonstrate my point:
var destination = _.object(['_333st', 'offroad', 'fbi'], waybillInfo.destination.split(','));
*/

So if you wanted you could get the index using underscore itself: _.last(_.initial(arguments)). A possible exception (I haven't tried) is _.map, as it can take an object instead of a list: "If list is a JavaScript object, iterator's arguments will be (value, key, list)." -- see: http://underscorejs.org/#map

WebSocket with SSL

1 additional caveat (besides the answer by kanaka/peter): if you use WSS, and the server certificate is not acceptable to the browser, you may not get any browser rendered dialog (like it happens for Web pages). This is because WebSockets is treated as a so-called "subresource", and certificate accept / security exception / whatever dialogs are not rendered for subresources.

how to display progress while loading a url to webview in android?

Check out the sample code. It help you.

 private ProgressBar progressBar;
 progressBar=(ProgressBar)findViewById(R.id.webloadProgressBar);
 WebView urlWebView= new WebView(Context);
    urlWebView.setWebViewClient(new AppWebViewClients(progressBar));
                        urlWebView.getSettings().setJavaScriptEnabled(true);
                        urlWebView.loadUrl(detailView.getUrl());

public class AppWebViewClients extends WebViewClient {
     private ProgressBar progressBar;

    public AppWebViewClients(ProgressBar progressBar) {
        this.progressBar=progressBar;
        progressBar.setVisibility(View.VISIBLE);
    }
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        // TODO Auto-generated method stub
        view.loadUrl(url);
        return true;
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        // TODO Auto-generated method stub
        super.onPageFinished(view, url);
        progressBar.setVisibility(View.GONE);
    }
}

Thanks.

Error: request entity too large

I've used another practice for this problem with multer dependancie.

Example:

multer = require('multer');

var uploading = multer({
  limits: {fileSize: 1000000, files:1},
});

exports.uploadpictureone = function(req, res) {
  cloudinary.uploader.upload(req.body.url, function(result) {
    res.send(result);
  });
};

module.exports = function(app) {
    app.route('/api/upload', uploading).all(uploadPolicy.isAllowed)
        .post(upload.uploadpictureone);
};

SQL Case Sensitive String Compare

You Can easily Convert columns to VARBINARY(Max Length), The length must be the maximum you expect to avoid defective comparison, It's enough to set length as the column length. Trim column help you to compare the real value except space has a meaning and valued in your table columns, This is a simple sample and as you can see I Trim the columns value and then convert and compare.:

CONVERT(VARBINARY(250),LTRIM(RTRIM(Column1))) = CONVERT(VARBINARY(250),LTRIM(RTRIM(Column2)))

Hope this help.

How to convert float to varchar in SQL Server

This can help without rounding

declare @test float(25)

declare @test1 decimal(10,5)

select @test = 34.0387597207
select @test
set @test1 = convert (decimal(10,5), @test)
select cast((@test1) as varchar(12))


Select  LEFT(cast((@test1) as varchar(12)),LEN(cast((@test1) as varchar(12)))-1)

How to write a file or data to an S3 object using boto3

You may use the below code to write, for example an image to S3 in 2019. To be able to connect to S3 you will have to install AWS CLI using command pip install awscli, then enter few credentials using command aws configure:

import urllib3
import uuid
from pathlib import Path
from io import BytesIO
from errors import custom_exceptions as cex

BUCKET_NAME = "xxx.yyy.zzz"
POSTERS_BASE_PATH = "assets/wallcontent"
CLOUDFRONT_BASE_URL = "https://xxx.cloudfront.net/"


class S3(object):
    def __init__(self):
        self.client = boto3.client('s3')
        self.bucket_name = BUCKET_NAME
        self.posters_base_path = POSTERS_BASE_PATH

    def __download_image(self, url):
        manager = urllib3.PoolManager()
        try:
            res = manager.request('GET', url)
        except Exception:
            print("Could not download the image from URL: ", url)
            raise cex.ImageDownloadFailed
        return BytesIO(res.data)  # any file-like object that implements read()

    def upload_image(self, url):
        try:
            image_file = self.__download_image(url)
        except cex.ImageDownloadFailed:
            raise cex.ImageUploadFailed

        extension = Path(url).suffix
        id = uuid.uuid1().hex + extension
        final_path = self.posters_base_path + "/" + id
        try:
            self.client.upload_fileobj(image_file,
                                       self.bucket_name,
                                       final_path
                                       )
        except Exception:
            print("Image Upload Error for URL: ", url)
            raise cex.ImageUploadFailed

        return CLOUDFRONT_BASE_URL + id

Git - What is the difference between push.default "matching" and "simple"

From GIT documentation: Git Docs

Below gives the full information. In short, simple will only push the current working branch and even then only if it also has the same name on the remote. This is a very good setting for beginners and will become the default in GIT 2.0

Whereas matching will push all branches locally that have the same name on the remote. (Without regard to your current working branch ). This means potentially many different branches will be pushed, including those that you might not even want to share.

In my personal usage, I generally use a different option: current which pushes the current working branch, (because I always branch for any changes). But for a beginner I'd suggest simple

push.default
Defines the action git push should take if no refspec is explicitly given. Different values are well-suited for specific workflows; for instance, in a purely central workflow (i.e. the fetch source is equal to the push destination), upstream is probably what you want. Possible values are:

nothing - do not push anything (error out) unless a refspec is explicitly given. This is primarily meant for people who want to avoid mistakes by always being explicit.

current - push the current branch to update a branch with the same name on the receiving end. Works in both central and non-central workflows.

upstream - push the current branch back to the branch whose changes are usually integrated into the current branch (which is called @{upstream}). This mode only makes sense if you are pushing to the same repository you would normally pull from (i.e. central workflow).

simple - in centralized workflow, work like upstream with an added safety to refuse to push if the upstream branch's name is different from the local one.

When pushing to a remote that is different from the remote you normally pull from, work as current. This is the safest option and is suited for beginners.

This mode will become the default in Git 2.0.

matching - push all branches having the same name on both ends. This makes the repository you are pushing to remember the set of branches that will be pushed out (e.g. if you always push maint and master there and no other branches, the repository you push to will have these two branches, and your local maint and master will be pushed there).

To use this mode effectively, you have to make sure all the branches you would push out are ready to be pushed out before running git push, as the whole point of this mode is to allow you to push all of the branches in one go. If you usually finish work on only one branch and push out the result, while other branches are unfinished, this mode is not for you. Also this mode is not suitable for pushing into a shared central repository, as other people may add new branches there, or update the tip of existing branches outside your control.

This is currently the default, but Git 2.0 will change the default to simple.

Determining the last row in a single column

Old thread but I have found a simple way that seems to work

ws.getRange("A2").getNextDataCell(SpreadsheetApp.Direction.DOWN).getLastRow()

How to set image for bar button with swift?

If your UIBarButtonItem is already allocated like in a storyboard. (printBtn)

    let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
    btn.setImage(UIImage(named: Constants.ImageName.print)?.withRenderingMode(.alwaysTemplate), for: .normal)
    btn.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handlePrintPress(tapGesture:))))
    printBtn.customView = btn

How do I fill arrays in Java?

Check out the Arrays.fill methods.

int[] array = new int[4];
Arrays.fill(array, 0);

Java: convert seconds to minutes, hours and days

Have a look at the class

org.joda.time.DateTime

This allows you to do things like:

old = new DateTime();
new = old.plusSeconds(500000);
System.out.println("Hours: " + (new.Hours() - old.Hours()));

However, your solution probably can be simpler:

You need to work out how many seconds in a day, divide your input by the result to get the days, and subtract it from the input to keep the remainder. You then need to work out how many hours in the remainder, followed by the minutes, and the final remainder is the seconds.

This is the analysis done for you, now you can focus on the code.

You need to ask what s/he means by "no hard coding", generally it means pass parameters, rather than fixing the input values. There are many ways to do this, depending on how you run your code. Properties are a common way in java.

How to query for Xml values and attributes from table in SQL Server?

Actually you're close to your goal, you just need to use nodes() method to split your rows and then get values:

select
    s.SqmId,
    m.c.value('@id', 'varchar(max)') as id,
    m.c.value('@type', 'varchar(max)') as type,
    m.c.value('@unit', 'varchar(max)') as unit,
    m.c.value('@sum', 'varchar(max)') as [sum],
    m.c.value('@count', 'varchar(max)') as [count],
    m.c.value('@minValue', 'varchar(max)') as minValue,
    m.c.value('@maxValue', 'varchar(max)') as maxValue,
    m.c.value('.', 'nvarchar(max)') as Value,
    m.c.value('(text())[1]', 'nvarchar(max)') as Value2
from sqm as s
    outer apply s.data.nodes('Sqm/Metrics/Metric') as m(c)

sql fiddle demo

How to declare local variables in postgresql?

Postgresql historically doesn't support procedural code at the command level - only within functions. However, in Postgresql 9, support has been added to execute an inline code block that effectively supports something like this, although the syntax is perhaps a bit odd, and there are many restrictions compared to what you can do with SQL Server. Notably, the inline code block can't return a result set, so can't be used for what you outline above.

In general, if you want to write some procedural code and have it return a result, you need to put it inside a function. For example:

CREATE OR REPLACE FUNCTION somefuncname() RETURNS int LANGUAGE plpgsql AS $$
DECLARE
  one int;
  two int;
BEGIN
  one := 1;
  two := 2;
  RETURN one + two;
END
$$;
SELECT somefuncname();

The PostgreSQL wire protocol doesn't, as far as I know, allow for things like a command returning multiple result sets. So you can't simply map T-SQL batches or stored procedures to PostgreSQL functions.

Java equivalent to JavaScript's encodeURIComponent that produces identical output?

I have successfully used the java.net.URI class like so:

public static String uriEncode(String string) {
    String result = string;
    if (null != string) {
        try {
            String scheme = null;
            String ssp = string;
            int es = string.indexOf(':');
            if (es > 0) {
                scheme = string.substring(0, es);
                ssp = string.substring(es + 1);
            }
            result = (new URI(scheme, ssp, null)).toString();
        } catch (URISyntaxException usex) {
            // ignore and use string that has syntax error
        }
    }
    return result;
}

Search an array for matching attribute

Must be too late now, but the right version would be:

for(var i = 0; i < restaurants.restaurant.length; i++)
{
  if(restaurants.restaurant[i].food == 'chicken')
  {
    return restaurants.restaurant[i].name;
  }
}

nodeJS - How to create and read session with express

Steps I did:

  1. Include the angular-cookies.js file in the HTML!
  2. Init cookies as being NOT http-only in server-side app.'s:

    app.configure(function(){
       //a bunch of stuff
       app.use(express.cookieSession({secret: 'mySecret', store: store, cookie: cookieSettings}));```
    
  3. Then in client-side services.jss I put ['ngCookies'] in like this:

    angular.module('swrp', ['ngCookies']).//etc

  4. Then in controller.js, in my function UserLoginCtrl, I have $cookies in there with $scope at the top like so:

    function UserLoginCtrl($scope, $cookies, socket) {

  5. Lastly, to get the value of a cookie inside the controller function I did:

    var mySession = $cookies['connect.sess'];

Now you can send that back to the server from the client. Awesome. Wish they would've put this in the Angular.js documentation. I figured it out by just reading the actual code for angular-cookies.js directly.

How to get a variable name as a string in PHP?

You could use get_defined_vars() to find the name of a variable that has the same value as the one you're trying to find the name of. Obviously this will not always work, since different variables often have the same values, but it's the only way I can think of to do this.

Edit: get_defined_vars() doesn't seem to be working correctly, it returns 'var' because $var is used in the function itself. $GLOBALS seems to work so I've changed it to that.

function print_var_name($var) {
    foreach($GLOBALS as $var_name => $value) {
        if ($value === $var) {
            return $var_name;
        }
    }

    return false;
}

Edit: to be clear, there is no good way to do this in PHP, which is probably because you shouldn't have to do it. There are probably better ways of doing what you're trying to do.

How to check if a windows form is already open, and close it if it is?

this will word definitely. i use this function for myself as well.

  public static bool isFormOpen(Form formm)
    {

        foreach (Form OpenForm in Application.OpenForms)
        {
            if (OpenForm.Name == formm.Name)
            {
                return true;
            }
        }

        return false;
    }

Synchronously waiting for an async operation, and why does Wait() freeze the program here

Here is what I did

private void myEvent_Handler(object sender, SomeEvent e)
{
  // I dont know how many times this event will fire
  Task t = new Task(() =>
  {
    if (something == true) 
    {
        DoSomething(e);  
    }
  });
  t.RunSynchronously();
}

working great and not blocking UI thread

Update a submodule to the latest commit

My project should use the 'latest' for the submodule. On Mac OSX 10.11, git version 2.7.1, I did not need to go 'into' my submodule folder in order to collect its commits. I merely did a regular

git pull --rebase 

at the top level, and it correctly updated my submodule.

How to convert a string to an integer in JavaScript?

Here is the easiest solution

let myNumber = "123" | 0;

More easy solution

let myNumber = +"123";

Listen to changes within a DIV and act accordingly

If possible you can change the div to an textarea and use .change().

Another solution could be use a hidden textarea and update the textarea same time as you update the div. Then use .change() on the hidden textarea.

You can also use http://www.jacklmoore.com/autosize/ to make the text area act more like a div.

<style>
.hidden{
display:none
}
</style>

<textarea class="hidden" rows="4" cols="50">

</textarea>


$("#hiddentextarea").change(function() {

alert('Textarea changed');

})

Update: It seems like textarea has to be defocused after updated, for more info: How do I set up a listener in jQuery/javascript to monitor a if a value in the textbox has changed?

Integer division: How do you produce a double?

Just add "D".

int i = 6;
double d = i / 2D; // This will divide bei double.
System.out.println(d); // This will print a double. = 3D

How to reload apache configuration for a site without restarting apache?

If you are using Ubuntu server, you can use systemctl

systemctl reload apache2

Error: The processing instruction target matching "[xX][mM][lL]" is not allowed

in my case was a wrong path in a config file: file was not found (path was wrong) and it came out with this exception:

Error configuring from input stream. Initial cause was The processing instruction target matching "[xX][mM][lL]" is not allowed.

sorting dictionary python 3

I like python numpy for this kind of stuff! eg:

r=readData()
nsorted = np.lexsort((r.calls, r.slow_requests, r.very_slow_requests, r.stalled_requests))

I have an example of importing CSV data into a numpy and ordering by column priorities. https://github.com/unixunion/toolbox/blob/master/python/csv-numpy.py

Kegan

Does MySQL ignore null values on unique constraints?

I am unsure if the author originally was just asking whether or not this allows duplicate values or if there was an implied question here asking, "How to allow duplicate NULL values while using UNIQUE?" Or "How to only allow one UNIQUE NULL value?"

The question has already been answered, yes you can have duplicate NULL values while using the UNIQUE index.

Since I stumbled upon this answer while searching for "how to allow one UNIQUE NULL value." For anyone else who may stumble upon this question while doing the same, the rest of my answer is for you...

In MySQL you can not have one UNIQUE NULL value, however you can have one UNIQUE empty value by inserting with the value of an empty string.

Warning: Numeric and types other than string may default to 0 or another default value.

Nexus 7 (2013) and Win 7 64 - cannot install USB driver despite checking many forums and online resources

SkipSoft.net has some great toolkits. I ran into a similar problem with my Galaxy Nexus.... Ran the corresponding toolkit, which configured my system and downloaded the correct drivers. I then went into Windows Hardware manager after connecting the phone... Windows reported the exclamation that it couldn't find the device driver, so I ran update, and gave it the drivers directory the toolkit had created... and everything started working great. Hope this helps :)

Fixed position but relative to container

2019 SOLUTION: You can use position: sticky property.

Here is an example CODEPEN demonstrating the usage and also how it differs from position: fixed.

How it behaves is explained below:

  1. An element with sticky position is positioned based on the user's scroll position. It basically acts like position: relative until an element is scrolled beyond a specific offset, in which case it turns into position: fixed. When it is scrolled back it gets back to its previous (relative) position.

  2. It effects the flow of other elements in the page ie occupies a specific space on the page(just like position: relative).

  3. If it is defined inside some container, it is positioned with respect to that container. If the container has some overflow(scroll), depending on the scroll offset it turns into position:fixed.

So if you want to achieve the fixed functionality but inside a container, use sticky.

Reset Windows Activation/Remove license key

On Windows XP -

  1. Reboot into "Safe mode with Command Prompt"
  2. Type "explorer" in the command prompt that comes up and push [Enter]
  3. Click on Start>Run, and type the following :

    rundll32.exe syssetup,SetupOobeBnk

Reboot, and login as normal.

This will reset the 30 day timer for activation back to 30 days so you can enter in the key normally.

How can I create an editable dropdownlist in HTML?

A combobox is unfortunately something that was left out of the HTML specifications.

The only way to manage it, rather unfortunately, is to roll your own or use a pre-built one. This one looks quite simple. I use this one for an open-source app although unfortunately you have to pay for commercial usage.

Visual Studio - How to change a project's folder name and solution name without breaking the solution

You could open the SLN file in any text editor (Notepad, etc.) and simply change the project path there.

C++ inheritance - inaccessible base?

You have to do this:

class Bar : public Foo
{
    // ...
}

The default inheritance type of a class in C++ is private, so any public and protected members from the base class are limited to private. struct inheritance on the other hand is public by default.

How can get the text of a div tag using only javascript (no jQuery)

Actually you dont need to call document.getElementById() function to get access to your div.

You can use this object directly by id:

text = test.textContent || test.innerText;
alert(text);

How to click a link whose href has a certain substring in Selenium?

use driver.findElement(By.partialLinkText("long")).click();

Choosing the default value of an Enum type without having to change values

If zero doesn't work as the proper default value, you can use the component model to define a workaround for the enum:

[DefaultValue(None)]
public enum Orientation
{
     None = -1,
     North = 0,
     East = 1,
     South = 2,
     West = 3
 }

public static class Utilities
{
    public static TEnum GetDefaultValue<TEnum>() where TEnum : struct
    {
        Type t = typeof(TEnum);
        DefaultValueAttribute[] attributes = (DefaultValueAttribute[])t.GetCustomAttributes(typeof(DefaultValueAttribute), false);
        if (attributes != null &&
            attributes.Length > 0)
        {
            return (TEnum)attributes[0].Value;
        }
        else
        {
            return default(TEnum);
        }
    }
}

and then you can call:

Orientation o = Utilities.GetDefaultValue<Orientation>();
System.Diagnostics.Debug.Print(o.ToString());

Note: you will need to include the following line at the top of the file:

using System.ComponentModel;

This does not change the actual C# language default value of the enum, but gives a way to indicate (and get) the desired default value.

Implementing two interfaces in a class with same method. Which interface method is overridden?

Well if they are both the same it doesn't matter. It implements both of them with a single concrete method per interface method.

Spring Resttemplate exception handling

You should catch a HttpStatusCodeException exception:

try {
    restTemplate.exchange(...);
} catch (HttpStatusCodeException exception) {
    int statusCode = exception.getStatusCode().value();
    ...
}

How to run a python script from IDLE interactive shell?

To run a python script in a python shell such as Idle or in a Django shell you can do the following using the exec() function. Exec() executes a code object argument. A code object in Python is simply compiled Python code. So you must first compile your script file and then execute it using exec(). From your shell:

>>>file_to_compile = open('/path/to/your/file.py').read()
>>>code_object = compile(file_to_compile, '<string>', 'exec')
>>>exec(code_object)

I'm using Python 3.4. See the compile and exec docs for detailed info.

How to declare an array of strings in C++?

Problems - no way to get the number of strings automatically (that i know of).

There is a bog-standard way of doing this, which lots of people (including MS) define macros like arraysize for:

#define arraysize(ar)  (sizeof(ar) / sizeof(ar[0]))

Bootstrap datetimepicker is not a function

Try to use datepicker/ timepicker instead of datetimepicker like:

replace:

$('#datetimepicker1').datetimepicker();

with:

$('#datetimepicker1').datepicker(); // or timepicker for time picker

How to convert a plain object into an ES6 Map?

Yes, the Map constructor takes an array of key-value pairs.

Object.entries is a new Object static method available in ES2017 (19.1.2.5).

const map = new Map(Object.entries({foo: 'bar'}));

map.get('foo'); // 'bar'

It's currently implemented in Firefox 46+ and Edge 14+ and newer versions of Chrome

If you need to support older environments and transpilation is not an option for you, use a polyfill, such as the one recommended by georg:

Object.entries = typeof Object.entries === 'function' ? Object.entries : obj => Object.keys(obj).map(k => [k, obj[k]]);

Endless loop in C/C++

Everyone seems to like while (true):

https://stackoverflow.com/a/224142/1508519

https://stackoverflow.com/a/1401169/1508519

https://stackoverflow.com/a/1401165/1508519

https://stackoverflow.com/a/1401164/1508519

https://stackoverflow.com/a/1401176/1508519

According to SLaks, they compile identically.

Ben Zotto also says it doesn't matter:

It's not faster. If you really care, compile with assembler output for your platform and look to see. It doesn't matter. This never matters. Write your infinite loops however you like.

In response to user1216838, here's my attempt to reproduce his results.

Here's my machine:

cat /etc/*-release
CentOS release 6.4 (Final)

gcc version:

Target: x86_64-unknown-linux-gnu
Thread model: posix
gcc version 4.8.2 (GCC)

And test files:

// testing.cpp
#include <iostream>

int main() {
    do { break; } while(1);
}

// testing2.cpp
#include <iostream>

int main() {
    while(1) { break; }
}

// testing3.cpp
#include <iostream>

int main() {
    while(true) { break; }
}

The commands:

gcc -S -o test1.asm testing.cpp
gcc -S -o test2.asm testing2.cpp
gcc -S -o test3.asm testing3.cpp

cmp test1.asm test2.asm

The only difference is the first line, aka the filename.

test1.asm test2.asm differ: byte 16, line 1

Output:

        .file   "testing2.cpp"
        .local  _ZStL8__ioinit
        .comm   _ZStL8__ioinit,1,1
        .text
        .globl  main
        .type   main, @function
main:
.LFB969:
        .cfi_startproc
        pushq   %rbp
        .cfi_def_cfa_offset 16
        .cfi_offset 6, -16
        movq    %rsp, %rbp
        .cfi_def_cfa_register 6
        nop
        movl    $0, %eax
        popq    %rbp
        .cfi_def_cfa 7, 8
        ret
        .cfi_endproc
.LFE969:
        .size   main, .-main
        .type   _Z41__static_initialization_and_destruction_0ii, @function
_Z41__static_initialization_and_destruction_0ii:
.LFB970:
        .cfi_startproc
        pushq   %rbp
        .cfi_def_cfa_offset 16
        .cfi_offset 6, -16
        movq    %rsp, %rbp
        .cfi_def_cfa_register 6
        subq    $16, %rsp
        movl    %edi, -4(%rbp)
        movl    %esi, -8(%rbp)
        cmpl    $1, -4(%rbp)
        jne     .L3
        cmpl    $65535, -8(%rbp)
        jne     .L3
        movl    $_ZStL8__ioinit, %edi
        call    _ZNSt8ios_base4InitC1Ev
        movl    $__dso_handle, %edx
        movl    $_ZStL8__ioinit, %esi
        movl    $_ZNSt8ios_base4InitD1Ev, %edi
        call    __cxa_atexit
.L3:
        leave
        .cfi_def_cfa 7, 8
        ret
        .cfi_endproc
.LFE970:
        .size   _Z41__static_initialization_and_destruction_0ii, .-_Z41__static_initialization_and_destruction_0ii
        .type   _GLOBAL__sub_I_main, @function
_GLOBAL__sub_I_main:
.LFB971:
        .cfi_startproc
        pushq   %rbp
        .cfi_def_cfa_offset 16
        .cfi_offset 6, -16
        movq    %rsp, %rbp
        .cfi_def_cfa_register 6
        movl    $65535, %esi
        movl    $1, %edi
        call    _Z41__static_initialization_and_destruction_0ii
        popq    %rbp
        .cfi_def_cfa 7, 8
        ret
        .cfi_endproc
.LFE971:
        .size   _GLOBAL__sub_I_main, .-_GLOBAL__sub_I_main
        .section        .ctors,"aw",@progbits
        .align 8
        .quad   _GLOBAL__sub_I_main
        .hidden __dso_handle
        .ident  "GCC: (GNU) 4.8.2"
        .section        .note.GNU-stack,"",@progbits

With -O3, the output is considerably smaller of course, but still no difference.

What's the difference between session.persist() and session.save() in Hibernate?

save()- As the method name suggests, hibernate save() can be used to save entity to database. We can invoke this method outside a transaction. If we use this without transaction and we have cascading between entities, then only the primary entity gets saved unless we flush the session.

persist()-Hibernate persist is similar to save (with transaction) and it adds the entity object to the persistent context, so any further changes are tracked. If the object properties are changed before the transaction is committed or session is flushed, it will also be saved into database. Also, we can use persist() method only within the boundary of a transaction, so it’s safe and takes care of any cascaded objects. Finally, persist doesn't return anything so we need to use the persisted object to get the generated identifier value.

How do you add an SDK to Android Studio?

I had to restart Android Studio for changing the sdk after installing a new one. Then Android Studio asked me for configuring my SDK and let me do it.

How to use Spring Boot with MySQL database and JPA?

Your code is in the default package, i.e. you have source all files in src/main/java with no custom package. I strongly suggest u to create package n then place your source file in it.

Ex-
 src->
     main->
          java->
                com.myfirst.example
                   Example.java
                com.myfirst.example.controller
                   PersonController.java
                com.myfirst.example.repository
                  PersonRepository.java
                com.myfirst.example.model
                   Person.java

I hope it will resolve your problem.

How to reset (clear) form through JavaScript?

Try this code. A complete solution for your answer.

    <!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $(":reset").css("background-color", "red");
});
</script>
</head>
<body>

<form action="">
  Name: <input type="text" name="user"><br>
  Password: <input type="password" name="password"><br>
  <button type="button">Useless Button</button>
  <input type="button" value="Another useless button"><br>
  <input type="reset" value="Reset">
  <input type="submit" value="Submit"><br>
</form>

</body>
</html>

How to toggle boolean state of react component?

Set: const [state, setState] = useState(1);

Toggle: setState(state*-1);

Use: state > 0 ? 'on' : 'off';

CSS3 transition events

Just for fun, don't do this!

$.fn.transitiondone = function () {
  return this.each(function () {
    var $this = $(this);
    setTimeout(function () {
      $this.trigger('transitiondone');
    }, (parseFloat($this.css('transitionDelay')) + parseFloat($this.css('transitionDuration'))) * 1000);
  });
};


$('div').on('mousedown', function (e) {
  $(this).addClass('bounce').transitiondone();
});

$('div').on('transitiondone', function () {
  $(this).removeClass('bounce');
});

How to POST JSON Data With PHP cURL?

Try this example.

<?php 
 $url = 'http://localhost/test/page2.php';
    $data = array("first_name" => "First name","last_name" => "last name","email"=>"[email protected]","addresses" => array ("address1" => "some address" ,"city" => "city","country" => "CA", "first_name" =>  "Mother","last_name" =>  "Lastnameson","phone" => "555-1212", "province" => "ON", "zip" => "123 ABC" ) );
    $ch=curl_init($url);
    $data_string = urlencode(json_encode($data));
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, array("customer"=>$data_string));


    $result = curl_exec($ch);
    curl_close($ch);

    echo $result;
?>

Your page2.php code

<?php
$datastring = $_POST['customer'];
$data = json_decode( urldecode( $datastring));

?>

Get size of a View in React Native

You can directly use the Dimensions module and calc your views sizes. Actually, Dimensions give to you the main window sizes.

import { Dimensions } from 'Dimensions';

Dimensions.get('window').height;
Dimensions.get('window').width;

Hope to help you!

Update: Today using native StyleSheet with Flex arranging on your views help to write clean code with elegant layout solutions in wide cases instead computing your view sizes...

Although building a custom grid components, which responds to main window resize events, could produce a good solution in simple widget components

Linker Command failed with exit code 1 (use -v to see invocation), Xcode 8, Swift 3

For me, the gem lock file was specifying an older version of cocoapods than the one I had installed. I had to re-branch and run bundle exec pod install instead of pod install

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

When you use @DataJpaTest you need to load classes using @Import explicitly. It wouldn't load you for auto.

How to set a bitmap from resource

just replace this line

bm = BitmapFactory.decodeResource(null, R.id.image);

with

Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.YourImageName);

I mean to say just change null value with getResources() If you use this code in any button or Image view click event just append getApplicationContext() before getResources()..

How to find sum of multiple columns in a table in SQL Server 2005?

use a trigges it will work:-

->CREATE TRIGGER trigger_name BEFORE INSERT ON table_name

FOR EACH ROW SET NEW.column_name3 = NEW.column_name1 + NEW.column_name2;

this will only work only when you will insert a row in table not when you will be updating your table for such a pupose create another trigger of different name and use UPDATE on the place of INSERT in the above syntax

Example for boost shared_mutex (multiple reads/one write)?

Since C++ 17 (VS2015) you can use the standard for read-write locks:

#include <shared_mutex>

typedef std::shared_mutex Lock;
typedef std::unique_lock< Lock > WriteLock;
typedef std::shared_lock< Lock > ReadLock;

Lock myLock;


void ReadFunction()
{
    ReadLock r_lock(myLock);
    //Do reader stuff
}

void WriteFunction()
{
     WriteLock w_lock(myLock);
     //Do writer stuff
}

For older version, you can use boost with the same syntax:

#include <boost/thread/locks.hpp>
#include <boost/thread/shared_mutex.hpp>

typedef boost::shared_mutex Lock;
typedef boost::unique_lock< Lock >  WriteLock;
typedef boost::shared_lock< Lock >  ReadLock;

single line comment in HTML

Let's keep it simple. Loved @digitaldreamer 's answer but it might leave the beginners confused. So, I am going to try and simplify it.

The only HTML comment is <!-- --> It can be used as a single line comment or double, it is really up to the developer.

So, an HTML comment starts with <!-- and ends with -->. It is really that simple. You should not use any other format, to avoid any compatibility issue even if the comment format is legit or not.

Difference between .on('click') vs .click()

Here you will get list of diffrent ways of applying the click event. You can select accordingly as suaitable or if your click is not working just try an alternative out of these.

$('.clickHere').click(function(){ 
     // this is flat click. this event will be attatched 
     //to element if element is available in 
     //dom at the time when JS loaded. 

  // do your stuff
});

$('.clickHere').on('click', function(){ 
    // same as first one

    // do your stuff
})

$(document).on('click', '.clickHere', function(){
          // this is diffrent type 
          //  of click. The click will be registered on document when JS 
          //  loaded and will delegate to the '.clickHere ' element. This is 
          //  called event delegation 
   // do your stuff
});

$('body').on('click', '.clickHere', function(){
   // This is same as 3rd 
   // point. Here we used body instead of document/

   // do your stuff
});

$('.clickHere').off().on('click', function(){ // 
    // deregister event listener if any and register the event again. This 
    // prevents the duplicate event resistration on same element. 
    // do your stuff
})

fatal error LNK1104: cannot open file 'libboost_system-vc110-mt-gd-1_51.lib'

b2 -j%cores% toolset=%msvcver% address-model=64 architecture=x86 link=static threading=multi runtime-link=shared --build-type=minimal stage --stagedir=stage/x64

Properties ? Linker ? General ? Additional Library Directories $(BOOST)\stage\x64\lib

How do I determine the size of my array in C?

If you know the data type of the array, you can use something like:

int arr[] = {23, 12, 423, 43, 21, 43, 65, 76, 22};

int noofele = sizeof(arr)/sizeof(int);

Or if you don't know the data type of array, you can use something like:

noofele = sizeof(arr)/sizeof(arr[0]);

Note: This thing only works if the array is not defined at run time (like malloc) and the array is not passed in a function. In both cases, arr (array name) is a pointer.

auto run a bat script in windows 7 at login

I hit this question looking for how to run batch scripts during user logon on a standalone windows server (workgroup not in domain). I found the answer in using group policy.

  1. gpedit.msc
  2. user configuration->administrative templates->system->logon->run these programs at user logon
  3. add batch scripts.
  4. you can add them using cmd /k mybatchfile.cmd if you want the command window to stay (on desktop) after batch script have finished.
  5. gpupdate - to update the group policy.

Generate a random number in the range 1 - 10

Actually I don't know you want to this.

try this

INSERT INTO my_table (my_column)
SELECT
    (random() * 10) + 1
;

How can I install Visual Studio Code extensions offline?

adding on to t3chb0t's answer, not sure why the option to download is not visible, so created a patch for those who use GreaseMonkey/ TamperMonkey: you can find the gist code here

Or you can just paste the below lines in your browser console, and the link would magically appear:

let version = document.querySelector('.ux-table-metadata > tbody:nth-child(1) > tr:nth-child(1) > td:nth-child(2) > div:nth-child(1)').innerText
    , itemDetails = window.location.search.replace('?', '').split('&').filter(str => !str.indexOf('itemName')).map(str => str.split('=')[1])[0]
    , [author, extension] = itemDetails.split('.')
    , lAuthor = author.toLowerCase()
    , href = `https://${lAuthor}.gallery.vsassets.io:443/_apis/public/gallery/publisher/${author}/extension/${extension}/${version}/assetbyname/Microsoft.VisualStudio.Services.VSIXPackage`
    , element = document.createElement('a');


element.href = href;
element.className = 'vscode-moreinformation dark';
element.innerHTML = 'download .vsix file';
element.download  = `${extension}.${version}.vsix`;
document.querySelector('.vscode-install-info-container').appendChild(element);

How do I escape ampersands in batch files?

For special characters like '&' you can surround the entire expression with quotation marks

set "url=https://url?retry=true&w=majority"

Combining two expressions (Expression<Func<T, bool>>)

Well, you can use Expression.AndAlso / OrElse etc to combine logical expressions, but the problem is the parameters; are you working with the same ParameterExpression in expr1 and expr2? If so, it is easier:

var body = Expression.AndAlso(expr1.Body, expr2.Body);
var lambda = Expression.Lambda<Func<T,bool>>(body, expr1.Parameters[0]);

This also works well to negate a single operation:

static Expression<Func<T, bool>> Not<T>(
    this Expression<Func<T, bool>> expr)
{
    return Expression.Lambda<Func<T, bool>>(
        Expression.Not(expr.Body), expr.Parameters[0]);
}

Otherwise, depending on the LINQ provider, you might be able to combine them with Invoke:

// OrElse is very similar...
static Expression<Func<T, bool>> AndAlso<T>(
    this Expression<Func<T, bool>> left,
    Expression<Func<T, bool>> right)
{
    var param = Expression.Parameter(typeof(T), "x");
    var body = Expression.AndAlso(
            Expression.Invoke(left, param),
            Expression.Invoke(right, param)
        );
    var lambda = Expression.Lambda<Func<T, bool>>(body, param);
    return lambda;
}

Somewhere, I have got some code that re-writes an expression-tree replacing nodes to remove the need for Invoke, but it is quite lengthy (and I can't remember where I left it...)


Generalized version that picks the simplest route:

static Expression<Func<T, bool>> AndAlso<T>(
    this Expression<Func<T, bool>> expr1,
    Expression<Func<T, bool>> expr2)
{
    // need to detect whether they use the same
    // parameter instance; if not, they need fixing
    ParameterExpression param = expr1.Parameters[0];
    if (ReferenceEquals(param, expr2.Parameters[0]))
    {
        // simple version
        return Expression.Lambda<Func<T, bool>>(
            Expression.AndAlso(expr1.Body, expr2.Body), param);
    }
    // otherwise, keep expr1 "as is" and invoke expr2
    return Expression.Lambda<Func<T, bool>>(
        Expression.AndAlso(
            expr1.Body,
            Expression.Invoke(expr2, param)), param);
}

Starting from .NET 4.0, there is the ExpressionVisitor class which allows you to build expressions that are EF safe.

    public static Expression<Func<T, bool>> AndAlso<T>(
        this Expression<Func<T, bool>> expr1,
        Expression<Func<T, bool>> expr2)
    {
        var parameter = Expression.Parameter(typeof (T));

        var leftVisitor = new ReplaceExpressionVisitor(expr1.Parameters[0], parameter);
        var left = leftVisitor.Visit(expr1.Body);

        var rightVisitor = new ReplaceExpressionVisitor(expr2.Parameters[0], parameter);
        var right = rightVisitor.Visit(expr2.Body);

        return Expression.Lambda<Func<T, bool>>(
            Expression.AndAlso(left, right), parameter);
    }



    private class ReplaceExpressionVisitor
        : ExpressionVisitor
    {
        private readonly Expression _oldValue;
        private readonly Expression _newValue;

        public ReplaceExpressionVisitor(Expression oldValue, Expression newValue)
        {
            _oldValue = oldValue;
            _newValue = newValue;
        }

        public override Expression Visit(Expression node)
        {
            if (node == _oldValue)
                return _newValue;
            return base.Visit(node);
        }
    }

Spring Data JPA find by embedded object property

According to me, Spring doesn't handle all the cases with ease. In your case the following should do the trick

Page<QueuedBook> findByBookIdRegion(Region region, Pageable pageable);  

or

Page<QueuedBook> findByBookId_Region(Region region, Pageable pageable);

However, it also depends on the naming convention of fields that you have in your @Embeddable class,

e.g. the following field might not work in any of the styles that mentioned above

private String cRcdDel;

I tried with both the cases (as follows) and it didn't work (it seems like Spring doesn't handle this type of naming conventions(i.e. to many Caps , especially in the beginning - 2nd letter (not sure about if this is the only case though)

Page<QueuedBook> findByBookIdCRcdDel(String cRcdDel, Pageable pageable); 

or

Page<QueuedBook> findByBookIdCRcdDel(String cRcdDel, Pageable pageable);

When I renamed column to

private String rcdDel;

my following solutions work fine without any issue:

Page<QueuedBook> findByBookIdRcdDel(String rcdDel, Pageable pageable); 

OR

Page<QueuedBook> findByBookIdRcdDel(String rcdDel, Pageable pageable);

Creating a new DOM element from an HTML string using built-in DOM methods or Prototype

I am using this method (Works in IE9+), although it will not parse <td> or some other invalid direct childs of body:

function stringToEl(string) {
    var parser = new DOMParser(),
        content = 'text/html',
        DOM = parser.parseFromString(string, content);

    // return element
    return DOM.body.childNodes[0];
}

stringToEl('<li>text</li>'); //OUTPUT: <li>text</li>

File 'app/hero.ts' is not a module error in the console, where to store interfaces files in directory structure with angular2?

Don't forget to export your class or interface as well.

export interface Sort {
    value: string;
    viewValue: string;
}

How can we programmatically detect which iOS version is device running on?

In MonoTouch:

To get the Major version use:

UIDevice.CurrentDevice.SystemVersion.Split('.')[0]

For minor version use:

UIDevice.CurrentDevice.SystemVersion.Split('.')[1]

Insert value into a string at a certain position?

You can't modify strings; they're immutable. You can do this instead:

txtBox.Text = txtBox.Text.Substring(0, i) + "TEXT" + txtBox.Text.Substring(i);

Eclipse - Failed to load class "org.slf4j.impl.StaticLoggerBinder"

Did you update the project (right-click on the project, "Maven" > "Update project...")? Otherwise, you need to check if pom.xml contains the necessary slf4j dependencies, e.g.:

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>jcl-over-slf4j</artifactId>
        <version>1.7.0</version>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.0</version>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.0</version>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.14</version>
    </dependency>

MS SQL 2008 - get all table names and their row counts in a DB

to get all tables in a database:

select * from INFORMATION_SCHEMA.TABLES

to get all columns in a database:

select * from INFORMATION_SCHEMA.columns

to get all views in a db:

select * from INFORMATION_SCHEMA.TABLES where table_type = 'view'

Creating virtual directories in IIS express

I had to make the entry in the [project].vs\config\applicationhost.config file.

Prior to this, it worked from deployment but not from code.

Instantiating a generic class in Java

And this is the Factory implementation, as Jon Skeet suggested:

interface Factory<T> {
    T factory();
}

class Araba {
    //static inner class for Factory<T> implementation
    public static class ArabaFactory implements Factory<Araba> {
        public Araba factory() {
            return new Araba();
        }
    }
    public String toString() { return "Abubeee"; }
}

class Generic<T> {
    private T var;

    Generic(Factory<T> fact) {
        System.out.println("Constructor with Factory<T> parameter");
        var = fact.factory();
    }
    Generic(T var) {
        System.out.println("Constructor with T parameter");
        this.var = var;
    }
    T get() { return var; }
}

public class Main {
    public static void main(String[] string) {
        Generic<Araba> gen = new Generic<Araba>(new Araba.ArabaFactory());
        System.out.print(gen.get());
    }
}

Output:

Constructor with Factory<T> parameter
Abubeee

Cannot uninstall angular-cli

I had angular-cli version 1.0.0-beta.28.3, and the only thing that worked for me was deleting the angular-cli directly from the global node_modules folder:

cd /usr/local/bin/lib/node_modules
rm -rf angular-cli

After that ng version output was, as expected:

command not found: ng

And I could install the latest angular-cli version:

npm install -g @angular/cli@latest

Hope it helps...

How to format html table with inline styles to look like a rendered Excel table?

Add cellpadding and cellspacing to solve it. Edit: Also removed double pixel border.

<style>
td
{border-left:1px solid black;
border-top:1px solid black;}
table
{border-right:1px solid black;
border-bottom:1px solid black;}
</style>
<html>
    <body>
        <table cellpadding="0" cellspacing="0">
            <tr>
                <td width="350" >
                    Foo
                </td>
                <td width="80" >
                    Foo1
                </td>
                <td width="65" >
                    Foo2
                </td>
            </tr>
            <tr>
                <td>
                    Bar1
                </td>
                <td>
                    Bar2
                </td>
                <td>
                    Bar3
                </td>
            </tr>
            <tr >
                <td>
                    Bar1
                </td>
                <td>
                    Bar2
                </td>
                <td>
                    Bar3
                </td>
            </tr>
        </table>
    </body>
</html>

How to map an array of objects in React

try the following snippet

const renObjData = this.props.data.map(function(data, idx) {
    return <ul key={idx}>{$.map(data,(val,ind) => {
        return (<li>{val}</li>);
    }
    }</ul>;
});

SQL time difference between two dates result in hh:mm:ss

DECLARE @dt1 datetime='2012/06/13 08:11:12', @dt2 datetime='2012/06/12 02:11:12'

SELECT CAST((@dt2-@dt1) as time(0))

Disabling Chrome cache for website development

In addition to the disable cache option (which you get to via a button in the lower right corner of the developer tools window -- Tools | Developer Tools, or Ctrl + Shift + I), on the network pane of the developer tools you can now right click and choose "Clear Cache" from the popup menu.

How can I escape a single quote?

You could try using: &#145;

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled

I solved it by myself.

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>5.0.7.Final</version>
</dependency>

Error Code: 1062. Duplicate entry '1' for key 'PRIMARY'

If you are trying to populate a table from a SQL dump, make sure that the table listed in the "INSERT INTO" statements of the dump is the same one you are trying to populate. Opening "MyTable" and importing with a SQL dump will throw exactly that kind of error if the dump is trying to put entries into "MyOtherTable", which may already have entries.

Access PHP variable in JavaScript

metrobalderas is partially right. Partially, because the PHP variable's value may contain some special characters, which are metacharacters in JavaScript. To avoid such problem, use the code below:

<script type="text/javascript">
var something=<?php echo json_encode($a); ?>;
</script>

How to return more than one value from a function in Python?

Return as a tuple, e.g.

def foo (a):
    x=a
    y=a*2
    return (x,y)

How do you use the "WITH" clause in MySQL?

MySQL prior to version 8.0 doesn't support the WITH clause (CTE in SQL Server parlance; Subquery Factoring in Oracle), so you are left with using:

  • TEMPORARY tables
  • DERIVED tables
  • inline views (effectively what the WITH clause represents - they are interchangeable)

The request for the feature dates back to 2006.

As mentioned, you provided a poor example - there's no need to perform a subselect if you aren't altering the output of the columns in any way:

  SELECT * 
    FROM ARTICLE t
    JOIN USERINFO ui ON ui.user_userid = t.article_ownerid
    JOIN CATEGORY c ON c.catid =  t.article_categoryid
   WHERE t.published_ind = 0
ORDER BY t.article_date DESC 
   LIMIT 1, 3

Here's a better example:

SELECT t.name,
       t.num
  FROM TABLE t
  JOIN (SELECT c.id
               COUNT(*) 'num'
          FROM TABLE c
         WHERE c.column = 'a'
      GROUP BY c.id) ta ON ta.id = t.id

MySQL - Trigger for updating same table after insert

On the last entry; this is another trick:

SELECT AUTO_INCREMENT FROM information_schema.tables WHERE table_schema = ... and table_name = ...

Set focus on textbox in WPF

txtCompanyID.Focusable = true;
Keyboard.Focus(txtCompanyID);

msdn:

There can be only one element on the whole desktop that has keyboard focus. In WPF, the element that has keyboard focus will have IsKeyboardFocused set to true.

You could break after the setting line and check the value of IsKeyboardFocused property. Also check if you really reach that line or maybe you set some other element to get focus after that.

Java 8 Stream API to find Unique Object matching a property value

Guava API provides MoreCollectors.onlyElement() which is a collector that takes a stream containing exactly one element and returns that element.

The returned collector throws an IllegalArgumentException if the stream consists of two or more elements, and a NoSuchElementException if the stream is empty.

Refer the below code for usage:

import static com.google.common.collect.MoreCollectors.onlyElement;

Person matchingPerson = objects.stream
                        .filter(p -> p.email().equals("testemail"))
                        .collect(onlyElement());

How to save an image locally using Python whose URL address I already know?

I wrote a script that does just this, and it is available on my github for your use.

I utilized BeautifulSoup to allow me to parse any website for images. If you will be doing much web scraping (or intend to use my tool) I suggest you sudo pip install BeautifulSoup. Information on BeautifulSoup is available here.

For convenience here is my code:

from bs4 import BeautifulSoup
from urllib2 import urlopen
import urllib

# use this image scraper from the location that 
#you want to save scraped images to

def make_soup(url):
    html = urlopen(url).read()
    return BeautifulSoup(html)

def get_images(url):
    soup = make_soup(url)
    #this makes a list of bs4 element tags
    images = [img for img in soup.findAll('img')]
    print (str(len(images)) + "images found.")
    print 'Downloading images to current working directory.'
    #compile our unicode list of image links
    image_links = [each.get('src') for each in images]
    for each in image_links:
        filename=each.split('/')[-1]
        urllib.urlretrieve(each, filename)
    return image_links

#a standard call looks like this
#get_images('http://www.wookmark.com')

Is it possible to open a Windows Explorer window from PowerShell?

Just use the Invoke-Item cmdlet. For example, if you want to open a explorer window on the current directory you can do:

Invoke-Item .

How to Sort Date in descending order From Arraylist Date in android?

Easier alternative to above answers

  1. If Object(Model Class/POJO) contains the date in String datatype.

    private void sortArray(ArrayList<myObject> arraylist) {
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); //your own date format
    if (reports != null) {
        Collections.sort(arraylist, new Comparator<myObject>() {
            @Override
            public int compare(myObject o1, myObject o2) {
                try {
                    return simpleDateFormat.parse(o2.getCreated_at()).compareTo(simpleDateFormat.parse(o1.getCreated_at()));
                } catch (ParseException e) {
                    e.printStackTrace();
                    return 0;
                }
            }
        });
    }
    
  2. If Object(Model Class/POJO) contains date in Date datatype

    private void sortArray(ArrayList<myObject> arrayList) {
    if (arrayList != null) {
        Collections.sort(arrayList, new Comparator<myObject>() {
            @Override
            public int compare(myObject o1, myObject o2) {
                return o2.getCreated_at().compareTo(o1.getCreated_at()); }
        });
    } }
    

The above code is for sorting the array in descending order of date, swap o1 and o2 for ascending order.

Python, how to read bytes from file and save it?

Use the open function to open the file. The open function returns a file object, which you can use the read and write to files:

file_input = open('input.txt') #opens a file in reading mode
file_output = open('output.txt') #opens a file in writing mode

data = file_input.read(1024) #read 1024 bytes from the input file
file_output.write(data) #write the data to the output file

How to correctly set Http Request Header in Angular 2

The simpler and current approach for adding header to a single request is:

// Step 1

const yourHeader: HttpHeaders = new HttpHeaders({
    Authorization: 'Bearer JWT-token'
});

// POST request

this.http.post(url, body, { headers: yourHeader });

// GET request

this.http.get(url, { headers: yourHeader });

Change the background color of CardView programmatically

You can use this in XML

card_view:cardBackgroundColor="@android:color/white"

or this in Java

cardView.setCardBackgroundColor(Color.WHITE);

Setting dropdownlist selecteditem programmatically

On load of My Windows Form the comboBox will display the ClassName column of my DataTable as it's the DisplayMember also has its ValueMember (not visible to user) with it.

private void Form1_Load(object sender, EventArgs e)
            {
                this.comboBoxSubjectCName.DataSource = this.Student.TableClass;
                this.comboBoxSubjectCName.DisplayMember = TableColumn.ClassName;//Column name that will be the DisplayMember
                this.comboBoxSubjectCName.ValueMember = TableColumn.ClassID;//Column name that will be the ValueMember
            }

Getting DOM element value using pure JavaScript

Pass the object:

doSomething(this)

You can get all data from object:

function(obj){
    var value = obj.value;
    var id = obj.id;
}

Or pass the id only:

doSomething(this.id)

Get the object and after that value:

function(id){
    var value = document.getElementById(id).value;  
}

How do I set the maximum line length in PyCharm?

For PyCharm 4

File >> Settings >> Editor >> Code Style: Right margin (columns)

suggestion: Take a look at other options in that tab, they're very helpful

The type or namespace name could not be found

It is also possible, that the referenced projects targets .NET 4.0, while the Console App Project targets .NET 4.0 Client Library.

While it might not have been related to this particular case, I think someone else can find this information useful.

How to remove all MySQL tables from the command-line without DROP database permissions?

You can drop the database and then recreate it with the below:-

mysql> drop database [database name];
mysql> create database [database name];

Android SDK manager won't open

There are many reasons as to why the SDK Manager won't open. Rather than trying each one of them blindly, I recommend running the android.bat in a command window so you can read the error message and apply the correct fix.

Ripple effect on Android Lollipop CardView

You should add following to CardView:

android:foreground="?android:attr/selectableItemBackground"
android:clickable="true"

Angular error: "Can't bind to 'ngModel' since it isn't a known property of 'input'"

Try adding

ngModel in module level

The code is same as the above

How do you do a limit query in JPQL or HQL?

This was posted on the Hibernate forum a few years back when asked about why this worked in Hibernate 2 but not in Hibernate 3:

Limit was never a supported clause in HQL. You are meant to use setMaxResults().

So if it worked in Hibernate 2, it seems that was by coincidence, rather than by design. I think this was because the Hibernate 2 HQL parser would replace the bits of the query that it recognised as HQL, and leave the rest as it was, so you could sneak in some native SQL. Hibernate 3, however, has a proper AST HQL Parser, and it's a lot less forgiving.

I think Query.setMaxResults() really is your only option.

How do I add python3 kernel to jupyter (IPython)

This worked for me on Ubuntu 16.04:

python2 -m pip install ipykernel
python2 -m ipykernel install --user

python3 -m pip install ipykernel
python3 -m ipykernel install --user

Reference to the documentation:
Kernels for Python 2 and 3. Installing the IPython kernel - IPython Docs.

Array[n] vs Array[10] - Initializing array with variable vs real number

In C++, variable length arrays are not legal. G++ allows this as an "extension" (because C allows it), so in G++ (without being -pedantic about following the C++ standard), you can do:

int n = 10;
double a[n]; // Legal in g++ (with extensions), illegal in proper C++

If you want a "variable length array" (better called a "dynamically sized array" in C++, since proper variable length arrays aren't allowed), you either have to dynamically allocate memory yourself:

int n = 10;
double* a = new double[n]; // Don't forget to delete [] a; when you're done!

Or, better yet, use a standard container:

int n = 10;
std::vector<double> a(n); // Don't forget to #include <vector>

If you still want a proper array, you can use a constant, not a variable, when creating it:

const int n = 10;
double a[n]; // now valid, since n isn't a variable (it's a compile time constant)

Similarly, if you want to get the size from a function in C++11, you can use a constexpr:

constexpr int n()
{
    return 10;
}

double a[n()]; // n() is a compile time constant expression

Communicating between a fragment and an activity - best practices

I am using Intents to communicate actions back to the main activity. The main activity is listening to these by overriding onNewIntent(Intent intent). The main activity translates these actions to the corresponding fragments for example.

So you can do something like this:

public class MainActivity extends Activity  {

    public static final String INTENT_ACTION_SHOW_FOO = "show_foo";
    public static final String INTENT_ACTION_SHOW_BAR = "show_bar";


   @Override
   protected void onNewIntent(Intent intent) {
        routeIntent(intent);
   }

  private void routeIntent(Intent intent) {
       String action = intent.getAction();
       if (action != null) {               
            switch (action) {
            case INTENT_ACTION_SHOW_FOO:
                // for example show the corresponding fragment
                loadFragment(FooFragment);
                break;
            case INTENT_ACTION_SHOW_BAR:
                loadFragment(BarFragment);
                break;               
        }
    }
}

Then inside any fragment to show the foo fragment:

Intent intent = new Intent(context, MainActivity.class);
intent.setAction(INTENT_ACTION_SHOW_FOO);
// Prevent activity to be re-instantiated if it is already running.
// Instead, the onNewEvent() is triggered
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
getContext().startActivity(intent);

Passing parameters from jsp to Spring Controller method

Use the @RequestParam to pass a parameter to the controller handler method. In the jsp your form should have an input field with name = "id" like the following:

<input type="text" name="id" />
<input type="submit" />

Then in your controller, your handler method should be like the following:

@RequestMapping("listNotes")
public String listNotes(@RequestParam("id") int id) {
    Person person = personService.getCurrentlyAuthenticatedUser();
    model.addAttribute("person", new Person());
    model.addAttribute("listPersons", this.personService.listPersons());
    model.addAttribute("listNotes", this.notesService.listNotesBySectionId(id, person));
    return "note";
}

Please also refer to these answers and tutorial:

Installing Python packages from local file system folder to virtualenv with pip

From the installing-packages page you can simply run:

pip install /srv/pkg/mypackage

where /srv/pkg/mypackage is the directory, containing setup.py.


Additionally1, you can install it from the archive file:

pip install ./mypackage-1.0.4.tar.gz

1 Although noted in the question, due to its popularity, it is also included.

List comprehension with if statement

If you use sufficiently big list not in b clause will do a linear search for each of the item in a. Why not use set? Set takes iterable as parameter to create a new set object.

>>> a = ["a", "b", "c", "d", "e"]
>>> b = ["c", "d", "f", "g"]
>>> set(a).intersection(set(b))
{'c', 'd'}

HTTP Ajax Request via HTTPS Page

From the javascript I tried from several ways and I could not.

You need an server side solution, for example on c# I did create an controller that call to the http, en deserialize the object, and the result is that when I call from javascript, I'm doing an request from my https://domain to my htpps://domain. Please see my c# code:

[Authorize]
public class CurrencyServicesController : Controller
{
    HttpClient client;
    //GET: CurrencyServices/Consultar?url=valores?moedas=USD&alt=json
    public async Task<dynamic> Consultar(string url)
    {
        client = new HttpClient();
        client.BaseAddress = new Uri("http://api.promasters.net.br/cotacao/v1/");
        client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
        System.Net.Http.HttpResponseMessage response = client.GetAsync(url).Result;

        var FromURL = response.Content.ReadAsStringAsync().Result;

        return JsonConvert.DeserializeObject(FromURL);
    }

And let me show to you my client side (Javascript)

<script async>
$(document).ready(function (data) {

    var TheUrl = '@Url.Action("Consultar", "CurrencyServices")?url=valores';
    $.getJSON(TheUrl)
        .done(function (data) {
            $('#DolarQuotation').html(
                '$ ' + data.valores.USD.valor.toFixed(2) + ','
            );
            $('#EuroQuotation').html(
                '€ ' + data.valores.EUR.valor.toFixed(2) + ','
            );

            $('#ARGPesoQuotation').html(
                'Ar$ ' + data.valores.ARS.valor.toFixed(2) + ''
            );

        });       

});

I wish that this help you! Greetings

How to rollback just one step using rake db:migrate

If the version is 20150616132425, then use:

rails db:migrate:down VERSION=20150616132425

How to connect TFS in Visual Studio code

I know I'm a little late to the party, but I did want to throw some interjections. (I would have commented but not enough reputation points yet, so, here's a full answer).

This requires the latest version of VS Code, Azure Repo Extention, and Git to be installed.

Anyone looking to use the new VS Code (or using the preview like myself), when you go to the Settings (Still File -> Preferences -> Settings or CTRL+, ) you'll be looking under User Settings -> Extensions -> Azure Repos.

Azure_Repo_Settings

Then under Tfvc: Location you can paste the location of the executable.

Location_Settings

For 2017 it'll be

C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\TF.exe

Or for 2019 (Preview)

C:\Program Files (x86)\Microsoft Visual Studio\2019\Preview\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\TF.exe

After adding the location, I closed my VS Code (not sure if this was needed) and went my git repo to copy the git URL.

Git_URL

After that, went back into VS Code went to the Command Palette (View -> Command Palette or CTRL+Shift+P) typed Git: Clone pasted my repo:

Git_Repo

Selected the location for the repo to be stored. Next was an error that popped up. I proceeded to follow this video which walked me through clicking on the Team button with the exclamation mark on the bottom of your VS Code Screen

Team_Button

Then chose the new method of authentication

New_Method

Copy by using CTRL+C and then press enter. Your browser will launch a page where you'll enter the code you copied (CTRL+V).

Enter_Code_Screen

Click Continue

Continue_Button

Log in with your Microsoft Credentials and you should see a change on the bottom bar of VS Code.

Bottom_Bar

Cheers!

SVN 405 Method Not Allowed

This means that the folder/file that you are trying to put on svn already exists there. My advice is that before doing anything just right click on the folder/file and click on repo-browser. By doing this you will be able to see all the files/sub-folders etc that are already present on svn. If the required file/folder is not present on the svn then you just delete(after taking backup) the file that you you want to add and then run an update.

Is there any difference between DECIMAL and NUMERIC in SQL Server?

They are the same. Numeric is functionally equivalent to decimal.

MSDN: decimal and numeric

Interpreting "condition has length > 1" warning from `if` function

The way I cam across this question was when I tried doing something similar where I was defining a function and it was being called with the array like others pointed out

You could do something like this however for this scenarios its less elegant compared to Sven's method.

sapply(a, function(x) afunc(x))

afunc<-function(a){
  if (a>0){
    a/sum(a)
  }
  else 1
}

How to convert answer into two decimal point

For formatting options, see this

Dim v1 as Double = Val(txtD.Text) / Val(txtC.Text) *
                   Val(txtF.Text) / Val(txtE.Text)
txtA.text = v1.ToString("N2");

How to parse XML and count instances of a particular node attribute?

If the source is an xml file, say like this sample

<pa:Process xmlns:pa="http://sssss">
        <pa:firsttag>SAMPLE</pa:firsttag>
    </pa:Process>

you may try the following code

from lxml import etree, objectify
metadata = 'C:\\Users\\PROCS.xml' # this is sample xml file the contents are shown above
parser = etree.XMLParser(remove_blank_text=True) # this line removes the  name space from the xml in this sample the name space is --> http://sssss
tree = etree.parse(metadata, parser) # this line parses the xml file which is PROCS.xml
root = tree.getroot() # we get the root of xml which is process and iterate using a for loop
for elem in root.getiterator():
    if not hasattr(elem.tag, 'find'): continue  # (1)
    i = elem.tag.find('}')
    if i >= 0:
        elem.tag = elem.tag[i+1:]

dict={}  # a python dictionary is declared
for elem in tree.iter(): #iterating through the xml tree using a for loop
    if elem.tag =="firsttag": # if the tag name matches the name that is equated then the text in the tag is stored into the dictionary
        dict["FIRST_TAG"]=str(elem.text)
        print(dict)

Output would be

{'FIRST_TAG': 'SAMPLE'}

How to set level logging to DEBUG in Tomcat?

Firstly, the level name to use is FINE, not DEBUG. Let's assume for a minute that DEBUG is actually valid, as it makes the following explanation make a bit more sense...

In the Handler specific properties section, you're setting the logging level for those handlers to DEBUG. This means the handlers will handle any log messages with the DEBUG level or higher. It doesn't necessarily mean any DEBUG messages are actually getting passed to the handlers.

In the Facility specific properties section, you're setting the logging level for a few explicitly-named loggers to DEBUG. For those loggers, anything at level DEBUG or above will get passed to the handlers.

The default logging level is INFO, and apart from the loggers mentioned in the Facility specific properties section, all loggers will have that level.

If you want to see all FINE messages, add this:

.level = FINE

However, this will generate a vast quantity of log messages. It's probably more useful to set the logging level for your code:

your.package.level = FINE

See the Tomcat 6/Tomcat 7 logging documentation for more information. The example logging.properties file shown there uses FINE instead of DEBUG:

...
1catalina.org.apache.juli.FileHandler.level = FINE
...

and also gives you examples of setting additional logging levels:

# For example, set the com.xyz.foo logger to only log SEVERE
# messages:
#org.apache.catalina.startup.ContextConfig.level = FINE
#org.apache.catalina.startup.HostConfig.level = FINE
#org.apache.catalina.session.ManagerBase.level = FINE

How to retrieve the current value of an oracle sequence without increment it?

SELECT last_number
  FROM all_sequences
 WHERE sequence_owner = '<sequence owner>'
   AND sequence_name = '<sequence_name>';

You can get a variety of sequence metadata from user_sequences, all_sequences and dba_sequences.

These views work across sessions.

EDIT:

If the sequence is in your default schema then:

SELECT last_number
  FROM user_sequences
 WHERE sequence_name = '<sequence_name>';

If you want all the metadata then:

SELECT *
  FROM user_sequences
 WHERE sequence_name = '<sequence_name>';

Hope it helps...

EDIT2:

A long winded way of doing it more reliably if your cache size is not 1 would be:

SELECT increment_by I
  FROM user_sequences
 WHERE sequence_name = 'SEQ';

      I
-------
      1

SELECT seq.nextval S
  FROM dual;

      S
-------
   1234

-- Set the sequence to decrement by 
-- the same as its original increment
ALTER SEQUENCE seq 
INCREMENT BY -1;

Sequence altered.

SELECT seq.nextval S
  FROM dual;

      S
-------
   1233

-- Reset the sequence to its original increment
ALTER SEQUENCE seq 
INCREMENT BY 1;

Sequence altered.

Just beware that if others are using the sequence during this time - they (or you) may get

ORA-08004: sequence SEQ.NEXTVAL goes below the sequences MINVALUE and cannot be instantiated

Also, you might want to set the cache to NOCACHE prior to the resetting and then back to its original value afterwards to make sure you've not cached a lot of values.

equivalent of rm and mv in windows .cmd

If you want to see a more detailed discussion of differences for the commands, see the Details about Differences section, below.

From the LeMoDa.net website1 (archived), specifically the Windows and Unix command line equivalents page (archived), I found the following2. There's a better/more complete table in the next edit.

Windows command     Unix command
rmdir               rmdir
rmdir /s            rm -r
move                mv

I'm interested to hear from @Dave and @javadba to hear how equivalent the commands are - how the "behavior and capabilities" compare, whether quite similar or "woefully NOT equivalent".

All I found out was that when I used it to try and recursively remove a directory and its constituent files and subdirectories, e.g.

(Windows cmd)>rmdir /s C:\my\dirwithsubdirs\

gave me a standard Windows-knows-better-than-you-do-are-you-sure message and prompt

dirwithsubdirs, Are you sure (Y/N)?

and that when I typed Y, the result was that my top directory and its constituent files and subdirectories went away.


Edit

I'm looking back at this after finding this answer. I retried each of the commands, and I'd change the table a little bit.

Windows command     Unix command
rmdir               rmdir
rmdir /s /q         rm -r
rmdir /s /q         rm -rf
rmdir /s            rm -ri
move                mv
del <file>          rm <file>

If you want the equivalent for

rm -rf

you can use

rmdir /s /q

or, as the author of the answer I sourced described,

But there is another "old school" way to do it that was used back in the day when commands did not have options to suppress confirmation messages. Simply ECHO the needed response and pipe the value into the command.

echo y | rmdir /s


Details about Differences

I tested each of the commands using Windows CMD and Cygwin (with its bash).

Before each test, I made the following setup.

Windows CMD

>mkdir this_directory
>echo some text stuff > this_directory/some.txt
>mkdir this_empty_directory

Cygwin bash

$ mkdir this_directory
$ echo "some text stuff" > this_directory/some.txt
$ mkdir this_empty_directory

That resulted in the following file structure for both.

base
|-- this_directory
|   `-- some.txt
`-- this_empty_directory

Here are the results. Note that I'll not mark each as CMD or bash; the CMD will have a > in front, and the bash will have a $ in front.

RMDIR

>rmdir this_directory
The directory is not empty.

>tree /a /f .
Folder PATH listing for volume Windows
Volume serial number is ¦¦¦¦¦¦¦¦ ¦¦¦¦:¦¦¦¦
base
+---this_directory
|       some.txt
|
\---this_empty_directory

> rmdir this_empty_directory

>tree /a /f .
base
\---this_directory
        some.txt
$ rmdir this_directory
rmdir: failed to remove 'this_directory': Directory not empty

$ tree --charset=ascii
base
|-- this_directory
|   `-- some.txt
`-- this_empty_directory

2 directories, 1 file

$ rmdir this_empty_directory

$ tree --charset=ascii
base
`-- this_directory
    `-- some.txt

RMDIR /S /Q and RM -R ; RM -RF

>rmdir /s /q this_directory

>tree /a /f
base
\---this_empty_directory

>rmdir /s /q this_empty_directory

>tree /a /f
base
No subfolders exist
$ rm -r this_directory

$ tree --charset=ascii
base
`-- this_empty_directory

$ rm -r this_empty_directory

$ tree --charset=ascii
base
0 directories, 0 files
$ rm -rf this_directory

$ tree --charset=ascii
base
`-- this_empty_directory

$ rm -rf this_empty_directory

$ tree --charset=ascii
base
0 directories, 0 files

RMDIR /S AND RM -RI Here, we have a bit of a difference, but they're pretty close.

>rmdir /s this_directory
this_directory, Are you sure (Y/N)? y

>tree /a /f
base
\---this_empty_directory

>rmdir /s this_empty_directory
this_empty_directory, Are you sure (Y/N)? y

>tree /a /f
base
No subfolders exist
$ rm -ri this_directory
rm: descend into directory 'this_directory'? y
rm: remove regular file 'this_directory/some.txt'? y
rm: remove directory 'this_directory'? y

$ tree --charset=ascii
base
`-- this_empty_directory

$ rm -ri this_empty_directory
rm: remove directory 'this_empty_directory'? y

$ tree --charset=ascii
base
0 directories, 0 files

I'M HOPING TO GET A MORE THOROUGH MOVE AND MV TEST


Notes

  1. I know almost nothing about the LeMoDa website, other than the fact that the info is

Copyright © Ben Bullock 2009-2018. All rights reserved.

(archived copyright notice)

and that there seem to be a bunch of useful programming tips along with some humour (yes, the British spelling) and information on how to fix Japanese toilets. I also found some stuff talking about the "Ibaraki Report", but I don't know if that is the website.

I think I shall go there more often; it's quite useful. Props to Ben Bullock, whose email is on his page. If he wants me to remove this info, I will.

I will include the disclaimer (archived) from the site:

Disclaimer Please read the following disclaimer before using any of the computer program code on this site.

There Is No Warranty For The Program, To The Extent Permitted By Applicable Law. Except When Otherwise Stated In Writing The Copyright Holders And/Or Other Parties Provide The Program “As Is” Without Warranty Of Any Kind, Either Expressed Or Implied, Including, But Not Limited To, The Implied Warranties Of Merchantability And Fitness For A Particular Purpose. The Entire Risk As To The Quality And Performance Of The Program Is With You. Should The Program Prove Defective, You Assume The Cost Of All Necessary Servicing, Repair Or Correction.

In No Event Unless Required By Applicable Law Or Agreed To In Writing Will Any Copyright Holder, Or Any Other Party Who Modifies And/Or Conveys The Program As Permitted Above, Be Liable To You For Damages, Including Any General, Special, Incidental Or Consequential Damages Arising Out Of The Use Or Inability To Use The Program (Including But Not Limited To Loss Of Data Or Data Being Rendered Inaccurate Or Losses Sustained By You Or Third Parties Or A Failure Of The Program To Operate With Any Other Programs), Even If Such Holder Or Other Party Has Been Advised Of The Possibility Of Such Damages.


  1. Actually, I found the information with a Google search for "cmd equivalent of rm"

https://www.google.com/search?q=cmd+equivalent+of+rm

The information I'm sharing came up first.

How to check if directory exists in %PATH%?

This routine will search for a path\ or file.ext in the path variable it returns 0 if found. Path\ or file may contain spaces if quoted. If a variable is passed as the last argument it will be set to d:\path\file.

@echo off&goto :PathCheck
:PathCheck.CMD
echo.PathCheck.CMD: Checks for existence of a path or file in %%PATH%% variable
echo.Usage: PathCheck.CMD [Checkpath] or [Checkfile] [PathVar]
echo.Checkpath must have a trailing \ but checkfile must not
echo.If Checkpath contains spaces use quotes ie. "C:\Check path\"
echo.Checkfile must not include a path, just the filename.ext
echo.If Checkfile contains spaces use quotes ie. "Check File.ext"
echo.Returns 0 if found, 1 if not or -1 if checkpath does not exist at all
echo.If PathVar is not in command line it will be echoed with surrounding quotes
echo.If PathVar is passed it will be set to d:\path\checkfile with no trailing \
echo.Then %%PathVar%% will be set to the fully qualified path to Checkfile
echo.Note: %%PathVar%% variable set will not be surrounded with quotes
echo.To view the path listing line by line use: PathCheck.CMD /L
exit/b 1

:PathCheck
if "%~1"=="" goto :PathCheck.CMD
setlocal EnableDelayedExpansion
set "PathVar=%~2"
set "pth="
set "pcheck=%~1"
if "%pcheck:~-1%" equ "\" (
  if not exist %pcheck% endlocal&exit/b -1
  set/a pth=1
) 
for %%G in ("%path:;=" "%") do (
  set "Pathfd=%%~G\"
  set "Pathfd=!Pathfd:\\=\!"
  if /i "%pcheck%" equ "/L" echo.!Pathfd!
  if defined pth (
    if /i "%pcheck%" equ "!Pathfd!" endlocal&exit/b 0
  ) else (
    if exist "!Pathfd!%pcheck%" goto :CheckfileFound
  )
)
endlocal&exit/b 1

:CheckfileFound
endlocal&(
  if not "%PathVar%"=="" (
    call set "%~2=%Pathfd%%pcheck%"
  ) else (echo."%Pathfd%%pcheck%")
  exit/b 0
)

jQuery hover and class selector

Always keep things easy and simple by creating a class

.bcolor{ background:#F00; }

THEN USE THE addClass() & removeClass() to finish it up

Most simple code to populate JTable from ResultSet

You have to Download the Jar called rs2xml by click this link rs2xml.jar Then Add it to your project libraries then import

import net.proteanit.sql.DbUtils;

I prepare Only a method to do so as a sample

private void Update_table(){
    try{
        // fetch a connection
        connection = your_connection_class_name_here.getInstance().getConnection();
        if (connection != null) {
        String sql="select name,description  from sell_mode";
        pst=connection.prepareStatement(sql);
        rs=pst.executeQuery();
         your_table_name_for_populating_your_Data.setModel(DbUtils.resultSetToTableModel(rs));
        }
    }
    catch(IOException | SQLException | PropertyVetoException e){
    JOptionPane.showMessageDialog(null,e);
    }
    finally {
          if (rs!= null) try { rs.close(); } catch (SQLException e) {}
          if (pst != null) try { pst.close(); } catch (SQLException e) {}
          if (connection != null) try { connection.close(); } catch (SQLException e) {}
      }
}

Hope this will help more

How to add an image to a JPanel?

I think there is no need to subclass of anything. Just use a Jlabel. You can set an image into a Jlabel. So, resize the Jlabel then fill it with an image. Its OK. This is the way I do.

How to use ADB in Android Studio to view an SQLite DB

You can use a very nice tool called Stetho by adding this to build.gradle file:

compile 'com.facebook.stetho:stetho:1.4.1'

And initialized it inside your Application or Activity onCreate() method:

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

Then you can view the db records in chrome in the address:

chrome://inspect/#devices

For more details you can read my post: How to view easily your db records

What is the best open XML parser for C++?

Do not use TinyXML if you're concerned about efficiency/memory management (it tends to allocate lots of tiny blocks). My personal favourite is RapidXML.

How to define two fields "unique" as couple

There is a simple solution for you called unique_together which does exactly what you want.

For example:

class MyModel(models.Model):
  field1 = models.CharField(max_length=50)
  field2 = models.CharField(max_length=50)

  class Meta:
    unique_together = ('field1', 'field2',)

And in your case:

class Volume(models.Model):
  id = models.AutoField(primary_key=True)
  journal_id = models.ForeignKey(Journals, db_column='jid', null=True, verbose_name = "Journal")
  volume_number = models.CharField('Volume Number', max_length=100)
  comments = models.TextField('Comments', max_length=4000, blank=True)

  class Meta:
    unique_together = ('journal_id', 'volume_number',)

A cron job for rails: best practices?

Both will work fine. I usually use script/runner.

Here's an example:

0 6 * * * cd /var/www/apps/your_app/current; ./script/runner --environment production 'EmailSubscription.send_email_subscriptions' >> /var/www/apps/your_app/shared/log/send_email_subscriptions.log 2>&1

You can also write a pure-Ruby script to do this if you load the right config files to connect to your database.

One thing to keep in mind if memory is precious is that script/runner (or a Rake task that depends on 'environment') will load the entire Rails environment. If you only need to insert some records into the database, this will use memory you don't really have to. If you write your own script, you can avoid this. I haven't actually needed to do this yet, but I am considering it.

RegEx to extract all matches from string using RegExp.exec

If you have ES9

(Meaning if your system: Chrome, Node.js, Firefox, etc supports Ecmascript 2019 or later)

Use the new yourString.matchAll( /your-regex/ ).

If you don't have ES9

If you have an older system, here's a function for easy copy and pasting

function findAll(regexPattern, sourceString) {
    let output = []
    let match
    // make sure the pattern has the global flag
    let regexPatternWithGlobal = RegExp(regexPattern,[...new Set("g"+regexPattern.flags)].join(""))
    while (match = regexPatternWithGlobal.exec(sourceString)) {
        // get rid of the string copy
        delete match.input
        // store the match data
        output.push(match)
    } 
    return output
}

example usage:

console.log(   findAll(/blah/g,'blah1 blah2')   ) 

outputs:

[ [ 'blah', index: 0 ], [ 'blah', index: 6 ] ]

Ascending and Descending Number Order in java

public static void main(String[] args) {
          Scanner input =new Scanner(System.in);
          System.out.print("enter how many:");
         int num =input.nextInt();
    int[] arr= new int [num];
    for(int b=0;b<arr.length;b++){
   System.out.print("enter no." + (b+1) +"=");
   arr[b]=input.nextInt();
    }

    for (int i=0; i<arr.length;i++) {
        for (int k=i;k<arr.length;k++) {

        if(arr[i] > arr[k]) {

        int temp=arr[k];
        arr[k]=arr[i];
        arr[i]=temp;
        }
            }

    }
    System.out.println("******************\n output\t accending order");


    for (int i : arr){
        System.out.println(i);
    }
}
}

jQuery Ajax requests are getting cancelled without being sent

In my case, I Apache's mod-rewrite was matching the url and redirecting the request to https.

Look at the request in chrome://net-internals/#events.

It will show an internal log of the request. Check for redirects.

Setting href attribute at runtime

Set the href attribute with

$(selector).attr('href', 'url_goes_here');

and read it using

$(selector).attr('href');

Where "selector" is any valid jQuery selector for your <a> element (".myClass" or "#myId" to name the most simple ones).

Hope this helps !

How can I catch a ctrl-c event?

For a Windows console app, you want to use SetConsoleCtrlHandler to handle CTRL+C and CTRL+BREAK.

See here for an example.

How do I get the output of a shell command executed using into a variable from Jenkinsfile (groovy)?

Easiest way is use this way

my_var=`echo 2` echo $my_var output : 2

note that is not simple single quote is back quote ( ` ).

Postgresql Windows, is there a default password?

Try this:

Open PgAdmin -> Files -> Open pgpass.conf

You would get the path of pgpass.conf at the bottom of the window. Go to that location and open this file, you can find your password there.

Reference

If the above does not work, you may consider trying this:

 1. edit pg_hba.conf to allow trust authorization temporarily
 2. Reload the config file (pg_ctl reload)
 3. Connect and issue ALTER ROLE / PASSWORD to set the new password
 4. edit pg_hba.conf again and restore the previous settings
 5. Reload the config file again

How to copy part of an array to another array in C#?

Note: I found this question looking for one of the steps in the answer to how to resize an existing array.

So I thought I would add that information here, in case anyone else was searching for how to do a ranged copy as a partial answer to the question of resizing an array.

For anyone else finding this question looking for the same thing I was, it is very simple:

Array.Resize<T>(ref arrayVariable, newSize);

where T is the type, i.e. where arrayVariable is declared:

T[] arrayVariable;

That method handles null checks, as well as newSize==oldSize having no effect, and of course silently handles the case where one of the arrays is longer than the other.

See the MSDN article for more.

How to enable scrolling of content inside a modal?

Actually for Bootstrap 3 you also need to override the .modal-open class on body.

    body.modal-open, 
    .modal-open 
    .navbar-fixed-top, 
    .modal-open 
    .navbar-fixed-bottom {
     margin-right: 15px; /*<-- to margin-right: 0px;*/
    }

XMLHttpRequest cannot load an URL with jQuery

I am using WebAPI 3 and was facing the same issue. The issue has resolve as @Rytis added his solution. And I think in WebAPI 3, we don't need to define method RegisterWebApi.

My change was only in web.config file and is working.

<httpProtocol>
 <customHeaders>
 <add name="Access-Control-Allow-Origin" value="*" />
 <add name="Access-Control-Allow-Methods" value="GET, POST" />
</customHeaders>
</httpProtocol> 

Thanks for you solution @Rytis!

How to check if character is a letter in Javascript?

if( char.toUpperCase() != char.toLowerCase() ) 

Will return true only in case of letter

As point out in below comment, if your character is non English, High Ascii or double byte range then you need to add check for code point.

if( char.toUpperCase() != char.toLowerCase() || char.codePointAt(0) > 127 )

Get only specific attributes with from Laravel Collection

Method below also works.

$users = User::all()->map(function ($user) {
  return collect($user)->only(['id', 'name', 'email']);
});

WHERE Clause to find all records in a specific month

Can I just ask to compare based on the year and month?

You can. Here's a simple example using the AdventureWorks sample database...

DECLARE @Year       INT
DECLARE @Month      INT

SET @Year = 2002
SET @Month = 6

SELECT 
    [pch].* 
FROM 
    [Production].[ProductCostHistory]   pch
WHERE
    YEAR([pch].[ModifiedDate]) = @Year
AND MONTH([pch].[ModifiedDate]) = @Month

How to copy a char array in C?

You cannot assign arrays to copy them. How you can copy the contents of one into another depends on multiple factors:

For char arrays, if you know the source array is null terminated and destination array is large enough for the string in the source array, including the null terminator, use strcpy():

#include <string.h>

char array1[18] = "abcdefg";
char array2[18];

...

strcpy(array2, array1);

If you do not know if the destination array is large enough, but the source is a C string, and you want the destination to be a proper C string, use snprinf():

#include <stdio.h>

char array1[] = "a longer string that might not fit";
char array2[18];

...

snprintf(array2, sizeof array2, "%s", array1);

If the source array is not necessarily null terminated, but you know both arrays have the same size, you can use memcpy:

#include <string.h>

char array1[28] = "a non null terminated string";
char array2[28];

...

memcpy(array2, array1, sizeof array2);

No Activity found to handle Intent : android.intent.action.VIEW

Had this exception even changed to

"audio/*"

But thanx to @Stan i have turned very simple but usefully solution:

Uri.fromFile(File(content)) instead Uri.parse(path)

 val intent =Intent(Intent.ACTION_VIEW)
                    intent.setDataAndType(Uri.fromFile(File(content)),"audio/*")
                    startActivity(intent)

React JSX: selecting "selected" on selected <select> option

With React 16.8. We can do this with hooks like the following example

Codesandbox link

import React, { useState } from "react";
import "./styles.css";

export default function App() {
  const options = [
    "Monty Python and the Holy Grail",
    "Monty Python's Life of Brian",
    "Monty Python's The Meaning of Life"
  ];
  const filmsByTati = [
    {
      id: 1,
      title: "Jour de fête",
      releasedYear: 1949
    },
    {
      id: 2,
      title: "Play time",
      releasedYear: 1967
    },
    {
      id: 3,
      releasedYear: 1958,
      title: "Mon Oncle"
    }
  ];
  const [selectedOption, setSelectedOption] = useState(options[0]);
  const [selectedTatiFilm, setSelectedTatiFilm] = useState(filmsByTati[0]);
  return (
    <div className="App">
      <h1>Select Example</h1>
      <select
        value={selectedOption}
        onChange={(e) => setSelectedOption(e.target.value)}
      >
        {options.map((option) => (
          <option key={option} value={option}>
            {option}
          </option>
        ))}
      </select>
      <span>Selected option: {selectedOption}</span>

      <select
        value={selectedTatiFilm}
        onChange={(e) =>
          setSelectedTatiFilm(
            filmsByTati.find(film => (film.id == e.target.value))
          )
        }
      >
        {filmsByTati.map((film) => (
          <option key={film.id} value={film.id}>
            {film.title}
          </option>
        ))}
      </select>
      <span>Selected option: {selectedTatiFilm.title}</span>
    </div>
  );
}

How to filter files when using scp to copy dir recursively?

scp -i /home/<user>/.ssh/id_rsa -o "StrictHostKeyChecking=no" -rp /source/directory/path/[!.]* <target_user>@<target_system:/destination/directory/path

Git with SSH on Windows

If Git for windows is installed, run Git Bash shell:

  bash

You can run ssh from within Bash shell (Bash is aware of the path of ssh)

To know the exact path of ssh, run "where" command in Bash shell:

  $ where ssh

you get:

  c:\Program Files\Git\usr\bin\ssh.exe

How to add multiple columns to pandas dataframe in one assignment?

You could use assign with a dict of column names and values.

In [1069]: df.assign(**{'col_new_1': np.nan, 'col2_new_2': 'dogs', 'col3_new_3': 3})
Out[1069]:
   col_1  col_2 col2_new_2  col3_new_3  col_new_1
0      0      4       dogs           3        NaN
1      1      5       dogs           3        NaN
2      2      6       dogs           3        NaN
3      3      7       dogs           3        NaN

Download a single folder or directory from a GitHub repo

For a Generic git Repo:

If you want to download files, not clone the repository with history, you can do this with git-archive.

git-archive makes a compressed zip or tar archive of a git repository. Some things that make it special:

  1. You can choose which files or directories in the git repository to archive.
  2. It doesn't archive the .git/ folder, or any untracked files in the repository it's run on.
  3. You can archive a specific branch, tag, or commit. Projects managed with git often use this to generate archives of versions of the project (beta, release, 2.0, etc.) for users to download.

An example of creating an archive of the docs/usage directory from a remote repo you're connected to with ssh:

# in terminal
$ git archive --format tar --remote ssh://server.org/path/to/git HEAD docs/usage > /tmp/usage_docs.tar

More information in this blog post and the git documentation.

Note on GitHub Repos:

GitHub doesn't allow git-archive access. ??

Entity Framework select distinct name

use Select().Distinct()

for example

DBContext db = new DBContext();
var data= db.User_Food_UserIntakeFood .Select( ).Distinct();

How to DROP multiple columns with a single ALTER TABLE statement in SQL Server?

alter table tablename drop (column1, column2, column3......);

Using ffmpeg to encode a high quality video

A couple of things:

  • You need to set the video bitrate. I have never used minrate and maxrate so I don't know how exactly they work, but by setting the bitrate using the -b switch, I am able to get high quality video. You need to come up with a bitrate that offers a good tradeoff between compression and video quality. You may have to experiment with this because it all depends on the frame size, frame rate and the amount of motion in the content of your video. Keep in mind that DVD tends to be around 4-5 Mbit/s on average for 720x480, so I usually start from there and decide whether I need more or less and then just experiment. For example, you could add -b 5000k to the command line to get more or less DVD video bitrate.

  • You need to specify a video codec. If you don't, ffmpeg will default to MPEG-1 which is quite old and does not provide near the amount of compression as MPEG-4 or H.264. If your ffmpeg version is built with libx264 support, you can specify -vcodec libx264 as part of the command line. Otherwise -vcodec mpeg4 will also do a better job than MPEG-1, but not as well as x264.

  • There are a lot of other advanced options that will help you squeeze out the best quality at the lowest bitrates. Take a look here for some examples.

Postgres where clause compare timestamp

Assuming you actually mean timestamp because there is no datetime in Postgres

Cast the timestamp column to a date, that will remove the time part:

select *
from the_table
where the_timestamp_column::date = date '2015-07-15';

This will return all rows from July, 15th.

Note that the above will not use an index on the_timestamp_column. If performance is critical, you need to either create an index on that expression or use a range condition:

select *
from the_table
where the_timestamp_column >= timestamp '2015-07-15 00:00:00'
  and the_timestamp_column < timestamp '2015-07-16 00:00:00';

How to get whole and decimal part of a number?

This is the way which I use:

$float = 4.3;    

$dec = ltrim(($float - floor($float)),"0."); // result .3

Send JavaScript variable to PHP variable

As Jordan already said you have to post back the javascript variable to your server before the server can handle the value. To do this you can either program a javascript function that submits a form - or you can use ajax / jquery. jQuery.post

Maybe the most easiest approach for you is something like this

function myJavascriptFunction() { 
  var javascriptVariable = "John";
  window.location.href = "myphpfile.php?name=" + javascriptVariable; 
}

On your myphpfile.php you can use $_GET['name'] after your javascript was executed.

Regards

How to vertically align <li> elements in <ul>?

Here's a good one:

Set line-height equal to whatever the height is; works like a charm!

E.g:

li {
    height: 30px;
    line-height: 30px;
}

How do I convert a column of text URLs into active hyperlinks in Excel?

Thank you Cassiopeia for code. I change his code to work with local addresses and made little changes to his conditions. I removed following conditions:

  1. Change http:/ to file:///
  2. Removed all type of white space conditions
  3. Changed 10k cell range condition to 100k

Sub HyperAddForLocalLinks()
Dim CellsWithSpaces As String
    'Converts each text hyperlink selected into a working hyperlink
    Application.ScreenUpdating = False
    Dim NotPresent As Integer
    NotPresent = 0

    For Each xCell In Selection
        xCell.Formula = Trim(xCell.Formula)
            If InStr(xCell.Formula, "file:///") <> 0 Then
                Hyperstring = Trim(xCell.Formula)
            Else
                Hyperstring = "file:///" & Trim(xCell.Formula)
            End If

            ActiveSheet.Hyperlinks.Add Anchor:=xCell, Address:=Hyperstring

        i = i + 1
        If i = 100000 Then Exit Sub
Nextxcell:
      Next xCell
    Application.ScreenUpdating = True
End Sub

regex string replace

This should work :

str = str.replace(/[^a-z0-9-]/g, '');

Everything between the indicates what your are looking for

  1. / is here to delimit your pattern so you have one to start and one to end
  2. [] indicates the pattern your are looking for on one specific character
  3. ^ indicates that you want every character NOT corresponding to what follows
  4. a-z matches any character between 'a' and 'z' included
  5. 0-9 matches any digit between '0' and '9' included (meaning any digit)
  6. - the '-' character
  7. g at the end is a special parameter saying that you do not want you regex to stop on the first character matching your pattern but to continue on the whole string

Then your expression is delimited by / before and after. So here you say "every character not being a letter, a digit or a '-' will be removed from the string".

RandomForestClassfier.fit(): ValueError: could not convert string to float

Indeed a one-hot encoder will work just fine here, convert any string and numerical categorical variables you want into 1's and 0's this way and random forest should not complain.

Cannot push to GitHub - keeps saying need merge

This can cause the remote repository to lose commits; use it with care.

If you do not wish to merge the remote branch into your local branch (see differences with git diff), and want to do a force push, use the push command with -f

git push -f origin <branch>

where origin is the name of your remote repo.

Usually, the command refuses to update a remote ref that is not an ancestor of the local ref used to overwrite it. This flag disables the check. This can cause the remote repository to lose commits; use it with care.

Android - Get value from HashMap

 Iterator iterator = meMap.keySet().iterator();
                while(iterator.hasNext() ){
                  //get key
                    String key=(String)iterator.next();
                    //toast value
                                           Toast.makeText(getBaseContext(),""+(String)meMap.get(key),Toast.LENGTH_SHORT).show();

                }

java.sql.SQLException Parameter index out of range (1 > number of parameters, which is 0)

You will get this error when you call any of the setXxx() methods on PreparedStatement, while the SQL query string does not have any placeholders ? for this.

For example this is wrong:

String sql = "INSERT INTO tablename (col1, col2, col3) VALUES (val1, val2, val3)";
// ...

preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, val1); // Fail.
preparedStatement.setString(2, val2);
preparedStatement.setString(3, val3);

You need to fix the SQL query string accordingly to specify the placeholders.

String sql = "INSERT INTO tablename (col1, col2, col3) VALUES (?, ?, ?)";
// ...

preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, val1);
preparedStatement.setString(2, val2);
preparedStatement.setString(3, val3);

Note the parameter index starts with 1 and that you do not need to quote those placeholders like so:

String sql = "INSERT INTO tablename (col1, col2, col3) VALUES ('?', '?', '?')";

Otherwise you will still get the same exception, because the SQL parser will then interpret them as the actual string values and thus can't find the placeholders anymore.

See also:

How do I call a JavaScript function on page load?

here's the trick (works everywhere):

r(function(){
alert('DOM Ready!');
});
function r(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()}

Passing data between view controllers

Passing data back from ViewController 2 (destination) to viewController 1 (source) is the more interesting thing. Assuming you use storyBoard, these are all the ways I found out:

  • Delegate
  • Notification
  • User defaults
  • Singleton

Those were discussed here already.

I found there are more ways:

Using Block callbacks:

Use it in the prepareForSegue method in the VC1

NextViewController *destinationVC = (NextViewController *) segue.destinationViewController;
[destinationVC setDidFinishUsingBlockCallback:^(NextViewController *destinationVC)
{
    self.blockLabel.text = destination.blockTextField.text;
}];

Using storyboards Unwind (Exit)

Implement a method with a UIStoryboardSegue argument in VC 1,like this one:

-(IBAction)UnWindDone:(UIStoryboardSegue *)segue { }

In the storyBoard, hook the "return" button to the green Exit button (Unwind) of the vc. Now you have a segue that "goes back" so you can use the destinationViewController property in the prepareForSegue of VC2 and change any property of VC1 before it goes back.

  • Another option of using storyboards Undwind (Exit) - you can use the method you wrote in VC1

     -(IBAction)UnWindDone:(UIStoryboardSegue *)segue {
         NextViewController *nextViewController = segue.sourceViewController;
         self.unwindLabel.text = nextViewController.unwindPropertyPass;
     }
    

And in the prepareForSegue of VC1 you can change any property you want to share.

In both unwind options, you can set the tag property of the button and check it in the prepareForSegue.

Can I install/update WordPress plugins without providing FTP access?

It is possible to use SFTP or SSH to auto update Plugins in WordPress, but you need to have ssh2 pecl extension. You can find out how to do it, using the following tutorial

No generated R.java file in my project

Go to Project and hit Clean. This should, among others, regenerate your R.java file.

Also get rid of any import android.R.* statements and then do the clean up I mentioned.

Apparently Jonas problem was related to incorrect target build settings. His target build was set to Android 2.1 (SDK v7) where his layout XML used Android 2.2 (SDK v8) elements (layout parameter match_parent), due to this there was no way for Eclipse to correctly generate the R.java file which caused all the problems.

jQuery scroll to ID from different page

On the link put a hash:

<a href="otherpage.html#elementID">Jump</a>

And on other page, you can do:

$('html,body').animate({
  scrollTop: $(window.location.hash).offset().top
});

On other page, you should have element with id set to elementID to scroll to. Of course you can change the name of it.

How to show x and y axes in a MATLAB graph?

Easiest solution:

plot([0,0],[0.0], xData, yData);

This creates an invisible line between the points [0,0] to [0,0] and since Matlab wants to include these points it will shows the axis.

How to remove all debug logging calls before building the release version of an Android app?

my Way:

1) enable Column Selection Mode (alt+shift+insert)

2) select on one Log.d(TAG, "text"); the part 'Log.'

3) then do shift + ctrl + alt + j

4) click left arrow

5) do shift+end

6) hit delete.

this removes all LOG calls at once in a java file.

VBA Public Array : how to?

Option Explicit
     Public myarray (1 To 10)
     Public Count As Integer
     myarray(1) = "A"
     myarray(2) = "B"
     myarray(3) = "C"
     myarray(4) = "D"
     myarray(5) = "E"
     myarray(6) = "F"
     myarray(7) = "G"
     myarray(8) = "H"
     myarray(9) = "I"
     myarray(10) = "J"
Private Function unwrapArray()
     For Count = 1 to UBound(myarray)
       MsgBox "Letters of the Alphabet : " & myarray(Count)
     Next 
End Function

Programmatically Install Certificate into Mozilla

I was trying to achieve the same thing in Powershell and wrote a script to perform various functions that can be interactively selected. Of course, it's fairly easy to modify the script to automate certain things instead of provide options.

I'm an Infrastructure guy rather than a coder/programmer, so apologies if it's a bit cumbersome (but it does work!!).

Save the following as a PS1:

##################################################################################################
#  
# NAME: RegisterFireFoxCertificates.ps1
#  
# AUTHOR: Andy Pyne
# 
# DATE  : 22.07.2015
#  
# COMMENT: To provide options for listing, adding, deleting and purging
# FireFox Certificates using Mozilla's NSS Util CertUtil
# Source: https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/tools/NSS_Tools_certutil
#
# NOTE: You need a copy of the NSS Util CertUtil and it's associated dll's
# The specific files I used were:
# 
# certutil.exe, fort32.dll, freebl3.dll, libnspr4.dll, libplc4.dll, libplds4.dll, nspr4.dll, 
# nss3.dll, nssckbi.dll, nssdbm3.dll, nssutil3.dll, plc4.dll, plds4.dll, smime3.dll, 
# softokn3.dll, sqlite3.dll, ssl3.dll, swft32.dll
#
##################################################################################################

##################################################################################################

# Setup a few parameters
$ErrorActionPreference = "Silentlycontinue"
$ExecutionPolicyOriginal = Get-ExecutionPolicy
$FireFoxExecutable = "C:\Program Files (x86)\Mozilla Firefox\Firefox.exe" 

# This is the Firefox certificate database
$CertDB = "Cert8.db"

# The Certificate Nickname is a name you want to see on the certificates that you've imported in - so you know they were imported by this process
# However, when you look at the certificates in Firefox, they will be listed under whatever the certificate name was when it was generated
# So if your certificate is listed as 'Company123' when imported, it will still be called that as the Common Name, but when you click to view
# it, you will see that the first item in the Certificate Fields is what you 'nicknamed' it.
$CertificateNickname = "MyCompanyName FF AutoImport Cert"

# The Legacy Certificates are specific/explicit certificates which you wish to delete (The 'purge' option later in the script references these items)
$LegacyCertificates = @("OldCertificate1", "Company Cert XYZ", "Previous Company name", "Unwanted Certificate - 7", "123APTEST123")

# This is the list of databases / Firefox profiles on the machine
$FFDBList = @()

# Making sure our temporary directory is empty
$FFCertLocationLocal = "C:\FFCertTemp"

# The remote location of the certificates and 
$FFCertLocationRemote = "\\myUNC\NETLOGON\FireFoxCert\"

# The local CertUtil executable (this is copied from the remote location above)
$FFCertTool = "$FFCertLocationLocal\CertUtil.exe"

# Making sure our temporary directory is empty
Remove-Item $FFCertLocationLocal -Recurse
New-Item -ItemType Directory -Path $FFCertLocationLocal

##################################################################################################

##################################################################################################


Clear

# We're going to get a list of the Firefox processes on the machine that are open and close them
# Otherwise the add/delete parts might not be successful with Firefox still running
$FireFoxRunningProcessesList = Get-Process | Where-Object {$_.Name -Match "FireFox"} | Select-Object ProcessName,Id | Format-Table -AutoSize
$FireFoxRunningProcesses = Get-Process | Where-Object {$_.Name -Match "FireFox"} | Select-Object -ExpandProperty Id
If (!$FireFoxRunningProcesses) {}
Else {
Write-Host "The following processes will be stopped to perform certificate manipulation:"
$FireFoxRunningProcessesList
$TerminateProcessQuestion = Read-Host "To auto-terminate (ungracefully!) processes, press 'Y', otherwise, press any other key"
If ($TerminateProcessQuestion -ne 'y') {
Clear
Write-Host "Cannot continue as Firefox process is still running, ending script ..."
Exit} 
Else {ForEach ($FireFoxRunningProcess in $FireFoxRunningProcesses) {
[Int]$FireFoxRunningProcess = [Convert]::ToInt32($FireFoxRunningProcess, 10)
Stop-Process -Id $FireFoxRunningProcess -Force}}
}

##################################################################################################

##################################################################################################

# The remote files (certificates and the NSS Tools CertUtil files are copied locally)
$FFCertificateListItemRemote = Get-ChildItem $FFCertLocationRemote -Recurse -Include *.cer,*.dll,certutil.exe
ForEach ($FFCertificateItemRemote in $FFCertificateListItemRemote) {
Copy-Item $FFCertificateItemRemote.FullName -Destination $FFCertLocationLocal}

# Get a list of the local certificates
$FFCertificateListLocal = Get-ChildItem $FFCertLocationLocal -Recurse -filter *.cer

Clear
Set-ExecutionPolicy "Unrestricted"

# Find all Firefox profiles and create an array called FFDBList
# Of course, you'll only be able to get to the ones your permissions allow
$LocalProfiles = Get-ChildItem "C:\Users" | Select-Object -ExpandProperty FullName
ForEach ($LocalProfile in $LocalProfiles) {
$FFProfile = Get-ChildItem "$LocalProfile\AppData\Roaming\Mozilla\Firefox\Profiles" | Select-Object -ExpandProperty FullName
If (!$FFProfile) {Write-Host "There is no Firefox Profile for $LocalProfile"}
ELSE {$FFDBList += $FFProfile}
}

Clear
Write-Host "#################################"
Write-Host "The List of FireFox Profiles is:"
Write-Host "#################################"
$FFDBList
PAUSE

##################################################################################################

##################################################################################################

# Setup 4x functions (List, Delete, Add and Purge)
#
# - List will simply list certificates from the Firefox profiles
#
# - Delete will delete the certificates the same as the certificates you're going to add back in
#   So for example, if you have 2x certificates copied earlier for import, 'CompanyA' and 'CompanyZ'
#   then you can delete certificates with these names beforehand. This will prevent the 
#   certificates you want to import being skipped/duplicated because they already exist
#
# - Add will simply add the list of certificates you've copied locally
#
# - Purge will allow you to delete 'other' certificates that you've manually listed in the
#   variable '$LegacyCertificates' at the top of the script

# Each of the functions perform the same 4x basic steps
#
# 1) Do the following 3x things for each of the Firefox profiles
# 2) Do the 2x following things for each of the certificates
# 3) Generate an expression using parameters based on the certificate nickname specified
#    earlier, and the profile and certificate informaiton
# 4) Invoke the expression

Function ListCertificates {
Write-Host "#############################"
ForEach ($FFDBItem in $FFDBList) {
$FFCertificateListItemFull = $FFCertificateListItem.FullName
Write-Host "Listing Certificates for $FFDBitem"
$ExpressionToListCerts = "$FFCertTool -L -d `"$FFDBItem`""
Invoke-Expression $ExpressionToListCerts
}
PAUSE}

Function DeleteOldCertificates {
Write-Host "#############################"
ForEach ($FFDBItem in $FFDBList) {
ForEach ($FFCertificateListItem in $FFCertificateListLocal) {
$FFCertificateListItemFull = $FFCertificateListItem.FullName
Write-Host "Deleting Cert $FFCertificateListItem for $FFDBitem"
$ExpressionToDeleteCerts = "$FFCertTool -D -n `"$CertificateNickname`" -d `"$FFDBItem`""
Invoke-Expression $ExpressionToDeleteCerts
}}
PAUSE}

Function AddCertificates {
Write-Host "#############################"
ForEach ($FFDBItem in $FFDBList) {
ForEach ($FFCertificateListItem in $FFCertificateListLocal) {
$FFCertificateListItemFull = $FFCertificateListItem.FullName
Write-Host "Adding $FFCertificateListItem Cert for $FFDBitem"
$ExpressionToAddCerts = "$FFCertTool -A -n `"$CertificateNickname`" -t `"CT,C,C`" -d `"$FFDBItem`" -i `"$FFCertificateListItemFull`""
Write-Host $ExpressionToAddCerts
Invoke-Expression $ExpressionToAddCerts
#PAUSE
}}
PAUSE}

Function PurgeLegacyCertificates {
Write-Host "#############################"
ForEach ($FFDBItem in $FFDBList) {
ForEach ($LegacyCertificateItem in $LegacyCertificates) {
$LegacyCertificateItemFull = $LegacyCertificateItem.FullName
Write-Host "Purging Old Certs ($LegacyCertificateItem) for $FFDBitem"
#$ExpressionToDeleteLegacyCerts = "$FFCertTool -D -n `"$OldCertificate`" -d `"$FFDBItem`""
$ExpressionToDeleteLegacyCerts = "$FFCertTool -D -n `"$LegacyCertificateItem`" -d `"$FFDBItem`""
ForEach ($LegacyCertificate in $LegacyCertificates) {
Invoke-Expression $ExpressionToDeleteLegacyCerts}
}}
PAUSE}

##################################################################################################

##################################################################################################

    # Creating a few options to invoke the various functions created above

$CertificateAction = ""

Function CertificateActionSelection {
Do {
Clear
$CertificateAction = Read-Host "Would you like to [L]ist all certificates [D]elete all old certificates, [A]dd new certificates, or [P]urge legacy certificates?"
} Until ($CertificateAction -eq "L" -or $CertificateAction -eq "D" -or $CertificateAction -eq "A" -or $CertificateAction -eq "P" )

If ($CertificateAction -eq "L") {ListCertificates}
If ($CertificateAction -eq "D") {DeleteOldCertificates}
If ($CertificateAction -eq "A") {AddCertificates}
If ($CertificateAction -eq "P") {PurgeLegacyCertificates}
}

Do {
Clear
$MoreCertificateActions = Read-Host "Would you like to [L]aunch Firefox (as $env:USERNAME), take a [C]ertificate action, or [Q]uit?"
If ($MoreCertificateActions -eq "L") {
Invoke-Item $FireFoxExecutable
Exit}
If ($MoreCertificateActions -eq "C") {CertificateActionSelection}

} Until ($MoreCertificateActions -eq "Q")

Remove-Item $FFCertLocationLocal -Recurse
Set-ExecutionPolicy $ExecutionPolicyOriginal

Exit

System.Collections.Generic.List does not contain a definition for 'Select'

This question's bit old, but, there's a tricky scenario which also leads to this error:

In controller:

ViewBag.id = //id from querystring
List<string> = GrabDataFromDBByID(ViewBag.id).Select(a=>a.ToString());

The above code will lead to an error in this part: .Select(a=>a.ToString()) because of the below reason: You're passing a ViewBag.id to a method which in compiler, it doesn't know the type, so there might be several methods with the same name and different parameters let's say:

GrabDataFromDBByID(string)
GrabDataFromDBByID(int)
GrabDataFromDBByID(whateverType)

So to prevent this case, either explicitly cast the ViewBag or create another variable storing it.

How do I install the ext-curl extension with PHP 7?

We can install any PHP7 Extensions which we are needed at the time of install Magento just use related command which you get error at the time of installin Magento

sudo apt-get install php7.0-curl
sudo apt-get install php7.0-dom
sudo apt-get install php7.0-mcrypt
sudo apt-get install php7.0-simplexml
sudo apt-get install php7.0-spl
sudo apt-get install php7.0-xsl
sudo apt-get install php7.0-intl
sudo apt-get install php7.0-mbstring
sudo apt-get install php7.0-ctype
sudo apt-get install php7.0-hash
sudo apt-get install php7.0-openssl
sudo apt-get install php7.0-zip
sudo apt-get install php7.0-xmlwriter
sudo apt-get install php7.0-gd
sudo apt-get install php7.0-iconv

Thanks! Hope this will help you

Twitter Bootstrap tabs not working: when I click on them nothing happens

i had the same problem until i downloaded bootstrap-tab.js and included it in my script, download from here https://code.google.com/p/fusionleaf/source/browse/webroot/fusionleaf/com/www/inc/bootstrap/js/bootstrap-tab.js?r=82aacd63ee1f7f9a15ead3574fe2c3f45b5c1027

include the bootsrap-tab.js in the just below the jquery

<script type="text/javascript" src="bootstrap/js/bootstrap-tab.js"></script>

Final Code Looked like this:

 <!DOCTYPE html>
<html lang="en">
<head>
<link href="bootstrap/css/bootstrap.css" rel="stylesheet">
<script type="text/javascript" src="libraries/jquery.js"></script>
<script type="text/javascript" src="bootstrap/js/bootstrap.js"></script>
<script type="text/javascript" src="bootstrap/js/bootstrap-tab.js"></script>
</head>

<body>

<div class="container">

<!-------->
<div id="content">
    <ul id="tabs" class="nav nav-tabs" data-tabs="tabs">
        <li class="active"><a href="#red" data-toggle="tab">Red</a></li>
        <li><a href="#orange" data-toggle="tab">Orange</a></li>
        <li><a href="#yellow" data-toggle="tab">Yellow</a></li>
        <li><a href="#green" data-toggle="tab">Green</a></li>
        <li><a href="#blue" data-toggle="tab">Blue</a></li>
    </ul>
    <div id="my-tab-content" class="tab-content">
        <div class="tab-pane active" id="red">
            <h1>Red</h1>
            <p>red red red red red red</p>
        </div>
        <div class="tab-pane" id="orange">
            <h1>Orange</h1>
            <p>orange orange orange orange orange</p>
        </div>
        <div class="tab-pane" id="yellow">
            <h1>Yellow</h1>
            <p>yellow yellow yellow yellow yellow</p>
        </div>
        <div class="tab-pane" id="green">
            <h1>Green</h1>
            <p>green green green green green</p>
        </div>
        <div class="tab-pane" id="blue">
            <h1>Blue</h1>
            <p>blue blue blue blue blue</p>
        </div>
    </div>
</div>


<script type="text/javascript">
    jQuery(document).ready(function ($) {
        $('#tabs').tab();
    });
</script>    
</div> <!-- container -->


<script type="text/javascript" src="bootstrap/js/bootstrap.js"></script>

</body>
</html>

How to delete an instantiated object Python?

What do you mean by delete? In Python, removing a reference (or a name) can be done with the del keyword, but if there are other names to the same object that object will not be deleted.

--> test = 3
--> print(test)
3
--> del test
--> print(test)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'test' is not defined

compared to:

--> test = 5
--> other is test  # check that both name refer to the exact same object
True
--> del test       # gets rid of test, but the object is still referenced by other
--> print(other)
5

How do I get my C# program to sleep for 50 msec?

Since now you have async/await feature, the best way to sleep for 50ms is by using Task.Delay:

async void foo()
{
    // something
    await Task.Delay(50);
}

Or if you are targeting .NET 4 (with Async CTP 3 for VS2010 or Microsoft.Bcl.Async), you must use:

async void foo()
{
    // something
    await TaskEx.Delay(50);
}

This way you won't block UI thread.

C# : "A first chance exception of type 'System.InvalidOperationException'"

The problem here is that your timer starts a thread and when it runs the callback function, the callback function ( updatelistview) is accessing controls on UI thread so this can not be done becuase of this

accessing a docker container from another container

You will have to access db through the ip of host machine, or if you want to access it via localhost:1521, then run webserver like -

docker run --net=host --name oracle-wls wls-image:latest

See here

how to read a text file using scanner in Java?

This should help you..:

import java.io.*;
import static java.lang.System.*;
/**
* Write a description of class InRead here.
* 
* @author (your name) 
* @version (a version number or a date)
*/
public class InRead
{
public InRead(String Recipe)
{
    find(Recipe);
}
public void find(String Name){
    String newRecipe= Name+".txt";
    try{
        FileReader fr= new FileReader(newRecipe);
        BufferedReader br= new BufferedReader(fr);

        String str;


    while ((str=br.readLine()) != null){
            out.println(str + "\n");
        }
        br.close();

    }catch (IOException e){
        out.println("File Not Found!");
    }
}

}

How do I completely rename an Xcode project (i.e. inclusive of folders)?

There is a GitHub project called Xcode Project Renamer:

It should be executed from inside root of Xcode project directory and called with two string parameters: $OLD_PROJECT_NAME & $NEW_PROJECT_NAME

Script goes through all the files and directories recursively, including Xcode project or workspace file and replaces all occurrences of $OLD_PROJECT_NAME string with $NEW_PROJECT_NAME string (both in each file's name and content).

DON'T FORGET TO BACKUP YOUR PROJECT!

Xcode Project Renamer

How to force file download with PHP

header("Content-Type: application/octet-stream");
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"file.exe\""); 
echo readfile($url);

is correct

or better one for exe type of files

header("Location: $url");

Django ManyToMany filter()

Note that if the user may be in multiple zones used in the query, you may probably want to add .distinct(). Otherwise you get one user multiple times:

users_in_zones = User.objects.filter(zones__in=[zone1, zone2, zone3]).distinct()

CheckBox in RecyclerView keeps on checking different items

Just add two override methods of RecyclerView

@Override
public long getItemId(int position) {
    return position;
}

@Override
public int getItemViewType(int position) {
    return position;
}

Setting focus to a textbox control

create a textbox:

 <TextBox Name="tb">
 ..hello..
</TextBox>

focus() ---> it is used to set input focus to the textbox control

tb.focus()

Procedure expects parameter which was not supplied

I had the same issue, to solve it just add exactly the same parameter name to your parameter collection as in your stored procedures.

Example

Let's say you create a stored procedure:

create procedure up_select_employe_by_ID 
     (@ID int) 
as
    select * 
    from employe_t 
    where employeID = @ID

So be sure to name your parameter exactly as it is in your stored procedure this would be

cmd.parameter.add("@ID", sqltype,size).value = @ID

if you go

cmd.parameter.add("@employeID", sqltype,size).value = @employeid 

then the error happens.

LINQ extension methods - Any() vs. Where() vs. Exists()

Any() returns true if any of the elements in a collection meet your predicate's criteria.

Where() returns an enumerable of all elements in a collection that meet your predicate's criteria.

Exists() does the same thing as any except it's just an older implementation that was there on the IList back before Linq.

How can I make Bootstrap 4 columns all the same height?

You can use the new Bootstrap cards:

_x000D_
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">_x000D_
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>_x000D_
_x000D_
<div class="card-group">_x000D_
  <div class="card">_x000D_
    <img class="card-img-top" src="..." alt="Card image cap">_x000D_
    <div class="card-block">_x000D_
      <h4 class="card-title">Card title</h4>_x000D_
      <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>_x000D_
    </div>_x000D_
    <div class="card-footer">_x000D_
      <small class="text-muted">Last updated 3 mins ago</small>_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class="card">_x000D_
    <img class="card-img-top" src="..." alt="Card image cap">_x000D_
    <div class="card-block">_x000D_
      <h4 class="card-title">Card title</h4>_x000D_
      <p class="card-text">This card has supporting text below as a natural lead-in to additional content.</p>_x000D_
    </div>_x000D_
    <div class="card-footer">_x000D_
      <small class="text-muted">Last updated 3 mins ago</small>_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class="card">_x000D_
    <img class="card-img-top" src="..." alt="Card image cap">_x000D_
    <div class="card-block">_x000D_
      <h4 class="card-title">Card title</h4>_x000D_
      <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This card has even longer content than the first to show that equal height action.</p>_x000D_
    </div>_x000D_
    <div class="card-footer">_x000D_
      <small class="text-muted">Last updated 3 mins ago</small>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Link: Click here

regards,

How do I join two lines in vi?

Shift+J removes the line change character from the current line, so by pressing "J" at any place in the line you can combine the current line and the next line in the way you want.

How to install sklearn?

pip install numpy scipy scikit-learn

if you don't have pip, install it using

python get-pip.py

Download get-pip.py from the following link. or use curl to download it.

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py