Programs & Examples On #Clist

Monitoring the Full Disclosure mailinglist

Two generic ways to do the same thing... I'm not aware of any specific open solutions to do this, but it'd be rather trivial to do.

You could write a daily or weekly cron/jenkins job to scrape the previous time period's email from the archive looking for your keyworkds/combinations. Sending a batch digest with what it finds, if anything.

But personally, I'd Setup a specific email account to subscribe to the various security lists you're interested in. Add a simple automated script to parse the new emails for various keywords or combinations of keywords, when it finds a match forward that email on to you/your team. Just be sure to keep the keywords list updated with new products you're using.

You could even do this with a gmail account and custom rules, which is what I currently do, but I have setup an internal inbox in the past with a simple python script to forward emails that were of interest.

How can I fix the 'Missing Cross-Origin Resource Sharing (CORS) Response Header' webfont issue?

We had this exact problem with fontawesome-webfont.woff2 throwing a 406 error on a shared host (Cpanel). I was working on the elusive "cookie-less domain" for a Wordpress Multisite project and my "www.domain.tld" pages would have the following error (3 times) in Chrome:

Font from origin 'http://static.domain.tld' has been blocked from loading by Cross-Origin Resource Sharing policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.domain.tld' is therefore not allowed access.

and in Firefox, a little more detail:

downloadable font: download failed (font-family: "FontAwesome" style:normal weight:normal stretch:normal src index:1): bad URI or cross-site access not allowed source: http://static.domain.tld/wp-content/themes/some-theme-here/fonts/fontawesome-webfont.woff2?v=4.7.0
font-awesome.min.css:4:14 Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://static.domain.tld/wp-content/themes/some-theme-here/fonts/fontawesome-webfont.woff?v=4.7.0. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

I got to QWANT-ing around (QWANT.com = fantastic) and found this SO post:

Access-Control-Allow-Origin wildcard subdomains, ports and protocols

An hour in chat with different Shared Host support staff (one didn't even know about F12 in a browser...) then waiting for a response to the ticket that got cut after no joy while playing with mod_security. I tried to cobble the code for the .htaccess file together from the post in the meantime, and got this to work to remedy the 406 errors, flawlessly:

    <IfModule mod_headers.c>
    <IfModule mod_rewrite.c>
        SetEnvIf Origin "http(s)?://(.+\.)?domain\.tld(:\d{1,5})?$" CORS=$0
        Header set Access-Control-Allow-Origin "%{CORS}e" env=CORS
        Header merge  Vary "Origin"
    </IfModule>
    </IfModule>

I added that to the top of my .htaccess at the site root and now I have a new Uncle named Bob. (***of course change the domain.tld parts to whatever your domain that you are working with is...)

My FAVORITE part of this post though is the ability to RegEx OR (|) multiple sites into this CORS "hack" by doing:

To allow Multiple sites:

SetEnvIf Origin "http(s)?://(.+\.)?(othersite\.com|mywebsite\.com)(:\d{1,5})?$" CORS=$0

This fix honestly kind of blew my mind because I've ran into this issue before, working with Dev's at Fortune 500 companies that are MILES above my knowledgebase of Apache and couldn't solve problems like this without getting IT to tweak on Apache settings.

This is kind of the magic bullet to fix all those CDN issues with cookie-less (or near cookie-less if you use CloudFlare...) domains to reduce the amount of unnecessary web traffic from cookies that get sent with every image request only to be ditched like a bad blind date by the server.

Super Secure, Super Elegant. Love it: You don't have to open up your servers bandwidth to resource thieves / hot-link-er types.

Props to a collective effort from these 3 brilliant minds for solving what was once thought to unsolvable with .htaccess, whom I pieced this code together from:

@Noyo https://stackoverflow.com/users/357774/noyo

@DaveRandom https://stackoverflow.com/users/889949/daverandom

@pratap-koritala https://stackoverflow.com/users/4401569/pratap-koritala

System.Collections.Generic.List does not contain a definition for 'Select'

This question's bit old, but, there's a tricky scenario which also leads to this error:

In controller:

ViewBag.id = //id from querystring
List<string> = GrabDataFromDBByID(ViewBag.id).Select(a=>a.ToString());

The above code will lead to an error in this part: .Select(a=>a.ToString()) because of the below reason: You're passing a ViewBag.id to a method which in compiler, it doesn't know the type, so there might be several methods with the same name and different parameters let's say:

GrabDataFromDBByID(string)
GrabDataFromDBByID(int)
GrabDataFromDBByID(whateverType)

So to prevent this case, either explicitly cast the ViewBag or create another variable storing it.

Python: subplot within a loop: first panel appears in wrong position

Using your code with some random data, this would work:

fig, axs = plt.subplots(2,5, figsize=(15, 6), facecolor='w', edgecolor='k')
fig.subplots_adjust(hspace = .5, wspace=.001)

axs = axs.ravel()

for i in range(10):

    axs[i].contourf(np.random.rand(10,10),5,cmap=plt.cm.Oranges)
    axs[i].set_title(str(250+i))

The layout is off course a bit messy, but that's because of your current settings (the figsize, wspace etc).

enter image description here

Android: Pass data(extras) to a fragment

There is a simple why that I prefered to the bundle due to the no duplicate data in memory. It consists of a init public method for the fragment

private ArrayList<Music> listMusics = new ArrayList<Music>();
private ListView listMusic;


public static ListMusicFragment createInstance(List<Music> music) {
    ListMusicFragment fragment = new ListMusicFragment();
    fragment.init(music);
    return fragment;
}

public void init(List<Music> music){
    this.listMusic = music;
}

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

    View view = inflater.inflate(R.layout.musiclistview, container, false);
    listMusic = (ListView) view.findViewById(R.id.musicListView);
    listMusic.setAdapter(new MusicBaseAdapter(getActivity(), listMusics));

    return view;
}
}

In two words, you create an instance of the fragment an by the init method (u can call it as u want) you pass the reference of your list without create a copy by serialization to the instance of the fragment. This is very usefull because if you change something in the list u will get it in the other parts of the app and ofcourse, you use less memory.

Why ModelState.IsValid always return false in mvc

As Brad Wilson states in his answer here:

ModelState.IsValid tells you if any model errors have been added to ModelState.

The default model binder will add some errors for basic type conversion issues (for example, passing a non-number for something which is an "int"). You can populate ModelState more fully based on whatever validation system you're using.

Try using :-

if (!ModelState.IsValid)
{
    var errors = ModelState.SelectMany(x => x.Value.Errors.Select(z => z.Exception));

    // Breakpoint, Log or examine the list with Exceptions.
}

If it helps catching you the error. Courtesy this and this

Creating a List of Lists in C#

public class ListOfLists<T> : List<List<T>>
{
}


var myList = new ListOfLists<string>();

JSON to PHP Array using file_get_contents

Check some typo ','

<?php
 //file_get_content(url);
$jsonD = '{
    "bpath":"http://www.sampledomain.com/",
    "clist":[{
            "cid":"11",
            "display_type":"grid",
            "ctitle":"abc",
            "acount":"71",
            "alist":[{
                    "aid":"6865",
                    "adate":"2 Hours ago",
                    "atitle":"test",
                    "adesc":"test desc",
                    "aimg":"",
                    "aurl":"?nid=6865",
                    "weburl":"news.php?nid=6865",
                    "cmtcount":"0"
                },
                {
                    "aid":"6857",
                    "adate":"20 Hours ago",
                    "atitle":"test1",
                    "adesc":"test desc1",
                    "aimg":"",
                    "aurl":"?nid=6857",
                    "weburl":"news.php?nid=6857",
                    "cmtcount":"0"
                }
            ]
        },
        {
            "cid":"1",
            "display_type":"grid",
            "ctitle":"test1",
            "acount":"2354",
            "alist":[{
                    "aid":"6851",
                    "adate":"1 Days ago",
                    "atitle":"test123",
                    "adesc":"test123 desc",
                    "aimg":"",
                    "aurl":"?nid=6851",
                    "weburl":"news.php?nid=6851",
                    "cmtcount":"7"
                },
                {
                    "aid":"6847",
                    "adate":"2 Days ago",
                    "atitle":"test12345",
                    "adesc":"test12345 desc",
                    "aimg":"",
                    "aurl":"?nid=6847",
                    "weburl":"news.php?nid=6847",
                    "cmtcount":"7"
                }
            ]
        }
    ]
}
';

$parseJ = json_decode($jsonD,true);

print_r($parseJ);
?>

Sort a list alphabetically

There are two ways:

Without LINQ: yourList.Sort();

With LINQ: yourList.OrderBy(x => x).ToList()

You will find more information in: https://www.dotnetperls.com/sort

ACCESS_FINE_LOCATION AndroidManifest Permissions Not Being Granted

Compatible with all SDK versions (android.permission.ACCESS_FINE_LOCATION became dangerous permission in Android M and requires user to manually grant it).

In Android versions below Android M ContextCompat.checkSelfPermission(...) always returns true if you add these permission(s) in AndroidManifest.xml)

public void onSomeButtonClick() {
    ...
    if (!permissionsGranted()) {
        ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION}, 123);
    } else doLocationAccessRelatedJob();
    ...
}

private Boolean permissionsGranted() {
    return ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED);
}

@Override
public void onRequestPermissionsResult(final int requestCode, @NonNull final String[] permissions, @NonNull final int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == 123) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // Permission granted.
            doLocationAccessRelatedJob();
        } else {
            // User refused to grant permission. You can add AlertDialog here
            Toast.makeText(this, "You didn't give permission to access device location", Toast.LENGTH_LONG).show();
            startInstalledAppDetailsActivity();
        }
    }
}

private void startInstalledAppDetailsActivity() {
    Intent i = new Intent();
    i.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
    i.addCategory(Intent.CATEGORY_DEFAULT);
    i.setData(Uri.parse("package:" + getPackageName()));
    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(i);
}

in AndroidManifest.xml:

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

how to check if List<T> element contains an item with a Particular Property Value

This is pretty easy to do using LINQ:

var match = pricePublicList.FirstOrDefault(p => p.Size == 200);
if (match == null)
{
    // Element doesn't exist
}

org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

its happen when you try to delete the same object and then again update the same object use this after delete

session.clear();

What is the behavior difference between return-path, reply-to and from?

Another way to think about Return-Path vs Reply-To is to compare it to snail mail.

When you send an envelope in the mail, you specify a return address. If the recipient does not exist or refuses your mail, the postmaster returns the envelope back to the return address. For email, the return address is the Return-Path.

Inside of the envelope might be a letter and inside of the letter it may direct the recipient to "Send correspondence to example address". For email, the example address is the Reply-To.

In essence, a Postage Return Address is comparable to SMTP's Return-Path header and SMTP's Reply-To header is similar to the replying instructions contained in a letter.

VB.Net Properties - Public Get, Private Set

Yes, quite straight forward:

Private _name As String

Public Property Name() As String
    Get
        Return _name
    End Get
    Private Set(ByVal value As String)
        _name = value
    End Set
End Property

What do curly braces mean in Verilog?

As Matt said, the curly braces are for concatenation. The extra curly braces around 16{a[15]} are the replication operator. They are described in the IEEE Standard for Verilog document (Std 1364-2005), section "5.1.14 Concatenations".

{16{a[15]}}

is the same as

{ 
   a[15], a[15], a[15], a[15], a[15], a[15], a[15], a[15],
   a[15], a[15], a[15], a[15], a[15], a[15], a[15], a[15]
}

In bit-blasted form,

assign result = {{16{a[15]}}, {a[15:0]}};

is the same as:

assign result[ 0] = a[ 0];
assign result[ 1] = a[ 1];
assign result[ 2] = a[ 2];
assign result[ 3] = a[ 3];
assign result[ 4] = a[ 4];
assign result[ 5] = a[ 5];
assign result[ 6] = a[ 6];
assign result[ 7] = a[ 7];
assign result[ 8] = a[ 8];
assign result[ 9] = a[ 9];
assign result[10] = a[10];
assign result[11] = a[11];
assign result[12] = a[12];
assign result[13] = a[13];
assign result[14] = a[14];
assign result[15] = a[15];
assign result[16] = a[15];
assign result[17] = a[15];
assign result[18] = a[15];
assign result[19] = a[15];
assign result[20] = a[15];
assign result[21] = a[15];
assign result[22] = a[15];
assign result[23] = a[15];
assign result[24] = a[15];
assign result[25] = a[15];
assign result[26] = a[15];
assign result[27] = a[15];
assign result[28] = a[15];
assign result[29] = a[15];
assign result[30] = a[15];
assign result[31] = a[15];

Can I give a default value to parameters or optional parameters in C# functions?

This is a feature of C# 4.0, but was not possible without using function overload prior to that version.

Java Equivalent of C# async/await?

The await uses a continuation to execute additional code when the asynchronous operation completes (client.GetStringAsync(...)).

So, as the most close approximation I would use a CompletableFuture<T> (the Java 8 equivalent to .net Task<TResult>) based solution to process the Http request asynchronously.

UPDATED on 25-05-2016 to AsyncHttpClient v.2 released on Abril 13th of 2016:

So the Java 8 equivalent to the OP example of AccessTheWebAsync() is the following:

CompletableFuture<Integer> AccessTheWebAsync()
{
    AsyncHttpClient asyncHttpClient = new DefaultAsyncHttpClient();
    return asyncHttpClient
       .prepareGet("http://msdn.microsoft.com")
       .execute()
       .toCompletableFuture()
       .thenApply(Response::getResponseBody)
       .thenApply(String::length);
}

This usage was taken from the answer to How do I get a CompletableFuture from an Async Http Client request? and which is according to the new API provided in version 2 of AsyncHttpClient released on Abril 13th of 2016, that has already intrinsic support for CompletableFuture<T>.

Original answer using version 1 of AsyncHttpClient:

To that end we have two possible approaches:

  • the first one uses non-blocking IO and I call it AccessTheWebAsyncNio. Yet, because the AsyncCompletionHandler is an abstract class (instead of a functional interface) we cannot pass a lambda as argument. So it incurs in inevitable verbosity due to the syntax of anonymous classes. However, this solution is the most close to the execution flow of the given C# example.

  • the second one is slightly less verbose however it will submit a new Task that ultimately will block a thread on f.get() until the response is complete.

First approach, more verbose but non-blocking:

static CompletableFuture<Integer> AccessTheWebAsyncNio(){
    final AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
    final CompletableFuture<Integer> promise = new CompletableFuture<>();
    asyncHttpClient
        .prepareGet("https://msdn.microsoft.com")
        .execute(new AsyncCompletionHandler<Response>(){
            @Override
            public Response onCompleted(Response resp) throws Exception {
                promise.complete(resp.getResponseBody().length());
                return resp;
            }
        });
    return promise;
}

Second approach less verbose but blocking a thread:

static CompletableFuture<Integer> AccessTheWebAsync(){
    try(AsyncHttpClient asyncHttpClient = new AsyncHttpClient()){
        Future<Response> f = asyncHttpClient
            .prepareGet("https://msdn.microsoft.com")
            .execute();
        return CompletableFuture.supplyAsync(
            () -> return f.join().getResponseBody().length());
    }
}

How do I expand the output display to see more columns of a pandas DataFrame?

The below line is enough to display all columns from dataframe. pd.set_option('display.max_columns', None)

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.

Web.Config Debug/Release

The web.config transforms that are part of Visual Studio 2010 use XSLT in order to "transform" the current web.config file into its .Debug or .Release version.

In your .Debug/.Release files, you need to add the following parameter in your connection string fields:

xdt:Transform="SetAttributes" xdt:Locator="Match(name)"

This will cause each connection string line to find the matching name and update the attributes accordingly.

Note: You won't have to worry about updating your providerName parameter in the transform files, since they don't change.

Here's an example from one of my apps. Here's the web.config file section:

<connectionStrings>
      <add name="EAF" connectionString="[Test Connection String]" />
</connectionString>

And here's the web.config.release section doing the proper transform:

<connectionStrings>
      <add name="EAF" connectionString="[Prod Connection String]"
           xdt:Transform="SetAttributes"
           xdt:Locator="Match(name)" />
</connectionStrings>

One added note: Transforms only occur when you publish the site, not when you simply run it with F5 or CTRL+F5. If you need to run an update against a given config locally, you will have to manually change your Web.config file for this.

For more details you can see the MSDN documentation

https://msdn.microsoft.com/en-us/library/dd465326(VS.100).aspx

Flask at first run: Do not use the development server in a production environment

Unless you tell the development server that it's running in development mode, it will assume you're using it in production and warn you not to. The development server is not intended for use in production. It is not designed to be particularly efficient, stable, or secure.

Enable development mode by setting the FLASK_ENV environment variable to development.

$ export FLASK_APP=example
$ export FLASK_ENV=development
$ flask run

If you're running in PyCharm (or probably any other IDE) you can set environment variables in the run configuration.

Development mode enables the debugger and reloader by default. If you don't want these, pass --no-debugger or --no-reloader to the run command.


That warning is just a warning though, it's not an error preventing your app from running. If your app isn't working, there's something else wrong with your code.

How to copy JavaScript object to new variable NOT by reference?

Your only option is to somehow clone the object.

See this stackoverflow question on how you can achieve this.

For simple JSON objects, the simplest way would be:

var newObject = JSON.parse(JSON.stringify(oldObject));

if you use jQuery, you can use:

// Shallow copy
var newObject = jQuery.extend({}, oldObject);

// Deep copy
var newObject = jQuery.extend(true, {}, oldObject);

UPDATE 2017: I should mention, since this is a popular answer, that there are now better ways to achieve this using newer versions of javascript:

In ES6 or TypeScript (2.1+):

var shallowCopy = { ...oldObject };

var shallowCopyWithExtraProp = { ...oldObject, extraProp: "abc" };

Note that if extraProp is also a property on oldObject, its value will not be used because the extraProp : "abc" is specified later in the expression, which essentially overrides it. Of course, oldObject will not be modified.

Seaborn plots not showing up

This worked for me

import matplotlib.pyplot as plt
import seaborn as sns
.
.
.
plt.show(sns)

Determine if an element has a CSS class with jQuery

In my case , I used the 'is' a jQuery function, I had a HTML element with different css classes added , I was looking for a specific class in the middle of these , so I used the "is" a good alternative to check a class dynamically added to an html element , which already has other css classes, it is another good alternative.

simple example :

 <!--element html-->
 <nav class="cbp-spmenu cbp-spmenu-horizontal cbp-spmenu-bottom cbp-spmenu-open" id="menu">somethings here... </nav>

 <!--jQuery "is"-->
 $('#menu').is('.cbp-spmenu-open');

advanced example :

 <!--element html-->
    <nav class="cbp-spmenu cbp-spmenu-horizontal cbp-spmenu-bottom cbp-spmenu-open" id="menu">somethings here... </nav>

   <!--jQuery "is"-->
    if($('#menu').is('.cbp-spmenu-bottom.cbp-spmenu-open')){
       $("#menu").show();
    }

Create a string and append text to it

Use the string concatenation operator:

Dim str As String = New String("") & "some other string"

Strings in .NET are immutable and thus there exist no concept of appending strings. All string modifications causes a new string to be created and returned.

This obviously cause a terrible performance. In common everyday code this isn't an issue, but if you're doing intensive string operations in which time is of the essence then you will benefit from looking into the StringBuilder class. It allow you to queue appends. Once you're done appending you can ask it to actually perform all the queued operations.

See "How to: Concatenate Multiple Strings" for more information on both methods.

How to instantiate a javascript class in another js file?

It is saying the value is undefined because it is a constructor function, not a class with a constructor. In order to use it, you would need to use Customer() or customer().

First, you need to load file1.js before file2.js, like slebetman said:

<script defer src="file1.js" type="module"></script>
<script defer src="file2.js" type="module"></script>

Then, you could change your file1.js as follows:

export default class Customer(){
    constructor(){
        this.name="Jhon";
        this.getName=function(){
            return this.name;
        };
    }
}

And the file2.js as follows:

import { Customer } from "./file1";
var customer=new Customer();

Please correct me if I am wrong.

Does Visual Studio have code coverage for unit tests?

For anyone that is looking for an easy solution in Visual Studio Community 2019, Fine Code Coverage is simple but it works well.

It cannot give accurate numbers on the precise coverage, but it will tell which lines are being covered with green/red gutters.

send checkbox value in PHP form

If the checkbox is checked you will get a value for it in your $_POST array. If it isn't the element will be omitted from the array altogether.

The easiest way to test it is like this:

if (isset($_POST['myCheckbox'])) {
  $checkBoxValue = "yes";
} else {
  $checkBoxValue = "no";
}

For your code, add it immediately below the other preprocessing:

$name = $_POST['name']; 
$email_address = $_POST['email']; 
$message = $_POST['tel']; 

if (isset($_POST['newsletter'])) {
  $newsletter = "yes";
} else {
  $newsletter = "no";
}

You'll also need to change the HTML slightly. Change this line:

<input type="checkbox" name="newsletter[]" value="newsletter" checked>i want to sign up for newsletter<br>

to this:

<input type="checkbox" name="newsletter" value="newsletter" checked>i want to sign up   for newsletter<br>
                                      ^^^ remove square brackets here.

ORA-30926: unable to get a stable set of rows in the source tables

How to Troubleshoot ORA-30926 Errors? (Doc ID 471956.1)

1) Identify the failing statement

alter session set events ‘30926 trace name errorstack level 3’;

or

alter system set events ‘30926 trace name errorstack off’;

and watch for .trc files in UDUMP when it occurs.

2) Having found the SQL statement, check if it is correct (perhaps using explain plan or tkprof to check the query execution plan) and analyze or compute statistics on the tables concerned if this has not recently been done. Rebuilding (or dropping/recreating) indexes may help too.

3.1) Is the SQL statement a MERGE? evaluate the data returned by the USING clause to ensure that there are no duplicate values in the join. Modify the merge statement to include a deterministic where clause

3.2) Is this an UPDATE statement via a view? If so, try populating the view result into a table and try updating the table directly.

3.3) Is there a trigger on the table? Try disabling it to see if it still fails.

3.4) Does the statement contain a non-mergeable view in an 'IN-Subquery'? This can result in duplicate rows being returned if the query has a "FOR UPDATE" clause. See Bug 2681037

3.5) Does the table have unused columns? Dropping these may prevent the error.

4) If modifying the SQL does not cure the error, the issue may be with the table, especially if there are chained rows. 4.1) Run the ‘ANALYZE TABLE VALIDATE STRUCTURE CASCADE’ statement on all tables used in the SQL to see if there are any corruptions in the table or its indexes. 4.2) Check for, and eliminate, any CHAINED or migrated ROWS on the table. There are ways to minimize this, such as the correct setting of PCTFREE. Use Note 122020.1 - Row Chaining and Migration 4.3) If the table is additionally Index Organized, see: Note 102932.1 - Monitoring Chained Rows on IOTs

Vertical Alignment of text in a table cell

td.description {vertical-align: top;}

where description is the class name of the td with that text in it

_x000D_
_x000D_
td.description {_x000D_
  vertical-align: top;_x000D_
}
_x000D_
<td class="description">Description</td>
_x000D_
_x000D_
_x000D_

OR inline (yuk!)

_x000D_
_x000D_
<td style="vertical-align: top;">Description</td>
_x000D_
_x000D_
_x000D_

How to create a self-signed certificate for a domain name for development?

To Create the new certificate for your specific domain:

Open Powershell ISE as admin, run the command:

New-SelfSignedCertificate -DnsName *.mydomain.com, localhost -CertStoreLocation cert:\LocalMachine\My

To trust the new certificate:

  • Open mmc.exe
  • Go to Console Root -> Certificates (Local Computer) -> Personal
  • Select the certificate you have created, do right click -> All Tasks -> Export and follow the export wizard to create a .pfx file
  • Go to Console Root -> Certificates -> Trusted Root Certification Authorities and import the new .pfx file

To bind the certificate to your site:

  • Open IIS Manager
  • Select your site and choose Edit Site -> Bindings in the right pane
  • Add new https binding with the correct hostname and the new certificate

get and set in TypeScript

TS offers getters and setters which allow object properties to have more control of how they are accessed (getter) or updated (setter) outside of the object. Instead of directly accessing or updating the property a proxy function is called.

Example:

class Person {
    constructor(name: string) {
        this._name = name;
    }

    private _name: string;

    get name() {
        return this._name;
    }

    // first checks the length of the name and then updates the name.
    set name(name: string) {
        if (name.length > 10) {
            throw new Error("Name has a max length of 10");
        }

        this._name = name;  
    }

    doStuff () {
        this._name = 'foofooooooofoooo';
    }


}

const person = new Person('Willem');

// doesn't throw error, setter function not called within the object method when this._name is changed
person.doStuff();  

// throws error because setter is called and name is longer than 10 characters
person.name = 'barbarbarbarbarbar';  

Running a single test from unittest.TestCase via the command line

In case you want to run only tests from a specific class:

if __name__ == "__main__":
    unittest.main(MyCase())

It works for me in Python 3.6.

Redirection of standard and error output appending to the same log file

Andy gave me some good pointers, but I wanted to do it in an even cleaner way. Not to mention that with the 2>&1 >> method PowerShell complained to me about the log file being accessed by another process, i.e. both stderr and stdout trying to lock the file for access, I guess. So here's how I worked it around.

First let's generate a nice filename, but that's really just for being pedantic:

$name = "sync_common"
$currdate = get-date -f yyyy-MM-dd
$logfile = "c:\scripts\$name\log\$name-$currdate.txt"

And here's where the trick begins:

start-transcript -append -path $logfile

write-output "starting sync"
robocopy /mir /copyall S:\common \\10.0.0.2\common 2>&1 | Write-Output
some_other.exe /exeparams 2>&1 | Write-Output
...
write-output "ending sync"

stop-transcript

With start-transcript and stop-transcript you can redirect ALL output of PowerShell commands to a single file, but it doesn't work correctly with external commands. So let's just redirect all the output of those to the stdout of PS and let transcript do the rest.

In fact, I have no idea why the MS engineers say they haven't fixed this yet "due to the high cost and technical complexities involved" when it can be worked around in such a simple way.

Either way, running every single command with start-process is a huge clutter IMHO, but with this method, all you gotta do is append the 2>&1 | Write-Output code to each line which runs external commands.

Get selected value from combo box in C# WPF

Solving this problem is simple. All I did was to add "SelectedValuePath" to my XAML code and bind it to my model property that I want to return with the combobox.

<ComboBox SelectedValuePath="_Department"
          DisplayMemberPath="_Department"
          Height="23"
          HorizontalAlignment="Left"
          ItemsSource="{Binding}"
          Margin="-58,1,0,5"
          Name="_DepartmentComboBox"
          VerticalAlignment="Center"
          Width="268"/>

How to include() all PHP files from a directory?

I suggest you use a readdir() function and then loop and include the files (see the 1st example on that page).

How to pass a value to razor variable from javascript variable?

Razor View Server Side variable can be read to Client Side JavaScript using @ While and JavaScript client side variable can read to Razor View using @:

Set bootstrap modal body height by percentage

The scss solution for Bootstrap 4.0

.modal { max-height: 100vh; .modal-dialog { .modal-content { .modal-body { max-height: calc(80vh - 140px); overflow-y: auto; } } } }

Make sure the .modal max-height is 100vh. Then for .modal-body use calc() function to calculate desired height. In above case we want to occupy 80vh of the viewport, reduced by the size of header + footer in pixels. This is around 140px together but you can measure it easily and apply your own custom values. For smaller/taller modal modify 80vh accordingly.

What does this mean? "Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM"

if you still need to use the double-colon then make sure your on PHP 5.3+

Unloading classes in java?

If you're live watching if unloading class worked in JConsole or something, try also adding java.lang.System.gc() at the end of your class unloading logic. It explicitly triggers Garbage Collector.

Disable Logback in SpringBoot

The reason is, spring boot comes with logback as its default log configuration whereas camel uses log4j. Thats the reason of conflict. You have two options, either remove logback from spring boot as mentioned in above answers or remove log4j from camel.

<dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-spring-boot-starter</artifactId>
            <version>${camel.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-log4j12</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

List of Stored Procedures/Functions Mysql Command Line

Alternative:

SELECT * FROM INFORMATION_SCHEMA.ROUTINES

How to style child components from parent component's CSS file?

Sadly it appears that the /deep/ selector is deprecated (at least in Chrome) https://www.chromestatus.com/features/6750456638341120

In short it appears there is (currently) no long term solution other than to somehow get your child component to style things dynamically.

You could pass a style object to your child and have it applied via:
<div [attr.style]="styleobject">

Or if you have a specific style you can use something like:
<div [style.background-color]="colorvar">

More discussion related to this: https://github.com/angular/angular/issues/6511

How to cache Google map tiles for offline usage?

Unfortunately, I found this link which appears to indicate that we cannot cache these locally, therefore making this question moot.

http://support.google.com/enterprise/doc/gme/terms/maps_purchase_agreement.html

4.4 Cache Restrictions. Customer may not pre-fetch, retrieve, cache, index, or store any Content, or portion of the Services with the exception being Customer may store limited amounts of Content solely to improve the performance of the Customer Implementation due to network latency, and only if Customer does so temporarily, securely, and in a manner that (a) does not permit use of the Content outside of the Services; (b) is session-based only (once the browser is closed, any additional storage is prohibited); (c) does not manipulate or aggregate any Content or portion of the Services; (d) does not prevent Google from accurately tracking Page Views; and (e) does not modify or adjust attribution in any way.

So it appears we cannot use Google map tiles offline, legally.

Specifying Style and Weight for Google Fonts

you can use the weight value specified in the Google Fonts.

body{
 font-family: 'Heebo', sans-serif;
 font-weight: 100;
}

How do I convert a String to a BigInteger?

BigInteger has a constructor where you can pass string as an argument.

try below,

private void sum(String newNumber) {
    // BigInteger is immutable, reassign the variable:
    this.sum = this.sum.add(new BigInteger(newNumber));
}

Maintain the aspect ratio of a div with CSS

Just create a wrapper <div> with a percentage value for padding-bottom, like this:

_x000D_
_x000D_
.demoWrapper {
  padding: 10px;
  background: white;
  box-sizing: border-box;
  resize: horizontal;
  border: 1px dashed;
  overflow: auto;
  max-width: 100%;
  height: calc(100vh - 16px);
}

div {
  width: 100%;
  padding-bottom: 75%;
  background: gold; /** <-- For the demo **/
}
_x000D_
<div class="demoWrapper">
  <div></div>
</div>
_x000D_
_x000D_
_x000D_

It will result in a <div> with height equal to 75% of the width of its container (a 4:3 aspect ratio).

This relies on the fact that for padding :

The percentage is calculated with respect to the width of the generated box's containing block [...] (source: w3.org, emphasis mine)

Padding-bottom values for other aspect ratios and 100% width :

aspect ratio  | padding-bottom value
--------------|----------------------
    16:9      |       56.25%
    4:3       |       75%
    3:2       |       66.66%
    8:5       |       62.5%

Placing content in the div :

In order to keep the aspect ratio of the div and prevent its content from stretching it, you need to add an absolutely positioned child and stretch it to the edges of the wrapper with:

div.stretchy-wrapper {
  position: relative;
}

div.stretchy-wrapper > div {
  position: absolute;
  top: 0; bottom: 0; left: 0; right: 0;
}

Here's a demo and another more in depth demo

Python: instance has no attribute

Your class doesn't have a __init__(), so by the time it's instantiated, the attribute atoms is not present. You'd have to do C.setdata('something') so C.atoms becomes available.

>>> C = Residues()
>>> C.atoms.append('thing')

Traceback (most recent call last):
  File "<pyshell#84>", line 1, in <module>
    B.atoms.append('thing')
AttributeError: Residues instance has no attribute 'atoms'

>>> C.setdata('something')
>>> C.atoms.append('thing')   # now it works
>>> 

Unlike in languages like Java, where you know at compile time what attributes/member variables an object will have, in Python you can dynamically add attributes at runtime. This also implies instances of the same class can have different attributes.

To ensure you'll always have (unless you mess with it down the line, then it's your own fault) an atoms list you could add a constructor:

def __init__(self):
    self.atoms = []

Malformed String ValueError ast.literal_eval() with String representation of Tuple

I know this is an old question, but I think found a very simple answer, in case anybody needs it.

If you put string quotes inside your string ("'hello'"), ast_literaleval() will understand it perfectly.

You can use a simple function:

    def doubleStringify(a):
        b = "\'" + a + "\'"
        return b

Or probably more suitable for this example:

    def perfectEval(anonstring):
        try:
            ev = ast.literal_eval(anonstring)
            return ev
        except ValueError:
            corrected = "\'" + anonstring + "\'"
            ev = ast.literal_eval(corrected)
            return ev

What is the difference between Nexus and Maven?

Sonatype Nexus and Apache Maven are two pieces of software that often work together but they do very different parts of the job. Nexus provides a repository while Maven uses a repository to build software.

Here's a quote from "What is Nexus?":

Nexus manages software "artifacts" required for development. If you develop software, your builds can download dependencies from Nexus and can publish artifacts to Nexus creating a new way to share artifacts within an organization. While Central repository has always served as a great convenience for developers you shouldn't be hitting it directly. You should be proxying Central with Nexus and maintaining your own repositories to ensure stability within your organization. With Nexus you can completely control access to, and deployment of, every artifact in your organization from a single location.

And here is a quote from "Maven and Nexus Pro, Made for Each Other" explaining how Maven uses repositories:

Maven leverages the concept of a repository by retrieving the artifacts necessary to build an application and deploying the result of the build process into a repository. Maven uses the concept of structured repositories so components can be retrieved to support the build. These components or dependencies include libraries, frameworks, containers, etc. Maven can identify components in repositories, understand their dependencies, retrieve all that are needed for a successful build, and deploy its output back to repositories when the build is complete.

So, when you want to use both you will have a repository managed by Nexus and Maven will access this repository.

Angular expression if array contains

You shouldn't overload the templates with complex logic, it's a bad practice. Remember to always keep it simple!

The better approach would be to extract this logic into reusable function on your $rootScope:

.run(function ($rootScope) {
  $rootScope.inArray = function (item, array) {
    return (-1 !== array.indexOf(item));
  };
})

Then, use it in your template:

<li ng-class="{approved: inArray(jobSet, selectedForApproval)}"></li>

I think everyone will agree that this example is much more readable and maintainable.

Override console.log(); for production

Here is what I did

    var domainNames =["fiddle.jshell.net"]; // we replace this by our production domain.

var logger = {
    force:false,
    original:null,
    log:function(obj)
    {
        var hostName = window.location.hostname;
        if(domainNames.indexOf(hostName) > -1)
        {
            if(window.myLogger.force === true)
            {
                window.myLogger.original.apply(this,arguments);
            }
        }else {
            window.myLogger.original.apply(this,arguments);
        }
    },
    forceLogging:function(force){
        window.myLogger.force = force;
    },
    original:function(){
        return window.myLogger.original;
    },
    init:function(){
        window.myLogger.original = console.log;
        console.log = window.myLogger.log;
    }
}

window.myLogger = logger;
console.log("this should print like normal");
window.myLogger.init();
console.log("this should not print");
window.myLogger.forceLogging(true);
console.log("this should print now");

Also posted about it here. http://bhavinsurela.com/naive-way-of-overriding-console-log/

Syntax for creating a two-dimensional array in Java

It is also possible to declare it the following way. It's not good design, but it works.

int[] twoDimIntArray[] = new int[5][10];

Uncaught syntaxerror: unexpected identifier?

There are errors here :

var formTag = document.getElementsByTagName("form"), // form tag is an array
selectListItem = $('select'),
makeSelect = document.createElement('select'),
makeSelect.setAttribute("id", "groups");

The code must change to:

var formTag = document.getElementsByTagName("form");
var selectListItem = $('select');
var makeSelect = document.createElement('select');
makeSelect.setAttribute("id", "groups");

By the way, there is another error at line 129 :

var createLi.appendChild(createSubList);

Replace it with:

createLi.appendChild(createSubList);

Powershell 2 copy-item which creates a folder if doesn't exist

I have stumbled here twice, and this last time was a unique situation and even though I ditch using copy-item I wanted to post the solution I used.

Had a list of nothing but files with the full path and in majority of the case the files have no extensions. the -Recurse -Force option would not work for me so I ditched copy-item function and fell back to something like below using xcopy as I still wanted to keep it a one liner. Initially I tied with Robocopy but it is apparently looking for a file extension and since many of mine had no extension it considered it a directory.

$filelist = @("C:\Somepath\test\location\here\file","C:\Somepath\test\location\here2\file2")

$filelist | % { echo f | xcopy $_  $($_.Replace("somepath", "somepath_NEW")) }

Hope it helps someone.

Getting View's coordinates relative to the root layout

Incase someone is still trying to figure this out. This is how you get the center X and Y of the view.

    int pos[] = new int[2];
    view.getLocationOnScreen(pos);
    int centerX = pos[0] + view.getMeasuredWidth() / 2;
    int centerY = pos[1] + view.getMeasuredHeight() / 2;

Maven Unable to locate the Javac Compiler in:

It depends on of Maven version. When you will install newer version of Maven, this error would not appear. You may also add another directory with tools.jar file lib/tools.jar - it also solve this problem.

Get screenshot on Windows with Python?

A simple way to take a screenshot is through Pygame.

 pygame.image.save(Surface, filename)

Where 'Surface' is the surface you are taking a screenshot of, and 'filename' is the file path, name, and type where you save thew image.

You can export as BMP, TGA, PNG, or JPEG. As of Pygame 1.8, PNG, and JPEG also work.

If no file extension is specified it will default to a .TGA file.

You can even use the 'os' library for saving to specific file directories.

An example:

import os
import pygame
surface = pygame.display.set_mode((100, 100), 0, 32)
surface.fill((255, 255, 255))
pygame.draw.circle(surface, (0, 0, 0), (10, 10), 15, 0)
pygame.display.update()
pygame.image.save(surface, os.path.expanduser("~/Desktop/pic.png"))

This saves anything on the 'surface' Surface to the user's desktop as pic.png

Bind event to right mouse click

Just use the event-handler. Something like this should work:

$('.js-my-element').bind('contextmenu', function(e) {
     e.preventDefault();
     alert('The eventhandler will make sure, that the contextmenu dosn&#39;t appear.');
});

Jenkins - How to access BUILD_NUMBER environment variable

For Groovy script in the Jenkinsfile using the $BUILD_NUMBER it works.

Python: 'ModuleNotFoundError' when trying to import module from imported package

For me when I created a file and saved it as python file, I was getting this error during importing. I had to create a filename with the type ".py" , like filename.py and then save it as a python file. post trying to import the file worked for me.

What is DOM Event delegation?

Event delegation makes use of two often overlooked features of JavaScript events: event bubbling and the target element.When an event is triggered on an element, for example a mouse click on a button, the same event is also triggered on all of that element’s ancestors. This process is known as event bubbling; the event bubbles up from the originating element to the top of the DOM tree.

Imagine an HTML table with 10 columns and 100 rows in which you want something to happen when the user clicks on a table cell. For example, I once had to make each cell of a table of that size editable when clicked. Adding event handlers to each of the 1000 cells would be a major performance problem and, potentially, a source of browser-crashing memory leaks. Instead, using event delegation, you would add only one event handler to the table element, intercept the click event and determine which cell was clicked.

Isn't the size of character in Java 2 bytes?

Java allocates 2 of 2 bytes for character as it follows UTF-16. It occupies minimum 2 bytes while storing a character, and maximum of 4 bytes. There is no 1 byte or 3 bytes of storage for character.

AngularJS Folder Structure

There is also the approach of organizing the folders not by the structure of the framework, but by the structure of the application's function. There is a github starter Angular/Express application that illustrates this called angular-app.

How to determine a user's IP address in node

If using express...

req.ip

I was looking this up then I was like wait, I'm using express. Duh.

BehaviorSubject vs Observable?

BehaviorSubject vs Observable : RxJS has observers and observables, Rxjs offers a multiple classes to use with data streams, and one of them is a BehaviorSubject.

Observables : Observables are lazy collections of multiple values over time.

BehaviorSubject:A Subject that requires an initial value and emits its current value to new subscribers.

 // RxJS v6+
import { BehaviorSubject } from 'rxjs';

const subject = new BehaviorSubject(123);

//two new subscribers will get initial value => output: 123, 123
subject.subscribe(console.log);
subject.subscribe(console.log);

//two subscribers will get new value => output: 456, 456
subject.next(456);

//new subscriber will get latest value (456) => output: 456
subject.subscribe(console.log);

//all three subscribers will get new value => output: 789, 789, 789
subject.next(789);

// output: 123, 123, 456, 456, 456, 789, 789, 789

How do I use Assert.Throws to assert the type of the exception?

I recently ran into the same thing, and suggest this function for MSTest:

public bool AssertThrows(Action action) where T : Exception
{
    try {action();
}
catch(Exception exception)
{
    if (exception.GetType() == typeof(T))
        return true;
}
    return false;
}

Usage:

Assert.IsTrue(AssertThrows<FormatException>(delegate{ newMyMethod(MyParameter); }));

There is more in Assert that a particular exception has occured (Assert.Throws in MSTest).

How could I put a border on my grid control in WPF?

If someone is interested in the similar problem, but is not working with XAML, here's my solution:

var B1 = new Border();
B1.BorderBrush = Brushes.Black;
B1.BorderThickness = new Thickness(0, 1, 0, 0); // You can specify here which borders do you want
YourPanel.Children.Add(B1);

How does Python return multiple values from a function?

Python functions always return a unique value. The comma operator is the constructor of tuples so self.first_name, self.last_name evaluates to a tuple and that tuple is the actual value the function is returning.

Get selected item value from Bootstrap DropDown with specific ID

Did you just try

$('#datebox li a').on('click', function(){
    //$('#datebox').val($(this).text());
    alert($(this).text());
});

It works for me :)

How do I best silence a warning about unused variables?

This works well but requires C++11

template <typename ...Args>
void unused(Args&& ...args)
{
  (void)(sizeof...(args));
}

try/catch blocks with async/await

An alternative to try-catch block is await-to-js lib. I often use it. For example:

import to from 'await-to-js';

async function main(callback) {
    const [err,quote] = await to(getQuote());
    
    if(err || !quote) return callback(new Error('No Quote found'));

    callback(null,quote);

}

This syntax is much cleaner when compared to try-catch.

What does $@ mean in a shell script?

$@ is nearly the same as $*, both meaning "all command line arguments". They are often used to simply pass all arguments to another program (thus forming a wrapper around that other program).

The difference between the two syntaxes shows up when you have an argument with spaces in it (e.g.) and put $@ in double quotes:

wrappedProgram "$@"
# ^^^ this is correct and will hand over all arguments in the way
#     we received them, i. e. as several arguments, each of them
#     containing all the spaces and other uglinesses they have.
wrappedProgram "$*"
# ^^^ this will hand over exactly one argument, containing all
#     original arguments, separated by single spaces.
wrappedProgram $*
# ^^^ this will join all arguments by single spaces as well and
#     will then split the string as the shell does on the command
#     line, thus it will split an argument containing spaces into
#     several arguments.

Example: Calling

wrapper "one two    three" four five "six seven"

will result in:

"$@": wrappedProgram "one two    three" four five "six seven"
"$*": wrappedProgram "one two    three four five six seven"
                             ^^^^ These spaces are part of the first
                                  argument and are not changed.
$*:   wrappedProgram one two three four five six seven

Using Tempdata in ASP.NET MVC - Best practice

Just be aware of TempData persistence, it's a bit tricky. For example if you even simply read TempData inside the current request, it would be removed and consequently you don't have it for the next request. Instead, you can use Peek method. I would recommend reading this cool article:

MVC Tempdata , Peek and Keep confusion

What is the difference between HTTP status code 200 (cache) vs status code 304?

200 (cache) means Firefox is simply using the locally cached version. This is the fastest because no request to the Web server is made.

304 means Firefox is sending a "If-Modified-Since" conditional request to the Web server. If the file has not been updated since the date sent by the browser, the Web server returns a 304 response which essentially tells Firefox to use its cached version. It is not as fast as 200 (cache) because the request is still sent to the Web server, but the server doesn't have to send the contents of the file.

To your last question, I don't know why the two JavaScript files in the same directory are returning different results.

no overload for matches delegate 'system.eventhandler'

You need to wrap button click handler to match the pattern

public void klik(object sender, EventArgs e)

Convert Newtonsoft.Json.Linq.JArray to a list of specific object type

using Newtonsoft.Json.Linq;
using System.Linq;
using System.IO;
using System.Collections.Generic;

public List<string> GetJsonValues(string filePath, string propertyName)
{
  List<string> values = new List<string>();
  string read = string.Empty;
  using (StreamReader r = new StreamReader(filePath))
  {
    var json = r.ReadToEnd();
    var jObj = JObject.Parse(json);
    foreach (var j in jObj.Properties())
    {
      if (j.Name.Equals(propertyName))
      {
        var value = jObj[j.Name] as JArray;
        return values = value.ToObject<List<string>>();
      }
    }
    return values;
  }
}

How to find all the subclasses of a class given its name?

Here is a simple but efficient version of code:

def get_all_subclasses(cls):
    subclass_list = []

    def recurse(klass):
        for subclass in klass.__subclasses__():
            subclass_list.append(subclass)
            recurse(subclass)

    recurse(cls)

    return set(subclass_list)

Its time complexity is O(n) where n is the number of all subclasses if there's no multiple inheritance. It's more efficient than the functions that recursively create lists or yield classes with generators, whose complexity could be (1) O(nlogn) when the class hierarchy is a balanced tree or (2) O(n^2) when the class hierarchy is a biased tree.

Using CSS to insert text

Just code it like this:

.OwnerJoe {
  //other things here
  &:before{
    content: "Joe's Task: ";
  }
}

What's the difference between RANK() and DENSE_RANK() functions in oracle?

rank() : It is used to rank a record within a group of rows.

dense_rank() : The DENSE_RANK function acts like the RANK function except that it assigns consecutive ranks.

Query -

select 
    ENAME,SAL,RANK() over (order by SAL) RANK
from 
    EMP;

Output -

+--------+------+------+
| ENAME  | SAL  | RANK |
+--------+------+------+
| SMITH  |  800 |    1 |
| JAMES  |  950 |    2 |
| ADAMS  | 1100 |    3 |
| MARTIN | 1250 |    4 |
| WARD   | 1250 |    4 |
| TURNER | 1500 |    6 |
+--------+------+------+

Query -

select 
    ENAME,SAL,dense_rank() over (order by SAL) DEN_RANK
from 
    EMP;

Output -

+--------+------+-----------+
| ENAME  | SAL  |  DEN_RANK |
+--------+------+-----------+
| SMITH  |  800 |         1 |
| JAMES  |  950 |         2 |
| ADAMS  | 1100 |         3 |
| MARTIN | 1250 |         4 |
| WARD   | 1250 |         4 |
| TURNER | 1500 |         5 |
+--------+------+-----------+

Add back button to action bar

Simpler and better: For API >= 16

Simply add "parentActivityName" for each activity in Manifest. The back button will automatically take u to the parent activity.

<activity
        android:name="com.example.myfirstapp.DisplayMessageActivity"
        android:label="@string/title_activity_display_message"
        android:parentActivityName="com.example.myfirstapp.MainActivity" >

Setting the default active profile in Spring-boot

What you are doing here is setting the default default profile (the profile that is used on any bean if you don't specify the @Profile annotation) to be production.

What you actually need to do is set the default active profile, which is done like this:

spring.profiles.active=production

Allow Google Chrome to use XMLHttpRequest to load a URL from a local file

Mac version. From terminal run:

open /Applications/Google\ Chrome.app/ --args --allow-file-access-from-files

Convert json to a C# array?

using Newtonsoft.Json;

Install this class in package console This class works fine in all .NET Versions, for example in my project: I have DNX 4.5.1 and DNX CORE 5.0 and everything works.

Firstly before JSON deserialization, you need to declare a class to read normally and store some data somewhere This is my class:

public class ToDoItem
{
    public string text { get; set; }
    public string complete { get; set; }
    public string delete { get; set; }
    public string username { get; set; }
    public string user_password { get; set; }
    public string eventID { get; set; }
}

In HttpContent section where you requesting data by GET request for example:

HttpContent content = response.Content;
string mycontent = await content.ReadAsStringAsync();
//deserialization in items
ToDoItem[] items = JsonConvert.DeserializeObject<ToDoItem[]>(mycontent);

How to use variables in a command in sed?

Say:

sed "s|\$ROOT|${HOME}|" abc.sh

Note:

  • Use double quotes so that the shell would expand variables.
  • Use a separator different than / since the replacement contains /
  • Escape the $ in the pattern since you don't want to expand it.

EDIT: In order to replace all occurrences of $ROOT, say

sed "s|\$ROOT|${HOME}|g" abc.sh

Determine if JavaScript value is an "integer"?

Here's a polyfill for the Number predicate functions:

"use strict";

Number.isNaN = Number.isNaN ||
    n => n !== n; // only NaN

Number.isNumeric = Number.isNumeric ||
    n => n === +n; // all numbers excluding NaN

Number.isFinite = Number.isFinite ||
    n => n === +n               // all numbers excluding NaN
      && n >= Number.MIN_VALUE  // and -Infinity
      && n <= Number.MAX_VALUE; // and +Infinity

Number.isInteger = Number.isInteger ||
    n => n === +n              // all numbers excluding NaN
      && n >= Number.MIN_VALUE // and -Infinity
      && n <= Number.MAX_VALUE // and +Infinity
      && !(n % 1);             // and non-whole numbers

Number.isSafeInteger = Number.isSafeInteger ||
    n => n === +n                     // all numbers excluding NaN
      && n >= Number.MIN_SAFE_INTEGER // and small unsafe numbers
      && n <= Number.MAX_SAFE_INTEGER // and big unsafe numbers
      && !(n % 1);                    // and non-whole numbers

All major browsers support these functions, except isNumeric, which is not in the specification because I made it up. Hence, you can reduce the size of this polyfill:

"use strict";

Number.isNumeric = Number.isNumeric ||
    n => n === +n; // all numbers excluding NaN

Alternatively, just inline the expression n === +n manually.

How to migrate GIT repository from one server to a new one

Please follow the steps:

  • git remote add new-origin
  • git push --all new-origin
  • git push --tags new-origin
  • git remote rm origin
  • git remote rename new-origin origin

webpack command not working

Installing webpack with -g option installs webpack in a folder in

C:\Users\<.profileusername.>\AppData\Roaming\npm\node_modules

same with webpack-cli and webpack-dev-server

Outside the global node_modules a link is created for webpack to be run from commandline

C:\Users\<.profileusername.>\AppData\Roaming\npm

to make this work locally, I did the following

  1. renamed the webpack folder in global node_modules to _old
  2. installed webpack locally within project
  3. edited the command link webpack.cmd and pointed the webpack.js to look into my local node_modules folder within my application

Problem with this approach is you'd have to maintain links for each project you have. Theres no other way since you are using the command line editor to run webpack command when installing with a -g option.

So if you had proj1, proj2 and proj3 all with their local node_modules and local webpack installed( not using -g when installing), then you'd have to create non-generic link names instead of just webpack.

example here would be to create webpack_proj1.cmd, webpack_proj2.cmd and webpack_proj3.cmd and in each cmd follow point 2 and 3 above

PS: dont forget to update your package.json with these changes or else you'll get errors as it won't find webpack command

How can I query a value in SQL Server XML column

I came up with a simple work around below which is easy to remember too :-)

select * from  
(select cast (xmlCol as varchar(max)) texty
 from myTable (NOLOCK) 
) a 
where texty like '%MySearchText%'

Using Helvetica Neue in a Website

They are taking a 'shotgun' approach to referencing the font. The browser will attempt to match each font name with any installed fonts on the user's machine (in the order they have been listed).

In your example "HelveticaNeue-Light" will be tried first, if this font variant is unavailable the browser will try "Helvetica Neue Light" and finally "Helvetica Neue".

As far as I'm aware "Helvetica Neue" isn't considered a 'web safe font', which means you won't be able to rely on it being installed for your entire user base. It is quite common to define "serif" or "sans-serif" as a final default position.

In order to use fonts which aren't 'web safe' you'll need to use a technique known as font embedding. Embedded fonts do not need to be installed on a user's computer, instead they are downloaded as part of the page. Be aware this increases the overall payload (just like an image does) and can have an impact on page load times.

A great resource for free fonts with open-source licenses is Google Fonts. (You should still check individual licenses before using them.) Each font has a download link with instructions on how to embed them in your website.

Android: How to open a specific folder via Intent and show its content in a file browser?

You seem close.

I would try to set the URI like this :

String folderPath = Environment.getExternalStorageDirectory()+"/pathTo/folder";

Intent intent = new Intent();  
intent.setAction(Intent.ACTION_GET_CONTENT);
Uri myUri = Uri.parse(folderPath);
intent.setDataAndType(myUri , "file/*");   
startActivity(intent);

But it's not so different from what you have tried. Tell us if it changes anything ?

Also make sure the targeted folder exists, and have a look on the resulting Uri object before to send it to the intent, it may not be what we are expected.

What characters are forbidden in Windows and Linux directory names?

When creating internet shortcuts in Windows, to create the file name, it skips illegal characters, except for forward slash, which is converted to minus.

Java out.println() how is this possible?

Or simply:

System.out.println("Some text");

Datagrid binding in WPF

PLEASE do not use object as a class name:

public class MyObject //better to choose an appropriate name
{
    string id;
    DateTime date;
    public string ID
    {
       get { return id; }
       set { id = value; }
    }
    public DateTime Date
    {
       get { return date; }
       set { date = value; }
    }
}

You should implement INotifyPropertyChanged for this class and of course call it on the Property setter. Otherwise changes are not reflected in your ui.

Your Viewmodel class/ dialogbox class should have a Property of your MyObject list. ObservableCollection<MyObject> is the way to go:

public ObservableCollection<MyObject> MyList
{
     get...
     set...
}

In your xaml you should set the Itemssource to your collection of MyObject. (the Datacontext have to be your dialogbox class!)

<DataGrid ItemsSource="{Binding Source=MyList}"  AutoGenerateColumns="False">
   <DataGrid.Columns>                
     <DataGridTextColumn Header="ID" Binding="{Binding ID}"/>
     <DataGridTextColumn Header="Date" Binding="{Binding Date}"/>
   </DataGrid.Columns>
</DataGrid>

Add x and y labels to a pandas plot

For cases where you use pandas.DataFrame.hist:

plt = df.Column_A.hist(bins=10)

Note that you get an ARRAY of plots, rather than a plot. Thus to set the x label you will need to do something like this

plt[0][0].set_xlabel("column A")

How to print an unsigned char in C?

Declare your ch as

unsigned char ch = 212 ;

And your printf will work.

Redirect using AngularJS

If you need to redirect out of your angular application use $window.location. That was my case; hopefully someone will find it useful.

Formatting ISODate from Mongodb

// from MongoDate object to Javascript Date object

var MongoDate = {sec: 1493016016, usec: 650000};
var dt = new Date("1970-01-01T00:00:00+00:00");
    dt.setSeconds(MongoDate.sec);

count files in specific folder and display the number into 1 cel

Try below code :

Assign the path of the folder to variable FolderPath before running the below code.

Sub sample()

    Dim FolderPath As String, path As String, count As Integer
    FolderPath = "C:\Documents and Settings\Santosh\Desktop"

    path = FolderPath & "\*.xls"

    Filename = Dir(path)

    Do While Filename <> ""
       count = count + 1
        Filename = Dir()
    Loop

    Range("Q8").Value = count
    'MsgBox count & " : files found in folder"
End Sub

Spring @Autowired and @Qualifier

@Autowired to autowire(or search) by-type
@Qualifier to autowire(or search) by-name
Other alternate option for @Qualifier is @Primary

@Component
@Qualifier("beanname")
public class A{}

public class B{

//Constructor
@Autowired  
public B(@Qualifier("beanname")A a){...} //  you need to add @autowire also 

//property
@Autowired
@Qualifier("beanname")
private A a;

}

//If you don't want to add the two annotations, we can use @Resource
public class B{

//property
@Resource(name="beanname")
private A a;

//Importing properties is very similar
@Value("${property.name}")  //@Value know how to interpret ${}
private String name;
}

more about @value

while EOF in JAVA?

you should use while (fileReader.hasNextLine())

Invalid default value for 'create_date' timestamp field

I try to set type of column as 'timestamp' and it works for me.

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type

HttpClient webClient = new HttpClient();
Uri uri = new Uri("your url");
HttpResponseMessage response = await webClient.GetAsync(uri)
var jsonString = await response.Content.ReadAsStringAsync();
var objData = JsonConvert.DeserializeObject<List<CategoryModel>>(jsonString);

How to get a list of images on docker registry v2

I had to do the same here and the above works except I had to provide login details as it was a local docker repository.

It is as per the above but with supplying the username/password in the URL.

curl -k -X GET https://yourusername:yourpassword@theregistryURL/v2/_catalog

It comes back as unformatted JSON.

I piped it through the python formatter for ease of human reading, in case you would like to have it in this format.

curl -k -X GET https://yourusername:yourpassword@theregistryURL/v2/_catalog | python -m json.tool

How to detect incoming calls, in an Android device?

@Gabe Sechan, thanks for your code. It works fine except the onOutgoingCallEnded(). It is never executed. Testing phones are Samsung S5 & Trendy. There are 2 bugs I think.

1: a pair of brackets is missing.

case TelephonyManager.CALL_STATE_IDLE: 
    // Went to idle-  this is the end of a call.  What type depends on previous state(s)
    if (lastState == TelephonyManager.CALL_STATE_RINGING) {
        // Ring but no pickup-  a miss
        onMissedCall(context, savedNumber, callStartTime);
    } else {
        // this one is missing
        if(isIncoming){
            onIncomingCallEnded(context, savedNumber, callStartTime, new Date());                       
        } else {
            onOutgoingCallEnded(context, savedNumber, callStartTime, new Date());                                               
        }
    }
    // this one is missing
    break;

2: lastState is not updated by the state if it is at the end of the function. It should be replaced to the first line of this function by

public void onCallStateChanged(Context context, int state, String number) {
    int lastStateTemp = lastState;
    lastState = state;
    // todo replace all the "lastState" by lastStateTemp from here.
    if (lastStateTemp  == state) {
        //No change, debounce extras
        return;
    }
    //....
}

Additional I've put lastState and savedNumber into shared preference as you suggested.

Just tested it with above changes. Bug fixed at least on my phones.

exporting multiple modules in react.js

You can have only one default export which you declare like:

export default App; or export default class App extends React.Component {...

and later do import App from './App'

If you want to export something more you can use named exports which you declare without default keyword like:

export {
  About,
  Contact,
}

or:

export About;
export Contact;

or:

export const About = class About extends React.Component {....
export const Contact = () => (<div> ... </div>);

and later you import them like:

import App, { About, Contact } from './App';

EDIT:

There is a mistake in the tutorial as it is not possible to make 3 default exports in the same main.js file. Other than that why export anything if it is no used outside the file?. Correct main.js :

import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, Link, browserHistory, IndexRoute  } from 'react-router'

class App extends React.Component {
...
}

class Home extends React.Component {
...
}


class About extends React.Component {
...
}


class Contact extends React.Component {
...
}


ReactDOM.render((
   <Router history = {browserHistory}>
      <Route path = "/" component = {App}>
         <IndexRoute component = {Home} />
         <Route path = "home" component = {Home} />
         <Route path = "about" component = {About} />
         <Route path = "contact" component = {Contact} />
      </Route>
   </Router>

), document.getElementById('app'))

EDIT2:

another thing is that this tutorial is based on react-router-V3 which has different api than v4.

How to use pip on windows behind an authenticating proxy

I had a similar issue, and found that my company uses NTLM proxy authentication. If you see this error in your pip.log, this is probably the issue:

Could not fetch URL http://pypi.python.org/simple/pyreadline: HTTP Error 407: Proxy Authentication Required ( The ISA Server requires authorization to fulfill the request. Access to the Web Proxy filter is denied. )

NTLMaps can be used to interface with the NTLM proxy server by becoming an intermediate proxy.

Download NTLMAPs, update the included server.cfg, run the main.py file, then point pip's proxy setting to 127.0.0.1:.

I also needed to change these default values in the server.cfg file to:

LM_PART:1
NT_PART:1

# Highly experimental option. See research.txt for details.
# LM - 06820000
# NT - 05820000
# LM + NT - 
NTLM_FLAGS: 07820000

http://ntlmaps.sourceforge.net/

How to change JAVA.HOME for Eclipse/ANT

If you are using Eclipse, try the following:

  • Right click on the ant build file, then choose "Properties".
  • Click on the "Run/Debug Settings", then click on the launch configuration file. You should be able to edit it then.
  • After you click "Edit", you should see a new window with a "Properties" tab which will show you a list of Ant build properties. There is a "java.home" property in the list. Make sure it refers to the correct path.

Pass a data.frame column name to a function

With dplyr it's now also possible to access a specific column of a dataframe by simply using double curly braces {{...}} around the desired column name within the function body, e.g. for col_name:

library(tidyverse)

fun <- function(df, col_name){
   df %>% 
     filter({{col_name}} == "test_string")
} 

Disable Enable Trigger SQL server for a table

Below is the simplest way

Try the code

ALTER TRIGGER trigger_name DISABLE

That's it :)

Vim autocomplete for Python

I ran into this on my Mac using the MacPorts vim with +python. Problem was that the MacPorts vim will only bind to python 2.5 with +python, while my extensions were installed under python 2.7. Installing the extensions using pip-2.5 solved it.

JavaScript: How to get parent element by selector?

Here is simple way to access parent id

document.getElementById("child1").parentNode;

will do the magic for you to access the parent div.

<html>
<head>
</head>
<body id="body">
<script>
function alertAncestorsUntilID() {
var a = document.getElementById("child").parentNode;
alert(a.id);
}
</script>
<div id="master">
Master
<div id="child">Child</div>
</div>
<script>
alertAncestorsUntilID();
</script>
</body>
</html>

What is the canonical way to trim a string in Ruby without creating a new string?

If you want to use another method after you need something like this:

( str.strip || str ).split(',')

This way you can strip and still do something after :)

HTML5 live streaming

Use ffmpeg + ffserver. It works!!! You can get a config file for ffserver from ffmpeg.org and accordingly set the values.

Accessing localhost of PC from USB connected Android mobile device

I've read numerous forums and tried play apps but not found a solution until now.

My scenario I believe is similar to yours, but I will clarify to help others. I have a locally hosted website and web services to be used by my android application. I need to have this working on the road for demonstration with only my laptop and no network connection.

Note: Using my iPhone as a wifi hotspot and connecting both my pc and my android device worked, but the iPhone 4S connection is slow and dropped out regularly.

My solution is as follows:

  • Unplug network cables on PC and turn off wifi.
  • Turn off wifi on android device
  • Connect android to pc via USB
  • Turn on "USB Tethering" in the android menu. (Under networks->more...->Tethering and portable hotspot")
  • Get the IP of your computer that has been assigned by the USB tether cable. (open command prompt and type "ipconfig" then look for the IP that the USB network adapter has assigned)
  • Open a browser on the PC using the IP address found instead of localhost to test. i.e. http://192.168.1.1/myWebSite
  • Open a browser on the android and test it works

The application may be doing too much work on its main thread

My app had same problem. But it was not doing other than displaying list of cards and text on it. Nothing running in background. But then after some investigation found that the image set for card background was causing this, even though it was small(350kb). Then I converted the image to 9patch images using http://romannurik.github.io/AndroidAssetStudio/index.html.
This worked for me.

Format datetime to YYYY-MM-DD HH:mm:ss in moment.js

Use different format or pattern to get the information from the date

_x000D_
_x000D_
var myDate = new Date("2015-06-17 14:24:36");_x000D_
console.log(moment(myDate).format("YYYY-MM-DD HH:mm:ss"));_x000D_
console.log("Date: "+moment(myDate).format("YYYY-MM-DD"));_x000D_
console.log("Year: "+moment(myDate).format("YYYY"));_x000D_
console.log("Month: "+moment(myDate).format("MM"));_x000D_
console.log("Month: "+moment(myDate).format("MMMM"));_x000D_
console.log("Day: "+moment(myDate).format("DD"));_x000D_
console.log("Day: "+moment(myDate).format("dddd"));_x000D_
console.log("Time: "+moment(myDate).format("HH:mm")); // Time in24 hour format_x000D_
console.log("Time: "+moment(myDate).format("hh:mm A"));
_x000D_
<script src="https://momentjs.com/downloads/moment.js"></script>
_x000D_
_x000D_
_x000D_

For more info: https://momentjs.com/docs/#/parsing/string-format/

UNION with WHERE clause

I would make sure you have an index on ColA, and then run both of them and time them. That would give you the best answer.

Change the background color of a pop-up dialog

Use setInverseBackgroundForced(true) on the alert dialog builder to invert the background.

Python loop that also accesses previous and next values

Using a list comprehension, return a 3-tuple with current, previous and next elements:

three_tuple = [(current, 
                my_list[idx - 1] if idx >= 1 else None, 
                my_list[idx + 1] if idx < len(my_list) - 1 else None) for idx, current in enumerate(my_list)]

How can I set the max-width of a table cell using percentages?

According to the definition of max-width in the CSS 2.1 spec, “the effect of 'min-width' and 'max-width' on tables, inline tables, table cells, table columns, and column groups is undefined.” So you cannot directly set max-width on a td element.

If you just want the second column to take up at most 67%, then you can set the width (which is in effect minimum width, for table cells) to 33%, e.g. in the example case

td:first-child { width: 33% ;}

Setting that for both columns won’t work that well, since it tends to make browsers give the columns equal width.

How to reset index in a pandas dataframe?

DataFrame.reset_index is what you're looking for. If you don't want it saved as a column, then do:

df = df.reset_index(drop=True)

If you don't want to reassign:

df.reset_index(drop=True, inplace=True)

How To have Dynamic SQL in MySQL Stored Procedure

I don't believe MySQL supports dynamic sql. You can do "prepared" statements which is similar, but different.

Here is an example:

mysql> PREPARE stmt FROM 
    -> 'select count(*) 
    -> from information_schema.schemata 
    -> where schema_name = ? or schema_name = ?'
;
Query OK, 0 rows affected (0.00 sec)
Statement prepared
mysql> EXECUTE stmt 
    -> USING @schema1,@schema2
+----------+
| count(*) |
+----------+
|        2 |
+----------+
1 row in set (0.00 sec)
mysql> DEALLOCATE PREPARE stmt;

The prepared statements are often used to see an execution plan for a given query. Since they are executed with the execute command and the sql can be assigned to a variable you can approximate the some of the same behavior as dynamic sql.

Here is a good link about this:

Don't forget to deallocate the stmt using the last line!

Good Luck!

Show a child form in the centre of Parent form in C#

Assuming your code is running inside your parent form, then something like this is probably what you're looking for:

loginForm = new SubLogin();
loginForm.StartPosition = FormStartPosition.CenterParent
loginForm.Show(this);

For the record, there's also a Form.CenterToParent() function, if you need to center it after creation for whatever reason too.

Measuring function execution time in R

A slightly nicer way of measuring execution time, is to use the rbenchmark package. This package (easily) allows you to specify how many times to replicate your test and would the relative benchmark should be.

See also a related question at stats.stackexchange

Splitting String and put it on int array

String input = "2,1,3,4,5,10,100";
String[] strings = input.split(",");
int[] numbers = new int[strings.length];
for (int i = 0; i < numbers.length; i++)
{
  numbers[i] = Integer.parseInt(strings[i]);
}
Arrays.sort(numbers);

System.out.println(Arrays.toString(numbers));

ASP.NET document.getElementById('<%=Control.ClientID%>'); returns null

Gotcha!

You have to use RegisterStartupScript instead of RegisterClientScriptBlock

Here My Example.

MasterPage:

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="MasterPage.master.cs"
    Inherits="prueba.MasterPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

    <script type="text/javascript">

        function confirmCallBack() {
            var a = document.getElementById('<%= Page.Master.FindControl("ContentPlaceHolder1").FindControl("Button1").ClientID %>');

            alert(a.value);

        }

    </script>

    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
        </asp:ContentPlaceHolder>
    </div>
    </form>
</body>
</html>

WebForm1.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.Master" AutoEventWireup="true"
    CodeBehind="WebForm1.aspx.cs" Inherits="prueba.WebForm1" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">

</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Button" />
</asp:Content>

WebForm1.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace prueba
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            ClientScript.RegisterStartupScript(this.GetType(), "js", "confirmCallBack();", true);

        }
    }
}

CGRectMake, CGPointMake, CGSizeMake, CGRectZero, CGPointZero is unavailable in Swift

In Swift 3, you can simply use CGPoint.zero or CGRect.zero in place of CGRectZero or CGPointZero.

However, in Swift 4, CGRect.zero and 'CGPoint.zero' will work

scp via java

Like some here, I ended up writing a wrapper around the JSch library.

It's called way-secshell and it is hosted on GitHub:

https://github.com/objectos/way-secshell

// scp myfile.txt localhost:/tmp
File file = new File("myfile.txt");
Scp res = WaySSH.scp()
  .file(file)
  .toHost("localhost")
  .at("/tmp")
  .send();

limit text length in php and provide 'Read more' link

Another method: insert the following in your theme's function.php file.

remove_filter('get_the_excerpt', 'wp_trim_excerpt');
add_filter('get_the_excerpt', 'custom_trim_excerpt');

function custom_trim_excerpt($text) { // Fakes an excerpt if needed
global $post;
if ( '' == $text ) {
$text = get_the_content('');
$text = apply_filters('the_content', $text);
$text = str_replace(']]>', ']]>', $text);
$text = strip_tags($text);
$excerpt_length = x;
$words = explode(' ', $text, $excerpt_length + 1);
if (count($words) > $excerpt_length) {
array_pop($words);
array_push($words, '...');
$text = implode(' ', $words);
}
}
return $text;
}

You can use this.

Reset select2 value and show placeholder

The only thing can work for me is:

$('select2element').val(null).trigger("change")

I'm using version 4.0.3

Reference

According to Select2 Documentation

How do I publish a UDP Port on Docker?

Use the -p flag and add /udp suffix to the port number.

-p 53160:53160/udp

Full command

sudo docker run -p 53160:53160 \
    -p 53160:53160/udp -p 58846:58846 \ 
    -p 8112:8112 -t -i aostanin/deluge /start.sh

If you're running boot2docker on Mac, be sure to forward the same ports on boot2docker to your local machine.

You can also document that your container needs to receive UDP using EXPOSE in The Dockerfile (EXPOSE does not publish the port):

EXPOSE 8285/udp

Here is a link with more Docker Networking info covered in the container docs: https://docs.docker.com/config/containers/container-networking/ (Courtesy of Old Pro in the comments)

Finding longest string in array

A new answer to an old question: in ES6 you can do shorter:

Math.max(...(x.map(el => el.length)));

Argparse optional positional arguments?

parser.add_argument also has a switch required. You can use required=False. Here is a sample snippet with Python 2.7:

parser = argparse.ArgumentParser(description='get dir')
parser.add_argument('--dir', type=str, help='dir', default=os.getcwd(), required=False)
args = parser.parse_args()

Case insensitive access for generic dictionary

There's no way to specify a StringComparer at the point where you try to get a value. If you think about it, "foo".GetHashCode() and "FOO".GetHashCode() are totally different so there's no reasonable way you could implement a case-insensitive get on a case-sensitive hash map.

You can, however, create a case-insensitive dictionary in the first place using:-

var comparer = StringComparer.OrdinalIgnoreCase;
var caseInsensitiveDictionary = new Dictionary<string, int>(comparer);

Or create a new case-insensitive dictionary with the contents of an existing case-sensitive dictionary (if you're sure there are no case collisions):-

var oldDictionary = ...;
var comparer = StringComparer.OrdinalIgnoreCase;
var newDictionary = new Dictionary<string, int>(oldDictionary, comparer);

This new dictionary then uses the GetHashCode() implementation on StringComparer.OrdinalIgnoreCase so comparer.GetHashCode("foo") and comparer.GetHashcode("FOO") give you the same value.

Alternately, if there are only a few elements in the dictionary, and/or you only need to lookup once or twice, you can treat the original dictionary as an IEnumerable<KeyValuePair<TKey, TValue>> and just iterate over it:-

var myKey = ...;
var myDictionary = ...;
var comparer = StringComparer.OrdinalIgnoreCase;
var value = myDictionary.FirstOrDefault(x => String.Equals(x.Key, myKey, comparer)).Value;

Or if you prefer, without the LINQ:-

var myKey = ...;
var myDictionary = ...;
var comparer = StringComparer.OrdinalIgnoreCase;
int? value;
foreach (var element in myDictionary)
{
  if (String.Equals(element.Key, myKey, comparer))
  {
    value = element.Value;
    break;
  }
}

This saves you the cost of creating a new data structure, but in return the cost of a lookup is O(n) instead of O(1).

get UTC timestamp in python with datetime

If input datetime object is in UTC:

>>> dt = datetime(2008, 1, 1, 0, 0, 0, 0)
>>> timestamp = (dt - datetime(1970, 1, 1)).total_seconds()
1199145600.0

Note: it returns float i.e., microseconds are represented as fractions of a second.

If input date object is in UTC:

>>> from datetime import date
>>> utc_date = date(2008, 1, 1)
>>> timestamp = (utc_date.toordinal() - date(1970, 1, 1).toordinal()) * 24*60*60
1199145600

See more details at Converting datetime.date to UTC timestamp in Python.

XPath - Difference between node() and text()

text() and node() are node tests, in XPath terminology (compare).

Node tests operate on a set (on an axis, to be exact) of nodes and return the ones that are of a certain type. When no axis is mentioned, the child axis is assumed by default.

There are all kinds of node tests:

  • node() matches any node (the least specific node test of them all)
  • text() matches text nodes only
  • comment() matches comment nodes
  • * matches any element node
  • foo matches any element node named "foo"
  • processing-instruction() matches PI nodes (they look like <?name value?>).
  • Side note: The * also matches attribute nodes, but only along the attribute axis. @* is a shorthand for attribute::*. Attributes are not part of the child axis, that's why a normal * does not select them.

This XML document:

<produce>
    <item>apple</item>
    <item>banana</item>
    <item>pepper</item>
</produce>

represents the following DOM (simplified):

root node
   element node (name="produce")
      text node (value="\n    ")
      element node (name="item")
         text node (value="apple")
      text node (value="\n    ")
      element node (name="item")
         text node (value="banana")
      text node (value="\n    ")
      element node (name="item")
         text node (value="pepper")
      text node (value="\n")

So with XPath:

  • / selects the root node
  • /produce selects a child element of the root node if it has the name "produce" (This is called the document element; it represents the document itself. Document element and root node are often confused, but they are not the same thing.)
  • /produce/node() selects any type of child node beneath /produce/ (i.e. all 7 children)
  • /produce/text() selects the 4 (!) whitespace-only text nodes
  • /produce/item[1] selects the first child element named "item"
  • /produce/item[1]/text() selects all child text nodes (there's only one - "apple" - in this case)

And so on.

So, your questions

  • "Select the text of all items under produce" /produce/item/text() (3 nodes selected)
  • "Select all the manager nodes in all departments" //department/manager (1 node selected)

Notes

  • The default axis in XPath is the child axis. You can change the axis by prefixing a different axis name. For example: //item/ancestor::produce
  • Element nodes have text values. When you evaluate an element node, its textual contents will be returned. In case of this example, /produce/item[1]/text() and string(/produce/item[1]) will be the same.
  • Also see this answer where I outline the individual parts of an XPath expression graphically.

Referenced Project gets "lost" at Compile Time

Make sure that both projects have same target framework version here: right click on project -> properties -> application (tab) -> target framework

Also, make sure that the project "logger" (which you want to include in the main project) has the output type "Class Library" in: right click on project -> properties -> application (tab) -> output type

Finally, Rebuild the solution.

How to write a:hover in inline CSS?

Inline pseudoclass declarations aren't supported in the current iteration of CSS (though, from what I understand, it may come in a future version).

For now, your best bet is probably to just define a style block directly above the link you want to style:

<style type="text/css">
    .myLinkClass:hover {text-decoration:underline;}
</style>
<a href="/foo" class="myLinkClass">Foo!</a>

How to get HTML 5 input type="date" working in Firefox and/or IE 10

It is in Firefox since version 51 (January 26, 2017), but it is not activated by default (yet)

To activate it:

about:config

dom.forms.datetime -> set to true

https://developer.mozilla.org/en-US/Firefox/Experimental_features

Cannot start GlassFish 4.1 from within Netbeans 8.0.1 Service area

I also had this problem, it is because there is an application LISTENING to 8080 port. To solve this problem I followed the below steps:

  1. Open cmd.exe then type

    netstat -aon | find ":8080" | find "LISTENING"

  2. You will see like this result

    TCP 0.0.0.0:8080 0.0.0.0:0 LISTENING 1464

  3. Copy PID "1464".

  4. Open Task Manager (Ctrl+Alt+del), go to the details tag, then find the program or service via PID that is listening to the port 8080 then STOP it or End process.

How do I make a WinForms app go Full Screen

You can use the following code to fit your system screen and task bar is visible.

    private void Form1_Load(object sender, EventArgs e)
    {   
        // hide max,min and close button at top right of Window
        this.FormBorderStyle = FormBorderStyle.None;
        // fill the screen
        this.Bounds = Screen.PrimaryScreen.Bounds;
    }

No need to use:

    this.TopMost = true;

That line interferes with alt+tab to switch to other application. ("TopMost" means the window stays on top of other windows, unless they are also marked "TopMost".)

Create a <ul> and fill it based on a passed array

What are disadvantages of the following solution? Seems to be faster and shorter.

var options = {
    set0: ['Option 1','Option 2'],
    set1: ['First Option','Second Option','Third Option']
};

var list = "<li>" + options.set0.join("</li><li>") + "</li>";
document.getElementById("list").innerHTML = list;

intelliJ IDEA 13 error: please select Android SDK

I faced the problem in IntelliJ Idea 14 actually. My project was working fine on Android Studio. I decided to continue development on IntelliJ idea. After import of project, I wasn't successful to RUN it and I got similar error message in Edit Configuration box. Based on What @Ali said, I deleted all my SDKs and reinstalled them again but didn't work.

I opened "Project Structure">"Platform Settings">SDKs. I found "Build target" of "Android API 21 Platform" is not set. By set it to one of my latest SDK the problem fixed and I could run project without problem.

What is the iOS 6 user agent string?

Some more:

Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_3 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B329 Safari/8536.25

Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_4 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B350 Safari/8536.25

JavaScript operator similar to SQL "like"

No there isn't, but you can check out indexOf as a starting point to developing your own, and/or look into regular expressions. It would be a good idea to familiarise yourself with the JavaScript string functions.

EDIT: This has been answered before:

Emulating SQL LIKE in JavaScript

How can I give eclipse more memory than 512M?

Configuring this worked for me: -vmargs -Xms1536m -Xmx2048m -XX:MaxPermSize=1024m on Eclipse Java Photon June 2018

Running Windows 10, 8 GB ram and 64 bit. You can extend -Xmx2048 -XX:MaxpermSize= 1024m to 4096m too, if your computer has good ram.Mine worked well.

How to scale images to screen size in Pygame

You can scale the image with pygame.transform.scale:

import pygame
picture = pygame.image.load(filename)
picture = pygame.transform.scale(picture, (1280, 720))

You can then get the bounding rectangle of picture with

rect = picture.get_rect()

and move the picture with

rect = rect.move((x, y))
screen.blit(picture, rect)

where screen was set with something like

screen = pygame.display.set_mode((1600, 900))

To allow your widgets to adjust to various screen sizes, you could make the display resizable:

import os
import pygame
from pygame.locals import *

pygame.init()
screen = pygame.display.set_mode((500, 500), HWSURFACE | DOUBLEBUF | RESIZABLE)
pic = pygame.image.load("image.png")
screen.blit(pygame.transform.scale(pic, (500, 500)), (0, 0))
pygame.display.flip()
while True:
    pygame.event.pump()
    event = pygame.event.wait()
    if event.type == QUIT:
        pygame.display.quit()
    elif event.type == VIDEORESIZE:
        screen = pygame.display.set_mode(
            event.dict['size'], HWSURFACE | DOUBLEBUF | RESIZABLE)
        screen.blit(pygame.transform.scale(pic, event.dict['size']), (0, 0))
        pygame.display.flip()

CSS full screen div with text in the middle

The accepted answer works, but if:

  • you don't know the content's dimensions
  • the content is dynamic
  • you want to be future proof

use this:

.centered {
  position: fixed; /* or absolute */
  top: 50%;
  left: 50%;
  /* bring your own prefixes */
  transform: translate(-50%, -50%);
}

More information about centering content in this excellent CSS-Tricks article.


Also, if you don't need to support old browsers: a flex-box makes this a piece of cake:

.center{
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
}

Another great guide about flexboxs from CSS Tricks; http://css-tricks.com/snippets/css/a-guide-to-flexbox/

How to check a radio button with jQuery?

In addition, you can check if the element is checked or not:

if ($('.myCheckbox').attr('checked'))
{
   //do others stuff
}
else
{
   //do others stuff
}

You can checked for unchecked element:

$('.myCheckbox').attr('checked',true) //Standards way

You can also uncheck this way:

$('.myCheckbox').removeAttr('checked')

You can checked for radio button:

For versions of jQuery equal or above (>=) 1.6, use:

$("#radio_1").prop("checked", true);

For versions prior to (<) 1.6, use:

$("#radio_1").attr('checked', 'checked');

How can I count occurrences with groupBy?

If you're open to using a third-party library, you can use the Collectors2 class in Eclipse Collections to convert the List to a Bag using a Stream. A Bag is a data structure that is built for counting.

Bag<String> counted =
        list.stream().collect(Collectors2.countBy(each -> each));

Assert.assertEquals(1, counted.occurrencesOf("World"));
Assert.assertEquals(2, counted.occurrencesOf("Hello"));

System.out.println(counted.toStringOfItemToCount());

Output:

{World=1, Hello=2}

In this particular case, you can simply collect the List directly into a Bag.

Bag<String> counted = 
        list.stream().collect(Collectors2.toBag());

You can also create the Bag without using a Stream by adapting the List with the Eclipse Collections protocols.

Bag<String> counted = Lists.adapt(list).countBy(each -> each);

or in this particular case:

Bag<String> counted = Lists.adapt(list).toBag();

You could also just create the Bag directly.

Bag<String> counted = Bags.mutable.with("Hello", "Hello", "World");

A Bag<String> is like a Map<String, Integer> in that it internally keeps track of keys and their counts. But, if you ask a Map for a key it doesn't contain, it will return null. If you ask a Bag for a key it doesn't contain using occurrencesOf, it will return 0.

Note: I am a committer for Eclipse Collections.

Best data type to store money values in MySQL

We use double.

*gasp*

Why?

Because it can represent any 15 digit number with no constraints on where the decimal point is. All for a measly 8 bytes!

So it can represent:

  • 0.123456789012345
  • 123456789012345.0

...and anything in between.

This is useful because we're dealing with global currencies, and double can store the various numbers of decimal places we'll likely encounter.

A single double field can represent 999,999,999,999,999s in Japanese yens, 9,999,999,999,999.99s in US dollars and even 9,999,999.99999999s in bitcoins

If you try doing the same with decimal, you need decimal(30, 15) which costs 14 bytes.

Caveats

Of course, using double isn't without caveats.

However, it's not loss of accuracy as some tend to point out. Even though double itself may not be internally exact to the base 10 system, we can make it exact by rounding the value we pull from the database to its significant decimal places. If needed that is. (e.g. If it's going to be outputted, and base 10 representation is required.)

The caveats are, any time we perform arithmetic with it, we need to normalize the result (by rounding it to its significant decimal places) before:

  1. Performing comparisons on it.
  2. Writing it back to the database.

Another kind of caveat is, unlike decimal(m, d) where the database will prevent programs from inserting a number with more than m digits, no such validations exists with double. A program could insert a user inputted value of 20 digits and it'll end up being silently recorded as an inaccurate amount.

React-Router open Link in new tab

In React Router version 5.0.1 and above, you can use:

<Link to="route" target="_blank" onClick={(event) => {event.preventDefault(); window.open(this.makeHref("route"));}} />

SQL WHERE.. IN clause multiple columns

You can make a derived table from the subquery, and join table1 to this derived table:

select * from table1 LEFT JOIN 
(
   Select CM_PLAN_ID, Individual_ID
   From CRM_VCM_CURRENT_LEAD_STATUS
   Where Lead_Key = :_Lead_Key
) table2
ON 
   table1.CM_PLAN_ID=table2.CM_PLAN_ID
   AND table1.Individual=table2.Individual
WHERE table2.CM_PLAN_ID IS NOT NULL

Use success() or complete() in AJAX call

Well, speaking from quarantine, the complete() in $.ajax is like finally in try catch block.

If you use try catch block in any programming language, it doesn't matter whether you execute a thing successfully or got an error in execution. the finally{} block will always be executed.

Same goes for complete() in $.ajax, whether you get success() response or error() the complete() function always will be called once the execution has been done.

How to request a random row in SQL?

I have to agree with CD-MaN: Using "ORDER BY RAND()" will work nicely for small tables or when you do your SELECT only a few times.

I also use the "num_value >= RAND() * ..." technique, and if I really want to have random results I have a special "random" column in the table that I update once a day or so. That single UPDATE run will take some time (especially because you'll have to have an index on that column), but it's much faster than creating random numbers for every row each time the select is run.

Accessing all items in the JToken

If you know the structure of the json that you're receiving then I'd suggest having a class structure that mirrors what you're receiving in json.

Then you can call its something like this...

AddressMap addressMap = JsonConvert.DeserializeObject<AddressMap>(json);

(Where json is a string containing the json in question)

If you don't know the format of the json you've receiving then it gets a bit more complicated and you'd probably need to manually parse it.

check out http://www.hanselman.com/blog/NuGetPackageOfTheWeek4DeserializingJSONWithJsonNET.aspx for more info

Run bash command on jenkins pipeline

For multi-line shell scripts or those run multiple times, I would create a new bash script file (starting from #!/bin/bash), and simply run it with sh from Jenkinsfile:

sh 'chmod +x ./script.sh'
sh './script.sh'

Django ChoiceField

New method in Django 3

you can use Field.choices Enumeration Types new update in django3 like this :

from django.db import models

class Status(models.TextChoices):
    UNPUBLISHED = 'UN', 'Unpublished'
    PUBLISHED = 'PB', 'Published'


class Book(models.Model):
    status = models.CharField(
        max_length=2,
        choices=Status.choices,
        default=Status.UNPUBLISHED,
    )

django docs

String parsing in Java with delimiter tab "\t" using split

Try this:

String[] columnDetail = column.split("\t", -1);

Read the Javadoc on String.split(java.lang.String, int) for an explanation about the limit parameter of split function:

split

public String[] split(String regex, int limit)
Splits this string around matches of the given regular expression.
The array returned by this method contains each substring of this string that is terminated by another substring that matches the given expression or is terminated by the end of the string. The substrings in the array are in the order in which they occur in this string. If the expression does not match any part of the input then the resulting array has just one element, namely this string.

The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter. If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.

The string "boo:and:foo", for example, yields the following results with these parameters:

Regex   Limit   Result
:   2   { "boo", "and:foo" }
:   5   { "boo", "and", "foo" }
:   -2  { "boo", "and", "foo" }
o   5   { "b", "", ":and:f", "", "" }
o   -2  { "b", "", ":and:f", "", "" }
o   0   { "b", "", ":and:f" }

When the last few fields (I guest that's your situation) are missing, you will get the column like this:

field1\tfield2\tfield3\t\t

If no limit is set to split(), the limit is 0, which will lead to that "trailing empty strings will be discarded". So you can just get just 3 fields, {"field1", "field2", "field3"}.

When limit is set to -1, a non-positive value, trailing empty strings will not be discarded. So you can get 5 fields with the last two being empty string, {"field1", "field2", "field3", "", ""}.

Regular Expression to match valid dates

Maintainable Perl 5.10 version

/
  (?:
      (?<month> (?&mon_29)) [\/] (?<day>(?&day_29))
    | (?<month> (?&mon_30)) [\/] (?<day>(?&day_30))
    | (?<month> (?&mon_31)) [\/] (?<day>(?&day_31))
  )
  [\/]
  (?<year> [0-9]{4})
  
  (?(DEFINE)
    (?<mon_29> 0?2 )
    (?<mon_30> 0?[469]   | (11) )
    (?<mon_31> 0?[13578] | 1[02] )

    (?<day_29> 0?[1-9] | [1-2]?[0-9] )
    (?<day_30> 0?[1-9] | [1-2]?[0-9] | 30 )
    (?<day_31> 0?[1-9] | [1-2]?[0-9] | 3[01] )
  )
/x

You can retrieve the elements by name in this version.

say "Month=$+{month} Day=$+{day} Year=$+{year}";

( No attempt has been made to restrict the values for the year. )

How to get names of classes inside a jar file?

You can try:

jar tvf jarfile.jar 

This will be helpful only if your jar is executable i.e. in manifest you have defined some class as main class

Redirect after Login on WordPress

The accepted answer is clearly not a good answer! It may solve your problem for a while, but what will happen next time you update your WordPress installation? Your core files may get overridden and you will loose all your modifications.

As already stated by others (Dan and Travis answers), the correct answer is to use the login_redirect filter.

Excluding directory when creating a .tar.gz file

This worked for me:

tar -zcvf target.tar.gz target/ --exclude="target/backups" --exclude="target/cache"

How can I split a text file using PowerShell?

Many of these answers were too slow for my source files. My source files were SQL files between 10 MB and 800 MB that needed to split into files of roughly equal line counts.

I found some of the previous answers which use Add-Content to be quite slow. Waiting many hours for a split to finish wasn't uncommon.

I didn't try Typhlosaurus's answer, but it looks to only do splits by file size, not line count.

The following has suited my purposes.

$sw = new-object System.Diagnostics.Stopwatch
$sw.Start()
Write-Host "Reading source file..."
$lines = [System.IO.File]::ReadAllLines("C:\Temp\SplitTest\source.sql")
$totalLines = $lines.Length

Write-Host "Total Lines :" $totalLines

$skip = 0
$count = 100000; # Number of lines per file

# File counter, with sort friendly name
$fileNumber = 1
$fileNumberString = $filenumber.ToString("000")

while ($skip -le $totalLines) {
    $upper = $skip + $count - 1
    if ($upper -gt ($lines.Length - 1)) {
        $upper = $lines.Length - 1
    }

    # Write the lines
    [System.IO.File]::WriteAllLines("C:\Temp\SplitTest\result$fileNumberString.txt",$lines[($skip..$upper)])

    # Increment counters
    $skip += $count
    $fileNumber++
    $fileNumberString = $filenumber.ToString("000")
}

$sw.Stop()

Write-Host "Split complete in " $sw.Elapsed.TotalSeconds "seconds"

For a 54 MB file, I get the output...

Reading source file...
Total Lines : 910030
Split complete in  1.7056578 seconds

I hope others looking for a simple, line-based splitting script that matches my requirements will find this useful.

How do I turn off the mysql password validation?

Building on the answer from Sharfi, edit the /etc/my.cnf file and add just this one line:

validate_password_policy=LOW

That should sufficiently neuter the validation as requested by the OP. You will probably want to restart mysqld after this change. Depending on your OS, it would look something like:

sudo service mysqld restart

validate_password_policy takes either values 0, 1, or 2 or words LOW, MEDIUM, and STRONG which correspond to those numbers. The default is MEDIUM (1) which requires passwords contain at least one upper case letter, one lower case letter, one digit, and one special character, and that the total password length is at least 8 characters. Changing to LOW as I suggest here then only will check for length, which if it hasn't been changed through other parameters will check for a length of 8. If you wanted to shorten that length limit too, you could also add validate_password_length in to the my.cnf file.

For more info about the levels and details, see the mysql doc.


For MySQL 8, the property has changed from "validate_password_policy" to "validate_password.policy". See the updated mysql doc for the latest info.

ArrayList of int array in java

java.util.Arrays.toString() converts Java arrays to a string:

System.out.println("Arraylist contains:"+Arrays.toString(arl.get(0)));

Laravel 5 call a model function in a blade view

want to use model in view as:

{{ Product::find($id) }}

you can use in view:

<?php
$tmp = \App\Product::find($id);
?>
{{ $tmp->name }}

Hope this will help you

Install a Nuget package in Visual Studio Code

The answers above are good, but insufficient if you have more than 1 project (.csproj) in the same folder.

First, you easily add the "PackageReference" tag to the .csproj file (either manually, by using the nuget package manager or by using the dotnet add package command).

But then, you need to run the "restore" command manually so you can tell it which project you are trying to restore (if I just clicked the restore button that popped up, nothing happened). You can do that by running:

dotnet restore Project-File-Name.csproj

And that installs the package

Calling Objective-C method from C++ member function?

Step 1

Create a objective c file(.m file) and it's corresponding header file.

// Header file (We call it "ObjCFunc.h")

#ifndef test2_ObjCFunc_h
#define test2_ObjCFunc_h
@interface myClass :NSObject
-(void)hello:(int)num1;
@end
#endif

// Corresponding Objective C file(We call it "ObjCFunc.m")

#import <Foundation/Foundation.h>
#include "ObjCFunc.h"
@implementation myClass
//Your objective c code here....
-(void)hello:(int)num1
{
NSLog(@"Hello!!!!!!");
}
@end

Step 2

Now we will implement a c++ function to call the objective c function that we just created! So for that we will define a .mm file and its corresponding header file(".mm" file is to be used here because we will be able to use both Objective C and C++ coding in the file)

//Header file(We call it "ObjCCall.h")

#ifndef __test2__ObjCCall__
#define __test2__ObjCCall__
#include <stdio.h>
class ObjCCall
{
public:
static void objectiveC_Call(); //We define a static method to call the function directly using the class_name
};
#endif /* defined(__test2__ObjCCall__) */

//Corresponding Objective C++ file(We call it "ObjCCall.mm")

#include "ObjCCall.h"
#include "ObjCFunc.h"
void ObjCCall::objectiveC_Call()
{
//Objective C code calling.....
myClass *obj=[[myClass alloc]init]; //Allocating the new object for the objective C   class we created
[obj hello:(100)];   //Calling the function we defined
}

Step 3

Calling the c++ function(which actually calls the objective c method)

#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__
#include "cocos2d.h"
#include "ObjCCall.h"
class HelloWorld : public cocos2d::Layer
{
public:
// there's no 'id' in cpp, so we recommend returning the class instance pointer
static cocos2d::Scene* createScene();
// Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning  'id' in cocos2d-iphone
virtual bool init();
// a selector callback
void menuCloseCallback(cocos2d::Ref* pSender);
void ObCCall();  //definition
// implement the "static create()" method manually
CREATE_FUNC(HelloWorld);
};
#endif // __HELLOWORLD_SCENE_H__

//Final call

#include "HelloWorldScene.h"
#include "ObjCCall.h"
USING_NS_CC;
Scene* HelloWorld::createScene()
{
// 'scene' is an autorelease object
auto scene = Scene::create();
// 'layer' is an autorelease object
auto layer = HelloWorld::create();
// add layer as a child to scene
scene->addChild(layer);
// return the scene
return scene;
}
// on "init" you need to initialize your instance
bool HelloWorld::init()
{
//////////////////////////////
// 1. super init first
if ( !Layer::init() )
{
    return false;
}
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();

/////////////////////////////
// 2. add a menu item with "X" image, which is clicked to quit the program
//    you may modify it.

// add a "close" icon to exit the progress. it's an autorelease object
auto closeItem = MenuItemImage::create(
                                       "CloseNormal.png",
                                       "CloseSelected.png",
                                       CC_CALLBACK_1(HelloWorld::menuCloseCallback,  this));

closeItem->setPosition(Vec2(origin.x + visibleSize.width - closeItem->getContentSize().width/2 ,
                            origin.y + closeItem->getContentSize().height/2));

// create menu, it's an autorelease object
auto menu = Menu::create(closeItem, NULL);
menu->setPosition(Vec2::ZERO);
this->addChild(menu, 1);

/////////////////////////////
// 3. add your codes below...

// add a label shows "Hello World"
// create and initialize a label

auto label = Label::createWithTTF("Hello World", "fonts/Marker Felt.ttf", 24);

// position the label on the center of the screen
label->setPosition(Vec2(origin.x + visibleSize.width/2,
                        origin.y + visibleSize.height - label- >getContentSize().height));
// add the label as a child to this layer
this->addChild(label, 1);
// add "HelloWorld" splash screen"
auto sprite = Sprite::create("HelloWorld.png");
// position the sprite on the center of the screen
sprite->setPosition(Vec2(visibleSize.width/2 + origin.x, visibleSize.height/2 +     origin.y));
// add the sprite as a child to this layer
this->addChild(sprite, 0);
this->ObCCall();   //first call
return true;
}
void HelloWorld::ObCCall()  //Definition
{
ObjCCall::objectiveC_Call();  //Final Call  
}
void HelloWorld::menuCloseCallback(Ref* pSender)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) || (CC_TARGET_PLATFORM ==   CC_PLATFORM_WINRT)
MessageBox("You pressed the close button. Windows Store Apps do not implement a close    button.","Alert");
return;
#endif
Director::getInstance()->end();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
exit(0);
#endif
}

Hope this works!

Error: "Adb connection Error:An existing connection was forcibly closed by the remote host"

In my case, resetting ADB didn't make a difference. I also needed to delete my existing virtual devices, which were pretty old, and create new ones.

Select query to get data from SQL Server

you can use ExecuteScalar() in place of ExecuteNonQuery() to get a single result use it like this

Int32 result= (Int32) command.ExecuteScalar();
Console.WriteLine(String.Format("{0}", result));

It will execute the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.

As you want only one row in return, remove this use of SqlDataReader from your code

using (SqlDataReader reader = command.ExecuteReader())
{
    // iterate your results here
    Console.WriteLine(String.Format("{0}",reader["id"]));
}

because it will again execute your command and effect your page performance.

How to remove trailing and leading whitespace for user-provided input in a batch file?

You can also strip whitespace by passing in those variables with whitespace as parameters into a sub and then inside your sub simply set them again with the passed in parameters.

@echo off 
set "a=    apple      "
set "b=     banana    "
echo [%a%]
echo [%b%]
call :Strip %a% %b%
pause
goto :EOF

:Strip
set a=%1
set b=%2
echo [%a%]
echo [%b%]

----------------
Results....
[    apple      ]
[     banana    ]
[apple]
[banana]
Press any key to continue . . .

Python mock multiple return values

You can assign an iterable to side_effect, and the mock will return the next value in the sequence each time it is called:

>>> from unittest.mock import Mock
>>> m = Mock()
>>> m.side_effect = ['foo', 'bar', 'baz']
>>> m()
'foo'
>>> m()
'bar'
>>> m()
'baz'

Quoting the Mock() documentation:

If side_effect is an iterable then each call to the mock will return the next value from the iterable.

How to get C# Enum description from value?

To make this easier to use, I wrote a generic extension:

public static string ToDescription<TEnum>(this TEnum EnumValue) where TEnum : struct
{
    return Enumerations.GetEnumDescription((Enum)(object)((TEnum)EnumValue));
}

now I can write:

        MyEnum my = MyEnum.HereIsAnother;
        string description = my.ToDescription();
        System.Diagnostics.Debug.Print(description);

Note: replace "Enumerations" above with your class name

VBA array sort function?

I posted some code in answer to a related question on StackOverflow:

Sorting a multidimensionnal array in VBA

The code samples in that thread include:

  1. A vector array Quicksort;
  2. A multi-column array QuickSort;
  3. A BubbleSort.

Alain's optimised Quicksort is very shiny: I just did a basic split-and-recurse, but the code sample above has a 'gating' function that cuts down on redundant comparisons of duplicated values. On the other hand, I code for Excel, and there's a bit more in the way of defensive coding - be warned, you'll need it if your array contains the pernicious 'Empty()' variant, which will break your While... Wend comparison operators and trap your code in an infinite loop.

Note that quicksort algorthms - and any recursive algorithm - can fill the stack and crash Excel. If your array has fewer than 1024 members, I'd use a rudimentary BubbleSort.

Public Sub QuickSortArray(ByRef SortArray As Variant, _
                                Optional lngMin As Long = -1, _ 
                                Optional lngMax As Long = -1, _ 
                                Optional lngColumn As Long = 0)
On Error Resume Next
'Sort a 2-Dimensional array
' Sample Usage: sort arrData by the contents of column 3 ' ' QuickSortArray arrData, , , 3
' 'Posted by Jim Rech 10/20/98 Excel.Programming
'Modifications, Nigel Heffernan:
' ' Escape failed comparison with empty variant ' ' Defensive coding: check inputs
Dim i As Long Dim j As Long Dim varMid As Variant Dim arrRowTemp As Variant Dim lngColTemp As Long

If IsEmpty(SortArray) Then Exit Sub End If
If InStr(TypeName(SortArray), "()") < 1 Then 'IsArray() is somewhat broken: Look for brackets in the type name Exit Sub End If
If lngMin = -1 Then lngMin = LBound(SortArray, 1) End If
If lngMax = -1 Then lngMax = UBound(SortArray, 1) End If
If lngMin >= lngMax Then ' no sorting required Exit Sub End If

i = lngMin j = lngMax
varMid = Empty varMid = SortArray((lngMin + lngMax) \ 2, lngColumn)
' We send 'Empty' and invalid data items to the end of the list: If IsObject(varMid) Then ' note that we don't check isObject(SortArray(n)) - varMid might pick up a valid default member or property i = lngMax j = lngMin ElseIf IsEmpty(varMid) Then i = lngMax j = lngMin ElseIf IsNull(varMid) Then i = lngMax j = lngMin ElseIf varMid = "" Then i = lngMax j = lngMin ElseIf varType(varMid) = vbError Then i = lngMax j = lngMin ElseIf varType(varMid) > 17 Then i = lngMax j = lngMin End If

While i <= j
While SortArray(i, lngColumn) < varMid And i < lngMax i = i + 1 Wend
While varMid < SortArray(j, lngColumn) And j > lngMin j = j - 1 Wend

If i <= j Then
' Swap the rows ReDim arrRowTemp(LBound(SortArray, 2) To UBound(SortArray, 2)) For lngColTemp = LBound(SortArray, 2) To UBound(SortArray, 2) arrRowTemp(lngColTemp) = SortArray(i, lngColTemp) SortArray(i, lngColTemp) = SortArray(j, lngColTemp) SortArray(j, lngColTemp) = arrRowTemp(lngColTemp) Next lngColTemp Erase arrRowTemp
i = i + 1 j = j - 1
End If

Wend
If (lngMin < j) Then Call QuickSortArray(SortArray, lngMin, j, lngColumn) If (i < lngMax) Then Call QuickSortArray(SortArray, i, lngMax, lngColumn)

End Sub

How to custom switch button?

However, I might not be taking the best approach, but this is how I have created some Switch like UIs in few of my apps. Here is the code -

<RadioGroup
        android:checkedButton="@+id/offer"
        android:id="@+id/toggle"
        android:layout_width="match_parent"
        android:layout_height="30dp"
        android:layout_marginBottom="@dimen/margin_medium"
        android:layout_marginLeft="50dp"
        android:layout_marginRight="50dp"
        android:layout_marginTop="@dimen/margin_medium"
        android:background="@drawable/pink_out_line"
        android:orientation="horizontal">

        <RadioButton
            android:layout_marginTop="1dp"
            android:layout_marginBottom="1dp"
            android:layout_marginLeft="1dp"
            android:id="@+id/search"
            android:background="@drawable/toggle_widget_background"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:button="@null"
            android:gravity="center"
            android:text="Search"
            android:textColor="@color/white" />

        <RadioButton
            android:layout_marginRight="1dp"
            android:layout_marginTop="1dp"
            android:layout_marginBottom="1dp"
            android:id="@+id/offer"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@drawable/toggle_widget_background"
            android:button="@null"
            android:gravity="center"
            android:text="Offers"
            android:textColor="@color/white" />
    </RadioGroup>

pink_out_line.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners android:radius="2dp" />
    <solid android:color="#80000000" />
    <stroke
        android:width="1dp"
        android:color="@color/pink" />
</shape>

toggle_widget_background.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/pink" android:state_checked="true" />
    <item android:drawable="@color/dark_pink" android:state_pressed="true" />
    <item android:drawable="@color/transparent" />
</selector>

And here is the output -enter image description here

How to remove MySQL completely with config and library files?

Just a little addition to the answer of @dAm2k :

In addition to sudo apt-get remove --purge mysql\*

I've done a sudo apt-get remove --purge mariadb\*.

I seems that in the new release of debian (stretch), when you install mysql it install mariadb package with it.

Hope it helps.

Get name of current script in Python

all that answers are great, but have some problems You might not see at the first glance.

lets define what we want - we want the name of the script that was executed, not the name of the current module - so __file__ will only work if it is used in the executed script, not in an imported module. sys.argv is also questionable - what if your program was called by pytest ? or pydoc runner ? or if it was called by uwsgi ?

and - there is a third method of getting the script name, I havent seen in the answers - You can inspect the stack.

Another problem is, that You (or some other program) can tamper around with sys.argv and __main__.__file__ - it might be present, it might be not. It might be valid, or not. At least You can check if the script (the desired result) exists !

the library lib_programname does exactly that :

  • check if __main__ is present
  • check if __main__.__file__ is present
  • does give __main__.__file__ a valid result (does that script exist ?)
  • if not: check sys.argv:
  • is there pytest, docrunner, etc in the sys.argv ? --> if yes, ignore that
  • can we get a valid result here ?
  • if not: inspect the stack and get the result from there possibly
  • if also the stack does not give a valid result, then throw an Exception.

by that way, my solution is working so far with setup.py test, uwsgi, pytest, pycharm pytest , pycharm docrunner (doctest), dreampie, eclipse

there is also a nice blog article about that problem from Dough Hellman, "Determining the Name of a Process from Python"

BTW, it will change again in python 3.9 : the file attribute of the main module became an absolute path, rather than a relative path. These paths now remain valid after the current directory is changed by os.chdir()

So I rather want to take care of one small module, instead of skimming my codebase if it should be changed somewere ...


Disclaimer: I'm the author of the lib_programname library.

How to use Bootstrap in an Angular project?

An integration with Angular2 is also available through the ng2-bootstrap project : https://github.com/valor-software/ng2-bootstrap.

To install it simply put these files in your main HTML page:

<script src="https://cdnjs.cloudflare.com/ajax/libs/ng2-bootstrap/x.x.x/ng2-bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">

Then you can use it into your components this way:

import {Component} from 'angular2/core';
import {Alert} from 'ng2-bootstrap/ng2-bootstrap';

@Component({
  selector: 'my-app',
  directives: [Alert],
  template: `<alert type="info">ng2-bootstrap hello world!</alert>`
})
export class AppComponent {
}

nginx 502 bad gateway

Try disabling the xcache or apc modules. Seems to cause a problem with some versions are saving objects to a session variable.

Finalize vs Dispose

Others have already covered the difference between Dispose and Finalize (btw the Finalize method is still called a destructor in the language specification), so I'll just add a little about the scenarios where the Finalize method comes in handy.

Some types encapsulate disposable resources in a manner where it is easy to use and dispose of them in a single action. The general usage is often like this: open, read or write, close (Dispose). It fits very well with the using construct.

Others are a bit more difficult. WaitEventHandles for instances are not used like this as they are used to signal from one thread to another. The question then becomes who should call Dispose on these? As a safeguard types like these implement a Finalize method, which makes sure resources are disposed when the instance is no longer referenced by the application.

Bundler::GemNotFound: Could not find rake-10.3.2 in any of the sources

I think rake must be preinstalled if you want work with bundler. Try to install rake via 'gem install' and then run 'bundle install' again:

gem install rake && bundle install

If you are using rvm ( http://rvm.io ) rake is installed by default...

Call Python function from JavaScript code

Communicating through processes

Example:

Python: This python code block should return random temperatures.

# sensor.py

import random, time
while True:
    time.sleep(random.random() * 5)  # wait 0 to 5 seconds
    temperature = (random.random() * 20) - 5  # -5 to 15
    print(temperature, flush=True, end='')

Javascript (Nodejs): Here we will need to spawn a new child process to run our python code and then get the printed output.

// temperature-listener.js

const { spawn } = require('child_process');
const temperatures = []; // Store readings

const sensor = spawn('python', ['sensor.py']);
sensor.stdout.on('data', function(data) {

    // convert Buffer object to Float
    temperatures.push(parseFloat(data));
    console.log(temperatures);
});

Cancel a vanilla ECMAScript 6 Promise chain

I am still working through this idea, but here is how I have implemented a cancellable Promise using setTimeout as an example.

The idea is that a promise is resolved or rejected whenever you have decided it is, so it should be a matter of deciding when you want to cancel, satisfying the criterion, and then calling the reject() function yourself.

  • First, I think there are two reasons to finish a promise early: to get it over and done with (which I have called resolve) and to cancel (which I have called reject). Of course, that’s just my feeling. Of course there is a Promise.resolve() method, but it’s in the constructor itself, and returns a dummy resolved promise. This instance resolve() method actually resolves an instantiated promise object.

  • Second, you can happily add anything you like to a newly created promise object before you return it, and so I have just added resolve() and reject() methods to make it self-contained.

  • Third, the trick is to be able to access the executor resolve and reject functions later, so I have simply stored them in a simple object from within the closure.

I think the solution is simple, and I can’t see any major problems with it.

_x000D_
_x000D_
function wait(delay) {_x000D_
  var promise;_x000D_
  var timeOut;_x000D_
  var executor={};_x000D_
  promise=new Promise(function(resolve,reject) {_x000D_
    console.log(`Started`);_x000D_
    executor={resolve,reject};  //  Store the resolve and reject methods_x000D_
    timeOut=setTimeout(function(){_x000D_
      console.log(`Timed Out`);_x000D_
      resolve();_x000D_
    },delay);_x000D_
  });_x000D_
  //  Implement your own resolve methods,_x000D_
  //  then access the stored methods_x000D_
      promise.reject=function() {_x000D_
        console.log(`Cancelled`);_x000D_
        clearTimeout(timeOut);_x000D_
        executor.reject();_x000D_
      };_x000D_
      promise.resolve=function() {_x000D_
        console.log(`Finished`);_x000D_
        clearTimeout(timeOut);_x000D_
        executor.resolve();_x000D_
      };_x000D_
  return promise;_x000D_
}_x000D_
_x000D_
var promise;_x000D_
document.querySelector('button#start').onclick=()=>{_x000D_
  promise=wait(5000);_x000D_
  promise_x000D_
  .then(()=>console.log('I have finished'))_x000D_
  .catch(()=>console.log('or not'));_x000D_
};_x000D_
document.querySelector('button#cancel').onclick=()=>{ promise.reject(); }_x000D_
document.querySelector('button#finish').onclick=()=>{ promise.resolve(); }
_x000D_
<button id="start">Start</button>_x000D_
<button id="cancel">Cancel</button>_x000D_
<button id="finish">Finish</button>
_x000D_
_x000D_
_x000D_

Read each line of txt file to new array element

    $file = file("links.txt");
print_r($file);

This will be accept the txt file as array. So write anything to the links.txt file (use one line for one element) after, run this page :) your array will be $file

Best way to get user GPS location in background in Android

I have try to my code and got success try this

package com.mobeyosoft.latitudelongitude;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

/**
 * Created by 5943 6417 on 14-09-2016.
 */
public class LocationService extends Service
{
    public static final String BROADCAST_ACTION = "Hello World";
    private static final int TWO_MINUTES = 1000 * 60 * 1;
    public LocationManager locationManager;
    public MyLocationListener listener;
    public Location previousBestLocation = null;

    Context context;

    Intent intent;
    int counter = 0;

    @Override
    public void onCreate() {
        super.onCreate();
        intent = new Intent(BROADCAST_ACTION);
        context=this;
    }

    @Override
    public void onStart(Intent intent, int startId) {
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        listener = new MyLocationListener();
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 4000, 0, listener);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 4000, 0, listener);
    }

    @Override
    public IBinder onBind(Intent intent){
        return null;
    }

    protected boolean isBetterLocation(Location location, Location currentBestLocation) {
        if (currentBestLocation == null) {
            // A new location is always better than no location
            return true;
        }

        // Check whether the new location fix is newer or older
        long timeDelta = location.getTime() - currentBestLocation.getTime();
        boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
        boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
        boolean isNewer = timeDelta > 0;

        // If it's been more than two minutes since the current location, use the new location
        // because the user has likely moved
        if (isSignificantlyNewer) {
            return true;
            // If the new location is more than two minutes older, it must be worse
        } else if (isSignificantlyOlder) {
            return false;
        }

        // Check whether the new location fix is more or less accurate
        int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
        boolean isLessAccurate = accuracyDelta > 0;
        boolean isMoreAccurate = accuracyDelta < 0;
        boolean isSignificantlyLessAccurate = accuracyDelta > 200;

        // Check if the old and new location are from the same provider
        boolean isFromSameProvider = isSameProvider(location.getProvider(),
                currentBestLocation.getProvider());

        // Determine location quality using a combination of timeliness and accuracy
        if (isMoreAccurate) {
            return true;
        } else if (isNewer && !isLessAccurate) {
            return true;
        } else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
            return true;
        }
        return false;
    }



    /** Checks whether two providers are the same */
    private boolean isSameProvider(String provider1, String provider2) {
        if (provider1 == null) {
            return provider2 == null;
        }
        return provider1.equals(provider2);
    }



    @Override
    public void onDestroy() {
        // handler.removeCallbacks(sendUpdatesToUI);
        super.onDestroy();
        Log.v("STOP_SERVICE", "DONE");
        locationManager.removeUpdates(listener);
    }

    public static Thread performOnBackgroundThread(final Runnable runnable) {
        final Thread t = new Thread() {
            @Override
            public void run() {
                try {
                    runnable.run();
                } finally {

                }
            }
        };
        t.start();
        return t;
    }




    public class MyLocationListener implements LocationListener{

        public void onLocationChanged(final Location loc)
        {
            Log.i("**********", "Location changed");
            if(isBetterLocation(loc, previousBestLocation)) {
                loc.getLatitude();
                loc.getLongitude();
                Toast.makeText(context, "Latitude" + loc.getLatitude() + "\nLongitude"+loc.getLongitude(),Toast.LENGTH_SHORT).show();
                intent.putExtra("Latitude", loc.getLatitude());
                intent.putExtra("Longitude", loc.getLongitude());
                intent.putExtra("Provider", loc.getProvider());
                sendBroadcast(intent);

            }
        }

        public void onProviderDisabled(String provider)
        {
            Toast.makeText( getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT ).show();
        }


        public void onProviderEnabled(String provider)
        {
            Toast.makeText( getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show();
        }


        public void onStatusChanged(String provider, int status, Bundle extras)
        {

        }

    }
}

Laravel 5 – Remove Public from URL

1) I haven't found a working method for moving the public directory in L5. While you can modify some things in the bootstrap index.php, it appears several helper functions are based on the assumption of that public directory being there. In all honestly you really shouldn't be moving the public directory.

2) If your using MAMP then you should be creating new vhosts for each project, each serving that projects public directory. Once created you access each project by your defined server name like this :

http://project1.dev
http://project2.dev

Convert DataTable to CSV stream

public void CreateCSVFile(DataTable dt, string strFilePath,string separator)
        {               
            #region Export Grid to CSV
            // Create the CSV file to which grid data will be exported.

            StreamWriter sw = new StreamWriter(strFilePath, false); 
            int iColCount = dt.Columns.Count;
            for (int i = 0; i < iColCount; i++)
            {    
                sw.Write(dt.Columns[i]);    
                if (i < iColCount - 1)
                {
                    sw.Write(separator);
                }  
            }    

            sw.Write(sw.NewLine);

            // Now write all the rows.
            foreach (DataRow dr in dt.Rows)
            {
                for (int i = 0; i < iColCount; i++)
                {
                    if (!Convert.IsDBNull(dr[i]))
                    {
                        sw.Write(dr[i].ToString());  
                    }

                    if (i < iColCount - 1)
                    {
                        sw.Write(separator);
                    }
                }
                sw.Write(sw.NewLine);
            }

            sw.Close();
            #endregion
        }

How to convert a single char into an int

You can utilize the fact that the character encodings for digits are all in order from 48 (for '0') to 57 (for '9'). This holds true for ASCII, UTF-x and practically all other encodings (see comments below for more on this).

Therefore the integer value for any digit is the digit minus '0' (or 48).

char c = '1';
int i = c - '0'; // i is now equal to 1, not '1'

is synonymous to

char c = '1';
int i = c - 48; // i is now equal to 1, not '1'

However I find the first c - '0' far more readable.

Regular expression to match any character being repeated more than 10 times

={10,}

matches = that is repeated 10 or more times.

Checking for a null object in C++

Basically, all I'm trying to do is to prevent the program from crashing when some_cpp_function() is called with NULL.

It is not possible to call the function with NULL. One of the purpose of having the reference, it will point to some object always as you have to initialize it when defining it. Do not think reference as a fancy pointer, think of it as an alias name for the object itself. Then this type of confusion will not arise.

How do I select an element that has a certain class?

h2.myClass is only valid for h2 elements which got the class myClass directly assigned.

Your want to note it like this:

.myClass h2

Which selects all children of myClass which have the tagname h2

Find oldest/youngest datetime object in a list

Datetimes are comparable; so you can use max(datetimes_list) and min(datetimes_list)

Add Insecure Registry to Docker

Creating /etc/docker/daemon.json file and adding the below content and then doing a docker restart on CentOS 7 resolved the issue.

{
    "insecure-registries" : [ "hostname.cloudapp.net:5000" ]
}

Storing integer values as constants in Enum manner in java

Well, you can't quite do it that way. PAGE.SIGN_CREATE will never return 1; it will return PAGE.SIGN_CREATE. That's the point of enumerated types.

However, if you're willing to add a few keystrokes, you can add fields to your enums, like this:


    public enum PAGE{
        SIGN_CREATE(0),
        SIGN_CREATE_BONUS(1),
        HOME_SCREEN(2),
        REGISTER_SCREEN(3);

        private final int value;

        PAGE(final int newValue) {
            value = newValue;
        }

        public int getValue() { return value; }
    }

And then you call PAGE.SIGN_CREATE.getValue() to get 0.

How to input a string from user into environment variable from batch file

A rather roundabout way, just for completeness:

 for /f "delims=" %i in ('type CON') do set inp=%i

Of course that requires ^Z as a terminator, and so the Johannes answer is better in all practical ways.

How to use passive FTP mode in Windows command prompt?

Although this doesnt answer the question directly about command line, but from Windows OS, use the Windows Explorer ftp://username@server

this will use Passive Mode by default

For command line, active mode is the default

Arithmetic operation resulted in an overflow. (Adding integers)

For simplicity I will use bytes:

byte a=250;
byte b=8;
byte c=a+b;

if a, b, and c were 'int', you would expect 258, but in the case of 'byte', the expected result would be 2 (258 & 0xFF), but in a Windows application you get an exception, in a console one you may not (I don't, but this may depend on IDE, I use SharpDevelop).

Sometimes, however, that behaviour is desired (e.g. you only care about the lower 8 bits of the result).

You could do the following:

byte a=250;
byte b=8;

byte c=(byte)((int)a + (int)b);

This way both 'a' and 'b' are converted to 'int', added, then casted back to 'byte'.

To be on the safe side, you may also want to try:

...
byte c=(byte)(((int)a + (int)b) & 0xFF);

Or if you really want that behaviour, the much simpler way of doing the above is:

unchecked
{
    byte a=250;
    byte b=8;
    byte c=a+b;
}

Or declare your variables first, then do the math in the 'unchecked' section.

Alternately, if you want to force the checking of overflow, use 'checked' instead.

Hope this clears things up.

Nurchi

P.S.

Trust me, that exception is your friend :)

How to auto-scroll to end of div when data is added?

If you don't know when data will be added to #data, you could set an interval to update the element's scrollTop to its scrollHeight every couple of seconds. If you are controlling when data is added, just call the internal of the following function after the data has been added.

window.setInterval(function() {
  var elem = document.getElementById('data');
  elem.scrollTop = elem.scrollHeight;
}, 5000);

How to delete an instantiated object Python?

object.__del__(self) is called when the instance is about to be destroyed.

>>> class Test:
...     def __del__(self):
...         print "deleted"
... 
>>> test = Test()
>>> del test
deleted

Object is not deleted unless all of its references are removed(As quoted by ethan)

Also, From Python official doc reference:

del x doesn’t directly call x.del() — the former decrements the reference count for x by one, and the latter is only called when x‘s reference count reaches zero

How to iterate over the file in python

You should learn about EAFP vs LBYL.

from sys import stdin, stdout
def main(infile=stdin, outfile=stdout):
    if isinstance(infile, basestring):
        infile=open(infile,'r')
    if isinstance(outfile, basestring):
        outfile=open(outfile,'w')
    for lineno, line in enumerate(infile, 1):
        line = line.strip()
         try:
             print >>outfile, int(line,16)
         except ValueError:
             return "Bad value at line %i: %r" % (lineno, line)

if __name__ == "__main__":
    from sys import argv, exit
    exit(main(*argv[1:]))

How to correctly link php-fpm and Nginx Docker containers?

I think we also need to give the fpm container the volume, dont we? So =>

fpm:
    image: php:fpm
    volumes:
        - ./:/var/www/test/

If i dont do this, i run into this exception when firing a request, as fpm cannot find requested file:

[error] 6#6: *4 FastCGI sent in stderr: "Primary script unknown" while reading response header from upstream, client: 172.17.42.1, server: localhost, request: "GET / HTTP/1.1", upstream: "fastcgi://172.17.0.81:9000", host: "localhost"

Push eclipse project to GitHub with EGit

Simple Steps:

-Open Eclipse.

  • Select Project which you want to push on github->rightclick.
  • select Team->share Project->Git->Create repository->finish.(it will ask to login in Git account(popup).
  • Right click again to Project->Team->commit. you are done

Convert Java Date to UTC String

Well if you want to use java.util.Date only, here is a small trick you can use:

String dateString = Long.toString(Date.UTC(date.getYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds()));

Print directly from browser without print popup window

I don't believe this is possible. The dialog box that gets displayed allows the user to select a printer to print to. So, let's say it would be possible for your application to just click and print, and a user clicks your print button, but has two printers connected to the computer. Or, more likely, that user is working in an office building with 25 printers. Without that dialog box, how would the computer know to which printer to print?

Call child method from parent

Here's a bug? to look out for: I concur with rossipedia's solution using forwardRef, useRef, useImperativeHandle

There's some misinformation online that says refs can only be created from React Class components, but you can indeed use Function Components if you use the aforementioned hooks above. A note, the hooks only worked for me after I changed the file to not use withRouter() when exporting the component. I.e. a change from

export default withRouter(TableConfig);

to instead be

export default TableConfig;

In hindsight the withRouter() is not needed for such a component anyway, but usually it doesn't hurt anything having it in. My use case is that I created a component to create a Table to handle the viewing and editing of config values, and I wanted to be able to tell this Child component to reset it's state values whenever the Parent form's Reset button was hit. UseRef() wouldn't properly get the ref or ref.current (kept on getting null) until I removed withRouter() from the file containing my child component TableConfig

How to create global variables accessible in all views using Express / Node.JS?

you can also use "global"

Example:

declare like this :

  app.use(function(req,res,next){
      global.site_url = req.headers.host;   // hostname = 'localhost:8080'
      next();
   });

Use like this: in any views or ejs file <% console.log(site_url); %>

in js files console.log(site_url);

ping: google.com: Temporary failure in name resolution

If you get the IP address from a DHCP server, you can also set the server to send a DNS server. Or add the nameserver 8.8.8.8 into /etc/resolvconf/resolv.conf.d/base file. The information in this file is included in the resolver configuration file even when no interfaces are configured.

phpMyAdmin says no privilege to create database, despite logged in as root user

Login using the system maintenance user and password created when you installed phpMyAdmin.
It can be found in the debian.cnf file at /etc/mysql then you will have total access.

cd /etc/mysql
sudo nano debian.cnf
Just look - don't change anything!
[mysql_upgrade]
host     = localhost
user     = debian-sys-maint       <----use this user
password = s0meRaND0mChar$s       <----use this password
socket   = /var/run/mysqld/mysqld.sock

Worked for me.