Programs & Examples On #Assembly.load

Could not load file or assembly 'Newtonsoft.Json' or one of its dependencies. Manifest definition does not match the assembly reference

After hours struggling with this... I did the following:

web.config

<runtime>

  <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">

    <dependentAssembly>
      <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
      <bindingRedirect oldVersion="0.0.0.0-12.0.0.0" newVersion="12.0.0.0" />
    </dependentAssembly>

    <!-- other assemblies... -->

  </assemblyBinding>
</runtime>

The key to enter the correct newVersion and oldVersion number is open the project's References find the package go to its properties or click alt + enter

You'll find a section Version which in my case was 12.0.0.0 while its actually 12.0.3 when exploring with Manage NuGet.

So you need to pick the package's version from the reference properties (in my case 12.0.0.0)

Finally, clean and rebuild the project (you might want to delete the bin and obj folders before).

You might face other packages dependencies issues, i did that for all and they worked.

Exception of type 'System.OutOfMemoryException' was thrown.

Another thing to try is

Tools -> Options -> search for IIS -> tick Use the 64 bit version of IIS Express for web sites and projects.

Use the 64 bit version of IIS Express for web sites and projects screenshot

Loading DLLs at runtime in C#

It's not so difficult.

You can inspect the available functions of the loaded object, and if you find the one you're looking for by name, then snoop its expected parms, if any. If it's the call you're trying to find, then call it using the MethodInfo object's Invoke method.

Another option is to simply build your external objects to an interface, and cast the loaded object to that interface. If successful, call the function natively.

This is pretty simple stuff.

The module was expected to contain an assembly manifest

In my case, I was using InstallUtil.exe which was causing an error. To install the .Net Core service in window best way to use sc command.

More information here Exe installation throwing error The module was expected to contain an assembly manifest .Net Core

Reflection: How to Invoke Method with parameters

The provided solution does not work for instances of types loaded from a remote assembly. To do that, here is a solution that works in all situations, which involves an explicit type re-mapping of the type returned through the CreateInstance call.

This is how I need to create my classInstance, as it was located in a remote assembly.

// sample of my CreateInstance call with an explicit assembly reference
object classInstance = Activator.CreateInstance(assemblyName, type.FullName); 

However, even with the answer provided above, you'd still get the same error. Here is how to go about:

// first, create a handle instead of the actual object
ObjectHandle classInstanceHandle = Activator.CreateInstance(assemblyName, type.FullName);
// unwrap the real slim-shady
object classInstance = classInstanceHandle.Unwrap(); 
// re-map the type to that of the object we retrieved
type = classInstace.GetType(); 

Then do as the other users mentioned here.

C# catch a stack overflow exception

You can't as most of the posts are explaining, let me add another area:

On many websites you will find people saying that the way to avoid this is using a different AppDomain so if this happens the domain will be unloaded. That is absolutely wrong (unless you host your CLR) as the default behavior of the CLR will raise a KillProcess event, bringing down your default AppDomain.

Could not load file or assembly 'System.Data.SQLite'

I got this error when our windows server was converted from 32 bit OS to 64 bit. The assembly that was throwing the error was set to compile in x86 mode (ie 32 mode). I switched it to "Any CPU" and that did the trick. You can change this value by doing the following:

right click on the project go to Properties -> Build -> Platform Target -> change to "Any CPU"

Correct Way to Load Assembly, Find Class and Call Run() Method

You will need to use reflection to get the type "TestRunner". Use the Assembly.GetType method.

class Program
{
    static void Main(string[] args)
    {
        Assembly assembly = Assembly.LoadFile(@"C:\dyn.dll");
        Type type = assembly.GetType("TestRunner");
        var obj = (TestRunner)Activator.CreateInstance(type);
        obj.Run();
    }
}

Can I load a .NET assembly at runtime and instantiate a type knowing only the name?

You can load an assembly using *Assembly.Load** methods. Using Activator.CreateInstance you can create new instances of the type you want. Keep in mind that you have to use the full type name of the class you want to load (for example Namespace.SubNamespace.ClassName). Using the method InvokeMember of the Type class you can invoke methods on the type.

Also, take into account that once loaded, an assembly cannot be unloaded until the whole AppDomain is unloaded too (this is basically a memory leak).

The HTTP request is unauthorized with client authentication scheme 'Ntlm' The authentication header received from the server was 'NTLM'

I would try to connect to your Sharepoint site with this tool here. If that works you can be sure that the problem is in your code / configuration. That maybe does not solve your problem immediately but it rules out that there is something wrong with the server. Assuming that it does not work I would investigate the following:

  • Does your user really have enough rights on the site?
  • Is there a proxy that interferes? (Your configuration looks a bit like there is a proxy. Can you bypass it?)

I think there is nothing wrong with using security mode Transport, but I am not so sure about the proxyCredentialType="Ntlm", maybe this should be set to None.

CSS Cell Margin

Apply this to your first <td>:

padding-right:10px;

HTML example:

<table>
   <tr>
      <td style="padding-right:10px">data</td>
      <td>more data</td>
   </tr>
</table>

What does the @Valid annotation indicate in Spring?

@Valid in itself has nothing to do with Spring. It's part of Bean Validation specification(there are several of them, the latest one being JSR 380 as of second half of 2017), but @Valid is very old and derives all the way from JSR 303.

As we all know, Spring is very good at providing integration with all different JSRs and java libraries in general(think of JPA, JTA, Caching, etc.) and of course those guys took care of validation as well. One of the key components that facilitates this is MethodValidationPostProcessor.

Trying to answer your question - @Valid is very handy for so called validation cascading when you want to validate a complex graph and not just a top-level elements of an object. Every time you want to go deeper, you have to use @Valid. That's what JSR dictates. Spring will comply with that with some minor deviations(for example I tried putting @Validated instead of @Valid on RestController method and validation works, but the same will not apply for a regular "service" beans).

Comparison of Android Web Service and Networking libraries: OKHTTP, Retrofit and Volley

And yet another option: https://github.com/apptik/jus

  • It is modular like Volley, but more extended and documentation is improving, supporting different HTTP stacks and converters out of the box
  • It has a module to generate server API interface mappings like Retrofit
  • It also has JavaRx support

And many other handy features like markers, transformers, etc.

How can I find my Apple Developer Team id and Team Agent Apple ID?

For personal teams

grep DEVELOPMENT_TEAM MyProject.xcodeproj/project.pbxproj

should give you the team ID

DEVELOPMENT_TEAM = ZU88ND8437;

MVC Razor @foreach

When people say don't put logic in views, they're usually referring to business logic, not rendering logic. In my humble opinion, I think using @foreach in views is perfectly fine.

ASP.NET Bundles how to disable minification

I tried a lot of these suggestions but noting seemed to work. I've wasted quite a few hours only to found out that this was my mistake:

@Scripts.Render("/bundles/foundation")

It always have me minified and bundled javascript, no matter what I tried. Instead, I should have used this:

@Scripts.Render("~/bundles/foundation")

The extra '~' did it. I've even removed it again in only one instance to see if that was really it. It was... hopefully I can save at least one person the hours I wasted on this.

Changing all files' extensions in a folder with one command on Windows

NOTE: not for Windows

Using ren-1.0 the correct form is:

"ren *.*" "#2.jpg"

From man ren

The replacement pattern is another filename with embedded wildcard indexes, each of which consists of the character # followed by a digit from 1 to 9. In the new name of a matching file, the wildcard indexes are replaced by the actual characters that matched the referenced wildcards in the original filename.

and

Note that the shell normally expands the wildcards * and ?, which in the case of ren is undesirable. Thus, in most cases it is necessary to enclose the search pattern in quotes.

What does the red exclamation point icon in Eclipse mean?

There can be several reasons. Most of the times it may be some of the below reasons ,

  1. You have deleted some of the .jar files from your /lib folder
  2. You have added new .jar files
  3. you have added new .jar files which may be conflict with others

So what to do is we have to resolve those missing / updating / newly_added jar files.

  1. right click on the project and go to properties
  2. Select Java Build Path
  3. go to the Libraries tab
  4. Remove the jar file references which you have removed already. There will be a red mark near them so you can identify them easily.
  5. Add the references to the newly added .jar files by using Add JARs
  6. Refresh the project

This will solve the problem if it's because one of the above reasons.

Spring data JPA query with parameter properties

@Autowired
private EntityManager entityManager;

@RequestMapping("/authors/{fname}/{lname}")
    public List actionAutherMulti(@PathVariable("fname") String fname, @PathVariable("lname") String lname) {
        return entityManager.createQuery("select A from Auther A WHERE A.firstName = ?1 AND A.lastName=?2")
                .setParameter(1, fname)
                .setParameter(2, lname)
                .getResultList();
    }

Redirect using AngularJS

Don't forget to inject $location into controller.

Get OS-level system information

I think the best method out there is to implement the SIGAR API by Hyperic. It works for most of the major operating systems ( darn near anything modern ) and is very easy to work with. The developer(s) are very responsive on their forum and mailing lists. I also like that it is GPL2 Apache licensed. They provide a ton of examples in Java too!

SIGAR == System Information, Gathering And Reporting tool.

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

Think about protected internal as applying two access modifier (protected, and internal) on the same field, property or method.

In the real world, imagine we are issuing privilege for people to visit museum:

  1. Everyone inside the city are allowed to visit museum (internal).
  2. Everyone outside of the city that their parents live here are allowed to visit museum (protected).

And we can put them together in these way:

Everyone inside the city (internal) and everyone outside of city that their parents live here (protected) are allowed to visit the museum (protected internal).

Programming world:

internal: The field is available everywhere in the assembly (project). It is like saying it is public in its project scope (but can not being accessed outside of project scope even by those classes outside of assembly which inherit from that class). Every instance of that type can see it in that assembly (project scope).

protected: simply means that all derived classes can see it (inside or outside of assembly). For example derived classes can see the field or method inside its methods and constructors using: base.NameOfProtectedInternal.

So, putting these two access modifier together (protected internal), you have something that can being public inside the project, and can be seen by those which have inherited from that class inside their scope.

They can be written in the internal protected, and does not change the meaning, but it is convenient to write it protected internal.

Can the Android drawable directory contain subdirectories?

  1. Right click on Drawable
  2. Select New ---> Directory
  3. Enter the directory name. Eg: logo.png(the location will already show the drawable folder by default)
  4. Copy and paste the images directly into the drawable folder. While pasting you get an option to choose mdpi/xhdpi/xxhdpi etc for each of the images from a list. Select the appropriate option and enter the name of the image. Make sure to keep the same name as the directory name i.e logo.png
  5. Do the same for the remaining images. All of them will be placed under the logo.png main folder.

Bitwise operation and usage

Bit representations of integers are often used in scientific computing to represent arrays of true-false information because a bitwise operation is much faster than iterating through an array of booleans. (Higher level languages may use the idea of a bit array.)

A nice and fairly simple example of this is the general solution to the game of Nim. Take a look at the Python code on the Wikipedia page. It makes heavy use of bitwise exclusive or, ^.

Position of a string within a string using Linux shell script?

You can use grep to get the byte-offset of the matching part of a string:

echo $str | grep -b -o str

As per your example:

[user@host ~]$ echo "The cat sat on the mat" | grep -b -o cat
4:cat

you can pipe that to awk if you just want the first part

echo $str | grep -b -o str | awk 'BEGIN {FS=":"}{print $1}'

Can't connect to MySQL server on '127.0.0.1' (10061) (2003)

I know that there are a lot of answers to this question already already but i wanted to share my experience as none of the answers provided fixed this issue for me.

After about a day of exploring different solutions I believe the issue was that I have recently installed XAMPP and it was interfering with the MySQL workbench. I have tried changing the port numbers however this hasn't helped, and it seems that both programs are sharing configuration files. Repairing MySQL in the Control Panel didn't resolve it, so now I am uninstalling MySQL and plan to reinstall it. Another potential solution maybe to uninstall XAMPP however the config files may either be deleted, or left in the xampp folder instead of the MySQL folder by doing so.

Using Razor within JavaScript

One thing to add - I found that Razor syntax hilighter (and probably the compiler) interpret the position of the opening bracket differently:

<script type="text/javascript">
    var somevar = new Array();

    @foreach (var item in items)
    {  // <----  placed on a separate line, NOT WORKING, HILIGHTS SYNTAX ERRORS
        <text>
        </text>
    }

    @foreach (var item in items) {  // <----  placed on the same line, WORKING !!!
        <text>
        </text>
    }
</script>

Overriding css style?

Instead of override you can add another class to the element and then you have an extra abilities. for example:

HTML

<div class="style1 style2"></div>

CSS

//only style for the first stylesheet
.style1 {
   width: 100%;      
}
//only style for second stylesheet
.style2 {
   width: 50%;     
}
//override all
.style1.style2 { 
   width: 70%;
}

PKIX path building failed in Java application

If you are using Eclipse just cross check in Eclipse Windows--> preferences---->java---> installed JREs is pointing the current JRE and the JRE where you have configured your certificate. If not remove the JRE and add the jre where your certificate is installed

How can I get a character in a string by index?

string s = "hello";
char c = s[1];
// now c == 'e'

See also Substring, to return more than one character.

Compiling dynamic HTML strings from database

Found in a google discussion group. Works for me.

var $injector = angular.injector(['ng', 'myApp']);
$injector.invoke(function($rootScope, $compile) {
  $compile(element)($rootScope);
});

How do you know a variable type in java?

I learned from the Search Engine(My English is very bad , So code...) How to get variable's type? Up's :

String str = "test";
String type = str.getClass().getName();
value: type = java.lang.String

this method :

str.getClass().getSimpleName();
value:String

now example:

Object o = 1;
o.getClass().getSimpleName();
value:Integer

MySQL integer field is returned as string in PHP

For mysqlnd only:

 mysqli_options($conn, MYSQLI_OPT_INT_AND_FLOAT_NATIVE, true);

Otherwise:

  $row = $result->fetch_assoc();

  while ($field = $result->fetch_field()) {
    switch (true) {
      case (preg_match('#^(float|double|decimal)#', $field->type)):
        $row[$field->name] = (float)$row[$field->name];
        break;
      case (preg_match('#^(bit|(tiny|small|medium|big)?int)#', $field->type)):
        $row[$field->name] = (int)$row[$field->name];
        break;
    }
  }

Crop image in android

hope you are doing well. you can use my code to crop image.you just have to make a class and use this class into your XMl and java classes. Crop image. you can crop your selected image into circle and square into many of option. hope fully it will works for you.because this is totally manageable for you and you can change it according to you.

enjoy your work :)

How To Use DateTimePicker In WPF?

There is DatePicker in WPF Tool Kit, but I have not seen DateTime Picker in WPF ToolKit. So I don't know what kind of DateTimePicker control John is talking about.

How to load json into my angular.js ng-model?

I use following code, found somewhere in the internet don't remember the source though.

    var allText;
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", file, false);
    rawFile.onreadystatechange = function () {
        if (rawFile.readyState === 4) {
            if (rawFile.status === 200 || rawFile.status == 0) {
                allText = rawFile.responseText;
            }
        }
    }
    rawFile.send(null);
    return JSON.parse(allText);

How to do an Integer.parseInt() for a decimal number?

String s = "0.01";
double d = Double.parseDouble(s);
int i = (int) d;

The reason for the exception is that an integer does not hold rational numbers (= basically fractions). So, trying to parse 0.3 to a int is nonsense. A double or a float datatype can hold rational numbers.

The way Java casts a double to an int is done by removing the part after the decimal separator by rounding towards zero.

int i = (int) 0.9999;

i will be zero.

How do I convert hex to decimal in Python?

If by "hex data" you mean a string of the form

s = "6a48f82d8e828ce82b82"

you can use

i = int(s, 16)

to convert it to an integer and

str(i)

to convert it to a decimal string.

Iterate through 2 dimensional array

These functions should work.

// First, cache your array dimensions so you don't have to
//  access them during each iteration of your for loops.
int rowLength = array.length,       // array width (# of columns)
    colLength = array[0].length;    // array height (# of rows)

//     This is your function:
// Prints array elements row by row
var rowString = "";
for(int x = 0; x < rowLength; x++){     // x is the column's index
    for(int y = 0; y < colLength; y++){ // y is the row's index
        rowString += array[x][y];
    } System.out.println(rowString)
}

//      This is the one you want:
// Prints array elements column by column
var colString = "";
for(int y = 0; y < colLength; y++){      // y is the row's index
    for(int x = 0; x < rowLength; x++){  // x is the column's index
        colString += array[x][y];
    } System.out.println(colString)
}

In the first block, the inner loop iterates over each item in the row before moving to the next column.

In the second block (the one you want), the inner loop iterates over all the columns before moving to the next row.

tl;dr: Essentially, the for() loops in both functions are switched. That's it.

I hope this helps you to understand the logic behind iterating over 2-dimensional arrays.

Also, this works whether you have a string[,] or string[][]

how to insert value into DataGridView Cell?

This is perfect code but it cannot add a new row:

dataGridView1.Rows[rowIndex].Cells[columnIndex].Value = value;

But this code can insert a new row:

var index = this.dataGridView1.Rows.Add();
this.dataGridView1.Rows[index].Cells[1].Value = "1";
this.dataGridView1.Rows[index].Cells[2].Value = "Baqar";

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

Simple example

    public  class Simple
    {
        public int Propery { get; set; }
    }

How do I check whether a file exists without exceptions?

import os
path = /path/to/dir

root,dirs,files = os.walk(path).next()
if myfile in files:
   print "yes it exists"

This is helpful when checking for several files. Or you want to do a set intersection/ subtraction with an existing list.

How can I find all of the distinct file extensions in a folder hierarchy?

Try this (not sure if it's the best way, but it works):

find . -type f | perl -ne 'print $1 if m/\.([^.\/]+)$/' | sort -u

It work as following:

  • Find all files from current folder
  • Prints extension of files if any
  • Make a unique sorted list

Ruby on Rails form_for select field with class

You can see in here: http://apidock.com/rails/ActionView/Helpers/FormBuilder/select

Or here: http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/select

Select tag has maximun 4 agrument, and last agrument is html option, it mean you can put class, require, selection option in here.

= f.select :sms_category_id, @sms_category_collect, {}, {class: 'form-control', required: true, selected: @set}

foreach loop in angularjs

The angular.forEach() will iterate through your json object.

First iteration,

key = 0, value = { "name" : "Thomas", "password" : "thomasTheKing"}

Second iteration,

key = 1, value = { "name" : "Linda", "password" : "lindatheQueen" }

To get the value of your name, you can use value.name or value["name"]. Same with your password, you use value.password or value["password"].

The code below will give you what you want:

   angular.forEach(json, function (value, key)
         {
                //console.log(key);
                //console.log(value);
                if (value.password == "thomasTheKing") {
                    console.log("username is thomas");
                }
         });

How can I store and retrieve images from a MySQL database using PHP?

i also recommend thinking this thru and then choosing to store images in your file system rather than the DB .. see here: Storing Images in DB - Yea or Nay?

Yahoo Finance All Currencies quote API Documentation

I have used this URL to obtain multiple currency market quotes.

http://finance.yahoo.com/d/quotes.csv?e=.csv&f=c4l1&s=USD=X,CAD=X,EUR=X

"USD",1.0000
"CAD",1.2458
"EUR",0.8396

They can be parsed in PHP like this:

$symbols = ['USD=X', 'CAD=X', 'EUR=X'];
$url = "http://finance.yahoo.com/d/quotes.csv?e=.csv&f=c4l1&s=".join($symbols, ',');

$quote = array_map( 'str_getcsv', file($url) );

foreach ($quote as $key => $symb) {
    $symbol = $quote[$key][0];
    $value = $quote[$key][1];
}

Duplicate symbols for architecture x86_64 under Xcode

In my case, I named an Entity of my Core Data Model the same as an Object. So: I defined an object "Event.h" and at the same time I had this entity called "Event". I ended up renaming the entity.

What is the most accurate way to retrieve a user's correct IP address in PHP?

Just another clean way:

  function validateIp($var_ip){
    $ip = trim($var_ip);

    return (!empty($ip) &&
            $ip != '::1' &&
            $ip != '127.0.0.1' &&
            filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false)
            ? $ip : false;
  }

  function getClientIp() {
    $ip = @$this->validateIp($_SERVER['HTTP_CLIENT_IP']) ?:
          @$this->validateIp($_SERVER['HTTP_X_FORWARDED_FOR']) ?:
          @$this->validateIp($_SERVER['HTTP_X_FORWARDED']) ?:
          @$this->validateIp($_SERVER['HTTP_FORWARDED_FOR']) ?:
          @$this->validateIp($_SERVER['HTTP_FORWARDED']) ?:
          @$this->validateIp($_SERVER['REMOTE_ADDR']) ?:
          'LOCAL OR UNKNOWN ACCESS';

    return $ip;
  }

Firefox and SSL: sec_error_unknown_issuer

I had this problem with Firefox and my server. I contacted GoDaddy customer support, and they had me install the intermediate server certificate:

http://support.godaddy.com/help/article/868/what-is-an-intermediate-certificate

After a re-start of the World Wide Web Publishing Service, everything worked perfectly.

If you do not have full access to your server, your ISP will have to do this for you.

How to set a Default Route (To an Area) in MVC

I guess you want user to be redirected to ~/AreaZ URL once (s)he has visited ~/ URL. I'd achieve by means of the following code within your root HomeController.

public class HomeController
{
    public ActionResult Index()
    {
        return RedirectToAction("ActionY", "ControllerX", new { Area = "AreaZ" });
    }
}

And the following route in Global.asax.

routes.MapRoute(
    "Redirection to AreaZ",
    String.Empty,
    new { controller = "Home ", action = "Index" }
);

R: numeric 'envir' arg not of length one in predict()

There are several problems here:

  1. The newdata argument of predict() needs a predictor variable. You should thus pass it values for Coupon, instead of Total, which is the response variable in your model.

  2. The predictor variable needs to be passed in as a named column in a data frame, so that predict() knows what the numbers its been handed represent. (The need for this becomes clear when you consider more complicated models, having more than one predictor variable).

  3. For this to work, your original call should pass df in through the data argument, rather than using it directly in your formula. (This way, the name of the column in newdata will be able to match the name on the RHS of the formula).

With those changes incorporated, this will work:

model <- lm(Total ~ Coupon, data=df)
new <- data.frame(Coupon = df$Coupon)
predict(model, newdata = new, interval="confidence")

Run "mvn clean install" in Eclipse

I use eclipse STS, so the maven plugin comes pre-installed. However, if you aren't using STS (Springsource Tool Suite), you can still install the m2Eclipse plugin. Here is the link:

http://www.eclipse.org/m2e/

Once you have this installed, you should be able to run all the maven commands. To do so, from the package explorer, you would right click on either the maven project or the pom.xml in the maven project, highlight Run As, then click Maven Install.

Hope this helped.

pandas python how to count the number of records or rows in a dataframe

The Nan example above misses one piece, which makes it less generic. To do this more "generically" use df['column_name'].value_counts() This will give you the counts of each value in that column.

d=['A','A','A','B','C','C'," " ," "," "," "," ","-1"] # for simplicity

df=pd.DataFrame(d)
df.columns=["col1"]
df["col1"].value_counts() 
      5
A     3
C     2
-1    1
B     1
dtype: int64
"""len(df) give you 12, so we know the rest must be Nan's of some form, while also having a peek into other invalid entries, especially when you might want to ignore them like -1, 0 , "", also"""

How do I make flex box work in safari?

Just try -webkit-flexbox. it's working for safari. webkit-flex safari will not taking.

How to split a number into individual digits in c#?

Substring and Join methods are usable for this statement.

string no = "12345";
string [] numberArray = new string[no.Length];
int counter = 0;

   for (int i = 0; i < no.Length; i++)
   {
     numberArray[i] = no.Substring(counter, 1); // 1 is split length
     counter++;
   }

Console.WriteLine(string.Join(" ", numberArray)); //output >>> 0 1 2 3 4 5

ORA-12154 could not resolve the connect identifier specified

I have an Entity Framework web application that works on my local machine, but this error appears when pushed to another environment. There are other non-Entity Framework applications that work, and I'm able to connect with sqlplus.

Using sysinternals Process Monitor shows that tns names file is not being loaded correctly:

tnsnames.ora status NAME NOT FOUND

Following the documentation I tried to add a section giving the location of the tnsnames file like so:

<configuration>

  <configSections>
    <section name="oracle.manageddataaccess.client"
      type="OracleInternal.Common.ODPMSectionHandler, Oracle.ManagedDataAccess, Version=4.122.1.0, Culture=neutral, PublicKeyToken=89b483f429c47342"/>
  </configSections>
  
  <oracle.manageddataaccess.client>
    <version number="*">
      <settings>
        <setting name="TNS_ADMIN" value="C:\Oracle\product\12.1.0\client_1\Network\Admin"/>
      </settings>
    </version>
  </oracle.manageddataaccess.client>
  
<configuration>

However, this resulted in an immediate 500 server error.

Further investigation showed that the dll I was packaging with the web application was version 4.122.1.0, while the Oracle client environment installed on the machine was 4.121.2.0. As explained in the Oracle EntityFramework package documentation

Note: If your application is a web application and the above entry was added to a web.config and the same config section handler for "oracle.manageddataaccess.client" also exists in machine.config but the "Version" attribute values are different, an error message of "There is a duplicate 'oracle.manageddataaccess.client' section defined." may be observed at runtime. If so, the config section handler entry in the machine.config for "oracle.manageddataaccess.client" has to be removed from the machine.config for the web application to not encounter this error. But given that there may be other applications on the machine that depended on this entry in the machine.config, this config section handler entry may need to be moved to all of the application's .NET config file on that machine that depend on it.

I attempted to add a separate version section in the .NET machine.config without success (there existed a section for version 4.121.2.0 and I added a section for version 4.122.1.0). After I removed the "oracle.manageddataaccess.client" section from the machine.config, the above addition to the web.config resolved ORA-12154.

Solution #1 summary:

  1. Remove "oracle.manageddataaccess.client" from .NET machine.config
  2. Give TNS_ADMIN configuration setting in web.config as above

Solution 2

While researching this problem I found that the TNS_ADMIN environmental variable was not set. I created a new environmental variable called TNS_ADMIN and set the value to "C:\Oracle\product\12.1.0\client_1\Network\Admin". I removed the web.config changes, and removed the "oracle.manageddataaccess.client" section from .NET machine.config, but still received ORA-12154. Only after I restarted the machine did this resolve the issue.

Solution #2 summary:

  1. Create a new environmental variable called TNS_ADMIN and set the value to "C:\Oracle\product\12.1.0\client_1\Network\Admin"
  2. Restart machine

Solution 3

I added an entry for the correct version in the registry and this resolved the issue:

HKLM\Software\Wow6432Node\Oracle\ODP.NET.Managed\4.121.2.0  

The name of the key is TNS_ADMIN and this points to the folder containing the tnsnames file:

C:\Oracle\product\12.1.0\client_1\network 

Not the C:\Oracle\product\12.1.0\client_1\network\admin folder.

Get cart item name, quantity all details woocommerce

This will show only Cart Items Count.

 global $woocommerce; 
    echo $woocommerce->cart->cart_contents_count;

how to copy only the columns in a DataTable to another DataTable?

If only the columns are required then DataTable.Clone() can be used. With Clone function only the schema will be copied. But DataTable.Copy() copies both the structure and data

E.g.

DataTable dt = new DataTable();
dt.Columns.Add("Column Name");
dt.Rows.Add("Column Data");
DataTable dt1 = dt.Clone();
DataTable dt2 = dt.Copy();

dt1 will have only the one column but dt2 will have one column with one row.

PHP Warning: include_once() Failed opening '' for inclusion (include_path='.;C:\xampp\php\PEAR')

It is because you use a relative path.

The easy way to fix this is by using the __DIR__ magic constant, like:

require_once(__DIR__."/initcontrols/config.php");

From the PHP doc:

The directory of the file. If used inside an include, the directory of the included file is returned

How to use wget in php?

You can use curl in order to both fetch the data, and be identified (for both "basic" and "digest" auth), without requiring extended permissions (like exec or allow_url_fopen).

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/file.xml");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_USERPWD, "user:pass");
$result = curl_exec($ch);
curl_close($ch);

Your result will then be stored in the $result variable.

How to add Certificate Authority file in CentOS 7

Complete instruction is as follow:

  1. Extract Private Key from PFX

openssl pkcs12 -in myfile.pfx -nocerts -out private-key.pem -nodes

  1. Extract Certificate from PFX

openssl pkcs12 -in myfile.pfx -nokeys -out certificate.pem

  1. install certificate

yum install -y ca-certificates,

cp your-cert.pem /etc/pki/ca-trust/source/anchors/your-cert.pem ,

update-ca-trust ,

update-ca-trust force-enable

Hope to be useful

Break statement in javascript array map method

That's not possible using the built-in Array.prototype.map. However, you could use a simple for-loop instead, if you do not intend to map any values:

var hasValueLessThanTen = false;
for (var i = 0; i < myArray.length; i++) {
  if (myArray[i] < 10) {
    hasValueLessThanTen = true;
    break;
  }
}

Or, as suggested by @RobW, use Array.prototype.some to test if there exists at least one element that is less than 10. It will stop looping when some element that matches your function is found:

var hasValueLessThanTen = myArray.some(function (val) { 
  return val < 10;
});

How to find all occurrences of an element in a list

import numpy as np
import random  # to create test list

# create sample list
random.seed(365)
l = [random.choice(['s1', 's2', 's3', 's4']) for _ in range(20)]

# convert the list to an array for use with these numpy methods
a = np.array(l)

# create a dict of each unique entry and the associated indices
idx = {v: np.where(a == v)[0].tolist() for v in np.unique(a)}

# print(idx)
{'s1': [7, 9, 10, 11, 17],
 's2': [1, 3, 6, 8, 14, 18, 19],
 's3': [0, 2, 13, 16],
 's4': [4, 5, 12, 15]}

# find a single element with 
idx = np.where(a == 's1')

print(idx)
[out]:
(array([ 7,  9, 10, 11, 17], dtype=int64),)

%timeit

  • Find indices of a single element in a 2M element list with 4 unique elements
# create 2M element list
random.seed(365)
l = [random.choice(['s1', 's2', 's3', 's4']) for _ in range(2000000)]

# create array
a = np.array(l)

# np.where
%timeit np.where(a == 's1')
[out]:
25.9 ms ± 827 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

# list-comprehension
%timeit [i for i, x in enumerate(l) if x == "s1"]
[out]:
175 ms ± 2.73 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

VBA - Run Time Error 1004 'Application Defined or Object Defined Error'

Assgining a value that starts with a "=" will kick in formula evaluation and gave in my case the above mentioned error #1004. Prepending it with a space was the ticket for me.

How can I upload fresh code at github?

If you haven't already created the project in Github, do so on that site. If memory serves, they display a page that tells you exactly how to get your existing code into your new repository. At the risk of oversimplification, though, you'd follow Veeti's instructions, then:

git remote add [name to use for remote] [private URI] # associate your local repository to the remote
git push [name of remote] master # push your repository to the remote

Selenium using Python - Geckodriver executable needs to be in PATH

To set up geckodriver for Selenium Python:

It needs to set the geckodriver path with FirefoxDriver as the below code:

self.driver = webdriver.Firefox(executable_path = 'D:\Selenium_RiponAlWasim\geckodriver-v0.18.0-win64\geckodriver.exe')

Download geckodriver for your suitable OS (from https://github.com/mozilla/geckodriver/releases) ? Extract it in a folder of your choice ? Set the path correctly as mentioned above.

I'm using Python 3.6.2 and Selenium WebDriver 3.4.3 on Windows 10.

Another way to set up geckodriver:

i) Simply paste the geckodriver.exe under /Python/Scripts/ (in my case the folder was: C:\Python36\Scripts)
ii) Now write the simple code as below:

self.driver = webdriver.Firefox()

Error : Index was outside the bounds of the array.

//if i input 9 it should go to 8?

You still have to work with the elements of the array. You will count 8 elements when looping through the array, but they are still going to be array(0) - array(7).

Traverse all the Nodes of a JSON Object Tree with JavaScript

Original Simplified Answer

For a newer way to do it if you don't mind dropping IE and mainly supporting more current browsers (check kangax's es6 table for compatibility). You can use es2015 generators for this. I've updated @TheHippo's answer accordingly. Of course if you really want IE support you can use the babel JavaScript transpiler.

_x000D_
_x000D_
// Implementation of Traverse
function* traverse(o, path=[]) {
    for (var i in o) {
        const itemPath = path.concat(i);
        yield [i,o[i],itemPath,o];
        if (o[i] !== null && typeof(o[i])=="object") {
            //going one step down in the object tree!!
            yield* traverse(o[i], itemPath);
        }
    }
}

// Traverse usage:
//that's all... no magic, no bloated framework
for(var [key, value, path, parent] of traverse({ 
    foo:"bar",
    arr:[1,2,3],
    subo: {
        foo2:"bar2"
    }
})) {
  // do something here with each key and value
  console.log(key, value, path, parent);
}
_x000D_
_x000D_
_x000D_

If you want only own enumerable properties (basically non-prototype chain properties) you can change it to iterate using Object.keys and a for...of loop instead:

_x000D_
_x000D_
function* traverse(o,path=[]) {
    for (var i of Object.keys(o)) {
        const itemPath = path.concat(i);
        yield [i,o[i],itemPath,o];
        if (o[i] !== null && typeof(o[i])=="object") {
            //going one step down in the object tree!!
            yield* traverse(o[i],itemPath);
        }
    }
}

//that's all... no magic, no bloated framework
for(var [key, value, path, parent] of traverse({ 
    foo:"bar",
    arr:[1,2,3],
    subo: {
        foo2:"bar2"
    }
})) {
  // do something here with each key and value
  console.log(key, value, path, parent);
}
_x000D_
_x000D_
_x000D_

EDIT: This edited answer solves infinite looping traversals.

Stopping Pesky Infinite Object Traversals

This edited answer still provides one of the added benefits of my original answer which allows you to use the provided generator function in order to use a cleaner and simple iterable interface (think using for of loops as in for(var a of b) where b is an iterable and a is an element of the iterable). By using the generator function along with being a simpler api it also helps with code reuse by making it so you don't have to repeat the iteration logic everywhere you want to iterate deeply on an object's properties and it also makes it possible to break out of the loop if you would like to stop iteration earlier.

One thing that I notice that has not been addressed and that isn't in my original answer is that you should be careful traversing arbitrary (i.e. any "random" set of) objects, because JavaScript objects can be self referencing. This creates the opportunity to have infinite looping traversals. Unmodified JSON data however cannot be self referencing, so if you are using this particular subset of JS objects you don't have to worry about infinite looping traversals and you can refer to my original answer or other answers. Here is an example of a non-ending traversal (note it is not a runnable piece of code, because otherwise it would crash your browser tab).

Also in the generator object in my edited example I opted to use Object.keys instead of for in which iterates only non-prototype keys on the object. You can swap this out yourself if you want the prototype keys included. See my original answer section below for both implementations with Object.keys and for in.

Worse - This will infinite loop on self-referential objects:

function* traverse(o, path=[]) {
    for (var i of Object.keys(o)) {
        const itemPath = path.concat(i);
        yield [i,o[i],itemPath, o]; 
        if (o[i] !== null && typeof(o[i])=="object") {
            //going one step down in the object tree!!
            yield* traverse(o[i], itemPath);
        }
    }
}

//your object
var o = { 
    foo:"bar",
    arr:[1,2,3],
    subo: {
        foo2:"bar2"
    }
};

// this self-referential property assignment is the only real logical difference 
// from the above original example which ends up making this naive traversal 
// non-terminating (i.e. it makes it infinite loop)
o.o = o;

//that's all... no magic, no bloated framework
for(var [key, value, path, parent] of traverse(o)) {
  // do something here with each key and value
  console.log(key, value, path, parent);
}

To save yourself from this you can add a set within a closure, so that when the function is first called it starts to build a memory of the objects it has seen and does not continue iteration once it comes across an already seen object. The below code snippet does that and thus handles infinite looping cases.

Better - This will not infinite loop on self-referential objects:

_x000D_
_x000D_
function* traverse(o) {
  const memory = new Set();
  function * innerTraversal (o, path=[]) {
    if(memory.has(o)) {
      // we've seen this object before don't iterate it
      return;
    }
    // add the new object to our memory.
    memory.add(o);
    for (var i of Object.keys(o)) {
      const itemPath = path.concat(i);
      yield [i,o[i],itemPath, o]; 
      if (o[i] !== null && typeof(o[i])=="object") {
        //going one step down in the object tree!!
        yield* innerTraversal(o[i], itemPath);
      }
    }
  }
  yield* innerTraversal(o);
}

//your object
var o = { 
  foo:"bar",
  arr:[1,2,3],
  subo: {
    foo2:"bar2"
  }
};

/// this self-referential property assignment is the only real logical difference 
// from the above original example which makes more naive traversals 
// non-terminating (i.e. it makes it infinite loop)
o.o = o;
    
console.log(o);
//that's all... no magic, no bloated framework
for(var [key, value, path, parent] of traverse(o)) {
  // do something here with each key and value
  console.log(key, value, path, parent);
}
_x000D_
_x000D_
_x000D_


EDIT: All above examples in this answer have been edited to include a new path variable yielded from the iterator as per @supersan's request. The path variable is an array of strings where each string in the array represents each key that was accessed to get to the resulting iterated value from the original source object. The path variable can be fed into lodash's get function/method. Or you could write your own version of lodash's get which handles only arrays like so:

_x000D_
_x000D_
function get (object, path) {
  return path.reduce((obj, pathItem) => obj ? obj[pathItem] : undefined, object);
}

const example = {a: [1,2,3], b: 4, c: { d: ["foo"] }};
// these paths exist on the object
console.log(get(example, ["a", "0"]));
console.log(get(example, ["c", "d", "0"]));
console.log(get(example, ["b"]));
// these paths do not exist on the object
console.log(get(example, ["e", "f", "g"]));
console.log(get(example, ["b", "f", "g"]));
_x000D_
_x000D_
_x000D_

You could also make a set function like so:

_x000D_
_x000D_
function set (object, path, value) {
    const obj = path.slice(0,-1).reduce((obj, pathItem) => obj ? obj[pathItem] : undefined, object)
    if(obj && obj[path[path.length - 1]]) {
        obj[path[path.length - 1]] = value;
    }
    return object;
}

const example = {a: [1,2,3], b: 4, c: { d: ["foo"] }};
// these paths exist on the object
console.log(set(example, ["a", "0"], 2));
console.log(set(example, ["c", "d", "0"], "qux"));
console.log(set(example, ["b"], 12));
// these paths do not exist on the object
console.log(set(example, ["e", "f", "g"], false));
console.log(set(example, ["b", "f", "g"], null));
_x000D_
_x000D_
_x000D_

EDIT Sep. 2020: I added a parent for quicker access of the previous object. This could allow you to more quickly build a reverse traverser. Also you could always modify the traversal algorithm to do breadth first search instead of depth first which is actually probably more predictable in fact here's a TypeScript version with Breadth First Search. Since this is a JavaScript question I'll put the JS version here:

_x000D_
_x000D_
var TraverseFilter;
(function (TraverseFilter) {
    /** prevents the children from being iterated. */
    TraverseFilter["reject"] = "reject";
})(TraverseFilter || (TraverseFilter = {}));
function* traverse(o) {
    const memory = new Set();
    function* innerTraversal(root) {
        const queue = [];
        queue.push([root, []]);
        while (queue.length > 0) {
            const [o, path] = queue.shift();
            if (memory.has(o)) {
                // we've seen this object before don't iterate it
                continue;
            }
            // add the new object to our memory.
            memory.add(o);
            for (var i of Object.keys(o)) {
                const item = o[i];
                const itemPath = path.concat([i]);
                const filter = yield [i, item, itemPath, o];
                if (filter === TraverseFilter.reject)
                    continue;
                if (item !== null && typeof item === "object") {
                    //going one step down in the object tree!!
                    queue.push([item, itemPath]);
                }
            }
        }
    }
    yield* innerTraversal(o);
}
//your object
var o = {
    foo: "bar",
    arr: [1, 2, 3],
    subo: {
        foo2: "bar2"
    }
};
/// this self-referential property assignment is the only real logical difference
// from the above original example which makes more naive traversals
// non-terminating (i.e. it makes it infinite loop)
o.o = o;
//that's all... no magic, no bloated framework
for (const [key, value, path, parent] of traverse(o)) {
    // do something here with each key and value
    console.log(key, value, path, parent);
}
_x000D_
_x000D_
_x000D_

What is a simple command line program or script to backup SQL server databases?

To backup a single database from the command line, use osql or sqlcmd.

"C:\Program Files\Microsoft SQL Server\90\Tools\Binn\osql.exe" 
    -E -Q "BACKUP DATABASE mydatabase TO DISK='C:\tmp\db.bak' WITH FORMAT"

You'll also want to read the documentation on BACKUP and RESTORE and general procedures.

Remove decimal values using SQL query

Simply update with a convert/cast to INT:

UPDATE YOUR_TABLE
SET YOUR_COLUMN = CAST(YOUR_COLUMN AS INT)
WHERE -- some condition is met if required

Or convert:

UPDATE YOUR_TABLE
SET YOUR_COLUMN = CONVERT(INT, YOUR_COLUMN)
WHERE -- some condition is met if required

To test you can do this:

SELECT YOUR_COLUMN AS CurrentValue,
       CAST(YOUR_COLUMN AS INT) AS NewValue
FROM YOUR_TABLE

Converting ISO 8601-compliant String to java.util.Date

java.time

The java.time API (built into Java 8 and later), makes this a little easier.

If you know the input is in UTC, such as the Z (for Zulu) on the end, the Instant class can parse.

java.util.Date date = Date.from( Instant.parse( "2014-12-12T10:39:40Z" ));

If your input may be another offset-from-UTC values rather than UTC indicated by the Z (Zulu) on the end, use the OffsetDateTime class to parse.

OffsetDateTime odt = OffsetDateTime.parse( "2010-01-01T12:00:00+01:00" );

Then extract an Instant, and convert to a java.util.Date by calling from.

Instant instant = odt.toInstant();  // Instant is always in UTC.
java.util.Date date = java.util.Date.from( instant );

How to call a javaScript Function in jsp on page load without using <body onload="disableView()">

Either use window.onload this way

<script>
    window.onload = function() {
        // ...
    }
</script>

or alternatively

<script>
    window.onload = functionName;
</script>

(yes, without the parentheses)


Or just put the script at the very bottom of page, right before </body>. At that point, all HTML DOM elements are ready to be accessed by document functions.

<body>
    ...

    <script>
        functionName();
    </script>
</body>

How to reference image resources in XAML?

One of the benefit of using the resource file is accessing the resources by names, so the image can change, the image name can change, as long as the resource is kept up to date correct image will show up.

Here is a cleaner approach to accomplish this: Assuming Resources.resx is in 'UI.Images' namespace, add the namespace reference in your xaml like this:

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:UI="clr-namespace:UI.Images" 

Set your Image source like this:

<Image Source={Binding {x:Static UI:Resources.Search}} /> where 'Search' is name of the resource.

Interesting 'takes exactly 1 argument (2 given)' Python error

The call

e.extractAll("th")

for a regular method extractAll() is indeed equivalent to

Extractor.extractAll(e, "th")

These two calls are treated the same in all regards, including the error messages you get.

If you don't need to pass the instance to a method, you can use a staticmethod:

@staticmethod
def extractAll(tag):
    ...

which can be called as e.extractAll("th"). But I wonder why this is a method on a class at all if you don't need to access any instance.

Number of elements in a javascript object

if you are already using jQuery in your build just do this:

$(yourObject).length

It works nicely for me on objects, and I already had jQuery as a dependancy.

How do I kill background processes / jobs when my shell script exits?

trap 'kill $(jobs -p)' EXIT

I would make only minor changes to Johannes' answer and use jobs -pr to limit the kill to running processes and add a few more signals to the list:

trap 'kill $(jobs -pr)' SIGINT SIGTERM EXIT

What resources are shared between threads?

Something that really needs to be pointed out is that there are really two aspects to this question - the theoretical aspect and the implementations aspect.

First, let's look at the theoretical aspect. You need to understand what a process is conceptually to understand the difference between a process and a thread and what's shared between them.

We have the following from section 2.2.2 The Classical Thread Model in Modern Operating Systems 3e by Tanenbaum:

The process model is based on two independent concepts: resource grouping and execution. Sometimes it is use­ful to separate them; this is where threads come in....

He continues:

One way of looking at a process is that it is a way to group related resources together. A process has an address space containing program text and data, as well as other resources. These resource may include open files, child processes, pending alarms, signal handlers, accounting information, and more. By putting them together in the form of a process, they can be managed more easily. The other concept a process has is a thread of execution, usually shortened to just thread. The thread has a program counter that keeps track of which instruc­tion to execute next. It has registers, which hold its current working variables. It has a stack, which contains the execution history, with one frame for each proce­dure called but not yet returned from. Although a thread must execute in some process, the thread and its process are different concepts and can be treated sepa­rately. Processes are used to group resources together; threads are the entities scheduled for execution on the CPU.

Further down he provides the following table:

Per process items             | Per thread items
------------------------------|-----------------
Address space                 | Program counter
Global variables              | Registers
Open files                    | Stack
Child processes               | State
Pending alarms                |
Signals and signal handlers   |
Accounting information        |

The above is what you need for threads to work. As others have pointed out, things like segments are OS dependant implementation details.

How to update core-js to core-js@3 dependency?

For ng9 upgraders:

npm i -g core-js@^3

..then:

npm cache clean -f

..followed by:

npm i

Default values for Vue component props & how to check if a user did not set the prop?

Vue allows for you to specify a default prop value and type directly, by making props an object (see: https://vuejs.org/guide/components.html#Prop-Validation):

props: {
  year: {
    default: 2016,
    type: Number
  }
}

If the wrong type is passed then it throws an error and logs it in the console, here's the fiddle:

https://jsfiddle.net/cexbqe2q/

Want to show/hide div based on dropdown box selection

The core problem is the js errors:

$('#purpose').on('change', function () {
    // if (this.value == '1'); { No semicolon and I used === instead of ==
    if (this.value === '1'){
        $("#business").show();
    } else {
        $("#business").hide();
    }
});
// }); remove

http://jsfiddle.net/Bushwazi/2kGzZ/3/

I had to clean up the html & js...I couldn't help myself.

HTML:

<select id='purpose'>
    <option value="0">Personal use</option>
    <option value="1">Business use</option>
    <option value="2">Passing on to a client</option>
</select>
<form id="business">
    <label for="business">Business Name</label>
    <input type='text' class='text' name='business' value size='20' />
</form>

CSS:

#business {
  display:none;
}

JS:

$('#purpose').on('change', function () {
    if(this.value === "1"){
        $("#business").show();
    } else {
        $("#business").hide();
    }
});

Remove duplicate elements from array in Ruby

Just another alternative if anyone cares.

You can also use the to_set method of an array which converts the Array into a Set and by definition, set elements are unique.

[1,2,3,4,5,5,5,6].to_set => [1,2,3,4,5,6]

How does EL empty operator work in JSF?

From EL 2.2 specification (get the one below "Click here to download the spec for evaluation"):

1.10 Empty Operator - empty A

The empty operator is a prefix operator that can be used to determine if a value is null or empty.

To evaluate empty A

  • If A is null, return true
  • Otherwise, if A is the empty string, then return true
  • Otherwise, if A is an empty array, then return true
  • Otherwise, if A is an empty Map, return true
  • Otherwise, if A is an empty Collection, return true
  • Otherwise return false

So, considering the interfaces, it works on Collection and Map only. In your case, I think Collection is the best option. Or, if it's a Javabean-like object, then Map. Either way, under the covers, the isEmpty() method is used for the actual check. On interface methods which you can't or don't want to implement, you could throw UnsupportedOperationException.

How to load a UIView using a nib file created with Interface Builder

You can also use UIViewController's initWithNibName instead of loadNibNamed. It is simpler, I find.

UIViewController *aViewController = [[UIViewController alloc] initWithNibName:@"MySubView" bundle:nil];
[self.subview addSubview:aViewController.view];
[aViewController release];  // release the VC

Now you just have to create MySubView.xib and MySubView.h/m. In MySubView.xib set the File's Owner class to UIViewController and view class to MySubView.

You can position and size of the subview using the parent xib file.

How do I discard unstaged changes in Git?

When you want to transfer a stash to someone else:

# add files
git add .  
# diff all the changes to a file
git diff --staged > ~/mijn-fix.diff
# remove local changes 
git reset && git checkout .
# (later you can re-apply the diff:)
git apply ~/mijn-fix.diff

[edit] as commented, it ís possible to name stashes. Well, use this if you want to share your stash ;)

How can I label points in this scatterplot?

For just plotting a vector, you should use the following command:

text(your.vector, labels=your.labels, cex= labels.size, pos=labels.position)

Java: Identifier expected

You can't call methods outside a method. Code like this cannot float around in the class.

You need something like:

public class MyClass {

  UserInput input = new UserInput();

  public void foo() {
      input.name();
  }
}

or inside a constructor:

public class MyClass {

  UserInput input = new UserInput();

  public MyClass() {
      input.name();
  }
}

What are NDF Files?

An NDF file is a user defined secondary database file of Microsoft SQL Server with an extension .ndf, which store user data. Moreover, when the size of the database file growing automatically from its specified size, you can use .ndf file for extra storage and the .ndf file could be stored on a separate disk drive. Every NDF file uses the same filename as its corresponding MDF file. We cannot open an .ndf file in SQL Server Without attaching its associated .mdf file.

Get the previous month's first and last day dates in c#

var today = DateTime.Today;
var month = new DateTime(today.Year, today.Month, 1);       
var first = month.AddMonths(-1);
var last = month.AddDays(-1);

In-line them if you really need one or two lines.

Python, Pandas : write content of DataFrame into text File

@AHegde - To get the tab delimited output use separator sep='\t'.

For df.to_csv:

df.to_csv(r'c:\data\pandas.txt', header=None, index=None, sep='\t', mode='a')

For np.savetxt:

np.savetxt(r'c:\data\np.txt', df.values, fmt='%d', delimiter='\t')

What's the best way to iterate an Android Cursor?

I'd just like to point out a third alternative which also works if the cursor is not at the start position:

if (cursor.moveToFirst()) {
    do {
        // do what you need with the cursor here
    } while (cursor.moveToNext());
}

How to find my php-fpm.sock?

Check the config file, the config path is /etc/php5/fpm/pool.d/www.conf, there you'll find the path by config and if you want you can change it.

EDIT:
well you're correct, you need to replace listen = 127.0.0.1:9000 to listen = /var/run/php5-fpm/php5-fpm.sock, then you need to run sudo service php5-fpm restart, and make sure it says that it restarted correctly, if not then make sure that /var/run/ has a folder called php5-fpm, or make it listen to /var/run/php5-fpm.sock cause i don't think the folder inside /var/run is created automatically, i remember i had to edit the start up script to create that folder, otherwise even if you mkdir /var/run/php5-fpm after restart that folder will disappear and the service starting will fail.

How to get name of calling function/method in PHP?

My favourite way, in one line!

debug_backtrace()[1]['function'];

You can use it like this:

echo 'The calling function: ' . debug_backtrace()[1]['function'];

Note that this is only compatible with versions of PHP released within the last year. But it's a good idea to keep your PHP up to date anyway for security reasons.

jQuery iframe load() event?

That's the same behavior I've seen: iframe's load() will fire first on an empty iframe, then the second time when your page is loaded.

Edit: Hmm, interesting. You could increment a counter in your event handler, and a) ignore the first load event, or b) ignore any duplicate load event.

How to return a part of an array in Ruby?

I like ranges for this:

def first_half(list)
  list[0...(list.length / 2)]
end

def last_half(list)
  list[(list.length / 2)..list.length]
end

However, be very careful about whether the endpoint is included in your range. This becomes critical on an odd-length list where you need to choose where you're going to break the middle. Otherwise you'll end up double-counting the middle element.

The above example will consistently put the middle element in the last half.

HTML/JavaScript: Simple form validation on submit

The simplest validation is as follows:

_x000D_
_x000D_
<form name="ff1" method="post">
  <input type="email" name="email" id="fremail" placeholder="[email protected]" />
  <input type="text" pattern="[a-z0-9. -]+" title="Please enter only alphanumeric characters." name="title" id="frtitle" placeholder="Title" />
  <input type="url" name="url" id="frurl" placeholder="http://yourwebsite.com/" />
  <input type="submit" name="Submit" value="Continue" />
</form>
_x000D_
_x000D_
_x000D_

It uses HTML5 attributes (like as pattern).

JavaScript: none.

Difference between a Structure and a Union

You have it, that's all. But so, basically, what's the point of unions?

You can put in the same location content of different types. You have to know the type of what you have stored in the union (so often you put it in a struct with a type tag...).

Why is this important? Not really for space gains. Yes, you can gain some bits or do some padding, but that's not the main point anymore.

It's for type safety, it enables you to do some kind of 'dynamic typing': the compiler knows that your content may have different meanings and the precise meaning of how your interpret it is up to you at run-time. If you have a pointer that can point to different types, you MUST use a union, otherwise you code may be incorrect due to aliasing problems (the compiler says to itself "oh, only this pointer can point to this type, so I can optimize out those accesses...", and bad things can happen).

How to discard local changes and pull latest from GitHub repository

git reset is what you want, but I'm going to add a couple extra things you might find useful that the other answers didn't mention.

git reset --hard HEAD resets your changes back to the last commit that your local repo has tracked. If you made a commit, did not push it to GitHub, and want to throw that away too, see @absiddiqueLive's answer.

git clean -df will discard any new files or directories that you may have added, in case you want to throw those away. If you haven't added any, you don't have to run this.

git pull (or if you are using git shell with the GitHub client) git sync will get the new changes from GitHub.

Edit from way in the future: I updated my git shell the other week and noticed that the git sync command is no longer defined by default. For the record, typing git sync was equivalent to git pull && git push in bash. I find it still helpful so it is in my bashrc.

Sqlite in chrome

You might be able to make use of sql.js.

sql.js is a port of SQLite to JavaScript, by compiling the SQLite C code with Emscripten. no C bindings or node-gyp compilation here.

<script src='js/sql.js'></script>
<script>
    //Create the database
    var db = new SQL.Database();
    // Run a query without reading the results
    db.run("CREATE TABLE test (col1, col2);");
    // Insert two rows: (1,111) and (2,222)
    db.run("INSERT INTO test VALUES (?,?), (?,?)", [1,111,2,222]);

    // Prepare a statement
    var stmt = db.prepare("SELECT * FROM test WHERE col1 BETWEEN $start AND $end");
    stmt.getAsObject({$start:1, $end:1}); // {col1:1, col2:111}

    // Bind new values
    stmt.bind({$start:1, $end:2});
    while(stmt.step()) { //
        var row = stmt.getAsObject();
        // [...] do something with the row of result
    }
</script>

sql.js is a single JavaScript file and is about 1.5MiB in size currently. While this could be a problem in a web-page, the size is probably acceptable for an extension.

fatal error LNK1104: cannot open file 'kernel32.lib'

For command line (i.e. - makefile) users only:

  1. When you install VC++ Express, it is 32-bit only. So, things go into C:\Program Files (x86).
  2. Then, you decide to upgrade to 64-bit capabillities. So, you install the SDK. But it is 64-bit capable. So, things go into C:\Program Files.

You (like me) probably "tuned" your makefile to #1, above, via something like this:

MS_SDK_BASE_DOS := C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A
ENV_SET         := LIB="$(MS_SDK_BASE_DOS)\Lib\x64"

But, now, you need to change that tuning to #2, above, like this:

MS_SDK_BASE_DOS := C:\Program Files\Microsoft SDKs\Windows\v7.1

(Don't miss the "v7.0A" to "v7.1" change, as well.)

Are there best practices for (Java) package organization?

I organize packages by feature, not by patterns or implementation roles. I think packages like:

  • beans
  • factories
  • collections

are wrong.

I prefer, for example:

  • orders
  • store
  • reports

so I can hide implementation details through package visibility. Factory of orders should be in the orders package so details about how to create an order are hidden.

Moving x-axis to the top of a plot in matplotlib

Use

ax.xaxis.tick_top()

to place the tick marks at the top of the image. The command

ax.set_xlabel('X LABEL')    
ax.xaxis.set_label_position('top') 

affects the label, not the tick marks.

import matplotlib.pyplot as plt
import numpy as np
column_labels = list('ABCD')
row_labels = list('WXYZ')
data = np.random.rand(4, 4)
fig, ax = plt.subplots()
heatmap = ax.pcolor(data, cmap=plt.cm.Blues)

# put the major ticks at the middle of each cell
ax.set_xticks(np.arange(data.shape[1]) + 0.5, minor=False)
ax.set_yticks(np.arange(data.shape[0]) + 0.5, minor=False)

# want a more natural, table-like display
ax.invert_yaxis()
ax.xaxis.tick_top()

ax.set_xticklabels(column_labels, minor=False)
ax.set_yticklabels(row_labels, minor=False)
plt.show()

enter image description here

How to open the default webbrowser using java

Hope you don't mind but I cobbled together all the helpful stuff, from above, and came up with a complete class ready for testing...

import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

public class MultiBrowPop {

    public static void main(String[] args) {
        OUT("\nWelcome to Multi Brow Pop.\nThis aims to popup a browsers in multiple operating systems.\nGood luck!\n");

        String url = "http://www.birdfolk.co.uk/cricmob";
        OUT("We're going to this page: "+ url);

        String myOS = System.getProperty("os.name").toLowerCase();
        OUT("(Your operating system is: "+ myOS +")\n");

        try {
            if(Desktop.isDesktopSupported()) { // Probably Windows
                OUT(" -- Going with Desktop.browse ...");
                Desktop desktop = Desktop.getDesktop();
                desktop.browse(new URI(url));
            } else { // Definitely Non-windows
                Runtime runtime = Runtime.getRuntime();
                if(myOS.contains("mac")) { // Apples
                    OUT(" -- Going on Apple with 'open'...");
                    runtime.exec("open " + url);
                } 
                else if(myOS.contains("nix") || myOS.contains("nux")) { // Linux flavours 
                    OUT(" -- Going on Linux with 'xdg-open'...");
                    runtime.exec("xdg-open " + url);
                }
                else 
                    OUT("I was unable/unwilling to launch a browser in your OS :( #SadFace");
            }
            OUT("\nThings have finished.\nI hope you're OK.");
        }
        catch(IOException | URISyntaxException eek) {
            OUT("**Stuff wrongly: "+ eek.getMessage());
        }
    }

    private static void OUT(String str) {
        System.out.println(str);
    }
}

How to give the background-image path in CSS?

There are two basic ways:

url(../../images/image.png)

or

url(/Web/images/image.png)

I prefer the latter, as it's easier to work with and works from all locations in the site (so useful for inline image paths too).

Mind you, I wouldn't do so much deep nesting of folders. It seems unnecessary and makes life a bit difficult, as you've found.

HTTP Get with 204 No Content: Is that normal

I use GET/204 with a RESTful collection that is a positional array of known fixed length but with holes.

GET /items
    200: ["a", "b", null]

GET /items/0
    200: "a"

GET /items/1
    200: "b"

GET /items/2
    204:

GET /items/3
    404: Not Found

Removing u in list

For python datasets you can use an index.

tmpColumnsSQL = ("show columns in dim.date_dim")
hiveCursor.execute(tmpColumnsSQL)
columnlist = hiveCursor.fetchall()

for columns in jayscolumnlist:
    print columns[0]

for i in range(len(jayscolumnlist)):    
    print columns[i][0])

Center icon in a div - horizontally and vertically

Horizontal centering is as easy as:

text-align: center

Vertical centering when the container is a known height:

height: 100px;
line-height: 100px;
vertical-align: middle

Vertical centering when the container isn't a known height AND you can set the image in the background:

background: url(someimage) no-repeat center center;

Is __init__.py not required for packages in Python 3.3+

Overview

@Mike's answer is correct but too imprecise. It is true that Python 3.3+ supports Implicit Namespace Packages that allows it to create a package without an __init__.py file. This is called a namespace package in contrast to a regular package which does have an __init__.py file (empty or not empty).

However, creating a namespace package should ONLY be done if there is a need for it. For most use cases and developers out there, this doesn't apply so you should stick with EMPTY __init__.py files regardless.

Namespace package use case

To demonstrate the difference between the two types of python packages, lets look at the following example:

google_pubsub/              <- Package 1
    google/                 <- Namespace package (there is no __init__.py)
        cloud/              <- Namespace package (there is no __init__.py)
            pubsub/         <- Regular package (with __init__.py)
                __init__.py <- Required to make the package a regular package
                foo.py

google_storage/             <- Package 2
    google/                 <- Namespace package (there is no __init__.py)
        cloud/              <- Namespace package (there is no __init__.py)
            storage/        <- Regular package (with __init__.py)
                __init__.py <- Required to make the package a regular package
                bar.py

google_pubsub and google_storage are separate packages but they share the same namespace google/cloud. In order to share the same namespace, it is required to make each directory of the common path a namespace package, i.e. google/ and cloud/. This should be the only use case for creating namespace packages, otherwise, there is no need for it.

It's crucial that there are no __init__py files in the google and google/cloud directories so that both directories can be interpreted as namespace packages. In Python 3.3+ any directory on the sys.path with a name that matches the package name being looked for will be recognized as contributing modules and subpackages to that package. As a result, when you import both from google_pubsub and google_storage, the Python interpreter will be able to find them.

This is different from regular packages which are self-contained meaning all parts live in the same directory hierarchy. When importing a package and the Python interpreter encounters a subdirectory on the sys.path with an __init__.py file, then it will create a single directory package containing only modules from that directory, rather than finding all appropriately named subdirectories outside that directory. This is perfectly fine for packages that don't want to share a namespace. I highly recommend taking a look at Traps for the Unwary in Python’s Import System to get a better understanding of how Python importing behaves with regular and namespace package and what __init__.py traps to watch out for.

Summary

  • Only skip __init__.py files if you want to create namespace packages. Only create namespace packages if you have different libraries that reside in different locations and you want them each to contribute a subpackage to the parent package, i.e. the namespace package.
  • Keep on adding empty __init__py to your directories because 99% of the time you just want to create regular packages. Also, Python tools out there such as mypy and pytest require empty __init__.py files to interpret the code structure accordingly. This can lead to weird errors if not done with care.

Resources

My answer only touches the surface of how regular packages and namespace packages work so take a look at the following resources for further information:

SQL Server SELECT INTO @variable?

"SELECT *
  INTO 
    @TempCustomer 
FROM 
    Customer
WHERE 
    CustomerId = @CustomerId"

Which means creating a new @tempCustomer tablevariable and inserting data FROM Customer. You had already declared it above so no need of again declaring. Better to go with

INSERT INTO @tempCustomer SELECT * FROM Customer

How can I discover the "path" of an embedded resource?

This will get you a string array of all the resources:

System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceNames();

Pandas: ValueError: cannot convert float NaN to integer

ValueError: cannot convert float NaN to integer

From v0.24, you actually can. Pandas introduces Nullable Integer Data Types which allows integers to coexist with NaNs.

Given a series of whole float numbers with missing data,

s = pd.Series([1.0, 2.0, np.nan, 4.0])
s

0    1.0
1    2.0
2    NaN
3    4.0
dtype: float64

s.dtype
# dtype('float64')

You can convert it to a nullable int type (choose from one of Int16, Int32, or Int64) with,

s2 = s.astype('Int32') # note the 'I' is uppercase
s2

0      1
1      2
2    NaN
3      4
dtype: Int32

s2.dtype
# Int32Dtype()

Your column needs to have whole numbers for the cast to happen. Anything else will raise a TypeError:

s = pd.Series([1.1, 2.0, np.nan, 4.0])

s.astype('Int32')
# TypeError: cannot safely cast non-equivalent float64 to int32

Download/Stream file from URL - asp.net

Download url to bytes and convert bytes into stream:

using (var client = new WebClient())
{
    var content = client.DownloadData(url);
    using (var stream = new MemoryStream(content))
    {
        ...
    }
}   

Bash ignoring error for a particular command

If you want to prevent your script failing and collect the return code:

command () {
    return 1  # or 0 for success
}

set -e

command && returncode=$? || returncode=$?
echo $returncode

returncode is collected no matter whether command succeeds or fails.

How do I clone a specific Git branch?

git --branch <branchname> <url>

But bash completion don't get this key: --branch

How to pass ArrayList<CustomeObject> from one activity to another?

You can pass an ArrayList<E> the same way, if the E type is Serializable.

You would call the putExtra (String name, Serializable value) of Intent to store, and getSerializableExtra (String name) for retrieval.

Example:

ArrayList<String> myList = new ArrayList<String>();
intent.putExtra("mylist", myList);

In the other Activity:

ArrayList<String> myList = (ArrayList<String>) getIntent().getSerializableExtra("mylist");

How to use sbt from behind proxy?

Add both http and https configuration:

export JAVA_OPTS="$JAVA_OPTS -Dhttp.proxyHost=yourserver -Dhttp.proxyPort=8080 -Dhttp.proxyUser=username -Dhttp.proxyPassword=password"

export JAVA_OPTS="$JAVA_OPTS -Dhttps.proxyHost=yourserver -Dhttps.proxyPort=8080 -Dhttps.proxyUser=username -Dhttps.proxyPassword=password"

(https config is must, since many urls referred by the sbt libraries are https)

In fact, I even had an extra setting 'http.proxySet' to 'true' in both configuration entries.

jquery function val() is not equivalent to "$(this).value="?

Note that :

typeof $(this) is JQuery object.

and

typeof $(this)[0] is HTMLElement object

then : if you want to apply .val() on HTMLElement , you can add this extension .

HTMLElement.prototype.val=function(v){
   if(typeof v!=='undefined'){this.value=v;return this;}
   else{return this.value}
}

Then :

document.getElementById('myDiv').val() ==== $('#myDiv').val()

And

 document.getElementById('myDiv').val('newVal') ==== $('#myDiv').val('newVal')

????? INVERSE :

Conversely? if you want to add value property to jQuery object , follow those steps :

  1. Download the full source code (not minified) i.e: example http://code.jquery.com/jquery-1.11.1.js .

  2. Insert Line after L96 , add this code value:"" to init this new prop enter image description here

  3. Search on jQuery.fn.init , it will be almost Line 2747

enter image description here

  1. Now , assign a value to value prop : (Before return statment add this.value=jQuery(selector).val()) enter image description here

Enjoy now : $('#myDiv').value

How to generate a random String in Java

This is very nice:

http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/RandomStringUtils.html - something like RandomStringUtils.randomNumeric(7).

There are 10^7 equiprobable (if java.util.Random is not broken) distinct values so uniqueness may be a concern.

How do I uninstall a Windows service if the files do not exist anymore?

You can try running Autoruns, which would save you from having to edit the registry by hand. This is especially useful when you don't have the needed permissions.

How to run an application as "run as administrator" from the command prompt?

Try this:

runas.exe /savecred /user:administrator "%sysdrive%\testScripts\testscript1.ps1" 

It saves the password the first time and never asks again. Maybe when you change the administrator password you will be prompted again.

What is the symbol for whitespace in C?

#include <stdio.h>
main()
{
int c,sp,tb,nl;
sp = 0;
tb = 0;
nl = 0;
while((c = getchar()) != EOF)
{
   switch( c )
{
   case ' ':
        ++sp;
     printf("space:%d\n", sp);
     break;
   case  '\t':
        ++tb;
     printf("tab:%d\n", tb);
     break;
   case '\n':
        ++nl;
     printf("new line:%d\n", nl);
     break;
  }
 }
}

How to print a int64_t type in C

With C99 the %j length modifier can also be used with the printf family of functions to print values of type int64_t and uint64_t:

#include <stdio.h>
#include <stdint.h>

int main(int argc, char *argv[])
{
    int64_t  a = 1LL << 63;
    uint64_t b = 1ULL << 63;

    printf("a=%jd (0x%jx)\n", a, a);
    printf("b=%ju (0x%jx)\n", b, b);

    return 0;
}

Compiling this code with gcc -Wall -pedantic -std=c99 produces no warnings, and the program prints the expected output:

a=-9223372036854775808 (0x8000000000000000)
b=9223372036854775808 (0x8000000000000000)

This is according to printf(3) on my Linux system (the man page specifically says that j is used to indicate a conversion to an intmax_t or uintmax_t; in my stdint.h, both int64_t and intmax_t are typedef'd in exactly the same way, and similarly for uint64_t). I'm not sure if this is perfectly portable to other systems.

How to read a text file directly from Internet using Java?

I did that in the following way for an image, you should be able to do it for text using similar steps.

// folder & name of image on PC          
File fileObj = new File("C:\\Displayable\\imgcopy.jpg"); 

Boolean testB = fileObj.createNewFile();

System.out.println("Test this file eeeeeeeeeeeeeeeeeeee "+testB);

// image on server
URL url = new URL("http://localhost:8181/POPTEST2/imgone.jpg"); 
InputStream webIS = url.openStream();

FileOutputStream fo = new FileOutputStream(fileObj);
int c = 0;
do {
    c = webIS.read();
    System.out.println("==============> " + c);
    if (c !=-1) {
        fo.write((byte) c);
    }
} while(c != -1);

webIS.close();
fo.close();

Can attributes be added dynamically in C#?

No, it's not.

Attributes are meta-data and stored in binary-form in the compiled assembly (that's also why you can only use simple types in them).

VBA copy rows that meet criteria to another sheet

You need to specify workseet. Change line

If Worksheet.Cells(i, 1).Value = "X" Then

to

If Worksheets("Sheet2").Cells(i, 1).Value = "X" Then

UPD:

Try to use following code (but it's not the best approach. As @SiddharthRout suggested, consider about using Autofilter):

Sub LastRowInOneColumn()
   Dim LastRow As Long
   Dim i As Long, j As Long

   'Find the last used row in a Column: column A in this example
   With Worksheets("Sheet2")
      LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
   End With

   MsgBox (LastRow)
   'first row number where you need to paste values in Sheet1'
   With Worksheets("Sheet1")
      j = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
   End With 

   For i = 1 To LastRow
       With Worksheets("Sheet2")
           If .Cells(i, 1).Value = "X" Then
               .Rows(i).Copy Destination:=Worksheets("Sheet1").Range("A" & j)
               j = j + 1
           End If
       End With
   Next i
End Sub

Optimal way to DELETE specified rows from Oracle

First, disabling the index during the deletion would be helpful.

Try with a MERGE INTO statement :
1) create a temp table with IDs and an additional column from TABLE1 and test with the following

MERGE INTO table1 src
USING (SELECT id,col1
         FROM test_merge_delete) tgt
ON (src.id = tgt.id)
WHEN MATCHED THEN
  UPDATE
     SET src.col1 = tgt.col1
  DELETE
   WHERE src.id = tgt.id

how to use sqltransaction in c#

Update or Delete with sql transaction

 private void SQLTransaction() {
   try {
     string sConnectionString = "My Connection String";
     string query = "UPDATE [dbo].[MyTable] SET ColumnName = '{0}' WHERE ID = {1}";

     SqlConnection connection = new SqlConnection(sConnectionString);
     SqlCommand command = connection.CreateCommand();
     connection.Open();
     SqlTransaction transaction = connection.BeginTransaction("");
     command.Transaction = transaction;
     try {
       foreach(DataRow row in dt_MyData.Rows) {
         command.CommandText = string.Format(query, row["ColumnName"].ToString(), row["ID"].ToString());
         command.ExecuteNonQuery();
       }
       transaction.Commit();
     } catch (Exception ex) {
       transaction.Rollback();
       MessageBox.Show(ex.Message, "Error");
     }
   } catch (Exception ex) {
     MessageBox.Show("Problem connect to database.", "Error");
   }
 }

Easiest way to toggle 2 classes in jQuery

If your element exposes class A from the start, you can write:

$(element).toggleClass("A B");

This will remove class A and add class B. If you do that again, it will remove class B and reinstate class A.

If you want to match the elements that expose either class, you can use a multiple class selector and write:

$(".A, .B").toggleClass("A B");

Simple JavaScript Checkbox Validation

You could use:

 if(!this.form.checkbox.checked)
{
    alert('You must agree to the terms first.');
    return false;
}

(demo page).

<input type="checkbox" name="checkbox" value="check"  />
<input type="submit" name="email_submit" value="submit" onclick="if(!this.form.checkbox.checked){alert('You must agree to the terms first.');return false}"  />
  • Returning false from an inline event handler will prevent the default action from taking place (in this case, submitting the form).
  • ! is the Boolean NOT operator.
  • this is the submit button because it is the element the event handler is attached to.
  • .form is the form the submit button is in.
  • .checkbox is the control named "checkbox" in that form.
  • .checked is true if the checkbox is checked and false if the checkbox is unchecked.

jquery validate check at least one checkbox

make sure the input-name[] is in inverted commas in the ruleset. Took me hours to figure that part out.

$('#testform').validate({
  rules : {
    "name[]": { required: true, minlength: 1 }
  }
});

read more here... http://docs.jquery.com/Plugins/Valid...ets.2C_dots.29

PHP Accessing Parent Class Variable

all the properties and methods of the parent class is inherited in the child class so theoretically you can access them in the child class but beware using the protected keyword in your class because it throws a fatal error when used in the child class.
as mentioned in php.net

The visibility of a property or method can be defined by prefixing the declaration with the keywords public, protected or private. Class members declared public can be accessed everywhere. Members declared protected can be accessed only within the class itself and by inherited and parent classes. Members declared as private may only be accessed by the class that defines the member.

To show error message without alert box in Java Script

You should place your script code after your HTML code and within your body tags. That way it doesn't run before the html code.

CSS Selector "(A or B) and C"?

is there a better syntax?

No. CSS' or operator (,) does not permit groupings. It's essentially the lowest-precedence logical operator in selectors, so you must use .a.c,.b.c.

putting a php variable in a HTML form value

You can do it like this,

<input type="text" name="name" value="<?php echo $name;?>" />

But seen as you've taken it straight from user input, you want to sanitize it first so that nothing nasty is put into the output of your page.

<input type="text" name="name" value="<?php echo htmlspecialchars($name);?>" />

Use sed to replace all backslashes with forward slashes

I had to use [\\] or [/] to be able to make this work, FYI.

awk '!/[\\]/' file > temp && mv temp file

and

awk '!/[/]/' file > temp && mv temp file

I was using awk to remove backlashes and forward slashes from a list.

Create table with jQuery - append

It is important to note that you could use Emmet to achieve the same result. First, check what Emmet can do for you at https://emmet.io/

In a nutshell, with Emmet, you can expand a string into a complexe HTML markup as shown in the examples below:

Example #1

ul>li*5

... will produce

<ul>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
</ul>

Example #2

div#header+div.page+div#footer.class1.class2.class3

... will produce

<div id="header"></div>
<div class="page"></div>
<div id="footer" class="class1 class2 class3"></div>

And list goes on. There are more examples at https://docs.emmet.io/abbreviations/syntax/

And there is a library for doing that using jQuery. It's called Emmet.js and available at https://github.com/christiansandor/Emmet.js

How to create a new text file using Python

# Method 1
f = open("Path/To/Your/File.txt", "w")   # 'r' for reading and 'w' for writing
f.write("Hello World from " + f.name)    # Write inside file 
f.close()                                # Close file 

# Method 2
with open("Path/To/Your/File.txt", "w") as f:   # Opens file and casts as f 
    f.write("Hello World form " + f.name)       # Writing
    # File closed automatically

There are many more methods but these two are most common. Hope this helped!

CodeIgniter - accessing $config variable in view

You can do something like that:

$ci = get_instance(); // CI_Loader instance
$ci->load->config('email');
echo $ci->config->item('name');

PostgreSQL : cast string to date DD/MM/YYYY

A DATE column does not have a format. You cannot specify a format for it.

You can use DateStyle to control how PostgreSQL emits dates, but it's global and a bit limited.

Instead, you should use to_char to format the date when you query it, or format it in the client application. Like:

SELECT to_char("date", 'DD/MM/YYYY') FROM mytable;

e.g.

regress=> SELECT to_char(DATE '2014-04-01', 'DD/MM/YYYY');
  to_char   
------------
 01/04/2014
(1 row)

How to determine if object is in array

i know this is an old post, but i wanted to provide a JQuery plugin version and my code.

// Find the first occurrence of object in list, Similar to $.grep, but stops searching 
function findFirst(a,b){
var i; for (i = 0; i < a.length; ++i) { if (b(a[i], i)) return a[i]; } return undefined;
}

usage:

var product = $.findFirst(arrProducts, function(p) { return p.id == 10 });

Input text dialog Android

Sounds like a good opportunity to use an AlertDialog.

As basic as it seems, Android does not have a built-in dialog to do this (as far as I know). Fortunately, it's just a little extra work on top of creating a standard AlertDialog. You simply need to create an EditText for the user to input data, and set it as the view of the AlertDialog. You can customize the type of input allowed using setInputType, if you need.

If you're able to use a member variable, you can simply set the variable to the value of the EditText, and it will persist after the dialog has dismissed. If you can't use a member variable, you may need to use a listener to send the string value to the right place. (I can edit and elaborate more if this is what you need).

Within your class:

private String m_Text = "";

Within the OnClickListener of your button (or in a function called from there):

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Title");

// Set up the input
final EditText input = new EditText(this);
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
builder.setView(input);

// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { 
    @Override
    public void onClick(DialogInterface dialog, int which) {
        m_Text = input.getText().toString();
    }
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        dialog.cancel();
    }
});

builder.show();

The best way to remove duplicate values from NSMutableArray in Objective-C?

One more simple way you can try out which will not add duplicate Value before adding object in array:-

//Assume mutableArray is allocated and initialize and contains some value

if (![yourMutableArray containsObject:someValue])
{
   [yourMutableArray addObject:someValue];
}

What's the difference between tilde(~) and caret(^) in package.json?

See the NPM docs and semver docs:

  • ~version “Approximately equivalent to version”, will update you to all future patch versions, without incrementing the minor version. ~1.2.3 will use releases from 1.2.3 to <1.3.0.

  • ^version “Compatible with version”, will update you to all future minor/patch versions, without incrementing the major version. ^2.3.4 will use releases from 2.3.4 to <3.0.0.

See Comments below for exceptions, in particular for pre-one versions, such as ^0.2.3

How do I fix maven error The JAVA_HOME environment variable is not defined correctly?

In case of windows if there is any space in path to jdk like ("C:\Program Files\jdk") then it doesn't work, but if we keep jdk in a location which doesn't have space then it works fine like ("C:\jdk")

What's the point of the X-Requested-With header?

Make sure you read SilverlightFox's answer. It highlights a more important reason.

The reason is mostly that if you know the source of a request you may want to customize it a little bit.

For instance lets say you have a website which has many recipes. And you use a custom jQuery framework to slide recipes into a container based on a link they click. The link may be www.example.com/recipe/apple_pie

Now normally that returns a full page, header, footer, recipe content and ads. But if someone is browsing your website some of those parts are already loaded. So you can use an AJAX to get the recipe the user has selected but to save time and bandwidth don't load the header/footer/ads.

Now you can just write a secondary endpoint for the data like www.example.com/recipe_only/apple_pie but that's harder to maintain and share to other people.

But it's easier to just detect that it is an ajax request making the request and then returning only a part of the data. That way the user wastes less bandwidth and the site appears more responsive.

The frameworks just add the header because some may find it useful to keep track of which requests are ajax and which are not. But it's entirely dependent on the developer to use such techniques.

It's actually kind of similar to the Accept-Language header. A browser can request a website please show me a Russian version of this website without having to insert /ru/ or similar in the URL.

What is lexical scope?

Lexical scoping: Variables declared outside of a function are global variables and are visible everywhere in a JavaScript program. Variables declared inside a function have function scope and are visible only to code that appears inside that function.

How do you say not equal to in Ruby?

Yes. In Ruby the not equal to operator is:

!=

You can get a full list of ruby operators here: https://www.tutorialspoint.com/ruby/ruby_operators.htm.

how to change a selections options based on another select option selected?

Here is an example of what you are trying to do => fiddle

_x000D_
_x000D_
$(document).ready(function () {_x000D_
    $("#type").change(function () {_x000D_
        var val = $(this).val();_x000D_
        if (val == "item1") {_x000D_
            $("#size").html("<option value='test'>item1: test 1</option><option value='test2'>item1: test 2</option>");_x000D_
        } else if (val == "item2") {_x000D_
            $("#size").html("<option value='test'>item2: test 1</option><option value='test2'>item2: test 2</option>");_x000D_
        } else if (val == "item3") {_x000D_
            $("#size").html("<option value='test'>item3: test 1</option><option value='test2'>item3: test 2</option>");_x000D_
        } else if (val == "item0") {_x000D_
            $("#size").html("<option value=''>--select one--</option>");_x000D_
        }_x000D_
    });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<select id="type">_x000D_
    <option value="item0">--Select an Item--</option>_x000D_
    <option value="item1">item1</option>_x000D_
    <option value="item2">item2</option>_x000D_
    <option value="item3">item3</option>_x000D_
</select>_x000D_
_x000D_
<select id="size">_x000D_
    <option value="">-- select one -- </option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

TypeError: 'str' object cannot be interpreted as an integer

You have to convert input x and y into int like below.

x=int(x)
y=int(y)

Simplest way to have a configuration file in a Windows Forms C# application

In Windows Forms, you have the app.config file, which is very similar to the web.config file. But since what I see you need it for are custom values, I suggest using Settings.

To do that, open your project properties, and then go to settings. If a settings file does not exist you will have a link to create one. Then, you can add the settings to the table you see there, which would generate both the appropriate XML, and a Settings class that can be used to load and save the settings.

The settings class will be named something like DefaultNamespace.Properties.Settings. Then, you can use code similar to:

using DefaultNamespace.Properties;

namespace DefaultNamespace {
    class Class {
        public int LoadMySettingValue() {
            return Settings.Default.MySettingValue;
        }
        public void SaveMySettingValue(int value) {
            Settings.Default.MySettingValue = value;
        }
    }
}

Inline IF Statement in C#

You can do inline ifs with

return y == 20 ? 1 : 2;

which will give you 1 if true and 2 if false.

How to add border radius on table row

Or use box-shadow if table have collapse

Why do we check up to the square root of a prime number to determine if it is prime?

Let n be non-prime. Therefore, it has at least two integer factors greater than 1. Let f be the smallest of n's such factors. Suppose f > sqrt n. Then n/f is an integer LTE sqrt n, thus smaller than f. Therefore, f cannot be n's smallest factor. Reductio ad absurdum; n's smallest factor must be LTE sqrt n.

How to create a cron job using Bash automatically without the interactive editor?

You may be able to do it on-the-fly

crontab -l | { cat; echo "0 0 0 0 0 some entry"; } | crontab -

crontab -l lists the current crontab jobs, cat prints it, echo prints the new command and crontab - adds all the printed stuff into the crontab file. You can see the effect by doing a new crontab -l.

Syntax error: Illegal return statement in JavaScript

where are you trying to return the value? to console in dev tools is better for debugging

<script type = 'text/javascript'>
var ask = confirm('".$message."');
function answer(){
  if(ask==false){
    return false;     
  } else {
    return true;
  }
}
console.log("ask : ", ask);
console.log("answer : ", answer());
</script>

C# using streams

A stream is an object used to transfer data. There is a generic stream class System.IO.Stream, from which all other stream classes in .NET are derived. The Stream class deals with bytes.

The concrete stream classes are used to deal with other types of data than bytes. For example:

  • The FileStream class is used when the outside source is a file
  • MemoryStream is used to store data in memory
  • System.Net.Sockets.NetworkStream handles network data

Reader/writer streams such as StreamReader and StreamWriter are not streams - they are not derived from System.IO.Stream, they are designed to help to write and read data from and to stream!

Computed / calculated / virtual / derived columns in PostgreSQL

A lightweight solution with Check constraint:

CREATE TABLE example (
    discriminator INTEGER DEFAULT 0 NOT NULL CHECK (discriminator = 0)
);

How to set HttpResponse timeout for Android in Java

In my example, two timeouts are set. The connection timeout throws java.net.SocketTimeoutException: Socket is not connected and the socket timeout java.net.SocketTimeoutException: The operation timed out.

HttpGet httpGet = new HttpGet(url);
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used. 
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT) 
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpResponse response = httpClient.execute(httpGet);

If you want to set the Parameters of any existing HTTPClient (e.g. DefaultHttpClient or AndroidHttpClient) you can use the function setParams().

httpClient.setParams(httpParameters);

Reading Datetime value From Excel sheet

i had a similar situation and i used the below code for getting this worked..

Aspose.Cells.LoadOptions loadOptions = new Aspose.Cells.LoadOptions(Aspose.Cells.LoadFormat.CSV);

Workbook workbook = new Workbook(fstream, loadOptions);

Worksheet worksheet = workbook.Worksheets[0];

dt = worksheet.Cells.ExportDataTable(0, 0, worksheet.Cells.MaxDisplayRange.RowCount, worksheet.Cells.MaxDisplayRange.ColumnCount, true);

DataTable dtCloned = dt.Clone();
ArrayList myAL = new ArrayList();

foreach (DataColumn column in dtCloned.Columns)
{
    if (column.DataType == Type.GetType("System.DateTime"))
    {
        column.DataType = typeof(String);
        myAL.Add(column.ColumnName);
    }
}


foreach (DataRow row in dt.Rows)
{
    dtCloned.ImportRow(row);
}



foreach (string colName in myAL)
{
    dtCloned.Columns[colName].Convert(val => DateTime.Parse(Convert.ToString(val)).ToString("MMMM dd, yyyy"));
}


/*******************************/

public static class MyExtension
{
    public static void Convert<T>(this DataColumn column, Func<object, T> conversion)
    {
        foreach (DataRow row in column.Table.Rows)
        {
            row[column] = conversion(row[column]);
        }
    }
}

Hope this helps some1 thx_joxin

Add vertical scroll bar to panel

AutoScroll is really the solution! You just have to set AutoScrollMargin to 0, 1000 or something like this, then use it to scroll down and add buttons and items there!

Get average color of image via Javascript

"Dominant Color" is tricky. What you want to do is compare the distance between each pixel and every other pixel in color space (Euclidean Distance), and then find the pixel whose color is closest to every other color. That pixel is the dominant color. The average color will usually be mud.

I wish I had MathML in here to show you Euclidean Distance. Google it.

I have accomplished the above execution in RGB color space using PHP/GD here: https://gist.github.com/cf23f8bddb307ad4abd8

This however is very computationally expensive. It will crash your system on large images, and will definitely crash your browser if you try it in the client. I have been working on refactoring my execution to: - store results in a lookup table for future use in the iteration over each pixel. - to divide large images into grids of 20px 20px for localized dominance. - to use the euclidean distance between x1y1 and x1y2 to figure out the distance between x1y1 and x1y3.

Please let me know if you make progress on this front. I would be happy to see it. I will do the same.

Canvas is definitely the best way to do this in the client. SVG is not, SVG is vector based. After I get the execution down, the next thing I want to do is get this running in the canvas (maybe with a webworker for each pixel's overall distance calculation).

Another thing to think about is that RGB is not a good color space for doing this in, because the euclidean distance between colors in RGB space is not very close to the visual distance. A better color space for doing this might be LUV, but I have not found a good library for this, or any algorythims for converting RGB to LUV.

An entirely different approach would be to sort your colors in a rainbow, and build a histogram with tolerance to account for varying shades of a color. I have not tried this, because sorting colors in a rainbow is hard, and so are color histograms. I might try this next. Again, let me know if you make any progress here.

Get a UTC timestamp

new Date().getTime();

For more information, see @James McMahon's answer.

Spring 3.0: Unable to locate Spring NamespaceHandler for XML schema namespace

Did you try putting all your jars directly in the WEB-INF/lib dir instead of sub-dirs of that?

No WEB-INF/lib/spring/org.springframework.aop-3.0.0.RELEASE.jar, just WEB-INF/lib/org.springframework.aop-3.0.0.RELEASE.jar

Same with the rest of the jars.

Pandas Merging 101

In this answer, I will consider practical examples.

The first one, is of pandas.concat.

The second one, of merging dataframes from the index of one and the column of another one.


1. pandas.concat

Considering the following DataFrames with the same column names:

Preco2018 with size (8784, 5)

DataFrame 1

Preco 2019 with size (8760, 5)

DataFrame 2

That have the same column names.

You can combine them using pandas.concat, by simply

import pandas as pd

frames = [Preco2018, Preco2019]

df_merged = pd.concat(frames)

Which results in a DataFrame with the following size (17544, 5)

DataFrame result of the combination of two dataframes

If you want to visualize, it ends up working like this

How concat works

(Source)


2. Merge by Column and Index

In this part, I will consider a specific case: If one wants to merge the index of one dataframe and the column of another dataframe.

Let's say one has the dataframe Geo with 54 columns, being one of the columns the Date Data, which is of type datetime64[ns].

enter image description here

And the dataframe Price that has one column with the price and the index corresponds to the dates

enter image description here

In this specific case, to merge them, one uses pd.merge

merged = pd.merge(Price, Geo, left_index=True, right_on='Data')

Which results in the following dataframe

enter image description here

Style the first <td> column of a table differently

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

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

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

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

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

How to not wrap contents of a div?

Forcing the buttons stay in the same line will make them go beyond the fixed width of the div they are in. If you are okay with that then you can make another div inside the div you already have. The new div in turn will hold the buttons and have the fixed width of however much space the two buttons need to stay in one line.

Here is an example:

<div id="parentDiv" style="width: [less-than-what-buttons-need]px;">
    <div id="holdsButtons" style="width: [>=-than-buttons-need]px;">
       <button id="button1">1</button>
       <button id="button2">2</button>
    </div>
</div>

You may want to consider overflow property for the chunk of the content outside of the parentDiv border.

Good luck!

Xcode variables

The best source is probably Apple's official documentation. The specific variable you are looking for is CONFIGURATION.

MySQL wait_timeout Variable - GLOBAL vs SESSION

Your session status are set once you start a session, and by default, take the current GLOBAL value.

If you disconnected after you did SET @@GLOBAL.wait_timeout=300, then subsequently reconnected, you'd see

SHOW SESSION VARIABLES LIKE "%wait%";

Result: 300

Similarly, at any time, if you did

mysql> SET session wait_timeout=300;

You'd get

mysql> SHOW SESSION VARIABLES LIKE 'wait_timeout';

+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| wait_timeout  | 300   |
+---------------+-------+

Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

You need to use bitwise operators | instead of or and & instead of and in pandas, you can't simply use the bool statements from python.

For much complex filtering create a mask and apply the mask on the dataframe.
Put all your query in the mask and apply it.
Suppose,

mask = (df["col1"]>=df["col2"]) & (stock["col1"]<=df["col2"])
df_new = df[mask]

How to use the TextWatcher class in Android?

Supplemental answer

Here is a visual supplement to the other answers. My fuller answer with the code and explanations is here.

  • Red: text about to be deleted (replaced)
  • Green: text that was just added (replacing the old red text)

enter image description here

Input type DateTime - Value format?

For <input type="datetime" value="" ...

A string representing a global date and time.

Value: A valid date-time as defined in [RFC 3339], with these additional qualifications:

•the literal letters T and Z in the date/time syntax must always be uppercase

•the date-fullyear production is instead defined as four or more digits representing a number greater than 0

Examples:

1990-12-31T23:59:60Z

1996-12-19T16:39:57-08:00

http://www.w3.org/TR/html-markup/input.datetime.html#input.datetime.attrs.value

Update:

This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it.

The HTML was a control for entering a date and time (hour, minute, second, and fraction of a second) as well as a timezone. This feature has been removed from WHATWG HTML, and is no longer supported in browsers.

Instead, browsers are implementing (and developers are encouraged to use) the datetime-local input type.

Why is HTML5 input type datetime removed from browsers already supporting it?

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/datetime

How to debug JavaScript / jQuery event bindings with Firebug or similar tools?

There's a nice bookmarklet called Visual Event that can show you all the events attached to an element. It has color-coded highlights for different types of events (mouse, keyboard, etc.). When you hover over them, it shows the body of the event handler, how it was attached, and the file/line number (on WebKit and Opera). You can also trigger the event manually.

It can't find every event because there's no standard way to look up what event handlers are attached to an element, but it works with popular libraries like jQuery, Prototype, MooTools, YUI, etc.

Need to perform Wildcard (*,?, etc) search on a string using Regex

You must escape special Regex symbols in input wildcard pattern (for example pattern *.txt will equivalent to ^.*\.txt$) So slashes, braces and many special symbols must be replaced with @"\" + s, where s - special Regex symbol.

Difference between checkout and export in SVN

Use export if you want to upload (or give to somebody) a project. If you are working with a project, use checkout.

groovy: safely find a key in a map and return its value

The reason you get a Null Pointer Exception is because there is no key likesZZZ in your second example. Try:

def mymap = [name:"Gromit", likes:"cheese", id:1234]
def x = mymap.find{ it.key == "likes" }.value
if(x)
    println "x value: ${x}"

laravel 5 : Class 'input' not found

In larvel => 6 Version:

Input no longer exists In larvel 6,7,8 Version. Use Request instead of Input.

Based on the Laravel docs, since version 6.x Input has been removed.

The Input Facade

Likelihood Of Impact: Medium

The Input facade, which was primarily a duplicate of the Request facade, has been removed. If you are using the Input::get method, you should now call the Request::input method. All other calls to the Input facade may simply be updated to use the Request facade.

use Illuminate\Support\Facades\Request;
..
..
..
 public function functionName(Request $request)
    {
        $searchInput = $request->q;
}

How to call a method daily, at specific time, in C#?

I have a simple approach to this. This creates a 1 minute delay before the action happens. You could add seconds as well to make the Thread.Sleep(); shorter.

private void DoSomething(int aHour, int aMinute)
{
    bool running = true;
    while (running)
    {
        Thread.Sleep(1);
        if (DateTime.Now.Hour == aHour && DateTime.Now.Minute == aMinute)
        {
            Thread.Sleep(60 * 1000); //Wait a minute to make the if-statement false
            //Do Stuff
        }
    }
}

You need to install postgresql-server-dev-X.Y for building a server-side extension or libpq-dev for building a client-side application

For me this simple command solved the problem:

sudo apt-get install postgresql postgresql-contrib libpq-dev python-dev

Then I can do:

 pip install psycopg2

Get all LI elements in array

QuerySelectorAll will get all the matching elements with defined selector. Here on the example I've used element's name(li tag) to get all of the li present inside the div with navbar element.

_x000D_
_x000D_
    let navbar = document_x000D_
      .getElementById("navbar")_x000D_
      .querySelectorAll('li');_x000D_
_x000D_
    navbar.forEach((item, index) => {_x000D_
      console.log({ index, item })_x000D_
    });
_x000D_
   _x000D_
<div id="navbar">_x000D_
 <ul>_x000D_
  <li id="navbar-One">One</li>_x000D_
  <li id="navbar-Two">Two</li>_x000D_
  <li id="navbar-Three">Three</li>_x000D_
  <li id="navbar-Four">Four</li>_x000D_
  <li id="navbar-Five">Five</li>_x000D_
 </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Call a child class method from a parent class object

I had the same situation and I found a way around with a bit of engineering as follows - -

  1. You have to have your method in parent class without any parameter and use - -

    Class<? extends Person> cl = this.getClass(); // inside parent class
    
  2. Now, with 'cl' you can access all child class fields with their name and initialized values by using - -

    cl.getDeclaredFields(); cl.getField("myfield"); // and many more
    
  3. In this situation your 'this' pointer will reference your child class object if you are calling parent method through your child class object.

  4. Another thing you might need to use is Object obj = cl.newInstance();

Let me know if still you got stucked somewhere.

Palindrome check in Javascript

Some above short anwsers is good, but it's not easy for understand, I suggest one more way:

function checkPalindrome(inputString) {

    if(inputString.length == 1){
        return true;
    }else{
        var i = 0;
        var j = inputString.length -1;
        while(i < j){
            if(inputString[i] != inputString[j]){
                return false;
            }
            i++;
            j--;
        }
    }
    return true;
}

I compare each character, i start form left, j start from right, until their index is not valid (i<j). It's also working in any languages

How to obfuscate Python code effectively?

Try pasting your hello world python code to the following site:

http://enscryption.com/encrypt-and-obfuscate-scripts.html

It will produce a complex encrypted and obfuscated, but fully functional script for you. See if you can crack the script and reveal the actual code. Or see if the level of complexity it provides satisfies your need for peace of mind.

The encrypted script that is produced for you through this site should work on any Unix system that has python installed.

If you would like to encrypt another way, I strongly suggest you write your own encryption/obfuscation algorithm (if security is that important to you). That way, no one can figure out how it works but you. But, for this to really work, you have to spend a tremendous amount of time on it to ensure there aren't any loopholes that someone who has a lot of time on their hands can exploit. And make sure you use tools that are already natural to the Unix system... i.e. openssl or base64. That way, your encrypted script is more portable.

Convert string to BigDecimal in java

You are storing 135.69 as String in currency. But instead of passing variable currency, you are again passing 135.69(double value) into new BigDecimal(). So you are seeing a lot of numbers in the output. If you pass the currency variable, your output will be 135.69

How to select an option from drop down using Selenium WebDriver C#?

Other way could be this one:

driver.FindElement(By.XPath(".//*[@id='examp']/form/select[1]/option[3]")).Click();

and you can change the index in option[x] changing x by the number of element that you want to select.

I don't know if it is the best way but I hope that help you.

How to make a round button?

For a round button create a shape:

<?xml version="1.0" encoding="utf-8"?>

<stroke
    android:width="8dp"
    android:color="#FFFFFF" />

<solid android:color="#ffee82ee" />


<corners
    android:bottomLeftRadius="45dp"
    android:bottomRightRadius="45dp"
    android:topLeftRadius="45dp"
    android:topRightRadius="45dp" />

use it as a background of your button link

angular 2 how to return data from subscribe

Two ways I know of:

export class SomeComponent implements OnInit
{
    public localVar:any;

    ngOnInit(){
        this.http.get(Path).map(res => res.json()).subscribe(res => this.localVar = res);
    }
}

This will assign your result into local variable once information is returned just like in a promise. Then you just do {{ localVar }}

Another Way is to get a observable as a localVariable.

export class SomeComponent
{
    public localVar:any;

    constructor()
    {
        this.localVar = this.http.get(path).map(res => res.json());
    }
}

This way you're exposing a observable at which point you can do in your html is to use AsyncPipe {{ localVar | async }}

Please try it out and let me know if it works. Also, since angular 2 is pretty new, feel free to comment if something is wrong.

Hope it helps

Input widths on Bootstrap 3

In Bootstrap 3

All textual < input >, < textarea >, and < select > elements with .form-control are set to width: 100%; by default.

http://getbootstrap.com/css/#forms-example

It seems, in some cases, we have to set manually the max width we want for the inputs.

Anyway, your example works. Just check it with a large screen, so you can see the name and email fields are getting the 2/12 of the with (col-lg-1 + col-lg-1 and you have 12 columns). But if you have a smaller screen (just resize your browser), the inputs will expand until the end of the row.

setAttribute('display','none') not working

display is not an attribute - it's a CSS property. You need to access the style object for this:

document.getElementById('classRight').style.display = 'none';

Explaining the 'find -mtime' command

The POSIX specification for find says:

-mtimen The primary shall evaluate as true if the file modification time subtracted from the initialization time, divided by 86400 (with any remainder discarded), is n.

Interestingly, the description of find does not further specify 'initialization time'. It is probably, though, the time when find is initialized (run).

In the descriptions, wherever n is used as a primary argument, it shall be interpreted as a decimal integer optionally preceded by a plus ( '+' ) or minus-sign ( '-' ) sign, as follows:

+n More than n.
  n Exactly n.
-n Less than n.

At the given time (2014-09-01 00:53:44 -4:00, where I'm deducing that AST is Atlantic Standard Time, and therefore the time zone offset from UTC is -4:00 in ISO 8601 but +4:00 in ISO 9945 (POSIX), but it doesn't matter all that much):

1409547224 = 2014-09-01 00:53:44 -04:00
1409457540 = 2014-08-30 23:59:00 -04:00

so:

1409547224 - 1409457540 = 89684
89684 / 86400 = 1

Even if the 'seconds since the epoch' values are wrong, the relative values are correct (for some time zone somewhere in the world, they are correct).

The n value calculated for the 2014-08-30 log file therefore is exactly 1 (the calculation is done with integer arithmetic), and the +1 rejects it because it is strictly a > 1 comparison (and not >= 1).

Converting a string to an integer on Android

Best way to convert your string into int is :

 EditText et = (EditText) findViewById(R.id.entry1);
 String hello = et.getText().toString();
 int converted=Integer.parseInt(hello);

Asynchronously load images with jQuery

Using jQuery you may simply change the "src" attribute to "data-src". The image won't be loaded. But the location is stored with the tag. Which I like.

<img class="loadlater" data-src="path/to/image.ext"/>

A Simple piece of jQuery copies data-src to src, which will start loading the image when you need it. In my case when the page has finished loading.

$(document).ready(function(){
    $(".loadlater").each(function(index, element){
        $(element).attr("src", $(element).attr("data-src"));
    });
});

I bet the jQuery code could be abbreviated, but it is understandable this way.

Fire event on enter key press for a textbox

You could wrap the textbox and button in an ASP:Panel, and set the DefaultButton property of the Panel to the Id of your Submit button.

<asp:Panel ID="Panel1" runat="server" DefaultButton="SubmitButton">
    <asp:TextBox ID="TextBox1" runat="server" />
    <asp:Button ID="SubmitButton" runat="server" Text="Submit" OnClick="SubmitButton_Click" />
</asp:Panel>

Now anytime the focus is within the Panel, the 'SubmitButton_Click' event will fire when enter is pressed.

Keytool is not recognized as an internal or external command

I finally solved the problem!!! You should first set the jre path to system variables by navigating to::

control panel > System and Security > System > Advanced system settings 

Under System variables click on new

Variable name: KEY_PATH
Variable value: C:\Program Files (x86)\Java\jre1.8.0_171\bin

Where Variable value should be the path to your JDK's bin folder.

Then open command prompt and Change directory to the same JDK's bin folder like this

C:\Program Files (x86)\Java\jre1.8.0_171\bin 

then paste,

keytool -list -v -keystore "C:\Users\user\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android   

NOTE: People are confusing jre and jdk. All I did applied strictly to jre

How to check if mod_rewrite is enabled in php?

You can get a list of installed apache modules, and check against that. Perhaps you can check if its installed by searching for its .dll (or linux equivalent) file.

vagrant login as root by default

I had some troubles with provisioning when trying to login as root, even with PermitRootLogin yes. I made it so only the vagrant ssh command is affected:

# Login as root when doing vagrant ssh
if ARGV[0]=='ssh'
  config.ssh.username = 'root'
end

CSS Margin: 0 is not setting to 0

After reading this and troubleshooting the same issues, I agree that it is related to headings (h1 for sure, havent played with any others), also browser styles adding margins and paddings with clever rules that are hard to find and over-ride.

I have adapted a technique used to apply the box-sizing property properly to margins and paddings. the original article for box-sizing is located at CSS-Tricks :

html {
margin: 0;
padding: 0;
}
*, *:before, *:after {
margin: inherit;
padding: inherit;
}

So far it is exactly the trick for not using complex resets and makes applying a design much easier for myself anyways. Hope it helps.

Java: Clear the console

This is how I would handle it. This method will work for the Windows OS case and the Linux/Unix OS case (which means it also works for Mac OS X).

public final static void clearConsole()
{
    try
    {
        final String os = System.getProperty("os.name");

        if (os.contains("Windows"))
        {
            Runtime.getRuntime().exec("cls");
        }
        else
        {
            Runtime.getRuntime().exec("clear");
        }
    }
    catch (final Exception e)
    {
        //  Handle any exceptions.
    }
}

Note that this method generally will not clear the console if you are running inside an IDE.

Generating CSV file for Excel, how to have a newline inside a value

Recently I had similar problem, I solved it by importing a HTML file, the baseline example would be like this:

<html xmlns:v="urn:schemas-microsoft-com:vml"
xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns="http://www.w3.org/TR/REC-html40">
  <head>
    <style>
      <!--
      br {mso-data-placement:same-cell;}
      -->
    </style>
  </head>
  <body>
    <table>
      <tr>
        <td>first line<br/>second line</td>
        <td style="white-space:normal">first line<br/>second line</td>
      </tr>
    </table>
  </body>
</html>

I know, it is not a CSV, and might work differently for various versions of Excel, but I think it is worth a try.

I hope this helps ;-)

How to use onResume()?

After an activity started, restarted (onRestart() happens before onStart()), or paused (onPause()), onResume() called. When the activity is in the state of onResume(), the activity is ready to be used by the app user.

I have studied the activity lifecycle a little bit, and here's my understanding of this topic: If you want to restart the activity (A) at the end of the execution of another, there could be a few different cases.

  1. The other activity (B) has been paused and/or stopped or destroyed, and the activity A possibly had been paused (onPause()), in this case, activity A will call onResume()

  2. The activity B has been paused and/or stopped or destroyed, the activity A possibly had been stopped (onStop()) due to memory thing, in this case, activity A will call onRestart() first, onStart() second, then onResume()

  3. The activity B has been paused and/or stopped or destroyed, the activity A has been destroyed, the programmer can call onStart() manually to start the activity first, then onResume() because when an activity is in the destroyed status the activity has not started, and this happens before the activity being completely removed. If the activity is removed, the activity needs to be created again. Manually calling onStart() I think it's because if the activity not started and it is created, onStart() will be called after onCreate().

If you want to update data, make a data update function and put the function inside the onResume(). Or put a loadData function inside onResume()

It's better to understand the lifecycle with the help of the Activity lifecycle diagram.

How to make PDF file downloadable in HTML link?

This is the key:

header("Content-Type: application/octet-stream");

Content-type application/x-pdf-document or application/pdf is sent while sending PDF file. Adobe Reader usually sets the handler for this MIME type so browser will pass the document to Adobe Reader when any of PDF MIME types is received.

Oracle SQL update based on subquery between two tables

Without examples of the dataset of staging this is a shot in the dark, but have you tried something like this?

update PRODUCTION p,
       staging s
set p.name = s.name  
    p.count = s.count
where p.id = s.id

This would work assuming the id column matches on both tables.

Run JavaScript in Visual Studio Code

Follow these steps in VS code.[performed in windows os]

  1. Create new file

  2. Write javascript codes in it

  3. Save file as filename.js

  4. Go to Debugging menu

  5. Click on Start debugging

  6. or simply press F5

screenshot of starting debugging

screenshot of output of js code in terminal

Immutable array in Java

The of(E... elements) method in Java9 can be used to create immutable list using just a line:

List<Integer> items = List.of(1,2,3,4,5);

The above method returns an immutable list containing an arbitrary number of elements. And adding any integer to this list would result in java.lang.UnsupportedOperationExceptionexception. This method also accepts a single array as an argument.

String[] array = ... ;
List<String[]> list = List.<String[]>of(array);

How can I calculate the time between 2 Dates in typescript

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

that way typescript converts the dates to numbers.

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

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

How would I get everything before a : in a string Python

Just use the split function. It returns a list, so you can keep the first element:

>>> s1.split(':')
['Username', ' How are you today?']
>>> s1.split(':')[0]
'Username'

How to remove a build from itunes connect?

UPDATE:

Time has changed, you can now remove (expire) TestFlight Builds as in this answer but you still cannot delete the build.

OLD:

I asked apple and here is their answer:

I understand you would like to remove a build from iTunes Connect as shown in your screenshot.

Please be advised this is expected behavior as you can remove a build from being the current build but you cannot delete it from iTunes Connect. For more information, please refer to the iTunes Connect Developer Guide: https://developer.apple.com/library/content/documentation/LanguagesUtilities/Conceptual/iTunesConnect_Guide/

So i just can't.

Get the first N elements of an array?

You can use array_slice as:

$sliced_array = array_slice($array,0,$N);

What is HEAD in Git?

Assuming it is not a special case called "detached HEAD", then, as stated in the O'Reilly Git book, 2nd edtion, p.69, HEAD means:

HEAD always refers to the most recent commit on the current branch. When you change branches, HEAD is updated to refer to the new branch’s latest commit.

so

HEAD is the "tip" of the current branch.

Note that we can use HEAD to refer to the most recent commit, and use HEAD~ as the commit before the tip, and HEAD~~ or HEAD~2 as the commit even earlier, and so forth.