Programs & Examples On #Consistent hashing

Position absolute but relative to parent

#father {
   position: relative;
}

#son1 {
   position: absolute;
   top: 0;
}

#son2 {
   position: absolute;
   bottom: 0;
}

This works because position: absolute means something like "use top, right, bottom, left to position yourself in relation to the nearest ancestor who has position: absolute or position: relative."

So we make #father have position: relative, and the children have position: absolute, then use top and bottom to position the children.

How to check if activity is in foreground or in visible background?

Why not use broadcasts for this? the second activity (the one that needs to be up) can send a local broadcast like this:

//put this in onCreate(..) or any other lifecycle method that suits you best
//notice the string sent to the intent, it will be used to register a receiver!
Intent result = new Intent("broadcast identifier");
result.putString("some message");//this is optional
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(result);

then write a simple receiver within the splash activity:

//this goes on the class level (like a class/instance variable, not in a method) of your splash activity:
private BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        //kill activity here!!!
        //mission accomplished!
    }
};

and register your new receiver with the LocalBroadcastManager to listen to the broadcast from your second activity:

//notice the string sent to the intent filter, this is where you tell the BroadcastManager which broadcasts you want to listen to!
LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(receiver, new IntentFilter("broadcast identifier"));

NOTE that you could use a constant or a string resource for the "broadcast identifier" string.

Could not load type 'System.ServiceModel.Activation.HttpModule' from assembly 'System.ServiceModel

We are using a web service along side a web site and when we publish the web site it returns same this error. We found out that by going into IIS and removing the ServiceModel from Modules and the svc-Integrated from the Handler Mappings the error went away.

The Response content must be a string or object implementing __toString(), "boolean" given after move to psql

You can use json_decode(Your variable Name):

json_decode($result)

I was getting value from Model.where a column has value like this way

{"dayList":[
            {"day":[1,2,3,4],"time":[{"in_time":"10:00"},{"late_time":"15:00"},{"out_time":"16:15"}]
             },
             {"day":[5,6,7],"time":[{"in_time":"10:00"},{"late_time":"15:00"},{"out_time":"16:15"}]}
           ]
}

so access this value form model. you have to use this code.

$dayTimeListObject = json_decode($settingAttendance->bio_attendance_day_time,1);

 foreach ( $dayTimeListObject['dayList'] as $dayListArr)
 {
     foreach ( $dayListArr['day'] as $dayIndex)
     {
         if( $dayIndex == Date('w',strtotime('2020-02-11')))
         {
             $dayTimeList= $dayListArr['time'];
         }
     }
 }

 return $dayTimeList[2]['out_time'] ;

You can also define caste in your Model file.

 protected $casts = [
    'your-column-name' => 'json'
  ];

so after this no need of this line .

$dayTimeListObject = json_decode($settingAttendance->bio_attendance_day_time,1);

you can directly access this code.

$settingAttendance->bio_attendance_day_time

Mailto: Body formatting

From the first result on Google:

mailto:[email protected]_t?subject=Header&body=This%20is...%20the%20first%20line%0D%0AThis%20is%20the%20second

Where does npm install packages?

You can find globally installed modules by the command

npm list -g

It will provide you the location where node.js modules have been installed.

C:\Users\[Username]\AppData\Roaming\npm

If you install node.js modules locally in a folder, you can type the following command to see the location.

npm list

Using NULL in C++?

The downside of NULL in C++ is that it is a define for 0. This is a value that can be silently converted to pointer, a bool value, a float/double, or an int.

That is not very type safe and has lead to actual bugs in an application I worked on.

Consider this:

void Foo(int i);
void Foo(Bar* b);
void Foo(bool b);


main()
{
     Foo(0);         
     Foo(NULL); // same as Foo(0)
} 

C++11 defines a nullptr that is convertible to a null pointer but not to other scalars. This is supported in all modern C++ compilers, including VC++ as of 2008. In older versions of GCC there is a similar feature, but then it was called __null.

Substring a string from the end of the string

Try this:

var s = "Hello Marco !";

var corrected = s.Substring(0, s.Length - 2);

How to clear cache of Eclipse Indigo

you can use -clean parameter while starting eclipse like

C:\eclipse\eclipse.exe -vm "C:\Program Files\Java\jdk1.6.0_24\bin" -clean

Can I try/catch a warning?

I would only recommend using @ to suppress warnings when it's a straight forward operation (e.g. $prop = @($high/($width - $depth)); to skip division by zero warnings). However in most cases it's better to handle.

How to import keras from tf.keras in Tensorflow?

I had the same problem with Tensorflow 2.0.0 in PyCharm. PyCharm did not recognize tensorflow.keras; I updated my PyCharm and the problem was resolved!

System.loadLibrary(...) couldn't find native library in my case

In gradle, after copying all files folders to libs/

jniLibs.srcDirs = ['libs']

Adding the above line to sourceSets in build.gradle file worked. Nothing else worked whatsoever.

Create text file and fill it using bash

If you're wanting this as a script, the following Bash script should do what you want (plus tell you when the file already exists):

#!/bin/bash
if [ -e $1 ]; then
  echo "File $1 already exists!"
else
  echo >> $1
fi

If you don't want the "already exists" message, you can use:

#!/bin/bash
if [ ! -e $1 ]; then
  echo >> $1
fi

Edit about using:

Save whichever version with a name you like, let's say "create_file" (quotes mine, you don't want them in the file name). Then, to make the file executatble, at a command prompt do:

chmod u+x create_file

Put the file in a directory in your path, then use it with:

create_file NAME_OF_NEW_FILE

The $1 is a special shell variable which takes the first argument on the command line after the program name; i.e. $1 will pick up NAME_OF_NEW_FILE in the above usage example.

How to put labels over geom_bar for each bar in R with ggplot2

Try this:

ggplot(data=dat, aes(x=Types, y=Number, fill=sample)) + 
     geom_bar(position = 'dodge', stat='identity') +
     geom_text(aes(label=Number), position=position_dodge(width=0.9), vjust=-0.25)

ggplot output

How to permanently export a variable in Linux?

If it suits anyone, here are some brief guidelines for adding environment variables permanently.

vi ~/.bash_profile

Add the variables to the file:

export DISPLAY=:0
export JAVA_HOME=~/opt/openjdk11

Immediately apply all changes:

source ~/.bash_profile

Source: https://www.serverlab.ca/tutorials/linux/administration-linux/how-to-set-environment-variables-in-linux/

Check if string contains a value in array

$owned_urls= array('website1.com', 'website2.com', 'website3.com');
    $string = 'my domain name is website3.com';
    for($i=0; $i < count($owned_urls); $i++)
    {
        if(strpos($string,$owned_urls[$i]) != false)
            echo 'Found';
    }   

Could not load file or assembly ... An attempt was made to load a program with an incorrect format (System.BadImageFormatException)

I had this same problem. I had set Project A's "Platform Target" ("Project A"(Right Click)->Properties->Build->"Platform Target") to x86 but kept Project B's at "Any CPU". Setting Project B's to "x86" fixed this.

Pycharm and sys.argv arguments

In addition to Jim's answer (sorry not enough rep points to make a comment), just wanted to point out that the arguments specified in PyCharm do not have special characters escaped, unlike what you would do on the command line. So, whereas on the command line you'd do:

python mediadb.py  /media/paul/New\ Volume/Users/paul/Documents/spinmaster/\*.png

the PyCharm parameter would be:

"/media/paul/New Volume/Users/paul/Documents/spinmaster/*.png"

How to combine multiple conditions to subset a data-frame using "OR"?

my.data.frame <- subset(data , V1 > 2 | V2 < 4)

An alternative solution that mimics the behavior of this function and would be more appropriate for inclusion within a function body:

new.data <- data[ which( data$V1 > 2 | data$V2 < 4) , ]

Some people criticize the use of which as not needed, but it does prevent the NA values from throwing back unwanted results. The equivalent (.i.e not returning NA-rows for any NA's in V1 or V2) to the two options demonstrated above without the which would be:

 new.data <- data[ !is.na(data$V1 | data$V2) & ( data$V1 > 2 | data$V2 < 4)  , ]

Note: I want to thank the anonymous contributor that attempted to fix the error in the code immediately above, a fix that got rejected by the moderators. There was actually an additional error that I noticed when I was correcting the first one. The conditional clause that checks for NA values needs to be first if it is to be handled as I intended, since ...

> NA & 1
[1] NA
> 0 & NA
[1] FALSE

Order of arguments may matter when using '&".

Merge two rows in SQL

I had a similar problem. The difference was that I needed far more control over what I was returning so I ended up with an simple clear but rather long query. Here is a simplified version of it based on your example.

select main.id, Field1_Q.Field1, Field2_Q.Field2
from 
(
    select distinct id
    from Table1
)as main
left outer join (
    select id, max(Field1)
    from Table1
    where Field1 is not null
    group by id
) as Field1_Q on main.id = Field1_Q.id
left outer join (
    select id, max(Field2)
    from Table1
    where Field2 is not null
    group by id
) as Field2_Q on main.id = Field2_Q.id 
;

The trick here is that the first select 'main' selects the rows to display. Then you have one select per field. What is being joined on should be all of the same values returned by the 'main' query.

Be warned, those other queries need to return only one row per id or you will be ignoring data

Android View shadow

I know this question has already been answered but I want you to know that I found a drawable on Android Studio that is very similar to the pics you have in the question: Take a look at this:

android:background="@drawable/abc_menu_dropdown_panel_holo_light"

It looks like this:

enter image description here

Hope it will be helpful

Edit

The option above is for the older versions of Android Studio so you may not find it. For newer versions:

android:background="@android:drawable/dialog_holo_light_frame"

Moreover, if you want to have your own custom shape, I suggest to use a drawing software like Photoshop and draw it.

enter image description here

Don't forget to save it as .9.png file (example: my_background.9.png)

Read the documentation: Draw 9-patch

Edit 2

An even better and less hard working solution is to use a CardView and set app:cardPreventCornerOverlap="false" to prevent views to overlap the borders:

<android.support.v7.widget.CardView
    android:id="@+id/card_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:cardCornerRadius="2dp"
    app:cardElevation="2dp"
    app:cardPreventCornerOverlap="false"
    app:contentPadding="0dp">

    <!-- your layout stuff here -->

</android.support.v7.widget.CardView>

Also make sure to have included the latest version in the build.gradle, current is

compile 'com.android.support:cardview-v7:26.0.0'

SQL Query for Selecting Multiple Records

You want to add the IN() clause to your WHERE

SELECT * 
FROM `Buses` 
WHERE `BusID` IN (Id1, ID2, ID3,.... put your ids here)

If you have a list of Ids stored in a table you can also do this:

SELECT * 
FROM `Buses` 
WHERE `BusID` IN (SELECT Id FROM table)

How to import a bak file into SQL Server Express

I had the same error. What worked for me is when you go for the SMSS GUI option, look at General, Files in Options settings. After I did that (replace DB, set location) all went well.

How to convert a date string to different format

If you can live with 01 for January instead of 1, then try...

d = datetime.datetime.strptime("2013-1-25", '%Y-%m-%d')
print datetime.date.strftime(d, "%m/%d/%y")

You can check the docs for other formatting directives.

java.lang.ClassNotFoundException: org.apache.xmlbeans.XmlObject Error

You have to include one more jar.

xmlbeans-2.3.0.jar

Add this and try.

Note: It is required for the files with .xlsx formats only, not for just .xls formats.

Cassandra port usage - how are the ports used?

In addition to the above answers, as part of configuring your firewall, if you are using SSH then use port 22.

How do I calculate square root in Python?

What you're seeing is integer division. To get floating point division by default,

from __future__ import division

Or, you could convert 1 or 2 of 1/2 into a floating point value.

sqrt = x**(1.0/2)

How to convert a string with Unicode encoding to a string of letters

This simple method will work for most cases, but would trip up over something like "u005Cu005C" which should decode to the string "\u0048" but would actually decode "H" as the first pass produces "\u0048" as the working string which then gets processed again by the while loop.

static final String decode(final String in)
{
    String working = in;
    int index;
    index = working.indexOf("\\u");
    while(index > -1)
    {
        int length = working.length();
        if(index > (length-6))break;
        int numStart = index + 2;
        int numFinish = numStart + 4;
        String substring = working.substring(numStart, numFinish);
        int number = Integer.parseInt(substring,16);
        String stringStart = working.substring(0, index);
        String stringEnd   = working.substring(numFinish);
        working = stringStart + ((char)number) + stringEnd;
        index = working.indexOf("\\u");
    }
    return working;
}

How to add 20 minutes to a current date?

var d = new Date();
var v = new Date();
v.setMinutes(d.getMinutes()+20);

Adding gif image in an ImageView in android

I would suggest you to use Glide library. To use Glide you need to add this to add these dependencies

compile 'com.github.bumptech.glide:glide:3.7.0'
compile 'com.android.support:support-v4:23.4.0'

to your grandle (Module:app) file.

Then use this line of code to load your gif image

Glide.with(context).load(R.drawable.loading).asGif().diskCacheStrategy(DiskCacheStrategy.SOURCE).crossFade().into(loadingImageView);

More Information on Glide

Java regular expression OR operator

You can just use the pipe on its own:

"string1|string2"

for example:

String s = "string1, string2, string3";
System.out.println(s.replaceAll("string1|string2", "blah"));

Output:

blah, blah, string3

The main reason to use parentheses is to limit the scope of the alternatives:

String s = "string1, string2, string3";
System.out.println(s.replaceAll("string(1|2)", "blah"));

has the same output. but if you just do this:

String s = "string1, string2, string3";
System.out.println(s.replaceAll("string1|2", "blah"));

you get:

blah, stringblah, string3

because you've said "string1" or "2".

If you don't want to capture that part of the expression use ?::

String s = "string1, string2, string3";
System.out.println(s.replaceAll("string(?:1|2)", "blah"));

How to change btn color in Bootstrap

I am not the OP of this answer but it helped me so:

I wanted to change the color of the next/previous buttons of the bootstrap carousel on my homepage.

Solution: Copy the selector names from bootstrap.css and move them to your own style.css (with your own prefrences..) :

_x000D_
_x000D_
.carousel-control-prev-icon,
.carousel-control-next-icon {
  height: 100px;
  width: 100px;
  outline: black;
  background-size: 100%, 100%;
  border-radius: 50%;
  border: 1px solid black;
  background-image: none;
}

.carousel-control-next-icon:after
{
  content: '>';
  font-size: 55px;
  color: red;
}

.carousel-control-prev-icon:after {
  content: '<';
  font-size: 55px;
  color: red;
}
_x000D_
_x000D_
_x000D_

Common CSS Media Queries Break Points

Consider using twitter bootstrap's break points. with such a massive adoption rate you should be safe...

Convert Variable Name to String?

Does Django not do this when generating field names?

http://docs.djangoproject.com/en/dev//topics/db/models/#verbose-field-names

Seems reasonable to me.

Postgres FOR LOOP

Procedural elements like loops are not part of the SQL language and can only be used inside the body of a procedural language function, procedure (Postgres 11 or later) or a DO statement, where such additional elements are defined by the respective procedural language. The default is PL/pgSQL, but there are others.

Example with plpgsql:

DO
$do$
BEGIN 
   FOR i IN 1..25 LOOP
      INSERT INTO playtime.meta_random_sample
         (col_i, col_id)                       -- declare target columns!
      SELECT  i,     id
      FROM   tbl
      ORDER  BY random()
      LIMIT  15000;
   END LOOP;
END
$do$;

For many tasks that can be solved with a loop, there is a shorter and faster set-based solution around the corner. Pure SQL equivalent for your example:

INSERT INTO playtime.meta_random_sample (col_i, col_id)
SELECT t.*
FROM   generate_series(1,25) i
CROSS  JOIN LATERAL (
   SELECT i, id
   FROM   tbl
   ORDER  BY random()
   LIMIT  15000
   ) t;

About generate_series():

About optimizing performance of random selections:

How does createOrReplaceTempView work in Spark?

SparkSQl support writing programs using Dataset and Dataframe API, along with it need to support sql.

In order to support Sql on DataFrames, first it requires a table definition with column names are required, along with if it creates tables the hive metastore will get lot unnecessary tables, because Spark-Sql natively resides on hive. So it will create a temporary view, which temporarily available in hive for time being and used as any other hive table, once the Spark Context stop it will be removed.

In order to create the view, developer need an utility called createOrReplaceTempView

if...else within JSP or JSTL

<%@ taglib prefix='c' uri='http://java.sun.com/jsp/jstl/core' %>
<c:set var="isiPad" value="value"/>
<c:choose>
   <!-- if condition -->
   <c:when test="${...}">Html Code</c:when> 
   <!-- else condition -->
   <c:otherwise>Html code</c:otherwise>   
</c:choose>

Deserialize a JSON array in C#

This should work...

JavaScriptSerializer ser = new JavaScriptSerializer();
var records = new ser.Deserialize<List<Record>>(jsonData);

public class Person
{
    public string Name;
    public int Age;
    public string Location;
}
public class Record
{
    public Person record;
}

Get clicked element using jQuery on event?

You are missing the event parameter on your function.

$(document).on("click",".appDetails", function (event) {
    alert(event.target.id);
});

Python Pandas replicate rows in dataframe

This is an old question, but since it still comes up at the top of my results in Google, here's another way.

import pandas as pd
import numpy as np

df = pd.DataFrame({'col1':list("abc"),'col2':range(3)},index = range(3))

Say you want to replicate the rows where col1="b".

reps = [3 if val=="b" else 1 for val in df.col1]
df.loc[np.repeat(df.index.values, reps)]

You could replace the 3 if val=="b" else 1 in the list interpretation with another function that could return 3 if val=="b" or 4 if val=="c" and so on, so it's pretty flexible.

How do I size a UITextView to its content?

Not sure why people always over complicate things: here it is :

- (void)textViewDidChange:(UITextView *)textView{ CGRect frame = textView.frame;
CGFloat height = [self measureHeightOfUITextView:textView];
CGFloat insets = textView.textContainerInset.top + textView.textContainerInset.bottom;
height += insets;
frame.size.height = height;

if(frame.size.height > textView.frame.size.height){
    CGFloat diff = frame.size.height - textView.frame.size.height;
    textView.frame = CGRectMake(5, textView.frame.origin.y - diff, textView.frame.size.width, frame.size.height);
}
else if(frame.size.height < textView.frame.size.height){
    CGFloat diff = textView.frame.size.height - frame.size.height;
    textView.frame = CGRectMake(5, textView.frame.origin.y + diff, textView.frame.size.width, frame.size.height);
}
[textView setNeedsDisplay];
}

What to do with "Unexpected indent" in python?

Turn on visible whitespace in whatever editor you are using and turn on replace tabs with spaces.

While you can use tabs with Python mixing tabs and space usually leads to the error you are experiencing. Replacing tabs with 4 spaces is the recommended approach for writing Python code.

Use a JSON array with objects with javascript

This isn't a single JSON object. You have an array of JSON objects. You need to loop over array first and then access each object. Maybe the following kickoff example is helpful:

var arrayOfObjects = [{
  "id": 28,
  "Title": "Sweden"
}, {
  "id": 56,
  "Title": "USA"
}, {
  "id": 89,
  "Title": "England"
}];

for (var i = 0; i < arrayOfObjects.length; i++) {
  var object = arrayOfObjects[i];
  for (var property in object) {
    alert('item ' + i + ': ' + property + '=' + object[property]);
  }
  // If property names are known beforehand, you can also just do e.g.
  // alert(object.id + ',' + object.Title);
}

If the array of JSON objects is actually passed in as a plain vanilla string, then you would indeed need eval() here.

var string = '[{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}]';
var arrayOfObjects = eval(string);
// ...

To learn more about JSON, check MDN web docs: Working with JSON .

How to run Unix shell script from Java code?

The ZT Process Executor library is an alternative to Apache Commons Exec. It has functionality to run commands, capturing their output, setting timeouts, etc.

I have not used it yet, but it looks reasonably well-documented.

An example from the documentation: Executing a command, pumping the stderr to a logger, returning the output as UTF8 string.

 String output = new ProcessExecutor().command("java", "-version")
    .redirectError(Slf4jStream.of(getClass()).asInfo())
    .readOutput(true).execute()
    .outputUTF8();

Its documentation lists the following advantages over Commons Exec:

  • Improved handling of streams
    • Reading/writing to streams
    • Redirecting stderr to stdout
  • Improved handling of timeouts
  • Improved checking of exit codes
  • Improved API
    • One liners for quite complex use cases
    • One liners to get process output into a String
    • Access to the Process object available
    • Support for async processes ( Future )
  • Improved logging with SLF4J API
  • Support for multiple processes

What are some resources for getting started in operating system development?

There are good resources for operating system fundamentals in books. Since there isn't much call to create new OS's from scratch you won't find a ton of hobbyist type information on the internet.

I recommend the standard text book, "Modern Operating Systems" by Tanenbaum. You may also be able to find "Operating System Elements" by Calingaert useful - it's a thin overview of a book which give a rough sketch of what an OS is from a designer's standpoint.

If you have any interest in real time systems (and you should at least understand the differences and reasons for real time OS's) then I'd also recommend "MicroC/OS-II" by Labrosse.

Edit:

Can you specify what you mean by "more technical"? These books give pseudo code implementation details, but are you looking for an example OS, or code snippets for a particular machine/language?

-Adam

Run php function on button click

You are trying to call a javascript function. If you want to call a PHP function, you have to use for example a form:

    <form action="action_page.php">
       First name:<br>
       <input type="text" name="firstname" value="Mickey">
       <br>
       Last name:<br>
       <input type="text" name="lastname" value="Mouse">
       <br><br>
       <input type="submit" value="Submit">
     </form> 

(Original Code from: http://www.w3schools.com/html/html_forms.asp)

So if you want do do a asynchron call, you could use 'Ajax' - and yeah, that's the Javascript-Way. But I think, that my code example is enough for this time :)

Bootstrap 3 Navbar with Logo

You shouldn't need to add additional CSS, since Bootstrap3 does provide it. Unless you do want to add it. This is my code on putting the logo to the left and links to the right. This navigation is responsive. Make changes to this as you see fit.

HTML:

<nav class="navbar navbar-expand-lg navbar-light fixed-top" style="background-color:white;">
        <div class="container">
        <a class="navbar-brand" href="#"><img style="   width: 150px;" src="image.jpg" alt="Image text"></a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
        </button>
            <div class="collapse navbar-collapse" id="navbarResponsive">
                <ul class="navbar-nav ml-auto">
                    <li class="nav-item"><a class="nav-link" href="#">Home</a></li>
                    <li class="nav-item"><a class="nav-link" href="#">Projects</a></li>
                    <li class="nav-item"><a class="nav-link" href="#">Blog</a></li>
                    <li class="nav-item"><a class="nav-link" href="#">Contact</a></li>
                </ul>
            </div>
        </div>
    </nav>

Unable to compile class for JSP: The type java.util.Map$Entry cannot be resolved. It is indirectly referenced from required .class files

There are a lot of correct/same answers, but for future references:

Same stands for Tomcat 7. Be aware that updating only your used frameworks' versions (as proposed in other similar questions) isn't enough.

You also have to update Tomcat plugin's version. What worked for me, using Java 7, was upgrading to version 2.2 of tomcat7-maven-plugin (= Tomcat 7.0.47).

Automatically size JPanel inside JFrame

You need to set a layout manager for the JFrame to use - This deals with how components are positioned. A useful one is the BorderLayout manager.

Simply adding the following line of code should fix your problems:

mainFrame.setLayout(new BorderLayout());

(Do this before adding components to the JFrame)

How to update an "array of objects" with Firestore?

Here is the latest example from the Firestore documentation:

firebase.firestore.FieldValue.ArrayUnion

var washingtonRef = db.collection("cities").doc("DC");

// Atomically add a new region to the "regions" array field.
washingtonRef.update({
    regions: firebase.firestore.FieldValue.arrayUnion("greater_virginia")
});

// Atomically remove a region from the "regions" array field.
washingtonRef.update({
    regions: firebase.firestore.FieldValue.arrayRemove("east_coast")
});

Eclipse CDT: Symbol 'cout' could not be resolved

To get rid of symbol warnings you don't want, first you should understand how Eclipse CDT normally comes up with unknown symbol warnings in the first place. This is its process, more or less:

  1. Eclipse detects the GCC toolchains available on the system
  2. Your Eclipse project is configured to use a particular toolchain
  3. Eclipse does discovery on the toolchain to find its include paths and built-in defines, i.e. by running it with relevant options and reading the output
  4. Eclipse reads the header files from the include paths
  5. Eclipse indexes the source code in your project
  6. Eclipse shows warnings about unresolved symbols in the editor

It might be better in the long run to fix problems with the earlier steps rather than to override their results by manually adding include directories, symbols, etc.

Toolchains

If you have GCC installed, and Eclipse has detected it, it should list that GCC as a toolchain choice that a new C++ project could use, which will also show up in Window -> Preferences -> C/C++ -> New CDT Project Wizard on the Preferred Toolchains tab's Toolchains box on the right side. If it's not showing up, see the CDT FAQ's answer about compilers that need special environments (as well as MinGW and Cygwin answers for the Windows folk.)

If you have an existing Eclipse C++ project, you can change the associated toolchain by opening the project properties, and going to C/C++ Build -> Tool Chain Editor and choosing the toolchain you want from the Current toolchain: pulldown. (You'll have to uncheck the Display compatible toolchains only box first if the toolchain you want is different enough from the one that was previously set in the project.)

If you added a toolchain to the system after launching Eclipse, you will need to restart it for it to detect the toolchain.

Discovery

Then, if the project's C/C++ Build -> Discovery Options -> Discovery profiles scope is set to Per Language, during the next build the new toolchain associated with the project will be used for auto-discovery of include paths and symbols, and will be used to update the "built-in" paths and symbols that show up in the project's C/C++ General -> Paths and Symbols in the Includes and Symbols tabs.

Indexing

Sometimes you need to re-index again after setting the toolchain and doing a build to get the old symbol warnings to go away; right-click on the project folder and go to Index -> Rebuild to do it.

(tested with Eclipse 3.7.2 / CDT 8)

PHP PDO: charset, set names?

For completeness, there're actually three ways to set the encoding when connecting to MySQL from PDO and which ones are available depend on your PHP version. The order of preference would be:

  1. charset parameter in the DSN string
  2. Run SET NAMES utf8 with PDO::MYSQL_ATTR_INIT_COMMAND connection option
  3. Run SET NAMES utf8 manually

This sample code implements all three:

<?php

define('DB_HOST', 'localhost');
define('DB_SCHEMA', 'test');
define('DB_USER', 'test');
define('DB_PASSWORD', 'test');
define('DB_ENCODING', 'utf8');


$dsn = 'mysql:host=' . DB_HOST . ';dbname=' . DB_SCHEMA;
$options = array(
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
);

if( version_compare(PHP_VERSION, '5.3.6', '<') ){
    if( defined('PDO::MYSQL_ATTR_INIT_COMMAND') ){
        $options[PDO::MYSQL_ATTR_INIT_COMMAND] = 'SET NAMES ' . DB_ENCODING;
    }
}else{
    $dsn .= ';charset=' . DB_ENCODING;
}

$conn = @new PDO($dsn, DB_USER, DB_PASSWORD, $options);

if( version_compare(PHP_VERSION, '5.3.6', '<') && !defined('PDO::MYSQL_ATTR_INIT_COMMAND') ){
    $sql = 'SET NAMES ' . DB_ENCODING;
    $conn->exec($sql);
}

Doing all three is probably overkill (unless you're writing a class you plan to distribute or reuse).

MongoDB: Server has startup warnings ''Access control is not enabled for the database''

Mongodb v3.4

You need to do the following to create a secure database:

Make sure the user starting the process has permissions and that the directories exist (/data/db in this case).

1) Start MongoDB without access control.

mongod --port 27017 --dbpath /data/db

2) Connect to the instance.

mongo --port 27017

3) Create the user administrator (in the admin authentication database).

use admin
db.createUser(
  {
    user: "myUserAdmin",
    pwd: "abc123",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
  }
)

4) Re-start the MongoDB instance with access control.

mongod --auth --port 27017 --dbpath /data/db

5) Connect and authenticate as the user administrator.

mongo --port 27017 -u "myUserAdmin" -p "abc123" --authenticationDatabase "admin"

6) Create additional users as needed for your deployment (e.g. in the test authentication database).

use test
db.createUser(
  {
    user: "myTester",
    pwd: "xyz123",
    roles: [ { role: "readWrite", db: "test" },
             { role: "read", db: "reporting" } ]
  }
)

7) Connect and authenticate as myTester.

mongo --port 27017 -u "myTester" -p "xyz123" --authenticationDatabase "test"

I basically just explained the short version of the official docs here: https://docs.mongodb.com/master/tutorial/enable-authentication/

Why I can't access remote Jupyter Notebook server?

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

see this answer

When is assembly faster than C?

Short answer? Sometimes.

Technically every abstraction has a cost and a programming language is an abstraction for how the CPU works. C however is very close. Years ago I remember laughing out loud when I logged onto my UNIX account and got the following fortune message (when such things were popular):

The C Programming Language -- A language which combines the flexibility of assembly language with the power of assembly language.

It's funny because it's true: C is like portable assembly language.

It's worth noting that assembly language just runs however you write it. There is however a compiler in between C and the assembly language it generates and that is extremely important because how fast your C code is has an awful lot to do with how good your compiler is.

When gcc came on the scene one of the things that made it so popular was that it was often so much better than the C compilers that shipped with many commercial UNIX flavours. Not only was it ANSI C (none of this K&R C rubbish), was more robust and typically produced better (faster) code. Not always but often.

I tell you all this because there is no blanket rule about the speed of C and assembler because there is no objective standard for C.

Likewise, assembler varies a lot depending on what processor you're running, your system spec, what instruction set you're using and so on. Historically there have been two CPU architecture families: CISC and RISC. The biggest player in CISC was and still is the Intel x86 architecture (and instruction set). RISC dominated the UNIX world (MIPS6000, Alpha, Sparc and so on). CISC won the battle for the hearts and minds.

Anyway, the popular wisdom when I was a younger developer was that hand-written x86 could often be much faster than C because the way the architecture worked, it had a complexity that benefitted from a human doing it. RISC on the other hand seemed designed for compilers so noone (I knew) wrote say Sparc assembler. I'm sure such people existed but no doubt they've both gone insane and been institutionalized by now.

Instruction sets are an important point even in the same family of processors. Certain Intel processors have extensions like SSE through SSE4. AMD had their own SIMD instructions. The benefit of a programming language like C was someone could write their library so it was optimized for whichever processor you were running on. That was hard work in assembler.

There are still optimizations you can make in assembler that no compiler could make and a well written assembler algoirthm will be as fast or faster than it's C equivalent. The bigger question is: is it worth it?

Ultimately though assembler was a product of its time and was more popular at a time when CPU cycles were expensive. Nowadays a CPU that costs $5-10 to manufacture (Intel Atom) can do pretty much anything anyone could want. The only real reason to write assembler these days is for low level things like some parts of an operating system (even so the vast majority of the Linux kernel is written in C), device drivers, possibly embedded devices (although C tends to dominate there too) and so on. Or just for kicks (which is somewhat masochistic).

How to push both key and value into an Array in Jquery

I think you need to define an object and then push in array

var obj = {};
obj[name] = val;
ary.push(obj);

Get timezone from DateTime

From the API (http://msdn.microsoft.com/en-us/library/system.datetime_members(VS.71).aspx) it does not seem it can show the name of the time zone used.

Multiple rows to one comma-separated value in Sql Server

Test Data

DECLARE @Table1 TABLE(ID INT, Value INT)
INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400)

Query

SELECT  ID
       ,STUFF((SELECT ', ' + CAST(Value AS VARCHAR(10)) [text()]
         FROM @Table1 
         WHERE ID = t.ID
         FOR XML PATH(''), TYPE)
        .value('.','NVARCHAR(MAX)'),1,2,' ') List_Output
FROM @Table1 t
GROUP BY ID

Result Set

+--------------------------+
¦ ID ¦     List_Output     ¦
¦----+---------------------¦
¦  1 ¦  100, 200, 300, 400 ¦
+--------------------------+

SQL Server 2017 and Later Versions

If you are working on SQL Server 2017 or later versions, you can use built-in SQL Server Function STRING_AGG to create the comma delimited list:

DECLARE @Table1 TABLE(ID INT, Value INT);
INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400);


SELECT ID , STRING_AGG([Value], ', ') AS List_Output
FROM @Table1
GROUP BY ID;

Result Set

+--------------------------+
¦ ID ¦     List_Output     ¦
¦----+---------------------¦
¦  1 ¦  100, 200, 300, 400 ¦
+--------------------------+

JSON.stringify output to div in pretty print way

print the state of a component with JSX

render() {
  return (
    <div>
      <h1>Adopt Me!</h1>
      <pre>
        <code>{JSON.stringify(this.state, null, 4)}</code>
      </pre>
    </div>
  );
}

stringify

Python TypeError: cannot convert the series to <class 'int'> when trying to do math on dataframe

Seems your initial data contains strings and not numbers. It would probably be best to ensure that the data is already of the required type up front.

However, you can convert strings to numbers like this:

pd.Series(['123', '42']).astype(float)

instead of float(series)

PDO support for multiple queries (PDO_MYSQL, PDO_MYSQLND)

PDO does support this (as of 2020). Just do a query() call on a PDO object as usual, separating queries by ; and then nextRowset() to step to the next SELECT result, if you have multiple. Resultsets will be in the same order as the queries. Obviously think about the security implications - so don't accept user supplied queries, use parameters, etc. I use it with queries generated by code for example.

$statement = $connection->query($query);
do {
  $data[] = $statement->fetchAll(PDO::FETCH_ASSOC);
} while ($statement->nextRowset());

Create a sample login page using servlet and JSP?

You're comparing the message with the empty string using ==.

First, your comparison is wrong because the message will be null (and not the empty string).

Second, it's wrong because Objects must be compared with equals() and not with ==.

Third, it's wrong because you should avoid scriptlets in JSP, and use the JSP EL, the JSTL, and other custom tags instead:

<c:id test="${!empty message}">
    <c:out value="${message}"/>
</c:if>

How do I POST XML data to a webservice with Postman?

Send XML requests with the raw data type, then set the Content-Type to text/xml.


  1. After creating a request, use the dropdown to change the request type to POST.

    Set request type to POST

  2. Open the Body tab and check the data type for raw.

    Setting data type to raw

  3. Open the Content-Type selection box that appears to the right and select either XML (application/xml) or XML (text/xml)

    Selecting content-type text/xml

  4. Enter your raw XML data into the input field below

    Example of XML request in Postman

  5. Click Send to submit your XML Request to the specified server.

    Clicking the Send button

How to set headers in http get request?

The Header field of the Request is public. You may do this :

req.Header.Set("name", "value")

How can I get the UUID of my Android phone in an application?

As of API 26, getDeviceId() is deprecated. If you need to get the IMEI of the device, use the following:

 String deviceId = "";
    if (Build.VERSION.SDK_INT >= 26) {
        deviceId = getSystemService(TelephonyManager.class).getImei();
    }else{
        deviceId = getSystemService(TelephonyManager.class).getDeviceId();
    }

Submit a form using jQuery

Use it to submit your form using jquery. Here is the link http://api.jquery.com/submit/

<form id="form" method="post" action="#">
    <input type="text" id="input">
    <input type="button" id="button" value="Submit">
</form>

<script type="text/javascript">
$(document).ready(function () {
    $( "#button" ).click(function() {
        $( "#form" ).submit();
    });
});
</script>

What does upstream mean in nginx?

If we have a single server we can directly include it in the proxy_pass. But in case if we have many servers we use upstream to maintain the servers. Nginx will load-balance based on the incoming traffic.

Is there an opposite to display:none?

display:unset sets it back to some initial setting, not to the previous "display" values

i just copied the previous display value (in my case display: flex;) again(after display non), and it overtried the display:none successfuly

(i used display:none for hiding elements for mobile and small screens)

How to convert a Title to a URL slug in jQuery?

All you needed was a plus :)

$("#Restaurant_Name").keyup(function(){
        var Text = $(this).val();
        Text = Text.toLowerCase();
        var regExp = /\s+/g;
        Text = Text.replace(regExp,'-');
        $("#Restaurant_Slug").val(Text);        
});

How to detect input type=file "change" for the same file?

So, there is no way to 100% be sure they are selecting the same file unless you store each file and compare them programmatically.

The way you interact with files (what JS does when the user 'uploads' a file) is HTML5 File API and JS FileReader.

https://www.html5rocks.com/en/tutorials/file/dndfiles/

https://scotch.io/tutorials/use-the-html5-file-api-to-work-with-files-locally-in-the-browser

These tutorials show you how to capture and read the metadata (stored as js object) when a file is uploaded.

Create a function that fires 'onChange' that will read->store->compare metadata of the current file against the previous files. Then you can trigger your event when the desired file is selected.

How to force reloading a page when using browser back button?

You can use pageshow event to handle situation when browser navigates to your page through history traversal:

window.addEventListener( "pageshow", function ( event ) {
  var historyTraversal = event.persisted || 
                         ( typeof window.performance != "undefined" && 
                              window.performance.navigation.type === 2 );
  if ( historyTraversal ) {
    // Handle page restore.
    window.location.reload();
  }
});

Note that HTTP cache may be involved too. You need to set proper cache related HTTP headers on server to cache only those resources that need to be cached. You can also do forced reload to instuct browser to ignore HTTP cache: window.location.reload( true ). But I don't think that it is best solution.

For more information check:

Can an Android Toast be longer than Toast.LENGTH_LONG?

The values of LENGTH_SHORT and LENGTH_LONG are 0 and 1. This means they are treated as flags rather than actual durations so I don't think it will be possible to set the duration to anything other than these values.

If you want to display a message to the user for longer, consider a Status Bar Notification. Status Bar Notifications can be programmatically canceled when they are no longer relevant.

Moq, SetupGet, Mocking a property

But while mocking read-only properties means properties with getter method only you should declare it as virtual otherwise System.NotSupportedException will be thrown because it is only supported in VB as moq internally override and create proxy when we mock anything.

How to convert minutes to Hours and minutes (hh:mm) in java

(In Kotlin) If you are going to put the answer into a TextView or something you can instead use a string resource:

<string name="time">%02d:%02d</string>

And then you can use this String resource to then set the text at run time using:

private fun setTime(time: Int) {
    val hour = time / 60
    val min = time % 60
    main_time.text = getString(R.string.time, hour, min)
}

In OS X Lion, LANG is not set to UTF-8, how to fix it?

I noticed the exact same issue when logging onto servers running Red Hat from an OSX Lion machine.

Try adding or editing the ~/.profile file for it to correctly export your locale settings upon initiating a new session.

export LC_ALL=en_US.UTF-8  
export LANG=en_US.UTF-8

These two lines added to the file should suffice to set the locale [replace en_US for your desired locale, and check beforehand that it is indeed installed on your system (locale -a)].

After that, you can start a new session and check using locale:

$ locale

The following should be the output:

LANG="en_US.UTF-8"  
LC_COLLATE="en_US.UTF-8"  
LC_CTYPE="en_US.UTF-8"  
LC_MESSAGES="en_US.UTF-8"  
LC_MONETARY="en_US.UTF-8"  
LC_NUMERIC="en_US.UTF-8"  
LC_TIME="en_US.UTF-8"  
LC_ALL="en_US.UTF-8"  

How to grant all privileges to root user in MySQL 8.0

Starting with MySQL 8 you no longer can (implicitly) create a user using the GRANT command. Use CREATE USER instead, followed by the GRANT statement:

mysql> CREATE USER 'root'@'%' IDENTIFIED BY 'root';
mysql> GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' WITH GRANT OPTION;

Caution about the security risks about WITH GRANT OPTION, see:

Convert pyQt UI to python

For pyqt5 you can use

pyuic5 xyz.ui > xyz.py 

or

pyuic5 xyz.ui -o xyz.py

Push local Git repo to new remote including all branches and tags

Here is another take on the same thing which worked better for the situation I was in. It solves the problem where you have more than one remote, would like to clone all branches in remote source to remote destination but without having to check them all out beforehand.

(The problem I had with Daniel's solution was that it would refuse to checkout a tracking branch from the source remote if I had previously checked it out already, ie, it would not update my local branch before the push)

git push destination +refs/remotes/source/*:refs/heads/*

Note: If you are not using direct CLI, you must escape the asterisks:

git push destination +refs/remotes/source/\*:refs/heads/\*

this will push all branches in remote source to a head branch in destination, possibly doing a non-fast-forward push. You still have to push tags separately.

Maximum size of an Array in Javascript

I have shamelessly pulled some pretty big datasets in memory, and altough it did get sluggish it took maybe 15 Mo of data upwards with pretty intense calculations on the dataset. I doubt you will run into problems with memory unless you have intense calculations on the data and many many rows. Profiling and benchmarking with different mock resultsets will be your best bet to evaluate performance.

Error: Microsoft Visual C++ 10.0 is required (Unable to find vcvarsall.bat) when running Python script

you have to check your pip package to be updated to the latest version in your pycharm and then install numpy package. in settings -> project:progLangComp -> Project Interpreter there is a table of packages and their current version (just labelled as Version) and their latest version (labelled as Latest). Pip current version number should be the same as latest version. If you see a blue arrow in front of pip, you have to update it to the latest then trying to install numpy or any other packages that you couldn't install, for me it was pandas which I wanted to install.

enter image description here

In nodeJs is there a way to loop through an array without using array size?

Use Iterators...

var myarray = ['hello', ' hello again'];
processArray(myarray[Symbol.iterator](), () => {
    console.log('all done')
})
function processArray(iter, cb) {
    var curr = iter.next()
    if(curr.done)
        return cb()
    console.log(curr.value)
    processArray(iter, cb)
}

More in depth overview: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols

How to test if JSON object is empty in Java

A JSON notation {} represents an empty object, meaning an object without members. This is not the same as null. Neither it is string as you are trying to compare it with string "{}". I don't know which json library are you using, but try to look for method something like:

isEmptyObject() 

Maven2: Best practice for Enterprise Project (EAR file)

i have made a github repository to show what i think is a good (or best practices) startup project structure...

https://github.com/StefanHeimberg/stackoverflow-1134894

some keywords:

  • Maven 3
  • BOM (DependencyManagement of own dependencies)
  • Parent for all Projects (DependencyManagement from external dependencies and PluginManagement for global Project configuration)
  • JUnit / Mockito / DBUnit
  • Clean War project without WEB-INF/lib because dependencies are in EAR/lib folder.
  • Clean Ear project.
  • Minimal deployment descriptors for Java EE7
  • No Local EJB Interface because @LocalBean is sufficient.
  • Minimal maven configuration through maven user properties
  • Actual Deployment Descriptors for Servlet 3.1 / EJB 3.2 / JPA 2.1
  • usage of macker-maven-plugin to check architecture rules
  • Integration Tests enabled, but skipped. (skipITs=false) useful to enable on CI Build Server

Maven Output:

Reactor Summary:

MyProject - BOM .................................... SUCCESS [  0.494 s]
MyProject - Parent ................................. SUCCESS [  0.330 s]
MyProject - Common ................................. SUCCESS [  3.498 s]
MyProject - Persistence ............................ SUCCESS [  1.045 s]
MyProject - Business ............................... SUCCESS [  1.233 s]
MyProject - Web .................................... SUCCESS [  1.330 s]
MyProject - Application ............................ SUCCESS [  0.679 s]
------------------------------------------------------------------------
BUILD SUCCESS
------------------------------------------------------------------------
Total time: 8.817 s
Finished at: 2015-01-27T00:51:59+01:00
Final Memory: 24M/207M
------------------------------------------------------------------------

Threading pool similar to the multiprocessing Pool?

If you don't mind executing other's code, here's mine:

Note: There is lot of extra code you may want to remove [added for better clarificaiton and demonstration how it works]

Note: Python naming conventions were used for method names and variable names instead of camelCase.

Working procedure:

  1. MultiThread class will initiate with no of instances of threads by sharing lock, work queue, exit flag and results.
  2. SingleThread will be started by MultiThread once it creates all instances.
  3. We can add works using MultiThread (It will take care of locking).
  4. SingleThreads will process work queue using a lock in middle.
  5. Once your work is done, you can destroy all threads with shared boolean value.
  6. Here, work can be anything. It can automatically import (uncomment import line) and process module using given arguments.
  7. Results will be added to results and we can get using get_results

Code:

import threading
import queue


class SingleThread(threading.Thread):
    def __init__(self, name, work_queue, lock, exit_flag, results):
        threading.Thread.__init__(self)
        self.name = name
        self.work_queue = work_queue
        self.lock = lock
        self.exit_flag = exit_flag
        self.results = results

    def run(self):
        # print("Coming %s with parameters %s", self.name, self.exit_flag)
        while not self.exit_flag:
            # print(self.exit_flag)
            self.lock.acquire()
            if not self.work_queue.empty():
                work = self.work_queue.get()
                module, operation, args, kwargs = work.module, work.operation, work.args, work.kwargs
                self.lock.release()
                print("Processing : " + operation + " with parameters " + str(args) + " and " + str(kwargs) + " by " + self.name + "\n")
                # module = __import__(module_name)
                result = str(getattr(module, operation)(*args, **kwargs))
                print("Result : " + result + " for operation " + operation + " and input " + str(args) + " " + str(kwargs))
                self.results.append(result)
            else:
                self.lock.release()
        # process_work_queue(self.work_queue)

class MultiThread:
    def __init__(self, no_of_threads):
        self.exit_flag = bool_instance()
        self.queue_lock = threading.Lock()
        self.threads = []
        self.work_queue = queue.Queue()
        self.results = []
        for index in range(0, no_of_threads):
            thread = SingleThread("Thread" + str(index+1), self.work_queue, self.queue_lock, self.exit_flag, self.results)
            thread.start()
            self.threads.append(thread)

    def add_work(self, work):
        self.queue_lock.acquire()
        self.work_queue._put(work)
        self.queue_lock.release()

    def destroy(self):
        self.exit_flag.value = True
        for thread in self.threads:
            thread.join()

    def get_results(self):
        return self.results


class Work:
    def __init__(self, module, operation, args, kwargs={}):
        self.module = module
        self.operation = operation
        self.args = args
        self.kwargs = kwargs


class SimpleOperations:
    def sum(self, *args):
        return sum([int(arg) for arg in args])

    @staticmethod
    def mul(a, b, c=0):
        return int(a) * int(b) + int(c)


class bool_instance:
    def __init__(self, value=False):
        self.value = value

    def __setattr__(self, key, value):
        if key != "value":
            raise AttributeError("Only value can be set!")
        if not isinstance(value, bool):
            raise AttributeError("Only True/False can be set!")
        self.__dict__[key] = value
        # super.__setattr__(key, bool(value))

    def __bool__(self):
        return self.value

if __name__ == "__main__":
    multi_thread = MultiThread(5)
    multi_thread.add_work(Work(SimpleOperations(), "mul", [2, 3], {"c":4}))
    while True:
        data_input = input()
        if data_input == "":
            pass
        elif data_input == "break":
            break
        else:
            work = data_input.split()
            multi_thread.add_work(Work(SimpleOperations(), work[0], work[1:], {}))
    multi_thread.destroy()
    print(multi_thread.get_results())

How to check if two words are anagrams

I saw that no one has used the "hashcode" approach to find out the anagrams. I found my approach little different than the approaches discussed above hence thought of sharing it. I wrote the below code to find the anagrams which works in O(n).

/**
 * This class performs the logic of finding anagrams
 * @author ripudam
 *
 */
public class AnagramTest {

    public static boolean isAnagram(final String word1, final String word2) {

            if (word1 == null || word2 == null || word1.length() != word2.length()) {
                 return false;
            }

            if (word1.equals(word2)) {
                return true;
            }

            final AnagramWrapper word1Obj = new AnagramWrapper(word1);
            final AnagramWrapper word2Obj = new AnagramWrapper(word2);

            if (word1Obj.equals(word2Obj)) {
                return true;
            }

            return false;
        }

        /*
         * Inner class to wrap the string received for anagram check to find the
         * hash
         */
        static class AnagramWrapper {
            String word;

            public AnagramWrapper(final String word) {
                this.word = word;
            }

            @Override
            public boolean equals(final Object obj) {

                return hashCode() == obj.hashCode();
            }

            @Override
            public int hashCode() {
                final char[] array = word.toCharArray();
                int hashcode = 0;
                for (final char c : array) {
                    hashcode = hashcode + (c * c);
                }
                return hashcode;
            }
         }
    }

How to change port number for apache in WAMP

Click on the WAMP server icon and from the menu under Config Files select httpd.conf. A long text file will open up in notepad. In this file scroll down to the line that reads Port 80 and change this to read Port 8080, Save the file and close notepad. Once again click on the wamp server icon and select restart all services. One more change needs to be made before we are done. In Windows Explorer find the location where WAMP server was installed which is by Default C:\Wamp.

How do I strip all spaces out of a string in PHP?

str_replace will do the trick thusly

$new_str = str_replace(' ', '', $old_str);

Set Label Text with JQuery

The checkbox is in a td, so need to get the parent first:

$("input:checkbox").on("change", function() {
    $(this).parent().next().find("label").text("TESTTTT");
});

Alternatively, find a label which has a for with the same id (perhaps more performant than reverse traversal) :

$("input:checkbox").on("change", function() {
    $("label[for='" + $(this).attr('id') + "']").text("TESTTTT");
});

Or, to be more succinct just this.id:

$("input:checkbox").on("change", function() {
    $("label[for='" + this.id + "']").text("TESTTTT");
});

Invoke(Delegate)

The answer to this question lies in how C# Controls work

Controls in Windows Forms are bound to a specific thread and are not thread safe. Therefore, if you are calling a control's method from a different thread, you must use one of the control's invoke methods to marshal the call to the proper thread. This property can be used to determine if you must call an invoke method, which can be useful if you do not know what thread owns a control.

From Control.InvokeRequired

Effectively, what Invoke does is ensure that the code you are calling occurs on the thread that the control "lives on" effectively preventing cross threaded exceptions.

From a historical perspective, in .Net 1.1, this was actually allowed. What it meant is that you could try and execute code on the "GUI" thread from any background thread and this would mostly work. Sometimes it would just cause your app to exit because you were effectively interrupting the GUI thread while it was doing something else. This is the Cross Threaded Exception - imagine trying to update a TextBox while the GUI is painting something else.

  • Which action takes priority?
  • Is it even possible for both to happen at once?
  • What happens to all of the other commands the GUI needs to run?

Effectively, you are interrupting a queue, which can have lots of unforeseen consequences. Invoke is effectively the "polite" way of getting what you want to do into that queue, and this rule was enforced from .Net 2.0 onward via a thrown InvalidOperationException.

To understand what is actually going on behind the scenes, and what is meant by "GUI Thread", it's useful to understand what a Message Pump or Message Loop is.

This is actually already answered in the question "What is a Message Pump" and is recommended reading for understanding the actual mechanism that you are tying into when interacting with controls.

Other reading you may find useful includes:

What's up with Begin Invoke

One of the cardinal rules of Windows GUI programming is that only the thread that created a control can access and/or modify its contents (except for a few documented exceptions). Try doing it from any other thread and you'll get unpredictable behavior ranging from deadlock, to exceptions to a half updated UI. The right way then to update a control from another thread is to post an appropriate message to the application message queue. When the message pump gets around to executing that message, the control will get updated, on the same thread that created it (remember, the message pump runs on the main thread).

and, for a more code heavy overview with a representative sample:

Invalid Cross-thread Operations

// the canonical form (C# consumer)

public delegate void ControlStringConsumer(Control control, string text);  // defines a delegate type

public void SetText(Control control, string text) {
    if (control.InvokeRequired) {
        control.Invoke(new ControlStringConsumer(SetText), new object[]{control, text});  // invoking itself
    } else {
        control.Text=text;      // the "functional part", executing only on the main thread
    }
}

Once you have an appreciation for InvokeRequired, you may wish to consider using an extension method for wrapping these calls up. This is ably covered in the Stack Overflow question Cleaning Up Code Littered with Invoke Required.

There is also a further write up of what happened historically that may be of interest.

Declare and initialize a Dictionary in Typescript

For using dictionary object in typescript you can use interface as below:

interface Dictionary<T> {
    [Key: string]: T;
}

and, use this for your class property type.

export class SearchParameters {
    SearchFor: Dictionary<string> = {};
}

to use and initialize this class,

getUsers(): Observable<any> {
        var searchParams = new SearchParameters();
        searchParams.SearchFor['userId'] = '1';
        searchParams.SearchFor['userName'] = 'xyz';

        return this.http.post(searchParams, 'users/search')
            .map(res => {
                return res;
            })
            .catch(this.handleError.bind(this));
    }

When should the xlsm or xlsb formats be used?

One could think that xlsb has only advantages over xlsm. The fact that xlsm is XML-based and xlsb is binary is that when workbook corruption occurs, you have better chances to repair a xlsm than a xlsb.

Accept function as parameter in PHP

Just code it like this:

function example($anon) {
  $anon();
}

example(function(){
  // some codes here
});

it would be great if you could invent something like this (inspired by Laravel Illuminate):

Object::method("param_1", function($param){
  $param->something();
});

How to implement a Navbar Dropdown Hover in Bootstrap v4?

This solution switches on and off

<script>
$(document).ready(function() {
  // close all dropdowns that are open
  $('body').click(function(e) {
      $('.nav-item.show').removeClass('show');
      //$('.nav-item.clicked').removeClass('clicked');
      $('.dropdown-menu.show').removeClass('show');
  });

  $('.nav-item').click( function(e) {
    $(this).addClass('clicked')
  });

  // show dropdown for the link clicked
  $('.nav-item').hover(function(e) {
      if ($('.nav-item.show').length < 1) {
        $('.nav-item.clicked').removeClass('clicked');
      }
      if ($('.nav-item.clicked').length < 1) {
          $('.nav-item.show').removeClass('show');
          $('.dropdown-menu.show').removeClass('show');
          $dd = $(this).find('.dropdown-menu');
          $dd.parent().addClass('show');
          $dd.addClass('show');
      }
  });
});</script>

To disable the hover for lg sized collapse menus add

if(( $(window).width() >= 992 )) {

Assign width to half available screen width declaratively

<LinearLayout 
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
    android:id="@+id/textD_Author"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="20dp"
    android:text="Author : "
    android:textColor="#0404B4"
    android:textSize="20sp" />
 <TextView
    android:id="@+id/textD_Tag"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="20dp"
    android:text="Edition : "
    android:textColor="#0404B4"
    android:textSize="20sp" />
<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal"
    android:weightSum="1" >
    <Button
        android:id="@+id/btbEdit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0.5"
        android:text="Edit" />
    <Button
        android:id="@+id/btnDelete"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0.5"
        android:text="Delete" />
</LinearLayout>
</LinearLayout>

Responsive background image in div full width

When you use background-size: cover the background image will automatically be stretched to cover the entire container. Aspect ratio is maintained however, so you will always lose part of the image, unless the aspect ratio of the image and the element it is applied to are identical.

I see two ways you could solve this:

  • Do not maintain the aspect ratio of the image by setting background-size: 100% 100% This will also make the image cover the entire container, but the ratio will not be maintained. Disadvantage is that this distorts your image, and therefore may look very weird, depending on the image. With the image you are using in the fiddle, I think you could get away with it though.

  • You could also calculate and set the height of the element with javascript, based on its width, so it gets the same ratio as the image. This calculation would have to be done on load and on resize. It should be easy enough with a few lines of code (feel free to ask if you want an example). Disadvantage of this method is that your width may become very small (on mobile devices), and therfore the calculated height also, which may cause the content of the container to overflow. This could be solved by changing the size of the content as well or something, but it adds some complexity to the solution/

How do I get the backtrace for all the threads in GDB?

Generally, the backtrace is used to get the stack of the current thread, but if there is a necessity to get the stack trace of all the threads, use the following command.

thread apply all bt

Convert a dta file to csv without Stata software

I have not tried, but if you know Perl you can use the Parse-Stata-DtaReader module to convert the file for you.

The module has a command-line tool dta2csv, which can "convert Stata 8 and Stata 10 .dta files to csv"

Split array into two parts without for loop in java

Use this code it works perfectly for odd or even list sizes. Hope it help somebody .

 int listSize = listOfArtist.size();
 int mid = 0;
 if (listSize % 2 == 0) {
    mid = listSize / 2;
    Log.e("Parting", "You entered an even number. mid " + mid
                    + " size is " + listSize);
 } else {
    mid = (listSize + 1) / 2;
    Log.e("Parting", "You entered an odd number. mid " + mid
                    + " size is " + listSize);
 }
 //sublist returns List convert it into arraylist * very important
 leftArray = new ArrayList<ArtistModel>(listOfArtist.subList(0, mid));
 rightArray = new ArrayList<ArtistModel>(listOfArtist.subList(mid,
                listSize));

Vue.js get selected option on @change

You can save your @change="onChange()" an use watchers. Vue computes and watches, it´s designed for that. In case you only need the value and not other complex Event atributes.

Something like:

  ...
  watch: {
    leaveType () {
      this.whateverMethod(this.leaveType)
    }
  },
  methods: {
     onChange() {
         console.log('The new value is: ', this.leaveType)
     }
  }

Fastest method of screen capturing on Windows

For C++ you can use: http://www.pinvoke.net/default.aspx/gdi32/BitBlt.html
This may hower not work on all types of 3D applications/video apps. Then this link may be more useful as it describes 3 different methods you can use.

Old answer (C#):
You can use System.Drawing.Graphics.Copy, but it is not very fast.

A sample project I wrote doing exactly this: http://blog.tedd.no/index.php/2010/08/16/c-image-analysis-auto-gaming-with-source/

I'm planning to update this sample using a faster method like Direct3D: http://spazzarama.com/2009/02/07/screencapture-with-direct3d/

And here is a link for capturing to video: How to capture screen to be video using C# .Net?

Convert INT to DATETIME (SQL)

you need to convert to char first because converting to int adds those days to 1900-01-01

select CONVERT (datetime,convert(char(8),rnwl_efctv_dt ))

here are some examples

select CONVERT (datetime,5)

1900-01-06 00:00:00.000

select CONVERT (datetime,20100101)

blows up, because you can't add 20100101 days to 1900-01-01..you go above the limit

convert to char first

declare @i int
select @i = 20100101
select CONVERT (datetime,convert(char(8),@i))

Spring get current ApplicationContext

Simply inject it..

@Autowired
private ApplicationContext appContext;

or implement this interface: ApplicationContextAware

Single vs double quotes in JSON

import json
data = json.dumps(list)
print(data)

The above code snippet should work.

How to autosize and right-align GridViewColumn data in WPF?

If the width of the contents changes, you'll have to use this bit of code to update each column:

private void ResizeGridViewColumn(GridViewColumn column)
{
    if (double.IsNaN(column.Width))
    {
        column.Width = column.ActualWidth;
    }

    column.Width = double.NaN;
}

You'd have to fire it each time the data for that column updates.

Display help message with python argparse when script is called without any arguments

With argparse you could do:

parser.argparse.ArgumentParser()
#parser.add_args here

#sys.argv includes a list of elements starting with the program
if len(sys.argv) < 2:
    parser.print_usage()
    sys.exit(1)

Sending message through WhatsApp

this is much lengthy but surly working. enjoy your code:)

 //method used to show IMs
private void show_custom_chooser(String value) {
    List<ResolveInfo> list = null;
    final Intent email = new Intent(Intent.ACTION_SEND);
    email.setData(Uri.parse("sms:"));
    email.putExtra(Intent.EXTRA_TEXT, "" + value);
    email.setType("text/plain"); // vnd.android-dir/mms-sms

    WindowManager.LayoutParams WMLP = dialogCustomChooser.getWindow()
            .getAttributes();
    WMLP.gravity = Gravity.CENTER;
    dialogCustomChooser.getWindow().setAttributes(WMLP);
    dialogCustomChooser.getWindow().setBackgroundDrawable(
            new ColorDrawable(android.graphics.Color.TRANSPARENT));
    dialogCustomChooser.setCanceledOnTouchOutside(true);
    dialogCustomChooser.setContentView(R.layout.about_dialog);
    dialogCustomChooser.setCancelable(true);
    ListView lvOfIms = (ListView) dialogCustomChooser
            .findViewById(R.id.listView1);
    PackageManager pm = getPackageManager();
    List<ResolveInfo> launchables = pm.queryIntentActivities(email, 0);
    // ////////////new
    list = new ArrayList<ResolveInfo>();
    for (int i = 0; i < launchables.size(); i++) {
        String string = launchables.get(i).toString();
        Log.d("heh", string);
//check only messangers
        if (string.contains("whatsapp")) {
            list.add(launchables.get(i));
        }
    }
    Collections.sort(list, new ResolveInfo.DisplayNameComparator(pm));
    int size = launchables.size();
    adapter = new AppAdapter(pm, list, MainActivity.this);
    lvOfIms.setAdapter(adapter);
    lvOfIms.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1,
                int position, long arg3) {
            ResolveInfo launchable = adapter.getItem(position);
            ActivityInfo activity = launchable.activityInfo;
            ComponentName name = new ComponentName(
                    activity.applicationInfo.packageName, activity.name);
            email.addCategory(Intent.CATEGORY_LAUNCHER);
            email.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                    | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
            email.setComponent(name);
            startActivity(email);
            dialogCustomChooser.dismiss();
        }
    });
    dialogCustomChooser.show();

}

How to override the [] operator in Python?

You need to use the __getitem__ method.

class MyClass:
    def __getitem__(self, key):
        return key * 2

myobj = MyClass()
myobj[3] #Output: 6

And if you're going to be setting values you'll need to implement the __setitem__ method too, otherwise this will happen:

>>> myobj[5] = 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: MyClass instance has no attribute '__setitem__'

Error handling in AngularJS http get then construct

You can make this bit more cleaner by using:

$http.get(url)
    .then(function (response) {
        console.log('get',response)
    })
    .catch(function (data) {
        // Handle error here
    });

Similar to @this.lau_ answer, different approach.

Razor View Without Layout

Logic for determining if a View should use a layout or not should NOT be in the _viewStart nor the View. Setting a default in _viewStart is fine, but adding any layout logic in the view/viewstart prevents that view from being used anywhere else (with or without layout).

Your Controller Action should:

return PartialView()

By putting this type of logic in the View you breaking the Single responsibility principle rule in M (data), V (visual), C (logic).

jQuery click event not working after adding class

.live() is deprecated.When you want to use for delegated elements then use .on() wiht the following syntax

$(document).on('click', "a.tabclick", function() {

This syntax will work for delegated events

.on()

Remove characters except digits from string using Python?

Use re.sub, like so:

>>> import re
>>> re.sub('\D', '', 'aas30dsa20')
'3020'

\D matches any non-digit character so, the code above, is essentially replacing every non-digit character for the empty string.

Or you can use filter, like so (in Python 2):

>>> filter(str.isdigit, 'aas30dsa20')
'3020'

Since in Python 3, filter returns an iterator instead of a list, you can use the following instead:

>>> ''.join(filter(str.isdigit, 'aas30dsa20'))
'3020'

Select row on click react-table

I found the solution after a few tries, I hope this can help you. Add the following to your <ReactTable> component:

getTrProps={(state, rowInfo) => {
  if (rowInfo && rowInfo.row) {
    return {
      onClick: (e) => {
        this.setState({
          selected: rowInfo.index
        })
      },
      style: {
        background: rowInfo.index === this.state.selected ? '#00afec' : 'white',
        color: rowInfo.index === this.state.selected ? 'white' : 'black'
      }
    }
  }else{
    return {}
  }
}

In your state don't forget to add a null selected value, like:

state = { selected: null }

Launch iOS simulator from Xcode and getting a black screen, followed by Xcode hanging and unable to stop tasks

When i have carried my project on Xcode 11.1, i got that problem. That black screen problem may occur any presentation inter ViewControllers.

That answer helped me. Because modal presentation changed with iOS 13. If you don't get that problem before iOS 13, please try to add line below to your ViewController before its presentation;

viewController.modalPresentationStyle = .fullScreen

after your code may seem like below;

let vc = UIViewController()
vc.modalPresentationStyle = .fullScreen //or .overFullScreen for transparency
self.present(vc, animated: true, completion: nil)

Good ways to manage a changelog using git?

Based on bithavoc, it lists the last tag until HEAD. But I hope to list the logs between 2 tags.

// 2 or 3 dots between `YOUR_LAST_VERSION_TAG` and `HEAD`
git log YOUR_LAST_VERSION_TAG..HEAD --no-merges --format=%B

List logs between 2 tags.

// 2 or 3 dots between 2 tags
git log FROM_TAG...TO_TAG

For example, it will list logs from v1.0.0 to v1.0.1.

git log v1.0.0...v1.0.1 --oneline --decorate

Lombok added but getters and setters not recognized in Intellij IDEA

Complete steps to fix or configure lombok.

1. Add dependency

<dependency>
          <groupId>org.projectlombok</groupId>
          <artifactId>lombok</artifactId>
          <version>1.18.8</version>
          <scope>provided</scope>
      </dependency>

2. Install the plugin of Lombok for ide. File > Settings > Plugins > Search (lombok) > install

3.Ticking the "Enable annotation processing" checkbox using below steps:- Settings->Compiler->Annotation Processors

4.Restart for change to take effect.

How to sort strings in JavaScript

I had been bothered about this for long, so I finally researched this and give you this long winded reason for why things are the way they are.

From the spec:

Section 11.9.4   The Strict Equals Operator ( === )

The production EqualityExpression : EqualityExpression === RelationalExpression
is evaluated as follows: 
- Let lref be the result of evaluating EqualityExpression.
- Let lval be GetValue(lref).
- Let rref be the result of evaluating RelationalExpression.
- Let rval be GetValue(rref).
- Return the result of performing the strict equality comparison 
  rval === lval. (See 11.9.6)

So now we go to 11.9.6

11.9.6   The Strict Equality Comparison Algorithm

The comparison x === y, where x and y are values, produces true or false. 
Such a comparison is performed as follows: 
- If Type(x) is different from Type(y), return false.
- If Type(x) is Undefined, return true.
- If Type(x) is Null, return true.
- If Type(x) is Number, then
...
- If Type(x) is String, then return true if x and y are exactly the 
  same sequence of characters (same length and same characters in 
  corresponding positions); otherwise, return false.

That's it. The triple equals operator applied to strings returns true iff the arguments are exactly the same strings (same length and same characters in corresponding positions).

So === will work in the cases when we're trying to compare strings which might have arrived from different sources, but which we know will eventually have the same values - a common enough scenario for inline strings in our code. For example, if we have a variable named connection_state, and we wish to know which one of the following states ['connecting', 'connected', 'disconnecting', 'disconnected'] is it in right now, we can directly use the ===.

But there's more. Just above 11.9.4, there is a short note:

NOTE 4     
  Comparison of Strings uses a simple equality test on sequences of code 
  unit values. There is no attempt to use the more complex, semantically oriented
  definitions of character or string equality and collating order defined in the 
  Unicode specification. Therefore Strings values that are canonically equal
  according to the Unicode standard could test as unequal. In effect this 
  algorithm assumes that both Strings are already in normalized form.

Hmm. What now? Externally obtained strings can, and most likely will, be weird unicodey, and our gentle === won't do them justice. In comes localeCompare to the rescue:

15.5.4.9   String.prototype.localeCompare (that)
    ...
    The actual return values are implementation-defined to permit implementers 
    to encode additional information in the value, but the function is required 
    to define a total ordering on all Strings and to return 0 when comparing
    Strings that are considered canonically equivalent by the Unicode standard. 

We can go home now.

tl;dr;

To compare strings in javascript, use localeCompare; if you know that the strings have no non-ASCII components because they are, for example, internal program constants, then === also works.

How to determine programmatically the current active profile using Spring boot

It doesn't matter is your app Boot or just raw Spring. There is just enough to inject org.springframework.core.env.Environment to your bean.

@Autowired
private Environment environment;
....

this.environment.getActiveProfiles();

Bundler::GemNotFound: Could not find rake-10.3.2 in any of the sources

If you're having this issue, and try to run bundle exec jekyll serve per this Jekyll documentation, it'll ask you to run bundle install, which should prompt you to install any missing gems, which in this case will be rake. This should resolve your issue.

You may also need to run bundle update to ensure Gemfile.lock is referencing the most up-to-date gems.

To get specific part of a string in c#

To avoid getting expections at run time , do something like this.

There are chances of having empty string sometimes,

string a = "abc,xyz,wer";
string b=string.Empty;

if(!string.IsNullOrEmpty(a ))
{
  b = a.Split(',')[0];
}

Change icon on click (toggle)

If your icon is based on the text in the block (ligatures) rather the class of the block then the following will work. This example uses the Google Material Icons '+' and '-' icons as part of MaterializeCSS.

<a class="btn-class"><i class="material-icons">add</i></a>

$('.btn-class').on('click',function(){
    if ($(this).find('i').text() == 'add'){
        $(this).find('i').text('remove');
    } else {
        $(this).find('i').text('add');
    }
});

Edit: Added missing ); needed for this to function properly.

It also works for JQuery post 1.9 where toggling of functions was deprecated.

java.sql.SQLException: Incorrect string value: '\xF0\x9F\x91\xBD\xF0\x9F...'

I had kind of the same problem and after going carefully against all charsets and finding that they were all right, I realized that the bugged property I had in my class was annotated as @Column instead of @JoinColumn (javax.presistence; hibernate) and it was breaking everything up.

Implement Validation for WPF TextBoxes

I have implemented this validation. But you would be used code behind. It is too much easy and simplest way.

XAML: For name Validtion only enter character from A-Z and a-z.

<TextBox x:Name="first_name_texbox" PreviewTextInput="first_name_texbox_PreviewTextInput" >  </TextBox>

Code Behind.

private void first_name_texbox_PreviewTextInput ( object sender, TextCompositionEventArgs e )
{
    Regex regex = new Regex ( "[^a-zA-Z]+" );
    if ( regex.IsMatch ( first_name_texbox.Text ) )
    {
        MessageBox.Show("Invalid Input !");
    }
}

For Salary and ID validation, replace regex constructor passed value with [0-9]+. It means you can only enter number from 1 to infinite.

You can also define length with [0-9]{1,4}. It means you can only enter less then or equal to 4 digit number. This baracket means {at least,How many number}. By doing this you can define range of numbers in textbox.

May it help to others.

XAML:

Code Behind.

private void salary_texbox_PreviewTextInput ( object sender, TextCompositionEventArgs e )
{
    Regex regex = new Regex ( "[^0-9]+" );
    if ( regex.IsMatch ( salary_texbox.Text ) )
    {
        MessageBox.Show("Invalid Input !");
    }
}

How can I tell what edition of SQL Server runs on the machine?

You can get just the edition (plus under individual properties) using SERVERPROPERTY

e.g.

SELECT SERVERPROPERTY('Edition')

Quote (for "Edition"):

Installed product edition of the instance of SQL Server. Use the value of this property to determine the features and the limits, such as maximum number of CPUs, that are supported by the installed product.
Returns:
'Desktop Engine' (Not available for SQL Server 2005.)
'Developer Edition'
'Enterprise Edition'
'Enterprise Evaluation Edition'
'Personal Edition'(Not available for SQL Server 2005.)
'Standard Edition'
'Express Edition'
'Express Edition with Advanced Services'
'Workgroup Edition'
'Windows Embedded SQL'
Base data type: nvarchar(128)

Converting a Date object to a calendar object

Here's your method:

public static Calendar toCalendar(Date date){ 
  Calendar cal = Calendar.getInstance();
  cal.setTime(date);
  return cal;
}

Everything else you are doing is both wrong and unnecessary.

BTW, Java Naming conventions suggest that method names start with a lower case letter, so it should be: dateToCalendar or toCalendar (as shown).


OK, let's milk your code, shall we?

DateFormat formatter = new SimpleDateFormat("yyyyMMdd");
date = (Date)formatter.parse(date.toString()); 

DateFormat is used to convert Strings to Dates (parse()) or Dates to Strings (format()). You are using it to parse the String representation of a Date back to a Date. This can't be right, can it?

How to Configure SSL for Amazon S3 bucket

I found you can do this easily via the Cloud Flare service.

Set up a bucket, enable webhosting on the bucket and point the desired CNAME to that endpoint via Cloudflare... and pay for the service of course... but $5-$20 VS $600 is much easier to stomach.

Full detail here: https://www.engaging.io/easy-way-to-configure-ssl-for-amazon-s3-bucket-via-cloudflare/

MySQL: How to set the Primary Key on phpMyAdmin?

You can view the INDEXES column below where you find a default PRIMARY KEY is set. If it is not set or you want to set any other variable as a PRIMARY KEY then , there is a dialog box below to create an index which asks for a column number ,either way you can create a new one or edit an existing one.The existing one shows up a edit button whee you can go and edit it and you're done save it and you are ready to go

How to get table list in database, using MS SQL 2008?

This should give you a list of all the tables in your database

SELECT Distinct TABLE_NAME FROM information_schema.TABLES

So you can use it similar to your database check.

If NOT EXISTS(SELECT Distinct TABLE_NAME FROM information_schema.TABLES Where TABLE_NAME = 'Your_Table')
BEGIN
    --CREATE TABLE Your_Table
END
GO

Auto-click button element on page load using jQuery

We should rather use Javascript.

    <button href="images/car.jpg" id="myButton">
        Here is the Button to be clicked
    </button>


    <script>

        $(document).ready(function(){
            document.getElementById("myButton").click();
        });

    </script>

How do I access Configuration in any class in ASP.NET Core?

I have to read own parameters by startup.
That has to be there before the WebHost is started (as I need the “to listen” url/IP and port from the parameter file and apply it to the WebHost). Further, I need the settings public in the whole application.

After searching for a while (no complete example found, only snippets) and after various try-and-error's, I have decided to do it the “old way" with an own .ini file.
So.. if you want to use your own .ini file and/or set the "to listen url/IP" your own and/or need the settings public, this is for you...

Complete example, valid for core 2.1 (mvc):

Create an .ini-file - example:

[Startup]
URL=http://172.16.1.201:22222
[Parameter]
*Dummy1=gew7623
Dummy1=true
Dummy2=1

whereby the Dummyx are only included as example for other date types than string (and also to test the case “wrong param” (see code below).

Added a code file in the root of the project, to store the global variables:

namespace MatrixGuide
{
    public static class GV
    {
        // In this class all gobals are defined

        static string _cURL;
        public static string cURL // URL (IP + Port) on that the application has to listen
        {
            get { return _cURL; }
            set { _cURL = value; }
        }

        static bool _bdummy1;
        public static bool bdummy1 // 
        {
            get { return _bdummy1; }
            set { _bdummy1 = value; }
        }

        static int _idummy1;
        public static int idummy1 // 
        {
            get { return _idummy1; }
            set { _idummy1 = value; }
        }

        static bool _bFehler_Ini;
        public static bool bFehler_Ini // 
        {
            get { return _bFehler_Ini; }
            set { _bFehler_Ini = value; }
        }

        // add further  GV variables here..
    }
    // Add further classes here... 
}

Changed the code in program.cs (before CreateWebHostBuilder()):

namespace MatrixGuide
{
    public class Program
    {
        public static void Main(string[] args)
        {
            // Read .ini file and overtake the contend in globale
            // Do it in an try-catch to be able to react to errors
            GV.bFehler_Ini = false;
            try
            {
                var iniconfig = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddIniFile("matrixGuide.ini", optional: false, reloadOnChange: true)
                .Build();
                string cURL = iniconfig.GetValue<string>("Startup:URL");
                bool bdummy1 = iniconfig.GetValue<bool>("Parameter:Dummy1");
                int idummy2 = iniconfig.GetValue<int>("Parameter:Dummy2");
                //
                GV.cURL = cURL;
                GV.bdummy1 = bdummy1;
                GV.idummy1 = idummy2;
            }
            catch (Exception e)
            {
                GV.bFehler_Ini = true;
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("!! Fehler beim Lesen von MatrixGuide.ini !!");
                Console.WriteLine("Message:" + e.Message);
                if (!(e.InnerException != null))
                {
                    Console.WriteLine("InnerException: " + e.InnerException.ToString());
                }

                Console.ForegroundColor = ConsoleColor.White;
            }
            // End .ini file processing
            //
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>() //;
            .UseUrls(GV.cURL, "http://localhost:5000"); // set the to use URL from .ini -> no impact to IISExpress

    }
}

This way:

  • My Application config is separated from the appsettings.json and I have no sideeffects to fear, if MS does changes in future versions ;-)
  • I have my settings in global variables
  • I am able to set the "to listen url" for each device, the applicaton run's on (my dev machine, the intranet server and the internet server)
  • I'm able to deactivate settings, the old way (just set a * before)
  • I'm able to react, if something is wrong in the .ini file (e.g. type mismatch)
    If - e.g. - a wrong type is set (e.g. the *Dummy1=gew7623 is activated instead of the Dummy1=true) the host shows red information's on the console (including the exception) and I' able to react also in the application (GV.bFehler_Ini ist set to true, if there are errors with the .ini)

CSS div element - how to show horizontal scroll bars only?

You shouldn't get both horizontal and vertical scrollbars unless you make the content large enough to require them.

However you typically do in IE due to a bug. Check in other browsers (Firefox etc.) to find out whether it is in fact only IE that is doing it.

IE6-7 (amongst other browsers) supports the proposed CSS3 extension to set scrollbars independently, which you could use to suppress the vertical scrollbar:

overflow: auto;
overflow-y: hidden;

You may also need to add for IE8:

-ms-overflow-y: hidden;

as Microsoft are threatening to move all pre-CR-standard properties into their own ‘-ms’ box in IE8 Standards Mode. (This would have made sense if they'd always done it that way, but is rather an inconvenience for everyone now.)

On the other hand it's entirely possible IE8 will have fixed the bug anyway.

How to show "if" condition on a sequence diagram?

Very simple , using Alt fragment

Lets take an example of sequence diagram for an ATM machine.Let's say here you want

IF card inserted is valid then prompt "Enter Pin"....ELSE prompt "Invalid Pin"

Then here is the sequence diagram for the same

ATM machine sequence diagram

Hope this helps!

How can I print using JQuery

There is a jquery print area. I've been using it for some time now.

$(".printMe").click(function(){
   $("#outprint").printArea({ mode: 'popup', popClose: true });
});

Android ImageView Zoom-in and Zoom-Out

It's old, but this may help someone else.

Below TouchImageView class supports both zooming in/out on either pinch or double tap

import android.content.Context;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.widget.ImageView;

public class TouchImageView extends ImageView implements GestureDetector.OnGestureListener, GestureDetector.OnDoubleTapListener {

    Matrix matrix;

    // We can be in one of these 3 states
    static final int NONE = 0;
    static final int DRAG = 1;
    static final int ZOOM = 2;
    int mode = NONE;

    // Remember some things for zooming
    PointF last = new PointF();
    PointF start = new PointF();
    float minScale = 1f;
    float maxScale = 3f;
    float[] m;

    int viewWidth, viewHeight;
    static final int CLICK = 3;
    float saveScale = 1f;
    protected float origWidth, origHeight;
    int oldMeasuredWidth, oldMeasuredHeight;

    ScaleGestureDetector mScaleDetector;

    Context context;

    public TouchImageView(Context context) {
        super(context);
        sharedConstructing(context);
    }

    public TouchImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        sharedConstructing(context);
    }

    GestureDetector mGestureDetector;

    private void sharedConstructing(Context context) {
        super.setClickable(true);
        this.context = context;
        mGestureDetector = new GestureDetector(context, this);
        mGestureDetector.setOnDoubleTapListener(this);

        mScaleDetector = new ScaleGestureDetector(context, new ScaleListener());
        matrix = new Matrix();
        m = new float[9];
        setImageMatrix(matrix);
        setScaleType(ScaleType.MATRIX);

        setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                mScaleDetector.onTouchEvent(event);
                mGestureDetector.onTouchEvent(event);

                PointF curr = new PointF(event.getX(), event.getY());

                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        last.set(curr);
                        start.set(last);
                        mode = DRAG;
                        break;

                    case MotionEvent.ACTION_MOVE:
                        if (mode == DRAG) {
                            float deltaX = curr.x - last.x;
                            float deltaY = curr.y - last.y;
                            float fixTransX = getFixDragTrans(deltaX, viewWidth,
                                    origWidth * saveScale);
                            float fixTransY = getFixDragTrans(deltaY, viewHeight,
                                    origHeight * saveScale);
                            matrix.postTranslate(fixTransX, fixTransY);
                            fixTrans();
                            last.set(curr.x, curr.y);
                        }
                        break;

                    case MotionEvent.ACTION_UP:
                        mode = NONE;
                        int xDiff = (int) Math.abs(curr.x - start.x);
                        int yDiff = (int) Math.abs(curr.y - start.y);
                        if (xDiff < CLICK && yDiff < CLICK)
                            performClick();
                        break;

                    case MotionEvent.ACTION_POINTER_UP:
                        mode = NONE;
                        break;
                }

                setImageMatrix(matrix);
                invalidate();
                return true; // indicate event was handled
            }

        });
    }

    public void setMaxZoom(float x) {
        maxScale = x;
    }

    @Override
    public boolean onSingleTapConfirmed(MotionEvent e) {
        return false;
    }

    @Override
    public boolean onDoubleTap(MotionEvent e) {
        // Double tap is detected
        Log.i("MAIN_TAG", "Double tap detected");
        float origScale = saveScale;
        float mScaleFactor;

        if (saveScale == maxScale) {
            saveScale = minScale;
            mScaleFactor = minScale / origScale;
        } else {
            saveScale = maxScale;
            mScaleFactor = maxScale / origScale;
        }

        matrix.postScale(mScaleFactor, mScaleFactor, viewWidth / 2,
                viewHeight / 2);

        fixTrans();
        return false;
    }

    @Override
    public boolean onDoubleTapEvent(MotionEvent e) {
        return false;
    }

    @Override
    public boolean onDown(MotionEvent e) {
        return false;
    }

    @Override
    public void onShowPress(MotionEvent e) {

    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        return false;
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        return false;
    }

    @Override
    public void onLongPress(MotionEvent e) {

    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        return false;
    }

    private class ScaleListener extends
            ScaleGestureDetector.SimpleOnScaleGestureListener {
        @Override
        public boolean onScaleBegin(ScaleGestureDetector detector) {
            mode = ZOOM;
            return true;
        }

        @Override
        public boolean onScale(ScaleGestureDetector detector) {
            float mScaleFactor = detector.getScaleFactor();
            float origScale = saveScale;
            saveScale *= mScaleFactor;
            if (saveScale > maxScale) {
                saveScale = maxScale;
                mScaleFactor = maxScale / origScale;
            } else if (saveScale < minScale) {
                saveScale = minScale;
                mScaleFactor = minScale / origScale;
            }

            if (origWidth * saveScale <= viewWidth
                    || origHeight * saveScale <= viewHeight)
                matrix.postScale(mScaleFactor, mScaleFactor, viewWidth / 2,
                        viewHeight / 2);
            else
                matrix.postScale(mScaleFactor, mScaleFactor,
                        detector.getFocusX(), detector.getFocusY());

            fixTrans();
            return true;
        }
    }

    void fixTrans() {
        matrix.getValues(m);
        float transX = m[Matrix.MTRANS_X];
        float transY = m[Matrix.MTRANS_Y];

        float fixTransX = getFixTrans(transX, viewWidth, origWidth * saveScale);
        float fixTransY = getFixTrans(transY, viewHeight, origHeight
                * saveScale);

        if (fixTransX != 0 || fixTransY != 0)
            matrix.postTranslate(fixTransX, fixTransY);
    }

    float getFixTrans(float trans, float viewSize, float contentSize) {
        float minTrans, maxTrans;

        if (contentSize <= viewSize) {
            minTrans = 0;
            maxTrans = viewSize - contentSize;
        } else {
            minTrans = viewSize - contentSize;
            maxTrans = 0;
        }

        if (trans < minTrans)
            return -trans + minTrans;
        if (trans > maxTrans)
            return -trans + maxTrans;
        return 0;
    }

    float getFixDragTrans(float delta, float viewSize, float contentSize) {
        if (contentSize <= viewSize) {
            return 0;
        }
        return delta;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        viewWidth = MeasureSpec.getSize(widthMeasureSpec);
        viewHeight = MeasureSpec.getSize(heightMeasureSpec);

        //
        // Rescales image on rotation
        //
        if (oldMeasuredHeight == viewWidth && oldMeasuredHeight == viewHeight
                || viewWidth == 0 || viewHeight == 0)
            return;
        oldMeasuredHeight = viewHeight;
        oldMeasuredWidth = viewWidth;

        if (saveScale == 1) {
            // Fit to screen.
            float scale;

            Drawable drawable = getDrawable();
            if (drawable == null || drawable.getIntrinsicWidth() == 0
                    || drawable.getIntrinsicHeight() == 0)
                return;
            int bmWidth = drawable.getIntrinsicWidth();
            int bmHeight = drawable.getIntrinsicHeight();

            Log.d("bmSize", "bmWidth: " + bmWidth + " bmHeight : " + bmHeight);

            float scaleX = (float) viewWidth / (float) bmWidth;
            float scaleY = (float) viewHeight / (float) bmHeight;
            scale = Math.min(scaleX, scaleY);
            matrix.setScale(scale, scale);

            // Center the image
            float redundantYSpace = (float) viewHeight
                    - (scale * (float) bmHeight);
            float redundantXSpace = (float) viewWidth
                    - (scale * (float) bmWidth);
            redundantYSpace /= (float) 2;
            redundantXSpace /= (float) 2;

            matrix.postTranslate(redundantXSpace, redundantYSpace);

            origWidth = viewWidth - 2 * redundantXSpace;
            origHeight = viewHeight - 2 * redundantYSpace;
            setImageMatrix(matrix);
        }
        fixTrans();
    }
}

Usage: You can replace your ImageView with TouchImageView in both XML & java

1. For XML

<?xml version="1.0" encoding="utf-8"?>
<com.example.android.myapp.TouchImageView 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/imViewedImage"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clickable="true"
    android:focusable="true" />

2. For Java

TouchImageView imViewedImage = findViewById(R.id.imViewedImage);

Extract images from PDF without resampling, in python?

I did this for my own program, and found that the best library to use was PyMuPDF. It lets you find out the "xref" numbers of each image on each page, and use them to extract the raw image data from the PDF.

import fitz
from PIL import Image
import io

filePath = "path/to/file.pdf"
#opens doc using PyMuPDF
doc = fitz.Document(filePath)

#loads the first page
page = doc.loadPage(0)

#[First image on page described thru a list][First attribute on image list: xref n], check PyMuPDF docs under getImageList()
xref = page.getImageList()[0][0]

#gets the image as a dict, check docs under extractImage 
baseImage = doc.extractImage(xref)

#gets the raw string image data from the dictionary and wraps it in a BytesIO object before using PIL to open it
image = Image.open(io.BytesIO(baseImage['image']))

#Displays image for good measure
image.show()

Definitely check out the docs, though.

How to set default value for form field in Symfony2?

A general solution for any case/approach, mainly by using a form without a class or when we need access to any services to set the default value:

// src/Form/Extension/DefaultFormTypeExtension.php

class DefaultFormTypeExtension extends AbstractTypeExtension
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        if (null !== $options['default']) {
            $builder->addEventListener(
                FormEvents::PRE_SET_DATA,
                function (FormEvent $event) use ($options) {
                    if (null === $event->getData()) {
                        $event->setData($options['default']);
                    }
                }
            );
        }
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefault('default', null);
    }

    public function getExtendedType()
    {
        return FormType::class;
    }
}

and register the form extension:

app.form_type_extension:
    class: App\Form\Extension\DefaultFormTypeExtension
    tags:
        - { name: form.type_extension, extended_type: Symfony\Component\Form\Extension\Core\Type\FormType }

After that, we can use default option in any form field:

$formBuilder->add('user', null, array('default' => $this->getUser()));
$formBuilder->add('foo', null, array('default' => 'bar'));

Arrow operator (->) usage in C

struct Node {
    int i;
    int j;
};
struct Node a, *p = &a;

Here the to access the values of i and j we can use the variable a and the pointer p as follows: a.i, (*p).i and p->i are all the same.

Here . is a "Direct Selector" and -> is an "Indirect Selector".

How to add a class to a given element?

Shortest

image1.parentNode.className+=' box';

_x000D_
_x000D_
image1.parentNode.className+=' box';
_x000D_
.box { width: 100px; height:100px; background: red; }
_x000D_
<div class="someclass">_x000D_
    <img ... id="image1" name="image1" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

Select mysql query between date?

All the above works, and here is another way if you just want to number of days/time back rather a entering date

select * from *table_name* where *datetime_column* BETWEEN DATE_SUB(NOW(), INTERVAL 30 DAY)  AND NOW() 

How to show what a commit did?

I found out that "git show --stat" is the best out of all here, gives you a brief summary of the commit, what files did you add and modify without giving you whole bunch of stuff, especially if you changed a lot files.

Get generic type of class at runtime

I used follow approach:

public class A<T> {

    protected Class<T> clazz;

    public A() {
        this.clazz = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }

    public Class<T> getClazz() {
        return clazz;
    }
}

public class B extends A<C> {
   /* ... */
    public void anything() {
       // here I may use getClazz();
    }
}

Formatting code snippets for blogging on Blogger

1. First, take backup of your blogger template
2. After that open your blogger template (In Edit HTML mode) & copy the all css given in this link before </b:skin> tag
3. Paste the followig code before </head> tag

<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shCore.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushCpp.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushCSharp.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushCss.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushDelphi.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushJava.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushJScript.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushPhp.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushPython.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushRuby.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushSql.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushVb.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushXml.js' type='text/javascript'></script>

4. Paste the following code before </body> tag.

<script language='javascript'>
dp.SyntaxHighlighter.BloggerMode();
dp.SyntaxHighlighter.HighlightAll('code');
</script>

5. Save Blogger Template.
6. Now syntax highlighting is ready to use you can use it with <pre></pre> tag.

<pre name="code">
...Your html-escaped code goes here...
</pre>

<pre name="code" class="php">
    echo "I like PHP";
</pre>

7. You can Escape your code here.
8. Here is list of supported language for <class> attribute.

Register 32 bit COM DLL to 64 bit Windows 7

For 32 bit DLLS in Windows 64 bit platforms:

  1. Copy whatever.dll to c:\windows\sysWOW64\
  2. Open a CMD prompt AS ADMINISTRATOR (very important)

In the CMD window:

  1. CD c:\windows\sysWOW64\
  2. regsvr32 whatever.dll

You will then be executing the 32-bit regsvr (c:\windows\sysWOW64\regsvr.exe) on a 32 bit dll

How can I use "." as the delimiter with String.split() in java

String.split takes a regex, and '.' has a special meaning for regexes.

You (probably) want something like:

String[] words = line.split("\\.");

Some folks seem to be having trouble getting this to work, so here is some runnable code you can use to verify correct behaviour.

import java.util.Arrays;

public class TestSplit {
  public static void main(String[] args) {
    String line = "aa.bb.cc.dd";
    String[] words = line.split("\\.");
    System.out.println(Arrays.toString(words));
    // Output is "[aa, bb, cc, dd]"
  }
}

How to create a custom-shaped bitmap marker with Android map API v2

From lambda answer, I have made something closer to the requirements.

boolean imageCreated = false;

Bitmap bmp = null;
Marker currentLocationMarker;
private void doSomeCustomizationForMarker(LatLng currentLocation) {
    if (!imageCreated) {
        imageCreated = true;
        Bitmap.Config conf = Bitmap.Config.ARGB_8888;
        bmp = Bitmap.createBitmap(400, 400, conf);
        Canvas canvas1 = new Canvas(bmp);

        Paint color = new Paint();
        color.setTextSize(30);
        color.setColor(Color.WHITE);

        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inMutable = true;

        Bitmap imageBitmap=BitmapFactory.decodeResource(getResources(),
                R.drawable.messi,opt);
        Bitmap resized = Bitmap.createScaledBitmap(imageBitmap, 320, 320, true);
        canvas1.drawBitmap(resized, 40, 40, color);

        canvas1.drawText("Le Messi", 30, 40, color);

        currentLocationMarker = mMap.addMarker(new MarkerOptions().position(currentLocation)
                .icon(BitmapDescriptorFactory.fromBitmap(bmp))
                // Specifies the anchor to be at a particular point in the marker image.
                .anchor(0.5f, 1));
    } else {
        currentLocationMarker.setPosition(currentLocation);
    }

}

Is it possible to have a HTML SELECT/OPTION value as NULL using PHP?

Yes, it is possible. You have to do something like this:

if(isset($_POST['submit']))
{
  $type_id = ($_POST['type_id'] == '' ? "null" : "'".$_POST['type_id']."'");
  $sql = "INSERT INTO `table` (`type_id`) VALUES (".$type_id.")";
}

It checks if the $_POST['type_id'] variable has an empty value. If yes, it assign NULL as a string to it. If not, it assign the value with ' to it for the SQL notation

Save modifications in place with awk

In case you want an awk-only solution without creating a temporary file and usable with version!=(gawk 4.1.0):

awk '{a[b++]=$0} END {for(c=0;c<=b;c++)print a[c]>ARGV[1]}' file

What does the "More Columns than Column Names" error mean?

Depending on the data (e.g. tsv extension) it may use tab as separators, so you may try sep = '\t' with read.csv.

Using BETWEEN in CASE SQL statement

Take out the MONTHS from your case, and remove the brackets... like this:

CASE 
    WHEN RATE_DATE BETWEEN '2010-01-01' AND '2010-01-31' THEN 'JANUARY'
    ELSE 'NOTHING'
END AS 'MONTHS'

You can think of this as being equivalent to:

CASE TRUE
    WHEN RATE_DATE BETWEEN '2010-01-01' AND '2010-01-31' THEN 'JANUARY'
    ELSE 'NOTHING'
END AS 'MONTHS'

Alter table add multiple columns ms sql

ALTER TABLE Regions
ADD ( HasPhotoInReadyStorage  bit,
     HasPhotoInWorkStorage  bit,
     HasPhotoInMaterialStorage bit *(Missing ,)*
     HasText  bit);

regex.test V.S. string.match to know if a string matches a regular expression

Basic Usage

First, let's see what each function does:

regexObject.test( String )

Executes the search for a match between a regular expression and a specified string. Returns true or false.

string.match( RegExp )

Used to retrieve the matches when matching a string against a regular expression. Returns an array with the matches or null if there are none.

Since null evaluates to false,

if ( string.match(regex) ) {
  // There was a match.
} else {
  // No match.
} 

Performance

Is there any difference regarding performance?

Yes. I found this short note in the MDN site:

If you need to know if a string matches a regular expression regexp, use regexp.test(string).

Is the difference significant?

The answer once more is YES! This jsPerf I put together shows the difference is ~30% - ~60% depending on the browser:

test vs match | Performance Test

Conclusion

Use .test if you want a faster boolean check. Use .match to retrieve all matches when using the g global flag.

Firefox Add-on RESTclient - How to input POST parameters?

I tried the methods mentioned in some other answers, but they look like workarounds to me. Using Firefox Add-on RESTclient to send HTTP POST requests with parameters is not straightforward in my opinion, at least for the version I'm currently using, 2.0.1.

Instead, try using other free open source tools, such as Apache JMeter. It is simple and straightforward (see the screenshot as below)

enter image description here

Filtering DataGridView without changing datasource

I just spent an hour on a similar problem. For me the answer turned out to be embarrassingly simple.

(dataGridViewFields.DataSource as DataTable).DefaultView.RowFilter = string.Format("Field = '{0}'", textBoxFilter.Text);

Escaping single quote in PHP when inserting into MySQL

For anyone finding this solution in 2015 and moving forward...

The mysql_real_escape_string() function is deprecated as of PHP 5.5.0.

See: php.net

Warning

This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

mysqli_real_escape_string()

PDO::quote()

Bootstrap 3 Carousel Not Working

There are just two minor things here.

The first is in the following carousel indicator list items:

<li data-target="carousel" data-slide-to="0"></li>

You need to pass the data-target attribute a selector which means the ID must be prefixed with #. So change them to the following:

<li data-target="#carousel" data-slide-to="0"></li>

Secondly, you need to give the carousel a starting point so both the carousel indicator items and the carousel inner items must have one active class. Like this:

<ol class="carousel-indicators">
    <li data-target="#carousel" data-slide-to="0" class="active"></li>
    <!-- Other Items -->
</ol>
<div class="carousel-inner">
    <div class="item active">
        <img src="https://picsum.photos/1500/600?image=1" alt="Slide 1" />
    </div>
    <!-- Other Items -->
</div>

Working Demo in Fiddle

How to create a new column in a select query

It depends what you wanted to do with that column e.g. here's an example of appending a new column to a recordset which can be updated on the client side:

Sub MSDataShape_AddNewCol()

  Dim rs As ADODB.Recordset
  Set rs = CreateObject("ADODB.Recordset")
  With rs
    .ActiveConnection = _
    "Provider=MSDataShape;" & _
    "Data Provider=Microsoft.Jet.OLEDB.4.0;" & _
    "Data Source=C:\Tempo\New_Jet_DB.mdb"
    .Source = _
    "SHAPE {" & _
    " SELECT ExistingField" & _
    " FROM ExistingTable" & _
    " ORDER BY ExistingField" & _
    "} APPEND NEW adNumeric(5, 4) AS NewField"

    .LockType = adLockBatchOptimistic

    .Open

    Dim i As Long
    For i = 0 To .RecordCount - 1
      .Fields("NewField").Value = Round(.Fields("ExistingField").Value, 4)
      .MoveNext
    Next

    rs.Save "C:\rs.xml", adPersistXML

  End With
End Sub

This declaration has no storage class or type specifier in C++

You can declare an object of a class in another Class,that's possible but you cant initialize that object. For that you need to do something like this :--> (inside main)

Orderbook o1;
o1.m.check(side)

but that would be unnecessary. Keeping things short :-

You can't call functions inside a Class

Tried to Load Angular More Than Once

You must change angular route '/'! It is a problem because '/' base url request. If you change '/' => '/home' or '/hede' angular will good work.

Datatype for storing ip address in SQL Server

The technically correct way to store IPv4 is binary(4), since that is what it actually is (no, not even an INT32/INT(4), the numeric textual form that we all know and love (255.255.255.255) being just the display conversion of its binary content).

If you do it this way, you will want functions to convert to and from the textual-display format:

Here's how to convert the textual display form to binary:

CREATE FUNCTION dbo.fnBinaryIPv4(@ip AS VARCHAR(15)) RETURNS BINARY(4)
AS
BEGIN
    DECLARE @bin AS BINARY(4)

    SELECT @bin = CAST( CAST( PARSENAME( @ip, 4 ) AS INTEGER) AS BINARY(1))
                + CAST( CAST( PARSENAME( @ip, 3 ) AS INTEGER) AS BINARY(1))
                + CAST( CAST( PARSENAME( @ip, 2 ) AS INTEGER) AS BINARY(1))
                + CAST( CAST( PARSENAME( @ip, 1 ) AS INTEGER) AS BINARY(1))

    RETURN @bin
END
go

And here's how to convert the binary back to the textual display form:

CREATE FUNCTION dbo.fnDisplayIPv4(@ip AS BINARY(4)) RETURNS VARCHAR(15)
AS
BEGIN
    DECLARE @str AS VARCHAR(15) 

    SELECT @str = CAST( CAST( SUBSTRING( @ip, 1, 1) AS INTEGER) AS VARCHAR(3) ) + '.'
                + CAST( CAST( SUBSTRING( @ip, 2, 1) AS INTEGER) AS VARCHAR(3) ) + '.'
                + CAST( CAST( SUBSTRING( @ip, 3, 1) AS INTEGER) AS VARCHAR(3) ) + '.'
                + CAST( CAST( SUBSTRING( @ip, 4, 1) AS INTEGER) AS VARCHAR(3) );

    RETURN @str
END;
go

Here's a demo of how to use them:

SELECT dbo.fnBinaryIPv4('192.65.68.201')
--should return 0xC04144C9
go

SELECT dbo.fnDisplayIPv4( 0xC04144C9 )
-- should return '192.65.68.201'
go

Finally, when doing lookups and compares, always use the binary form if you want to be able to leverage your indexes.


UPDATE:

I wanted to add that one way to address the inherent performance problems of scalar UDFs in SQL Server, but still retain the code-reuse of a function is to use an iTVF (inline table-valued function) instead. Here's how the first function above (string to binary) can be re-written as an iTVF:

CREATE FUNCTION dbo.itvfBinaryIPv4(@ip AS VARCHAR(15)) RETURNS TABLE
AS RETURN (
    SELECT CAST(
               CAST( CAST( PARSENAME( @ip, 4 ) AS INTEGER) AS BINARY(1))
            +  CAST( CAST( PARSENAME( @ip, 3 ) AS INTEGER) AS BINARY(1))
            +  CAST( CAST( PARSENAME( @ip, 2 ) AS INTEGER) AS BINARY(1))
            +  CAST( CAST( PARSENAME( @ip, 1 ) AS INTEGER) AS BINARY(1))
                AS BINARY(4)) As bin
        )
go

Here's it in the example:

SELECT bin FROM dbo.fnBinaryIPv4('192.65.68.201')
--should return 0xC04144C9
go

And here's how you would use it in an INSERT

INSERT INTo myIpTable
SELECT {other_column_values,...},
       (SELECT bin FROM dbo.itvfBinaryIPv4('192.65.68.201'))

How do you Change a Package's Log Level using Log4j?

set the system property log4j.debug=true. Then you can determine where your configuration is running amuck.

Spring's overriding bean

Whether can we declare the same bean id in other xml for other reference e.x.

Servlet-Initialize.xml

<bean id="inheritedTestBean"   class="org.springframework.beans.TestBean">
  <property name="name" value="parent"/>
  <property name="age" value="1"/>
</bean>

Other xml (Document.xml)

<bean id="inheritedTestBean"  class="org.springframework.beans.Document">
  <property name="name" value="document"/>
  <property name="age" value="1"/>
</bean>

In Python, is there an elegant way to print a list in a custom format without explicit looping?

Take a look on pprint, The pprint module provides a capability to “pretty-print” arbitrary Python data structures in a form which can be used as input to the interpreter. If the formatted structures include objects which are not fundamental Python types, the representation may not be loadable. This may be the case if objects such as files, sockets or classes are included, as well as many other objects which are not representable as Python literals.

>>> import pprint
>>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
>>> stuff.insert(0, stuff[:])
>>> pp = pprint.PrettyPrinter(indent=4)
>>> pp.pprint(stuff)
[   ['spam', 'eggs', 'lumberjack', 'knights', 'ni'],
    'spam',
    'eggs',
    'lumberjack',
    'knights',
    'ni']
>>> pp = pprint.PrettyPrinter(width=41, compact=True)
>>> pp.pprint(stuff)
[['spam', 'eggs', 'lumberjack',
  'knights', 'ni'],
 'spam', 'eggs', 'lumberjack', 'knights',
 'ni']
>>> tup = ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead',
... ('parrot', ('fresh fruit',))))))))
>>> pp = pprint.PrettyPrinter(depth=6)
>>> pp.pprint(tup)
('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead', (...)))))))

Node.js, can't open files. Error: ENOENT, stat './path/to/file'

Here the code to use your app.js

input specifies file name

res.download(__dirname+'/'+input);

Passing Javascript variable to <a href >

Alternatively you could just use a document.write:

<script type="text\javascript">
var loc = "http://";
document.write('<a href="' + loc + '">Link text</a>');
</script>

How to give a Linux user sudo access?

This answer will do what you need, although usually you don't add specific usernames to sudoers. Instead, you have a group of sudoers and just add your user to that group when needed. This way you don't need to use visudo more than once when giving sudo permission to users.

If you're on Ubuntu, the group is most probably already set up and called admin:

$ sudo cat /etc/sudoers
#
# This file MUST be edited with the 'visudo' command as root.
#

...

# Members of the admin group may gain root privileges
%admin ALL=(ALL) ALL

# Allow members of group sudo to execute any command
%sudo   ALL=(ALL:ALL) ALL

# See sudoers(5) for more information on "#include" directives:

#includedir /etc/sudoers.d

On other distributions, like Arch and some others, it's usually called wheel and you may need to set it up: Arch Wiki

To give users in the wheel group full root privileges when they precede a command with "sudo", uncomment the following line: %wheel ALL=(ALL) ALL

Also note that on most systems visudo will read the EDITOR environment variable or default to using vi. So you can try to do EDITOR=vim visudo to use vim as the editor.

To add a user to the group you should run (as root):

# usermod -a -G groupname username

where groupname is your group (say, admin or wheel) and username is the username (say, john).

$.ajax - dataType

(ps: the answer given by Nick Craver is incorrect)

contentType specifies the format of data being sent to the server as part of request(it can be sent as part of response too, more on that later).

dataType specifies the expected format of data to be received by the client(browser).

Both are not interchangable.

  • contentType is the header sent to the server, specifying the format of data(i.e the content of message body) being being to the server. This is used with POST and PUT requests. Usually when u send POST request, the message body comprises of passed in parameters like:

==============================

Sample request:

POST /search HTTP/1.1 
Content-Type: application/x-www-form-urlencoded 
<<other header>>

name=sam&age=35

==============================

The last line above "name=sam&age=35" is the message body and contentType specifies it as application/x-www-form-urlencoded since we are passing the form parameters in the message body. However we aren't limited to just sending the parameters, we can send json, xml,... like this(sending different types of data is especially useful with RESTful web services):

==============================

Sample request:

POST /orders HTTP/1.1
Content-Type: application/xml
<<other header>>

<order>
   <total>$199.02</total>
   <date>December 22, 2008 06:56</date>
...
</order>

==============================

So the ContentType this time is: application/xml, cause that's what we are sending. The above examples showed sample request, similarly the response send from the server can also have the Content-Type header specifying what the server is sending like this:

==============================

sample response:

HTTP/1.1 201 Created
Content-Type: application/xml
<<other headers>>

<order id="233">
   <link rel="self" href="http://example.com/orders/133"/>
   <total>$199.02</total>
   <date>December 22, 2008 06:56</date>
...
</order>

==============================

  • dataType specifies the format of response to expect. Its related to Accept header. JQuery will try to infer it based on the Content-Type of the response.

==============================

Sample request:

GET /someFolder/index.html HTTP/1.1
Host: mysite.org
Accept: application/xml
<<other headers>>

==============================

Above request is expecting XML from the server.

Regarding your question,

contentType: "application/json; charset=utf-8",
dataType: "json",

Here you are sending json data using UTF8 character set, and you expect back json data from the server. As per the JQuery docs for dataType,

The json type parses the fetched data file as a JavaScript object and returns the constructed object as the result data.

So what you get in success handler is proper javascript object(JQuery converts the json object for you)

whereas

contentType: "application/json",
dataType: "text",

Here you are sending json data, since you haven't mentioned the encoding, as per the JQuery docs,

If no charset is specified, data will be transmitted to the server using the server's default charset; you must decode this appropriately on the server side.

and since dataType is specified as text, what you get in success handler is plain text, as per the docs for dataType,

The text and xml types return the data with no processing. The data is simply passed on to the success handler

Show a PDF files in users browser via PHP/Perl

You can also use fpdf class available at: http://www.fpdf.org. It gives options for both outputting to a file and displaying on browser.

tar: file changed as we read it

Here is a one-liner for ignoring the tar exit status if it is 1. There is no need to set +e as in sandeep's script. If the tar exit status is 0 or 1, this one-liner will return with exit status 0. Otherwise it will return with exit status 1. This is different from sandeep's script where the original exit status value is preserved if it is different from 1.

tar -czf sample.tar.gz dir1 dir2 || [[ $? -eq 1 ]]

Set height of <div> = to height of another <div> through .css

If you're open to using javascript then you can get the property on an element like this: document.GetElementByID('rightdiv').style.getPropertyValue('max-height');

And you can set the attribute on an element like this: .setAttribute('style','max-height:'+heightVariable+';');

Note: if you're simply looking to set both element's max-height property in one line, you can do so like this:

#leftdiv,#rightdiv
{
    min-height: 600px;   
}

How do I enable php to work with postgresql?

You need to install the pgsql module for php. In debian/ubuntu is something like this:

sudo apt-get install php5-pgsql

Or if the package is installed, you need to enable de module in php.ini

extension=php_pgsql.dll (windows)
extension=php_pgsql.so (linux)

Greatings.

How to pass parameters to maven build using pom.xml?

mvn install "-Dsomeproperty=propety value"

In pom.xml:

<properties>
    <someproperty> ${someproperty} </someproperty>
</properties>

Referred from this question

Fatal error: Call to undefined function imap_open() in PHP

if you are on linux, edit the /etc/php/php.ini (or you will have to create a new extension import file at /etc/php5/cli/conf.d) file so that you add the imap shared object file and then, restart the apache server. Uncomment

;extension=imap.so

so that it becomes like this:

extension=imap.so

Then, restart the apache by

# /etc/rc.d/httpd restart

PHP array: count or sizeof?

I would use count() if they are the same, as in my experience it is more common, and therefore will cause less developers reading your code to say "sizeof(), what is that?" and having to consult the documentation.

I think it means sizeof() does not work like it does in C (calculating the size of a datatype). It probably made this mention explicitly because PHP is written in C, and provides a lot of identically named wrappers for C functions (strlen(), printf(), etc)

How to get started with Windows 7 gadgets

Combining and organizing all the current answers into one answer, then adding my own research:

Brief summary of Microsoft gadget development:

What are they written in? Windows Vista/Seven gadgets are developed in a mix of XML, HTML, CSS, and some IE scripting language. It is also possible to use C# with the latest release of Script#.

How are they packaged/deployed? The actual gadgets are stored in *.gadget files, which are simply the text source files listed above compressed into a single zip file.

Useful references for gadget development:

where do I start? Good introductory references to Windows Vista/Seven gadget development:

If you are willing to use offline resources, this book appears to be an excellent resource:

What do I need to know? Some other useful references; not necessarily instructional


Update: Well, this has proven to be a popular answer~ Sharing my own recent experience with Windows 7 gadget development:

Perhaps the easiest way to get started with Windows 7 gadget development is to modify a gadget that has already been developed. I recently did this myself because I wanted a larger clock gadget. Unable to find any, I tinkered with a copy of the standard Windows clock gadget until it was twice as large. I recommend starting with the clock gadget because it is fairly small and well-written. Here is the process I used:

  1. Locate the gadget you wish to modify. They are located in several different places. Search for folders named *.gadget. Example: C:\Program Files\Windows Sidebar\Gadgets\Clock.Gadget\
  2. Make a copy of this folder (installed gadgets are not wrapped in zip files.)
  3. Rename some key parts:
    1. The folder name
    2. The name inside the gadget.xml file. It looks like:<name>Clock</name> This is the name that will be displayed in the "Gadgets Gallery" window.
  4. Zip up the entire *.gadget directory.
  5. Change the file extension from "zip" to "gadget" (Probably just need to remove the ".zip" extension.)
  6. Install your new copy of the gadget by double clicking the new *.gadget file. You can now add your gadget like any other gadget (right click desktop->Gadgets)
  7. Locate where this gadget is installed (probably to %LOCALAPPDATA%\Microsoft\Windows Sidebar\)
  8. Modify the files in this directory. The gadget is very similar to a web page: HTML, CSS, JS, and image files. The gadget.xml file specifies which file is opened as the "index" page for the gadget.
  9. After you save the changes, view the results by installing a new instance of the gadget. You can also debug the JavaScript (The rest of that article is pretty informative, too).

Android studio 3.0: Unable to resolve dependency for :app@dexOptions/compileClasspath': Could not resolve project :animators

It seems like it's a bug on Gradle. This solves the problem for me, but it's not a solution. We have to wait for a new version fixing this problems.

On build.gradle in the project set classpath 'com.android.tools.build:gradle:2.3.3' instead classpath 'com.android.tools.build:gradle:3.0.0'.

On gradle-wrapper.properties set https://services.gradle.org/distributions/gradle-3.3-all.zip instead https://services.gradle.org/distributions/gradle-4.1.2-all.zip

Clearing the terminal screen?

/*
As close as I can get to Clear Screen

*/


void setup() {
// put your setup code here, to run once:
Serial.begin(115200);

}

void loop() {

Serial.println("This is Line ZERO ");

// put your main code here, to run repeatedly:

for (int i = 1; i < 37; i++)
{

 // Check and print Line
  if (i == 15)
  {
   Serial.println("Line 15");
  }

  else
   Serial.println(i);  //Prints line numbers   Delete i for blank line
  }

  delay(5000);  

  }

to remove first and last element in array

push() adds a new element to the end of an array.
pop() removes an element from the end of an array.

unshift() adds a new element to the beginning of an array.
shift() removes an element from the beginning of an array.

To remove first element from an array arr , use arr.shift()
To remove last element from an array arr , use arr.pop()

Split string using a newline delimiter with Python

data = """a,b,c
d,e,f
g,h,i
j,k,l"""

print(data.split())       # ['a,b,c', 'd,e,f', 'g,h,i', 'j,k,l']

str.split, by default, splits by all the whitespace characters. If the actual string has any other whitespace characters, you might want to use

print(data.split("\n"))   # ['a,b,c', 'd,e,f', 'g,h,i', 'j,k,l']

Or as @Ashwini Chaudhary suggested in the comments, you can use

print(data.splitlines())

HTML-encoding lost when attribute read from input field

Faster without Jquery. You can encode every character in your string:

function encode(e){return e.replace(/[^]/g,function(e){return"&#"+e.charCodeAt(0)+";"})}

Or just target the main characters to worry about (&, inebreaks, <, >, " and ') like:

_x000D_
_x000D_
function encode(r){_x000D_
return r.replace(/[\x26\x0A\<>'"]/g,function(r){return"&#"+r.charCodeAt(0)+";"})_x000D_
}_x000D_
_x000D_
test.value=encode('Encode HTML entities!\n\n"Safe" escape <script id=\'\'> & useful in <pre> tags!');_x000D_
_x000D_
testing.innerHTML=test.value;_x000D_
_x000D_
/*************_x000D_
* \x26 is &ampersand (it has to be first),_x000D_
* \x0A is newline,_x000D_
*************/
_x000D_
<textarea id=test rows="9" cols="55"></textarea>_x000D_
_x000D_
<div id="testing">www.WHAK.com</div>
_x000D_
_x000D_
_x000D_

Close dialog on click (anywhere)

If you'd like to do it for all dialogs throughout the site try the following code...

$.extend( $.ui.dialog.prototype.options, { 
    open: function() {
        var dialog = this;
        $('.ui-widget-overlay').bind('click', function() {
            $(dialog).dialog('close');
        });
    }   

});

How to update record using Entity Framework Core?

According to Microsoft docs:

the read-first approach requires an extra database read, and can result in more complex code for handling concurrency conflict

However, you should know that using Update method on DbContext will mark all the fields as modified and will include all of them in the query. If you want to update a subset of fields you should use the Attach method and then mark the desired field as modified manually.

context.Attach(person);
context.Entry(person).Property(p => p.Name).IsModified = true;
context.SaveChanges();

Import existing Gradle Git project into Eclipse

The simpliest way is to use sts gradle integration and import project

http://static.springsource.org/sts/docs/2.7.0.M1/reference/html/gradle/gradle-sts-tutorial.html

Don't forget to click "Build Model" button.

What's the difference between JPA and Hibernate?

JPA or Java Persistence API is a standard specification for ORM implementations whereas Hibernate is the actual ORM implementation or framework.

how to pass command line arguments to main method dynamically

Run ---> Debug Configuration ---> YourConfiguration ---> Arguments tab

enter image description here

Access to the path is denied

I got this problem when I try to save the file without set the file name.

Old Code

File.WriteAllBytes(@"E:\Folder", Convert.FromBase64String(Base64String));

Working Code

File.WriteAllBytes(@"E:\Folder\"+ fileName, Convert.FromBase64String(Base64String));

Why is my Git Submodule HEAD detached from master?

As other people have said, the reason this happens is that the parent repo only contains a reference to (the SHA1 of) a specific commit in the submodule – it doesn't know anything about branches. This is how it should work: the branch that was at that commit may have moved forward (or backwards), and if the parent repo had referenced the branch then it could easily break when that happens.

However, especially if you are actively developing in both the parent repo and the submodule, detached HEAD state can be confusing and potentially dangerous. If you make commits in the submodule while it's in detached HEAD state, these become dangling and you can easily lose your work. (Dangling commits can usually be rescued using git reflog, but it's much better to avoid them in the first place.)

If you're like me, then most of the time if there is a branch in the submodule that points to the commit being checked out, you would rather check out that branch than be in detached HEAD state at the same commit. You can do this by adding the following alias to your gitconfig file:

[alias]
    submodule-checkout-branch = "!f() { git submodule -q foreach 'branch=$(git branch --no-column --format=\"%(refname:short)\" --points-at `git rev-parse HEAD` | grep -v \"HEAD detached\" | head -1); if [[ ! -z $branch && -z `git symbolic-ref --short -q HEAD` ]]; then git checkout -q \"$branch\"; fi'; }; f"

Now, after doing git submodule update you just need to call git submodule-checkout-branch, and any submodule that is checked out at a commit which has a branch pointing to it will check out that branch. If you don't often have multiple local branches all pointing to the same commit, then this will usually do what you want; if not, then at least it will ensure that any commits you do make go onto an actual branch instead of being left dangling.

Furthermore, if you have set up git to automatically update submodules on checkout (using git config --global submodule.recurse true, see this answer), you can make a post-checkout hook that calls this alias automatically:

$ cat .git/hooks/post-checkout 
#!/bin/sh
git submodule-checkout-branch

Then you don't need to call either git submodule update or git submodule-checkout-branch, just doing git checkout will update all submodules to their respective commits and check out the corresponding branches (if they exist).

Convert a JSON Object to Buffer and Buffer to JSON Object back

You need to stringify the json, not calling toString

var buf = Buffer.from(JSON.stringify(obj));

And for converting string to json obj :

var temp = JSON.parse(buf.toString());

How do I set the selected item in a comboBox to match my string using C#?

Assuming that your combobox isn't databound you would need to find the object's index in the "items" collection on your form and then set the "selectedindex" property to the appropriate index.

comboBox1.SelectedIndex = comboBox1.Items.IndexOf("test1");

Keep in mind that the IndexOf function may throw an argumentexception if the item isn't found.

MYSQL Sum Query with IF Condition

Try with a CASE in this way :

SUM(CASE 
    WHEN PaymentType = "credit card" 
    THEN TotalAmount 
    ELSE 0 
END) AS CreditCardTotal,

Should give what you are looking for ...

How do we count rows using older versions of Hibernate (~2009)?

Long count = (Long) session.createQuery("select count(*) from  Book").uniqueResult();

Calling a Function defined inside another function in Javascript

You could make it into a module and expose your inner function by returning it in an Object.

function outer() { 
    function inner() {
        console.log("hi");
    }
    return {
        inner: inner
    };
}
var foo = outer();
foo.inner();

LINQ to SQL - Left Outer Join with multiple join conditions

I know it's "a bit late" but just in case if anybody needs to do this in LINQ Method syntax (which is why I found this post initially), this would be how to do that:

var results = context.Periods
    .GroupJoin(
        context.Facts,
        period => period.id,
        fk => fk.periodid,
        (period, fact) => fact.Where(f => f.otherid == 17)
                              .Select(fact.Value)
                              .DefaultIfEmpty()
    )
    .Where(period.companyid==100)
    .SelectMany(fact=>fact).ToList();

How to call getResources() from a class which has no context?

A Context is a handle to the system; it provides services like resolving resources, obtaining access to databases and preferences, and so on. It is an "interface" that allows access to application specific resources and class and information about application environment. Your activities and services also extend Context to they inherit all those methods to access the environment information in which the application is running.

This means you must have to pass context to the specific class if you want to get/modify some specific information about the resources. You can pass context in the constructor like

public classname(Context context, String s1) 
{
...
}

“Origin null is not allowed by Access-Control-Allow-Origin” error for request made by application running from a file:// URL

Not all servers support jsonp. It requires the server to set the callback function in it's results. I use this to get json responses from sites that return pure json but don't support jsonp:

function AjaxFeed(){

    return $.ajax({
        url:            'http://somesite.com/somejsonfile.php',
        data:           {something: true},
        dataType:       'jsonp',

        /* Very important */
        contentType:    'application/json',
    });
}

function GetData() {
    AjaxFeed()

    /* Everything worked okay. Hooray */
    .done(function(data){
        return data;
    })

    /* Okay jQuery is stupid manually fix things */
    .fail(function(jqXHR) {

        /* Build HTML and update */
        var data = jQuery.parseJSON(jqXHR.responseText);

        return data;
    });
}

Reading all files in a directory, store them in objects, and send the object

For the code to work smoothy in different enviroments, path.resolve can be used in places where path is manipulated. Here is code which works better.

Reading part:

var fs = require('fs');

function readFiles(dirname, onFileContent, onError) {
  fs.readdir(dirname, function(err, filenames) {
    if (err) {
      onError(err);
      return;
    }
    filenames.forEach(function(filename) {
      fs.readFile(path.resolve(dirname, filename), 'utf-8', function(err, content) {
        if (err) {
          onError(err);
          return;
        }
        onFileContent(filename, content);
      });
    });
  });
}

Storing part:

var data = {};
readFiles(path.resolve(__dirname, 'dirname/'), function(filename, content) {
  data[filename] = content;
}, function(error) {
  throw err;
});

Just what is an IntPtr exactly?

Well this is the MSDN page that deals with IntPtr.

The first line reads:

A platform-specific type that is used to represent a pointer or a handle.

As to what a pointer or handle is the page goes on to state:

The IntPtr type can be used by languages that support pointers, and as a common means of referring to data between languages that do and do not support pointers.

IntPtr objects can also be used to hold handles. For example, instances of IntPtr are used extensively in the System.IO.FileStream class to hold file handles.

A pointer is a reference to an area of memory that holds some data you are interested in.

A handle can be an identifier for an object and is passed between methods/classes when both sides need to access that object.

Git commit with no commit message

I have the following config in my private project:

git config alias.auto 'commit -a -m "changes made from [device name]"'

That way, when I'm in a hurry I do

git auto
git push

And at least I know what device the commit was made from.

iOS Safari – How to disable overscroll but allow scrollable divs to scroll normally?

This solves the issue when you scroll past the beginning or end of the div

var selScrollable = '.scrollable';
// Uses document because document will be topmost level in bubbling
$(document).on('touchmove',function(e){
  e.preventDefault();
});
// Uses body because jQuery on events are called off of the element they are
// added to, so bubbling would not work if we used document instead.
$('body').on('touchstart', selScrollable, function(e) {
  if (e.currentTarget.scrollTop === 0) {
    e.currentTarget.scrollTop = 1;
  } else if (e.currentTarget.scrollHeight === e.currentTarget.scrollTop + e.currentTarget.offsetHeight) {
    e.currentTarget.scrollTop -= 1;
  }
});
// Stops preventDefault from being called on document if it sees a scrollable div
$('body').on('touchmove', selScrollable, function(e) {
  e.stopPropagation();
});

Note that this won't work if you want to block whole page scrolling when a div does not have overflow. To block that, use the following event handler instead of the one immediately above (adapted from this question):

$('body').on('touchmove', selScrollable, function(e) {
    // Only block default if internal div contents are large enough to scroll
    // Warning: scrollHeight support is not universal. (https://stackoverflow.com/a/15033226/40352)
    if($(this)[0].scrollHeight > $(this).innerHeight()) {
        e.stopPropagation();
    }
});

no suitable HttpMessageConverter found for response type

Or you can use

public void setSupportedMediaTypes(List supportedMediaTypes)

method which belongs to AbstractHttpMessageConverter<T>, to add some ContentTypes you like. This way can let the MappingJackson2HttpMessageConverter canRead() your response, and transform it to your desired Class, which on this case,is ProductList Class.

and I think this step should hooked up with the Spring Context initializing. for example, by using

implements ApplicationListener { ... }

Dark color scheme for Eclipse

I played with customizing the colors. I went with the yellow text/blue background I've liked from Turbo Pascal. The problem I ran into was it let you set the colors of the editors but then the other views like Package Explorer or Navigator stayed with the default black-on-white colors. I'm sure you could do it programatically but there are waaaay to many settings for my patience.

javax.servlet.ServletException cannot be resolved to a type in spring web app

As almost anyone said, adding a runtime service will solve the problem. But if there is no runtime services or there is something like Google App Engine which is not your favorite any how, click New button right down the Targeted Runtimes list and add a new runtime server environment. Then check it and click OK and let the compiler to compile your project again.

Hope it helps ;)