Programs & Examples On #Gruber

Understanding CUDA grid dimensions, block dimensions and threads organization (simple explanation)

Suppose a 9800GT GPU:

  • it has 14 multiprocessors (SM)
  • each SM has 8 thread-processors (AKA stream-processors, SP or cores)
  • allows up to 512 threads per block
  • warpsize is 32 (which means each of the 14x8=112 thread-processors can schedule up to 32 threads)

https://www.tutorialspoint.com/cuda/cuda_threads.htm

A block cannot have more active threads than 512 therefore __syncthreads can only synchronize limited number of threads. i.e. If you execute the following with 600 threads:

func1();
__syncthreads();
func2();
__syncthreads();

then the kernel must run twice and the order of execution will be:

  1. func1 is executed for the first 512 threads
  2. func2 is executed for the first 512 threads
  3. func1 is executed for the remaining threads
  4. func2 is executed for the remaining threads

Note:

The main point is __syncthreads is a block-wide operation and it does not synchronize all threads.


I'm not sure about the exact number of threads that __syncthreads can synchronize, since you can create a block with more than 512 threads and let the warp handle the scheduling. To my understanding it's more accurate to say: func1 is executed at least for the first 512 threads.

Before I edited this answer (back in 2010) I measured 14x8x32 threads were synchronized using __syncthreads.

I would greatly appreciate if someone test this again for a more accurate piece of information.

How to get numbers after decimal point?

def fractional_part(numerator, denominator):
    # Operate with numerator and denominator to 
# keep just the fractional part of the quotient
if  denominator == 0:
      return 0
  else:
       return (numerator/ denominator)-(numerator // denominator)  
 

print(fractional_part(5, 5)) # Should be 0
print(fractional_part(5, 4)) # Should be 0.25
print(fractional_part(5, 3)) # Should be 0.66...
print(fractional_part(5, 2)) # Should be 0.5
print(fractional_part(5, 0)) # Should be 0
print(fractional_part(0, 5)) # Should be 0

Default value in Doctrine

If you use yaml definition for your entity, the following works for me on a postgresql database:

Entity\Entity_name:
    type: entity
    table: table_name
    fields: 
        field_name:
            type: boolean
            nullable: false
            options:
                default: false

Deserialize from string instead TextReader

public static string XmlSerializeToString(this object objectInstance)
{
    var serializer = new XmlSerializer(objectInstance.GetType());
    var sb = new StringBuilder();

    using (TextWriter writer = new StringWriter(sb))
    {
        serializer.Serialize(writer, objectInstance);
    }

    return sb.ToString();
}

public static T XmlDeserializeFromString<T>(this string objectData)
{
    return (T)XmlDeserializeFromString(objectData, typeof(T));
}

public static object XmlDeserializeFromString(this string objectData, Type type)
{
    var serializer = new XmlSerializer(type);
    object result;

    using (TextReader reader = new StringReader(objectData))
    {
        result = serializer.Deserialize(reader);
    }

    return result;
}

To use it:

//Make XML
var settings = new ObjectCustomerSettings();
var xmlString = settings.XmlSerializeToString();

//Make Object
var settings = xmlString.XmlDeserializeFromString<ObjectCustomerSettings>(); 

Checking if a character is a special character in Java

What I would do:

char c;
int cint;
for(int n = 0; n < str.length(); n ++;)
{
    c = str.charAt(n);
    cint = (int)c;
    if(cint <48 || (cint > 57 && cint < 65) || (cint > 90 && cint < 97) || cint > 122)
    {
        specialCharacterCount++
    }
}

That is a simple way to do things, without having to import any special classes. Stick it in a method, or put it straight into the main code.

ASCII chart: http://www.gophoto.it/view.php?i=http://i.msdn.microsoft.com/dynimg/IC102418.gif#.UHsqxFEmG08

How to set timeout in Retrofit library?

public class ApiClient {
    private static Retrofit retrofit = null;
    private static final Object LOCK = new Object();

    public static void clear() {
        synchronized (LOCK) {
            retrofit = null;
        }
    }

    public static Retrofit getClient() {
        synchronized (LOCK) {
            if (retrofit == null) {

                Gson gson = new GsonBuilder()
                        .setLenient()
                        .create();

                OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                        .connectTimeout(40, TimeUnit.SECONDS)
                        .readTimeout(60, TimeUnit.SECONDS)
                        .writeTimeout(60, TimeUnit.SECONDS)
                        .build();

                // Log.e("jjj", "=" + (MySharedPreference.getmInstance().isEnglish() ? Constant.WEB_SERVICE : Constant.WEB_SERVICE_ARABIC));
                retrofit = new Retrofit.Builder()
                        .client(okHttpClient)
                        .baseUrl(Constants.WEB_SERVICE)
                        .addConverterFactory(GsonConverterFactory.create(gson))
                        .build();
            }
            return retrofit;
        }`enter code here`

    }

    public static RequestBody plain(String content) {
        return getRequestBody("text/plain", content);
    }

    public static RequestBody getRequestBody(String type, String content) {
        return RequestBody.create(MediaType.parse(type), content);
    }
}


-------------------------------------------------------------------------


    implementation 'com.squareup.retrofit2:retrofit:2.4.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.4.0'

Counting DISTINCT over multiple columns

It works for me. In oracle:

SELECT SUM(DECODE(COUNT(*),1,1,1))
FROM DocumentOutputItems GROUP BY DocumentId, DocumentSessionId;

In jpql:

SELECT SUM(CASE WHEN COUNT(i)=1 THEN 1 ELSE 1 END)
FROM DocumentOutputItems i GROUP BY i.DocumentId, i.DocumentSessionId;

What exactly is \r in C language?

' \r ' means carriage return.

The \r means nothing special as a consequence.For character-mode terminals (typically emulating even-older printing ones as above), in raw mode, \r and \n act similarly (except both in terms of the cursor, as there is no carriage or roller . Historically a \n was used to move the carriage down, while the \r was used to move the carriage back to the left side of the screen.

How can I kill a process by name instead of PID?

I was asking myself the same question but the problem with the current answers is that they don't safe check the processes to be killed so... it could lead to terrible mistakes :)... especially if several processes matches the pattern.

As a disclaimer, I'm not a sh pro and there is certainly room for improvement.

So I wrote a little sh script :

#!/bin/sh

killables=$(ps aux | grep $1 | grep -v mykill | grep -v grep)
if [ ! "${killables}" = "" ]
then
  echo "You are going to kill some process:"
  echo "${killables}"
else
  echo "No process with the pattern $1 found."
  return
fi
echo -n "Is it ok?(Y/N)"
read input
if [ "$input" = "Y" ]
then
  for pid in $(echo "${killables}" | awk '{print $2}')
  do
    echo killing $pid "..."
    kill $pid 
    echo $pid killed
  done
fi

How to sort in mongoose?

with the current version of mongoose (1.6.0) if you only want to sort by one column, you have to drop the array and pass the object directly to the sort() function:

Content.find().sort('created', 'descending').execFind( ... );

took me some time, to get this right :(

Shell command to tar directory excluding certain files/folders

You can use standard "ant notation" to exclude directories relative.
This works for me and excludes any .git or node_module directories:

tar -cvf myFile.tar --exclude=**/.git/* --exclude=**/node_modules/*  -T /data/txt/myInputFile.txt 2> /data/txt/myTarLogFile.txt

myInputFile.txt contains:

/dev2/java
/dev2/javascript

Bridged networking not working in Virtualbox under Windows 10

WINDOWS FIX: Ive' Fixed it by downloading a new VMbox installer from the Official Website Here.

  • Just run the installer and install it to override your current VMBox version, that should fix it.

Dont worry about your VM's they will not disappear if you override your current installation.

NOTE: If you already have the latest version, you need to export all your VM's, unninstall your current VMBox and install it from new installer.

Upload artifacts to Nexus, without Maven

No need to use these commands .. you can directly use the nexus web Interface in order to upload your JAR using GAV parameters.

enter image description here

So it is very simple.

See changes to a specific file using git

You can use gitk [filename] to see the changes log

How to get table cells evenly spaced?

In your CSS file:

.TableHeader { width: 100px; }

This will set all of the td tags below each header to 100px. You can also add a width definition (in the markup) to each individual th tag, but the above solution would be easier.

Passing on command line arguments to runnable JAR

You can pass program arguments on the command line and get them in your Java app like this:

public static void main(String[] args) {
  String pathToXml = args[0];
....
}

Alternatively you pass a system property by changing the command line to:

java -Dpath-to-xml=enwiki-20111007-pages-articles.xml -jar wiki2txt

and your main class to:

public static void main(String[] args) {
  String pathToXml = System.getProperty("path-to-xml");
....
}

How to check if two words are anagrams

// When this method returns 0 means strings are Anagram, else Not.

public static int isAnagram(String str1, String str2) {
        int value = 0;
        if (str1.length() == str2.length()) {
            for (int i = 0; i < str1.length(); i++) {
                value = value + str1.charAt(i);
                value = value - str2.charAt(i);
            }

        } else {
            value = -1;
        }
        return value;
    }

Eclipse: Syntax Error, parameterized types are only if source level is 1.5

It can be resolved as follows:

  1. Go to Project properties.

  2. Then 'Java Compiler' -> Check the box ('Enable project specific settings')

  3. Change the compiler compliance level to '5.0' & click ok.

Do rebuild. It will be resolved.

Also, click the checkbox for "Use default compliance settings".

LINQ order by null column where order is ascending and nulls should be last

my decision:

Array = _context.Products.OrderByDescending(p => p.Val ?? float.MinValue)

Add and remove attribute with jquery

If you want to do this, you need to save it in a variable first. So you don't need to use id to query this element every time.

var el = $("#page_navigation1");

$("#add").click(function(){
  el.attr("id","page_navigation1");
});     

$("#remove").click(function(){
  el.removeAttr("id");
});     

Double vs. BigDecimal?

BigDecimal is Oracle's arbitrary-precision numerical library. BigDecimal is part of the Java language and is useful for a variety of applications ranging from the financial to the scientific (that's where sort of am).

There's nothing wrong with using doubles for certain calculations. Suppose, however, you wanted to calculate Math.Pi * Math.Pi / 6, that is, the value of the Riemann Zeta Function for a real argument of two (a project I'm currently working on). Floating-point division presents you with a painful problem of rounding error.

BigDecimal, on the other hand, includes many options for calculating expressions to arbitrary precision. The add, multiply, and divide methods as described in the Oracle documentation below "take the place" of +, *, and / in BigDecimal Java World:

http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html

The compareTo method is especially useful in while and for loops.

Be careful, however, in your use of constructors for BigDecimal. The string constructor is very useful in many cases. For instance, the code

BigDecimal onethird = new BigDecimal("0.33333333333");

utilizes a string representation of 1/3 to represent that infinitely-repeating number to a specified degree of accuracy. The round-off error is most likely somewhere so deep inside the JVM that the round-off errors won't disturb most of your practical calculations. I have, from personal experience, seen round-off creep up, however. The setScale method is important in these regards, as can be seen from the Oracle documentation.

The correct way to read a data file into an array

It depends on the size of the file! The solutions above tend to use convenient shorthands to copy the entire file into memory, which will work in many cases.

For very large files you may need to use a streaming design where read the file by line or in chucks, process the chunks, then discard them from memory.

See the answer on reading line by line with perl if that's what you need.

angularjs: ng-src equivalent for background-image:url(...)

This one works for me

<li ng-style="{'background-image':'url(/static/'+imgURL+')'}">...</li>

Node.js server that accepts POST requests

Receive POST and GET request in nodejs :

1).Server

    var http = require('http');
    var server = http.createServer ( function(request,response){

    response.writeHead(200,{"Content-Type":"text\plain"});
    if(request.method == "GET")
        {
            response.end("received GET request.")
        }
    else if(request.method == "POST")
        {
            response.end("received POST request.");
        }
    else
        {
            response.end("Undefined request .");
        }
});

server.listen(8000);
console.log("Server running on port 8000");

2). Client :

var http = require('http');

var option = {
    hostname : "localhost" ,
    port : 8000 ,
    method : "POST",
    path : "/"
} 

    var request = http.request(option , function(resp){
       resp.on("data",function(chunck){
           console.log(chunck.toString());
       }) 
    })
    request.end();

Set android shape color programmatically

Note: Answer has been updated to cover the scenario where background is an instance of ColorDrawable. Thanks Tyler Pfaff, for pointing this out.

The drawable is an oval and is the background of an ImageView

Get the Drawable from imageView using getBackground():

Drawable background = imageView.getBackground();

Check against usual suspects:

if (background instanceof ShapeDrawable) {
    // cast to 'ShapeDrawable'
    ShapeDrawable shapeDrawable = (ShapeDrawable) background;
    shapeDrawable.getPaint().setColor(ContextCompat.getColor(mContext,R.color.colorToSet));
} else if (background instanceof GradientDrawable) {
    // cast to 'GradientDrawable'
    GradientDrawable gradientDrawable = (GradientDrawable) background;
    gradientDrawable.setColor(ContextCompat.getColor(mContext,R.color.colorToSet));
} else if (background instanceof ColorDrawable) {
    // alpha value may need to be set again after this call
    ColorDrawable colorDrawable = (ColorDrawable) background;
    colorDrawable.setColor(ContextCompat.getColor(mContext,R.color.colorToSet));
}

Compact version:

Drawable background = imageView.getBackground();
if (background instanceof ShapeDrawable) {
    ((ShapeDrawable)background).getPaint().setColor(ContextCompat.getColor(mContext,R.color.colorToSet));
} else if (background instanceof GradientDrawable) {
    ((GradientDrawable)background).setColor(ContextCompat.getColor(mContext,R.color.colorToSet));
} else if (background instanceof ColorDrawable) {
    ((ColorDrawable)background).setColor(ContextCompat.getColor(mContext,R.color.colorToSet));
}

Note that null-checking is not required.

However, you should use mutate() on the drawables before modifying them if they are used elsewhere. (By default, drawables loaded from XML share the same state.)

How to use Git and Dropbox together?

Now in 2014, I have been using Git and Dropbox for about one year and a half without problem. Some points though:

  • All my machines using Dropbox are on Windows, different versions (7 to 8) + 1 mac.
  • I do not share the repository with someone else, so I am the only one to modify it.
  • git push pushes to a remote repository, so that if it ever gets corrupted, I can easily recover it.
  • I had to create aliases in C:\Users with mklink /D link target because some libraries were pointed to absolute locations.

How to set cursor to input box in Javascript?

I realize that this is quite and old question, but I have a 'stupid' solution to a similar problem which maybe could help someone.

I experienced the same problem with a text box which shown as selected (by the Focus method in JQuery), but did not take the cursor in.

The fact is that I had the Debugger window open to see what is happening and THAT window was stealing the focus. The solution is banally simple: just close the Debugger and everything is fine...1 hour spent in testing!

Why do Sublime Text 3 Themes not affect the sidebar?

You can manually change the sidebar style by editing Default.sublime-theme.

To do this, edit the “sidebar_tree”, “sidebar_heading” etc., classes in Packages/Theme - Default/Default.sublime-theme. You can override those defaults by putting this Default.sublime-theme inside the Packages/User folder.

From the Sublime Text menu, selecting “Preferences ? Browse Packages…” will take you to it.

How to sum a variable by group

Another solution that returns sums by groups in a matrix or a data frame and is short and fast:

rowsum(x$Frequency, x$Category)

What does the arrow operator, '->', do in Java?

This one is useful as well when you want to implement a functional interface

Runnable r = ()-> System.out.print("Run method");

is equivalent to

Runnable r = new Runnable() {
        @Override
        public void run() {
            System.out.print("Run method");
        }
};

How to get resources directory path programmatically

Just use com.google.common.io.Resources class. Example:

 URL url = Resources.getResource("file name")

After that you have methods like: .getContent(), .getFile(), .getPath() etc

How to write into a file in PHP?

Consider fwrite():

<?php
$fp = fopen('lidn.txt', 'w');
fwrite($fp, 'Cats chase mice');
fclose($fp);
?>

Flutter position stack widget in center

You can change the Positioned with Align inside a Stack:

Align(
  alignment: Alignment.bottomCenter,
  child: ... ,
),

For more info about Stack: Exploring Stack

Postgres Error: More than one row returned by a subquery used as an expression

Technically, to repair your statement, you can add LIMIT 1 to the subquery to ensure that at most 1 row is returned. That would remove the error, your code would still be nonsense.

... 'SELECT store_key FROM store LIMIT 1' ...

Practically, you want to match rows somehow instead of picking an arbitrary row from the remote table store to update every row of your local table customer.
Your rudimentary question doesn't provide enough details, so I am assuming a text column match_name in both tables (and UNIQUE in store) for the sake of this example:

... 'SELECT store_key FROM store
     WHERE match_name = ' || quote_literal(customer.match_name)  ...

But that's an extremely expensive way of doing things.

Ideally, you should completely rewrite the statement.

UPDATE customer c
SET    customer_id = s.store_key
FROM   dblink('port=5432, dbname=SERVER1 user=postgres password=309245'
             ,'SELECT match_name, store_key FROM store')
       AS s(match_name text, store_key integer)
WHERE c.match_name = s.match_name
AND   c.customer_id IS DISTINCT FROM s.store_key;

This remedies a number of problems in your original statement.

  • Obviously, the basic problem leading to your error is fixed.

  • It's almost always better to join in additional relations in the FROM clause of an UPDATE statement than to run correlated subqueries for every individual row.

  • When using dblink, the above becomes a thousand times more important. You do not want to call dblink() for every single row, that's extremely expensive. Call it once to retrieve all rows you need.

  • With correlated subqueries, if no row is found in the subquery, the column gets updated to NULL, which is almost always not what you want.
    In my updated form, the row only gets updated if a matching row is found. Else, the row is not touched.

  • Normally, you wouldn't want to update rows, when nothing actually changes. That's expensively doing nothing (but still produces dead rows). The last expression in the WHERE clause prevents such empty updates:

     AND   c.customer_id IS DISTINCT FROM sub.store_key
    

How to split a data frame?

subset() is also useful:

subset(DATAFRAME, COLUMNNAME == "")

For a survey package, maybe the survey package is pertinent?

http://faculty.washington.edu/tlumley/survey/

Java Hashmap: How to get key from value?

As far as I know keys and values of a HashMap are not mixed when you represent them as arrays:

hashmap.values().toArray()

and

hashmap.keySet().toArray()

So the following code (since java 8) should work as expected:

public Object getKeyByFirstValue(Object value) {
    int keyNumber =  Arrays.asList(hashmap.values().toArray()).indexOf(value);
    return hashmap.keySet().toArray()[keyNumber];
}

However, (WARNING!) it works 2-3 times slower than iteration.

Java Webservice Client (Best way)

What is the best approach to do this JAVA?

I would personally NOT use Axis 2, even for client side development only. Here is why I stay away from it:

  1. I don't like its architecture and hate its counter productive deployment model.
  2. I find it to be low quality project.
  3. I don't like its performances (see this benchmark against JAX-WS RI).
  4. It's always a nightmare to setup dependencies (I use Maven and I always have to fight with the gazillion of dependencies) (see #2)
  5. Axis sucked big time and Axis2 isn't better. No, this is not a personal opinion, there is a consensus.
  6. I suffered once, never again.

The only reason Axis is still around is IMO because it's used in Eclipse since ages. Thanks god, this has been fixed in Eclipse Helios and I hope Axis2 will finally die. There are just much better stacks.

I read about SAAJ, looks like that will be more granular level of approach?

To do what?

Is there any other way than using the WSDL2Java tool, to generate the code. Maybe wsimport in another option. What are the pros and cons?

Yes! Prefer a JAX-WS stack like CXF or JAX-WS RI (you might also read about Metro, Metro = JAX-WS RI + WSIT), they are just more elegant, simpler, easier to use. In your case, I would just use JAX-WS RI which is included in Java 6 and thus wsimport.

Can someone send the links for some good tutorials on these topics?

That's another pro, there are plenty of (good quality) tutorials for JAX-WS, see for example:

What are the options we need to use while generating the code using the WSDL2Java?

No options, use wsimport :)

See also

Related questions

Regex to remove all special characters from string?

tmp = Regex.Replace(n, @"\W+", "");

\w matches letters, digits, and underscores, \W is the negated version.

Convert String to Type in C#

You can only use just the name of the type (with its namespace, of course) if the type is in mscorlib or the calling assembly. Otherwise, you've got to include the assembly name as well:

Type type = Type.GetType("Namespace.MyClass, MyAssembly");

If the assembly is strongly named, you've got to include all that information too. See the documentation for Type.GetType(string) for more information.

Alternatively, if you have a reference to the assembly already (e.g. through a well-known type) you can use Assembly.GetType:

Assembly asm = typeof(SomeKnownType).Assembly;
Type type = asm.GetType(namespaceQualifiedTypeName);

When should we use intern method of String on String literals

string intern() method is used to create an exact copy of heap string object in string constant pool. The string objects in the string constant pool are automatically interned but string objects in heap are not. The main use of creating interns is to save the memory space and to perform faster comparison of string objects.

Source : What is string intern in java?

Split string with string as delimiter

I've found two older scripts that use an indefinite or even a specific string to split. As an approach, these are always helpful.

https://www.administrator.de/contentid/226533#comment-1059704 https://www.administrator.de/contentid/267522#comment-1000886

@echo off
:noOption
if "%~1" neq "" goto :nohelp
echo Gibt eine Ausgabe bis zur angebenen Zeichenfolge&echo(
echo %~n0 ist mit Eingabeumleitung zu nutzen
echo %~n0 "Zeichenfolge" ^<Quelldatei [^>Zieldatei]&echo(
echo    Zeichenfolge    die zu suchende Zeichenfolge wird mit FIND bestimmt
echo            ohne AusgabeUmleitung Ausgabe im CMD Fenster
exit /b
:nohelp
setlocal disabledelayedexpansion
set "intemp=%temp%%time::=%"
set "string=%~1"
set "stringlength=0"
:Laenge string bestimmen
for /f eol^=^

^ delims^= %%i in (' cmd /u /von /c "echo(!string!"^|find /v "" ') do set /a Stringlength += 1

:Eingabe temporär speichern
>"%intemp%" find /n /v ""

:suchen der Zeichenfolge und Zeile bestimmen und speichen
set "NRout="
for /f "tokens=*delims=" %%a in (' find "%string%"^<"%intemp%" ') do if not defined NRout (set "LineStr=%%a"
  for /f "delims=[]" %%b in ("%%a") do set "NRout=%%b"
)
if not defined NRout >&2 echo Zeichenfolge nicht gefunden.& set /a xcode=1 &goto :end
if %NRout% gtr 1 call :Line
call :LineStr

:end
del "%intemp%"
exit /b %xcode%

:LineStr Suche nur jeden ersten Buchstaben des Strings in der Treffer-Zeile dann Ausgabe bis dahin
for /f eol^=^

^ delims^= %%a in ('cmd /u /von /c "echo(!String!"^|findstr .') do (
  for /f "delims=[]" %%i in (' cmd /u /von /c "echo(!LineStr!"^|find /n "%%a" ') do (
    setlocal enabledelayedexpansion
    for /f %%n in ('set /a %%i-1') do if !LineStr:^~%%n^,%stringlength%! equ !string! (
      set "Lineout=!LineStr:~0,%%n!!string!"
      echo(!Lineout:*]=!
      exit /b
    )
) )
exit /b 

:Line vorige Zeilen ausgeben
for /f "usebackq tokens=* delims=" %%i in ("%intemp%") do (
  for /f "tokens=1*delims=[]" %%n in ("%%i") do if %%n EQU %NRout%  exit /b
  set "Line=%%i"
  setlocal enabledelayedexpansion 
  echo(!Line:*]=!
  endlocal
)
exit /b

@echo off
:: CUTwithWildcards.cmd
:noOption
if "%~1" neq "" goto :nohelp
echo Gibt eine Ausgabe ohne die angebene Zeichenfolge.
echo Der Rest wird abgeschnitten.&echo(
echo %~n0 "Zeichenfolge" B n E [/i] &echo(
echo    Zeichenfolge    String zum Durchsuchen
echo    B   Zeichen Wonach am Anfang gesucht wird
echo    n   Auszulassende Zeichenanzahl
echo    E   Zeichen was das Ende der Zeichen Bestimmt
echo    /i  Case intensive
exit /b
:nohelp
setlocal disabledelayedexpansion
set  "Original=%~1"
set     "Begin=%~2"
set /a    Excl=%~3 ||echo Syntaxfehler.>&2 &&exit /b 1
set       "End=%~4"
if not defined end echo Syntaxfehler.>&2 &exit /b 1
set   "CaseInt=%~5"
:: end Setting Input Param
set       "out="
set      "more="
call :read Original
if errorlevel 1 echo Zeichenfolge nicht gefunden.>&2
exit /b
:read VarName B # E [/i]
for /f "delims=[]" %%a in (' cmd /u /von /c "echo  !%~1!"^|find /n %CaseInt% "%Begin%" ') do (
  if defined out exit /b 0
  for /f "delims=[]" %%b in (' cmd /u /von /c "echo !%1!"^|more +%Excl%^|find /n %CaseInt% "%End%"^|find "[%%a]" ') do (
    set "out=1"
    setlocal enabledelayedexpansion
    set "In=  !Original!"
    set "In=!In:~,%%a!"
    echo !In:^~2!
    endlocal
) )
if not defined out exit /b 1 
exit /b

::oneliner for CMDLine
set "Dq=""
for %i in ("*S??E*") do @set "out=1" &for /f "delims=[]" %a in ('cmd/u/c "echo  %i"^|find /n "S"') do @if defined out for /f "delims=[]" %b in ('cmd/u/c "echo %i"^|more +2^|find /n "E"^|find "[%a]"') do @if %a equ %b set "out=" & set in= "%i" &cmd /v/c echo ren "%i" !in:^~0^,%a!!Dq!)

Cannot create JDBC driver of class ' ' for connect URL 'null' : I do not understand this exception

Did you try to specify resource only in context.xml

<Resource name="jdbc/PollDatasource" auth="Container" type="javax.sql.DataSource"
driverClassName="org.apache.derby.jdbc.EmbeddedDriver"
url="jdbc:derby://localhost:1527/poll_database;create=true"
username="suhail" password="suhail"
maxActive="20" maxIdle="10" maxWait="-1" />

and remove <resource-ref> section from web.xml?

In one project I've seen configuration without <resource-ref> section in web.xml and it worked.

It's an educated guess, but I think <resource-ref> declaration of JNDI resource named jdbc/PollDatasource in web.xml may override declaration of resource with same name in context.xml and the declaration in web.xml is missing both driverClassName and url hence the NPEs for that properties.

How do you join on the same table, twice, in mysql?

Read this and try, this will help you:

Table1

column11,column12,column13,column14

Table2

column21,column22,column23,column24


SELECT table1.column11,table1.column12,table2asnew1.column21,table2asnew2.column21 
FROM table1 INNER JOIN table2 AS table2asnew1 ON table1.column11=table2asnew1.column21  INNER TABLE table2 as table2asnew2 ON table1.column12=table2asnew2.column22

table2asnew1 is an instance of table 2 which is matched by table1.column11=table2asnew1.column21

and

table2asnew2 is another instance of table 2 which is matched by table1.column12=table2asnew2.column22

estimating of testing effort as a percentage of development time

Some years ago, in a safety critical field, I have heard something like one day for unit testing ten lines of code.

I have also observed 50% of effort for development and 50% for testing (not only unit testing).

Error: No toolchains found in the NDK toolchains folder for ABI with prefix: llvm

Steps I have followed to fix the issue as follows,

Analyze -> Code Cleanup

File -> Project Structures -> Select project from the list and update the gradle version to latest.

Build -> Clean Project

Build -> Make Project

Now the issue related to the build may get reported like using compile instead of implementation etc.

Please fix those and hopefully it should fix the issue.

Where does the .gitignore file belong?

When in doubt just place it in the root of your repository. See https://help.github.com/articles/ignoring-files/ for more information.

How to extract a string using JavaScript Regex?

Your regular expression most likely wants to be

/\nSUMMARY:(.*)$/g

A helpful little trick I like to use is to default assign on match with an array.

var arr = iCalContent.match(/\nSUMMARY:(.*)$/g) || [""]; //could also use null for empty value
return arr[0];

This way you don't get annoying type errors when you go to use arr

How to close a GUI when I push a JButton?

See JFrame.setDefaultCloseOperation(DISPOSE_ON_CLOSE)1. You might also use EXIT_ON_CLOSE, but it is better to explicitly clean up any running threads, then when the last GUI element becomes invisible, the EDT & JRE will end.

The 'button' to invoke this operation is already on a frame.

  1. See this answer to How to best position Swing GUIs? for a demo. of the DISPOSE_ON_CLOSE functionality.

    The JRE will end after all 3 frames are closed by clicking the X button.

How do you dynamically allocate a matrix?

or you can just allocate a 1D array but reference elements in a 2D fashion:

to address row 2, column 3 (top left corner is row 0, column 0):

arr[2 * MATRIX_WIDTH + 3]

where MATRIX_WIDTH is the number of elements in a row.

cURL equivalent in Node.js?

Use request npm module and after call

var request = require('request');
request('http://www.google.com', function (error, response, body) {
  console.log('error:', error); // Print the error if one occurred
  console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
  console.log('body:', body); // Print the HTML for the Google homepage.
});

For best practice also use some winston logger module or else simple console.log and then run your application like

npm start output.txt 

Result of above command will generate one txt file on root with all data which you have printed in console.log

Python - Count elements in list

To find count of unique elements of list use the combination of len() and set().

>>> ls = [1, 2, 3, 4, 1, 1, 2]
>>> len(ls)
7
>>> len(set(ls))
4

Downloading jQuery UI CSS from Google's CDN

The Google AJAX Libraries API, which includes jQuery UI (currently v1.10.3), also includes popular themes as per the jQuery UI blog:

Google Ajax Libraries API (CDN)

Download and open PDF file using Ajax

create a hidden iframe, then in your ajax code above:

url: document.getElementById('myiframeid').src = your_server_side_url,

and remove the window.open(response);

python's re: return True if string contains regex pattern

import re
word = 'fubar'
regexp = re.compile(r'ba[rzd]')
if regexp.search(word):
  print 'matched'

How to check if a particular service is running on Ubuntu

There is a simple way to verify if a service is running

systemctl status service_name

Try PostgreSQL:

systemctl status postgresql

PostgreSQL: Show tables in PostgreSQL

First Connect with the Database using following command

\c database_name

And you will see this message - You are now connected to database database_name. And them run the following command

SELECT * FROM table_name;

In database_name and table_name just update with your database and table name

How to completely remove borders from HTML table

For me I needed to do something like this to completely remove the borders from the table and all cells. This does not require modifying the HTML at all, which was helpful in my case.

table, tr, td {
    border: none;
}

Difference between natural join and inner join

Inner join and natural join are almost same but there is a slight difference between them. The difference is in natural join no need to specify condition but in inner join condition is obligatory. If we do specify the condition in inner join , it resultant tables is like a cartesian product.

Escaping double quotes in JavaScript onClick event handler

It needs to be HTML-escaped, not Javascript-escaped. Change \" to &quot;

Get column value length, not column max length of value

LENGTH() does return the string length (just verified). I suppose that your data is padded with blanks - try

SELECT typ, LENGTH(TRIM(t1.typ))
FROM AUTA_VIEW t1;

instead.

As OraNob mentioned, another cause could be that CHAR is used in which case LENGTH() would also return the column width, not the string length. However, the TRIM() approach also works in this case.

How do I clear/delete the current line in terminal?

Ctrl+A, Ctrl+K to wipe the current line in the terminal. You can then recall it with Ctrl+Y if you need.

Executing Javascript from Python

You can use requests-html which will download and use chromium underneath.

from requests_html import HTML

html = HTML(html="<a href='http://www.example.com/'>")

script = """
function escramble_758(){
    var a,b,c
    a='+1 '
    b='84-'
    a+='425-'
    b+='7450'
    c='9'
    return a+c+b;
}
"""

val = html.render(script=script, reload=False)
print(val)
# +1 425-984-7450

More on this read here

node.js, socket.io with SSL

Depending on your needs, you could allow both secure and unsecure connections and still only use one Socket.io instance.

You simply have to instanciate two servers, one for HTTP and one for HTTPS, then attach those servers to the Socket.io instance.

Server side :

// needed to read certificates from disk
const fs          = require( "fs"    );

// Servers with and without SSL
const http        = require( "http"  )
const https       = require( "https" );
const httpPort    = 3333;
const httpsPort   = 3334;
const httpServer  = http.createServer();
const httpsServer = https.createServer({
    "key" : fs.readFileSync( "yourcert.key" ),
    "cert": fs.readFileSync( "yourcert.crt" ),
    "ca"  : fs.readFileSync( "yourca.crt"   )
});
httpServer.listen( httpPort, function() {
    console.log(  `Listening HTTP on ${httpPort}` );
});
httpsServer.listen( httpsPort, function() {
    console.log(  `Listening HTTPS on ${httpsPort}` );
});

// Socket.io
const ioServer = require( "socket.io" );
const io       = new ioServer();
io.attach( httpServer  );
io.attach( httpsServer );

io.on( "connection", function( socket ) {

    console.log( "user connected" );
    // ... your code

});

Client side :

var url    = "//example.com:" + ( window.location.protocol == "https:" ? "3334" : "3333" );
var socket = io( url, {
    // set to false only if you use self-signed certificate !
    "rejectUnauthorized": true
});
socket.on( "connect", function( e ) {
    console.log( "connect", e );
});

If your NodeJS server is different from your Web server, you will maybe need to set some CORS headers. So in the server side, replace:

const httpServer  = http.createServer();
const httpsServer = https.createServer({
    "key" : fs.readFileSync( "yourcert.key" ),
    "cert": fs.readFileSync( "yourcert.crt" ),
    "ca"  : fs.readFileSync( "yourca.crt"   )
});

With:

const CORS_fn = (req, res) => {
    res.setHeader( "Access-Control-Allow-Origin"     , "*"    );
    res.setHeader( "Access-Control-Allow-Credentials", "true" );
    res.setHeader( "Access-Control-Allow-Methods"    , "*"    );
    res.setHeader( "Access-Control-Allow-Headers"    , "*"    );
    if ( req.method === "OPTIONS" ) {
        res.writeHead(200);
        res.end();
        return;
    }
};
const httpServer  = http.createServer( CORS_fn );
const httpsServer = https.createServer({
        "key" : fs.readFileSync( "yourcert.key" ),
        "cert": fs.readFileSync( "yourcert.crt" ),
        "ca"  : fs.readFileSync( "yourca.crt"   )
}, CORS_fn );

And of course add/remove headers and set the values of the headers according to your needs.

How to stop a thread created by implementing runnable interface?

How to stop a thread created by implementing runnable interface?

There are many ways that you can stop a thread but all of them take specific code to do so. A typical way to stop a thread is to have a volatile boolean shutdown field that the thread checks every so often:

  // set this to true to stop the thread
  volatile boolean shutdown = false;
  ...
  public void run() {
      while (!shutdown) {
          // continue processing
      }
  }

You can also interrupt the thread which causes sleep(), wait(), and some other methods to throw InterruptedException. You also should test for the thread interrupt flag with something like:

  public void run() {
      while (!Thread.currentThread().isInterrupted()) {
          // continue processing
          try {
              Thread.sleep(1000);
          } catch (InterruptedException e) {
              // good practice
              Thread.currentThread().interrupt();
              return;
          }
      }
  }

Note that that interrupting a thread with interrupt() will not necessarily cause it to throw an exception immediately. Only if you are in a method that is interruptible will the InterruptedException be thrown.

If you want to add a shutdown() method to your class which implements Runnable, you should define your own class like:

public class MyRunnable implements Runnable {
    private volatile boolean shutdown;
    public void run() {
        while (!shutdown) {
            ...
        }
    }
    public void shutdown() {
        shutdown = true;
    }
}

HTTP requests and JSON parsing in Python

import urllib
import json

url = 'http://maps.googleapis.com/maps/api/directions/json?origin=Chicago,IL&destination=Los+Angeles,CA&waypoints=Joplin,MO|Oklahoma+City,OK&sensor=false'
result = json.load(urllib.urlopen(url))

Send FormData and String Data Together Through JQuery AJAX?

well, as an easier alternative and shorter, you could do this too!!

var fd = new FormData();

var file_data = object.get(0).files[i];
var other_data = $('form').serialize(); //page_id=&category_id=15&method=upload&required%5Bcategory_id%5D=Category+ID

fd.append("file", file_data);

$.ajax({
    url: 'add.php?'+ other_data,  //<== just add it to the end of url ***
    data: fd,
    contentType: false,
    processData: false,
    type: 'POST',
    success: function(data){
        alert(data);
    }
});

How to use new PasswordEncoder from Spring Security

Having just gone round the internet to read up on this and the options in Spring I'd second Luke's answer, use BCrypt (it's mentioned in the source code at Spring).

The best resource I found to explain why to hash/salt and why use BCrypt is a good choice is here: Salted Password Hashing - Doing it Right.

Excel is not updating cells, options > formula > workbook calculation set to automatic

Go to Files->Options->Formulas-> Calculation Options / Set Workbook calculation to Automatic

create multiple tag docker image

You can't create tags with Dockerfiles but you can create multiple tags on your images via the command line.

Use this to list your image ids:

$ docker images

Then tag away:

$ docker tag 9f676bd305a4 ubuntu:13.10
$ docker tag 9f676bd305a4 ubuntu:saucy
$ docker tag eb601b8965b8 ubuntu:raring
...

How to trim whitespace from a Bash variable?

I've seen scripts just use variable assignment to do the job:

$ xyz=`echo -e 'foo \n bar'`
$ echo $xyz
foo bar

Whitespace is automatically coalesced and trimmed. One has to be careful of shell metacharacters (potential injection risk).

I would also recommend always double-quoting variable substitutions in shell conditionals:

if [ -n "$var" ]; then

since something like a -o or other content in the variable could amend your test arguments.

Copy a file in a sane, safe and efficient way

I'm not quite sure what a "good way" of copying a file is, but assuming "good" means "fast", I could broaden the subject a little.

Current operating systems have long been optimized to deal with run of the mill file copy. No clever bit of code will beat that. It is possible that some variant of your copy techniques will prove faster in some test scenario, but they most likely would fare worse in other cases.

Typically, the sendfile function probably returns before the write has been committed, thus giving the impression of being faster than the rest. I haven't read the code, but it is most certainly because it allocates its own dedicated buffer, trading memory for time. And the reason why it won't work for files bigger than 2Gb.

As long as you're dealing with a small number of files, everything occurs inside various buffers (the C++ runtime's first if you use iostream, the OS internal ones, apparently a file-sized extra buffer in the case of sendfile). Actual storage media is only accessed once enough data has been moved around to be worth the trouble of spinning a hard disk.

I suppose you could slightly improve performances in specific cases. Off the top of my head:

  • If you're copying a huge file on the same disk, using a buffer bigger than the OS's might improve things a bit (but we're probably talking about gigabytes here).
  • If you want to copy the same file on two different physical destinations you will probably be faster opening the three files at once than calling two copy_file sequentially (though you'll hardly notice the difference as long as the file fits in the OS cache)
  • If you're dealing with lots of tiny files on an HDD you might want to read them in batches to minimize seeking time (though the OS already caches directory entries to avoid seeking like crazy and tiny files will likely reduce disk bandwidth dramatically anyway).

But all that is outside the scope of a general purpose file copy function.

So in my arguably seasoned programmer's opinion, a C++ file copy should just use the C++17 file_copy dedicated function, unless more is known about the context where the file copy occurs and some clever strategies can be devised to outsmart the OS.

input type="submit" Vs button tag are they interchangeable?

<input type='submit' /> doesn't support HTML inside of it, since it's a single self-closing tag. <button>, on the other hand, supports HTML, images, etc. inside because it's a tag pair: <button><img src='myimage.gif' /></button>. <button> is also more flexible when it comes to CSS styling.

The disadvantage of <button> is that it's not fully supported by older browsers. IE6/7, for example, don't display it correctly.

Unless you have some specific reason, it's probably best to stick to <input type='submit' />.

row-level trigger vs statement-level trigger

1)row level trigger is used to perform action on set of rows as insert , update or delete

example:-you have to delete a set of rows and simultaneously that deleted rows must also inserted in new table for audit purpose;

2)statement level trigger:- it generally used to imposed restriction on the event you are performing.

example:- restriction to delete the data between 10 pm and 6 am;

hope this helps:)

Importing class/java files in Eclipse

I had the same problem. But What I did is I imported the .java files and then I went to Search->File-> and then changed the package name to whatever package it should belong in this way I fixed a lot of java files which otherwise would require to go to every file and change them manually.

How do you performance test JavaScript code?

Try jsPerf. It's an online javascript performance tool for benchmarking and comparing snippets of code. I use it all the time.

Can I return the 'id' field after a LINQ insert?

When inserting the generated ID is saved into the instance of the object being saved (see below):

protected void btnInsertProductCategory_Click(object sender, EventArgs e)
{
  ProductCategory productCategory = new ProductCategory();
  productCategory.Name = “Sample Category”;
  productCategory.ModifiedDate = DateTime.Now;
  productCategory.rowguid = Guid.NewGuid();
  int id = InsertProductCategory(productCategory);
  lblResult.Text = id.ToString();
}

//Insert a new product category and return the generated ID (identity value)
private int InsertProductCategory(ProductCategory productCategory)
{
  ctx.ProductCategories.InsertOnSubmit(productCategory);
  ctx.SubmitChanges();
  return productCategory.ProductCategoryID;
}

reference: http://blog.jemm.net/articles/databases/how-to-common-data-patterns-with-linq-to-sql/#4

How to make a hyperlink in telegram without using bots?

As of Telegram Desktop 1.3 you can format your messages and add links.

[Ctrl+K] = create link (https://my.website)

Other useful hotkeys are:

[Ctrl+B] = bold
[Ctrl+I] = italic
[Ctrl+Shift+M] = monospace
[Ctrl+Shift+N] = clear formatting

Clearing a text field on button click

If you want to reset it, then simple use:

<input type="reset" value="Reset" />

But beware, it will not clear out textboxes that have default value. For example, if we have the following textboxes and by default, they have the following values:

<input id="textfield1" type="text" value="sample value 1" />
<input id="textfield2" type="text" value="sample value 2" />

So, to clear it out, compliment it with javascript:

function clearText()  
{
    document.getElementById('textfield1').value = "";
    document.getElementById('textfield2').value = "";
}  

And attach it to onclick of the reset button:
<input type="reset" value="Reset" onclick="clearText()" />

Pushing value of Var into an Array

jQuery is not the same as an array. If you want to append something at the end of a jQuery object, use:

$('#fruit').append(veggies);

or to append it to the end of a form value like in your example:

 $('#fruit').val($('#fruit').val()+veggies);

In your case, fruitvegbasket is a string that contains the current value of #fruit, not an array.

jQuery (jquery.com) allows for DOM manipulation, and the specific function you called val() returns the value attribute of an input element as a string. You can't push something onto a string.

Python conditional assignment operator

No, not knowing which variables are defined is a bug, not a feature in Python.

Use dicts instead:

d = {}
d.setdefault('key', 1)
d['key'] == 1

d['key'] = 2
d.setdefault('key', 1)
d['key'] == 2

How to create a string with format?

nothing special

let str = NSString(format:"%d , %f, %ld, %@", INT_VALUE, FLOAT_VALUE, LONG_VALUE, STRING_VALUE)

How to set column widths to a jQuery datatable?

Configuration Options:

$(document).ready(function () {

  $("#companiesTable").dataTable({
    "sPaginationType": "full_numbers",
    "bJQueryUI": true,
    "bAutoWidth": false, // Disable the auto width calculation 
    "aoColumns": [
      { "sWidth": "30%" }, // 1st column width 
      { "sWidth": "30%" }, // 2nd column width 
      { "sWidth": "40%" } // 3rd column width and so on 
    ]
  });
});

Specify the css for the table:

table.display {
  margin: 0 auto;
  width: 100%;
  clear: both;
  border-collapse: collapse;
  table-layout: fixed;         // add this 
  word-wrap:break-word;        // add this 
}

HTML:

<table id="companiesTable" class="display"> 
  <thead>
    <tr>
      <th>Company name</th>
      <th>Address</th>
      <th>Town</th>
    </tr>
  </thead>
  <tbody>

    <% for(Company c: DataRepository.GetCompanies()){ %>
      <tr>  
        <td><%=c.getName()%></td>
        <td><%=c.getAddress()%></td>
        <td><%=c.getTown()%></td>
      </tr>
    <% } %>

  </tbody>
</table>

It works for me!

How to call a stored procedure (with parameters) from another stored procedure without temp table

You can call a stored procedure from another stored procedure by using the EXECUTE command.

Say your procedure is X. Then in X you can use

EXECUTE PROCEDURE Y () RETURNING_VALUES RESULT;"

Is it possible to install iOS 6 SDK on Xcode 5?

You can download the older SDK and install it in

Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/

folder. Logout + Login just to make sure the changes take effect and you should see the older SDK in your new XCode

How to take backup of a single table in a MySQL database?

You can use this code:

This example takes a backup of sugarcrm database and dumps the output to sugarcrm.sql

# mysqldump -u root -ptmppassword sugarcrm > sugarcrm.sql

# mysqldump -u root -p[root_password] [database_name] > dumpfilename.sql

The sugarcrm.sql will contain drop table, create table and insert command for all the tables in the sugarcrm database. Following is a partial output of sugarcrm.sql, showing the dump information of accounts_contacts table:

--

-- Table structure for table accounts_contacts

DROP TABLE IF EXISTS `accounts_contacts`;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
CREATE TABLE `accounts_contacts` (
`id` varchar(36) NOT NULL,
`contact_id` varchar(36) default NULL,
`account_id` varchar(36) default NULL,
`date_modified` datetime default NULL,
`deleted` tinyint(1) NOT NULL default '0',
PRIMARY KEY (`id`),
KEY `idx_account_contact` (`account_id`,`contact_id`),
KEY `idx_contid_del_accid` (`contact_id`,`deleted`,`account_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
SET character_set_client = @saved_cs_client;

--

CORS: Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true

This works for me in development but I can't advise that in production, it's just a different way of getting the job done that hasn't been mentioned yet but probably not the best. Anyway here goes:

You can get the origin from the request, then use that in the response header. Here's how it looks in express:

app.use(function(req, res, next) {
  res.header('Access-Control-Allow-Origin', req.header('origin') );
  next();
});

I don't know what that would look like with your python setup but that should be easy to translate.

Check if a value is within a range of numbers

If you want your code to pick a specific range of digits, be sure to use the && operator instead of the ||.

_x000D_
_x000D_
if (x >= 4 && x <= 9) {_x000D_
  // do something_x000D_
} else {_x000D_
  // do something else_x000D_
}_x000D_
_x000D_
// be sure not to do this_x000D_
_x000D_
if (x >= 4 || x <= 9) {_x000D_
  // do something_x000D_
} else {_x000D_
  // do something else_x000D_
}
_x000D_
_x000D_
_x000D_

How to launch an Activity from another Application in Android

It is possible to start an app's activity by using Intent.setClassName according to the docs.

An example:

val activityName = "com.google.android.apps.muzei.MuzeiActivity" // target activity name
val packageName = "net.nurik.roman.muzei" // target package's name
val intent = Intent().setClassName(packageName, activityName)
startActivity(intent)

To open it outside the current app, add this flag before starting the intent.

intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)

A related answer here

What does functools.wraps do?

I very often use classes, rather than functions, for my decorators. I was having some trouble with this because an object won't have all the same attributes that are expected of a function. For example, an object won't have the attribute __name__. I had a specific issue with this that was pretty hard to trace where Django was reporting the error "object has no attribute '__name__'". Unfortunately, for class-style decorators, I don't believe that @wrap will do the job. I have instead created a base decorator class like so:

class DecBase(object):
    func = None

    def __init__(self, func):
        self.__func = func

    def __getattribute__(self, name):
        if name == "func":
            return super(DecBase, self).__getattribute__(name)

        return self.func.__getattribute__(name)

    def __setattr__(self, name, value):
        if name == "func":
            return super(DecBase, self).__setattr__(name, value)

        return self.func.__setattr__(name, value)

This class proxies all the attribute calls over to the function that is being decorated. So, you can now create a simple decorator that checks that 2 arguments are specified like so:

class process_login(DecBase):
    def __call__(self, *args):
        if len(args) != 2:
            raise Exception("You can only specify two arguments")

        return self.func(*args)

MySQL Fire Trigger for both Insert and Update

unfortunately we can't use in MySQL after INSERT or UPDATE description, like in Oracle

INNER JOIN same table

I think the problem is in your JOIN condition.

SELECT user.user_fname,
       user.user_lname,
       parent.user_fname,
       parent.user_lname
FROM users AS user
JOIN users AS parent 
  ON parent.user_id = user.user_parent_id
WHERE user.user_id = $_GET[id]

Edit: You should probably use LEFT JOIN if there are users with no parents.

How do I convert NSMutableArray to NSArray?

you try this code---

NSMutableArray *myMutableArray = [myArray mutableCopy];

and

NSArray *myArray = [myMutableArray copy];

Vagrant shared and synced folders

shared folders VS synced folders

Basically shared folders are renamed to synced folder from v1 to v2 (docs), under the bonnet it is still using vboxsf between host and guest (there is known performance issues if there are large numbers of files/directories).

Vagrantfile directory mounted as /vagrant in guest

Vagrant is mounting the current working directory (where Vagrantfile resides) as /vagrant in the guest, this is the default behaviour.

See docs

NOTE: By default, Vagrant will share your project directory (the directory with the Vagrantfile) to /vagrant.

You can disable this behaviour by adding cfg.vm.synced_folder ".", "/vagrant", disabled: true in your Vagrantfile.

Why synced folder is not working

Based on the output /tmp on host was NOT mounted during up time.

Use VAGRANT_INFO=debug vagrant up or VAGRANT_INFO=debug vagrant reload to start the VM for more output regarding why the synced folder is not mounted. Could be a permission issue (mode bits of /tmp on host should be drwxrwxrwt).

I did a test quick test using the following and it worked (I used opscode bento raring vagrant base box)

config.vm.synced_folder "/tmp", "/tmp/src"

output

$ vagrant reload
[default] Attempting graceful shutdown of VM...
[default] Setting the name of the VM...
[default] Clearing any previously set forwarded ports...
[default] Creating shared folders metadata...
[default] Clearing any previously set network interfaces...
[default] Available bridged network interfaces:
1) eth0
2) vmnet8
3) lxcbr0
4) vmnet1
What interface should the network bridge to? 1
[default] Preparing network interfaces based on configuration...
[default] Forwarding ports...
[default] -- 22 => 2222 (adapter 1)
[default] Running 'pre-boot' VM customizations...
[default] Booting VM...
[default] Waiting for VM to boot. This can take a few minutes.
[default] VM booted and ready for use!
[default] Configuring and enabling network interfaces...
[default] Mounting shared folders...
[default] -- /vagrant
[default] -- /tmp/src

Within the VM, you can see the mount info /tmp/src on /tmp/src type vboxsf (uid=900,gid=900,rw).

ReactJS SyntheticEvent stopPropagation() only works with React events?

I ran into this problem yesterday, so I created a React-friendly solution.

Check out react-native-listener. It's working very well so far. Feedback appreciated.

How do you set the startup page for debugging in an ASP.NET MVC application?

Revisiting this page and I have more information to share with others.

Debugging environment (using Visual Studio)

1a) Stephen Walter's link to set the startup page on MVC using the project properties is only applicable when you are debugging your MVC application.

1b) Right mouse click on the .aspx page in Solution Explorer and select the "Set As Start Page" behaves the same.

Note: in both the above cases, the startup page setting is only recognised by your Visual Studio Development Server. It is not recognised by your deployed server.

Deployed environment

2a) To set the startup page, assuming that you have not change any of the default routings, change the content of /Views/Home/Index.aspx to do a "Server.Transfer" or a "Response.Redirect" to your desired page.

2b) Change your default routing in your global.asax.cs to your desired page.

Are there any other options that the readers are aware of? Which of the above (including your own option) would be your preferred solution (and please share with us why)?

Python coding standards/best practices

Yes, I try to follow it as closely as possible.

I don't follow any other coding standards.

How do you echo a 4-digit Unicode character in Bash?

Based on Stack Overflow questions Unix cut, remove first token and https://stackoverflow.com/a/15903654/781312:

(octal=$(echo -n ? | od -t o1 | head -1 | cut -d' ' -f2- | sed -e 's#\([0-9]\+\) *#\\0\1#g')
echo Octal representation is following $octal
echo -e "$octal")

Output is the following.

Octal representation is following \0342\0230\0240
?

SQLAlchemy ORDER BY DESCENDING?

You can use .desc() function in your query just like this

query = (model.Session.query(model.Entry)
        .join(model.ClassificationItem)
        .join(model.EnumerationValue)
        .filter_by(id=c.row.id)
        .order_by(model.Entry.amount.desc())
        )

This will order by amount in descending order or

query = session.query(
    model.Entry
).join(
    model.ClassificationItem
).join(
    model.EnumerationValue
).filter_by(
    id=c.row.id
).order_by(
    model.Entry.amount.desc()
)
)

Use of desc function of SQLAlchemy

from sqlalchemy import desc
query = session.query(
    model.Entry
).join(
    model.ClassificationItem
).join(
    model.EnumerationValue
).filter_by(
    id=c.row.id
).order_by(
    desc(model.Entry.amount)
)
)

For official docs please use the link or check below snippet

sqlalchemy.sql.expression.desc(column) Produce a descending ORDER BY clause element.

e.g.:

from sqlalchemy import desc

stmt = select([users_table]).order_by(desc(users_table.c.name))

will produce SQL as:

SELECT id, name FROM user ORDER BY name DESC

The desc() function is a standalone version of the ColumnElement.desc() method available on all SQL expressions, e.g.:

stmt = select([users_table]).order_by(users_table.c.name.desc())

Parameters column – A ColumnElement (e.g. scalar SQL expression) with which to apply the desc() operation.

See also

asc()

nullsfirst()

nullslast()

Select.order_by()

How can I remove the first line of a text file using bash/sed script?

Would using tail on N-1 lines and directing that into a file, followed by removing the old file, and renaming the new file to the old name do the job?

If i were doing this programatically, i would read through the file, and remember the file offset, after reading each line, so i could seek back to that position to read the file with one less line in it.

echo that outputs to stderr

Mac OS X: I tried the accepted answer and a couple of other answers and all of them resulted in writing STDOUT not STDERR on my Mac.

Here is a portable way to write to standard error using Perl:

echo WARNING! | perl -ne 'print STDERR'

How to print Unicode character in C++?

To represent the character you can use Universal Character Names (UCNs). The character '?' has the Unicode value U+0444 and so in C++ you could write it '\u0444' or '\U00000444'. Also if the source code encoding supports this character then you can just write it literally in your source code.

// both of these assume that the character can be represented with
// a single char in the execution encoding
char b = '\u0444';
char a = '?'; // this line additionally assumes that the source character encoding supports this character

Printing such characters out depends on what you're printing to. If you're printing to a Unix terminal emulator, the terminal emulator is using an encoding that supports this character, and that encoding matches the compiler's execution encoding, then you can do the following:

#include <iostream>

int main() {
    std::cout << "Hello, ? or \u0444!\n";
}

This program does not require that '?' can be represented in a single char. On OS X and most any modern Linux install this will work just fine, because the source, execution, and console encodings will all be UTF-8 (which supports all Unicode characters).

Things are harder with Windows and there are different possibilities with different tradeoffs.

Probably the best, if you don't need portable code (you'll be using wchar_t, which should really be avoided on every other platform), is to set the mode of the output file handle to take only UTF-16 data.

#include <iostream>
#include <io.h>
#include <fcntl.h>

int main() {
    _setmode(_fileno(stdout), _O_U16TEXT);
    std::wcout << L"Hello, \u0444!\n";
}

Portable code is more difficult.

How to fix libeay32.dll was not found error

Download libeay32.dll and ssleay32.dll binary package for 32Bit and 64Bit from http://indy.fulgan.com/SSL/ then put it into executable or System32 directory.

Delete from a table based on date

This is pretty vague. Do you mean like in SQL:

DELETE FROM myTable
WHERE dateColumn < '2007'

Merging dataframes on index with pandas

You should be able to use join, which joins on the index as default. Given your desired result, you must use outer as the join type.

>>> df1.join(df2, how='outer')
            V1  V2
A 1/1/2012  12  15
  2/1/2012  14 NaN
  3/1/2012 NaN  21
B 1/1/2012  15  24
  2/1/2012   8   9
C 1/1/2012  17 NaN
  2/1/2012   9 NaN
D 1/1/2012 NaN   7
  2/1/2012 NaN  16

Signature: _.join(other, on=None, how='left', lsuffix='', rsuffix='', sort=False) Docstring: Join columns with other DataFrame either on index or on a key column. Efficiently Join multiple DataFrame objects by index at once by passing a list.

Filtering lists using LINQ

Many thanks for this guys.

I mangaged to get this down to one line:

  var results = from p in People 
                where !(from e in exclusions 
                        select e.CompositeKey).Contains(p.CompositeKey) 
                select p;

Thanks again everyone.

Access denied for user 'root'@'localhost' (using password: Yes) after password reset LINUX

Actually I took a closer look at the user table in mysql database, turns out someone prior to me edited the ssl_type field for user root to SSL.

I edited that field and restarted mysql and it worked like a charm.

Thanks.

Bootstrap: wider input field

I made a wider input field by using either span4 or span6 as class.

<input type="text" class="span6 input-large search-query">

This way you don't need the additional custom css, mentioned earlier.

What is the dual table in Oracle?

More Facts about the DUAL....

http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:1562813956388

Thrilling experiments done here, and more thrilling explanations by Tom

How can I use different certificates on specific connections?

We copy the JRE's truststore and add our custom certificates to that truststore, then tell the application to use the custom truststore with a system property. This way we leave the default JRE truststore alone.

The downside is that when you update the JRE you don't get its new truststore automatically merged with your custom one.

You could maybe handle this scenario by having an installer or startup routine that verifies the truststore/jdk and checks for a mismatch or automatically updates the truststore. I don't know what happens if you update the truststore while the application is running.

This solution isn't 100% elegant or foolproof but it's simple, works, and requires no code.

How to force a hover state with jQuery?

I think the best solution I have come across is on this stackoverflow. This short jQuery code allows all your hover effects to show on click or touch..
No need to add anything within the function.

$('body').on('touchstart', function() {});

Hope this helps.

How do I install and use curl on Windows?

As you already know, you can find several packages of binaries on the official curl website.

Once you download a package, unzip it wherever you want. I recommend adding its location to your path, so you can call curl from batch or powershell scripts. To add a directory to your path type "environment variables" in the start menu, and select "edit user environment variables". Select Path, and add to the end of the "value" box: ;C:\curl\directory (with the directory changed to where you saved curl.)

If you want to use SSL you need a certificate bundle. Run either mk-ca-bundle.pl (perl) or mk-ca-bundle.vbs (VBScript). Some of the packages of binaries include one or both of them. If your download doesn't include one, download one here: https://github.com/bagder/curl/tree/master/lib. I recommend mk-ca-bundle.vbs, as on windows you simply double click it to run it. It will produce a file called ca-bundle.crt. Rename it curl-ca-bundle.crt and save it in the directory with curl.exe.

Alternatively, I recently developed an msi installer that sets up a full featured build of curl with just a few clicks. It automatically ads curl to your path, includes a ready-to-use ssl certificate bundle, and makes the curl manual and documentation accessible from the start menu. You can download it at www.confusedbycode.com/curl/.

Count all duplicates of each value

SELECT number, COUNT(*)
    FROM YourTable
    GROUP BY number
    ORDER BY number

prevent property from being serialized in web API

Instead of letting everything get serialized by default, you can take the "opt-in" approach. In this scenario, only the properties you specify are allowed to be serialized. You do this with the DataContractAttribute and DataMemberAttribute, found in the System.Runtime.Serialization namespace.

The DataContactAttribute is applied to the class, and the DataMemberAttribute is applied to each member you want to be serialized:

[DataContract]
public class MyClass {

  [DataMember]
  public int Id { get; set;} // Serialized

  [DataMember]
  public string Name { get; set; } // Serialized

  public string DontExposeMe { get; set; } // Will not be serialized
}

Dare I say this is a better approach because it forces you to make explicit decisions about what will or will not make it through serialization. It also allows your model classes to live in a project by themselves, without taking a dependency on JSON.net just because somewhere else you happen to be serializing them with JSON.net.

MongoDB: How to find the exact version of installed MongoDB

To check mongodb version use the mongod command with --version option.

To check MongoDB Server version, Open the command line via your terminal program and execute the following command:

Path : C:\Program Files\MongoDB\Server\3.2\bin Open Cmd and execute the following command: mongod --version To Check MongoDB Shell version, Type:

mongo --version

The resource could not be loaded because the App Transport Security policy requires the use of a secure connection

I have solved it with adding some key in info.plist. The steps I followed are:

  1. Opened my Project target's info.plist file

  2. Added a Key called NSAppTransportSecurity as a Dictionary.

  3. Added a Subkey called NSAllowsArbitraryLoads as Boolean and set its value to YES as like following image.

enter image description here

Clean the Project and Now Everything is Running fine as like before.

Ref Link: https://stackoverflow.com/a/32609970

EDIT: OR In source code of info.plist file we can add that:

<key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
        <key>NSExceptionDomains</key>
        <dict>
            <key>yourdomain.com</key>
            <dict>
                <key>NSIncludesSubdomains</key>
                <true/>
                <key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
                <false/>
            </dict>
       </dict>
  </dict>

Comparing arrays in JUnit assertions, concise built-in way?

You can use Arrays.equals(..):

assertTrue(Arrays.equals(expectedResult, result));

How to convert "Mon Jun 18 00:00:00 IST 2012" to 18/06/2012?

java.time

The modern approach is with the java.time classes. These supplant the troublesome old legacy date-time classes such as Date, Calendar, and SimpleDateFormat.

Parse as a ZonedDateTime.

String input = "Mon Jun 18 00:00:00 IST 2012";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "E MMM dd HH:mm:ss z uuuu" )
                                       .withLocale( Locale.US );
ZonedDateTime zdt = ZonedDateTime.parse( input , f );

Extract a date-only object, a LocalDate, without any time-of-day and without any time zone.

LocalDate ld = zdt.toLocalDate();
DateTimeFormatter fLocalDate = DateTimeFormatter.ofPattern( "dd/MM/uuuu" );
String output = ld.format( fLocalDate) ;

Dump to console.

System.out.println( "input: " + input );
System.out.println( "zdt: " + zdt );
System.out.println( "ld: " + ld );
System.out.println( "output: " + output );

input: Mon Jun 18 00:00:00 IST 2012

zdt: 2012-06-18T00:00+03:00[Asia/Jerusalem]

ld: 2012-06-18

output: 18/06/2012

See this code run live in IdeOne.com.

Poor choice of format

Your format is a poor choice for data exchange: hard to read by human, hard to parse by computer, uses non-standard 3-4 letter zone codes, and assumes English.

Instead use the standard ISO 8601 formats whenever possible. The java.time classes use ISO 8601 formats by default when parsing/generating date-time values.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!). For example, your use of IST may be Irish Standard Time, Israel Standard Time (as interpreted by java.time, seen above), or India Standard Time.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Concatenate two PySpark dataframes

This should do it for you ...

from pyspark.sql.types import FloatType
from pyspark.sql.functions import randn, rand, lit, coalesce, col
import pyspark.sql.functions as F

df_1 = sqlContext.range(0, 6)
df_2 = sqlContext.range(3, 10)
df_1 = df_1.select("id", lit("old").alias("source"))
df_2 = df_2.select("id")

df_1.show()
df_2.show()
df_3 = df_1.alias("df_1").join(df_2.alias("df_2"), df_1.id == df_2.id, "outer")\
  .select(\
    [coalesce(df_1.id, df_2.id).alias("id")] +\
    [col("df_1." + c) for c in df_1.columns if c != "id"])\
  .sort("id")
df_3.show()

jQuery limit to 2 decimal places

You could use a variable to make the calculation and use toFixed when you set the #diskamountUnit element value:

var amount = $("#disk").slider("value") * 1.60;
$("#diskamountUnit").val('$' + amount.toFixed(2));

You can also do that in one step, in the val method call but IMO the first way is more readable:

$("#diskamountUnit").val('$' + ($("#disk").slider("value") * 1.60).toFixed(2));

How do I make calls to a REST API using C#?

The ASP.NET Web API has replaced the WCF Web API previously mentioned.

I thought I'd post an updated answer since most of these responses are from early 2012, and this thread is one of the top results when doing a Google search for "call restful service C#".

Current guidance from Microsoft is to use the Microsoft ASP.NET Web API Client Libraries to consume a RESTful service. This is available as a NuGet package, Microsoft.AspNet.WebApi.Client. You will need to add this NuGet package to your solution.

Here's how your example would look when implemented using the ASP.NET Web API Client Library:

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;

namespace ConsoleProgram
{
    public class DataObject
    {
        public string Name { get; set; }
    }

    public class Class1
    {
        private const string URL = "https://sub.domain.com/objects.json";
        private string urlParameters = "?api_key=123";

        static void Main(string[] args)
        {
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri(URL);

            // Add an Accept header for JSON format.
            client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));

            // List data response.
            HttpResponseMessage response = client.GetAsync(urlParameters).Result;  // Blocking call! Program will wait here until a response is received or a timeout occurs.
            if (response.IsSuccessStatusCode)
            {
                // Parse the response body.
                var dataObjects = response.Content.ReadAsAsync<IEnumerable<DataObject>>().Result;  //Make sure to add a reference to System.Net.Http.Formatting.dll
                foreach (var d in dataObjects)
                {
                    Console.WriteLine("{0}", d.Name);
                }
            }
            else
            {
                Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            }

            // Make any other calls using HttpClient here.

            // Dispose once all HttpClient calls are complete. This is not necessary if the containing object will be disposed of; for example in this case the HttpClient instance will be disposed automatically when the application terminates so the following call is superfluous.
            client.Dispose();
        }
    }
}

If you plan on making multiple requests, you should re-use your HttpClient instance. See this question and its answers for more details on why a using statement was not used on the HttpClient instance in this case: Do HttpClient and HttpClientHandler have to be disposed between requests?

For more details, including other examples, see Call a Web API From a .NET Client (C#)

This blog post may also be useful: Using HttpClient to Consume ASP.NET Web API REST Services

bootstrap.min.js:6 Uncaught Error: Bootstrap dropdown require Popper.js

include popper.js before bootstrap.min.js

<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.0.4/popper.js"></script>

use this link to get popper

SQL keys, MUL vs PRI vs UNI

It means that the field is (part of) a non-unique index. You can issue

show create table <table>;

To see more information about the table structure.

Elevating process privilege programmatically?

You should use Impersonation to elevate the state.

WindowsIdentity identity = new WindowsIdentity(accessToken);
WindowsImpersonationContext context = identity.Impersonate();

Don't forget to undo the impersonated context when you are done.

iOS - Ensure execution on main thread

This will do it:

[[NSOperationQueue mainQueue] addOperationWithBlock:^ {

   //Your code goes in here
   NSLog(@"Main Thread Code");

}];

Hope this helps!

Convert time fields to strings in Excel

This kind of this is always a pain in Excel, you have to convert the values using a function because once Excel converts the cells to Time they are stored internally as numbers. Here is the best way I know how to do it:

I'll assume that your times are in column A starting at row 1. In cell B1 enter this formula: =TEXT(A1,"hh:mm:ss AM/PM") , drag the formula down column B to the end of your data in column A. Select the values from column B, copy, go to column C and select "Paste Special", then select "Values". Select the cells you just copied into column C and format the cells as "Text".

How to convert/parse from String to char in java?

If your string contains exactly one character the simplest way to convert it to a character is probably to call the charAt method:

char c = s.charAt(0);

Android intent for playing video?

From now onwards after API 24, Uri.parse(filePath) won't work. You need to use this

final File videoFile = new File("path to your video file");
Uri fileUri = FileProvider.getUriForFile(mContext, "{yourpackagename}.fileprovider", videoFile);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(fileUri, "video/*");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//DO NOT FORGET THIS EVER
startActivity(intent);

But before using this you need to understand how file provider works. Go to official document link to understand file provider better.

Creating a new directory in C

Look at stat for checking if the directory exists,

And mkdir, to create a directory.

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

struct stat st = {0};

if (stat("/some/directory", &st) == -1) {
    mkdir("/some/directory", 0700);
}

You can see the manual of these functions with the man 2 stat and man 2 mkdir commands.

Different font size of strings in the same TextView

Just in case you're wondering how you can set multiple different sizes in the same textview, but using an absolute size and not a relative one, you can achieve that using AbsoluteSizeSpan instead of a RelativeSizeSpan.

Just get the dimension in pixels of the desired text size

int textSize1 = getResources().getDimensionPixelSize(R.dimen.text_size_1);
int textSize2 = getResources().getDimensionPixelSize(R.dimen.text_size_2);

and then create a new AbsoluteSpan based on the text

String text1 = "Hi";
String text2 = "there";

SpannableString span1 = new SpannableString(text1);
span1.setSpan(new AbsoluteSizeSpan(textSize1), 0, text1.length(), SPAN_INCLUSIVE_INCLUSIVE);

SpannableString span2 = new SpannableString(text2);
span2.setSpan(new AbsoluteSizeSpan(textSize2), 0, text2.length(), SPAN_INCLUSIVE_INCLUSIVE);

// let's put both spans together with a separator and all
CharSequence finalText = TextUtils.concat(span1, " ", span2);

"Rate This App"-link in Google Play store app on the phone

Here is a working and up to date code :)

/*
* Start with rating the app
* Determine if the Play Store is installed on the device
*
* */
public void rateApp()
{
    try
    {
        Intent rateIntent = rateIntentForUrl("market://details");
        startActivity(rateIntent);
    }
    catch (ActivityNotFoundException e)
    {
        Intent rateIntent = rateIntentForUrl("https://play.google.com/store/apps/details");
        startActivity(rateIntent);
    }
}

private Intent rateIntentForUrl(String url)
{
    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(String.format("%s?id=%s", url, getPackageName())));
    int flags = Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_MULTIPLE_TASK;
    if (Build.VERSION.SDK_INT >= 21)
    {
        flags |= Intent.FLAG_ACTIVITY_NEW_DOCUMENT;
    }
    else
    {
        //noinspection deprecation
        flags |= Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET;
    }
    intent.addFlags(flags);
    return intent;
}

Put the code in the Activity you would like to call it from.
When the user clicks a button to rate the app, just call the rateApp() function.

Checking whether a string starts with XXXX

Can also be done this way..

regex=re.compile('^hello')

## THIS WAY YOU CAN CHECK FOR MULTIPLE STRINGS
## LIKE
## regex=re.compile('^hello|^john|^world')

if re.match(regex, somestring):
    print("Yes")

Importing class from another file

Your problem is basically that you never specified the right path to the file.

Try instead, from your main script:

from folder.file import Klasa

Or, with from folder import file:

from folder import file
k = file.Klasa()

Or again:

import folder.file as myModule
k = myModule.Klasa()

Call PowerShell script PS1 from another PS1 script inside Powershell ISE

This is just additional info to answers in order to pass argument into the another file

Where you expect argument

PrintName.ps1

Param(
    [Parameter( Mandatory = $true)]
    $printName = "Joe"    
)


Write-Host $printName

How to call the file

Param(
    [Parameter( Mandatory = $false)]
    $name = "Joe"    
)


& ((Split-Path $MyInvocation.InvocationName) + "\PrintName.ps1") -printName $name

If you do not do not provide any input it will default to "Joe" and this will be passed as argument into printName argument in PrintName.ps1 file which will in turn print out the "Joe" string

Laravel Eloquent - Get one Row

Using Laravel Eloquent you can get one row using first() method,

it returns first row of table if where() condition is not found otherwise it gives the first matched row of given criteria.

Syntax:

Model::where('fieldname',$value)->first();

Example:

$user = User::where('email',$email)->first(); 
//OR
//$user = User::whereEmail($email)->first();

How can I find the version of the Fedora I use?

[Belmiro@HP-550 ~]$ uname -a

Linux HP-550 2.6.30.10-105.2.23.fc11.x86_64 #1 SMP Thu Feb 11 07:06:34 UTC 2010
x86_64 x86_64 x86_64 GNU/Linux


[Belmiro@HP-550 ~]$ lsb_release -a

LSB Version: :core-3.1-amd64:core-3.1-noarch:core-3.2-amd64:core-3.2-noarch:deskt
op-3.1-amd64:desktop-3.1-noarch:desktop-3.2-amd64:desktop-3.2-noarch
Distributor ID: Fedora
Description: Fedora release 11 (Leonidas)
Release: 11
Codename: Leonidas
[Belmiro@HP-550 ~]$ 

How to make several plots on a single page using matplotlib?

This works also:

for i in range(19):
    plt.subplot(5,4,i+1) 

It plots 19 total graphs on one page. The format is 5 down and 4 across..

How to increase the vertical split window size in Vim

In case you need HORIZONTAL SPLIT resize as well:
The command is the same for all splits, just the parameter changes:

- + instead of < >

Examples:
Decrease horizontal size by 10 columns

:10winc -

Increase horizontal size by 30 columns

:30winc +

or within normal mode:

Horizontal splits

10 CTRL+w -

30 CTRL+w +

Vertical splits

10 CTRL+w < (decrease)

30 CTRL+w > (increase)

How do you display code snippets in MS Word preserving format and syntax highlighting?

The best presentation for code in documents is in a fixed-width font (as it should appear in an IDE), with either a faint, shaded background or a light border to distinguish the block from other text.

Razor HtmlHelper Extensions (or other namespaces for views) Not Found

I found that putting this section in my web.config for each view folder solved it.

<runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
            <dependentAssembly>
                <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
                <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="4.0.0.0" />
            </dependentAssembly>
        </assemblyBinding>
    </runtime>

HTML / CSS How to add image icon to input type="button"?

What it looks like

This works well for me, and I'm handling hover and click CSS as well (by changing background color):

HTML (here showing 2 images, image1 on top of image2):

<button class="iconButton" style="background-image: url('image1.png'), url('image2.png')"
  onclick="alert('clicked');"></button>

CSS (my images are 32px X 32px, so I gave them 4px for padding and a 5px border rounding):

.iconButton {
    width: 36px;
    height: 36px;
    background-color: #000000;
    background-position: center;
    background-repeat: no-repeat;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    outline: none;
}

.iconButton:hover {
    background-color: #303030;
}

.iconButton:active {
    background-color: #606060;
}

button::-moz-focus-inner {
    border: 0;
}

How to print Boolean flag in NSLog?

While this is not a direct answer to Devang's question I believe that the below macro can be very helpful to people looking to log BOOLs. This will log out the value of the bool as well as automatically labeling it with the name of the variable.

#define LogBool(BOOLVARIABLE) NSLog(@"%s: %@",#BOOLVARIABLE, BOOLVARIABLE ? @"YES" : @"NO" )

BOOL success = NO;
LogBool(success); // Prints out 'success: NO' to the console

success = YES;
LogBool(success); // Prints out 'success: YES' to the console

How to improve a case statement that uses two columns

Just change your syntax ever so slightly:

CASE WHEN STATE = 2 AND RetailerProcessType = 1 THEN '"AUTHORISED"'
     WHEN STATE = 1 AND RetailerProcessType = 2 THEN '"PENDING"'
     WHEN STATE = 2 AND RetailerProcessType = 2 THEN '"AUTHORISED"'
     ELSE '"DECLINED"'
END

If you don't put the field expression before the CASE statement, you can put pretty much any fields and comparisons in there that you want. It's a more flexible method but has slightly more verbose syntax.

Determine installed PowerShell version

The below cmdlet will return the PowerShell version.

$PSVersionTable.PSVersion.Major

How to get a table cell value using jQuery?

This works

$(document).ready(function() {
    for (var row = 0; row < 3; row++) {
        for (var col = 0; col < 3; col++) {
            $("#tbl").children().children()[row].children[col].innerHTML = "H!";
        }
    }
});

Storing data into list with class

  public IEnumerable<CustInfo> SaveCustdata(CustInfo cust)
        {
            try
            {
                var customerinfo = new CustInfo
                {
                    Name = cust.Name,
                    AccountNo = cust.AccountNo,
                    Address = cust.Address
                };
                List<CustInfo> custlist = new List<CustInfo>();
                custlist.Add(customerinfo);
                return custlist;
            }
            catch (Exception)
            {
                return null;
            }
        }

How do I access ViewBag from JS

<script type="text/javascript">
      $(document).ready(function() {
                showWarning('@ViewBag.Message');
      });

</script>

You can use ViewBag.PropertyName in javascript like this.

Running an outside program (executable) in Python?

Use subprocess, it is a smaller module so it runs the .exe quicker.

import subprocess
subprocess.Popen([r"U:\Year 8\kerbal space program\KSP.exe"])

PHP - define constant inside a class

See Class Constants:

class MyClass
{
    const MYCONSTANT = 'constant value';

    function showConstant() {
        echo  self::MYCONSTANT. "\n";
    }
}

echo MyClass::MYCONSTANT. "\n";

$classname = "MyClass";
echo $classname::MYCONSTANT. "\n"; // As of PHP 5.3.0

$class = new MyClass();
$class->showConstant();

echo $class::MYCONSTANT."\n"; // As of PHP 5.3.0

In this case echoing MYCONSTANT by itself would raise a notice about an undefined constant and output the constant name converted to a string: "MYCONSTANT".


EDIT - Perhaps what you're looking for is this static properties / variables:

class MyClass
{
    private static $staticVariable = null;

    public static function showStaticVariable($value = null)
    {
        if ((is_null(self::$staticVariable) === true) && (isset($value) === true))
        {
            self::$staticVariable = $value;
        }

        return self::$staticVariable;
    }
}

MyClass::showStaticVariable(); // null
MyClass::showStaticVariable('constant value'); // "constant value"
MyClass::showStaticVariable('other constant value?'); // "constant value"
MyClass::showStaticVariable(); // "constant value"

Difference between Destroy and Delete

Basically "delete" sends a query directly to the database to delete the record. In that case Rails doesn't know what attributes are in the record it is deleting nor if there are any callbacks (such as before_destroy).

The "destroy" method takes the passed id, fetches the model from the database using the "find" method, then calls destroy on that. This means the callbacks are triggered.

You would want to use "delete" if you don't want the callbacks to be triggered or you want better performance. Otherwise (and most of the time) you will want to use "destroy".

Appending HTML string to the DOM

Shortest - 18 chars (not confuse += (mention by OP) with = more details here)

test.innerHTML=str

_x000D_
_x000D_
var str = '<p>Just some <span>text</span> here</p>';_x000D_
_x000D_
test.innerHTML=str
_x000D_
<div id="test"></div>
_x000D_
_x000D_
_x000D_

How do I get JSON data from RESTful service using Python?

If you desire to use Python 3, you can use the following:

import json
import urllib.request
req = urllib.request.Request('url')
with urllib.request.urlopen(req) as response:
    result = json.loads(response.readall().decode('utf-8'))

How do I change the title of the "back" button on a Navigation Bar

PROBLEM: "Back" text in the navigation bar can not be replaced.

REASON: "Back" label is set in the navigation bar after pushing a view because the .title attribute in the parent view controller was set to nil (or not initialised).

ONE SOLUTION: If you set the self.title="Whatever..." you will see that instead of "Back" will appear "Whatever..." after pushing new view controller.

Setting session variable using javascript

A session is stored server side, you can't modify it with JavaScript. Sessions may contain sensitive data.

You can modify cookies using document.cookie.

You can easily find many examples how to modify cookies.

Why java.security.NoSuchProviderException No such provider: BC?

You can add security provider by editing java.security with using following code with creating static block:

static {
    Security.addProvider(new BouncyCastleProvider());
}

If you are using maven project, then you will have to add dependency for BouncyCastleProvider as follows in pom.xml file of your project.

<dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcprov-jdk15on</artifactId>
            <version>1.47</version>
</dependency>

If you are using normal java project, then you can add download bcprov-jdk15on-147.jar from the link given below and edit your classpath.

http://www.java2s.com/Code/Jar/b/Downloadbcprovextjdk15on147jar.htm

Pass a password to ssh in pure bash

Since there were no exact answers to my question, I made some investigation why my code doesn't work when there are other solutions that works, and decided to post what I found to complete the subject.
As it turns out:

"ssh uses direct TTY access to make sure that the password is indeed issued by an interactive keyboard user." sshpass manpage

which answers the question, why the pipes don't work in this case. The obvious solution was to create conditions so that ssh "thought" that it is run in the regular terminal and since it may be accomplished by simple posix functions, it is beyond what simple bash offers.

How can I compare strings in C using a `switch` statement?

If it is a 2 byte string you can do something like in this concrete example where I switch on ISO639-2 language codes.

    LANIDX_TYPE LanCodeToIdx(const char* Lan)
    {
      if(Lan)
        switch(Lan[0]) {
          case 'A':   switch(Lan[1]) {
                        case 'N': return LANIDX_AN;
                        case 'R': return LANIDX_AR;
                      }
                      break;
          case 'B':   switch(Lan[1]) {
                        case 'E': return LANIDX_BE;
                        case 'G': return LANIDX_BG;
                        case 'N': return LANIDX_BN;
                        case 'R': return LANIDX_BR;
                        case 'S': return LANIDX_BS;
                      }
                      break;
          case 'C':   switch(Lan[1]) {
                        case 'A': return LANIDX_CA;
                        case 'C': return LANIDX_CO;
                        case 'S': return LANIDX_CS;
                        case 'Y': return LANIDX_CY;
                      }
                      break;
          case 'D':   switch(Lan[1]) {
                        case 'A': return LANIDX_DA;
                        case 'E': return LANIDX_DE;
                      }
                      break;
          case 'E':   switch(Lan[1]) {
                        case 'L': return LANIDX_EL;
                        case 'N': return LANIDX_EN;
                        case 'O': return LANIDX_EO;
                        case 'S': return LANIDX_ES;
                        case 'T': return LANIDX_ET;
                        case 'U': return LANIDX_EU;
                      }
                      break;
          case 'F':   switch(Lan[1]) {
                        case 'A': return LANIDX_FA;
                        case 'I': return LANIDX_FI;
                        case 'O': return LANIDX_FO;
                        case 'R': return LANIDX_FR;
                        case 'Y': return LANIDX_FY;
                      }
                      break;
          case 'G':   switch(Lan[1]) {
                        case 'A': return LANIDX_GA;
                        case 'D': return LANIDX_GD;
                        case 'L': return LANIDX_GL;
                        case 'V': return LANIDX_GV;
                      }
                      break;
          case 'H':   switch(Lan[1]) {
                        case 'E': return LANIDX_HE;
                        case 'I': return LANIDX_HI;
                        case 'R': return LANIDX_HR;
                        case 'U': return LANIDX_HU;
                      }
                      break;
          case 'I':   switch(Lan[1]) {
                        case 'S': return LANIDX_IS;
                        case 'T': return LANIDX_IT;
                      }
                      break;
          case 'J':   switch(Lan[1]) {
                        case 'A': return LANIDX_JA;
                      }
                      break;
          case 'K':   switch(Lan[1]) {
                        case 'O': return LANIDX_KO;
                      }
                      break;
          case 'L':   switch(Lan[1]) {
                        case 'A': return LANIDX_LA;
                        case 'B': return LANIDX_LB;
                        case 'I': return LANIDX_LI;
                        case 'T': return LANIDX_LT;
                        case 'V': return LANIDX_LV;
                      }
                      break;
          case 'M':   switch(Lan[1]) {
                        case 'K': return LANIDX_MK;
                        case 'T': return LANIDX_MT;
                      }
                      break;
          case 'N':   switch(Lan[1]) {
                        case 'L': return LANIDX_NL;
                        case 'O': return LANIDX_NO;
                      }
                      break;
          case 'O':   switch(Lan[1]) {
                        case 'C': return LANIDX_OC;
                      }
                      break;
          case 'P':   switch(Lan[1]) {
                        case 'L': return LANIDX_PL;
                        case 'T': return LANIDX_PT;
                      }
                      break;
          case 'R':   switch(Lan[1]) {
                        case 'M': return LANIDX_RM;
                        case 'O': return LANIDX_RO;
                        case 'U': return LANIDX_RU;
                      }
                      break;
          case 'S':   switch(Lan[1]) {
                        case 'C': return LANIDX_SC;
                        case 'K': return LANIDX_SK;
                        case 'L': return LANIDX_SL;
                        case 'Q': return LANIDX_SQ;
                        case 'R': return LANIDX_SR;
                        case 'V': return LANIDX_SV;
                        case 'W': return LANIDX_SW;
                      }
                      break;
          case 'T':   switch(Lan[1]) {
                        case 'R': return LANIDX_TR;
                      }
                      break;
          case 'U':   switch(Lan[1]) {
                        case 'K': return LANIDX_UK;
                        case 'N': return LANIDX_UN;
                      }
                      break;
          case 'W':   switch(Lan[1]) {
                        case 'A': return LANIDX_WA;
                      }
                      break;
          case 'Z':   switch(Lan[1]) {
                        case 'H': return LANIDX_ZH;
                      }
                      break;
        }
      return LANIDX_UNDEFINED;
    }

LANIDX_* being constant integers used to index in arrays.

How can I open a popup window with a fixed size using the HREF tag?

Since many browsers block popups by default and popups are really ugly, I recommend using lightbox or thickbox.

They are prettier and are not popups. They are extra HTML markups that are appended to your document's body with the appropriate CSS content.

http://jquery.com/demo/thickbox/

Python BeautifulSoup extract text between element

The BeautifulSoup documentation provides an example about removing objects from a document using the extract method. In the following example the aim is to remove all comments from the document:

Removing Elements

Once you have a reference to an element, you can rip it out of the tree with the extract method. This code removes all the comments from a document:

from BeautifulSoup import BeautifulSoup, Comment
soup = BeautifulSoup("""1<!--The loneliest number-->
                    <a>2<!--Can be as bad as one--><b>3""")
comments = soup.findAll(text=lambda text:isinstance(text, Comment))
[comment.extract() for comment in comments]
print soup
# 1
# <a>2<b>3</b></a>

Java enum with multiple value types

First, the enum methods shouldn't be in all caps. They are methods just like other methods, with the same naming convention.

Second, what you are doing is not the best possible way to set up your enum. Instead of using an array of values for the values, you should use separate variables for each value. You can then implement the constructor like you would any other class.

Here's how you should do it with all the suggestions above:

public enum States {
    ...
    MASSACHUSETTS("Massachusetts",  "MA",   true),
    MICHIGAN     ("Michigan",       "MI",   false),
    ...; // all 50 of those

    private final String full;
    private final String abbr;
    private final boolean originalColony;

    private States(String full, String abbr, boolean originalColony) {
        this.full = full;
        this.abbr = abbr;
        this.originalColony = originalColony;
    }

    public String getFullName() {
        return full;
    }

    public String getAbbreviatedName() {
        return abbr;
    }

    public boolean isOriginalColony(){
        return originalColony;
    }
}

How do I draw a grid onto a plot in Python?

You want to use pyplot.grid:

x = numpy.arange(0, 1, 0.05)
y = numpy.power(x, 2)

fig = plt.figure()
ax = fig.gca()
ax.set_xticks(numpy.arange(0, 1, 0.1))
ax.set_yticks(numpy.arange(0, 1., 0.1))
plt.scatter(x, y)
plt.grid()
plt.show()

ax.xaxis.grid and ax.yaxis.grid can control grid lines properties.

Enter image description here

How do you develop Java Servlets using Eclipse?

You need to install a plugin, There is a free one from the eclipse foundation called the Web Tools Platform. It has all the development functionality that you'll need.

You can get the Java EE Edition of eclipse with has it pre-installed.

To create and run your first servlet:

  1. New... Project... Dynamic Web Project.
  2. Right click the project... New Servlet.
  3. Write some code in the doGet() method.
  4. Find the servers view in the Java EE perspective, it's usually one of the tabs at the bottom.
  5. Right click in there and select new Server.
  6. Select Tomcat X.X and a wizard will point you to finding the installation.
  7. Right click the server you just created and select Add and Remove... and add your created web project.
  8. Right click your servlet and select Run > Run on Server...

That should do it for you. You can use ant to build here if that's what you'd like but eclipse will actually do the build and automatically deploy the changes to the server. With Tomcat you might have to restart it every now and again depending on the change.

creating triggers for After Insert, After Update and After Delete in SQL

(Update: overlooked a fault in the matter, I have corrected)

(Update2: I wrote from memory the code screwed up, repaired it)

(Update3: check on SQLFiddle)

create table Derived_Values
  (
    BusinessUnit nvarchar(100) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values ADD CONSTRAINT PK_Derived_Values
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

create table Derived_Values_Test
  (
    BusinessUnit nvarchar(150)
    ,Questions nvarchar(100)
    ,Answer nvarchar(100)
    )

go

CREATE TRIGGER trgAfterUpdate ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Updated Record -- After Update Trigger.'

    insert into 
        [Derived_Values_Test]
        --(BusinessUnit,Questions, Answer) 
    SELECT 
        @BusinessUnit + i.BusinessUnit, i.Questions, i.Answer
    FROM 
        inserted i
        inner join deleted d on i.BusinessUnit = d.BusinessUnit
end

go

CREATE TRIGGER trgAfterDelete ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Deleted Record -- After Delete Trigger.'

    insert into 
        [Derived_Values_Test]
        --(BusinessUnit,Questions, Answer) 
    SELECT 
        @BusinessUnit + d.BusinessUnit, d.Questions, d.Answer
    FROM 
        deleted d
end

go

insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q11', 'A11')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q12', 'A12')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q21', 'A21')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q22', 'A22')

UPDATE Derived_Values SET Answer='Updated Answers A11' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q11');
UPDATE Derived_Values SET Answer='Updated Answers A12' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q12');
UPDATE Derived_Values SET Answer='Updated Answers A21' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q21');
UPDATE Derived_Values SET Answer='Updated Answers A22' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q22');

delete Derived_Values;

and then:

SELECT * FROM Derived_Values;
go

select * from Derived_Values_Test;


Record Count: 0;

BUSINESSUNIT    QUESTIONS   ANSWER
Updated Record -- After Update Trigger.BU1  Q11 Updated Answers A11
Deleted Record -- After Delete Trigger.BU1  Q11 A11
Updated Record -- After Update Trigger.BU1  Q12 Updated Answers A12
Deleted Record -- After Delete Trigger.BU1  Q12 A12
Updated Record -- After Update Trigger.BU2  Q21 Updated Answers A21
Deleted Record -- After Delete Trigger.BU2  Q21 A21
Updated Record -- After Update Trigger.BU2  Q22 Updated Answers A22
Deleted Record -- After Delete Trigger.BU2  Q22 A22

(Update4: If you want to sync: SQLFiddle)

create table Derived_Values
  (
    BusinessUnit nvarchar(100) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values ADD CONSTRAINT PK_Derived_Values
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

create table Derived_Values_Test
  (
    BusinessUnit nvarchar(150) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values_Test ADD CONSTRAINT PK_Derived_Values_Test
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

CREATE TRIGGER trgAfterInsert ON  [Derived_Values]
FOR INSERT
AS  
begin
    insert
        [Derived_Values_Test]
        (BusinessUnit,Questions,Answer)
    SELECT 
        i.BusinessUnit, i.Questions, i.Answer
    FROM 
        inserted i
end

go


CREATE TRIGGER trgAfterUpdate ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Updated Record -- After Update Trigger.'

    update
        [Derived_Values_Test]
    set
        --BusinessUnit = i.BusinessUnit
        --,Questions = i.Questions
        Answer = i.Answer
    from
        [Derived_Values]
        inner join inserted i 
    on
        [Derived_Values].BusinessUnit = i.BusinessUnit
        and
        [Derived_Values].Questions = i.Questions
end

go

CREATE TRIGGER trgAfterDelete ON  [Derived_Values]
FOR DELETE
AS  
begin
    delete 
        [Derived_Values_Test]
    from
        [Derived_Values_Test]
        inner join deleted d 
    on
        [Derived_Values_Test].BusinessUnit = d.BusinessUnit
        and
        [Derived_Values_Test].Questions = d.Questions
end

go

insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q11', 'A11')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q12', 'A12')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q21', 'A21')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q22', 'A22')

UPDATE Derived_Values SET Answer='Updated Answers A11' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q11');
UPDATE Derived_Values SET Answer='Updated Answers A12' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q12');
UPDATE Derived_Values SET Answer='Updated Answers A21' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q21');
UPDATE Derived_Values SET Answer='Updated Answers A22' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q22');

--delete Derived_Values;

And then:

SELECT * FROM Derived_Values;
go

select * from Derived_Values_Test;


BUSINESSUNIT    QUESTIONS   ANSWER
BU1 Q11 Updated Answers A11
BU1 Q12 Updated Answers A12
BU2 Q21 Updated Answers A21
BU2 Q22 Updated Answers A22

BUSINESSUNIT    QUESTIONS   ANSWER
BU1 Q11 Updated Answers A11
BU1 Q12 Updated Answers A12
BU2 Q21 Updated Answers A21
BU2 Q22 Updated Answers A22

How are environment variables used in Jenkins with Windows Batch Command?

I should this On Windows, environment variable expansion is %BUILD_NUMBER%

Escaping Strings in JavaScript

A variation of the function provided by Paolo Bergantino that works directly on String:

String.prototype.addSlashes = function() 
{ 
   //no need to do (str+'') anymore because 'this' can only be a string
   return this.replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
} 

By adding the code above in your library you will be able to do:

var test = "hello single ' double \" and slash \\ yippie";
alert(test.addSlashes());

EDIT:

Following suggestions in the comments, whoever is concerned about conflicts amongst JavaScript libraries can add the following code:

if(!String.prototype.addSlashes)
{
   String.prototype.addSlashes = function()... 
}
else
   alert("Warning: String.addSlashes has already been declared elsewhere.");

window.onload vs document.onload

Window.onload is the standard, however - the web browser in the PS3 (based on Netfront) doesn't support the window object, so you can't use it there.

How to set up Android emulator proxy settings

In console start the next command:

emulator -avd emulator_name -http-proxy you_proxy_ip_address:8080

How to select distinct query using symfony2 doctrine query builder?

Just open your repository file and add this new function, then call it inside your controller:

 public function distinctCategories(){
        return $this->createQueryBuilder('cc')
        ->where('cc.contenttype = :type')
        ->setParameter('type', 'blogarticle')
        ->groupBy('cc.blogarticle')
        ->getQuery()
        ->getResult()
        ;
    }

Then within your controller:

public function index(YourRepository $repo)
{
    $distinctCategories = $repo->distinctCategories();


    return $this->render('your_twig_file.html.twig', [
        'distinctCategories' => $distinctCategories
    ]);
}

Good luck!

Flash CS4 refuses to let go

Flash still has the ASO file, which is the compiled byte code for your classes. On Windows, you can see the ASO files here:

C:\Documents and Settings\username\Local Settings\Application Data\Adobe\Flash CS4\en\Configuration\Classes\aso

On a Mac, the directory structure is similar in /Users/username/Library/Application Support/


You can remove those files by hand, or in Flash you can select Control->Delete ASO files to remove them.

How to write a basic swap function in Java

Java is pass by value. So the swap in the sense you mean is not possible. But you can swap contents of two objects or you do it inline.

LINQ Group By and select collection

you can achive it with group join

var result = (from c in Customers
          join oi in OrderItems on c.Id equals oi.Order.Customer.Id into g
          Select new { customer = c, orderItems = g});

c is Customer and g is the customers order items.

PHPExcel set border and format for all sheets in spreadsheet

You can set a default style for the entire workbook (all worksheets):

$objPHPExcel->getDefaultStyle()
    ->getBorders()
    ->getTop()
        ->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
$objPHPExcel->getDefaultStyle()
    ->getBorders()
    ->getBottom()
        ->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
$objPHPExcel->getDefaultStyle()
    ->getBorders()
    ->getLeft()
        ->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
$objPHPExcel->getDefaultStyle()
    ->getBorders()
    ->getRight()
        ->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);

or

  $styleArray = array(
      'borders' => array(
          'allborders' => array(
              'style' => PHPExcel_Style_Border::BORDER_THIN
          )
      )
  );
$objPHPExcel->getDefaultStyle()->applyFromArray($styleArray);

And this can be used for all style properties, not just borders.

But column autosizing is structural rather than stylistic, and has to be set for each column on each worksheet individually.

EDIT

Note that default workbook style only applies to Excel5 Writer

Specify a Root Path of your HTML directory for script links?

Just start it with a slash? This means root. As long as you're testing on a web server (e.g. localhost) and not a file system (e.g. C:) then that should be all you need to do.

PHP $_FILES['file']['tmp_name']: How to preserve filename and extension?

$_FILES['file']['tmp_name']; will contain the temporary file name of the file on the server. This is just a placeholder on your server until you process the file

$_FILES['file']['name']; contains the original name of the uploaded file from the user's computer.

How to modify a specified commit?

Came to this approach (and it is probably exactly the same as using interactive rebase) but for me it's kind of straightforward.

Note: I present this approach for the sake of illustration of what you can do rather than an everyday alternative. Since it has many steps (and possibly some caveats.)

Say you want to change commit 0 and you are currently on feature-branch

some-commit---0---1---2---(feature-branch)HEAD

Checkout to this commit and create a quick-branch. You can also clone your feature branch as a recovery point (before starting).

?(git checkout -b feature-branch-backup)
git checkout 0
git checkout -b quick-branch

You will now have something like this:

0(quick-branch)HEAD---1---2---(feature-branch)

Stage changes, stash everything else.

git add ./example.txt
git stash

Commit changes and checkout back to feature-branch

git commit --amend
git checkout feature-branch

You will now have something like this:

some-commit---0---1---2---(feature-branch)HEAD
           \
             ---0'(quick-branch)

Rebase feature-branch onto quick-branch (resolve any conflicts along the way). Apply stash and remove quick-branch.

git rebase quick-branch
git stash pop
git branch -D quick-branch

And you end up with:

some-commit---0'---1'---2'---HEAD(feature-branch)

Git will not duplicate (although I can't really say to what extent) the 0 commit when rebasing.

Note: all commit hashes are changed starting from the commit we originally intended to change.

MySQL Select Multiple VALUES

Try this -

 select * from table where id in (3,4) or [name] in ('andy','paul');

how to write an array to a file Java

If you're okay with Apache commons lib

outputWriter.write(ArrayUtils.join(array, ","));

Common elements comparison between 2 lists

The solutions suggested by S.Mark and SilentGhost generally tell you how it should be done in a Pythonic way, but I thought you might also benefit from knowing why your solution doesn't work. The problem is that as soon as you find the first common element in the two lists, you return that single element only. Your solution could be fixed by creating a result list and collecting the common elements in that list:

def common_elements(list1, list2):
    result = []
    for element in list1:
        if element in list2:
            result.append(element)
    return result

An even shorter version using list comprehensions:

def common_elements(list1, list2):
    return [element for element in list1 if element in list2]

However, as I said, this is a very inefficient way of doing this -- Python's built-in set types are way more efficient as they are implemented in C internally.

How do I simulate a hover with a touch in touch enabled browsers?

OK, I've worked it out! It involves changing the CSS slightly and adding some JS.

Using jQuery to make it easy:

$(document).ready(function() {
    $('.hover').on('touchstart touchend', function(e) {
        e.preventDefault();
        $(this).toggleClass('hover_effect');
    });
});

In english: when you start or end a touch, turn the class hover_effect on or off.

Then, in your HTML, add a class hover to anything you want this to work with. In your CSS, replace any instance of:

element:hover {
    rule:properties;
}

with

element:hover, element.hover_effect {
    rule:properties;
}

And just for added usefulness, add this to your CSS as well:

.hover {
-webkit-user-select: none;
-webkit-touch-callout: none;        
}

To stop the browser asking you to copy/save/select the image or whatever.

Easy!

Maintain image aspect ratio when changing height

Actually I found out that the container of the image tag need to have a height in order to keep the ratio of the image. for example>

.container{display:flex; height:100%;} img{width:100%;height:auto;}

then in your html your container will wrap the tag image

<div class="container"><img src="image.jpg" alt="image" /></div>

this work for IE and other browsers

Real time data graphing on a line chart with html5

Flotr2 and Envision are options. Flotr2 has a real time example on the doco page I linked. Envision is a bit tougher to get started with, so try Flotr2.

Remove specific characters from a string in Python

you can use set

    charlist = list(set(string.digits+string.ascii_uppercase) - set('10IO'))
    return ''.join([random.SystemRandom().choice(charlist) for _ in range(passlen)])

Duplicate line in Visual Studio Code

Another 2 very usefull shortcuts are to move lines selected up and down, like sublime text does...

{
  "key" : "ctrl+shift+down", "command" : "editor.action.moveLinesDownAction",
  "when" : "editorTextFocus && !editorReadonly"
},

and

{
  "key" : "ctrl+shift+up", "command" : "editor.action.moveLinesUpAction",
  "when" : "editorTextFocus && !editorReadonly"
}

How to test an Oracle Stored Procedure with RefCursor return type?

Something like this lets you test your procedure on almost any client:

DECLARE 
  v_cur SYS_REFCURSOR;
  v_a   VARCHAR2(10);
  v_b   VARCHAR2(10);
BEGIN
  your_proc(v_cur);

  LOOP
    FETCH v_cur INTO v_a, v_b;
    EXIT WHEN v_cur%NOTFOUND;
    dbms_output.put_line(v_a || ' ' || v_b);
  END LOOP;
  CLOSE v_cur;
END;

Basically, your test harness needs to support the definition of a SYS_REFCURSOR variable and the ability to call your procedure while passing in the variable you defined, then loop through the cursor result set. PL/SQL does all that, and anonymous blocks are easy to set up and maintain, fairly adaptable, and quite readable to anyone who works with PL/SQL.

Another, albeit similar way would be to build a named procedure that does the same thing, and assuming the client has a debugger (like SQL Developer, PL/SQL Developer, TOAD, etc.) you could then step through the execution.

Remove trailing newline from the elements of a string list

>>> my_list = ['this\n', 'is\n', 'a\n', 'list\n', 'of\n', 'words\n']
>>> map(str.strip, my_list)
['this', 'is', 'a', 'list', 'of', 'words']

type object 'datetime.datetime' has no attribute 'datetime'

I found this to be a lot easier

from dateutil import relativedelta
relativedelta.relativedelta(end_time,start_time).seconds

Force DOM redraw/refresh on Chrome/Mac

We recently encountered this and discovered that promoting the affected element to a composite layer with translateZ fixed the issue without needing extra javascript.

.willnotrender { 
   transform: translateZ(0); 
}

As these painting issues show up mostly in Webkit/Blink, and this fix mostly targets Webkit/Blink, it's preferable in some cases. Especially since many JavaScript solutions cause a reflow and repaint, not just a repaint.

PhpMyAdmin not working on localhost

Same Object Not Found problem here - both in Xampp as well as in Wamp. It turns out the root name of "phpmyadmin" was "PhpMyAdmin". I got rid of all the capitals, renaming the folder to "phpmyadmin", and after a couple of reloads phpmyadmin was working.

Resource interpreted as Document but transferred with MIME type application/zip

Just ran into this and none of the other information I could find helped: it was a stupid error: I was sending output to the browser before starting the file download. Surprisingly, I found no helpful errors found (like "headers already sent" etc.). Hopefully, this saves someone else some grief!

Change "on" color of a Switch

In xml , you can change the color as :

 <androidx.appcompat.widget.SwitchCompat
    android:id="@+id/notificationSwitch"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:checked="true"
    app:thumbTint="@color/darkBlue"
    app:trackTint="@color/colorGrey"/>

Dynamically you can change as :

Switch.thumbDrawable.setColorFilter(ContextCompat.getColor(requireActivity(), R.color.darkBlue), PorterDuff.Mode.MULTIPLY)

javascript, for loop defines a dynamic variable name

I think you could do it by creating parameters in an object maybe?

var myObject = {}; for(var i=0;i<myArray.length;i++) {     myObject[ myArray[i] ]; } 

If you don't set them to anything, you'll just have an object with some parameters that are undefined. I'd have to write this myself to be sure though.

What's the equivalent of Java's Thread.sleep() in JavaScript?

You can either write a spin loop (a loop that just loops for a long period of time performing some sort of computation to delay the function) or use:

setTimeout("Func1()", 3000);

This will call 'Func1()' after 3 seconds.

Edit:

Credit goes to the commenters, but you can pass anonymous functions to setTimeout.

setTimeout(function() {
   //Do some stuff here
}, 3000);

This is much more efficient and does not invoke javascript's eval function.

How do I drop table variables in SQL-Server? Should I even do this?

Here is a solution

Declare @tablename varchar(20)
DECLARE @SQL NVARCHAR(MAX)

SET @tablename = '_RJ_TEMPOV4'
SET @SQL = 'DROP TABLE dbo.' + QUOTENAME(@tablename) + '';

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(@tablename) AND type in (N'U'))
    EXEC sp_executesql @SQL;

Works fine on SQL Server 2014 Christophe

How to get parameter value for date/time column from empty MaskedTextBox

You're storing the .Text properties of the textboxes directly into the database, this doesn't work. The .Text properties are Strings (i.e. simple text) and not typed as DateTime instances. Do the conversion first, then it will work.

Do this for each date parameter:

Dim bookIssueDate As DateTime = DateTime.ParseExact( txtBookDateIssue.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture ) cmd.Parameters.Add( New OleDbParameter("@Date_Issue", bookIssueDate ) ) 

Note that this code will crash/fail if a user enters an invalid date, e.g. "64/48/9999", I suggest using DateTime.TryParse or DateTime.TryParseExact, but implementing that is an exercise for the reader.

How to export query result to csv in Oracle SQL Developer?

Not exactly "exporting," but you can select the rows (or Ctrl-A to select all of them) in the grid you'd like to export, and then copy with Ctrl-C.

The default is tab-delimited. You can paste that into Excel or some other editor and manipulate the delimiters all you like.

Also, if you use Ctrl-Shift-C instead of Ctrl-C, you'll also copy the column headers.

How can I find the first occurrence of a sub-string in a python string?

def find_pos(chaine,x):

    for i in range(len(chaine)):
        if chaine[i] ==x :
            return 'yes',i 
    return 'no'

How do I display a wordpress page content?

This is more concise:

<?php echo get_post_field('post_content', $post->ID); ?>

and this even more:

<?= get_post_field('post_content', $post->ID) ?>

Concatenate rows of two dataframes in pandas

Thanks to @EdChum I was struggling with same problem especially when indexes do not match. Unfortunatly in pandas guide this case is missed (when you for example delete some rows)

import pandas as pd
t=pd.DataFrame()
t['a']=[1,2,3,4]
t=t.loc[t['a']>1] #now index starts from 1

u=pd.DataFrame()
u['b']=[1,2,3] #index starts from 0

#option 1
#keep index of t
u.index = t.index 

#option 2
#index of t starts from 0
t.reset_index(drop=True, inplace=True)

#now concat will keep number of rows 
r=pd.concat([t,u], axis=1)