Programs & Examples On #Mcms 2000

How to get the IP address of the server on which my C# application is running on?

The LINQ solution:

Dns.GetHostEntry(Dns.GetHostName()).AddressList.Where(ip => ip.AddressFamily == AddressFamily.InterNetwork).Select(ip => ip.ToString()).FirstOrDefault() ?? ""

Adding a column to an existing table in a Rails migration

Sometimes rails generate migration add_email_to_users email:string produces a migration like this

class AddEmailToUsers < ActiveRecord::Migration[5.0]
  def change
  end
end

In that case you have to manually an add_column to change:

class AddEmailToUsers < ActiveRecord::Migration[5.0]
  def change
    add_column :users, :email, :string
  end
end

And then run rake db:migrate

deny directory listing with htaccess

Try adding this to the .htaccess file in that directory.

Options -Indexes

This has more information.

How do you specify the Java compiler version in a pom.xml file?

<project>
  [...]
  <build>
    [...]
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>(whatever version is current)</version>
        <configuration>
          <!-- or whatever version you use -->
          <source>1.7</source>
          <target>1.7</target>
        </configuration>
      </plugin>
    </plugins>
    [...]
  </build>
  [...]
</project>

See the config page for the maven compiler plugin:

http://maven.apache.org/plugins/maven-compiler-plugin/examples/set-compiler-source-and-target.html

Oh, and: don't use Java 1.3.x, current versions are Java 1.7.x or 1.8.x

Extract csv file specific columns to list in Python

import csv
from sys import argv

d = open("mydata.csv", "r")

db = []

for line in csv.reader(d):
    db.append(line)

# the rest of your code with 'db' filled with your list of lists as rows and columbs of your csv file.

How to add button in ActionBar(Android)?

you have to create an entry inside res/menu,override onCreateOptionsMenu and inflate it

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.yourentry, menu);
    return true;
}

an entry for the menu could be:

<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:id="@+id/action_cart"
        android:icon="@drawable/cart"
        android:orderInCategory="100"
        android:showAsAction="always"/> 
</menu>

How to square all the values in a vector in R?

Try this (faster and simpler):

newData <- data^2

Difference between request.getSession() and request.getSession(true)

request.getSession() is just a convenience method. It does exactly the same as request.getSession(true).

Using Jasmine to spy on a function without an object

A very simple way:

import * as myFunctionContainer from 'whatever-lib';

const fooSpy = spyOn(myFunctionContainer, 'myFunc');

Accessing nested JavaScript objects and arrays by string path

I think you are asking for this:

var part1name = someObject.part1.name;
var part2quantity = someObject.part2.qty;
var part3name1 =  someObject.part3[0].name;

You could be asking for this:

var part1name = someObject["part1"]["name"];
var part2quantity = someObject["part2"]["qty"];
var part3name1 =  someObject["part3"][0]["name"];

Both of which will work


Or maybe you are asking for this

var partName = "part1";
var nameStr = "name";

var part1name = someObject[partName][nameStr];

Finally you could be asking for this

var partName = "part1.name";

var partBits = partName.split(".");

var part1name = someObject[partBits[0]][partBits[1]];

2D arrays in Python

>>> a = []

>>> for i in xrange(3):
...     a.append([])
...     for j in xrange(3):
...             a[i].append(i+j)
...
>>> a
[[0, 1, 2], [1, 2, 3], [2, 3, 4]]
>>>

How to use bitmask?

Briefly bitmask helps to manipulate position of multiple values. There is a good example here ;

Bitflags are a method of storing multiple values, which are not mutually exclusive, in one variable. You've probably seen them before. Each flag is a bit position which can be set on or off. You then have a bunch of bitmasks #defined for each bit position so you can easily manipulate it:

    #define LOG_ERRORS            1  // 2^0, bit 0
    #define LOG_WARNINGS          2  // 2^1, bit 1
    #define LOG_NOTICES           4  // 2^2, bit 2
    #define LOG_INCOMING          8  // 2^3, bit 3
    #define LOG_OUTGOING         16  // 2^4, bit 4
    #define LOG_LOOPBACK         32  // and so on...

// Only 6 flags/bits used, so a char is fine
unsigned char flags;

// initialising the flags
// note that assigning a value will clobber any other flags, so you
// should generally only use the = operator when initialising vars.
flags = LOG_ERRORS;
// sets to 1 i.e. bit 0

//initialising to multiple values with OR (|)
flags = LOG_ERRORS | LOG_WARNINGS | LOG_INCOMING;
// sets to 1 + 2 + 8 i.e. bits 0, 1 and 3

// setting one flag on, leaving the rest untouched
// OR bitmask with the current value
flags |= LOG_INCOMING;

// testing for a flag
// AND with the bitmask before testing with ==
if ((flags & LOG_WARNINGS) == LOG_WARNINGS)
   ...

// testing for multiple flags
// as above, OR the bitmasks
if ((flags & (LOG_INCOMING | LOG_OUTGOING))
         == (LOG_INCOMING | LOG_OUTGOING))
   ...

// removing a flag, leaving the rest untouched
// AND with the inverse (NOT) of the bitmask
flags &= ~LOG_OUTGOING;

// toggling a flag, leaving the rest untouched
flags ^= LOG_LOOPBACK;



**

WARNING: DO NOT use the equality operator (i.e. bitflags == bitmask) for testing if a flag is set - that expression will only be true if that flag is set and all others are unset. To test for a single flag you need to use & and == :

**

if (flags == LOG_WARNINGS) //DON'T DO THIS
   ...
if ((flags & LOG_WARNINGS) == LOG_WARNINGS) // The right way
   ...
if ((flags & (LOG_INCOMING | LOG_OUTGOING)) // Test for multiple flags set
         == (LOG_INCOMING | LOG_OUTGOING))
   ...

You can also search C++ Triks

The name 'ConfigurationManager' does not exist in the current context

In NetCore 3.1 I had to use Microsoft.Extensions.Configuration instead:

    public static async Task Main(string[] args)
    {
        var configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile(path: "appsettings.json", optional: false, reloadOnChange: true)
            .Build();

...

call javascript function onchange event of dropdown list

Your code is working just fine, you have to declare javscript method before DOM ready.

your working example

File uploading with Express 4.0: req.files undefined

Just to add to answers above, you can streamline the use of express-fileupload to just a single route that needs it, instead of adding it to the every route.

let fileupload = require("express-fileupload");

...

app.post("/upload", fileupload, function(req, res){

...

});

Notepad++ change text color?

You can use the "User-Defined Language" option available at the notepad++. You do not need to do the xml-based hacks, where the formatting would be available only in the searched window, with the formatting rules.

Sample for your reference here.

In c# what does 'where T : class' mean?

'T' represents a generic type. It means it can accept any type of class. The following article might help:

http://www.15seconds.com/issue/031024.htm

Regex for password must contain at least eight characters, at least one number and both lower and uppercase letters and special characters

Use the following Regex to satisfy the below conditions:

Conditions:

  1. Min 1 uppercase letter.
  2. Min 1 lowercase letter.
  3. Min 1 special character.
  4. Min 1 number.
  5. Min 8 characters.
  6. Max 30 characters.

Regex:

/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[#$@!%&*?])[A-Za-z\d#$@!%&*?]{8,30}$/

How do I use IValidatableObject?

Quote from Jeff Handley's Blog Post on Validation Objects and Properties with Validator:

When validating an object, the following process is applied in Validator.ValidateObject:

  1. Validate property-level attributes
  2. If any validators are invalid, abort validation returning the failure(s)
  3. Validate the object-level attributes
  4. If any validators are invalid, abort validation returning the failure(s)
  5. If on the desktop framework and the object implements IValidatableObject, then call its Validate method and return any failure(s)

This indicates that what you are attempting to do won't work out-of-the-box because the validation will abort at step #2. You could try to create attributes that inherit from the built-in ones and specifically check for the presence of an enabled property (via an interface) before performing their normal validation. Alternatively, you could put all of the logic for validating the entity in the Validate method.

You also could take a look a the exact implemenation of Validator class here

What is the maximum float in Python?

If you are using numpy, you can use dtype 'float128' and get a max float of 10e+4931

>>> np.finfo(np.float128)
finfo(resolution=1e-18, min=-1.18973149536e+4932, max=1.18973149536e+4932, dtype=float128)

How to access child's state in React?

If you already have onChange handler for the individual FieldEditors I don't see why you couldn't just move the state up to the FormEditor component and just pass down a callback from there to the FieldEditors that will update the parent state. That seems like a more React-y way to do it, to me.

Something along the line of this perhaps:

const FieldEditor = ({ value, onChange, id }) => {
  const handleChange = event => {
    const text = event.target.value;
    onChange(id, text);
  };

  return (
    <div className="field-editor">
      <input onChange={handleChange} value={value} />
    </div>
  );
};

const FormEditor = props => {
  const [values, setValues] = useState({});
  const handleFieldChange = (fieldId, value) => {
    setValues({ ...values, [fieldId]: value });
  };

  const fields = props.fields.map(field => (
    <FieldEditor
      key={field}
      id={field}
      onChange={handleFieldChange}
      value={values[field]}
    />
  ));

  return (
    <div>
      {fields}
      <pre>{JSON.stringify(values, null, 2)}</pre>
    </div>
  );
};

// To add abillity to dynamically add/remove fields keep the list in state
const App = () => {
  const fields = ["field1", "field2", "anotherField"];

  return <FormEditor fields={fields} />;
};

Original - pre-hooks version:

_x000D_
_x000D_
class FieldEditor extends React.Component {_x000D_
  constructor(props) {_x000D_
    super(props);_x000D_
    this.handleChange = this.handleChange.bind(this);_x000D_
  }_x000D_
_x000D_
  handleChange(event) {_x000D_
    const text = event.target.value;_x000D_
    this.props.onChange(this.props.id, text);_x000D_
  }_x000D_
_x000D_
  render() {_x000D_
    return (_x000D_
      <div className="field-editor">_x000D_
        <input onChange={this.handleChange} value={this.props.value} />_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
}_x000D_
_x000D_
class FormEditor extends React.Component {_x000D_
  constructor(props) {_x000D_
    super(props);_x000D_
    this.state = {};_x000D_
_x000D_
    this.handleFieldChange = this.handleFieldChange.bind(this);_x000D_
  }_x000D_
_x000D_
  handleFieldChange(fieldId, value) {_x000D_
    this.setState({ [fieldId]: value });_x000D_
  }_x000D_
_x000D_
  render() {_x000D_
    const fields = this.props.fields.map(field => (_x000D_
      <FieldEditor_x000D_
        key={field}_x000D_
        id={field}_x000D_
        onChange={this.handleFieldChange}_x000D_
        value={this.state[field]}_x000D_
      />_x000D_
    ));_x000D_
_x000D_
    return (_x000D_
      <div>_x000D_
        {fields}_x000D_
        <div>{JSON.stringify(this.state)}</div>_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
}_x000D_
_x000D_
// Convert to class component and add ability to dynamically add/remove fields by having it in state_x000D_
const App = () => {_x000D_
  const fields = ["field1", "field2", "anotherField"];_x000D_
_x000D_
  return <FormEditor fields={fields} />;_x000D_
};_x000D_
_x000D_
ReactDOM.render(<App />, document.body);
_x000D_
_x000D_
_x000D_

No WebApplicationContext found: no ContextLoaderListener registered?

You'll have to have a ContextLoaderListener in your web.xml - It loads your configuration files.

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

You need to understand the difference between Web application context and root application context .

In the web MVC framework, each DispatcherServlet has its own WebApplicationContext, which inherits all the beans already defined in the root WebApplicationContext. These inherited beans defined can be overridden in the servlet-specific scope, and new scope-specific beans can be defined local to a given servlet instance.

The dispatcher servlet's application context is a web application context which is only applicable for the Web classes . You cannot use these for your middle tier layers . These need a global app context using ContextLoaderListener .

Read the spring reference here for spring mvc .

How to remove leading zeros from alphanumeric text?

If you are using Kotlin This is the only code that you need:

yourString.trimStart('0')

How do I display a wordpress page content?

Page content can be displayed easily and perfectly this way:

<?php if(have_posts()) : ?>
    <?php while(have_posts())  : the_post(); ?>
      <h2><?php the_title(); ?></h2>                        
      <?php the_content(); ?>          
      <?php comments_template( '', true ); ?> 
    <?php endwhile; ?>                   
      <?php else : ?>                       
        <h3><?php _e('404 Error&#58; Not Found'); ?></h3>
<?php endif; ?>         

Note:

In terms of displaying content - i) comments_template() function is an optional use if you need to enable commenting with different functionality.

ii) _e() function is also optional but more meaningful & effective than just showing text through <p>. while preferred stylized 404.php can be created to be redirected.

Selecting Folder Destination in Java?

Along with JFileChooser is possible use this:

UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");

for have a Look and Feel like Windows.

for others settings, view here: https://docs.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html#available

There is already an object named in the database

Make sure your solutions startup project has the correct connectionstring in the config file. Or set the -StartUpProjectName parameter when executing the update-database command. The -StartUpProjectName parameter specifies the configuration file to use for named connection strings. If omitted, the specified project’s configuration file is used.

Here is a link for ef-migration command references http://coding.abel.nu/2012/03/ef-migrations-command-reference/

Good tool to visualise database schema?

I usually use SchemaSpy to do this, but recently I found a really simple article on sqlfairy that just uses the dump file to create the structure graph

How do you clone an Array of Objects in Javascript?

Depending if you have Underscore or Babel here is a Benchmark of the different way of deep cloning an array.

https://jsperf.com/object-rest-spread-vs-clone/2

Look like babel is the fastest.

var x = babel({}, obj)

Oracle PL/SQL - Are NO_DATA_FOUND Exceptions bad for stored procedure performance?

Stephen Darlington makes a very good point, and you can see that if you change my benchmark to use a more realistically sized table if I fill the table out to 10000 rows using the following:

begin 
  for i in 2 .. 10000 loop
    insert into t (NEEDED_FIELD, cond) values (i, 10);
  end loop;
end;

Then re-run the benchmarks. (I had to reduce the loop counts to 5000 to get reasonable times).

declare
  otherVar  number;
  cnt number;
begin
  for i in 1 .. 5000 loop
     select count(*) into cnt from t where cond = 0;

     if (cnt = 1) then
       select NEEDED_FIELD INTO otherVar from t where cond = 0;
     else
       otherVar := 0;
     end if;
   end loop;
end;
/

PL/SQL procedure successfully completed.

Elapsed: 00:00:04.34

declare
  otherVar  number;
begin
  for i in 1 .. 5000 loop
     begin
       select NEEDED_FIELD INTO otherVar from t where cond = 0;
     exception
       when no_data_found then
         otherVar := 0;
     end;
   end loop;
end;
/

PL/SQL procedure successfully completed.

Elapsed: 00:00:02.10

The method with the exception is now more than twice as fast. So, for almost all cases,the method:

SELECT NEEDED_FIELD INTO var WHERE condition;
EXCEPTION
WHEN NO_DATA_FOUND....

is the way to go. It will give correct results and is generally the fastest.

How to force R to use a specified factor level as reference in a regression?

Others have mentioned the relevel command which is the best solution if you want to change the base level for all analyses on your data (or are willing to live with changing the data).

If you don't want to change the data (this is a one time change, but in the future you want the default behavior again), then you can use a combination of the C (note uppercase) function to set contrasts and the contr.treatments function with the base argument for choosing which level you want to be the baseline.

For example:

lm( Sepal.Width ~ C(Species,contr.treatment(3, base=2)), data=iris )

jQuery Popup Bubble/Tooltip

Sounds to me you dn't want the mouse over events: you want the jQuery hover() event.

And what you seem to want is a "rich" tooltip, in which case I suggest jQuery tooltip. With the bodyHandler option you can put arbitrary HTML in.

How do I merge dictionaries together in Python?

Starting in Python 3.9, the operator | creates a new dictionary with the merged keys and values from two dictionaries:

# d1 = { 'a': 1, 'b': 2 }
# d2 = { 'b': 1, 'c': 3 }
d3 = d2 | d1
# d3: {'b': 2, 'c': 3, 'a': 1}

This:

Creates a new dictionary d3 with the merged keys and values of d2 and d1. The values of d1 take priority when d2 and d1 share keys.


Also note the |= operator which modifies d2 by merging d1 in, with priority on d1 values:

# d1 = { 'a': 1, 'b': 2 }
# d2 = { 'b': 1, 'c': 3 }
d2 |= d1
# d2: {'b': 2, 'c': 3, 'a': 1}

?

Python vs. Java performance (runtime speed)

If you ignore the characteristics of both languages, how do you define "SPEED"? Which features should be in your benchmark and which do you want to omit?

For example:

  • Does it count when Java executes an empty loop faster than Python?
  • Or is Python faster when it notices that the loop body is empty, the loop header has no side effects and it optimizes the whole loop away?
  • Or is that "a language characteristic"?
  • Do you want to know how many bytecodes each language can execute per second?
  • Which ones? Only the fast ones or all of them?
  • How do you count the Java VM JIT compiler which turns bytecode into CPU-specific assembler code at runtime?
  • Do you include code compilation times (which are extra in Java but always included in Python)?

Conclusion: Your question has no answer because it isn't defined what you want. Even if you made it more clear, the question will probably become academic since you will measure something that doesn't count in real life. For all of my projects, both Java and Python have always been fast enough. Of course, I would prefer one language over the other for a specific problem in a certain context.

change html input type by JS?

Try:

<input id="hybrid" type="text" name="password" />

<script type="text/javascript">
    document.getElementById('hybrid').type = 'password';
</script>

PHP Array to CSV

Try using;

PHP_EOL

To terminate each new line in your CSV output.

I'm assuming that the text is delimiting, but isn't moving to the next row?

That's a PHP constant. It will determine the correct end of line you need.

Windows, for example, uses "\r\n". I wracked my brains with that one when my output wasn't breaking to a new line.

how to write unified new line in PHP?

React Router with optional path parameter

for react-router V5 and above use below syntax for multiple paths

<Route
          exact
          path={[path1, path2]}
          component={component}
        />

add scroll bar to table body

you can wrap the content of the <tbody> in a scrollable <div> :

html

....
<tbody>
  <tr>
    <td colspan="2">
      <div class="scrollit">
        <table>
          <tr>
            <td>January</td>
            <td>$100</td>
          </tr>
          <tr>
            <td>February</td>
            <td>$80</td>
          </tr>
          <tr>
            <td>January</td>
            <td>$100</td>
          </tr>
          <tr>
            <td>February</td>
            <td>$80</td>
          </tr>
          ...

css

.scrollit {
    overflow:scroll;
    height:100px;
}

see my jsfiddle, forked from yours: http://jsfiddle.net/VTNax/2/

SQL Server Jobs with SSIS packages - Failed to decrypt protected XML node "DTS:Password" with error 0x8009000B

It is because creator of the SSIS packages is someone else and other person is executing the packages.

If suppose A person has created SSIS packages and B person is trying to execute than the above error comes.

You can solve the error by changing creator name from package properties from A to B.

Thanks, Kiran Sagar

Unexpected character encountered while parsing value

This error occurs when we parse json content to model object. Json content type is string. For example: https://dotnetfiddle.net/uFClKj Some times, an api that we call may return an error. If we do not check the response status, but proceed to parse the response to model, this issue will occur.

Create auto-numbering on images/figures in MS Word

Office 2007

Right click the figure, select Insert Caption, Select Numbering, check box next to 'Include chapter number', select OK, Select OK again, then you figure identifier should be updated.

Immutable vs Mutable types

The goal of this answer is to create a single place to find all the good ideas about how to tell if you are dealing with mutating/nonmutating (immutable/mutable), and where possible, what to do about it? There are times when mutation is undesirable and python's behavior in this regard can feel counter-intuitive to coders coming into it from other languages.

As per a useful post by @mina-gabriel:

Analyzing the above and combining w/ a post by @arrakëën:

What cannot change unexpectedly?

  • scalars (variable types storing a single value) do not change unexpectedly
    • numeric examples: int(), float(), complex()
  • there are some "mutable sequences":
    • str(), tuple(), frozenset(), bytes()

What can?

  • list like objects (lists, dictionaries, sets, bytearray())
  • a post on here also says classes and class instances but this may depend on what the class inherits from and/or how its built.

by "unexpectedly" I mean that programmers from other languages might not expect this behavior (with the exception or Ruby, and maybe a few other "Python like" languages).

Adding to this discussion:

This behavior is an advantage when it prevents you from accidentally populating your code with mutliple copies of memory-eating large data structures. But when this is undesirable, how do we get around it?

With lists, the simple solution is to build a new one like so:

list2 = list(list1)

with other structures ... the solution can be trickier. One way is to loop through the elements and add them to a new empty data structure (of the same type).

functions can mutate the original when you pass in mutable structures. How to tell?

  • There are some tests given on other comments on this thread but then there are comments indicating these tests are not full proof
  • object.function() is a method of the original object but only some of these mutate. If they return nothing, they probably do. One would expect .append() to mutate without testing it given its name. .union() returns the union of set1.union(set2) and does not mutate. When in doubt, the function can be checked for a return value. If return = None, it does not mutate.
  • sorted() might be a workaround in some cases. Since it returns a sorted version of the original, it can allow you to store a non-mutated copy before you start working on the original in other ways. However, this option assumes you don't care about the order of the original elements (if you do, you need to find another way). In contrast .sort() mutates the original (as one might expect).

Non-standard Approaches (in case helpful): Found this on github published under an MIT license:

  • github repository under: tobgu named: pyrsistent
  • What it is: Python persistent data structure code written to be used in place of core data structures when mutation is undesirable

For custom classes, @semicolon suggests checking if there is a __hash__ function because mutable objects should generally not have a __hash__() function.

This is all I have amassed on this topic for now. Other ideas, corrections, etc. are welcome. Thanks.

Delete all lines starting with # or ; in Notepad++

Maybe you should try

^[#;].*$

^ matches the beggining, $ the end.

How do I remove diacritics (accents) from a string in .NET?

In case anyone's interested, here is the java equivalent:

import java.text.Normalizer;

public class MyClass
{
    public static String removeDiacritics(String input)
    {
        String nrml = Normalizer.normalize(input, Normalizer.Form.NFD);
        StringBuilder stripped = new StringBuilder();
        for (int i=0;i<nrml.length();++i)
        {
            if (Character.getType(nrml.charAt(i)) != Character.NON_SPACING_MARK)
            {
                stripped.append(nrml.charAt(i));
            }
        }
        return stripped.toString();
    }
}

Laravel Controller Subfolder routing

Create controller go to cmd and the type php artisan make:controller auth\LoginController

Maximum execution time in phpMyadmin

For Xampp version on Windows

Add this line to xampp\phpmyadmin\config.inc.php

$cfg['ExecTimeLimit'] = 6000;

And Change xampp\php\php.ini to

post_max_size = 750M 
upload_max_filesize = 750M   
max_execution_time = 5000
max_input_time = 5000
memory_limit = 1000M

And change xampp\mysql\bin\my.ini

max_allowed_packet = 200M

JSONObject - How to get a value?

This may be helpful while searching keys present in nested objects and nested arrays. And this is a generic solution to all cases.

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

public class MyClass
{
    public static Object finalresult = null;
    public static void main(String args[]) throws JSONException
    {
        System.out.println(myfunction(myjsonstring,key));
    }

    public static Object myfunction(JSONObject x,String y) throws JSONException
    {
        JSONArray keys =  x.names();
        for(int i=0;i<keys.length();i++)
        {
            if(finalresult!=null)
            {
                return finalresult;                     //To kill the recursion
            }

            String current_key = keys.get(i).toString();

            if(current_key.equals(y))
            {
                finalresult=x.get(current_key);
                return finalresult;
            }

            if(x.get(current_key).getClass().getName().equals("org.json.JSONObject"))
            {
                myfunction((JSONObject) x.get(current_key),y);
            }
            else if(x.get(current_key).getClass().getName().equals("org.json.JSONArray"))
            {
                for(int j=0;j<((JSONArray) x.get(current_key)).length();j++)
                {
                    if(((JSONArray) x.get(current_key)).get(j).getClass().getName().equals("org.json.JSONObject"))
                    {
                        myfunction((JSONObject)((JSONArray) x.get(current_key)).get(j),y);
                    }
                }
            }
        }
        return null;
    }
}

Possibilities:

  1. "key":"value"
  2. "key":{Object}
  3. "key":[Array]

Logic :

  • I check whether the current key and search key are the same, if so I return the value of that key.
  • If it is an object, I send the value recursively to the same function.
  • If it is an array, I check whether it contains an object, if so I recursively pass the value to the same function.

using stored procedure in entity framework

Simple. Just instantiate your entity, set it to an object and pass it to your view in your controller.

enter image description here

Entity

VehicleInfoEntities db = new VehicleInfoEntities();

Stored Procedure

dbo.prcGetMakes()

or

you can add any parameters in your stored procedure inside the brackets ()

dbo.prcGetMakes("BMW")

Controller

public class HomeController : Controller
{
    VehicleInfoEntities db = new VehicleInfoEntities();

    public ActionResult Index()
    {
        var makes = db.prcGetMakes(null);

        return View(makes);
    }
}

How do I make flex box work in safari?

display: flex;
display: -webkit-box;

did it for me. Also there were two display: flex; on the same element from different classes. So I removed the other one.

Mockito - NullpointerException when stubbing Method

For future readers, another cause for NPE when using mocks is forgetting to initialize the mocks like so:

@Mock
SomeMock someMock;

@InjectMocks
SomeService someService;

@Before
public void setup(){
    MockitoAnnotations.initMocks(this); //without this you will get NPE
}

@Test
public void someTest(){
    Mockito.when(someMock.someMethod()).thenReturn("some result");
   // ...
}

Also make sure you are using JUnit for all annotations. I once accidently created a test with @Test from testNG so the @Before didn't work with it (in testNG the annotation is @BeforeTest)

How to make Bootstrap carousel slider use mobile left/right swipe

If anyone is looking for the angular version of this answer then I would suggest creating a directive would be a great idea.

NOTE: ngx-bootstrap is used.

import { Directive, Host, Self, Optional, Input, Renderer2, OnInit, ElementRef } from '@angular/core';
import { CarouselComponent } from 'ngx-bootstrap/carousel';

@Directive({
  selector: '[appCarouselSwipe]'
})
export class AppCarouselSwipeDirective implements OnInit {
  @Input() swipeThreshold = 50;
  private start: number;
  private stillMoving: boolean;
  private moveListener: Function;

  constructor(
    @Host() @Self() @Optional() private carousel: CarouselComponent,
    private renderer: Renderer2,
    private element: ElementRef
  ) {
  }

  ngOnInit(): void {
    if ('ontouchstart' in document.documentElement) {
      this.renderer.listen(this.element.nativeElement, 'touchstart', this.onTouchStart.bind(this));
      this.renderer.listen(this.element.nativeElement, 'touchend', this.onTouchEnd.bind(this));
    }
  }

  private onTouchStart(e: TouchEvent): void {
    if (e.touches.length === 1) {
      this.start = e.touches[0].pageX;
      this.stillMoving = true;
      this.moveListener = this.renderer.listen(this.element.nativeElement, 'touchmove', this.onTouchMove.bind(this));
    }
  }

  private onTouchMove(e: TouchEvent): void {
    if (this.stillMoving) {
      const x = e.touches[0].pageX;
      const difference = this.start - x;
      if (Math.abs(difference) >= this.swipeThreshold) {
        this.cancelTouch();
        if (difference > 0) {
          if (this.carousel.activeSlide < this.carousel.slides.length - 1) {
            this.carousel.activeSlide = this.carousel.activeSlide + 1;
          }
        } else {
          if (this.carousel.activeSlide > 0) {
            this.carousel.activeSlide = this.carousel.activeSlide - 1;
          }
        }
      }
    }
  }

  private onTouchEnd(e: TouchEvent): void {
    this.cancelTouch();
  }

  private cancelTouch() {
    if (this.moveListener) {
      this.moveListener();
      this.moveListener = undefined;
    }
    this.start = null;
    this.stillMoving = false;
  }
}

in html:

<carousel appCarouselSwipe>

    ...

</carousel>

Reference

How to watch and compile all TypeScript sources?

EDIT: Note, this is if you have multiple tsconfig.json files in your typescript source. For my project we have each tsconfig.json file compile to a differently-named .js file. This makes watching every typescript file really easy.

I wrote a sweet bash script that finds all of your tsconfig.json files and runs them in the background, and then if you CTRL+C the terminal it will close all the running typescript watch commands.

This is tested on MacOS, but should work anywhere that BASH 3.2.57 is supported. Future versions may have changed some things, so be careful!

#!/bin/bash
# run "chmod +x typescript-search-and-compile.sh" in the directory of this file to ENABLE execution of this script
# then in terminal run "path/to/this/file/typescript-search-and-compile.sh" to execute this script
# (or "./typescript-search-and-compile.sh" if your terminal is in the folder the script is in)

# !!! CHANGE ME !!!    
# location of your scripts root folder
# make sure that you do not add a trailing "/" at the end!!
# also, no spaces! If you have a space in the filepath, then
# you have to follow this link: https://stackoverflow.com/a/16703720/9800782
sr=~/path/to/scripts/root/folder
# !!! CHANGE ME !!!

# find all typescript config files
scripts=$(find $sr -name "tsconfig.json")

for s in $scripts
do
    # strip off the word "tsconfig.json"
    cd ${s%/*} # */ # this function gets incorrectly parsed by style linters on web
    # run the typescript watch in the background
    tsc -w &
    # get the pid of the last executed background function
    pids+=$!
    # save it to an array
    pids+=" "
done

# end all processes we spawned when you close this process
wait $pids

Helpful resources:

Excluding files/directories from Gulp task

Quick answer

On src, you can always specify files to ignore using "!".

Example (you want to exclude all *.min.js files on your js folder and subfolder:

gulp.src(['js/**/*.js', '!js/**/*.min.js'])

You can do it as well for individual files.

Expanded answer:

Extracted from gulp documentation:

gulp.src(globs[, options])

Emits files matching provided glob or an array of globs. Returns a stream of Vinyl files that can be piped to plugins.

glob refers to node-glob syntax or it can be a direct file path.

So, looking to node-glob documentation we can see that it uses the minimatch library to do its matching.

On minimatch documentation, they point out the following:

if the pattern starts with a ! character, then it is negated.

And that is why using ! symbol will exclude files / directories from a gulp task

jQuery: Clearing Form Inputs

Demo : http://jsfiddle.net/xavi3r/D3prt/

$(':input','#myform')
  .not(':button, :submit, :reset, :hidden')
  .val('')
  .removeAttr('checked')
  .removeAttr('selected');

Original Answer: Resetting a multi-stage form with jQuery


Mike's suggestion (from the comments) to keep checkbox and selects intact!

Warning: If you're creating elements (so they're not in the dom), replace :hidden with [type=hidden] or all fields will be ignored!

$(':input','#myform')
  .removeAttr('checked')
  .removeAttr('selected')
  .not(':button, :submit, :reset, :hidden, :radio, :checkbox')
  .val('');

How to get the file path from URI?

File myFile = new File(uri.toString());
myFile.getAbsolutePath()

should return u the correct path

EDIT

As @Tron suggested the working code is

File myFile = new File(uri.getPath());
myFile.getAbsolutePath()

How to increase buffer size in Oracle SQL Developer to view all records?

It is easy, but takes 3 steps:

  1. In SQL Developer, enter your query in the "Worksheet" and highlight it, and press F9 to run it. The first 50 rows will be fetched into the "Query Result" window.
  2. Click on any cell in the "Query Result" window to set the focus to that window.
  3. Hold the Ctrl key and tap the "A" key.

All rows will be fetched into the "Query Result" window!

Mobile overflow:scroll and overflow-scrolling: touch // prevent viewport "bounce"

This answer seems quite outdated and not adapt for nowadays single page applications. In my case I found the solution thank to this aricle where a simple but effective solution is proposed:

_x000D_
_x000D_
html,
body {
  position: fixed;
  overflow: hidden;
}
_x000D_
_x000D_
_x000D_

This solution it's not applicable if your body is your scroll container.

Why call git branch --unset-upstream to fixup?

I had this question twice, and it was always caused by the corruption of the git cache file at my local branch. I fixed it by writing the missing commit hash into that file. I got the right commit hash from the server and ran the following command locally:

cat .git/refs/remotes/origin/feature/mybranch \
echo 1edf9668426de67ab764af138a98342787dc87fe \
>> .git/refs/remotes/origin/feature/mybranch

Find the most common element in a list

Sort a copy of the list and find the longest run. You can decorate the list before sorting it with the index of each element, and then choose the run that starts with the lowest index in the case of a tie.

How to copy text to the client's clipboard using jQuery?

Copying to the clipboard is a tricky task to do in Javascript in terms of browser compatibility. The best way to do it is using a small flash. It will work on every browser. You can check it in this article.

Here's how to do it for Internet Explorer:

function copy (str)
{
    //for IE ONLY!
    window.clipboardData.setData('Text',str);
}

VBA: Counting rows in a table (list object)

You can use this:

    Range("MyTable[#Data]").Rows.Count

You have to distinguish between a table which has either one row of data or no data, as the previous code will return "1" for both cases. Use this to test for an empty table:

    If WorksheetFunction.CountA(Range("MyTable[#Data]"))

How do I animate constraint changes?

Working and just tested solution for Swift 3 with Xcode 8.3.3:

self.view.layoutIfNeeded()
self.calendarViewHeight.constant = 56.0

UIView.animate(withDuration: 0.5, delay: 0.0, options: UIViewAnimationOptions.curveEaseIn, animations: {
        self.view.layoutIfNeeded()
    }, completion: nil)

Just keep in mind that self.calendarViewHeight is a constraint referred to a customView (CalendarView). I called the .layoutIfNeeded() on self.view and NOT on self.calendarView

Hope this help.

Is a Python dictionary an example of a hash table?

To expand upon nosklo's explanation:

a = {}
b = ['some', 'list']
a[b] = 'some' # this won't work
a[tuple(b)] = 'some' # this will, same as a['some', 'list']

JSON.Parse,'Uncaught SyntaxError: Unexpected token o

var jsonStringNoQuotes = [{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}];

it will create json object. no need to parse.

jsonStringQuotes = "'" + jsonStringNoQuotes + "'";

will return '[object]'

thats why it(below) is causing error

var myData = JSON.parse(jsonStringQuotes);

Get list of JSON objects with Spring RestTemplate

After multiple tests, this is the best way I found :)

Set<User> test = httpService.get(url).toResponseSet(User[].class);

All you need there

public <T> Set<T> toResponseSet(Class<T[]> setType) {
    HttpEntity<?> body = new HttpEntity<>(objectBody, headers);
    ResponseEntity<T[]> response = template.exchange(url, method, body, setType);
    return Sets.newHashSet(response.getBody());
}

Getting ssh to execute a command in the background on target machine

First follow this procedure:

Log in on A as user a and generate a pair of authentication keys. Do not enter a passphrase:

a@A:~> ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/a/.ssh/id_rsa): 
Created directory '/home/a/.ssh'.
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/a/.ssh/id_rsa.
Your public key has been saved in /home/a/.ssh/id_rsa.pub.
The key fingerprint is:
3e:4f:05:79:3a:9f:96:7c:3b:ad:e9:58:37:bc:37:e4 a@A

Now use ssh to create a directory ~/.ssh as user b on B. (The directory may already exist, which is fine):

a@A:~> ssh b@B mkdir -p .ssh
b@B's password: 

Finally append a's new public key to b@B:.ssh/authorized_keys and enter b's password one last time:

a@A:~> cat .ssh/id_rsa.pub | ssh b@B 'cat >> .ssh/authorized_keys'
b@B's password: 

From now on you can log into B as b from A as a without password:

a@A:~> ssh b@B

then this will work without entering a password

ssh b@B "cd /some/directory; program-to-execute &"

"The system cannot find the file C:\ProgramData\Oracle\Java\javapath\java.exe"

<>\Common Files\Oracle\Java\javapath\ is now created as a junction, no symlinks anymore

How to change the sender's name or e-mail address in mutt?

before you send the email you can press <ESC> f (Escape followed by f) to change the From: Address.

Constraint: This only works if you use mutt in curses mode and do not wan't to script it or if you want to change the address permanent. Then the other solutions are way better!

How do I find all the files that were created today in Unix/Linux?

On my Fedora 10 system, with findutils-4.4.0-1.fc10.i386:

find <path> -daystart -ctime 0 -print

The -daystart flag tells it to calculate from the start of today instead of from 24 hours ago.

Note however that this will actually list files created or modified in the last day. find has no options that look at the true creation date of the file.

manage.py runserver

Just in case any Windows users are having trouble, I thought I'd add my own experience. When running python manage.py runserver 0.0.0.0:8000, I could view urls using localhost:8000, but not my ip address 192.168.1.3:8000.

I ended up disabling ipv6 on my wireless adapter, and running ipconfig /renew. After this everything worked as expected.

Hidden features of Windows batch files

You can use call to evaluate names later, leading to some useful properties.

call set SomeEnvVariable_%extension%=%%%somevalue%%%

Using call to set variables whose names depend on other variables. If used with some variable naming rules, you can emulate data collections like arrays or dictionaries by using careful naming rules. The triple %'s around somevalue are so it will evaluate to one variable name surrounded by single %'s after the call and before set is invoked. This means two %'s in a row escape down to a single % character, and then it will expand it again, so somevalue is effectively a name pointer.

call set TempVar=%%SomeEnvVariable_%extension%%%

Using it with a temp variable to retrieve the value, which you can then use in logic. This most useful when used in conjunction with delayed variable expansion.

To use this method properly, delayed variable expansion needs to be enabled. Because it is off by default, it is best to enable it within the script by putting this as one of the first instructions:

setlocal EnableDelayedExpansion

How to get content body from a httpclient call?

If you are not wanting to use async you can add .Result to force the code to execute synchronously:

private string GetResponseString(string text)
{
    var httpClient = new HttpClient();

    var parameters = new Dictionary<string, string>();
    parameters["text"] = text;

    var response = httpClient.PostAsync(BaseUri, new FormUrlEncodedContent(parameters)).Result;
    var contents = response.Content.ReadAsStringAsync().Result;

    return contents;
 }  

remove double quotes from Json return data using Jquery

Someone here suggested using eval() to remove the quotes from a string. Don't do that, that's just begging for code injection.

Another way to do this that I don't see listed here is using:

let message = JSON.stringify(your_json_here); // "Hello World"
console.log(JSON.parse(message))              // Hello World

Defining array with multiple types in TypeScript

My TS lint was complaining about other solutions, so the solution that was working for me was:

item: Array<Type1 | Type2>

if there's only one type, it's fine to use:

item: Type1[]

scp or sftp copy multiple files with single command

The answers with {file1,file2,file3} works only with bash (on remote or locally)

The real way is :

scp user@remote:'/path1/file1 /path2/file2 /path3/file3' /localPath

Unable to compile class for JSP

org.apache.jasper.JasperException: Unable to compile class for JSP:

enter image

'App not Installed' Error on Android

I had a similar issue and it was because I was trying to install an apk on a phone with a previous version of the same apk, and both apks hadn't been signed with the same certificate. I mean when I used the same certificate I was able to overwrite the previous installation, but when I changed the certificate between versions, the installation was not possible. Are you using the same certificate?

VS 2012: Scroll Solution Explorer to current file

If you need one-off sync with the solution pane, then there is new command "Sync with Active Document" (default shortcut: Ctrl+[, S). Explained here: Visual Studio 2012 New Features: Solution Explorer

Insert data to MySql DB and display if insertion is success or failure

After INSERT query you can use ROW_COUNT() to check for successful insert operation as:

SELECT IF(ROW_COUNT() = 1,  "Insert Success", "Insert Failed") As status;

How to calculate a mod b in Python?

mod = a % b

This stores the result of a mod b in the variable mod.

And you are right, 15 mod 4 is 3, which is exactly what python returns:

>>> 15 % 4
3

a %= b is also valid.

How are "mvn clean package" and "mvn clean install" different?

Package & install are various phases in maven build lifecycle. package phase will execute all phases prior to that & it will stop with packaging the project as a jar. Similarly install phase will execute all prior phases & finally install the project locally for other dependent projects.

For understanding maven build lifecycle please go through the following link https://ayolajayamaha.blogspot.in/2014/05/difference-between-mvn-clean-install.html

Multiple Python versions on the same machine?

I think it is totally independent. Just install them, then you have the commands e.g. /usr/bin/python2.5 and /usr/bin/python2.6. Link /usr/bin/python to the one you want to use as default.

All the libraries are in separate folders (named after the version) anyway.

If you want to compile the versions manually, this is from the readme file of the Python source code:

Installing multiple versions

On Unix and Mac systems if you intend to install multiple versions of Python using the same installation prefix (--prefix argument to the configure script) you must take care that your primary python executable is not overwritten by the installation of a different version. All files and directories installed using "make altinstall" contain the major and minor version and can thus live side-by-side. "make install" also creates ${prefix}/bin/python3 which refers to ${prefix}/bin/pythonX.Y. If you intend to install multiple versions using the same prefix you must decide which version (if any) is your "primary" version. Install that version using "make install". Install all other versions using "make altinstall".

For example, if you want to install Python 2.5, 2.6 and 3.0 with 2.6 being the primary version, you would execute "make install" in your 2.6 build directory and "make altinstall" in the others.

Append an int to a std::string

You cannot cast an int to a char* to get a string. Try this:

std::ostringstream sstream;
sstream << "select logged from login where id = " << ClientID;
std::string query = sstream.str();

stringstream reference

How to increase editor font size?

You can try to search in preferences (android studio IDE > preferences). In aptana studio it works like this making smaller: CMD and -, use CMD shift and =. Works?

Using jquery to get element's position relative to viewport

The easiest way to determine the size and position of an element is to call its getBoundingClientRect() method. This method returns element positions in viewport coordinates. It expects no arguments and returns an object with properties left, right, top, and bottom. The left and top properties give the X and Y coordinates of the upper-left corner of the element and the right and bottom properties give the coordinates of the lower-right corner.

element.getBoundingClientRect(); // Get position in viewport coordinates

Supported everywhere.

Why am I getting "(304) Not Modified" error on some links when using HttpWebRequest?

It is not an issue it is because of caching...

To overcome this add a timestamp to your endpoint call, e.g. axios.get('/api/products').

After timestamp it should be axios.get(/api/products?${Date.now()}.

It will resolve your 304 status code.

Docker: Copying files from Docker container to host

If you just want to pull a file from an image (instead of a running container) you can do this:

docker run --rm <image> cat <source> > <local_dest>

This will bring up the container, write the new file, then remove the container. One drawback, however, is that the file permissions and modified date will not be preserved.

Redis command to get all available keys?

We should be using --scan --pattern with redis 2.8 and later.

You can try using this wrapper on top of redis-cli. https://github.com/VijayantSoni/redis-helper

Difference between clustered and nonclustered index

In general, use an index on a column that's going to be used (a lot) to search the table, such as a primary key (which by default has a clustered index). For example, if you have the query (in pseudocode)

SELECT * FROM FOO WHERE FOO.BAR = 2

You might want to put an index on FOO.BAR. A clustered index should be used on a column that will be used for sorting. A clustered index is used to sort the rows on disk, so you can only have one per table. For example if you have the query

SELECT * FROM FOO ORDER BY FOO.BAR ASCENDING

You might want to consider a clustered index on FOO.BAR.

Probably the most important consideration is how much time your queries are taking. If a query doesn't take much time or isn't used very often, it may not be worth adding indexes. As always, profile first, then optimize. SQL Server Studio can give you suggestions on where to optimize, and MSDN has some information1 that you might find useful

How to install Flask on Windows?

heres a step by step procedure (assuming you've already installed python):

  1. first install chocolatey:

open terminal (Run as Administrator) and type in the command line:

C:/> @powershell -NoProfile -ExecutionPolicy Bypass -Command "iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1'))" && SET PATH=%PATH%;%ALLUSERSPROFILE%\chocolatey\bin

it will take some time to get chocolatey installed on your machine. sit back n relax...

  1. now install pip. type in terminal cinst easy.install pip

  2. now type in terminal: pip install flask

YOU'RE DONE !!! Tested on Win 8.1 with Python 2.7

Splitting String with delimiter

split doesn't work that way in groovy. you have to use tokenize...

See the docs:

http://groovy-lang.org/gdk.html#split()

Check if two unordered lists are equal

You want to see if they contain the same elements, but don't care about the order.

You can use a set:

>>> set(['one', 'two', 'three']) == set(['two', 'one', 'three'])
True

But the set object itself will only contain one instance of each unique value, and will not preserve order.

>>> set(['one', 'one', 'one']) == set(['one'])
True

So, if tracking duplicates/length is important, you probably want to also check the length:

def are_eq(a, b):
    return set(a) == set(b) and len(a) == len(b)

Can I style an image's ALT text with CSS?

Setting the img tag color works

img {color:#fff}

http://jsfiddle.net/YEkAt/

_x000D_
_x000D_
body {background:#000022}_x000D_
img {color:#fff}
_x000D_
<img src="http://badsrc.com/blah" alt="BLAH BLAH BLAH" />
_x000D_
_x000D_
_x000D_

At least one JAR was scanned for TLDs yet contained no TLDs

(tomcat 7.0.32) I had problems to see debug messages althought was enabling TldLocationsCache row in tomcat/conf/logging.properties file. All I could see was a warning but not what libs were scanned. Changed every loglevel tried everything no luck. Then I went rogue debug mode (=remove one by one, clean install etc..) and finally found a reason.

My webapp had a customized tomcat/webapps/mywebapp/WEB-INF/classes/logging.properties file. I copied TldLocationsCache row to this file, finally I could see jars filenames.

# To see debug messages in TldLocationsCache, uncomment the following line: org.apache.jasper.compiler.TldLocationsCache.level = FINE

CSS hide scroll bar if not needed

You can use both .content and .container to overflow:auto. Means if it's text is exceed automatically scroll will come x-axis and y-axis. (no need to give separete x-axis and y-axis commonly give overflow:auto)

.content {overflow:auto;}

Angular2 *ngIf check object array length in template

<div class="row" *ngIf="teamMembers?.length > 0">

This checks first if teamMembers has a value and if teamMembers doesn't have a value, it doesn't try to access length of undefined because the first part of the condition already fails.

unable to dequeue a cell with identifier Cell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard

Stupid mistake:

make sure you add register(TableViewCell.self, forCellReuseIdentifier: "Cell") instead of register(TableViewCell.self, forHeaderFooterViewReuseIdentifier: "Cell")

How can I solve the error LNK2019: unresolved external symbol - function?

For me it works if I add this line below in .vcxproj in the itemGroup cpp file, which is connected to the header file.

<ClCompile Include="file.cpp" />

Play audio file from the assets directory

Here my static version:

public static void playAssetSound(Context context, String soundFileName) {
    try {
        MediaPlayer mediaPlayer = new MediaPlayer();

        AssetFileDescriptor descriptor = context.getAssets().openFd(soundFileName);
        mediaPlayer.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
        descriptor.close();

        mediaPlayer.prepare();
        mediaPlayer.setVolume(1f, 1f);
        mediaPlayer.setLooping(false);
        mediaPlayer.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

read complete file without using loop in java

Since Java 11 you can do it even simpler:

import java.nio.file.Files;

Files.readString(Path path);
Files.readString?(Path path, Charset cs)

Source: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/nio/file/Files.html#readString(java.nio.file.Path)

How to find the statistical mode?

A quick and dirty way of estimating the mode of a vector of numbers you believe come from a continous univariate distribution (e.g. a normal distribution) is defining and using the following function:

estimate_mode <- function(x) {
  d <- density(x)
  d$x[which.max(d$y)]
}

Then to get the mode estimate:

x <- c(5.8, 5.6, 6.2, 4.1, 4.9, 2.4, 3.9, 1.8, 5.7, 3.2)
estimate_mode(x)
## 5.439788

How to sort a collection by date in MongoDB?

Sushant Gupta's answers are a tad bit outdated and don't work anymore.

The following snippet should be like this now :

collection.find({}, {"sort" : ['datefield', 'asc']} ).toArray(function(err,docs) {});

6 digits regular expression

  ^\d{1,6}$

....................

Check if number is decimal

A total cludge.. but hey it works !

$numpart = explode(".", $sumnum); 

if ((exists($numpart[1]) && ($numpart[1] > 0 )){
//    it's a decimal that is greater than zero
} else {
// its not a decimal, or the decimal is zero
}

How to convert string to char array in C++?

If you don't know the size of the string beforehand, you can dynamically allocate an array:

auto tab2 = std::make_unique<char[]>(temp.size() + 1);
std::strcpy(tab2.get(), temp.c_str());

How to remove/delete a large file from commit history in Git repository?

This will remove it from your history

git filter-branch --force --index-filter 'git rm -r --cached --ignore-unmatch bigfile.txt' --prune-empty --tag-name-filter cat -- --all

How can I install Visual Studio Code extensions offline?

Adding to t3chb0t's excellent answer - Use these PowerShell commands to install all VSCode extensions in a folder:

cd C:\PathToFolderWithManyDownloadedExtensionFiles
Get-ChildItem . -Filter *.vsix | ForEach-Object { code --install-extension $_.FullName }

Then, reload VSCode to complete the installation.

Delete all local git branches

Above answers works fine. Here is another approach when we have lot of branches in local repo and we have to delete many branches except few which are lying in local machine.

First git branch will list all the local branches.

To transpose the column of branch names into single row in file by running a unix command
git branch > sample.txt
This will save it in sample.txt file. And run
awk 'BEGIN { ORS = " " } { print }' sample.txt
command in shell. This will transform the column to row and copy the list of branch names in single row.

And then run
git branch -D branch_name(s).
This will delete all listed branches present in local

FutureWarning: elementwise comparison failed; returning scalar, but in the future will perform elementwise comparison

My experience to the same warning message was caused by TypeError.

TypeError: invalid type comparison

So, you may want to check the data type of the Unnamed: 5

for x in df['Unnamed: 5']:
  print(type(x))  # are they 'str' ?

Here is how I can replicate the warning message:

import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(3, 2), columns=['num1', 'num2'])
df['num3'] = 3
df.loc[df['num3'] == '3', 'num3'] = 4  # TypeError and the Warning
df.loc[df['num3'] == 3, 'num3'] = 4  # No Error

Hope it helps.

What is the difference between i = i + 1 and i += 1 in a 'for' loop?

As already pointed out, b += 1 updates b in-place, while a = a + 1 computes a + 1 and then assigns the name a to the result (now a does not refer to a row of A anymore).

To understand the += operator properly though, we need also to understand the concept of mutable versus immutable objects. Consider what happens when we leave out the .reshape:

C = np.arange(12)
for c in C:
    c += 1
print(C)  # [ 0  1  2  3  4  5  6  7  8  9 10 11]

We see that C is not updated, meaning that c += 1 and c = c + 1 are equivalent. This is because now C is a 1D array (C.ndim == 1), and so when iterating over C, each integer element is pulled out and assigned to c.

Now in Python, integers are immutable, meaning that in-place updates are not allowed, effectively transforming c += 1 into c = c + 1, where c now refers to a new integer, not coupled to C in any way. When you loop over the reshaped arrays, whole rows (np.ndarray's) are assigned to b (and a) at a time, which are mutable objects, meaning that you are allowed to stick in new integers at will, which happens when you do a += 1.

It should be mentioned that though + and += are meant to be related as described above (and very much usually are), any type can implement them any way it wants by defining the __add__ and __iadd__ methods, respectively.

How to change the value of attribute in appSettings section with Web.config transformation

You want something like:

<appSettings>
  <add key="developmentModeUserId" xdt:Transform="Remove" xdt:Locator="Match(key)"/>
  <add key="developmentMode" value="false" xdt:Transform="SetAttributes"
          xdt:Locator="Match(key)"/>
</appSettings>

See Also: Web.config Transformation Syntax for Web Application Project Deployment

Change the row color in DataGridView based on the quantity of a cell value

If drv.Item("Quantity").Value < 5  Then

use this to like this

If Cint(drv.Item("Quantity").Value) < 5  Then

MySQL create stored procedure syntax with delimiter

Here is my code to create procedure in MySQL :

DELIMITER $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `procedureName`(IN comId int)
BEGIN
select * from tableName 
         (add joins OR sub query as per your requirement)
         Where (where condition here)
END $$
DELIMITER ;

To call this procedure use this query :

call procedureName(); // without parameter
call procedureName(id,pid); // with parameter

Detail :

1) DEFINER : root is the user name and change it as per your username of mysql localhost is the host you can change it with ip address of the server if you are execute this query on hosting server.

Read here for more detail

How to create a simple proxy in C#?

You can build one with the HttpListener class to listen for incoming requests and the HttpWebRequest class to relay the requests.

How to plot a histogram using Matplotlib in Python with a list of data?

This is an old question but none of the previous answers has addressed the real issue, i.e. that fact that the problem is with the question itself.

First, if the probabilities have been already calculated, i.e. the histogram aggregated data is available in a normalized way then the probabilities should add up to 1. They obviously do not and that means that something is wrong here, either with terminology or with the data or in the way the question is asked.

Second, the fact that the labels are provided (and not intervals) would normally mean that the probabilities are of categorical response variable - and a use of a bar plot for plotting the histogram is best (or some hacking of the pyplot's hist method), Shayan Shafiq's answer provides the code.

However, see issue 1, those probabilities are not correct and using bar plot in this case as "histogram" would be wrong because it does not tell the story of univariate distribution, for some reason (perhaps the classes are overlapping and observations are counted multiple times?) and such plot should not be called a histogram in this case.

Histogram is by definition a graphical representation of the distribution of univariate variable (see Histogram | NIST/SEMATECH e-Handbook of Statistical Methods & Histogram | Wikipedia) and is created by drawing bars of sizes representing counts or frequencies of observations in selected classes of the variable of interest. If the variable is measured on a continuous scale those classes are bins (intervals). Important part of histogram creation procedure is making a choice of how to group (or keep without grouping) the categories of responses for a categorical variable, or how to split the domain of possible values into intervals (where to put the bin boundaries) for continuous type variable. All observations should be represented, and each one only once in the plot. That means that the sum of the bar sizes should be equal to the total count of observation (or their areas in case of the variable widths, which is a less common approach). Or, if the histogram is normalised then all probabilities must add up to 1.

If the data itself is a list of "probabilities" as a response, i.e. the observations are probability values (of something) for each object of study then the best answer is simply plt.hist(probability) with maybe binning option, and use of x-labels already available is suspicious.

Then bar plot should not be used as histogram but rather simply

import matplotlib.pyplot as plt
probability = [0.3602150537634409, 0.42028985507246375, 
  0.373117033603708, 0.36813186813186816, 0.32517482517482516, 
  0.4175257731958763, 0.41025641025641024, 0.39408866995073893, 
  0.4143222506393862, 0.34, 0.391025641025641, 0.3130841121495327, 
  0.35398230088495575]
plt.hist(probability)
plt.show()

with the results

enter image description here

matplotlib in such case arrives by default with the following histogram values

(array([1., 1., 1., 1., 1., 2., 0., 2., 0., 4.]),
 array([0.31308411, 0.32380469, 0.33452526, 0.34524584, 0.35596641,
        0.36668698, 0.37740756, 0.38812813, 0.39884871, 0.40956928,
        0.42028986]),
 <a list of 10 Patch objects>)

the result is a tuple of arrays, the first array contains observation counts, i.e. what will be shown against the y-axis of the plot (they add up to 13, total number of observations) and the second array are the interval boundaries for x-axis.

One can check they they are equally spaced,

x = plt.hist(probability)[1]
for left, right in zip(x[:-1], x[1:]):
  print(left, right, right-left)

enter image description here

Or, for example for 3 bins (my judgment call for 13 observations) one would get this histogram

plt.hist(probability, bins=3)

enter image description here

with the plot data "behind the bars" being

enter image description here

The author of the question needs to clarify what is the meaning of the "probability" list of values - is the "probability" just a name of the response variable (then why are there x-labels ready for the histogram, it makes no sense), or are the list values the probabilities calculated from the data (then the fact they do not add up to 1 makes no sense).

How to write a foreach in SQL Server?

Although cursors usually considered horrible evil I believe this is a case for FAST_FORWARD cursor - the closest thing you can get to FOREACH in TSQL.

Case insensitive searching in Oracle

select user_name
from my_table
where nlssort(user_name, 'NLS_SORT = Latin_CI') = nlssort('%AbC%', 'NLS_SORT = Latin_CI')

Extract elements of list at odd positions

For the odd positions, you probably want:

>>>> list_ = list(range(10))
>>>> print list_[1::2]
[1, 3, 5, 7, 9]
>>>>

Install apps silently, with granted INSTALL_PACKAGES permission

I have been implementing installation without user consent recently - it was a kiosk application for API level 21+ where I had full control over environment.

The basic requirements are

  • API level 21+
  • root access to install the updater as a system privileged app.

The following method reads and installs APK from InputStream:

public static boolean installPackage(Context context, InputStream in, String packageName)
            throws IOException {
        PackageInstaller packageInstaller = context.getPackageManager().getPackageInstaller();
        PackageInstaller.SessionParams params = new PackageInstaller.SessionParams(
                PackageInstaller.SessionParams.MODE_FULL_INSTALL);
        params.setAppPackageName(packageName);
        // set params
        int sessionId = packageInstaller.createSession(params);
        PackageInstaller.Session session = packageInstaller.openSession(sessionId);
        OutputStream out = session.openWrite("COSU", 0, -1);
        byte[] buffer = new byte[65536];
        int c;
        while ((c = in.read(buffer)) != -1) {
            out.write(buffer, 0, c);
        }
        session.fsync(out);
        in.close();
        out.close();

        Intent intent = new Intent(context, MainActivity.class);
        intent.putExtra("info", "somedata");  // for extra data if needed..

        Random generator = new Random();

        PendingIntent i = PendingIntent.getActivity(context, generator.nextInt(), intent,PendingIntent.FLAG_UPDATE_CURRENT);
            session.commit(i.getIntentSender());


        return true;
    }

The following code calls the installation

 try {
     InputStream is = getResources().openRawResource(R.raw.someapk_source);
                    installPackage(MainActivity.this, is, "com.example.apk");
     } catch (IOException e) {
                    Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
     }

for the whole thing to work you desperately need INSTALL_PACKAGES permission, or the code above will fail silently

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

to get this permission you must install your APK as System application which REQUIRES root (however AFTER you have installed your updater application it seem to work WITHOUT root)

To install as system application I created a signed APK and pushed it with

adb push updater.apk /sdcard/updater.apk

and then moved it to system/priv-app - which requires remounting FS (this is why the root is required)

adb shell
su
mount -o rw,remount /system
mv /sdcard/updater.apk /system/priv-app
chmod 644 /system/priv-app/updater.apk

for some reason it didn't work with simple debug version, but logcat shows useful info if your application in priv-app is not picked up for some reason.

How to truncate text in Angular2?

Two way to truncate text into angular.

let str = 'How to truncate text in angular';

1. Solution

  {{str | slice:0:6}}

Output:

   how to

If you want to append any text after slice string like

   {{ (str.length>6)? (str | slice:0:6)+'..':(str) }}

Output:

 how to...

2. Solution(Create custom pipe)

if you want to create custom truncate pipe

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
 name: 'truncate'
})

export class TruncatePipe implements PipeTransform {

transform(value: string, args: any[]): string {
    const limit = args.length > 0 ? parseInt(args[0], 10) : 20;
    const trail = args.length > 1 ? args[1] : '...';
    return value.length > limit ? value.substring(0, limit) + trail : value;
   }
}

In Markup

{{ str | truncate:[20] }} // or 
{{ str | truncate:[20, '...'] }} // or

Don't forget to add a module entry.

@NgModule({
  declarations: [
    TruncatePipe
  ]
})
export class AppModule {}

How can I give eclipse more memory than 512M?

Here is how i increased the memory allocation of eclipse Juno:

enter image description here

I have a total of 4GB on my system and when im working on eclipse, i dont run any other heavy softwares along side it. So I allocated 2Gb.

The thing i noticed is that the difference between min and max values should be of 512. The next value should be let say 2048 min + 512 = 2560max

Here is the heap value inside eclipse after setting -Xms2048m -Xmx2560m:

enter image description here

How to pass arguments to addEventListener listener function?

If I'm not mistaken using calling the function with bind actually creates a new function that is returned by the bind method. This will cause you problems later or if you would like to remove the event listener, as it's basically like an anonymous function:

// Possible:
function myCallback() { /* code here */ }
someObject.addEventListener('event', myCallback);
someObject.removeEventListener('event', myCallback);

// Not Possible:
function myCallback() { /* code here */ }
someObject.addEventListener('event', function() { myCallback });
someObject.removeEventListener('event', /* can't remove anonymous function */);

So take that in mind.

If you are using ES6 you could do the same as suggested but a bit cleaner:

someObject.addEventListener('event', () => myCallback(params));

copy all files and folders from one drive to another drive using DOS (command prompt)

xcopy "C:\SomeFolderName" "D:\SomeFolderName" /h /i /c /k /e /r /y

Use the above command. It will definitely work.

In this command data will be copied from c:\ to D:\, even folders and system files as well. Here's what the flags do:

  • /h copies hidden and system files also
  • /i if destination does not exist and copying more than one file, assume that destination must be a directory
  • /c continue copying even if error occurs
  • /k copies attributes
  • /e copies directories and subdirectories, including empty ones
  • /r overwrites read-only files
  • /y suppress prompting to confirm whether you want to overwrite a file

how to show progress bar(circle) in an activity having a listview before loading the listview with data

ProgressDialog dialog = ProgressDialog.show(Example.this, "", "Loading...", true);

How can I replace a newline (\n) using sed?

Easy-to-understand Solution

I had this problem. The kicker was that I needed the solution to work on BSD's (Mac OS X) and GNU's (Linux and Cygwin) sed and tr:

$ echo 'foo
bar
baz


foo2
bar2
baz2' \
| tr '\n' '\000' \
| sed 's:\x00\x00.*:\n:g' \
| tr '\000' '\n'

Output:

foo
bar
baz

(has trailing newline)

It works on Linux, OS X, and BSD - even without UTF-8 support or with a crappy terminal.

  1. Use tr to swap the newline with another character.

    NULL (\000 or \x00) is nice because it doesn't need UTF-8 support and it's not likely to be used.

  2. Use sed to match the NULL

  3. Use tr to swap back extra newlines if you need them

How to set a value for a selectize.js input?

I had a similar problem. My data is provided by a remote server. I want some value to be entered in the selectize box, but it is not sure in advance whether this value is a valid one on the server.

So I want the value to be entered in the box, and I want selectize to show the possible options just if like the user had entered the value.

I ended up using this hack (which it is probably unsupported):

var $selectize = $("#my_input").selectize(/* settings with load*/);
var selectize = $select[0].selectize;
// get the search from the remote server
selectize.onSearchChange('my value');
// enter the input in the input field
$selectize.parent().find('input').val('my value');
// focus on the input field, to make the options visible
$selectize.parent().find('input').focus();

How to split a string into an array of characters in Python?

from itertools import chain

string = 'your string'
chain(string)

similar to list(string) but returns a generator that is lazily evaluated at point of use, so memory efficient.

How to find if a native DLL file is compiled as x64 or x86?

The Magic field of the IMAGE_OPTIONAL_HEADER (though there is nothing optional about the header in Windows executable images (DLL/EXE files)) will tell you the architecture of the PE.

Here's an example of grabbing the architecture from a file.

public static ushort GetImageArchitecture(string filepath) {
    using (var stream = new System.IO.FileStream(filepath, System.IO.FileMode.Open, System.IO.FileAccess.Read))
    using (var reader = new System.IO.BinaryReader(stream)) {
        //check the MZ signature to ensure it's a valid Portable Executable image
        if (reader.ReadUInt16() != 23117) 
            throw new BadImageFormatException("Not a valid Portable Executable image", filepath);

        // seek to, and read, e_lfanew then advance the stream to there (start of NT header)
        stream.Seek(0x3A, System.IO.SeekOrigin.Current); 
        stream.Seek(reader.ReadUInt32(), System.IO.SeekOrigin.Begin);

        // Ensure the NT header is valid by checking the "PE\0\0" signature
        if (reader.ReadUInt32() != 17744)
            throw new BadImageFormatException("Not a valid Portable Executable image", filepath);

        // seek past the file header, then read the magic number from the optional header
        stream.Seek(20, System.IO.SeekOrigin.Current); 
        return reader.ReadUInt16();
    }
}

The only two architecture constants at the moment are:

0x10b - PE32
0x20b - PE32+

Cheers

UPDATE It's been a while since I posted this answer, yet I still see that it gets a few upvotes now and again so I figured it was worth updating. I wrote a way to get the architecture of a Portable Executable image, which also checks to see if it was compiled as AnyCPU. Unfortunately the answer is in C++, but it shouldn't be too hard to port to C# if you have a few minutes to look up the structures in WinNT.h. If people are interested I'll write a port in C#, but unless people actually want it I wont spend much time stressing about it.

#include <Windows.h>

#define MKPTR(p1,p2) ((DWORD_PTR)(p1) + (DWORD_PTR)(p2))

typedef enum _pe_architecture {
    PE_ARCHITECTURE_UNKNOWN = 0x0000,
    PE_ARCHITECTURE_ANYCPU  = 0x0001,
    PE_ARCHITECTURE_X86     = 0x010B,
    PE_ARCHITECTURE_x64     = 0x020B
} PE_ARCHITECTURE;

LPVOID GetOffsetFromRva(IMAGE_DOS_HEADER *pDos, IMAGE_NT_HEADERS *pNt, DWORD rva) {
    IMAGE_SECTION_HEADER *pSecHd = IMAGE_FIRST_SECTION(pNt);
    for(unsigned long i = 0; i < pNt->FileHeader.NumberOfSections; ++i, ++pSecHd) {
        // Lookup which section contains this RVA so we can translate the VA to a file offset
        if (rva >= pSecHd->VirtualAddress && rva < (pSecHd->VirtualAddress + pSecHd->Misc.VirtualSize)) {
            DWORD delta = pSecHd->VirtualAddress - pSecHd->PointerToRawData;
            return (LPVOID)MKPTR(pDos, rva - delta);
        }
    }
    return NULL;
}

PE_ARCHITECTURE GetImageArchitecture(void *pImageBase) {
    // Parse and validate the DOS header
    IMAGE_DOS_HEADER *pDosHd = (IMAGE_DOS_HEADER*)pImageBase;
    if (IsBadReadPtr(pDosHd, sizeof(pDosHd->e_magic)) || pDosHd->e_magic != IMAGE_DOS_SIGNATURE)
        return PE_ARCHITECTURE_UNKNOWN;

    // Parse and validate the NT header
    IMAGE_NT_HEADERS *pNtHd = (IMAGE_NT_HEADERS*)MKPTR(pDosHd, pDosHd->e_lfanew);
    if (IsBadReadPtr(pNtHd, sizeof(pNtHd->Signature)) || pNtHd->Signature != IMAGE_NT_SIGNATURE)
        return PE_ARCHITECTURE_UNKNOWN;

    // First, naive, check based on the 'Magic' number in the Optional Header.
    PE_ARCHITECTURE architecture = (PE_ARCHITECTURE)pNtHd->OptionalHeader.Magic;

    // If the architecture is x86, there is still a possibility that the image is 'AnyCPU'
    if (architecture == PE_ARCHITECTURE_X86) {
        IMAGE_DATA_DIRECTORY comDirectory = pNtHd->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR];
        if (comDirectory.Size) {
            IMAGE_COR20_HEADER *pClrHd = (IMAGE_COR20_HEADER*)GetOffsetFromRva(pDosHd, pNtHd, comDirectory.VirtualAddress);
            // Check to see if the CLR header contains the 32BITONLY flag, if not then the image is actually AnyCpu
            if ((pClrHd->Flags & COMIMAGE_FLAGS_32BITREQUIRED) == 0)
                architecture = PE_ARCHITECTURE_ANYCPU;
        }
    }

    return architecture;
}

The function accepts a pointer to an in-memory PE image (so you can choose your poison on how to get it their; memory-mapping or reading the whole thing into memory...whatever).

How to detect when a UIScrollView has finished scrolling

I think scrollViewDidEndDecelerating is the one you want. Its UIScrollViewDelegates optional method:

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView

Tells the delegate that the scroll view has ended decelerating the scrolling movement.

UIScrollViewDelegate documentation

How to check if pytorch is using the GPU?

On the office site and the get start page, check GPU for PyTorch as below:

import torch
torch.cuda.is_available()

Reference: PyTorch|Get Start

.htaccess mod_rewrite - how to exclude directory from rewrite rule

What you could also do is put a .htaccess file containing

RewriteEngine Off

In the folders you want to exclude from being rewritten (by the rules in a .htaccess file that's higher up in the tree). Simple but effective.

Why is datetime.strptime not working in this simple example?

You can also do the following,to import datetime

from datetime import datetime as dt

dt.strptime(date, '%Y-%m-%d')

How to put comments in Django templates

Multiline comment in django templates use as follows ex: for .html etc.

{% comment %} All inside this tags are treated as comment {% endcomment %}

Tool to Unminify / Decompress JavaScript

If one is in JS possibility of using Firefox is more. And if its Firefox add on is for rescue. Following one is particularly useful.

https://addons.mozilla.org/en-US/firefox/addon/phoenix/

Using AJAX to pass variable to PHP and retrieve those using AJAX again

Use dataType:"json" for json data

$.ajax({
     url: 'ajax.php', //This is the current doc
     type: "POST",
     dataType:'json', // add json datatype to get json
     data: ({name: 145}),
     success: function(data){
         console.log(data);
     }
});  

Read Docs http://api.jquery.com/jQuery.ajax/

Also in PHP

<?php
  $userAnswer = $_POST['name']; 
  $sql="SELECT * FROM <tablename> where color='".$userAnswer."'" ;
  $result=mysql_query($sql);
  $row=mysql_fetch_array($result);
  // for first row only and suppose table having data
  echo json_encode($row);  // pass array in json_encode  
?>

C# equivalent of C++ map<string,double>

Although System.Collections.Generic.Dictionary matches the tag "hashmap" and will work well in your example, it is not an exact equivalent of C++'s std::map - std::map is an ordered collection.

If ordering is important you should use SortedDictionary.

CSS Change List Item Background Color with Class

Scenario: I have a navigation menu like this. Note: Link <a> is child of list item <li>. I wanted to change the background of the selected list item and remove the background color of unselected list item.

<nav>
        <ul>
            <li><a href="#">Intro</a></li>
            <li><a href="#">Size</a></li>
            <li><a href="#">Play</a></li>
            <li><a href="#">Food</a></li>
        </ul>
        <div class="clear"></div>

       </nav>

I tried to add a class .active into the list item using jQuery but it was not working

.active
{
    background-color: #480048;
}

$("nav li a").click(function () {
        $(this).parent().addClass("active");
        $(this).parent().siblings().removeClass("active");
    });

Solution: Basically, using .active class changing the background-color of list item does not work. So I changed the css class name from .active to "nav li.active a" so using the same javascript it will add the .active class into the selected list item. Now if the list item <li> has .active class then css will change the background color of the child of that list item <a>.

nav li.active a
{
    background-color: #480048;
}

What are all the possible values for HTTP "Content-Type" header?

You can find every content type here: http://www.iana.org/assignments/media-types/media-types.xhtml

The most common type are:

  1. Type application

    application/java-archive
    application/EDI-X12   
    application/EDIFACT   
    application/javascript   
    application/octet-stream   
    application/ogg   
    application/pdf  
    application/xhtml+xml   
    application/x-shockwave-flash    
    application/json  
    application/ld+json  
    application/xml   
    application/zip  
    application/x-www-form-urlencoded  
    
  2. Type audio

    audio/mpeg   
    audio/x-ms-wma   
    audio/vnd.rn-realaudio   
    audio/x-wav   
    
  3. Type image

    image/gif   
    image/jpeg   
    image/png   
    image/tiff    
    image/vnd.microsoft.icon    
    image/x-icon   
    image/vnd.djvu   
    image/svg+xml    
    
  4. Type multipart

    multipart/mixed    
    multipart/alternative   
    multipart/related (using by MHTML (HTML mail).)  
    multipart/form-data  
    
  5. Type text

    text/css    
    text/csv    
    text/html    
    text/javascript (obsolete)    
    text/plain    
    text/xml    
    
  6. Type video

    video/mpeg    
    video/mp4    
    video/quicktime    
    video/x-ms-wmv    
    video/x-msvideo    
    video/x-flv   
    video/webm   
    
  7. Type vnd :

    application/vnd.android.package-archive
    application/vnd.oasis.opendocument.text    
    application/vnd.oasis.opendocument.spreadsheet  
    application/vnd.oasis.opendocument.presentation   
    application/vnd.oasis.opendocument.graphics   
    application/vnd.ms-excel    
    application/vnd.openxmlformats-officedocument.spreadsheetml.sheet   
    application/vnd.ms-powerpoint    
    application/vnd.openxmlformats-officedocument.presentationml.presentation    
    application/msword   
    application/vnd.openxmlformats-officedocument.wordprocessingml.document   
    application/vnd.mozilla.xul+xml   
    

Effective swapping of elements of an array in Java

first of all you shouldn't write for (int k = 0; k **<** data.length **- 1**; k++)because the < is until the k is smaller the length -1 and then the loop will run until the last position in the array and won't get the last place in the array; so you can fix it by two ways: 1: for (int k = 0; k <= data.length - 1; k++) 2: for (int k = 0; k < data.length; k++) and then it will work fine!!! and to swap you can use: to keep one of the int's in another place and then to replace

int x = data[k]
data[k] = data[data.length - 1]
data[data.length - 1] = x;

because you don't want to lose one of the int's!!

Anaconda Navigator won't launch (windows 10)

I tried the following @janny loco's answer first and then reset anaconda to get it to work.

Step 1:

activate root
conda update -n root conda
conda update --all

Step 2:

anaconda-navigator --reset

After running the update commands in step 1 and not seeing any success, I reset anaconda by running the command above based on what I found here.

I am not sure if it was the combination of updating conda and reseting the navigator or just one of the two. So, please try accordingly.

What is thread safe or non-thread safe in PHP?

Apache MPM prefork with modphp is used because it is easy to configure/install. Performance-wise it is fairly inefficient. My preferred way to do the stack, FastCGI/PHP-FPM. That way you can use the much faster MPM Worker. The whole PHP remains non-threaded, but Apache serves threaded (like it should).

So basically, from bottom to top

Linux

Apache + MPM Worker + ModFastCGI (NOT FCGI) |(or)| Cherokee |(or)| Nginx

PHP-FPM + APC

ModFCGI does not correctly support PHP-FPM, or any external FastCGI applications. It only supports non-process managed FastCGI scripts. PHP-FPM is the PHP FastCGI process manager.

How to to send mail using gmail in Laravel?

Using a G Suite account

If you are using a G Suite account, anything you try will fail. At least at the time, this answer is being typed. You must use @gmail.com account, anything else like @example.com will not work.

After you use the gmail.com address. You just need to update .env as most of the people already mentioned.

MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=****@gmail.com
MAIL_PASSWORD=16digitapppassword
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=****@gmail.com
MAIL_FROM_NAME="${APP_NAME}"

Don't forget to create an App password, if you don't see the option probably your 2-factor authentication is not enabled. And there is no need to allow less secure apps if you follow this approach.

Find duplicate records in a table using SQL Server

Select * from dbo.sales group by shoppername having(count(Item) > 1)

Use mysql_fetch_array() with foreach() instead of while()

There's not a good way to convert it to foreach, because mysql_fetch_array() just fetches the next result from $result_select. If you really wanted to foreach, you could do pull all the results into an array first, doing something like the following:

$result_list = array();
while($row = mysql_fetch_array($result_select)) {
   result_list[] = $row;
}

foreach($result_list as $row) {
   ...
}

But there's no good reason I can see to do that - and you still have to use the while loop, which is unavoidable due to how mysql_fetch_array() works. Why is it so important to use a foreach()?

EDIT: If this is just for learning purposes: you can't convert this to a foreach. You have to have a pre-existing array to use a foreach() instead of a while(), and mysql_fetch_array() fetches one result per call - there's no pre-existing array for foreach() to iterate through.

How to print out all the elements of a List in Java?

The Java 8 Streams approach...

list.stream().forEach(System.out::println);

JavaScript, getting value of a td with id name

if i click table name its shown all fields about table. i did table field to show. but i need to know click function.

My Code:

$sql = "SHOW tables from database_name where tables_in_databasename not like '%tablename' and tables_in_databasename not like '%tablename%'";


$result=mysqli_query($cons,$sql);

$count = 0;

$array = array();

while ($row = mysqli_fetch_assoc($result)) {

    $count++;

    $tbody_txt .= '<tr>';

    foreach ($row as $key => $value) {
        if($count  == '1') {
            $thead_txt .='<td>'.$key.'</td>';
        }
        $tbody_txt .='<td>'.$value.'</td>';


        $array[$key][] = $value;
    }
}?>

How to destroy a DOM element with jQuery?

Not sure if it's just me, but using .remove() doesn't seem to work if you are selecting by an id.

Ex: $("#my-element").remove();

I had to use the element's class instead, or nothing happened.

Ex: $(".my-element").remove();

How to read line by line or a whole text file at once?

Well, to do this one can also use the freopen function provided in C++ - http://www.cplusplus.com/reference/cstdio/freopen/ and read the file line by line as follows -:

#include<cstdio>
#include<iostream>

using namespace std;

int main(){
   freopen("path to file", "rb", stdin);
   string line;
   while(getline(cin, line))
       cout << line << endl;
   return 0;
}

do { ... } while (0) — what is it good for?

It helps to group multiple statements into a single one so that a function-like macro can actually be used as a function. Suppose you have:

#define FOO(n)   foo(n);bar(n)

and you do:

void foobar(int n) {
  if (n)
     FOO(n);
}

then this expands to:

void foobar(int n) {
  if (n)
     foo(n);bar(n);
}

Notice that the second call bar(n) is not part of the if statement anymore.

Wrap both into do { } while(0), and you can also use the macro in an if statement.

Why do people write #!/usr/bin/env python on the first line of a Python script?

Expanding a bit on the other answers, here's a little example of how your command line scripts can get into trouble by incautious use of /usr/bin/env shebang lines:

$ /usr/local/bin/python -V
Python 2.6.4
$ /usr/bin/python -V
Python 2.5.1
$ cat my_script.py 
#!/usr/bin/env python
import json
print "hello, json"
$ PATH=/usr/local/bin:/usr/bin
$ ./my_script.py 
hello, json
$ PATH=/usr/bin:/usr/local/bin
$ ./my_script.py 
Traceback (most recent call last):
  File "./my_script.py", line 2, in <module>
    import json
ImportError: No module named json

The json module doesn't exist in Python 2.5.

One way to guard against that kind of problem is to use the versioned python command names that are typically installed with most Pythons:

$ cat my_script.py 
#!/usr/bin/env python2.6
import json
print "hello, json"

If you just need to distinguish between Python 2.x and Python 3.x, recent releases of Python 3 also provide a python3 name:

$ cat my_script.py 
#!/usr/bin/env python3
import json
print("hello, json")

Magento: get a static block as html in a phtml file

<?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('my_static_block_name')->toHtml() ?>

and use this link for more http://www.justwebdevelopment.com/blog/how-to-call-static-block-in-magento/

Read user input inside a loop

Read from the controlling terminal device:

read input </dev/tty

more info: http://compgroups.net/comp.unix.shell/Fixing-stdin-inside-a-redirected-loop

Creating dummy variables in pandas for python

You can create dummy variables to handle the categorical data

# Creating dummy variables for categorical datatypes
trainDfDummies = pd.get_dummies(trainDf, columns=['Col1', 'Col2', 'Col3', 'Col4'])

This will drop the original columns in trainDf and append the column with dummy variables at the end of the trainDfDummies dataframe.

It automatically creates the column names by appending the values at the end of the original column name.

Java Enum return Int

Font.PLAIN is not an enum. It is just an int. If you need to take the value out of an enum, you can't avoid calling a method or using a .value, because enums are actually objects of its own type, not primitives.

If you truly only need an int, and you are already to accept that type-safety is lost the user may pass invalid values to your API, you may define those constants as int also:

public final class DownloadType {
    public static final int AUDIO = 0;
    public static final int VIDEO = 1;
    public static final int AUDIO_AND_VIDEO = 2;

    // If you have only static members and want to simulate a static
    // class in Java, then you can make the constructor private.
    private DownloadType() {}
}

By the way, the value field is actually redundant because there is also an .ordinal() method, so you could define the enum as:

enum DownloadType { AUDIO, VIDEO, AUDIO_AND_VIDEO }

and get the "value" using

DownloadType.AUDIO_AND_VIDEO.ordinal()

Edit: Corrected the code.. static class is not allowed in Java. See this SO answer with explanation and details on how to define static classes in Java.

Import SQL dump into PostgreSQL database

I believe that you want to run in psql:

\i C:/database/db-backup.sql

Remove all special characters, punctuation and spaces from string

import re
abc = "askhnl#$%askdjalsdk"
ddd = abc.replace("#$%","")
print (ddd)

and you shall see your result as

'askhnlaskdjalsdk

Eclipse Java Missing required source folder: 'src'

Right Click Project -> New -> Folder -> Folder Name: src -> Finish

Position Absolute + Scrolling

I ran into this situation and creating an extra div was impractical. I ended up just setting the full-height div to height: 10000%; overflow: hidden;

Clearly not the cleanest solution, but it works really fast.

jquery append div inside div with id and manipulate

Why not go even simpler with either one of these options:

$("#box").html('<div id="myid" style="display:block; float:left;width:'+width+'px; height:'+height+'px; margin-top:'+positionY+'px;margin-left:'+positionX+'px;border:1px dashed #CCCCCC;"></div>');

Or, if you want to append it to existing content:

$("#box").append('<div id="myid" style="display:block; float:left;width:'+width+'px; height:'+height+'px; margin-top:'+positionY+'px;margin-left:'+positionX+'px;border:1px dashed #CCCCCC;"></div>');

Note: I put the id="myid" right into the HTML string rather than using separate code to set it.

Both the .html() and .append() jQuery methods can take a string of HTML so there's no need to use a separate step for creating the objects.

Run javascript function when user finishes typing instead of on key up?

If you need wait until user is finished with typing use simple this:

$(document).on('change','#PageSize', function () {
    //Do something after new value in #PageSize       
});

Complete Example with ajax call - this working for my pager - count of item per list:

$(document).ready(function () {
    $(document).on('change','#PageSize', function (e) {
        e.preventDefault();
        var page = 1;
        var pagesize = $("#PageSize").val();
        var q = $("#q").val();
        $.ajax({
            url: '@Url.Action("IndexAjax", "Materials", new { Area = "TenantManage" })',
            data: { q: q, pagesize: pagesize, page: page },
            type: 'post',
            datatype: "json",
            success: function (data) {
                $('#tablecontainer').html(data);
               // toastr.success('Pager has been changed', "Success!");
            },
            error: function (jqXHR, exception) {
                ShowErrorMessage(jqXHR, exception);
            }
        });  
    });
});    

How can I pass data from Flask to JavaScript in a template?

You can use {{ variable }} anywhere in your template, not just in the HTML part. So this should work:

<html>
<head>
  <script>
    var someJavaScriptVar = '{{ geocode[1] }}';
  </script>
</head>
<body>
  <p>Hello World</p>
  <button onclick="alert('Geocode: {{ geocode[0] }} ' + someJavaScriptVar)" />
</body>
</html>

Think of it as a two-stage process: First, Jinja (the template engine Flask uses) generates your text output. This gets sent to the user who executes the JavaScript he sees. If you want your Flask variable to be available in JavaScript as an array, you have to generate an array definition in your output:

<html>
  <head>
    <script>
      var myGeocode = ['{{ geocode[0] }}', '{{ geocode[1] }}'];
    </script>
  </head>
  <body>
    <p>Hello World</p>
    <button onclick="alert('Geocode: ' + myGeocode[0] + ' ' + myGeocode[1])" />
  </body>
</html>

Jinja also offers more advanced constructs from Python, so you can shorten it to:

<html>
<head>
  <script>
    var myGeocode = [{{ ', '.join(geocode) }}];
  </script>
</head>
<body>
  <p>Hello World</p>
  <button onclick="alert('Geocode: ' + myGeocode[0] + ' ' + myGeocode[1])" />
</body>
</html>

You can also use for loops, if statements and many more, see the Jinja2 documentation for more.

Also, have a look at Ford's answer who points out the tojson filter which is an addition to Jinja2's standard set of filters.

Edit Nov 2018: tojson is now included in Jinja2's standard set of filters.

Importing variables from another file?

In Python you can access the contents of other files like as if they
are some kind of a library, compared to other languages like java or any oop base languages , This is really cool ;

This makes accessing the contents of the file or import it to to process it or to do anything with it ; And that is the Main reason why Python is highly preferred Language for Data Science and Machine Learning etc. ;

And this is the picture of project structure This

Where I am accessing variables from .env file where the API links and Secret keys reside .

General Structure:

from <File-Name> import *

Align div with fixed position on the right side

Here's the real solution (with other cool CSS3 stuff):

#fixed-square {
position: fixed;
top: 0;
right: 0;
z-index: 9500;
cursor: pointer;
width: 24px;
padding: 18px 18px 14px;
opacity: 0.618;
-webkit-transform: rotate(-90deg);
-moz-transform: rotate(-90deg);
-ms-transform: rotate(-90deg);
transform: rotate(-90deg);
-webkit-transition: all 0.145s ease-out;
-moz-transition: all 0.145s ease-out;
-ms-transition: all 0.145s ease-out;
transition: all 0.145s ease-out;
}

Note the top:0 and right:0. That's what did it for me.

What are file descriptors, explained in simple terms?

A file descriptor is an opaque handle that is used in the interface between user and kernel space to identify file/socket resources. Therefore, when you use open() or socket() (system calls to interface to the kernel), you are given a file descriptor, which is an integer (it is actually an index into the processes u structure - but that is not important). Therefore, if you want to interface directly with the kernel, using system calls to read(), write(), close() etc. the handle you use is a file descriptor.

There is a layer of abstraction overlaid on the system calls, which is the stdio interface. This provides more functionality/features than the basic system calls do. For this interface, the opaque handle you get is a FILE*, which is returned by the fopen() call. There are many many functions that use the stdio interface fprintf(), fscanf(), fclose(), which are there to make your life easier. In C, stdin, stdout, and stderr are FILE*, which in UNIX respectively map to file descriptors 0, 1 and 2.

HTML meta tag for content language

As a complement to other answers note that you can also put the lang attribute on various HTML tags inside a page. For example to give a hint to the spellchecker that the input text should be in english:

<input ... spellcheck="true" lang="en"> ...

See: https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/lang

Get Max value from List<myType>

Easiest way is to use System.Linq as previously described

using System.Linq;

public int GetHighestValue(List<MyTypes> list)
{
    return list.Count > 0 ? list.Max(t => t.Age) : 0; //could also return -1
}

This is also possible with a Dictionary

using System.Linq;

public int GetHighestValue(Dictionary<MyTypes, OtherType> obj)
{
    return obj.Count > 0 ? obj.Max(t => t.Key.Age) : 0; //could also return -1
}

What's the difference between "Layers" and "Tiers"?

When you talk about presentation, service, data, network layer, you are talking about layers. When you "deploy them separately", you talk about tiers.

Tiers is all about deployment. Take it this way: We have an application which has a frontend created in Angular, it has a backend as MongoDB and a middle layer which interacts between the frontend and the backend. So, when this frontend application, database application, and the middle layer is all deployed separately, we say it's a 3 tier application.

Benefit: If we need to scale our backend in the future, we only need to scale the backend independently and there's no need to scale up the frontend.

Mergesort with Python

After implementing different versions of solution, I finally made a trade-off to achieve these goals based on CLRS version.

Goal

  • not using list.pop() to iterate values
  • not creating a new list for saving result, modifying the original one instead
  • not using float('inf') as sentinel values
def mergesort(A, p, r):
    if(p < r):
        q = (p+r)//2
        mergesort(A, p, q)
        mergesort(A, q+1, r)
        merge(A, p, q, r)
def merge(A, p, q, r):
    L = A[p:q+1]
    R = A[q+1:r+1]
    i = 0
    j = 0
    k = p
    while i < len(L) and j < len(R):
        if(L[i] < R[j]):
            A[k] = L[i]
            i += 1
        else:
            A[k] = R[j]
            j += 1
        k += 1
    if i < len(L):
        A[k:r+1] = L[i:]
if __name__ == "__main__":
    items = [6, 2, 9, 1, 7, 3, 4, 5, 8]
    mergesort(items, 0, len(items)-1)
    print items
    assert items == [1, 2, 3, 4, 5, 6, 7, 8, 9]

Reference

[1] Book: CLRS

[2] https://github.com/gzc/CLRS/blob/master/C02-Getting-Started/exercise_code/merge-sort.py

Powershell Execute remote exe with command line arguments on remote computer

I have been trying to achieve this by using 1 row single entry but I ended that Invoke command did not worked successfully because it is killing the process immediately after starting despite it can work if you are entering the session and waiting enough before exiting.

The only working way I could find, for example, to run a command with arguments and space on the remote machine HFVMACHINE1 (running Windows 7) is the following:

([WMICLASS]"\\HFVMACHINE1\ROOT\CIMV2:win32_process").Create('c:\Program Files (x86)\Thinware\vBackup\vBackup.exe -v HFSVR12-WWW')

jQuery get input value after keypress

Just use a timeout to make your call; the timeout will be called when the event stack is finished (i.e. after the default event is called)

$("body").on('keydown', 'input[type=tel]', function (e) {
    setTimeout(() => {
        formatPhone(e)
    }, 0)
});

Error: Module not specified (IntelliJ IDEA)

this is how I fix this issue
1.open my project structure

2.click module enter image description here 3.click plus button enter image description here 4.click import module,and find the module's pom enter image description here
5.make sure you select the module you want to import,then next next finish:) enter image description here

IIS7: Setup Integrated Windows Authentication like in IIS6

Two-stage authentication is not supported with IIS7 Integrated mode. Authentication is now modularized, so rather than IIS performing authentication followed by asp.net performing authentication, it all happens at the same time.

You can either:

  1. Change the app domain to be in IIS6 classic mode...
  2. Follow this example (old link) of how to fake two-stage authentication with IIS7 integrated mode.
  3. Use Helicon Ape and mod_auth to provide basic authentication

CSS body background image fixed to full screen even when zooming in/out

Add this in your css file:

.custom_class
 {
    background-image: url(../img/beach.jpg);
    -moz-background-size: cover;
    -webkit-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
 }

and then, in your .html (or .php) file call this class like that:

<div class="custom_class">
   ...
</div>

How to represent matrices in python

If you are not going to use the NumPy library, you can use the nested list. This is code to implement the dynamic nested list (2-dimensional lists).

Let r is the number of rows

let r=3

m=[]
for i in range(r):
    m.append([int(x) for x in raw_input().split()])

Any time you can append a row using

m.append([int(x) for x in raw_input().split()])

Above, you have to enter the matrix row-wise. To insert a column:

for i in m:
    i.append(x) # x is the value to be added in column

To print the matrix:

print m       # all in single row

for i in m:
    print i   # each row in a different line

Limit Decimal Places in Android EditText

I've also came across this problem. I wanted to be able to reuse the code in many EditTexts. This is my solution:

Usage :

CurrencyFormat watcher = new CurrencyFormat();
priceEditText.addTextChangedListener(watcher);

Class:

public static class CurrencyFormat implements TextWatcher {

    public void onTextChanged(CharSequence arg0, int start, int arg2,int arg3) {}

    public void beforeTextChanged(CharSequence arg0, int start,int arg2, int arg3) {}

    public void afterTextChanged(Editable arg0) {
        int length = arg0.length();
        if(length>0){
            if(nrOfDecimal(arg0.toString())>2)
                    arg0.delete(length-1, length);
        }

    }


    private int nrOfDecimal(String nr){
        int len = nr.length();
        int pos = len;
        for(int i=0 ; i<len; i++){
            if(nr.charAt(i)=='.'){
                pos=i+1;
                    break;
            }
        }
        return len-pos;
    }
}

How can I call PHP functions by JavaScript?

use document.write for example,

<script>
  document.write(' <?php add(1,2); ?> ');
  document.write(' <?php milt(1,2); ?> ');
  document.write(' <?php divide(1,2); ?> ');
</script>

Accessing a property in a parent Component

There are different way:

export class Profile implements OnInit {
constructor(@Host() parent: App) {
  parent.userStatus ...
}
  • data-binding
export class Profile implements OnInit {
  @Input() userStatus:UserStatus;
  ...
}

<profile [userStatus]="userStatus">

Bash mkdir and subfolders

FWIW,

Poor mans security folder (to protect a public shared folder from little prying eyes ;) )

mkdir -p {0..9}/{0..9}/{0..9}/{0..9}

Now you can put your files in a pin numbered folder. Not exactly waterproof, but it's a barrier for the youngest.

How do I run SSH commands on remote system using Java?

Below is the easiest way to SSh in java. Download any of the file in the below link and extract, then add the jar file from the extracted file and add to your build path of the project http://www.ganymed.ethz.ch/ssh2/ and use the below method

public void SSHClient(String serverIp,String command, String usernameString,String password) throws IOException{
        System.out.println("inside the ssh function");
        try
        {
            Connection conn = new Connection(serverIp);
            conn.connect();
            boolean isAuthenticated = conn.authenticateWithPassword(usernameString, password);
            if (isAuthenticated == false)
                throw new IOException("Authentication failed.");        
            ch.ethz.ssh2.Session sess = conn.openSession();
            sess.execCommand(command);  
            InputStream stdout = new StreamGobbler(sess.getStdout());
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
            System.out.println("the output of the command is");
            while (true)
            {
                String line = br.readLine();
                if (line == null)
                    break;
                System.out.println(line);
            }
            System.out.println("ExitCode: " + sess.getExitStatus());
            sess.close();
            conn.close();
        }
        catch (IOException e)
        {
            e.printStackTrace(System.err);

        }
    }

How to select the first row of each group?

The pattern is group by keys => do something to each group e.g. reduce => return to dataframe

I thought the Dataframe abstraction is a bit cumbersome in this case so I used RDD functionality

 val rdd: RDD[Row] = originalDf
  .rdd
  .groupBy(row => row.getAs[String]("grouping_row"))
  .map(iterableTuple => {
    iterableTuple._2.reduce(reduceFunction)
  })

val productDf = sqlContext.createDataFrame(rdd, originalDf.schema)

How do I check if an object has a key in JavaScript?

Try the JavaScript in operator.

if ('key' in myObj)

And the inverse.

if (!('key' in myObj))

Be careful! The in operator matches all object keys, including those in the object's prototype chain.

Use myObj.hasOwnProperty('key') to check an object's own keys and will only return true if key is available on myObj directly:

myObj.hasOwnProperty('key')

Unless you have a specific reason to use the in operator, using myObj.hasOwnProperty('key') produces the result most code is looking for.

jQuery access input hidden value

If you want to select an individual hidden field, you can select it through the different selectors of jQuery :

<input type="hidden" id="hiddenField" name="hiddenField" class="hiddenField"/> 


$("#hiddenField").val(); //by id
$("[name='hiddenField']").val(); // by name
$(".hiddenField").val(); // by class

How do I clone into a non-empty directory?

Here's what I ended up doing when I had the same problem (at least I think it's the same problem). I went into directory A and ran git init.

Since I didn't want the files in directory A to be followed by git, I edited .gitignore and added the existing files to it. After this I ran git remote add origin '<url>' && git pull origin master et voíla, B is "cloned" into A without a single hiccup.

How do I access (read, write) Google Sheets spreadsheets with Python?

I know this thread is old now, but here is some decent documentation on Google Docs API. It was ridiculously hard to find, but useful, so maybe it will help you some. http://pythonhosted.org/gdata/docs/api.html.

I used gspread recently for a project to graph employee time data. I don't know how much it might help you, but here's a link to the code: https://github.com/lightcastle/employee-timecards

Gspread made things pretty easy for me. I was also able to add logic in to check for various conditions to create month-to-date and year-to-date results. But I just imported the whole dang spreadsheet and parsed it from there, so I'm not 100% sure that it is exactly what you're looking for. Best of luck.

The property 'Id' is part of the object's key information and cannot be modified

I had this happening when I was editing related objects from two separate contexts at the same time. Example:

DataContext ctxA = new DataContext();
DataContext ctxB = new DataContext();

Author orwell = new Author {Name = "George Orwell" };
ctxA.Add(orwell);
ctxB.Add(new Book {Name = "1984", Author = orwell});

ctxA.SaveChanges();
ctxB.SaveChanges();

My case was a little bit more convoluted (as this is obviously quite stupid) but in essence this was causing the error in my case.

jQuery posting valid json in request body

An actual JSON request would look like this:

data: '{"command":"on"}',

Where you're sending an actual JSON string. For a more general solution, use JSON.stringify() to serialize an object to JSON, like this:

data: JSON.stringify({ "command": "on" }),

To support older browsers that don't have the JSON object, use json2.js which will add it in.


What's currently happening is since you have processData: false, it's basically sending this: ({"command":"on"}).toString() which is [object Object]...what you see in your request.

Python NameError: name is not defined

Define the class before you use it:

class Something:
    def out(self):
        print("it works")

s = Something()
s.out()

You need to pass self as the first argument to all instance methods.

Get generic type of java.util.List

You can do the same for method parameters as well:

Method method = someClass.getDeclaredMethod("someMethod");
Type[] types = method.getGenericParameterTypes();
//Now assuming that the first parameter to the method is of type List<Integer>
ParameterizedType pType = (ParameterizedType) types[0];
Class<?> clazz = (Class<?>) pType.getActualTypeArguments()[0];
System.out.println(clazz); //prints out java.lang.Integer

How to do exponential and logarithmic curve fitting in Python? I found only polynomial fitting

For fitting y = A + B log x, just fit y against (log x).

>>> x = numpy.array([1, 7, 20, 50, 79])
>>> y = numpy.array([10, 19, 30, 35, 51])
>>> numpy.polyfit(numpy.log(x), y, 1)
array([ 8.46295607,  6.61867463])
# y ˜ 8.46 log(x) + 6.62

For fitting y = AeBx, take the logarithm of both side gives log y = log A + Bx. So fit (log y) against x.

Note that fitting (log y) as if it is linear will emphasize small values of y, causing large deviation for large y. This is because polyfit (linear regression) works by minimizing ?i (?Y)2 = ?i (YiYi)2. When Yi = log yi, the residues ?Yi = ?(log yi) ˜ ?yi / |yi|. So even if polyfit makes a very bad decision for large y, the "divide-by-|y|" factor will compensate for it, causing polyfit favors small values.

This could be alleviated by giving each entry a "weight" proportional to y. polyfit supports weighted-least-squares via the w keyword argument.

>>> x = numpy.array([10, 19, 30, 35, 51])
>>> y = numpy.array([1, 7, 20, 50, 79])
>>> numpy.polyfit(x, numpy.log(y), 1)
array([ 0.10502711, -0.40116352])
#    y ˜ exp(-0.401) * exp(0.105 * x) = 0.670 * exp(0.105 * x)
# (^ biased towards small values)
>>> numpy.polyfit(x, numpy.log(y), 1, w=numpy.sqrt(y))
array([ 0.06009446,  1.41648096])
#    y ˜ exp(1.42) * exp(0.0601 * x) = 4.12 * exp(0.0601 * x)
# (^ not so biased)

Note that Excel, LibreOffice and most scientific calculators typically use the unweighted (biased) formula for the exponential regression / trend lines. If you want your results to be compatible with these platforms, do not include the weights even if it provides better results.


Now, if you can use scipy, you could use scipy.optimize.curve_fit to fit any model without transformations.

For y = A + B log x the result is the same as the transformation method:

>>> x = numpy.array([1, 7, 20, 50, 79])
>>> y = numpy.array([10, 19, 30, 35, 51])
>>> scipy.optimize.curve_fit(lambda t,a,b: a+b*numpy.log(t),  x,  y)
(array([ 6.61867467,  8.46295606]), 
 array([[ 28.15948002,  -7.89609542],
        [ -7.89609542,   2.9857172 ]]))
# y ˜ 6.62 + 8.46 log(x)

For y = AeBx, however, we can get a better fit since it computes ?(log y) directly. But we need to provide an initialize guess so curve_fit can reach the desired local minimum.

>>> x = numpy.array([10, 19, 30, 35, 51])
>>> y = numpy.array([1, 7, 20, 50, 79])
>>> scipy.optimize.curve_fit(lambda t,a,b: a*numpy.exp(b*t),  x,  y)
(array([  5.60728326e-21,   9.99993501e-01]),
 array([[  4.14809412e-27,  -1.45078961e-08],
        [ -1.45078961e-08,   5.07411462e+10]]))
# oops, definitely wrong.
>>> scipy.optimize.curve_fit(lambda t,a,b: a*numpy.exp(b*t),  x,  y,  p0=(4, 0.1))
(array([ 4.88003249,  0.05531256]),
 array([[  1.01261314e+01,  -4.31940132e-02],
        [ -4.31940132e-02,   1.91188656e-04]]))
# y ˜ 4.88 exp(0.0553 x). much better.

comparison of exponential regression

How do I assert an Iterable contains elements with a certain property?

As long as your List is a concrete class, you can simply call the contains() method as long as you have implemented your equals() method on MyItem.

// given 
// some input ... you to complete

// when
List<MyItems> results = service.getMyItems();

// then
assertTrue(results.contains(new MyItem("foo")));
assertTrue(results.contains(new MyItem("bar")));

Assumes you have implemented a constructor that accepts the values you want to assert on. I realise this isn't on a single line, but it's useful to know which value is missing rather than checking both at once.

Consider defining a bean of type 'package' in your configuration [Spring-Boot]

For me - using Spring Boot with MongoDB, the following was the Problem:

In my POM.xml I had:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-starter-data-mongodb</artifactId>
</dependency>

but I needed the following:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-mongodb</artifactId>
    </dependency>

(Short: Add "spring-boot-..." instead of only "spring-...")

How to force delete a file?

You have to close that application first. There is no way to delete it, if it's used by some application.

UnLock IT is a neat utility that helps you to take control of any file or folder when it is locked by some application or system. For every locked resource, you get a list of locking processes and can unlock it by terminating those processes. EMCO Unlock IT offers Windows Explorer integration that allows unlocking files and folders by one click in the context menu.

There's also Unlocker (not recommended, see Warning below), which is a free tool which helps locate any file locking handles running, and give you the option to turn it off. Then you can go ahead and do anything you want with those files.

Warning: The installer includes a lot of undesirable stuff. You're almost certainly better off with UnLock IT.

Get Excel sheet name and use as variable in macro

in a Visual Basic Macro you would use

pName = ActiveWorkbook.Path      ' the path of the currently active file
wbName = ActiveWorkbook.Name     ' the file name of the currently active file
shtName = ActiveSheet.Name       ' the name of the currently selected worksheet

The first sheet in a workbook can be referenced by

ActiveWorkbook.Worksheets(1)

so after deleting the [Report] tab you would use

ActiveWorkbook.Worksheets("Report").Delete
shtName = ActiveWorkbook.Worksheets(1).Name

to "work on that sheet later on" you can create a range object like

Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(shtName).[A1]

and continue working on MySheet(rowNum, colNum) etc. ...

shortcut creation of a range object without defining shtName:

Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(1).[A1]

What is the difference between 'protected' and 'protected internal'?

In practice, about methods:

protected - accessible for inherited classes, otherwise private.

internal - public only for classes inside the assembly, otherwise private.

protected internal - means protected or internal - methods become accessible for inherited classes and for any classes inside the assembly.

Replace Default Null Values Returned From Left Outer Join

MySQL

COALESCE(field, 'default')

For example:

  SELECT
    t.id,
    COALESCE(d.field, 'default')
  FROM
     test t
  LEFT JOIN
     detail d ON t.id = d.item

Also, you can use multiple columns to check their NULL by COALESCE function. For example:

mysql> SELECT COALESCE(NULL, 1, NULL);
        -> 1
mysql> SELECT COALESCE(0, 1, NULL);
        -> 0
mysql> SELECT COALESCE(NULL, NULL, NULL);
        -> NULL