Programs & Examples On #Iptv

notifyDataSetChange not working from custom adapter

Change your method from

public void updateReceiptsList(List<Receipt> newlist) {
    receiptlist = newlist;
    this.notifyDataSetChanged();
}

To

public void updateReceiptsList(List<Receipt> newlist) {
    receiptlist.clear();
    receiptlist.addAll(newlist);
    this.notifyDataSetChanged();
}

So you keep the same object as your DataSet in your Adapter.

Send JavaScript variable to PHP variable

As Jordan already said you have to post back the javascript variable to your server before the server can handle the value. To do this you can either program a javascript function that submits a form - or you can use ajax / jquery. jQuery.post

Maybe the most easiest approach for you is something like this

function myJavascriptFunction() { 
  var javascriptVariable = "John";
  window.location.href = "myphpfile.php?name=" + javascriptVariable; 
}

On your myphpfile.php you can use $_GET['name'] after your javascript was executed.

Regards

UIImageView - How to get the file name of the image assigned?

No no no… in general these things are possible. It'll just make you feel like a dirty person. If you absolutely must, do this:

  • Create a category with your own implementation of +imageNamed:(NSString*)imageName that calls through to the existing implementation and uses the technique identified here (How do I use objc_setAssociatedObject/objc_getAssociatedObject inside an object?) to permanently associate imageName with the UIImage object that is returned.

  • Use Method Swizzling to swap the provided implementation of imageNamed: for your implementation in the method lookup table of the Objective-C runtime.

  • Access the name you associated with the UIImage instance (using objc_getAssociatedObject) anytime you want it.

I can verify that this works, with the caveat that you can't get the names of UIImage's loaded in NIBs. It appears that images loaded from NIBs are not created through any standard function calls, so it's really a mystery to me.

I'm leaving the implementation up to you. Copy-pasting code that screws with the Objective-C runtime is a very bad idea, so think carefully about your project's needs and implement this only if you must.

How to make the overflow CSS property work with hidden as value

In addition to provided answers:

it seems like parent element (the one with overflow:hidden) must not be display:inline. Changing to display:inline-block worked for me.

_x000D_
_x000D_
.outer {_x000D_
  position: relative;_x000D_
  border: 1px dotted black;_x000D_
  padding: 5px;_x000D_
  overflow: hidden;_x000D_
}_x000D_
.inner {_x000D_
  position: absolute;_x000D_
  left: 50%;_x000D_
  margin-left: -20px;_x000D_
  top: 70%;_x000D_
  width: 40px;_x000D_
  height: 80px;_x000D_
  background: yellow;_x000D_
}
_x000D_
<span class="outer">_x000D_
  Some text_x000D_
  <span class="inner"></span>_x000D_
</span>_x000D_
<span class="outer" style="display:inline-block;">_x000D_
  Some text_x000D_
  <span class="inner"></span>_x000D_
</span>
_x000D_
_x000D_
_x000D_

PHP DateTime __construct() Failed to parse time string (xxxxxxxx) at position x

$start_date = new DateTime();
$start_date->setTimestamp($dbResult->db_timestamp);

What is the difference between x86 and x64

x64 is a generic name for the 64-bit extensions to Intel's and AMD's 32-bit x86 instruction set architecture (ISA). AMD introduced the first version of x64, initially called x86-64 and later renamed AMD64. Intel named their implementation IA-32e and then EMT64.

Pseudo-terminal will not be allocated because stdin is not a terminal

I don't know where the hang comes from, but redirecting (or piping) commands into an interactive ssh is in general a recipe for problems. It is more robust to use the command-to-run-as-a-last-argument style and pass the script on the ssh command line:

ssh user@server 'DEP_ROOT="/home/matthewr/releases"
datestamp=$(date +%Y%m%d%H%M%S)
REL_DIR=$DEP_ROOT"/"$datestamp
if [ ! -d "$DEP_ROOT" ]; then
    echo "creating the root directory"
    mkdir $DEP_ROOT
fi
mkdir $REL_DIR'

(All in one giant '-delimited multiline command-line argument).

The pseudo-terminal message is because of your -t which asks ssh to try to make the environment it runs on the remote machine look like an actual terminal to the programs that run there. Your ssh client is refusing to do that because its own standard input is not a terminal, so it has no way to pass the special terminal APIs onwards from the remote machine to your actual terminal at the local end.

What were you trying to achieve with -t anyway?

Get the latest record from mongodb collection

I need a query with constant time response

By default, the indexes in MongoDB are B-Trees. Searching a B-Tree is a O(logN) operation, so even find({_id:...}) will not provide constant time, O(1) responses.

That stated, you can also sort by the _id if you are using ObjectId for you IDs. See here for details. Of course, even that is only good to the last second.

You may to resort to "writing twice". Write once to the main collection and write again to a "last updated" collection. Without transactions this will not be perfect, but with only one item in the "last updated" collection it will always be fast.

Error loading the SDK when Eclipse starts

In my case, I have the latest Android SDK and just have to remove/delete the Android Wear system images and it worked.

String comparison in Objective-C

Use the -isEqualToString: method to compare the value of two strings. Using the C == operator will simply compare the addresses of the objects.

if ([category isEqualToString:@"Some String"])
{
    // Do stuff...
}

How can I get the assembly file version

When I want to access the application file version (what is set in Assembly Information -> File version), say to set a label's text to it on form load to display the version, I have just used

versionlabel.Text = "Version " + Application.ProductVersion;

This approach requires a reference to System.Windows.Forms.

CSS : center form in page horizontally and vertically

The accepted answer didn't work with my form, even when I stripped it down to the bare minimum and copied & pasted the code. If anyone else is having this problem, please give my solution a try. Basically, you set Top and Left to 50% as the OP did, but offset the form's container with negative margins on the top and left equal to 50% of the div's height and width, respectively. This moves the center point of the Top and Left coordinates to the center of the form. I will stress that the height and width of the form must be specified (not relative). In this example, a 300x300px form div with margins of -150px on the top and left is perfectly centered no matter the window size:

HTML

<body>
    <div class="login_div">
        <form class="login_form" action="#">
        </form>
    </div>
</body>

CSS

.login_div {
    position: absolute;

    width: 300px;
    height: 300px;

    /* Center form on page horizontally & vertically */
    top: 50%;
    left: 50%;
    margin-top: -150px;
    margin-left: -150px;
}

.login_form {
    width: 300px;
    height: 300px;

    background: gray;
    border-radius: 10px;

    margin: 0;
    padding: 0;
}

JSFiddle

Now, for those wondering why I used a container for the form, it's because I like to have the option of placing other elements in the form's vicinity and having them centered as well. The form container is completely unnecessary in this example, but would definitely be useful in other cases. Hope this helps!

Android: Difference between Parcelable and Serializable?

In Android we cannot just pass objects to activities. To do this the objects must either implement Serializable or Parcelable interface.

Serializable

Serializable is a standard Java interface. You can just implement Serializable interface and add override methods. The problem with this approach is that reflection is used and it is a slow process. This method creates a lot of temporary objects and causes quite a bit of garbage collection. However, Serializable interface is easier to implement.

Look at the example below (Serializable):

// MyObjects Serializable class

import java.io.Serializable;
import java.util.ArrayList;
import java.util.TreeMap;

import android.os.Parcel;
import android.os.Parcelable;

public class MyObjects implements Serializable {

    private String name;
    private int age;
    public ArrayList<String> address;

    public MyObjects(String name, int age, ArrayList<String> address) {
        super();
        this.name = name;
        this.age = age;
        this.address = address;
    }

    public ArrayList<String> getAddress() {
        if (!(address == null))
            return address;
        else
            return new ArrayList<String>();
    }

    public String getName() {
        return name;
    }

    public String getAge() {
        return age;
    }
}
// MyObjects instance
MyObjects mObjects = new MyObjects("name", "age", "Address array here");

// Passing MyObjects instance via intent
Intent mIntent = new Intent(FromActivity.this, ToActivity.class);
mIntent.putExtra("UniqueKey", mObjects);
startActivity(mIntent);
// Getting MyObjects instance
Intent mIntent = getIntent();
MyObjects workorder = (MyObjects)    mIntent.getSerializableExtra("UniqueKey");

Parcelable

Parcelable process is much faster than Serializable. One of the reasons for this is that we are being explicit about the serialization process instead of using reflection to infer it. It also stands to reason that the code has been heavily optimized for this purpose.

Look at the example below (Parcelable):

// MyObjects Parcelable class

import java.util.ArrayList;

import android.os.Parcel;
import android.os.Parcelable;

public class MyObjects implements Parcelable {

    private int age;
    private String name;
    private ArrayList<String> address;

    public MyObjects(String name, int age, ArrayList<String> address) {
        this.name = name;
        this.age = age;
        this.address = address;
    }

    public MyObjects(Parcel source) {
        age = source.readInt();
        name = source.readString();
        address = source.createStringArrayList();
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(age);
        dest.writeString(name);
        dest.writeStringList(address);
    }

    public int getAge() {
        return age;
    }

    public String getName() {
        return name;
    }

    public ArrayList<String> getAddress() {
        if (!(address == null))
            return address;
        else
            return new ArrayList<String>();
    }

    public static final Creator<MyObjects> CREATOR = new Creator<MyObjects>() {
        @Override
        public MyObjects[] newArray(int size) {
            return new MyObjects[size];
        }

        @Override
        public MyObjects createFromParcel(Parcel source) {
            return new MyObjects(source);
        }
    };
}
// MyObjects instance
MyObjects mObjects = new MyObjects("name", "age", "Address array here");

// Passing MyOjects instance
Intent mIntent = new Intent(FromActivity.this, ToActivity.class);
mIntent.putExtra("UniqueKey", mObjects);
startActivity(mIntent);
// Getting MyObjects instance
Intent mIntent = getIntent();
MyObjects workorder = (MyObjects) mIntent.getParcelableExtra("UniqueKey");

You can pass ArrayList of Parcelable objects as below:

// Array of MyObjects
ArrayList<MyObjects> mUsers;

// Passing MyOjects instance
Intent mIntent = new Intent(FromActivity.this, ToActivity.class);
mIntent.putParcelableArrayListExtra("UniqueKey", mUsers);
startActivity(mIntent);
// Getting MyObjects instance
Intent mIntent = getIntent();
ArrayList<MyObjects> mUsers = mIntent.getParcelableArrayList("UniqueKey");

Conclusion

  1. Parcelable is faster than Serializable interface
  2. Parcelable interface takes more time to implement compared to Serializable interface
  3. Serializable interface is easier to implement
  4. Serializable interface creates a lot of temporary objects and causes quite a bit of garbage collection
  5. Parcelable array can be passed via Intent in android

mySQL :: insert into table, data from another table?

INSERT INTO Table1 SELECT * FROM Table2

Update a local branch with the changes from a tracked remote branch

You have set the upstream of that branch

(see:

git branch -f --track my_local_branch origin/my_remote_branch
# OR (if my_local_branch is currently checked out):
$ git branch --set-upstream-to my_local_branch origin/my_remote_branch

(git branch -f --track won't work if the branch is checked out: use the second command git branch --set-upstream-to instead, or you would get "fatal: Cannot force update the current branch.")

That means your branch is already configured with:

branch.my_local_branch.remote origin
branch.my_local_branch.merge my_remote_branch

Git already has all the necessary information.
In that case:

# if you weren't already on my_local_branch branch:
git checkout my_local_branch 
# then:
git pull

is enough.


If you hadn't establish that upstream branch relationship when it came to push your 'my_local_branch', then a simple git push -u origin my_local_branch:my_remote_branch would have been enough to push and set the upstream branch.
After that, for the subsequent pulls/pushes, git pull or git push would, again, have been enough.

jquery ajax get responsetext from http url

Actually, you can make cross domain requests with i.e. Firefox, se this for a overview: http://ajaxian.com/archives/cross-site-xmlhttprequest-in-firefox-3

Webkit and IE8 supports it as well in some fashion.

JSON to pandas DataFrame

I prefer a more generic method in which may be user doesn't prefer to give key 'results'. You can still flatten it by using a recursive approach of finding key having nested data or if you have key but your JSON is very nested. It is something like:

from pandas import json_normalize

def findnestedlist(js):
    for i in js.keys():
        if isinstance(js[i],list):
            return js[i]
    for v in js.values():
        if isinstance(v,dict):
            return check_list(v)


def recursive_lookup(k, d):
    if k in d:
        return d[k]
    for v in d.values():
        if isinstance(v, dict):
            return recursive_lookup(k, v)
    return None

def flat_json(content,key):
    nested_list = []
    js = json.loads(content)
    if key is None or key == '':
        nested_list = findnestedlist(js)
    else:
        nested_list = recursive_lookup(key, js)
    return json_normalize(nested_list,sep="_")

key = "results" # If you don't have it, give it None

csv_data = flat_json(your_json_string,root_key)
print(csv_data)

Is there a program to decompile Delphi?

Languages like Delphi, C and C++ Compile to processor-native machine code, and the output executables have little or no metadata in them. This is in contrast with Java or .Net, which compile to object-oriented platform-independent bytecode, which retains the names of methods, method parameters, classes and namespaces, and other metadata.

So there is a lot less useful decompiling that can be done on Delphi or C code. However, Delphi typically has embedded form data for any form in the project (generated by the $R *.dfm line), and it also has metadata on all published properties, so a Delphi-specific tool would be able to extract this information.

Reading inputStream using BufferedReader.readLine() is too slow

I strongly suspect that's because of the network connection or the web server you're talking to - it's not BufferedReader's fault. Try measuring this:

InputStream stream = conn.getInputStream();
byte[] buffer = new byte[1000];
// Start timing
while (stream.read(buffer) > 0)
{
}
// End timing

I think you'll find it's almost exactly the same time as when you're parsing the text.

Note that you should also give InputStreamReader an appropriate encoding - the platform default encoding is almost certainly not what you should be using.

Download File Using Javascript/jQuery

There are so many little things that can happen when trying to download a file. The inconsistency between browsers alone is a nightmare. I ended up using this great little library. https://github.com/rndme/download

Nice thing about it is that its flexible for not only urls but for client side data you want to download.

  1. text string
  2. text dataURL
  3. text blob
  4. text arrays
  5. html string
  6. html blob
  7. ajax callback
  8. binary files

Jquery to change form action

$('#button1').click(function(){
$('#myform').prop('action', 'page1.php');
});

Using Position Relative/Absolute within a TD?

also works if you do a "display: block;" on the td, destroying the td identity, but works!

SQL-Server: Error - Exclusive access could not be obtained because the database is in use

I'll assume that if you're restoring a db, you don't care about any existing transactions on that db. Right? If so, this should work for you:

USE master
GO

ALTER DATABASE AdventureWorksDW
SET SINGLE_USER
--This rolls back all uncommitted transactions in the db.
WITH ROLLBACK IMMEDIATE
GO

RESTORE DATABASE AdventureWorksDW
FROM ...
...
GO

Now, one additional item to be aware. After you set the db into single user mode, someone else may attempt to connect to the db. If they succeed, you won't be able to proceed with your restore. It's a race! My suggestion is to run all three statements at once.

Python JSON serialize a Decimal object

Based on stdOrgnlDave answer I have defined this wrapper that it can be called with optional kinds so the encoder will work only for certain kinds inside your projects. I believe the work should be done inside your code and not to use this "default" encoder since "it is better explicit than implicit", but I understand using this will save some of your time. :-)

import time
import json
import decimal
from uuid import UUID
from datetime import datetime

def JSONEncoder_newdefault(kind=['uuid', 'datetime', 'time', 'decimal']):
    '''
    JSON Encoder newdfeault is a wrapper capable of encoding several kinds
    Use it anywhere on your code to make the full system to work with this defaults:
        JSONEncoder_newdefault()  # for everything
        JSONEncoder_newdefault(['decimal'])  # only for Decimal
    '''
    JSONEncoder_olddefault = json.JSONEncoder.default

    def JSONEncoder_wrapped(self, o):
        '''
        json.JSONEncoder.default = JSONEncoder_newdefault
        '''
        if ('uuid' in kind) and isinstance(o, uuid.UUID):
            return str(o)
        if ('datetime' in kind) and isinstance(o, datetime):
            return str(o)
        if ('time' in kind) and isinstance(o, time.struct_time):
            return datetime.fromtimestamp(time.mktime(o))
        if ('decimal' in kind) and isinstance(o, decimal.Decimal):
            return str(o)
        return JSONEncoder_olddefault(self, o)
    json.JSONEncoder.default = JSONEncoder_wrapped

# Example
if __name__ == '__main__':
    JSONEncoder_newdefault()

Spring: How to inject a value to static field?

Spring uses dependency injection to populate the specific value when it finds the @Value annotation. However, instead of handing the value to the instance variable, it's handed to the implicit setter instead. This setter then handles the population of our NAME_STATIC value.

    @RestController 
//or if you want to declare some specific use of the properties file then use
//@Configuration
//@PropertySource({"classpath:application-${youeEnvironment}.properties"})
public class PropertyController {

    @Value("${name}")//not necessary
    private String name;//not necessary

    private static String NAME_STATIC;

    @Value("${name}")
    public void setNameStatic(String name){
        PropertyController.NAME_STATIC = name;
    }
}

Align Bootstrap Navigation to Center

Thank you all for your help, I added this code and it seems it fixed the issue:

.navbar .navbar-nav {
    display: inline-block;
    float: none;
}

.navbar .navbar-collapse {
    text-align: center;
}

Source

Center content in responsive bootstrap navbar

'node' is not recognized as an internal or an external command, operable program or batch file while using phonegap/cordova

Add a system variable named "node", with value of your node path. It solves my problem, hope it helps.

PHP Array to JSON Array using json_encode();

A common use of JSON is to read data from a web server, and display the data in a web page.

This chapter will teach you how to exchange JSON data between the client and a PHP server.

PHP has some built-in functions to handle JSON.

Objects in PHP can be converted into JSON by using the PHP function json_encode():

_x000D_
_x000D_
<?php_x000D_
$myObj->name = "John";_x000D_
$myObj->age = 30;_x000D_
$myObj->city = "New York";_x000D_
_x000D_
$myJSON = json_encode($myObj);_x000D_
_x000D_
echo $myJSON;_x000D_
?>
_x000D_
_x000D_
_x000D_

In Jenkins, how to checkout a project into a specific directory (using GIT)

The default git plugin for Jenkins does the job quite nicely.

After adding a new git repository (project configuration > Source Code Management > check the GIT option) to the project navigate to the bottom of the plugin settings, just above Repository browser region. There should be an Advanced button. After clicking it a new form should appear, with a value described as Local subdirectory for repo (optional). Setting this to folder will make the plugin to check out the repository into the folder relative to your workspace. This way you can have as many repositories in your project as you need, all in separate locations.

Alternatively, if the project you're using will allow that, you can use GIT sub modules, which are similar to external paths in SVN. In the GIT Book there is a section on that very topic. If that will not be against some policy, submodules are fairly simple to use, giving you powerful way to control the locations, versions/tags/branches that will be imported AND it will be available on your local repository as well giving you better portability.

Obviously the GIT plugin supports checking out submodules, so Jenkins can work with them quite effectively.

"The system cannot find the file specified" when running C++ program

This is a first step for somebody that is a beginner. Same thing happened to me:

Look in the Solution Explorer box to the left. Make sure that there is actually a .cpp file there. You can do the same by looking the .cpp file where the .sln file for the project is stored. If there is not one, then you will get that error.

When adding a cpp file you want to use the Add new item icon. (top left with a gold star on it, hover over it to see the name) For some reason Ctrl+N does not actually add a .cpp file to the project.

How can I mix LaTeX in with Markdown?

you should look at multimarkdown http://fletcherpenney.net/multimarkdown/

it has support for metadata (headers, keywords, date, author, etc), tables, asciimath, mathml, hell i'm sure you could stick latex math code right in there. it's basically an extension to markdown to add all these other very useful features. It uses XSLT, so you can easily whip up your own LaTeX styles, and have it directly convert. I use it all the time, and I like it a lot.

I wish the markdown would just incorporate multimarkdown. it would be rather nice.

Edit: Multimarkdown will produce html, latex, and a few other formats. html can come with a style sheet of your choice. it will convert into MathML as well, which displays in Firefox and Safari/Chrome, if I remember correctly.

ImportError: No module named PytQt5

pip install pyqt5 for python3 for ubuntu

Run PowerShell scripts on remote PC

Accepted answer doesn't work for me, but this does. Ensure script in the location (c:\temp_ below on each remote server. servers.txt contains a list of IP addresses (one per line).

psexec @servers.txt -u <username> cmd /c "powershell -noninteractive -file C:\temp\script.ps1"

Unsetting array values in a foreach loop


foreach($images as $key=>$image)                                
{               
   if($image == 'http://i27.tinypic.com/29ykt1f.gif' ||    
   $image == 'http://img3.abload.de/img/10nxjl0fhco.gif' ||    
   $image == 'http://i42.tinypic.com/9pp2tx.gif')     
   { unset($images[$key]); }                               
}

!!foreach($images as $key=>$image

cause $image is the value, so $images[$image] make no sense.

Populate one dropdown based on selection in another

_x000D_
_x000D_
function configureDropDownLists(ddl1, ddl2) {_x000D_
  var colours = ['Black', 'White', 'Blue'];_x000D_
  var shapes = ['Square', 'Circle', 'Triangle'];_x000D_
  var names = ['John', 'David', 'Sarah'];_x000D_
_x000D_
  switch (ddl1.value) {_x000D_
    case 'Colours':_x000D_
      ddl2.options.length = 0;_x000D_
      for (i = 0; i < colours.length; i++) {_x000D_
        createOption(ddl2, colours[i], colours[i]);_x000D_
      }_x000D_
      break;_x000D_
    case 'Shapes':_x000D_
      ddl2.options.length = 0;_x000D_
      for (i = 0; i < shapes.length; i++) {_x000D_
        createOption(ddl2, shapes[i], shapes[i]);_x000D_
      }_x000D_
      break;_x000D_
    case 'Names':_x000D_
      ddl2.options.length = 0;_x000D_
      for (i = 0; i < names.length; i++) {_x000D_
        createOption(ddl2, names[i], names[i]);_x000D_
      }_x000D_
      break;_x000D_
    default:_x000D_
      ddl2.options.length = 0;_x000D_
      break;_x000D_
  }_x000D_
_x000D_
}_x000D_
_x000D_
function createOption(ddl, text, value) {_x000D_
  var opt = document.createElement('option');_x000D_
  opt.value = value;_x000D_
  opt.text = text;_x000D_
  ddl.options.add(opt);_x000D_
}
_x000D_
<select id="ddl" onchange="configureDropDownLists(this,document.getElementById('ddl2'))">_x000D_
  <option value=""></option>_x000D_
  <option value="Colours">Colours</option>_x000D_
  <option value="Shapes">Shapes</option>_x000D_
  <option value="Names">Names</option>_x000D_
</select>_x000D_
_x000D_
<select id="ddl2">_x000D_
</select>
_x000D_
_x000D_
_x000D_

Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed

This error has been happening randomly during my test runs over the last six months (still happens with Chrome 76 and Chromedriver 76) and only on Linux. On average one of every few hundred tests would fail, then the next test would run fine.

Unable to resolve the issue, in Python I wrapped the driver = webdriver.Chrome() in a try..except block in setUp() in my test case class that all my tests are derived from. If it hits the Webdriver exception it waits ten seconds and tries again.

It solved the issue I was having; not elegantly but it works.

from selenium import webdriver
from selenium.common.exceptions import WebDriverException

try:
    self.driver = webdriver.Chrome(chrome_options=chrome_options, desired_capabilities=capabilities)
except WebDriverException as e:
    print("\nChrome crashed on launch:")
    print(e)
    print("Trying again in 10 seconds..")
    sleep(10)
    self.driver = webdriver.Chrome(chrome_options=chrome_options, desired_capabilities=capabilities)
    print("Success!\n")
except Exception as e:
    raise Exception(e)

How to print out the method name and line number and conditionally disable NSLog?

There are a new trick that no answer give. You can use printf instead NSLog. This will give you a clean log:

With NSLog you get things like this:

2011-11-03 13:43:55.632 myApp[3739:207] Hello Word

But with printf you get only:

Hello World

Use this code

#ifdef DEBUG
    #define NSLog(FORMAT, ...) fprintf(stderr,"%s\n", [[NSString stringWithFormat:FORMAT, ##__VA_ARGS__] UTF8String]);
#else
    #define NSLog(...) {}              
#endif

What is the use of "assert"?

Here is a simple example, save this in file (let's say b.py)

def chkassert(num):
    assert type(num) == int


chkassert('a')

and the result when $python b.py

Traceback (most recent call last):
  File "b.py", line 5, in <module>
    chkassert('a')
  File "b.py", line 2, in chkassert
    assert type(num) == int
AssertionError

What's the difference of $host and $http_host in Nginx

$host is a variable of the Core module.

$host

This variable is equal to line Host in the header of request or name of the server processing the request if the Host header is not available.

This variable may have a different value from $http_host in such cases: 1) when the Host input header is absent or has an empty value, $host equals to the value of server_name directive; 2)when the value of Host contains port number, $host doesn't include that port number. $host's value is always lowercase since 0.8.17.

$http_host is also a variable of the same module but you won't find it with that name because it is defined generically as $http_HEADER (ref).

$http_HEADER

The value of the HTTP request header HEADER when converted to lowercase and with 'dashes' converted to 'underscores', e.g. $http_user_agent, $http_referer...;


Summarizing:

  • $http_host equals always the HTTP_HOST request header.
  • $host equals $http_host, lowercase and without the port number (if present), except when HTTP_HOST is absent or is an empty value. In that case, $host equals the value of the server_name directive of the server which processed the request.

PostgreSQL Error: Relation already exists

There should be no single quotes here 'A'. Single quotes are for string literals: 'some value'.
Either use double quotes to preserve the upper case spelling of "A":

CREATE TABLE "A" ...

Or don't use quotes at all:

CREATE TABLE A ...

which is identical to

CREATE TABLE a ...

because all unquoted identifiers are folded to lower case automatically in PostgreSQL.


You could avoid problems with the index name completely by using simpler syntax:

CREATE TABLE csd_relationship (
    csd_relationship_id serial PRIMARY KEY,
    type_id integer NOT NULL,
    object_id integer NOT NULL
);

Does the same as your original query, only it avoids naming conflicts automatically. It picks the next free identifier automatically. More about the serial type in the manual.

convert xml to java object using jaxb (unmarshal)

Tests

On the Tests class we will add an @XmlRootElement annotation. Doing this will let your JAXB implementation know that when a document starts with this element that it should instantiate this class. JAXB is configuration by exception, this means you only need to add annotations where your mapping differs from the default. Since the testData property differs from the default mapping we will use the @XmlElement annotation. You may find the following tutorial helpful: http://wiki.eclipse.org/EclipseLink/Examples/MOXy/GettingStarted

package forum11221136;

import javax.xml.bind.annotation.*;

@XmlRootElement
public class Tests {

    TestData testData;

    @XmlElement(name="test-data")
    public TestData getTestData() {
        return testData;
    }

    public void setTestData(TestData testData) {
        this.testData = testData;
    }

}

TestData

On this class I used the @XmlType annotation to specify the order in which the elements should be ordered in. I added a testData property that appeared to be missing. I also used an @XmlElement annotation for the same reason as in the Tests class.

package forum11221136;

import java.util.List;
import javax.xml.bind.annotation.*;

@XmlType(propOrder={"title", "book", "count", "testData"})
public class TestData {
    String title;
    String book;
    String count;
    List<TestData> testData;

    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getBook() {
        return book;
    }
    public void setBook(String book) {
        this.book = book;
    }
    public String getCount() {
        return count;
    }
    public void setCount(String count) {
        this.count = count;
    }
    @XmlElement(name="test-data")
    public List<TestData> getTestData() {
        return testData;
    }
    public void setTestData(List<TestData> testData) {
        this.testData = testData;
    }
}

Demo

Below is an example of how to use the JAXB APIs to read (unmarshal) the XML and populate your domain model and then write (marshal) the result back to XML.

package forum11221136;

import java.io.File;
import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Tests.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        File xml = new File("src/forum11221136/input.xml");
        Tests tests = (Tests) unmarshaller.unmarshal(xml);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(tests, System.out);
    }

}

How to manage a redirect request after a jQuery Ajax call

I resolved this issue like this:

Add a middleware to process response, if it is a redirect for an ajax request, change the response to a normal response with the redirect url.

class AjaxRedirect(object):
  def process_response(self, request, response):
    if request.is_ajax():
      if type(response) == HttpResponseRedirect:
        r = HttpResponse(json.dumps({'redirect': response['Location']}))
        return r
    return response

Then in ajaxComplete, if the response contains redirect, it must be a redirect, so change the browser's location.

$('body').ajaxComplete(function (e, xhr, settings) {
   if (xhr.status == 200) {
       var redirect = null;
       try {
           redirect = $.parseJSON(xhr.responseText).redirect;
           if (redirect) {
               window.location.href = redirect.replace(/\?.*$/, "?next=" + window.location.pathname);
           }
       } catch (e) {
           return;
       }
   }
}

Get form data in ReactJS

Also, this can be used too.

handleChange: function(state,e) {
  this.setState({[state]: e.target.value});
},
render : function() {
  return (
    <form>
      <input type="text" name="email" placeholder="Email" value={this.state.email} onChange={this.handleChange.bind(this, 'email')} />
      <input type="password" name="password" placeholder="Password" value={this.state.password} onChange={this.handleChange.bind(this, 'password')}/>
      <button type="button" onClick={this.handleLogin}>Login</button>
    </form>
  );
},
handleLogin: function() {
  console.log("EMail: ", this.state.email);
  console.log("Password: ", this.state.password);
}

Are string.Equals() and == operator really same?

The Header property of the TreeViewItem is statically typed to be of type object.

Therefore the == yields false. You can reproduce this with the following simple snippet:

object s1 = "Hallo";

// don't use a string literal to avoid interning
string s2 = new string(new char[] { 'H', 'a', 'l', 'l', 'o' });

bool equals = s1 == s2;         // equals is false
equals = string.Equals(s1, s2); // equals is true

How can I remove the decimal part from JavaScript number?

This is for those who want to prevent users to enter decimal numbers

<input id="myInput" onkeyup="doSomething()" type="number" />

<script>
    function doSomething() {

        var intNum = $('#myInput').val();

        if (!Number.isInteger(intNum)) {
            intNum = Math.round(intNum);
        }

        console.log(intNum);
    }
</script>

Cannot find the '@angular/common/http' module

Refer to this: http: deprecate @angular/http in favor of @angular/common/http.

How do I fix a NoSuchMethodError?

If you are writing a webapp, ensure that you don't have conflicting versions of a jar in your container's global library directory and also in your app. You may not necessarily know which jar is being used by the classloader.

e.g.

  • tomcat/common/lib
  • mywebapp/WEB-INF/lib

AJAX cross domain call

JSONP is the best option, in my opinion. Try to figure out why you get the syntax error - are you sure the received data is not JSON? Then maybe you're using the API wrong somehow.

Another way you could use, but I don't think that it applies in your case, is have an iFrame in the page which src is in the domain you want to call. Have it do the calls for you, and then use JS to communicate between the iFrame and the page. This will bypass the cross domain, but only if you can have the iFrame's src in the domain you want to call.

How to set the id attribute of a HTML element dynamically with angularjs (1.x)?

ngAttr directive can totally be of help here, as introduced in the official documentation

https://docs.angularjs.org/guide/interpolation#-ngattr-for-binding-to-arbitrary-attributes

For instance, to set the id attribute value of a div element, so that it contains an index, a view fragment might contain

<div ng-attr-id="{{ 'object-' + myScopeObject.index }}"></div>

which would get interpolated to

<div id="object-1"></div>

Questions every good Java/Java EE Developer should be able to answer?

What is difference between String, StringBuffer and StringBuilder?

Locking pattern for proper use of .NET MemoryCache

I assume this code has concurrency issues:

Actually, it's quite possibly fine, though with a possible improvement.

Now, in general the pattern where we have multiple threads setting a shared value on first use, to not lock on the value being obtained and set can be:

  1. Disastrous - other code will assume only one instance exists.
  2. Disastrous - the code that obtains the instance is not can only tolerate one (or perhaps a certain small number) concurrent operations.
  3. Disastrous - the means of storage is not thread-safe (e.g. have two threads adding to a dictionary and you can get all sorts of nasty errors).
  4. Sub-optimal - the overall performance is worse than if locking had ensured only one thread did the work of obtaining the value.
  5. Optimal - the cost of having multiple threads do redundant work is less than the cost of preventing it, especially since that can only happen during a relatively brief period.

However, considering here that MemoryCache may evict entries then:

  1. If it's disastrous to have more than one instance then MemoryCache is the wrong approach.
  2. If you must prevent simultaneous creation, you should do so at the point of creation.
  3. MemoryCache is thread-safe in terms of access to that object, so that is not a concern here.

Both of these possibilities have to be thought about of course, though the only time having two instances of the same string existing can be a problem is if you're doing very particular optimisations that don't apply here*.

So, we're left with the possibilities:

  1. It is cheaper to avoid the cost of duplicate calls to SomeHeavyAndExpensiveCalculation().
  2. It is cheaper not to avoid the cost of duplicate calls to SomeHeavyAndExpensiveCalculation().

And working that out can be difficult (indeed, the sort of thing where it's worth profiling rather than assuming you can work it out). It's worth considering here though that most obvious ways of locking on insert will prevent all additions to the cache, including those that are unrelated.

This means that if we had 50 threads trying to set 50 different values, then we'll have to make all 50 threads wait on each other, even though they weren't even going to do the same calculation.

As such, you're probably better off with the code you have, than with code that avoids the race-condition, and if the race-condition is a problem, you quite likely either need to handle that somewhere else, or need a different caching strategy than one that expels old entries†.

The one thing I would change is I'd replace the call to Set() with one to AddOrGetExisting(). From the above it should be clear that it probably isn't necessary, but it would allow the newly obtained item to be collected, reducing overall memory use and allowing a higher ratio of low generation to high generation collections.

So yeah, you could use double-locking to prevent concurrency, but either the concurrency isn't actually a problem, or your storing the values in the wrong way, or double-locking on the store would not be the best way to solve it.

*If you know only one each of a set of strings exists, you can optimise equality comparisons, which is about the only time having two copies of a string can be incorrect rather than just sub-optimal, but you'd want to be doing very different types of caching for that to make sense. E.g. the sort XmlReader does internally.

†Quite likely either one that stores indefinitely, or one that makes use of weak references so it will only expel entries if there are no existing uses.

concatenate variables

Note that if strings has spaces then quotation marks are needed at definition and must be chopped while concatenating:

rem The retail files set
set FILES_SET="(*.exe *.dll"

rem The debug extras files set
set DEBUG_EXTRA=" *.pdb"

rem Build the DEBUG set without any
set FILES_SET=%FILES_SET:~1,-1%%DEBUG_EXTRA:~1,-1%

rem Append the closing bracket
set FILES_SET=%FILES_SET%)

echo %FILES_SET%

Cheers...

Getting the difference between two repositories

I use PyCharm which has great capabilities to compare between folders and files.

Just open the parent folder for both repos and wait until it indexes. Then you can use right click on a folder or file and Compare to... and pick the corresponding folder / file on the other side.

It shows not only what files are different but also their content. Much easier than command line.

Fragment pressing back button

Still better solution could be to follow a design pattern such that the back-button press event gets propagated from active fragment down to host Activity. So, it's like.. if one of the active fragments consume the back-press, the Activity wouldn't get to act upon it, and vice-versa.

One way to do it is to have all your Fragments extend a base fragment that has an abstract 'boolean onBackPressed()' method.

@Override
public boolean onBackPressed() {
   if(some_condition)
      // Do something
      return true; //Back press consumed.
   } else {
      // Back-press not consumed. Let Activity handle it
      return false;
   }
}

Keep track of active fragment inside your Activity and inside it's onBackPressed callback write something like this

@Override
public void onBackPressed() {
   if(!activeFragment.onBackPressed())
      super.onBackPressed();
   }
}

This post has this pattern described in detail

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

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

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

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

HTTP Ajax Request via HTTPS Page

I've created a module called cors-bypass, that allows you to do this without the need for a server. It uses postMessage to send cross-domain events, which is used to provide mock HTTP APIs (fetch, WebSocket, XMLHTTPRequest etc.).

It fundamentally does the same as the answer by Endless, but requires no code changes to use it.

Example usage:

import { Client, WebSocket } from 'cors-bypass'

const client = new Client()

await client.openServerInNewTab({
  serverUrl: 'http://random-domain.com/server.html',
  adapterUrl: 'https://your-site.com/adapter.html'
})

const ws = new WebSocket('ws://echo.websocket.org')
ws.onopen = () => ws.send('hello')
ws.onmessage = ({ data }) => console.log('received', data)

Table and Index size in SQL Server

The exec sp_spaceused without parameter shows the summary for the whole database. The foreachtable solution generates one result set per table - which SSMS might not be able to handle if you have too many tables.

I created a script which collects the table infos via sp_spaceused and displays a summary in a single record set, sorted by size.

create table #t
(
  name nvarchar(128),
  rows varchar(50),
  reserved varchar(50),
  data varchar(50),
  index_size varchar(50),
  unused varchar(50)
)

declare @id nvarchar(128)
declare c cursor for
select '[' + sc.name + '].[' + s.name + ']' FROM sysobjects s INNER JOIN sys.schemas sc ON s.uid = sc.schema_id where s.xtype='U'

open c
fetch c into @id

while @@fetch_status = 0 begin

  insert into #t
  exec sp_spaceused @id

  fetch c into @id
end

close c
deallocate c

select * from #t
order by convert(int, substring(data, 1, len(data)-3)) desc

drop table #t

Compute a confidence interval from sample data

import numpy as np
import scipy.stats


def mean_confidence_interval(data, confidence=0.95):
    a = 1.0 * np.array(data)
    n = len(a)
    m, se = np.mean(a), scipy.stats.sem(a)
    h = se * scipy.stats.t.ppf((1 + confidence) / 2., n-1)
    return m, m-h, m+h

you can calculate like this way.

Best way to compare dates in Android

Sometimes we need to do a list with dates, like

today with hour

yesterday with yesterday

other days with 23/06/2017

To make this we need to compare current time with our data.

Public class DateUtil {

    Public static int getDateDayOfMonth (Date date) {
        Calendar calendar = Calendar.getInstance ();
        Calendar.setTime (date);
        Return calendar.get (Calendar.DAY_OF_MONTH);
    }

    Public static int getCurrentDayOfMonth () {
        Calendar calendar = Calendar.getInstance ();
        Return calendar.get (Calendar.DAY_OF_MONTH);
    }

    Public static String convertMillisSecondsToHourString (long millisSecond) {
        Date date = new Date (millisSecond);
        Format formatter = new SimpleDateFormat ("HH: mm");
        Return formatter.format (date);
    }

    Public static String convertMillisSecondsToDateString (long millisSecond) {
        Date date = new Date (millisSecond);
        Format formatter = new SimpleDateFormat ("dd / MM / yyyy");
        Return formatter.format (date);
    }

    Public static long convertToMillisSecond (Date date) {
        Return date.getTime ();
    }

    Public static String compare (String stringData, String yesterday) {

        String result = "";

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat ("yyyy-MM-dd HH: mm: ss");
        Date date = null;

        Try {
            Date = simpleDateFormat.parse (stringData);
        } Catch (ParseException e) {
            E.printStackTrace ();
        }

        Long millisSecond = convertToMillisSecond (date);
        Long currencyMillisSecond = System.currentTimeMillis ();

        If (currencyMillisSecond> millisSecond) {
            Long diff = currencyMillisSecond - millisSecond;
            Long day = 86400000L;

            If (diff <day && getCurrentDayOfMonth () == getDateDayOfMonth (date)) {
                Result = convertMillisSecondsToHourString (millisSecond);

            } Else if (diff <(day * 2) && getCurrentDayOfMonth () -1 == getDateDayOfMonth (date)) {
                Result = yesterday;
            } Else {
                Result = convertMillisSecondsToDateString (millisSecond);
            }
        }

        Return result;
    }
}

Also you can check this example in GitHub and this post.

Webpack not excluding node_modules

From your config file, it seems like you're only excluding node_modules from being parsed with babel-loader, but not from being bundled.

In order to exclude node_modules and native node libraries from bundling, you need to:

  1. Add target: 'node' to your webpack.config.js. This will exclude native node modules (path, fs, etc.) from being bundled.
  2. Use webpack-node-externals in order to exclude other node_modules.

So your result config file should look like:

var nodeExternals = require('webpack-node-externals');
...
module.exports = {
    ...
    target: 'node', // in order to ignore built-in modules like path, fs, etc. 
    externals: [nodeExternals()], // in order to ignore all modules in node_modules folder 
    ...
};

Pandas: how to change all the values of a column?

As @DSM points out, you can do this more directly using the vectorised string methods:

df['Date'].str[-4:].astype(int)

Or using extract (assuming there is only one set of digits of length 4 somewhere in each string):

df['Date'].str.extract('(?P<year>\d{4})').astype(int)

An alternative slightly more flexible way, might be to use apply (or equivalently map) to do this:

df['Date'] = df['Date'].apply(lambda x: int(str(x)[-4:]))
             #  converts the last 4 characters of the string to an integer

The lambda function, is taking the input from the Date and converting it to a year.
You could (and perhaps should) write this more verbosely as:

def convert_to_year(date_in_some_format):
    date_as_string = str(date_in_some_format)  # cast to string
    year_as_string = date_in_some_format[-4:] # last four characters
    return int(year_as_string)

df['Date'] = df['Date'].apply(convert_to_year)

Perhaps 'Year' is a better name for this column...

Get the length of a String

You could use SwiftString (https://github.com/amayne/SwiftString) to do this.

"string".length // 6

DISCLAIMER: I wrote this extension

How to get the last characters in a String in Java, regardless of String size

How about:

String numbers = text.substring(text.length() - 7);

That assumes that there are 7 characters at the end, of course. It will throw an exception if you pass it "12345". You could address that this way:

String numbers = text.substring(Math.max(0, text.length() - 7));

or

String numbers = text.length() <= 7 ? text : text.substring(text.length() - 7);

Note that this still isn't doing any validation that the resulting string contains numbers - and it will still throw an exception if text is null.

Can't connect to local MySQL server through socket '/var/mysql/mysql.sock' (38)

try with -h (host) and -P(port):

mysql -h 127.0.0.1 -P 3306 -u root -p

Cross-platform way of getting temp directory in Python

That would be the tempfile module.

It has functions to get the temporary directory, and also has some shortcuts to create temporary files and directories in it, either named or unnamed.

Example:

import tempfile

print tempfile.gettempdir() # prints the current temporary directory

f = tempfile.TemporaryFile()
f.write('something on temporaryfile')
f.seek(0) # return to beginning of file
print f.read() # reads data back from the file
f.close() # temporary file is automatically deleted here

For completeness, here's how it searches for the temporary directory, according to the documentation:

  1. The directory named by the TMPDIR environment variable.
  2. The directory named by the TEMP environment variable.
  3. The directory named by the TMP environment variable.
  4. A platform-specific location:
    • On RiscOS, the directory named by the Wimp$ScrapDir environment variable.
    • On Windows, the directories C:\TEMP, C:\TMP, \TEMP, and \TMP, in that order.
    • On all other platforms, the directories /tmp, /var/tmp, and /usr/tmp, in that order.
  5. As a last resort, the current working directory.

Folder structure for a Node.js project

This is indirect answer, on the folder structure itself, very related.

A few years ago I had same question, took a folder structure but had to do a lot directory moving later on, because the folder was meant for a different purpose than that I have read on internet, that is, what a particular folder does has different meanings for different people on some folders.

Now, having done multiple projects, in addition to explanation in all other answers, on the folder structure itself, I would strongly suggest to follow the structure of Node.js itself, which can be seen at: https://github.com/nodejs/node. It has great detail on all, say linters and others, what file and folder structure they have and where. Some folders have a README that explains what is in that folder.

Starting in above structure is good because some day a new requirement comes in and but you will have a scope to improve as it is already followed by Node.js itself which is maintained over many years now.

Hope this helps.

How do I get my Python program to sleep for 50 milliseconds?

You can also use pyautogui as:

import pyautogui
pyautogui._autoPause(0.05, False)

If the first argument is not None, then it will pause for first argument's seconds, in this example: 0.05 seconds

If the first argument is None, and the second argument is True, then it will sleep for the global pause setting which is set with:

pyautogui.PAUSE = int

If you are wondering about the reason, see the source code:

def _autoPause(pause, _pause):
    """If `pause` is not `None`, then sleep for `pause` seconds.
    If `_pause` is `True`, then sleep for `PAUSE` seconds (the global pause setting).

    This function is called at the end of all of PyAutoGUI's mouse and keyboard functions. Normally, `_pause`
    is set to `True` to add a short sleep so that the user can engage the failsafe. By default, this sleep
    is as long as `PAUSE` settings. However, this can be override by setting `pause`, in which case the sleep
    is as long as `pause` seconds.
    """
    if pause is not None:
        time.sleep(pause)
    elif _pause:
        assert isinstance(PAUSE, int) or isinstance(PAUSE, float)
        time.sleep(PAUSE)

asterisk : Unable to connect to remote asterisk (does /var/run/asterisk.ctl exist?)

I had this problem today. It had nothing to do with any of the posted answers. I tried them all. My problem was a misconfiguration with the zaptel.conf (running old asterisk!). I had commented out some span details trying to troubleshoot a PRI issue. When the server got rebooted this issue presented itself. I was able to discover this by looking at the wanrouter messages in the logs. I noticed there were 3 errors, and the corresponding line numbers, once I corrected these issues, and ran an #asterisk -vvvvc the server came back up and everything worked.

RE error: illegal byte sequence on Mac OS X

My workaround had been using Perl:

find . -type f -print0 | xargs -0 perl -pi -e 's/was/now/g'

Loading cross-domain endpoint with AJAX

To get the data form external site by passing using a local proxy as suggested by jherax you can create a php page that fetches the content for you from respective external url and than send a get request to that php page.

var req = new XMLHttpRequest();
req.open('GET', 'http://localhost/get_url_content.php',false);
if(req.status == 200) {
   alert(req.responseText);
}

as a php proxy you can use https://github.com/cowboy/php-simple-proxy

How to get the focused element with jQuery?

Try this::

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

Plugin execution not covered by lifecycle configuration (JBossas 7 EAR archetype)

You need to understand the content in M2E_plugin_execution_not_covered and follow the steps mentioned below:

  • Pick org.eclipse.m2e.lifecyclemapping.defaults jar from the eclipse plugin folder
  • Extract it and open lifecycle-mapping-metadata.xml where you can find all the pluginExecutions.
  • Add the pluginExecutions of your plugins which are shown as errors with <ignore/> under <action> tags.

eg: for write-project-properties error, add this snippet under the <pluginExecutions> section of the lifecycle-mapping-metadata.xml file:

 <pluginExecution>
    <pluginExecutionFilter>
       <groupId>org.codehaus.mojo</groupId>
       <artifactId>properties-maven-plugin</artifactId>
       <versionRange>1.0-alpha-2</versionRange>
       <goals>
         <goal>write-project-properties</goal>
       </goals>
    </pluginExecutionFilter>
     <action>
       <ignore />
     </action>
   </pluginExecution>
  • Replace that XML file in the JAR
  • Replace the updated JAR in Eclipse's plugin folder
  • Restart Eclipse

You should see no errors in the future for any project.

Maximize a window programmatically and prevent the user from changing the windows state

Change the property WindowState to System.Windows.Forms.FormWindowState.Maximized, in some cases if the older answers doesn't works.

So the window will be maximized, and the other parts are in the other answers.

How can I avoid running ActiveRecord callbacks?

Why would you want to be able to do this in development? Surely this will mean you are building your application with invalid data and as such it will behave strangely and not as you expect in production.

If you want to populate your dev db with data a better approach would be to build a rake task that used the faker gem to build valid data and import it into the db creating as many or few records as you desire, but if you are heel bent on it and have a good reason I guess that update_without_callbacks and create_without_callbacks will work fine, but when you are trying to bend rails to your will, ask yourself you have a good reason and if what you are doing is really a good idea.

How to change the font on the TextView?

I finally got a very easy solution to this.

  1. use these Support libraries in app level gradle,

    compile 'com.android.support:appcompat-v7:26.0.2'
    compile 'com.android.support:support-v4:26.0.2'
    
  2. then create a directory named "font" inside the res folder

  3. put fonts(ttf) files in that font directory, keep in mind the naming conventions [e.g.name should not contain any special character, any uppercase character and any space or tab]
  4. After that, reference that font from xml like this

            <Button
            android:id="@+id/btn_choose_employee"
            android:layout_width="140dp"
            android:layout_height="40dp"
            android:layout_centerInParent="true"
            android:background="@drawable/rounded_red_btn"
            android:onClick="btnEmployeeClickedAction"
            android:text="@string/searching_jobs"
            android:textAllCaps="false"
            android:textColor="@color/white"
            android:fontFamily="@font/times_new_roman_test"
            />
    

In this example, times_new_roman_test is a font ttf file from that font directory

How to stick a footer to bottom in css?

I had a similar issue with this sticky footer tutorial. If memory serves, you need to put your form tags within your <div class=Main /> section since the form tag itself causes issues with the lineup.

How to find day of week in php in a specific timezone

$myTimezone = date_default_timezone_get();
date_default_timezone_set($userTimezone);
$userDay = date('l', $userTimestamp);
date_default_timezone_set($myTimezone);

This should work (didn't test it, so YMMV). It works by storing the script's current timezone, changing it to the one specified by the user, getting the day of the week from the date() function at the specified timestamp, and then setting the script's timezone back to what it was to begin with.

You might have some adventures with timezone identifiers, though.

MySQL Query GROUP BY day / month / year

.... group by to_char(date, 'YYYY') --> 1989

.... group by to_char(date,'MM') -->05

.... group by to_char(date,'DD') --->23

.... group by to_char(date,'MON') --->MAY

.... group by to_char(date,'YY') --->89

How to prevent a file from direct URL Access?

Try the following:

RewriteEngine on 
RewriteCond %{HTTP_REFERER} !^http://(www\.)?localhost [NC] 
RewriteCond %{HTTP_REFERER} !^http://(www\.)?localhost.*$ [NC] 
RewriteRule \.(gif|jpg)$ - [F]

Returns 403, if you access images directly, but allows them to be displayed on site.

Note: It is possible that when you open some page with image and then copy that image's path into the address bar you can see that image, it is only because of the browser's cache, in fact that image has not been loaded from the server (from Davo, full comment below).

Do a "git export" (like "svn export")?

The equivalent of

svn export . otherpath

inside an existing repo is

git archive branchname | (cd otherpath; tar x)

The equivalent of

svn export url otherpath

is

git archive --remote=url branchname | (cd otherpath; tar x)

HttpClient - A task was cancelled?

Promoting @JobaDiniz's comment to an answer:

Do not do the obvious thing and dispose the HttpClient instance, even though the code "looks right":

async Task<HttpResponseMessage> Method() {
  using (var client = new HttpClient())
    return client.GetAsync(request);
}

The same happens with C#'s new RIAA syntax; slightly less obvious:

async Task<HttpResponseMessage> Method() {
  using var client = new HttpClient();
  return client.GetAsync(request);
}

Instead, cache a static instance of HttpClient for your app or library, and reuse it:

static HttpClient client = new HttpClient();

async Task<HttpResponseMessage> Method() {
  return client.GetAsync(request);
}

(The Async() request methods are all thread safe.)

Find unused npm packages in package.json

There is also a package called npm-check:

npm-check

Check for outdated, incorrect, and unused dependencies.

enter image description here

It is quite powerful and actively developed. One of it's features it checking for unused dependencies - for this part it uses the depcheck module mentioned in the other answer.

Passing data to a bootstrap modal

Bootstrap 4.0 gives an option to modify modal data using jquery: https://getbootstrap.com/docs/4.0/components/modal/#varying-modal-content

Here is the script tag on the docs :

$('#exampleModal').on('show.bs.modal', function (event) {
  var button = $(event.relatedTarget) // Button that triggered the modal
  var recipient = button.data('whatever') // Extract info from data-* attributes
  // If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
  // Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
  var modal = $(this)
  modal.find('.modal-title').text('New message to ' + recipient)
  modal.find('.modal-body input').val(recipient)
})

It works for the most part. Only call to modal was not working. Here is a modification on the script that works for me:

$(document).on('show.bs.modal', '#exampleModal',function(event){
... // same as in above script
})

How do I apply a diff patch on Windows?

TortoiseMerge is a separate utility that comes bundled with TortoiseSVN.

It can also be can be downloaded separately in the TortoiseDiff.zip archive. This will allow you to apply unified diffs to non-versioned files.

java.math.BigInteger cannot be cast to java.lang.Integer

As we see from the javaDoc, BigInteger is not a subclass of Integer:

java.lang.Object                      java.lang.Object
   java.lang.Number                       java.lang.Number
      java.math.BigInteger                    java.lang.Integer

And that's the reason why casting from BigInteger to Integer is impossible.

Casting of java primitives will do some conversion (like casting from double to int) while casting of types will never transform classes.

jquery $(window).height() is returning the document height

Its really working if we use Doctype on our web page jquery(window) will return the viewport height else it will return the complete document height.

Define the following tag on the top of your web page: <!DOCTYPE html>

DateTime format to SQL format using C#

   DateTime date1 = new DateTime();

    date1 = Convert.ToDateTime(TextBox1.Text);
    Label1.Text = (date1.ToLongTimeString()); //11:00 AM
    Label2.Text = date1.ToLongDateString(); //Friday, November 1, 2019;
    Label3.Text = date1.ToString();
    Label4.Text = date1.ToShortDateString();
    Label5.Text = date1.ToShortTimeString();

Numpy: find index of the elements within range

As in @deinonychusaur's reply, but even more compact:

In [7]: np.where((a >= 6) & (a <=10))
Out[7]: (array([3, 4, 5]),)

Creating layout constraints programmatically

why can't I use a property like self.myView instead of a local variable like myView?

try using:

NSDictionaryOfVariableBindings(_view)

instead of self.view

How to get Android application id?

Package name is your android app id .

String appId = BuildConfig.APPLICATION_ID

Or

https://play.google.com/store/apps/details?id=com.whatsapp

App Id = com.whatsapp

Setting Timeout Value For .NET Web Service

After creating your client specifying the binding and endpoint address, you can assign an OperationTimeout,

client.InnerChannel.OperationTimeout = new TimeSpan(0, 5, 0);

Set mouse focus and move cursor to end of input using jQuery

It will focus with mouse point

$("#TextBox").focus();

Maintain/Save/Restore scroll position when returning to a ListView

My answer is for Firebase and position 0 is a workaround

Parcelable state;

DatabaseReference everybody = db.getReference("Everybody Room List");
    everybody.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            state = listView.onSaveInstanceState(); // Save
            progressBar.setVisibility(View.GONE);
            arrayList.clear();
            for (DataSnapshot messageSnapshot : dataSnapshot.getChildren()) {
                Messages messagesSpacecraft = messageSnapshot.getValue(Messages.class);
                arrayList.add(messagesSpacecraft);
            }
            listView.setAdapter(convertView);
            listView.onRestoreInstanceState(state); // Restore
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
        }
    });

and convertView

position 0 a add a blank item that you are not using

public class Chat_ConvertView_List_Room extends BaseAdapter {

private ArrayList<Messages> spacecrafts;
private Context context;

@SuppressLint("CommitPrefEdits")
Chat_ConvertView_List_Room(Context context, ArrayList<Messages> spacecrafts) {
    this.context = context;
    this.spacecrafts = spacecrafts;
}

@Override
public int getCount() {
    return spacecrafts.size();
}

@Override
public Object getItem(int position) {
    return spacecrafts.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

@SuppressLint({"SetTextI18n", "SimpleDateFormat"})
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    if (convertView == null) {
        convertView = LayoutInflater.from(context).inflate(R.layout.message_model_list_room, parent, false);
    }

    final Messages s = (Messages) this.getItem(position);

    if (position == 0) {
        convertView.getLayoutParams().height = 1; // 0 does not work
    } else {
        convertView.getLayoutParams().height = RelativeLayout.LayoutParams.WRAP_CONTENT;
    }

    return convertView;
}
}

I have seen this work temporarily without disturbing the user, I hope it works for you

How to overplot a line on a scatter plot in python?

I'm partial to scikits.statsmodels. Here an example:

import statsmodels.api as sm
import numpy as np
import matplotlib.pyplot as plt

X = np.random.rand(100)
Y = X + np.random.rand(100)*0.1

results = sm.OLS(Y,sm.add_constant(X)).fit()

print results.summary()

plt.scatter(X,Y)

X_plot = np.linspace(0,1,100)
plt.plot(X_plot, X_plot*results.params[0] + results.params[1])

plt.show()

The only tricky part is sm.add_constant(X) which adds a columns of ones to X in order to get an intercept term.

     Summary of Regression Results
=======================================
| Dependent Variable:            ['y']|
| Model:                           OLS|
| Method:                Least Squares|
| Date:               Sat, 28 Sep 2013|
| Time:                       09:22:59|
| # obs:                         100.0|
| Df residuals:                   98.0|
| Df model:                        1.0|
==============================================================================
|                   coefficient     std. error    t-statistic          prob. |
------------------------------------------------------------------------------
| x1                      1.007       0.008466       118.9032         0.0000 |
| const                 0.05165       0.005138        10.0515         0.0000 |
==============================================================================
|                          Models stats                      Residual stats  |
------------------------------------------------------------------------------
| R-squared:                     0.9931   Durbin-Watson:              1.484  |
| Adjusted R-squared:            0.9930   Omnibus:                    12.16  |
| F-statistic:                1.414e+04   Prob(Omnibus):           0.002294  |
| Prob (F-statistic):        9.137e-108   JB:                        0.6818  |
| Log likelihood:                 223.8   Prob(JB):                  0.7111  |
| AIC criterion:                 -443.7   Skew:                     -0.2064  |
| BIC criterion:                 -438.5   Kurtosis:                   2.048  |
------------------------------------------------------------------------------

example plot

How to check if a string contains only numbers?

http://msdn.microsoft.com/en-us/library/f02979c7(v=VS.90).aspx

You can pass nothing if you don't need the returned integer like so

if integer.TryParse(number,nothing) then

How to delete a cookie using jQuery?

You can also delete cookies without using jquery.cookie plugin:

document.cookie = 'NAMEOFYOURCOOKIE' + '=; expires=Thu, 01-Jan-70 00:00:01 GMT;';

Including jars in classpath on commandline (javac or apt)

javac HelloWorld.java -classpath ./javax.jar , assuming javax is in current folder, and compile target is "HelloWorld.java", and you can compile without a main method

Convert alphabet letters to number in Python

What about something like this:

print [ord(char) - 96 for char in raw_input('Write Text: ').lower()]

ord
list comprehension
ASCII character codes

EDIT
Since you asked me to explain I will... though it has been explained pretty well in the comments already by [?].

Let's do this in more that one line to start.

input = raw_input('Write Text: ')
input = input.lower()
output = []
for character in input:
    number = ord(character) - 96
    output.append(number)
print output

This does the same thing, but is more readable. Make sure you can understand what is going on here before you try to understand my first answer. Everything here is pretty standard, simple Python. The one thing to note is the ord function. ord stand for ordinal, and pretty much every high level language will have this type of function available. It gives you a mapping to the numerical representation of any character. The inverse function of ord is called chr.

chr(ord('x')) == 'x' # for any character, not just x.

If you test for yourself, the ordinal of a is 97 (the third link I posted above will show the complete ASCII character set.) Each lower case letter is in the range 97-122 (26 characters.) So, if you just subtract 96 from the ordinal of any lower case letter, you will get its position in the alphabet assuming you take 'a' == 1. So, ordinal of 'b' == 98, 'c' == 99, etc. When you subtract 96, 'b' == 2, 'c' == 3, etc.

The rest of the initial solution I posted is just some Python trickery you can learn called list comprehension. But, I wouldn't focus on that as much as I would focus on learning to solve the problem in any language, where ord is your friend. I hope this helps.

Date Conversion from String to sql Date in Java giving different output?

mm is minutes. You want MM for months:

SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MM-yyyy");

Don't feel bad - this exact mistake comes up a lot.

UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactory'

Well, you're getting a java.lang.NoClassDefFoundError. In your pom.xml, hibernate-core version is 3.3.2.GA and declared after hibernate-entitymanager, so it prevails. You can remove that dependency, since will be inherited version 3.6.7.Final from hibernate-entitymanager.

You're using spring-boot as parent, so no need to declare version of some dependencies, since they are managed by spring-boot.

Also, hibernate-commons-annotations is inherited from hibernate-entitymanager and hibernate-annotations is an old version of hibernate-commons-annotations, you can remove both.

Finally, your pom.xml can look like this:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.elsys.internetprogramming.trafficspy.server</groupId>
    <artifactId>TrafficSpyService</artifactId>
    <version>0.1.0</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.2.3.RELEASE</version>
    </parent>

    <dependencies>
        <!-- Spring -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cloud-connectors</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>javax.persistence</artifactId>
            <version>2.0.0</version>
        </dependency>

        <!-- Hibernate -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-pool</groupId>
            <artifactId>commons-pool</artifactId>
        </dependency>

        <!-- MySQL -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
    </dependencies>

    <properties>
        <java.version>1.7</java.version>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-releases</id>
            <url>https://repo.spring.io/libs-release</url>
        </repository>

        <repository>
            <id>codehaus</id>
            <url>http://repository.codehaus.org/org/codehaus</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-releases</id>
            <url>https://repo.spring.io/libs-release</url>
        </pluginRepository>
    </pluginRepositories>

</project>

Let me know if you have a problem.

How to tell if a connection is dead in python

From the link Jweede posted:

exception socket.timeout:

This exception is raised when a timeout occurs on a socket
which has had timeouts enabled via a prior call to settimeout().
The accompanying value is a string whose value is currently
always “timed out”.

Here are the demo server and client programs for the socket module from the python docs

# Echo server program
import socket

HOST = ''                 # Symbolic name meaning all available interfaces
PORT = 50007              # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
    data = conn.recv(1024)
    if not data: break
    conn.send(data)
conn.close()

And the client:

# Echo client program
import socket

HOST = 'daring.cwi.nl'    # The remote host
PORT = 50007              # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send('Hello, world')
data = s.recv(1024)
s.close()
print 'Received', repr(data)

On the docs example page I pulled these from, there are more complex examples that employ this idea, but here is the simple answer:

Assuming you're writing the client program, just put all your code that uses the socket when it is at risk of being dropped, inside a try block...

try:
    s.connect((HOST, PORT))
    s.send("Hello, World!")
    ...
except socket.timeout:
    # whatever you need to do when the connection is dropped

PHP - count specific array values

$array = array("Kyle","Ben","Sue","Phil","Ben","Mary","Sue","Ben");
$counts = array_count_values($array);
echo $counts['Ben'];

Python: Append item to list N times

Use extend to add a list comprehension to the end.

l.extend([x for i in range(100)])

See the Python docs for more information.

Understanding the set() function

Python's sets (and dictionaries) will iterate and print out in some order, but exactly what that order will be is arbitrary, and not guaranteed to remain the same after additions and removals.

Here's an example of a set changing order after a lot of values are added and then removed:

>>> s = set([1,6,8])
>>> print(s)
{8, 1, 6}
>>> s.update(range(10,100000))
>>> for v in range(10, 100000):
    s.remove(v)
>>> print(s)
{1, 6, 8}

This is implementation dependent though, and so you should not rely upon it.

How to parse a string in JavaScript?

as amber and sinan have noted above, the javascritp '.split' method will work just fine. Just pass it the string separator(-) and the string that you intend to split('123-abc-itchy-knee') and it will do the rest.

    var coolVar = '123-abc-itchy-knee';
    var coolVarParts = coolVar.split('-'); // this is an array containing the items

    var1=coolVarParts[0]; //this will retrieve 123

To access each item from the array just use the respective index(indices start at zero).

Eclipse error: 'Failed to create the Java Virtual Machine'

For me it solved by changing the JDK bin path in the Path environment variable. Put the JDK bin path which has jre/bin/client/jvm.dll under JDK home.

How to check if an user is logged in Symfony2 inside a controller?

If you using roles you could check for ROLE_USER that is the solution i use:

if (TRUE === $this->get('security.authorization_checker')->isGranted('ROLE_USER')) {
    // user is logged in
} 

How do I refresh a DIV content?

You can use jQuery to achieve this using simple $.get method. .html work like innerHtml and replace the content of your div.

$.get("/YourUrl", {},
      function (returnedHtml) {
      $("#here").html(returnedHtml);
});

And call this using javascript setInterval method.

Adding asterisk to required fields in Bootstrap 3

I modified the css, as i am using bootstrap 3.3.6

.form-group.required label:after{   
color: #d00;   
font-family: 'FontAwesome'; 
font-weight: normal;
font-size: 10px;
content: "\f069"; 
top:4px;   
position: absolute;   
 margin-left: 8px;
}

the HTML

<div class="form-group required">
 <label for="return_notes"><?= _lang('notes') ?></label>
 <textarea class="form-control" name="return_notes" id="return_notes"  required="required"></textarea>
</div>

openCV program compile error "libopencv_core.so.2.4: cannot open shared object file: No such file or directory" in ubuntu 12.04

Find the folder containing the shared library libopencv_core.so.2.4 using the following command line.

sudo find / -name "libopencv_core.so.2.4*"

Then I got the result:

 /usr/local/lib/libopencv_core.so.2.4.

Create a file called /etc/ld.so.conf.d/opencv.conf and write to it the path to the folder where the binary is stored.For example, I wrote /usr/local/lib/ to my opencv.conf file. Run the command line as follows.

sudo ldconfig -v

Try to run the command again.

Using Server.MapPath() inside a static field in ASP.NET MVC

I think you can try this for calling in from a class

 System.Web.HttpContext.Current.Server.MapPath("~/SignatureImages/");

*----------------Sorry I oversight, for static function already answered the question by adrift*

System.Web.Hosting.HostingEnvironment.MapPath("~/SignatureImages/");

Update

I got exception while using System.Web.Hosting.HostingEnvironment.MapPath("~/SignatureImages/");

Ex details : System.ArgumentException: The relative virtual path 'SignatureImages' is not allowed here. at System.Web.VirtualPath.FailIfRelativePath()

Solution (tested in static webmethod)

System.Web.HttpContext.Current.Server.MapPath("~/SignatureImages/"); Worked

Why do I get "'property cannot be assigned" when sending an SMTP email?

Just need to try this:

string smtpAddress = "smtp.gmail.com";
int portNumber = 587;
bool enableSSL = true;
string emailFrom = "companyemail";
string password = "password";
string emailTo = "Your email";
string subject = "Hello!";
string body = "Hello, Mr.";
MailMessage mail = new MailMessage();
mail.From = new MailAddress(emailFrom);
mail.To.Add(emailTo);
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = true;
using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
{
   smtp.Credentials = new NetworkCredential(emailFrom, password);
   smtp.EnableSsl = enableSSL;
   smtp.Send(mail);
}

Delimiter must not be alphanumeric or backslash and preg_match

Please try with this

 $pattern = "/My name is '\(.*\)' and im fine/"; 

Get pixel color from canvas, on mousemove

calling getImageData every time will slow the process ... to speed up things i recommend store image data and then you can get pix value easily and quickly, so do something like this for better performance

// keep it global
let imgData = false;  // initially no image data we have

// create some function block 
if(imgData === false){   
  // fetch once canvas data     
  var ctx = canvas.getContext("2d");
  imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
}
    // Prepare your X Y coordinates which you will be fetching from your mouse loc
    let x = 100;   // 
    let y = 100;
    // locate index of current pixel
    let index = (y * imgData.width + x) * 4;

        let red = imgData.data[index];
        let green = imgData.data[index+1];
        let blue = imgData.data[index+2];
        let alpha = imgData.data[index+3];
   // Output
   console.log('pix x ' + x +' y '+y+ ' index '+index +' COLOR '+red+','+green+','+blue+','+alpha);

How to delete a cookie?

You can do this by setting the date of expiry to yesterday.

Setting it to "-1" doesn't work. That marks a cookie as a Sessioncookie.

C - gettimeofday for computing time?

If you want to measure code efficiency, or in any other way measure time intervals, the following will be easier:

#include <time.h>

int main()
{
   clock_t start = clock();
   //... do work here
   clock_t end = clock();
   double time_elapsed_in_seconds = (end - start)/(double)CLOCKS_PER_SEC;
   return 0;
}

hth

How to get CPU temperature?

It can be done in your code via WMI. I've found a tool from Microsoft that creates code for it.

The WMI Code Creator tool allows you to generate VBScript, C#, and VB .NET code that uses WMI to complete a management task such as querying for management data, executing a method from a WMI class, or receiving event notifications using WMI.

You can download it here.

How to convert answer into two decimal point

If you just want to print a decimal number with 2 digits after decimal point in specific format no matter of locals use something like this

dim d as double = 1.23456789
dim s as string = d.Tostring("0.##", New System.Globalization.CultureInfo("en-US"))

Is there a way to make Firefox ignore invalid ssl-certificates?

Using a free certificate is a better idea if your developers use Firefox 3. Firefox 3 complains loudly about self-signed certificates, and it is a major annoyance.

How do I print to the debug output window in a Win32 app?

Your Win32 project is likely a GUI project, not a console project. This causes a difference in the executable header. As a result, your GUI project will be responsible for opening its own window. That may be a console window, though. Call AllocConsole() to create it, and use the Win32 console functions to write to it.

How to return multiple values in one column (T-SQL)?

Well... I see that an answer was already accepted... but I think you should see another solutions anyway:

/* EXAMPLE */
DECLARE @UserAliases TABLE(UserId INT , Alias VARCHAR(10))
INSERT INTO @UserAliases (UserId,Alias) SELECT 1,'MrX'
     UNION ALL SELECT 1,'MrY' UNION ALL SELECT 1,'MrA'
     UNION ALL SELECT 2,'Abc' UNION ALL SELECT 2,'Xyz'

/* QUERY */
;WITH tmp AS ( SELECT DISTINCT UserId FROM @UserAliases )
SELECT 
    LEFT(tmp.UserId, 10) +
    '/ ' +
    STUFF(
            (   SELECT ', '+Alias 
                FROM @UserAliases 
                WHERE UserId = tmp.UserId 
                FOR XML PATH('') 
            ) 
            , 1, 2, ''
        ) AS [UserId/Alias]
FROM tmp

/* -- OUTPUT
  UserId/Alias
  1/ MrX, MrY, MrA
  2/ Abc, Xyz    
*/

Make .gitignore ignore everything except a few files

To ignore some files in a directory, you have to do this in the correct order:

For example, ignore everything in folder "application" except index.php and folder "config" pay attention to the order.

You must negate want you want first.

FAILS

application/*

!application/config/*

!application/index.php

WORKS

!application/config/*

!application/index.php

application/*

Reversing a string in C

Just a rearrangement, and safety check. I also removed your non-used return type. I think this is a safe and clean as it gets:

#include <stdio.h>
#include <string.h>

void reverse_string(char *str)
{
    /* skip null */
    if (str == 0)
    {
        return;
    }

    /* skip empty string */
    if (*str == 0)
    {
        return;
    }

    /* get range */
    char *start = str;
    char *end = start + strlen(str) - 1; /* -1 for \0 */
    char temp;

    /* reverse */
    while (end > start)
    {
        /* swap */
        temp = *start;
        *start = *end;
        *end = temp;

        /* move */
        ++start;
        --end;
    }
}


int main(void)
{
    char s1[] = "Reverse me!";
    char s2[] = "abc";
    char s3[] = "ab";
    char s4[] = "a";
    char s5[] = "";

    reverse_string(0);

    reverse_string(s1);
    reverse_string(s2);
    reverse_string(s3);
    reverse_string(s4);
    reverse_string(s5);

    printf("%s\n", s1);
    printf("%s\n", s2);
    printf("%s\n", s3);
    printf("%s\n", s4);
    printf("%s\n", s5);

    return 0;
}

Edited so that end will not point to a possibly bad memory location when strlen is 0.

How do I get a HttpServletRequest in my spring beans?

This is kind of Flex/BlazeDS specific, but here's the solution I've come up with. Sorry if answering my own question is a faux pas.

    HttpServletRequest request = flex.messaging.FlexContext.getHttpRequest();

    Cookie[] cookies = request.getCookies();

    for (Cookie c:cookies)
    {
        log.debug(String.format("Cookie: %s, %s, domain: %s",c.getName(), c.getValue(),c.getDomain()));
    }

It works, I get the cookies. My problem was looking to Spring - BlazeDS had it. Spring probably does too, but I still don't know how to get to it.

Blade if(isset) is not working Laravel

@forelse ($users as $user)
    <li>{{ $user->name }}</li>
@empty
    <p>No users</p>
@endforelse

Maximum request length exceeded.

It may be worth noting that you may want to limit this change to the URL you expect to be used for the upload rather then your entire site.

<location path="Documents/Upload">
  <system.web>
    <!-- 50MB in kilobytes, default is 4096 or 4MB-->
    <httpRuntime maxRequestLength="51200" />
  </system.web>
  <system.webServer>
    <security>
      <requestFiltering>
        <!-- 50MB in bytes, default is 30000000 or approx. 28.6102 Mb-->
        <requestLimits maxAllowedContentLength="52428800" /> 
      </requestFiltering>
    </security>
  </system.webServer>
</location>

Using Javascript in CSS

Not in any conventional sense of the phrase "inside CSS."

HTML Upload MAX_FILE_SIZE does not appear to work

There IS A POINT in introducing MAX_FILE_SIZE client side hidden form field.

php.ini can limit uploaded file size. So, while your script honors the limit imposed by php.ini, different HTML forms can further limit an uploaded file size. So, when uploading video, form may limit* maximum size to 10MB, and while uploading photos, forms may put a limit of just 1mb. And at the same time, the maximum limit can be set in php.ini to suppose 10mb to allow all this.

Although this is not a fool proof way of telling the server what to do, yet it can be helpful.

  • HTML does'nt limit anything. It just forwards the server all form variable including MAX_FILE_SIZE and its value.

Hope it helped someone.

How to fix corrupted git repository?

I was facing the same issue, so I replaced the ".git" folder with a backed up version and it still wasn't working because .gitconfig file was corrupted. The BSOD on my laptop corrupted it. I replaced it with the following code and sourcetree restored all my repositories.

[user]
name = *your username*
email = *your email address*
[core]
autocrlf = true
excludesfile = C:\\Users\\*user name*\\Documents\\gitignore_global.txt

I don't know if this will help anybody, but this is just another solution that worked for me.

How to create new div dynamically, change it, move it, modify it in every way possible, in JavaScript?

Have you tried JQuery? Vanilla javascript can be tough. Try using this:

$('.container-element').add('<div>Insert Div Content</div>');

.container-element is a JQuery selector that marks the element with the class "container-element" (presumably the parent element in which you want to insert your divs). Then the add() function inserts HTML into the container-element.

How to analyze a JMeter summary report?

Short explanation looks like:

  1. Sample - number of requests sent
  2. Avg - an Arithmetic mean for all responses (sum of all times / count)
  3. Minimal response time (ms)
  4. Maximum response time (ms)
  5. Deviation - see Standard Deviation article
  6. Error rate - percentage of failed tests
  7. Throughput - how many requests per second does your server handle. Larger is better.
  8. KB/Sec - self expalanatory
  9. Avg. Bytes - average response size

If you having troubles with interpreting results you could try BM.Sense results analysis service

How to programmatically open the Permission Screen for a specific app on Android Marshmallow?

According to the official Marshmallow permissions video (at the 4m 43s mark), you must open the application Settings page instead (from there it is one click to the Permissions page).

To open the settings page, you would do

Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivity(intent);

Not receiving Google OAuth refresh token

1. How to get 'refresh_token' ?

Solution: access_type='offline' option should be used when generating authURL. source : Using OAuth 2.0 for Web Server Applications

2. But even with 'access_type=offline', I am not getting the 'refresh_token' ?

Solution: Please note that you will get it only on the first request, so if you are storing it somewhere and there is a provision to overwrite this in your code when getting new access_token after previous expires, then make sure not to overwrite this value.

From Google Auth Doc : (this value = access_type)

This value instructs the Google authorization server to return a refresh token and an access token the first time that your application exchanges an authorization code for tokens.

If you need 'refresh_token' again, then you need to remove access for your app as by following the steps written in Rich Sutton's answer.

How to convert an Instant to a date format?

Instant i = Instant.ofEpochSecond(cal.getTime);

Read more here and here

How to handle anchor hash linking in AngularJS

Here is kind of dirty workaround by creating custom directive that will scrolls to specified element (with hardcoded "faq")

app.directive('h3', function($routeParams) {
  return {
    restrict: 'E',
    link: function(scope, element, attrs){        
        if ('faq'+$routeParams.v == attrs.id) {
          setTimeout(function() {
             window.scrollTo(0, element[0].offsetTop);
          },1);        
        }
    }
  };
});

http://plnkr.co/edit/Po37JFeP5IsNoz5ZycFs?p=preview

How can I copy a Python string?

I'm just starting some string manipulations and found this question. I was probably trying to do something like the OP, "usual me". The previous answers did not clear up my confusion, but after thinking a little about it I finally "got it".

As long as a, b, c, d, and e have the same value, they reference to the same place. Memory is saved. As soon as the variable start to have different values, they get start to have different references. My learning experience came from this code:

import copy
a = 'hello'
b = str(a)
c = a[:]
d = a + ''
e = copy.copy(a)

print map( id, [ a,b,c,d,e ] )

print a, b, c, d, e

e = a + 'something'
a = 'goodbye'
print map( id, [ a,b,c,d,e ] )
print a, b, c, d, e

The printed output is:

[4538504992, 4538504992, 4538504992, 4538504992, 4538504992]

hello hello hello hello hello

[6113502048, 4538504992, 4538504992, 4538504992, 5570935808]

goodbye hello hello hello hello something

Reading/writing an INI file

Preface

Firstly, read this MSDN blog post on the limitations of INI files. If it suits your needs, read on.

This is a concise implementation I wrote, utilising the original Windows P/Invoke, so it is supported by all versions of Windows with .NET installed, (i.e. Windows 98 - Windows 10). I hereby release it into the public domain - you're free to use it commercially without attribution.

The tiny class

Add a new class called IniFile.cs to your project:

using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;

// Change this to match your program's normal namespace
namespace MyProg
{
    class IniFile   // revision 11
    {
        string Path;
        string EXE = Assembly.GetExecutingAssembly().GetName().Name;

        [DllImport("kernel32", CharSet = CharSet.Unicode)]
        static extern long WritePrivateProfileString(string Section, string Key, string Value, string FilePath);

        [DllImport("kernel32", CharSet = CharSet.Unicode)]
        static extern int GetPrivateProfileString(string Section, string Key, string Default, StringBuilder RetVal, int Size, string FilePath);

        public IniFile(string IniPath = null)
        {
            Path = new FileInfo(IniPath ?? EXE + ".ini").FullName;
        }

        public string Read(string Key, string Section = null)
        {
            var RetVal = new StringBuilder(255);
            GetPrivateProfileString(Section ?? EXE, Key, "", RetVal, 255, Path);
            return RetVal.ToString();
        }

        public void Write(string Key, string Value, string Section = null)
        {
            WritePrivateProfileString(Section ?? EXE, Key, Value, Path);
        }

        public void DeleteKey(string Key, string Section = null)
        {
            Write(Key, null, Section ?? EXE);
        }

        public void DeleteSection(string Section = null)
        {
            Write(null, null, Section ?? EXE);
        }

        public bool KeyExists(string Key, string Section = null)
        {
            return Read(Key, Section).Length > 0;
        }
    }
}

How to use it

Open the INI file in one of the 3 following ways:

// Creates or loads an INI file in the same directory as your executable
// named EXE.ini (where EXE is the name of your executable)
var MyIni = new IniFile();

// Or specify a specific name in the current dir
var MyIni = new IniFile("Settings.ini");

// Or specify a specific name in a specific dir
var MyIni = new IniFile(@"C:\Settings.ini");

You can write some values like so:

MyIni.Write("DefaultVolume", "100");
MyIni.Write("HomePage", "http://www.google.com");

To create a file like this:

[MyProg]
DefaultVolume=100
HomePage=http://www.google.com

To read the values out of the INI file:

var DefaultVolume = MyIni.Read("DefaultVolume");
var HomePage = MyIni.Read("HomePage");

Optionally, you can set [Section]'s:

MyIni.Write("DefaultVolume", "100", "Audio");
MyIni.Write("HomePage", "http://www.google.com", "Web");

To create a file like this:

[Audio]
DefaultVolume=100

[Web]
HomePage=http://www.google.com

You can also check for the existence of a key like so:

if(!MyIni.KeyExists("DefaultVolume", "Audio"))
{
    MyIni.Write("DefaultVolume", "100", "Audio");
}

You can delete a key like so:

MyIni.DeleteKey("DefaultVolume", "Audio");

You can also delete a whole section (including all keys) like so:

MyIni.DeleteSection("Web");

Please feel free to comment with any improvements!

Transparent background in JPEG image

JPEG can't support transparency because it uses RGB color space. If you want transparency use a format that supports alpha values. Example PNG is an image format that uses RGBA color space where (r = red, g = green, b = blue, a = alpha value). Alpha value is used as an opacity measure, 0% is fully transparent and 100% is completely opaque. pixel.

Angularjs if-then-else construction in expression

You can use ternary operator since version 1.1.5 and above like demonstrated in this little plunker (example in 1.1.5):

For history reasons (maybe plnkr.co get down for some reason in the future) here is the main code of my example:

{{true?true:false}}

How can I make XSLT work in chrome?

I had the same problem on localhost. Running around the Internet looking for the answer and I approve that adding --allow-file-access-from-files works. I work on Mac, so for me I had to go through terminal sudo /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --allow-file-access-from-files and enter your password (if you have one).

Another small thing - nothing will work unless you add to your .xml file the reference to your .xsl file as follows <?xml-stylesheet type="text/xsl" href="<path to file>"?>. Another small thing I didn't realise immediately - you should be opening your .xml file in browser, no the .xsl.

Parsing json and searching through it

As json.loads simply returns a dict, you can use the operators that apply to dicts:

>>> jdata = json.load('{"uri": "http:", "foo", "bar"}')
>>> 'uri' in jdata       # Check if 'uri' is in jdata's keys
True
>>> jdata['uri']         # Will return the value belonging to the key 'uri'
u'http:'

Edit: to give an idea regarding how to loop through the data, consider the following example:

>>> import json
>>> jdata = json.loads(open ('bookmarks.json').read())
>>> for c in jdata['children'][0]['children']:
...     print 'Title: {}, URI: {}'.format(c.get('title', 'No title'),
                                          c.get('uri', 'No uri'))
...
Title: Recently Bookmarked, URI: place:folder=BOOKMARKS_MENU(...)
Title: Recent Tags, URI: place:sort=14&type=6&maxResults=10&queryType=1
Title: , URI: No uri
Title: Mozilla Firefox, URI: No uri

Inspecting the jdata data structure will allow you to navigate it as you wish. The pprint call you already have is a good starting point for this.

Edit2: Another attempt. This gets the file you mentioned in a list of dictionaries. With this, I think you should be able to adapt it to your needs.

>>> def build_structure(data, d=[]):
...     if 'children' in data:
...         for c in data['children']:
...             d.append({'title': c.get('title', 'No title'),
...                                      'uri': c.get('uri', None)})
...             build_structure(c, d)
...     return d
...
>>> pprint.pprint(build_structure(jdata))
[{'title': u'Bookmarks Menu', 'uri': None},
 {'title': u'Recently Bookmarked',
  'uri':   u'place:folder=BOOKMARKS_MENU&folder=UNFILED_BOOKMARKS&(...)'},
 {'title': u'Recent Tags',
  'uri':   u'place:sort=14&type=6&maxResults=10&queryType=1'},
 {'title': u'', 'uri': None},
 {'title': u'Mozilla Firefox', 'uri': None},
 {'title': u'Help and Tutorials',
  'uri':   u'http://www.mozilla.com/en-US/firefox/help/'},
 (...)
}]

To then "search through it for u'uri': u'http:'", do something like this:

for c in build_structure(jdata):
    if c['uri'].startswith('http:'):
        print 'Started with http'

Case insensitive searching in Oracle

From Oracle 12c R2 you could use COLLATE operator:

The COLLATE operator determines the collation for an expression. This operator enables you to override the collation that the database would have derived for the expression using standard collation derivation rules.

The COLLATE operator takes one argument, collation_name, for which you can specify a named collation or pseudo-collation. If the collation name contains a space, then you must enclose the name in double quotation marks.

Demo:

CREATE TABLE tab1(i INT PRIMARY KEY, name VARCHAR2(100));

INSERT INTO tab1(i, name) VALUES (1, 'John');
INSERT INTO tab1(i, name) VALUES (2, 'Joe');
INSERT INTO tab1(i, name) VALUES (3, 'Billy'); 
--========================================================================--
SELECT /*csv*/ *
FROM tab1
WHERE name = 'jOHN' ;
-- no rows selected

SELECT /*csv*/ *
FROM tab1
WHERE name COLLATE BINARY_CI = 'jOHN' ;
/*
"I","NAME"
1,"John"
*/

SELECT /*csv*/ *
FROM tab1 
WHERE name LIKE 'j%';
-- no rows selected

SELECT /*csv*/ *
FROM tab1 
WHERE name COLLATE BINARY_CI LIKE 'j%';
/*
"I","NAME"
1,"John"
2,"Joe"
*/

db<>fiddle demo

UPDATE multiple tables in MySQL using LEFT JOIN

UPDATE `Table A` a
SET a.`text`=(
        SELECT group_concat(b.`B-num`,' from ',b.`date` SEPARATOR ' / ') 
        FROM `Table B` b WHERE (a.`A-num`=b.`A-num`)
)

Get Return Value from Stored procedure in asp.net

Procedure never returns a value.You have to use a output parameter in store procedure.

ALTER PROC TESTLOGIN
@UserName   varchar(50),
@password   varchar(50)
@retvalue int output
 as
 Begin
    declare @return     int 
    set @return  = (Select COUNT(*) 
    FROM    CPUser  
    WHERE   UserName = @UserName AND Password = @password)

   set @retvalue=@return
  End

Then you have to add a sqlparameter from c# whose parameter direction is out. Hope this make sense.

How to disable <br> tags inside <div> by css?

<p style="color:black">Shop our collection of beautiful women's <br> <span> wedding ring in classic &amp; modern design.</span></p>

Remove <br> effect using CSS.

<style> p br{ display:none; } </style>

Converting .NET DateTime to JSON

The previous answers all state that you can do the following:

var d = eval(net_datetime.slice(1, -1));

However, this doesn't work in either Chrome or FF because what's getting evaluated literally is:

// returns the current timestamp instead of the specified epoch timestamp
var d = Date([epoch timestamp]);

The correct way to do this is:

var d = eval("new " + net_datetime.slice(1, -1)); // which parses to

var d = new Date([epoch timestamp]); 

How do I copy a range of formula values and paste them to a specific range in another sheet?

You can change

Range("B3:B65536").Copy Destination:=Sheets("DB").Range("B" & lastrow)

to

Range("B3:B65536").Copy 
Sheets("DB").Range("B" & lastrow).PasteSpecial xlPasteValues

BTW, if you have xls file (excel 2003), you would get an error if your lastrow would be greater 3.

Try to use this code instead:

Sub Get_Data()
    Dim lastrowDB As Long, lastrow As Long
    Dim arr1, arr2, i As Integer

    With Sheets("DB")
        lastrowDB = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
    End With

    arr1 = Array("B", "C", "D", "E", "F", "AH", "AI", "AJ", "J", "P", "AF")
    arr2 = Array("B", "A", "C", "P", "D", "E", "G", "F", "H", "I", "J")

    For i = LBound(arr1) To UBound(arr1)
        With Sheets("Sheet1")
             lastrow = Application.Max(3, .Cells(.Rows.Count, arr1(i)).End(xlUp).Row)
             .Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Copy
             Sheets("DB").Range(arr2(i) & lastrowDB).PasteSpecial xlPasteValues
        End With
    Next
    Application.CutCopyMode = False
End Sub

Note, above code determines last non empty row on DB sheet in column A (variable lastrowDB). If you need to find lastrow for each destination column in DB sheet, use next modification:

For i = LBound(arr1) To UBound(arr1)
   With Sheets("DB")
       lastrowDB = .Cells(.Rows.Count, arr2(i)).End(xlUp).Row + 1
   End With

   ' NEXT CODE

Next

You could also use next approach instead Copy/PasteSpecial. Replace

.Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Copy
Sheets("DB").Range(arr2(i) & lastrowDB).PasteSpecial xlPasteValues

with

Sheets("DB").Range(arr2(i) & lastrowDB).Resize(lastrow - 2).Value = _
      .Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Value

Autocomplete syntax for HTML or PHP in Notepad++. Not auto-close, autocompelete

If you want extended auto-completion for PHP (not only for the code in the current window or standard classes), try out the "ACCPC" plugin: https://github.com/StanDog/npp-phpautocompletion

Circular gradient in android

I guess you should add android:centerColor

<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
  android:startColor="#FFFFFF"
  android:centerColor="#000000"
  android:endColor="#FFFFFF"
  android:angle="0" />
</shape>

This example displays a horizontal gradient from white to black to white.

Declaring and initializing arrays in C

No, you can't set them to arbitrary values in one statement (unless done as part of the declaration).

You can either do it with code, something like:

myArray[0] = 1;
myArray[1] = 2;
myArray[2] = 27;
:
myArray[99] = -7;

or (if there's a formula):

for (int i = 0; i < 100; i++) myArray[i] = i + 1;

The other possibility is to keep around some templates that are set at declaration time and use them to initialise your array, something like:

static const int onceArr[]  = {  0,  1,  2,  3,  4,..., 99};
static const int twiceArr[] = {  0,  2,  4,  6,  8,...,198};
:
int myArray[7];
:
memcpy (myArray, twiceArr, sizeof (myArray));

This has the advantage of (most likely) being faster and allows you to create smaller arrays than the templates. I've used this method in situations where I have to re-initialise an array fast but to a specific state (if the state were all zeros, I would just use memset).


You can even localise it to an initialisation function:

void initMyArray (int *arr, size_t sz) {
    static const int template[] = {2, 3, 5, 7, 11, 13, 17, 19, 21, ..., 9973};
    memcpy (arr, template, sz);
}
:
int myArray[100];
initMyArray (myArray, sizeof(myArray));

The static array will (almost certainly) be created at compile time so there will be no run-time cost for that, and the memcpy should be blindingly fast, likely faster than 1,229 assignment statements but very definitely less typing on your part :-).

How to use font-awesome icons from node-modules

SASS modules version

Soon, using @import in sass will be depreciated. SASS modules configuration works using @use instead.

@use "../node_modules/font-awesome/scss/font-awesome"  with (
  $fa-font-path: "../icons"
);

.icon-user {
  @extend .fa;
  @extend .fa-user;
}

What is the bit size of long on 64-bit Windows?

In the Unix world, there were a few possible arrangements for the sizes of integers and pointers for 64-bit platforms. The two mostly widely used were ILP64 (actually, only a very few examples of this; Cray was one such) and LP64 (for almost everything else). The acronynms come from 'int, long, pointers are 64-bit' and 'long, pointers are 64-bit'.

Type           ILP64   LP64   LLP64
char              8      8       8
short            16     16      16
int              64     32      32
long             64     64      32
long long        64     64      64
pointer          64     64      64

The ILP64 system was abandoned in favour of LP64 (that is, almost all later entrants used LP64, based on the recommendations of the Aspen group; only systems with a long heritage of 64-bit operation use a different scheme). All modern 64-bit Unix systems use LP64. MacOS X and Linux are both modern 64-bit systems.

Microsoft uses a different scheme for transitioning to 64-bit: LLP64 ('long long, pointers are 64-bit'). This has the merit of meaning that 32-bit software can be recompiled without change. It has the demerit of being different from what everyone else does, and also requires code to be revised to exploit 64-bit capacities. There always was revision necessary; it was just a different set of revisions from the ones needed on Unix platforms.

If you design your software around platform-neutral integer type names, probably using the C99 <inttypes.h> header, which, when the types are available on the platform, provides, in signed (listed) and unsigned (not listed; prefix with 'u'):

  • int8_t - 8-bit integers
  • int16_t - 16-bit integers
  • int32_t - 32-bit integers
  • int64_t - 64-bit integers
  • uintptr_t - unsigned integers big enough to hold pointers
  • intmax_t - biggest size of integer on the platform (might be larger than int64_t)

You can then code your application using these types where it matters, and being very careful with system types (which might be different). There is an intptr_t type - a signed integer type for holding pointers; you should plan on not using it, or only using it as the result of a subtraction of two uintptr_t values (ptrdiff_t).

But, as the question points out (in disbelief), there are different systems for the sizes of the integer data types on 64-bit machines. Get used to it; the world isn't going to change.

Best way to use Google's hosted jQuery, but fall back to my hosted library on Google fail

if (typeof jQuery == 'undefined')) { ...

Or

if(!window.jQuery){

Will not works if cdn version not loaded, because browser will run through this condition and during it still downloading the rest of javascripts which needs jQuery and it returns error. Solution was to load scripts through that condition.

    <script src="http://WRONGPATH.code.jquery.com/jquery-1.4.2.min.js" type="text/javascript"></script><!--  WRONGPATH for test-->
  <script type="text/javascript">
  function loadCDN_or_local(){
    if(!window.jQuery){//jQuery not loaded, take a local copy of jQuery and then my scripts
      var scripts=['local_copy_jquery.js','my_javascripts.js'];
      for(var i=0;i<scripts.length;i++){
      scri=document.getElementsByTagName('head')[0].appendChild(document.createElement('script'));
      scri.type='text/javascript';
      scri.src=scripts[i];
    }
  }
  else{// jQuery loaded can load my scripts
    var s=document.getElementsByTagName('head')[0].appendChild(document.createElement('script'));
    s.type='text/javascript';
    s.src='my_javascripts.js';
  }
  }
  window.onload=function(){loadCDN_or_local();};
  </script>

Error message "Linter pylint is not installed"

I had the same problem. Open the cmd and type:

python -m pip install pylint

Heroku 'Permission denied (publickey) fatal: Could not read from remote repository' woes

you need to create a new ssh key by typing the following - ssh-keygen -t rsa

Then you need to add: - heroku keys:add

Then if you type - heroku open

The problem has been solved.

It worked for me anyway, you could give it a try...

How to wrap text in textview in Android

By setting android:maxEms to a given value together with android:layout_weight="1" will cause the TextView to wrap once it reaches the given length of the ems.

rotating axis labels in R

Use par(las=1).

See ?par:

las
numeric in {0,1,2,3}; the style of axis labels.
0: always parallel to the axis [default],
1: always horizontal,
2: always perpendicular to the axis,
3: always vertical.

How can I initialize C++ object member variables in the constructor?

You're trying to create a ThingOne by using operator= which isn't going to work (incorrect syntax). Also, you're using a class name as a variable name, that is, ThingOne* ThingOne. Firstly, let's fix the variable names:

private:
    ThingOne* t1;
    ThingTwo* t2;

Since these are pointers, they must point to something. If the object hasn't been constructed yet, you'll need to do so explicitly with new in your BigMommaClass constructor:

BigMommaClass::BigMommaClass(int n1, int n2)
{
    t1 = new ThingOne(100);
    t2 = new ThingTwo(n1, n2);
}

Generally initializer lists are preferred for construction however, so it will look like:

BigMommaClass::BigMommaClass(int n1, int n2)
    : t1(new ThingOne(100)), t2(new ThingTwo(n1, n2))
{ }

Composer install error - requires ext_curl when it's actually enabled

This worked for me: http://ubuntuforums.org/showthread.php?t=1519176

After installing composer using the command curl -sS https://getcomposer.org/installer | php just run a sudo apt-get update then reinstall curl with sudo apt-get install php5-curl. Then composer's installation process should work so you can finally run php composer.phar install to get the dependencies listed in your composer.json file.

Failed to load resource: the server responded with a status of 404 (Not Found) css

you have defined the public dir in app root/public

app.use(express.static(__dirname + '/public')); 

so you have to use:

./css/main.css

How do I change button size in Python?

I've always used .place() for my tkinter widgets. place syntax

You can specify the size of it just by changing the keyword arguments!

Of course, you will have to call .place() again if you want to change it.

Works in python 3.8.2, if you're wondering.

Cannot connect to local SQL Server with Management Studio

I was having this problem on a Windows 7 (64 bit) after a power outage. The SQLEXPRESS service was not started even though is status was set to 'Automatic' and the mahine had been rebooted several times. Had to start the service manually.

How do I remove the file suffix and path portion from a path string in Bash?

The basename does that, removes the path. It will also remove the suffix if given and if it matches the suffix of the file but you would need to know the suffix to give to the command. Otherwise you can use mv and figure out what the new name should be some other way.

Doctrine - How to print out the real sql, not just the prepared statement?

getSqlQuery() does technically show the whole SQL command, but it's a lot more useful when you can see the parameters as well.

echo $q->getSqlQuery();
foreach ($q->getFlattenedParams() as $index => $param)
  echo "$index => $param";

To make this pattern more reusable, there's a nice approach described in the comments at Raw SQL from Doctrine Query Object.

How do I compile jrxml to get jasper?

Using Version 5.1.0:

Just click preview and it will create a YourReportName.jasper for you in the same working directory.

How to create byte array from HttpPostedFile

in your question, both buffer and byteArray seem to be byte[]. So:

ImageElement image = ImageElement.FromBinary(buffer);

How to Deserialize JSON data?

Step 1: Go to json.org to find the JSON library for whatever technology you're using to call this web service. Download and link to that library.

Step 2: Let's say you're using Java. You would use JSONArray like this:

JSONArray myArray=new JSONArray(queryResponse);
for (int i=0;i<myArray.length;i++){
    JSONArray myInteriorArray=myArray.getJSONArray(i);
    if (i==0) {
        //this is the first one and is special because it holds the name of the query.
    }else{
        //do your stuff
        String stateCode=myInteriorArray.getString(0);
        String stateName=myInteriorArray.getString(1);
    }
}

CSS Circular Cropping of Rectangle Image

If you can live without the <img> tag, I suggest you use the photo as a background image.

_x000D_
_x000D_
.cropcircle{_x000D_
    width: 250px;_x000D_
    height: 250px;_x000D_
    border-radius: 100%;_x000D_
    background: #eee no-repeat center;_x000D_
    background-size: cover;_x000D_
}_x000D_
_x000D_
#image1{_x000D_
    background-image: url(http://www.voont.com/files/images/edit/7-ridiculous-ways-boost-self-esteem/happy.jpg);_x000D_
}
_x000D_
<div id="image1" class="cropcircle"></div>
_x000D_
_x000D_
_x000D_

How do I work with a git repository within another repository?

I had issues with subtrees and submodules that the other answers suggest... mainly because I am using SourceTree and it seems fairly buggy.

Instead, I ended up using SymLinks and that seems to work well so I am posting it here as a possible alternative.

There is a complete guide here: http://www.howtogeek.com/howto/16226/complete-guide-to-symbolic-links-symlinks-on-windows-or-linux/

But basically you just need to mklink the two paths in an elevated command prompt. Make sure you use the /J hard link prefix. Something along these lines: mklink /J C:\projects\MainProject\plugins C:\projects\SomePlugin

You can also use relative folder paths and put it in a bat to be executed by each person when they first check out your project.

Example: mklink /J .\Assets\TaqtileTools ..\TaqtileHoloTools

Once the folder has been linked you may need to ignore the folder within your main repository that is referencing it. Otherwise you are good to go.

Note I've deleted my duplicate answer from another post as that post was marked as a duplicate question to this one.

What are the differences between the BLOB and TEXT datatypes in MySQL?

BLOB stores binary data which are more than 2 GB. Max size for BLOB is 4 GB. Binary data means unstructured data i.e images audio files vedio files digital signature

Text is used to store large string.

How to create a template function within a class? (C++)

See here: Templates, template methods,Member Templates, Member Function Templates

class   Vector
{
  int     array[3];

  template <class TVECTOR2> 
  void  eqAdd(TVECTOR2 v2);
};

template <class TVECTOR2>
void    Vector::eqAdd(TVECTOR2 a2)
{
  for (int i(0); i < 3; ++i) array[i] += a2[i];
}

How to get json key and value in javascript?

http://jsfiddle.net/v8aWF/

Worked out a fiddle. Do check it out

(function() {
    var oJson = {
        "name": "", 
        "skills": "", 
        "jobtitle": "Entwickler", 
        "res_linkedin": "GwebSearch"
    }
    alert(oJson.jobtitle);
})();

Convert NVARCHAR to DATETIME in SQL Server 2008

As your data is nvarchar there is no guarantee it will convert to datetime (as it may hold invalid date/time information) - so a way to handle this is to use ISDATE which I would use within a cross apply. (Cross apply results are reusable hence making is easier for the output formats.)

|                     YOUR_DT |             SQL2008 |
|-----------------------------|---------------------|
|         2013-08-29 13:55:48 | 29-08-2013 13:55:48 |
|    2013-08-29 13:55:48 blah |              (null) |
| 2013-08-29 13:55:48 rubbish |              (null) |

SELECT
  [Your_Dt]
, convert(varchar, ca1.dt_converted ,105) + ' ' + convert(varchar, ca1.dt_converted ,8) AS sql2008
FROM your_table
CROSS apply ( SELECT CASE WHEN isdate([Your_Dt]) = 1
                        THEN convert(datetime,[Your_Dt])
                        ELSE NULL
                     END
            ) AS ca1 (dt_converted)
;

Notes:

You could also introduce left([Your_Dt],19) to only get a string like '2013-08-29 13:55:48' from '2013-08-29 13:55:48 rubbish'

For that specific output I think you will need 2 sql 2008 date styles (105 & 8) sql2012 added for comparison

declare @your_dt as datetime2
set @your_dt = '2013-08-29 13:55:48'

select
  FORMAT(@your_dt, 'dd-MM-yyyy H:m:s') as sql2012
, convert(varchar, @your_dt ,105) + ' ' + convert(varchar, @your_dt ,8) as sql2008

|             SQL2012 |             SQL2008 |
|---------------------|---------------------|
| 29-08-2013 13:55:48 | 29-08-2013 13:55:48 | 

Better/Faster to Loop through set or list?

set is what you want, so you should use set. Trying to be clever introduces subtle bugs like forgetting to add one tomax(mylist)! Code defensively. Worry about what's faster when you determine that it is too slow.

range(min(mylist), max(mylist) + 1)  # <-- don't forget to add 1

Where/how can I download (and install) the Microsoft.Jet.OLEDB.4.0 for Windows 8, 64 bit?

Make sure to target x86 on your project in Visual Studio. This should fix your trouble.

Why can't I enter a string in Scanner(System.in), when calling nextLine()-method?

use a temporary scan.nextLine(); this will consume the \n character

Downloading a picture via urllib and python

For Python 3 you will need to import import urllib.request:

import urllib.request 

urllib.request.urlretrieve(url, filename)

for more info check out the link

Insert text into textarea with jQuery

What you ask for should be reasonably straightforward in jQuery-

$(function() {
    $('#myAnchorId').click(function() { 
        var areaValue = $('#area').val();
        $('#area').val(areaValue + 'Whatever you want to enter');
    });
});

The best way that I can think of highlighting inserted text is by wrapping it in a span with a CSS class with background-color set to the color of your choice. On the next insert, you could remove the class from any existing spans (or strip the spans out).

However, There are plenty of free WYSIWYG HTML/Rich Text editors available on the market, I'm sure one will fit your needs

What is the simplest way to convert array to vector?

One simple way can be the use of assign() function that is pre-defined in vector class.

e.g.

array[5]={1,2,3,4,5};

vector<int> v;
v.assign(array, array+5); // 5 is size of array.

Differences between CHMOD 755 vs 750 permissions set

0755 = User:rwx Group:r-x World:r-x

0750 = User:rwx Group:r-x World:--- (i.e. World: no access)

r = read
w = write
x = execute (traverse for directories)

Difference between window.location.href=window.location.href and window.location.reload()

If you say window.location.reload(true) the browser will skip the cache and reload the page from the server. window.location.reload(false) will do the opposite.

Note: default value for window.location.reload() is false

Adjusting the Xcode iPhone simulator scale and size

You can't have 1:1 ratio.

However you can scale it from the iOS Simulator > Window > Scale menu.

python numpy machine epsilon

An easier way to get the machine epsilon for a given float type is to use np.finfo():

print(np.finfo(float).eps)
# 2.22044604925e-16

print(np.finfo(np.float32).eps)
# 1.19209e-07

What is "with (nolock)" in SQL Server?

I use with (nolock) hint particularly in SQLServer 2000 databases with high activity. I am not certain that it is needed in SQL Server 2005 however. I recently added that hint in a SQL Server 2000 at the request of the client's DBA, because he was noticing a lot of SPID record locks.

All I can say is that using the hint has NOT hurt us and appears to have made the locking problem solve itself. The DBA at that particular client basically insisted that we use the hint.

By the way, the databases I deal with are back-ends to enterprise medical claims systems, so we are talking about millions of records and 20+ tables in many joins. I typically add a WITH (nolock) hint for each table in the join (unless it is a derived table, in which case you can't use that particular hint)

CSS container div not getting height

You are floating the children which means they "float" in front of the container. In order to take the correct height, you must "clear" the float

The div style="clear: both" clears the floating an gives the correct height to the container. see http://css.maxdesign.com.au/floatutorial/clear.htm for more info on floats.

eg.

<div class="c">
    <div class="l">

    </div>
    <div class="m">
        World
    </div>
    <div style="clear: both" />
</div>

Can you "compile" PHP code and upload a binary-ish file, which will just be run by the byte code interpreter?

Um, anybody heard of Zend Guard, which does exactly what this person is asking. It encodes/obfuscates PHP code into "machine code".

How to get week number of the month from the date in sql server 2008

Just look at the date and see what range it falls in.

Range 1-7 is the 1st week, Range 8-14 is the 2nd week, etc.

SELECT 
CASE WHEN DATEPART(day,yourdate) < 8 THEN '1' 
  ELSE CASE WHEN DATEPART(day,yourdate) < 15 then '2' 
    ELSE CASE WHEN  DATEPART(day,yourdate) < 22 then '3' 
      ELSE CASE WHEN  DATEPART(day,yourdate) < 29 then '4'     
        ELSE '5'
      END
    END
  END
END

Counting array elements in Perl

It sounds like you want a sparse array. A normal array would have 24 items in it, but a sparse array would have 3. In Perl we emulate sparse arrays with hashes:

#!/usr/bin/perl

use strict;
use warnings;

my %sparse;

@sparse{0, 5, 23} = (1 .. 3);

print "there are ", scalar keys %sparse, " items in the sparse array\n",
    map { "\t$sparse{$_}\n" } sort { $a <=> $b } keys %sparse;

The keys function in scalar context will return the number of items in the sparse array. The only downside to using a hash to emulate a sparse array is that you must sort the keys before iterating over them if their order is important.

You must also remember to use the delete function to remove items from the sparse array (just setting their value to undef is not enough).

How to include bootstrap css and js in reactjs app?

Here is how to include latest bootstrap
https://react-bootstrap.github.io/getting-started/introduction

1.Install

npm install react-bootstrap bootstrap

  1. then import to App.js import 'bootstrap/dist/css/bootstrap.min.css';

  2. Then you need to import the components that you use at your app, example If you use navbar, nav, button, form, formcontrol then import all of these like below:

import Navbar from 'react-bootstrap/Navbar'
import Nav from 'react-bootstrap/Nav'
import Form from 'react-bootstrap/Form'
import FormControl from 'react-bootstrap/FormControl'
import Button from 'react-bootstrap/Button'


// or less ideally
import { Button } from 'react-bootstrap';

difference between primary key and unique key

difference between Primary Key and Unique Key

Both Primary key and Unique Key are used to uniquely define of a row in a table. Primary Key creates a clustered index of the column whereas a Unique creates an unclustered index of the column.

A Primary Key doesn’t allow NULL value, however a Unique Key does allow one NULL value.

convert string to char*

First of all, you would have to allocate memory:

char * S = new char[R.length() + 1];

then you can use strcpy with S and R.c_str():

std::strcpy(S,R.c_str());

You can also use R.c_str() if the string doesn't get changed or the c string is only used once. However, if S is going to be modified, you should copy the string, as writing to R.c_str() results in undefined behavior.

Note: Instead of strcpy you can also use str::copy.

How to continue the code on the next line in VBA

To have newline in code you use _

Example:

Dim a As Integer
a = 500 _
  + 80 _
  + 90

MsgBox a

Detecting which UIButton was pressed in a UITableView

create an nsmutable array and put all button in that array usint[array addObject:yourButton];

in the button press method

-

 (void)buttonPressedAction:(id)sender
{
    UIButton *button = (UIButton *)sender;

for(int i=0;i<[yourArray count];i++){

if([buton isEqual:[yourArray objectAtIndex:i]]){

//here write wat u need to do

}
}

IOCTL Linux device driver

An ioctl, which means "input-output control" is a kind of device-specific system call. There are only a few system calls in Linux (300-400), which are not enough to express all the unique functions devices may have. So a driver can define an ioctl which allows a userspace application to send it orders. However, ioctls are not very flexible and tend to get a bit cluttered (dozens of "magic numbers" which just work... or not), and can also be insecure, as you pass a buffer into the kernel - bad handling can break things easily.

An alternative is the sysfs interface, where you set up a file under /sys/ and read/write that to get information from and to the driver. An example of how to set this up:

static ssize_t mydrvr_version_show(struct device *dev,
        struct device_attribute *attr, char *buf)
{
    return sprintf(buf, "%s\n", DRIVER_RELEASE);
}

static DEVICE_ATTR(version, S_IRUGO, mydrvr_version_show, NULL);

And during driver setup:

device_create_file(dev, &dev_attr_version);

You would then have a file for your device in /sys/, for example, /sys/block/myblk/version for a block driver.

Another method for heavier use is netlink, which is an IPC (inter-process communication) method to talk to your driver over a BSD socket interface. This is used, for example, by the WiFi drivers. You then communicate with it from userspace using the libnl or libnl3 libraries.

Is it possible in Java to check if objects fields are null and then add default value to all those attributes?

I tried this and it works without any issues to validate if the field is empty. I have answered your question partially as I haven't personally tried to add default values to attributes

if(field.getText()!= null && !field.getText().isEmpty())

Hope it helps

jQuery: count number of rows in a table

Alternatively...

var rowCount = $('table#myTable tr:last').index() + 1;

jsFiddle DEMO

This will ensure that any nested table-rows are not also counted.

Create a new file in git bash

Yes, it is. Just create files in the windows explorer and git automatically detects these files as currently untracked. Then add it with the command you already mentioned.

git add does not create any files. See also http://gitref.org/basic/#add

Github probably creates the file with touch and adds the file for tracking automatically. You can do this on the bash as well.

Android Service needs to run always (Never pause or stop)

A simple solution is to restart the service when the system stops it.

I found this very simple implementation of this method:

How to make android service unstoppable

Is it possible to get all arguments of a function as single object inside that function?

ES6 allows a construct where a function argument is specified with a "..." notation such as

function testArgs (...args) {
 // Where you can test picking the first element
 console.log(args[0]); 
}

Defined Edges With CSS3 Filter Blur

I used -webkit-transform: translate3d(0, 0, 0); with overflow:hidden;.

DOM:

<div class="parent">
    <img class="child" src="http://placekitten.com/100" />
</div>

CSS:

.parent {
    width: 100px;
    height: 100px;
    overflow: hidden;
    -webkit-transform: translate3d(0, 0, 0);
}
.child {
    -webkit-filter: blur(10px);
}

DEMO: http://jsfiddle.net/DA5L4/18/

This technic works on Chrome34 and iOS7.1

Update

http://jsfiddle.net/DA5L4/50/

if you use latest version of Chrome, you don't need to use -webkit-transform: translate3d(0, 0, 0); hack. But it doesn't works on Safari(webkit).