Programs & Examples On #Mib

A MIB is an acronym for Management Information Base in use with the SNMP Protocol.

How to assign more memory to docker container

That 2GB limit you see is the total memory of the VM in which docker runs.

If you are using docker-for-windows or docker-for-mac you can easily increase it from the Whale icon in the task bar, then go to Preferences -> Advanced:

Docker Preferences

But if you are using VirtualBox behind, open VirtualBox, Select and configure the docker-machine assigned memory.

See this for Mac:

https://docs.docker.com/docker-for-mac/#memory

MEMORY By default, Docker for Mac is set to use 2 GB runtime memory, allocated from the total available memory on your Mac. You can increase the RAM on the app to get faster performance by setting this number higher (for example to 3) or lower (to 1) if you want Docker for Mac to use less memory.

For Windows:

https://docs.docker.com/docker-for-windows/#advanced

Memory - Change the amount of memory the Docker for Windows Linux VM uses

NVIDIA-SMI has failed because it couldn't communicate with the NVIDIA driver

One important fact about NVIDIA drivers that is not very well known is that its built is done by DKMS. This allows automatic rebuild in case of kernel upgrade, this happens on system startup. Because of that, it's quite easy to miss error messages, especially if you're working on cloud VM, or server without an additional IPMI/management interface. However, it's possible to trigger DKMS build just executing dkms autoinstall right after packages installation. If this fails then you'll have a meaningful error message about missing dependency or what so ever. If dkms autoinstall builds modules correctly you can simply load it by modprobe - there is no need to reboot the system (which is often used as a way to trigger DKMS rebuild). You can check an example here

How to define and use function inside Jenkins Pipeline config?

Solved! The call build job: project, parameters: params fails with an error java.lang.UnsupportedOperationException: must specify $class with an implementation of interface java.util.List when params = [:]. Replacing it with params = null solved the issue. Here the working code below.

def doCopyMibArtefactsHere(projectName) {
    step ([
        $class: 'CopyArtifact',
        projectName: projectName,
        filter: '**/**.mib',
        fingerprintArtifacts: true, 
        flatten: true
    ]);
}

def BuildAndCopyMibsHere(projectName, params = null) {
    build job: project, parameters: params
    doCopyMibArtefactsHere(projectName)
}
node { 
    stage('Prepare Mib'){
        BuildAndCopyMibsHere('project1')
    }
}

How to add fonts to create-react-app based projects?

  1. Go to Google Fonts https://fonts.google.com/
  2. Select your font as depicted in image below:

enter image description here

  1. Copy and then paste that url in new tab you will get the css code to add that font. In this case if you go to

https://fonts.googleapis.com/css?family=Spicy+Rice

It will open like this:

enter image description here

4, Copy and paste that code in your style.css and simply start using that font like this:

      <Typography
          variant="h1"
          gutterBottom
          style={{ fontFamily: "Spicy Rice", color: "pink" }}
        >
          React Rock
        </Typography>

Result:

enter image description here

Docker: unable to prepare context: unable to evaluate symlinks in Dockerfile path: GetFileAttributesEx

I erroneously created Dockerfile.txt in my working directory leading to the above-mentioned error while build

The fix was to remove the .txt extension from the file.

The file name should be Dockerfile only without any extension.

ffprobe or avprobe not found. Please install one

Compiling the last answers into one:

If you're on Windows, use chocolatey:

choco install ffmpeg

If you are on Mac, use Brew:

brew install ffmpeg

If you are on a Debian Linux distribution, use apt:

sudo apt-get install ffmpeg

And make sure Youtube-dl is updated:

youtube-dl -U

resize2fs: Bad magic number in super-block while trying to open

To resize the existing volume mounted

sudo mount -t xfs /dev/sdf /opt/data/

mount: /opt/data: /dev/nvme1n1 already mounted on /opt/data.

sudo xfs_growfs /opt/data/

Saving binary data as file using JavaScript from a browser

This is possible if the browser supports the download property in anchor elements.

var sampleBytes = new Int8Array(4096);

var saveByteArray = (function () {
    var a = document.createElement("a");
    document.body.appendChild(a);
    a.style = "display: none";
    return function (data, name) {
        var blob = new Blob(data, {type: "octet/stream"}),
            url = window.URL.createObjectURL(blob);
        a.href = url;
        a.download = name;
        a.click();
        window.URL.revokeObjectURL(url);
    };
}());

saveByteArray([sampleBytes], 'example.txt');


JSFiddle: http://jsfiddle.net/VB59f/2

Linux bash script to extract IP address

If You want to use only sed to extract IP address:

ifconfig eth0 2>/dev/null sed -n 's/.*[[:space:]]\([[:digit:]][[:digit:]]*\.[[:digit:]][[:digit:]]*\.[[:digit:]][[:digit:]]*\.[[:digit:]][[:digit:]]*\).*/\1/p'

fatal: early EOF fatal: index-pack failed

I was getting the same error, on my side i resolved by running this command, In windows it has some memory issue.

git config --global pack.windowsMemory 256m

New xampp security concept: Access Forbidden Error 403 - Windows 7 - phpMyAdmin

I tried everything but nothing worked. So I just used : chmod -R 777 to htdocs. At least it's only in my local.

Create a remote branch on GitHub

Git is supposed to understand what files already exist on the server, unless you somehow made a huge difference to your tree and the new changes need to be sent.

To create a new branch with a copy of your current state

git checkout -b new_branch #< create a new local branch with a copy of your code
git push origin new_branch #< pushes to the server

Can you please describe the steps you did to understand what might have made your repository need to send that much to the server.

Programmatically Creating UILabel

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 30, 300, 50)];
label.backgroundColor = [UIColor clearColor];
label.textAlignment = NSTextAlignmentCenter;
label.textColor = [UIColor whiteColor];
label.numberOfLines = 0;
label.lineBreakMode = UILineBreakModeWordWrap;
label.text = @"Your Text";
[self.view addSubview:label];

Why emulator is very slow in Android Studio?

Use x86 images and download "Intel Hardware Accelerated Execution Manager" from the sdk manager.

See here how to enable it: http://developer.android.com/tools/devices/emulator.html#accel-vm

Your emulator will be super fast!

jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class

The servlet API .jar file must not be embedded inside the webapp since, obviously, the container already has these classes in its classpath: it implements the interfaces contained in this jar.

The dependency should be in the provided scope, rather than the default compile scope, in your Maven pom:

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>
</dependency>

Git, fatal: The remote end hung up unexpectedly

This looks similar to How do I get github to default to ssh and not https for new repositories. Probably it's worth trying to switch from http protocol to ssh:

$ git remote add origin [email protected]:username/project.git

failed to push some refs to [email protected]

I had same problem, and I resolved it by doing this: heroku config:set DISABLE_COLLECTSTATIC=1 It was a django project on python 3.7

remote rejected master -> master (pre-receive hook declined)

I was facing the same problem.

[remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to ""

Cause of Error :
I was in develop branch and trying to push to remote master branch

Solution:
Checkout to develop branch(another branch) and execute :

git push heroku develop 

fatal: does not appear to be a git repository

It is most likely that you got your repo's SSH URL wrong.

To confirm, go to your repository on Github and click the clone or download button. Then click the use SSH link.

ssh link

Now copy your official repo's SSH link. Mine looked like this - [email protected]:borenho/que-ay.git

You can now do git remote add origin [email protected]:borenho/que-ay.git if you didn't have origin yet.

If you had set origin before, change it by using git remote set-url origin [email protected]:borenho/que-ay.git

Now push with git push -u origin master

TypeError: 'module' object is not callable

I know this thread is a year old, but the real problem is in your working directory.

I believe that the working directory is C:\Users\Administrator\Documents\Mibot\oops\. Please check for the file named socket.py in this directory. Once you find it, rename or move it. When you import socket, socket.py from the current directory is used instead of the socket.py from Python's directory. Hope this helped. :)

Note: Never use the file names from Python's directory to save your program's file name; it will conflict with your program(s).

Git fails when pushing commit to github

If this command not help

git config http.postBuffer 524288000

Try to change ssh method to https

git remote -v
git remote rm origin 
git remote add origin https://github.com/username/project.git

Convert pem key to ssh-rsa format

ssh-keygen -i -m PKCS8 -f public-key.pem

C - The %x format specifier

The format string attack on printf you mentioned isn't specific to the "%x" formatting - in any case where printf has more formatting parameters than passed variables, it will read values from the stack that do not belong to it. You will get the same issue with %d for example. %x is useful when you want to see those values as hex.

As explained in previous answers, %08x will produce a 8 digits hex number, padded by preceding zeros.

Using the formatting in your code example in printf, with no additional parameters:

printf ("%08x %08x %08x %08x");

Will fetch 4 parameters from the stack and display them as 8-digits padded hex numbers.

How can I remove jenkins completely from linux

if you are ubuntu user than try this:

sudo apt-get remove jenkins
sudo apt-get remove --auto-remove jenkins

'apt-get remove' command is use to remove package.

AppSettings get value from .config file

See I did what I thought was the obvious thing was:

string filePath = ConfigurationManager.AppSettings.GetValues("ClientsFilePath").ToString();

While that compiles it always returns null.

This however (from above) works:

string filePath = ConfigurationManager.AppSettings["ClientsFilePath"];

Sorting arrays in NumPy by column

I suppose this works: a[a[:,1].argsort()]

This indicates the second column of a and sort it based on it accordingly.

Best way to handle list.index(might-not-exist) in python?

I don't know why you should think it is dirty... because of the exception? if you want a oneliner, here it is:

thing_index = thing_list.index(elem) if thing_list.count(elem) else -1

but i would advise against using it; I think Ross Rogers solution is the best, use an object to encapsulate your desiderd behaviour, don't try pushing the language to its limits at the cost of readability.

Android: Scale a Drawable or background image?

The Below code make the bitmap perfectly with same size of the imageview. Get the bitmap image height and width and then calculate the new height and width with the help of imageview's parameters. That give you required image with best aspect ratio.

int bwidth=bitMap1.getWidth();
int bheight=bitMap1.getHeight();
int swidth=imageView_location.getWidth();
int sheight=imageView_location.getHeight();
new_width=swidth;
new_height = (int) Math.floor((double) bheight *( (double) new_width / (double) bwidth));
Bitmap newbitMap = Bitmap.createScaledBitmap(bitMap1,new_width,new_height, true);
imageView_location.setImageBitmap(newbitMap)

kill a process in bash

Please check "top" command then if your script or any are running please note 'PID'

PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
 1384 root      20   0  514m  32m 2188 S  0.3  5.4  55:09.88 example
14490 root      20   0 15140 1216  920 R  0.3  0.2   0:00.02 example2



kill <you process ID>

Example : kill 1384

Replace text inside td using jQuery having td containing other elements

Remove the textnode, and replace the <b> tag with whatever you need without ever touching the inputs :

$('#demoTable').find('tr > td').contents().filter(function() {
    return this.nodeType===3;
}).remove().end().end()
  .find('b').replaceWith($('<span />', {text: 'Hello Kitty'}));

FIDDLE

Best way to store date/time in mongodb

The best way is to store native JavaScript Date objects, which map onto BSON native Date objects.

> db.test.insert({date: ISODate()})
> db.test.insert({date: new Date()})
> db.test.find()
{ "_id" : ObjectId("..."), "date" : ISODate("2014-02-10T10:50:42.389Z") }
{ "_id" : ObjectId("..."), "date" : ISODate("2014-02-10T10:50:57.240Z") }

The native type supports a whole range of useful methods out of the box, which you can use in your map-reduce jobs, for example.

If you need to, you can easily convert Date objects to and from Unix timestamps1), using the getTime() method and Date(milliseconds) constructor, respectively.

1) Strictly speaking, the Unix timestamp is measured in seconds. The JavaScript Date object measures in milliseconds since the Unix epoch.

vba listbox multicolumn add

Simplified example (with counter):

With Me.lstbox
    .ColumnCount = 2
    .ColumnWidths = "60;60"
    .AddItem
    .List(i, 0) = Company_ID
    .List(i, 1) = Company_name 
    i = i + 1

end with

Make sure to start the counter with 0, not 1 to fill up a listbox.

An unhandled exception occurred during the execution of the current web request. ASP.NET

I had the same problem and found out that I had forgotten to include the script in the file which I want to include in the live site.

Also, you should try this:

bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));

How do I split a string with multiple separators in JavaScript?

I use regexp:

str =  'Write a program that extracts from a given text all palindromes, e.g. "ABBA", "lamal", "exe".';

var strNew = str.match(/\w+/g);

// Output: ["Write", "a", "program", "that", "extracts", "from", "a", "given", "text", "all", "palindromes", "e", "g", "ABBA", "lamal", "exe"]

mvn clean install vs. deploy vs. release

  • mvn install will put your packaged maven project into the local repository, for local application using your project as a dependency.
  • mvn release will basically put your current code in a tag on your SCM, change your version in your projects.
  • mvn deploy will put your packaged maven project into a remote repository for sharing with other developers.

Resources :

Are the PUT, DELETE, HEAD, etc methods available in most web browsers?

HTML forms support GET and POST. (HTML5 at one point added PUT/DELETE, but those were dropped.)

XMLHttpRequest supports every method, including CHICKEN, though some method names are matched against case-insensitively (methods are case-sensitive per HTTP) and some method names are not supported at all for security reasons (e.g. CONNECT).

Browsers are slowly converging on the rules specified by XMLHttpRequest, but as the other comment pointed out there are still some differences.

C Linking Error: undefined reference to 'main'

You are overwriting your object file runexp.o by running this command :

 gcc -o runexp.o scd.o data_proc.o -lm -fopenmp

In fact, the -o is for the output file. You need to run :

gcc -o runexp.out runexp.o scd.o data_proc.o -lm -fopenmp

runexp.out will be you binary file.

How do I list all remote branches in Git 1.7+?

Make sure that the remote origin you are listing is really the repository that you want and not an older clone.

How organize uploaded media in WP?

Check this plugin WP Media Folder at Joomunited, you can:

  • Create visual folders and move file inside
  • Restrict file visualisation
  • Create galleries from folders
  • ...

Since the last months they add a lot of must use features.

This is a paid plugin but it worth the money, I install it now by default on all my customers websites.

UILabel text margin

Instead of UILabel perhaps use https://github.com/mattt/TTTAttributedLabel

BITAttributedLabel *label = [BITAttributedLabel new];
label.font = font;
label.text = @"hello";
label.textInsets = UIEdgeInsetsMake(10, 10, 10, 10);
[label sizeToFit];

Find multiple files and rename them in Linux

Scipt above can be written in one line:

find /tmp -name "*.txt" -exec bash -c 'mv $0 $(echo "$0" | sed -r \"s|.txt|.cpp|g\")' '{}' \;

Angular2 Material Dialog css, dialog size

You can inspect the dialog element with dev tools and see what classes are applied on mdDialog.

For example, .md-dialog-container is the main classe of the MDDialog and has padding: 24px

you can create a custom CSS to overwrite whatever you want

.md-dialog-container {
      background-color: #000;
      width: 250px;
      height: 250px
}

In my opinion this is not a good option and probably goes against Material guide but since it doesn't have all features it has in it's previous version, you should do what you think is best for you.

How to convert between bytes and strings in Python 3?

In python3, there is a bytes() method that is in the same format as encode().

str1 = b'hello world'
str2 = bytes("hello world", encoding="UTF-8")
print(str1 == str2) # Returns True

I didn't read anything about this in the docs, but perhaps I wasn't looking in the right place. This way you can explicitly turn strings into byte streams and have it more readable than using encode and decode, and without having to prefex b in front of quotes.

How do I launch a program from command line without opening a new cmd window?

1-Open you folder that contains your application in the File Explorer. 2-Press SHIFT and Right Click in White Space. 3-Click on "Open command window here". 4-Run your application. (you can type some of the first characters of application name and press Up Arrow Key OR Down Arrow Key)

List and kill at jobs on UNIX

To delete a job which has not yet run, you need the atrm command. You can use atq command to get its number in the at list.

To kill a job which has already started to run, you'll need to grep for it using:

ps -eaf | grep <command name>

and then use kill to stop it.

A quicker way to do this on most systems is:

pkill <command name>

How to search for a string in an arraylist

import java.util.*;
class ArrayLst
{
    public static void main(String args[])
    {
        ArrayList<String> ar = new ArrayList<String>();
        ar.add("pulak");
        ar.add("sangeeta");
        ar.add("sumit");
System.out.println("Enter the name:");
Scanner scan=new Scanner(System.in);
String st=scan.nextLine();
for(String lst: ar)
{
if(st.contains(lst))
{
System.out.println(st+"is here!");
break;
}
else
{
System.out.println("OOps search can't find!");
break;
}
}
}
}

Comparing strings in C# with OR in an if statement

Since you want to check whether textboxes contains any value or not your code should do the job. You should be more specific about the error you are having. You can also do:

if(textBox1.Text == string.Empty || textBox2.Text == string.Empty)
   {
    MessageBox.Show("You must enter a value into both boxes");
   }

EDIT 2: based on @JonSkeet comments:

Usage of string.Compare is not required as per OP's original unedited post. String.Equals should do the job if one wants to compare strings, and StringComparison may be used to ignore case for the comparison. string.Compare should be used for order comparison. Originally the question contain this comparison,

string testString = "This is a test";
string testString2 = "This is not a test";

if (testString == testString2)
{
    //do some stuff;
}

the if statement can be replaced with

if(testString.Equals(testString2))

or following to ignore case.

if(testString.Equals(testString2,StringComparison.InvariantCultureIgnoreCase)) 

login failed for user 'sa'. The user is not associated with a trusted SQL Server connection. (Microsoft SQL Server, Error: 18452) in sql 2008

  1. First make sure sa is enabled
  2. Change the authontication mode to mixed mode (Window and SQL authentication)
  3. Stop your SQL Server
  4. Restart your SQL Server

Can an XSLT insert the current date?

format-date(current-date(), '[M01]/[D01]/[Y0001]') = 09/19/2013
format-time(current-time(), '[H01]:[m01] [z]') = 09:26 GMT+10
format-dateTime(current-dateTime(), '[h1]:[m01] [P] on [MNn] [D].') = 9:26 a.m. on September 19.

reference: Formatting Dates and Times using XSLT 2.0 and XPath

Simplest PHP example for retrieving user_timeline with Twitter API version 1.1

From their signature generator, you can generate curl commands of the form:

curl --get 'https://api.twitter.com/1.1/statuses/user_timeline.json' --data 'count=2&screen_name=twitterapi' --header 'Authorization: OAuth oauth_consumer_key="YOUR_KEY", oauth_nonce="YOUR_NONCE", oauth_signature="YOUR-SIG", oauth_signature_method="HMAC-SHA1", oauth_timestamp="TIMESTAMP", oauth_token="YOUR-TOKEN", oauth_version="1.0"' --verbose

Getting path relative to the current working directory?

If you don't mind the slashes being switched, you could [ab]use Uri:

Uri file = new Uri(@"c:\foo\bar\blop\blap.txt");
// Must end in a slash to indicate folder
Uri folder = new Uri(@"c:\foo\bar\");
string relativePath = 
Uri.UnescapeDataString(
    folder.MakeRelativeUri(file)
        .ToString()
        .Replace('/', Path.DirectorySeparatorChar)
    );

As a function/method:

string GetRelativePath(string filespec, string folder)
{
    Uri pathUri = new Uri(filespec);
    // Folders must end in a slash
    if (!folder.EndsWith(Path.DirectorySeparatorChar.ToString()))
    {
        folder += Path.DirectorySeparatorChar;
    }
    Uri folderUri = new Uri(folder);
    return Uri.UnescapeDataString(folderUri.MakeRelativeUri(pathUri).ToString().Replace('/', Path.DirectorySeparatorChar));
}

Multiple left joins on multiple tables in one query

The JOIN statements are also part of the FROM clause, more formally a join_type is used to combine two from_item's into one from_item, multiple one of which can then form a comma-separated list after the FROM. See http://www.postgresql.org/docs/9.1/static/sql-select.html .

So the direct solution to your problem is:

SELECT something
FROM
    master as parent LEFT JOIN second as parentdata
        ON parent.secondary_id = parentdata.id,
    master as child LEFT JOIN second as childdata
        ON child.secondary_id = childdata.id
WHERE parent.id = child.parent_id AND parent.parent_id = 'rootID'

A better option would be to only use JOIN's, as it has already been suggested.

Can I scale a div's height proportionally to its width using CSS?

You can use the view width to set the height. 100 vw is 100% of the width. height: 60vw; would make the height 60% of the width.

Compare two dates with JavaScript

Comparing dates in JavaScript is quite easy... JavaScript has built-in comparison system for dates which makes it so easy to do the comparison...

Just follow these steps for comparing 2 dates value, for example you have 2 inputs which each has a Date value in String and you to compare them...

1. you have 2 string values you get from an input and you'd like to compare them, they are as below:

var date1 = '01/12/2018';
var date2 = '12/12/2018';

2. They need to be Date Object to be compared as date values, so simply convert them to date, using new Date(), I just re-assign them for simplicity of explanation, but you can do it anyway you like:

date1 = new Date(date1);
date2 = new Date(date2);

3. Now simply compare them, using the > < >= <=

date1 > date2;  //false
date1 < date2;  //true
date1 >= date2; //false
date1 <= date2; //true

compare dates in javascript

How to export and import environment variables in windows?

Combine @vincsilver and @jdigital's answers with some modifications,

  1. export .reg to current directory
  2. add date mark

code:

set TODAY=%DATE:~0,4%-%DATE:~5,2%-%DATE:~8,2%

regedit /e "%CD%\user_env_variables[%TODAY%].reg" "HKEY_CURRENT_USER\Environment"
regedit /e "%CD%\global_env_variables[%TODAY%].reg" "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"

Output would like:

global_env_variables[2017-02-14].reg
user_env_variables[2017-02-14].reg

Custom fonts and XML layouts (Android)

Extend TextView and give it a custom attribute or just use the android:tag attribute to pass in a String of what font you want to use. You will need to pick a convention and stick to it such as I will put all of my fonts in the res/assets/fonts/ folder so your TextView class knows where to find them. Then in your constructor you just set the font manually after the super call.

Why is using "for...in" for array iteration a bad idea?

for...in is useful when working on an object in JavaScript, but not for an Array, but still we can not say it's a wrong way, but it's not recommended, look at this example below using for...in loop:

let txt = "";
const person = {fname:"Alireza", lname:"Dezfoolian", age:35}; 
for (const x in person) {
    txt += person[x] + " ";
}
console.log(txt); //Alireza Dezfoolian 35 

OK, let's do it with Array now:

let txt = "";
const person = ["Alireza", "Dezfoolian", 35]; 
for (const x in person) {
   txt += person[x] + " ";
}
console.log(txt); //Alireza Dezfoolian 35 

As you see the result the same...

But let's try something, let's prototype something to Array...

Array.prototype.someoneelse = "someoneelse";

Now we create a new Array();

let txt = "";
const arr = new Array();
arr[0] = 'Alireza';
arr[1] = 'Dezfoolian';
arr[2] = 35;
for(x in arr) {
 txt += arr[x] + " ";
}
console.log(txt); //Alireza Dezfoolian 35 someoneelse

You see the someoneelse!!!... We actually looping through new Array object in this case!

So that's one of the reasons why we need to use for..in carefully, but it's not always the case...

How to embed a SWF file in an HTML page?

If you are using one of those js libraries to insert Flash, I suggest adding plain object embed tag inside of <noscript/>.

How can I get column names from a table in Oracle?

You can do this:

describe EVENT_LOG

or

desc EVENT_LOG

Note: only applicable if you know the table name and specifically for Oracle.

Converting an OpenCV Image to Black and White

Approach 1

While converting a gray scale image to a binary image, we usually use cv2.threshold() and set a threshold value manually. Sometimes to get a decent result we opt for Otsu's binarization.

I have a small hack I came across while reading some blog posts.

  1. Convert your color (RGB) image to gray scale.
  2. Obtain the median of the gray scale image.
  3. Choose a threshold value either 33% above the median

enter image description here

Why 33%?

This is because 33% works for most of the images/data-set.

You can also work out the same approach by replacing median with the mean.

Approach 2

Another approach would be to take an x number of standard deviations (std) from the mean, either on the positive or negative side; and set a threshold. So it could be one of the following:

  • th1 = mean - (x * std)
  • th2 = mean + (x * std)

Note: Before applying threshold it is advisable to enhance the contrast of the gray scale image locally (See CLAHE).

How to insert newline in string literal?

If I understand the question: Couple "\r\n" to get that new line below in a textbox. My example worked -

   string s1 = comboBox1.Text;     // s1 is the variable assigned to box 1, etc.
   string s2 = comboBox2.Text;

   string both = s1 + "\r\n" + s2;
   textBox1.Text = both;

A typical answer could be s1 s2 in the text box using defined type style.

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

I can't comment on Esben Skov Pedersen's answer directly, but using the following notation for links:

<a href="javascript:window.open('http://www.websiteofyourchoice.com');">Click here</a>

In Internet Explorer, the new browser window appears, but the current window navigates to a page which says "[Object]". To avoid this, simple put a "void(0)" behind the JavaScript function.

Source: https://support.microsoft.com/en-us/kb/257321

Java Webservice Client (Best way)

You can find some resources related to developing web services client using Apache axis2 here.

http://today.java.net/pub/a/today/2006/12/13/invoking-web-services-using-apache-axis2.html

Below posts gives good explanations about developing web services using Apache axis2.

http://www.ibm.com/developerworks/opensource/library/ws-webaxis1/

http://wso2.org/library/136

Python Pandas Error tokenizing data

Most of the useful answers are already mentioned, however I suggest saving the pandas dataframes as parquet file. Parquet files don't have this problem and they are memory efficient at the same time.

How do I make a checkbox required on an ASP.NET form?

Scott's answer will work for classes of checkboxes. If you want individual checkboxes, you have to be a little sneakier. If you're just doing one box, it's better to do it with IDs. This example does it by specific check boxes and doesn't require jQuery. It's also a nice little example of how you can get those pesky control IDs into your Javascript.

The .ascx:

<script type="text/javascript">

    function checkAgreement(source, args)
    {                
        var elem = document.getElementById('<%= chkAgree.ClientID %>');
        if (elem.checked)
        {
            args.IsValid = true;
        }
        else
        {        
            args.IsValid = false;
        }
    }

    function checkAge(source, args)
    {
        var elem = document.getElementById('<%= chkAge.ClientID %>');
        if (elem.checked)
        {
            args.IsValid = true;
        }
        else
        {
            args.IsValid = false;
        }    
    }

</script>

<asp:CheckBox ID="chkAgree" runat="server" />
<asp:Label AssociatedControlID="chkAgree" runat="server">I agree to the</asp:Label>
<asp:HyperLink ID="lnkTerms" runat="server">Terms & Conditions</asp:HyperLink>
<asp:Label AssociatedControlID="chkAgree" runat="server">.</asp:Label>
<br />

<asp:CustomValidator ID="chkAgreeValidator" runat="server" Display="Dynamic"
    ClientValidationFunction="checkAgreement">
    You must agree to the terms and conditions.
    </asp:CustomValidator>

<asp:CheckBox ID="chkAge" runat="server" />
<asp:Label AssociatedControlID="chkAge" runat="server">I certify that I am at least 18 years of age.</asp:Label>        
<asp:CustomValidator ID="chkAgeValidator" runat="server" Display="Dynamic"
    ClientValidationFunction="checkAge">
    You must be 18 years or older to continue.
    </asp:CustomValidator>

And the codebehind:

Protected Sub chkAgreeValidator_ServerValidate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ServerValidateEventArgs) _
Handles chkAgreeValidator.ServerValidate
    e.IsValid = chkAgree.Checked
End Sub

Protected Sub chkAgeValidator_ServerValidate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ServerValidateEventArgs) _
Handles chkAgeValidator.ServerValidate
    e.IsValid = chkAge.Checked
End Sub

Run function from the command line

I had a requirement of using various python utilities (range, string, etc.) on the command line and had written the tool pyfunc specifically for that. You can use it to enrich you command line usage experience:

 $ pyfunc -m range -a 1 7 2
 1
 3
 5

 $ pyfunc -m string.upper -a test
 TEST

 $ pyfunc -m string.replace -a 'analyze what' 'what' 'this'
 analyze this

Convert a numpy.ndarray to string(or bytes) and convert it back to numpy.ndarray

You can use the fromstring() method for this:

arr = np.array([1, 2, 3, 4, 5, 6])
ts = arr.tostring()
print(np.fromstring(ts, dtype=int))

>>> [1 2 3 4 5 6]

Sorry for the short answer, not enough points for commenting. Remember to state the data types or you'll end up in a world of pain.

Note on fromstring from numpy 1.14 onwards:

sep : str, optional

The string separating numbers in the data; extra whitespace between elements is also ignored.

Deprecated since version 1.14: Passing sep='', the default, is deprecated since it will trigger the deprecated binary mode of this function. This mode interprets string as binary bytes, rather than ASCII text with decimal numbers, an operation which is better spelt frombuffer(string, dtype, count). If string contains unicode text, the binary mode of fromstring will first encode it into bytes using either utf-8 (python 3) or the default encoding (python 2), neither of which produce sane results.

Margin between items in recycler view Android

change in Recycler view match_parent to wrap_content:

<android.support.v7.widget.RecyclerView
    android:id="@+id/recycleView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

Also change in item layout xml

Make parent layout height match_parent to wrap_content

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
    />

C# guid and SQL uniqueidentifier

Here's a code snippet showing how to insert a GUID using a parameterised query:

    using(SqlConnection conn = new SqlConnection(connectionString))
    {
        conn.Open();
        using(SqlTransaction trans = conn.BeginTransaction())
        using (SqlCommand cmd = conn.CreateCommand())
        {
            cmd.Transaction = trans;
            cmd.CommandText = @"INSERT INTO [MYTABLE] ([GuidValue]) VALUE @guidValue;";
            cmd.Parameters.AddWithValue("@guidValue", Guid.NewGuid());
            cmd.ExecuteNonQuery();
            trans.Commit();
        }
    }

Get Current Session Value in JavaScript?

Accessing & Assigning the Session Variable using Javascript:

Assigning the ASP.NET Session Variable using Javascript:

 <script type="text/javascript">
function SetUserName()
{
    var userName = "Shekhar Shete";
    '<%Session["UserName"] = "' + userName + '"; %>';
     alert('<%=Session["UserName"] %>');
}
</script>

Accessing ASP.NET Session variable using Javascript:

<script type="text/javascript">
    function GetUserName()
    {

        var username = '<%= Session["UserName"] %>';
        alert(username );
    }
</script>

Already Answered here

How to get the Power of some Integer in Swift language?

In Swift 5:

extension Int{
    func expo(_ power: Int) -> Int {
        var result = 1
        var powerNum = power
        var tempExpo = self
        while (powerNum != 0){
        if (powerNum%2 == 1){
            result *= tempExpo
        }
        powerNum /= 2
        tempExpo *= tempExpo
        }
        return result
    }
}

Use like this

2.expo(5) // pow(2, 5)

Thanks to @Paul Buis's answer.

JSON: why are forward slashes escaped?

JSON doesn't require you to do that, it allows you to do that. It also allows you to use "\u0061" for "A", but it's not required. Allowing \/ helps when embedding JSON in a <script> tag, which doesn't allow </ inside strings, like Seb points out.

Some of Microsoft's ASP.NET Ajax/JSON API's use this loophole to add extra information, e.g., a datetime will be sent as "\/Date(milliseconds)\/". (Yuck)

How can I parse String to Int in an Angular expression?

You can use javascript Number method to parse it to an number,

var num=Number (num_str);

Console.WriteLine does not show up in Output window

Using Console.WriteLine( "Test" ); is able to write log messages to the Output Window (View Menu --> Output) in Visual Studio for a Windows Forms/WPF project.

However, I encountered a case where it was not working and only System.Diagnostics.Debug.WriteLine( "Test" ); was working. I restarted Visual Studio and Console.WriteLine() started working again. Seems to be a Visual Studio bug.

How to use group by with union in t-sql

Identifying the column is easy:

SELECT  *
FROM    ( SELECT    id,
                    time
          FROM      dbo.a
          UNION
          SELECT    id,
                    time
          FROM      dbo.b
        )
GROUP BY id

But it doesn't solve the main problem of this query: what's to be done with the second column values upon grouping by the first? Since (peculiarly!) you're using UNION rather than UNION ALL, you won't have entirely duplicated rows between the two subtables in the union, but you may still very well have several values of time for one value of the id, and you give no hint of what you want to do - min, max, avg, sum, or what?! The SQL engine should give an error because of that (though some such as mysql just pick a random-ish value out of the several, I believe sql-server is better than that).

So, for example, change the first line to SELECT id, MAX(time) or the like!

In Flask, What is request.args and how is it used?

request.args is a MultiDict with the parsed contents of the query string. From the documentation of get method:

get(key, default=None, type=None)

Return the default value if the requested data doesn’t exist. If type is provided and is a callable it should convert the value, return it or raise a ValueError if that is not possible.

IDEA: javac: source release 1.7 requires target release 1.7

I resolved it by setting the field blank:

Settings > Compiler > Java Compiler > Project bytecode version

Than IntelliJ uses the JDK default version.

How can I limit ngFor repeat to some number of items in Angular?

You can directly apply slice() to the variable. StackBlitz Demo

<li *ngFor="let item of list.slice(0, 10);">
   {{item.text}}
</li>

Cannot deserialize instance of object out of START_ARRAY token in Spring Webservice

Taking for granted that the JSON you posted is actually what you are seeing in the browser, then the problem is the JSON itself.

The JSON snippet you have posted is malformed.

You have posted:

[{
        "name" : "shopqwe",
        "mobiles" : [],
        "address" : {
            "town" : "city",
            "street" : "streetqwe",
            "streetNumber" : "59",
            "cordX" : 2.229997,
            "cordY" : 1.002539
        },
        "shoe"[{
                "shoeName" : "addidas",
                "number" : "631744030",
                "producent" : "nike",
                "price" : 999.0,
                "sizes" : [30.0, 35.0, 38.0]
            }]

while the correct JSON would be:

[{
        "name" : "shopqwe",
        "mobiles" : [],
        "address" : {
            "town" : "city",
            "street" : "streetqwe",
            "streetNumber" : "59",
            "cordX" : 2.229997,
            "cordY" : 1.002539
        },
        "shoe" : [{
                "shoeName" : "addidas",
                "number" : "631744030",
                "producent" : "nike",
                "price" : 999.0,
                "sizes" : [30.0, 35.0, 38.0]
            }
        ]
    }
]

An unhandled exception of type 'System.TypeInitializationException' occurred in EntityFramework.dll

Check that right version is referenced in your project. E.g. the dll it is complaining about, could be from an older version and that's why there could be a version mismatch.

How do I create a unique ID in Java?

Unique ID with count information

import java.util.concurrent.atomic.AtomicLong;

public class RandomIdUtils {

    private static AtomicLong atomicCounter = new AtomicLong();

    public static String createId() {

        String currentCounter = String.valueOf(atomicCounter.getAndIncrement());
        String uniqueId = UUID.randomUUID().toString();

        return uniqueId + "-" + currentCounter;
    }
}

Exception : AAPT2 error: check logs for details

I was also getting same error because of using & character directly in layout xml. So, please be careful about using html entities in your project.

How to set specific Java version to Maven

On Linux/Unix, the JAVA_HOME within 'mvn' shell script is overridden by the settings in

$HOME/.mavenrc

please Where to add JAVA_HOME and MAVEN path variables in linux

Get bitcoin historical data

In case, you would like to collect bitstamp trade data form their websocket in higher resolution over longer time period you could use script log_bitstamp_trades.py below.

The script uses python websocket-client and pusher_client_python libraries, so install them.

#!/usr/bin/python

import pusherclient
import time
import logging
import sys
import datetime
import signal
import os

logging.basicConfig()
log_file_fd = None

def sigint_and_sigterm_handler(signal, frame):
    global log_file_fd
    log_file_fd.close()
    sys.exit(0)


class BitstampLogger:

    def __init__(self, log_file_path, log_file_reload_path, pusher_key, channel, event):
        self.channel = channel
        self.event = event
        self.log_file_fd = open(log_file_path, "a")
        self.log_file_reload_path = log_file_reload_path
        self.pusher = pusherclient.Pusher(pusher_key)
        self.pusher.connection.logger.setLevel(logging.WARNING)
        self.pusher.connection.bind('pusher:connection_established', self.connect_handler)
        self.pusher.connect()

    def callback(self, data):
        utc_timestamp = time.mktime(datetime.datetime.utcnow().timetuple())
        line = str(utc_timestamp) + " " + data + "\n"
        if os.path.exists(self.log_file_reload_path):
            os.remove(self.log_file_reload_path)
            self.log_file_fd.close()
            self.log_file_fd = open(log_file_path, "a")
        self.log_file_fd.write(line)

    def connect_handler(self, data):
        channel = self.pusher.subscribe(self.channel)
        channel.bind(self.event, self.callback)


def main(log_file_path, log_file_reload_path):
    global log_file_fd
    bitstamp_logger = BitstampLogger(
        log_file_path,
        log_file_reload_path,
        "de504dc5763aeef9ff52",
        "live_trades",
        "trade")
    log_file_fd = bitstamp_logger.log_file_fd
    signal.signal(signal.SIGINT, sigint_and_sigterm_handler)
    signal.signal(signal.SIGTERM, sigint_and_sigterm_handler)
    while True:
        time.sleep(1)


if __name__ == '__main__':
    log_file_path = sys.argv[1]
    log_file_reload_path = sys.argv[2]
    main(log_file_path, log_file_reload_path

and logrotate file config

/mnt/data/bitstamp_logs/bitstamp-trade.log
{
    rotate 10000000000
    minsize 10M
    copytruncate
    missingok
    compress
    postrotate
        touch /mnt/data/bitstamp_logs/reload_log > /dev/null
    endscript
}

then you can run it on background

nohup ./log_bitstamp_trades.py /mnt/data/bitstamp_logs/bitstamp-trade.log /mnt/data/bitstamp_logs/reload_log &

How to create and show common dialog (Error, Warning, Confirmation) in JavaFX 2.0?

EDIT: dialog support was added to JavaFX, see https://stackoverflow.com/a/28887273/1054140


There were no common dialog support in a year 2011. You had to write it yourself by creating new Stage():

Stage dialogStage = new Stage();
dialogStage.initModality(Modality.WINDOW_MODAL);

VBox vbox = new VBox(new Text("Hi"), new Button("Ok."));
vbox.setAlignment(Pos.CENTER);
vbox.setPadding(new Insets(15));

dialogStage.setScene(new Scene(vbox));
dialogStage.show();

Show current assembly instruction in GDB

If you want the next few instructions to display automatically while stepping through the program you can use the display command as follows -

display /3i $pc

The above will display 3 instructions whenever a breakpoint is hit or when you single step the program.

More details at the blog entry here.

How to SSH to a VirtualBox guest externally through a host?

The best way to login to a guest Linux VirtualBox VM is port forwarding. By default, you should have one interface already which is using NAT. Then go to the Network settings and click the Port Forwarding button. Add a new Rule. As the rule name, insert "ssh". As "Host port", insert 3022. As "Guest port", insert 22. Everything else of the rule can be left blank.

or from the command line

VBoxManage modifyvm myserver --natpf1 "ssh,tcp,,3022,,22"

where 'myserver' is the name of the created VM. Check the added rules:

VBoxManage showvminfo myserver | grep 'Rule'

That's all! Please be sure you don't forget to install an SSH server in the VM:

sudo apt-get install openssh-server

To SSH into the guest VM, write:

ssh -p 3022 [email protected]

Where user is your username within the VM.

What's onCreate(Bundle savedInstanceState)

onCreate(Bundle savedInstanceState) Function in Android:

  1. When an Activity first call or launched then onCreate(Bundle savedInstanceState) method is responsible to create the activity.

  2. When ever orientation(i.e. from horizontal to vertical or vertical to horizontal) of activity gets changed or when an Activity gets forcefully terminated by any Operating System then savedInstanceState i.e. object of Bundle Class will save the state of an Activity.

  3. After Orientation changed then onCreate(Bundle savedInstanceState) will call and recreate the activity and load all data from savedInstanceState.

  4. Basically Bundle class is used to stored the data of activity whenever above condition occur in app.

  5. onCreate() is not required for apps. But the reason it is used in app is because that method is the best place to put initialization code.

  6. You could also put your initialization code in onStart() or onResume() and when you app will load first, it will work same as in onCreate().

Stored Procedure parameter default value - is this a constant or a variable

It has to be a constant - the value has to be computable at the time that the procedure is created, and that one computation has to provide the value that will always be used.

Look at the definition of sys.all_parameters:

default_value sql_variant If has_default_value is 1, the value of this column is the value of the default for the parameter; otherwise, NULL.

That is, whatever the default for a parameter is, it has to fit in that column.


As Alex K pointed out in the comments, you can just do:

CREATE PROCEDURE [dbo].[problemParam] 
    @StartDate INT = NULL,
    @EndDate INT = NULL
AS  
BEGIN
   SET @StartDate = COALESCE(@StartDate,CONVERT(INT,(CONVERT(CHAR(8),GETDATE()-130,112))))

provided that NULL isn't intended to be a valid value for @StartDate.


As to the blog post you linked to in the comments - that's talking about a very specific context - that, the result of evaluating GETDATE() within the context of a single query is often considered to be constant. I don't know of many people (unlike the blog author) who would consider a separate expression inside a UDF to be part of the same query as the query that calls the UDF.

Type Checking: typeof, GetType, or is?

I prefer is

That said, if you're using is, you're likely not using inheritance properly.

Assume that Person : Entity, and that Animal : Entity. Feed is a virtual method in Entity (to make Neil happy)

class Person
{
  // A Person should be able to Feed
  // another Entity, but they way he feeds
  // each is different
  public override void Feed( Entity e )
  {
    if( e is Person )
    {
      // feed me
    }
    else if( e is Animal )
    {
      // ruff
    }
  }
}

Rather

class Person
{
  public override void Feed( Person p )
  {
    // feed the person
  }
  public override void Feed( Animal a )
  {
    // feed the animal
  }
}

Making a Sass mixin with optional arguments

With [email protected] :

// declare
@mixin button( $bgcolor:blue ){
    background:$bgcolor;
}

and use without value, button will be blue

//use
.my_button{
    @include button();
}

and with value, button will be red

//use
.my_button{
    @include button( red );
}

works with hexa too

Show whitespace characters in Visual Studio Code

I'd like to offer this suggestion as a side note.
If you're looking to fix all the 'trailing whitespaces' warnings your linter throws at you.
You can have VSCode automatically trim whitespaces from an entire file using the keyboard chord.
CTRL+K / X (by default)

I was looking into showing whitespaces because my linter kept bugging me with whitespace warnings. So that's why I'm here.

How to obtain a Thread id in Python?

I saw examples of thread IDs like this:

class myThread(threading.Thread):
    def __init__(self, threadID, name, counter):
        self.threadID = threadID
        ...

The threading module docs lists name attribute as well:

...

A thread has a name. 
The name can be passed to the constructor, 
and read or changed through the name attribute.

...

Thread.name

A string used for identification purposes only. 
It has no semantics. Multiple threads may
be given the same name. The initial name is set by the constructor.

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

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

How to get URL parameter using jQuery or plain JavaScript?

_x000D_
_x000D_
var RequestQuerystring;_x000D_
(window.onpopstate = function () {_x000D_
    var match,_x000D_
        pl = /\+/g,  // Regex for replacing addition symbol with a space_x000D_
        search = /([^&=]+)=?([^&]*)/g,_x000D_
        decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },_x000D_
        query = window.location.search.substring(1);_x000D_
_x000D_
    RequestQuerystring = {};_x000D_
    while (match = search.exec(query))_x000D_
        RequestQuerystring[decode(match[1])] = decode(match[2]);_x000D_
})();
_x000D_
_x000D_
_x000D_

RequestQuerystring is now an object with all you parameters

Useful example of a shutdown hook in Java?

Shutdown Hooks are unstarted threads that are registered with Runtime.addShutdownHook().JVM does not give any guarantee on the order in which shutdown hooks are started.For more info refer http://techno-terminal.blogspot.in/2015/08/shutdown-hooks.html

Get value from SimpleXMLElement Object

you can convert array with this function

function xml2array($xml){
$arr = array();

foreach ($xml->children() as $r)
{
    $t = array();
    if(count($r->children()) == 0)
    {
        $arr[$r->getName()] = strval($r);
    }
    else
    {
        $arr[$r->getName()][] = xml2array($r);
    }
}
return $arr;
}

LIMIT 10..20 in SQL Server

select * from (select id,name,ROW_NUMBER() OVER (ORDER BY id  asc) as row
from tableName1) tbl1
where tbl1.row>=10 and tbl1.row<=15

Will print rows from 10 to 15.

Size of character ('a') in C/C++

In C the type of character literals are int and char in C++. This is in C++ required to support function overloading. See this example:

void foo(char c)
{
    puts("char");
}
void foo(int i)
{
    puts("int");
}
int main()
{
    foo('i');
    return 0;
}

Output:

char

How to use IntelliJ IDEA to find all unused code?

After you've run the Inspect by Name, select all the locations, and make use of the Apply quick fixes to all the problems drop-down, and use either (or both) of Delete unused parameter(s) and Safe Delete.

Don't forget to hit Do Refactor afterwards.

Then you'll need to run another analysis, as the refactored code will no doubt reveal more unused declarations.

Apply quick fixes to all the problems

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'xxx'

Check the Namespace.

You might assign System.Web.Webpages.Html.SelectListItem in the Controller, instead of System.Web.Mvc.SelectListItem.

Get records with max value for each group of grouped SQL results

In Oracle below query can give the desired result.

SELECT group,person,Age,
  ROWNUMBER() OVER (PARTITION BY group ORDER BY age desc ,person asc) as rankForEachGroup
  FROM tablename where rankForEachGroup=1

did you specify the right host or port? error on Kubernetes

I got this issue when using " Bash on Windows " with azure kubernetes

az aks get-credentials -n <myCluster>-g <myResourceGroup>

The config file is autogenerated and placed in '~/.kube/config' file as per OS (which is windows in my case)

To solve this - Run from Bash commandline cp <yourWindowsPathToConfigPrintedFromAbobeCommand> ~/.kube/config

How to stop a vb script running in windows

I can think of at least 2 different ways:

  1. using Task Manager (Ctrl-Shift-Esc), select the process tab, look for a process name cscript.exe or wscript.exe and use End Process.

  2. From the command line you could use taskkill /fi "imagename eq cscript.exe" (change to wscript.exe as needed)

Another way is using scripting and WMI. Here are some hints: look for the Win32_Process class and the Terminate method.

How to capture the android device screen content?

You can try the following library: Android Screenshot Library (ASL) enables to programmatically capture screenshots from Android devices without requirement of having root access privileges. Instead, ASL utilizes a native service running in the background, started via the Android Debug Bridge (ADB) once per device boot.

Mount current directory as a volume in Docker on Windows 10

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

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

$WIN_PATH=Convert-Path .

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

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

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

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

SQL Statement using Where clause with multiple values

SELECT PersonName, songName, status
FROM table
WHERE name IN ('Holly', 'Ryan')

If you are using parametrized Stored procedure:

  1. Pass in comma separated string
  2. Use special function to split comma separated string into table value variable
  3. Use INNER JOIN ON t.PersonName = newTable.PersonName using a table variable which contains passed in names

Tower of Hanoi: Recursive Algorithm

It's simple. Suppose you want to move from A to C

if there's only one disk, just move it.

If there's more than one disk, do

  • move all disks (n-1 disks), except the bottom one from A to B
  • move the bottom disk from A to C
  • move the n-1 disks from the first step from A to C

Keep in mind that, when moving the n-1 disks, the nth won't be a problem at all (once it is bigger than all the others)

Note that moving the n-1 disks recurs on the same problem again, until n-1 = 1, in which case you'll be on the first if (where you should just move it).

Spring Data JPA - "No Property Found for Type" Exception

If you are using a composite key in your bean, your parameter will be an object. You need to adjust your findBy method according to the new combination.

@Embeddable
public class CombinationId implements Serializable {

  private String xId;
  private String yId;
}

public class RealObject implements Serializable, Persistable<CombinationId> {

  @EmbeddedId private CombinationId id;
}

In that case, your repository findBy method should be as this

@Repository
public interface PaymentProfileRepository extends JpaRepository<RealObject, String> {

  List<RealObject> findById_XId(String someString);
}

Convert an integer to an array of digits

It would be much simpler to use the String.split method:

public static void fn(int guess) {
    String[] sNums = Integer.toString(guess).split("");
    for (String s : nums) {
    ...

git push rejected

First, attempt to pull from the same refspec that you are trying to push to.

If this does not work, you can force a git push by using git push -f <repo> <refspec>, but use caution: this method can cause references to be deleted on the remote repository.

How to do a https request with bad certificate?

The correct way to do this if you want to maintain the default transport settings is now (as of Go 1.13):

customTransport := http.DefaultTransport.(*http.Transport).Clone()
customTransport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
client = &http.Client{Transport: customTransport}

Transport.Clone makes a deep copy of the transport. This way you don't have to worry about missing any new fields that get added to the Transport struct over time.

How to preview a part of a large pandas DataFrame, in iPython notebook?

df.head(5) # will print out the first 5 rows
df.tail(5) # will print out the 5 last rows

Get integer value from string in swift

You can bridge from String to NSString and convert from CInt to Int like this:

var myint: Int = Int(stringNumb.bridgeToObjectiveC().intValue)

apt-get for Cygwin?

You can do this using Cygwin’s setup.exe from Windows command line. Example:

cd C:\cygwin64
setup-x86_64 -q -P wget,tar,gawk,bzip2,subversion,vim

For a more convenient installer, you may want to use the apt-cyg package manager. Its syntax is similar to apt-get, which is a plus. For this, follow the above steps and then use Cygwin Bash for the following steps:

wget rawgit.com/transcode-open/apt-cyg/master/apt-cyg
install apt-cyg /bin

Now that apt-cyg is installed. Here are a few examples of installing some packages:

apt-cyg install nano
apt-cyg install git
apt-cyg install ca-certificates

Create a Bitmap/Drawable from file path

Well, using the static Drawable.createFromPath(String pathName) seems a bit more straightforward to me than decoding it yourself... :-)

If your mImg is a simple ImageView, you don't even need it, use mImg.setImageUri(Uri uri) directly.

What does "Content-type: application/json; charset=utf-8" really mean?

Dart http's implementation process the bytes thanks to that "charset=utf-8", so i'm sure several implementations out there supports this, to avoid the "latin-1" fallback charset when reading the bytes from the response. In my case, I totally lose format on the response body string, so I have to do the bytes encoding manually to utf8, or add that header "inner" parameter on my server's API response.

ORA-01830: date format picture ends before converting entire input string / Select sum where date query

What you have written in your sql string is a Timestamp not Date. You must convert it to Date or change type of database field to Timestamp for it to be seen correctly.

React-Router open Link in new tab

We can use the following options:-

 // first option is:-
    <Link to="myRoute" params={myParams} target="_blank">

 // second option is:-
    var href = this.props.history.createHref('myRoute', myParams);
    <a href={href} target="_blank">

 //third option is:-
    var href = '/myRoute/' + myParams.foo + '/' + myParams.bar;
    <a href={href} target="_blank">

We can use either of three option to open in new tab by react routing.

Reverting to a previous revision using TortoiseSVN

In the TortoiseSVN context menu, select 'Update to Revision', enter the desired revision number, and voilà :)

Removing empty rows of a data file in R

I assume you want to remove rows that are all NAs. Then, you can do the following :

data <- rbind(c(1,2,3), c(1, NA, 4), c(4,6,7), c(NA, NA, NA), c(4, 8, NA)) # sample data
data
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    1   NA    4
[3,]    4    6    7
[4,]   NA   NA   NA
[5,]    4    8   NA

data[rowSums(is.na(data)) != ncol(data),]
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    1   NA    4
[3,]    4    6    7
[4,]    4    8   NA

If you want to remove rows that have at least one NA, just change the condition :

data[rowSums(is.na(data)) == 0,]
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    6    7

How do I use LINQ Contains(string[]) instead of Contains(string)

var SelecetdSteps = Context.FFTrakingSubCriticalSteps
             .Where(x => x.MeetingId == meetid)
             .Select(x =>    
         x.StepID  
             );

        var crtiticalsteps = Context.MT_CriticalSteps.Where(x =>x.cropid==FFT.Cropid).Select(x=>new
        {
            StepID= x.crsid,
            x.Name,
            Checked=false

        });


        var quer = from ax in crtiticalsteps
                   where (!SelecetdSteps.Contains(ax.StepID))
                   select ax;

Bootstrap 4 Center Vertical and Horizontal Alignment

been going thru a lot of posts on getting a form centered in the page and none of them worked. code below is from a react component using bootstrap 4.1. height should be 100vh and not 100%

<div className="container">
      <div className="d-flex justify-content-center align-items-center" style={height}>
        <form>
          <div className="form-group">
            <input className="form-control form-control-lg" placeholder="Email" type="email"/>
          </div>
          <div className="form-group">
            <input className="form-control form-control-lg" placeholder="Password" type="password"/>
          </div>
          <div className="form-group">
            <button className="btn btn-info btn-lg btn-block">Sign In</button>
          </div>
        </form>
      </div>
    </div>

where height in style is:

const height = { height: '100vh' }

Bad File Descriptor with Linux Socket write() Bad File Descriptor C

In general, when "Bad File Descriptor" is encountered, it means that the socket file descriptor you passed into the API is not valid, which has multiple possible reasons:

  1. The fd is already closed somewhere.
  2. The fd has a wrong value, which is inconsistent with the value obtained from socket() api

How to get the part of a file after the first line that matches a regular expression?

This could be a one way of doing it. If you know what line of the file you have your grep word and how many lines you have in your file:

grep -A466 'TERMINATE' file

Getting the application's directory from a WPF application

Here is another:

System.Reflection.Assembly.GetExecutingAssembly().Location

How to write logs in text file when using java.util.logging.Logger

int SIZE = "<intialize-here>"
int ROTATIONCOUNT = "<intialize-here>"

Handler handler = new FileHandler("test.log", SIZE, LOG_ROTATIONCOUNT);
logger.addHandler(handler);     // for your code.. 

// you can also set logging levels
Logger.getLogger(this.getClass().getName()).log(Level.[...]).addHandler(handler);

Button background as transparent

use #0000 (only four zeros otherwise it will be considered as black) this is the color code for transparent. You can use it directly but I recommend you to define a color in color.xml so you can enjoy re-usefullness of the code.

Simplest way to read json from a URL in java

Use HttpClient to grab the contents of the URL. And then use the library from json.org to parse the JSON. I've used these two libraries on many projects and they have been robust and simple to use.

Other than that you can try using a Facebook API java library. I don't have any experience in this area, but there is a question on stack overflow related to using a Facebook API in java. You may want to look at RestFB as a good choice for a library to use.

How to serve static files in Flask

All the answers are good but what worked well for me is just using the simple function send_file from Flask. This works well when you just need to send an html file as response when host:port/ApiName will show the output of the file in browser


@app.route('/ApiName')
def ApiFunc():
    try:
        return send_file('some-other-directory-than-root/your-file.extension')
    except Exception as e:
        logging.info(e.args[0])```

what do <form action="#"> and <form method="post" action="#"> do?

action="" will resolve to the page's address. action="#" will resolve to the page's address + #, which will mean an empty fragment identifier.

Doing the latter might prevent a navigation (new load) to the same page and instead try to jump to the element with the id in the fragment identifier. But, since it's empty, it won't jump anywhere.

Usually, authors just put # in href-like attributes when they're not going to use the attribute where they're using scripting instead. In these cases, they could just use action="" (or omit it if validation allows).

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

on php7 run for example:

> sudo apt-get install php-curl
> sudo apt-get install php-mbstring

for every missing extension. Then:

> sudo apt-get update

and finally (in the project's root folder):

> composer install

nodejs send html file to client

you can render the page in express more easily


 var app   = require('express')();    
    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'jade');
 
    app.get('/signup',function(req,res){      
    res.sendFile(path.join(__dirname,'/signup.html'));
    });

so if u request like http://127.0.0.1:8080/signup that it will render signup.html page under views folder.

How do I get the old value of a changed cell in Excel VBA?

You can use an event on the cell change to fire a macro that does the following:

vNew = Range("cellChanged").value
Application.EnableEvents = False
Application.Undo
vOld = Range("cellChanged").value
Range("cellChanged").value = vNew
Application.EnableEvents = True 

How to load all the images from one of my folder into my web page, using Jquery/Javascript

Works both localhost and on live server without issues, and allows you to extend the delimited list of allowed file-extensions:

var folder = "images/";

$.ajax({
    url : folder,
    success: function (data) {
        $(data).find("a").attr("href", function (i, val) {
            if( val.match(/\.(jpe?g|png|gif)$/) ) { 
                $("body").append( "<img src='"+ folder + val +"'>" );
            } 
        });
    }
});

NOTICE

Apache server has Option Indexes turned on by default - if you use another server like i.e. Express for Node you could use this NPM package for the above to work: https://github.com/expressjs/serve-index

If the files you want to get listed are in /images than inside your server.js you could add something like:

const express = require('express');
const app = express();
const path = require('path');

// Allow assets directory listings
const serveIndex = require('serve-index'); 
app.use('/images', serveIndex(path.join(__dirname, '/images')));

Download files in laravel using Response::download

Quite a few of these solutions suggest referencing the public_path() of the Laravel application in order to locate the file. Sometimes you'll want to control access to the file or offer real-time monitoring of the file. In this case, you'll want to keep the directory private and limit access by a method in a controller class. The following method should help with this:

public function show(Request $request, File $file) {

    // Perform validation/authentication/auditing logic on the request

    // Fire off any events or notifiations (if applicable)

    return response()->download(storage_path('app/' . $file->location));
}

There are other paths that you could use as well, described on Laravel's helper functions documentation

Laravel Redirect Back with() Message

In laravel 5.8 you can do the following:

return redirect()->back()->withErrors(['name' => 'The name is required']);

and in blade:

@error('name')
<p>{{ $message }}</p>
@enderror

Adding external resources (CSS/JavaScript/images etc) in JSP

Using Following Code You Solve thisQuestion.... If you run a file using localhost server than this problem solve by following Jsp Page Code.This Code put Between Head Tag in jsp file

<style type="text/css">
    <%@include file="css/style.css" %>
</style>
<script type="text/javascript">
    <%@include file="js/script.js" %>
</script>

Lumen: get URL parameter in a Blade view

The shortest way i have used

{{ Request::get('a') }}

How to make a floated div 100% height of its parent?

For #outer height to be based on its content, and have #inner base its height on that, make both elements absolutely positioned.

More details can be found in the spec for the css height property, but essentially, #inner must ignore #outer height if #outer's height is auto, unless #outer is positioned absolutely. Then #inner height will be 0, unless #inner itself is positioned absolutely.

<style>
    #outer {
        position:absolute; 
        height:auto; width:200px; 
        border: 1px solid red; 
    }
    #inner {
        position:absolute; 
        height:100%; 
        width:20px; 
        border: 1px solid black; 
    }
</style>

<div id='outer'>
    <div id='inner'>
    </div>
    text
</div>

However... By positioning #inner absolutely, a float setting will be ignored, so you will need to choose a width for #inner explicitly, and add padding in #outer to fake the text wrapping I suspect you want. For example, below, the padding of #outer is the width of #inner +3. Conveniently (as the whole point was to get #inner height to 100%) there's no need to wrap text beneath #inner, so this will look just like #inner is floated.

<style>
    #outer2{
        padding-left: 23px;
        position:absolute; 
        height:auto; 
        width:200px; 
        border: 1px solid red; 
    }
    #inner2{
        left:0;
        position:absolute; 
        height:100%; 
        width:20px; 
        border: 1px solid black; 
   }
</style>

<div id='outer2'>
    <div id='inner2'>
    </div>
    text
</div>

I deleted my previous answer, as it was based on too many wrong assumptions about your goal.

How to substitute shell variables in complex text files

I know this topic is old, but I have a simpler working solution without export the variables. Can be a oneliner, but I prefer to split using \ on line end.

var1='myVar1'\
var2=2\
var3=${var1}\
envsubst '$var1,$var3' < "source.txt" > "destination.txt"

#         ^^^^^^^^^^^    ^^^^^^^^^^     ^^^^^^^^^^^^^^^
# define which to replace   input            output

The variables need to be defined to the same line as envsubst is to get considered as environment variables.

The '$var1,$var3' is optional to only replace the specified ones. Imagine an input file containing ${VARIABLE_USED_BY_JENKINS} which should not be replaced.

Does it make sense to use Require.js with Angular.js?

It makes sense to use requirejs with angularjs if you plan on lazy loading controllers and directives etc, while also combining multiple lazy dependencies into single script files for much faster lazy loading. RequireJS has an optimisation tool that makes the combining easy. See http://ify.io/using-requirejs-with-optimisation-for-lazy-loading-angularjs-artefacts/

CSS image overlay with color and transparency

something like this? http://codepen.io/Nunotmp/pen/wKjvB

You can add an empty div and use absolute positioning.

System.BadImageFormatException: Could not load file or assembly (from installutil.exe)

After trying all the mentioned solutions I found the PlatformTarget somehow added to AnyCPU configuration in my project .csproj.

<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
    <PlatformTarget>x64</PlatformTarget>
</PropertyGroup>

Removing the line worked for me.

how to set the query timeout from SQL connection string

Only from code:

_x000D_
_x000D_
namespace xxx.DsXxxTableAdapters {_x000D_
    partial class ZzzTableAdapter_x000D_
    {_x000D_
        public void SetTimeout(int timeout)_x000D_
        {_x000D_
            if (this.Adapter.DeleteCommand != null) { this.Adapter.DeleteCommand.CommandTimeout = timeout; }_x000D_
            if (this.Adapter.InsertCommand != null) { this.Adapter.InsertCommand.CommandTimeout = timeout; }_x000D_
            if (this.Adapter.UpdateCommand != null) { this.Adapter.UpdateCommand.CommandTimeout = timeout; }_x000D_
            if (this._commandCollection == null) { this.InitCommandCollection(); }_x000D_
            if (this._commandCollection != null)_x000D_
            {_x000D_
                foreach (System.Data.SqlClient.SqlCommand item in this._commandCollection)_x000D_
                {_x000D_
                    if (item != null)_x000D_
                    { item.CommandTimeout = timeout; }_x000D_
                }_x000D_
            }_x000D_
        }_x000D_
    }_x000D_
 _x000D_
    //...._x000D_
 _x000D_
 }
_x000D_
_x000D_
_x000D_

Footnotes for tables in LaTeX

\begin{figure}[H]
\centering
{\includegraphics[width=1.0\textwidth]{image}}
\caption{captiontext\protect\footnotemark}
\label{fig:}
\end{figure}
\footnotetext{Footnotetext} 

failed to push some refs to [email protected]

I had similar issue where local build was working fine however when I push my branch onto heroku it would fail to build. Issue was that I had some devDependencies in my package.json which were not installed during npm install which was causing my build to fail.

If you need access to packages declared under devDependencies in a different buildpack or at runtime, then you can set NPM_CONFIG_PRODUCTION=false or YARN_PRODUCTION=false to skip the pruning step.

Also you can move you devDependencies into dependencies...

Floating point comparison functions for C#

Here's how I solved it, with nullable double extension method.

    public static bool NearlyEquals(this double? value1, double? value2, double unimportantDifference = 0.0001)
    {
        if (value1 != value2)
        {
            if(value1 == null || value2 == null)
                return false;

            return Math.Abs(value1.Value - value2.Value) < unimportantDifference;
        }

        return true;
    }

...

        double? value1 = 100;
        value1.NearlyEquals(100.01); // will return false
        value1.NearlyEquals(100.000001); // will return true
        value1.NearlyEquals(100.01, 0.1); // will return true

XAMPP: Couldn't start Apache (Windows 10)

Actually, by default IIS (Microsoft, .NET, etc.) is installed.

  • Go to Control Panel
  • Turn Windows features on or off...
  • Under (IIS) Internet Information Services, uncheck the (WWWS) world wide web services.
  • Click OK.

This could be a permanent solution. :)

Git Push Error: insufficient permission for adding an object to repository database

For my case none of the suggestions worked. I'm on Windows and this worked for me:

  • Copy the remote repo into another folder
  • Share the folder and give appropriate permissions.
  • Make sure you can access the folder from your local machine.
  • Add this repo as another remote repo in your local repo. (git remote add foo //SERVERNAME/path/to/copied/git)
  • Push to foo. git push foo master. Did it worked? Great! Now delete not-working repo and rename this into whatever it was before. Make sure permissions and share property remains the same.

Difference between pre-increment and post-increment in a loop?

Yes, there is. The difference is in the return value. The return value of "++i" will be the value after incrementing i. The return of "i++" will be the value before incrementing. This means that code that looks like the following:

int a = 0;
int b = ++a; // a is incremented and the result after incrementing is saved to b.
int c = a++; // a is incremented again and the result before incremening is saved to c.

Therefore, a would be 2, and b and c would each be 1.

I could rewrite the code like this:

int a = 0; 

// ++a;
a = a + 1; // incrementing first.
b = a; // setting second. 

// a++;
c = a; // setting first. 
a = a + 1; // incrementing second. 

Replace image src location using CSS

you can use: content:url("image.jpg")

<style>
.your-class-name{
    content: url("http://imgur.com/SZ8Cm.jpg");
}
</style>

<img class="your-class-name" src="..."/>

How to exit git log or git diff

In this case, as snarly suggested, typing q is the intended way to quit git log (as with most other pagers or applications that use pagers).

However normally, if you just want to abort a command that is currently executing, you can try ctrl+c (doesn't seem to work for git log, however) or ctrl+z (although in bash, ctrl-z will freeze the currently running foreground process, which can then be thawed as a background process with the bg command).

How to choose the id generation strategy when using JPA and Hibernate

I find this lecture very valuable https://vimeo.com/190275665, in point 3 it summarizes these generators and also gives some performance analysis and guideline one when you use each one.

Python TypeError: not enough arguments for format string

You need to put the format arguments into a tuple (add parentheses):

instr = "'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % (softname, procversion, int(percent), exe, description, company, procurl)

What you currently have is equivalent to the following:

intstr = ("'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % softname), procversion, int(percent), exe, description, company, procurl

Example:

>>> "%s %s" % 'hello', 'world'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string
>>> "%s %s" % ('hello', 'world')
'hello world'

How do I configure php to enable pdo and include mysqli on CentOS?

You might just have to install the packages.

yum install php-pdo php-mysqli

After they're installed, restart Apache.

httpd restart

or

apachectl restart

Is it correct to use alt tag for an anchor link?

You should use the title attribute for anchor tags if you wish to apply descriptive information similarly as you would for an alt attribute. The title attribute is valid on anchor tags and is serves no other purpose than providing information about the linked page.

W3C recommends that the value of the title attribute should match the value of the title of the linked document but it's not mandatory.

http://www.w3.org/MarkUp/1995-archive/Elements/A.html


Alternatively, and likely to be more beneficial, you can use the ARIA accessibility attribute aria-label (not to be confused with aria-labeledby). aria-label serves the same function as the alt attribute does for images but for non-image elements and includes some measure of optimization since your optimizing for screen readers.

http://www.w3.org/WAI/GL/wiki/Using_aria-label_to_provide_labels_for_objects


If you want to describe an anchor tag though, it's usually appropriate to use the rel or rev tag but your limited to specific values, they should not be used for human readable descriptions.

Rel serves to describe the relationship of the linked page to the current page. (e.g. if the linked page is next in a logical series it would be rel=next)

The rev attribute is essentially the reverse relationship of the rel attribute. Rev describes the relationship of the current page to the linked page.

You can find a list of valid values here: http://microformats.org/wiki/existing-rel-values

How can I draw vertical text with CSS cross-browser?

Updated this answer with recent information (from CSS Tricks). Kudos to Matt and Douglas for pointing out the filter implementation.

.rotate {
  -webkit-transform: rotate(-90deg);
  -moz-transform: rotate(-90deg);
  -ms-transform: rotate(-90deg);
  -o-transform: rotate(-90deg);
  transform: rotate(-90deg);

  /* also accepts left, right, top, bottom coordinates; not required, but a good idea for styling */
  -webkit-transform-origin: 50% 50%;
  -moz-transform-origin: 50% 50%;
  -ms-transform-origin: 50% 50%;
  -o-transform-origin: 50% 50%;
  transform-origin: 50% 50%;

  /* Should be unset in IE9+ I think. */
  filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3);
}

Old answer:

For FF 3.5 or Safari/Webkit 3.1, check out: -moz-transform (and -webkit-transform). IE has a Matrix filter(v5.5+), but I'm not certain how to use it. Opera has no transformation capabilities yet.

.rot-neg-90 {
  /* rotate -90 deg, not sure if a negative number is supported so I used 270 */
  -moz-transform: rotate(270deg);
  -moz-transform-origin: 50% 50%;
  -webkit-transform: rotate(270deg);
  -webkit-transform-origin: 50% 50%;
  /* IE support too convoluted for the time I've got on my hands... */
}

How can I find out if an .EXE has Command-Line Options?

The easiest way would be to use use ProcessExplorer but it would still require some searching.

Make sure your exe is running and open ProcessExplorer. In ProcessExplorer find the name of your binary file and double click it to show properties. Click the Strings tab. Search down the list of string found in the binary file. Most strings will be garbage so they can be ignored. Search for anything that might possibly resemble a command line switch. Test this switch from the command line and see if it does anything.

Note that it might be your binary simply has no command line switches.

For reference here is the above steps applied to the Chrome executable. The command line switches accepted by Chrome can be seen in the list:

Process explorer analyzing Chrome.exe

In Git, how do I figure out what my current revision is?

below will work with any previously pushed revision, not only HEAD

for abbreviated revision hash:

git log -1 --pretty=format:%h

for long revision hash:

git log -1 --pretty=format:%H

How to get a substring between two strings in PHP?

I have to add something to the post of Julius Tilvikas. I looked for a solution like this one he described in his post. But i think there is a mistake. I don't get realy the string between two string, i also get more with this solution, because i have to substract the lenght of the start-string. When do this, i realy get the String between two strings.

Here are my changes of his solution:

function get_string_between ($string, $start, $end, $inclusive = false){
    $string = " ".$string;

    if ($start == "") { $ini = 0; }
    else { $ini = strpos($string, $start); }

    if ($end == "") { $len = strlen($string); }
    else { $len = strpos($string, $end, $ini) - $ini - strlen($start);}

    if (!$inclusive) { $ini += strlen($start); }
    else { $len += strlen($end); }

    return substr($string, $ini, $len);
}

Greetz

V

In c# what does 'where T : class' mean?

It's a type constraint on T, specifying that it must be a class.

The where clause can be used to specify other type constraints, e.g.:

where T : struct // T must be a struct
where T : new()  // T must have a default parameterless constructor
where T : IComparable // T must implement the IComparable interface

For more information, check out MSDN's page on the where clause, or generic parameter constraints.

How to print matched regex pattern using awk?

Off topic, this can be done using the grep also, just posting it here in case if anyone is looking for grep solution

echo 'xxx yyy zzze ' | grep -oE 'yyy'

Android Open External Storage directory(sdcard) for storing file

taking @rijul's answer forward, it doesn't work in marshmallow and above versions:

       //for pre-marshmallow versions
       String path = System.getenv("SECONDARY_STORAGE");

       // For Marshmallow, use getExternalCacheDirs() instead of System.getenv("SECONDARY_STORAGE")
       if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
           File[] externalCacheDirs = mContext.getExternalCacheDirs();
           for (File file : externalCacheDirs) {
               if (Environment.isExternalStorageRemovable(file)) {
                   // Path is in format /storage.../Android....
                   // Get everything before /Android
                   path = file.getPath().split("/Android")[0];
                   break;
               }
           }
       }


        // Android avd emulator doesn't support this variable name so using other one
        if ((null == path) || (path.length() == 0))
            path = Environment.getExternalStorageDirectory().getAbsolutePath();

JS - window.history - Delete a state

You may have moved on by now, but... as far as I know there's no way to delete a history entry (or state).

One option I've been looking into is to handle the history yourself in JavaScript and use the window.history object as a carrier of sorts.

Basically, when the page first loads you create your custom history object (we'll go with an array here, but use whatever makes sense for your situation), then do your initial pushState. I would pass your custom history object as the state object, as it may come in handy if you also need to handle users navigating away from your app and coming back later.

var myHistory = [];

function pageLoad() {
    window.history.pushState(myHistory, "<name>", "<url>");

    //Load page data.
}

Now when you navigate, you add to your own history object (or don't - the history is now in your hands!) and use replaceState to keep the browser out of the loop.

function nav_to_details() {
    myHistory.push("page_im_on_now");
    window.history.replaceState(myHistory, "<name>", "<url>");

    //Load page data.
}

When the user navigates backwards, they'll be hitting your "base" state (your state object will be null) and you can handle the navigation according to your custom history object. Afterward, you do another pushState.

function on_popState() {
    // Note that some browsers fire popState on initial load,
    // so you should check your state object and handle things accordingly.
    // (I did not do that in these examples!)

    if (myHistory.length > 0) {
        var pg = myHistory.pop();
        window.history.pushState(myHistory, "<name>", "<url>");

        //Load page data for "pg".
    } else {
        //No "history" - let them exit or keep them in the app.
    }
}

The user will never be able to navigate forward using their browser buttons because they are always on the newest page.

From the browser's perspective, every time they go "back", they've immediately pushed forward again.

From the user's perspective, they're able to navigate backwards through the pages but not forward (basically simulating the smartphone "page stack" model).

From the developer's perspective, you now have a high level of control over how the user navigates through your application, while still allowing them to use the familiar navigation buttons on their browser. You can add/remove items from anywhere in the history chain as you please. If you use objects in your history array, you can track extra information about the pages as well (like field contents and whatnot).

If you need to handle user-initiated navigation (like the user changing the URL in a hash-based navigation scheme), then you might use a slightly different approach like...

var myHistory = [];

function pageLoad() {
    // When the user first hits your page...
    // Check the state to see what's going on.

    if (window.history.state === null) {
        // If the state is null, this is a NEW navigation,
        //    the user has navigated to your page directly (not using back/forward).

        // First we establish a "back" page to catch backward navigation.
        window.history.replaceState(
            { isBackPage: true },
            "<back>",
            "<back>"
        );

        // Then push an "app" page on top of that - this is where the user will sit.
        // (As browsers vary, it might be safer to put this in a short setTimeout).
        window.history.pushState(
            { isBackPage: false },
            "<name>",
            "<url>"
        );

        // We also need to start our history tracking.
        myHistory.push("<whatever>");

        return;
    }

    // If the state is NOT null, then the user is returning to our app via history navigation.

    // (Load up the page based on the last entry of myHistory here)

    if (window.history.state.isBackPage) {
        // If the user came into our app via the back page,
        //     you can either push them forward one more step or just use pushState as above.

        window.history.go(1);
        // or window.history.pushState({ isBackPage: false }, "<name>", "<url>");
    }

    setTimeout(function() {
        // Add our popstate event listener - doing it here should remove
        //     the issue of dealing with the browser firing it on initial page load.
        window.addEventListener("popstate", on_popstate);
    }, 100);
}

function on_popstate(e) {
    if (e.state === null) {
        // If there's no state at all, then the user must have navigated to a new hash.

        // <Look at what they've done, maybe by reading the hash from the URL>
        // <Change/load the new page and push it onto the myHistory stack>
        // <Alternatively, ignore their navigation attempt by NOT loading anything new or adding to myHistory>

        // Undo what they've done (as far as navigation) by kicking them backwards to the "app" page
        window.history.go(-1);

        // Optionally, you can throw another replaceState in here, e.g. if you want to change the visible URL.
        // This would also prevent them from using the "forward" button to return to the new hash.
        window.history.replaceState(
            { isBackPage: false },
            "<new name>",
            "<new url>"
        );
    } else {
        if (e.state.isBackPage) {
            // If there is state and it's the 'back' page...

            if (myHistory.length > 0) {
                // Pull/load the page from our custom history...
                var pg = myHistory.pop();
                // <load/render/whatever>

                // And push them to our "app" page again
                window.history.pushState(
                    { isBackPage: false },
                    "<name>",
                    "<url>"
                );
            } else {
                // No more history - let them exit or keep them in the app.
            }
        }

        // Implied 'else' here - if there is state and it's NOT the 'back' page
        //     then we can ignore it since we're already on the page we want.
        //     (This is the case when we push the user back with window.history.go(-1) above)
    }
}

What is (x & 1) and (x >>= 1)?

In addition to the answer of "dasblinkenlight" I think an example could help. I will only use 8 bits for a better understanding.

x & 1 produces a value that is either 1 or 0, depending on the least significant bit of x: if the last bit is 1, the result of x & 1 is 1; otherwise, it is 0. This is a bitwise AND operation.

This is because 1 will be represented in bits as 00000001. Only the last bit is set to 1. Let's assume x is 185 which will be represented in bits as 10111001. If you apply a bitwise AND operation on x with 1 this will be the result:

00000001
10111001
--------
00000001

The first seven bits of the operation result will be 0 after the operation and will carry no information in this case (see Logical AND operation). Because whatever the first seven bits of the operand x were before, after the operation they will be 0. But the last bit of the operand 1 is 1 and it will reveal if the last bit of operand x was 0 or 1. So in this example the result of the bitwise AND operation will be 1 because our last bit of x is 1. If the last bit would have been 0, then the result would have been also 0, indicating that the last bit of operand x is 0:

00000001
10111000
--------
00000000

x >>= 1 means "set x to itself shifted by one bit to the right". The expression evaluates to the new value of x after the shift

Let's pick the example from above. For x >>= 1 this would be:

10111001
--------
01011100

And for left shift x <<= 1 it would be:

10111001
--------
01110010

Please pay attention to the note of user "dasblinkenlight" in regard to shifts.

Copy filtered data to another sheet using VBA

it needs to be .Row.count not Row.Number?

That's what I used and it works fine Sub TransfersToCleared() Dim ws As Worksheet Dim LastRow As Long Set ws = Application.Worksheets("Export (2)") 'Data Source LastRow = Range("A" & Rows.Count).End(xlUp).Row ws.Range("A2:AB" & LastRow).SpecialCells(xlCellTypeVisible).Copy

Adding Buttons To Google Sheets and Set value to Cells on clicking

You can insert an image that looks like a button. Then attach a script to the image.

  • INSERT menu
  • Image

Insert Image

You can insert any image. The image can be edited in the spreadsheet

Edit Image

Image of a Button

Image of Button

Assign a function name to an image:

Assign Function

Display open transactions in MySQL

You can use show innodb status (or show engine innodb status for newer versions of mysql) to get a list of all the actions currently pending inside the InnoDB engine. Buried in the wall of output will be the transactions, and what internal process ID they're running under.

You won't be able to force a commit or rollback of those transactions, but you CAN kill the MySQL process running them, which does essentially boil down to a rollback. It kills the processes' connection and causes MySQL to clean up the mess its left.

Here's what you'd want to look for:

------------
TRANSACTIONS
------------
Trx id counter 0 140151
Purge done for trx's n:o < 0 134992 undo n:o < 0 0
History list length 10
LIST OF TRANSACTIONS FOR EACH SESSION:
---TRANSACTION 0 0, not started, process no 17004, OS thread id 140621902116624
MySQL thread id 10594, query id 10269885 localhost marc
show innodb status

In this case, there's just one connection to the InnoDB engine right now (my login, running the show query). If that line were an actual connection/stuck transaction you'd want to terminate, you'd then do a kill 10594.

MVC - Set selected value of SelectList

I wanted the dropdown to select the matching value of the id in the action method. The trick is to set the Selected property when creating the SelectListItem Collection. It would not work any other way, perhaps I missed something but in end, it is more elegant in my option.

You can write any method that returns a boolean to set the Selected value based on your requirements, in my case I used the existing Equal Method

public ActionResult History(long id)
        {
            var app = new AppLogic();
            var historyVM = new ActivityHistoryViewModel();

            historyVM.ProcessHistory = app.GetActivity(id);
            historyVM.Process = app.GetProcess(id);
            var processlist = app.GetProcessList();

            historyVM.ProcessList = from process in processlist
                                    select new SelectListItem
                                    {
                                        Text = process.ProcessName,
                                        Value = process.ID.ToString(),
                                        Selected = long.Equals(process.ID, id)                                    

                                    };

            var listitems = new List<SelectListItem>();

            return View(historyVM);
        }

How can I use break or continue within for loop in Twig template?

A way to be able to use {% break %} or {% continue %} is to write TokenParsers for them.

I did it for the {% break %} token in the code below. You can, without much modifications, do the same thing for the {% continue %}.

  • AppBundle\Twig\AppExtension.php:

    namespace AppBundle\Twig;
    
    class AppExtension extends \Twig_Extension
    {
        function getTokenParsers() {
            return array(
                new BreakToken(),
            );
        }
    
        public function getName()
        {
            return 'app_extension';
        }
    }
    
  • AppBundle\Twig\BreakToken.php:

    namespace AppBundle\Twig;
    
    class BreakToken extends \Twig_TokenParser
    {
        public function parse(\Twig_Token $token)
        {
            $stream = $this->parser->getStream();
            $stream->expect(\Twig_Token::BLOCK_END_TYPE);
    
            // Trick to check if we are currently in a loop.
            $currentForLoop = 0;
    
            for ($i = 1; true; $i++) {
                try {
                    // if we look before the beginning of the stream
                    // the stream will throw a \Twig_Error_Syntax
                    $token = $stream->look(-$i);
                } catch (\Twig_Error_Syntax $e) {
                    break;
                }
    
                if ($token->test(\Twig_Token::NAME_TYPE, 'for')) {
                    $currentForLoop++;
                } else if ($token->test(\Twig_Token::NAME_TYPE, 'endfor')) {
                    $currentForLoop--;
                }
            }
    
    
            if ($currentForLoop < 1) {
                throw new \Twig_Error_Syntax(
                    'Break tag is only allowed in \'for\' loops.',
                    $stream->getCurrent()->getLine(),
                    $stream->getSourceContext()->getName()
                );
            }
    
            return new BreakNode();
        }
    
        public function getTag()
        {
            return 'break';
        }
    }
    
  • AppBundle\Twig\BreakNode.php:

    namespace AppBundle\Twig;
    
    class BreakNode extends \Twig_Node
    {
        public function compile(\Twig_Compiler $compiler)
        {
            $compiler
                ->write("break;\n")
            ;
        }
    }
    

Then you can simply use {% break %} to get out of loops like this:

{% for post in posts %}
    {% if post.id == 10 %}
        {% break %}
    {% endif %}
    <h2>{{ post.heading }}</h2>
{% endfor %}

To go even further, you may write token parsers for {% continue X %} and {% break X %} (where X is an integer >= 1) to get out/continue multiple loops like in PHP.

Catch KeyError in Python

I am using Python 3.6 and using a comma between Exception and e does not work. I need to use the following syntax (just for anyone wondering)

try:
    connection = manager.connect("I2Cx")
except KeyError as e:
    print(e.message)

How to select min and max values of a column in a datatable?

Session["MinDate"] = dtRecord.Compute("Min(AccountLevel)", string.Empty);
Session["MaxDate"] = dtRecord.Compute("Max(AccountLevel)", string.Empty);

Post to another page within a PHP script

For those using cURL, note that CURLOPT_POST option is taken as a boolean value, so there's actually no need to set it to the number of fields you are POSTing.
Setting CURLOPT_POST to TRUE (i.e. any integer except zero) will just tell cURL to encode the data as application/x-www-form-urlencoded, although I bet this is not strictly necessary when you're passing a urlencoded string as CURLOPT_POSTFIELDS, since cURL should already tell the encoding by the type of the value (string vs array) which this latter option is set to.

Also note that, since PHP 5, you can use the http_build_query function to make PHP urlencode the fields array for you, like this:

curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));

How does C#'s random number generator work?

I was just wondering how the random number generator in C# works.

That's implementation-specific, but the wikipedia entry for pseudo-random number generators should give you some ideas.

I was also curious how I could make a program that generates random WHOLE INTEGER numbers from 1-100.

You can use Random.Next(int, int):

Random rng = new Random();
for (int i = 0; i < 10; i++)
{
    Console.WriteLine(rng.Next(1, 101));
}

Note that the upper bound is exclusive - which is why I've used 101 here.

You should also be aware of some of the "gotchas" associated with Random - in particular, you should not create a new instance every time you want to generate a random number, as otherwise if you generate lots of random numbers in a short space of time, you'll see a lot of repeats. See my article on this topic for more details.

How to merge 2 JSON objects from 2 files using jq?

Who knows if you still need it, but here is the solution.

Once you get to the --slurp option, it's easy!

--slurp/-s:
    Instead of running the filter for each JSON object in the input,
    read the entire input stream into a large array and run the filter just once.

Then the + operator will do what you want:

jq -s '.[0] + .[1]' config.json config-user.json

(Note: if you want to merge inner objects instead of just overwriting the left file ones with the right file ones, you will need to do it manually)

How to format strings in Java

The org.apache.commons.text.StringSubstitutor helper class from Apache Commons Text provides named variable substitution

Map<String, String> valuesMap = new HashMap<>();
valuesMap.put("animal", "quick brown fox");
valuesMap.put("target", "lazy dog");
String resolved = new StringSubstitutor(valuesMap).replace("The ${animal} jumped over the ${target}.");
System.out.println(resolved); // The quick brown fox jumped over the lazy dog.

Native query with named parameter fails with "Not all named parameters have been set"

You are calling setProperty instead of setParameter. Change your code to

Query q = em.createNativeQuery("SELECT count(*) FROM mytable where username = :username");
em.setParameter("username", "test");
(int) q.getSingleResult();

and it should work.

Is there a way of setting culture for a whole application? All current threads and new threads?

This gets asked a lot. Basically, no there isn't, not for .NET 4.0. You have to do it manually at the start of each new thread (or ThreadPool function). You could perhaps store the culture name (or just the culture object) in a static field to save having to hit the DB, but that's about it.

Populate dropdown select with array using jQuery

You can also do this:

var list = $('#items')[0]; // HTMLSelectElement
$.each(numbers, function(index, text) { 
    list.options[list.options.length] = new Option(index, text);
}); 

Copy folder recursively, excluding some folders

Use tar along with a pipe.

cd /source_directory
tar cf - --exclude=dir_to_exclude . | (cd /destination && tar xvf - )

You can even use this technique across ssh.

Codesign error: Provisioning profile cannot be found after deleting expired profile

Unfortunately this approach didn't work out for me. But here's a fix which worked for me (to get this to work you need a working project file on Subversion or so):

I did roll back to an working version of my project file. As it isn't possible to revert with Xcode (Where is the 'Revert' option in Xcode 4's Source Control?) - I used Tortoise, my Windows machine and this Tutorial (http://tortoisesvn.net/docs/nightly/TortoiseSVN_en/tsvn-howto-rollback.html) to roll back to an older project file.

As the Tutorial didn't work out for me, I just used Tortoise to save the working revision of my project file to an usb stick to port it to my mac. After that I replaced the new broken project file with the old working one, cleaned and it worked like a charm!

How to store arrays in MySQL?

The reason that there are no arrays in SQL, is because most people don't really need it. Relational databases (SQL is exactly that) work using relations, and most of the time, it is best if you assign one row of a table to each "bit of information". For example, where you may think "I'd like a list of stuff here", instead make a new table, linking the row in one table with the row in another table.[1] That way, you can represent M:N relationships. Another advantage is that those links will not clutter the row containing the linked item. And the database can index those rows. Arrays typically aren't indexed.

If you don't need relational databases, you can use e.g. a key-value store.

Read about database normalization, please. The golden rule is "[Every] non-key [attribute] must provide a fact about the key, the whole key, and nothing but the key.". An array does too much. It has multiple facts and it stores the order (which is not related to the relation itself). And the performance is poor (see above).

Imagine that you have a person table and you have a table with phone calls by people. Now you could make each person row have a list of his phone calls. But every person has many other relationships to many other things. Does that mean my person table should contain an array for every single thing he is connected to? No, that is not an attribute of the person itself.

[1]: It is okay if the linking table only has two columns (the primary keys from each table)! If the relationship itself has additional attributes though, they should be represented in this table as columns.

Get the Query Executed in Laravel 3/4

Laravel 4+

In Laravel 4 and later, you have to call DB::getQueryLog() to get all ran queries.

$queries = DB::getQueryLog();
$last_query = end($queries);

Or you can download a profiler package. I'd recommend barryvdh/laravel-debugbar, which is pretty neat. You can read for instructions on how to install in their repository.

Note for Laravel 5 users: You'll need to call DB::enableQueryLog() before executing the query. Either just above the line that runs the query or inside a middleware.


Laravel 3

In Laravel 3, you can get the last executed query from an Eloquent model calling the static method last_query on the DB class.

DB::last_query();

This, however, requires that you enable the profiler option in application/config/database.php. Alternatively you could, as @dualed mentioned, enable the profiler option, in application/config/application.php or call DB::profile() to get all queries ran in the current request and their execution time.

Calculating a 2D Vector's Cross Product

In short: It's a shorthand notation for a mathematical hack.

Long explanation:

You can't do a cross product with vectors in 2D space. The operation is not defined there.

However, often it is interesting to evaluate the cross product of two vectors assuming that the 2D vectors are extended to 3D by setting their z-coordinate to zero. This is the same as working with 3D vectors on the xy-plane.

If you extend the vectors that way and calculate the cross product of such an extended vector pair you'll notice that only the z-component has a meaningful value: x and y will always be zero.

That's the reason why the z-component of the result is often simply returned as a scalar. This scalar can for example be used to find the winding of three points in 2D space.

From a pure mathematical point of view the cross product in 2D space does not exist, the scalar version is the hack and a 2D cross product that returns a 2D vector makes no sense at all.

How do I parse JSON into an int?

It depends on the property type that you are parsing.

If the json property is a number (e.g. 5) you can cast to Long directly, so you could do:

(long) jsonObj.get("id") // with id = 5, cast `5` to long 

After getting the long,you could cast again to int, resulting in:

(int) (long) jsonObj.get("id")

If the json property is a number with quotes (e.g. "5"), is is considered a string, and you need to do something similar to Integer.parseInt() or Long.parseLong();

Integer.parseInt(jsonObj.get("id")) // with id = "5", convert "5" to Long

The only issue is, if you sometimes receive id's a string or as a number (you cant predict your client's format or it does it interchangeably), you might get an exception, especially if you use parseInt/Long on a null json object.

If not using Java Generics, the best way to deal with these runtime exceptions that I use is:

if(jsonObj.get("id") == null) {
   // do something here
}

int id;
try{
    id = Integer.parseInt(jsonObj.get("id").toString());
} catch(NumberFormatException e) {
  // handle here
}

You could also remove that first if and add the exception to the catch. Hope this helps.

Iterating Over Dictionary Key Values Corresponding to List in Python

List comprehension can shorten things...

win_percentages = [m**2.0 / (m**2.0 + n**2.0) * 100 for m, n in [a[i] for i in NL_East]]

How to hide Bootstrap modal with javascript?

We need to take care of event bubbling. Need to add one line of code

$("#savechanges").on("click", function (e) {
        $("#userModal").modal("hide");
        e.stopPropagation(); //This line would take care of it
    });

How to strip all non-alphabetic characters from string in SQL Server?

Another possibe option for SQL Server 2017+, without loops and/or recursion, is a string-based approach using TRANSLATE() and REPLACE().

T-SQL statement:

DECLARE @pattern varchar(52) = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

SELECT 
   v.[Text], 
   REPLACE(
      TRANSLATE(
         v.[Text],
         REPLACE(TRANSLATE(v.[Text], @pattern, REPLICATE('a', LEN(@pattern))), 'a', ''),
         REPLICATE('0', LEN(REPLACE(TRANSLATE(v.[Text], @pattern, REPLICATE('a', LEN(@pattern))), 'a', '')))
      ),
      '0',
      ''
   ) AS AlphabeticCharacters
FROM (VALUES
   ('abc1234def5678ghi90jkl#@$&'),
   ('1234567890'),
   ('JAHDBESBN%*#*@*($E*sd55bn')
) v ([Text])

or as a function:

CREATE FUNCTION dbo.RemoveNonAlphabeticCharacters (@Text varchar(1000)) 
RETURNS varchar(1000)
AS BEGIN

   DECLARE @pattern varchar(52) = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
   SET @text = REPLACE(
      TRANSLATE(
         @Text,
         REPLACE(TRANSLATE(@Text, @pattern, REPLICATE('a', LEN(@pattern))), 'a', ''),
         REPLICATE('0', LEN(REPLACE(TRANSLATE(@Text, @pattern, REPLICATE('a', LEN(@pattern))), 'a', '')))
      ),
      '0',
      ''
   )
   
   RETURN @Text
END

What are the differences between WCF and ASMX web services?

WCF completely replaces ASMX web services. ASMX is the old way to do web services and WCF is the current way to do web services. All new SOAP web service development, on the client or the server, should be done using WCF.

Gradle - Move a folder from ABC to XYZ

Your task declaration is incorrectly combining the Copy task type and project.copy method, resulting in a task that has nothing to copy and thus never runs. Besides, Copy isn't the right choice for renaming a directory. There is no Gradle API for renaming, but a bit of Groovy code (leveraging Java's File API) will do. Assuming Project1 is the project directory:

task renABCToXYZ {     doLast {         file("ABC").renameTo(file("XYZ"))     } } 

Looking at the bigger picture, it's probably better to add the renaming logic (i.e. the doLast task action) to the task that produces ABC.

in_array multiple values

Going off of @Rok Kralj answer (best IMO) to check if any of needles exist in the haystack, you can use (bool) instead of !! which sometimes can be confusing during code review.

function in_array_any($needles, $haystack) {
   return (bool)array_intersect($needles, $haystack);
}

echo in_array_any( array(3,9), array(5,8,3,1,2) ); // true, since 3 is present
echo in_array_any( array(4,9), array(5,8,3,1,2) ); // false, neither 4 nor 9 is present

https://glot.io/snippets/f7dhw4kmju

openCV video saving in python

Try this. It's working for me (Windows 10).

import numpy as np
import cv2

cap = cv2.VideoCapture(0)

# Define the codec and create VideoWriter object
#fourcc = cv2.cv.CV_FOURCC(*'DIVX')
#out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))
out = cv2.VideoWriter('output.avi', -1, 20.0, (640,480))

while(cap.isOpened()):
    ret, frame = cap.read()
    if ret==True:
        frame = cv2.flip(frame,0)

        # write the flipped frame
        out.write(frame)

        cv2.imshow('frame',frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        break

# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()

1 = false and 0 = true?

I'm not sure if I'm answering the question right, but here's a familiar example:

The return type of GetLastError() in Windows is nonzero if there was an error, or zero otherwise. The reverse is usually true of the return value of the function you called.

websocket closing connection automatically

Since @Doua Beri is experiencing connection close even when there are 1 Hz SENDs, it may be instead be due to size limits on messages.

This passage from Spring's WebSockets may be useful, with my emphasis ...

Although in theory a WebSocket message can be almost unlimited in size, in practice WebSocket servers impose limits — for example, 8K on Tomcat and 64K on Jetty. For this reason STOMP clients such as stomp.js split larger STOMP messages at 16K boundaries and send them as multiple WebSocket messages thus requiring the server to buffer and re-assemble.

Excel VBA Automation Error: The object invoked has disconnected from its clients

I had this same problem in a large Excel 2000 spreadsheet with hundreds of lines of code. My solution was to make the Worksheet active at the beginning of the Class. I.E. ThisWorkbook.Worksheets("WorkSheetName").Activate This was finally discovered when I noticed that if "WorkSheetName" was active when starting the operation (the code) the error didn't occur. Drove me crazy for quite awhile.

Unable to install Maven on Windows: "JAVA_HOME is set to an invalid directory"

Due to security restrictions at my current place of work I was unable to set enviroment variables on my Windows based PC.

My workaround was to copy the mvn.bat file from %M2% into C:\WINNT and add the following to the top of the batch file:

@REM Needed as unable to set env variables on my desktop PC.

set MAVEN_OPTS=-Xms256m -Xmx1024m
set M2_HOME=C:\apache-maven-3.0.4
set M2=%M2_HOME%\bin
set JAVA_HOME=C:\Program Files\Java\jdk1.5.0_15
set PATH=%JAVA_HOME%\bin;%M2%;%PATH%

Not the nicest solution but it works. If anybody has any other way or work-around where the standard env vars are not able to be set into the system I'd welcome their response.

C# ASP.NET MVC Return to Previous Page

I know this is very late, but maybe this will help someone else.

I use a Cancel button to return to the referring url. In the View, try adding this:

@{
  ViewBag.Title = "Page title";
  Layout = "~/Views/Shared/_Layout.cshtml";

  if (Request.UrlReferrer != null)
  {
    string returnURL = Request.UrlReferrer.ToString();
    ViewBag.ReturnURL = returnURL;
  }
}

Then you can set your buttons href like this:

<a href="@ViewBag.ReturnURL" class="btn btn-danger">Cancel</a>

Other than that, the update by Jason Enochs works great!

Show or hide element in React

<style type="text/css">
    .hidden { display:none; }
</style>
render: function() {
    return (
      <div className={this.props.shouldHide ? 'hidden' : ''}>
        This will be hidden if you set <tt>props.shouldHide</tt> 
        to something truthy.
      </div>
    );
}

// or in more modern JS and stateless react
const Example = props => <div className={props.shouldHide}/>Hello</div>

python pandas convert index to datetime

Doing

df.index = pd.to_datetime(df.index, errors='coerce')

the data type of the index has changed to

dataframe information

Symfony2 and date_default_timezone_get() - It is not safe to rely on the system's timezone settings

The problem appear when we are using PHP 5.1 on Redhat or Cent OS

PHP 5.1 on RHEL/CentOS doesn't support the timezone functions

Android TabLayout Android Design

I had to collect information from various sources to put together a functioning TabLayout. The following is presented as a complete use case that can be modified as needed.

Make sure the module build.gradle file contains a dependency on com.android.support:design.

dependencies {
    compile 'com.android.support:design:23.1.1'
}

In my case, I am creating an About activity in the application with a TabLayout. I added the following section to AndroidMainifest.xml. Setting the parentActivityName allows the home arrow to take the user back to the main activity.

<!-- android:configChanges="orientation|screenSize" makes the activity not reload when the orientation changes. -->
<activity
    android:name=".AboutActivity"
    android:label="@string/about_app"
    android:theme="@style/MyApp.About"
    android:parentActivityName=".MainActivity"
    android:configChanges="orientation|screenSize" >

    <!-- android.support.PARENT_ACTIVITY is necessary for API <= 15. -->
    <meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value=".MainActivity" />
</activity>

styles.xml contains the following entries. This app has a white AppBar for the main activity and a blue AppBar for the About activity. We need to set colorPrimaryDark for the About activity so that the status bar above the AppBar is blue.

<style name="MyApp" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorAccent">@color/blue</item>
</style>

<style name="MyApp.About" />

<!-- ThemeOverlay.AppCompat.Dark.ActionBar" makes the text and the icons in the AppBar white. -->
<style name="MyApp.DarkAppBar" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />

<style name="MyApp.AppBarOverlay" parent="ThemeOverlay.AppCompat.ActionBar" />

<style name="MyApp.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />

There is also a styles.xml (v19). It is located at src/main/res/values-v19/styles.xml. This file is only applied if the API of the device is >= 19.

<!-- android:windowTranslucentStatus requires API >= 19.  It makes the system status bar transparent.
  When it is specified the root layout should include android:fitsSystemWindows="true".
  colorPrimaryDark goes behind the status bar, which is then darkened by the overlay. -->
<style name="MyApp.About">
    <item name="android:windowTranslucentStatus">true</item>
    <item name="colorPrimaryDark">@color/blue</item>
</style>

AboutActivity.java contains the following code. In my case I have a fixed number of tabs (7) so I could remove all the code dealing with dynamic tabs.

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

public class AboutActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.about_coordinatorlayout);

        // We need to use the SupportActionBar from android.support.v7.app.ActionBar until the minimum API is >= 21.
        Toolbar supportAppBar = (Toolbar) findViewById(R.id.about_toolbar);
        setSupportActionBar(supportAppBar);

        // Display the home arrow on supportAppBar.
        final ActionBar appBar = getSupportActionBar();
        assert appBar != null;// This assert removes the incorrect warning in Android Studio on the following line that appBar might be null.
        appBar.setDisplayHomeAsUpEnabled(true);

        //  Setup the ViewPager.
        ViewPager aboutViewPager = (ViewPager) findViewById(R.id.about_viewpager);
        assert aboutViewPager != null; // This assert removes the incorrect warning in Android Studio on the following line that aboutViewPager might be null.
        aboutViewPager.setAdapter(new aboutPagerAdapter(getSupportFragmentManager()));

        // Setup the TabLayout and connect it to the ViewPager.
        TabLayout aboutTabLayout = (TabLayout) findViewById(R.id.about_tablayout);
        assert aboutTabLayout != null; // This assert removes the incorrect warning in Android Studio on the following line that aboutTabLayout might be null.
        aboutTabLayout.setupWithViewPager(aboutViewPager);
    }

    public class aboutPagerAdapter extends FragmentPagerAdapter {
        public aboutPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        // Get the count of the number of tabs.
        public int getCount() {
            return 7;
        }

        @Override
        // Get the name of each tab.  Tab numbers start at 0.
        public CharSequence getPageTitle(int tab) {
            switch (tab) {
                case 0:
                    return getString(R.string.version);

                case 1:
                    return getString(R.string.permissions);

                case 2:
                    return getString(R.string.privacy_policy);

                case 3:
                    return getString(R.string.changelog);

                case 4:
                    return getString(R.string.license);

                case 5:
                    return getString(R.string.contributors);

                case 6:
                    return getString(R.string.links);

                default:
                    return "";
            }
        }

        @Override
        // Setup each tab.
        public Fragment getItem(int tab) {
            return AboutTabFragment.createTab(tab);
        }
    }
}

AboutTabFragment.java is used to populate each tab. In my case, the first tab has a LinearLayout inside of a ScrollView and all the others have a WebView as the root layout.

import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.TextView;

public class AboutTabFragment extends Fragment {
    private int tabNumber;

    // AboutTabFragment.createTab stores the tab number in the bundle arguments so it can be referenced from onCreate().
    public static AboutTabFragment createTab(int tab) {
        Bundle thisTabArguments = new Bundle();
        thisTabArguments.putInt("Tab", tab);
        AboutTabFragment thisTab = new AboutTabFragment();
        thisTab.setArguments(thisTabArguments);
        return thisTab;
    }

    @Override
    public void onCreate (Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Store the tab number in tabNumber.
        tabNumber = getArguments().getInt("Tab");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View tabLayout;

        // Load the about tab layout.  Tab numbers start at 0.
        if (tabNumber == 0) {
            // Setting false at the end of inflater.inflate does not attach the inflated layout as a child of container.
            // The fragment will take care of attaching the root automatically.
            tabLayout = inflater.inflate(R.layout.about_tab_version, container, false);
        } else { // load a WebView for all the other tabs.  Tab numbers start at 0.
            // Setting false at the end of inflater.inflate does not attach the inflated layout as a child of container.
            // The fragment will take care of attaching the root automatically.
            tabLayout = inflater.inflate(R.layout.about_tab_webview, container, false);
            WebView tabWebView = (WebView) tabLayout;

            switch (tabNumber) {
                case 1:
                tabWebView.loadUrl("file:///android_asset/about_permissions.html");
                    break;

                case 2:
                    tabWebView.loadUrl("file:///android_asset/about_privacy_policy.html");
                    break;

                case 3:
                    tabWebView.loadUrl("file:///android_asset/about_changelog.html");
                    break;

                case 4:
                    tabWebView.loadUrl("file:///android_asset/about_license.html");
                    break;

                case 5:
                    tabWebView.loadUrl("file:///android_asset/about_contributors.html");
                    break;

                case 6:
                    tabWebView.loadUrl("file:///android_asset/about_links.html");
                    break;

                default:
                    break;
            }
        }

        return tabLayout;
    }
}

about_coordinatorlayout.xml is as follows:

<!-- android:fitsSystemWindows="true" moves the AppBar below the status bar.
  When it is specified the theme should include <item name="android:windowTranslucentStatus">true</item>
  to make the status bar a transparent, darkened overlay. -->
<android.support.design.widget.CoordinatorLayout
    android:id="@+id/about_coordinatorlayout"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:fitsSystemWindows="true" >

    <!-- the LinearLayout with orientation="vertical" moves the ViewPager below the AppBarLayout. -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <!-- We need to set android:background="@color/blue" here or any space to the right of the TabLayout on large devices will be white. -->
        <android.support.design.widget.AppBarLayout
            android:id="@+id/about_appbarlayout"
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:background="@color/blue"
            android:theme="@style/MyApp.AppBarOverlay" >

            <!-- android:theme="@style/PrivacyBrowser.DarkAppBar" makes the text and icons in the AppBar white. -->
            <android.support.v7.widget.Toolbar
                android:id="@+id/about_toolbar"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@color/blue"
                android:theme="@style/MyApp.DarkAppBar"
                app:popupTheme="@style/MyApp.PopupOverlay" />

            <android.support.design.widget.TabLayout
                android:id="@+id/about_tablayout"
                xmlns:android.support.design="http://schemas.android.com/apk/res-auto"
                android:layout_height="wrap_content"
                android:layout_width="match_parent"
                android.support.design:tabBackground="@color/blue"
                android.support.design:tabTextColor="@color/light_blue"
                android.support.design:tabSelectedTextColor="@color/white"
                android.support.design:tabIndicatorColor="@color/white"
                android.support.design:tabMode="scrollable" />
        </android.support.design.widget.AppBarLayout>

        <!-- android:layout_weight="1" makes about_viewpager fill the rest of the screen. -->
        <android.support.v4.view.ViewPager
            android:id="@+id/about_viewpager"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1" />
    </LinearLayout>
</android.support.design.widget.CoordinatorLayout>

about_tab_version.xml is as follows:

<!-- The ScrollView allows the LinearLayout to scroll if it exceeds the height of the page. -->
<ScrollView
    android:id="@+id/about_version_scrollview"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="wrap_content"
    android:layout_width="match_parent" >

    <LinearLayout
        android:id="@+id/about_version_linearlayout"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:orientation="vertical"
        android:padding="16dp" >

        <!-- Include whatever content you want in this tab here. -->

    </LinearLayout>
</ScrollView>

And about_tab_webview.xml:

<!-- This WebView displays inside of the tabs in AboutActivity. -->
<WebView
    android:id="@+id/about_tab_webview"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

There are also entries in strings.xml

<string name="about_app">About App</string>
<string name="version">Version</string>
<string name="permissions">Permissions</string>
<string name="privacy_policy">Privacy Policy</string>
<string name="changelog">Changelog</string>
<string name="license">License</string>
<string name="contributors">Contributors</string>
<string name="links">Links</string>

And colors.xml

<color name="blue">#FF1976D2</color>
<color name="light_blue">#FFBBDEFB</color>
<color name="white">#FFFFFFFF</color>

src/main/assets contains the HTML files referenced in AboutTabFragemnt.java.

Transpose a data frame

Take advantage of as.matrix:

# keep the first column 
names <-  df.aree[,1]

# Transpose everything other than the first column
df.aree.T <- as.data.frame(as.matrix(t(df.aree[,-1])))

# Assign first column as the column names of the transposed dataframe
colnames(df.aree.T) <- names

Angular checkbox and ng-click

The order of execution of ng-click and ng-model is different with angular 1.2 vs 1.6

You must test, with 1.2 and 1.6,

for example, with angular 1.2, ng-click get execute before ng-model, with angular 1.6, ng-model maybe get excute before ng-click.

so you get 'true checked' / 'false uncheck' value maybe not you expect

C# using streams

I wouldn't call those different kind of streams. The Stream class have CanRead and CanWrite properties that tell you if the particular stream can be read from and written to.

The major difference between different stream classes (such as MemoryStream vs FileStream) is the backing store - where the data is read from or where it's written to. It's kind of obvious from the name. A MemoryStream stores the data in memory only, a FileStream is backed by a file on disk, a NetworkStream reads data from the network and so on.

How to convert an image to base64 encoding?

Use also this way to represent image in base64 encode format... find PHP function file_get_content and next to use function base64_encode

and get result to prepare str as data:" . file_mime_type . " base64_encoded string. Use it in img src attribute. see following code can I help for you.

// A few settings
$img_file = 'raju.jpg';

// Read image path, convert to base64 encoding
$imgData = base64_encode(file_get_contents($img_file));

// Format the image SRC:  data:{mime};base64,{data};
$src = 'data: '.mime_content_type($img_file).';base64,'.$imgData;

// Echo out a sample image
echo '<img src="'.$src.'">';

SQL changing a value to upper or lower case

You can do:

SELECT lower(FIRST NAME) ABC
FROM PERSON

NOTE: ABC is used if you want to change the name of the column

Display animated GIF in iOS

I would recommend using the following code, it's much more lightweight, and compatible with ARC and non-ARC project, it adds a simple category on UIImageView:

https://github.com/mayoff/uiimage-from-animated-gif/

TCP vs UDP on video stream

If the bandwidth is far higher than the bitrate, I would recommend TCP for unicast live video streaming.

Case 1: Consecutive packets are lost for a duration of several seconds. => live video will stop on the client side whatever the transport layer is (TCP or UDP). When the network recovers: - if TCP is used, client video player can choose to restart the stream at the first packet lost (timeshift) OR to drop all late packets and to restart the video stream with no timeshift. - if UDP is used, there is no choice on the client side, video restart live without any timeshift. => TCP equal or better.

Case 2: some packets are randomly and often lost on the network. - if TCP is used, these packets will be immediately retransmitted and with a correct jitter buffer, there will be no impact on the video stream quality/latency. - if UDP is used, video quality will be poor. => TCP much better

Force SSL/https using .htaccess and mod_rewrite

Simple and Easy , just add following

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

curl error 18 - transfer closed with outstanding read data remaining

I had the same problem, but managed to fix it by suppressing the 'Expect: 100-continue' header that cURL usually sends (the following is PHP code, but should work similarly with other cURL APIs):

curl_setopt($curl, CURLOPT_HTTPHEADER, array('Expect:'));

By the way, I am sending calls to the HTTP server that is included in the JDK 6 REST stuff, which has all kinds of problems. In this case, it first sends a 100 response, and then with some requests doesn't send the subsequent 200 response correctly.

Change a Django form field to a hidden field

If you want the field to always be hidden, use the following:

class MyForm(forms.Form):
    hidden_input = forms.CharField(widget=forms.HiddenInput(), initial="value")

If you want the field to be conditionally hidden, you can do the following:

form = MyForm()
if condition:
    form.fields["field_name"].widget = forms.HiddenInput()
    form.fields["field_name"].initial = "value"

What is the difference between 'typedef' and 'using' in C++11?

The using syntax has an advantage when used within templates. If you need the type abstraction, but also need to keep template parameter to be possible to be specified in future. You should write something like this.

template <typename T> struct whatever {};

template <typename T> struct rebind
{
  typedef whatever<T> type; // to make it possible to substitue the whatever in future.
};

rebind<int>::type variable;

template <typename U> struct bar { typename rebind<U>::type _var_member; }

But using syntax simplifies this use case.

template <typename T> using my_type = whatever<T>;

my_type<int> variable;
template <typename U> struct baz { my_type<U> _var_member; }

Subquery returned more than 1 value.This is not permitted when the subquery follows =,!=,<,<=,>,>= or when the subquery is used as an expression

Use In instead of =

 select * from dbo.books
 where isbn in (select isbn from dbo.lending 
                where act between @fdate and @tdate
                and stat ='close'
               )

or you can use Exists

SELECT t1.*,t2.*
FROM  books   t1 
WHERE  EXISTS ( SELECT * FROM dbo.lending t2 WHERE t1.isbn = t2.isbn and
                t2.act between @fdate and @tdate and t2.stat ='close' )

Javascript Get Values from Multiple Select Option Box

Take a look at HTMLSelectElement.selectedOptions.

HTML

<select name="north-america" multiple>
  <option valud="ca" selected>Canada</a>
  <option value="mx" selected>Mexico</a>
  <option value="us">USA</a>
</select>

JavaScript

var elem = document.querySelector("select");

console.log(elem.selectedOptions);
//=> HTMLCollection [<option value="ca">Canada</option>, <option value="mx">Mexico</option>]

This would also work on non-multiple <select> elements


Warning: Support for this selectedOptions seems pretty unknown at this point

Delete statement in SQL is very slow

Deleting a lot of rows can be very slow. Try to delete a few at a time, like:

delete top (10) YourTable where col in ('1','2','3','4')
while @@rowcount > 0
    begin
    delete top (10) YourTable where col in ('1','2','3','4')
    end

Count textarea characters

_x000D_
_x000D_
var maxchar = 10;_x000D_
$('#message').after('<span id="count" class="counter"></span>');_x000D_
$('#count').html(maxchar+' of '+maxchar);_x000D_
$('#message').attr('maxlength', maxchar);_x000D_
$('#message').parent().addClass('wrap-text');_x000D_
$('#message').on("keydown", function(e){_x000D_
 var len =  $('#message').val().length;_x000D_
 if (len >= maxchar && e.keyCode != 8)_x000D_
     e.preventDefault();_x000D_
 else if(len <= maxchar && e.keyCode == 8){_x000D_
  if(len <= maxchar && len != 0)_x000D_
      $('#count').html(maxchar+' of '+(maxchar - len +1));_x000D_
     else if(len == 0)_x000D_
      $('#count').html(maxchar+' of '+(maxchar - len));_x000D_
 }else_x000D_
   $('#count').html(maxchar+' of '+(maxchar - len-1)); _x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<textarea id="message" name="text"></textarea>
_x000D_
_x000D_
_x000D_

How to indent/format a selection of code in Visual Studio Code with Ctrl + Shift + F

  • you can also indent a whole section by selecting it and clicking TAB
  • and also indent backward using Shift+TAB

And of course for auto indentation and formatting, following the language you're using, you can see which good extensions do the good job, and which formatters to install or which parameters settings to enable or set for each language and its available tools. Just make sure to read well the documentation of the extension, to install and set all what it need.

Up to now the indentation problem bothers me with Python when copy pasting a block of code. If that's the case, here is how you solve that: Visual Studio Code indentation for Python