Programs & Examples On #Widget

A widget is an element of a user interface (GUI widget) or a self-contained (usually small) software application (desktop widget). In computing , an application, or a component of an interface, that enables a user to perform a function or access a service.

How to clear the Entry widget after a button is pressed in Tkinter?

You shall proceed with ent.delete(0,"end") instead of using 'END', use 'end' inside quotation.

 secret = randrange(1,100)
print(secret)
def res(real, secret):
    if secret==eval(real):
        showinfo(message='that is right!')
    real.delete(0, END)

def guess():
    ge = Tk()
    ge.title('guessing game')

    Label(ge, text="what is your guess:").pack(side=TOP)

    ent = Entry(ge)
    ent.pack(side=TOP)

    btn=Button(ge, text="Enter", command=lambda: res(ent.get(),secret))
    btn.pack(side=LEFT)

    ge.mainloop()

This shall solve your problem

How do I center text vertically and horizontally in Flutter?

Overview: I used the Flex widget to center text on my page using the MainAxisAlignment.center along the horizontal axis. I use the container padding to create a margin space around my text.

  Flex(
            direction: Axis.horizontal,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
                Container(
                    padding: EdgeInsets.all(20),
                    child:
                        Text("No Records found", style: NoRecordFoundStyle))
  ])

Failed binder transaction when putting an bitmap dynamically in a widget

The right approach is to use setImageViewUri() (slower) or the setImageViewBitmap() and recreating RemoteViews every time you update the notification.

How to make a GridLayout fit screen size

If you use fragments you can prepare XML layout and than stratch critical elements programmatically

int thirdScreenWidth = (int)(screenWidth *0.33);

View view = inflater.inflate(R.layout.fragment_second, null);
View _container = view.findViewById(R.id.rim1container);
_container.getLayoutParams().width = thirdScreenWidth * 2;

_container = view.findViewById(R.id.rim2container);
_container.getLayoutParams().width = screenWidth - thirdScreenWidth * 2;

_container = view.findViewById(R.id.rim3container);
_container.getLayoutParams().width = screenWidth - thirdScreenWidth * 2;

This layout for 3 equal columns. First element takes 2x2 Result in the picture enter image description here

Is there an easy way to strike through text in an app widget?

2015 Update: Folks, this is for very old versions of Android. See other answers for modern solutions!


To strike through the entire text view, you can use a specific background image to simulate the strikethrough effect:

android:background="@drawable/bg_strikethrough"

Where the bg_strikethrough drawable is a 9-patch that keeps a solid line through the middle, growing either side, with however much padding you think is reasonable. I've used one like this:

alt text

(enlarged for clarity.. 1300% !)

alt text

That is my HDPI version, so save it (the first one http://i.stack.imgur.com/nt6BK.png) as res/drawable-hdpi/bg_strikethrough.9.png and the configuration will work as so:

alt text

How to pass parameters to a Script tag?

It's better to Use feature in html5 5 data Attributes

<script src="http://path.to/widget.js" data-width="200" data-height="200">
</script>

Inside the script file http://path.to/widget.js you can get the paremeters in that way:

<script>
function getSyncScriptParams() {
         var scripts = document.getElementsByTagName('script');
         var lastScript = scripts[scripts.length-1];
         var scriptName = lastScript;
         return {
             width : scriptName.getAttribute('data-width'),
             height : scriptName.getAttribute('data-height')
         };
 }
</script>

Android widget: How to change the text of a button

I was able to change the button's text like this:

import android.widget.RemoteViews;

//grab the layout, then set the text of the Button called R.id.Counter:
RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.my_layout);
remoteViews.setTextViewText(R.id.Counter, "Set button text here");

Textarea that can do syntax highlighting on the fly?

It's not possible to achieve the required level of control over presentation in a regular textarea.

If you're OK with that, try CodeMirror or Ace or Monaco (used in MS VSCode).

From the duplicate thread - an obligatory wikipedia link: Comparison of JavaScript-based source code editors

RecyclerView - Get view at particular position

To get specific view from recycler view list OR show error at edittext of recycler view.

private void popupErrorMessageAtPosition(int itemPosition) {

    RecyclerView.ViewHolder viewHolder = recyclerView.findViewHolderForAdapterPosition(itemPosition);
    View view = viewHolder.itemView;
    EditText etDesc = (EditText) view.findViewById(R.id.et_description);
    etDesc.setError("Error message here !");
}

How to make the Facebook Like Box responsive?

As of August 4 2015, the native facebook like box have a responsive code snippet available at Facebook Developers page.

You can generate your responsive Facebook likebox here

https://developers.facebook.com/docs/plugins/page-plugin

This is the best solution ever rather than hacking CSS.

Resizing an iframe based on content

Work with jquery on load (cross browser):

 <iframe src="your_url" marginwidth="0"  marginheight="0" scrolling="No" frameborder="0"  hspace="0" vspace="0" id="containiframe" onload="loaderIframe();" height="100%"  width="100%"></iframe>

function loaderIframe(){
var heightIframe = $('#containiframe').contents().find('body').height();
$('#frame').css("height", heightFrame);
 }  

on resize in responsive page:

$(window).resize(function(){
if($('#containiframe').length !== 0) {
var heightIframe = $('#containiframe').contents().find('body').height();
 $('#frame').css("height", heightFrame);
}
});

How to convert a Django QuerySet to a list

Try this values_list('column_name', flat=True).

answers = Answer.objects.filter(id__in=[answer.id for answer in answer_set.answers.all()]).values_list('column_name', flat=True)

It will return you a list with specified column values

Array copy values to keys in PHP

$final_array = array_combine($a, $a);

Reference: http://php.net/array-combine

P.S. Be careful with source array containing duplicated keys like the following:

$a = ['one','two','one'];

Note the duplicated one element.

Maven dependency for Servlet 3.0 API?

Unfortunately, adding the javaee-(web)-api as a dependency doesn't give you the Javadoc or the Source to the Servlet Api to browse them from within the IDE. This is also the case for all other dependencies (JPA, EJB, ...) If you need the Servlet API sources/javadoc, you can add the following to your pom.xml (works at least for JBoss&Glassfish):

Repository:

<repository>
  <id>jboss-public-repository-group</id>
  <name>JBoss Public Repository Group</name>
  <url>https://repository.jboss.org/nexus/content/groups/public/</url>
</repository>

Dependency:

<!-- Servlet 3.0 Api Specification -->
<dependency>
   <groupId>org.jboss.spec.javax.servlet</groupId>
   <artifactId>jboss-servlet-api_3.0_spec</artifactId>
   <version>1.0.0.Beta2</version>
   <scope>provided</scope>
</dependency>

I completely removed the javaee-api from my dependencies and replaced it with the discrete parts (javax.ejb, javax.faces, ...) to get the sources and Javadocs for all parts of Java EE 6.

EDIT:

Here is the equivalent Glassfish dependency (although both dependencies should work, no matter what appserver you use).

<dependency>
  <groupId>org.glassfish</groupId>
  <artifactId>javax.servlet</artifactId>
  <version>3.0</version>
  <scope>provided</scope>
</dependency>

Merge r brings error "'by' must specify uniquely valid columns"

This is what I tried for a right outer join [as per my requirement]:

m1 <- merge(x=companies, y=rounds2, by.x=companies$permalink, 
            by.y=rounds2$company_permalink, all.y=TRUE)
# Error in fix.by(by.x, x) : 'by' must specify uniquely valid columns
m1 <- merge(x=companies, y=rounds2, by.x=c("permalink"), 
            by.y=c("company_permalink"), all.y=TRUE)

This worked.

Inherit CSS class

You dont inherit in css, you simply add another class to the element which overrides the values

.base{    
  color:green;
  ...other props
}

.basealt{
   color:red;
}

<span class="base basealt"></span>

Java best way for string find and replace?

When you dont want to put your hand yon regular expression (may be you should) you could first replace all "Milan Vasic" string with "Milan".

And than replace all "Milan" Strings with "Milan Vasic".

How To Create Table with Identity Column

Unique key allows max 2 NULL values. Explaination:

create table teppp
(
id int identity(1,1) primary key,
name varchar(10 )unique,
addresss varchar(10)
)

insert into teppp ( name,addresss) values ('','address1')
insert into teppp ( name,addresss) values ('NULL','address2')
insert into teppp ( addresss) values ('address3')

select * from teppp
null string , address1
NULL,address2
NULL,address3

If you try inserting same values as below:

insert into teppp ( name,addresss) values ('','address4')
insert into teppp ( name,addresss) values ('NULL','address5')
insert into teppp ( addresss) values ('address6')

Every time you will get error like:

Violation of UNIQUE KEY constraint 'UQ__teppp__72E12F1B2E1BDC42'. Cannot insert duplicate key in object 'dbo.teppp'.
The statement has been terminated.

printf() formatting for hex

The %#08X conversion must precede the value with 0X; that is required by the standard. There's no evidence in the standard that the # should alter the behaviour of the 08 part of the specification except that the 0X prefix is counted as part of the length (so you might want/need to use %#010X. If, like me, you like your hex presented as 0x1234CDEF, then you have to use 0x%08X to achieve the desired result. You could use %#.8X and that should also insert the leading zeroes.

Try variations on the following code:

#include <stdio.h>

int main(void)
{
    int j = 0;
    printf("0x%.8X = %#08X = %#.8X = %#010x\n", j, j, j, j);
    for (int i = 0; i < 8; i++)
    {
        j = (j << 4) | (i + 6);
        printf("0x%.8X = %#08X = %#.8X = %#010x\n", j, j, j, j);
    }
    return(0);
}

On an RHEL 5 machine, and also on Mac OS X (10.7.5), the output was:

0x00000000 = 00000000 = 00000000 = 0000000000
0x00000006 = 0X000006 = 0X00000006 = 0x00000006
0x00000067 = 0X000067 = 0X00000067 = 0x00000067
0x00000678 = 0X000678 = 0X00000678 = 0x00000678
0x00006789 = 0X006789 = 0X00006789 = 0x00006789
0x0006789A = 0X06789A = 0X0006789A = 0x0006789a
0x006789AB = 0X6789AB = 0X006789AB = 0x006789ab
0x06789ABC = 0X6789ABC = 0X06789ABC = 0x06789abc
0x6789ABCD = 0X6789ABCD = 0X6789ABCD = 0x6789abcd

I'm a little surprised at the treatment of 0; I'm not clear why the 0X prefix is omitted, but with two separate systems doing it, it must be standard. It confirms my prejudices against the # option.


The treatment of zero is according to the standard.

ISO/IEC 9899:2011 §7.21.6.1 The fprintf function

¶6 The flag characters and their meanings are:
...
# The result is converted to an "alternative form". ... For x (or X) conversion, a nonzero result has 0x (or 0X) prefixed to it. ...

(Emphasis added.)


Note that using %#X will use upper-case letters for the hex digits and 0X as the prefix; using %#x will use lower-case letters for the hex digits and 0x as the prefix. If you prefer 0x as the prefix and upper-case letters, you have to code the 0x separately: 0x%X. Other format modifiers can be added as needed, of course.

For printing addresses, use the <inttypes.h> header and the uintptr_t type and the PRIXPTR format macro:

#include <inttypes.h>
#include <stdio.h>

int main(void)
{
    void *address = &address;  // &address has type void ** but it converts to void *
    printf("Address 0x%.12" PRIXPTR "\n", (uintptr_t)address);
    return 0;
}

Example output:

Address 0x7FFEE5B29428

Choose your poison on the length — I find that a precision of 12 works well for addresses on a Mac running macOS. Combined with the . to specify the minimum precision (digits), it formats addresses reliably. If you set the precision to 16, the extra 4 digits are always 0 in my experience on the Mac, but there's certainly a case to be made for using 16 instead of 12 in portable 64-bit code (but you'd use 8 for 32-bit code).

Get SELECT's value and text in jQuery

<select id="ddlViewBy">
    <option value="value">text</option>
</select>

JQuery

var txt = $("#ddlViewBy option:selected").text();
var val = $("#ddlViewBy option:selected").val();

JS Fiddle DEMO

Do I commit the package-lock.json file created by npm 5?

Yes, it's intended to be checked in. I want to suggest that it gets its own unique commit. We find that it adds a lot of noise to our diffs.

Spring Boot how to hide passwords in properties file

UPDATE: I noticed folks down-voting this, so I have to say that although this is not an ideal solution, but this works and acceptable in some use-cases. Cloudfoundry uses Environment variables to inject credentials when a Service is binded to an application. More info https://docs.cloudfoundry.org/devguide/services/application-binding.html

And also if your system is not shared, then for local development this is also acceptable. Of course, the more safe and secure way is explained in Answer by @J-Alex.

Answer:

If you want to hide your passwords then the easiest solution is to use Environment variables in application.properties file or directly in your code.

In application.properties:

mypassword=${password}

Then in your configuration class:

@Autowired
private Environment environment;

[...]//Inside a method
System.out.println(environment.getProperty("mypassword"));

In your configuration class:

@Value("${password}")
private String herokuPath;

[...]//Inside a method
System.out.println(herokuPath);

Note: You might have to restart after setting the environment variable. For windows:

In Windows

Refer this Documentation for more info.

ggplot combining two plots from different data.frames

The only working solution for me, was to define the data object in the geom_line instead of the base object, ggplot.

Like this:

ggplot() + 
geom_line(data=Data1, aes(x=A, y=B), color='green') + 
geom_line(data=Data2, aes(x=C, y=D), color='red')

instead of

ggplot(data=Data1, aes(x=A, y=B), color='green') + 
geom_line() + 
geom_line(data=Data2, aes(x=C, y=D), color='red')

More info here

Run Function After Delay

You can simply use jQuery’s delay() method to set the delay time interval.

HTML code:

  <div class="box"></div>

JQuery code:

  $(document).ready(function(){ 
    $(".show-box").click(function(){
      $(this).text('loading...').delay(1000).queue(function() {
        $(this).hide();
        showBox(); 
        $(this).dequeue();
      });        
    });
  });

You can see an example here: How to Call a Function After Some Time in jQuery

What is the meaning of single and double underscore before an object name?

  • _var: variables with a leading single underscore in python are classic variables, intended to inform others using your code that this variable should be reserved for internal use. They differ on one point from classic variables: they are not imported when doing a wildcard import of an object/module where they are defined (exceptions when defining the __all__ variable). Eg:

    # foo.py
    
    var = "var"
    _var = "_var"
    
    # bar.py
    
    from foo import *
    
    print(dir())  # list of defined objects, contains 'var' but not '_var'
    print(var)    # var
    print(_var)   # NameError: name '_var' is not defined
    
  • _ : the single underscore is a special case of the leading single underscore variables. It is used by convention as a trash variable, to store a value that is not intended to be later accessed. It is also not imported by wildcard imports. Eg: this for loop prints "I must not talk in class" 10 times, and never needs to access the _ variable.

    for _ in range(10):
        print("I must not talk in class")
    
  • __var: double leading underscore variables (at least two leading underscores, at most one trailing underscore). When used as class attributes (variables and methods), these variables are subject to name mangling: outside of the class, python will rename the attribute to _<Class_name>__<attribute_name>. Example:

    class MyClass:
        __an_attribute = "attribute_value"
    
    my_class = MyClass()
    print(my_class._MyClass__an_attribute)  # "attribute_value"
    print(my_class.__an_attribute)  # AttributeError: 'MyClass' object has no attribute '__an_attribute'
    

    When used as variables outside a class, they behave like single leading underscore variables.

  • __var__: double leading and trailing underscore variables (at least two leading and trailing underscores). Also called dunders. This naming convention is used by python to define variables internally. Avoid using this convention to prevent name conflicts that could arise with python updates. Dunder variables behave like single leading underscore variables: they are not subject to name mangling when used inside classes, but are not imported in wildcard imports.

Java generics - ArrayList initialization

Think of the ? as to mean "unknown". Thus, "ArrayList<? extends Object>" is to say "an unknown type that (or as long as it)extends Object". Therefore, needful to say, arrayList.add(3) would be putting something you know, into an unknown. I.e 'Forgetting'.

how to remove css property using javascript?

actually, if you already know the property, this will do it...

for example:

<a href="test.html" style="color:white;zoom:1.2" id="MyLink"></a>

    var txt = "";
    txt = getStyle(InterTabLink);
    setStyle(InterTabLink, txt.replace("zoom\:1\.2\;","");

    function setStyle(element, styleText){
        if(element.style.setAttribute)
            element.style.setAttribute("cssText", styleText );
        else
            element.setAttribute("style", styleText );
    }

    /* getStyle function */
    function getStyle(element){
        var styleText = element.getAttribute('style');
        if(styleText == null)
            return "";
        if (typeof styleText == 'string') // !IE
            return styleText;
        else  // IE
            return styleText.cssText;
    } 

Note that this only works for inline styles... not styles you've specified through a class or something like that...

Other note: you may have to escape some characters in that replace statement, but you get the idea.

How do I install Python packages in Google's Colab?

You can use !setup.py install to do that.

Colab is just like a Jupyter notebook. Therefore, we can use the ! operator here to install any package in Colab. What ! actually does is, it tells the notebook cell that this line is not a Python code, its a command line script. So, to run any command line script in Colab, just add a ! preceding the line.

For example: !pip install tensorflow. This will treat that line (here pip install tensorflow) as a command prompt line and not some Python code. However, if you do this without adding the ! preceding the line, it'll throw up an error saying "invalid syntax".

But keep in mind that you'll have to upload the setup.py file to your drive before doing this (preferably into the same folder where your notebook is).

Hope this answers your question :)

How to end a session in ExpressJS

Express 4.x Updated Answer

Session handling is no longer built into Express. This answer refers to the standard session module: https://github.com/expressjs/session

To clear the session data, simply use:

req.session.destroy();

The documentation is a bit useless on this. It says:

Destroys the session, removing req.session, will be re-generated next request. req.session.destroy(function(err) { // cannot access session here })

This does not mean that the current session will be re-loaded on the next request. It means that a clean empty session will be created in your session store on next request. (Presumably the session ID isn't changing, but I have not tested that.)

Cannot find firefox binary in PATH. Make sure firefox is installed

I didn't see the C# anwer to this question here. The trick is to set the BrowserExecutableLocation property on a FirefoxOptions instance, and pass that into the driver constructor:

        var opt = new FirefoxOptions
        {
            BrowserExecutableLocation = @"c:\program files\mozilla firefox\firefox.exe"
        };
        var driver = new FirefoxDriver(opt);

Big-O summary for Java Collections Framework implementations?

The book Java Generics and Collections has this information (pages: 188, 211, 222, 240).

List implementations:

                      get  add  contains next remove(0) iterator.remove
ArrayList             O(1) O(1) O(n)     O(1) O(n)      O(n)
LinkedList            O(n) O(1) O(n)     O(1) O(1)      O(1)
CopyOnWrite-ArrayList O(1) O(n) O(n)     O(1) O(n)      O(n)

Set implementations:

                      add      contains next     notes
HashSet               O(1)     O(1)     O(h/n)   h is the table capacity
LinkedHashSet         O(1)     O(1)     O(1) 
CopyOnWriteArraySet   O(n)     O(n)     O(1) 
EnumSet               O(1)     O(1)     O(1) 
TreeSet               O(log n) O(log n) O(log n)
ConcurrentSkipListSet O(log n) O(log n) O(1)

Map implementations:

                      get      containsKey next     Notes
HashMap               O(1)     O(1)        O(h/n)   h is the table capacity
LinkedHashMap         O(1)     O(1)        O(1) 
IdentityHashMap       O(1)     O(1)        O(h/n)   h is the table capacity 
EnumMap               O(1)     O(1)        O(1) 
TreeMap               O(log n) O(log n)    O(log n) 
ConcurrentHashMap     O(1)     O(1)        O(h/n)   h is the table capacity 
ConcurrentSkipListMap O(log n) O(log n)    O(1)

Queue implementations:

                      offer    peek poll     size
PriorityQueue         O(log n) O(1) O(log n) O(1)
ConcurrentLinkedQueue O(1)     O(1) O(1)     O(n)
ArrayBlockingQueue    O(1)     O(1) O(1)     O(1)
LinkedBlockingQueue   O(1)     O(1) O(1)     O(1)
PriorityBlockingQueue O(log n) O(1) O(log n) O(1)
DelayQueue            O(log n) O(1) O(log n) O(1)
LinkedList            O(1)     O(1) O(1)     O(1)
ArrayDeque            O(1)     O(1) O(1)     O(1)
LinkedBlockingDeque   O(1)     O(1) O(1)     O(1)

The bottom of the javadoc for the java.util package contains some good links:

Converting float to char*

typedef union{
    float a;
    char b[4];
} my_union_t;

You can access to float data value byte by byte and send it through 8-bit output buffer (e.g. USART) without casting.

Configuring angularjs with eclipse IDE

Netbeans 8.0 (beta at the time of this post) has Angular support as well as HTML5 support.

Check out this Oracle article: https://blogs.oracle.com/geertjan/entry/integrated_angularjs_development

Show div on scrollDown after 800px

SCROLLBARS & $(window).scrollTop()

What I have discovered is that calling such functionality as in the solution thankfully provided above, (there are many more examples of this throughout this forum - which all work well) is only successful when scrollbars are actually visible and operating.

If (as I have maybe foolishly tried), you wish to implement such functionality, and you also wish to, shall we say, implement a minimalist "clean screen" free of scrollbars, such as at this discussion, then $(window).scrollTop() will not work.

It may be a programming fundamental, but thought I'd offer the heads up to any fellow newbies, as I spent a long time figuring this out.

If anyone could offer some advice as to how to overcome this or a little more insight, feel free to reply, as I had to resort to show/hide onmouseover/mouseleave instead here

Live long and program, CollyG.

How to call external url in jquery?

Hi url should be calling a function which in return will give response

$.ajax({
url:'function to call url',
...
...

});

try using/calling API facebook method

Why is "throws Exception" necessary when calling a function?

Exception is a checked exception class. Therefore, any code that calls a method that declares that it throws Exception must handle or declare it.

How do I set combobox read-only or user cannot write in a combo box only can select the given items?

Try this:

    private void comboBox1_KeyDown(object sender, KeyEventArgs e)
    {
        // comboBox1 is readonly
        e.SuppressKeyPress = true;
    }

What's the difference between a word and byte?

The terms of BYTE and WORD are relative to the size of the processor that is being referred to. The most common processors are/were 8 bit, 16 bit, 32 bit or 64 bit. These are the WORD lengths of the processor. Actually half of a WORD is a BYTE, whatever the numerical length is. Ready for this, half of a BYTE is a NIBBLE.

C# static class why use?

If a class is declared as static then the variables and methods need to be declared as static.

A class can be declared static, indicating that it contains only static members. It is not possible to create instances of a static class using the new keyword. Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.

Use a static class to contain methods that are not associated with a particular object. For example, it is a common requirement to create a set of methods that do not act on instance data and are not associated to a specific object in your code. You could use a static class to hold those methods.

->The main features of a static class are:

  • They only contain static members.
  • They cannot be instantiated.
  • They are sealed.
  • They cannot contain Instance Constructors or simply constructors as we know that they are associated with objects and operates on data when an object is created.

Example

static class CollegeRegistration
{
  //All static member variables
   static int nCollegeId; //College Id will be same for all the students studying
   static string sCollegeName; //Name will be same
   static string sColegeAddress; //Address of the college will also same

    //Member functions
   public static int GetCollegeId()
   {
     nCollegeId = 100;
     return (nCollegeID);
   }
    //similarly implementation of others also.
} //class end


public class student
{
    int nRollNo;
    string sName;

    public GetRollNo()
    {
       nRollNo += 1;
       return (nRollNo);
    }
    //similarly ....
    public static void Main()
   {
     //Not required.
     //CollegeRegistration objCollReg= new CollegeRegistration();

     //<ClassName>.<MethodName>
     int cid= CollegeRegistration.GetCollegeId();
    string sname= CollegeRegistration.GetCollegeName();


   } //Main end
}

Maven: add a folder or jar file into current classpath

The classpath setting of the compiler plugin are two args. Changed it like this and it worked for me:

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
  <compilerArgs>
     <arg>-cp</arg>
     <arg>${cp}:${basedir}/lib/bad.jar</arg>
  </compilerArgs>
</configuration>

I used the gmavenplus-plugin to read the path and create the property 'cp':

      <plugin>
    <!--
      Use Groovy to read classpath and store into
      file named value of property <cpfile>

      In second step use Groovy to read the contents of
      the file into a new property named <cp>

      In the compiler plugin this is used to create a
      valid classpath
    -->
    <groupId>org.codehaus.gmavenplus</groupId>
    <artifactId>gmavenplus-plugin</artifactId>
    <version>1.12.0</version>
    <dependencies>
      <dependency>
        <groupId>org.codehaus.groovy</groupId>
        <artifactId>groovy-all</artifactId>
        <!-- any version of Groovy \>= 1.5.0 should work here -->
        <version>3.0.6</version>
        <type>pom</type>
        <scope>runtime</scope>
      </dependency>
    </dependencies>
    <executions>
      <execution>
        <id>read-classpath</id>
        <phase>validate</phase>
        <goals>
          <goal>execute</goal>
        </goals>
      </execution>

    </executions>
    <configuration>
      <scripts>
        <script><![CDATA[
                def file = new File(project.properties.cpfile)
                /* create a new property named 'cp'*/
                project.properties.cp = file.getText()
                println '<<< Retrieving classpath into new property named <cp> >>>'
                println 'cp = ' + project.properties.cp
              ]]></script>
      </scripts>
    </configuration>
  </plugin>

Add custom icons to font awesome

Similar approach to @Samuel-bergström:

  • Download Fontawesome SVG https://github.com/FortAwesome/Font-Awesome/blob/master/src/assets/font-awesome/fonts/fontawesome-webfont.svg
  • Download FontForge http://fontforge.github.io/en-US/downloads/
  • Download Inkscape
  • Open Inskscape and create a single layer shape as your new font icon
  • Save SVG file, Close Inkscape
  • Open FontForge (If you have multiple monitors, use Windows-LeftArrow, to reposition as they have strange SWING java windows that go off monitor, and have modal problems with popups - I had to check my task bar for some)
  • File | Open fontawesome-webfont.svg
  • File | Import
  • Scroll to the bottom, Right Click on Icon | Glyph Info
  • Update Glyph Name to uniFXXX (XXX is something like 501, a higher number than the highest Unicode used in v4.5 of FontAwesome)
  • Unicode Vlaue U+fXXX
  • Click OK
  • File | Save
  • File | Generate Fonts ...
  • Close FontForge
  • Open your web project
  • Copy your font files to the (in my project) "\Content\fonts\" folder.
  • Edit "\Content\styles\fa\path.less" to be like:

_x000D_
_x000D_
@font-face {_x000D_
      font-family: 'FontAwesome';_x000D_
      //src: url('@{fa-font-path}/fontawesome-webfont.eot?v=@{fa-version}');_x000D_
      src: _x000D_
     //url('@{fa-font-path}/fontawesome-webfont.eot?#iefix&v=@{fa-version}') format('embedded-opentype'),_x000D_
        //url('@{fa-font-path}/fontawesome-webfont.woff2?v=@{fa-version}') format('woff2'),_x000D_
        url('@{fa-font-path}/fontawesomeregular.woff?v=@{fa-version}') format('woff'),_x000D_
        url('@{fa-font-path}/fontawesomeregular.ttf?v=@{fa-version}') format('truetype'),_x000D_
        url('@{fa-font-path}/fontawesomeregular.svg?v=@{fa-version}#fontawesomeregular') format('svg');_x000D_
    //  src: url('@{fa-font-path}/FontAwesome.otf') format('opentype'); // used when developing fonts_x000D_
      font-weight: normal;_x000D_
      font-style: normal;_x000D_
    }
_x000D_
_x000D_
_x000D_

I know it may be 'controversial' to comment out other file types, but happy to hear how to generate .eot or .otf files in the comments.

  • and finally, as Samuel mentions, update your CSS/LESS with:

    .fa-XXX:before { content: "\f501"; }

Map and Reduce in .NET

Since I never can remember that LINQ calls it Where, Select and Aggregate instead of Filter, Map and Reduce so I created a few extension methods you can use:

IEnumerable<string> myStrings = new List<string>() { "1", "2", "3", "4", "5" };
IEnumerable<int> convertedToInts = myStrings.Map(s => int.Parse(s));
IEnumerable<int> filteredInts = convertedToInts.Filter(i => i <= 3); // Keep 1,2,3
int sumOfAllInts = filteredInts.Reduce((sum, i) => sum + i); // Sum up all ints
Assert.Equal(6, sumOfAllInts); // 1+2+3 is 6

Here are the 3 methods (from https://github.com/cs-util-com/cscore/blob/master/CsCore/PlainNetClassLib/src/Plugins/CsCore/com/csutil/collections/IEnumerableExtensions.cs ):

public static IEnumerable<R> Map<T, R>(this IEnumerable<T> self, Func<T, R> selector) {
    return self.Select(selector);
}

public static T Reduce<T>(this IEnumerable<T> self, Func<T, T, T> func) {
    return self.Aggregate(func);
}

public static IEnumerable<T> Filter<T>(this IEnumerable<T> self, Func<T, bool> predicate) {
    return self.Where(predicate);
}

Some more details from https://github.com/cs-util-com/cscore#ienumerable-extensions :

enter image description here

What is Java EE?

J2EE traditionally referred to products and standards released by Sun. For example if you were developing a standard J2EE web application, you would be using EJBs, Java Server Faces, and running in an application server that supports the J2EE standard. However since there is such a huge open source plethora of libraries and products that do the same jobs as well as (and many will argue better) then these Sun offerings, the day to day meaning of J2EE has migrated into referring to these as well (For instance a Spring/Tomcat/Hibernate solution) in many minds.

This is a great book in my opinion that discusses the 'open source' approach to J2EE http://www.theserverside.com/tt/articles/article.tss?l=J2EEWithoutEJB_BookReview

How to set a cron job to run every 3 hours

Change Minute to be 0. That's it :)

Note: you can check your "crons" in http://cronchecker.net/

Example

How to fix itunes could not connect to the iphone because an invalid response was received from the device?

Try resetting your network settings

Settings -> General -> Reset -> Reset Network Settings

And try deleting the contents of your mac/pc lockdown folder. Here's the link, follow the steps on "Reset the Lockdown folder".

http://support.apple.com/kb/ts2529

This one worked for me.

TypeError: ObjectId('') is not JSON serializable

As a quick replacement, you can change {'owner': objectid} to {'owner': str(objectid)}.

But defining your own JSONEncoder is a better solution, it depends on your requirements.

How to copy directory recursively in python and overwrite all?

You can use distutils.dir_util.copy_tree. It works just fine and you don't have to pass every argument, only src and dst are mandatory.

However in your case you can't use a similar tool likeshutil.copytree because it behaves differently: as the destination directory must not exist this function can't be used for overwriting its contents.

If you want to use the cp tool as suggested in the question comments beware that using the subprocess module is currently the recommended way for spawning new processes as you can see in the documentation of the os.system function.

UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 1

I was getting the same type of error, and I found that the console is not capable of displaying the string in another language. Hence I made the below code changes to set default_charset as UTF-8.

data_head = [('\x81\xa1\x8fo\x89\xef\x82\xa2\x95\xdb\x8f\xd8\x90\xa7\x93x\x81\xcb3\x8c\x8e\x8cp\x91\xb1\x92\x86(\x81\x86\x81\xde\x81\x85)\x81\xa1\x8f\x89\x89\xf1\x88\xc8\x8aO\x81A\x82\xa8\x8b\xe0\x82\xcc\x90S\x94z\x82\xcd\x88\xea\x90\xd8\x95s\x97v\x81\xa1\x83}\x83b\x83v\x82\xcc\x82\xa8\x8e\x8e\x82\xb5\x95\xdb\x8c\xaf\x82\xc5\x8fo\x89\xef\x82\xa2\x8am\x92\xe8\x81\xa1', 'shift_jis')]
default_charset = 'UTF-8' #can also try 'ascii' or other unicode type
print ''.join([ unicode(lin[0], lin[1] or default_charset) for lin in data_head ])

Changing WPF title bar background color

In WPF the titlebar is part of the non-client area, which can't be modified through the WPF window class. You need to manipulate the Win32 handles (if I remember correctly).
This article could be helpful for you: Custom Window Chrome in WPF.

Matplotlib discrete colorbar

You could follow this example:

#!/usr/bin/env python
"""
Use a pcolor or imshow with a custom colormap to make a contour plot.

Since this example was initially written, a proper contour routine was
added to matplotlib - see contour_demo.py and
http://matplotlib.sf.net/matplotlib.pylab.html#-contour.
"""

from pylab import *


delta = 0.01
x = arange(-3.0, 3.0, delta)
y = arange(-3.0, 3.0, delta)
X,Y = meshgrid(x, y)
Z1 = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
Z = Z2 - Z1 # difference of Gaussians

cmap = cm.get_cmap('PiYG', 11)    # 11 discrete colors

im = imshow(Z, cmap=cmap, interpolation='bilinear',
            vmax=abs(Z).max(), vmin=-abs(Z).max())
axis('off')
colorbar()

show()

which produces the following image:

poormans_contour

Convert a video to MP4 (H.264/AAC) with ffmpeg

Try This one:: Libav in Linux

Installation: run command  
               sudo apt-get install libav-tools 

Video conversion command::Go to folder contains the video and run in terminal
               avconv -i oldvideo.flv -ar 22050 convertedvideo.mp4

Clear the value of bootstrap-datepicker

I know its too late to answer, but in my scenario below code was not working.

 $('#datepicker').val("");
 $('#datepicker').val('').datepicker('update');
 $('#datepicker').datepicker('update','');

here is my solution.

 $('#datepicker').val('').datepicker('remove').datepicker();

I did clear datepicker value first then removed datepicker and again reinitialize datepicker. its resolved my problem.

How do I run a Python program?

I have tried many of the commands listed above, however none worked, even after setting my path to include the directory where I installed Python.

The command py -3 file.py always works for me, and if I want to run Python 2 code, as long as Python 2 is in my path, just changing the command to py -2 file.py works perfectly.

I am using Windows, so I'm not too sure if this command will work on Linux, or Mac, but it's worth a try.

How to change style of a default EditText

edittext_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/edittext_pressed" android:state_pressed="true" /> <!-- pressed -->
    <item android:drawable="@drawable/edittext_disable" android:state_enabled="false" /> <!-- focused -->
    <item android:drawable="@drawable/edittext_default" /> <!-- default -->
</selector>

edittext_default.xml

       <?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item>
        <shape android:shape="rectangle" >
            <solid android:color="#BBDEFB" />
            <padding android:bottom="2dp" />
        </shape>
    </item>
    <item android:bottom="5dp">
        <shape android:shape="rectangle" >
            <solid android:color="#fff" />

            <padding
                android:left="0dp"
                android:right="0dp" />
        </shape>
    </item>
    <item>
        <shape android:shape="rectangle" >
            <solid android:color="#fff" />
        </shape>
    </item>
</layer-list>

edittext_pressed.xml

 <?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item>
        <shape android:shape="rectangle" >
            <solid android:color="#00f" />
            <padding android:bottom="2dp" />
        </shape>
    </item>
    <item android:bottom="5dp">
        <shape android:shape="rectangle" >
            <solid android:color="#fff" />

            <padding
                android:left="0dp"
                android:right="0dp" />
        </shape>
    </item>
    <item>
        <shape android:shape="rectangle" >
            <solid android:color="#fff" />
        </shape>
    </item>

</layer-list>

edittext_disable.xml

    <?xml version="1.0" encoding="utf-8"?>
    <layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
        <item>
            <shape android:shape="rectangle" >
                <solid android:color="#aaaaaa" />
                <padding android:bottom="2dp" />
            </shape>
        </item>
        <item android:bottom="5dp">
            <shape android:shape="rectangle" >
                <solid android:color="#fff" />

                <padding
                    android:left="0dp"
                    android:right="0dp" />
            </shape>
        </item>
        <item>
            <shape android:shape="rectangle" >
                <solid android:color="#fff" />
            </shape>
        </item>

    </layer-list>

it works fine without nine-patch Api 10+ enter image description here

How to add a "open git-bash here..." context menu to the windows explorer?

When you install git-scm found in "https://git-scm.com/downloads" uncheck the "Only show new options" located at the very bottom of the installation window

Make sure you check

  • Windows Explorer integration
    • Git Bash Here
    • Git GUI Here

Click Next and you're good to go!

How do I get the first element from an IEnumerable<T> in .net?

Well, you didn't specify which version of .Net you're using.

Assuming you have 3.5, another way is the ElementAt method:

var e = enumerable.ElementAt(0);

Zsh: Conda/Pip installs command not found

You should do the following:
1. /home/$USER/anaconda/bin/conda init zsh (or /home/$USER/miniconda3/bin/conda init zsh if you use miniconda)
2. source ~/.zshrc (or just reopen terminal)

Why this answer is better than others?

  • You shouldn't reinvent the wheel: there is already command in conda to activate, all you need to do is to call conda with full path
  • Maybe ~/.bash_profile doesn't exist (my case, only ~/.bashrc)
  • You can have bash-specific config inside ~/.bash_profile
  • You don't need manually paste and export any pathes

Most efficient way to concatenate strings?

It would depend on the code. StringBuilder is more efficient generally, but if you're only concatenating a few strings and doing it all in one line, code optimizations will likely take care of it for you. It's important to think about how the code looks too: for larger sets StringBuilder will make it easier to read, for small ones StringBuilder will just add needless clutter.

Swift days between two NSDates

You have to consider the time difference as well. For example if you compare the dates 2015-01-01 10:00 and 2015-01-02 09:00, days between those dates will return as 0 (zero) since the difference between those dates is less than 24 hours (it's 23 hours).

If your purpose is to get the exact day number between two dates, you can work around this issue like this:

// Assuming that firstDate and secondDate are defined
// ...

let calendar = NSCalendar.currentCalendar()

// Replace the hour (time) of both dates with 00:00
let date1 = calendar.startOfDayForDate(firstDate)
let date2 = calendar.startOfDayForDate(secondDate)

let flags = NSCalendarUnit.Day
let components = calendar.components(flags, fromDate: date1, toDate: date2, options: [])

components.day  // This will return the number of day(s) between dates

Swift 3 and Swift 4 Version

let calendar = Calendar.current

// Replace the hour (time) of both dates with 00:00
let date1 = calendar.startOfDay(for: firstDate)
let date2 = calendar.startOfDay(for: secondDate)

let components = calendar.dateComponents([.day], from: date1, to: date2)

Pretty graphs and charts in Python

I used pychart and thought it was very straightforward.

http://home.gna.org/pychart/

It's all native python and does not have a busload of dependencies. I'm sure matplotlib is lovely but I'd be downloading and installing for days and I just want one measley bar chart!

It doesn't seem to have been updated in a few years but hey it works!

How can I disable the Maven Javadoc plugin from the command line?

You can use the maven.javadoc.skip property to skip execution of the plugin, going by the Mojo's javadoc. You can specify the value as a Maven property:

<properties>
    <maven.javadoc.skip>true</maven.javadoc.skip>
</properties>

or as a command-line argument: -Dmaven.javadoc.skip=true, to skip generation of the Javadocs.

WCF error - There was no endpoint listening at

You can solve the issue by clearing value of address in endpoint tag in web.config:

<endpoint address="" name="wsHttpEndpoint"  .......           />

Is there a way to list open transactions on SQL Server 2000 database?

Use this because whenever transaction open more than one transaction then below will work SELECT * FROM sys.sysprocesses WHERE open_tran <> 0

No String-argument constructor/factory method to deserialize from String value ('')

This exception says that you are trying to deserialize the object "Address" from string "\"\"" instead of an object description like "{…}". The deserializer can't find a constructor of Address with String argument. You have to replace "" by {} to avoid this error.

SQL Server database restore error: specified cast is not valid. (SqlManagerUI)

Could be because of restoring SQL Server 2012 version backup file into SQL Server 2008 R2 or even less.

Remove multiple objects with rm()

Another variation you can try is(expanding @mnel's answer) if you have many temp'x'.

here "n" could be the number of temp variables present

rm(list = c(paste("temp",c(1:n),sep="")))

xsd:boolean element type accept "true" but not "True". How can I make it accept it?

If you're on Linux, or have cygwin available on Windows, you can run the input XML through a simple sed script that will replace <Active>True</Active> with <Active>true</Active>, like so:

cat <your XML file> | sed 'sX<Active>True</Active>X<Active>true</Active>X' | xmllint --schema -

If you're not, you can still use a non-validating xslt pocessor (xalan, saxon etc.) to run a simple xslt transformation on the input, and only then pipe it to xmllint.

What the xsl should contain something like below, for the example you listed above (the xslt processor should be 2.0 capable):

<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
    <xsl:output method="xml" indent="yes"/>
    <xsl:template match="/">
    <xsl:for-each select="XML">
        <xsl:for-each select="Active">
            <xsl:value-of select=" replace(current(), 'True','true')"/>
        </xsl:for-each>
    </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>

javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found

I use this class and have no problem.

public class WCFs
{
    // https://192.168.30.8/myservice.svc?wsdl
    private static final String NAMESPACE = "http://tempuri.org/";
    private static final String URL = "192.168.30.8";
    private static final String SERVICE = "/myservice.svc?wsdl";
    private static String SOAP_ACTION = "http://tempuri.org/iWCFserviceMe/";


    public static Thread myMethod(Runnable rp)
    {
        String METHOD_NAME = "myMethod";

        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

        request.addProperty("Message", "Https WCF Running...");
        return _call(rp,METHOD_NAME, request);
    }

    protected static HandlerThread _call(final RunProcess rp,final String METHOD_NAME, SoapObject soapReq)
    {
        final SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        int TimeOut = 5*1000;

        envelope.dotNet = true;
        envelope.bodyOut = soapReq;
        envelope.setOutputSoapObject(soapReq);

        final HttpsTransportSE httpTransport_net = new HttpsTransportSE(URL, 443, SERVICE, TimeOut);

        try
        {
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() // use this section if crt file is handmake
            {
                @Override
                public boolean verify(String hostname, SSLSession session)
                {
                    return true;
                }
            });

            KeyStore k = getFromRaw(R.raw.key, "PKCS12", "password");
            ((HttpsServiceConnectionSE) httpTransport_net.getServiceConnection()).setSSLSocketFactory(getSSLSocketFactory(k, "SSL"));


        }
        catch(Exception e){}

        HandlerThread thread = new HandlerThread("wcfTd"+ Generator.getRandomNumber())
        {
            @Override
            public void run()
            {
                Handler h = new Handler(Looper.getMainLooper());
                Object response = null;

                for(int i=0; i<4; i++)
                {
                    response = send(envelope, httpTransport_net , METHOD_NAME, null);

                    try
                    {if(Thread.currentThread().isInterrupted()) return;}catch(Exception e){}

                    if(response != null)
                        break;

                    ThreadHelper.threadSleep(250);
                }

                if(response != null)
                {
                    if(rp != null)
                    {
                        rp.setArguments(response.toString());
                        h.post(rp);
                    }
                }
                else
                {
                    if(Thread.currentThread().isInterrupted())
                        return;

                    if(rp != null)
                    {
                        rp.setExceptionState(true);
                        h.post(rp);
                    }
                }

                ThreadHelper.stopThread(this);
            }
        };

        thread.start();

        return thread;
    }


    private static Object send(SoapSerializationEnvelope envelope, HttpTransportSE androidHttpTransport, String METHOD_NAME, List<HeaderProperty> headerList)
    {
        try
        {
            if(headerList != null)
                androidHttpTransport.call(SOAP_ACTION + METHOD_NAME, envelope, headerList);
            else
                androidHttpTransport.call(SOAP_ACTION + METHOD_NAME, envelope);

            Object res = envelope.getResponse();

            if(res instanceof SoapPrimitive)
                return (SoapPrimitive) envelope.getResponse();
            else if(res instanceof SoapObject)
                return ((SoapObject) envelope.getResponse());
        }
        catch(Exception e)
        {}

        return null;
    }

    public static KeyStore getFromRaw(@RawRes int id, String algorithm, String filePassword)
    {
        try
        {
            InputStream inputStream = ResourceMaster.openRaw(id);
            KeyStore keystore = KeyStore.getInstance(algorithm);
            keystore.load(inputStream, filePassword.toCharArray());
            inputStream.close();

            return keystore;
        }
        catch(Exception e)
        {}

        return null;
    }

    public static SSLSocketFactory getSSLSocketFactory(KeyStore trustKey, String SSLAlgorithm)
    {
        try
        {
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            tmf.init(trustKey);

            SSLContext context = SSLContext.getInstance(SSLAlgorithm);//"SSL" "TLS"
            context.init(null, tmf.getTrustManagers(), null);

            return context.getSocketFactory();
        }
        catch(Exception e){}

        return null;
    }
}

What is the use of the @Temporal annotation in Hibernate?

use this

@Temporal(TemporalType.TIMESTAMP)
@Column(name="create_date")
private Calendar createDate;

public Calendar getCreateDate() {
    return createDate;
}

public void setCreateDate(Calendar createDate) {
    this.createDate = createDate;
}

How can I use jQuery in Greasemonkey?

If you are using chrome you have to opt for an alternative as Chromium does not support @require.

Source: The Chromium Project - User scripts

More details and alternatives on How can I use jQuery in Greasemonkey scripts in Google Chrome?

Expected corresponding JSX closing tag for input Reactjs

You need to close the input element with /> at the end. In React, we have to close every element. Your code should be:

<input id="icon_prefix" type="text" class="validate/">

Replace multiple strings with multiple other strings

String.prototype.replaceSome = function() {
    var replaceWith = Array.prototype.pop.apply(arguments),
        i = 0,
        r = this,
        l = arguments.length;
    for (;i<l;i++) {
        r = r.replace(arguments[i],replaceWith);
    }
    return r;
}

/* replaceSome method for strings it takes as ,much arguments as we want and replaces all of them with the last argument we specified 2013 CopyRights saved for: Max Ahmed this is an example:

var string = "[hello i want to 'replace x' with eat]";
var replaced = string.replaceSome("]","[","'replace x' with","");
document.write(string + "<br>" + replaced); // returns hello i want to eat (without brackets)

*/

jsFiddle: http://jsfiddle.net/CPj89/

CSS Equivalent of the "if" statement

I would argue that you can use if statements in CSS. Although they aren't worded as such. In the example below, I've said that if the check-box is checked I want the background changed to white. If you want to see a working example check out www.armstrongdes.com. I built this for a client. Re size your window so that the mobile navigation takes over and click the nav button. All CSS. I think it's safe to say this concept could be used for many things.

     #sidebartoggler:checked + .page-wrap .hamb {
        background: #fff;
      }

// example set as if statement sudo code.

if (sidebaretoggler is checked == true) {
set the background color of .hamb to white;
}

SQL - How to find the highest number in a column?

select * from tablename order by ID DESC

that will give you row with id 22

Get IPv4 addresses from Dns.GetHostEntry()

    public Form1()
    {
        InitializeComponent();

        string myHost = System.Net.Dns.GetHostName();
        string myIP = null;

        for (int i = 0; i <= System.Net.Dns.GetHostEntry(myHost).AddressList.Length - 1; i++)
        {
            if (System.Net.Dns.GetHostEntry(myHost).AddressList[i].IsIPv6LinkLocal == false)
            {
                myIP = System.Net.Dns.GetHostEntry(myHost).AddressList[i].ToString();
            }
        }
    }

Declare myIP and myHost in public Variable and use in any function of the form.

Is it correct to use alt tag for an anchor link?

"title" is widely implemented in browsers. Try:

<a href="#" title="hello">asf</a>

Split long commands in multiple lines through Windows batch file

You can break up long lines with the caret ^ as long as you remember that the caret and the newline following it are completely removed. So, if there should be a space where you're breaking the line, include a space. (More on that below.)

Example:

copy file1.txt file2.txt

would be written as:

copy file1.txt^
 file2.txt

PHP - Modify current object in foreach loop

Surely using array_map and if using a container implementing ArrayAccess to derive objects is just a smarter, semantic way to go about this?

Array map semantics are similar across most languages and implementations that I've seen. It's designed to return a modified array based upon input array element (high level ignoring language compile/runtime type preference); a loop is meant to perform more logic.

For retrieving objects by ID / PK, depending upon if you are using SQL or not (it seems suggested), I'd use a filter to ensure I get an array of valid PK's, then implode with comma and place into an SQL IN() clause to return the result-set. It makes one call instead of several via SQL, optimising a bit of the call->wait cycle. Most importantly my code would read well to someone from any language with a degree of competence and we don't run into mutability problems.

<?php

$arr = [0,1,2,3,4];
$arr2 = array_map(function($value) { return is_int($value) ? $value*2 : $value; }, $arr);
var_dump($arr);
var_dump($arr2);

vs

<?php

$arr = [0,1,2,3,4];
foreach($arr as $i => $item) {
    $arr[$i] = is_int($item) ? $item * 2 : $item;
}
var_dump($arr);

If you know what you are doing will never have mutability problems (bearing in mind if you intend upon overwriting $arr you could always $arr = array_map and be explicit.

Should ol/ul be inside <p> or outside?

The second. The first is invalid.

  • A paragraph cannot contain a list.
  • A list cannot contain a paragraph unless that paragraph is contained entirely within a single list item.

A browser will handle it like so:

<p>tetxtextextete 
<!-- Start of paragraph -->
<ol>
<!-- Start of ordered list. Paragraphs cannot contain lists. Insert </p> -->
<li>first element</li></ol>
<!-- A list item element. End of list -->
</p>
<!-- End of paragraph, but not inside paragraph, discard this tag to recover from the error -->
<p>other textetxet</p>
<!-- Another paragraph -->

Get loop count inside a Python FOR loop

Try using itertools.count([n])

Date constructor returns NaN in IE, but works in Firefox and Chrome

I tried all the above solution but nothing worked for me. I did some brainstorming and found this and worked fine in IE11 as well.

_x000D_
_x000D_
value="2020-08-10 05:22:44.0";
var date=new Date(value.replace(" ","T")).$format("d/m/yy h:i:s");
console.log(date);
_x000D_
_x000D_
_x000D_

if $format is not working for you use format only.

Annotation @Transactional. How to rollback?

or programatically

TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

Get HTML code using JavaScript with a URL

There is a tutorial on how to use Ajax here: https://www.w3schools.com/xml/ajax_intro.asp

This is an example code taken from that tutorial:

<html>

<head>
    <script type="text/javascript">
        function loadXMLDoc()
        {
            var xmlhttp;
            if (window.XMLHttpRequest)
            {
              // Code for Internet Explorer 7+, Firefox, Chrome, Opera, and Safari
              xmlhttp = new XMLHttpRequest();
            }
            else
            {
                // Code for Internet Explorer 6 and Internet Explorer 5
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange=function()
            {
                if (xmlhttp.readyState==4 && xmlhttp.status==200)
                {
                    document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
                }
            }
            xmlhttp.open("GET", "ajax_info.txt", true);
            xmlhttp.send();
        }
    </script>
</head>

<body>
    <div id="myDiv"><h2>Let AJAX change this text</h2></div>
    <button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>

</html>

How to bind DataTable to Datagrid

In cs file:

    private DataTable _dataTable;

    public DataTable DataTable
    {
        get { return _dataTable; }
        set { _dataTable = value; }
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        this._dataTable = new DataTable("table");

        this._dataTable.Columns.Add("col0");
        this._dataTable.Columns.Add("col1");
        this._dataTable.Columns.Add("col2");

        this._dataTable.Rows.Add("data00", "data01", "data02");
        this._dataTable.Rows.Add("data10", "data11", "data22");
        this._dataTable.Rows.Add("data20", "data21", "data22");

        this.grid1.DataContext = this;

    }

In Xaml file:

<DataGrid x:Name="grid1"
          Margin="10"
          AutoGenerateColumns="True"
          ItemsSource="{Binding Path=DataTable, Mode=TwoWay}" />

how to fire event on file select

<input id="fusk" type="file" name="upload" style="display: none;"
    onChange=" document.getElementById('myForm').submit();"
>

How do I replace NA values with zeros in an R dataframe?

With dplyr 0.5.0, you can use coalesce function which can be easily integrated into %>% pipeline by doing coalesce(vec, 0). This replaces all NAs in vec with 0:

Say we have a data frame with NAs:

library(dplyr)
df <- data.frame(v = c(1, 2, 3, NA, 5, 6, 8))

df
#    v
# 1  1
# 2  2
# 3  3
# 4 NA
# 5  5
# 6  6
# 7  8

df %>% mutate(v = coalesce(v, 0))
#   v
# 1 1
# 2 2
# 3 3
# 4 0
# 5 5
# 6 6
# 7 8

File Upload in WebView

This solution also works for Honeycomb and Ice Cream Sandwich. Seems like Google introduced a cool new feature (accept attribute) and forgot to to implement an overload for backwards compatibility.

protected class CustomWebChromeClient extends WebChromeClient
{
    // For Android 3.0+
    public void openFileChooser( ValueCallback<Uri> uploadMsg, String acceptType ) 
    {  
        context.mUploadMessage = uploadMsg;  
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);  
        i.addCategory(Intent.CATEGORY_OPENABLE);  
        i.setType("image/*");  
        context.startActivityForResult( Intent.createChooser( i, "File Chooser" ), MainActivity.FILECHOOSER_RESULTCODE );  
    }

    // For Android < 3.0
    public void openFileChooser( ValueCallback<Uri> uploadMsg ) 
    {
        openFileChooser( uploadMsg, "" );
    }
}

NoSuchMethodError in javax.persistence.Table.indexes()[Ljavax/persistence/Index

You probablly have 2 different versions of hibernate-jpa-api on the classpath. To check that run:

mvn dependency:tree >dep.txt

Then search if there are hibernate-jpa-2.0-api and hibernate-jpa-2.1-api. And exclude the excess one.

How to fix "unable to write 'random state' " in openssl

What is the instanceof operator in JavaScript?

On the question "When is it appropriate and when not?", my 2 cents:

instanceof is rarely useful in production code, but useful in tests where you want to assert that your code returns / creates objects of the correct types. By being explicit about the kinds of objects your code is returning / creating, your tests become more powerful as a tool for understanding and documenting your code.

Laravel - Model Class not found

As @bulk said, it uses namespaces.

I recommend you to start using an IDE, it will suggest you to import all the required namespaces (\App\Post in this case).

Indent multiple lines quickly in vi

In addition to the answer already given and accepted, it is also possible to place a marker and then indent everything from the current cursor to the marker.

Thus, enter ma where you want the top of your indented block, cursor down as far as you need and then type >'a (note that "a" can be substituted for any valid marker name). This is sometimes easier than 5>> or vjjj>.

Hiding the scroll bar on an HTML page

This works for me with simple CSS properties:

.container {
    -ms-overflow-style: none;  // Internet Explorer 10+
    scrollbar-width: none;  // Firefox
}
.container::-webkit-scrollbar { 
    display: none;  // Safari and Chrome
}

For older versions of Firefox, use: overflow: -moz-scrollbars-none;

Certificate is trusted by PC but not by Android

With Godaddy certs you most likely will have a domain.key, gd_bundle_something.crt and (random alphanumeric string) 4923hg4k23jh4.crt

You'll need to: cat gd_bundle_something.crt >> 4923hg4k23jh4.crt

And then, on nginx, you will use

ssl                  on;
ssl_certificate      /etc/ssl/certs/4923hg4k23jh4.crt;
ssl_certificate_key  /etc/ssl/certs/domain.key;

ActiveX component can't create object

It turns out to get this application working under VBScript, I had to do two things.

  1. Run RegAsm.exe to register the DLLs.
  2. Run the C:\Windows\SysWOW64\cscript.exe to run my VBScript.

If these don't work, check out the other answer here about enabling 32-bit applications in IIS.

How to overcome "datetime.datetime not JSON serializable"?

I may not 100% correct but, this is the simple way to do serialize

#!/usr/bin/python
import datetime,json

sampledict = {}
sampledict['a'] = "some string"
sampledict['b'] = datetime.datetime.now()

print sampledict   # output : {'a': 'some string', 'b': datetime.datetime(2017, 4, 15, 5, 15, 34, 652996)}

#print json.dumps(sampledict)

'''
output : 

Traceback (most recent call last):
  File "./jsonencodedecode.py", line 10, in <module>
    print json.dumps(sampledict)
  File "/usr/lib/python2.7/json/__init__.py", line 244, in dumps
    return _default_encoder.encode(obj)
  File "/usr/lib/python2.7/json/encoder.py", line 207, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/usr/lib/python2.7/json/encoder.py", line 270, in iterencode
    return _iterencode(o, 0)
  File "/usr/lib/python2.7/json/encoder.py", line 184, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: datetime.datetime(2017, 4, 15, 5, 16, 17, 435706) is not JSON serializable


'''

sampledict['b'] = datetime.datetime.now().strftime("%B %d, %Y %H:%M %p")

afterdump = json.dumps(sampledict)

print afterdump  #output : {"a": "some string", "b": "April 15, 2017 05:18 AM"}

print type(afterdump) #<type 'str'>


afterloads = json.loads(afterdump) 

print afterloads # output : {u'a': u'some string', u'b': u'April 15, 2017 05:18 AM'}


print type(afterloads) # output :<type 'dict'> 

Does Java SE 8 have Pairs or Tuples?

Vavr (formerly called Javaslang) (http://www.vavr.io) provides tuples (til size of 8) as well. Here is the javadoc: https://static.javadoc.io/io.vavr/vavr/0.9.0/io/vavr/Tuple.html.

This is a simple example:

Tuple2<Integer, String> entry = Tuple.of(1, "A");

Integer key = entry._1;
String value = entry._2;

Why JDK itself did not come with a simple kind of tuples til now is a mystery to me. Writing wrapper classes seems to be an every day business.

Is it possible to set UIView border properties from interface builder?

You can make a category of UIView and add this in .h file of category

@property (nonatomic) IBInspectable UIColor *borderColor;
@property (nonatomic) IBInspectable CGFloat borderWidth;
@property (nonatomic) IBInspectable CGFloat cornerRadius;

Now add this in .m file

@dynamic borderColor,borderWidth,cornerRadius;

and this as well in . m file

-(void)setBorderColor:(UIColor *)borderColor{
    [self.layer setBorderColor:borderColor.CGColor];
}

-(void)setBorderWidth:(CGFloat)borderWidth{
    [self.layer setBorderWidth:borderWidth];
}

-(void)setCornerRadius:(CGFloat)cornerRadius{
    [self.layer setCornerRadius:cornerRadius];
}

now you will see this in your storyboard for all UIView subclasses (UILabel, UITextField, UIImageView etc)

enter image description here

Thats it.. No Need to import category anywhere, just add the category's files in the project and see these properties in the storyboard.

Concatenate in jQuery Selector

There is nothing wrong with syntax of

$('#part' + number).html(text);

jQuery accepts a String (usually a CSS Selector) or a DOM Node as parameter to create a jQuery Object.

In your case you should pass a String to $() that is

$(<a string>)

Make sure you have access to the variables number and text.

To test do:

function(){
    alert(number + ":" + text);//or use console.log(number + ":" + text)
    $('#part' + number).html(text);
}); 

If you see you dont have access, pass them as parameters to the function, you have to include the uual parameters for $.get and pass the custom parameters after them.

Handle JSON Decode Error when nothing returned

If you don't mind importing the json module, then the best way to handle it is through json.JSONDecodeError (or json.decoder.JSONDecodeError as they are the same) as using default errors like ValueError could catch also other exceptions not necessarily connected to the json decode one.

from json.decoder import JSONDecodeError


try:
    qByUser = byUsrUrlObj.read()
    qUserData = json.loads(qByUser).decode('utf-8')
    questionSubjs = qUserData["all"]["questions"]
except JSONDecodeError as e:
    # do whatever you want

//EDIT (Oct 2020):

As @Jacob Lee noted in the comment, there could be the basic common TypeError raised when the JSON object is not a str, bytes, or bytearray. Your question is about JSONDecodeError, but still it is worth mentioning here as a note; to handle also this situation, but differentiate between different issues, the following could be used:

from json.decoder import JSONDecodeError


try:
    qByUser = byUsrUrlObj.read()
    qUserData = json.loads(qByUser).decode('utf-8')
    questionSubjs = qUserData["all"]["questions"]
except JSONDecodeError as e:
    # do whatever you want
except TypeError as e:
    # do whatever you want in this case

Java Program to test if a character is uppercase/lowercase/number/vowel

You appear to have upper and lowercase back to front. A-Z would be upper, a-z would be lower. While not exactly efficient - with the inverted case exception, I think it should output correctly.

String.Format like functionality in T-SQL?

Here is my version. Can be extended to accommodate more number of parameters and can extend formatting based on type. Currently only date and datetime types are formatted.

Example:

select dbo.FormatString('some string %s some int %s date %s','"abcd"',100,cast(getdate() as date),DEFAULT,DEFAULT)
select dbo.FormatString('some string %s some int %s date time %s','"abcd"',100,getdate(),DEFAULT,DEFAULT)

Output:

some string "abcd" some int 100 date 29-Apr-2017
some string "abcd" some int 100 date time 29-Apr-2017 19:40

Functions:

create function dbo.FormatValue(@param sql_variant)
returns nvarchar(100)
begin
/*
Tejasvi Hegde, 29-April-2017
Can extend formatting here.
*/
    declare @result nvarchar(100)

    if (SQL_VARIANT_PROPERTY(@param,'BaseType') in ('date'))
    begin
       select @result = REPLACE(CONVERT(CHAR(11), @param, 106), ' ', '-')
    end
    else  if (SQL_VARIANT_PROPERTY(@param,'BaseType') in ('datetime','datetime2'))
    begin
       select @result = REPLACE(CONVERT(CHAR(11), @param, 106), ' ', '-')+' '+CONVERT(VARCHAR(5),@param,108)
    end
    else
    begin
       select @result = cast(@param as nvarchar(100))
    end
    return @result

/*
BaseType:
bigint
binary
char
date
datetime
datetime2
datetimeoffset
decimal
float
int
money
nchar
numeric
nvarchar
real
smalldatetime
smallint
smallmoney
time
tinyint
uniqueidentifier
varbinary
varchar
*/   

end;


create function dbo.FormatString(
    @format nvarchar(4000)
    ,@param1 sql_variant = null
    ,@param2 sql_variant = null
    ,@param3 sql_variant = null
    ,@param4 sql_variant = null
    ,@param5 sql_variant = null
    )
returns nvarchar(4000)
begin
/*
Tejasvi Hegde, 29-April-2017

select dbo.FormatString('some string value %s some int %s date %s','"abcd"',100,cast(getdate() as date),DEFAULT,DEFAULT)
select dbo.FormatString('some string value %s some int %s date time %s','"abcd"',100,getdate(),DEFAULT,DEFAULT)
*/

    declare @result nvarchar(4000)

    select @param1 = dbo.formatValue(@param1)
    ,@param2 = dbo.formatValue(@param2)
    ,@param3 = dbo.formatValue(@param3)
    ,@param4 = dbo.formatValue(@param4)
    ,@param5 = dbo.formatValue(@param5)

    select @param2 = cast(@param2 as nvarchar)
    EXEC xp_sprintf @result OUTPUT,@format , @param1, @param2, @param3, @param4, @param5

    return @result

end;

How do you create a dropdownlist from an enum in ASP.NET MVC?

I bumped into the same problem, found this question, and thought that the solution provided by Ash wasn't what I was looking for; Having to create the HTML myself means less flexibility compared to the built-in Html.DropDownList() function.

Turns out C#3 etc. makes this pretty easy. I have an enum called TaskStatus:

var statuses = from TaskStatus s in Enum.GetValues(typeof(TaskStatus))
               select new { ID = s, Name = s.ToString() };
ViewData["taskStatus"] = new SelectList(statuses, "ID", "Name", task.Status);

This creates a good ol' SelectList that can be used like you're used to in the view:

<td><b>Status:</b></td><td><%=Html.DropDownList("taskStatus")%></td></tr>

The anonymous type and LINQ makes this so much more elegant IMHO. No offence intended, Ash. :)

How do I escape a single quote ( ' ) in JavaScript?

The answer here is very simple:

You're already containing it in double quotes, so there's no need to escape it with \.

If you want to escape single quotes in a single quote string:

var string = 'this isn\'t a double quoted string';
var string = "this isn\"t a single quoted string";
//           ^         ^ same types, hence we need to escape it with a backslash

or if you want to escape \', you can escape the bashslash to \\ and the quote to \' like so:

var string = 'this isn\\\'t a double quoted string';
//                    vvvv
//                     \ ' (the escaped characters)

However, if you contain the string with a different quote type, you don't need to escape:

var string = 'this isn"t a double quoted string';
var string = "this isn't a single quoted string";
//           ^        ^ different types, hence we don't need escaping

What do 1.#INF00, -1.#IND00 and -1.#IND mean?

From IEEE floating-point exceptions in C++ :

This page will answer the following questions.

  • My program just printed out 1.#IND or 1.#INF (on Windows) or nan or inf (on Linux). What happened?
  • How can I tell if a number is really a number and not a NaN or an infinity?
  • How can I find out more details at runtime about kinds of NaNs and infinities?
  • Do you have any sample code to show how this works?
  • Where can I learn more?

These questions have to do with floating point exceptions. If you get some strange non-numeric output where you're expecting a number, you've either exceeded the finite limits of floating point arithmetic or you've asked for some result that is undefined. To keep things simple, I'll stick to working with the double floating point type. Similar remarks hold for float types.

Debugging 1.#IND, 1.#INF, nan, and inf

If your operation would generate a larger positive number than could be stored in a double, the operation will return 1.#INF on Windows or inf on Linux. Similarly your code will return -1.#INF or -inf if the result would be a negative number too large to store in a double. Dividing a positive number by zero produces a positive infinity and dividing a negative number by zero produces a negative infinity. Example code at the end of this page will demonstrate some operations that produce infinities.

Some operations don't make mathematical sense, such as taking the square root of a negative number. (Yes, this operation makes sense in the context of complex numbers, but a double represents a real number and so there is no double to represent the result.) The same is true for logarithms of negative numbers. Both sqrt(-1.0) and log(-1.0) would return a NaN, the generic term for a "number" that is "not a number". Windows displays a NaN as -1.#IND ("IND" for "indeterminate") while Linux displays nan. Other operations that would return a NaN include 0/0, 0*8, and 8/8. See the sample code below for examples.

In short, if you get 1.#INF or inf, look for overflow or division by zero. If you get 1.#IND or nan, look for illegal operations. Maybe you simply have a bug. If it's more subtle and you have something that is difficult to compute, see Avoiding Overflow, Underflow, and Loss of Precision. That article gives tricks for computing results that have intermediate steps overflow if computed directly.

Adding asterisk to required fields in Bootstrap 3

Use .form-group.required without the space.

.form-group.required .control-label:after {
  content:"*";
  color:red;
}

Edit:

For the checkbox you can use the pseudo class :not(). You add the required * after each label unless it is a checkbox

.form-group.required:not(.checkbox) .control-label:after, 
.form-group.required .text:after { /* change .text in whatever class of the text after the checkbox has */
   content:"*";
   color:red;
}

Note: not tested

You should use the .text class or target it otherwise probably, try this html:

<div class="form-group required">
   <label class="col-md-2 control-label">&#160;</label>
   <div class="col-md-4">
      <div class="checkbox">
         <label class='text'> <!-- use this class -->
            <input class="" id="id_tos" name="tos" required="required" type="checkbox" /> I have read and agree to the Terms of Service
         </label>
      </div>
   </div>
</div>

Ok third edit:

CSS back to what is was

.form-group.required .control-label:after { 
   content:"*";
   color:red;
}

HTML:

<div class="form-group required">
   <label class="col-md-2">&#160;</label> <!-- remove class control-label -->
   <div class="col-md-4">
      <div class="checkbox">
         <label class='control-label'> <!-- use this class as the red * will be after control-label -->
            <input class="" id="id_tos" name="tos" required="required" type="checkbox" /> I have read and agree to the Terms of Service
         </label>
      </div>
   </div>
</div>

Select * from subquery

You can select every column from that sub-query by aliasing it and adding the alias before the *:

SELECT t.*, a+b AS total_sum
FROM
(
   SELECT SUM(column1) AS a, SUM(column2) AS b
   FROM table
) t

Pandas convert string to int

You need add parameter errors='coerce' to function to_numeric:

ID = pd.to_numeric(ID, errors='coerce')

If ID is column:

df.ID = pd.to_numeric(df.ID, errors='coerce')

but non numeric are converted to NaN, so all values are float.

For int need convert NaN to some value e.g. 0 and then cast to int:

df.ID = pd.to_numeric(df.ID, errors='coerce').fillna(0).astype(np.int64)

Sample:

df = pd.DataFrame({'ID':['4806105017087','4806105017087','CN414149']})
print (df)
              ID
0  4806105017087
1  4806105017087
2       CN414149

print (pd.to_numeric(df.ID, errors='coerce'))
0    4.806105e+12
1    4.806105e+12
2             NaN
Name: ID, dtype: float64

df.ID = pd.to_numeric(df.ID, errors='coerce').fillna(0).astype(np.int64)
print (df)
              ID
0  4806105017087
1  4806105017087
2              0

EDIT: If use pandas 0.25+ then is possible use integer_na:

df.ID = pd.to_numeric(df.ID, errors='coerce').astype('Int64')
print (df)
              ID
0  4806105017087
1  4806105017087
2            NaN

How to change the URI (URL) for a remote Git repository?

For those who want to make this change from Visual Studio 2019

Open Team Explorer (Ctrl+M)

Home -> Settings

Git -> Repository Settings

Remotes -> Edit

enter image description here

"Uncaught TypeError: Illegal invocation" in Chrome

In your code you are assigning a native method to a property of custom object. When you call support.animationFrame(function () {}) , it is executed in the context of current object (ie support). For the native requestAnimationFrame function to work properly, it must be executed in the context of window.

So the correct usage here is support.animationFrame.call(window, function() {});.

The same happens with alert too:

var myObj = {
  myAlert : alert //copying native alert to an object
};

myObj.myAlert('this is an alert'); //is illegal
myObj.myAlert.call(window, 'this is an alert'); // executing in context of window 

Another option is to use Function.prototype.bind() which is part of ES5 standard and available in all modern browsers.

var _raf = window.requestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        window.oRequestAnimationFrame;

var support = {
   animationFrame: _raf ? _raf.bind(window) : null
};

What is the best way to remove the first element from an array?

You can't do it at all, let alone quickly. Arrays in Java are fixed size. Two things you could do are:

  1. Shift every element up one, then set the last element to null.
  2. Create a new array, then copy it.

You can use System.arraycopy for either of these. Both of these are O(n), since they copy all but 1 element.

If you will be removing the first element often, consider using LinkedList instead. You can use LinkedList.remove, which is from the Queue interface, for convenience. With LinkedList, removing the first element is O(1). In fact, removing any element is O(1) once you have a ListIterator to that position. However, accessing an arbitrary element by index is O(n).

Replace all 0 values to NA

Replacing all zeroes to NA:

df[df == 0] <- NA



Explanation

1. It is not NULL what you should want to replace zeroes with. As it says in ?'NULL',

NULL represents the null object in R

which is unique and, I guess, can be seen as the most uninformative and empty object.1 Then it becomes not so surprising that

data.frame(x = c(1, NULL, 2))
#   x
# 1 1
# 2 2

That is, R does not reserve any space for this null object.2 Meanwhile, looking at ?'NA' we see that

NA is a logical constant of length 1 which contains a missing value indicator. NA can be coerced to any other vector type except raw.

Importantly, NA is of length 1 so that R reserves some space for it. E.g.,

data.frame(x = c(1, NA, 2))
#    x
# 1  1
# 2 NA
# 3  2

Also, the data frame structure requires all the columns to have the same number of elements so that there can be no "holes" (i.e., NULL values).

Now you could replace zeroes by NULL in a data frame in the sense of completely removing all the rows containing at least one zero. When using, e.g., var, cov, or cor, that is actually equivalent to first replacing zeroes with NA and setting the value of use as "complete.obs". Typically, however, this is unsatisfactory as it leads to extra information loss.

2. Instead of running some sort of loop, in the solution I use df == 0 vectorization. df == 0 returns (try it) a matrix of the same size as df, with the entries TRUE and FALSE. Further, we are also allowed to pass this matrix to the subsetting [...] (see ?'['). Lastly, while the result of df[df == 0] is perfectly intuitive, it may seem strange that df[df == 0] <- NA gives the desired effect. The assignment operator <- is indeed not always so smart and does not work in this way with some other objects, but it does so with data frames; see ?'<-'.


1 The empty set in the set theory feels somehow related.
2 Another similarity with the set theory: the empty set is a subset of every set, but we do not reserve any space for it.

Javascript: How to loop through ALL DOM elements on a page?

i think this is really quick

document.querySelectorAll('body,body *').forEach(function(e) {

How can I divide one column of a data frame through another?

There are a plethora of ways in which this can be done. The problem is how to make R aware of the locations of the variables you wish to divide.

Assuming

d <- read.table(text = "263807.0    1582
196190.5    1016
586689.0    3479
")
names(d) <- c("min", "count2.freq")
> d
       min count2.freq
1 263807.0        1582
2 196190.5        1016
3 586689.0        3479

My preferred way

To add the desired division as a third variable I would use transform()

> d <- transform(d, new = min / count2.freq)
> d
       min count2.freq      new
1 263807.0        1582 166.7554
2 196190.5        1016 193.1009
3 586689.0        3479 168.6373

The basic R way

If doing this in a function (i.e. you are programming) then best to avoid the sugar shown above and index. In that case any of these would do what you want

## 1. via `[` and character indexes
d[, "new"] <- d[, "min"] / d[, "count2.freq"]

## 2. via `[` with numeric indices
d[, 3] <- d[, 1] / d[, 2]

## 3. via `$`
d$new <- d$min / d$count2.freq

All of these can be used at the prompt too, but which is easier to read:

d <- transform(d, new = min / count2.freq)

or

d$new <- d$min / d$count2.freq ## or any of the above examples

Hopefully you think like I do and the first version is better ;-)

The reason we don't use the syntactic sugar of tranform() et al when programming is because of how they do their evaluation (look for the named variables). At the top level (at the prompt, working interactively) transform() et al work just fine. But buried in function calls or within a call to one of the apply() family of functions they can and often do break.

Likewise, be careful using numeric indices (## 2. above); if you change the ordering of your data, you will select the wrong variables.

The preferred way if you don't need replacement

If you are just wanting to do the division (rather than insert the result back into the data frame, then use with(), which allows us to isolate the simple expression you wish to evaluate

> with(d, min / count2.freq)
[1] 166.7554 193.1009 168.6373

This is again much cleaner code than the equivalent

> d$min / d$count2.freq
[1] 166.7554 193.1009 168.6373

as it explicitly states that "using d, execute the code min / count2.freq. Your preference may be different to mine, so I have shown all options.

Python script to copy text to clipboard

GTK3:

#!/usr/bin/python3

from gi.repository import Gtk, Gdk


class Hello(Gtk.Window):

    def __init__(self):
        super(Hello, self).__init__()
        clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
        clipboard.set_text("hello world", -1)
        Gtk.main_quit()


def main():
    Hello()
    Gtk.main()

if __name__ == "__main__":
    main()

CSS / HTML Navigation and Logo on same line

You need to apply the logo class to the image...then float the ul

Codepen Demo

HTML

<img class="logo" src="http://i.imgur.com/hCrQkJi.png">

CSS

.navigation-bar ul {
  padding: 0px;
  margin: 0px;
  text-align: center;
  float: left;
  background: white;
}

Getting or changing CSS class property with Javascript using DOM style

Maybe better document.querySelectorAll(".col1") because getElementsByClassName doesn't works in IE 8 and querySelectorAll does (althought CSS2 selectors only).

https://developer.mozilla.org/en-US/docs/Web/API/document.getElementsByClassName https://developer.mozilla.org/en-US/docs/Web/API/Document.querySelectorAll

Eclipse error: indirectly referenced from required .class files?

In my case ,I created a project and made its minSdkVersion=9 and targetSdkVersion=17. I used automatically generated libs/android-support-v4.jar. I also had to make use of ActionBarActivity using android-support-v7-appcomapt.jar. So I just copied the android-support-v7-appcompat.jar file from android-sdk/extras/andrid/support/v7/appcompat/libs folder and pasted it to my project libs folder. And this caused the above error. So basically,I needed to put android-support-v4.jar file from android-sdk/extras/andrid/support/v7/appcompat/libs as well to my project libs folder. As per my knowledge the v7.jar file had dependencies on v4.jar file. So ,it needed it own v4.jarfile,instead of my project,automatically created v4.jar file.

socket.error:[errno 99] cannot assign requested address and namespace in python

This error will also appear if you try to connect to an exposed port from within a Docker container, when nothing is actively serving the port.

On a host where nothing is listening/bound to that port you'd get a No connection could be made because the target machine actively refused it error instead when making a request to a local URL that is not served, eg: localhost:5000. However, if you start a container that binds to the port, but there is no server running inside of it actually serving the port, any requests to that port on localhost will result in:

  • [Errno 99] Cannot assign requested address (if called from within the container), or
  • [Errno 0] Error (if called from outside of the container).

You can reproduce this error and the behaviour described above as follows:

Start a dummy container (note: this will pull the python image if not found locally):

docker run --name serv1 -p 5000:5000 -dit python

Then for [Errno 0] Error enter a Python console on host, while for [Errno 99] Cannot assign requested address access a Python console on the container by calling:

docker exec -it -u 0 serv1 python

And then in either case call:

import urllib.request
urllib.request.urlopen('https://localhost:5000')

I concluded with treating either of these errors as equivalent to No connection could be made because the target machine actively refused it rather than trying to fix their cause - although please advise if that's a bad idea.


I've spent over a day figuring this one out, given that all resources and answers I could find on the [Errno 99] Cannot assign requested address point in the direction of binding to an occupied port, connecting to an invalid IP, sysctl conflicts, docker network issues, TIME_WAIT being incorrect, and many more things. Therefore I wanted to leave this answer here, despite not being a direct answer to the question at hand, given that it can be a common cause for the error described in this question.

Find if a String is present in an array

Use Arrays.asList() to wrap the array in a List<String>, which does have a contains() method:

Arrays.asList(dan).contains(say.getText())

How to insert a column in a specific position in oracle without dropping and recreating the table?

Amit-

I don't believe you can add a column anywhere but at the end of the table once the table is created. One solution might be to try this:

CREATE TABLE MY_TEMP_TABLE AS
SELECT *
FROM TABLE_TO_CHANGE;

Drop the table you want to add columns to:

DROP TABLE TABLE_TO_CHANGE;

It's at the point you could rebuild the existing table from scratch adding in the columns where you wish. Let's assume for this exercise you want to add the columns named "COL2 and COL3".

Now insert the data back into the new table:

INSERT INTO TABLE_TO_CHANGE (COL1, COL2, COL3, COL4) 
SELECT COL1, 'Foo', 'Bar', COL4
FROM MY_TEMP_TABLE;

When the data is inserted into your "new-old" table, you can drop the temp table.

DROP TABLE MY_TEMP_TABLE;

This is often what I do when I want to add columns in a specific location. Obviously if this is a production on-line system, then it's probably not practical, but just one potential idea.

-CJ

Using $setValidity inside a Controller

This line:

myForm.file.$setValidity("myForm.file.$error.size", false);

Should be

$scope.myForm.file.$setValidity("size", false);

How can I change the width and height of slides on Slick Carousel?

You could also use this:

$('.slider').slick({
   //other settings ................
   respondTo: 'slider', //makes the slider to change width depending on the container it is in
   adaptiveHeight: true //makes the height change depending on the height of the element inside
})

Why am I getting AttributeError: Object has no attribute

This may also occur if your using slots in class and have not added this new attribute in slots yet.

class xyz(object):
"""
class description

"""

__slots__ = ['abc', 'ijk']

def __init__(self):
   self.abc = 1
   self.ijk = 2
   self.pqr = 6 # This will throw error 'AttributeError: <name_of_class_object> object has no attribute 'pqr'

PHP Parse error: syntax error, unexpected '?' in helpers.php 233

I had approximately the same problem with Laravel 5.5 on ubuntu, finally i've found a solution here to switch between the versions of php used by apache :

  1. sudo a2dismod php5
  2. sudo a2enmod php7.1
  3. sudo service apache2 restart

and it works

How to use the 'og' (Open Graph) meta tag for Facebook share

Use:

<!-- For Google -->
<meta name="description" content="" />
<meta name="keywords" content="" />

<meta name="author" content="" />
<meta name="copyright" content="" />
<meta name="application-name" content="" />

<!-- For Facebook -->
<meta property="og:title" content="" />
<meta property="og:type" content="article" />
<meta property="og:image" content="" />
<meta property="og:url" content="" />
<meta property="og:description" content="" />

<!-- For Twitter -->
<meta name="twitter:card" content="summary" />
<meta name="twitter:title" content="" />
<meta name="twitter:description" content="" />
<meta name="twitter:image" content="" />

Fill the content =" ... " according to the content of your page.

For more information, visit 18 Meta Tags Every Webpage Should Have in 2013.

PowerShell: Store Entire Text File Contents in Variable

On a side note, in PowerShell 3.0 you can use the Get-Content cmdlet with the new Raw switch:

$text = Get-Content .\file.txt -Raw 

JavaScript closure inside loops – simple practical example

  asyncIterable = [1,2,3,4,5,6,7,8];

  (async function() {
       for await (let num of asyncIterable) {
         console.log(num);
       }
    })();

How to draw a rounded Rectangle on HTML Canvas?

So this is based out of using lineJoin="round" and with the proper proportions, mathematics and logic I have been able to make this function, this is not perfect but hope it helps. If you want to make each corner have a different radius take a look at: https://p5js.org/reference/#/p5/rect

Here ya go:

CanvasRenderingContext2D.prototype.roundRect = function (x,y,width,height,radius) {
    radius = Math.min(Math.max(width-1,1),Math.max(height-1,1),radius);
    var rectX = x;
    var rectY = y;
    var rectWidth = width;
    var rectHeight = height;
    var cornerRadius = radius;

    this.lineJoin = "round";
    this.lineWidth = cornerRadius;
    this.strokeRect(rectX+(cornerRadius/2), rectY+(cornerRadius/2), rectWidth-cornerRadius, rectHeight-cornerRadius);
    this.fillRect(rectX+(cornerRadius/2), rectY+(cornerRadius/2), rectWidth-cornerRadius, rectHeight-cornerRadius);
    this.stroke();
    this.fill();
}

_x000D_
_x000D_
CanvasRenderingContext2D.prototype.roundRect = function (x,y,width,height,radius) {_x000D_
    radius = Math.min(Math.max(width-1,1),Math.max(height-1,1),radius);_x000D_
    var rectX = x;_x000D_
    var rectY = y;_x000D_
    var rectWidth = width;_x000D_
    var rectHeight = height;_x000D_
    var cornerRadius = radius;_x000D_
_x000D_
    this.lineJoin = "round";_x000D_
    this.lineWidth = cornerRadius;_x000D_
    this.strokeRect(rectX+(cornerRadius/2), rectY+(cornerRadius/2), rectWidth-cornerRadius, rectHeight-cornerRadius);_x000D_
    this.fillRect(rectX+(cornerRadius/2), rectY+(cornerRadius/2), rectWidth-cornerRadius, rectHeight-cornerRadius);_x000D_
    this.stroke();_x000D_
    this.fill();_x000D_
}_x000D_
    var canvas = document.getElementById("myCanvas");_x000D_
    var ctx = canvas.getContext('2d');_x000D_
function yop() {_x000D_
  ctx.clearRect(0,0,1000,1000)_x000D_
  ctx.fillStyle = "#ff0000";_x000D_
  ctx.strokeStyle = "#ff0000";  ctx.roundRect(Number(document.getElementById("myRange1").value),Number(document.getElementById("myRange2").value),Number(document.getElementById("myRange3").value),Number(document.getElementById("myRange4").value),Number(document.getElementById("myRange5").value));_x000D_
requestAnimationFrame(yop);_x000D_
}_x000D_
requestAnimationFrame(yop);
_x000D_
<input type="range" min="0" max="1000" value="10" class="slider" id="myRange1"><input type="range" min="0" max="1000" value="10" class="slider" id="myRange2"><input type="range" min="0" max="1000" value="200" class="slider" id="myRange3"><input type="range" min="0" max="1000" value="100" class="slider" id="myRange4"><input type="range" min="1" max="1000" value="50" class="slider" id="myRange5">_x000D_
<canvas id="myCanvas" width="1000" height="1000">_x000D_
</canvas>
_x000D_
_x000D_
_x000D_

Get time in milliseconds using C#

I used DateTime.Now.TimeOfDay.TotalMilliseconds (for current day), hope it helps you out as well.

How do I tell what type of value is in a Perl variable?

At some point I read a reasonably convincing argument on Perlmonks that testing the type of a scalar with ref or reftype is a bad idea. I don't recall who put the idea forward, or the link. Sorry.

The point was that in Perl there are many mechanisms that make it possible to make a given scalar act like just about anything you want. If you tie a filehandle so that it acts like a hash, the testing with reftype will tell you that you have a filehanle. It won't tell you that you need to use it like a hash.

So, the argument went, it is better to use duck typing to find out what a variable is.

Instead of:

sub foo {
    my $var = shift;
    my $type = reftype $var;

    my $result;
    if( $type eq 'HASH' ) {
        $result = $var->{foo};
    }
    elsif( $type eq 'ARRAY' ) {
        $result = $var->[3];
    }
    else {
        $result = 'foo';
    }

    return $result;
}

You should do something like this:

sub foo {
    my $var = shift;
    my $type = reftype $var;

    my $result;

    eval {
        $result = $var->{foo};
        1; # guarantee a true result if code works.
    }
    or eval { 
        $result = $var->[3];
        1;
    }
    or do {
        $result = 'foo';
    }

    return $result;
}

For the most part I don't actually do this, but in some cases I have. I'm still making my mind up as to when this approach is appropriate. I thought I'd throw the concept out for further discussion. I'd love to see comments.

Update

I realized I should put forward my thoughts on this approach.

This method has the advantage of handling anything you throw at it.

It has the disadvantage of being cumbersome, and somewhat strange. Stumbling upon this in some code would make me issue a big fat 'WTF'.

I like the idea of testing whether a scalar acts like a hash-ref, rather that whether it is a hash ref.

I don't like this implementation.

Why cannot cast Integer to String in java?

Use .toString instead like below:

String myString = myIntegerObject.toString();

Access Https Rest Service using Spring RestTemplate

Here is what I ended up with for the similar problem. The idea is the same as in @Avi's answer, but I also wanted to avoid the static "System.setProperty("https.protocols", "TLSv1");", so that any adjustments won't affect the system. Inspired by an answer from here http://www.coderanch.com/t/637177/Security/Disabling-handshake-message-Java

public class MyCustomClientHttpRequestFactory extends SimpleClientHttpRequestFactory {

@Override
protected void prepareConnection(HttpURLConnection connection, String httpMethod) {
    try {
        if (!(connection instanceof HttpsURLConnection)) {
            throw new RuntimeException("An instance of HttpsURLConnection is expected");
        }

        HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;

        TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }

                    public void checkClientTrusted(X509Certificate[] certs, String authType) {
                    }

                    public void checkServerTrusted(X509Certificate[] certs, String authType) {
                    }

                }
        };
        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        httpsConnection.setSSLSocketFactory(new MyCustomSSLSocketFactory(sslContext.getSocketFactory()));

        httpsConnection.setHostnameVerifier((hostname, session) -> true);

        super.prepareConnection(httpsConnection, httpMethod);
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}

/**
 * We need to invoke sslSocket.setEnabledProtocols(new String[] {"SSLv3"});
 * see http://www.oracle.com/technetwork/java/javase/documentation/cve-2014-3566-2342133.html (Java 8 section)
 */
private static class MyCustomSSLSocketFactory extends SSLSocketFactory {

    private final SSLSocketFactory delegate;

    public MyCustomSSLSocketFactory(SSLSocketFactory delegate) {
        this.delegate = delegate;
    }

    @Override
    public String[] getDefaultCipherSuites() {
        return delegate.getDefaultCipherSuites();
    }

    @Override
    public String[] getSupportedCipherSuites() {
        return delegate.getSupportedCipherSuites();
    }

    @Override
    public Socket createSocket(final Socket socket, final String host, final int port, final boolean autoClose) throws IOException {
        final Socket underlyingSocket = delegate.createSocket(socket, host, port, autoClose);
        return overrideProtocol(underlyingSocket);
    }

    @Override
    public Socket createSocket(final String host, final int port) throws IOException {
        final Socket underlyingSocket = delegate.createSocket(host, port);
        return overrideProtocol(underlyingSocket);
    }

    @Override
    public Socket createSocket(final String host, final int port, final InetAddress localAddress, final int localPort) throws IOException {
        final Socket underlyingSocket = delegate.createSocket(host, port, localAddress, localPort);
        return overrideProtocol(underlyingSocket);
    }

    @Override
    public Socket createSocket(final InetAddress host, final int port) throws IOException {
        final Socket underlyingSocket = delegate.createSocket(host, port);
        return overrideProtocol(underlyingSocket);
    }

    @Override
    public Socket createSocket(final InetAddress host, final int port, final InetAddress localAddress, final int localPort) throws IOException {
        final Socket underlyingSocket = delegate.createSocket(host, port, localAddress, localPort);
        return overrideProtocol(underlyingSocket);
    }

    private Socket overrideProtocol(final Socket socket) {
        if (!(socket instanceof SSLSocket)) {
            throw new RuntimeException("An instance of SSLSocket is expected");
        }
        ((SSLSocket) socket).setEnabledProtocols(new String[] {"SSLv3"});
        return socket;
    }
}
}

Automapper missing type map configuration or unsupported mapping - Error

Upgrade Automapper to version 6.2.2. It helped me

Using crontab to execute script every minute and another every 24 hours

every minute:

* * * * * /path/to/php /var/www/html/a.php

every 24hours (every midnight):

0 0 * * * /path/to/php /var/www/html/reset.php

See this reference for how crontab works: http://adminschoice.com/crontab-quick-reference, and this handy tool to build cron jobx: http://www.htmlbasix.com/crontab.shtml

How to use onBlur event on Angular2?

You can also use (focusout) event:

Use (eventName) for while binding event to DOM, basically () is used for event binding. Also you can use ngModel to get two way binding for your model. With the help of ngModel you can manipulate model variable value inside your component.

Do this in HTML file

<input type="text" [(ngModel)]="model" (focusout)="someMethodWithFocusOutEvent($event)">

And in your (component) .ts file

export class AppComponent { 
 model: any;
 constructor(){ }
 someMethodWithFocusOutEvent(){
   console.log('Your method called');
   // Do something here
 }
}

$(document).ready(function() is not working

Use:

jQuery(document).ready(function($){
    // code where you can use $ thanks to the parameter
});

Or its shorter version:

jQuery(function($){
    // code where you can use $ thanks to the parameter
});

How to easily duplicate a Windows Form in Visual Studio?

If you're working in VS 2019, take a few minutes to create an item template -- it's a perfect solution. How to: Create item templates

Not sure if it applies to earlier versions of VS.

gdb: how to print the current line or find the current line number?

Command where or frame can be used. where command will give more info with the function name

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

create table test (a int, b int , c int, d int);
alter table test drop column b, d;

Be aware that DROP COLUMN does not physically remove the data, and for fixed length types (int, numeric, float, datetime, uniqueidentifier etc) the space is consumed even for records added after the columns were dropped. To get rid of the wasted space do ALTER TABLE ... REBUILD.

Python string.replace regular expression

str.replace() v2|v3 does not recognize regular expressions.

To perform a substitution using a regular expression, use re.sub() v2|v3.

For example:

import re

line = re.sub(
           r"(?i)^.*interfaceOpDataFile.*$", 
           "interfaceOpDataFile %s" % fileIn, 
           line
       )

In a loop, it would be better to compile the regular expression first:

import re

regex = re.compile(r"^.*interfaceOpDataFile.*$", re.IGNORECASE)
for line in some_file:
    line = regex.sub("interfaceOpDataFile %s" % fileIn, line)
    # do something with the updated line

Is there a way to make a PowerShell script work by double clicking a .ps1 file?

I tried the top-most answers to this question, but encountered error messages. Then I found the answer here:

PowerShell says "execution of scripts is disabled on this system."

What worked well for me was to use this solution:

powershell -ExecutionPolicy Bypass -File script.ps1

You can paste that into a .bat file and double-click on it.

Can't include C++ headers like vector in Android NDK

It is possible. Here is some step by step:

In $PROJECT_DIR/jni/Application.mk:

APP_STL                 := stlport_static

I tried using stlport_shared, but no luck. Same with libstdc++.

In $PROJECT_DIR/jni/Android.mk:

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE    := hello-jni
LOCAL_SRC_FILES := hello-jni.cpp
LOCAL_LDLIBS    := -llog

include $(BUILD_SHARED_LIBRARY)

Nothing special here, but make sure your files are .cpp.

In $PROJECT_DIR/jni/hello-jni.cpp:

#include <string.h>
#include <jni.h>
#include <android/log.h>

#include <iostream>
#include <vector>


#define  LOG_TAG    "hellojni"
#define  LOGI(...)  __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__)
#define  LOGE(...)  __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__)


#ifdef __cplusplus
extern "C" {
#endif

// Comments omitted.    
void
Java_com_example_hellojni_HelloJni_stringFromJNI( JNIEnv* env,
                                                  jobject thiz )
{
    std::vector<std::string> vec;

    // Go ahead and do some stuff with this vector of strings now.
}

#ifdef __cplusplus
}
#endif

The only thing that bite me here was #ifdef __cplusplus.

Watch the directories.

To compile, use ndk-build clean && ndk-build.

Windows equivalent of OS X Keychain?

OS X keychain equivalent is Credential Manager in windows.

How to create a file in memory for user to download, but not through server?

If the file contains text data, a technique I use is to put the text into a textarea element and have the user select it (click in textarea then ctrl-A) then copy followed by a paste to a text editor.

How to set fake GPS location on IOS real device

Create a .GPX file with xcode, then specify your coordinates and when your device connected, hit the little arrow button and select your .GPX file. You can create multiple files and add lots of coordinates to single .GPX file in order to make some kind of route.

(WAMP/XAMP) send Mail using SMTP localhost

If any one of you are getting error like following after following answer given by Afwe Wef

 Warning: mail() [<a href='function.mail'>function.mail</a>]: SMTP server response:

 550 The address is not valid. in c:\wamp\www\email.php

Go to php.ini

; For Win32 only.
; http://php.net/sendmail-from
sendmail_from = [email protected]

Enter [email protected] as your email id which you used to configure the hMailserver in front of sendmail_from .

your problem will be solved.

Tested on Wamp server2.2(Apache 2.2.22, php 5.3.13) on windows 8

If you are also getting following error

"APPLICATION"   6364    "2014-03-24 13:13:33.979"   "SMTPDeliverer - Message 2: Relaying to host smtp.gmail.com."
"APPLICATION"   6364    "2014-03-24 13:13:34.415"   "SMTPDeliverer - Message 2: Message could not be delivered. Scheduling it for later delivery in 60 minutes."
"APPLICATION"   6364    "2014-03-24 13:13:34.430"   "SMTPDeliverer - Message 2: Message delivery thread completed."

You might have forgot to change the port from 25 to 465

php exec() is not executing the command

I already said that I was new to exec() function. After doing some more digging, I came upon 2>&1 which needs to be added at the end of command in exec().

Thanks @mattosmat for pointing it out in the comments too. I did not try this at once because you said it is a Linux command, I am on Windows.

So, what I have discovered, the command is actually executing in the back-end. That is why I could not see it actually running, which I was expecting to happen.

For all of you, who had similar problem, my advise is to use that command. It will point out all the errors and also tell you info/details about execution.

exec('some_command 2>&1', $output);
print_r($output);  // to see the response to your command

Thanks for all the help guys, I appreciate it ;)

Reading Excel file using node.js

Useful link

https://ciphertrick.com/read-excel-files-convert-json-node-js/

 var express = require('express'); 
    var app = express(); 
    var bodyParser = require('body-parser');
    var multer = require('multer');
    var xlstojson = require("xls-to-json-lc");
    var xlsxtojson = require("xlsx-to-json-lc");
    app.use(bodyParser.json());
    var storage = multer.diskStorage({ //multers disk storage settings
        destination: function (req, file, cb) {
            cb(null, './uploads/')
        },
        filename: function (req, file, cb) {
            var datetimestamp = Date.now();
            cb(null, file.fieldname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length -1])
        }
    });
    var upload = multer({ //multer settings
                    storage: storage,
                    fileFilter : function(req, file, callback) { //file filter
                        if (['xls', 'xlsx'].indexOf(file.originalname.split('.')[file.originalname.split('.').length-1]) === -1) {
                            return callback(new Error('Wrong extension type'));
                        }
                        callback(null, true);
                    }
                }).single('file');
    /** API path that will upload the files */
    app.post('/upload', function(req, res) {
        var exceltojson;
        upload(req,res,function(err){
            if(err){
                 res.json({error_code:1,err_desc:err});
                 return;
            }
            /** Multer gives us file info in req.file object */
            if(!req.file){
                res.json({error_code:1,err_desc:"No file passed"});
                return;
            }
            /** Check the extension of the incoming file and 
             *  use the appropriate module
             */
            if(req.file.originalname.split('.')[req.file.originalname.split('.').length-1] === 'xlsx'){
                exceltojson = xlsxtojson;
            } else {
                exceltojson = xlstojson;
            }
            try {
                exceltojson({
                    input: req.file.path,
                    output: null, //since we don't need output.json
                    lowerCaseHeaders:true
                }, function(err,result){
                    if(err) {
                        return res.json({error_code:1,err_desc:err, data: null});
                    } 
                    res.json({error_code:0,err_desc:null, data: result});
                });
            } catch (e){
                res.json({error_code:1,err_desc:"Corupted excel file"});
            }
        })
    }); 
    app.get('/',function(req,res){
        res.sendFile(__dirname + "/index.html");
    });
    app.listen('3000', function(){
        console.log('running on 3000...');
    });

SELECT using 'CASE' in SQL

Try this.

SELECT 
  CASE 
     WHEN FRUIT = 'A' THEN 'APPLE'
     WHEN FRUIT = 'B' THEN 'BANANA'
     ELSE 'UNKNOWN FRUIT'
  END AS FRUIT
FROM FRUIT_TABLE;

How to convert std::string to LPCWSTR in C++ (Unicode)

string  myMessage="helloworld";
int len;
int slength = (int)myMessage.length() + 1;
len = MultiByteToWideChar(CP_ACP, 0, myMessage.c_str(), slength, 0, 0); 
wchar_t* buf = new wchar_t[len];
MultiByteToWideChar(CP_ACP, 0, myMessage.c_str(), slength, buf, len);
std::wstring r(buf);
 std::wstring stemp = r.C_str();
LPCWSTR result = stemp.c_str();

Get child node index

Object.defineProperties(Element.prototype,{
group : {
    value: function (str, context) {
        // str is valid css selector like :not([attr_name]) or .class_name
        var t = "to_select_siblings___";
        var parent = context ? context : this.parentNode;
        parent.setAttribute(t, '');
        var rez = document.querySelectorAll("[" + t + "] " + (context ? '' : ">") + this.nodeName + (str || "")).toArray();
        parent.removeAttribute(t);            
        return rez;  
    }
},
siblings: {
    value: function (str, context) {
        var rez=this.group(str,context);
        rez.splice(rez.indexOf(this), 1);
        return rez; 
    }
},
nth: {  
    value: function(str,context){
       return this.group(str,context).indexOf(this);
    }
}
}

Ex

/* html */
<ul id="the_ul">   <li></li> ....<li><li>....<li></li>   </ul>

 /*js*/
 the_ul.addEventListener("click",
    function(ev){
       var foo=ev.target;
       foo.setAttribute("active",true);
       foo.siblings().map(function(elm){elm.removeAttribute("active")});
       alert("a click on li" + foo.nth());
     });

How can I add a column that doesn't allow nulls in a Postgresql database?

Since rows already exist in the table, the ALTER statement is trying to insert NULL into the newly created column for all of the existing rows. You would have to add the column as allowing NULL, then fill the column with the values you want, and then set it to NOT NULL afterwards.

What does the shrink-to-fit viewport meta attribute do?

As stats on iOS usage, indicating that iOS 9.0-9.2.x usage is currently at 0.17%. If these numbers are truly indicative of global use of these versions, then it’s even more likely to be safe to remove shrink-to-fit from your viewport meta tag.

After 9.2.x. IOS remove this tag check on its' browser.

You can check this page https://www.scottohara.me/blog/2018/12/11/shrink-to-fit.html

Hide Signs that Meteor.js was Used

The amount of hacks you would need to go through to completely hide the fact your site is built by Meteor.js is absolutely ridiculous. You would have to strip essentially all core functionality and just serve straight up html, completely defeating the purpose of using the framework anyway.

That being said, I suggest looking at buildwith.com

You enter a url, and it reveals a ton of information about a site. If you only need to "fool" engines like this, there may be simple solutions.

Call japplet from jframe

First of all, Applets are designed to be run from within the context of a browser (or applet viewer), they're not really designed to be added into other containers.

Technically, you can add a applet to a frame like any other component, but personally, I wouldn't. The applet is expecting a lot more information to be available to it in order to allow it to work fully.

Instead, I would move all of the "application" content to a separate component, like a JPanel for example and simply move this between the applet or frame as required...

ps- You can use f.setLocationRelativeTo(null) to center the window on the screen ;)

Updated

You need to go back to basics. Unless you absolutely must have one, avoid applets until you understand the basics of Swing, case in point...

Within the constructor of GalzyTable2 you are doing...

JApplet app = new JApplet(); add(app); app.init(); app.start(); 

...Why are you adding another applet to an applet??

Case in point...

Within the main method, you are trying to add the instance of JFrame to itself...

f.getContentPane().add(f, button2); 

Instead, create yourself a class that extends from something like JPanel, add your UI logical to this, using compound components if required.

Then, add this panel to whatever top level container you need.

Take the time to read through Creating a GUI with Swing

Updated with example

import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.event.ActionEvent; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException;  public class GalaxyTable2 extends JPanel {      private static final int PREF_W = 700;     private static final int PREF_H = 600;      String[] columnNames                     = {"Phone Name", "Brief Description", "Picture", "price",                         "Buy"};  // Create image icons     ImageIcon Image1 = new ImageIcon(                     getClass().getResource("s1.png"));     ImageIcon Image2 = new ImageIcon(                     getClass().getResource("s2.png"));     ImageIcon Image3 = new ImageIcon(                     getClass().getResource("s3.png"));     ImageIcon Image4 = new ImageIcon(                     getClass().getResource("s4.png"));     ImageIcon Image5 = new ImageIcon(                     getClass().getResource("note.png"));     ImageIcon Image6 = new ImageIcon(                     getClass().getResource("note2.png"));     ImageIcon Image7 = new ImageIcon(                     getClass().getResource("note3.png"));      Object[][] rowData = {         {"Galaxy S", "3G Support,CPU 1GHz",             Image1, 120, false},         {"Galaxy S II", "3G Support,CPU 1.2GHz",             Image2, 170, false},         {"Galaxy S III", "3G Support,CPU 1.4GHz",             Image3, 205, false},         {"Galaxy S4", "4G Support,CPU 1.6GHz",             Image4, 230, false},         {"Galaxy Note", "4G Support,CPU 1.4GHz",             Image5, 190, false},         {"Galaxy Note2 II", "4G Support,CPU 1.6GHz",             Image6, 190, false},         {"Galaxy Note 3", "4G Support,CPU 2.3GHz",             Image7, 260, false},};      MyTable ss = new MyTable(                     rowData, columnNames);      // Create a table     JTable jTable1 = new JTable(ss);      public GalaxyTable2() {         jTable1.setRowHeight(70);          add(new JScrollPane(jTable1),                         BorderLayout.CENTER);          JPanel buttons = new JPanel();          JButton button = new JButton("Home");         buttons.add(button);         JButton button2 = new JButton("Confirm");         buttons.add(button2);          add(buttons, BorderLayout.SOUTH);     }      @Override      public Dimension getPreferredSize() {         return new Dimension(PREF_W, PREF_H);     }      public void actionPerformed(ActionEvent e) {         new AMainFrame7().setVisible(true);     }      public static void main(String[] args) {          EventQueue.invokeLater(new Runnable() {             @Override             public void run() {                 try {                     UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());                 } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {                     ex.printStackTrace();                 }                  JFrame frame = new JFrame("Testing");                 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);                 frame.add(new GalaxyTable2());                 frame.pack();                 frame.setLocationRelativeTo(null);                 frame.setVisible(true);             }         });     } } 

You also seem to have a lack of understanding about how to use layout managers.

Take the time to read through Creating a GUI with Swing and Laying components out in a container

How to style a div to have a background color for the entire width of the content, and not just for the width of the display?

The inline-block display style seems to do what you want. Note that the <nobr> tag is deprecated, and should not be used. Non-breaking white space is doable in CSS. Here's how I would alter your example style rules:

div { display: inline-block; white-space: nowrap; }
.success { background-color: #ccffcc; }

Alter your stylesheet, remove the <nobr> tags from your source, and give it a try. Note that display: inline-block does not work in every browser, though it tends to only be problematic in older browsers (newer versions should support it to some degree). My personal opinion is to ignore coding for broken browsers. If your code is standards compliant, it should work in all of the major, modern browsers. Anyone still using IE6 (or earlier) deserves the pain. :-)

How to format numbers by prepending 0 to single-digit numbers?

`${number}`.replace(/^(\d)$/, '0$1');

Regex is the best.

what's the correct way to send a file from REST web service to client?

If you want to return a File to be downloaded, specially if you want to integrate with some javascript libs of file upload/download, then the code bellow should do the job:

@GET
@Path("/{key}")
public Response download(@PathParam("key") String key,
                         @Context HttpServletResponse response) throws IOException {
    try {
        //Get your File or Object from wherever you want...
            //you can use the key parameter to indentify your file
            //otherwise it can be removed
        //let's say your file is called "object"
        response.setContentLength((int) object.getContentLength());
        response.setHeader("Content-Disposition", "attachment; filename="
                + object.getName());
        ServletOutputStream outStream = response.getOutputStream();
        byte[] bbuf = new byte[(int) object.getContentLength() + 1024];
        DataInputStream in = new DataInputStream(
                object.getDataInputStream());
        int length = 0;
        while ((in != null) && ((length = in.read(bbuf)) != -1)) {
            outStream.write(bbuf, 0, length);
        }
        in.close();
        outStream.flush();
    } catch (S3ServiceException e) {
        e.printStackTrace();
    } catch (ServiceException e) {
        e.printStackTrace();
    }
    return Response.ok().build();
}

Does a foreign key automatically create an index?

Strictly speaking, foreign keys have absolutely nothing to do with indexes, yes. But, as the speakers above me pointed out, it makes sense to create one to speed up the FK-lookups. In fact, in MySQL, if you don't specify an index in your FK declaration, the engine (InnoDB) creates it for you automatically.

How to get the groups of a user in Active Directory? (c#, asp.net)

In my case the only way I could keep using GetGroups() without any expcetion was adding the user (USER_WITH_PERMISSION) to the group which has permission to read the AD (Active Directory). It's extremely essential to construct the PrincipalContext passing this user and password.

var pc = new PrincipalContext(ContextType.Domain, domain, "USER_WITH_PERMISSION", "PASS");
var user = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, userName);
var groups = user.GetGroups();

Steps you may follow inside Active Directory to get it working:

  1. Into Active Directory create a group (or take one) and under secutiry tab add "Windows Authorization Access Group"
  2. Click on "Advanced" button
  3. Select "Windows Authorization Access Group" and click on "View"
  4. Check "Read tokenGroupsGlobalAndUniversal"
  5. Locate the desired user and add to the group you created (taken) from the first step

What's the better (cleaner) way to ignore output in PowerShell?

I realize this is an old thread, but for those taking @JasonMArcher's accepted answer above as fact, I'm surprised it has not been corrected many of us have known for years it is actually the PIPELINE adding the delay and NOTHING to do with whether it is Out-Null or not. In fact, if you run the tests below you will quickly see that the same "faster" casting to [void] and $void= that for years we all used thinking it was faster, are actually JUST AS SLOW and in fact VERY SLOW when you add ANY pipelining whatsoever. In other words, as soon as you pipe to anything, the whole rule of not using out-null goes into the trash.

Proof, the last 3 tests in the list below. The horrible Out-null was 32339.3792 milliseconds, but wait - how much faster was casting to [void]? 34121.9251 ms?!? WTF? These are REAL #s on my system, casting to VOID was actually SLOWER. How about =$null? 34217.685ms.....still friggin SLOWER! So, as the last three simple tests show, the Out-Null is actually FASTER in many cases when the pipeline is already in use.

So, why is this? Simple. It is and always was 100% a hallucination that piping to Out-Null was slower. It is however that PIPING TO ANYTHING is slower, and didn't we kind of already know that through basic logic? We just may not have know HOW MUCH slower, but these tests sure tell a story about the cost of using the pipeline if you can avoid it. And, we were not really 100% wrong because there is a very SMALL number of true scenarios where out-null is evil. When? When adding Out-Null is adding the ONLY pipeline activity. In other words....the reason a simple command like $(1..1000) | Out-Null as shown above showed true.

If you simply add an additional pipe to Out-String to every test above, the #s change radically (or just paste the ones below) and as you can see for yourself, the Out-Null actually becomes FASTER in many cases:

$GetProcess = Get-Process

# Batch 1 - Test 1 
(Measure-Command { 
for ($i = 1; $i -lt 99; $i++) 
{ 
$GetProcess | Out-Null 
} 
}).TotalMilliseconds

# Batch 1 - Test 2 
(Measure-Command { 
for ($i = 1; $i -lt 99; $i++) 
{ 
[void]($GetProcess) 
} 
}).TotalMilliseconds

# Batch 1 - Test 3 
(Measure-Command { 
for ($i = 1; $i -lt 99; $i++) 
{ 
$null = $GetProcess 
} 
}).TotalMilliseconds

# Batch 2 - Test 1 
(Measure-Command { 
for ($i = 1; $i -lt 99; $i++) 
{ 
$GetProcess | Select-Object -Property ProcessName | Out-Null 
} 
}).TotalMilliseconds

# Batch 2 - Test 2 
(Measure-Command { 
for ($i = 1; $i -lt 99; $i++) 
{ 
[void]($GetProcess | Select-Object -Property ProcessName ) 
} 
}).TotalMilliseconds

# Batch 2 - Test 3 
(Measure-Command { 
for ($i = 1; $i -lt 99; $i++) 
{ 
$null = $GetProcess | Select-Object -Property ProcessName 
} 
}).TotalMilliseconds

# Batch 3 - Test 1 
(Measure-Command { 
for ($i = 1; $i -lt 99; $i++) 
{ 
$GetProcess | Select-Object -Property Handles, NPM, PM, WS, VM, CPU, Id, SI, Name | Out-Null 
} 
}).TotalMilliseconds

# Batch 3 - Test 2 
(Measure-Command { 
for ($i = 1; $i -lt 99; $i++) 
{ 
[void]($GetProcess | Select-Object -Property Handles, NPM, PM, WS, VM, CPU, Id, SI, Name ) 
} 
}).TotalMilliseconds

# Batch 3 - Test 3 
(Measure-Command { 
for ($i = 1; $i -lt 99; $i++) 
{ 
$null = $GetProcess | Select-Object -Property Handles, NPM, PM, WS, VM, CPU, Id, SI, Name 
} 
}).TotalMilliseconds

# Batch 4 - Test 1 
(Measure-Command { 
for ($i = 1; $i -lt 99; $i++) 
{ 
$GetProcess | Out-String | Out-Null 
} 
}).TotalMilliseconds

# Batch 4 - Test 2 
(Measure-Command { 
for ($i = 1; $i -lt 99; $i++) 
{ 
[void]($GetProcess | Out-String ) 
} 
}).TotalMilliseconds

# Batch 4 - Test 3 
(Measure-Command { 
for ($i = 1; $i -lt 99; $i++) 
{ 
$null = $GetProcess | Out-String 
} 
}).TotalMilliseconds

How to refresh activity after changing language (Locale) inside application

This approach will work on all API level device.

  1. Use Base Activity for attachBaseContext to set the locale language and extend this activity for all activities

    open class  BaseAppCompactActivity() : AppCompatActivity() {
    
        override fun attachBaseContext(newBase: Context) {
            super.attachBaseContext(LocaleHelper.onAttach(newBase))    
        }
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)           
        }
    }
    
  2. Use Application attachBaseContext and onConfigurationChanged to set the locale language

    public class MyApplication extends Application {
        private static MyApplication application;
    
        @Override
        public void onCreate() {
            super.onCreate();
        }
    
        public static MyApplication getApplication() {
            return application;
        }
    
        /**
         * overide to change local sothat language can be chnaged from android device  nogaut and above
         */
        @Override
        protected void attachBaseContext(Context base) {
            super.attachBaseContext(LocaleHelper.INSTANCE.onAttach(base));
        }
    
        @Override
        public void onConfigurationChanged(Configuration newConfig) {
            setLanguageFromNewConfig(newConfig);
            super.onConfigurationChanged(newConfig);
        }
    
        /*** also handle chnage  language if  device language chnaged **/
        private void setLanguageFromNewConfig(Configuration newConfig){
            Prefs.putSaveLocaleLanguage(this,  selectedLocaleLanguage );
            LocaleHelper.INSTANCE.onAttach(this);
        }
    
  3. Use Locale Helper for handling language changes, this approach work on all device

    object LocaleHelper {
        private var defaultLanguage  :String = KycUtility.KYC_LANGUAGE.ENGLISH.languageCode
    
        fun onAttach(context: Context, defaultLanguage: String): Context {
            return setLocale(context, defaultLanguage)
        }
    
    
    
        fun setLocale(context: Context, language: String): Context {
            return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                updateResources(context, language)
            } else updateResourcesLegacy(context, language)
    
        }
    
    
        @TargetApi(Build.VERSION_CODES.N)
        private fun updateResources(context: Context, language: String): Context {
            val locale = Locale(language)
            Locale.setDefault(locale)
    
            val configuration = context.getResources().getConfiguration()
            configuration.setLocale(locale)
            configuration.setLayoutDirection(locale)
    
            return context.createConfigurationContext(configuration)
        }
    
        private fun updateResourcesLegacy(context: Context, language: String): Context {
            val locale = Locale(language)
            Locale.setDefault(locale)
    
            val resources = context.getResources()
    
            val configuration = resources.getConfiguration()
            configuration.locale = locale
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                configuration.setLayoutDirection(locale)
            }
            resources.updateConfiguration(configuration, resources.getDisplayMetrics())
            return context
        }
    }
    

How can I divide two integers stored in variables in Python?

x / y

quotient of x and y

x // y 

(floored) quotient of x and y

Angular4 - No value accessor for form control

You should use formControlName="surveyType" on an input and not on a div

Why should we typedef a struct so often in C?

In 'C' programming language the keyword 'typedef' is used to declare a new name for some object(struct, array, function..enum type). For example, I will use a 'struct-s'. In 'C' we often declare a 'struct' outside of the 'main' function. For example:

struct complex{ int real_part, img_part }COMPLEX;

main(){

 struct KOMPLEKS number; // number type is now a struct type
 number.real_part = 3;
 number.img_part = -1;
 printf("Number: %d.%d i \n",number.real_part, number.img_part);

}

Each time I decide to use a struct type I will need this keyword 'struct 'something' 'name'.'typedef' will simply rename that type and I can use that new name in my program every time I want. So our code will be:

typedef struct complex{int real_part, img_part; }COMPLEX;
//now COMPLEX is the new name for this structure and if I want to use it without
// a keyword like in the first example 'struct complex number'.

main(){

COMPLEX number; // number is now the same type as in the first example
number.real_part = 1;
number.img)part = 5;
printf("%d %d \n", number.real_part, number.img_part);

}

If you have some local object(struct, array, valuable) that will be used in your entire program you can simply give it a name using a 'typedef'.

Android YouTube app Play Video Intent

You can use the Youtube Android player API to play the video if Youtube app is installed, otherwise just prompt the user to choose from the available web browsers.

if(YouTubeIntents.canResolvePlayVideoIntent(mContext)){
                    mContext.startActivity(YouTubeIntents.createPlayVideoIntent(mContext, mVideoId));
}else {
    Intent webIntent = new Intent(Intent.ACTION_VIEW, 
           Uri.parse("http://www.youtube.com/watch?v=" + mVideoId));

    mContext.startActivity(webIntent);
}

JavaFX: How to get stage from controller during initialization?

The simplest way to get stage object in controller is:

  1. Add an extra method in own created controller class like (it will be a setter method to set the stage in controller class),

    private Stage myStage;
    public void setStage(Stage stage) {
         myStage = stage;
    }
    
  2. Get controller in start method and set stage

    FXMLLoader loader = new FXMLLoader(getClass().getResource("MyFXML.fxml"));
    OwnController controller = loader.getController();
    controller.setStage(this.stage);
    
  3. Now you can access the stage in controller

How to control font sizes in pgf/tikz graphics in latex?

\begin{tikzpicture}

    \tikzstyle{every node}=[font=\small]

\end{tikzpicture}

will give you font size control on every node.

Int to Decimal Conversion - Insert decimal point at specified location

Declare it as a decimal which uses the int variable and divide this by 100

int number = 700
decimal correctNumber = (decimal)number / 100;

Edit: Bala was faster with his reaction

Create a new Ruby on Rails application using MySQL instead of SQLite

For Rails 3 you can use this command to create a new project using mysql:

$ rails new projectname -d mysql

Setting cursor at the end of any text of a textbox

Try like below... it will help you...

Some time in Window Form Focus() doesn't work correctly. So better you can use Select() to focus the textbox.

txtbox.Select(); // to Set Focus
txtbox.Select(txtbox.Text.Length, 0); //to set cursor at the end of textbox

HTTP Status 500 - Servlet.init() for servlet Dispatcher threw exception

You map your dispatcher on *.do:

<servlet-mapping>
   <servlet-name>Dispatcher</servlet-name>
   <url-pattern>*.do</url-pattern>
</servlet-mapping>

but your controller is mapped on an url without .do:

@RequestMapping("/editPresPage")

Try changing this to:

@RequestMapping("/editPresPage.do")

Retrieve column names from java.sql.ResultSet

import java.sql.*;

public class JdbcGetColumnNames {

    public static void main(String args[]) {
        Connection con = null;
        Statement st = null;
        ResultSet rs = null;

        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/komal", "root", "root");

            st = con.createStatement();

            String sql = "select * from person";
            rs = st.executeQuery(sql);
            ResultSetMetaData metaData = rs.getMetaData();

            int rowCount = metaData.getColumnCount();

            System.out.println("Table Name : " + metaData.getTableName(2));
            System.out.println("Field  \tDataType");

            for (int i = 0; i < rowCount; i++) {
                System.out.print(metaData.getColumnName(i + 1) + "  \t");
                System.out.println(metaData.getColumnTypeName(i + 1));
            }
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

Table Name : person Field DataType id VARCHAR cname VARCHAR dob DATE

Relation between CommonJS, AMD and RequireJS?

It is quite normal to organize JavaScript program modular into several files and to call child-modules from the main js module.

The thing is JavaScript doesn't provide this. Not even today in latest browser versions of Chrome and FF.

But, is there any keyword in JavaScript to call another JavaScript module?

This question may be a total collapse of the world for many because the answer is No.


In ES5 ( released in 2009 ) JavaScript had no keywords like import, include, or require.

ES6 saves the day ( released in 2015 ) proposing the import keyword ( https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/import ), but no browser implements this.

If you use Babel 6.18.0 and transpile with ES2015 option only

import myDefault from "my-module";

you will get require again.

"use strict";
var _myModule = require("my-module");
var _myModule2 = _interopRequireDefault(_myModule);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

This is because require means the module will be loaded from Node.js. Node.js will handle everything from system level file read to wrapping functions into the module.

Because in JavaScript functions are the only wrappers to represent the modules.

I'm a lot confused about CommonJS and AMD?

Both CommonJS and AMD are just two different techniques how to overcome the JavaScript "defect" to load modules smart.

Insert 2 million rows into SQL Server quickly

I use the bcp utility. (Bulk Copy Program) I load about 1.5 million text records each month. Each text record is 800 characters wide. On my server, it takes about 30 seconds to add the 1.5 million text records into a SQL Server table.

The instructions for bcp are at http://msdn.microsoft.com/en-us/library/ms162802.aspx

Python requests - print entire http request (raw)?

Note: this answer is outdated. Newer versions of requests support getting the request content directly, as AntonioHerraizS's answer documents.

It's not possible to get the true raw content of the request out of requests, since it only deals with higher level objects, such as headers and method type. requests uses urllib3 to send requests, but urllib3 also doesn't deal with raw data - it uses httplib. Here's a representative stack trace of a request:

-> r= requests.get("http://google.com")
  /usr/local/lib/python2.7/dist-packages/requests/api.py(55)get()
-> return request('get', url, **kwargs)
  /usr/local/lib/python2.7/dist-packages/requests/api.py(44)request()
-> return session.request(method=method, url=url, **kwargs)
  /usr/local/lib/python2.7/dist-packages/requests/sessions.py(382)request()
-> resp = self.send(prep, **send_kwargs)
  /usr/local/lib/python2.7/dist-packages/requests/sessions.py(485)send()
-> r = adapter.send(request, **kwargs)
  /usr/local/lib/python2.7/dist-packages/requests/adapters.py(324)send()
-> timeout=timeout
  /usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/connectionpool.py(478)urlopen()
-> body=body, headers=headers)
  /usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/connectionpool.py(285)_make_request()
-> conn.request(method, url, **httplib_request_kw)
  /usr/lib/python2.7/httplib.py(958)request()
-> self._send_request(method, url, body, headers)

Inside the httplib machinery, we can see HTTPConnection._send_request indirectly uses HTTPConnection._send_output, which finally creates the raw request and body (if it exists), and uses HTTPConnection.send to send them separately. send finally reaches the socket.

Since there's no hooks for doing what you want, as a last resort you can monkey patch httplib to get the content. It's a fragile solution, and you may need to adapt it if httplib is changed. If you intend to distribute software using this solution, you may want to consider packaging httplib instead of using the system's, which is easy, since it's a pure python module.

Alas, without further ado, the solution:

import requests
import httplib

def patch_send():
    old_send= httplib.HTTPConnection.send
    def new_send( self, data ):
        print data
        return old_send(self, data) #return is not necessary, but never hurts, in case the library is changed
    httplib.HTTPConnection.send= new_send

patch_send()
requests.get("http://www.python.org")

which yields the output:

GET / HTTP/1.1
Host: www.python.org
Accept-Encoding: gzip, deflate, compress
Accept: */*
User-Agent: python-requests/2.1.0 CPython/2.7.3 Linux/3.2.0-23-generic-pae

TypeError: $ is not a function WordPress

jQuery might be missing.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>

Regex matching beginning AND end strings

^dbo\..*_fn$

This should work you.

How do I make a PHP form that submits to self?

The proper way would be to use $_SERVER["PHP_SELF"] (in conjunction with htmlspecialchars to avoid possible exploits). You can also just skip the action= part empty, which is not W3C valid, but currently works in most (all?) browsers - the default is to submit to self if it's empty.

Here is an example form that takes a name and email, and then displays the values you have entered upon submit:

<?php if (!empty($_POST)): ?>
    Welcome, <?php echo htmlspecialchars($_POST["name"]); ?>!<br>
    Your email is <?php echo htmlspecialchars($_POST["email"]); ?>.<br>
<?php else: ?>
    <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
        Name: <input type="text" name="name"><br>
        Email: <input type="text" name="email"><br>
        <input type="submit">
    </form>
<?php endif; ?>

Changing the default icon in a Windows Forms application

On the solution explorer, right click on the project title and select the 'Properties' on the context menu to open the 'Project Property' form. In the 'Application' tab, on the 'Resources' group box there is a entry field where you can select the icon file you want for your application.

reading external sql script in python

A very simple way to read an external script into an sqlite database in python is using executescript():

import sqlite3

conn = sqlite3.connect('csc455_HW3.db')

with open('ZooDatabase.sql', 'r') as sql_file:
    conn.executescript(sql_file.read())

conn.close()

Efficiently finding the last line in a text file

If you can pick a reasonable maximum line length, you can seek to nearly the end of the file before you start reading.

myfile.seek(-max_line_length, os.SEEK_END)
line = myfile.readlines()[-1]

Why is 1/1/1970 the "epoch time"?

http://en.wikipedia.org/wiki/Unix_time#History explains a little about the origins of Unix time and the chosen epoch. The definition of unix time and the epoch date went through a couple of changes before stabilizing on what it is now.

But it does not say why exactly 1/1/1970 was chosen in the end.

Notable excerpts from the Wikipedia page:

The first edition Unix Programmer's Manual dated November 3, 1971 defines the Unix time as "the time since 00:00:00, Jan. 1, 1971, measured in sixtieths of a second".

Because of [the] limited range, the epoch was redefined more than once, before the rate was changed to 1 Hz and the epoch was set to its present value.

Several later problems, including the complexity of the present definition, result from Unix time having been defined gradually by usage rather than fully defined to start with.

psql: FATAL: role "postgres" does not exist

If you installed postgres from brew, run this in your terminal :

/usr/local/opt/postgres/bin/createuser -s postgres

How to detect incoming calls, in an Android device?

You need a BroadcastReceiver for ACTION_PHONE_STATE_CHANGED This will call your received whenever the phone-state changes from idle, ringing, offhook so from the previous value and the new value you can detect if this is an incoming/outgoing call.

Required permission would be:

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

But if you also want to receive the EXTRA_INCOMING_NUMBER in that broadcast, you'll need another permission: "android.permission.READ_CALL_LOG"

And the code something like this:

val receiver: BroadcastReceiver = object : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        Log.d(TAG, "onReceive")
    }
}

override fun onResume() {
    val filter = IntentFilter()
    filter.addAction("android.intent.action.PHONE_STATE")
    registerReceiver(receiver, filter)
    super.onResume()
}

override fun onPause() {
    unregisterReceiver(receiver)
    super.onPause()
}

and in receiver class, we can get current state by reading intent like this:

intent.extras["state"]

the result of extras could be:

RINGING -> If your phone is ringing

OFFHOOK -> If you are talking with someone (Incoming or Outcoming call)

IDLE -> if call ended (Incoming or Outcoming call)

With PHONE_STATE broadcast we don't need to use PROCESS_OUTGOING_CALLS permission or deprecated NEW_OUTGOING_CALL action.

How to get the function name from within that function?

You can't. Functions don't have names according to the standard (though mozilla has such an attribute) - they can only be assigned to variables with names.

Also your comment:

// access fully qualified name (ie "my.namespace.myFunc")

is inside the function my.namespace.myFunc.getFn

What you can do is return the constructor of an object created by new

So you could say

var obj = new my.namespace.myFunc();
console.info(obj.constructor); //my.namespace.myFunc

How to get item's position in a list?

What about the following?

print testlist.index(element)

If you are not sure whether the element to look for is actually in the list, you can add a preliminary check, like

if element in testlist:
    print testlist.index(element)

or

print(testlist.index(element) if element in testlist else None)

or the "pythonic way", which I don't like so much because code is less clear, but sometimes is more efficient,

try:
    print testlist.index(element)
except ValueError:
    pass

ffprobe or avprobe not found. Please install one

  • Update your version of youtube-dl to the lastest as older version might not support.

     pip install --upgrade youtube_dl
    
  • Install 'ffmpeg' and 'ffprobe' module

     pip install ffmpeg
     pip install ffprobe
    
  • If you face the same issue, then download ffmpeg builds and put all the .exe files to Script folder($path: "Python\Python38-32\Scripts") (Windows OS only)

Show/Hide the console window of a C# console application

If you don't have a problem integrating a small batch application, there is this program called Cmdow.exe that will allow you to hide console windows based on console title.

Console.Title = "MyConsole";
System.Diagnostics.Process HideConsole = new System.Diagnostics.Process();
HideConsole.StartInfo.UseShellExecute = false;
HideConsole.StartInfo.Arguments = "MyConsole /hid";
HideConsole.StartInfo.FileName = "cmdow.exe";
HideConsole.Start();

Add the exe to the solution, set the build action to "Content", set Copy to Output Directory to what suits you, and cmdow will hide the console window when it is ran.

To make the console visible again, you just change the Arguments

HideConsole.StartInfo.Arguments = "MyConsole /Vis";

Python threading.timer - repeat function every 'n' seconds

In addition to the above great answers using Threads, in case you have to use your main thread or prefer an async approach - I wrapped a short class around aio_timers Timer class (to enable repeating)

import asyncio
from aio_timers import Timer

class RepeatingAsyncTimer():
    def __init__(self, interval, cb, *args, **kwargs):
        self.interval = interval
        self.cb = cb
        self.args = args
        self.kwargs = kwargs
        self.aio_timer = None
        self.start_timer()
    
    def start_timer(self):
        self.aio_timer = Timer(delay=self.interval, 
                               callback=self.cb_wrapper, 
                               callback_args=self.args, 
                               callback_kwargs=self.kwargs
                              )
    
    def cb_wrapper(self, *args, **kwargs):
        self.cb(*args, **kwargs)
        self.start_timer()


from time import time
def cb(timer_name):
    print(timer_name, time())

print(f'clock starts at: {time()}')
timer_1 = RepeatingAsyncTimer(interval=5, cb=cb, timer_name='timer_1')
timer_2 = RepeatingAsyncTimer(interval=10, cb=cb, timer_name='timer_2')

clock starts at: 1602438840.9690785

timer_1 1602438845.980087

timer_2 1602438850.9806316

timer_1 1602438850.9808934

timer_1 1602438855.9863033

timer_2 1602438860.9868324

timer_1 1602438860.9876585

Why are there two ways to unstage a file in Git?

It would seem to me that git rm --cached <file> removes the file from the index without removing it from the directory where a plain git rm <file> would do both, just as an OS rm <file> would remove the file from the directory without removing its versioning.

Eclipse error: "The import XXX cannot be resolved"

pom.xml

If it's a Maven project, go to pom.xml and remove all the dependency jars. Save it. Project will automatically build.

Then add dependency jars again (you can do Ctrl+Z). Save it. Project will automatically build and you won't see that error.

Generate a random number in a certain range in MATLAB

Best solution is randint , but this function produce integer numbers.

You can use rand with rounding function

  r = round(a + (b-a).*rand(m,n));

This produces Real random number between a and b , size of output matrix is m*n

How to get length of a list of lists in python

This saves the data in a list of lists.

text = open("filetest.txt", "r")
data = [ ]
for line in text:
    data.append( line.strip().split() )

print "number of lines ", len(data)
print "number of columns ", len(data[0])

print "element in first row column two ", data[0][1]

Swift - Integer conversion to Hours/Minutes/Seconds

Here is a more structured/flexible approach: (Swift 3)

struct StopWatch {

    var totalSeconds: Int

    var years: Int {
        return totalSeconds / 31536000
    }

    var days: Int {
        return (totalSeconds % 31536000) / 86400
    }

    var hours: Int {
        return (totalSeconds % 86400) / 3600
    }

    var minutes: Int {
        return (totalSeconds % 3600) / 60
    }

    var seconds: Int {
        return totalSeconds % 60
    }

    //simplified to what OP wanted
    var hoursMinutesAndSeconds: (hours: Int, minutes: Int, seconds: Int) {
        return (hours, minutes, seconds)
    }
}

let watch = StopWatch(totalSeconds: 27005 + 31536000 + 86400)
print(watch.years) // Prints 1
print(watch.days) // Prints 1
print(watch.hours) // Prints 7
print(watch.minutes) // Prints 30
print(watch.seconds) // Prints 5
print(watch.hoursMinutesAndSeconds) // Prints (7, 30, 5)

Having an approach like this allows the adding of convenience parsing like this:

extension StopWatch {

    var simpleTimeString: String {
        let hoursText = timeText(from: hours)
        let minutesText = timeText(from: minutes)
        let secondsText = timeText(from: seconds)
        return "\(hoursText):\(minutesText):\(secondsText)"
    }

    private func timeText(from number: Int) -> String {
        return number < 10 ? "0\(number)" : "\(number)"
    }
}
print(watch.simpleTimeString) // Prints 07:30:05

It should be noted that purely Integer based approaches don't take leap day/seconds into account. If the use case is dealing with real dates/times Date and Calendar should be used.

How to get a matplotlib Axes instance to plot to?

Use the gca ("get current axes") helper function:

ax = plt.gca()

Example:

import matplotlib.pyplot as plt
import matplotlib.finance
quotes = [(1, 5, 6, 7, 4), (2, 6, 9, 9, 6), (3, 9, 8, 10, 8), (4, 8, 8, 9, 8), (5, 8, 11, 13, 7)]
ax = plt.gca()
h = matplotlib.finance.candlestick(ax, quotes)
plt.show()

enter image description here

how to disable DIV element and everything inside

I think inline scripts are hard to stop instead you can try with this:

<div id="test">
    <div>Click Me</div>
</div>

and script:

$(function () {
    $('#test').children().click(function(){
      alert('hello');
    });
    $('#test').children().off('click');
});

CHEKOUT FIDDLE AND SEE IT HELPS

Read More about .off()

How can I represent an 'Enum' in Python?

The new standard in Python is PEP 435, so an Enum class will be available in future versions of Python:

>>> from enum import Enum

However to begin using it now you can install the original library that motivated the PEP:

$ pip install flufl.enum

Then you can use it as per its online guide:

>>> from flufl.enum import Enum
>>> class Colors(Enum):
...     red = 1
...     green = 2
...     blue = 3
>>> for color in Colors: print color
Colors.red
Colors.green
Colors.blue

Command to escape a string in bash

It may not be quite what you want, since it's not a standard command on anyone's systems, but since my program should work fine on POSIX systems (if compiled), I'll mention it anyway. If you have the ability to compile or add programs on the machine in question, it should work.

I've used it without issue for about a year now, but it could be that it won't handle some edge cases. Most specifically, I have no idea what it would do with newlines in strings; a case for \\n might need to be added. This list of characters is not authoritative, but I believe it covers everything else.

I wrote this specifically as a 'helper' program so I could make a wrapper for things like scp commands.

It can likely be implemented as a shell function as well

I therefore present escapify.c. I use it like so:

scp user@host:"$(escapify "/this/path/needs to be escaped/file.c")" destination_file.c

PLEASE NOTE: I made this program for my own personal use. It also will (probably wrongly) assume that if it is given more than one argument that it should just print an unescaped space and continue on. This means that it can be used to pass multiple escaped arguments correctly, but could be seen as unwanted behavior by some.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
  char c='\0';
  int i=0;
  int j=1;
  /* do not care if no args passed; escaped nothing is still nothing. */
  if(argc < 2)
  {
    return 0;
  }
  while(j<argc)
  {
    while(i<strlen(argv[j]))
    {
      c=argv[j][i];
      /* this switch has no breaks on purpose. */
      switch(c)
      {
      case ';':
      case '\'':
      case ' ':
      case '!':
      case '"':
      case '#':
      case '$':
      case '&':
      case '(':
      case ')':
      case '|':
      case '*':
      case ',':
      case '<':
      case '>':
      case '[':
      case ']':
      case '\\':
      case '^':
      case '`':
      case '{':
      case '}':
        putchar('\\');
      default:
        putchar(c);
      }
      i++;
    }
    j++;
    if(j<argc) {
      putchar(' ');
    }
    i=0;
  }
  /* newline at end */
  putchar ('\n');
  return 0;
}

Linux Shell Script For Each File in a Directory Grab the filename and execute a program

for i in *.xls ; do 
  [[ -f "$i" ]] || continue
  xls2csv "$i" "${i%.xls}.csv"
done

The first line in the do checks if the "matching" file really exists, because in case nothing matches in your for, the do will be executed with "*.xls" as $i. This could be horrible for your xls2csv.

SQL Server 2008 Insert with WHILE LOOP

First of all I'd like to say that I 100% agree with John Saunders that you must avoid loops in SQL in most cases especially in production.

But occasionally as a one time thing to populate a table with a hundred records for testing purposes IMHO it's just OK to indulge yourself to use a loop.

For example in your case to populate your table with records with hospital ids between 16 and 100 and make emails and descriptions distinct you could've used

CREATE PROCEDURE populateHospitals
AS
DECLARE @hid INT;
SET @hid=16;
WHILE @hid < 100
BEGIN 
    INSERT hospitals ([Hospital ID], Email, Description) 
    VALUES(@hid, 'user' + LTRIM(STR(@hid)) + '@mail.com', 'Sample Description' + LTRIM(STR(@hid))); 
    SET @hid = @hid + 1;
END

And result would be

ID   Hospital ID Email            Description          
---- ----------- ---------------- ---------------------
1    16          [email protected]  Sample Description16 
2    17          [email protected]  Sample Description17 
...                                                    
84   99          [email protected]  Sample Description99 

Hiding an Excel worksheet with VBA

To hide from the UI, use Format > Sheet > Hide

To hide programatically, use the Visible property of the Worksheet object. If you do it programatically, you can set the sheet as "very hidden", which means it cannot be unhidden through the UI.

ActiveWorkbook.Sheets("Name").Visible = xlSheetVeryHidden 
' or xlSheetHidden or xlSheetVisible

You can also set the Visible property through the properties pane for the worksheet in the VBA IDE (ALT+F11).

Converting a string to a date in a cell

The best solution is using DATE() function and extracting yy, mm, and dd from the string with RIGHT(), MID() and LEFT() functions, the final will be some DATE(LEFT(),MID(),RIGHT()), details here

Copy folder recursively, excluding some folders

You can use find with the -prune option.

An example from man find:

       cd /source-dir
       find . -name .snapshot -prune -o \( \! -name *~ -print0 \)|
       cpio -pmd0 /dest-dir

       This command copies the contents of /source-dir to /dest-dir, but omits
       files  and directories named .snapshot (and anything in them).  It also
       omits files or directories whose name ends in ~,  but  not  their  con-
       tents.  The construct -prune -o \( ... -print0 \) is quite common.  The
       idea here is that the expression before -prune matches things which are
       to  be  pruned.  However, the -prune action itself returns true, so the
       following -o ensures that the right hand side  is  evaluated  only  for
       those  directories  which didn't get pruned (the contents of the pruned
       directories are not even visited, so their  contents  are  irrelevant).
       The  expression on the right hand side of the -o is in parentheses only
       for clarity.  It emphasises that the -print0 action  takes  place  only
       for  things  that  didn't  have  -prune  applied  to them.  Because the
       default `and' condition between tests binds more tightly than -o,  this
       is  the  default anyway, but the parentheses help to show what is going
       on.

Multiple aggregate functions in HAVING clause

GROUP BY meetingID
HAVING COUNT(caseID) < 4 AND COUNT(caseID) > 2

Reading NFC Tags with iPhone 6 / iOS 8

At the moment, Apple has not opened any access to the embedded NFC chip to developers as suggested by many articles such as these ones :

The list goes on. The main reason seems (like lots the other hardware features added to the iPhone in the past) that Apple wants to ensure the security of such technology before releasing any API for developers to let them do whatever they want. So at first, they will use it internally for their needs only (such as Apple Pay at launch time).

"At the moment, there isn't any open access to the NFC controller," said RapidNFC, a provider of NFC tags. "There are currently no NFC APIs in the iOS 8 GM SDK".

But eventually, I think we can all agree that they will develop such API, it's only a matter of time.

Scala: write string to file in one statement

Here's the modern, safe one liner:

java.nio.file.Files.write(java.nio.file.Paths.get("/tmp/output.txt"), "Hello world".getBytes());

nio is a modern IO library shipped by default with the JDK 9+ so no imports or dependencies required.

Resync git repo with new .gitignore file

I might misunderstand, but are you trying to delete files newly ignored or do you want to ignore new modifications to these files ? In this case, the thing is working.

If you want to delete ignored files previously commited, then use

git rm –cached `git ls-files -i –exclude-standard`
git commit -m 'clean up'