Programs & Examples On #Fixup

Forward X11 failed: Network error: Connection refused

Other answers are outdated, or incomplete, or simply don't work.

You need to also specify an X-11 server on the host machine to handle the launch of GUId programs. If the client is a Windows machine install Xming. If the client is a Linux machine install XQuartz.

Now suppose this is Windows connecting to Linux. In order to be able to launch X11 programs as well over putty do the following:

- Launch XMing on Windows client
- Launch Putty
    * Fill in basic options as you know in session category
    * Connection -> SSH -> X11
        -> Enable X11 forwarding
        -> X display location = :0.0
        -> MIT-Magic-Cookie-1
        -> X authority file for local display = point to the Xming.exe executable

Of course the ssh server should have permitted Desktop Sharing "Allow other user to view your desktop".

MobaXterm and other complete remote desktop programs work too.

Various ways to remove local Git changes

As with everything in git there are multiple ways of doing it. The two commands you used are one way of doing it. Another thing you could have done is simply stash them with git stash -u. The -u makes sure that newly added files (untracked) are also included.

The handy thing about git stash -u is that

  1. it is probably the simplest (only?) single command to accomplish your goal
  2. if you change your mind afterwards you get all your work back with git stash pop (it's like deleting an email in gmail where you can just undo if you change your mind afterwards)

As of your other question git reset --hard won't remove the untracked files so you would still need the git clean -f. But a git stash -u might be the most convenient.

Why call git branch --unset-upstream to fixup?

Actually torek told you already how to use the tools much better than I would be able to do. However, in this case I think it is important to point out something peculiar if you follow the guidelines at http://octopress.org/docs/deploying/github/. Namely, you will have multiple github repositories in your setup. First of all the one with all the source code for your website in say the directory $WEBSITE, and then the one with only the static generated files residing in $WEBSITE/_deploy. The funny thing of the setup is that there is a .gitignore file in the $WEBSITE directory so that this setup actually works.

Enough introduction. In this case the error might also come from the repository in _deploy.

cd _deploy

git branch -a
* master
remotes/origin/master
remotes/origin/source

In .git/config you will normally need to find something like this:

[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
[remote "origin"]
    url = [email protected]:yourname/yourname.github.io.git
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
    remote = origin
    merge = refs/heads/master

But in your case the branch master does not have a remote.

[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
[remote "origin"]
    url = [email protected]:yourname/yourname.github.io.git
    fetch = +refs/heads/*:refs/remotes/origin/*

Which you can solve by:

cd _deploy
git branch --set-upstream-to=origin/master

So, everything is as torek told you, but it might be important to point out that this very well might concern the _deploy directory rather than the root of your website.

PS: It might be worth to use a shell such as zsh with a git plugin to not be bitten by this thing in the future. It will immediately show that _deploy concerns a different repository.

How to close off a Git Branch?

Yes, just delete the branch by running git push origin :branchname. To fix a new issue later, branch off from master again.

How to change maven java home

The best way to force a specific JVM for MAVEN is to create a system wide file loaded by the mvn script.

This file is /etc/mavenrc and it must declare a JAVA_HOME environment variable pointing to your specific JVM.

Example:

export JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk-amd64

If the file exists, it's loaded.

Here is an extract of the mvn script in order to understand :

  if [ -f /etc/mavenrc ] ; then
    . /etc/mavenrc
  fi

  if [ -f "$HOME/.mavenrc" ] ; then
    . "$HOME/.mavenrc"
  fi

Alternately, the same content can be written in ~/.mavenrc

How do I replace multiple spaces with a single space in C#?

This is a shorter version, which should only be used if you are only doing this once, as it creates a new instance of the Regex class every time it is called.

temp = new Regex(" {2,}").Replace(temp, " "); 

If you are not too acquainted with regular expressions, here's a short explanation:

The {2,} makes the regex search for the character preceding it, and finds substrings between 2 and unlimited times.
The .Replace(temp, " ") replaces all matches in the string temp with a space.

If you want to use this multiple times, here is a better option, as it creates the regex IL at compile time:

Regex singleSpacify = new Regex(" {2,}", RegexOptions.Compiled);
temp = singleSpacify.Replace(temp, " ");

Is it possible to use std::string in a constexpr?

As of C++20, yes.

As of C++17, you can use string_view:

constexpr std::string_view sv = "hello, world";

A string_view is a string-like object that acts as an immutable, non-owning reference to any sequence of char objects.

The name 'ViewBag' does not exist in the current context

In my case, changing the webpage:Version to the proper value resolved my issue, for me the correct value was(2.0.0.0 instead of 3.0.0.0) :

<appSettings>
        <add key="webpages:Version" value="2.0.0.0"/>
        <add key="webpages:Enabled" value="false"/>

Is it ok to use `any?` to check if an array is not empty?

any? isn't the same as not empty? in some cases.

>> [nil, 1].any?
=> true
>> [nil, nil].any?
=> false

From the documentation:

If the block is not given, Ruby adds an implicit block of {|obj| obj} (that is any? will return true if at least one of the collection members is not false or nil).

How to write asynchronous functions for Node.js

I've dealing too many hours for such task in for node.js. I'm mainly front-end guy.

I find this quite important, because all node methods asyncronous deal with callback, and transform it into Promise is better to handle it.

I Just want to show a possible outcome, more lean and readable. Using ECMA-6 with async you can write it like this.

 async function getNameFiles (dirname) {
  return new Promise((resolve, reject) => {
    fs.readdir(dirname, (err, filenames) => {
      err !== (undefined || null) ? reject(err) : resolve(filenames)
    })
  })
}

the (undefined || null) is for repl (read event print loop) scenarios, using undefined also work.

pip install: Please check the permissions and owner of that directory

I also saw this change on my Mac when I went from running pip to sudo pip. Adding -H to sudo causes the message to go away for me. E.g.

sudo -H pip install foo

man sudo tells me that -H causes sudo to set $HOME to the target users (root in this case).

So it appears pip is looking into $HOME/Library/Log and sudo by default isn't setting $HOME to /root/. Not surprisingly ~/Library/Log is owned by you as a user rather than root.

I suspect this is some recent change in pip. I'll run it with sudo -H for now to work around.

Set the table column width constant regardless of the amount of text in its cells?

You don't need to set "fixed" - all you need is setting overflow:hidden since the column width is set.

CSS - Overflow: Scroll; - Always show vertical scroll bar?

This will work with iPad on Safari on iOS 7.1.x from my testing, I'm not sure about iOS 6 though. However, it will not work on Firefox. There is a jQuery plugin which aims to be cross browser compliant called jScrollPane.

Also, there is a duplicate post here on Stack Overflow which has some other details.

fs.writeFile in a promise, asynchronous-synchronous stuff

If you want to import the promise based version of fs as an ES module you can do:

import { promises as fs } from 'fs'

await fs.writeFile(...)

As soon as node v14 is released (see this PR), you can also use

import { writeFile } from 'fs/promises'

Make hibernate ignore class variables that are not mapped

Placing @Transient on getter with private field worked for me.

private String name;

    @Transient
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

How do I pick randomly from an array?

myArray.sample(x) can also help you to get x random elements from the array.

Split string on whitespace in Python

import re
s = "many   fancy word \nhello    \thi"
re.split('\s+', s)

Java: How to read a text file

Java 1.5 introduced the Scanner class for handling input from file and streams.

It is used for getting integers from a file and would look something like this:

List<Integer> integers = new ArrayList<Integer>();
Scanner fileScanner = new Scanner(new File("c:\\file.txt"));
while (fileScanner.hasNextInt()){
   integers.add(fileScanner.nextInt());
}

Check the API though. There are many more options for dealing with different types of input sources, differing delimiters, and differing data types.

Merging Cells in Excel using C#

Code Snippet

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private Excel.Application excelApp = null;
    private void button1_Click(object sender, EventArgs e)
    {
        excelApp.get_Range("A1:A360,B1:E1", Type.Missing).Merge(Type.Missing);
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        excelApp = Marshal.GetActiveObject("Excel.Application") as Excel.Application ;
    }
}

Thanks

Using tr to replace newline with space

Best guess is you are on windows and your line ending settings are set for windows. See this topic: How to change line-ending settings

or use:

tr '\r\n' ' '

accessing a docker container from another container

Easiest way is to use --link, however the newer versions of docker are moving away from that and in fact that switch will be removed soon.

The link below offers a nice how too, on connecting two containers. You can skip the attach portion, since that is just a useful how to on adding items to images.

https://deis.com/blog/2016/connecting-docker-containers-1/

The part you are interested in is the communication between two containers. The easiest way, is to refer to the DB container by name from the webserver container.

Example:

you named the db container db1 and the webserver container web0. The containers should both be on the bridge network, which means the web container should be able to connect to the DB container by referring to it's name.

So if you have a web config file for your app, then for DB host you will use the name db1.

if you are using an older version of docker, then you should use --link.

Example:

Step 1: docker run --name db1 oracle/database:12.1.0.2-ee

then when you start the web app. use:

Step 2: docker run --name web0 --link db1 webapp/webapp:3.0

and the web app will be linked to the DB. However, as I said the --link switch will be removed soon.

I'd use docker compose instead, which will build a network for you. However; you will need to download docker compose for your system. https://docs.docker.com/compose/install/#prerequisites

an example setup is like this:

file name is base.yml

version: "2"
services:
  webserver:
    image: "moodlehq/moodle-php-apache:7.1
    depends_on:
      - db
    volumes:
      - "/var/www/html:/var/www/html"
      - "/home/some_user/web/apache2_faildumps.conf:/etc/apache2/conf-enabled/apache2_faildumps.conf"
    environment:
      MOODLE_DOCKER_DBTYPE: pgsql
      MOODLE_DOCKER_DBNAME: moodle
      MOODLE_DOCKER_DBUSER: moodle
      MOODLE_DOCKER_DBPASS: "m@0dl3ing"
      HTTP_PROXY: "${HTTP_PROXY}"
      HTTPS_PROXY: "${HTTPS_PROXY}"
      NO_PROXY: "${NO_PROXY}"
  db:
    image: postgres:9
    environment:
      POSTGRES_USER: moodle
      POSTGRES_PASSWORD: "m@0dl3ing"
      POSTGRES_DB: moodle
      HTTP_PROXY: "${HTTP_PROXY}"
      HTTPS_PROXY: "${HTTPS_PROXY}"
      NO_PROXY: "${NO_PROXY}"

this will name the network a generic name, I can't remember off the top of my head what that name is, unless you use the --name switch.

IE docker-compose --name setup1 up base.yml

NOTE: if you use the --name switch, you will need to use it when ever calling docker compose, so docker-compose --name setup1 down this is so you can have more then one instance of webserver and db, and in this case, so docker compose knows what instance you want to run commands against; and also so you can have more then one running at once. Great for CI/CD, if you are running test in parallel on the same server.

Docker compose also has the same commands as docker so docker-compose --name setup1 exec webserver do_some_command

best part is, if you want to change db's or something like that for unit test you can include an additional .yml file to the up command and it will overwrite any items with similar names, I think of it as a key=>value replacement.

Example:

db.yml

version: "2"
services:
  webserver:
    environment:
      MOODLE_DOCKER_DBTYPE: oci
      MOODLE_DOCKER_DBNAME: XE
  db:
    image: moodlehq/moodle-db-oracle

Then call docker-compose --name setup1 up base.yml db.yml

This will overwrite the db. with a different setup. When needing to connect to these services from each container, you use the name set under service, in this case, webserver and db.

I think this might actually be a more useful setup in your case. Since you can set all the variables you need in the yml files and just run the command for docker compose when you need them started. So a more start it and forget it setup.

NOTE: I did not use the --port command, since exposing the ports is not needed for container->container communication. It is needed only if you want the host to connect to the container, or application from outside of the host. If you expose the port, then the port is open to all communication that the host allows. So exposing web on port 80 is the same as starting a webserver on the physical host and will allow outside connections, if the host allows it. Also, if you are wanting to run more then one web app at once, for whatever reason, then exposing port 80 will prevent you from running additional webapps if you try exposing on that port as well. So, for CI/CD it is best to not expose ports at all, and if using docker compose with the --name switch, all containers will be on their own network so they wont collide. So you will pretty much have a container of containers.

UPDATE: After using features further and seeing how others have done it for CICD programs like Jenkins. Network is also a viable solution.

Example:

docker network create test_network

The above command will create a "test_network" which you can attach other containers too. Which is made easy with the --network switch operator.

Example:

docker run \
    --detach \
    --name db1 \
    --network test_network \
    -e MYSQL_ROOT_PASSWORD="${DBPASS}" \
    -e MYSQL_DATABASE="${DBNAME}" \
    -e MYSQL_USER="${DBUSER}" \
    -e MYSQL_PASSWORD="${DBPASS}" \
    --tmpfs /var/lib/mysql:rw \
    mysql:5

Of course, if you have proxy network settings you should still pass those into the containers using the "-e" or "--env-file" switch statements. So the container can communicate with the internet. Docker says the proxy settings should be absorbed by the container in the newer versions of docker; however, I still pass them in as an act of habit. This is the replacement for the "--link" switch which is going away. Once the containers are attached to the network you created you can still refer to those containers from other containers using the 'name' of the container. Per the example above that would be db1. You just have to make sure all containers are connected to the same network, and you are good to go.

For a detailed example of using network in a cicd pipeline, you can refer to this link: https://git.in.moodle.com/integration/nightlyscripts/blob/master/runner/master/run.sh

Which is the script that is ran in Jenkins for a huge integration tests for Moodle, but the idea/example can be used anywhere. I hope this helps others.

How can I clear the SQL Server query cache?

Eight different ways to clear the plan cache

1. Remove all elements from the plan cache for the entire instance

DBCC FREEPROCCACHE;

Use this to clear the plan cache carefully. Freeing the plan cache causes, for example, a stored procedure to be recompiled instead of reused from the cache. This can cause a sudden, temporary decrease in query performance.

2. Flush the plan cache for the entire instance and suppress the regular completion message

"DBCC execution completed. If DBCC printed error messages, contact your system administrator."

DBCC FREEPROCCACHE WITH NO_INFOMSGS;

3. Flush the ad hoc and prepared plan cache for the entire instance

DBCC FREESYSTEMCACHE ('SQL Plans');

4. Flush the ad hoc and prepared plan cache for one resource pool

DBCC FREESYSTEMCACHE ('SQL Plans', 'LimitedIOPool');

5. Flush the entire plan cache for one resource pool

DBCC FREEPROCCACHE ('LimitedIOPool');

6. Remove all elements from the plan cache for one database (does not work in SQL Azure)

-- Get DBID from one database name first
DECLARE @intDBID INT;
SET @intDBID = (SELECT [dbid] 
                FROM master.dbo.sysdatabases 
                WHERE name = N'AdventureWorks2014');

DBCC FLUSHPROCINDB (@intDBID);

7. Clear plan cache for the current database

USE AdventureWorks2014;
GO
-- New in SQL Server 2016 and SQL Azure
ALTER DATABASE SCOPED CONFIGURATION CLEAR PROCEDURE_CACHE;

8. Remove one query plan from the cache

USE AdventureWorks2014;
GO

-- Run a stored procedure or query
EXEC dbo.uspGetEmployeeManagers 9;

-- Find the plan handle for that query 
-- OPTION (RECOMPILE) keeps this query from going into the plan cache
SELECT cp.plan_handle, cp.objtype, cp.usecounts, 
DB_NAME(st.dbid) AS [DatabaseName]
FROM sys.dm_exec_cached_plans AS cp CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS st 
WHERE OBJECT_NAME (st.objectid)
LIKE N'%uspGetEmployeeManagers%' OPTION (RECOMPILE); 

-- Remove the specific query plan from the cache using the plan handle from the above query 
DBCC FREEPROCCACHE (0x050011007A2CC30E204991F30200000001000000000000000000000000000000000000000000000000000000);
 

Source 1 2 3

OpenJDK availability for Windows OS

Found all the windows binaries here :

https://github.com/ojdkbuild/ojdkbuild

These Windows binaries are built to keep them as close as possible in behaviour to java-x-openjdk CentOS packages.

Django model "doesn't declare an explicit app_label"

In my case, this was happening because I used a relative module path in project-level urls.py, INSTALLED_APPS and apps.py instead of being rooted in the project root. i.e. absolute module paths throughout, rather than relative modules paths + hacks.

No matter how much I messed with the paths in INSTALLED_APPS and apps.py in my app, I couldn't get both runserver and pytest to work til all three of those were rooted in the project root.

Folder structure:

|-- manage.py
|-- config
    |-- settings.py
    |-- urls.py
|-- biz_portal
    |-- apps
        |-- portal
            |-- models.py
            |-- urls.py
            |-- views.py
            |-- apps.py

With the following, I could run manage.py runserver and gunicorn with wsgi and use portal app views without trouble, but pytest would error with ModuleNotFoundError: No module named 'apps' despite DJANGO_SETTINGS_MODULE being configured correctly.

config/settings.py:

INSTALLED_APPS = [
    ...
    "apps.portal.apps.PortalConfig",
]

biz_portal/apps/portal/apps.py:

class PortalConfig(AppConfig):
    name = 'apps.portal'

config/urls.py:

urlpatterns = [
    path('', include('apps.portal.urls')),
    ...
]

Changing the app reference in config/settings.py to biz_portal.apps.portal.apps.PortalConfig and PortalConfig.name to biz_portal.apps.portal allowed pytest to run (I don't have tests for portal views yet) but runserver would error with

RuntimeError: Model class apps.portal.models.Business doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS

Finally I grepped for apps.portal to see what's still using a relative path, and found that config/urls.py should also use biz_portal.apps.portal.urls.

How to drop a unique constraint from table column?

To drop a UNIQUE constraint, you don’t need the name of the constraint, just the list of columns that are included in the constraint.

The syntax would be:

ALTER TABLE table_name DROP UNIQUE (column1, column2, . . . )

Excel "External table is not in the expected format."

Thanks for this code :) I really appreciate it. Works for me.

public static string connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;";

So if you have diff version of Excel file, get the file name, if its extension is .xlsx, use this:

Private Const connstring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;";

and if it is .xls, use:

Private Const connstring As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=" + path + ";Extended Properties=""Excel 8.0;HDR=YES;"""

Order of execution of tests in TestNG

Piggy backing off of user1927494's answer, In case you want to run a single test before all others, you can do this:

@Test()
public void testOrderDoesntMatter_1() {
}

@Test(priority=-1)
public void testToRunFirst() {
}

@Test()
public void testOrderDoesntMatter_2() {
}

How to assign an exec result to a sql variable?

declare @EventId int

CREATE TABLE #EventId (EventId int)

insert into #EventId exec rptInputEventId

set @EventId = (select * from #EventId)

drop table #EventId 

Converting LastLogon to DateTime format

LastLogon is the last time that the user logged into whichever domain controller you happen to have been load balanced to at the moment that you ran the GET-ADUser cmdlet, and is not replicated across the domain. You really should use LastLogonTimestamp if you want the time the last user logged in to any domain controller in your domain.

How to find the php.ini file used by the command line?

If you want all the configuration files loaded, this is will tell you:

php -i | grep "\.ini"

Some systems load things from more than one ini file. On my ubuntu system, it looks like this:

$  php -i | grep "\.ini"
Configuration File (php.ini) Path => /etc/php5/cli
Loaded Configuration File => /etc/php5/cli/php.ini
Scan this dir for additional .ini files => /etc/php5/cli/conf.d
additional .ini files parsed => /etc/php5/cli/conf.d/apc.ini,
/etc/php5/cli/conf.d/curl.ini,
/etc/php5/cli/conf.d/gd.ini,
/etc/php5/cli/conf.d/mcrypt.ini,
/etc/php5/cli/conf.d/memcache.ini,
/etc/php5/cli/conf.d/mysql.ini,
/etc/php5/cli/conf.d/mysqli.ini,
/etc/php5/cli/conf.d/pdo.ini,
/etc/php5/cli/conf.d/pdo_mysql.ini

Declaring an HTMLElement Typescript

Okay: weird syntax!

var el: HTMLElement = document.getElementById('content');

fixes the problem. I wonder why the example didn't do this in the first place?

complete code:

class Greeter {
    element: HTMLElement;
    span: HTMLElement;
    timerToken: number;

    constructor (element: HTMLElement) { 
        this.element = element;
        this.element.innerText += "The time is: ";
        this.span = document.createElement('span');
        this.element.appendChild(this.span);
        this.span.innerText = new Date().toUTCString();
    }

    start() {
        this.timerToken = setInterval(() => this.span.innerText = new Date().toUTCString(), 500);
    }

    stop() {
        clearTimeout(this.timerToken);
    }

}

window.onload = () => {
    var el: HTMLElement = document.getElementById('content');
    var greeter = new Greeter(el);
    greeter.start();
};

Update a table using JOIN in SQL Server?

Seems like SQL Server 2012 can handle the old update syntax of Teradata too:

UPDATE a
SET a.CalculatedColumn= b.[Calculated Column]
FROM table1 a, table2 b 
WHERE 
    b.[common field]= a.commonfield
AND a.BatchNO = '110'

If I remember correctly, 2008R2 was giving error when I tried similar query.

How to get id from URL in codeigniter?

$CI =& get_instance();

if($CI->input->get('id'){
    $id = $CI->input->get('id');

}

How to remove multiple indexes from a list at the same time?

another option (in place, any combination of indices):

_marker = object()

for i in indices:
    my_list[i] = _marker  # marked for deletion

obj[:] = [v for v in my_list if v is not _marker]

Java: JSON -> Protobuf & back conversion

I don't much like an idea of writing binary protobuf to database, because it can one day become not backward-compatible with newer versions and break the system that way.

Converting protobuf to JSON for storage and then back to protobuf on load is much more likely to create compatibility problems, because:

  • If the process which performs the conversion is not built with the latest version of the protobuf schema, then converting will silently drop any fields that the process doesn't know about. This is true both of the storing and loading ends.
  • Even with the most recent schema available, JSON <-> Protobuf conversion may be lossy in the presence of imprecise floating-point values and similar corner cases.
  • Protobufs actually have (slightly) stronger backwards-compatibility guarantees than JSON. Like with JSON, if you add a new field, old clients will ignore it. Unlike with JSON, Protobufs allow declaring a default value, which can make it somewhat easier for new clients to deal with old data that is otherwise missing the field. This is only a slight advantage, but otherwise Protobuf and JSON have equivalent backwards-compatibility properties, therefore you are not gaining any backwards-compatibility advantages from storing in JSON.

With all that said, there are many libraries out there for converting protobufs to JSON, usually built on the Protobuf reflection interface (not to be confused with the Java reflection interface; Protobuf reflection is offered by the com.google.protobuf.Message interface).

How to manually force a commit in a @Transactional method?

I know that due to this ugly anonymous inner class usage of TransactionTemplate doesn't look nice, but when for some reason we want to have a test method transactional IMHO it is the most flexible option.

In some cases (it depends on the application type) the best way to use transactions in Spring tests is a turned-off @Transactional on the test methods. Why? Because @Transactional may leads to many false-positive tests. You may look at this sample article to find out details. In such cases TransactionTemplate can be perfect for controlling transaction boundries when we want that control.

JavaScript: location.href to open in new window/tab?

If you want to use location.href to avoid popup problems, you can use an empty <a> ref and then use javascript to click it.

something like in HTML

<a id="anchorID" href="mynewurl" target="_blank"></a>

Then javascript click it as follows

document.getElementById("anchorID").click();

Favicon: .ico or .png / correct tags?

I know this is an old question.

Here's another option - attending to different platform requirements - Source

<link rel='shortcut icon' type='image/vnd.microsoft.icon' href='/favicon.ico'> <!-- IE -->
<link rel='apple-touch-icon' type='image/png' href='/icon.57.png'> <!-- iPhone -->
<link rel='apple-touch-icon' type='image/png' sizes='72x72' href='/icon.72.png'> <!-- iPad -->
<link rel='apple-touch-icon' type='image/png' sizes='114x114' href='/icon.114.png'> <!-- iPhone4 -->
<link rel='icon' type='image/png' href='/icon.114.png'> <!-- Opera Speed Dial, at least 144×114 px -->

This is the broadest approach I have found so far.

Ultimately the decision depends on your own needs. Ask yourself, who is your target audience?

UPDATE May 27, 2018: As expected, time goes by and things change. But there's good news too. I found a tool called Real Favicon Generator that generates all the required lines for the icon to work on all modern browsers and platforms. It doesn't handle backwards compatibility though.

How can I loop through enum values for display in radio buttons?

Two options:

for (let item in MotifIntervention) {
    if (isNaN(Number(item))) {
        console.log(item);
    }
}

Or

Object.keys(MotifIntervention).filter(key => !isNaN(Number(MotifIntervention[key])));

(code in playground)


Edit

String enums look different than regular ones, for example:

enum MyEnum {
    A = "a",
    B = "b",
    C = "c"
}

Compiles into:

var MyEnum;
(function (MyEnum) {
    MyEnum["A"] = "a";
    MyEnum["B"] = "b";
    MyEnum["C"] = "c";
})(MyEnum || (MyEnum = {}));

Which just gives you this object:

{
    A: "a",
    B: "b",
    C: "c"
}

You can get all the keys (["A", "B", "C"]) like this:

Object.keys(MyEnum);

And the values (["a", "b", "c"]):

Object.keys(MyEnum).map(key => MyEnum[key])

Or using Object.values():

Object.values(MyEnum)

Angular2 equivalent of $document.ready()

You can fire an event yourself in ngOnInit() of your Angular root component and then listen for this event outside of Angular.

This is Dart code (I don't know TypeScript) but should't be to hard to translate

@Component(selector: 'app-element')
@View(
    templateUrl: 'app_element.html',
)
class AppElement implements OnInit {
  ElementRef elementRef;
  AppElement(this.elementRef);

  void ngOnInit() {
    DOM.dispatchEvent(elementRef.nativeElement, new CustomEvent('angular-ready'));
  }
}

PYTHONPATH on Linux

1) PYTHONPATH is an environment variable which you can set to add additional directories where python will look for modules and packages. e.g.:

# make python look in the foo subdirectory of your home directory for
# modules and packages 
export PYTHONPATH=${PYTHONPATH}:${HOME}/foo 

Here I use the sh syntax. For other shells (e.g. csh,tcsh), the syntax would be slightly different. To make it permanent, set the variable in your shell's init file (usually ~/.bashrc).

2) Ubuntu comes with python already installed. There may be reasons for installing other (independent) python versions, but I've found that to be rarely necessary.

3) The folder where your modules live is dependent on PYTHONPATH and where the directories were set up when python was installed. For the most part, the installed stuff you shouldn't care about where it lives -- Python knows where it is and it can find the modules. Sort of like issuing the command ls -- where does ls live? /usr/bin? /bin? 99% of the time, you don't need to care -- Just use ls and be happy that it lives somewhere on your PATH so the shell can find it.

4) I'm not sure I understand the question. 3rd party modules usually come with install instructions. If you follow the instructions, python should be able to find the module and you shouldn't have to care about where it got installed.

5) Configure PYTHONPATH to include the directory where your module resides and python will be able to find your module.

Python error "ImportError: No module named"

  1. You must have the file __ init__.py in the same directory where it's the file that you are importing.
  2. You can not try to import a file that has the same name and be a file from 2 folders configured on the PYTHONPATH.

eg: /etc/environment

PYTHONPATH=$PYTHONPATH:/opt/folder1:/opt/folder2

/opt/folder1/foo

/opt/folder2/foo

And, if you are trying to import foo file, python will not know which one you want.

from foo import ... >>> importerror: no module named foo

How do I determine if a checkbox is checked?

The line where you define lfckv is run whenever the browser finds it. When you put it into the head of your document, the browser tries to find lifecheck id before the lifecheck element is created. You must add your script below the lifecheck input in order for your code to work.

Best way to change the background color for an NSView

Have a look at RMSkinnedView. You can set the NSView's background color from within Interface Builder.

List of special characters for SQL LIKE clause

Potential answer for SQL Server

Interesting I just ran a test using LinqPad with SQL Server which should be just running Linq to SQL underneath and it generates the following SQL statement.

Records .Where(r => r.Name.Contains("lkjwer--_~[]"))

-- Region Parameters
DECLARE @p0 VarChar(1000) = '%lkjwer--~_~~~[]%'
-- EndRegion
SELECT [t0].[ID], [t0].[Name]
FROM [RECORDS] AS [t0]
WHERE [t0].[Name] LIKE @p0 ESCAPE '~'

So I haven't tested it yet but it looks like potentially the ESCAPE '~' keyword may allow for automatic escaping of a string for use within a like expression.

Change selected value of kendo ui dropdownlist

It's possible to "natively" select by value:

dropdownlist.select(1);

Moq, SetupGet, Mocking a property

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

Is there a better way to iterate over two lists, getting one element from each list for each iteration?

Good to see lots of love for zip in the answers here.

However it should be noted that if you are using a python version before 3.0, the itertools module in the standard library contains an izip function which returns an iterable, which is more appropriate in this case (especially if your list of latt/longs is quite long).

In python 3 and later zip behaves like izip.

How to output messages to the Eclipse console when developing for Android

i use below log format for print my content in logCat

Log.e("Msg","What you have to print");

node.js hash string?

sha256("string or binary");

I experienced issue with other answer. I advice you to set encoding argument to binary to use the byte string and prevent different hash between Javascript (NodeJS) and other langage/service like Python, PHP, Github...

If you don't use this code, you can get a different hash between NodeJS and Python...

How to get the same hash that Python, PHP, Perl, Github (and prevent an issue) :

NodeJS is hashing the UTF-8 representation of the string. Other languages (like Python, PHP or PERL...) are hashing the byte string.

We can add binary argument to use the byte string.

Code :

const crypto = require("crypto");

function sha256(data) {
    return crypto.createHash("sha256").update(data, "binary").digest("base64");
    //                                               ------  binary: hash the byte string
}

sha256("string or binary");

Documentation:

  • crypto.createHash(algorithm[, options]): The algorithm is dependent on the available algorithms supported by the version of OpenSSL on the platform.
  • hash.digest([encoding]): The encoding can be 'hex', 'latin1' or 'base64'. (base 64 is less longer).

You can get the issue with : sha256("\xac"), "\xd1", "\xb9", "\xe2", "\xbb", "\x93", etc...

  • Other languages (like PHP, Python, Perl...) and my solution with .update(data, "binary") :

      sha1("\xac") //39527c59247a39d18ad48b9947ea738396a3bc47
    
  • Nodejs by default (without binary) :

      sha1("\xac") //f50eb35d94f1d75480496e54f4b4a472a9148752
    

Get list of databases from SQL Server

In SQL Server 2008 R2 this works:

select name 
from master.sys.databases 
where owner_sid > 1;

And list only databases created by user(s).

how to display full stored procedure code?

Use \df to list all the stored procedure in Postgres.

XAMPP Port 80 in use by "Unable to open process" with PID 4

So I have faced the same problem when trying to start apache service and I would like to share my solutions with you. Here is some notes about services or programs that may use port 80:

  1. Skype: skype uses port 80/443 by default. You can change this from tools->options-> advanced->connections and disable checkbox "use port 80 and 443 for addtional incoming connections".
  2. IIS: IIS uses port 80 be default so you need to shut down it. You can use the following two commands net stop w3svc net stop iisadmin
  3. SQL Server Reporting Service: You need to stop this service because it may take port 80 if IIS is not running. Go to local services and stop it.

These options work great with me and I can start apache service without errors.

The other option is to change apache listen port from httpd.conf and set another port number.

Hope this solution helps anyone who face the same problem again.

HTML - Arabic Support

i edit the html page with notepad ++ ,set encoding to utf-8 and its work

Creating a config file in PHP

You can create a config class witch static properties

class Config 
{
    static $dbHost = 'localhost';
    static $dbUsername = 'user';
    static $dbPassword  = 'pass';
}

then you can simple use it:

Config::$dbHost  

Sometimes in my projects I use a design pattern SINGLETON to access configuration data. It's very comfortable in use.

Why?

For example you have 2 data source in your project. And you can choose witch of them is enabled.

  • mysql
  • json

Somewhere in config file you choose:

$dataSource = 'mysql' // or 'json'

When you change source whole app shoud switch to new data source, work fine and dont need change in code.

Example:

Config:

class Config 
{
  // ....
  static $dataSource = 'mysql';
  / .....
}

Singleton class:

class AppConfig
{
    private static $instance;
    private $dataSource;

    private function __construct()
    {
        $this->init();
    }

    private function init()
    {
        switch (Config::$dataSource)
        {
            case 'mysql':
                $this->dataSource = new StorageMysql();
                break;
            case 'json':
                $this->dataSource = new StorageJson();
                break;
            default:
                $this->dataSource = new StorageMysql();
        }
    }

    public static function getInstance()
    {
        if (empty(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function getDataSource()
    {
        return $this->dataSource;
    }
}

... and somewhere in your code (eg. in some service class):

$container->getItemsLoader(AppConfig::getInstance()->getDataSource()) // getItemsLoader need Object of specific data source class by dependency injection

We can obtain an AppConfig object from any place in the system and always get the same copy (thanks to static). The init () method of the class is called In the constructor, which guarantees only one execution. Init() body checks The value of the config $dataSource, and create new object of specific data source class. Now our script can get object and operate on it, not knowing even which specific implementation actually exists.

Force IE10 to run in IE10 Compatibility View?

I had the same problem. The problem is a bug in MSIE 10, so telling people to fix their issues isn't helpful. Neither is telling visitors to your site to add your site to compatibility view, bleh. In my case, the problem was that the following code displayed no text:

document.write ('<P>'); 
document.write ('Blah, blah, blah... ');
document.write ('</P>');

After much trial and error, I determined that removing the <P> and </P> tags caused the text to appear properly on the page (thus, the problem IS with document mode rather than browser mode, at least in my case). Removing the <P> tags when userAgent is MSIE is not a "fix" I want to put into my pages.

The solution, as others have said, is:

<!DOCTYPE HTML whatever doctype you're using....> 
<HTML>
 <HEAD>
  <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8">
  <TITLE>Blah...

Yes, the meta tag has to be the FIRST tag after HEAD.

Converting NSString to NSDictionary / JSON

Use the following code to get the response object from the AFHTTPSessionManager failure block; then you can convert the generic type into the required data type:

id responseObject = [NSJSONSerialization JSONObjectWithData:(NSData *)error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] options:0 error:nil];

CSS - center two images in css side by side

I understand that this question is old, but there is a good solution for it in HTML5. You can wrap it all in a <figure></figure> tag. The code would look something like this:

<div id="wrapper">
<figure>

<a href="mailto:[email protected]">
<img id="fblogo" border="0" alt="Mail" src="http://olympiahaacht.be/wp- 
content/uploads/2012/07/email-icon-e1343123697991.jpg"/>
</a>

<a href="https://www.facebook.com/OlympiaHaacht" target="_blank">
<img id="fblogo" border="0" alt="Facebook" src="http://olympiahaacht.be/wp- 
content/uploads/2012/04/FacebookButtonRevised-e1334605872360.jpg"/>
</a>

</figure>
</div>

and the CSS:

#wrapper{
 text-align:center;
}

How to check if X server is running?

I wrote xdpyprobe program which is intended for this purpose. Unlike xset, xdpyinfo and other general tools, it does not do any extra actions (just checks X server and exits) and it may not produce any output (if "-q" option is specified).

Excel data validation with suggestions/autocomplete

I adapted the answer by ChrisB. Like in his example a temporary combobox is made visible when a cell is clicked. Additionally:

  1. List of Combobox items is updated as user types, only matching items are displayed
  2. if any item from combobox is selected, filtering is skipped as it makes sense and because of this error

_x000D_
_x000D_
Option Explicit_x000D_
_x000D_
Private Const DATA_RANGE = "A1:A16"_x000D_
Private Const DROPDOWN_RANGE = "F2:F10"_x000D_
Private Const HELP_COLUMN = "$G"_x000D_
_x000D_
_x000D_
Private Sub Worksheet_SelectionChange(ByVal target As Range)_x000D_
    Dim xWs As Worksheet_x000D_
    Set xWs = Application.ActiveSheet_x000D_
    _x000D_
    On Error Resume Next_x000D_
    _x000D_
    With Me.TempCombo_x000D_
        .LinkedCell = vbNullString_x000D_
        .Visible = False_x000D_
    End With_x000D_
    _x000D_
    If target.Cells.count > 1 Then_x000D_
        Exit Sub_x000D_
    End If_x000D_
    _x000D_
    Dim isect As Range_x000D_
    Set isect = Application.Intersect(target, Range(DROPDOWN_RANGE))_x000D_
    If isect Is Nothing Then_x000D_
       Exit Sub_x000D_
    End If_x000D_
       _x000D_
    With Me.TempCombo_x000D_
        .Visible = True_x000D_
        .Left = target.Left - 1_x000D_
        .Top = target.Top - 1_x000D_
        .Width = target.Width + 5_x000D_
        .Height = target.Height + 5_x000D_
        .LinkedCell = target.Address_x000D_
_x000D_
    End With_x000D_
_x000D_
    Me.TempCombo.Activate_x000D_
    Me.TempCombo.DropDown_x000D_
End Sub_x000D_
_x000D_
Private Sub TempCombo_Change()_x000D_
    If Me.TempCombo.Visible = False Then_x000D_
        Exit Sub_x000D_
    End If_x000D_
    _x000D_
    Dim currentValue As String_x000D_
    currentValue = Range(Me.TempCombo.LinkedCell).Value_x000D_
    _x000D_
    If Trim(currentValue & vbNullString) = vbNullString Then_x000D_
        Me.TempCombo.ListFillRange = "=" & DATA_RANGE_x000D_
    Else_x000D_
        If Me.TempCombo.ListIndex = -1 Then_x000D_
             Dim listCount As Integer_x000D_
             listCount = write_matching_items(currentValue)_x000D_
             Me.TempCombo.ListFillRange = "=" & HELP_COLUMN & "1:" & HELP_COLUMN & listCount_x000D_
             Me.TempCombo.DropDown_x000D_
        End If_x000D_
_x000D_
    End If_x000D_
End Sub_x000D_
_x000D_
_x000D_
Private Function write_matching_items(currentValue As String) As Integer_x000D_
    Dim xWs As Worksheet_x000D_
    Set xWs = Application.ActiveSheet_x000D_
_x000D_
    Dim cell As Range_x000D_
    Dim c As Range_x000D_
    Dim firstAddress As Variant_x000D_
    Dim count As Integer_x000D_
    count = 0_x000D_
    xWs.Range(HELP_COLUMN & ":" & HELP_COLUMN).Delete_x000D_
    With xWs.Range(DATA_RANGE)_x000D_
        Set c = .Find(currentValue, LookIn:=xlValues)_x000D_
        If Not c Is Nothing Then_x000D_
            firstAddress = c.Address_x000D_
            Do_x000D_
              Set cell = xWs.Range(HELP_COLUMN & "$" & (count + 1))_x000D_
              cell.Value = c.Value_x000D_
              count = count + 1_x000D_
             _x000D_
              Set c = .FindNext(c)_x000D_
              If c Is Nothing Then_x000D_
                GoTo DoneFinding_x000D_
              End If_x000D_
           Loop While c.Address <> firstAddress_x000D_
        End If_x000D_
DoneFinding:_x000D_
    End With_x000D_
    _x000D_
    write_matching_items = count_x000D_
_x000D_
End Function_x000D_
_x000D_
Private Sub TempCombo_KeyDown( __x000D_
                ByVal KeyCode As MSForms.ReturnInteger, __x000D_
                ByVal Shift As Integer)_x000D_
_x000D_
    Select Case KeyCode_x000D_
        Case 9  ' Tab key_x000D_
            Application.ActiveCell.Offset(0, 1).Activate_x000D_
        Case 13 ' Pause key_x000D_
            Application.ActiveCell.Offset(1, 0).Activate_x000D_
    End Select_x000D_
End Sub
_x000D_
_x000D_
_x000D_

Notes:

  1. ComboBoxe's MatchEntry must be set to 2 - fmMatchEntryNone. Don't forget to set ComboBox name to TempCombo
  2. I am using listFillRange to set ComboBox options. The range must be continuous, so, matching items are stored in a help column.
  3. I have tried accomplishing the same with ComboBox.addItem, but it turned out to be hard to repaint list box as user types

What is the difference between background, backgroundTint, backgroundTintMode attributes in android layout xml?

I tested various combinations of android:background, android:backgroundTint and android:backgroundTintMode.

android:backgroundTint applies the color filter to the resource of android:background when used together with android:backgroundTintMode.

Here are the results:

Tint Check

Here's the code if you want to experiment further:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:showIn="@layout/activity_main">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="32dp"
        android:textSize="45sp"
        android:background="#37AEE4"
        android:text="Background" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="32dp"
        android:textSize="45sp"
        android:backgroundTint="#FEFBDE"
        android:text="Background tint" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="32dp"
        android:textSize="45sp"
        android:background="#37AEE4"
        android:backgroundTint="#FEFBDE"
        android:text="Both together" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="32dp"
        android:textSize="45sp"
        android:background="#37AEE4"
        android:backgroundTint="#FEFBDE"
        android:backgroundTintMode="multiply"
        android:text="With tint mode" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="32dp"
        android:textSize="45sp"
        android:text="Without any" />
</LinearLayout>

What is the proper way to display the full InnerException?

If you want information about all exceptions then use exception.ToString(). It will collect data from all inner exceptions.

If you want only the original exception then use exception.GetBaseException().ToString(). This will get you the first exception, e.g. the deepest inner exception or the current exception if there is no inner exception.

Example:

try {
    Exception ex1 = new Exception( "Original" );
    Exception ex2 = new Exception( "Second", ex1 );
    Exception ex3 = new Exception( "Third", ex2 );
    throw ex3;
} catch( Exception ex ) {
    // ex => ex3
    Exception baseEx = ex.GetBaseException(); // => ex1
}

MySQL "Group By" and "Order By"

Do a GROUP BY after the ORDER BY by wrapping your query with the GROUP BY like this:

SELECT t.* FROM (SELECT * FROM table ORDER BY time DESC) t GROUP BY t.from

How can I convert an RGB image into grayscale in Python?

you could do:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

def rgb_to_gray(img):
        grayImage = np.zeros(img.shape)
        R = np.array(img[:, :, 0])
        G = np.array(img[:, :, 1])
        B = np.array(img[:, :, 2])

        R = (R *.299)
        G = (G *.587)
        B = (B *.114)

        Avg = (R+G+B)
        grayImage = img

        for i in range(3):
           grayImage[:,:,i] = Avg

        return grayImage       

image = mpimg.imread("your_image.png")   
grayImage = rgb_to_gray(image)  
plt.imshow(grayImage)
plt.show()

Reading *.wav files in Python

You can accomplish this using the scikits.audiolab module. It requires NumPy and SciPy to function, and also libsndfile.

Note, I was only able to get it to work on Ubunutu and not on OSX.

from scikits.audiolab import wavread

filename = "testfile.wav"

data, sample_frequency,encoding = wavread(filename)

Now you have the wav data

Error: TypeError: $(...).dialog is not a function

Change jQueryUI to version 1.11.4 and make sure jQuery is not added twice.

How to stop a thread created by implementing runnable interface?

The simplest way is to interrupt() it, which will cause Thread.currentThread().isInterrupted() to return true, and may also throw an InterruptedException under certain circumstances where the Thread is waiting, for example Thread.sleep(), otherThread.join(), object.wait() etc.

Inside the run() method you would need catch that exception and/or regularly check the Thread.currentThread().isInterrupted() value and do something (for example, break out).

Note: Although Thread.interrupted() seems the same as isInterrupted(), it has a nasty side effect: Calling interrupted() clears the interrupted flag, whereas calling isInterrupted() does not.

Other non-interrupting methods involve the use of "stop" (volatile) flags that the running Thread monitors.

C++ -- expected primary-expression before ' '

Change

int wordLength = wordLengthFunction(string word);

to

int wordLength = wordLengthFunction(word);

Check if a input box is empty

Even you don't need to measure the length of string. A ! operator can solve everything for you. Remember always: !(empty string) = true !(some string) = false

So you could write:

<input ng-model="somefield">
<span ng-show="!somefield">Sorry, the field is empty!</span>
<span ng-hide="!somefield">Thanks. Successfully validated!</span>

IIS: Idle Timeout vs Recycle

Idle Timeout is if no action has been asked from your web app, it the process will drop and release everything from memory

Recycle is a forced action on the application where your processed is closed and started again, for memory leaking purposes and system health

The negative impact of both is usually the use of your Session and Application state is lost if you mess with Recycle to a faster time.(logged in users etc will be logged out, if they where about to "check out" all would have been lost" that's why recycle is at such a large time out value, idle timeout doesn't matter because nobody is logged in anyway and figure 20 minutes an no action they are not still "shopping"

The positive would be get rid of the idle time out as your website will respond faster on its "first" response if its not a highly active site where a user would have to wait for it to load if you have 1 user every 20 minutes lets say. So a website that get his less then 1 time in 20 minutes actually you would want to increase this value as the website has to load up again from scratch for each user. but if you set this to 0 over a long time, any memory leaks in code could over a certain amount of time, entirely take over the server.

SQLSTATE[HY000] [1698] Access denied for user 'root'@'localhost'

Just Create New User for MySQL do not use root. there is a problem its security issue

sudo mysql -p -u root

Login into MySQL or MariaDB with root privileges

CREATE USER 'troy121'@'%' IDENTIFIED BY 'mypassword123';

login and create a new user

GRANT ALL PRIVILEGES ON *.* TO 'magento121121'@'%' WITH GRANT OPTION;

and grant privileges to access "." and "@" "%" any location not just only 'localhost'

exit;

if you want to see your privilege table SHOW GRANTS; & Enjoy.

JavaScript console.log causes error: "Synchronous XMLHttpRequest on the main thread is deprecated..."

The question raised in 2014 and it's 2019 so I guess it's good to look for better option.

You can simply use fetch api in Javascript which provide you more flexibility.

for example, see this code

fetch('./api/some.json')
    .then((response) => {
        response.json().then((data) => { 
            ... 
        });
    })
    .catch((err) => { ... });

How to make connection to Postgres via Node.js

Slonik is an alternative to answers proposed by Kuberchaun and Vitaly.

Slonik implements safe connection handling; you create a connection pool and connection opening/handling is handled for you.

import {
  createPool,
  sql
} from 'slonik';

const pool = createPool('postgres://user:password@host:port/database');

return pool.connect((connection) => {
  // You are now connected to the database.
  return connection.query(sql`SELECT foo()`);
})
  .then(() => {
    // You are no longer connected to the database.
  });

postgres://user:password@host:port/database is your connection string (or more canonically a connection URI or DSN).

The benefit of this approach is that your script ensures that you never accidentally leave hanging connections.

Other benefits for using Slonik include:

How to trigger checkbox click event even if it's checked through Javascript code?

You can also use this, I hope you can serve them.

_x000D_
_x000D_
$(function(){_x000D_
  $('#elements input[type="checkbox"]').prop("checked", true).trigger("change");_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>_x000D_
_x000D_
<div id="elements">_x000D_
  <input type="checkbox" id="item-1" value="1"> Item 1 <br />_x000D_
  <input type="checkbox" id="item-2" value="2" disabled> Item 2 <br /> _x000D_
  <input type="checkbox" id="item-3" value="3" disabled> Item 3 <br />_x000D_
  <input type="checkbox" id="item-4" value="4" disabled> Item 4 <br />_x000D_
  <input type="checkbox" id="item-5" value="5"> Item 5_x000D_
</div>
_x000D_
_x000D_
_x000D_

Is it possible to move/rename files in Git and maintain their history?

I would like to rename/move a project subtree in Git moving it from

/project/xyz

to

/components/xyz

If I use a plain git mv project components, then all the commit history for the xyz project gets lost.

No (8 years later, Git 2.19, Q3 2018), because Git will detect the directory rename, and this is now better documented.

See commit b00bf1c, commit 1634688, commit 0661e49, commit 4d34dff, commit 983f464, commit c840e1a, commit 9929430 (27 Jun 2018), and commit d4e8062, commit 5dacd4a (25 Jun 2018) by Elijah Newren (newren).
(Merged by Junio C Hamano -- gitster -- in commit 0ce5a69, 24 Jul 2018)

That is now explained in Documentation/technical/directory-rename-detection.txt:

Example:

When all of x/a, x/b and x/c have moved to z/a, z/b and z/c, it is likely that x/d added in the meantime would also want to move to z/d by taking the hint that the entire directory 'x' moved to 'z'.

But they are many other cases, like:

one side of history renames x -> z, and the other renames some file to x/e, causing the need for the merge to do a transitive rename.

To simplify directory rename detection, those rules are enforced by Git:

a couple basic rules limit when directory rename detection applies:

  1. If a given directory still exists on both sides of a merge, we do not consider it to have been renamed.
  2. If a subset of to-be-renamed files have a file or directory in the way (or would be in the way of each other), "turn off" the directory rename for those specific sub-paths and report the conflict to the user.
  3. If the other side of history did a directory rename to a path that your side of history renamed away, then ignore that particular rename from the other side of history for any implicit directory renames (but warn the user).

You can see a lot of tests in t/t6043-merge-rename-directories.sh, which also point out that:

  • a) If renames split a directory into two or more others, the directory with the most renames, "wins".
  • b) Avoid directory-rename-detection for a path, if that path is the source of a rename on either side of a merge.
  • c) Only apply implicit directory renames to directories if the other side of history is the one doing the renaming.

How can I get the day of a specific date with PHP

You can use the date function. I'm using strtotime to get the timestamp to that day ; there are other solutions, like mktime, for instance.

For instance, with the 'D' modifier, for the textual representation in three letters :

$timestamp = strtotime('2009-10-22');

$day = date('D', $timestamp);
var_dump($day);

You will get :

string 'Thu' (length=3)

And with the 'l' modifier, for the full textual representation :

$day = date('l', $timestamp);
var_dump($day);

You get :

string 'Thursday' (length=8)

Or the 'w' modifier, to get to number of the day (0 to 6, 0 being sunday, and 6 being saturday) :

$day = date('w', $timestamp);
var_dump($day);

You'll obtain :

string '4' (length=1)

JPA - Returning an auto generated id after persist()

This is how I did it. You can try

    public class ABCService {
    @Resource(name="ABCDao")
    ABCDao abcDao;

    public int addNewABC(ABC abc) {
         ABC.setId(0);
         return abcDao.insertABC(abc);
    }
}

How do you set CMAKE_C_COMPILER and CMAKE_CXX_COMPILER for building Assimp for iOS?

The cc and cxx is located inside /Applications/Xcode.app. This should find the right paths

export CXX=`xcrun -find c++`
export CC=`xcrun -find cc`

Pass by Reference / Value in C++

As I parse it, those words are wrong. It should read "If the function modifies that value, the modifications appear also within the scope of the calling function when passing by reference, but not when passing by value."

Printing the value of a variable in SQL Developer

select View-->DBMS Output in menu and

How can I sanitize user input with PHP?

Easiest way to avoid mistakes in sanitizing input and escaping data is using PHP framework like Symfony, Nette etc. or part of that framework (templating engine, database layer, ORM).

Templating engine like Twig or Latte has output escaping on by default - you don't have to solve manually if you have properly escaped your output depending on context (HTML or Javascript part of web page).

Framework is automatically sanitizing input and you should't use $_POST, $_GET or $_SESSION variables directly, but through mechanism like routing, session handling etc.

And for database (model) layer there are ORM frameworks like Doctrine or wrappers around PDO like Nette Database.

You can read more about it here - What is a software framework?

Changing datagridview cell color based on condition

Kyle's and Simon's answers are gross waste of CPU resources. CellFormatting and CellPainting events occur far too many times and should not be used for applying styles. Here are two better ways of doing it:

If your DataGridView or at least the columns that decide cell style are read-only, you should change DefaultCellStyle of rows in RowsAdded event. This event occurs only once when a new row is added. The condition should be evaluated at that time and DefaultCellStyle of the row should be set therein. Note that this event occurs for DataBound situations too.

If your DataGridView or those columns allow editing, you should use CellEndEdit or CommitEdit events to change DefaultCellStyle.

How do I empty an array in JavaScript?

A more cross-browser friendly and more optimal solution will be to use the splice method to empty the content of the array A as below:

A.splice(0, A.length);

How to map with index in Ruby?

A fun, but useless way to do this:

az  = ('a'..'z').to_a
azz = az.map{|e| [e, az.index(e)+2]}

Can't load IA 32-bit .dll on a AMD 64-bit platform

I had the same issue with a Java application using tibco dll originally intended to run on Win XP. To get it to work on Windows 7, I made the application point to 32-bit JRE. Waiting to see if there is another solution.

Call of overloaded function is ambiguous

The solution is very simple if we consider the type of the constant value, which should be "unsigned int" instead of "int".

Instead of:

setval(0)

Use:

setval(0u)

The suffix "u" tell the compiler this is a unsigned integer. Then, no conversion would be needed, and the call will be unambiguous.

JavaScript validation for empty input field

_x000D_
_x000D_
<script type="text/javascript">_x000D_
  function validateForm() {_x000D_
    var a = document.forms["Form"]["answer_a"].value;_x000D_
    var b = document.forms["Form"]["answer_b"].value;_x000D_
    var c = document.forms["Form"]["answer_c"].value;_x000D_
    var d = document.forms["Form"]["answer_d"].value;_x000D_
    if (a == null || a == "", b == null || b == "", c == null || c == "", d == null || d == "") {_x000D_
      alert("Please Fill All Required Field");_x000D_
      return false;_x000D_
    }_x000D_
  }_x000D_
</script>_x000D_
_x000D_
<form method="post" name="Form" onsubmit="return validateForm()" action="">_x000D_
  <textarea cols="30" rows="2" name="answer_a" id="a"></textarea>_x000D_
  <textarea cols="30" rows="2" name="answer_b" id="b"></textarea>_x000D_
  <textarea cols="30" rows="2" name="answer_c" id="c"></textarea>_x000D_
  <textarea cols="30" rows="2" name="answer_d" id="d"></textarea>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Reflection - get attribute name and value on property

to get attribute from enum, i'm using :

 public enum ExceptionCodes
 {
  [ExceptionCode(1000)]
  InternalError,
 }

 public static (int code, string message) Translate(ExceptionCodes code)
        {
            return code.GetType()
            .GetField(Enum.GetName(typeof(ExceptionCodes), code))
            .GetCustomAttributes(false).Where((attr) =>
            {
                return (attr is ExceptionCodeAttribute);
            }).Select(customAttr =>
            {
                var attr = (customAttr as ExceptionCodeAttribute);
                return (attr.Code, attr.FriendlyMessage);
            }).FirstOrDefault();
        }

// Using

 var _message = Translate(code);

font-family is inherit. How to find out the font-family in chrome developer pane?

The inherit value, when used, means that the value of the property is set to the value of the same property of the parent element. For the root element (in HTML documents, for the html element) there is no parent element; by definition, the value used is the initial value of the property. The initial value is defined for each property in CSS specifications.

The font-family property is special in the sense that the initial value is not fixed in the specification but defined to be browser-dependent. This means that the browser’s default font family is used. This value can be set by the user.

If there is a continuous chain of elements (in the sense of parent-child relationships) from the root element to the current element, all with font-family set to inherit or not set at all in any style sheet (which also causes inheritance), then the font is the browser default.

This is rather uninteresting, though. If you don’t set fonts at all, browsers defaults will be used. Your real problem might be different – you seem to be looking at the part of style sheets that constitute a browser style sheet. There are probably other, more interesting style sheets that affect the situation.

Custom style to jquery ui dialogs

The solution only solves part of the problem, it may let you style the container and contents but doesn't let you change the titlebar. I developed a workaround of sorts but adding an id to the dialog div, then using jQuery .prev to change the style of the div which is the previous sibling of the dialog's div. This works because when jQueryUI creates the dialog, your original div becomes a sibling of the new container, but the title div is a the immediately previous sibling to your original div but neither the container not the title div has an id to simplify selecting the div.

HTML

<button id="dialog1" class="btn btn-danger">Warning</button>
<div title="Nothing here, really" id="nonmodal1">
  Nothing here
</div>

You can use CSS to style the main section of the dialog but not the title

.custom-ui-widget-header-warning {
  background: #EBCCCC;
  font-size: 1em;
}

You need some JS to style the title

$(function() {
                   $("#nonmodal1").dialog({
                     minWidth: 400,
                     minHeight: 'auto',
                     autoOpen: false,
                     dialogClass: 'custom-ui-widget-header-warning',
                     position: {
                       my: 'center',
                       at: 'left'
                     }
                   });

                   $("#dialog1").click(function() {
                     if ($("#nonmodal1").dialog("isOpen") === true) {
                       $("#nonmodal1").dialog("close");
                     } else {
                       $("#nonmodal1").dialog("open").prev().css('background','#D9534F');

                     }
                   });
    });

The example only shows simple styling (background) but you can make it as complex as you wish.

You can see it in action here:

http://codepen.io/chris-hore/pen/OVMPay

How to printf "unsigned long" in C?

For int %d

For long int %ld

For long long int %lld

For unsigned long long int %llu

What requests do browsers' "F5" and "Ctrl + F5" refreshes generate?

IE7/8/9 seem to behave differently depending on whether the page has focus or not.

If you click on the page and CTRL+F5 then "Cache-Control: no-cache" is included in the request headers. If you click in the Location/Address bar then press CTRL+F5 it isn't.

Pagination using MySQL LIMIT, OFFSET

Use .. LIMIT :pageSize OFFSET :pageStart

Where :pageStart is bound to the_page_index (i.e. 0 for the first page) * number_of_items_per_pages (e.g. 4) and :pageSize is bound to number_of_items_per_pages.

To detect for "has more pages", either use SQL_CALC_FOUND_ROWS or use .. LIMIT :pageSize OFFSET :pageStart + 1 and detect a missing last (pageSize+1) record. Needless to say, for pages with an index > 0, there exists a previous page.

If the page index value is embedded in the URL (e.g. in "prev page" and "next page" links) then it can be obtained via the appropriate $_GET item.

TokenMismatchException in VerifyCsrfToken.php Line 67

For me, I had to use secure https rather than http.

How to display the string html contents into webbrowser control?

Old question, but here's my go-to for this operation.

If browser.Document IsNot Nothing Then
    browser.Document.OpenNew(True)
    browser.Document.Write(My.Resources.htmlTemplate)
Else
    browser.DocumentText = My.Resources.htmlTemplate
End If

And be sure that any browser.Navigating event DOES NOT cancel "about:blank" URLs. Example event below for full control of WebBrowser navigating.

Private Sub browser_Navigating(sender As Object, e As WebBrowserNavigatingEventArgs) Handles browser.Navigating

    Try
        Me.Cursor = Cursors.WaitCursor

        Select Case e.Url.Scheme

            Case Constants.App_Url_Scheme

                Dim query As Specialized.NameValueCollection = System.Web.HttpUtility.ParseQueryString(e.Url.Query)

                Select Case e.Url.Host

                    Case Constants.Navigation.URLs.ToggleExpander.Host

                        Dim nodeID As String = query.Item(Constants.Navigation.URLs.ToggleExpander.Parameters.NodeID)

                        :
                        :
                        <other operations here>
                        :
                        :

                End Select

            Case Else
                e.Cancel = (e.Url.ToString() <> "about:blank")

        End Select

    Catch ex As Exception
        ExceptionBox.Show(ex, "Operation failed.")
    Finally
        Me.Cursor = Cursors.Default
    End Try

End Sub

PHP - define constant inside a class

You can define a class constant in php. But your class constant would be accessible from any object instance as well. This is php's functionality. However, as of php7.1, you can define your class constants with access modifiers (public, private or protected).

A work around would be to define your constant as private or protected and then make them readable via a static function. This function should only return the constant values if called from the static context.

You can also create this static function in your parent class and simply inherit this parent class on all other classes to make it a default functionality.

Credits: http://dwellupper.io/post/48/defining-class-constants-in-php

Split string to equal length substrings in Java

Here's a one-liner version which uses Java 8 IntStream to determine the indexes of the slice beginnings:

String x = "Thequickbrownfoxjumps";

String[] result = IntStream
                    .iterate(0, i -> i + 4)
                    .limit((int) Math.ceil(x.length() / 4.0))
                    .mapToObj(i ->
                        x.substring(i, Math.min(i + 4, x.length())
                    )
                    .toArray(String[]::new);

How to fix "ImportError: No module named ..." error in Python?

Here is a step-by-step solution:

  1. Add a script called run.py in /home/bodacydo/work/project and edit it like this:

    import programs.my_python_program
    programs.my_python_program.main()
    

    (replace main() with your equivalent method in my_python_program.)

  2. Go to /home/bodacydo/work/project
  3. Run run.py

Explanation: Since python appends to PYTHONPATH the path of the script from which it runs, running run.py will append /home/bodacydo/work/project. And voilà, import foo.tasks will be found.

How do I select which GPU to run a job on?

You can also set the GPU in the command line so that you don't need to hard-code the device into your script (which may fail on systems without multiple GPUs). Say you want to run your script on GPU number 5, you can type the following on the command line and it will run your script just this once on GPU#5:

CUDA_VISIBLE_DEVICES=5, python test_script.py

Git push: "fatal 'origin' does not appear to be a git repository - fatal Could not read from remote repository."

I had the same issue. When I checked my config file I noticed that 'fetch = +refs/heads/:refs/remotes/origin/' was on the same line as 'url = Z:/GIT/REPOS/SEL.git' as shown:

[core]
    repositoryformatversion = 0
    filemode = false
    bare = false
    logallrefupdates = true
    symlinks = false
    ignorecase = true
[remote "origin"]
    url = Z:/GIT/REPOS/SEL.git     fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
    remote = origin
    merge = refs/heads/master
[gui]
    wmstate = normal
    geometry = 1109x563+32+32 216 255

At first I did not think that this would have mattered but after seeing the post by Magere I moved the line and that fixed the problem:

[core]
    repositoryformatversion = 0
    filemode = false
    bare = false
    logallrefupdates = true
    symlinks = false
    ignorecase = true
[remote "origin"]
    url = Z:/GIT/REPOS/SEL.git
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
    remote = origin
    merge = refs/heads/master
[gui]
    wmstate = normal
    geometry = 1109x563+32+32 216 255

How can I select all options of multi-select select box on click?

I'm able to make it in a native way @ jsfiddle. Hope it will help.

Post improved answer when it work, and help others.

$(function () { 

    $(".example").multiselect({
                checkAllText : 'Select All',
            uncheckAllText : 'Deselect All',
            selectedText: function(numChecked, numTotal, checkedItems){
              return numChecked + ' of ' + numTotal + ' checked';
            },
            minWidth: 325
    });
    $(".example").multiselect("checkAll");    

});

http://jsfiddle.net/shivasakthi18/25uvnyra/

Regular Expression for alphanumeric and underscores

This works for me, found this in the O'Reilly's "Mastering Regular Expressions":

/^\w+$/

Explanation:

  • ^ asserts position at start of the string
    • \w+ matches any word character (equal to [a-zA-Z0-9_])
    • "+" Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)
  • $ asserts position at the end of the string

Verify yourself:

_x000D_
_x000D_
const regex = /^\w+$/;_x000D_
const str = `nut_cracker_12`;_x000D_
let m;_x000D_
_x000D_
if ((m = regex.exec(str)) !== null) {_x000D_
    // The result can be accessed through the `m`-variable._x000D_
    m.forEach((match, groupIndex) => {_x000D_
        console.log(`Found match, group ${groupIndex}: ${match}`);_x000D_
    });_x000D_
}
_x000D_
_x000D_
_x000D_

Android Studio 3.0 Flavor Dimension Issue

in KotlinDSL you can use like this :

flavorDimensions ("PlaceApp")
productFlavors {
    create("tapsi") {
        setDimension("PlaceApp")
        buildConfigField("String", "API_BASE_URL", "https://xxx/x/x/")
    }

}

SQL select only rows with max value on a column

Sorted the rev field in reverse order and then grouped by id which gave the first row of each grouping which is the one with the highest rev value.

SELECT * FROM (SELECT * FROM table1 ORDER BY id, rev DESC) X GROUP BY X.id;

Tested in http://sqlfiddle.com/ with the following data

CREATE TABLE table1
    (`id` int, `rev` int, `content` varchar(11));

INSERT INTO table1
    (`id`, `rev`, `content`)
VALUES
    (1, 1, 'One-One'),
    (1, 2, 'One-Two'),
    (2, 1, 'Two-One'),
    (2, 2, 'Two-Two'),
    (3, 2, 'Three-Two'),
    (3, 1, 'Three-One'),
    (3, 3, 'Three-Three')
;

This gave the following result in MySql 5.5 and 5.6

id  rev content
1   2   One-Two
2   2   Two-Two
3   3   Three-Two

How can I download a file from a URL and save it in Rails?

Try this:

require 'open-uri'
open('image.png', 'wb') do |file|
  file << open('http://example.com/image.png').read
end

Difference between agile and iterative and incremental development

Iterative development implies revisiting usual waterfall model steps over the course of product lifetime. The stages can even overlap, i.e. while doing end-to-end testing you could already start preparing new requirements.

Incremental development means you roadmap your features and implement them incrementally.

Agile aims at creating "potentially shippable product" after every sprint. How you achieve it is a different story. Agile tries to employ "best" techniques from various fields (e.g. extreme programming). Agile does not exclude running neither incremental nor iterative development.

Is there any way to return HTML in a PHP function? (without building the return value as a string)

This may be a sketchy solution, and I'd appreciate anybody pointing out whether this is a bad idea, since it's not a standard use of functions. I've had some success getting HTML out of a PHP function without building the return value as a string with the following:

function noStrings() {
    echo ''?>
        <div>[Whatever HTML you want]</div>
    <?php;
}

The just 'call' the function:

noStrings();

And it will output:

<div>[Whatever HTML you want]</div>

Using this method, you can also define PHP variables within the function and echo them out inside the HTML.

Simple parse JSON from URL on Android and display in listview

HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
BufferedReader in = new BufferedReader(new InputStreamReader(response
        .getEntity().getContent()));
String line = "";

while ((line = in.readLine()) != null) {

    JSONObject jObject = new JSONObject(line);

    if (jObject.has("name")) {

        String temp = jObject.getString("name");
        Log.e("name",temp);

    }

}

Key existence check in HashMap

Do you mean that you've got code like

if(map.containsKey(key)) doSomethingWith(map.get(key))

all over the place ? Then you should simply check whether map.get(key) returned null and that's it. By the way, HashMap doesn't throw exceptions for missing keys, it returns null instead. The only case where containsKey is needed is when you're storing null values, to distinguish between a null value and a missing value, but this is usually considered bad practice.

AngularJS access parent scope from child controller

If your HTML is like below you could do something like this:

<div ng-controller="ParentCtrl">
    <div ng-controller="ChildCtrl">
    </div>
</div>

Then you can access the parent scope as follows

function ParentCtrl($scope) {
    $scope.cities = ["NY", "Amsterdam", "Barcelona"];
}

function ChildCtrl($scope) {
    $scope.parentcities = $scope.$parent.cities;
}

If you want to access a parent controller from your view you have to do something like this:

<div ng-controller="xyzController as vm">
   {{$parent.property}}
</div>

See jsFiddle: http://jsfiddle.net/2r728/

Update

Actually since you defined cities in the parent controller your child controller will inherit all scope variables. So theoritically you don't have to call $parent. The above example can also be written as follows:

function ParentCtrl($scope) {
    $scope.cities = ["NY","Amsterdam","Barcelona"];
}

function ChildCtrl($scope) {
    $scope.parentCities = $scope.cities;
}

The AngularJS docs use this approach, here you can read more about the $scope.

Another update

I think this is a better answer to the original poster.

HTML

<div ng-app ng-controller="ParentCtrl as pc">
    <div ng-controller="ChildCtrl as cc">
        <pre>{{cc.parentCities | json}}</pre>
        <pre>{{pc.cities | json}}</pre>
    </div>
</div>

JS

function ParentCtrl() {
    var vm = this;
    vm.cities = ["NY", "Amsterdam", "Barcelona"];
}

function ChildCtrl() {
    var vm = this;
    ParentCtrl.apply(vm, arguments); // Inherit parent control

    vm.parentCities = vm.cities;
}

If you use the controller as method you can also access the parent scope as follows

function ChildCtrl($scope) {
    var vm = this;
    vm.parentCities = $scope.pc.cities; // note pc is a reference to the "ParentCtrl as pc"
}

As you can see there are many different ways in accessing $scopes.

Updated fiddle

_x000D_
_x000D_
function ParentCtrl() {_x000D_
    var vm = this;_x000D_
    vm.cities = ["NY", "Amsterdam", "Barcelona"];_x000D_
}_x000D_
    _x000D_
function ChildCtrl($scope) {_x000D_
    var vm = this;_x000D_
    ParentCtrl.apply(vm, arguments);_x000D_
    _x000D_
    vm.parentCitiesByScope = $scope.pc.cities;_x000D_
    vm.parentCities = vm.cities;_x000D_
}_x000D_
    
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.20/angular.min.js"></script>_x000D_
<div ng-app ng-controller="ParentCtrl as pc">_x000D_
  <div ng-controller="ChildCtrl as cc">_x000D_
    <pre>{{cc.parentCities | json}}</pre>_x000D_
    <pre>{{cc.parentCitiesByScope | json }}</pre>_x000D_
    <pre>{{pc.cities | json}}</pre>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Efficient iteration with index in Scala

I have the following approaches

object HelloV2 {

   def main(args: Array[String]) {

     //Efficient iteration with index in Scala

     //Approach #1
     var msg = "";

     for (i <- args.indices)
     {
       msg+=(args(i));
     }
     var msg1="";

     //Approach #2
     for (i <- 0 until args.length) 
     {
       msg1 += (args(i));
     }

     //Approach #3
     var msg3=""
     args.foreach{
       arg =>
        msg3 += (arg)
     }


      println("msg= " + msg);

      println("msg1= " + msg1);

      println("msg3= " + msg3);

   }
}

intelliJ IDEA 13 error: please select Android SDK

You have to Select Build Tool Version from your project setting.

  1. Select Project App Folder
  2. Press F4 OR Right Click on Project App Folder and open Module Settings In The Properties tab select Build Tool Version from List

This will work on my side i hope it will help you.

MongoDB distinct aggregation

You can use $addToSet with the aggregation framework to count distinct objects.

For example:

db.collectionName.aggregate([{
    $group: {_id: null, uniqueValues: {$addToSet: "$fieldName"}}
}])

Getting a Request.Headers value

if (Request.Headers["XYZComponent"].Count() > 0)

... will attempted to count the number of characters in the returned string, but if the header doesn't exist it will return NULL, hence why it's throwing an exception. Your second example effectively does the same thing, it will search through the collection of Headers and return NULL if it doesn't exist, which you then attempt to count the number of characters on:

Use this instead:

if(Request.Headers["XYZComponent"] != null)

Or if you want to treat blank or empty strings as not set then use:

if((Request.Headers["XYZComponent"] ?? "").Trim().Length > 0)

The Null Coalesce operator ?? will return a blank string if the header is null, stopping it throwing a NullReferenceException.

A variation of your second attempt will also work:

if (Request.Headers.AllKeys.Any(k => string.Equals(k, "XYZComponent")))

Edit: Sorry didn't realise you were explicitly checking for the value true:

bool isSet = Boolean.TryParse(Request.Headers["XYZComponent"], out isSet) && isSet;

Will return false if Header value is false, or if Header has not been set or if Header is any other value other than true or false. Will return true is the Header value is the string 'true'

Check if option is selected with jQuery, if not select a default

Look at the selectedIndex of the select element. BTW, that's a plain ol' DOM thing, not JQuery-specific.

Launch Minecraft from command line - username and password as prefix

You can do this, you just need to circumvent the launcher.

In %appdata%\.minecraft\bin (or ~/.minecraft/bin on unixy systems), there is a minecraft.jar file. This is the actual game - the launcher runs this.

Invoke it like so:

java -Xms512m -Xmx1g -Djava.library.path=natives/ -cp "minecraft.jar;lwjgl.jar;lwjgl_util.jar" net.minecraft.client.Minecraft <username> <sessionID>

Set the working directory to .minecraft/bin.

To get the session ID, POST (request this page):

https://login.minecraft.net?user=<username>&password=<password>&version=13

You'll get a response like this:

1343825972000:deprecated:SirCmpwn:7ae9007b9909de05ea58e94199a33b30c310c69c:dba0c48e1c584963b9e93a038a66bb98

The fourth field is the session ID. More details here. Read those details, this answer is outdated

Here's an example of logging in to minecraft.net in C#.

Struct with template variables in C++

From the other answers, the problem is that you're templating a typedef. The only "way" to do this is to use a templated class; ie, basic template metaprogramming.

template<class T> class vector_Typedefs {
    /*typedef*/ struct array { //The typedef isn't necessary
        size_t x; 
        T *ary; 
    }; 

    //Any other templated typedefs you need. Think of the templated class like something
    // between a function and namespace.
}

//An advantage is:
template<> class vector_Typedefs<bool>
{
    struct array {
        //Special behavior for the binary array
    }
}

ios app maximum memory budget

You should watch session 147 from the WWDC 2010 Session videos. It is "Advanced Performance Optimization on iPhone OS, part 2".
There is a lot of good advice on memory optimizations.

Some of the tips are:

  • Use nested NSAutoReleasePools to make sure your memory usage does not spike.
  • Use CGImageSource when creating thumbnails from large images.
  • Respond to low memory warnings.

How to git commit a single file/directory

For git 1.9.5 on Windows 7: "my Notes" (double quotes) corrected this issue. In my case putting the file(s) before or after the -m 'message'. made no difference; using single quotes was the problem.

PHP salt and hash SHA256 for login password

These examples are from php.net. Thanks to you, I also just learned about the new php hashing functions.

Read the php documentation to find out about the possibilities and best practices: http://www.php.net/manual/en/function.password-hash.php

Save a password hash:

$options = [
    'cost' => 11,
];
// Get the password from post
$passwordFromPost = $_POST['password'];

$hash = password_hash($passwordFromPost, PASSWORD_BCRYPT, $options);

// Now insert it (with login or whatever) into your database, use mysqli or pdo!

Get the password hash:

// Get the password from the database and compare it to a variable (for example post)
$passwordFromPost = $_POST['password'];
$hashedPasswordFromDB = ...;

if (password_verify($passwordFromPost, $hashedPasswordFromDB)) {
    echo 'Password is valid!';
} else {
    echo 'Invalid password.';
}

How do you add an ActionListener onto a JButton in Java

I don't know if this works but I made the variable names

public abstract class beep implements ActionListener {
    public static void main(String[] args) {
        JFrame f = new JFrame("beeper");
        JButton button = new JButton("Beep me");
        f.setVisible(true);
        f.setSize(300, 200);
        f.add(button);
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // Insert code here
            }
        });
    }
}

Javascript, viewing [object HTMLInputElement]

When you get a value from client make and that a value for example.

var current_text = document.getElementById('user_text').value;
        var http = new XMLHttpRequest();
        http.onreadystatechange = function () {

            if (http.readyState == 4 &&  http.status == 200 ){
                var response = http.responseText;
              document.getElementById('server_response').value = response;
                console.log(response.value);


            }

How can I open multiple files using "with open" in Python?

From Python 3.10 there is a new feature of Parenthesized context managers, which permits syntax like:

with (
    open("a", "w") as a,
    open("b", "w") as b
):
    do_something()

How can I use ":" as an AWK field separator?

-F is an argument to awk itself:

$echo "1: " | awk -F":" '/1/ {print $1}'
1

How do I replace part of a string in PHP?

This is probably what you need:

$text = str_replace(' ', '_', substr($text, 0, 10));

This view is not constrained

you can try this: 1. ensure you have added: compile 'com.android.support:design:25.3.1' (maybe you also should add compile 'com.android.support.constraint:constraint-layout:1.0.2') 2. enter image description here

3.click the Infer Constraints, hope it can help you.

How do you calculate program run time in python?

@JoshAdel covered a lot of it, but if you just want to time the execution of an entire script, you can run it under time on a unix-like system.

kotai:~ chmullig$ cat sleep.py 
import time

print "presleep"
time.sleep(10)
print "post sleep"
kotai:~ chmullig$ python sleep.py 
presleep
post sleep
kotai:~ chmullig$ time python sleep.py 
presleep
post sleep

real    0m10.035s
user    0m0.017s
sys 0m0.016s
kotai:~ chmullig$ 

What is &amp used for

That's a great example. When &current is parsed into a text node it is converted to ¤t. When parsed into an attribute value, it is parsed as &current.

If you want &current in a text node, you should write &amp;current in your markup.

The gory details are in the HTML5 parsing spec - Named Character Reference State

What is the simplest way to convert a Java string from all caps (words separated by underscores) to CamelCase (no word separators)?

static String toCamelCase(String s){
   String[] parts = s.split("_");
   String camelCaseString = "";
   for (String part : parts){
      camelCaseString = camelCaseString + toProperCase(part);
   }
   return camelCaseString;
}

static String toProperCase(String s) {
    return s.substring(0, 1).toUpperCase() +
               s.substring(1).toLowerCase();
}

Note: You need to add argument validation.

Serializing to JSON in jQuery

No, the standard way to serialize to JSON is to use an existing JSON serialization library. If you don't wish to do this, then you're going to have to write your own serialization methods.

If you want guidance on how to do this, I'd suggest examining the source of some of the available libraries.

EDIT: I'm not going to come out and say that writing your own serliazation methods is bad, but you must consider that if it's important to your application to use well-formed JSON, then you have to weigh the overhead of "one more dependency" against the possibility that your custom methods may one day encounter a failure case that you hadn't anticipated. Whether that risk is acceptable is your call.

Changing the resolution of a VNC session in linux

Real VNC server 4.4 includes support for Xrandr, which allows resizing the VNC. Start the server with:

vncserver -geometry 1600x1200 -randr 1600x1200,1440x900,1024x768

Then resize with:

xrandr -s 1600x1200
xrandr -s 1440x900
xrandr -s 1024x768

Is there a way to know your current username in mysql?

Use this query:

SELECT USER();

Or

SELECT CURRENT_USER;

How to remove an id attribute from a div using jQuery?

I'm not sure what jQuery api you're looking at, but you should only have to specify id.

$('#thumb').removeAttr('id');

C# get and set properties for a List Collection

Your setters are strange, which is why you may be seeing a problem.

First, consider whether you even need these setters - if so, they should take a List<string>, not just a string:

set
{
    _subHead = value;
}

These lines:

newSec.subHead.Add("test string");

Are calling the getter and then call Add on the returned List<string> - the setter is not invoked.

How to change menu item text dynamically in Android

Declare your menu field.

private Menu menu;

Following is onCreateOptionsMenu() method

public boolean onCreateOptionsMenu(Menu menu) {
this.menu = menu;
    try {
        getMenuInflater().inflate(R.menu.menu_main,menu);
    } catch (Exception e) {
        e.printStackTrace();
        Log.i(TAG, "onCreateOptionsMenu: error: "+e.getMessage());
    }
    return super.onCreateOptionsMenu(menu);
}

Following will be your name setter activity. Either through a button click or through conditional code

public void setMenuName(){
menu.findItem(R.id.menuItemId).setTitle(/*Set your desired menu title here*/);
}

This worked for me.

Neither user 10102 nor current process has android.permission.READ_PHONE_STATE

I was experiencing this problem on Samsung devices (fine on others). like zyamys suggested in his/her comment, I added the manifest.permission line but in addition to rather than instead of the original line, so:

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

I'm targeting API 22, so don't need to explicitly ask for permissions.

Calling a php function by onclick event

You cannot execute php functions from JavaScript.

PHP runs on the server before the browser sees it. PHP outputs HTML and JavaScript.

When the browser reads the html and javascript it executes it.

Check if a String is in an ArrayList of Strings

    List list1 = new ArrayList();
    list1.add("one");
    list1.add("three");
    list1.add("four");

    List list2 = new ArrayList();
    list2.add("one");
    list2.add("two");
    list2.add("three");
    list2.add("four");
    list2.add("five");


    list2.stream().filter( x -> !list1.contains(x) ).forEach(x -> System.out.println(x));

The output is:

two
five

Copy entire contents of a directory to another using php

Like said elsewhere, copy only works with a single file for source and not a pattern. If you want to copy by pattern, use glob to determine the files, then run copy. This will not copy subdirectories though, nor will it create the destination directory.

function copyToDir($pattern, $dir)
{
    foreach (glob($pattern) as $file) {
        if(!is_dir($file) && is_readable($file)) {
            $dest = realpath($dir . DIRECTORY_SEPARATOR) . basename($file);
            copy($file, $dest);
        }
    }    
}
copyToDir('./test/foo/*.txt', './test/bar'); // copies all txt files

pycharm running way slow

It is super easy by changing the heap size as it was mentioned. Just easily by going to Pycharm HELP -> Edit custom VM option ... and change it to:

-Xms2048m
-Xmx2048m

How to add class active on specific li on user click with jQuery

        // Remove active for all items.
        $('.sidebar-menu li').removeClass('active');
        // highlight submenu item
        $('li a[href="' + this.location.pathname + '"]').parent().addClass('active');
        // Highlight parent menu item.
        $('ul a[href="' + this.location.pathname + '"]').parents('li').addClass('active')

Check image width and height before upload with Javascript

Attach the function to the onchange method of the input type file /onchange="validateimg(this)"/

   function validateimg(ctrl) { 
        var fileUpload = ctrl;
        var regex = new RegExp("([a-zA-Z0-9\s_\\.\-:])+(.jpg|.png|.gif)$");
        if (regex.test(fileUpload.value.toLowerCase())) {
            if (typeof (fileUpload.files) != "undefined") {
                var reader = new FileReader();
                reader.readAsDataURL(fileUpload.files[0]);
                reader.onload = function (e) {
                    var image = new Image();
                    image.src = e.target.result;
                    image.onload = function () {
                        var height = this.height;
                        var width = this.width;
                        if (height < 1100 || width < 750) {
                            alert("At least you can upload a 1100*750 photo size.");
                            return false;
                        }else{
                            alert("Uploaded image has valid Height and Width.");
                            return true;
                        }
                    };
                }
            } else {
                alert("This browser does not support HTML5.");
                return false;
            }
        } else {
            alert("Please select a valid Image file.");
            return false;
        }
    }

How to enable CORS in ASP.NET Core

You have to configure in Startup.cs class

services.AddCors(options =>
        {
            options.AddPolicy("CorsPolicy",
                builder => builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials());
        });

How to specify a local file within html using the file: scheme?

the "file://" url protocol can only be used to locate files in the file system of the local machine. since this html code is interpreted by a browser, the "local machine" is the machine that is running the browser.

if you are getting file not found errors, i suspect it is because the file is not found. however, it could also be a security limitation of the browser. some browsers will not let you reference a filesystem file from a non-filesystem html page. you could try using the file path from the command line on the machine running the browser to confirm that this is a browser limitation and not a legitimate missing file.

How do you redirect to a page using the POST verb?

try this one

return Content("<form action='actionname' id='frmTest' method='post'><input type='hidden' name='someValue' value='" + someValue + "' /><input type='hidden' name='anotherValue' value='" + anotherValue + "' /></form><script>document.getElementById('frmTest').submit();</script>");

Expected initializer before function name

You are missing a semicolon at the end of your 'struct' definition.

Also,

*sotrudnik

needs to be

sotrudnik*

Stop UIWebView from "bouncing" vertically?

Came across this searching for an answer and I eventually just lucked on an answer of my own by messing about. I did

[[webview scrollView] setBounces:NO];

and it worked.

Change background color of R plot

Old question but I have a much better way of doing this. Rather than using rect() use polygon. This allows you to keep everything in plot without using points. Also you don't have to mess with par at all. If you want to keep things automated make the coordinates of polygon a function of your data.

plot.new()
polygon(c(-min(df[,1])^2,-min(df[,1])^2,max(df[,1])^2,max(df[,1])^2),c(-min(df[,2])^2,max(df[,2])^2,max(df[,2])^2,-min(df[,2])^2), col="grey")
par(new=T)
plot(df)

How to select all textareas and textboxes using jQuery?

names = [];
$('input[name=text], textarea').each(
    function(index){  
        var input = $(this);
        names.push( input.attr('name') );
        //input.attr('id');
    }
);

it select all textboxes and textarea in your DOM, where $.each function iterates to provide name of ecah element.

Get file size, image width and height before upload

A working jQuery validate example:

   $(function () {
        $('input[type=file]').on('change', function() {
            var $el = $(this);
            var files = this.files;
            var image = new Image();
            image.onload = function() {
                $el
                    .attr('data-upload-width', this.naturalWidth)
                    .attr('data-upload-height', this.naturalHeight);
            }

            image.src = URL.createObjectURL(files[0]);
        });

        jQuery.validator.unobtrusive.adapters.add('imageminwidth', ['imageminwidth'], function (options) {
            var params = {
                imageminwidth: options.params.imageminwidth.split(',')
            };

            options.rules['imageminwidth'] = params;
            if (options.message) {
                options.messages['imageminwidth'] = options.message;
            }
        });

        jQuery.validator.addMethod("imageminwidth", function (value, element, param) {
            var $el = $(element);
            if(!element.files && element.files[0]) return true;
            return parseInt($el.attr('data-upload-width')) >=  parseInt(param["imageminwidth"][0]);
        });

    } (jQuery));

How to center HTML5 Videos?

_x000D_
_x000D_
<html>
  <body>
    <h1 align="center">
      <video width="1000" controls>
        <source src="video.mp4" type="video/mp4">
      </video>
    </h1>
  </body>
</html>
_x000D_
_x000D_
_x000D_

What is the equivalent of "none" in django templates?

You could try this:

{% if not profile.user.first_name.value %}
  <p> -- </p>
{% else %}
  {{ profile.user.first_name }} {{ profile.user.last_name }}
{% endif %}

This way, you're essentially checking to see if the form field first_name has any value associated with it. See {{ field.value }} in Looping over the form's fields in Django Documentation.

I'm using Django 3.0.

Convert timestamp to date in Oracle SQL

You can try the simple one

select to_date('2020-07-08T15:30:42Z','yyyy-mm-dd"T"hh24:mi:ss"Z"') from dual;

go get results in 'terminal prompts disabled' error for github private repo

It complains because it needs to use ssh instead of https but your git is still configured with https. so basically as others mentioned previously you need to either enable prompts or to configure git to use ssh instead of https. a simple way to do this by running the following:

git config --global --add url."[email protected]:".insteadOf "https://github.com/"

or if you already use ssh with git in your machine, you can safely edit ~/.gitconfig and add the following line at the very bottom

Note: This covers all SVC, source version control, that depends on what you exactly use, github, gitlab, bitbucket)

# Enforce SSH
[url "ssh://[email protected]/"]
  insteadOf = https://github.com/
[url "ssh://[email protected]/"]
        insteadOf = https://gitlab.com/
[url "ssh://[email protected]/"]
  insteadOf = https://bitbucket.org/
  • If you want to keep password pompts disabled, you need to cache password. For more information on how to cache your github password on mac, windows or linux, please visit this page.

  • For more information on how to add ssh to your github account, please visit this page.

Also, more importantly, if this is a private repository for a company or for your self, you may need to skip using proxy or checksum database for such repos to avoid exposing them publicly.

To do this, you need to set GOPRIVATE environment variable that controls which modules the go command considers to be private (not available publicly) and should therefore NOT use the proxy or checksum database.

The variable is a comma-separated list of patterns (same syntax of Go's path.Match) of module path prefixes. For example,

export GOPRIVATE=*.corp.example.com,github.com/mycompany/*

Or

go env -w GOPRIVATE=github.com/mycompany/*
  • For more information on how to solve private packages/modules checksum validation issues, please read this article.
  • For more information about go 13 modules and new enhancements, please check out Go 1.13 Modules Release notes.

One last thing not to forget to mention, you can still configure go get to authenticate and fetch over https, all you need to do is to add the following line to $HOME/.netrc

machine github.com login USERNAME password APIKEY
  • For GitHub accounts, the password can be a personal access tokens.
  • For more information on how to do this, please check Go FAQ page.

I hope this helps the community and saves others' time to solve described issues quickly. please feel free to leave a comment in case you want more support or help.

How to check if spark dataframe is empty?

For Spark 2.1.0, my suggestion would be to use head(n: Int) or take(n: Int) with isEmpty, whichever one has the clearest intent to you.

df.head(1).isEmpty
df.take(1).isEmpty

with Python equivalent:

len(df.head(1)) == 0  # or bool(df.head(1))
len(df.take(1)) == 0  # or bool(df.take(1))

Using df.first() and df.head() will both return the java.util.NoSuchElementException if the DataFrame is empty. first() calls head() directly, which calls head(1).head.

def first(): T = head()
def head(): T = head(1).head

head(1) returns an Array, so taking head on that Array causes the java.util.NoSuchElementException when the DataFrame is empty.

def head(n: Int): Array[T] = withAction("head", limit(n).queryExecution)(collectFromPlan)

So instead of calling head(), use head(1) directly to get the array and then you can use isEmpty.

take(n) is also equivalent to head(n)...

def take(n: Int): Array[T] = head(n)

And limit(1).collect() is equivalent to head(1) (notice limit(n).queryExecution in the head(n: Int) method), so the following are all equivalent, at least from what I can tell, and you won't have to catch a java.util.NoSuchElementException exception when the DataFrame is empty.

df.head(1).isEmpty
df.take(1).isEmpty
df.limit(1).collect().isEmpty

I know this is an older question so hopefully it will help someone using a newer version of Spark.

C# adding a character in a string

I had to do something similar, trying to convert a string of numbers into a timespan by adding in : and .. Basically I was taking 235959999 and needing to convert it to 23:59:59.999. For me it was easy because I knew where I needed to "insert" said characters.

ts = ts.Insert(6,".");
ts = ts.Insert(4,":");
ts = ts.Insert(2,":");

Basically reassigning ts to itself with the inserted character. I worked my way from the back to front, because I was lazy and didn't want to do additional math for the other inserted characters.

You could try something similar by doing:

alpha = alpha.Insert(5,"-");
alpha = alpha.Insert(11,"-"); //add 1 to account for 1 -
alpha = alpha.Insert(17,"-"); //add 2 to account for 2 -
...

See what's in a stash without applying it

From the man git-stash page:

The modifications stashed away by this command can be listed with git stash list, inspected with git stash show

show [<stash>]
       Show the changes recorded in the stash as a diff between the stashed state and
       its original parent. When no <stash> is given, shows the latest one. By default,
       the command shows the diffstat, but it will accept any format known to git diff
       (e.g., git stash show -p stash@{1} to view the second most recent stash in patch
       form).

To list the stashed modifications

git stash list

To show files changed in the last stash

git stash show

So, to view the content of the most recent stash, run

git stash show -p

To view the content of an arbitrary stash, run something like

git stash show -p stash@{1}

Laravel 5.4 Specific Table Migration

php artisan migrate --path=/database/migrations/fileName.php

Just follow the instruction execute this commant file name here should be your migration table name Example: php artisan migrate --path=/database/migrations/2020_02_21_101937_create_jobs_table.php

Max or Default?

Sounds like a case for DefaultIfEmpty (untested code follows):

Dim x = (From y In context.MyTable _
         Where y.MyField = value _
         Select y.MyCounter).DefaultIfEmpty.Max

Adding a rule in iptables in debian to open a new port

About your command line:

root@debian:/# sudo iptables -A INPUT -p tcp --dport 3306 --jump ACCEPT
root@debian:/# iptables-save
  • You are already authenticated as root so sudo is redundant there.

  • You are missing the -j or --jump just before the ACCEPT parameter (just tought that was a typo and you are inserting it correctly).

About yout question:

If you are inserting the iptables rule correctly as you pointed it in the question, maybe the issue is related to the hypervisor (virtual machine provider) you are using.

If you provide the hypervisor name (VirtualBox, VMWare?) I can further guide you on this but here are some suggestions you can try first:

check your vmachine network settings and:

  • if it is set to NAT, then you won't be able to connect from your base machine to the vmachine.

  • if it is set to Hosted, you have to configure first its network settings, it is usually to provide them an IP in the range 192.168.56.0/24, since is the default the hypervisors use for this.

  • if it is set to Bridge, same as Hosted but you can configure it whenever IP range makes sense for you configuration.

Hope this helps.

What's the difference between commit() and apply() in SharedPreferences

Use apply().

It writes the changes to the RAM immediately and waits and writes it to the internal storage(the actual preference file) after. Commit writes the changes synchronously and directly to the file.

String Pattern Matching In Java

You can do it using string.indexOf("{item}"). If the result is greater than -1 {item} is in the string

How to write "Html.BeginForm" in Razor

The following code works fine:

@using (Html.BeginForm("Upload", "Upload", FormMethod.Post, 
                                      new { enctype = "multipart/form-data" }))
{
    @Html.ValidationSummary(true)
    <fieldset>
        Select a file <input type="file" name="file" />
        <input type="submit" value="Upload" />
    </fieldset>
}

and generates as expected:

<form action="/Upload/Upload" enctype="multipart/form-data" method="post">    
    <fieldset>
        Select a file <input type="file" name="file" />
        <input type="submit" value="Upload" />
    </fieldset>
</form>

On the other hand if you are writing this code inside the context of other server side construct such as an if or foreach you should remove the @ before the using. For example:

@if (SomeCondition)
{
    using (Html.BeginForm("Upload", "Upload", FormMethod.Post, 
                                      new { enctype = "multipart/form-data" }))
    {
        @Html.ValidationSummary(true)
        <fieldset>
            Select a file <input type="file" name="file" />
            <input type="submit" value="Upload" />
        </fieldset>
    }
}

As far as your server side code is concerned, here's how to proceed:

[HttpPost]
public ActionResult Upload(HttpPostedFileBase file) 
{
    if (file != null && file.ContentLength > 0) 
    {
        var fileName = Path.GetFileName(file.FileName);
        var path = Path.Combine(Server.MapPath("~/content/pics"), fileName);
        file.SaveAs(path);
    }
    return RedirectToAction("Upload");
}

How to upgrade Git to latest version on macOS?

In order to keep both versions, I just changed the value of PATH environment variable by putting the new version's git path "/usr/local/git/bin/" at the beginning, it forces to use the newest version:

$ echo $PATH

/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/X11/bin:/usr/local/git/bin/

$ git --version

git version 2.4.9 (Apple Git-60)

original value: /usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/X11/bin:/usr/local/git/bin/

new value: /usr/local/git/bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/X11/bin

$ export PATH=/usr/local/git/bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/X11/bin

$ git --version

git version 2.13.0

Entity Framework code first unique column

Solution for EF4.3

Unique UserName

Add data annotation over column as:

 [Index(IsUnique = true)]
 [MaxLength(255)] // for code-first implementations
 public string UserName{get;set;}

Unique ID , I have added decoration [Key] over my column and done. Same solution as described here: https://msdn.microsoft.com/en-gb/data/jj591583.aspx

IE:

[Key]
public int UserId{get;set;}

Alternative answers

using data annotation

[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Column("UserId")]

using mapping

  mb.Entity<User>()
            .HasKey(i => i.UserId);
        mb.User<User>()
          .Property(i => i.UserId)
          .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)
          .HasColumnName("UserId");

CodeIgniter Active Record - Get number of returned rows

If you only need the number of rows in a query and don't need the actual row data, use count_all_results

echo $this->db
       ->where('active',1)
       ->count_all_results('table_name');

Read next word in java

Using Scanners, you will end up spawning a lot of objects for every line. You will generate a decent amount of garbage for the GC with large files. Also, it is nearly three times slower than using split().

On the other hand, If you split by space (line.split(" ")), the code will fail if you try to read a file with a different whitespace delimiter. If split() expects you to write a regular expression, and it does matching anyway, use split("\\s") instead, that matches a "bit" more whitespace than just a space character.

P.S.: Sorry, I don't have right to comment on already given answers.

Send JSON data with jQuery

You need to set the correct content type and stringify your object.

var arr = {City:'Moscow', Age:25};
$.ajax({
    url: "Ajax.ashx",
    type: "POST",
    data: JSON.stringify(arr),
    dataType: 'json',
    async: false,
    contentType: 'application/json; charset=utf-8',
    success: function(msg) {
        alert(msg);
    }
});

Setting Android Theme background color

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="android:Theme.Holo.NoActionBar">
        <item name="android:windowBackground">@android:color/black</item>
    </style>

</resources>

How to Identify Microsoft Edge browser via CSS?

More accurate for Edge (do not include latest IE 15) is:

@supports (display:-ms-grid) { ... }

@supports (-ms-ime-align:auto) { ... } works for all Edge versions (currently up to IE15).

How do I call a function inside of another function?

_x000D_
_x000D_
function function_one()_x000D_
{_x000D_
    alert("The function called 'function_one' has been called.")_x000D_
    //Here u would like to call function_two._x000D_
    function_two(); _x000D_
}_x000D_
_x000D_
function function_two()_x000D_
{_x000D_
    alert("The function called 'function_two' has been called.")_x000D_
}
_x000D_
_x000D_
_x000D_

How to extract filename.tar.gz file

A tar.gz is a tar file inside a gzip file, so 1st you must unzip the gzip file with gunzip -d filename.tar.gz , and then use tar to untar it. However, since gunzip says it isn't in gzip format, you can see what format it is in with file filename.tar.gz, and use the appropriate program to open it.

Getting coordinates of marker in Google Maps API

One more alternative options

var map = new google.maps.Map(document.getElementById('map_canvas'), {
    zoom: 1,
    center: new google.maps.LatLng(35.137879, -82.836914),
    mapTypeId: google.maps.MapTypeId.ROADMAP
});

var myMarker = new google.maps.Marker({
    position: new google.maps.LatLng(47.651968, 9.478485),
    draggable: true
});

google.maps.event.addListener(myMarker, 'dragend', function (evt) {
    document.getElementById('current').innerHTML = '<p>Marker dropped: Current Lat: ' + evt.latLng.lat().toFixed(3) + ' Current Lng: ' + evt.latLng.lng().toFixed(3) + '</p>';
});

google.maps.event.addListener(myMarker, 'dragstart', function (evt) {
    document.getElementById('current').innerHTML = '<p>Currently dragging marker...</p>';
});

map.setCenter(myMarker.position);
myMarker.setMap(map);

and html file

<body>
    <section>
        <div id='map_canvas'></div>
        <div id="current">Nothing yet...</div>
    </section>
</body>

Reset all the items in a form

Additional-> To clear the Child Controls The below function would clear the nested(Child) controls also, wrap up in a class.

 public static void ClearControl(Control control)
        {
            if (control is TextBox)
            {
                TextBox txtbox = (TextBox)control;
                txtbox.Text = string.Empty;
            }
            else if (control is CheckBox)
            {
                CheckBox chkbox = (CheckBox)control;
                chkbox.Checked = false;
            }
            else if (control is RadioButton)
            {
                RadioButton rdbtn = (RadioButton)control;
                rdbtn.Checked = false;
            }
            else if (control is DateTimePicker)
            {
                DateTimePicker dtp = (DateTimePicker)control;
                dtp.Value = DateTime.Now;
            }
            else if (control is ComboBox)
            {
                ComboBox cmb = (ComboBox)control;
                if (cmb.DataSource != null)
                {
                    cmb.SelectedItem = string.Empty;
                    cmb.SelectedValue = 0;
                }
            }
            ClearErrors(control);
            // repeat for combobox, listbox, checkbox and any other controls you want to clear
            if (control.HasChildren)
            {
                foreach (Control child in control.Controls)
                {
                    ClearControl(child);
                }
            }


        }

What is the difference between #include <filename> and #include "filename"?

#include <abc.h>

is used to include standard library files. So the compiler will check in the locations where standard library headers are residing.

#include "xyz.h"

will tell the compiler to include user-defined header files. So the compiler will check for these header files in the current folder or -I defined folders.

How to interactively (visually) resolve conflicts in SourceTree / git

I'm using SourceTree along with TortoiseMerge/Diff, which is very easy and convinient diff/merge tool.

If you'd like to use it as well, then:

  1. Get standalone version of TortoiseMerge/Diff (quite old, since it doesn't ship standalone since version 1.6.7 of TortosieSVN, that is since July 2011). Links and details in this answer.

  2. Unzip TortoiseIDiff.exe and TortoiseMerge.exe to any folder (c:\Program Files (x86)\Atlassian\SourceTree\extras\ in my case).

  3. In SourceTree open Tools > Options > Diff > External Diff / Merge. Select TortoiseMerge in both dropdown lists.

  4. Hit OK and point SourceTree to your location of TortoiseIDiff.exe and TortoiseMerge.exe.

After that, you can select Resolve Conflicts > Launch External Merge Tool from context menu on each conflicted file in your local repository. This will open up TortoiseMerge, where you can easily deal with all the conflicts, you have. Once finished, simply close TortoiseMerge (you don't even need to save changes, this will probably be done automatically) and after few seconds SourceTree should handle that gracefully.

The only problem is, that it automatically creates backup copy, even though proper option is unchecked.

How can I insert into a BLOB column from an insert statement in sqldeveloper?

  1. insert into mytable(id, myblob) values (1,EMPTY_BLOB);
  2. SELECT * FROM mytable mt where mt.id=1 for update
  3. Click on the Lock icon to unlock for editing
  4. Click on the ... next to the BLOB to edit
  5. Select the appropriate tab and click open on the top left.
  6. Click OK and commit the changes.

How do I use StringUtils in Java?

StringUtils is an Apache Commons project. You need to download and add the library to your classpath.

To use:

import org.apache.commons.lang3.StringUtils;

How to put a List<class> into a JSONObject and then read that object?

This is how I do it using Google Gson. I am not sure, if there are a simpler way to do this.( with or without an external library).

 Type collectionType = new TypeToken<List<Class>>() {
                } // end new
                        .getType();

                String gsonString = 
                new Gson().toJson(objList, collectionType);

Find a file with a certain extension in folder

Look at the System.IO.Directory class and the static method GetFiles. It has an overload that accepts a path and a search pattern. Example:

 string[] files = System.IO.Directory.GetFiles(path, "*.txt");

#if DEBUG vs. Conditional("DEBUG")

With the first example, SetPrivateValue won't exist in the build if DEBUG is not defined, with the second example, calls to SetPrivateValue won't exist in the build if DEBUG is not defined.

With the first example, you'll have to wrap any calls to SetPrivateValue with #if DEBUG as well.

With the second example, the calls to SetPrivateValue will be omitted, but be aware that SetPrivateValue itself will still be compiled. This is useful if you're building a library, so an application referencing your library can still use your function (if the condition is met).

If you want to omit the calls and save the space of the callee, you could use a combination of the two techniques:

[System.Diagnostics.Conditional("DEBUG")]
public void SetPrivateValue(int value){
    #if DEBUG
    // method body here
    #endif
}

How to uninstall/upgrade Angular CLI?

Run the following commands to get the very latest of angular

npm uninstall -g @angular/cli
npm cache verify
npm install -g @angular/cli@latest
npm install

Use multiple @font-face rules in CSS

Multiple variations of a font family can be declared by changing the font-weight and src property of @font-face rule.

/* Regular Weight */
@font-face {
    font-family: Montserrat;
    src: url("../fonts/Montserrat-Regular.ttf");
}

/* SemiBold (600) Weight */
@font-face {
    font-family: Montserrat;
    src: url("../fonts/Montserrat-SemiBold.ttf");
    font-weight: 600;
}

/* Bold Weight */
@font-face {
    font-family: Montserrat;
    src: url("../fonts/Montserrat-Bold.ttf");
    font-weight: bold;
}

Declared rules can be used by following

/* Regular */
font-family: Montserrat;


/* Semi Bold */
font-family: Montserrat;
font-weght: 600;

/* Bold */
font-family: Montserrat;
font-weight: bold;

ASP.NET Web API session or something?

You can use cookies if the data is small enough and does not present a security concern. The same HttpContext.Current based approach should work.

Request and response HTTP headers can also be used to pass information between service calls.

Can I use a binary literal in C or C++?

You can use the function found in this question to get up to 22 bits in C++. Here's the code from the link, suitably edited:

template< unsigned long long N >
struct binary
{
  enum { value = (N % 8) + 2 * binary< N / 8 > :: value } ;
};

template<>
struct binary< 0 >
{
  enum { value = 0 } ;
};

So you can do something like binary<0101011011>::value.

Windows XP or later Windows: How can I run a batch file in the background with no window displayed?

I think this is the easiest and shortest solution to running a batch file without opening the DOS window, it can be very distracting when you want to schedule a set of commands to run periodically, so the DOS window keeps poping up, here is your solution. Use a VBS Script to call the batch file ...

Set WshShell = CreateObject("WScript.Shell" ) 
WshShell.Run chr(34) & "C:\Batch Files\ mycommands.bat" & Chr(34), 0 
Set WshShell = Nothing 

Copy the lines above to an editor and save the file with .VBS extension. Edit the .BAT file name and path accordingly.

Set Text property of asp:label in Javascript PROPER way

Instead of using a Label use a text input:

<script type="text/javascript">
    onChange = function(ctrl) {
        var txt = document.getElementById("<%= txtResult.ClientID %>");
        if (txt){
            txt.value = ctrl.value;
        }           
    }
</script>

<asp:TextBox ID="txtTest" runat="server" onchange="onChange(this);" />      

<!-- pseudo label that will survive postback -->  
<input type="text" id="txtResult" runat="server" readonly="readonly" tabindex="-1000" style="border:0px;background-color:transparent;" />        

<asp:Button ID="btnTest" runat="server" Text="Test" />

How to iterate using ngFor loop Map containing key as string and values as map iteration

Edit

For angular 6.1 and newer, use the KeyValuePipe as suggested by Londeren.

For angular 6.0 and older

To make things easier, you can create a pipe.

import {Pipe, PipeTransform} from '@angular/core';

@Pipe({name: 'getValues'})
export class GetValuesPipe implements PipeTransform {
    transform(map: Map<any, any>): any[] {
        let ret = [];

        map.forEach((val, key) => {
            ret.push({
                key: key,
                val: val
            });
        });

        return ret;
    }
}

 <li *ngFor="let recipient of map |getValues">

As it it pure, it will not be triggered on every change detection, but only if the reference to the map variable changes

Stackblitz demo

How to add (vertical) divider to a horizontal LinearLayout?

Your divider may not be showing due to too large dividerPadding. You set 22dip, that means the divider is truncated by 22dip from top and by 22dip from bottom. If your layout height is less than or equal 44dip then no divider is visible.

git remove merge commit from history

To Just Remove a Merge Commit

If all you want to do is to remove a merge commit (2) so that it is like it never happened, the command is simply as follows

git rebase --onto <sha of 1> <sha of 2> <blue branch>

And now the purple branch isn't in the commit log of blue at all and you have two separate branches again. You can then squash the purple independently and do whatever other manipulations you want without the merge commit in the way.

rsync error: failed to set times on "/foo/bar": Operation not permitted

If /foo/bar is on NFS (or possibly some FUSE filesystem), that might be the problem.

Either way, adding -O / --omit-dir-times to your command line will avoid it trying to set modification times on directories.

Where do I find some good examples for DDD?

The difficulty with DDD samples is that they're often very domain specific and the technical implementation of the resulting system doesn't always show the design decisions and transitions that were made in modelling the domain, which is really at the core of DDD. DDD is much more about the process than it is the code. (as some say, the best DDD sample is the book itself!)

That said, a well commented sample app should at least reveal some of these decisions and give you some direction in terms of matching up your domain model with the technical patterns used to implement it.

You haven't specified which language you're using, but I'll give you a few in a few different languages:

DDDSample - a Java sample that reflects the examples Eric Evans talks about in his book. This is well commented and shows a number of different methods of solving various problems with separate bounded contexts (ie, the presentation layer). It's being actively worked on, so check it regularly for updates.

dddps - Tim McCarthy's sample C# app for his book, .NET Domain-Driven Design with C#

S#arp Architecture - a pragmatic C# example, not as "pure" a DDD approach perhaps due to its lack of a real domain problem, but still a nice clean approach.

With all of these sample apps, it's probably best to check out the latest trunk versions from SVN/whatever to really get an idea of the thinking and technology patterns as they should be updated regularly.

How do I show my global Git configuration?

Git 2.6 (Sept/Oct 2015) will add the option --name-only to simplify the output of a git config -l:

See commit a92330d, commit f225987, commit 9f1429d (20 Aug 2015) by Jeff King (peff).
See commit ebca2d4 (20 Aug 2015), and commit 905f203, commit 578625f (10 Aug 2015) by SZEDER Gábor (szeder).
(Merged by Junio C Hamano -- gitster -- in commit fc9dfda, 31 Aug 2015)

config: add '--name-only' option to list only variable names

'git config' can only show values or name-value pairs, so if a shell script needs the names of set config variables it has to run 'git config --list' or '--get-regexp' and parse the output to separate config variable names from their values.
However, such a parsing can't cope with multi-line values.

Though 'git config' can produce null-terminated output for newline-safe parsing, that's of no use in such a case, because shells can't cope with null characters.

Even our own bash completion script suffers from these issues.

Help the completion script, and shell scripts in general, by introducing the '--name-only' option to modify the output of '--list' and '--get-regexp' to list only the names of config variables, so they don't have to perform error-prone post processing to separate variable names from their values anymore.

How can I select and upload multiple files with HTML and PHP, using HTTP POST?

i have created a php function which is used to upload multiple images, this function can upload multiple images in specific folder as well it can saves the records into the database in the following code $arrayimage is the array of images which is sent through form note that it will not allow upload to use multiple but you need to create different input field with same name as will you can set dynamic add field of file unput on button click.

$dir is the directory in which you want to save the image $fields is the name of the field which you want to store in the database

database field must be in array formate example if you have database imagestore and fields name like id,name,address then you need to post data like

$fields=array("id"=$_POST['idfieldname'], "name"=$_POST['namefield'],"address"=$_POST['addressfield']);

and then pass that field into function $fields

$table is the name of the table in which you want to store the data..

function multipleImageUpload($arrayimage,$dir,$fields,$table)
{
    //extracting extension of uploaded file
    $allowedExts = array("gif", "jpeg", "jpg", "png");
    $temp = explode(".", $arrayimage["name"]);
    $extension = end($temp);

    //validating image
    if ((($arrayimage["type"] == "image/gif")
    || ($arrayimage["type"] == "image/jpeg")
    || ($arrayimage["type"] == "image/jpg")
    || ($arrayimage["type"] == "image/pjpeg")
    || ($arrayimage["type"] == "image/x-png")
    || ($arrayimage["type"] == "image/png"))

    //check image size

    && ($arrayimage["size"] < 20000000)

    //check iamge extension in above created extension array
    && in_array($extension, $allowedExts)) 
    {
        if ($arrayimage["error"] > 0) 
        {
            echo "Error: " . $arrayimage["error"] . "<br>";
        } 
        else 
        {
            echo "Upload: " . $arrayimage["name"] . "<br>";
            echo "Type: " . $arrayimage["type"] . "<br>";
            echo "Size: " . ($arrayimage["size"] / 1024) . " kB<br>";
            echo "Stored in: ".$arrayimage['tmp_name']."<br>";

            //check if file is exist in folder of not
            if (file_exists($dir."/".$arrayimage["name"])) 
            {
                echo $arrayimage['name'] . " already exists. ";
            } 
            else 
            {
                //extracting database fields and value
                foreach($fields as $key=>$val)
                {
                    $f[]=$key;
                    $v[]=$val;
                    $fi=implode(",",$f);
                    $value=implode("','",$v);
                }
                //dynamic sql for inserting data into any table
                $sql="INSERT INTO " . $table ."(".$fi.") VALUES ('".$value."')";
                //echo $sql;
                $imginsquery=mysql_query($sql);
                move_uploaded_file($arrayimage["tmp_name"],$dir."/".$arrayimage['name']);
                echo "<br> Stored in: " .$dir ."/ Folder <br>";

            }
        }
    } 
    //if file not match with extension
    else 
    {
        echo "Invalid file";
    }
}
//function imageUpload ends here
}

//imageFunctions class ends here

you can try this code for inserting multiple images with its extension this function is created for checking image files you can replace the extension list for perticular files in the code

How to add Action bar options menu in Android Fragments

in AndroidManifest.xml set theme holo like this:

<activity
android:name="your Fragment or activity"
android:label="@string/xxxxxx"
android:theme="@android:style/Theme.Holo" >

Scaling an image to fit on canvas

Provide the source image (img) size as the first rectangle:

ctx.drawImage(img, 0, 0, img.width,    img.height,     // source rectangle
                   0, 0, canvas.width, canvas.height); // destination rectangle

The second rectangle will be the destination size (what source rectangle will be scaled to).

Update 2016/6: For aspect ratio and positioning (ala CSS' "cover" method), check out:
Simulation background-size: cover in canvas

Displaying a vector of strings in C++

Your vector<string> userString has size 0, so the loop is never entered. You could start with a vector of a given size:

vector<string> userString(10);      
string word;        
string sentence;           
for (decltype(userString.size()) i = 0; i < userString.size(); ++i)
{
    cin >> word;
    userString[i] = word;
    sentence += userString[i] + " ";
}

although it is not clear why you need the vector at all:

string word;        
string sentence;           
for (int i = 0; i < 10; ++i)
{
    cin >> word;
    sentence += word + " ";
}

If you don't want to have a fixed limit on the number of input words, you can use std::getline in a while loop, checking against a certain input, e.g. "q":

while (std::getline(std::cin, word) && word != "q")
{
    sentence += word + " ";
}

This will add words to sentence until you type "q".

Index of duplicates items in a python list

In a single line with pandas 1.2.2 and numpy:

 import numpy as np
 import pandas as pd
 
 idx = np.where(pd.DataFrame(List).duplicated(keep=False))

The argument keep=False will mark every duplicate as True and np.where() will return an array with the indices where the element in the array was True.

In SQL, is UPDATE always faster than DELETE+INSERT?

Keep in mind the actual fragmentation that occurs when DELETE+INSERT is issued opposed to a correctly implemented UPDATE will make great difference by time.

Thats why, for instance, REPLACE INTO that MySQL implements is discouraged as opposed to using the INSERT INTO ... ON DUPLICATE KEY UPDATE ... syntax.

Unable to Git-push master to Github - 'origin' does not appear to be a git repository / permission denied

I had this problem and tried various solutions to solve it including many of those listed above (config file, debug ssh etc). In the end, I resolved it by including the -u switch in the git push, per the github instructions when creating a new repository onsite - Github new Repository