Programs & Examples On #Flexbuilder

Adobe Flex Builder is the former name of Adobe Flash Builder.

How do I define the name of image built with docker-compose

For docker-compose version 2 file format, you can build and tag an image for one service and then use that same built image for another service.

For my case, I want to set up an elasticsearch cluster with 2 nodes, they both need to use the same image, but configured to run differently. I also want to build my own custom elasticsearch image from my own Dockerfile. So this is what I did (docker-compose.yml):

version: '2'

services:
  es-master:
    build: ./elasticsearch
    image: porter/elasticsearch
    ports:
      - "9200:9200"
    container_name: es_master

  es-node:
    image: porter/elasticsearch
    depends_on:
      - es-master
    ports:
      - "9200"
    command: elasticsearch --discovery.zen.ping.unicast.hosts=es_master

You can see that in the first service definition es-master, I use the build option to build an image from the Dockerfile in ./elasticsearch. I tag the image with the name porter/elasticsearch with the image option.
Then, I reference this built image in the es-node service definition with the image option, and also use a depends_on to make sure the other container es-master is built and run first.

Is there any way to do HTTP PUT in python

I also recommend httplib2 by Joe Gregario. I use this regularly instead of httplib in the standard lib.

remove inner shadow of text input

Add border: none or border: 0 to remove border at all, or border: 1px solid #ccc to make border thin and flat.

To remove ghost padding in Firefox, you can use ::-moz-focus-inner:

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

See live demo.

What is external linkage and internal linkage?

In C++

Any variable at file scope and that is not nested inside a class or function, is visible throughout all translation units in a program. This is called external linkage because at link time the name is visible to the linker everywhere, external to that translation unit.

Global variables and ordinary functions have external linkage.

Static object or function name at file scope is local to translation unit. That is called as Internal Linkage

Linkage refers only to elements that have addresses at link/load time; thus, class declarations and local variables have no linkage.

How can I get zoom functionality for images?

Something like below will do it.

@Override public boolean onTouch(View v,MotionEvent e)
{

    tap=tap2=drag=pinch=none;
    int mask=e.getActionMasked();
    posx=e.getX();posy=e.getY();

    float midx= img.getWidth()/2f;
    float midy=img.getHeight()/2f;
    int fingers=e.getPointerCount();

    switch(mask)
    {
        case MotionEvent.ACTION_POINTER_UP:
            tap2=1;break;

        case MotionEvent.ACTION_UP:
            tap=1;break;

        case MotionEvent.ACTION_MOVE:
            drag=1;
    }
    if(fingers==2){nowsp=Math.abs(e.getX(0)-e.getX(1));}
    if((fingers==2)&&(drag==0)){ tap2=1;tap=0;drag=0;}
    if((fingers==2)&&(drag==1)){ tap2=0;tap=0;drag=0;pinch=1;}

    if(pinch==1)

    {
        if(nowsp>oldsp)scale+=0.1;
        if(nowsp<oldsp)scale-=0.1;
        tap2=tap=drag=0;    
    }
    if(tap2==1)
        {
            scale-=0.1;
            tap=0;drag=0;
        }
    if(tap==1)
        {
            tap2=0;drag=0;
            scale+=0.1;
        }
    if(drag==1)
        {
            movx=posx-oldx;
            movy=posy-oldy;
            x+=movx;
            y+=movy;
            tap=0;tap2=0;
        }
    m.setTranslate(x,y);
    m.postScale(scale,scale,midx,midy);
    img.setImageMatrix(m);img.invalidate();
    tap=tap2=drag=none;
    oldx=posx;oldy=posy;
    oldsp=nowsp;
    return true;
}


public void onCreate(Bundle b)
{
        super.onCreate(b);

    img=new ImageView(this);
    img.setScaleType(ImageView.ScaleType.MATRIX);
    img.setOnTouchListener(this);

    path=Environment.getExternalStorageDirectory().getPath();   
    path=path+"/DCIM"+"/behala.jpg";
    byte[] bytes;
    bytes=null;
    try{
        FileInputStream fis;
        fis=new FileInputStream(path);
        BufferedInputStream bis;
        bis=new BufferedInputStream(fis);
        bytes=new byte[bis.available()];
        bis.read(bytes);
        if(bis!=null)bis.close();
        if(fis!=null)fis.close();

     }
    catch(Exception e)
        {
        ret="Nothing";
        }
    Bitmap bmp=BitmapFactory.decodeByteArray(bytes,0,bytes.length);

    img.setImageBitmap(bmp);

    setContentView(img);
}

For viewing complete program see here: Program to zoom image in android

convert string array to string

I used this way to make my project faster:

RichTextBox rcbCatalyst = new RichTextBox()
{
    Lines = arrayString
};
string text = rcbCatalyst.Text;
rcbCatalyst.Dispose();

return text;

RichTextBox.Text will automatically convert your array to a multiline string!

how to rename an index in a cluster?

Just in case someone still needs it. The successful, not official, way to rename indexes are:

  1. Close indexes that need to be renamed
  2. Rename indexes' folders in all data directories of master and data nodes.
  3. Reopen old closed indexes (I use kofp plugin). Old indexes will be reopened but stay unassigned. New indexes will appear in closed state
  4. Reopen new indexes
  5. Delete old indexes

If you happen to get this error "dangled index directory name is", remove index folder in all master nodes (not data nodes), and restart one of the data nodes.

How to extract extension from filename string in Javascript?

Try this. May solve your problem.

var file_name_string = "file.name.string.png"

var file_name_array = file_name_string.split(".");
var file_extension = file_name_array[file_name_array.length - 1];

Regards

Sending JSON to PHP using ajax

If you want to get the values via the $_POST variable then you should not specify the contentType as "application/json" but rather use the default "application/x-www-form-urlencoded; charset=UTF-8":

JavaScript:

var person = { name: "John" };

$.ajax({
    //contentType: "application/json", // php://input
    contentType: "application/x-www-form-urlencoded; charset=UTF-8", // $_POST
    dataType : "json",
    method: "POST",
    url: "http://localhost/test/test.php",
    data: {data: person}
})
.done(function(data) {  
    console.log("test: ", data);
    $("#result").text(data.name);
})
.fail(function(data) {
    console.log("error: ", data);
});

PHP:

<?php

// $_POST

$jsonString = $_POST['data'];

$newJsonString = json_encode($jsonString);
header('Content-Type: application/json');
echo $newJsonString;

Else if you want to send a JSON from JavaScript to PHP:

JavaScript:

var person = { name: "John" };

$.ajax({
    contentType: "application/json", // php://input
    //contentType: "application/x-www-form-urlencoded; charset=UTF-8", // $_POST
    dataType : "json",
    method: "POST",
    url: "http://localhost/test/test.php",
    data: person
})
.done(function(data) {  
    console.log("test: ", data);
    $("#result").text(data.name);
})
.fail(function(data) {
    console.log("error: ", data);
});

PHP:

<?php

$jsonString = file_get_contents("php://input");
$phpObject = json_decode($jsonString);

$newJsonString = json_encode($phpObject);
header('Content-Type: application/json');
echo $newJsonString;

How can I check if a string contains a character in C#?

bool containsCharacter = test.IndexOf("s", StringComparison.OrdinalIgnoreCase) >= 0;

Checking for empty result (php, pdo, mysql)

Even though this is an old thread, I thought I would weigh in as I had to deal with this lately.

You should not use rowCount for SELECT statements as it is not portable. I use the isset function to test if a select statement worked:

$today = date('Y-m-d', strtotime('now'));

$sth = $db->prepare("SELECT id_email FROM db WHERE hardcopy = '1' AND hardcopy_date <= :today AND hardcopy_sent = '0' ORDER BY id_email ASC");

//I would usually put this all in a try/catch block, but kept it the same for continuity
if(!$sth->execute(array(':today'=>$today))) 
{
    $db = null ;
    exit();
}

$result = $sth->fetch(PDO::FETCH_OBJ)

if(!isset($result->id_email))
{
    echo "empty";
}
else
{
    echo "not empty, value is $result->id_email";
}

$db = null;

Of course this is only for a single result, as you might have when looping over a dataset.

Default value in an asp.net mvc view model

Set this in the constructor:

public class SearchModel
{
    public bool IsMale { get; set; }
    public bool IsFemale { get; set; }

    public SearchModel()
    { 
        IsMale = true;
        IsFemale = true;
    }
}

Then pass it to the view in your GET action:

[HttpGet]
public ActionResult Search()
{
    return new View(new SearchModel());
}

I want to calculate the distance between two points in Java

This may be OLD, but here is the best answer:

    float dist = (float) Math.sqrt(
            Math.pow(x1 - x2, 2) +
            Math.pow(y1 - y2, 2) );

Parse rfc3339 date strings in Python?

You can use dateutil.parser.parse (install with python -m pip install python-dateutil) to parse strings into datetime objects.

dateutil.parser.parse will attempt to guess the format of your string, if you know the exact format in advance then you can use datetime.strptime which you supply a format string to (see Brent Washburne's answer).

from dateutil.parser import parse

a = "2012-10-09T19:00:55Z"

b = parse(a)

print(b.weekday())
# 1 (equal to a Tuesday)

git push: permission denied (public key)

If you have your private key(s) in ~/.ssh and have added them to https://github.com/settings/ssh, but still are unable to commit to a Github repo added via ssh, make sure they are added to your ssh-agent:

ssh-add -k ~/.ssh/[PRIVATE_KEY]

You can add multiple private keys for multiple servers (e.g. Bitbucket & GitHub) and it will use the correct one when dealing with git.

jQuery: Get selected element tag name

jQuery 1.6+

jQuery('selector').prop("tagName").toLowerCase()

Older versions

jQuery('selector').attr("tagName").toLowerCase()

toLowerCase() is not mandatory.

Regex to match words of a certain length

Method 1

Word boundaries would work perfectly here, such as with:

\b\w{3,8}\b
\b\w{2,}
\b\w{,10}\b
\b\w{5}\b

RegEx Demo 1

Java

Some languages such as Java and C++ are double-escape required:

\\b\\w{3,8}\\b
\\b\\w{2,}
\\b\\w{,10}\\b
\\b\\w{5}\\b

PS: \\b\\w{,10}\\b may not work for all languages or flavors.

Test 1

import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class RegularExpression{

    public static void main(String[] args){


        final String regex = "\\b\\w{3,8}\\b";
        final String string = "words with length three to eight";

        final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
        final Matcher matcher = pattern.matcher(string);

        while (matcher.find()) {
            System.out.println("Full match: " + matcher.group(0));
        }

    }
}

Output 1

Full match: words
Full match: with
Full match: length
Full match: three
Full match: eight

Method 2

Another good-to-know method is to use negative lookarounds:

(?<!\w)\w{3,8}(?!\w)
(?<!\w)\w{2,}
(?<!\w)\w{,10}(?!\w)
(?<!\w)\w{5}(?!\w)

Java

(?<!\\w)\\w{3,8}(?!\\w)
(?<!\\w)\\w{2,}
(?<!\\w)\\w{,10}(?!\\w)
(?<!\\w)\\w{5}(?!\\w)

RegEx Demo 2

Test 2

import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class RegularExpression{

    public static void main(String[] args){


        final String regex = "(?<!\\w)\\w{1,10}(?!\\w)";
        final String string = "words with length three to eight";

        final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
        final Matcher matcher = pattern.matcher(string);

        while (matcher.find()) {
            System.out.println("Full match: " + matcher.group(0));
        }

    }
}

Output 2

Full match: words
Full match: with
Full match: length
Full match: three
Full match: to
Full match: eight

RegEx Circuit

jex.im visualizes regular expressions:

enter image description here


If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


Conditional Binding: if let error – Initializer for conditional binding must have Optional type

What it is telling you is - the 2nd guard let or the if let check is not happening on an Optional Int or Optional String. You already have a non-optional value, so guarding or if-letting is not needed anymore

How to pass boolean parameter value in pipeline to downstream jobs?

Things are much easier nowadays: the builtin Snippet Generator supports the 'build' step (I don't know since when though).

Get current date, given a timezone in PHP?

The other answers set the timezone for all dates in your system. This doesn't always work well if you want to support multiple timezones for your users.

Here's the short version:

<?php
$date = new DateTime("now", new DateTimeZone('America/New_York') );
echo $date->format('Y-m-d H:i:s');

Works in PHP >= 5.2.0

List of supported timezones: php.net/manual/en/timezones.php


Here's a version with an existing time and setting timezone by a user setting

<?php

$usersTimezone = 'America/New_York';
$date = new DateTime( 'Thu, 31 Mar 2011 02:05:59 GMT', new DateTimeZone($usersTimezone) );
echo $date->format('Y-m-d H:i:s');

Here is a more verbose version to show the process a little more clearly

<?php

// Date for a specific date/time:
$date = new DateTime('Thu, 31 Mar 2011 02:05:59 GMT');

// Output date (as-is)
echo $date->format('l, F j Y g:i:s A');     

// Output line break (for testing)
echo "\n<br />\n";

// Example user timezone (to show it can be used dynamically)
$usersTimezone = 'America/New_York';

// Convert timezone
$tz = new DateTimeZone($usersTimezone);
$date->setTimeZone($tz);

// Output date after 
echo $date->format('l, F j Y g:i:s A');

Libraries

  • Carbon — A very popular date library.
  • Chronos — A drop-in replacement for Carbon focused on immutability. See below on why that's important.
  • jenssegers/date — An extension of Carbon that adds multi-language support.

I'm sure there are a number of other libraries available, but these are a few I'm familiar with.


Bonus Lesson: Immutable Date Objects

While you're here, let me save you some future headache. Let's say you want to calculate 1 week from today and 2 weeks from today. You might write some code like:

<?php

// Create a datetime (now, in this case 2017-Feb-11)
$today = new DateTime();

echo $today->format('Y-m-d') . "\n<br>";
echo "---\n<br>";

$oneWeekFromToday = $today->add(DateInterval::createFromDateString('7 days'));
$twoWeeksFromToday = $today->add(DateInterval::createFromDateString('14 days'));

echo $today->format('Y-m-d') . "\n<br>";
echo $oneWeekFromToday->format('Y-m-d') . "\n<br>";
echo $twoWeeksFromToday->format('Y-m-d') . "\n<br>";
echo "\n<br>";

The output:

2017-02-11 
--- 
2017-03-04 
2017-03-04 
2017-03-04

Hmmmm... That's not quite what we wanted. Modifying a traditional DateTime object in PHP not only returns the updated date but modifies the original object as well.

This is where DateTimeImmutable comes in.

$today = new DateTimeImmutable();

echo $today->format('Y-m-d') . "\n<br>";
echo "---\n<br>";

$oneWeekFromToday = $today->add(DateInterval::createFromDateString('7 days'));
$twoWeeksFromToday = $today->add(DateInterval::createFromDateString('14 days'));

echo $today->format('Y-m-d') . "\n<br>";
echo $oneWeekFromToday->format('Y-m-d') . "\n<br>";
echo $twoWeeksFromToday->format('Y-m-d') . "\n<br>";

The output:

2017-02-11 
--- 
2017-02-11 
2017-02-18 
2017-02-25 

In this second example, we get the dates we expected back. By using DateTimeImmutable instead of DateTime, we prevent accidental state mutations and prevent potential bugs.

Event system in Python

You can try buslane module.

This library makes implementation of message-based system easier. It supports commands (single handler) and events (0 or multiple handlers) approach. Buslane uses Python type annotations to properly register handler.

Simple example:

from dataclasses import dataclass

from buslane.commands import Command, CommandHandler, CommandBus


@dataclass(frozen=True)
class RegisterUserCommand(Command):
    email: str
    password: str


class RegisterUserCommandHandler(CommandHandler[RegisterUserCommand]):

    def handle(self, command: RegisterUserCommand) -> None:
        assert command == RegisterUserCommand(
            email='[email protected]',
            password='secret',
        )


command_bus = CommandBus()
command_bus.register(handler=RegisterUserCommandHandler())
command_bus.execute(command=RegisterUserCommand(
    email='[email protected]',
    password='secret',
))

To install buslane, simply use pip:

$ pip install buslane

Mount current directory as a volume in Docker on Windows 10

Here is mine which is compatible for both Win10 docker-ce & Win7 docker-toolbox. At las at the time I'm writing this :).

You can notice I prefer use /host_mnt/c instead of c:/ because I sometimes encountered trouble on docker-ce Win 10 with c:/

$WIN_PATH=Convert-Path .

#Convert for docker mount to be OK on Windows10 and Windows 7 Powershell
#Exact conversion is : remove the ":" symbol, replace all "\" by "/", remove last "/" and minor case only the disk letter
#Then for Windows10, add a /host_mnt/" at the begin of string => this way : c:\Users is translated to /host_mnt/c/Users
#For Windows7, add "//" => c:\Users is translated to //c/Users
$MOUNT_PATH=(($WIN_PATH -replace "\\","/") -replace ":","").Trim("/")

[regex]$regex='^[a-zA-Z]/'
$MOUNT_PATH=$regex.Replace($MOUNT_PATH, {$args[0].Value.ToLower()})

#Win 10
if ([Environment]::OSVersion.Version -ge (new-object 'Version' 10,0)) {
$MOUNT_PATH="/host_mnt/$MOUNT_PATH"
}
elseif ([Environment]::OSVersion.Version -ge (new-object 'Version' 6,1)) {
$MOUNT_PATH="//$MOUNT_PATH"
}

docker run -it -v "${MOUNT_PATH}:/tmp/test" busybox ls /tmp/test

Date object to Calendar [Java]

Calendar tCalendar = Calendar.getInstance();
tCalendar.setTime(date);

date is a java.util.Date object. You may use Calendar.getInstance() as well to obtain the Calendar instance(much more efficient).

how to set select element as readonly ('disabled' doesnt pass select value on server)

You can simulate a readonly select box using the CSS pointer-events property:

select[readonly]
{
    pointer-events: none;
}

The HTML tabindex property will also prevent it from being selected by keyboard tabbing:

<select tabindex="-1">

_x000D_
_x000D_
select[readonly]_x000D_
{_x000D_
    pointer-events: none;_x000D_
}_x000D_
_x000D_
_x000D_
/* irrelevent styling */_x000D_
_x000D_
*_x000D_
{_x000D_
  box-sizing: border-box;_x000D_
}_x000D_
_x000D_
*[readonly]_x000D_
{_x000D_
  background: #fafafa;_x000D_
  border: 1px solid #ccc;_x000D_
  color: #555;_x000D_
}_x000D_
_x000D_
input, select_x000D_
{_x000D_
  display:block;_x000D_
  width: 20rem;_x000D_
  padding: 0.5rem;_x000D_
  margin-bottom: 1rem;_x000D_
}
_x000D_
<form>_x000D_
  <input type="text" value="this is a normal text box">_x000D_
  <input type="text" readonly value="this is a readonly text box">_x000D_
  <select readonly tabindex="-1">_x000D_
    <option>This is a readonly select box</option>_x000D_
    <option>Option 2</option>_x000D_
  </select>_x000D_
  <select>_x000D_
    <option>This is a normal select box</option>_x000D_
    <option>Option 2</option>_x000D_
  </select>_x000D_
</form>
_x000D_
_x000D_
_x000D_

How to Consume WCF Service with Android

To get started with WCF, it might be easiest to just use the default SOAP format and HTTP POST (rather than GET) for the web-service bindings. The easiest HTTP binding to get working is "basicHttpBinding". Here is an example of what the ServiceContract/OperationContract might look like for your login service:

[ServiceContract(Namespace="http://mycompany.com/LoginService")]
public interface ILoginService
{
    [OperationContract]
    string Login(string username, string password);
}

The implementation of the service could look like this:

public class LoginService : ILoginService
{
    public string Login(string username, string password)
    {
        // Do something with username, password to get/create sessionId
        // string sessionId = "12345678";
        string sessionId = OperationContext.Current.SessionId;

        return sessionId;
    }
}

You can host this as a windows service using a ServiceHost, or you can host it in IIS like a normal ASP.NET web (service) application. There are a lot of tutorials out there for both of these.

The WCF service config might look like this:

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


    <system.serviceModel>
        <behaviors>
            <serviceBehaviors>
                <behavior name="LoginServiceBehavior">
                    <serviceMetadata />
                </behavior>
            </serviceBehaviors>
        </behaviors>

        <services>
            <service name="WcfTest.LoginService"
                     behaviorConfiguration="LoginServiceBehavior" >
                <host>
                    <baseAddresses>
                        <add baseAddress="http://somesite.com:55555/LoginService/" />
                    </baseAddresses>
                </host>
                <endpoint name="LoginService"
                          address=""
                          binding="basicHttpBinding"
                          contract="WcfTest.ILoginService" />

                <endpoint name="LoginServiceMex"
                          address="mex"
                          binding="mexHttpBinding"
                          contract="IMetadataExchange" />
            </service>
        </services>
    </system.serviceModel>
</configuration>

(The MEX stuff is optional for production, but is needed for testing with WcfTestClient.exe, and for exposing the service meta-data).

You'll have to modify your Java code to POST a SOAP message to the service. WCF can be a little picky when inter-operating with non-WCF clients, so you'll have to mess with the POST headers a little to get it to work. Once you get this running, you can then start to investigate security for the login (might need to use a different binding to get better security), or possibly using WCF REST to allow for logins with a GET rather than SOAP/POST.

Here is an example of what the HTTP POST should look like from the Java code. There is a tool called "Fiddler" that can be really useful for debugging web-services.

POST /LoginService HTTP/1.1
Content-Type: text/xml; charset=utf-8
SOAPAction: "http://mycompany.com/LoginService/ILoginService/Login"
Host: somesite.com:55555
Content-Length: 216
Expect: 100-continue
Connection: Keep-Alive

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<Login xmlns="http://mycompany.com/LoginService">
<username>Blah</username>
<password>Blah2</password>
</Login>
</s:Body>
</s:Envelope>

Static Initialization Blocks

If your static variables need to be set at runtime then a static {...} block is very helpful.

For example, if you need to set the static member to a value which is stored in a config file or database.

Also useful when you want to add values to a static Map member as you can't add these values in the initial member declaration.

Laravel Eloquent limit and offset

laravel have own function skip for offset and take for limit. just like below example of laravel query :-

Article::where([['user_id','=',auth()->user()->id]])
                ->where([['title','LIKE',"%".$text_val."%"]])
                ->orderBy('id','DESC')
                ->skip(0)
                ->take(2)
                ->get();

What's the difference between the 'ref' and 'out' keywords?

 public static void Main(string[] args)
    {
        //int a=10;
        //change(ref a);
        //Console.WriteLine(a);
        // Console.Read();

        int b;
        change2(out b);
        Console.WriteLine(b);
        Console.Read();
    }
    // static void change(ref int a)
    //{
    //    a = 20;
    //}

     static void change2(out int b)
     {
         b = 20;
     }

you can check this code it will describe you its complete differnce when you use "ref" its mean that u already initialize that int/string

but when you use "out" it works in both conditions wheather u initialize that int/string or not but u must initialize that int/string in that function

Pythonic way of checking if a condition holds for any element of a list

any():

if any(t < 0 for t in x):
    # do something

Also, if you're going to use "True in ...", make it a generator expression so it doesn't take O(n) memory:

if True in (t < 0 for t in x):

Regex empty string or email

I prefer /^\s+$|^$/gi to match empty and empty spaces.

_x000D_
_x000D_
console.log("  ".match(/^\s+$|^$/gi));_x000D_
console.log("".match(/^\s+$|^$/gi));
_x000D_
_x000D_
_x000D_

Calculating the angle between the line defined by two points

in android i did this using kotlin:

private fun angleBetweenPoints(a: PointF, b: PointF): Double {
        val deltaY = abs(b.y - a.y)
        val deltaX = abs(b.x - a.x)
        return Math.toDegrees(atan2(deltaY.toDouble(), deltaX.toDouble()))
    }

Writing your own square root function

Found a great article about Integer Square Roots.

This is a slightly improved version that it presents there:

unsigned long sqrt(unsigned long a){
    int i;
    unsigned long rem = 0;
    unsigned long root = 0;
    for (i = 0; i < 16; i++){
        root <<= 1;
        rem = (rem << 2) | (a >> 30);
        a <<= 2;
        if(root < rem){
            root++;
            rem -= root;
            root++;
        }
    }
    return root >> 1;
}

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

Just for the sake of completeness, we can use the operators [ and [[:

set.seed(1)
df <- data.frame(v1 = runif(10), v2 = letters[1:10])

Several options

df[df[1] < 0.5 | df[2] == "g", ] 
df[df[[1]] < 0.5 | df[[2]] == "g", ] 
df[df["v1"] < 0.5 | df["v2"] == "g", ]

df$name is equivalent to df[["name", exact = FALSE]]

Using dplyr:

library(dplyr)
filter(df, v1 < 0.5 | v2 == "g")

Using sqldf:

library(sqldf)
sqldf('SELECT *
      FROM df 
      WHERE v1 < 0.5 OR v2 = "g"')

Output for the above options:

          v1 v2
1 0.26550866  a
2 0.37212390  b
3 0.20168193  e
4 0.94467527  g
5 0.06178627  j

How can I get the image url in a Wordpress theme?

You need to use

 <?php bloginfo('template_directory'); ?>

It returns the directory of the current WordPress theme.

Now for example, if your theme has some image named example.jpg inside some folder name subfolder folder in the images folder.

 themes
   |-> your theme
          |-> images
                |->subfolder
                      |-> examples.jpg

You access it like this

 <img class="article-image" src="<?php bloginfo('template_directory'); ?> /images/subfolder/example.jpg" border="0" alt="">

PDO::__construct(): Server sent charset (255) unknown to the client. Please, report to the developers

I had this problem also. The issue was because I was running an old version of PHP (5.6) and once I upgraded to PHP 7.4 the errors went away.

This was on Amazon Linux 2 for me and the command to upgrade was:

amazon-linux-extras install php7.4

Other flavors of *nix might have it in their repositories otherwise if you're on a flavor of Linux then Remi might have it for you here: https://rpms.remirepo.net/

How to sort an array of objects with jquery or javascript

data.sort(function(a,b) 
{
   return a.val - b.val;
});

What is the default scope of a method in Java?

The default scope is package-private. All classes in the same package can access the method/field/class. Package-private is stricter than protected and public scopes, but more permissive than private scope.

More information:
http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
http://mindprod.com/jgloss/scope.html

Replace all particular values in a data frame

Like this:

> df[df==""]<-NA
> df
     A    B
1 <NA>   12
2  xyz <NA>
3  jkl  100

IIS - can't access page by ip address instead of localhost

The IIS is a multi web site server. The way is distinct the site is by the host header name. So you need to setup that on your web site.

Here is the steps that you need to follow:

How to configure multiple IIS websites to access using host headers?

In general, open your web site properties, locate the Ip Address and near its there is the advanced, "multiple identities for this web site". There you need ether to add all income to this site with a star: "*", ether place the names you like to work with.

resize font to fit in a div (on one line)

@Clovis Six thank for your answer. It prove very usefull to me. A pity I cannot thanks you more than just a vote up.

Note: I have to change the "$J(" for "$(" for it to work on my config.

evendo, this out of the scope of this question and not in the use of SO, I extended your code to make it work for multi-line box with max-height.

  /**
   * Adjust the font-size of the text so it fits the container
   *
   * support multi-line, based on css 'max-height'.
   * 
   * @param minSize     Minimum font size?
   * @param maxSize     Maximum font size?
   */
  $.fn.autoTextSize_UseMaxHeight = function(minSize, maxSize) {
    var _self = this,
        _width = _self.innerWidth(),
        _boxHeight = parseInt(_self.css('max-height')),
        _textHeight = parseInt(_self.getTextHeight(_width)),
        _fontSize = parseInt(_self.css('font-size'));

    while (_boxHeight < _textHeight || (maxSize && _fontSize > parseInt(maxSize))) {
      if (minSize && _fontSize <= parseInt(minSize)) break;

      _fontSize--;
      _self.css('font-size', _fontSize + 'px');

      _textHeight = parseInt(_self.getTextHeight(_width));
    }
  };

PS: I know this should be a comment, but comments don't let me post code properly.

Does Python support short-circuiting?

Yes, Python does support Short-circuit evaluation, minimal evaluation, or McCarthy evaluation for Boolean operators. It is used to reduce the number of evaluations for computing the output of boolean expression. Example -

Base Functions

def a(x):
    print('a')
    return x

def b(x):
    print('b')
    return x 

AND

if(a(True) and b(True)):
    print(1,end='\n\n')

if(a(False) and b(True)):
    print(2,end='\n\n') 

AND-OUTPUT

a
b
1

a 

OR

if(a(True) or b(False)):
    print(3,end='\n\n')

if(a(False) or b(True)):
    print(4,end='\n\n') 

OR-OUTPUT

a
3

a
b
4 

How to find Current open Cursors in Oracle

Here's how to find open cursors that have been parsed. You need to be logged in as a user with access to v$open_cursor and v$session.

COLUMN USER_NAME FORMAT A15

SELECT s.machine, oc.user_name, oc.sql_text, count(1) 
FROM v$open_cursor oc, v$session s
WHERE oc.sid = s.sid
GROUP BY user_name, sql_text, machine
HAVING COUNT(1) > 2
ORDER BY count(1) DESC
;

If gives you part of the SQL text so it can be useful for identifying leaky applications. If a cursor has not been parsed, then it does not appear here. Note that Oralce will sometimes keep things open longer than you do.

What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?

What Is It?

This exception means that you're trying to access a collection item by index, using an invalid index. An index is invalid when it's lower than the collection's lower bound or greater than or equal to the number of elements it contains.

When It Is Thrown

Given an array declared as:

byte[] array = new byte[4];

You can access this array from 0 to 3, values outside this range will cause IndexOutOfRangeException to be thrown. Remember this when you create and access an array.

Array Length
In C#, usually, arrays are 0-based. It means that first element has index 0 and last element has index Length - 1 (where Length is total number of items in the array) so this code doesn't work:

array[array.Length] = 0;

Moreover please note that if you have a multidimensional array then you can't use Array.Length for both dimension, you have to use Array.GetLength():

int[,] data = new int[10, 5];
for (int i=0; i < data.GetLength(0); ++i) {
    for (int j=0; j < data.GetLength(1); ++j) {
        data[i, j] = 1;
    }
}

Upper Bound Is Not Inclusive
In the following example we create a raw bidimensional array of Color. Each item represents a pixel, indices are from (0, 0) to (imageWidth - 1, imageHeight - 1).

Color[,] pixels = new Color[imageWidth, imageHeight];
for (int x = 0; x <= imageWidth; ++x) {
    for (int y = 0; y <= imageHeight; ++y) {
        pixels[x, y] = backgroundColor;
    }
}

This code will then fail because array is 0-based and last (bottom-right) pixel in the image is pixels[imageWidth - 1, imageHeight - 1]:

pixels[imageWidth, imageHeight] = Color.Black;

In another scenario you may get ArgumentOutOfRangeException for this code (for example if you're using GetPixel method on a Bitmap class).

Arrays Do Not Grow
An array is fast. Very fast in linear search compared to every other collection. It is because items are contiguous in memory so memory address can be calculated (and increment is just an addition). No need to follow a node list, simple math! You pay this with a limitation: they can't grow, if you need more elements you need to reallocate that array (this may take a relatively long time if old items must be copied to a new block). You resize them with Array.Resize<T>(), this example adds a new entry to an existing array:

Array.Resize(ref array, array.Length + 1);

Don't forget that valid indices are from 0 to Length - 1. If you simply try to assign an item at Length you'll get IndexOutOfRangeException (this behavior may confuse you if you think they may increase with a syntax similar to Insert method of other collections).

Special Arrays With Custom Lower Bound
First item in arrays has always index 0. This is not always true because you can create an array with a custom lower bound:

var array = Array.CreateInstance(typeof(byte), new int[] { 4 }, new int[] { 1 });

In that example, array indices are valid from 1 to 4. Of course, upper bound cannot be changed.

Wrong Arguments
If you access an array using unvalidated arguments (from user input or from function user) you may get this error:

private static string[] RomanNumbers =
    new string[] { "I", "II", "III", "IV", "V" };

public static string Romanize(int number)
{
    return RomanNumbers[number];
}

Unexpected Results
This exception may be thrown for another reason too: by convention, many search functions will return -1 (nullables has been introduced with .NET 2.0 and anyway it's also a well-known convention in use from many years) if they didn't find anything. Let's imagine you have an array of objects comparable with a string. You may think to write this code:

// Items comparable with a string
Console.WriteLine("First item equals to 'Debug' is '{0}'.",
    myArray[Array.IndexOf(myArray, "Debug")]);

// Arbitrary objects
Console.WriteLine("First item equals to 'Debug' is '{0}'.",
    myArray[Array.FindIndex(myArray, x => x.Type == "Debug")]);

This will fail if no items in myArray will satisfy search condition because Array.IndexOf() will return -1 and then array access will throw.

Next example is a naive example to calculate occurrences of a given set of numbers (knowing maximum number and returning an array where item at index 0 represents number 0, items at index 1 represents number 1 and so on):

static int[] CountOccurences(int maximum, IEnumerable<int> numbers) {
    int[] result = new int[maximum + 1]; // Includes 0

    foreach (int number in numbers)
        ++result[number];

    return result;
}

Of course, it's a pretty terrible implementation but what I want to show is that it'll fail for negative numbers and numbers above maximum.

How it applies to List<T>?

Same cases as array - range of valid indexes - 0 (List's indexes always start with 0) to list.Count - accessing elements outside of this range will cause the exception.

Note that List<T> throws ArgumentOutOfRangeException for the same cases where arrays use IndexOutOfRangeException.

Unlike arrays, List<T> starts empty - so trying to access items of just created list lead to this exception.

var list = new List<int>();

Common case is to populate list with indexing (similar to Dictionary<int, T>) will cause exception:

list[0] = 42; // exception
list.Add(42); // correct

IDataReader and Columns
Imagine you're trying to read data from a database with this code:

using (var connection = CreateConnection()) {
    using (var command = connection.CreateCommand()) {
        command.CommandText = "SELECT MyColumn1, MyColumn2 FROM MyTable";

        using (var reader = command.ExecuteReader()) {
            while (reader.Read()) {
                ProcessData(reader.GetString(2)); // Throws!
            }
        }
    }
}

GetString() will throw IndexOutOfRangeException because you're dataset has only two columns but you're trying to get a value from 3rd one (indices are always 0-based).

Please note that this behavior is shared with most IDataReader implementations (SqlDataReader, OleDbDataReader and so on).

You can get the same exception also if you use the IDataReader overload of the indexer operator that takes a column name and pass an invalid column name.
Suppose for example that you have retrieved a column named Column1 but then you try to retrieve the value of that field with

 var data = dr["Colum1"];  // Missing the n in Column1.

This happens because the indexer operator is implemented trying to retrieve the index of a Colum1 field that doesn't exist. The GetOrdinal method will throw this exception when its internal helper code returns a -1 as the index of "Colum1".

Others
There is another (documented) case when this exception is thrown: if, in DataView, data column name being supplied to the DataViewSort property is not valid.

How to Avoid

In this example, let me assume, for simplicity, that arrays are always monodimensional and 0-based. If you want to be strict (or you're developing a library), you may need to replace 0 with GetLowerBound(0) and .Length with GetUpperBound(0) (of course if you have parameters of type System.Array, it doesn't apply for T[]). Please note that in this case, upper bound is inclusive then this code:

for (int i=0; i < array.Length; ++i) { }

Should be rewritten like this:

for (int i=array.GetLowerBound(0); i <= array.GetUpperBound(0); ++i) { }

Please note that this is not allowed (it'll throw InvalidCastException), that's why if your parameters are T[] you're safe about custom lower bound arrays:

void foo<T>(T[] array) { }

void test() {
    // This will throw InvalidCastException, cannot convert Int32[] to Int32[*]
    foo((int)Array.CreateInstance(typeof(int), new int[] { 1 }, new int[] { 1 }));
}

Validate Parameters
If index comes from a parameter you should always validate them (throwing appropriate ArgumentException or ArgumentOutOfRangeException). In the next example, wrong parameters may cause IndexOutOfRangeException, users of this function may expect this because they're passing an array but it's not always so obvious. I'd suggest to always validate parameters for public functions:

static void SetRange<T>(T[] array, int from, int length, Func<i, T> function)
{
    if (from < 0 || from>= array.Length)
        throw new ArgumentOutOfRangeException("from");

    if (length < 0)
        throw new ArgumentOutOfRangeException("length");

    if (from + length > array.Length)
        throw new ArgumentException("...");

    for (int i=from; i < from + length; ++i)
        array[i] = function(i);
}

If function is private you may simply replace if logic with Debug.Assert():

Debug.Assert(from >= 0 && from < array.Length);

Check Object State
Array index may not come directly from a parameter. It may be part of object state. In general is always a good practice to validate object state (by itself and with function parameters, if needed). You can use Debug.Assert(), throw a proper exception (more descriptive about the problem) or handle that like in this example:

class Table {
    public int SelectedIndex { get; set; }
    public Row[] Rows { get; set; }

    public Row SelectedRow {
        get {
            if (Rows == null)
                throw new InvalidOperationException("...");

            // No or wrong selection, here we just return null for
            // this case (it may be the reason we use this property
            // instead of direct access)
            if (SelectedIndex < 0 || SelectedIndex >= Rows.Length)
                return null;

            return Rows[SelectedIndex];
        }
}

Validate Return Values
In one of previous examples we directly used Array.IndexOf() return value. If we know it may fail then it's better to handle that case:

int index = myArray[Array.IndexOf(myArray, "Debug");
if (index != -1) { } else { }

How to Debug

In my opinion, most of the questions, here on SO, about this error can be simply avoided. The time you spend to write a proper question (with a small working example and a small explanation) could easily much more than the time you'll need to debug your code. First of all, read this Eric Lippert's blog post about debugging of small programs, I won't repeat his words here but it's absolutely a must read.

You have source code, you have exception message with a stack trace. Go there, pick right line number and you'll see:

array[index] = newValue;

You found your error, check how index increases. Is it right? Check how array is allocated, is coherent with how index increases? Is it right according to your specifications? If you answer yes to all these questions, then you'll find good help here on StackOverflow but please first check for that by yourself. You'll save your own time!

A good start point is to always use assertions and to validate inputs. You may even want to use code contracts. When something went wrong and you can't figure out what happens with a quick look at your code then you have to resort to an old friend: debugger. Just run your application in debug inside Visual Studio (or your favorite IDE), you'll see exactly which line throws this exception, which array is involved and which index you're trying to use. Really, 99% of the times you'll solve it by yourself in a few minutes.

If this happens in production then you'd better to add assertions in incriminated code, probably we won't see in your code what you can't see by yourself (but you can always bet).

The VB.NET side of the story

Everything that we have said in the C# answer is valid for VB.NET with the obvious syntax differences but there is an important point to consider when you deal with VB.NET arrays.

In VB.NET, arrays are declared setting the maximum valid index value for the array. It is not the count of the elements that we want to store in the array.

' declares an array with space for 5 integer 
' 4 is the maximum valid index starting from 0 to 4
Dim myArray(4) as Integer

So this loop will fill the array with 5 integers without causing any IndexOutOfRangeException

For i As Integer = 0 To 4
    myArray(i) = i
Next

The VB.NET rule

This exception means that you're trying to access a collection item by index, using an invalid index. An index is invalid when it's lower than the collection's lower bound or greater than equal to the number of elements it contains. the maximum allowed index defined in the array declaration

How to add a file to the last commit in git?

If you didn't push the update in remote then the simple solution is remove last local commit using following command: git reset HEAD^. Then add all files and commit again.

How to start http-server locally

When you're running npm install in the project's root, it installs all of the npm dependencies into the project's node_modules directory.

If you take a look at the project's node_modules directory, you should see a directory called http-server, which holds the http-server package, and a .bin folder, which holds the executable binaries from the installed dependencies. The .bin directory should have the http-server binary (or a link to it).

So in your case, you should be able to start the http-server by running the following from your project's root directory (instead of npm start):

./node_modules/.bin/http-server -a localhost -p 8000 -c-1

This should have the same effect as running npm start.

If you're running a Bash shell, you can simplify this by adding the ./node_modules/.bin folder to your $PATH environment variable:

export PATH=./node_modules/.bin:$PATH

This will put this folder on your path, and you should be able to simply run

http-server -a localhost -p 8000 -c-1

Simple pagination in javascript

Just create and save a page token in global variable with window.nextPageToken. Send this to API server everytime you make a request and have it return the next one with response and you can easily keep track of last token. The below is an example how you can move forward and backward from search results. The key is the offset you send to API based on the nextPageToken that you have saved:

function getPrev() {
  var offset = Number(window.nextPageToken) - limit * 2;
  if (offset < 0) {
    offset = 0;
  }
  window.nextPageToken = offset;
  if (canSubmit(searchForm, offset)) {
    searchForm.submit();
  }
}

function getNext() {
  var offset = Number(window.nextPageToken);
  window.nextPageToken = offset;
  if (canSubmit(searchForm, offset)) {
    searchForm.submit();
  }
}

Open a new tab on button click in AngularJS

You should use the $location service

Angular docs:

Convert SVG image to PNG with PHP

This is v. easy, have been doing work on this for the past few weeks.

You need the Batik SVG Toolkit. Download, and place the files in the same directory as the SVG you want to convert to a JPEG, also make sure you unzip it first.

Open the terminal, and run this command:

java -jar batik-rasterizer.jar -m image/jpeg -q 0.8 NAME_OF_SVG_FILE.svg

That should output a JPEG of the SVG file. Really easy. You can even just place it in a loop and convert loads of SVGs,

import os

svgs = ('test1.svg', 'test2.svg', 'etc.svg') 
for svg in svgs:
    os.system('java -jar batik-rasterizer.jar -m image/jpeg -q 0.8 '+str(svg)+'.svg')

What is Dispatcher Servlet in Spring?

I know this question is marked as solved already but I want to add a newer image explaining this pattern in detail(source: spring in action 4):

enter image description here

Explanation

When the request leaves the browser (1), it carries information about what the user is asking for. At the least, the request will be carrying the requested URL. But it may also carry additional data, such as the information submitted in a form by the user.

The first stop in the request’s travels is at Spring’s DispatcherServlet. Like most Java- based web frameworks, Spring MVC funnels requests through a single front controller servlet. A front controller is a common web application pattern where a single servlet delegates responsibility for a request to other components of an application to per- form actual processing. In the case of Spring MVC, DispatcherServlet is the front controller. The DispatcherServlet’s job is to send the request on to a Spring MVC controller. A controller is a Spring component that processes the request. But a typical application may have several controllers, and DispatcherServlet needs some help deciding which controller to send the request to. So the DispatcherServlet consults one or more handler mappings (2) to figure out where the request’s next stop will be. The handler mapping pays particular attention to the URL carried by the request when making its decision. Once an appropriate controller has been chosen, DispatcherServlet sends the request on its merry way to the chosen controller (3). At the controller, the request drops off its payload (the information submitted by the user) and patiently waits while the controller processes that information. (Actually, a well-designed controller per- forms little or no processing itself and instead delegates responsibility for the business logic to one or more service objects.) The logic performed by a controller often results in some information that needs to be carried back to the user and displayed in the browser. This information is referred to as the model. But sending raw information back to the user isn’t suffi- cient—it needs to be formatted in a user-friendly format, typically HTML. For that, the information needs to be given to a view, typically a JavaServer Page (JSP). One of the last things a controller does is package up the model data and identify the name of a view that should render the output. It then sends the request, along with the model and view name, back to the DispatcherServlet (4). So that the controller doesn’t get coupled to a particular view, the view name passed back to DispatcherServlet doesn’t directly identify a specific JSP. It doesn’t even necessarily suggest that the view is a JSP. Instead, it only carries a logical name that will be used to look up the actual view that will produce the result. The DispatcherServlet consults a view resolver (5) to map the logical view name to a spe- cific view implementation, which may or may not be a JSP. Now that DispatcherServlet knows which view will render the result, the request’s job is almost over. Its final stop is at the view implementation (6), typically a JSP, where it delivers the model data. The request’s job is finally done. The view will use the model data to render output that will be carried back to the client by the (not- so-hardworking) response object (7).

Can I use a min-height for table, tr or td?

In CSS 2.1, the effect of 'min-height' and 'max-height' on tables, inline tables, table cells, table rows, and row groups is undefined.

So try wrapping the content in a div, and give the div a min-height jsFiddle here

<table cellspacing="0" cellpadding="0" border="0" style="width:300px">
    <tbody>
        <tr>
            <td>
                <div style="min-height: 100px; background-color: #ccc">
                    Hello World !
                </div>
            </td>
            <td>
                <div style="min-height: 100px; background-color: #f00">
                    Good Morning !
                </div>
            </td>
        </tr>
    </tbody>
</table>

Sequence contains more than one element

Use FirstOrDefault insted of SingleOrDefault..

SingleOrDefault returns a SINGLE element or null if no element is found. If 2 elements are found in your Enumerable then it throws the exception you are seeing

FirstOrDefault returns the FIRST element it finds or null if no element is found. so if there are 2 elements that match your predicate the second one is ignored

   public int GetPackage(int id,int emp)
           {
             int getpackages=Convert.ToInt32(EmployerSubscriptionPackage.GetAllData().Where(x
   => x.SubscriptionPackageID ==`enter code here` id && x.EmployerID==emp ).FirstOrDefault().ID);
               return getpackages;
           }

 1. var EmployerId = Convert.ToInt32(Session["EmployerId"]);
               var getpackage = GetPackage(employerSubscription.ID, EmployerId);

React eslint error missing in props validation

Issue: 'id1' is missing in props validation, eslintreact/prop-types

<div id={props.id1} >
    ...
</div>

Below solution worked, in a function component:

let { id1 } = props;

<div id={id1} >
    ...
</div>

Hope that helps.

push object into array

can be done like this too.

       let data_array = [];
    
       let my_object = {}; 

       my_object.name = "stack";
       my_object.age = 20;
       my_object.hair_color = "red";
       my_object.eye_color = "green";
        
       data_array.push(my_object);

sed fails with "unknown option to `s'" error

The problem is with slashes: your variable contains them and the final command will be something like sed "s/string/path/to/something/g", containing way too many slashes.

Since sed can take any char as delimiter (without having to declare the new delimiter), you can try using another one that doesn't appear in your replacement string:

replacement="/my/path"
sed --expression "s@pattern@$replacement@"

Note that this is not bullet proof: if the replacement string later contains @ it will break for the same reason, and any backslash sequences like \1 will still be interpreted according to sed rules. Using | as a delimiter is also a nice option as it is similar in readability to /.

VBA Excel - Insert row below with same format including borders and frames

When inserting a row, regardless of the CopyOrigin, Excel will only put vertical borders on the inserted cells if the borders above and below the insert position are the same.

I'm running into a similar (but rotated) situation with inserting columns, but Copy/Paste is too slow for my workbook (tens of thousands of rows, many columns, and complex formatting).

I've found three workarounds that don't require copying the formatting from the source row:

  1. Ensure the vertical borders are the same weight, color, and pattern above and below the insert position so Excel will replicate them in your new row. (This is the "It hurts when I do this," "Stop doing that!" answer.)

  2. Use conditional formatting to establish the border (with a Formula of "=TRUE"). The conditional formatting will be copied to the new row, so you still end up with a border.Caveats:

    • Conditional formatting borders are limited to the thin-weight lines.
    • Works best for sheets where borders are relatively consistent so you don't have to create a bunch of conditional formatting rules.
  3. Set the border on the inserted row in VBA after inserting the row. Setting a border on a range is much faster than copying and pasting all of the formatting just to get a border (assuming you know ahead of time what the border should be or can sample it from the row above without losing performance).

Git Pull is Not Possible, Unmerged Files

Assuming you want to throw away any changes you have, first check the output of git status. For any file that says "unmerged" next to it, run git add <unmerged file>. Then follow up with git reset --hard. That will git rid of any local changes except for untracked files.

How to change default text file encoding in Eclipse?

If you need to edit files of same type with more encodings in different folders and projects (e.g. one project is in UTF-8 and other in Windows-12xx), go to Window > Preferences > General > Content Types > Text > and select each type with multiple encodings.

For each type delete content of the Default encoding and click Update.

This way Eclipse will not "autodetect" encoding and will use encoding set for project or folder.

How to replace a character from a String in SQL?

Use the REPLACE function.

eg: SELECT REPLACE ('t?es?t', '?', 'w');

Source

T-SQL: Export to new Excel file

This is by far the best post for exporting to excel from SQL:

http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=49926

To quote from user madhivanan,

Apart from using DTS and Export wizard, we can also use this query to export data from SQL Server2000 to Excel

Create an Excel file named testing having the headers same as that of table columns and use these queries

1 Export data to existing EXCEL file from SQL Server table

insert into OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
    'Excel 8.0;Database=D:\testing.xls;', 
    'SELECT * FROM [SheetName$]') select * from SQLServerTable

2 Export data from Excel to new SQL Server table

select * 
into SQLServerTable FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
    'Excel 8.0;Database=D:\testing.xls;HDR=YES', 
    'SELECT * FROM [Sheet1$]')

3 Export data from Excel to existing SQL Server table (edited)

Insert into SQLServerTable Select * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
    'Excel 8.0;Database=D:\testing.xls;HDR=YES', 
    'SELECT * FROM [SheetName$]')

4 If you dont want to create an EXCEL file in advance and want to export data to it, use

EXEC sp_makewebtask 
    @outputfile = 'd:\testing.xls', 
    @query = 'Select * from Database_name..SQLServerTable', 
    @colheaders =1, 
    @FixedFont=0,@lastupdated=0,@resultstitle='Testing details'

(Now you can find the file with data in tabular format)

5 To export data to new EXCEL file with heading(column names), create the following procedure

create procedure proc_generate_excel_with_columns
(
    @db_name    varchar(100),
    @table_name varchar(100),   
    @file_name  varchar(100)
)
as

--Generate column names as a recordset
declare @columns varchar(8000), @sql varchar(8000), @data_file varchar(100)
select 
    @columns=coalesce(@columns+',','')+column_name+' as '+column_name 
from 
    information_schema.columns
where 
    table_name=@table_name
select @columns=''''''+replace(replace(@columns,' as ',''''' as '),',',',''''')

--Create a dummy file to have actual data
select @data_file=substring(@file_name,1,len(@file_name)-charindex('\',reverse(@file_name)))+'\data_file.xls'

--Generate column names in the passed EXCEL file
set @sql='exec master..xp_cmdshell ''bcp " select * from (select '+@columns+') as t" queryout "'+@file_name+'" -c'''
exec(@sql)

--Generate data in the dummy file
set @sql='exec master..xp_cmdshell ''bcp "select * from '+@db_name+'..'+@table_name+'" queryout "'+@data_file+'" -c'''
exec(@sql)

--Copy dummy file to passed EXCEL file
set @sql= 'exec master..xp_cmdshell ''type '+@data_file+' >> "'+@file_name+'"'''
exec(@sql)

--Delete dummy file 
set @sql= 'exec master..xp_cmdshell ''del '+@data_file+''''
exec(@sql)

After creating the procedure, execute it by supplying database name, table name and file path:

EXEC proc_generate_excel_with_columns 'your dbname', 'your table name','your file path'

Its a whomping 29 pages but that is because others show various other ways as well as people asking questions just like this one on how to do it.

Follow that thread entirely and look at the various questions people have asked and how they are solved. I picked up quite a bit of knowledge just skimming it and have used portions of it to get expected results.

To update single cells

A member also there Peter Larson posts the following: I think one thing is missing here. It is great to be able to Export and Import to Excel files, but how about updating single cells? Or a range of cells?

This is the principle of how you do manage that

update OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
'Excel 8.0;Database=c:\test.xls;hdr=no', 
'SELECT * FROM [Sheet1$b7:b7]') set f1 = -99

You can also add formulas to Excel using this:

update OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
'Excel 8.0;Database=c:\test.xls;hdr=no', 
'SELECT * FROM [Sheet1$b7:b7]') set f1 = '=a7+c7'

Exporting with column names using T-SQL

Member Mladen Prajdic also has a blog entry on how to do this here

References: www.sqlteam.com (btw this is an excellent blog / forum for anyone looking to get more out of SQL Server). For error referencing I used this

Errors that may occur

If you get the following error:

OLE DB provider 'Microsoft.Jet.OLEDB.4.0' cannot be used for distributed queries

Then run this:

sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ad Hoc Distributed Queries', 1;
GO
RECONFIGURE;
GO

How to combine results of two queries into a single dataset

I think you are after something like this; (Using row_number() with CTE and performing a FULL OUTER JOIN )

Fiddle example

;with t1 as (
  select col1,col2, row_number() over (order by col1) rn
  from table1 
),
t2 as (
  select col3,col4, row_number() over (order by col3) rn
  from table2
)
select col1,col2,col3,col4
from t1 full outer join t2 on t1.rn = t2.rn

Tables and data :

create table table1 (col1 int, col2 int)
create table table2 (col3 int, col4 int)

insert into table1 values
(1,2),(3,4)

insert into table2 values
(10,11),(30,40),(50,60)

Results :

|   COL1 |   COL2 | COL3 | COL4 |
---------------------------------
|      1 |      2 |   10 |   11 |
|      3 |      4 |   30 |   40 |
| (null) | (null) |   50 |   60 |

How to change root logging level programmatically for logback

I assume you are using logback (from the configuration file).

From logback manual, I see

Logger rootLogger = LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);

Perhaps this can help you change the value?

WebDriver: check if an element exists?

As the comment stated, this is in C# not Java but the idea is the same. I've researched this issue extensively and ultimately the issue is, FindElement always returns an exception when the element doesn't exist. There isn't an overloaded option that allows you to get null or anything else. Here is why I prefer this solution over others.

  1. Returning a list of elements then checking if the list size is 0 works but you lose functionality that way. You can't do a .click() on a collection of links even if the collection size is 1.
  2. You could assert that the element exists but often that stops your testing. In some cases, I have an extra link to click depending on how I got to that page and I want to click it if it exists or move on otherwise.
  3. It's only slow if you don't set the timeout driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(0));
  4. It's actually a very simple and elegant once the method is created. By using FindElementSafe instead of FindElement, I don't "see" the ugly try/catch block and I can use a simple Exists method. That would look something like this:

    IWebElement myLink = driver.FindElementSafe(By.Id("myId"));
    if (myLink.Exists)
    {
       myLink.Click();
    }
    

Here is how you extend IWebElement & IWebDriver

IWebDriver.FindElementSafe

    /// <summary>
    /// Same as FindElement only returns null when not found instead of an exception.
    /// </summary>
    /// <param name="driver">current browser instance</param>
    /// <param name="by">The search string for finding element</param>
    /// <returns>Returns element or null if not found</returns>
    public static IWebElement FindElementSafe(this IWebDriver driver, By by)
    {
        try
        {
            return driver.FindElement(by);
        }
        catch (NoSuchElementException)
        {
            return null;
        }
    }

IWebElement.Exists

    /// <summary>
    /// Requires finding element by FindElementSafe(By).
    /// Returns T/F depending on if element is defined or null.
    /// </summary>
    /// <param name="element">Current element</param>
    /// <returns>Returns T/F depending on if element is defined or null.</returns>
    public static bool Exists(this IWebElement element)
    {
        if (element == null)
        { return false; }
        return true;
    }

You could use polymorphism to modify the IWebDriver class instance of FindElement but that's a bad idea from a maintenance standpoint.

How to get jSON response into variable from a jquery script

Your PHP array is defined as:

$arr = array ('resonse'=>'error','comment'=>'test comment here');

Notice the mispelling "resonse". Also, as RaYell has mentioned, you have to use data instead of json in your success function because its parameter is currently data.

Try editing your PHP file to change the spelling form resonse to response. It should work then.

PHP Checking if the current date is before or after a set date

I wanted to set a specific date so have used this to do stuff before 2nd December 2013

if(mktime(0,0,0,12,2,2013) > strtotime('now')) {
    // do stuff
}

The 0,0,0 is midnight, the 12 is the month, the 2 is the day and the 2013 is the year.

select data up to a space?

select left(col, charindex(' ', col) - 1)

Laravel 4 Eloquent Query Using WHERE with OR AND OR?

if you want to use parentheses in laravel 4 and don't forget return
In Laravel 4 (at least) you need to use $a, $b in parentheses as in the example

$a = 1;
$b = 1;
$c = 1;
$d = 1;
Model::where(function ($query) use ($a, $b) {
    return $query->where('a', '=', $a)
          ->orWhere('b', '=', $b);
})->where(function ($query) use ($c, $d) {
    return $query->where('c', '=', $c)
          ->orWhere('d', '=', $d);
});

This is my result: enter image description here

Trust Store vs Key Store - creating with keytool

The terminology is a bit confusing indeed, but both javax.net.ssl.keyStore and javax.net.ssl.trustStore are used to specify which keystores to use, for two different purposes. Keystores come in various formats and are not even necessarily files (see this question), and keytool is just a tool to perform various operations on them (import/export/list/...).

The javax.net.ssl.keyStore and javax.net.ssl.trustStore parameters are the default parameters used to build KeyManagers and TrustManagers (respectively), then used to build an SSLContext which essentially contains the SSL/TLS settings to use when making an SSL/TLS connection via an SSLSocketFactory or an SSLEngine. These system properties are just where the default values come from, which is then used by SSLContext.getDefault(), itself used by SSLSocketFactory.getDefault() for example. (All of this can be customized via the API in a number of places, if you don't want to use the default values and that specific SSLContexts for a given purpose.)

The difference between the KeyManager and TrustManager (and thus between javax.net.ssl.keyStore and javax.net.ssl.trustStore) is as follows (quoted from the JSSE ref guide):

TrustManager: Determines whether the remote authentication credentials (and thus the connection) should be trusted.

KeyManager: Determines which authentication credentials to send to the remote host.

(Other parameters are available and their default values are described in the JSSE ref guide. Note that while there is a default value for the trust store, there isn't one for the key store.)

Essentially, the keystore in javax.net.ssl.keyStore is meant to contain your private keys and certificates, whereas the javax.net.ssl.trustStore is meant to contain the CA certificates you're willing to trust when a remote party presents its certificate. In some cases, they can be one and the same store, although it's often better practice to use distinct stores (especially when they're file-based).

What is the difference between signed and unsigned int

Sometimes we know in advance that the value stored in a given integer variable will always be positive-when it is being used to only count things, for example. In such a case we can declare the variable to be unsigned, as in, unsigned int num student;. With such a declaration, the range of permissible integer values (for a 32-bit compiler) will shift from the range -2147483648 to +2147483647 to range 0 to 4294967295. Thus, declaring an integer as unsigned almost doubles the size of the largest possible value that it can otherwise hold.

Why does Eclipse automatically add appcompat v7 library support whenever I create a new project?

I'm new with Android and the project appcompat_v7 always be created when I create new Android application project makes me so uncomfortable.

This is just a walk around. Choose Project Properties -> Android then at Library box just remove appcompat_v7_x and add appcompat_v7. Now you can delete appcompat_v7_x.

Uncheck Create Activity in create project wizard doesn't work, because when creating activity by wizard the appcompat_v7_x appear again. My ADT's version is v22.6.2-1085508.
I'm sorry if my English is bad.

How to fix Error: "Could not find schema information for the attribute/element" by creating schema

UPDATE Sept 2015
This answer continues to get upvotes, so I'm going to leave it here since it seems to be helpful to some people, but please check out the other answers from @reexmonkey and @Pressacco first. They may provide better results.

ORIGINAL ANSWER
Give this a shot:

  1. In Visual Studio, open your app.config or web.config file.
  2. Go to the "XML" menu and select "Create Schema". This action should create a new file called "app.xsd" or "web.xsd".
  3. Save that file to your disk.
  4. Go back to your app.config or web.config and in the edit window, right click and select properties. From there, make sure the xsd you just generated is referenced in the Schemas property. If it's not there then add it.

That should cause those messages to disappear.

I saved my web.xsd in the root of my web folder (which might not be the best place for it, but just for demonstration purposes) and my Schemas property looks like this:

"C:\Program Files (x86)\Microsoft Visual Studio 10.0\xml\Schemas\DotNetConfig.xsd" "Web.xsd"

How can I export the schema of a database in PostgreSQL?

pg_dump -s databasename -t tablename -U user -h host -p port > tablename.sql

this will limit the schema dump to the table "tablename" of "databasename"

Generate random numbers uniformly over an entire range

@Solution ((double) rand() / (RAND_MAX+1)) * (max-min+1) + min

Warning: Don't forget due to stretching and possible precision errors (even if RAND_MAX were large enough), you'll only be able to generate evenly distributed "bins" and not all numbers in [min,max].


@Solution: Bigrand

Warning: Note that this doubles the bits, but still won't be able to generate all numbers in your range in general, i.e., it is not necessarily true that BigRand() will generate all numbers between in its range.


Info: Your approach (modulo) is "fine" as long as the range of rand() exceeds your interval range and rand() is "uniform". The error for at most the first max - min numbers is 1/(RAND_MAX +1).

Also, I suggest to switch to the new random packagee in C++11 too, which offers better and more varieties of implementations than rand().

How to send a html email with the bash command "sendmail"?

It's simpler to use, the -a option :

cat ~/campaigns/release-status.html | mail -s "Release Status [Green]" -a "Content-Type: text/html" [email protected]

Use of Application.DoEvents()

The DoEvents does allow the user to click around or type and trigger other events, and background threads are a better approach.

However, there are still cases where you may run into issues that require flushing event messages. I ran into a problem where the RichTextBox control was ignoring the ScrollToCaret() method when the control had messages in queue to process.

The following code blocks all user input while executing DoEvents:

using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace Integrative.Desktop.Common
{
    static class NativeMethods
    {
        #region Block input

        [DllImport("user32.dll", EntryPoint = "BlockInput")]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool BlockInput([MarshalAs(UnmanagedType.Bool)] bool fBlockIt);

        public static void HoldUser()
        {
            BlockInput(true);
        }

        public static void ReleaseUser()
        {
            BlockInput(false);
        }

        public static void DoEventsBlockingInput()
        {
            HoldUser();
            Application.DoEvents();
            ReleaseUser();
        }

        #endregion
    }
}

How to reset all checkboxes using jQuery or pure JS?

 $(":checkbox:checked").each(function () {

 this.click(); 
});

to unchecked checked box, turn your logic around to do opposite

How to show data in a table by using psql command line interface?

On windows use the name of the table in quotes: TABLE "user"; or SELECT * FROM "user";

How to resize the jQuery DatePicker control

To get this to work in Safari 5.1 with Rails 3.1, I had to add:

.ui-datepicker, .ui-datepicker a{
 font-size:10px;
}

How do I tell Maven to use the latest version of a dependency?

The truth is even in 3.x it still works, surprisingly the projects builds and deploys. But the LATEST/RELEASE keyword causing problems in m2e and eclipse all over the place, ALSO projects depends on the dependency which deployed through the LATEST/RELEASE fail to recognize the version.

It will also causing problem if you are try to define the version as property, and reference it else where.

So the conclusion is use the versions-maven-plugin if you can.

How do you find out the type of an object (in Swift)?

If you get an "always true/fails" warning you may need to cast to Any before using is

(foo as Any) is SomeClass

How to set the opacity/alpha of a UIImage?

Set the opacity of its view it is showed in.

UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageWithName:@"SomeName.png"]];
imageView.alpha = 0.5; //Alpha runs from 0.0 to 1.0

Use this in an animation. You can change the alpha in an animation for an duration.

[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:1.0];
//Set alpha
[UIView commitAnimations];

How to push JSON object in to array using javascript

Observation

  • If there is a single object and you want to push whole object into an array then no need to iterate the object.

Try this :

_x000D_
_x000D_
var feed = {created_at: "2017-03-14T01:00:32Z", entry_id: 33358, field1: "4", field2: "4", field3: "0"};_x000D_
_x000D_
var data = [];_x000D_
data.push(feed);_x000D_
_x000D_
console.log(data);
_x000D_
_x000D_
_x000D_

Instead of :

_x000D_
_x000D_
var my_json = {created_at: "2017-03-14T01:00:32Z", entry_id: 33358, field1: "4", field2: "4", field3: "0"};_x000D_
_x000D_
var data = [];_x000D_
for(var i in my_json) {_x000D_
    data.push(my_json[i]);_x000D_
}_x000D_
_x000D_
console.log(data);
_x000D_
_x000D_
_x000D_

Routing for custom ASP.NET MVC 404 Error page

This solution doesn't need web.config file changes or catch-all routes.

First, create a controller like this;

public class ErrorController : Controller
{
    public ActionResult Index()
    {
        ViewBag.Title = "Regular Error";
        return View();
    }

    public ActionResult NotFound404()
    {
        ViewBag.Title = "Error 404 - File not Found";
        return View("Index");
    }
}

Then create the view under "Views/Error/Index.cshtml" as;

 @{
      Layout = "~/Views/Shared/_Layout.cshtml";
  }                     
  <p>We're sorry, page you're looking for is, sadly, not here.</p>

Then add the following in the Global asax file as below:

protected void Application_Error(object sender, EventArgs e)
{
        // Do whatever you want to do with the error

        //Show the custom error page...
        Server.ClearError(); 
        var routeData = new RouteData();
        routeData.Values["controller"] = "Error";

        if ((Context.Server.GetLastError() is HttpException) && ((Context.Server.GetLastError() as HttpException).GetHttpCode() != 404))
        {
            routeData.Values["action"] = "Index";
        }
        else
        {
            // Handle 404 error and response code
            Response.StatusCode = 404;
            routeData.Values["action"] = "NotFound404";
        } 
        Response.TrySkipIisCustomErrors = true; // If you are using IIS7, have this line
        IController errorsController = new ErrorController();
        HttpContextWrapper wrapper = new HttpContextWrapper(Context);
        var rc = new System.Web.Routing.RequestContext(wrapper, routeData);
        errorsController.Execute(rc);

        Response.End();
}

If you still get the custom IIS error page after doing this, make sure the following sections are commented out(or empty) in the web config file:

<system.web>
   <customErrors mode="Off" />
</system.web>
<system.webServer>   
   <httpErrors>     
   </httpErrors>
</system.webServer>

Change color of bootstrap navbar on hover link?

_x000D_
_x000D_
.navbar-default .navbar-nav > li > a{_x000D_
  color: #e9b846;_x000D_
}_x000D_
.navbar-default .navbar-nav > li > a:hover{_x000D_
  background-color: #e9b846;_x000D_
  color: #FFFFFF;_x000D_
}
_x000D_
_x000D_
_x000D_

What is meaning of negative dbm in signal strength?

I think it is confusing to think of it in terms of negative numbers. Since it is a logarithm think of the negative values the same way you think of powers of ten. 10^3 = 1000 while 10^-3 = 0.001.

With this in mind and using the formulas from S Lists's answer (and assuming our base power is 1mW in all these cases) we can build a little table:

|--------|-------------------|
| P(dBm) |        P(mW)      |
|--------|-------------------|
|    50  |  100000           |    
|    40  |   10000           |    strong transmitter
|    30  |    1000           |             ^  
|    20  |     100           |             |
|    10  |      10           |             |
|     0  |       1           |
|   -10  |       0.1         |
|   -20  |       0.01        |
|   -30  |       0.001       |
|   -40  |       0.0001      |
|   -50  |       0.00001     |             |
|   -60  |       0.000001    |             |
|   -70  |       0.0000001   |             v
|   -80  |       0.00000001  |    sensitive receiver
|   -90  |       0.000000001 |
|--------|-------------------|

When I think of it like this I find that it's easier to see that the more negative the dBm value then the farther to the right of the decimal the actual power value is.

When it comes to mobile networks, it not so much that they aren't powerful enough, rather it is that they are more sensitive. When you see receivers specs with dBm far into the negative values, then what you are seeing is more sensitive equipment.

Normally you would want your transmitter to be powerful (further in to the positives) and your receiver to be sensitive (further in to the negatives).

How to write character & in android strings.xml

This may be very old. But for those whose looking for a quick code.

 public String handleEscapeCharacter( String str ) {
    String[] escapeCharacters = { "&gt;", "&lt;", "&amp;", "&quot;", "&apos;" };
    String[] onReadableCharacter = {">", "<", "&", "\"\"", "'"};
    for (int i = 0; i < escapeCharacters.length; i++) {
        str = str.replace(escapeCharacters[i], onReadableCharacter[i]);
    } return str;
 }

That handles escape characters, you can add characters and symbols on their respective arrays.

-Cheers

How to check for a JSON response using RSpec?

JSON comparison solution

Yields a clean but potentially large Diff:

actual = JSON.parse(response.body, symbolize_names: true)
expected = { foo: "bar" }
expect(actual).to eq expected

Example of console output from real data:

expected: {:story=>{:id=>1, :name=>"The Shire"}}
     got: {:story=>{:id=>1, :name=>"The Shire", :description=>nil, :body=>nil, :number=>1}}

   (compared using ==)

   Diff:
   @@ -1,2 +1,2 @@
   -:story => {:id=>1, :name=>"The Shire"},
   +:story => {:id=>1, :name=>"The Shire", :description=>nil, ...}

(Thanks to comment by @floatingrock)

String comparison solution

If you want an iron-clad solution, you should avoid using parsers which could introduce false positive equality; compare the response body against a string. e.g:

actual = response.body
expected = ({ foo: "bar" }).to_json
expect(actual).to eq expected

But this second solution is less visually friendly as it uses serialized JSON which would include lots of escaped quotation marks.

Custom matcher solution

I tend to write myself a custom matcher that does a much better job of pinpointing at exactly which recursive slot the JSON paths differ. Add the following to your rspec macros:

def expect_response(actual, expected_status, expected_body = nil)
  expect(response).to have_http_status(expected_status)
  if expected_body
    body = JSON.parse(actual.body, symbolize_names: true)
    expect_json_eq(body, expected_body)
  end
end

def expect_json_eq(actual, expected, path = "")
  expect(actual.class).to eq(expected.class), "Type mismatch at path: #{path}"
  if expected.class == Hash
    expect(actual.keys).to match_array(expected.keys), "Keys mismatch at path: #{path}"
    expected.keys.each do |key|
      expect_json_eq(actual[key], expected[key], "#{path}/:#{key}")
    end
  elsif expected.class == Array
    expected.each_with_index do |e, index|
      expect_json_eq(actual[index], expected[index], "#{path}[#{index}]")
    end
  else
    expect(actual).to eq(expected), "Type #{expected.class} expected #{expected.inspect} but got #{actual.inspect} at path: #{path}"
  end
end

Example of usage 1:

expect_response(response, :no_content)

Example of usage 2:

expect_response(response, :ok, {
  story: {
    id: 1,
    name: "Shire Burning",
    revisions: [ ... ],
  }
})

Example output:

Type String expected "Shire Burning" but got "Shire Burnin" at path: /:story/:name

Another example output to demonstrate a mismatch deep in a nested array:

Type Integer expected 2 but got 1 at path: /:story/:revisions[0]/:version

As you can see, the output tells you EXACTLY where to fix your expected JSON.

Render a string in HTML and preserve spaces and linebreaks

There is a simple way to do it. I tried it on my app and it worked pretty well.

Just type: $text = $row["text"]; echo nl2br($text);

Round up to Second Decimal Place in Python

from math import ceil

num = 0.1111111111000
num = ceil(num * 100) / 100.0

See:
math.ceil documentation
round documentation - You'll probably want to check this out anyway for future reference

How do I POST form data with UTF-8 encoding by using curl?

You CAN use UTF-8 in the POST request, all you need is to specify the charset in your request.

You should use this request:

curl -X POST -H "Content-Type: application/x-www-form-urlencoded; charset=utf-8" --data-ascii "content=derinhält&date=asdf" http://myserverurl.com/api/v1/somemethod

What is the scope of variables in JavaScript?

There are two types of scopes in JavaScript.

  1. Global scope: variable which is announced in global scope can be used anywhere in the program very smoothly. For example:

    var carName = " BMW";
    
    // code here can use carName
    
    function myFunction() {
         // code here can use carName 
    }
    
  2. Functional scope or Local scope: variable declared in this scope can be used in its own function only. For example:

    // code here can not use carName
    function myFunction() {
       var carName = "BMW";
       // code here can use carName
    }
    

List all liquibase sql types

For checking type conversions in version 3, you can go to their github and check into the different liquibase types and check the method toDatabaseDataType. For example, for Boolean, you can check here:

https://github.com/liquibase/liquibase/blob/master/liquibase-core/src/main/java/liquibase/datatype/core/BooleanType.java

For version 2.0.x, the conversion seems to be into database specific classes. For example, for Mysql:

https://github.com/liquibase/liquibase/blob/2_0_x/liquibase-core/src/main/java/liquibase/database/typeconversion/core/MySQLTypeConverter.java

How to convert a Binary String to a base 10 integer in Java

This might work:

public int binaryToInteger(String binary) {
    char[] numbers = binary.toCharArray();
    int result = 0;
    for(int i=numbers.length - 1; i>=0; i--)
        if(numbers[i]=='1')
            result += Math.pow(2, (numbers.length-i - 1));
    return result;
}

How to make a deep copy of Java ArrayList

Cloning the objects before adding them. For example, instead of newList.addAll(oldList);

for(Person p : oldList) {
    newList.add(p.clone());
}

Assuming clone is correctly overriden inPerson.

Associating enums with strings in C#

Have you considered a lookup table using a Dictionary?

enum GroupTypes
{
    TheGroup,
    TheOtherGroup
}

Dictionary<string, GroupTypes> GroupTypeLookup = new Dictionary<string, GroupTypes>();
// initialize lookup table:
GroupTypeLookup.Add("OEM", TheGroup);
GroupTypeLookup.Add("CMB", TheOtherGroup);

You can then use GroupTypeLookup.TryGetValue() to look up a string when you read it.

What is the most efficient/elegant way to parse a flat table into a tree?

It's a quite old question, but as it's got many views I think it's worth to present an alternative, and in my opinion very elegant, solution.

In order to read a tree structure you can use recursive Common Table Expressions (CTEs). It gives a possibility to fetch whole tree structure at once, have the information about the level of the node, its parent node and order within children of the parent node.

Let me show you how this would work in PostgreSQL 9.1.

  1. Create a structure

    CREATE TABLE tree (
        id int  NOT NULL,
        name varchar(32)  NOT NULL,
        parent_id int  NULL,
        node_order int  NOT NULL,
        CONSTRAINT tree_pk PRIMARY KEY (id),
        CONSTRAINT tree_tree_fk FOREIGN KEY (parent_id) 
          REFERENCES tree (id) NOT DEFERRABLE
    );
    
    
    insert into tree values
      (0, 'ROOT', NULL, 0),
      (1, 'Node 1', 0, 10),
      (2, 'Node 1.1', 1, 10),
      (3, 'Node 2', 0, 20),
      (4, 'Node 1.1.1', 2, 10),
      (5, 'Node 2.1', 3, 10),
      (6, 'Node 1.2', 1, 20);
    
  2. Write a query

    WITH RECURSIVE 
    tree_search (id, name, level, parent_id, node_order) AS (
      SELECT 
        id, 
        name,
        0,
        parent_id, 
        1 
      FROM tree
      WHERE parent_id is NULL
    
      UNION ALL 
      SELECT 
        t.id, 
        t.name,
        ts.level + 1, 
        ts.id, 
        t.node_order 
      FROM tree t, tree_search ts 
      WHERE t.parent_id = ts.id 
    ) 
    SELECT * FROM tree_search 
    WHERE level > 0 
    ORDER BY level, parent_id, node_order;
    

    Here are the results:

     id |    name    | level | parent_id | node_order 
    ----+------------+-------+-----------+------------
      1 | Node 1     |     1 |         0 |         10
      3 | Node 2     |     1 |         0 |         20
      2 | Node 1.1   |     2 |         1 |         10
      6 | Node 1.2   |     2 |         1 |         20
      5 | Node 2.1   |     2 |         3 |         10
      4 | Node 1.1.1 |     3 |         2 |         10
    (6 rows)
    

    The tree nodes are ordered by a level of depth. In the final output we would present them in the subsequent lines.

    For each level, they are ordered by parent_id and node_order within the parent. This tells us how to present them in the output - link node to the parent in this order.

    Having such a structure it wouldn't be difficult to make a really nice presentation in HTML.

    Recursive CTEs are available in PostgreSQL, IBM DB2, MS SQL Server and Oracle.

    If you'd like to read more on recursive SQL queries, you can either check the documentation of your favourite DBMS or read my two articles covering this topic:

Build Eclipse Java Project from Command Line

Short answer. No. Eclipse does not have a command line switch like Visual Studio to build a project.

Find the least number of coins required that can make any change from 1 to 99 cents

A vb version

Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, _
                              ByVal e As System.EventArgs) Handles Button1.Click
        For saleAMT As Decimal = 0.01D To 0.99D Step 0.01D
            Dim foo As New CashDrawer(0, 0, 0)
            Dim chg As List(Of Money) = foo.MakeChange(saleAMT, 1D)
            Dim t As Decimal = 1 - saleAMT
            Debug.WriteLine(t.ToString("C2"))
            For Each c As Money In chg
                Debug.WriteLine(String.Format("{0} of {1}", c.Count.ToString("N0"), c.moneyValue.ToString("C2")))
            Next
        Next
    End Sub

    Class CashDrawer

        Private _drawer As List(Of Money)

        Public Sub New(Optional ByVal QTYtwoD As Integer = -1, _
                       Optional ByVal QTYoneD As Integer = -1, _
                       Optional ByVal QTYfifty As Integer = -1, _
                       Optional ByVal QTYquarters As Integer = -1, _
                       Optional ByVal QTYdimes As Integer = -1, _
                       Optional ByVal QTYnickels As Integer = -1, _
                       Optional ByVal QTYpennies As Integer = -1)
            _drawer = New List(Of Money)
            _drawer.Add(New Money(2D, QTYtwoD))
            _drawer.Add(New Money(1D, QTYoneD))
            _drawer.Add(New Money(0.5D, QTYfifty))
            _drawer.Add(New Money(0.25D, QTYquarters))
            _drawer.Add(New Money(0.1D, QTYdimes))
            _drawer.Add(New Money(0.05D, QTYnickels))
            _drawer.Add(New Money(0.01D, QTYpennies))
        End Sub

        Public Function MakeChange(ByVal SaleAmt As Decimal, _
                                   ByVal amountTendered As Decimal) As List(Of Money)
            Dim change As Decimal = amountTendered - SaleAmt
            Dim rv As New List(Of Money)
            For Each c As Money In Me._drawer
                change -= (c.NumberOf(change) * c.moneyValue)
                If c.Count > 0 Then
                    rv.Add(c)
                End If
            Next
            If change <> 0D Then Throw New ArithmeticException
            Return rv
        End Function
    End Class

    Class Money
        '-1 equals unlimited qty
        Private _qty As Decimal 'quantity in drawer
        Private _value As Decimal 'value money
        Private _count As Decimal = 0D

        Public Sub New(ByVal theValue As Decimal, _
                       ByVal theQTY As Decimal)
            Me._value = theValue
            Me._qty = theQTY
        End Sub

        ReadOnly Property moneyValue As Decimal
            Get
                Return Me._value
            End Get
        End Property

        Public Function NumberOf(ByVal theAmount As Decimal) As Decimal
            If (Me._qty > 0 OrElse Me._qty = -1) AndAlso Me._value <= theAmount Then
                Dim ct As Decimal = Math.Floor(theAmount / Me._value)
                If Me._qty <> -1D Then 'qty?
                    'limited qty
                    If ct > Me._qty Then 'enough 
                        'no
                        Me._count = Me._qty
                        Me._qty = 0D
                    Else
                        'yes
                        Me._count = ct
                        Me._qty -= ct
                    End If
                Else
                    'unlimited qty
                    Me._count = ct
                End If
            End If
            Return Me._count
        End Function

        ReadOnly Property Count As Decimal
            Get
                Return Me._count
            End Get
        End Property
    End Class
End Class

Uncaught TypeError: Cannot read property 'value' of null

I am unsure which of them is wrong because you did not provide your HTML, but one of these does not exist:

var str = document.getElementById("cal_preview").value;
var str1 = document.getElementById("year").value;
var str2 = document.getElementById("holiday").value;
var str3 = document.getElementById("cal_option").value;

There is either no element with the id cal_preview, year, holiday, cal_option, or some combination.

Therefore, JavaScript is unable to read the value of something that does not exist.

EDIT:

If you want to check that the element exists first, you could use an if statement for each:

var str,
element = document.getElementById('cal_preview');
if (element != null) {
    str = element.value;
}
else {
    str = null;
}

You could obviously change the else statement if you want or have no else statement at all, but that is all about preference.

How do I protect javascript files?

I know that this is the wrong time to be answering this question but i just thought of something

i know it might be stressful but atleast it might still work

Now the trick is to create a lot of server side encoding scripts, they have to be decodable(for example a script that replaces all vowels with numbers and add the letter 'a' to every consonant so that the word 'bat' becomes ba1ta) then create a script that will randomize between the encoding scripts and create a cookie with the name of the encoding script being used (quick tip: try not to use the actual name of the encoding script for the cookie for example if our cookie is name 'encoding_script_being_used' and the randomizing script chooses an encoding script named MD10 try not to use MD10 as the value of the cookie but 'encoding_script4567656' just to prevent guessing) then after the cookie has been created another script will check for the cookie named 'encoding_script_being_used' and get the value, then it will determine what encoding script is being used.

Now the reason for randomizing between the encoding scripts was that the server side language will randomize which script to use to decode your javascript.js and then create a session or cookie to know which encoding scripts was used then the server side language will also encode your javascript .js and put it as a cookie






so now let me summarize with an example

PHP randomizes between a list of encoding scripts and encrypts javascript.js then it create a cookie telling the client side language which encoding script was used then client side language decodes the javascript.js cookie(which is obviously encoded)

so people can't steal your code

but i would not advise this because

  1. it is a long process
  2. It is too stressful

How do I abort the execution of a Python script?

You can either use:

import sys
sys.exit(...)

or:

raise SystemExit(...)

The optional parameter can be an exit code or an error message. Both methods are identical. I used to prefer sys.exit, but I've lately switched to raising SystemExit, because it seems to stand out better among the rest of the code (due to the raise keyword).

How to limit google autocomplete results to City and Country only

try this

_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
<style type="text/css">_x000D_
   body {_x000D_
         font-family: sans-serif;_x000D_
         font-size: 14px;_x000D_
   }_x000D_
</style>_x000D_
_x000D_
<title>Google Maps JavaScript API v3 Example: Places Autocomplete</title>_x000D_
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&amp;libraries=places&region=in" type="text/javascript"></script>_x000D_
<script type="text/javascript">_x000D_
   function initialize() {_x000D_
      var input = document.getElementById('searchTextField');_x000D_
      var autocomplete = new google.maps.places.Autocomplete(input);_x000D_
   }_x000D_
   google.maps.event.addDomListener(window, 'load', initialize);_x000D_
</script>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
   <div>_x000D_
      <input id="searchTextField" type="text" size="50" placeholder="Enter a location" autocomplete="on">_x000D_
   </div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places" type="text/javascript"

Change this to: "region=in" (in=india)

"http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places&region=in" type="text/javascript"

How to generate a random number between 0 and 1?

Here's a general procedure for producing a random number in a specified range:

int randInRange(int min, int max)
{
  return min + (int) (rand() / (double) (RAND_MAX + 1) * (max - min + 1));
}

Depending on the PRNG algorithm being used, the % operator may result in a very non-random sequence of numbers.

Converting between datetime, Timestamp and datetime64

One option is to use str, and then to_datetime (or similar):

In [11]: str(dt64)
Out[11]: '2012-05-01T01:00:00.000000+0100'

In [12]: pd.to_datetime(str(dt64))
Out[12]: datetime.datetime(2012, 5, 1, 1, 0, tzinfo=tzoffset(None, 3600))

Note: it is not equal to dt because it's become "offset-aware":

In [13]: pd.to_datetime(str(dt64)).replace(tzinfo=None)
Out[13]: datetime.datetime(2012, 5, 1, 1, 0)

This seems inelegant.

.

Update: this can deal with the "nasty example":

In [21]: dt64 = numpy.datetime64('2002-06-28T01:00:00.000000000+0100')

In [22]: pd.to_datetime(str(dt64)).replace(tzinfo=None)
Out[22]: datetime.datetime(2002, 6, 28, 1, 0)

Copy data into another table

Try this:

INSERT INTO MyTable1 (Col1, Col2, Col4)
   SELECT Col1, Col2, Col3 FROM MyTable2

How to Get a Specific Column Value from a DataTable?

I suggest such way based on extension methods:

IEnumerable<Int32> countryIDs =
    dataTable
    .AsEnumerable()
    .Where(row => row.Field<String>("CountryName") == countryName)
    .Select(row => row.Field<Int32>("CountryID"));

System.Data.DataSetExtensions.dll needs to be referenced.

HttpWebRequest-The remote server returned an error: (400) Bad Request

400 Bad request Error will be thrown due to incorrect authentication entries.

  1. Check if your API URL is correct or wrong. Don't append or prepend spaces.
  2. Verify that your username and password are valid. Please check any spelling mistake(s) while entering.

Note: Mostly due to Incorrect authentication entries due to spell changes will occur 400 Bad request.

docker command not found even though installed with apt-get

SET UP THE REPOSITORY

For Ubuntu 14.04/16.04/16.10/17.04:

sudo add-apt-repository "deb [arch=amd64] \
     https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"

For Ubuntu 17.10:

sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu zesty stable"

Add Docker’s official GPG key:

$ curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -

Then install

$ sudo apt-get update && sudo apt-get -y install docker-ce

UTF-8: General? Bin? Unicode?

You should also be aware of the fact, that with utf8_general_ci when using a varchar field as unique or primary index inserting 2 values like 'a' and 'á' would give a duplicate key error.

How to delete SQLite database from Android programmatically

It's easy just type from your shell:

adb shell
cd /data/data
cd <your.application.java.package>
cd databases
su rm <your db name>.db

How do I compare version numbers in Python?

You can use the semver package to determine if a version satisfies a semantic version requirement. This is not the same as comparing two actual versions, but is a type of comparison.

For example, version 3.6.0+1234 should be the same as 3.6.0.

import semver
semver.match('3.6.0+1234', '==3.6.0')
# True

from packaging import version
version.parse('3.6.0+1234') == version.parse('3.6.0')
# False

from distutils.version import LooseVersion
LooseVersion('3.6.0+1234') == LooseVersion('3.6.0')
# False

Proxies with Python 'Requests' module

here is my basic class in python for the requests module with some proxy configs and stopwatch !

import requests
import time
class BaseCheck():
    def __init__(self, url):
        self.http_proxy  = "http://user:pw@proxy:8080"
        self.https_proxy = "http://user:pw@proxy:8080"
        self.ftp_proxy   = "http://user:pw@proxy:8080"
        self.proxyDict = {
                      "http"  : self.http_proxy,
                      "https" : self.https_proxy,
                      "ftp"   : self.ftp_proxy
                    }
        self.url = url
        def makearr(tsteps):
            global stemps
            global steps
            stemps = {}
            for step in tsteps:
                stemps[step] = { 'start': 0, 'end': 0 }
            steps = tsteps
        makearr(['init','check'])
        def starttime(typ = ""):
            for stemp in stemps:
                if typ == "":
                    stemps[stemp]['start'] = time.time()
                else:
                    stemps[stemp][typ] = time.time()
        starttime()
    def __str__(self):
        return str(self.url)
    def getrequests(self):
        g=requests.get(self.url,proxies=self.proxyDict)
        print g.status_code
        print g.content
        print self.url
        stemps['init']['end'] = time.time()
        #print stemps['init']['end'] - stemps['init']['start']
        x= stemps['init']['end'] - stemps['init']['start']
        print x


test=BaseCheck(url='http://google.com')
test.getrequests()

How do I to insert data into an SQL table using C# as well as implement an upload function?

using System;
using System.Data;
using System.Data.SqlClient;

namespace InsertingData
{
    class sqlinsertdata
    {
        static void Main(string[] args)
        {
            try
            { 
            SqlConnection conn = new SqlConnection("Data source=USER-PC; Database=Emp123;User Id=sa;Password=sa123");
            conn.Open();
                SqlCommand cmd = new SqlCommand("insert into <Table Name>values(1,'nagendra',10000);",conn);
                cmd.ExecuteNonQuery();
                Console.WriteLine("Inserting Data Successfully");
                conn.Close();
        }
            catch(Exception e)
            {
                Console.WriteLine("Exception Occre while creating table:" + e.Message + "\t"  + e.GetType());
            }
            Console.ReadKey();

    }
    }
}

Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 71 bytes)

I changed the memory limit from .htaccess and this problem got resolved.

I was trying to scan my website from one of the antivirus plugin and there I was getting this problem. I increased memory by pasting this in my .htaccess file in Wordpress folder:

php_value memory_limit 512M

After scan was over, I removed this line to make the size as it was before.

How can I suppress column header output for a single SQL statement?

Invoke mysql with the -N (the alias for -N is --skip-column-names) option:

mysql -N ...
use testdb;
select * from names;

+------+-------+
|    1 | pete  |
|    2 | john  |
|    3 | mike  |
+------+-------+
3 rows in set (0.00 sec)

Credit to ErichBSchulz for pointing out the -N alias.

To remove the grid (the vertical and horizontal lines) around the results use -s (--silent). Columns are separated with a TAB character.

mysql -s ...
use testdb;
select * from names;

id  name
1   pete
2   john
3   mike

To output the data with no headers and no grid just use both -s and -N.

mysql -sN ...

Changing column names of a data frame

Just to correct and slightly extend Scott Wilson answer.
You can use data.table's setnames function on data.frames too.

Do not expect speed up of the operation but you can expect the setnames to be more efficient for memory consumption as it updates column names by reference. This can be tracked with address function, see below.

library(data.table)
set.seed(123)
n = 1e8

df = data.frame(bad=sample(1:3, n, TRUE), worse=rnorm(n))
address(df)
#[1] "0x208f9f00"
colnames(df) <- c("good", "better")
address(df)
#[1] "0x208fa1d8"
rm(df)

dt = data.table(bad=sample(1:3, n, TRUE), worse=rnorm(n))
address(dt)
#[1] "0x535c830"
setnames(dt, c("good", "better"))
address(dt)
#[1] "0x535c830"
rm(dt)

So if you are hitting your memory limits you may consider to use this one instead.

When should I use curly braces for ES6 import?

The curly braces ({}) are used to import named bindings and the concept behind it is destructuring assignment

A simple demonstration of how import statement works with an example can be found in my own answer to a similar question at When do we use '{ }' in javascript imports?.

How to display errors for my MySQLi query?

Just simply add or die(mysqli_error($db)); at the end of your query, this will print the mysqli error.

 mysqli_query($db,"INSERT INTO stockdetails (`itemdescription`,`itemnumber`,`sellerid`,`purchasedate`,`otherinfo`,`numberofitems`,`isitdelivered`,`price`) VALUES ('$itemdescription','$itemnumber','$sellerid','$purchasedate','$otherinfo','$numberofitems','$numberofitemsused','$isitdelivered','$price')") or die(mysqli_error($db));

As a side note I'd say you are at risk of mysql injection, check here How can I prevent SQL injection in PHP?. You should really use prepared statements to avoid any risk.

Getting "conflicting types for function" in C, why?

You have to declare the function before you use it. If the function name appears before its declaration, C compiler will follow certain rules and makes the declaration itself. If it is wrong, you will get that error.

You have two options: (1) define it before you use it, or (2) use forward declaration without implementation. For example:

char *do_something(char *dest, const char *src);

Note the semicolon at the end.

Read and write to binary files in C?

I'm quite happy with my "make a weak pin storage program" solution. Maybe it will help people who need a very simple binary file IO example to follow.

$ ls
WeakPin  my_pin_code.pin  weak_pin.c
$ ./WeakPin
Pin: 45 47 49 32
$ ./WeakPin 8 2
$ Need 4 ints to write a new pin!
$./WeakPin 8 2 99 49
Pin saved.
$ ./WeakPin
Pin: 8 2 99 49
$
$ cat weak_pin.c
// a program to save and read 4-digit pin codes in binary format

#include <stdio.h>
#include <stdlib.h>

#define PIN_FILE "my_pin_code.pin"

typedef struct { unsigned short a, b, c, d; } PinCode;


int main(int argc, const char** argv)
{
    if (argc > 1)  // create pin
    {
        if (argc != 5)
        {
            printf("Need 4 ints to write a new pin!\n");
            return -1;
        }
        unsigned short _a = atoi(argv[1]);
        unsigned short _b = atoi(argv[2]);
        unsigned short _c = atoi(argv[3]);
        unsigned short _d = atoi(argv[4]);
        PinCode pc;
        pc.a = _a; pc.b = _b; pc.c = _c; pc.d = _d;
        FILE *f = fopen(PIN_FILE, "wb");  // create and/or overwrite
        if (!f)
        {
            printf("Error in creating file. Aborting.\n");
            return -2;
        }

        // write one PinCode object pc to the file *f
        fwrite(&pc, sizeof(PinCode), 1, f);  

        fclose(f);
        printf("Pin saved.\n");
        return 0;
    }

    // else read existing pin
    FILE *f = fopen(PIN_FILE, "rb");
    if (!f)
    {
        printf("Error in reading file. Abort.\n");
        return -3;
    }
    PinCode pc;
    fread(&pc, sizeof(PinCode), 1, f);
    fclose(f);

    printf("Pin: ");
    printf("%hu ", pc.a);
    printf("%hu ", pc.b);
    printf("%hu ", pc.c);
    printf("%hu\n", pc.d);
    return 0;
}
$

How to run a bash script from C++ program

Use the system function.

system("myfile.sh"); // myfile.sh should be chmod +x

How can I see the raw SQL queries Django is running?

Django-extensions have a command shell_plus with a parameter print-sql

./manage.py shell_plus --print-sql

In django-shell all executed queries will be printed

Ex.:

User.objects.get(pk=1)
SELECT "auth_user"."id",
       "auth_user"."password",
       "auth_user"."last_login",
       "auth_user"."is_superuser",
       "auth_user"."username",
       "auth_user"."first_name",
       "auth_user"."last_name",
       "auth_user"."email",
       "auth_user"."is_staff",
       "auth_user"."is_active",
       "auth_user"."date_joined"
FROM "auth_user"
WHERE "auth_user"."id" = 1

Execution time: 0.002466s [Database: default]

<User: username>

Change Background color (css property) using Jquery

The code below will change the div to blue.

<script>
 $(document).ready(function(){ 
   $("#co").click({
            $("body").css("background-color","blue");
      });
    }); 
</script>
<body>
      <div id="co">hello</div>
</body>

How to get URI from an asset File?

Yeah you can't access your drive folder from you android phone or emulator because your computer and android are two different OS.I would go for res folder of android because it has good resources management methods. Until and unless you have very good reason to put you file in assets folder. Instead You can do this

try {
      Resources res = getResources();
      InputStream in_s = res.openRawResource(R.raw.yourfile);

      byte[] b = new byte[in_s.available()];
      in_s.read(b);
      String str = new String(b);
    } catch (Exception e) {
      Log.e(LOG_TAG, "File Reading Error", e);
 }

URL Encode a string in jQuery for an AJAX request

Try encodeURIComponent.

Encodes a Uniform Resource Identifier (URI) component by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters).

Example:

var encoded = encodeURIComponent(str);

How can I reuse a navigation bar on multiple pages?

This is what helped me. My navigation bar is in the body tag. Entire code for navigation bar is in nav.html file (without any html or body tag, only the code for navigation bar). In the target page, this goes in the head tag:

<script src="https://code.jquery.com/jquery-1.10.2.js"></script>

Then in the body tag, a container is made with an unique id and a javascript block to load the nav.html into the container, as follows:

<!--Navigation bar-->
<div id="nav-placeholder">

</div>

<script>
$(function(){
  $("#nav-placeholder").load("nav.html");
});
</script>
<!--end of Navigation bar-->

Cannot find vcvarsall.bat when running a Python script

After installation of Visual Studio Community 2015 Edition on Windows 10 64 bit. This error did not go. Then I install Microsoft Visual C++ Compiler for Python 2.7. Since it requires vcvarsall.bat file. This file is no where in Visual studio Community 2015, but it was in Microsoft Visual C++ Compiler for Python 2.7. I also added its path into my environment variables but it also did not work. Then I un-install python 3.4.2 and deleted all the folders of python, and installed python 2.7. Finally I run pip using powershell and I was able to install my required package i.e. flask-user, by using.

pip install flask-user

How to split one text file into multiple *.txt files?

Regardless to what is said above, on my ubuntu 16 i had to do :

> split -b 10M -d  system.log system_split.log 

Please note the space between -b and the value

Cannot open local file - Chrome: Not allowed to load local resource

You just need to replace all image network paths to byte strings in stored Encoded HTML string. For this you required HtmlAgilityPack to convert Html string to Html document. https://www.nuget.org/packages/HtmlAgilityPack

Find Below code to convert each image src network path(or local path) to byte sting. It will definitely display all images with network path(or local path) in IE,chrome and firefox.

string encodedHtmlString = Emailmodel.DtEmailFields.Rows[0]["Body"].ToString();

// Decode the encoded string.
StringWriter myWriter = new StringWriter();
HttpUtility.HtmlDecode(encodedHtmlString, myWriter);
string DecodedHtmlString = myWriter.ToString();

//find and replace each img src with byte string
HtmlDocument document = new HtmlDocument();
document.LoadHtml(DecodedHtmlString);
document.DocumentNode.Descendants("img")
    .Where(e =>
    {
        string src = e.GetAttributeValue("src", null) ?? "";
        return !string.IsNullOrEmpty(src);//&& src.StartsWith("data:image");
    })
    .ToList()
    .ForEach(x =>
        {
        string currentSrcValue = x.GetAttributeValue("src", null);                                
        string filePath = Path.GetDirectoryName(currentSrcValue) + "\\";
        string filename = Path.GetFileName(currentSrcValue);
        string contenttype = "image/" + Path.GetExtension(filename).Replace(".", "");
        FileStream fs = new FileStream(filePath + filename, FileMode.Open, FileAccess.Read);
        BinaryReader br = new BinaryReader(fs);
        Byte[] bytes = br.ReadBytes((Int32)fs.Length);
        br.Close();
        fs.Close();
        x.SetAttributeValue("src", "data:" + contenttype + ";base64," + Convert.ToBase64String(bytes));                                
    });

string result = document.DocumentNode.OuterHtml;
//Encode HTML string
string myEncodedString = HttpUtility.HtmlEncode(result);

Emailmodel.DtEmailFields.Rows[0]["Body"] = myEncodedString;

jQuery function after .append

You've got many valid answers in here but none of them really tells you why it works as it does.

In JavaScript commands are executed one at a time, synchronously in the order they come, unless you explicitly tell them to be asynchronous by using a timeout or interval.

This means that your .append method will be executed and nothing else (disregarding any potential timeouts or intervals that may exist) will execute until that method have finished its job.

To summarize, there's no need for a callback since .append will be run synchronously.

How to start mongodb shell?

Both the mongod (database server) and mongo (database client shell) programs are command line programs and each expects to be run in its own command line session. So, after starting the server (as you did with "./mongod") you should open a second command line session and run "./mongo" in it to give you a command line shell for talking to the server.

Jackson and generic type reference

'JavaType' works !! I was trying to unmarshall (deserialize) a List in json String to ArrayList java Objects and was struggling to find a solution since days.
Below is the code that finally gave me solution. Code:

JsonMarshallerUnmarshaller<T> {
    T targetClass;

    public ArrayList<T> unmarshal(String jsonString) {
        ObjectMapper mapper = new ObjectMapper();

        AnnotationIntrospector introspector = new JacksonAnnotationIntrospector();
        mapper.getDeserializationConfig()
            .withAnnotationIntrospector(introspector);

        mapper.getSerializationConfig()
            .withAnnotationIntrospector(introspector);
        JavaType type = mapper.getTypeFactory().
            constructCollectionType(
                ArrayList.class, 
                targetclass.getClass());

        try {
            Class c1 = this.targetclass.getClass();
            Class c2 = this.targetclass1.getClass();
            ArrayList<T> temp = (ArrayList<T>) 
                mapper.readValue(jsonString,  type);
            return temp ;
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null ;
    }  
}

Implement a simple factory pattern with Spring 3 annotations

You are right, by creating object manually you are not letting Spring to perform autowiring. Consider managing your services by Spring as well:

@Component
public class MyServiceFactory {

    @Autowired
    private MyServiceOne myServiceOne;

    @Autowired
    private MyServiceTwo myServiceTwo;

    @Autowired
    private MyServiceThree myServiceThree;

    @Autowired
    private MyServiceDefault myServiceDefault;

    public static MyService getMyService(String service) {
        service = service.toLowerCase();

        if (service.equals("one")) {
            return myServiceOne;
        } else if (service.equals("two")) {
            return myServiceTwo;
        } else if (service.equals("three")) {
            return myServiceThree;
        } else {
            return myServiceDefault;
        }
    }
}

But I would consider the overall design to be rather poor. Wouldn't it better to have one general MyService implementation and pass one/two/three string as extra parameter to checkStatus()? What do you want to achieve?

@Component
public class MyServiceAdapter implements MyService {

    @Autowired
    private MyServiceOne myServiceOne;

    @Autowired
    private MyServiceTwo myServiceTwo;

    @Autowired
    private MyServiceThree myServiceThree;

    @Autowired
    private MyServiceDefault myServiceDefault;

    public boolean checkStatus(String service) {
        service = service.toLowerCase();

        if (service.equals("one")) {
            return myServiceOne.checkStatus();
        } else if (service.equals("two")) {
            return myServiceTwo.checkStatus();
        } else if (service.equals("three")) {
            return myServiceThree.checkStatus();
        } else {
            return myServiceDefault.checkStatus();
        }
    }
}

This is still poorly designed because adding new MyService implementation requires MyServiceAdapter modification as well (SRP violation). But this is actually a good starting point (hint: map and Strategy pattern).

Put search icon near textbox using bootstrap

You can do it in pure CSS using the :after pseudo-element and getting creative with the margins.

Here's an example, using Font Awesome for the search icon:

_x000D_
_x000D_
.search-box-container input {_x000D_
  padding: 5px 20px 5px 5px;_x000D_
}_x000D_
_x000D_
.search-box-container:after {_x000D_
    content: "\f002";_x000D_
    font-family: FontAwesome;_x000D_
    margin-left: -25px;_x000D_
    margin-right: 25px;_x000D_
}
_x000D_
<!-- font awesome -->_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
_x000D_
_x000D_
<div class="search-box-container">_x000D_
  <input type="text" placeholder="Search..."  />_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to correctly set the ORACLE_HOME variable on Ubuntu 9.x?

Usually the msb file not found problems are the result of an environment setting problem, but in your case I'm a little suspicious of the installation (I've never used the apt-get + configure method).

To check the sanity of the installation:

  • ORACLE_HOME should be set to a directory path one level above the bin directory where sqlplus executable is found.
  • There should some .msb files under $ORACLE_HOME/sqlplus/mesg
  • There should be hundreds (not sure of the number with XE) of .msb files under $ORACLE_HOME (try find $ORACLE_HOME -name "*.msb" -print to show them)
  • Your PATH should include $ORACLE_HOME/bin.
  • All files under ORACLE_HOME should be owned by user:oracle group:dba.

Rename multiple files based on pattern in Unix

Another possible parameter expansion:

for f in fgh*; do mv -- "$f" "jkl${f:3}"; done

How to Define Callbacks in Android?

No need to define a new interface when you can use an existing one: android.os.Handler.Callback. Pass an object of type Callback, and invoke callback's handleMessage(Message msg).

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

Try the JavaScript in operator.

if ('key' in myObj)

And the inverse.

if (!('key' in myObj))

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

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

myObj.hasOwnProperty('key')

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

python filter list of dictionaries based on key value

Use filter, or if the number of dictionaries in exampleSet is too high, use ifilter of the itertools module. It would return an iterator, instead of filling up your system's memory with the entire list at once:

from itertools import ifilter
for elem in ifilter(lambda x: x['type'] in keyValList, exampleSet):
    print elem

percentage of two int?

If you don't add .0f it will be treated like it is an integer, and an integer division is a lot different from a floating point division indeed :)

float percent = (n * 100.0f) / v;

If you need an integer out of this you can of course cast the float or the double again in integer.

int percent = (int)((n * 100.0f) / v);

If you know your n value is less than 21474836 (that is (2 ^ 31 / 100)), you can do all using integer operations.

int percent = (n * 100) / v;

If you get NaN is because wathever you do you cannot divide for zero of course... it doesn't make sense.

Select all from table with Laravel and Eloquent

Query
// Select all data of model table
Model::all();
// Select all data of model table
Model::get();

Model::where('foo', '=', 'bar')->get();

Model::find(1);
Model::find([1, 2, 3]);
Model::findOrFail(1);

How to loop through file names returned by find?

You can put the filenames returned by find into an array like this:

array=()
while IFS=  read -r -d ''; do
    array+=("$REPLY")
done < <(find . -name '*.txt' -print0)

Now you can just loop through the array to access individual items and do whatever you want with them.

Note: It's white space safe.

Run a .bat file using python code

  1. It is better to write .bat file in such way that its running is not dependent on current working directory, i.e. I recommend to put this line at the beginning of .bat file:

    cd "%~dp0"
    
  2. Enclose filepath of .bat file in double quotes, i.e.:

    os.system('"D:\\x\\so here can be spaces\\otr.bat" ["<arg0>" ["<arg1>" ...]]')
    
  3. To save output of some batch command in another file you can use usual redirection syntax, for example:

    os.system('"...bat" > outputfilename.txt')
    

    Or directly in your .bat file:

    Application.exe work.xml > outputfilename.txt
    

The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties

I have the same issue with Entity Framework 6.1.3

But with different scenario. My model property is of type nullable DateTime

DateTime? CreatedDate { get; set; }

So I need to query on today's date to check all the record, so this what works for me. Which means I need to truncate both records to get the proper query on DbContext:

Where(w => DbFunctions.TruncateTime(w.CreatedDate) == DbFunctions.TruncateTime(DateTime.Now);

How to extract a string using JavaScript Regex?

You need to use the m flag:

multiline; treat beginning and end characters (^ and $) as working over multiple lines (i.e., match the beginning or end of each line (delimited by \n or \r), not only the very beginning or end of the whole input string)

Also put the * in the right place:

"DATE:20091201T220000\r\nSUMMARY:Dad's birthday".match(/^SUMMARY\:(.*)$/gm);
//------------------------------------------------------------------^    ^
//-----------------------------------------------------------------------|

Check if string contains only letters in javascript

The fastest way is to check if there is a non letter:

if (!/[^a-zA-Z]/.test(word))

how we add or remove readonly attribute from textbox on clicking radion button in cakephp using jquery?

In your Case you can write the following jquery code:

$(document).ready(function(){

   $('.staff_on_site').click(function(){

     var rBtnVal = $(this).val();

     if(rBtnVal == "yes"){
         $("#no_of_staff").attr("readonly", false); 
     }
     else{ 
         $("#no_of_staff").attr("readonly", true); 
     }
   });
});

Here is the Fiddle: http://jsfiddle.net/P4QWx/3/

Add a properties file to IntelliJ's classpath

Faced a similar challenge adding files with .ini extensions to the classpath. Found this answer, which is to add it to Preferences -> Compiler -> Resource Patterns -> [...] ;*.ini

How can I set the form action through JavaScript?

You cannot invoke JavaScript functions in standard HTML attributes other than onXXX. Just assign it during window onload.

<script type="text/javascript">
    window.onload = function() {
        document.myform.action = get_action();
    }

    function get_action() {
        return form_action;
    }
</script>

<form name="myform">
    ...
</form>

You see that I've given the form a name, so that it's easily accessible in document.

Alternatively, you can also do it during submit event:

<script type="text/javascript">
    function get_action(form) {
        form.action = form_action;
    }
</script>

<form onsubmit="get_action(this);">
    ...
</form>

How to center cell contents of a LaTeX table whose columns have fixed widths?

\usepackage{array} in the preamble

then this:

\begin{tabular}{| >{\centering\arraybackslash}m{1in} | >{\centering\arraybackslash}m{1in} |}

note that the "m" for fixed with column is provided by the array package, and will give you vertical centering (if you don't want this just go back to "p"

How do I set the default page of my application in IIS7?

On IIS Manager--> Http view--> double click on Default and write the name of your desired startup page, Thats it

Allowed characters in filename

To be more precise about Mac OS X (now called MacOS) / in the Finder is interpreted to : in the Unix file system.

This was done for backward compatibility when Apple moved from Classic Mac OS.

It is legitimate to use a / in a file name in the Finder, looking at the same file in the terminal it will show up with a :.

And it works the other way around too: you can't use a / in a file name with the terminal, but a : is OK and will show up as a / in the Finder.

Some applications may be more restrictive and prohibit both characters to avoid confusion or because they kept logic from previous Classic Mac OS or for name compatibility between platforms.

How to check if a String contains only ASCII?

Iterate through the string and make sure all the characters have a value less than 128.

Java Strings are conceptually encoded as UTF-16. In UTF-16, the ASCII character set is encoded as the values 0 - 127 and the encoding for any non ASCII character (which may consist of more than one Java char) is guaranteed not to include the numbers 0 - 127

How to get a Char from an ASCII Character Code in c#

You can simply write:

char c = (char) 2;

or

char c = Convert.ToChar(2);

or more complex option for ASCII encoding only

char[] characters = System.Text.Encoding.ASCII.GetChars(new byte[]{2});
char c = characters[0];

Is it safe to delete a NULL pointer?

It is safe unless you overloaded the delete operator. if you overloaded the delete operator and not handling null condition then it is not safe at all.

Where does Vagrant download its .box files to?

To change the Path, you can set a new Path to an Enviroment-Variable named: VAGRANT_HOME

export VAGRANT_HOME=my/new/path/goes/here/

Thats maybe nice if you want to have those vagrant-Images on another HDD.

More Information here in the Documentations: http://docs.vagrantup.com/v2/other/environmental-variables.html

Best way to copy a database (SQL Server 2008)

Its hard to detach your production dB or other running dB's and deal with that downtime, so I almost always use a Backup / restore method.

If you also want to make sure to keep your login's in sync check out the MS KB article on using the stored proc sp_help_revlogin to do this.

Is there any method to get the URL without query string?

To get every part of the URL except for the query:

var url = (location.origin).concat(location.pathname).concat(location.hash);

Note that this includes the hash as well, if there is one (I'm aware there's no hash in your example URL, but I included that aspect for completeness). To eliminate the hash, simply exclude .concat(location.hash).

It's better practice to use concat to join Javascript strings together (rather than +): in some situations it avoids problems such as type confusion.

Change the background color of a row in a JTable

This is basically as simple as repainting the table. I haven't found a way to selectively repaint just one row/column/cell however.

In this example, clicking on the button changes the background color for a row and then calls repaint.

public class TableTest {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final Color[] rowColors = new Color[] {
                randomColor(), randomColor(), randomColor()
        };
        final JTable table = new JTable(3, 3);
        table.setDefaultRenderer(Object.class, new TableCellRenderer() {
            @Override
            public Component getTableCellRendererComponent(JTable table,
                    Object value, boolean isSelected, boolean hasFocus,
                    int row, int column) {
                JPanel pane = new JPanel();
                pane.setBackground(rowColors[row]);
                return pane;
            }
        });
        frame.setLayout(new BorderLayout());

        JButton btn = new JButton("Change row2's color");
        btn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                rowColors[1] = randomColor();
                table.repaint();
            }
        });

        frame.add(table, BorderLayout.NORTH);
        frame.add(btn, BorderLayout.SOUTH);
        frame.pack();
        frame.setVisible(true);
    }

    private static Color randomColor() {
        Random rnd = new Random();
        return new Color(rnd.nextInt(256),
                rnd.nextInt(256), rnd.nextInt(256));
    }
}

Jquery post, response in new window

Accepted answer doesn't work with "use strict" as the "with" statement throws an error. So instead:

$.post(url, function (data) {
    var w = window.open('about:blank', 'windowname');
    w.document.write(data);
    w.document.close();
});

Also, make sure 'windowname' doesn't have any spaces in it because that will fail in IE :)

Swift convert unix time to date and time

To get the date to show as the current time zone I used the following.

if let timeResult = (jsonResult["dt"] as? Double) {
     let date = NSDate(timeIntervalSince1970: timeResult)
     let dateFormatter = NSDateFormatter()
     dateFormatter.timeStyle = NSDateFormatterStyle.MediumStyle //Set time style
     dateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle //Set date style
     dateFormatter.timeZone = NSTimeZone()
     let localDate = dateFormatter.stringFromDate(date)
}

Swift 3.0 Version

if let timeResult = (jsonResult["dt"] as? Double) {
    let date = Date(timeIntervalSince1970: timeResult)
    let dateFormatter = DateFormatter()
    dateFormatter.timeStyle = DateFormatter.Style.medium //Set time style
    dateFormatter.dateStyle = DateFormatter.Style.medium //Set date style
    dateFormatter.timeZone = self.timeZone
    let localDate = dateFormatter.string(from: date)                     
}

Swift 5

if let timeResult = (jsonResult["dt"] as? Double) {
    let date = Date(timeIntervalSince1970: timeResult)
    let dateFormatter = DateFormatter()
    dateFormatter.timeStyle = DateFormatter.Style.medium //Set time style
    dateFormatter.dateStyle = DateFormatter.Style.medium //Set date style
    dateFormatter.timeZone = .current
    let localDate = dateFormatter.string(from: date)                                
}

raw_input function in Python

The raw_input() function reads a line from input (i.e. the user) and returns a string

Python v3.x as raw_input() was renamed to input()

PEP 3111: raw_input() was renamed to input(). That is, the new input() function reads a line from sys.stdin and returns it with the trailing newline stripped. It raises EOFError if the input is terminated prematurely. To get the old behavior of input(), use eval(input()).

Ref: Docs Python 3

removing table border

Most of the time your background color is different from the background of your table. Since there are spaces between the cells, those spaces will create the illusion of lines with the color of the background behind the table.

The solution is to get rid of those spaces.

Inside the table tag write:

cellspacing="0"

How to Install Font Awesome in Laravel Mix

How to Install Font Awesome 5 in Laravel 5.3 - 5.6 (The Right Way)

Build your webpack.mix.js configuration.

mix.setResourceRoot("../");

mix.js('resources/assets/js/app.js', 'public/js')
   .sass('resources/assets/sass/app.scss', 'public/css');

Install the latest free version of Font Awesome via a package manager like npm.

npm install @fortawesome/fontawesome-free

This dependency entry should now be in your package.json.

// Font Awesome
"dependencies": {
    "@fortawesome/fontawesome-free": "^5.15.2",

In your main SCSS file /resources/assets/sass/app.scss, import one or more styles.

@import '~@fortawesome/fontawesome-free/scss/fontawesome';
@import '~@fortawesome/fontawesome-free/scss/regular';
@import '~@fortawesome/fontawesome-free/scss/solid';
@import '~@fortawesome/fontawesome-free/scss/brands';

Compile your assets and produce a minified, production-ready build.

npm run production

Finally, reference your generated CSS file in your Blade template/layout.

<link type="text/css" rel="stylesheet" href="{{ mix('css/app.css') }}">

How to Install Font Awesome 5 with Laravel Mix 6 in Laravel 8 (The Right Way)

https://gist.github.com/karlhillx/89368bfa6a447307cbffc59f4e10b621

how to get data from selected row from datagridview

To get the cell value, you need to read it directly from DataGridView1 using e.RowIndex and e.ColumnIndex properties.

Eg:

Private Sub DataGridView1_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
   Dim value As Object = DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value

   If IsDBNull(value) Then 
      TextBox1.Text = "" ' blank if dbnull values
   Else
      TextBox1.Text = CType(value, String)
   End If
End Sub

How do I remove background-image in css?

div#a {
  background-image: none !important;
}

Although the "!important" might not be necessary, because "div#a" has a higher specificity than just "div".

How do I send a POST request as a JSON?

Here is an example of how to use urllib.request object from Python standard library.

import urllib.request
import json
from pprint import pprint

url = "https://app.close.com/hackwithus/3d63efa04a08a9e0/"

values = {
    "first_name": "Vlad",
    "last_name": "Bezden",
    "urls": [
        "https://twitter.com/VladBezden",
        "https://github.com/vlad-bezden",
    ],
}


headers = {
    "Content-Type": "application/json",
    "Accept": "application/json",
}

data = json.dumps(values).encode("utf-8")
pprint(data)

try:
    req = urllib.request.Request(url, data, headers)
    with urllib.request.urlopen(req) as f:
        res = f.read()
    pprint(res.decode())
except Exception as e:
    pprint(e)

What is the proper way to format a multi-line dict in Python?

I use #3. Same for long lists, tuples, etc. It doesn't require adding any extra spaces beyond the indentations. As always, be consistent.

mydict = {
    "key1": 1,
    "key2": 2,
    "key3": 3,
}

mylist = [
    (1, 'hello'),
    (2, 'world'),
]

nested = {
    a: [
        (1, 'a'),
        (2, 'b'),
    ],
    b: [
        (3, 'c'),
        (4, 'd'),
    ],
}

Similarly, here's my preferred way of including large strings without introducing any whitespace (like you'd get if you used triple-quoted multi-line strings):

data = (
    "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABG"
    "l0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAEN"
    "xBRpFYmctaKCfwrBSCrRLuL3iEW6+EEUG8XvIVjYWNgJdhFjIX"
    "rz6pKtPB5e5rmq7tmxk+hqO34e1or0yXTGrj9sXGs1Ib73efh1"
    "AAAABJRU5ErkJggg=="
)

Regular expression for matching HH:MM time format

The below regex will help to validate hh:mm format

^([0-1][0-9]|2[0-3]):[0-5][0-9]$

Find file in directory from command line

I use ls -R, piped to grep like this:

$ ls -R | grep -i "pattern"

where -R means recursively list all the files, and -i means case-insensitive. Finally, the patter could be something like this: "std*.h" or "^io" (anything that starts with "io" in the file name)

Modal width (increase)

This was the solution that worked for me:

_x000D_
_x000D_
.modal{_x000D_
 padding: 0 !important;_x000D_
}_x000D_
.modal-dialog {_x000D_
  max-width: 80% !important;_x000D_
  height: 100%;_x000D_
  padding: 0;_x000D_
  margin: 0;_x000D_
}_x000D_
_x000D_
.modal-content {_x000D_
  border-radius: 0 !important;_x000D_
  height: 100%;_x000D_
}
_x000D_
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<a href="#" class="menu-toggler" data-toggle="modal" data-target=".bd-example-modal-lg">Menu</a>_x000D_
_x000D_
<div class="modal mobile-nav-modal fade bd-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">_x000D_
  <div class="modal-dialog modal-lg">_x000D_
    <div class="modal-content">_x000D_
      <a href="#" class="" data-dismiss="modal">Close Menu</a>_x000D_
_x000D_
      <nav class="modal-nav">_x000D_
        <ul>_x000D_
          <li><a data-toggle="collapse" href="#collapseExample" role="button">Shop</a>_x000D_
            <div class="collapse" id="collapseExample">_x000D_
              <ul>_x000D_
                <li><a href="#">List 1</a></li>_x000D_
                <li><a href="#">List 2</a></li>_x000D_
                <li><a href="#">List 3</a></li>_x000D_
              </ul>_x000D_
              <ul>_x000D_
                <li><a href="#">List 1</a></li>_x000D_
                <li><a href="#">List 2</a></li>_x000D_
                <li><a href="#">List 3</a></li>_x000D_
              </ul>_x000D_
            </div>_x000D_
          </li>_x000D_
          <li><a href="#">Made To Order</a></li>_x000D_
          <li><a href="#">Heritage</a></li>_x000D_
          <li><a href="#">Style & Fit</a></li>_x000D_
          <li><a href="#">Sign In</a></li>_x000D_
        </ul>_x000D_
      </nav>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I insert a JPEG image into a python Tkinter window?

from tkinter import *
from PIL import ImageTk, Image

window = Tk()
window.geometry("1000x300")

path = "1.jpg"

image = PhotoImage(Image.open(path))

panel = Label(window, image = image)

panel.pack()

window.mainloop()

Maven plugins can not be found in IntelliJ

The red with warnings maven-site-plugin resolved after the build site Lifecycle:

enter image description here

My IntelliJ version is Community 2017.2.4

How to configure static content cache per folder and extension in IIS7?

You can do it on a per file basis. Use the path attribute to include the filename

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <location path="YourFileNameHere.xml">
        <system.webServer>
            <staticContent>
                <clientCache cacheControlMode="DisableCache" />
            </staticContent>
        </system.webServer>
    </location>
</configuration>

How do you strip a character out of a column in SQL Server?

UPDATE [TableName]
SET [ColumnName] = Replace([ColumnName], '[StringToRemove]', '[Replacement]')

In your instance it would be

UPDATE [TableName]
SET [ColumnName] = Replace([ColumnName], '[StringToRemove]', '')

Because there is no replacement (you want to get rid of it).

This will run on every row of the specified table. No need for a WHERE clause unless you want to specify only certain rows.

What is an idempotent operation?

An idempotent operation is an operation, action, or request that can be applied multiple times without changing the result, i.e. the state of the system, beyond the initial application.

EXAMPLES (WEB APP CONTEXT):

IDEMPOTENT: Making multiple identical requests has the same effect as making a single request. A message in an email messaging system is opened and marked as "opened" in the database. One can open the message many times but this repeated action will only ever result in that message being in the "opened" state. This is an idempotent operation. The first time one PUTs an update to a resource using information that does not match the resource (the state of the system), the state of the system will change as the resource is updated. If one PUTs the same update to a resource repeatedly then the information in the update will match the information already in the system upon every PUT, and no change to the state of the system will occur. Repeated PUTs with the same information are idempotent: the first PUT may change the state of the system, subsequent PUTs should not.

NON-IDEMPOTENT: If an operation always causes a change in state, like POSTing the same message to a user over and over, resulting in a new message sent and stored in the database every time, we say that the operation is NON-IDEMPOTENT.

NULLIPOTENT: If an operation has no side effects, like purely displaying information on a web page without any change in a database (in other words you are only reading the database), we say the operation is NULLIPOTENT. All GETs should be nullipotent.

When talking about the state of the system we are obviously ignoring hopefully harmless and inevitable effects like logging and diagnostics.

Sending data from HTML form to a Python script in Flask

The form tag needs some attributes set:

  1. action: The URL that the form data is sent to on submit. Generate it with url_for. It can be omitted if the same URL handles showing the form and processing the data.
  2. method="post": Submits the data as form data with the POST method. If not given, or explicitly set to get, the data is submitted in the query string (request.args) with the GET method instead.
  3. enctype="multipart/form-data": When the form contains file inputs, it must have this encoding set, otherwise the files will not be uploaded and Flask won't see them.

The input tag needs a name parameter.

Add a view to handle the submitted data, which is in request.form under the same key as the input's name. Any file inputs will be in request.files.

@app.route('/handle_data', methods=['POST'])
def handle_data():
    projectpath = request.form['projectFilepath']
    # your code
    # return a response

Set the form's action to that view's URL using url_for:

<form action="{{ url_for('handle_data') }}" method="post">
    <input type="text" name="projectFilepath">
    <input type="submit">
</form>

Creating a UICollectionView programmatically

Apple Docs:

- (id)initWithFrame:(CGRect)frame 
      collectionViewLayout:(UICollectionViewLayout *)layoutParameters

Use this method when initializing a collection view object programmatically. If you specify nil for the layout parameter, you must assign a layout object to the collectionViewLayout property before displaying the collection view onscreen. If you do not, the collection view will be unable to present any items onscreen.

This method is the designated initializer.

This method is used to initialize the UICollectionView. here you provide frame and a UICollectionViewLayout object.

UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];

At the end, add UICollectionView as a subview to your view.

Now collection view is added pro grammatically. You can go on learning.
Happy learning!! Hope it helps you.

Bootstrap Element 100% Width

Sometimes it's not possible to close the content container. The solution we are using is a bit different but prevent a overflow because of the firefox scrollbar size!

.full-width {
 margin-top: 15px;
 margin-bottom: 15px;
 position: relative;
 width: calc(100vw - 10px);
 margin-left: calc(-50vw + 5px);
 left: 50%;
}

Here is a example: https://jsfiddle.net/RubbelDeKatz/wvt9253q

How to add http:// if it doesn't exist in the URL

Scan the string for ://. If it does not have it, prepend http:// to the string... Everything else just use the string as is.

This will work unless you have a rubbish input string.

Java: Array with loop

If your array of numbers always is starting with 1 and ending with X then you could use the following formula: sum = x * (x+1) / 2

from 1 till 100 the sum would be 100 * 101 / 2 = 5050

Setting public class variables

Inside class Testclass:

public function __construct($new_value)
{
    $this->testvar = $new_value;
}

Objective-C: Extract filename from path string

Taken from the NSString reference, you can use :

NSString *theFileName = [[string lastPathComponent] stringByDeletingPathExtension];

The lastPathComponent call will return thefile.ext, and the stringByDeletingPathExtension will remove the extension suffix from the end.

OS X: equivalent of Linux's wget

brew install wget

Homebrew is a package manager for OSX analogous to yum, apt-get, choco, emerge, etc. Be aware that you will also need to install Xcode and the Command Line Tools. Virtually anyone who uses the command line in OSX will want to install these things anyway.

If you can't or don't want to use homebrew, you could also:

Install wget manually:

curl -# "http://ftp.gnu.org/gnu/wget/wget-1.17.1.tar.xz" -o "wget.tar.xz"
tar xf wget.tar.xz
cd wget-1.17.1
./configure --with-ssl=openssl -with-libssl-prefix=/usr/local/ssl && make -j8 && make install

Or, use a bash alias:

function _wget() { curl "${1}" -o $(basename "${1}") ; };
alias wget='_wget'

undefined reference to `WinMain@16'

To summarize the above post by Cheers and hth. - Alf, Make sure you have main() or WinMain() defined and g++ should do the right thing.

My problem was that main() was defined inside of a namespace by accident.

Import file size limit in PHPMyAdmin

I was facing the same problem where increasing max size in php.ini has no effect on wordpress and tried many solutions like -:

  1. Increase max size via functions.php
  2. Increase max size via .htaccess file.

The one that worked for me is adding max size in .htaccess file. It wasn't working with neither with php.ini file nor with functions.php file.

I just did add this code in .htaccess file and its done

php_value upload_max_filesize 64M
php_value post_max_size 64M
php_value max_execution_time 300
php_value max_input_time 300

NOTE: I did add above code in <IfModule> tag.

If php.ini file is not doing anything in changing size then try other 2 files for it and one of them will surely work for you.

READ THIS ARTICLE TO KNOW ABOUT ALL FILES IN WHICH YOU CAN INCREASE MAX SIZE

REST API error return good practices

As others have pointed, having a response entity in an error code is perfectly allowable.

Do remember that 5xx errors are server-side, aka the client cannot change anything to its request to make the request pass. If the client's quota is exceeded, that's definitly not a server error, so 5xx should be avoided.

How to get an HTML element's style values in javascript?

You can make function getStyles that'll take an element and other arguments are properties that's values you want.

const convertRestArgsIntoStylesArr = ([...args]) => {
    return args.slice(1);
}

const getStyles = function () {
    const args = [...arguments];
    const [element] = args;

    let stylesProps = [...args][1] instanceof Array ? args[1] : convertRestArgsIntoStylesArr(args);

    const styles = window.getComputedStyle(element);
    const stylesObj = stylesProps.reduce((acc, v) => {
        acc[v] = styles.getPropertyValue(v);
        return acc;
    }, {});

    return stylesObj;
};

Now, you can use this function like this:

const styles = getStyles(document.body, "height", "width");

OR

const styles = getStyles(document.body, ["height", "width"]);

Finding the index of an item in a list

All indexes with the zip function:

get_indexes = lambda x, xs: [i for (y, i) in zip(xs, range(len(xs))) if x == y]

print get_indexes(2, [1, 2, 3, 4, 5, 6, 3, 2, 3, 2])
print get_indexes('f', 'xsfhhttytffsafweef')

How to create streams from string in Node.Js?

Edit: Garth's answer is probably better.

My old answer text is preserved below.


To convert a string to a stream, you can use a paused through stream:

through().pause().queue('your string').end()

Example:

var through = require('through')

// Create a paused stream and buffer some data into it:
var stream = through().pause().queue('your string').end()

// Pass stream around:
callback(null, stream)

// Now that a consumer has attached, remember to resume the stream:
stream.resume()

Run PHP Task Asynchronously

If you don't want the full blown ActiveMQ, I recommend to consider RabbitMQ. RabbitMQ is lightweight messaging that uses the AMQP standard.

I recommend to also look into php-amqplib - a popular AMQP client library to access AMQP based message brokers.

How do I evenly add space between a label and the input field regardless of length of text?

2019 answer:

Some time has passed and I changed my approach now when building forms. I've done thousands of them till today and got really tired of typing id for every label/input pair, so this was flushed down the toilet. When you dive input right into the label, things work the same way, no ids necessary. I also took advantage of flexbox being, well, very flexible.

HTML:

<label>
  Short label <input type="text" name="dummy1" />
</label>

<label>
  Somehow longer label <input type="text" name="dummy2" />
</label>

<label>
  Very long label for testing purposes <input type="text" name="dummy3" />
</label>

CSS:

label {
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
  text-align: right;
  width: 400px;
  line-height: 26px;
  margin-bottom: 10px;
}

input {
  height: 20px;
  flex: 0 0 200px;
  margin-left: 10px;
}

Fiddle DEMO


Original answer:

Use label instead of span. It's meant to be paired with inputs and preserves some additional functionality (clicking label focuses the input).

This might be exactly what you want:

HTML:

<label for="dummy1">title for dummy1:</label>
<input id="dummy1" name="dummy1" value="dummy1">

<label for="dummy2">longer title for dummy2:</label>
<input id="dummy2" name="dummy2" value="dummy2">

<label for="dummy3">even longer title for dummy3:</label>
<input id="dummy3" name="dummy3" value="dummy3">

CSS:

label {
    width:180px;
    clear:left;
    text-align:right;
    padding-right:10px;
}

input, label {
    float:left;
}

jsfiddle DEMO here.

AngularJs - ng-model in a SELECT

You dont need to define option tags, you can do this using the ngOptions directive: https://docs.angularjs.org/api/ng/directive/ngOptions

<select class="form-control" ng-change="unitChanged()" ng-model="data.unit" ng-options="unit.id as unit.label for unit in units"></select>

Accessing attributes from an AngularJS directive

Although using '@' is more appropriate than using '=' for your particular scenario, sometimes I use '=' so that I don't have to remember to use attrs.$observe():

<su-label tooltip="field.su_documentation">{{field.su_name}}</su-label>

Directive:

myApp.directive('suLabel', function() {
    return {
        restrict: 'E',
        replace: true,
        transclude: true,
        scope: {
            title: '=tooltip'
        },
        template: '<label><a href="#" rel="tooltip" title="{{title}}" data-placement="right" ng-transclude></a></label>',
        link: function(scope, element, attrs) {
            if (scope.title) {
                element.addClass('tooltip-title');
            }
        },
    }
});

Fiddle.

With '=' we get two-way databinding, so care must be taken to ensure scope.title is not accidentally modified in the directive. The advantage is that during the linking phase, the local scope property (scope.title) is defined.

Is there a simple, elegant way to define singletons?

In cases where you don't want the metaclass-based solution above, and you don't like the simple function decorator-based approach (e.g. because in that case static methods on the singleton class won't work), this compromise works:

class singleton(object):
  """Singleton decorator."""

  def __init__(self, cls):
      self.__dict__['cls'] = cls

  instances = {}

  def __call__(self):
      if self.cls not in self.instances:
          self.instances[self.cls] = self.cls()
      return self.instances[self.cls]

  def __getattr__(self, attr):
      return getattr(self.__dict__['cls'], attr)

  def __setattr__(self, attr, value):
      return setattr(self.__dict__['cls'], attr, value)

Force git stash to overwrite added files

git stash show -p | git apply

and then git stash drop if you want to drop the stashed items.

How to make a button redirect to another page using jQuery or just Javascript

You can use:

  location.href = "newpage.html"

in the button's onclick event.

SQL state [99999]; error code [17004]; Invalid column type: 1111 With Spring SimpleJdbcCall

We had the same issue when we had a typo in the mybatis mapping file like

        ....
        #{column1Name,          jdbcType=INTEGER},
        #{column2Name,          jdbcType=VARCHAR},
        #{column3Name,      jdbcTyep=VARCHAR}  -- do you see the typo ?
        .....

So check this kind of typos as well. Unfortunately, it can not understand the typo in compile/build time, it causes an unchecked exception and booms in runtime.