Programs & Examples On #Afconvert

How to Multi-thread an Operation Within a Loop in Python

import numpy as np
import threading


def threaded_process(items_chunk):
    """ Your main process which runs in thread for each chunk"""
    for item in items_chunk:                                               
        try:                                                                    
            api.my_operation(item)                                              
        except Exception:                                                       
            print('error with item')  

n_threads = 20
# Splitting the items into chunks equal to number of threads
array_chunk = np.array_split(input_image_list, n_threads)
thread_list = []
for thr in range(n_threads):
    thread = threading.Thread(target=threaded_process, args=(array_chunk[thr]),)
    thread_list.append(thread)
    thread_list[thr].start()

for thread in thread_list:
    thread.join()

What is the difference/usage of homebrew, macports or other package installation tools?

MacPorts is the way to go.

  1. Like @user475443 pointed, MacPorts has many many more packages. With brew you'll find yourself trapped soon because the formula you need doesn't exist.

  2. MacPorts is a native application: C + TCL. You don't need Ruby at all. To install Ruby on Mac OS X you might need MacPorts, so just go with MacPorts and you'll be happy.

  3. MacPorts is really stable, in 8 years I never had a problem with it, and my entire Unix ecosystem relay on it.

  4. If you are a PHP developer you can install the last version of Apache (Mac OS X uses 2.2), PHP and all the extensions you need, then upgrade all with one command. Forget to do the same with Homebrew.

  5. MacPorts support groups.

    foo@macpro:~/ port select --summary
    
    Name        Selected      Options
    ====        ========      =======
    db          none          db46 none
    gcc         none          gcc42 llvm-gcc42 mp-gcc48 none
    llvm        none          mp-llvm-3.3 none
    mysql       mysql56       mysql56 none
    php         php55         php55 php56 none
    postgresql  postgresql94  postgresql93 postgresql94 none
    python      none          python24 python25-apple python26-apple python27 python27-apple none
    

    If you have both PHP55 and PHP56 installed (with many different extensions), you can swap between them with just one command. All the relative extensions are part of the group and they will be activated within the chosen group: php55 or php56. I'm not sure Homebrew has this feature.

  6. Rubists like to rewrite everything in Ruby, because the only thing they are at ease is Ruby itself.

Python No JSON object could be decoded

It seems that you have invalid JSON. In that case, that's totally dependent on the data the server sends you which you have not shown. I would suggest running the response through a JSON validator.

How to filter data in dataview

Eg:

Datatable newTable =  new DataTable();

            foreach(string s1 in list)
            {
                if (s1 != string.Empty) {
                    dvProducts.RowFilter = "(CODE like '" + serachText + "*') AND (CODE <> '" + s1 + "')";
                    foreach(DataRow dr in dvProducts.ToTable().Rows)
                    {
                       newTable.ImportRow(dr);
                    }
                }
            }
ListView1.DataSource = newTable;
ListView1.DataBind();

How to secure database passwords in PHP?

If you're hosting on someone else's server and don't have access outside your webroot, you can always put your password and/or database connection in a file and then lock the file using a .htaccess:

<files mypasswdfile>
order allow,deny
deny from all
</files>

Android: How to get a custom View's height and width?

Don't try to get them inside its constructor. Try Call them in onDraw() method.

ASP.net page without a code behind

By default Sharepoint does not allow server-side code to be executed in ASPX files. See this for how to resolve that.

However, I would raise that having a code-behind is not necessarily difficult to deploy in Sharepoint (we do it extensively) - just compile your code-behind classes into an assembly and deploy it using a solution.

If still no, you can include all the code you'd normally place in a codebehind like so:

<script language="c#" runat="server">
public void Page_Load(object sender, EventArgs e)
{
  //hello, world!
}
</script>

Why is it faster to check if dictionary contains the key, rather than catch the exception in case it doesn't?

On the one hand, throwing exceptions is inherently expensive, because the stack has to be unwound etc.
On the other hand, accessing a value in a dictionary by its key is cheap, because it's a fast, O(1) operation.

BTW: The correct way to do this is to use TryGetValue

obj item;
if(!dict.TryGetValue(name, out item))
    return null;
return item;

This accesses the dictionary only once instead of twice.
If you really want to just return null if the key doesn't exist, the above code can be simplified further:

obj item;
dict.TryGetValue(name, out item);
return item;

This works, because TryGetValue sets item to null if no key with name exists.

Python: read all text file lines in loop

You can stop the 2-line separation in the output by using

    with open('t.ini') as f:
       for line in f:
           print line.strip()
           if 'str' in line:
              break

How to completely remove node.js from Windows

Scenario: Removing NodeJS when Windows has no Program Entry for your Node installation

I ran into a problem where my version of NodeJS (0.10.26) could NOT be uninstalled nor removed, because Programs & Features in Windows 7 (aka Add/Remove Programs) had no record of my having installed NodeJS... so there was no option to remove it short of manually deleting registry keys and files.

Command to verify your NodeJS version: node --version

I attempted to install the newest recommended version of NodeJS, but it failed at the end of the installation process and rolled back. Multiple versions of NodeJS also failed, and the installer likewise rolled them back as well. I could not upgrade NodeJS from the command line as I did not have SUDO installed.

SOLUTION: After spending several hours troubleshooting the problem, including upgrading NPM, I decided to reinstall the EXACT version of NodeJS on my system, over the top of the existing installation.

That solution worked, and it reinstalled NodeJS without any errors. Better yet, it also added an official entry in Add/Remove Programs dialogue.

Now that Windows was aware of the forgotten NodeJS installation, I was able to uninstall my existing version of NodeJS completely. I then successfully installed the newest recommended release of NodeJS for the Windows platform (version 4.4.5 as of this writing) without a roll-back initiating.

It took me a while to reach sucess, so I am posting this in case it helps anyone else with a similar issue.

CSS center content inside div

There are many ways to center any element. I listed some

  1. Set it's width to some value and add margin: 0 auto.

_x000D_
_x000D_
.partners {_x000D_
    width: 80%;_x000D_
    margin: 0 auto;_x000D_
}
_x000D_
_x000D_
_x000D_


  1. Split into 3 column layout

_x000D_
_x000D_
.partners {_x000D_
    width: 80%;_x000D_
    margin-left: 10%;_x000D_
}
_x000D_
_x000D_
_x000D_


  1. Use bootstrap layout

_x000D_
_x000D_
<div class="row">_x000D_
    <div class="col-sm-4"></div>_x000D_
    <div class="col-sm-4">Your Content / Image here</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Error: Failed to lookup view in Express

use this code to solve the issue

app.get('/', function(req, res){
    res.render("index");
});

How to add new column to an dataframe (to the front not end)?

df <- data.frame(b = c(1, 1, 1), c = c(2, 2, 2), d = c(3, 3, 3))
df
##   b c d
## 1 1 2 3
## 2 1 2 3
## 3 1 2 3

df <- data.frame(a = c(0, 0, 0), df)
df
##   a b c d
## 1 0 1 2 3
## 2 0 1 2 3
## 3 0 1 2 3

How to use ConcurrentLinkedQueue?

This is probably what you're looking for in terms of thread safety & "prettyness" when trying to consume everything in the queue:

for (YourObject obj = queue.poll(); obj != null; obj = queue.poll()) {
}

This will guarantee that you quit when the queue is empty, and that you continue to pop objects off of it as long as it's not empty.

How to start mongodb shell?

Just type mongod instead of ./mongod. It works for me.

A project with an Output Type of Class Library cannot be started directly

.Exe's and .dll's are both assemblies. The key difference is that executeables define an entry point Main which can be invoked by the runtime. The error

"Class library cannot be started directly"

is due to the fact that said .dll's do not have a Main. To fix this issue, change the project type to a Windows application/Console application and define an entry point. Or, add a new project that is of type Windows application/Console application and reference said .dll.

How do I get multiple subplots in matplotlib?

There are several ways to do it. The subplots method creates the figure along with the subplots that are then stored in the ax array. For example:

import matplotlib.pyplot as plt

x = range(10)
y = range(10)

fig, ax = plt.subplots(nrows=2, ncols=2)

for row in ax:
    for col in row:
        col.plot(x, y)

plt.show()

enter image description here

However, something like this will also work, it's not so "clean" though since you are creating a figure with subplots and then add on top of them:

fig = plt.figure()

plt.subplot(2, 2, 1)
plt.plot(x, y)

plt.subplot(2, 2, 2)
plt.plot(x, y)

plt.subplot(2, 2, 3)
plt.plot(x, y)

plt.subplot(2, 2, 4)
plt.plot(x, y)

plt.show()

enter image description here

How can I convince IE to simply display application/json rather than offer to download it?

I had a similar problem. I was using the "$. GetJSON" jQuery and everything worked perfectly in Firefox and Chrome.

But it did not work in IE. So I tried to directly access the URL of json, but in IE it asked if I wanted to download the file.

After much searching I saw that there must be a header in the result with a content-type, in my case, the content-type was:

header("Content-type: text/html; charset=iso-8859-1");

But when the page that made the request receives this json, in IE, you have to be specified SAME CONTENT-TYPE, in my case was:

$.getJSON (
"<? site_url php echo (" ajax / tipoMenu ")?>"
{contentType: 'text / html; charset = utf-8'},
function (result) {

hugs

Could not load the Tomcat server configuration

I solved this problem. DON'T USE THE .exe Unistall Tomcat and download the .zip from Tomcat's web site. Then unpack and put it in C:\Program Files. Open Eclipse and set the server. it will work.

jQuery detect if textarea is empty

if (!$.trim($("element").val())) {

}

Can I get "&&" or "-and" to work in PowerShell?

&& and || were on the list of things to implement (still are) but did not pop up as the next most useful thing to add. The reason is that we have -AND and -OR. If you think it is important, please file a suggestion on Connect and we'll consider it for V3.

Load external css file like scripts in jquery which is compatible in ie also

Quick function based on responses.

loadCSS = function(href) {

  var cssLink = $("<link>");
  $("head").append(cssLink); //IE hack: append before setting href

  cssLink.attr({
    rel:  "stylesheet",
    type: "text/css",
    href: href
  });

};

Usage:

loadCSS("/css/file.css");

Changing the JFrame title

If your class extends JFrame then use this.setTitle(newTitle.getText());

If not and it contains a JFrame let's say named myFrame, then use myFrame.setTitle(newTitle.getText());

Now that you have posted your program, it is obvious that you need only one JTextField to get the new title. These changes will do the trick:

JTextField poolLengthText, poolWidthText, poolDepthText, poolVolumeText, hotTub,
        hotTubLengthText, hotTubWidthText, hotTubDepthText, hotTubVolumeText, temp, results,
        newTitle;

and:

    public void createOptions()
    {
        options = new JPanel();
        options.setLayout(null);
        JLabel labelOptions = new JLabel("Change Company Name:");
        labelOptions.setBounds(120, 10, 150, 20);
        options.add(labelOptions);
        newTitle = new JTextField("Some Title");
        newTitle.setBounds(80, 40, 225, 20);
        options.add(newTitle);
//        myTitle = new JTextField("My Title...");
//        myTitle.setBounds(80, 40, 225, 20);
//        myTitle.add(labelOptions);
        JButton newName = new JButton("Set New Name");
        newName.setBounds(60, 80, 150, 20);
        newName.addActionListener(this);
        options.add(newName);
        JButton Exit = new JButton("Exit");
        Exit.setBounds(250, 80, 80, 20);
        Exit.addActionListener(this);
        options.add(Exit);
    }

and:

private void New_Name()
{
    this.setTitle(newTitle.getText());
}

More elegant way of declaring multiple variables at the same time

Use a list/dictionary or define your own class to encapsulate the stuff you're defining, but if you need all those variables you can do:

a = b = c = d = e = g = h = i = j = True
f = False

Add a Progress Bar in WebView

I have added few lines in your code and now its working fine with progress bar.

        getWindow().requestFeature(Window.FEATURE_PROGRESS);
        setContentView(R.layout.main );
        // Makes Progress bar Visible
        getWindow().setFeatureInt( Window.FEATURE_PROGRESS, Window.PROGRESS_VISIBILITY_ON);

        webview = (WebView) findViewById(R.id.webview);
        webview.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress)   
            {
                //Make the bar disappear after URL is loaded, and changes string to Loading...
                setTitle("Loading...");
                setProgress(progress * 100); //Make the bar disappear after URL is loaded
     
                // Return the app name after finish loading
                if(progress == 100)
                   setTitle(R.string.app_name);
                }
            });
        webview.setWebViewClient(new HelloWebViewClient());
        webview.getSettings().setJavaScriptEnabled(true);
        webview.loadUrl("http://www.google.com");

Looking for a short & simple example of getters/setters in C#

My explanation would be following. (It's not so short, but it's quite simple.)


Imagine a class with a variable:

class Something
{
    int weight;
    // and other methods, of course, not shown here
}

Well, there is a small problem with this class: no one can see the weight. We could make weight public, but then everyone would be able to change the weight at any moment (which is perhaps not what we want). So, well, we can do a function:

class Something
{
    int weight;
    public int GetWeight() { return weight; }
    // and other methods
}

This is already better, but now everyone instead of plain something.Weight has to type something.GetWeight(), which is, well, ugly.

With properties, we can do the same, but the code stays clean:

class Something
{
    public int weight { get; private set; }
    // and other methods
}

int w = something.weight // works!
something.weight = x; // doesn't even compile

Nice, so with the properties we have finer control over the variable access.

Another problem: okay, we want the outer code to be able to set weight, but we'd like to control its value, and not allow the weights lower than 100. Moreover, there are is some other inner variable density, which depends on weight, so we'd want to recalculate the density as soon as the weight changes.

This is traditionally achieved in the following way:

class Something
{
    int weight;
    public int SetWeight(int w)
    {
        if (w < 100)
            throw new ArgumentException("weight too small");
        weight = w;
        RecalculateDensity();
    }
    // and other methods
}

something.SetWeight(anotherSomething.GetWeight() + 1);

But again, we don't want expose to our clients that setting the weight is a complicated operation, it's semantically nothing but assigning a new weight. So the code with a setter looks the same way, but nicer:

class Something
{
    private int _w;
    public int Weight
    {
        get { return _w; }
        set
        {
            if (value < 100)
                throw new ArgumentException("weight too small");
            _w = value;
            RecalculateDensity();
        }
    }
    // and other methods
}

something.Weight = otherSomething.Weight + 1; // much cleaner, right?

So, no doubt, properties are "just" a syntactic sugar. But it makes the client's code be better. Interestingly, the need for property-like things arises very often, you can check how often you find the functions like GetXXX() and SetXXX() in the other languages.

Convert factor to integer

Quoting directly from the help page for factor:

To transform a factor f to its original numeric values, as.numeric(levels(f))[f] is recommended and slightly more efficient than as.numeric(as.character(f)).

Check if a string contains a number

You can use a combination of any and str.isdigit:

def num_there(s):
    return any(i.isdigit() for i in s)

The function will return True if a digit exists in the string, otherwise False.

Demo:

>>> king = 'I shall have 3 cakes'
>>> num_there(king)
True
>>> servant = 'I do not have any cakes'
>>> num_there(servant)
False

CodeIgniter htaccess and URL rewrite issues

<IfModule mod_rewrite.c>
   RewriteEngine On
   RewriteBase /dmizone_bkp
   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteCond $1 !^(index\.php|images|robots\.txt|css|docs|js|system)
   RewriteRule ^(.*)$ /dmizone_bkp/index.php?/$1 [L]
</IfModule> 

sed: print only matching group

grep is the right tool for extracting.

using your example and your regex:

kent$  echo 'foo bar <foo> bla 1 2 3.4'|grep -o '[0-9][0-9]*[\ \t][0-9.]*[\ \t]*$'
2 3.4

Correct way of getting Client's IP Addresses from http.Request

Looking at http.Request you can find the following member variables:

// HTTP defines that header names are case-insensitive.
// The request parser implements this by canonicalizing the
// name, making the first character and any characters
// following a hyphen uppercase and the rest lowercase.
//
// For client requests certain headers are automatically
// added and may override values in Header.
//
// See the documentation for the Request.Write method.
Header Header

// RemoteAddr allows HTTP servers and other software to record
// the network address that sent the request, usually for
// logging. This field is not filled in by ReadRequest and
// has no defined format. The HTTP server in this package
// sets RemoteAddr to an "IP:port" address before invoking a
// handler.
// This field is ignored by the HTTP client.
RemoteAddr string

You can use RemoteAddr to get the remote client's IP address and port (the format is "IP:port"), which is the address of the original requestor or the last proxy (for example a load balancer which lives in front of your server).

This is all you have for sure.

Then you can investigate the headers, which are case-insensitive (per documentation above), meaning all of your examples will work and yield the same result:

req.Header.Get("X-Forwarded-For") // capitalisation
req.Header.Get("x-forwarded-for") // doesn't
req.Header.Get("X-FORWARDED-FOR") // matter

This is because internally http.Header.Get will normalise the key for you. (If you want to access header map directly, and not through Get, you would need to use http.CanonicalHeaderKey first.)

Finally, "X-Forwarded-For" is probably the field you want to take a look at in order to grab more information about client's IP. This greatly depends on the HTTP software used on the remote side though, as client can put anything in there if it wishes to. Also, note the expected format of this field is the comma+space separated list of IP addresses. You will need to parse it a little bit to get a single IP of your choice (probably the first one in the list), for example:

// Assuming format is as expected
ips := strings.Split("10.0.0.1, 10.0.0.2, 10.0.0.3", ", ")
for _, ip := range ips {
    fmt.Println(ip)
}

will produce:

10.0.0.1
10.0.0.2
10.0.0.3

Is there an opposite to display:none?

you can use

display: normal;

It works as normal.... Its a small hacking in css ;)

Android Spinner : Avoid onItemSelected calls during initialization

spinner.setOnItemSelectedListener(this); // Will call onItemSelected() Listener.

So first time handle this with any Integer value

Example: Initially Take int check = 0;

public void onItemSelected(AdapterView<?> parent, View arg1, int pos,long id) {
   if(++check > 1) {
      TextView textView = (TextView) findViewById(R.id.textView1);
      String str = (String) parent.getItemAtPosition(pos);
      textView.setText(str);
   }
}

You can do it with boolean value and also by checking current and previous positions. See here

Online code beautifier and formatter

I've used Quick Highlighter a lot. Works great for a huge list of languages.

Multiple IF statements between number ranges

I suggest using vlookup function to get the nearest match.


Step 1

Prepare data range and name it: 'numberRange':

enter image description here

Select the range. Go to menu: Data ? Named ranges... ? define the new named range.

Step 2

Use this simple formula:

=VLOOKUP(A2,numberRange,2)

enter image description here


This way you can ommit errors, and easily correct the result.

How to remove default mouse-over effect on WPF buttons?

An extension on dodgy_coder's answer which adds support for..

  • Maintaining WPF button style
  • Adds support for IsSelected and hover, i.e. a toggled button

        <Style x:Key="Button.Hoverless" TargetType="{x:Type ButtonBase}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type ButtonBase}">
                        <Border Name="border"
                                BorderThickness="{TemplateBinding BorderThickness}"
                                Padding="{TemplateBinding Padding}"
                                BorderBrush="{TemplateBinding BorderBrush}"
                                Background="{TemplateBinding Background}">
                            <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
                        </Border>
                        <ControlTemplate.Triggers>
                            <MultiTrigger>
                                <MultiTrigger.Conditions>
                                    <Condition Property="IsMouseOver" Value="True" />
                                    <Condition Property="Selector.IsSelected" Value="False" />
                                </MultiTrigger.Conditions>
                                <Setter Property="Background" Value="#FFBEE6FD" />
                            </MultiTrigger>
    
                            <MultiTrigger>
                                <MultiTrigger.Conditions>
                                    <Condition Property="IsMouseOver" Value="True" />
                                    <Condition Property="Selector.IsSelected" Value="True" />
                                </MultiTrigger.Conditions>
                                <Setter Property="Background" Value="#BB90EE90" />
                            </MultiTrigger>
    
                            <MultiTrigger>
                                <MultiTrigger.Conditions>
                                    <Condition Property="IsMouseOver" Value="False" />
                                    <Condition Property="Selector.IsSelected" Value="True" />
                                </MultiTrigger.Conditions>
                                <Setter Property="Background" Value="LightGreen" />
                            </MultiTrigger>
    
                            <Trigger Property="IsPressed" Value="True">
                                <Setter TargetName="border" Property="Opacity" Value="0.95" />
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    

examples..

<Button Content="Wipe On" Selector.IsSelected="True" /> <Button Content="Wipe Off" Selector.IsSelected="False" />

Simple way to change the position of UIView?

aView.center = CGPointMake(150, 150); // set center

or

aView.frame = CGRectMake( 100, 200, aView.frame.size.width, aView.frame.size.height ); // set new position exactly

or

aView.frame = CGRectOffset( aView.frame, 10, 10 ); // offset by an amount

Edit:

I didn't compile this yet, but it should work:

#define CGRectSetPos( r, x, y ) CGRectMake( x, y, r.size.width, r.size.height )

aView.frame = CGRectSetPos( aView.frame, 100, 200 );

How to find time complexity of an algorithm

Taken from here - Introduction to Time Complexity of an Algorithm

1. Introduction

In computer science, the time complexity of an algorithm quantifies the amount of time taken by an algorithm to run as a function of the length of the string representing the input.

2. Big O notation

The time complexity of an algorithm is commonly expressed using big O notation, which excludes coefficients and lower order terms. When expressed this way, the time complexity is said to be described asymptotically, i.e., as the input size goes to infinity.

For example, if the time required by an algorithm on all inputs of size n is at most 5n3 + 3n, the asymptotic time complexity is O(n3). More on that later.

Few more Examples:

  • 1 = O(n)
  • n = O(n2)
  • log(n) = O(n)
  • 2 n + 1 = O(n)

3. O(1) Constant Time:

An algorithm is said to run in constant time if it requires the same amount of time regardless of the input size.

Examples:

  • array: accessing any element
  • fixed-size stack: push and pop methods
  • fixed-size queue: enqueue and dequeue methods

4. O(n) Linear Time

An algorithm is said to run in linear time if its time execution is directly proportional to the input size, i.e. time grows linearly as input size increases.

Consider the following examples, below I am linearly searching for an element, this has a time complexity of O(n).

int find = 66;
var numbers = new int[] { 33, 435, 36, 37, 43, 45, 66, 656, 2232 };
for (int i = 0; i < numbers.Length - 1; i++)
{
    if(find == numbers[i])
    {
        return;
    }
}

More Examples:

  • Array: Linear Search, Traversing, Find minimum etc
  • ArrayList: contains method
  • Queue: contains method

5. O(log n) Logarithmic Time:

An algorithm is said to run in logarithmic time if its time execution is proportional to the logarithm of the input size.

Example: Binary Search

Recall the "twenty questions" game - the task is to guess the value of a hidden number in an interval. Each time you make a guess, you are told whether your guess is too high or too low. Twenty questions game implies a strategy that uses your guess number to halve the interval size. This is an example of the general problem-solving method known as binary search

6. O(n2) Quadratic Time

An algorithm is said to run in quadratic time if its time execution is proportional to the square of the input size.

Examples:

7. Some Useful links

Can you run GUI applications in a Docker container?

I just found this blog entry and want to share it here with you because I think it is the best way to do it and it is so easy.

http://fabiorehm.com/blog/2014/09/11/running-gui-apps-with-docker/

PROS:
+ no x server stuff in the docker container
+ no vnc client/server needed
+ no ssh with x forwarding
+ much smaller docker containers

CONS:
- using x on the host (not meant for secure-sandboxing)

in case the link will fail someday I have put the most important part here:
dockerfile:

FROM ubuntu:14.04

RUN apt-get update && apt-get install -y firefox

# Replace 1000 with your user / group id
RUN export uid=1000 gid=1000 && \
    mkdir -p /home/developer && \
    echo "developer:x:${uid}:${gid}:Developer,,,:/home/developer:/bin/bash" >> /etc/passwd && \
    echo "developer:x:${uid}:" >> /etc/group && \
    echo "developer ALL=(ALL) NOPASSWD: ALL" > /etc/sudoers.d/developer && \
    chmod 0440 /etc/sudoers.d/developer && \
    chown ${uid}:${gid} -R /home/developer

USER developer
ENV HOME /home/developer
CMD /usr/bin/firefox

build the image:

docker build -t firefox .

and the run command:

docker run -ti --rm \
   -e DISPLAY=$DISPLAY \
   -v /tmp/.X11-unix:/tmp/.X11-unix \
   firefox

of course you can also do this in the run command with sh -c "echo script-here"

HINT: for audio take a look at: https://stackoverflow.com/a/28985715/2835523

How to VueJS router-link active style

When you are creating the router, you can specify the linkExactActiveClass as a property to set the class that will be used for the active router link.

const routes = [
  { path: '/foo', component: Foo },
  { path: '/bar', component: Bar }
]

const router = new VueRouter({
  routes,
  linkActiveClass: "active", // active class for non-exact links.
  linkExactActiveClass: "active" // active class for *exact* links.
})

This is documented here.

jQuery changing style of HTML element

$('#navigation ul li').css('display', 'inline-block');

not a colon, a comma

How to connect to remote Oracle DB with PL/SQL Developer?

In the "database" section of the logon dialog box, enter //hostname.domain:port/database, in your case //123.45.67.89:1521/TEST - this assumes that you don't want to set up a tnsnames.ora file/entry for some reason.

Also make sure the firewall settings on your server are not blocking port 1521.

AddTransient, AddScoped and AddSingleton Services Differences

TL;DR

Transient objects are always different; a new instance is provided to every controller and every service.

Scoped objects are the same within a request, but different across different requests.

Singleton objects are the same for every object and every request.

For more clarification, this example from .NET documentation shows the difference:

To demonstrate the difference between these lifetime and registration options, consider a simple interface that represents one or more tasks as an operation with a unique identifier, OperationId. Depending on how we configure the lifetime for this service, the container will provide either the same or different instances of the service to the requesting class. To make it clear which lifetime is being requested, we will create one type per lifetime option:

using System;

namespace DependencyInjectionSample.Interfaces
{
    public interface IOperation
    {
        Guid OperationId { get; }
    }

    public interface IOperationTransient : IOperation
    {
    }

    public interface IOperationScoped : IOperation
    {
    }

    public interface IOperationSingleton : IOperation
    {
    }

    public interface IOperationSingletonInstance : IOperation
    {
    }
}

We implement these interfaces using a single class, Operation, that accepts a GUID in its constructor, or uses a new GUID if none is provided:

using System;
using DependencyInjectionSample.Interfaces;
namespace DependencyInjectionSample.Classes
{
    public class Operation : IOperationTransient, IOperationScoped, IOperationSingleton, IOperationSingletonInstance
    {
        Guid _guid;
        public Operation() : this(Guid.NewGuid())
        {

        }

        public Operation(Guid guid)
        {
            _guid = guid;
        }

        public Guid OperationId => _guid;
    }
}

Next, in ConfigureServices, each type is added to the container according to its named lifetime:

services.AddTransient<IOperationTransient, Operation>();
services.AddScoped<IOperationScoped, Operation>();
services.AddSingleton<IOperationSingleton, Operation>();
services.AddSingleton<IOperationSingletonInstance>(new Operation(Guid.Empty));
services.AddTransient<OperationService, OperationService>();

Note that the IOperationSingletonInstance service is using a specific instance with a known ID of Guid.Empty, so it will be clear when this type is in use. We have also registered an OperationService that depends on each of the other Operation types, so that it will be clear within a request whether this service is getting the same instance as the controller, or a new one, for each operation type. All this service does is expose its dependencies as properties, so they can be displayed in the view.

using DependencyInjectionSample.Interfaces;

namespace DependencyInjectionSample.Services
{
    public class OperationService
    {
        public IOperationTransient TransientOperation { get; }
        public IOperationScoped ScopedOperation { get; }
        public IOperationSingleton SingletonOperation { get; }
        public IOperationSingletonInstance SingletonInstanceOperation { get; }

        public OperationService(IOperationTransient transientOperation,
            IOperationScoped scopedOperation,
            IOperationSingleton singletonOperation,
            IOperationSingletonInstance instanceOperation)
        {
            TransientOperation = transientOperation;
            ScopedOperation = scopedOperation;
            SingletonOperation = singletonOperation;
            SingletonInstanceOperation = instanceOperation;
        }
    }
}

To demonstrate the object lifetimes within and between separate individual requests to the application, the sample includes an OperationsController that requests each kind of IOperation type as well as an OperationService. The Index action then displays all of the controller’s and service’s OperationId values.

using DependencyInjectionSample.Interfaces;
using DependencyInjectionSample.Services;
using Microsoft.AspNetCore.Mvc;

namespace DependencyInjectionSample.Controllers
{
    public class OperationsController : Controller
    {
        private readonly OperationService _operationService;
        private readonly IOperationTransient _transientOperation;
        private readonly IOperationScoped _scopedOperation;
        private readonly IOperationSingleton _singletonOperation;
        private readonly IOperationSingletonInstance _singletonInstanceOperation;

        public OperationsController(OperationService operationService,
            IOperationTransient transientOperation,
            IOperationScoped scopedOperation,
            IOperationSingleton singletonOperation,
            IOperationSingletonInstance singletonInstanceOperation)
        {
            _operationService = operationService;
            _transientOperation = transientOperation;
            _scopedOperation = scopedOperation;
            _singletonOperation = singletonOperation;
            _singletonInstanceOperation = singletonInstanceOperation;
        }

        public IActionResult Index()
        {
            // ViewBag contains controller-requested services
            ViewBag.Transient = _transientOperation;
            ViewBag.Scoped = _scopedOperation;
            ViewBag.Singleton = _singletonOperation;
            ViewBag.SingletonInstance = _singletonInstanceOperation;

            // Operation service has its own requested services
            ViewBag.Service = _operationService;
            return View();
        }
    }
}

Now two separate requests are made to this controller action:

First Request

Second Request

Observe which of the OperationId values varies within a request, and between requests.

  • Transient objects are always different; a new instance is provided to every controller and every service.

  • Scoped objects are the same within a request, but different across different requests

  • Singleton objects are the same for every object and every request (regardless of whether an instance is provided in ConfigureServices)

Routing HTTP Error 404.0 0x80070002

Having this in Global.asax.cs solved it for me.

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    RouteConfig.RegisterRoutes(RouteTable.Routes);
}

Check if at least two out of three booleans are true

Here's another implementation using map/reduce. This scales well to billions of booleans© in a distributed environment. Using MongoDB:

Creating a database values of booleans:

db.values.insert({value: true});
db.values.insert({value: false});
db.values.insert({value: true});

Creating the map, reduce functions:

Edit: I like CurtainDog's answer about having map/reduce apply to generic lists, so here goes a map function which takes a callback that determines whether a value should be counted or not.

var mapper = function(shouldInclude) {
    return function() {
        emit(null, shouldInclude(this) ? 1 : 0);
    };
}

var reducer = function(key, values) {
    var sum = 0;
    for(var i = 0; i < values.length; i++) {
        sum += values[i];
    }
    return sum;
}

Running map/reduce:

var result = db.values.mapReduce(mapper(isTrue), reducer).result;

containsMinimum(2, result); // true
containsMinimum(1, result); // false


function isTrue(object) {
    return object.value == true;
}

function containsMinimum(count, resultDoc) {
    var record = db[resultDoc].find().next();
    return record.value >= count;
}

How to make a Python script run like a service or daemon in Linux

If you are using terminal(ssh or something) and you want to keep a long-time script working after you log out from the terminal, you can try this:

screen

apt-get install screen

create a virtual terminal inside( namely abc): screen -dmS abc

now we connect to abc: screen -r abc

So, now we can run python script: python keep_sending_mails.py

from now on, you can directly close your terminal, however, the python script will keep running rather than being shut down

Since this keep_sending_mails.py's PID is a child process of the virtual screen rather than the terminal(ssh)

If you want to go back check your script running status, you can use screen -r abc again

Drop shadow for PNG image in CSS

Just add this:

-webkit-filter: drop-shadow(5px 5px 5px #fff);
 filter: drop-shadow(5px 5px 5px #fff); 

example:

<img class="home-tab-item-img" src="img/search.png"> 

.home-tab-item-img{
    -webkit-filter: drop-shadow(5px 5px 5px #fff);
     filter: drop-shadow(5px 5px 5px #fff); 
}

'Source code does not match the bytecode' when debugging on a device

So I created an account just so I could help fix this problem that is plaguing a lot of people and where the fixes above aren't working.

If you get this error and nothing here helps. Try clicking the "Resume program play button" until the program finishes past the error. Then click in the console tab next to debug and read the red text.

I was getting that source code error even though my issue was trying to insert a value into a null Array. Step 1 Click the resume button

Step 2 Click the console tab and read the red text

Change Toolbar color in Appcompat 21

You can change the color of the text in the toolbar with these:

<item name="android:textColorPrimary">#FFFFFF</item>
<item name="android:textColor">#FFFFFF</item>

"Object doesn't support property or method 'find'" in IE

I solved same issue by adding polyfill following:

<script src="https://cdn.polyfill.io/v3/polyfill.min.js?features=default,Array.prototype.includes,Array.prototype.find"></script>

A polyfill is a piece of code (usually JavaScript on the Web) used to provide modern functionality on older browsers that do not natively support it.

Hope someone find this helpful.

MsgBox "" vs MsgBox() in VBScript

The difference between "" and () is:

With "" you are not calling anything.
With () you are calling a sub.

Example with sub:

Sub = MsgBox("Msg",vbYesNo,vbCritical,"Title")
Select Case Sub
     Case = vbYes
          MsgBox"You said yes"
     Case = vbNo
          MsgBox"You said no"
 End Select

vs Normal:

 MsgBox"This is normal"

UIAlertView first deprecated IOS 9

//Calling     
[self showMessage:@"There is no internet connection for this device"
                    withTitle:@"Error"];

//Method

-(void)showMessage:(NSString*)message withTitle:(NSString *)title
{

 UIAlertController * alert=   [UIAlertController
                                  alertControllerWithTitle:title
                                  message:message
                                  preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){

        //do something when click button
    }];
    [alert addAction:okAction];
    UIViewController *vc = [[[[UIApplication sharedApplication] delegate] window] rootViewController];
    [vc presentViewController:alert animated:YES completion:nil];
}

If you want to use this alert in NSObject class you should use like:

-(void)showMessage:(NSString*)message withTitle:(NSString *)title{
dispatch_async(dispatch_get_main_queue(), ^{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

    }]];

    [[[[UIApplication sharedApplication] keyWindow] rootViewController] presentViewController:alertController animated:YES completion:^{
    }];
});
}

get all keys set in memcached

The easiest way is to use python-memcached-stats package, https://github.com/abstatic/python-memcached-stats

The keys() method should get you going.

Example -

from memcached_stats import MemcachedStats
mem = MemcachedStats()

mem.keys()
['key-1',
 'key-2',
 'key-3',
 ... ]

Omitting all xsi and xsd namespaces when serializing an object in .NET?

After reading Microsoft's documentation and several solutions online, I have discovered the solution to this problem. It works with both the built-in XmlSerializer and custom XML serialization via IXmlSerialiazble.

To wit, I'll use the same MyTypeWithNamespaces XML sample that's been used in the answers to this question so far.

[XmlRoot("MyTypeWithNamespaces", Namespace="urn:Abracadabra", IsNullable=false)]
public class MyTypeWithNamespaces
{
    // As noted below, per Microsoft's documentation, if the class exposes a public
    // member of type XmlSerializerNamespaces decorated with the 
    // XmlNamespacesDeclarationAttribute, then the XmlSerializer will utilize those
    // namespaces during serialization.
    public MyTypeWithNamespaces( )
    {
        this._namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
            // Don't do this!! Microsoft's documentation explicitly says it's not supported.
            // It doesn't throw any exceptions, but in my testing, it didn't always work.

            // new XmlQualifiedName(string.Empty, string.Empty),  // And don't do this:
            // new XmlQualifiedName("", "")

            // DO THIS:
            new XmlQualifiedName(string.Empty, "urn:Abracadabra") // Default Namespace
            // Add any other namespaces, with prefixes, here.
        });
    }

    // If you have other constructors, make sure to call the default constructor.
    public MyTypeWithNamespaces(string label, int epoch) : this( )
    {
        this._label = label;
        this._epoch = epoch;
    }

    // An element with a declared namespace different than the namespace
    // of the enclosing type.
    [XmlElement(Namespace="urn:Whoohoo")]
    public string Label
    {
        get { return this._label; }
        set { this._label = value; }
    }
    private string _label;

    // An element whose tag will be the same name as the property name.
    // Also, this element will inherit the namespace of the enclosing type.
    public int Epoch
    {
        get { return this._epoch; }
        set { this._epoch = value; }
    }
    private int _epoch;

    // Per Microsoft's documentation, you can add some public member that
    // returns a XmlSerializerNamespaces object. They use a public field,
    // but that's sloppy. So I'll use a private backed-field with a public
    // getter property. Also, per the documentation, for this to work with
    // the XmlSerializer, decorate it with the XmlNamespaceDeclarations
    // attribute.
    [XmlNamespaceDeclarations]
    public XmlSerializerNamespaces Namespaces
    {
        get { return this._namespaces; }
    }
    private XmlSerializerNamespaces _namespaces;
}

That's all to this class. Now, some objected to having an XmlSerializerNamespaces object somewhere within their classes; but as you can see, I neatly tucked it away in the default constructor and exposed a public property to return the namespaces.

Now, when it comes time to serialize the class, you would use the following code:

MyTypeWithNamespaces myType = new MyTypeWithNamespaces("myLabel", 42);

/******
   OK, I just figured I could do this to make the code shorter, so I commented out the
   below and replaced it with what follows:

// You have to use this constructor in order for the root element to have the right namespaces.
// If you need to do custom serialization of inner objects, you can use a shortened constructor.
XmlSerializer xs = new XmlSerializer(typeof(MyTypeWithNamespaces), new XmlAttributeOverrides(),
    new Type[]{}, new XmlRootAttribute("MyTypeWithNamespaces"), "urn:Abracadabra");

******/
XmlSerializer xs = new XmlSerializer(typeof(MyTypeWithNamespaces),
    new XmlRootAttribute("MyTypeWithNamespaces") { Namespace="urn:Abracadabra" });

// I'll use a MemoryStream as my backing store.
MemoryStream ms = new MemoryStream();

// This is extra! If you want to change the settings for the XmlSerializer, you have to create
// a separate XmlWriterSettings object and use the XmlTextWriter.Create(...) factory method.
// So, in this case, I want to omit the XML declaration.
XmlWriterSettings xws = new XmlWriterSettings();
xws.OmitXmlDeclaration = true;
xws.Encoding = Encoding.UTF8; // This is probably the default
// You could use the XmlWriterSetting to set indenting and new line options, but the
// XmlTextWriter class has a much easier method to accomplish that.

// The factory method returns a XmlWriter, not a XmlTextWriter, so cast it.
XmlTextWriter xtw = (XmlTextWriter)XmlTextWriter.Create(ms, xws);
// Then we can set our indenting options (this is, of course, optional).
xtw.Formatting = Formatting.Indented;

// Now serialize our object.
xs.Serialize(xtw, myType, myType.Namespaces);

Once you have done this, you should get the following output:

<MyTypeWithNamespaces>
    <Label xmlns="urn:Whoohoo">myLabel</Label>
    <Epoch>42</Epoch>
</MyTypeWithNamespaces>

I have successfully used this method in a recent project with a deep hierachy of classes that are serialized to XML for web service calls. Microsoft's documentation is not very clear about what to do with the publicly accesible XmlSerializerNamespaces member once you've created it, and so many think it's useless. But by following their documentation and using it in the manner shown above, you can customize how the XmlSerializer generates XML for your classes without resorting to unsupported behavior or "rolling your own" serialization by implementing IXmlSerializable.

It is my hope that this answer will put to rest, once and for all, how to get rid of the standard xsi and xsd namespaces generated by the XmlSerializer.

UPDATE: I just want to make sure I answered the OP's question about removing all namespaces. My code above will work for this; let me show you how. Now, in the example above, you really can't get rid of all namespaces (because there are two namespaces in use). Somewhere in your XML document, you're going to need to have something like xmlns="urn:Abracadabra" xmlns:w="urn:Whoohoo. If the class in the example is part of a larger document, then somewhere above a namespace must be declared for either one of (or both) Abracadbra and Whoohoo. If not, then the element in one or both of the namespaces must be decorated with a prefix of some sort (you can't have two default namespaces, right?). So, for this example, Abracadabra is the defalt namespace. I could inside my MyTypeWithNamespaces class add a namespace prefix for the Whoohoo namespace like so:

public MyTypeWithNamespaces
{
    this._namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
        new XmlQualifiedName(string.Empty, "urn:Abracadabra"), // Default Namespace
        new XmlQualifiedName("w", "urn:Whoohoo")
    });
}

Now, in my class definition, I indicated that the <Label/> element is in the namespace "urn:Whoohoo", so I don't need to do anything further. When I now serialize the class using my above serialization code unchanged, this is the output:

<MyTypeWithNamespaces xmlns:w="urn:Whoohoo">
    <w:Label>myLabel</w:Label>
    <Epoch>42</Epoch>
</MyTypeWithNamespaces>

Because <Label> is in a different namespace from the rest of the document, it must, in someway, be "decorated" with a namespace. Notice that there are still no xsi and xsd namespaces.

Redirect stderr to stdout in C shell

What about just

xxx >& /dev/stdout

???

how to make a specific text on TextView BOLD

As wtsang02 said, using HTML is an expensive overhead. Just use the native solution. If you don't have to modify the string, just use SpannableString, not SpannableStringBuilder.

String boldText = "id";
String normalText = "name";
SpannableString str = new SpannableString(boldText + normalText);
str.setSpan(new StyleSpan(Typeface.BOLD), 0, boldText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(str);

What is the difference between range and xrange functions in Python 2.X?

Some of the other answers mention that Python 3 eliminated 2.x's range and renamed 2.x's xrange to range. However, unless you're using 3.0 or 3.1 (which nobody should be), it's actually a somewhat different type.

As the 3.1 docs say:

Range objects have very little behavior: they only support indexing, iteration, and the len function.

However, in 3.2+, range is a full sequence—it supports extended slices, and all of the methods of collections.abc.Sequence with the same semantics as a list.*

And, at least in CPython and PyPy (the only two 3.2+ implementations that currently exist), it also has constant-time implementations of the index and count methods and the in operator (as long as you only pass it integers). This means writing 123456 in r is reasonable in 3.2+, while in 2.7 or 3.1 it would be a horrible idea.


* The fact that issubclass(xrange, collections.Sequence) returns True in 2.6-2.7 and 3.0-3.1 is a bug that was fixed in 3.2 and not backported.

Android ViewPager with bottom dots

If anyone wants to build a viewPager with thumbnails as indicators, using this library could be an option: ThumbIndicator for viewPager that works also with image links as resources.

How do I execute a Shell built-in command with a C function?

If you just want to execute the shell command in your c program, you could use,

   #include <stdlib.h>

   int system(const char *command);

In your case,

system("pwd");

The issue is that there isn't an executable file called "pwd" and I'm unable to execute "echo $PWD", since echo is also a built-in command with no executable to be found.

What do you mean by this? You should be able to find the mentioned packages in /bin/

sudo find / -executable -name pwd
sudo find / -executable -name echo

Why I can't access remote Jupyter Notebook server?

If you are still having trouble and you are running something like EC2 AWS instance, it may just be a case of opening the port through the AWS console.

see this answer

Is there a way to make numbers in an ordered list bold?

Pretty late answer, but hopefully someone will find this useful

I had a situation like this:

  1. List item

    a. List item

Where the first item was <strong>, the sub-element was normal weight and the '1.' just wouldn't bold.

My solution was via jQuery:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function () {
        if ($('ol').has('li').has('strong')) {
            $('ol ').css('font-weight', 'bold');
            $('ol > li > ol').css('font-weight', 'normal');
        }
     });
</script>

Hopefully this helps someone!

CASE WHEN statement for ORDER BY clause

declare @OrderByCmd  nvarchar(2000)
declare @OrderByName nvarchar(100)
declare @OrderByCity nvarchar(100)
set @OrderByName='Name'    
set @OrderByCity='city'
set @OrderByCmd= 'select * from customer Order By '+@OrderByName+','+@OrderByCity+''
EXECUTE sp_executesql @OrderByCmd 

Multiple file upload in php

HTML

  1. create div with id='dvFile';

  2. create a button;

  3. onclick of that button calling function add_more()

JavaScript

function  add_more() {
  var txt = "<br><input type=\"file\" name=\"item_file[]\">";
  document.getElementById("dvFile").innerHTML += txt;
}

PHP

if(count($_FILES["item_file"]['name'])>0)
 { 
//check if any file uploaded
 $GLOBALS['msg'] = ""; //initiate the global message
  for($j=0; $j < count($_FILES["item_file"]['name']); $j++)
 { //loop the uploaded file array
   $filen = $_FILES["item_file"]['name']["$j"]; //file name
   $path = 'uploads/'.$filen; //generate the destination path
   if(move_uploaded_file($_FILES["item_file"]['tmp_name']["$j"],$path)) 
{
   //upload the file
    $GLOBALS['msg'] .= "File# ".($j+1)." ($filen) uploaded successfully<br>";
    //Success message
   }
  }
 }
 else {
  $GLOBALS['msg'] = "No files found to upload"; //No file upload message 
}

In this way you can add file/images, as many as required, and handle them through php script.

Resetting MySQL Root Password with XAMPP on Localhost

2020 Sep

  1. launch xamp control panel

  2. press admin in mysql row

  3. in opened phpmyadmin press house icon on top left corner

  4. in the top middle you will see user accounts tab and tap it

  5. see in 'new' panel under the table to add a new user for your dbs and set access permissions

How do you use global variables or constant values in Ruby?

One of the reasons why the global variable needs a prefix (called a "sigil") is because in Ruby, unlike in C, you don't have to declare your variables before assigning to them. The sigil is used as a way to be explicit about the scope of the variable.

Without a specific prefix for globals, given a statement pointNew = offset + point inside your draw method then offset refers to a local variable inside the method (and results in a NameError in this case). The same for @ used to refer to instance variables and @@ for class variables.

In other languages that use explicit declarations such as C, Java etc. the placement of the declaration is used to control the scope.

Running code after Spring Boot starts

Best way you use CommandLineRunner or ApplicationRunner The only difference between is run() method CommandLineRunner accepts array of string and ApplicationRunner accepts ApplicationArugument.

Return values from the row above to the current row

To solve this problem in Excel, usually I would just type in the literal row number of the cell above, e.g., if I'm typing in Cell A7, I would use the formula =A6. Then if I copied that formula to other cells, they would also use the row of the previous cell.

Another option is to use Indirect(), which resolves the literal statement inside to be a formula. You could use something like:

=INDIRECT("A" & ROW() - 1)

The above formula will resolve to the value of the cell in column A and the row that is one less than that of the cell which contains the formula.

Select every Nth element in CSS

Try this

div:nth-child(4n+4)

How should I store GUID in MySQL tables?

My DBA asked me when I asked about the best way to store GUIDs for my objects why I needed to store 16 bytes when I could do the same thing in 4 bytes with an Integer. Since he put that challenge out there to me I thought now was a good time to mention it. That being said...

You can store a guid as a CHAR(16) binary if you want to make the most optimal use of storage space.

CSS transition shorthand with multiple properties?

Syntax:

transition: <property> || <duration> || <timing-function> || <delay> [, ...];

Note that the duration must come before the delay, if the latter is specified.

Individual transitions combined in shorthand declarations:

-webkit-transition: height 0.3s ease-out, opacity 0.3s ease 0.5s;
-moz-transition: height 0.3s ease-out, opacity 0.3s ease 0.5s;
-o-transition: height 0.3s ease-out, opacity 0.3s ease 0.5s;
transition: height 0.3s ease-out, opacity 0.3s ease 0.5s;

Or just transition them all:

-webkit-transition: all 0.3s ease-out;
-moz-transition: all 0.3s ease-out;
-o-transition: all 0.3s ease-out;
transition: all 0.3s ease-out;

Here is a straightforward example. Here is another one with the delay property.


Edit: previously listed here were the compatibilities and known issues regarding transition. Removed for readability.

Bottom-line: just use it. The nature of this property is non-breaking for all applications and compatibility is now well above 94% globally.

If you still want to be sure, refer to http://caniuse.com/css-transitions

Return datetime object of previous month

Some time ago I came across the following algorithm which works very well for incrementing and decrementing months on either a date or datetime.

CAVEAT: This will fail if day is not available in the new month. I use this on date objects where day == 1 always.

Python 3.x:

def increment_month(d, add=1):
    return date(d.year+(d.month+add-1)//12, (d.month+add-1) % 12+1, 1)

For Python 2.7 change the //12 to just /12 since integer division is implied.

I recently used this in a defaults file when a script started to get these useful globals:

MONTH_THIS = datetime.date.today()
MONTH_THIS = datetime.date(MONTH_THIS.year, MONTH_THIS.month, 1)

MONTH_1AGO = datetime.date(MONTH_THIS.year+(MONTH_THIS.month-2)//12,
                           (MONTH_THIS.month-2) % 12+1, 1)

MONTH_2AGO = datetime.date(MONTH_THIS.year+(MONTH_THIS.month-3)//12,
                           (MONTH_THIS.month-3) % 12+1, 1)

Merge 2 DataTables and store in a new one

dtAll = dtOne.Copy();
dtAll.Merge(dtTwo,true);

The parameter TRUE preserve the changes.

For more details refer to MSDN.

Getting first and last day of the current month

string firstdayofyear = new DateTime(DateTime.Now.Year, 1, 1).ToString("MM-dd-yyyy");
string lastdayofyear = new DateTime(DateTime.Now.Year, 12, 31).ToString("MM-dd-yyyy");
string firstdayofmonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).ToString("MM-dd-yyyy");
string lastdayofmonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(1).AddDays(-1).ToString("MM-dd-yyyy");

How do I print a datetime in the local timezone?

I believe the best way to do this is to use the LocalTimezone class defined in the datetime.tzinfo documentation (goto http://docs.python.org/library/datetime.html#tzinfo-objects and scroll down to the "Example tzinfo classes" section):

Assuming Local is an instance of LocalTimezone

t = datetime.datetime(2009, 7, 10, 18, 44, 59, 193982, tzinfo=utc)
local_t = t.astimezone(Local)

then str(local_t) gives:

'2009-07-11 04:44:59.193982+10:00'

which is what you want.

(Note: this may look weird to you because I'm in New South Wales, Australia which is 10 or 11 hours ahead of UTC)

How to run bootRun with spring profile via gradle task

Spring Boot v2 Gradle plugin docs provide an answer:

6.1. Passing arguments to your application

Like all JavaExec tasks, arguments can be passed into bootRun from the command line using --args='<arguments>' when using Gradle 4.9 or later.

To run server with active profile set to dev:

$ ./gradlew bootRun --args='--spring.profiles.active=dev'

Laravel - Form Input - Multiple select for a one to many relationship

@SamMonk your technique is great. But you can use laravel form helper to do so. I have a customer and dogs relationship.

On your controller

$dogs = Dog::lists('name', 'id');

On customer create view you can use.

{{ Form::label('dogs', 'Dogs') }}
{{ Form::select('dogs[]', $dogs, null, ['id' => 'dogs', 'multiple' => 'multiple']) }}

Third parameter accepts a list of array a well. If you define a relationship on your model you can do this:

{{ Form::label('dogs', 'Dogs') }}
{{ Form::select('dogs[]', $dogs, $customer->dogs->lists('id'), ['id' => 'dogs', 'multiple' => 'multiple']) }}

Update For Laravel 5.1

The lists method now returns a Collection. Upgrading To 5.1.0

{!! Form::label('dogs', 'Dogs') !!}
{!! Form::select('dogs[]', $dogs, $customer->dogs->lists('id')->all(), ['id' => 'dogs', 'multiple' => 'multiple']) !!}

How to create my json string by using C#?

To convert any object or object list into JSON, we have to use the function JsonConvert.SerializeObject.

The below code demonstrates the use of JSON in an ASP.NET environment:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Newtonsoft.Json;
using System.Collections.Generic;

namespace JSONFromCS
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e1)
        {
            List<Employee> eList = new List<Employee>();
            Employee e = new Employee();
            e.Name = "Minal";
            e.Age = 24;

            eList.Add(e);

            e = new Employee();
            e.Name = "Santosh";
            e.Age = 24;

            eList.Add(e);

            string ans = JsonConvert.SerializeObject(eList, Formatting.Indented);

            string script = "var employeeList = {\"Employee\": " + ans+"};";
            script += "for(i = 0;i<employeeList.Employee.length;i++)";
            script += "{";
            script += "alert ('Name : ='+employeeList.Employee[i].Name+' 
            Age : = '+employeeList.Employee[i].Age);";
            script += "}";

            ClientScriptManager cs = Page.ClientScript;
            cs.RegisterStartupScript(Page.GetType(), "JSON", script, true);
        }
    }
    public class Employee
    {
        public string Name;
        public int Age;
    }
}  

After running this program, you will get two alerts

In the above example, we have created a list of Employee object and passed it to function "JsonConvert.SerializeObject". This function (JSON library) will convert the object list into JSON format. The actual format of JSON can be viewed in the below code snippet:

{ "Maths" : [ {"Name"     : "Minal",        // First element
                             "Marks"     : 84,
                             "age"       : 23 },
                             {
                             "Name"      : "Santosh",    // Second element
                             "Marks"     : 91,
                             "age"       : 24 }
                           ],                       
              "Science" :  [ 
                             {
                             "Name"      : "Sahoo",     // First Element
                             "Marks"     : 74,
                             "age"       : 27 }, 
                             {                           
                             "Name"      : "Santosh",    // Second Element
                             "Marks"     : 78,
                             "age"       : 41 }
                           ] 
            } 

Syntax:

  • {} - acts as 'containers'

  • [] - holds arrays

  • : - Names and values are separated by a colon

  • , - Array elements are separated by commas

This code is meant for intermediate programmers, who want to use C# 2.0 to create JSON and use in ASPX pages.

You can create JSON from JavaScript end, but what would you do to convert the list of object into equivalent JSON string from C#. That's why I have written this article.

In C# 3.5, there is an inbuilt class used to create JSON named JavaScriptSerializer.

The following code demonstrates how to use that class to convert into JSON in C#3.5.

JavaScriptSerializer serializer = new JavaScriptSerializer()
return serializer.Serialize(YOURLIST);   

So, try to create a List of arrays with Questions and then serialize this list into JSON

What is use of c_str function In c++

In C/C++ programming there are two types of strings: the C strings and the standard strings. With the <string> header, we can use the standard strings. On the other hand, the C strings are just an array of normal chars. So, in order to convert a standard string to a C string, we use the c_str() function.

for example

// a string to a C-style string conversion//

const char *cstr1 = str1.c_str();
cout<<"Operation: *cstr1 = str1.c_str()"<<endl;
cout<<"The C-style string c_str1 is: "<<cstr1<<endl;
cout<<"\nOperation: strlen(cstr1)"<<endl;
cout<<"The length of C-style string str1 = "<<strlen(cstr1)<<endl;

And the output will be,

Operation: *cstr1 = str1.c_str()
The C-style string c_str1 is: Testing the c_str 
Operation: strlen(cstr1)
The length of C-style string str1 = 17

How to rename a directory/folder on GitHub website?

As a newer user to git, I took the following approach. From the command line, I was able to rename a folder by creating a new folder, copying the files to it, adding and commiting locally and pushing. These are my steps:

$mkdir newfolder 
$cp oldfolder/* newfolder
$git add newfolder 
$git commit -m 'start rename'     
$git push                             #New Folder appears on Github      
$git rm -r oldfolder
$git commit -m 'rename complete' 
$git push                             #Old Folder disappears on Github  

Probably a better way, but it worked for me.

Rails: How can I rename a database column in a Ruby on Rails migration?

I had this challenge when working on a Rails 6 application with PostgreSQL database.

Here's how I fixed it:

In my came the table_name was Products, the old_column was SKU and the new_column was ProductNumber:

Create a migration file that will contain the command for renaming the column:

rails generate migration RenameSKUToProductNumberInProducts

Open the migration file in the db/migrate directory:

db/migrate/20201028082344_rename_sku_to_product_number_in_products.rb

Add the command for renaming the column:

class RenameSkuToProductNumberInProducts < ActiveRecord::Migration[6.0]
  def change
    # rename_column :table_name, :old_column, :new_column
    rename_column :products, :sku, :product_number
  end
end

Save, and then run the migration command:

rails db:migrate

You can now confirm the renaming of the column by taking a look at the schema file:

db/schema.rb

If you are not satisfied with the renaming of the column, you can always rollback:

rails db:rollback

Note: Endeavour to modify the column name to the new name in all the places where it is called.

That's all.

I hope this helps

What does "static" mean in C?

It is important to note that static variables in functions get initialized at the first entry into that function and persist even after their call has been finished; in case of recursive functions the static variable gets initialized only once and persists as well over all recursive calls and even after the call of the function has been finished.

If the variable has been created outside a function, it means that the programmer is only able to use the variable in the source-file the variable has been declared.

MVC razor form with multiple different submit buttons?

In case you're using pure razor, i.e. no MVC controller:

<button name="SubmitForm" value="Hello">Hello</button>
<button name="SubmitForm" value="World">World</button>
@if (IsPost)
{
    <p>@Request.Form["SubmitForm"]</p>
}

Clicking each of the buttons should render out Hello and World.

Display calendar to pick a date in java

  1. Open your Java source code document and navigate to the JTable object you have created inside of your Swing class.

  2. Create a new TableModel object that holds a DatePickerTable. You must create the DatePickerTable with a range of date values in MMDDYYYY format. The first value is the begin date and the last is the end date. In code, this looks like:

    TableModel datePicker = new DatePickerTable("01011999","12302000");
    
  3. Set the display interval in the datePicker object. By default each day is displayed, but you may set a regular interval. To set a 15-day interval between date options, use this code:

    datePicker.interval = 15;
    
  4. Attach your table model into your JTable:

    JTable newtable = new JTable (datePicker);
    

    Your Java application now has a drop-down date selection dialog.

How to convert a selection to lowercase or uppercase in Sublime Text

For Windows:

  • Ctrl+K,Ctrl+U for UPPERCASE.
  • Ctrl+K,Ctrl+L for lowercase.

Method 1 (Two keys pressed at a time)

  1. Press Ctrl and hold.
  2. Now press K, release K while holding Ctrl. (Do not release the Ctrl key)
  3. Immediately, press U (for uppercase) OR L (for lowercase) with Ctrl still being pressed, then release all pressed keys.

Method 2 (3 keys pressed at a time)

  1. Press Ctrl and hold.
  2. Now press K.
  3. Without releasing Ctrl and K, immediately press U (for uppercase) OR L (for lowercase) and release all pressed keys.

Please note: If you press and hold Ctrl+K for more than two seconds it will start deleting text so try to be quick with it.

I use the above shortcuts, and they work on my Windows system.

How do I send an HTML email?

Take a look at http://commons.apache.org/email/ they have an HtmlEmail class that probably does exactly what you need.

How to split a dos path into its components in Python

One recursive for the fun.

Not the most elegant answer, but should work everywhere:

import os

def split_path(path):
    head = os.path.dirname(path)
    tail = os.path.basename(path)
    if head == os.path.dirname(head):
        return [tail]
    return split_path(head) + [tail]

CodeIgniter: 404 Page Not Found on Live Server

I am doing it on local and production server this way:


Routes:

$route['default_controller']   = 'Home_controller';

Files' names:

  • in controllers folder: Home_controller.php
  • in models folder: Home_model.php
  • in views folder: Home.php

Home_controller.php:

       class Home_controller extends CI_Controller {

           public function index(){

              //loading Home_model
              $this->load->model('Home_model');

              //get data from DB
              $data['db_data']  = $this->Home_model->getData();

              //pass $data to Home.html
              $this->load->view('Home', $data);
           }
       }

Home_model.php:

       class Home_model extends CI_Model {
       ...
       }

There should be no more problems with cases anymore :)

Should I use int or Int32

Also consider Int16. If you need to store an Integer in memory in your application and you are concerned about the amount of memory used, then you could go with Int16 since it uses less memeory and has a smaller min/max range than Int32 (which is what int is.)

How to get height of entire document with JavaScript?

The "jQuery method" of determining the document size - query everything, take the highest value, and hope for the best - works in most cases, but not in all of them .

If you really need bullet-proof results for the document size, I'd suggest you use my jQuery.documentSize plugin. Unlike the other methods, it actually tests and evaluates browser behaviour when it is loaded and, based on the result, queries the right property from there on out.

The impact of this one-time test on performance is minimal, and the plugin returns the right results in even the weirdest scenarios - not because I say so, but because a massive, auto-generated test suite actually verifies that it does.

Because the plugin is written in vanilla Javascript, you can use it without jQuery, too.

'Best' practice for restful POST response

Returning the whole object on an update would not seem very relevant, but I can hardly see why returning the whole object when it is created would be a bad practice in a normal use case. This would be useful at least to get the ID easily and to get the timestamps when relevant. This is actually the default behavior got when scaffolding with Rails.

I really do not see any advantage to returning only the ID and doing a GET request after, to get the data you could have got with your initial POST.

Anyway as long as your API is consistent I think that you should choose the pattern that fits your needs the best. There is not any correct way of how to build a REST API, imo.

c# - How to get sum of the values from List?

You can use the Sum function, but you'll have to convert the strings to integers, like so:

int total = monValues.Sum(x => Convert.ToInt32(x));

How to get a product's image in Magento?

get product images in magento using product id

    $product_id = $_POST['product_id'];
    $storeId    = Mage::app()->getStore()->getId();
    $loadpro    = Mage::getModel('catalog/product')->load($product_id);

    $mediaApi      =  Mage::getModel("catalog/product_attribute_media_api");
    $mediaApiItems = $mediaApi->items($loadpro->getId());
    foreach ($mediaApiItems as $item) {
            //for getting existing Images
            echo $item['file'];
            }

Convert interface{} to int

Simplest way I did this. Not the best way but simplest way I know how.

import "fmt"

func main() {
    fmt.Print(addTwoNumbers(5, 6))
}

func addTwoNumbers(val1 interface{}, val2 interface{}) int {
    op1, _ := val1.(int)
    op2, _ := val2.(int)

    return op1 + op2
}

Using sed, how do you print the first 'N' characters of a line?

Don't use sed, use cut:

grep .... | cut -c 1-N

If you MUST use sed:

grep ... | sed -e 's/^\(.\{12\}\).*/\1/'

Converting string to number in javascript/jQuery

It sounds like this is referring to something else than you think. In what context are you using it?

The this keyword is usually only used within a callback function of an event-handler, when you loop over a set of elements, or similar. In that context it refers to a particular DOM-element, and can be used the way you do.

If you only want to access that particular button (outside any callback or loop) and don't have any other elements that use the btn-info class, you could do something like:

parseInt($(".btn-info").data('votevalue'), 10);

You could also assign the element an ID, and use that to select on, which is probably a safer way, if you want to be sure that only one element match your selector.

How do I fix 'ImportError: cannot import name IncompleteRead'?

In Windows, this worked from an administrative prompt:

  • Delete C:\Python27\Lib\site-packages\requests*
  • easy_install requests==2.3
  • pip install --upgrade pip
  • pip install --upgrade requests

Apache SSL Configuration Error (SSL Connection Error)

I was getting the same error in chrome (and different one in Firefox, IE). Also in error.log i was getting [error] [client cli.ent.ip.add] Invalid method in request \x16\x03 Following the instructions form this site I changed my configuration FROM:

<VirtualHost subdomain.domain.com:443>

   ServerAdmin [email protected]
   ServerName subdomain.domain.com

   SSLEngine On
   SSLCertificateFile conf/ssl/ssl.crt
   SSLCertificateKeyFile conf/ssl/ssl.key
</VirtualHost>

TO:

<VirtualHost _default_:443>

   ServerAdmin [email protected]
   ServerName subdomain.domain.com

   SSLEngine On
   SSLCertificateFile conf/ssl/ssl.crt
   SSLCertificateKeyFile conf/ssl/ssl.key
</VirtualHost>

Now it's working fine :)

Generate 'n' unique random numbers within a range

You could add to a set until you reach n:

setOfNumbers = set()
while len(setOfNumbers) < n:
    setOfNumbers.add(random.randint(numLow, numHigh))

Be careful of having a smaller range than will fit in n. It will loop forever, unable to find new numbers to insert up to n

How can I find the last element in a List<>?

To get the last item of a collection use LastOrDefault() and Last() extension methods

var lastItem = integerList.LastOrDefault();

OR

var lastItem = integerList.Last();

Remeber to add using System.Linq;, or this method won't be available.

crop text too long inside div

_x000D_
_x000D_
   .cut_text {_x000D_
      white-space: nowrap; _x000D_
      width: 200px; _x000D_
      border: 1px solid #000000;_x000D_
      overflow: hidden;_x000D_
      text-overflow: ellipsis;_x000D_
    }
_x000D_
<div class="cut_text">_x000D_
_x000D_
very long text_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I get TimeSpan in minutes given two Dates?

Why not just doing it this way?

DateTime dt1 = new DateTime(2009, 6, 1);
DateTime dt2 = DateTime.Now;
double totalminutes = (dt2 - dt1).TotalMinutes;

Hope this helps.

How to use Lambda in LINQ select statement

Lambda Expression result

var storesList = context.Stores.Select(x => new { Value= x.name,Text= x.ID }).ToList();

How can one develop iPhone apps in Java?

If you've completed your other projects, why not take the time to learn Objective-C? There is a ton of material out on the web to help you get started. Honestly, it won't be that hard and learning to do some memory management will be a great learning exercise. Have you programmed in C before?

Most cross compilers won't do a great job in converting your code, and debugging your project may become much more difficult if you develop them this way.

IntelliJ Organize Imports

In addition to Optimize Imports and Auto Import, which were pointed out by @dave-newton and @ryan-stewart in earlier answers, go to:

  • IDEA <= 13: File menu > Settings > Code Style > Java > Imports
  • IDEA >= 14: File menu > Settings > Editor > Code Style > Java > Imports (thanks to @mathias-bader for the hint!) Settings dialog

There you can fine tune the grouping and order or imports, "Class count to use import with '*'", etc.

Note:
since IDEA 13 you can configure the project default settings from the IDEA "start page": Configure > Project defaults > Settings > .... Then every new project will have those default settings: enter image description here

how does Request.QueryString work?

The QueryString collection is used to retrieve the variable values in the HTTP query string.

The HTTP query string is specified by the values following the question mark (?), like this:

Link with a query string

The line above generates a variable named txt with the value "this is a query string test".

Query strings are also generated by form submission, or by a user typing a query into the address bar of the browser.

And see this sample : http://www.codeproject.com/Articles/5876/Passing-variables-between-pages-using-QueryString

refer this : http://www.dotnetperls.com/querystring

you can collect More details in google .

How do you open an SDF file (SQL Server Compact Edition)?

You can open SQL Compact 4.0 Databases from Visual Studio 2012 directly, by going to

  1. View ->
  2. Server Explorer ->
  3. Data Connections ->
  4. Add Connection...
  5. Change... (Data Source:)
  6. Microsoft SQL Server Compact 4.0
  7. Browse...

and following the instructions there.

If you're okay with them being upgraded to 4.0, you can open older versions of SQL Compact Databases also - handy if you just want to have a look at some tables, etc for stuff like Windows Phone local database development.

(note I'm not sure if this requires a specific SKU of VS2012, if it helps I'm running Premium)

mysql server port number

port number 3306 is used for MySQL and tomcat using 8080 port.more port numbers are available for run the servers or software whatever may be for our instant compilation..8080 is default for number so only we are getting port error in eclipse IDE. jvm and tomcat always prefer the 8080.3306 is default port number for MySQL.So only do not want to mention every time as "localhost:3306"

  <?php  
    $dbhost = 'localhost:3306';
//3306 default port number $dbhost='localhost'; is enough to specify the port number
//when we are utilizing xammp default port number is 8080.
      $dbuser = 'root';
      $dbpass = '';
         $db='users';

             $conn = mysqli_connect($dbhost, $dbuser, $dbpass,$db) or die ("could not connect to mysql");      

              // mysqli_select_db("users") or die ("no database");  

    if(! $conn ) {
        die('Could not connect: ' . mysqli_error($conn));
    }else{
        echo 'Connected successfully';
    }
    ?>

Test if string begins with a string?

There are several ways to do this:

InStr

You can use the InStr build-in function to test if a String contains a substring. InStr will either return the index of the first match, or 0. So you can test if a String begins with a substring by doing the following:

If InStr(1, "Hello World", "Hello W") = 1 Then
    MsgBox "Yep, this string begins with Hello W!"
End If

If InStr returns 1, then the String ("Hello World"), begins with the substring ("Hello W").

Like

You can also use the like comparison operator along with some basic pattern matching:

If "Hello World" Like "Hello W*" Then
    MsgBox "Yep, this string begins with Hello W!"
End If

In this, we use an asterisk (*) to test if the String begins with our substring.

Convert string to date in Swift

Just your passing your dateformate and your date then you get Year,month,day,hour. Extra info

func GetOnlyDateMonthYearFromFullDate(currentDateFormate:NSString , conVertFormate:NSString , convertDate:NSString ) -> NSString
    {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = currentDateFormate as String
        let formatter = NSDateFormatter()
        formatter.dateFormat = Key_DATE_FORMATE as String
        let finalDate = formatter.dateFromString(convertDate as String)
        formatter.dateFormat = conVertFormate as String
        let dateString = formatter.stringFromDate(finalDate!)

        return dateString
    }


Get Year

let Year = self.GetOnlyDateMonthYearFromFullDate("yyyy-MM-dd'T'HH:mm:ssZ", conVertFormate: "YYYY", convertDate: "2016-04-14T10:44:00+0000") as String


Get Month

let month = self.GetOnlyDateMonthYearFromFullDate("yyyy-MM-dd'T'HH:mm:ssZ", conVertFormate: "MM", convertDate: "2016-04-14T10:44:00+0000") as String


Get Day

let day = self.GetOnlyDateMonthYearFromFullDate("yyyy-MM-dd'T'HH:mm:ssZ", conVertFormate: "dd", convertDate: "2016-04-14T10:44:00+0000") as String


Get Hour

let hour  = self.GetOnlyDateMonthYearFromFullDate("yyyy-MM-dd'T'HH:mm:ssZ", conVertFormate: "hh", convertDate: "2016-04-14T10:44:00+0000") as String

How to display the first few characters of a string in Python?

If you want first 2 letters and last 2 letters of a string then you can use the following code: name = "India" name[0:2]="In" names[-2:]="ia"

HTML Code for text checkbox '?'

U+F0FE ? is not a checkbox, it's a Private Use Area character that might render as anything. Whilst you can certainly try to include it in an HTML document, either directly in a UTF-8 document, or as a character reference like &#xF0FE;, you shouldn't expect it to render as a checkbox. It certainly doesn't on any of my browsers—although on some the ‘unknown character’ glyph is a square box that at least looks similar!

So where does U+F0FE come from? It is an unfortunate artifact of Word RTF export where the original document used a symbol font: one with no standard mapping to normal unicode characters; specifically, in this case, Wingdings. If you need to accept Word RTF from documents still authored with symbol fonts, then you will need to map those symbol characters to proper Unicode characters. Unfortunately that's tricky as it requires you to know the particular symbol font and have a map for it. See this post for background.

The standardised Unicode characters that best represent a checkbox are:

  • ?, U+2610 Ballot box
  • ?, U+2611 Ballot box with check

If you don't have a Unicode-safe editor you can naturally spell them as &#x2610; and &#x2611;.

(There is also U+2612 using an X, ?.)

How to implement band-pass Butterworth filter with Scipy.signal.butter

The filter design method in accepted answer is correct, but it has a flaw. SciPy bandpass filters designed with b, a are unstable and may result in erroneous filters at higher filter orders.

Instead, use sos (second-order sections) output of filter design.

from scipy.signal import butter, sosfilt, sosfreqz

def butter_bandpass(lowcut, highcut, fs, order=5):
        nyq = 0.5 * fs
        low = lowcut / nyq
        high = highcut / nyq
        sos = butter(order, [low, high], analog=False, btype='band', output='sos')
        return sos

def butter_bandpass_filter(data, lowcut, highcut, fs, order=5):
        sos = butter_bandpass(lowcut, highcut, fs, order=order)
        y = sosfilt(sos, data)
        return y

Also, you can plot frequency response by changing

b, a = butter_bandpass(lowcut, highcut, fs, order=order)
w, h = freqz(b, a, worN=2000)

to

sos = butter_bandpass(lowcut, highcut, fs, order=order)
w, h = sosfreqz(sos, worN=2000)

Append text using StreamWriter

using(StreamWriter writer = new StreamWriter("debug.txt", true))
{
  writer.WriteLine("whatever you text is");
}

The second "true" parameter tells it to append.

http://msdn.microsoft.com/en-us/library/36b035cb.aspx

Using parameters in batch files at Windows command line

As others have already said, parameters passed through the command line can be accessed in batch files with the notation %1 to %9. There are also two other tokens that you can use:

  • %0 is the executable (batch file) name as specified in the command line.
  • %* is all parameters specified in the command line -- this is very useful if you want to forward the parameters to another program.

There are also lots of important techniques to be aware of in addition to simply how to access the parameters.

Checking if a parameter was passed

This is done with constructs like IF "%~1"=="", which is true if and only if no arguments were passed at all. Note the tilde character which causes any surrounding quotes to be removed from the value of %1; without a tilde you will get unexpected results if that value includes double quotes, including the possibility of syntax errors.

Handling more than 9 arguments (or just making life easier)

If you need to access more than 9 arguments you have to use the command SHIFT. This command shifts the values of all arguments one place, so that %0 takes the value of %1, %1 takes the value of %2, etc. %9 takes the value of the tenth argument (if one is present), which was not available through any variable before calling SHIFT (enter command SHIFT /? for more options).

SHIFT is also useful when you want to easily process parameters without requiring that they are presented in a specific order. For example, a script may recognize the flags -a and -b in any order. A good way to parse the command line in such cases is

:parse
IF "%~1"=="" GOTO endparse
IF "%~1"=="-a" REM do something
IF "%~1"=="-b" REM do something else
SHIFT
GOTO parse
:endparse
REM ready for action!

This scheme allows you to parse pretty complex command lines without going insane.

Substitution of batch parameters

For parameters that represent file names the shell provides lots of functionality related to working with files that is not accessible in any other way. This functionality is accessed with constructs that begin with %~.

For example, to get the size of the file passed in as an argument use

ECHO %~z1

To get the path of the directory where the batch file was launched from (very useful!) you can use

ECHO %~dp0

You can view the full range of these capabilities by typing CALL /? in the command prompt.

bash echo number of lines of file given in a bash variable without the file name

wc can't get the filename if you don't give it one.

wc -l < "$JAVA_TAGS_FILE"

python-pandas and databases like mysql

As Wes says, io/sql's read_sql will do it, once you've gotten a database connection using a DBI compatible library. We can look at two short examples using the MySQLdb and cx_Oracle libraries to connect to Oracle and MySQL and query their data dictionaries. Here is the example for cx_Oracle:

import pandas as pd
import cx_Oracle

ora_conn = cx_Oracle.connect('your_connection_string')
df_ora = pd.read_sql('select * from user_objects', con=ora_conn)    
print 'loaded dataframe from Oracle. # Records: ', len(df_ora)
ora_conn.close()

And here is the equivalent example for MySQLdb:

import MySQLdb
mysql_cn= MySQLdb.connect(host='myhost', 
                port=3306,user='myusername', passwd='mypassword', 
                db='information_schema')
df_mysql = pd.read_sql('select * from VIEWS;', con=mysql_cn)    
print 'loaded dataframe from MySQL. records:', len(df_mysql)
mysql_cn.close()

Setting public class variables

Inside class Testclass:

public function __construct($new_value)
{
    $this->testvar = $new_value;
}

'uint32_t' identifier not found error

On Windows I usually use windows types. To use it you have to include <Windows.h>.

In this case uint32_t is UINT32 or just UINT.

All types definitions are here: http://msdn.microsoft.com/en-us/library/windows/desktop/aa383751%28v=vs.85%29.aspx

How to Deep clone in javascript

This is the deep cloning method I use, I think it Great, hope you make suggestions

function deepClone (obj) {
    var _out = new obj.constructor;

    var getType = function (n) {
        return Object.prototype.toString.call(n).slice(8, -1);
    }

    for (var _key in obj) {
        if (obj.hasOwnProperty(_key)) {
            _out[_key] = getType(obj[_key]) === 'Object' || getType(obj[_key]) === 'Array' ? deepClone(obj[_key]) : obj[_key];
        }
    }
    return _out;
}

How can I go back/route-back on vue-router?

This works like a clock for me:

methods: {
 hasHistory () { return window.history.length > 2 }
}

Then, in the template:

<button 
  type="button"    
  @click="hasHistory() 
    ? $router.go(-1) 
    : $router.push('/')" class="my-5 btn btn-outline-success">&laquo; 
  Back
</button>

PHP code to get selected text of a combo box

Try with this. You will get the select box value in $_POST['Make'] and name will get in $_POST['selected_text']

<form method="POST" >
<label for="Manufacturer"> Manufacturer : </label>
  <select id="cmbMake" name="Make"     onchange="document.getElementById('selected_text').value=this.options[this.selectedIndex].text">
     <option value="0">Select Manufacturer</option>
     <option value="1">--Any--</option>
     <option value="2">Toyota</option>
     <option value="3">Nissan</option>
</select>
<input type="hidden" name="selected_text" id="selected_text" value="" />
<input type="submit" name="search" value="Search"/>
</form>


 <?php

if(isset($_POST['search']))
{

    $makerValue = $_POST['Make']; // make value

    $maker = mysql_real_escape_string($_POST['selected_text']); // get the selected text
    echo $maker;
}
 ?>

How to update the constant height constraint of a UIView programmatically?

First connect the Height constraint in to our viewcontroller for creating IBOutlet like the below code shown

@IBOutlet weak var select_dateHeight: NSLayoutConstraint!

then put the below code in view did load or inside any actions

self.select_dateHeight.constant = 0 // we can change the height value

if it is inside a button click

@IBAction func Feedback_button(_ sender: Any) {
 self.select_dateHeight.constant = 0

}

Getting String value from enum in Java

Use default method name() as given bellows

public enum Category {
        ONE("one"),
        TWO ("two"),
        THREE("three");

        private final String name;

        Category(String s) {
            name = s;
        }

    }

public class Main {
    public static void main(String[] args) throws Exception {
        System.out.println(Category.ONE.name());
    }
}

Preferred way to create a Scala list

just an example that uses collection.breakOut

scala> val a : List[Int] = (for( x <- 1 to 10 ) yield x * 3)(collection.breakOut)
a: List[Int] = List(3, 6, 9, 12, 15, 18, 21, 24, 27, 30)

scala> val b : List[Int] = (1 to 10).map(_ * 3)(collection.breakOut)
b: List[Int] = List(3, 6, 9, 12, 15, 18, 21, 24, 27, 30)

How to increase editor font size?

Acoustics answer works, on windows it would be File --> Settings --> Editor --> Colors & Fonts then save as, name it something then you can edit all the fields you want.

How do I get 'date-1' formatted as mm-dd-yyyy using PowerShell?

    Windows PowerShell
    Copyright (C) 2014 Microsoft Corporation. All rights reserved.

    PS C:\Windows\system32> **$dte = Get-Date**
    PS C:\Windows\system32> **$PastDueDate = $dte.AddDays(-45).Date**
    PS C:\Windows\system32> **$PastDueDate**

    Sunday, March 1, 2020 12:00:00 AM

   PS C:\Windows\system32> **$NewDateFormat = Get-Date $PastDueDate -Format MMddyyyy**
   PS C:\Windows\system32> **$NewDateFormat 03012020**

There're few additional methods available as well e.g.: $dte.AddDays(-45).Day

How can I change the image of an ImageView?

Just to go a little bit further in the matter, you can also set a bitmap directly, like this:

ImageView imageView = new ImageView(this);  
Bitmap bImage = BitmapFactory.decodeResource(this.getResources(), R.drawable.my_image);
imageView.setImageBitmap(bImage);

Of course, this technique is only useful if you need to change the image.

Access properties file programmatically with Spring?

Here is another sample .

XmlBeanFactory factory = new XmlBeanFactory(new FileSystemResource("beans.xml"));
PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer();
cfg.setLocation(new FileSystemResource("jdbc.properties"));
cfg.postProcessBeanFactory(factory);

How can I remove an entry in global configuration with git config?

You can edit the ~/.gitconfig file in your home folder. This is where all --global settings are saved.

Python's "in" set operator

Yes it can mean so, or it can be a simple iterator. For example: Example as iterator:

a=set(['1','2','3'])
for x in a:
 print ('This set contains the value ' + x)

Similarly as a check:

a=set('ILovePython')
if 'I' in a:
 print ('There is an "I" in here')

edited: edited to include sets rather than lists and strings

Blank HTML SELECT without blank item in dropdown list

Just use disabled and/or hidden attributes:

<option selected disabled hidden style='display: none' value=''></option>
  • selected makes this option the default one.
  • disabled makes this option unclickable.
  • style='display: none' makes this option not displayed in older browsers. See: Can I Use documentation for hidden attribute.
  • hidden makes this option to don't be displayed in the drop-down list.

Input size vs width

You can use both. The css style will override the size attribute in browsers that support CSS and make the field the correct width, and for those that don't, it will fall back to the specified number of characters.

Edit: I should have mentioned that the size attribute isn't a precise method of sizing: according to the HTML specification, it should refer to the number of characters of the current font the input will be able to display at once.

However, unless the font specified is a fixed-width/monospace font, this is not a guarantee that the specified number of characters will actually be visible; in most fonts, different characters will be different widths. This question has some good answers relating to this issue.

The snippet below demonstrates both approaches.

_x000D_
_x000D_
@font-face {_x000D_
    font-family: 'Diplomata';_x000D_
    font-style: normal;_x000D_
    font-weight: 400;_x000D_
    src: local('Diplomata'), local('Diplomata-Regular'), url(https://fonts.gstatic.com/s/diplomata/v8/8UgOK_RUxkBbV-q561I6kFtXRa8TVwTICgirnJhmVJw.woff2) format('woff2');_x000D_
    unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215;_x000D_
}_x000D_
@font-face {_x000D_
    font-family: 'Open Sans Condensed';_x000D_
    font-style: normal;_x000D_
    font-weight: 300;_x000D_
    src: local('Open Sans Condensed Light'), local('OpenSansCondensed-Light'), url(https://fonts.gstatic.com/s/opensanscondensed/v11/gk5FxslNkTTHtojXrkp-xBEur64QvLD-0IbiAdTUNXE.woff2) format('woff2');_x000D_
    unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215;_x000D_
}_x000D_
p {_x000D_
  margin: 0 0 10px 0;_x000D_
}_x000D_
input {_x000D_
  font-size: 20px;_x000D_
}_x000D_
.narrow-font {_x000D_
  font-family: 'Open Sans Condensed', sans-serif;_x000D_
}_x000D_
.wide-font {_x000D_
  font-family: 'Diplomata', cursive;_x000D_
}_x000D_
.set-width {_x000D_
  width: 220px;_x000D_
}
_x000D_
<p>_x000D_
  <input type="text" size="10" class="narrow-font" value="0123456789" />_x000D_
</p>_x000D_
<p>_x000D_
  <input type="text" size="10" class="wide-font" value="0123456789" />_x000D_
</p>_x000D_
<p>_x000D_
  <input type="text" size="10" class="narrow-font set-width" value="0123456789" />_x000D_
</p>_x000D_
<p>_x000D_
  <input type="text" size="10" class="wide-font set-width" value="0123456789" />_x000D_
</p>
_x000D_
_x000D_
_x000D_

Why can't static methods be abstract in Java?

You can't override a static method, so making it abstract would be meaningless. Moreover, a static method in an abstract class would belong to that class, and not the overriding class, so couldn't be used anyway.

Create a batch file to run an .exe with an additional parameter

You can use

start "" "%USERPROFILE%\Desktop\BGInfo\bginfo.exe" "%USERPROFILE%\Desktop\BGInfo\dc_bginfo.bgi"

or

start "" /D "%USERPROFILE%\Desktop\BGInfo" bginfo.exe dc_bginfo.bgi

or

"%USERPROFILE%\Desktop\BGInfo\bginfo.exe" "%USERPROFILE%\Desktop\BGInfo\dc_bginfo.bgi"

or

cd /D "%USERPROFILE%\Desktop\BGInfo"
bginfo.exe dc_bginfo.bgi

Help on commands start and cd is output by executing in a command prompt window help start or start /? and help cd or cd /?.

But I do not understand why you need a batch file at all for starting the application with the additional parameter. Create a shortcut (*.lnk) on your desktop for this application. Then right click on the shortcut, left click on Properties and append after a space character "%USERPROFILE%\Desktop\BGInfo\dc_bginfo.bgi" as parameter.

Cannot make file java.io.IOException: No such file or directory

If the directory ../.foo/bar/ doesn't exist, you can't create a file there, so make sure you create the directory first.

Try something like this:

File f = new File("somedirname1/somedirname2/somefilename");
if (!f.getParentFile().exists())
    f.getParentFile().mkdirs();
if (!f.exists())
    f.createNewFile();

How to pass complex object to ASP.NET WebApi GET from jQuery ajax call?

If you append json data to query string, and parse it later in web api side. you can parse complex object. It's useful rather than post json object style. This is my solution.

//javascript file 
var data = { UserID: "10", UserName: "Long", AppInstanceID: "100", ProcessGUID: "BF1CC2EB-D9BD-45FD-BF87-939DD8FF9071" };
var request = JSON.stringify(data);
request = encodeURIComponent(request);

doAjaxGet("/ProductWebApi/api/Workflow/StartProcess?data=", request, function (result) {
    window.console.log(result);
});

//webapi file:
[HttpGet]
public ResponseResult StartProcess()
{
    dynamic queryJson = ParseHttpGetJson(Request.RequestUri.Query);
        int appInstanceID = int.Parse(queryJson.AppInstanceID.Value);
    Guid processGUID = Guid.Parse(queryJson.ProcessGUID.Value);
    int userID = int.Parse(queryJson.UserID.Value);
    string userName = queryJson.UserName.Value;
}

//utility function:
public static dynamic ParseHttpGetJson(string query)
{
    if (!string.IsNullOrEmpty(query))
    {
        try
        {
            var json = query.Substring(7, query.Length - 7); //seperate ?data= characters
            json = System.Web.HttpUtility.UrlDecode(json);
            dynamic queryJson = JsonConvert.DeserializeObject<dynamic>(json);

            return queryJson;
        }
        catch (System.Exception e)
        {
            throw new ApplicationException("can't deserialize object as wrong string content!", e);
        }
    }
    else
    {
        return null;
    }
}

How to configure log4j.properties for SpringJUnit4ClassRunner?

I know this is old, but I was having trouble too. For Spring 3 using Maven and Eclipse, I needed to put the log4j.xml in src/test/resources for the Unit test to log properly. Placing in in the root of the test did not work for me. Hopefully this helps others.

Postgresql, update if row with some unique value exists, else insert

Firstly It tries insert. If there is a conflict on url column then it updates content and last_analyzed fields. If updates are rare this might be better option.

INSERT INTO URLs (url, content, last_analyzed)
VALUES
    (
        %(url)s,
        %(content)s,
        NOW()
    ) 
ON CONFLICT (url) 
DO
UPDATE
SET content=%(content)s, last_analyzed = NOW();

You must enable the openssl extension to download files via https

I had to uncomment extension=openssl in php.ini file for everything to work!

Remove a cookie

When you enter 0 for time, you mean "now" (+0s from now is actually now) for the browser and it deletes the cookie.

setcookie("key", NULL, 0, "/");

I checked it in chrome browser that gives me:

Name: key
Content: Deleted
Created: Sunday, November 18, 2018 at 2:33:14 PM
Expires: Sunday, November 18, 2018 at 2:33:14 PM

How to round the double value to 2 decimal points?

public static double addDoubles(double a, double b) {
        BigDecimal A = new BigDecimal(a + "");
        BigDecimal B = new BigDecimal(b + "");
        return A.add(B).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

Check if a file exists in jenkins pipeline

You need to use brackets when using the fileExists step in an if condition or assign the returned value to a variable

Using variable:

def exists = fileExists 'file'

if (exists) {
    echo 'Yes'
} else {
    echo 'No'
}

Using brackets:

if (fileExists('file')) {
    echo 'Yes'
} else {
    echo 'No'
}

I need a Nodejs scheduler that allows for tasks at different intervals

I think the best ranking is

1.node-schedule

2.later

3.crontab

and the sample of node-schedule is below:

var schedule = require("node-schedule");
var rule = new schedule.RecurrenceRule();
//rule.minute = 40;
rule.second = 10;
var jj = schedule.scheduleJob(rule, function(){
    console.log("execute jj");
});

Maybe you can find the answer from node modules.

Stop floating divs from wrapping

After reading John's answer, I discovered the following seemed to work for us (did not require specifying width):

<style>
.row {
    float:left;
    border: 1px solid yellow;
    overflow: visible;
    white-space: nowrap;
}

.cell {
    display: inline-block;
    border: 1px solid red;
    height: 100px;
}
</style>

<div class="row">
    <div class="cell">hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello </div>
    <div class="cell">hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello </div>
    <div class="cell">hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello </div>
</div>

Fastest way to remove non-numeric characters from a VARCHAR in SQL Server

In case you didn't want to create a function, or you needed just a single inline call in T-SQL, you could try:

set @Phone = REPLACE(REPLACE(REPLACE(REPLACE(@Phone,'(',''),' ',''),'-',''),')','')

Of course this is specific to removing phone number formatting, not a generic remove all special characters from string function.

How to navigate to a section of a page

Use HTML's anchors:

Main Page:

<a href="sample.html#sushi">Sushi</a>
<a href="sample.html#bbq">BBQ</a>

Sample Page:

<div id='sushi'><a name='sushi'></a></div>
<div id='bbq'><a name='bbq'></a></div>

DTO pattern: Best way to copy properties between two objects

You can have a look at dozer which is a

Java Bean to Java Bean mapper that recursively copies data from one object to another. Typically, these Java Beans will be of different complex types.

Another better link...

What is console.log?

It is used to log (anything you pass it) to the Firebug console. The main usage would be to debug your JavaScript code.

C++ deprecated conversion from string constant to 'char*'

There are 3 solutions:

Solution 1:

const char *x = "foo bar";

Solution 2:

char *x = (char *)"foo bar";

Solution 3:

char* x = (char*) malloc(strlen("foo bar")+1); // +1 for the terminator
strcpy(x,"foo bar");

Arrays also can be used instead of pointers because an array is already a constant pointer.

What is difference between functional and imperative programming languages?

Definition: An imperative language uses a sequence of statements to determine how to reach a certain goal. These statements are said to change the state of the program as each one is executed in turn.

Examples: Java is an imperative language. For example, a program can be created to add a series of numbers:

 int total = 0;
 int number1 = 5;
 int number2 = 10;
 int number3 = 15;
 total = number1 + number2 + number3; 

Each statement changes the state of the program, from assigning values to each variable to the final addition of those values. Using a sequence of five statements the program is explicitly told how to add the numbers 5, 10 and 15 together.

Functional languages: The functional programming paradigm was explicitly created to support a pure functional approach to problem solving. Functional programming is a form of declarative programming.

Advantages of Pure Functions: The primary reason to implement functional transformations as pure functions is that pure functions are composable: that is, self-contained and stateless. These characteristics bring a number of benefits, including the following: Increased readability and maintainability. This is because each function is designed to accomplish a specific task given its arguments. The function does not rely on any external state.

Easier reiterative development. Because the code is easier to refactor, changes to design are often easier to implement. For example, suppose you write a complicated transformation, and then realize that some code is repeated several times in the transformation. If you refactor through a pure method, you can call your pure method at will without worrying about side effects.

Easier testing and debugging. Because pure functions can more easily be tested in isolation, you can write test code that calls the pure function with typical values, valid edge cases, and invalid edge cases.

For OOP People or Imperative languages:

Object-oriented languages are good when you have a fixed set of operations on things and as your code evolves, you primarily add new things. This can be accomplished by adding new classes which implement existing methods and the existing classes are left alone.

Functional languages are good when you have a fixed set of things and as your code evolves, you primarily add new operations on existing things. This can be accomplished by adding new functions which compute with existing data types and the existing functions are left alone.

Cons:

It depends on the user requirements to choose the way of programming, so there is harm only when users don’t choose the proper way.

When evolution goes the wrong way, you have problems:

  • Adding a new operation to an object-oriented program may require editing many class definitions to add a new method
  • Adding a new kind of thing to a functional program may require editing many function definitions to add a new case.

How to load/edit/run/save text files (.py) into an IPython notebook cell?

To write/save

%%writefile myfile.py

  • write/save cell contents into myfile.py (use -a to append). Another alias: %%file myfile.py

To run

%run myfile.py

  • run myfile.py and output results in the current cell

To load/import

%load myfile.py

  • load "import" myfile.py into the current cell

For more magic and help

%lsmagic

  • list all the other cool cell magic commands.

%COMMAND-NAME?

  • for help on how to use a certain command. i.e. %run?

Note

Beside the cell magic commands, IPython notebook (now Jupyter notebook) is so cool that it allows you to use any unix command right from the cell (this is also equivalent to using the %%bash cell magic command).

To run a unix command from the cell, just precede your command with ! mark. for example:

  • !python --version see your python version
  • !python myfile.py run myfile.py and output results in the current cell, just like %run (see the difference between !python and %run in the comments below).

Also, see this nbviewer for further explanation with examples. Hope this helps.

how to delete all cookies of my website in php

All previous answers have overlooked that the setcookie could have been used with an explicit domain. Furthermore, the cookie might have been set on a higher subdomain, e.g. if you were on a foo.bar.tar.com domain, there might be a cookie set on tar.com. Therefore, you want to unset cookies for all domains that might have dropped the cookie:

$host = explode('.', $_SERVER['HTTP_HOST']);

while ($host) {
    $domain = '.' . implode('.', $host);

    foreach ($_COOKIE as $name => $value) {
        setcookie($name, '', 1, '/', $domain);
    }

    array_shift($host);
}

How to tell if JRE or JDK is installed

A generic, pure Java solution..

For Windows and MacOS, the following can be inferred (most of the time)...

public static boolean isJDK() {
    String path = System.getProperty("sun.boot.library.path");
    if(path != null && path.contains("jdk")) {
        return true;
    }
    return false;
}

However... on Linux this isn't as reliable... For example...

  • Many JREs on Linux contain openjdk the path
  • There's no guarantee that the JRE doesn't also contain a JDK.

So a more fail-safe approach is to check for the existence of the javac executable.

public static boolean isJDK() {
    String path = System.getProperty("sun.boot.library.path");
    if(path != null) {
        String javacPath = "";
        if(path.endsWith(File.separator + "bin")) {
            javacPath = path;
        } else {
            int libIndex = path.lastIndexOf(File.separator + "lib");
            if(libIndex > 0) {
                javacPath = path.substring(0, libIndex) + File.separator + "bin";
            }
        }
        if(!javacPath.isEmpty()) {
            return new File(javacPath, "javac").exists() || new File(javacPath, "javac.exe").exists();
        }
    }
    return false;
}

Warning: This will still fail for JRE + JDK combos which report the JRE's sun.boot.library.path identically between the JRE and the JDK. For example, Fedora's JDK will fail (or pass depending on how you look at it) when the above code is run. See unit tests below for more info...

Unit tests:

# Unix
java -XshowSettings:properties -version 2>&1|grep "sun.boot.library.path"
# Windows
java -XshowSettings:properties -version 2>&1|find "sun.boot.library.path"
    # PASS: MacOS AdoptOpenJDK JDK11
    /Library/Java/JavaVirtualMachines/adoptopenjdk-11.jdk/Contents/Home/lib

    # PASS: Windows Oracle JDK12
    c:\Program Files\Java\jdk-12.0.2\bin

    # PASS: Windows Oracle JRE8
    C:\Program Files\Java\jre1.8.0_181\bin

    # PASS: Windows Oracle JDK8
    C:\Program Files\Java\jdk1.8.0_181\bin

    # PASS: Ubuntu AdoptOpenJDK JDK11
    /usr/lib/jvm/adoptopenjdk-11-hotspot-amd64/lib

    # PASS: Ubuntu Oracle JDK11
    /usr/lib/jvm/java-11-oracle/lib

    # PASS: Fedora OpenJDK JDK8
    /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.141-1.b16.fc24.x86_64/jre/lib/amd64

    #### FAIL: Fedora OpenJDK JDK8
    /usr/java/jdk1.8.0_231-amd64/jre/lib/amd64

phpMyAdmin + CentOS 6.0 - Forbidden

I had the same issue.

Only after I changed in php.ini variable

display_errors = Off

to

display_errors = On

Phpadmin started working.. crazy....

string.IsNullOrEmpty(string) vs. string.IsNullOrWhiteSpace(string)

Check this out with IsNullOrEmpty and IsNullOrwhiteSpace

string sTestes = "I like sweat peaches";
    Stopwatch stopWatch = new Stopwatch();
    stopWatch.Start();
    for (int i = 0; i < 5000000; i++)
    {
        for (int z = 0; z < 500; z++)
        {
            var x = string.IsNullOrEmpty(sTestes);// OR string.IsNullOrWhiteSpace
        }
    }

    stopWatch.Stop();
    // Get the elapsed time as a TimeSpan value.
    TimeSpan ts = stopWatch.Elapsed;
    // Format and display the TimeSpan value. 
    string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
        ts.Hours, ts.Minutes, ts.Seconds,
        ts.Milliseconds / 10);
    Console.WriteLine("RunTime " + elapsedTime);
    Console.ReadLine();

You'll see that IsNullOrWhiteSpace is much slower :/

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

The answer from stereointeractive covers all the options. Just wanted to mention an alternate way of using FTP. I'm guessing that the reason you are not allowing FTP access is for security. One way to address those security concerns is to run your FTP server listening only on 127.0.0.1

This allows you to use FTP from inside WordPress and you will be able to install plugins while not exposing it to the rest of the world. This can also be applied to other popular web applications such as Joomla! and Drupal. This is what we do with our BitNami appliances and cloud servers and works quite well.

How big can a MySQL database get before performance starts to degrade

In general this is a very subtle issue and not trivial whatsoever. I encourage you to read mysqlperformanceblog.com and High Performance MySQL. I really think there is no general answer for this.

I'm working on a project which has a MySQL database with almost 1TB of data. The most important scalability factor is RAM. If the indexes of your tables fit into memory and your queries are highly optimized, you can serve a reasonable amount of requests with a average machine.

The number of records do matter, depending of how your tables look like. It's a difference to have a lot of varchar fields or only a couple of ints or longs.

The physical size of the database matters as well: think of backups, for instance. Depending on your engine, your physical db files on grow, but don't shrink, for instance with innodb. So deleting a lot of rows, doesn't help to shrink your physical files.

There's a lot to this issues and as in a lot of cases the devil is in the details.

How can I check if my python object is a number?

Sure you can use isinstance, but be aware that this is not how Python works. Python is a duck typed language. You should not explicitly check your types. A TypeError will be raised if the incorrect type was passed.

So just assume it is an int. Don't bother checking.

How can I remove an SSH key?

Check if folder .ssh is on your system

  1. Go to folder --> /Users/administrator/.ssh/id_ed25519.pub

If not, then

  1. Open Terminal.

Paste in the terminal

  1. Check user ? ssh -T [email protected]

Remove existing SSH keys

  1. Remove existing SSH keys ? rm ~/.ssh/github_rsa.pub

Create New

  1. Create new SSH key ? ssh-keygen -t rsa -b 4096 -C "[email protected]"

  2. The public key has been saved in "/Users/administrator/.ssh/id_ed25519.pub."

  3. Open the public key saved path.

  4. Copy the SSH key ? GitLab Account ? Setting ? SSH Key ? Add key

  5. Test again from the terminal ? ssh -T [email protected]

How do I center floated elements?

Set your container's width in px and add:

margin: 0 auto;

Reference.

Cannot find "Package Explorer" view in Eclipse

Not all view are listed directly in every perspective ... choose:

Window->Show View->Other...->Java->Package Explorer

Where can I find a NuGet package for upgrading to System.Web.Http v5.0.0.0?

You need the Microsoft.AspNet.WebApi.Core package.

You can see it in the .csproj file:

<Reference Include="System.Web.Http, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
  <SpecificVersion>False</SpecificVersion>
  <HintPath>..\packages\Microsoft.AspNet.WebApi.Core.5.0.0\lib\net45\System.Web.Http.dll</HintPath>
</Reference>

UIButton Image + Text IOS

I see very complicated answers, all of them using code. However, if you are using Interface Builder, there is a very easy way to do this:

  1. Select the button and set a title and an image. Note that if you set the background instead of the image then the image will be resized if it is smaller than the button.IB basic image and title
  2. Set the position of both items by changing the edge and insets. You could even control the alignment of both in the Control section.

IB position set IB Control set

You could even use the same approach by code, without creating UILabels and UIImages inside as other solutions proposed. Always Keep It Simple!

EDIT: Attached a small example having the 3 things set (title, image and background) with correct insets Button preview

Android open pdf file

As of API 24, sending a file:// URI to another app will throw a FileUriExposedException. Instead, use FileProvider to send a content:// URI:

public File getFile(Context context, String fileName) {
    if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        return null;
    }

    File storageDir = context.getExternalFilesDir(null);
    return new File(storageDir, fileName);
}

public Uri getFileUri(Context context, String fileName) {
    File file = getFile(context, fileName);
    return FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider", file);
}

You must also define the FileProvider in your manifest:

<provider
    android:name="android.support.v4.content.FileProvider"
    android:authorities="com.mydomain.fileprovider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths" />
</provider>

Example file_paths.xml:

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-files-path name="name" path="path" />
</paths>

Replace "name" and "path" as appropriate.

To give the PDF viewer access to the file, you also have to add the FLAG_GRANT_READ_URI_PERMISSION flag to the intent:

private void displayPdf(String fileName) {
    Uri uri = getFileUri(this, fileName);

    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(uri, "application/pdf");

    // FLAG_GRANT_READ_URI_PERMISSION is needed on API 24+ so the activity opening the file can read it
    intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_GRANT_READ_URI_PERMISSION);

    if (intent.resolveActivity(getPackageManager()) == null) {
        // Show an error
    } else {
        startActivity(intent);
    }
}

See the FileProvider documentation for more details.

.gitignore all the .DS_Store files in every folder and subfolder

If .DS_Store was never added to your git repository, simply add it to your .gitignore file.

If you don't have one, create a file called

.gitignore

In the root directory of your app and simply write

**/.DS_Store

In it. This will never allow the .DS_Store file to sneak in your git.

But, if it's already there, write in your terminal:

find . -name .DS_Store -print0 | xargs -0 git rm -f --ignore-unmatch

then commit and push the changes to remove the .DS_Store from your remote repo:

git commit -m "Remove .DS_Store from everywhere"

git push origin master

And now add .DS_Store to your .gitignore file, and then again commit and push with the 2 last pieces of code (git commit..., git push...)

Flex-box: Align last row to grid

Oh boy, I think I found a good solution with minimal CSS and no JS. Check it out:

_x000D_
_x000D_
img {width:100%;}_x000D_
li {_x000D_
  display: inline-block;_x000D_
  width:8em;_x000D_
  list-style:none;_x000D_
}_x000D_
ul {text-align: justify;}
_x000D_
<ul>_x000D_
  <li>_x000D_
    <img src="http://www.planwallpaper.com/static/images/kitty-cat.jpg" />_x000D_
  </li>_x000D_
  <li>_x000D_
    <img src="http://www.planwallpaper.com/static/images/kitty-cat.jpg" />_x000D_
  </li>_x000D_
  <li>_x000D_
    <img src="http://www.planwallpaper.com/static/images/kitty-cat.jpg" />_x000D_
  </li>_x000D_
  <li>_x000D_
    <img src="http://www.planwallpaper.com/static/images/kitty-cat.jpg" />_x000D_
  </li>_x000D_
  <li>_x000D_
    <img src="http://www.planwallpaper.com/static/images/kitty-cat.jpg" />_x000D_
  </li>_x000D_
  <li>_x000D_
    <img src="http://www.planwallpaper.com/static/images/kitty-cat.jpg" />_x000D_
  </li>_x000D_
  <li>_x000D_
    <img src="http://www.planwallpaper.com/static/images/kitty-cat.jpg" />_x000D_
  </li>_x000D_
  <li>_x000D_
    <img src="http://www.planwallpaper.com/static/images/kitty-cat.jpg" />_x000D_
  </li>_x000D_
  <li>_x000D_
    <img src="http://www.planwallpaper.com/static/images/kitty-cat.jpg" />_x000D_
  </li>_x000D_
  <li>_x000D_
    <img src="http://www.planwallpaper.com/static/images/kitty-cat.jpg" />_x000D_
  </li>_x000D_
  <li>_x000D_
    <img src="http://www.planwallpaper.com/static/images/kitty-cat.jpg" />_x000D_
  </li>_x000D_
  <li>_x000D_
    <img src="http://www.planwallpaper.com/static/images/kitty-cat.jpg" />_x000D_
  </li>_x000D_
  <li>_x000D_
    <img src="http://www.planwallpaper.com/static/images/kitty-cat.jpg" />_x000D_
  </li>_x000D_
  <li>_x000D_
    <img src="http://www.planwallpaper.com/static/images/kitty-cat.jpg" />_x000D_
  </li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

The key here is to remember that what we are trying to achieve is exactly what text-align: justify does!

The empty elements in the HTML are there to make the last row display perfectly without changing the appearance, but might not be needed given what you are trying to achieve. For perfect balance in every situation, you need at least x-4 empty elements, x being the number of elements to display, or n-2, n being the number of column you want to display.

Circle button css

Add display: block;. That's the difference between a <div> tag and an <a> tag

.btn {
      display: block;
      height: 300px;
      width: 300px;
      border-radius: 50%;
      border: 1px solid red;
    }

Extracting jar to specified directory

It's better to do this.

Navigate to the folder structure you require

Use the command

jar -xvf  'Path_to_ur_Jar_file'

Simple Vim commands you wish you'd known earlier

^r^w to paste the word under the cursor in command mode.

It is really useful when using grep or replace commands.

Handling data in a PHP JSON Object

You mean something like this?

<?php

$jsonurl = "http://search.twitter.com/trends.json";
$json = file_get_contents($jsonurl,0,null,null);
$json_output = json_decode($json);

foreach ( $json_output->trends as $trend )
{
    echo "{$trend->name}\n";
}

Remote Procedure call failed with sql server 2008 R2

Open Control Panel Administrative Tools Services Select Extended services tab

Find SQL Server(MSSQLSERVER) & SQL Server(SQLEXPRESS) Stop these services and Start again (from the start & stop button displayed above)

Done.

Locking a file in Python

You may find pylocker very useful. It can be used to lock a file or for locking mechanisms in general and can be accessed from multiple Python processes at once.

If you simply want to lock a file here's how it works:

import uuid
from pylocker import Locker

#  create a unique lock pass. This can be any string.
lpass = str(uuid.uuid1())

# create locker instance.
FL = Locker(filePath='myfile.txt', lockPass=lpass, mode='w')

# aquire the lock
with FL as r:
    # get the result
    acquired, code, fd  = r

    # check if aquired.
    if fd is not None:
        print fd
        fd.write("I have succesfuly aquired the lock !")

# no need to release anything or to close the file descriptor, 
# with statement takes care of that. let's print fd and verify that.
print fd

How to add a footer in ListView?

Answers here are a bit outdated. Though the code remains the same there are some changes in the behavior.

public class MyListActivity extends ListActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        TextView footerView = (TextView) ((LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.footer_view, null, false);
        getListView().addFooterView(footerView);
        setListAdapter(new ArrayAdapter<String>(this, getResources().getStringArray(R.array.news)));
    }
}

Info about addFooterView() method

Add a fixed view to appear at the bottom of the list. If addFooterView() is called more than once, the views will appear in the order they were added. Views added using this call can take focus if they want.

Most of the answers above stress very important point -

addFooterView() must be called before calling setAdapter().This is so ListView can wrap the supplied cursor with one that will also account for header and footer views.

From Kitkat this has changed.

Note: When first introduced, this method could only be called before setting the adapter with setAdapter(ListAdapter). Starting with KITKAT, this method may be called at any time. If the ListView's adapter does not extend HeaderViewListAdapter, it will be wrapped with a supporting instance of WrapperListAdapter.

Documentation

hash function for string

First, is 40 collisions for 130 words hashed to 0..99 bad? You can't expect perfect hashing if you are not taking steps specifically for it to happen. An ordinary hash function won't have fewer collisions than a random generator most of the time.

A hash function with a good reputation is MurmurHash3.

Finally, regarding the size of the hash table, it really depends what kind of hash table you have in mind, especially, whether buckets are extensible or one-slot. If buckets are extensible, again there is a choice: you choose the average bucket length for the memory/speed constraints that you have.

Viewing all defined variables

print locals()

edit continued from comment.

To make it look a little prettier when printing:

import sys, pprint
sys.displayhook = pprint.pprint
locals()

That should give you a more vertical printout.

Collision Detection between two images in Java

Use a rectangle to surround each player and enemy, the height and width of the rectangles should correspond to the object you're surrounding, imagine it being in a box only big enough to fit it.

Now, you move these rectangles the same as you do the objects, so they have a 'bounding box'

I'm not sure if Java has this, but it might have a method on the rectangle object called .intersects() so you'd do if(rectangle1.intersectS(rectangle2) to check to see if an object has collided with another.

Otherwise you can get the x and y co-ordinates of the boxes and using the height/width of them detect whether they've intersected yourself.

Anyway, you can use that to either do an event on intersection (make one explode, or whatever) or prevent the movement from being drawn. (revert to previous co-ordinates)

edit: here we go

boolean

intersects(Rectangle r) Determines whether or not this Rectangle and the specified Rectangle intersect.

So I would do (and don't paste this code, it most likely won't work, not done java for a long time and I didn't do graphics when I did use it.)

Rectangle rect1 = new Rectangle(player.x, player.y, player.width, player.height);

Rectangle rect2 = new Rectangle(enemy.x, enemy.y, enemy.width, enemy.height);

//detects when the two rectangles hit
if(rect1.intersects(rect2))
{

System.out.println("game over, g");
}

obviously you'd need to fit that in somewhere.

ValueError: object too deep for desired array while using convolution

The Y array in your screenshot is not a 1D array, it's a 2D array with 300 rows and 1 column, as indicated by its shape being (300, 1).

To remove the extra dimension, you can slice the array as Y[:, 0]. To generally convert an n-dimensional array to 1D, you can use np.reshape(a, a.size).

Another option for converting a 2D array into 1D is flatten() function from numpy.ndarray module, with the difference that it makes a copy of the array.

Get value from a string after a special character

_x000D_
_x000D_
//var val = $("#FieldId").val()_x000D_
//Get Value of hidden field by val() jquery function I'm using example string._x000D_
var val = "String to find after - DEMO"_x000D_
var foundString = val.substr(val.indexOf(' - ')+3,)_x000D_
console.log(foundString);
_x000D_
_x000D_
_x000D_ Assuming you need to find DEMO string after - by above code you can able to access DEMO string substr will return the string from whaterver the value indexOf return till the end of string it will return everything.

Error resolving template "index", template might not exist or might not be accessible by any of the configured Template Resolvers

If you are facing this issue and everything looks good, try invalidate cache/restart from your IDE. This will resolve the issue in most of the cases.

What are the basic rules and idioms for operator overloading?

The Three Basic Rules of Operator Overloading in C++

When it comes to operator overloading in C++, there are three basic rules you should follow. As with all such rules, there are indeed exceptions. Sometimes people have deviated from them and the outcome was not bad code, but such positive deviations are few and far between. At the very least, 99 out of 100 such deviations I have seen were unjustified. However, it might just as well have been 999 out of 1000. So you’d better stick to the following rules.

  1. Whenever the meaning of an operator is not obviously clear and undisputed, it should not be overloaded. Instead, provide a function with a well-chosen name.
    Basically, the first and foremost rule for overloading operators, at its very heart, says: Don’t do it. That might seem strange, because there is a lot to be known about operator overloading and so a lot of articles, book chapters, and other texts deal with all this. But despite this seemingly obvious evidence, there are only a surprisingly few cases where operator overloading is appropriate. The reason is that actually it is hard to understand the semantics behind the application of an operator unless the use of the operator in the application domain is well known and undisputed. Contrary to popular belief, this is hardly ever the case.

  2. Always stick to the operator’s well-known semantics.
    C++ poses no limitations on the semantics of overloaded operators. Your compiler will happily accept code that implements the binary + operator to subtract from its right operand. However, the users of such an operator would never suspect the expression a + b to subtract a from b. Of course, this supposes that the semantics of the operator in the application domain is undisputed.

  3. Always provide all out of a set of related operations.
    Operators are related to each other and to other operations. If your type supports a + b, users will expect to be able to call a += b, too. If it supports prefix increment ++a, they will expect a++ to work as well. If they can check whether a < b, they will most certainly expect to also to be able to check whether a > b. If they can copy-construct your type, they expect assignment to work as well.


Continue to The Decision between Member and Non-member.

Converting a string to int in Groovy

The Simpler Way Of Converting A String To Integer In Groovy Is As Follows...

String aa="25"
int i= aa.toInteger()

Now "i" Holds The Integer Value.

Django {% with %} tags within {% if %} {% else %} tags?

Like this:

{% if age > 18 %}
    {% with patient as p %}
    <my html here>
    {% endwith %}
{% else %}
    {% with patient.parent as p %}
    <my html here>
    {% endwith %}
{% endif %}

If the html is too big and you don't want to repeat it, then the logic would better be placed in the view. You set this variable and pass it to the template's context:

p = (age > 18 && patient) or patient.parent

and then just use {{ p }} in the template.

Is there a way to have printf() properly print out an array (of floats, say)?

you need to iterate through the array's elements

float foo[] = {1, 2, 3, 10};
int i;
for (i=0;i < (sizeof (foo) /sizeof (foo[0]));i++) {
    printf("%lf\n",foo[i]);
}

or create a function that returns stacked sn printf and then prints it with

printf("%s\n",function_that_makes_pretty_output(foo))

WCF Service Client: The content type text/html; charset=utf-8 of the response message does not match the content type of the binding

what's going on is that you're trying to access the service using wsHttpBind, which use secured encrypted messages by default (secured Messages). On other hand the netTcpBind uses Secured encrypted channels. (Secured Transport)... BUT basicHttpBind, doesn't require any security at all, and can access anonymous

SO. at the Server side, Add\Change this into your configuration.

<bindings>
    <wsHttpBinding>
     <binding name="wsbind"> 
         <security mode="Message">
             <transport clientCredentialType="Windows" proxyCredentialType="None" />
             <message clientCredentialType="Windows" negotiateServiceCredential="true"
                            algorithmSuite="Default" establishSecurityContext="true" />
         </security>
     </binding>
    </wsHttpBinding>
</bindings>

then add change your endpoint to

<endpoint address="" binding="wsHttpBinding" bindingConfiguration="wsbind" name="wshttpbind" contract="WCFService.IService" > 

That should do it.

Angular 4 default radio button checked by default

You can use [(ngModel)], but you'll need to update your value to [value] otherwise the value is evaluating as a string. It would look like this:

<label>This rule is true if:</label>
<label class="form-check-inline">
    <input class="form-check-input" type="radio" name="mode" [value]="true" [(ngModel)]="rule.mode">
</label>
<label class="form-check-inline">
    <input class="form-check-input" type="radio" name="mode" [value]="false" [(ngModel)]="rule.mode">
</label>

If rule.mode is true, then that radio is selected. If it's false, then the other.

The difference really comes down to the value. value="true" really evaluates to the string 'true', whereas [value]="true" evaluates to the boolean true.

sql searching multiple words in a string

Maybe EXISTS can help.

and exists (select 1 from @DocumentNames where pcd.Name like DocName+'%' or CD.DocumentName like DocName+'%')

How to change users in TortoiseSVN

There are several ways to do it, through settings or by deleting the cache.

Deleting the cache is the most versatile method. First, locate it:

On XP, it was located here:

C:\Documents and Settings\%USER%\Application Data\Subversion\auth\svn.simple\

On Vista, it was located here:

C:\Users\%USER%\AppData\Roaming\Subversion\auth\svn.simple\

Then look in those files with Notepad, and delete the one with your credentials.

Pass multiple parameters in Html.BeginForm MVC

There are two options here.

  1. a hidden field within the form, or
  2. Add it to the route values parameter in the begin form method.

Edit

@Html.Hidden("clubid", ViewBag.Club.id)

or

 @using(Html.BeginForm("action", "controller",
                       new { clubid = @Viewbag.Club.id }, FormMethod.Post, null)

How to check whether an object is a date?

The function is getMonth(), not GetMonth().

Anyway, you can check if the object has a getMonth property by doing this. It doesn't necessarily mean the object is a Date, just any object which has a getMonth property.

if (date.getMonth) {
    var month = date.getMonth();
}

C# 4.0: Convert pdf to byte[] and vice versa

// loading bytes from a file is very easy in C#. The built in System.IO.File.ReadAll* methods take care of making sure every byte is read properly.
// note that for Linux, you will not need the c: part
// just swap out the example folder here with your actual full file path
string pdfFilePath = "c:/pdfdocuments/myfile.pdf";
byte[] bytes = System.IO.File.ReadAllBytes(pdfFilePath);

// munge bytes with whatever pdf software you want, i.e. http://sourceforge.net/projects/itextsharp/
// bytes = MungePdfBytes(bytes); // MungePdfBytes is your custom method to change the PDF data
// ...
// make sure to cleanup after yourself

// and save back - System.IO.File.WriteAll* makes sure all bytes are written properly - this will overwrite the file, if you don't want that, change the path here to something else
System.IO.File.WriteAllBytes(pdfFilePath, bytes);

SQL server 2008 backup error - Operating system error 5(failed to retrieve text for this error. Reason: 15105)

I had this error. Nothing worked for me until I opened the SQLServer log file in the "MSSQL10_50" Log folder. That clearly stated which file could not be overwritten. It turned out that the .mdf file was being written into the "MSSQL10" data folder. I made sure that folder had the same SQLServer user permissions as the "MSSQL10_50" equivalent folder. Then it all worked.

The issue here is that the error detail is logged but not reported, so check the logs.

How To Get The Current Year Using Vba

Year(Date)

Year(): Returns the year portion of the date argument.
Date: Current date only.

Explanation of both of these functions from here.

How to check if IEnumerable is null or empty?

 public static bool AnyNotNull<TSource>(this IEnumerable<TSource> source)
    {
        return source != null && source.Any();
    }

my own extension method to check Not null and Any

Facebook Graph API, how to get users email?

Assuming you've requested email permissions when the user logged in from your app and you have a valid token,

With the fetch api you can just

const token = "some_valid_token";
const response = await fetch(
        `https://graph.facebook.com/me?fields=email&access_token=${token}`
      );
const result = await response.json();

result will be:

{
    "id": "some_id",
    "email": "[email protected]"
}

id will be returned anyway.

You can add to the fields query param more stuff, but you need permissions for them if they are not on the public profile (name is public).

?fields=name,email,user_birthday&token=

https://developers.facebook.com/docs/facebook-login/permissions

XAMPP permissions on Mac OS X?

This Solved WordPress Filesystem Permissions in Bitnami XAMPP

By changing the file permissions in apps/wordpress folder mounted on MAC XAMPP-VM shown in the below screenshot.

enter image description here

sudo chown -R bitnami:daemon TARGET # [ Replace "TARGET" with your file/folder path ]
find TARGET -type d -print0 | xargs -0 chmod 775
find TARGET -type f -print0 | xargs -0 chmod 664
chmod 640 TARGET/wp-config.php

Source: bitnami

TARGET - Replace placeholder for your mounted filesystem wordpress path eg: '1.1.1.1/lampp/apps/wordpress'

Now you can edit your themes in VS-Code or any developer editor of your choice.

NOTE: This should be done only in your development environment. Production build permissions are different & above doesn't apply