Programs & Examples On #Geonames

Geonames refers to a database / webservice to query various geographic data items such as names of places, latitude, longitude, elevation, population in various languages. It contains over 10 million geographical names categorized into nine classes and further subcategorized.

Could not read JSON: Can not deserialize instance of hello.Country[] out of START_OBJECT token

Another solution:

public class CountryInfoResponse {
  private List<Object> geonames;
}

Usage of a generic Object-List solved my problem, as there were other Datatypes like Boolean too.

Get value from SimpleXMLElement Object

foreach($xml->code as $vals )
{ 
    unset($geonames);
    $vals=(array)$vals;
    foreach($vals as $key => $value)
      {
        $value=(array)$value;
        $geonames[$key]=$value[0];
      }
}
print_r($geonames);

What is the difference between `git merge` and `git merge --no-ff`?

The --no-ff flag prevents git merge from executing a "fast-forward" if it detects that your current HEAD is an ancestor of the commit you're trying to merge. A fast-forward is when, instead of constructing a merge commit, git just moves your branch pointer to point at the incoming commit. This commonly occurs when doing a git pull without any local changes.

However, occasionally you want to prevent this behavior from happening, typically because you want to maintain a specific branch topology (e.g. you're merging in a topic branch and you want to ensure it looks that way when reading history). In order to do that, you can pass the --no-ff flag and git merge will always construct a merge instead of fast-forwarding.

Similarly, if you want to execute a git pull or use git merge in order to explicitly fast-forward, and you want to bail out if it can't fast-forward, then you can use the --ff-only flag. This way you can regularly do something like git pull --ff-only without thinking, and then if it errors out you can go back and decide if you want to merge or rebase.

How to check if a string "StartsWith" another string?

Also check out underscore.string.js. It comes with a bunch of useful string testing and manipulation methods, including a startsWith method. From the docs:

startsWith _.startsWith(string, starts)

This method checks whether string starts with starts.

_("image.gif").startsWith("image")
=> true

Replace single quotes in SQL Server

I ran into a strange anomaly that would apply here. Using Google API and getting the reply in XML format, it was failing to convert to XML data type because of single quotes.

Replace(@Strip ,'''','')

was not working because the single quote was ascii character 146 instead of 39. So I used:

Replace(@Strip, char(146), '')

which also works for regular single quotes char(39) and any other special character.

xsd:boolean element type accept "true" but not "True". How can I make it accept it?

You cannot.

According to the XML Schema specification, a boolean is true or false. True is not valid:


  3.2.2.1 Lexical representation
  An instance of a datatype that is defined as ·boolean· can have the 
  following legal literals {true, false, 1, 0}. 

  3.2.2.2 Canonical representation
  The canonical representation for boolean is the set of 
  literals {true, false}. 

If the tool you are using truly validates against the XML Schema standard, then you cannot convince it to accept True for a boolean.

Min and max value of input in angular4 application

You can control with a change event if the input is within your range, if it is not in the range you assign 0.

<md-input-container>
  <input type="number" 
    maxlength="3" 
    min="0" 
    max="100" 
    required 
    mdInput 
    placeholder="Charge" 
    [(ngModel)]="rateInput"
    (change)= "rateInput < 0 ? rateInput = 0 : rateInput; rateInput > 100 ? rateInput = 0 : rateIntput;"
    name="rateInput">
  <md-error>Required field</md-error>
</md-input-container>

How to bind an enum to a combobox control in WPF?

I just kept it simple. I created a list of items with the enum values in my ViewModel:

public enum InputsOutputsBoth
{
    Inputs,
    Outputs,
    Both
}

private IList<InputsOutputsBoth> _ioTypes = new List<InputsOutputsBoth>() 
{ 
    InputsOutputsBoth.Both, 
    InputsOutputsBoth.Inputs, 
    InputsOutputsBoth.Outputs 
};

public IEnumerable<InputsOutputsBoth> IoTypes
{
    get { return _ioTypes; }
    set { }
}

private InputsOutputsBoth _selectedIoType;

public InputsOutputsBoth SelectedIoType
{
    get { return _selectedIoType; }
    set
    {
        _selectedIoType = value;
        OnPropertyChanged("SelectedIoType");
        OnSelectionChanged();
    }
}

In my xaml code I just need this:

<ComboBox ItemsSource="{Binding IoTypes}" SelectedItem="{Binding SelectedIoType, Mode=TwoWay}">

How to extend a class in python?

Another way to extend (specifically meaning, add new methods, not change existing ones) classes, even built-in ones, is to use a preprocessor that adds the ability to extend out of/above the scope of Python itself, converting the extension to normal Python syntax before Python actually gets to see it.

I've done this to extend Python 2's str() class, for instance. str() is a particularly interesting target because of the implicit linkage to quoted data such as 'this' and 'that'.

Here's some extending code, where the only added non-Python syntax is the extend:testDottedQuad bit:

extend:testDottedQuad
def testDottedQuad(strObject):
    if not isinstance(strObject, basestring): return False
    listStrings = strObject.split('.')
    if len(listStrings) != 4: return False
    for strNum in listStrings:
        try:    val = int(strNum)
        except: return False
        if val < 0: return False
        if val > 255: return False
    return True

After which I can write in the code fed to the preprocessor:

if '192.168.1.100'.testDottedQuad():
    doSomething()

dq = '216.126.621.5'
if not dq.testDottedQuad():
    throwWarning();

dqt = ''.join(['127','.','0','.','0','.','1']).testDottedQuad()
if dqt:
    print 'well, that was fun'

The preprocessor eats that, spits out normal Python without monkeypatching, and Python does what I intended it to do.

Just as a c preprocessor adds functionality to c, so too can a Python preprocessor add functionality to Python.

My preprocessor implementation is too large for a stack overflow answer, but for those who might be interested, it is here on GitHub.

What is a PDB file?

I had originally asked myself the question "Do I need a PDB file deployed to my customer's machine?", and after reading this post, decided to exclude the file.

Everything worked fine, until today, when I was trying to figure out why a message box containing an Exception.StackTrace was missing the file and line number information - necessary for troubleshooting the exception. I re-read this post and found the key nugget of information: that although the PDB is not necessary for the app to run, it is necessary for the file and line numbers to be present in the StackTrace string. I included the PDB file in the executable folder and now all is fine.

HTML / CSS How to add image icon to input type="button"?

<img src="http://www.pic4ever.com/images/2mpe5id.gif">
            <button class="btn btn-<?php echo $settings["button_background"]; ?>" type="submit"><?php echo $settings["submit_button_text"]; ?></button>

Usage of sys.stdout.flush() method

import sys
for x in range(10000):
    print "HAPPY >> %s <<\r" % str(x),
    sys.stdout.flush()

How do I decode a base64 encoded string?

The m000493 method seems to perform some kind of XOR encryption. This means that the same method can be used for both encrypting and decrypting the text. All you have to do is reverse m0001cd:

string p0 = Encoding.UTF8.GetString(Convert.FromBase64String("OBFZDT..."));

string result = m000493(p0, "_p0lizei.");
//    result == "gaia^unplugged^Ta..."

with return m0001cd(builder3.ToString()); changed to return builder3.ToString();.

Android turn On/Off WiFi HotSpot programmatically

Your best bet will be looking at the WifiManager class. Specifically the setWifiEnabled(bool) function.

See the documentation at: http://developer.android.com/reference/android/net/wifi/WifiManager.html#setWifiEnabled(boolean)

A tutorial on how to use it (including what permissions you need) can be found here: http://www.tutorialforandroid.com/2009/10/turn-off-turn-on-wifi-in-android-using.html

What is Parse/parsing?

Parsing can be considered as a synonym of "Breaking down into small pieces" and then analysing what is there or using it in a modified way. In Java, Strings are parsed into Decimal, Octal, Binary, Hexadecimal, etc. It is done if your application is taking input from the user in the form of string but somewhere in your application you want to use that input in the form of an integer or of double type. It is not same as type casting. For type casting the types used should be compatible in order to caste but nothing such in parsing.

jQuery get html of container including the container itself

I like to use this;

$('#container').prop('outerHTML');

Angular CLI - Please add a @NgModule annotation when using latest

In my case, I created a new ChildComponent in Parentcomponent whereas both in the same module but Parent is registered in a shared module so I created ChildComponent using CLI which registered Child in the current module but my parent was registered in the shared module.

So register the ChildComponent in Shared Module manually.

undefined reference to `std::ios_base::Init::Init()'

Most of these linker errors occur because of missing libraries.

I added the libstdc++.6.dylib in my Project->Targets->Build Phases-> Link Binary With Libraries.

That solved it for me on Xcode 6.3.2 for iOS 8.3

Cheers!

How to enable LogCat/Console in Eclipse for Android?

In the "Window" menu, open "Open Perspective" -> "Debug".

alt text click On the plus image icon(you see the below image at status bar), and then select "Logcat"....

How to convert HTML to PDF using iTextSharp

I use the following code to create PDF

protected void CreatePDF(Stream stream)
        {
            using (var document = new Document(PageSize.A4, 40, 40, 40, 30))
            {
                var writer = PdfWriter.GetInstance(document, stream);
                writer.PageEvent = new ITextEvents();
                document.Open();

                // instantiate custom tag processor and add to `HtmlPipelineContext`.
                var tagProcessorFactory = Tags.GetHtmlTagProcessorFactory();
                tagProcessorFactory.AddProcessor(
                    new TableProcessor(),
                    new string[] { HTML.Tag.TABLE }
                );

                //Register Fonts.
                XMLWorkerFontProvider fontProvider = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS);
                fontProvider.Register(HttpContext.Current.Server.MapPath("~/Content/Fonts/GothamRounded-Medium.ttf"), "Gotham Rounded Medium");
                CssAppliers cssAppliers = new CssAppliersImpl(fontProvider);

                var htmlPipelineContext = new HtmlPipelineContext(cssAppliers);
                htmlPipelineContext.SetTagFactory(tagProcessorFactory);

                var pdfWriterPipeline = new PdfWriterPipeline(document, writer);
                var htmlPipeline = new HtmlPipeline(htmlPipelineContext, pdfWriterPipeline);

                // get an ICssResolver and add the custom CSS
                var cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(true);
                cssResolver.AddCss(CSSSource, "utf-8", true);
                var cssResolverPipeline = new CssResolverPipeline(
                    cssResolver, htmlPipeline
                );

                var worker = new XMLWorker(cssResolverPipeline, true);
                var parser = new XMLParser(worker);
                using (var stringReader = new StringReader(HTMLSource))
                {
                    parser.Parse(stringReader);
                    document.Close();
                    HttpContext.Current.Response.ContentType = "application /pdf";
                    if (base.View)
                        HttpContext.Current.Response.AddHeader("content-disposition", "inline;filename=\"" + OutputFileName + ".pdf\"");
                    else
                        HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=\"" + OutputFileName + ".pdf\"");
                    HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
                    HttpContext.Current.Response.WriteFile(OutputPath);
                    HttpContext.Current.Response.End();
                }
            }
        }

How do I resolve `The following packages have unmet dependencies`

This is a bug in the npm package regarding dependencies : https://askubuntu.com/questions/1088662/npm-depends-node-gyp-0-10-9-but-it-is-not-going-to-be-installed

Bugs have been reported. The above may not work depending what you have installed already, at least it didn't for me on an up to date Ubuntu 18.04 LTS.

I followed the suggested dependencies and installed them as the above link suggests:

sudo apt-get install nodejs-dev node-gyp libssl1.0-dev

and then

sudo apt-get install npm

Please subscribe to the bug if you're affected:

bugs.launchpad.net/ubuntu/+source/npm/+bug/1517491
bugs.launchpad.net/ubuntu/+source/npm/+bug/1809828

How to convert string to Date in Angular2 \ Typescript?

You can use date filter to convert in date and display in specific format.

In .ts file (typescript):

let dateString = '1968-11-16T00:00:00' 
let newDate = new Date(dateString);

In HTML:

{{dateString |  date:'MM/dd/yyyy'}}

Below are some formats which you can implement :

Backend:

public todayDate = new Date();

HTML :

<select>
<option value=""></option>
<option value="MM/dd/yyyy">[{{todayDate | date:'MM/dd/yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy">[{{todayDate | date:'EEEE, MMMM d, yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm a'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm:ss a'}}]</option>
<option value="MM/dd/yyyy h:mm a">[{{todayDate | date:'MM/dd/yyyy h:mm a'}}]</option>
<option value="MM/dd/yyyy h:mm:ss a">[{{todayDate | date:'MM/dd/yyyy h:mm:ss a'}}]</option>
<option value="MMMM d">[{{todayDate | date:'MMMM d'}}]</option>   
<option value="yyyy-MM-ddTHH:mm:ss">[{{todayDate | date:'yyyy-MM-ddTHH:mm:ss'}}]</option>
<option value="h:mm a">[{{todayDate | date:'h:mm a'}}]</option>
<option value="h:mm:ss a">[{{todayDate | date:'h:mm:ss a'}}]</option>      
<option value="EEEE, MMMM d, yyyy hh:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy hh:mm:ss a'}}]</option>
<option value="MMMM yyyy">[{{todayDate | date:'MMMM yyyy'}}]</option> 
</select>

Can a foreign key be NULL and/or duplicate?

it depends on what role this foreign key plays in your relation.

  1. if this foreign key is also a key attribute in your relation, then it can't be NULL
  2. if this foreign key is a normal attribute in your relation, then it can be NULL.

Add bottom line to view in SwiftUI / Swift / Objective-C / Xamarin

Swift 5 You can use a UIView extension so that you can add bottom border to any view:

extension UIView {

    func addBottomLine(width: CGFloat, color: UIColor) {
        let lineView: UIView = {
            let view = UIView()
            view.translatesAutoresizingMaskIntoConstraints = false
            view.backgroundColor = color
            return view
        }()
        addSubview(lineView)
        NSLayoutConstraint.activate([
            lineView.heightAnchor.constraint(equalToConstant: width),
            lineView.leadingAnchor.constraint(equalTo: leadingAnchor),
            lineView.trailingAnchor.constraint(equalTo: trailingAnchor),
            lineView.bottomAnchor.constraint(equalTo: bottomAnchor)
        ])
    }

}

Browser Caching of CSS files

Your file will probably be cached - but it depends...

Different browsers have slightly different behaviors - most noticeably when dealing with ambiguous/limited caching headers emanating from the server. If you send a clear signal, the browsers obey, virtually all of the time.

The greatest variance by far, is in the default caching configuration of different web servers and application servers.

Some (e.g. Apache) are likely to serve known static file types with HTTP headers encouraging the browser to cache them, while other servers may send no-cache commands with every response - regardless of filetype.

...

So, first off, read some of the excellent HTTP caching tutorials out there. HTTP Caching & Cache-Busting for Content Publishers was a real eye opener for me :-)

Next install and fiddle around with Firebug and the Live HTTP Headers add-on , to find out which headers your server is actually sending.

Then read your web server docs to find out how to tweak them to perfection (or talk your sysadmin into doing it for you).

...

As to what happens when the browser is restarted, it depends on the browser and the user configuration.

As a rule of thumb, expect the browser to be more likely to check in with the server after each restart, to see if anything has changed (see If-Last-Modified and If-None-Match).

If you configure your server correctly, it should be able to return a super-short 304 Not Modified (costing very little bandwidth) and after that the browser will use the cache as normal.

Very simple log4j2 XML configuration file using Console and File appender

There are excellent answers, but if you want to color your console logs you can use the pattern :

<PatternLayout pattern="%style{%date{DEFAULT}}{yellow}
            [%t] %highlight{%-5level}{FATAL=bg_red, ERROR=red, WARN=yellow, INFO=green} %logger{36} - %message\n"/>

The full log4j2 file is:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Properties>
        <Property name="APP_LOG_ROOT">/opt/test/log</Property>
    </Properties>
    <Appenders>
        <Console name="ConsoleAppender" target="SYSTEM_OUT">
            <PatternLayout pattern="%style{%date{DEFAULT}}{yellow}
                [%t] %highlight{%-5level}{FATAL=bg_red, ERROR=red, WARN=yellow, INFO=green} %logger{36} - %message\n"/>
        </Console>
        <RollingFile name="XML_ROLLING_FILE_APPENDER"
                     fileName="${APP_LOG_ROOT}/appName.log"
                     filePattern="${APP_LOG_ROOT}/appName-%d{yyyy-MM-dd}-%i.log.gz">
            <PatternLayout pattern="%d{DEFAULT} [%t] %-5level %logger{36} - %msg%n"/>
            <Policies>
                <SizeBasedTriggeringPolicy size="19500KB"/>
            </Policies>
        </RollingFile>
    </Appenders>
    <Loggers>
        <Root level="error">
            <AppenderRef ref="ConsoleAppender"/>
        </Root>
        <Logger name="com.compName.projectName" level="debug">
            <AppenderRef ref="XML_ROLLING_FILE_APPENDER"/>
        </Logger>
    </Loggers>
</Configuration>

And the logs will look like this: enter image description here

Setting selected values for ng-options bound select elements

You can use the ID field as the equality identifier. You can't use the adhoc object for this case because AngularJS checks references equality when comparing objects.

<select 
    ng-model="Choice.SelectedOption.ID" 
    ng-options="choice.ID as choice.Name for choice in Choice.Options">
</select>

How to parse a String containing XML in Java and retrieve the value of the root node?

You could do this with JAXB (an implementation is included in Java SE 6).

import java.io.StringReader;
import javax.xml.bind.*;
import javax.xml.transform.stream.StreamSource;

public class Demo {

    public static void main(String[] args) throws Exception {
        String xmlString = "<message>HELLO!</message> ";
        JAXBContext jc = JAXBContext.newInstance(String.class);
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        StreamSource xmlSource = new StreamSource(new StringReader(xmlString));
        JAXBElement<String> je = unmarshaller.unmarshal(xmlSource, String.class);
        System.out.println(je.getValue());
    }

}

Output

HELLO!

Iterate through a C array

If the size of the array is known at compile time, you can use the structure size to determine the number of elements.

struct foo fooarr[10];

for(i = 0; i < sizeof(fooarr) / sizeof(struct foo); i++)
{
  do_something(fooarr[i].data);
}

If it is not known at compile time, you will need to store a size somewhere or create a special terminator value at the end of the array.

Python update a key in dict if it doesn't exist

According to the above answers setdefault() method worked for me.

old_attr_name = mydict.setdefault(key, attr_name)
if attr_name != old_attr_name:
    raise RuntimeError(f"Key '{key}' duplication: "
                       f"'{old_attr_name}' and '{attr_name}'.")

Though this solution is not generic. Just suited me in this certain case. The exact solution would be checking for the key first (as was already advised), but with setdefault() we avoid one extra lookup on the dictionary, that is, though small, but still a performance gain.

How do I stop/start a scheduled task on a remote computer programmatically?

Note: "schtasks" (see the other, accepted response) has replaced "at". However, "at" may be of use if the situation calls for compatibility with older versions of Windows that don't have schtasks.

Command-line help for "at":

C:\>at /?
The AT command schedules commands and programs to run on a computer at
a specified time and date. The Schedule service must be running to use
the AT command.

AT [\\computername] [ [id] [/DELETE] | /DELETE [/YES]]
AT [\\computername] time [/INTERACTIVE]
    [ /EVERY:date[,...] | /NEXT:date[,...]] "command"

\\computername     Specifies a remote computer. Commands are scheduled on the
                   local computer if this parameter is omitted.
id                 Is an identification number assigned to a scheduled
                   command.
/delete            Cancels a scheduled command. If id is omitted, all the
                   scheduled commands on the computer are canceled.
/yes               Used with cancel all jobs command when no further
                   confirmation is desired.
time               Specifies the time when command is to run.
/interactive       Allows the job to interact with the desktop of the user
                   who is logged on at the time the job runs.
/every:date[,...]  Runs the command on each specified day(s) of the week or
                   month. If date is omitted, the current day of the month
                   is assumed.
/next:date[,...]   Runs the specified command on the next occurrence of the
                   day (for example, next Thursday).  If date is omitted, the
                   current day of the month is assumed.
"command"          Is the Windows NT command, or batch program to be run.

@selector() in Swift?

Using #selector will check your code at compile time to make sure the method you want to call actually exists. Even better, if the method doesn’t exist, you’ll get a compile error: Xcode will refuse to build your app, thus banishing to oblivion another possible source of bugs.

override func viewDidLoad() {
        super.viewDidLoad()

        navigationItem.rightBarButtonItem =
            UIBarButtonItem(barButtonSystemItem: .Add, target: self,
                            action: #selector(addNewFireflyRefernce))
    }

    func addNewFireflyReference() {
        gratuitousReferences.append("Curse your sudden but inevitable betrayal!")
    }

How do I find the index of a character in a string in Ruby?

index(substring [, offset]) ? fixnum or nil
index(regexp [, offset]) ? fixnum or nil

Returns the index of the first occurrence of the given substring or pattern (regexp) in str. Returns nil if not found. If the second parameter is present, it specifies the position in the string to begin the search.

"hello".index('e')             #=> 1
"hello".index('lo')            #=> 3
"hello".index('a')             #=> nil
"hello".index(?e)              #=> 1
"hello".index(/[aeiou]/, -3)   #=> 4

Check out ruby documents for more information.

How can I use grep to show just filenames on Linux?

The standard option grep -l (that is a lowercase L) could do this.

From the Unix standard:

-l
    (The letter ell.) Write only the names of files containing selected
    lines to standard output. Pathnames are written once per file searched.
    If the standard input is searched, a pathname of (standard input) will
    be written, in the POSIX locale. In other locales, standard input may be
    replaced by something more appropriate in those locales.

You also do not need -H in this case.

Retrieve column values of the selected row of a multicolumn Access listbox

For multicolumn listbox extract data from any column of selected row by

 listboxControl.List(listboxControl.ListIndex,col_num)

where col_num is required column ( 0 for first column)

Get HTML code from website in C#

Better you can use the Webclient class to simplify your task:

using System.Net;

using (WebClient client = new WebClient())
{
    string htmlCode = client.DownloadString("http://somesite.com/default.html");
}

Delete branches in Bitbucket

I've wrote this small script when the number of branches in my repo exceeded several hundreds. I did not know about the other methods (with CLI) so I decided to automate it with selenium. It simply opens Bitbucket website, goes to Branches, scrolls down the page to the end and clicks on every branch options menu -> clicks Delete button -> clicks Yes. It can be tuned to keep the last N (100 - default) branches and skip branches with specific names (master, develop - default, could be more). If this fits for you, you can try that way.

https://github.com/globad/remove-old-branches

All you need is to clone the repository, download the proper version of Chrome-webdriver, input few constants like URL to your repository and run the script.

The code is simple enough to understand. If you have any questions, write comments / create an Issue.

setSupportActionBar toolbar cannot be applied to (android.widget.Toolbar) error

For adding a ToolBar that supports Material Design, the official documentation directions are probably the best to follow.

  1. Add the v7 appcompat support library.
  2. Make your activity extend AppCompatActivity.

    public class MyActivity extends AppCompatActivity {
      // ...
    }
    
  3. Declare NoActionBar in the Manifest.

    <application
        android:theme="@style/Theme.AppCompat.Light.NoActionBar"
        />
    
  4. Add a toolbar to your activity's xml layout.

    <android.support.v7.widget.Toolbar
       android:id="@+id/my_toolbar"
       android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
       ...
       />
    
  5. Call setSupportActionBar in the activity's onCreate.

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);
        Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
        setSupportActionBar(myToolbar);
    }
    

Note: You will have to import the following in the activity.

import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

C# event with custom arguments

Here's a reworking of your sample to get you started.

  • your sample has a static event - it's more usual for an event to come from a class instance, but I've left it static below.

  • the sample below also uses the more standard naming OnXxx for the method that raises the event.

  • the sample below does not consider thread-safety, which may well be more of an issue if you insist on your event being static.

.

public enum MyEvents{ 
     Event1 
} 

public class MyEventArgs : EventArgs
{
    public MyEventArgs(MyEvents myEvents)
    {
        MyEvents = myEvents;
    }

    public MyEvents MyEvents { get; private set; }
}

public static class MyClass
{
     public static event EventHandler<MyEventArgs> EventTriggered; 

     public static void Trigger(MyEvents myEvents) 
     {
         OnMyEvent(new MyEventArgs(myEvents));
     }

     protected static void OnMyEvent(MyEventArgs e)
     {
         if (EventTriggered != null)
         {
             // Normally the first argument (sender) is "this" - but your example
             // uses a static event, so I'm passing null instead.
             // EventTriggered(this, e);
             EventTriggered(null, e);
         } 
     }
}

Fade In Fade Out Android Animation in Java

Here is my solution using AnimatorSet which seems to be a bit more reliable than AnimationSet.

// Custom animation on image
ImageView myView = (ImageView)splashDialog.findViewById(R.id.splashscreenImage);

ObjectAnimator fadeOut = ObjectAnimator.ofFloat(myView, "alpha",  1f, .3f);
fadeOut.setDuration(2000);
ObjectAnimator fadeIn = ObjectAnimator.ofFloat(myView, "alpha", .3f, 1f);
fadeIn.setDuration(2000);

final AnimatorSet mAnimationSet = new AnimatorSet();

mAnimationSet.play(fadeIn).after(fadeOut);

mAnimationSet.addListener(new AnimatorListenerAdapter() {
    @Override
    public void onAnimationEnd(Animator animation) {
        super.onAnimationEnd(animation);
        mAnimationSet.start();
    }
});
mAnimationSet.start();

How long do browsers cache HTTP 301s?

Test your redirects using incognito/InPrivate mode so when you close the browser it will flush that cache and reopening the window will not contain the cache.

How to amend older Git commit?

You could can use git rebase to rewrite the commit history. This can be potentially destructive to your changes, so use with care.

First commit your "amend" change as a normal commit. Then do an interactive rebase starting on the parent of your oldest commit

git rebase -i 47175e84c2cb7e47520f7dde824718eae3624550^

This will fire up your editor with all commits. Reorder them so your "amend" commit comes below the one you want to amend. Then replace the first word on the line with the "amend" commit with s which will combine (s quash) it with the commit before. Save and exit your editor and follow the instructions.

How do I save and restore multiple variables in python?

If you need to save multiple objects, you can simply put them in a single list, or tuple, for instance:

import pickle

# obj0, obj1, obj2 are created here...

# Saving the objects:
with open('objs.pkl', 'w') as f:  # Python 3: open(..., 'wb')
    pickle.dump([obj0, obj1, obj2], f)

# Getting back the objects:
with open('objs.pkl') as f:  # Python 3: open(..., 'rb')
    obj0, obj1, obj2 = pickle.load(f)

If you have a lot of data, you can reduce the file size by passing protocol=-1 to dump(); pickle will then use the best available protocol instead of the default historical (and more backward-compatible) protocol. In this case, the file must be opened in binary mode (wb and rb, respectively).

The binary mode should also be used with Python 3, as its default protocol produces binary (i.e. non-text) data (writing mode 'wb' and reading mode 'rb').

How to style SVG with external CSS?

What works for me: style tag with @import rule

<defs>
    <style type="text/css">
        @import url("svg-common.css");
    </style>
</defs>

CSV file written with Python has blank lines between each row

The simple answer is that csv files should always be opened in binary mode whether for input or output, as otherwise on Windows there are problems with the line ending. Specifically on output the csv module will write \r\n (the standard CSV row terminator) and then (in text mode) the runtime will replace the \n by \r\n (the Windows standard line terminator) giving a result of \r\r\n.

Fiddling with the lineterminator is NOT the solution.

How to check if element exists using a lambda expression?

The above answers require you to malloc a new stream object.

public <T>
boolean containsByLambda(Collection<? extends T> c, Predicate<? super T> p) {

    for (final T z : c) {
        if (p.test(z)) {
            return true;
        }
    }
    return false;
}

public boolean containsTabById(TabPane tabPane, String id) {
    return containsByLambda(tabPane.getTabs(), z -> z.getId().equals(id));
}
...
if (containsTabById(tabPane, idToCheck))) {
   ...
}

SQL query for today's date minus two months

SELECT COUNT(1) FROM FB 
WHERE Dte > DATE_SUB(now(), INTERVAL 2 MONTH)

How to bind WPF button to a command in ViewModelBase?

 <Grid >
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Button Command="{Binding ClickCommand}" Width="100" Height="100" Content="wefwfwef"/>
</Grid>

the code behind for the window:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new ViewModelBase();
    }
}

The ViewModel:

public class ViewModelBase
{
    private ICommand _clickCommand;
    public ICommand ClickCommand
    {
        get
        {
            return _clickCommand ?? (_clickCommand = new CommandHandler(() => MyAction(), ()=> CanExecute));
        }
    }
     public bool CanExecute
     {
        get
        {
            // check if executing is allowed, i.e., validate, check if a process is running, etc. 
            return true/false;
        }
     }

    public void MyAction()
    {

    }
}

Command Handler:

 public class CommandHandler : ICommand
{
    private Action _action;
    private Func<bool> _canExecute;

    /// <summary>
    /// Creates instance of the command handler
    /// </summary>
    /// <param name="action">Action to be executed by the command</param>
    /// <param name="canExecute">A bolean property to containing current permissions to execute the command</param>
    public CommandHandler(Action action, Func<bool> canExecute)
    {
        _action = action;
        _canExecute = canExecute;
    }

    /// <summary>
    /// Wires CanExecuteChanged event 
    /// </summary>
    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    /// <summary>
    /// Forcess checking if execute is allowed
    /// </summary>
    /// <param name="parameter"></param>
    /// <returns></returns>
    public bool CanExecute(object parameter)
    {
        return _canExecute.Invoke();
    }

    public void Execute(object parameter)
    {
        _action();
    }
}

I hope this will give you the idea.

Why is there an unexplainable gap between these inline-block div elements?

In this instance, your div elements have been changed from block level elements to inline elements. A typical characteristic of inline elements is that they respect the whitespace in the markup. This explains why a gap of space is generated between the elements. (example)

There are a few solutions that can be used to solve this.

Method 1 - Remove the whitespace from the markup

Example 1 - Comment the whitespace out: (example)

<div>text</div><!--
--><div>text</div><!--
--><div>text</div><!--
--><div>text</div><!--
--><div>text</div>

Example 2 - Remove the line breaks: (example)

<div>text</div><div>text</div><div>text</div><div>text</div><div>text</div>

Example 3 - Close part of the tag on the next line (example)

<div>text</div
><div>text</div
><div>text</div
><div>text</div
><div>text</div>

Example 4 - Close the entire tag on the next line: (example)

<div>text
</div><div>text
</div><div>text
</div><div>text
</div><div>text
</div>

Method 2 - Reset the font-size

Since the whitespace between the inline elements is determined by the font-size, you could simply reset the font-size to 0, and thus remove the space between the elements.

Just set font-size: 0 on the parent elements, and then declare a new font-size for the children elements. This works, as demonstrated here (example)

#parent {
    font-size: 0;
}

#child {
    font-size: 16px;
}

This method works pretty well, as it doesn't require a change in the markup; however, it doesn't work if the child element's font-size is declared using em units. I would therefore recommend removing the whitespace from the markup, or alternatively floating the elements and thus avoiding the space generated by inline elements.

Method 3 - Set the parent element to display: flex

In some cases, you can also set the display of the parent element to flex. (example)

This effectively removes the spaces between the elements in supported browsers. Don't forget to add appropriate vendor prefixes for additional support.

.parent {
    display: flex;
}
.parent > div {
    display: inline-block;
    padding: 1em;
    border: 2px solid #f00;
}

_x000D_
_x000D_
.parent {_x000D_
    display: flex;_x000D_
}_x000D_
.parent > div {_x000D_
    display: inline-block;_x000D_
    padding: 1em;_x000D_
    border: 2px solid #f00;_x000D_
}
_x000D_
<div class="parent">_x000D_
    <div>text</div>_x000D_
    <div>text</div>_x000D_
    <div>text</div>_x000D_
    <div>text</div>_x000D_
    <div>text</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_


Sides notes:

It is incredibly unreliable to use negative margins to remove the space between inline elements. Please don't use negative margins if there are other, more optimal, solutions.

Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema

A somewhat unlikely situation.

I have removed the yarn.lock file, which referenced an older version of webpack.

So check to see the differences in your yarn.lock file as a possiblity.

What is the difference between precision and scale?

Precision 4, scale 2: 99.99

Precision 10, scale 0: 9999999999

Precision 8, scale 3: 99999.999

Precision 5, scale -3: 99999000

UIWebView open links in Safari

One quick comment to user306253's answer: caution with this, when you try to load something in the UIWebView yourself (i.e. even from the code), this method will prevent it to happened.

What you can do to prevent this (thanks Wade) is:

if (inType == UIWebViewNavigationTypeLinkClicked) {
    [[UIApplication sharedApplication] openURL:[inRequest URL]];
    return NO;
}

return YES;

You might also want to handle the UIWebViewNavigationTypeFormSubmitted and UIWebViewNavigationTypeFormResubmitted types.

Should I use the Reply-To header when sending emails as a service to others?

Here is worked for me:

Subject: SomeSubject
From:Company B (me)
Reply-to:Company A
To:Company A's customers

Entity Framework throws exception - Invalid object name 'dbo.BaseCs'

Instead of

modelBuilder.Entity<BaseCs>().ToTable("dbo.BaseCs");

Try:

modelBuilder.Entity<BaseCs>().ToTable("BaseCs");

even if your table name is dbo.BaseCs

How to split data into trainset and testset randomly?

Well first of all there's no such thing as "arrays" in Python, Python uses lists and that does make a difference, I suggest you use NumPy which is a pretty good library for Python and it adds a lot of Matlab-like functionality.You can get started here Numpy for Matlab users

Creating a JSON Array in node js

Build up a JavaScript data structure with the required information, then turn it into the json string at the end.

Based on what I think you're doing, try something like this:

var result = [];
for (var name in goals) {
  if (goals.hasOwnProperty(name)) {
    result.push({name: name, goals: goals[name]});
  }
}

res.contentType('application/json');
res.send(JSON.stringify(result));

or something along those lines.

Log4net does not write the log in the log file

Also, Make sure the "Copy always" option is selected for [log4net].config

enter image description here

How to minify php page html output?

You can look into HTML TIDY - http://uk.php.net/tidy

It can be installed as a PHP module and will (correctly, safely) strip whitespace and all other nastiness, whilst still outputting perfectly valid HTML / XHTML markup. It will also clean your code, which can be a great thing or a terrible thing, depending on how good you are at writing valid code in the first place ;-)

Additionally, you can gzip the output using the following code at the start of your file:

ob_start('ob_gzhandler');

How do I put double quotes in a string in vba?

Another work-around is to construct a string with a temporary substitute character. Then you can use REPLACE to change each temp character to the double quote. I use tilde as the temporary substitute character.

Here is an example from a project I have been working on. This is a little utility routine to repair a very complicated formula if/when the cell gets stepped on accidentally. It is a difficult formula to enter into a cell, but this little utility fixes it instantly.

Sub RepairFormula()
Dim FormulaString As String

FormulaString = "=MID(CELL(~filename~,$A$1),FIND(~[~,CELL(~filename~,$A$1))+1,FIND(~]~, CELL(~filename~,$A$1))-FIND(~[~,CELL(~filename~,$A$1))-1)"
FormulaString = Replace(FormulaString, Chr(126), Chr(34)) 'this replaces every instance of the tilde with a double quote.
Range("WorkbookFileName").Formula = FormulaString

This is really just a simple programming trick, but it makes entering the formula in your VBA code pretty easy.

Single controller with multiple GET methods in ASP.NET Web API

None of the above examples worked for my personal needs. The below is what I ended up doing.

 public class ContainsConstraint : IHttpRouteConstraint
{       
    public string[] array { get; set; }
    public bool match { get; set; }

    /// <summary>
    /// Check if param contains any of values listed in array.
    /// </summary>
    /// <param name="param">The param to test.</param>
    /// <param name="array">The items to compare against.</param>
    /// <param name="match">Whether we are matching or NOT matching.</param>
    public ContainsConstraint(string[] array, bool match)
    {

        this.array = array;
        this.match = match;
    }

    public bool Match(System.Net.Http.HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection)
    {
        if (values == null) // shouldn't ever hit this.                   
            return true;

        if (!values.ContainsKey(parameterName)) // make sure the parameter is there.
            return true;

        if (string.IsNullOrEmpty(values[parameterName].ToString())) // if the param key is empty in this case "action" add the method so it doesn't hit other methods like "GetStatus"
            values[parameterName] = request.Method.ToString();

        bool contains = array.Contains(values[parameterName]); // this is an extension but all we are doing here is check if string array contains value you can create exten like this or use LINQ or whatever u like.

        if (contains == match) // checking if we want it to match or we don't want it to match
            return true;
        return false;             

    }

To use the above in your route use:

config.Routes.MapHttpRoute("Default", "{controller}/{action}/{id}", new { action = RouteParameter.Optional, id = RouteParameter.Optional}, new { action = new ContainsConstraint( new string[] { "GET", "PUT", "DELETE", "POST" }, true) });

What happens is the constraint kind of fakes in the method so that this route will only match the default GET, POST, PUT and DELETE methods. The "true" there says we want to check for a match of the items in array. If it were false you'd be saying exclude those in the strYou can then use routes above this default method like:

config.Routes.MapHttpRoute("GetStatus", "{controller}/status/{status}", new { action = "GetStatus" });

In the above it is essentially looking for the following URL => http://www.domain.com/Account/Status/Active or something like that.

Beyond the above I'm not sure I'd get too crazy. At the end of the day it should be per resource. But I do see a need to map friendly urls for various reasons. I'm feeling pretty certain as Web Api evolves there will be some sort of provision. If time I'll build a more permanent solution and post.

Purpose of a constructor in Java?

A constructor initializes an object when it is created . It has the same name as its class and is syntactically similar to a method , but constructor have no expicit return type.Typically , we use constructor to give initial value to the instance variables defined by the class , or to perform any other startup procedures required to make a fully formed object.

Here is an example of constructor:

class queen(){
   int beauty;

   queen(){ 
     beauty = 98;
   }
 }


class constructor demo{
    public static void main(String[] args){
       queen arth = new queen();
       queen y = new queen();

       System.out.println(arth.beauty+" "+y.beauty);

    }
} 

output is:

98 98

Here the construcor is :

queen(){
beauty =98;
}

Now the turn of parameterized constructor.

  class queen(){
   int beauty;

   queen(int x){ 
     beauty = x;
   }
 }


class constructor demo{
    public static void main(String[] args){
       queen arth = new queen(100);
       queen y = new queen(98);

       System.out.println(arth.beauty+" "+y.beauty);

    }
} 

output is:

100 98

Sorting an array of objects by property values

Create a function and sort based on the input using below code

var homes = [{

    "h_id": "3",
    "city": "Dallas",
    "state": "TX",
    "zip": "75201",
    "price": "162500"

 }, {

    "h_id": "4",
    "city": "Bevery Hills",
    "state": "CA",
    "zip": "90210",
    "price": "319250"

 }, {

    "h_id": "5",
    "city": "New York",
    "state": "NY",
    "zip": "00010",
    "price": "962500"

 }];

 function sortList(list,order){
     if(order=="ASC"){
        return list.sort((a,b)=>{
            return parseFloat(a.price) - parseFloat(b.price);
        })
     }
     else{
        return list.sort((a,b)=>{
            return parseFloat(b.price) - parseFloat(a.price);
        });
     }
 }

 sortList(homes,'DESC');
 console.log(homes);

Use -notlike to filter out multiple strings in PowerShell

Scenario: List all computers beginning with XX1 but not names where 4th character is L or P

Get-ADComputer -Filter {(name -like "XX1*")} | Select Name | Where {($_.name -notlike "XX1L*" -and $_.name -notlike "XX1P*")}

You can also count them by enclosing the above script in parens and adding a .count method like so:

(Get-ADComputer -Filter {(name -like "XX1*")} | Select Name | Where {($_.name -notlike "XX1L*" -and $_.name -notlike "XX1P*")}).count

Why is Ant giving me a Unsupported major.minor version error

  1. Check whether u have jdk installed in the path "C:\Program Files\Java" If not Install the JDK in your machine

  2. In Eclipse, right click on "build.xml" then select Run As > External Tools Configuration

  3. Click on "JRE" tab then click on "Installed JREs" > "ADD" > "Standard VM" > Click "Next

  4. Select the Directory "C:\Program Files\Java\jdk1.7.x_xx" and the directory will be added to the "installed jres"

  5. Select the new JDK directory and Click "OK"

  6. Click on "Seperate JRE" dropdown and select the JDK version "jdk1.7.x_xx" and click on "Run"

This would help:)

how to configure config.inc.php to have a loginform in phpmyadmin

$cfg['Servers'][$i]['AllowNoPassword'] = false;

How to list processes attached to a shared memory segment in linux?

I wrote a tool called who_attach_shm.pl, it parses /proc/[pid]/maps to get the information. you can download it from github

sample output:

shm attach process list, group by shm key
##################################################################

0x2d5feab4:    /home/curu/mem_dumper /home/curu/playd
0x4e47fc6c:    /home/curu/playd
0x77da6cfe:    /home/curu/mem_dumper /home/curu/playd /home/curu/scand

##################################################################
process shm usage
##################################################################
/home/curu/mem_dumper [2]:    0x2d5feab4 0x77da6cfe
/home/curu/playd [3]:    0x2d5feab4 0x4e47fc6c 0x77da6cfe
/home/curu/scand [1]:    0x77da6cfe

Resize external website content to fit iFrame width

Tip for 1 website resizing the height. But you can change to 2 websites.

Here is my code to resize an iframe with an external website. You need insert a code into the parent (with iframe code) page and in the external website as well, so, this won't work with you don't have access to edit the external website.

  • local (iframe) page: just insert a code snippet
  • remote (external) page: you need a "body onload" and a "div" that holds all contents. And body needs to be styled to "margin:0"

Local:

<IFRAME STYLE="width:100%;height:1px" SRC="http://www.remote-site.com/" FRAMEBORDER="no" BORDER="0" SCROLLING="no" ID="estframe"></IFRAME>

<SCRIPT>
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
eventer(messageEvent,function(e) {
  if (e.data.substring(0,3)=='frm') document.getElementById('estframe').style.height = e.data.substring(3) + 'px';
},false);
</SCRIPT>

You need this "frm" prefix to avoid problems with other embeded codes like Twitter or Facebook plugins. If you have a plain page, you can remove the "if" and the "frm" prefix on both pages (script and onload).

Remote:

You need jQuery to accomplish about "real" page height. I cannot realize how to do with pure JavaScript since you'll have problem when resize the height down (higher to lower height) using body.scrollHeight or related. For some reason, it will return always the biggest height (pre-redimensioned).

<BODY onload="parent.postMessage('frm'+$('#master').height(),'*')" STYLE="margin:0">
<SCRIPT SRC="path-to-jquery/jquery.min.js"></SCRIPT>
<DIV ID="master">
your content
</DIV>

So, parent page (iframe) has a 1px default height. The script inserts a "wait for message/event" from the iframe. When a message (post message) is received and the first 3 chars are "frm" (to avoid the mentioned problem), will get the number from 4th position and set the iframe height (style), including 'px' unit.

The external site (loaded in the iframe) will "send a message" to the parent (opener) with the "frm" and the height of the main div (in this case id "master"). The "*" in postmessage means "any source".

Hope this helps. Sorry for my english.

What is a singleton in C#?

It's a design pattern and it's not specific to c#. More about it all over the internet and SO, like on this wikipedia article.

In software engineering, the singleton pattern is a design pattern that is used to restrict instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects (say, five). Some consider it an anti-pattern, judging that it is overused, introduces unnecessary limitations in situations where a sole instance of a class is not actually required, and introduces global state into an application.

You should use it if you want a class that can only be instanciated once.

Shell script to copy files from one location to another location and rename add the current date to every file

cp --archive home/webapps/project1/folder1/{aaa,bbb,ccc,ddd}.csv home/webapps/project1/folder2
rename 's/\.csv$/'$(date +%m%d%Y).csv'/' home/webapps/project1/folder2/{aaa,bbb,ccc,ddd}.csv

Explanation:

  • --archive ensures that the files are copied with the same ownership and permissions.
  • foo{bar,baz} is expanded into foobar foobaz.
  • rename is a commonly available program to do exactly this kind of substitution.

PS: don't use ls for this.

What are the differences between delegates and events?

What a great misunderstanding between events and delegates!!! A delegate specifies a TYPE (such as a class, or an interface does), whereas an event is just a kind of MEMBER (such as fields, properties, etc). And, just like any other kind of member an event also has a type. Yet, in the case of an event, the type of the event must be specified by a delegate. For instance, you CANNOT declare an event of a type defined by an interface.

Concluding, we can make the following Observation: the type of an event MUST be defined by a delegate. This is the main relation between an event and a delegate and is described in the section II.18 Defining events of ECMA-335 (CLI) Partitions I to VI:

In typical usage, the TypeSpec (if present) identifies a delegate whose signature matches the arguments passed to the event’s fire method.

However, this fact does NOT imply that an event uses a backing delegate field. In truth, an event may use a backing field of any different data structure type of your choice. If you implement an event explicitly in C#, you are free to choose the way you store the event handlers (note that event handlers are instances of the type of the event, which in turn is mandatorily a delegate type---from the previous Observation). But, you can store those event handlers (which are delegate instances) in a data structure such as a List or a Dictionary or any other else, or even in a backing delegate field. But don’t forget that it is NOT mandatory that you use a delegate field.

Use of *args and **kwargs

These parameters are typically used for proxy functions, so the proxy can pass any input parameter to the target function.

def foo(bar=2, baz=5):
    print bar, baz

def proxy(x, *args, **kwargs): # reqire parameter x and accept any number of additional arguments
    print x
    foo(*args, **kwargs) # applies the "non-x" parameter to foo

proxy(23, 5, baz='foo') # calls foo with bar=5 and baz=foo
proxy(6)# calls foo with its default arguments
proxy(7, bar='asdas') # calls foo with bar='asdas' and leave baz default argument

But since these parameters hide the actual parameter names, it is better to avoid them.

Is there a way to view past mysql queries with phpmyadmin?

you can run your past mysql with run /PATH_PAST_MYSQL/bin/mysqld.exe

it run your last mysql and you can see it in phpmyadmin and other section of your system.

notice: stop your current mysql version.

S F My English.

C# How to change font of a label

You need to create a new Font

mainForm.lblName.Font = new Font("Arial", mainForm.lblName.Font.Size);

How do I float a div to the center?

Try margin: 0 auto, the div will need a fixed with.

Getting "NoSuchMethodError: org.hamcrest.Matcher.describeMismatch" when running test in IntelliJ 10.5

The problem was that the wrong hamcrest.Matcher, not hamcrest.MatcherAssert, class was being used. That was being pulled in from a junit-4.8 dependency one of my dependencies was specifying.

To see what dependencies (and versions) are included from what source while testing, run:

mvn dependency:tree -Dscope=test

Action Image MVC3 Razor

slide modification changed Helper

     public static IHtmlString ActionImageLink(this HtmlHelper html, string action, object routeValues, string styleClass, string alt)
    {
        var url = new UrlHelper(html.ViewContext.RequestContext);
        var anchorBuilder = new TagBuilder("a");
        anchorBuilder.MergeAttribute("href", url.Action(action, routeValues));
        anchorBuilder.AddCssClass(styleClass);
        string anchorHtml = anchorBuilder.ToString(TagRenderMode.Normal);

        return new HtmlString(anchorHtml);
    }

CSS Class

.Edit {
       background: url('../images/edit.png') no-repeat right;
       display: inline-block;
       height: 16px;
       width: 16px;
      }

Create the link just pass the class name

     @Html.ActionImageLink("Edit", new { id = item.ID }, "Edit" , "Edit") 

npm install error - unable to get local issuer certificate

Try

npm config set strict-ssl false

This is a alternative shared in this url https://github.com/nodejs/node/issues/3742

How to configure multi-module Maven + Sonar + JaCoCo to give merged coverage report?

This sample works very well for me :

<plugin>
            <groupId>org.jacoco</groupId>
            <artifactId>jacoco-maven-plugin</artifactId>
            <version>0.8.2</version>
            <executions>
                <execution>
                    <id>pre-unit-test</id>
                    <goals>
                        <goal>prepare-agent</goal>
                    </goals>
                    <configuration>
                        <destFile>${project.build.directory}/coverage-reports/jacoco-ut.exec</destFile>
                        <propertyName>surefireArgLine</propertyName>
                    </configuration>
                </execution>
                <execution>
                    <id>pre-integration-test</id>
                    <goals>
                        <goal>prepare-agent-integration</goal>
                    </goals>
                    <configuration>
                        <destFile>${project.build.directory}/coverage-reports/jacoco-it.exec</destFile>
                        <!--<excludes>
                            <exclude>com.asimio.demo.rest</exclude>
                            <exclude>com.asimio.demo.service</exclude>
                        </excludes>-->
                        <propertyName>testArgLine</propertyName>
                    </configuration>
                </execution>
                <execution>
                    <id>post-integration-test</id>
                    <phase>post-integration-test</phase>
                    <goals>
                        <goal>report</goal>
                    </goals>
                    <configuration>
                        <dataFile>${project.build.directory}/coverage-reports/jacoco-it.exec</dataFile>
                        <outputDirectory>${project.reporting.outputDirectory}/jacoco-it</outputDirectory>
                    </configuration>
                </execution>
                <execution>
                    <id>post-unit-test</id>
                    <phase>prepare-package</phase>
                    <goals>
                        <goal>report</goal>
                    </goals>
                    <configuration>
                        <dataFile>${project.build.directory}/coverage-reports/jacoco-ut.exec</dataFile>
                        <outputDirectory>${project.reporting.outputDirectory}/jacoco-ut</outputDirectory>
                    </configuration>
                </execution>
                <execution>
                    <id>merge-results</id>
                    <phase>verify</phase>
                    <goals>
                        <goal>merge</goal>
                    </goals>
                    <configuration>
                        <fileSets>
                            <fileSet>
                                <directory>${project.build.directory}/coverage-reports</directory>
                                <includes>
                                    <include>*.exec</include>
                                </includes>
                            </fileSet>
                        </fileSets>
                        <destFile>${project.build.directory}/coverage-reports/aggregate.exec</destFile>
                    </configuration>
                </execution>
                <execution>
                    <id>post-merge-report</id>
                    <phase>verify</phase>
                    <goals>
                        <goal>report</goal>
                    </goals>
                    <configuration>
                        <dataFile>${project.build.directory}/coverage-reports/aggregate.exec</dataFile>
                        <outputDirectory>${project.reporting.outputDirectory}/jacoco-aggregate</outputDirectory>
                    </configuration>
                </execution>
            </executions>
        </plugin>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.18.1</version>
            <configuration>
                <argLine>${surefireArgLine}</argLine>
                <!--<skipTests>${skip.unit.tests}</skipTests>-->
                <includes>
                    <include>**/*Test.java</include>
                    <!--<include>**/*MT.java</include>
                    <include>**/*Test.java</include>-->
                </includes>
            <!--    <skipTests>${skipUTMTs}</skipTests>-->
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-failsafe-plugin</artifactId>
            <version>2.12.4</version>
            <configuration>
                <!--<skipTests>${skipTests}</skipTests>
                <skipITs>${skipITs}</skipITs>-->
                <argLine>${testArgLine}</argLine>
                <includes>
                    <include>**/*IT.java</include>
                </includes>
                <!--<excludes>
                    <exclude>**/*UT*.java</exclude>
                </excludes>-->
            </configuration>
            <executions>
                <execution>
                    <goals>
                        <goal>integration-test</goal>
                        <goal>verify</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

Have nginx access_log and error_log log to STDOUT and STDERR of master process

If the question is docker related... the official nginx docker images do this by making softlinks towards stdout/stderr

RUN ln -sf /dev/stdout /var/log/nginx/access.log && ln -sf /dev/stderr /var/log/nginx/error.log

REF: https://microbadger.com/images/nginx

How can I set multiple CSS styles in JavaScript?

I just stumbled in here and I don't see why there is so much code required to achieve this.

Add your CSS code as a string.

_x000D_
_x000D_
let styles = `_x000D_
    font-size:15em;_x000D_
    color:red;_x000D_
    transform:rotate(20deg)`_x000D_
_x000D_
document.querySelector('*').style = styles
_x000D_
a
_x000D_
_x000D_
_x000D_

How do I get 'date-1' formatted as mm-dd-yyyy using PowerShell?

    Windows PowerShell
    Copyright (C) 2014 Microsoft Corporation. All rights reserved.

    PS C:\Windows\system32> **$dte = Get-Date**
    PS C:\Windows\system32> **$PastDueDate = $dte.AddDays(-45).Date**
    PS C:\Windows\system32> **$PastDueDate**

    Sunday, March 1, 2020 12:00:00 AM

   PS C:\Windows\system32> **$NewDateFormat = Get-Date $PastDueDate -Format MMddyyyy**
   PS C:\Windows\system32> **$NewDateFormat 03012020**

There're few additional methods available as well e.g.: $dte.AddDays(-45).Day

DateTime.TryParse issue with dates of yyyy-dd-MM format

DateTime dt = DateTime.ParseExact("11-22-2012 12:00 am", "MM-dd-yyyy hh:mm tt", System.Globalization.CultureInfo.InvariantCulture);

How to break nested loops in JavaScript?

Unfortunately you'll have to set a flag or use labels (think old school goto statements)

var breakout = false;

for(i=0;i<5;i++)
{
    for(j=i+1;j<5;j++)
    {
        breakout = true;
        break;
    }
    if (breakout) break;
    alert(1)
};

The label approach looks like:

end_loops:
for(i=0;i<5;i++)
{
    for(j=i+1;j<5;j++)
    {
        break end_loops;
    }
    alert(1)
};

edit: label incorrectly placed.

also see:

In HTML5, can the <header> and <footer> tags appear outside of the <body> tag?

Even though the <head> and <body> tags aren't required, the elements are still there - it's just that the browser can work out where the tags would have been from the rest of the document.

The other elements you're using still have to be inside the <body>

What is the most effective way for float and double comparison?

I'd be very wary of any of these answers that involves floating point subtraction (e.g., fabs(a-b) < epsilon). First, the floating point numbers become more sparse at greater magnitudes and at high enough magnitudes where the spacing is greater than epsilon, you might as well just be doing a == b. Second, subtracting two very close floating point numbers (as these will tend to be, given that you're looking for near equality) is exactly how you get catastrophic cancellation.

While not portable, I think grom's answer does the best job of avoiding these issues.

Is there a way to select sibling nodes?

1) Add selected class to target element
2) Find all children of parent element excluding target element
3) Remove class from target element

 <div id = "outer">
            <div class="item" id="inner1">Div 1 </div>
            <div class="item" id="inner2">Div 2 </div>
            <div class="item" id="inner3">Div 3 </div>
            <div class="item" id="inner4">Div 4 </div>
           </div>



function getSiblings(target) {
    target.classList.add('selected');
    let siblings = document.querySelecttorAll('#outer .item:not(.currentlySelected)')
    target.classList.remove('selected'); 
return siblings
    }

Fix height of a table row in HTML Table

This works, as long as you remove the height attribute from the table.

<table id="content" border="0px" cellspacing="0px" cellpadding="0px">
  <tr><td height='9px' bgcolor="#990000">Upper</td></tr>
  <tr><td height='100px' bgcolor="#990099">Lower</td></tr>
</table>

Can I get the name of the current controller in the view?

If you want to use all stylesheet in your app just adds this line in application.html.erb. Insert it inside <head> tag

  <%= stylesheet_link_tag  controller.controller_name , media: 'all', 'data-turbolinks-track': 'reload' %>

Also, to specify the same class CSS on a different controller
Add this line in the body of application.html.erb

  <body class="<%= controller.controller_name %>-<%= controller.action_name %>">

So, now for example I would like to change the p tag in 'home' controller and 'index' action. Inside index.scss file adds.

.nameOfController-nameOfAction <tag> { }

 .home-index p {
        color:red !important;
      }

When should you NOT use a Rules Engine?

I'm a big fan of Business Rules Engines, since it can help you make your life much easier as a programmer. One of the first experiences I've had while working on a Data Warehouse project was to find Stored Procedures containing complicated CASE structures stretching over entire pages. It was a nightmare to debug, since it was very difficult to understand the logic applied in such long CASE structures, and to determine if you have an overlapping between a rule at page 1 of the code and another from page 5. Overall, we had more than 300 such rules embedded in the code.

When we've received a new development requirement, for something called Accounting Destination, which was involving treating more than 3000 rules, i knew something had to change. Back then I've been working on a prototype which later on become the parent of what now is a Custom Business Rule engine, capable of handling all SQL standard operators. Initially we've been using Excel as an authoring tool and , later on, we've created an ASP.net application which will allow the Business Users to define their own business rules, without the need of writing code. Now the system works fine, with very few bugs, and contains over 7000 rules for calculating this Accounting Destination. I don't think such scenario would have been possible by just hard-coding. And the users are pretty happy that they can define their own rules without IT becoming their bottleneck.

Still, there are limits to such approach:

  • You need to have capable business users which have an excellent understanding of the company business.
  • There is a significant workload on searching the entire system (in our case a Data Warehouse), in order to determine all hard-coded conditions which make sense to translate into rules to be handled by a Business Rule Engine. We've also had to take good care that these initial templates to be fully understandable by Business Users.
  • You need to have an application used for rules authoring, in which algorithms for detection of overlapping business rules is implemented. Otherwise you'll end up with a big mess, where no one understands anymore the results they get. When you have a bug in a generic component like a Custom Business Rule Engine, it can be very difficult to debug and involve extensive tests to make sure that things that worked before also work now.

More details on this topic can be found on a post I've written: http://dwhbp.com/post/2011/10/30/Implementing-a-Business-Rule-Engine.aspx

Overall, the biggest advantage of using a Business Rule Engines is that it allows the users to take back control over the Business Rule definitions and authoring, without the need of going to the IT department each time they need to modify something. It also the reduces the workload over IT development teams, which can now focus on building stuff with more added value.

Cheers,

Nicolae

SQL time difference between two dates result in hh:mm:ss

I came across this post today as I was trying to gather the time difference between fields located in separate tables joined together on a key field. This is the working code for such an endeavor. (tested in sql 2010) Bare in mind that my original query co-joined 6 tables on a common keyfield, in the code below I have removed the other tables as to not cause any confusion for the reader.

The purpose of the query is to calculate the difference between the variables CreatedUTC & BackupUTC, where difference is expressed in days and the field is called 'DaysActive.'

declare @CreatedUTC datetime
declare @BackupUtc datetime


SELECT TOP 500

table02.Column_CreatedUTC AS DeviceCreated,
CAST(DATEDIFF(day, table02.Column_CreatedUTC, table03.Column_EndDateUTC) AS nvarchar(5))+ ' Days' As DaysActive,
table03.Column_EndDateUTC AS LastCompleteBackup

FROM

Operations.table01 AS table01

LEFT OUTER JOIN

    dbo.table02 AS table02
ON
    table02.Column_KeyField = table01.Column_KeyField

LEFT OUTER JOIN 

    dbo.table03 AS table03
ON
    table01.Column_KeyField = table03.Column_KeyField

Where table03.Column_EndDateUTC > dateadd(hour, -24, getutcdate()) --Gathers records with an end date in the last 24 hours
AND table02.[Column_CreatedUTC] = COALESCE(@CreatedUTC, table02.[Column_CreatedUTC])
AND table03.[Column_EndDateUTC] = COALESCE(@BackupUTC, table03.[Column_EndDateUTC])

GROUP BY table03.Column_EndDateUTC, table02.Column_CreatedUTC
ORDER BY table02.Column_CreatedUTC ASC, DaysActive, table03.Column_EndDateUTC DESC

The Output will be as follows:

[DeviceCreated]..[DaysActive]..[LastCompleteBackup]
---------------------------------------------------------
[2/13/12 16:04]..[463 Days]....[5/21/13 12:14]
[2/12/13 22:37]..[97 Days].....[5/20/13 22:10]

jQuery select by attribute using AND and OR operators

In your special case it would be

a=$('[myc="blue"][myid="1"],[myc="blue"][myid="3"]');

Sublime text 3. How to edit multiple lines?

Select multiple lines by clicking first line then holding shift and clicking last line. Then press:

CTRL+SHIFT+L

or on MAC: CMD+SHIFT+L (as per comments)

Alternatively you can select lines and go to SELECTION MENU >> SPLIT INTO LINES.

Now you can edit multiple lines, move cursors etc. for all selected lines.

What is w3wp.exe?

Chris pretty much sums up what w3wp is. In order to disable the warning, go to this registry key:

HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\10.0\Debugger

And set the value DisableAttachSecurityWarning to 1.

If statement in select (ORACLE)

use the variable, Oracle does not support SQL in that context without an INTO. With a properly named variable your code will be more legible anyway.

error UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

Check the path of the file to be read. My code kept on giving me errors until I changed the path name to present working directory. The error was:

newchars, decodedbytes = self.decode(data, self.errors)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

Sending private messages to user

Make the code say if (msg.content === ('trigger') msg.author.send('text')}

How to show text in combobox when no item selected?

Here you can find solution created by pavlo_ua: If you have .Net > 2.0 and If you have .Net == 2.0 (search for pavlo_ua answer)

Cheers, jbk

edit: So to have clear answer not just link

You can set Text of combobox when its style is set as DropDown (and it is editable). When you have .Net version < 3.0 there is no IsReadonly property so we need to use win api to set textbox of combobox as readonly:

private bool m_readOnly = false;
private const int EM_SETREADONLY = 0x00CF;

internal delegate bool EnumChildWindowsCallBack( IntPtr hwnd, IntPtr lParam );

[DllImport("user32.dll", CharSet = CharSet.Auto)]
internal static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);

[ DllImport( "user32.dll" ) ]
internal static extern int EnumChildWindows( IntPtr hWndParent, EnumChildWindowsCallBack lpEnumFunc, IntPtr lParam );


private bool EnumChildWindowsCallBackFunction(IntPtr hWnd, IntPtr lparam)
{
      if( hWnd != IntPtr.Zero )
       {
              IntPtr readonlyValue = ( m_readOnly ) ? new IntPtr( 1 ) : IntPtr.Zero;
             SendMessage( hWnd, EM_SETREADONLY, readonlyValue, IntPtr.Zero );
             comboBox1.Invalidate();
             return true;
       }
       return false;
}

private void MakeComboBoxReadOnly( bool readOnly )
{
    m_readOnly = readOnly;
    EnumChildWindowsCallBack callBack = new EnumChildWindowsCallBack(this.EnumChildWindowsCallBackFunction );
    EnumChildWindows( comboBox1.Handle, callBack, IntPtr.Zero );
}

Bash: Syntax error: redirection unexpected

Docker:

I was getting this problem from my Dockerfile as I had:

RUN bash < <(curl -s -S -L https://raw.githubusercontent.com/moovweb/gvm/master/binscripts/gvm-installer)

However, according to this issue, it was solved:

The exec form makes it possible to avoid shell string munging, and to RUN commands using a base image that does not contain /bin/sh.

Note

To use a different shell, other than /bin/sh, use the exec form passing in the desired shell. For example,

RUN ["/bin/bash", "-c", "echo hello"]

Solution:

RUN ["/bin/bash", "-c", "bash < <(curl -s -S -L https://raw.githubusercontent.com/moovweb/gvm/master/binscripts/gvm-installer)"]

Notice the quotes around each parameter.

Replace console output in Python

Below code will count Message from 0 to 137 each 0.3 second replacing previous number.

Number of symbol to backstage = number of digits.

stream = sys.stdout
for i in range(137):
    stream.write('\b' * (len(str(i)) + 10))
    stream.write("Message : " + str(i))
    stream.flush()
    time.sleep(0.3)

What is PostgreSQL equivalent of SYSDATE from Oracle?

The following functions are available to obtain the current date and/or time in PostgreSQL:

CURRENT_TIME

CURRENT_DATE

CURRENT_TIMESTAMP

Example

SELECT CURRENT_TIME;
08:05:18.864750+05:30

SELECT CURRENT_DATE;
2020-05-14

SELECT CURRENT_TIMESTAMP;
2020-05-14 08:04:51.290498+05:30

postgresql docs

How do I specify "not equals to" when comparing strings in an XSLT <xsl:if>?

As Filburt says; but also note that it's usually better to write

test="not(Count = 'N/A')"

If there's exactly one Count element they mean the same thing, but if there's no Count, or if there are several, then the meanings are different.

6 YEARS LATER

Since this answer seems to have become popular, but may be a little cryptic to some readers, let me expand it.

The "=" and "!=" operator in XPath can compare two sets of values. In general, if A and B are sets of values, then "=" returns true if there is any pair of values from A and B that are equal, while "!=" returns true if there is any pair that are unequal.

In the common case where A selects zero-or-one nodes, and B is a constant (say "NA"), this means that not(A = "NA") returns true if A is either absent, or has a value not equal to "NA". By contrast, A != "NA" returns true if A is present and not equal to "NA". Usually you want the "absent" case to be treated as "not equal", which means that not(A = "NA") is the appropriate formulation.

Pythonic way to check if a list is sorted or not

Although I don't think there is a guarantee for that the sorted built-in calls its cmp function with i+1, i, it does seem to do so for CPython.

So you could do something like:

def my_cmp(x, y):
   cmpval = cmp(x, y)
   if cmpval < 0:
      raise ValueError
   return cmpval

def is_sorted(lst):
   try:
      sorted(lst, cmp=my_cmp)
      return True
   except ValueError:
      return False

print is_sorted([1,2,3,5,6,7])
print is_sorted([1,2,5,3,6,7])

Or this way (without if statements -> EAFP gone wrong? ;-) ):

def my_cmp(x, y):
   assert(x >= y)
   return -1

def is_sorted(lst):
   try:
      sorted(lst, cmp=my_cmp)
      return True
   except AssertionError:
      return False

Most common C# bitwise operations on enums

C++ operations are: & | ^ ~ (for and, or, xor and not bitwise operations). Also of interest are >> and <<, which are bitshift operations.

So, to test for a bit being set in a flag, you would use: if (flags & 8) //tests bit 4 has been set

"Could not get any response" response when using postman with subdomain

Hi This issue is resolved for me.

setting ->general -> Requesttimeout in ms = 0

ModuleNotFoundError: What does it mean __main__ is not a package?

The problem still not resolved after remove the '.', then it start points the error to my folder. As i added this folder first time then i restarted the PyCharm and it automatically resolved the issue

SQL query with avg and group by

As I understand, you want the average value for each id at each pass. The solution is

SELECT id, pass, avg(value) FROM data_r1
GROUP BY id, pass;

Convert System.Drawing.Color to RGB and Hex Value

e.g.

 ColorTranslator.ToHtml(Color.FromArgb(Color.Tomato.ToArgb()))

This can avoid the KnownColor trick.

Print a list of space-separated elements in Python 3

You can apply the list as separate arguments:

print(*L)

and let print() take care of converting each element to a string. You can, as always, control the separator by setting the sep keyword argument:

>>> L = [1, 2, 3, 4, 5]
>>> print(*L)
1 2 3 4 5
>>> print(*L, sep=', ')
1, 2, 3, 4, 5
>>> print(*L, sep=' -> ')
1 -> 2 -> 3 -> 4 -> 5

Unless you need the joined string for something else, this is the easiest method. Otherwise, use str.join():

joined_string = ' '.join([str(v) for v in L])
print(joined_string)
# do other things with joined_string

Note that this requires manual conversion to strings for any non-string values in L!

ASP.NET MVC DropDownListFor with model of type List<string>

If you have a List of type string that you want in a drop down list I do the following:

EDIT: Clarified, making it a fuller example.

public class ShipDirectory
{
    public string ShipDirectoryName { get; set; }
    public List<string> ShipNames { get; set; }
}

ShipDirectory myShipDirectory = new ShipDirectory()
{
    ShipDirectoryName = "Incomming Vessels",
    ShipNames = new List<string>(){"A", "A B"},
}

myShipDirectory.ShipNames.Add("Aunt Bessy");

@Html.DropDownListFor(x => x.ShipNames, new SelectList(Model.ShipNames), "Select a Ship...", new { @style = "width:500px" })

Which gives a drop down list like so:

<select id="ShipNames" name="ShipNames" style="width:500px">
    <option value="">Select a Ship...</option>
    <option>A</option>
    <option>A B</option>
    <option>Aunt Bessy</option>
</select>

To get the value on a controllers post; if you are using a model (e.g. MyViewModel) that has the List of strings as a property, because you have specified x => x.ShipNames you simply have the method signature as (because it will be serialised/deserialsed within the model):

public ActionResult MyActionName(MyViewModel model)

Access the ShipNames value like so: model.ShipNames

If you just want to access the drop down list on post then the signature becomes:

public ActionResult MyActionName(string ShipNames)

EDIT: In accordance with comments have clarified how to access the ShipNames property in the model collection parameter.

How to find where javaw.exe is installed?

Open a cmd shell,

cd \\
dir javaw.exe /s

Stack, Static, and Heap in C++

Stack memory allocation (function variables, local variables) can be problematic when your stack is too "deep" and you overflow the memory available to stack allocations. The heap is for objects that need to be accessed from multiple threads or throughout the program lifecycle. You can write an entire program without using the heap.

You can leak memory quite easily without a garbage collector, but you can also dictate when objects and memory is freed. I have run in to issues with Java when it runs the GC and I have a real time process, because the GC is an exclusive thread (nothing else can run). So if performance is critical and you can guarantee there are no leaked objects, not using a GC is very helpful. Otherwise it just makes you hate life when your application consumes memory and you have to track down the source of a leak.

Notepad++ Multi editing

Notepad++ has a powerful regex engine, capable to search and replace patterns at will.

In your scenario:

  1. Click the menu item Search\Replace...

  2. Fill the 'Find what' field with the search pattern:

    ^(\d{4})\s+(\w{3})\s+(\w{3})$
    
  3. Fill the replace pattern:

    Insert into tbl (\1, \2) where clm = \3
    
  4. Click the Replace All button.

And that's it.

NotePad++ replace window screenshot

adding to window.onload event?

This might not be a popular option, but sometimes the scripts end up being distributed in various chunks, in that case I've found this to be a quick fix

if(window.onload != null){var f1 = window.onload;}
window.onload=function(){
    //do something

    if(f1!=null){f1();}
}

then somewhere else...

if(window.onload != null){var f2 = window.onload;}
window.onload=function(){
    //do something else

    if(f2!=null){f2();}
}

this will update the onload function and chain as needed

event.returnValue is deprecated. Please use the standard event.preventDefault() instead

This is only a warning: your code still works, but probably won't work in the future as the method is deprecated. See the relevant source of Chromium and corresponding patch.

This has already been recognised and fixed in jQuery 1.11 (see here and here).

How to make a new line or tab in <string> XML (eclipse/android)?

Add '\t' for tab

<string name="tab">\u0009</string>

What is an efficient way to implement a singleton pattern in Java?

Make sure that you really need it. Do a google search for "singleton anti-pattern" to see some arguments against it.

There's nothing inherently wrong with it I suppose, but it's just a mechanism for exposing some global resource/data so make sure that this is the best way. In particular, I've found dependency injection (DI) more useful particularly if you are also using unit tests, because DI allows you to use mocked resources for testing purposes.

Eclipse does not highlight matching variables

If highlighting is not working for large files, scalability mode has to be off. Properties / (c/c++) / Editor / Scalability

Syntax error due to using a reserved word as a table or column name in MySQL

The Problem

In MySQL, certain words like SELECT, INSERT, DELETE etc. are reserved words. Since they have a special meaning, MySQL treats it as a syntax error whenever you use them as a table name, column name, or other kind of identifier - unless you surround the identifier with backticks.

As noted in the official docs, in section 10.2 Schema Object Names (emphasis added):

Certain objects within MySQL, including database, table, index, column, alias, view, stored procedure, partition, tablespace, and other object names are known as identifiers.

...

If an identifier contains special characters or is a reserved word, you must quote it whenever you refer to it.

...

The identifier quote character is the backtick ("`"):

A complete list of keywords and reserved words can be found in section 10.3 Keywords and Reserved Words. In that page, words followed by "(R)" are reserved words. Some reserved words are listed below, including many that tend to cause this issue.

  • ADD
  • AND
  • BEFORE
  • BY
  • CALL
  • CASE
  • CONDITION
  • DELETE
  • DESC
  • DESCRIBE
  • FROM
  • GROUP
  • IN
  • INDEX
  • INSERT
  • INTERVAL
  • IS
  • KEY
  • LIKE
  • LIMIT
  • LONG
  • MATCH
  • NOT
  • OPTION
  • OR
  • ORDER
  • PARTITION
  • RANK
  • REFERENCES
  • SELECT
  • TABLE
  • TO
  • UPDATE
  • WHERE

The Solution

You have two options.

1. Don't use reserved words as identifiers

The simplest solution is simply to avoid using reserved words as identifiers. You can probably find another reasonable name for your column that is not a reserved word.

Doing this has a couple of advantages:

  • It eliminates the possibility that you or another developer using your database will accidentally write a syntax error due to forgetting - or not knowing - that a particular identifier is a reserved word. There are many reserved words in MySQL and most developers are unlikely to know all of them. By not using these words in the first place, you avoid leaving traps for yourself or future developers.

  • The means of quoting identifiers differs between SQL dialects. While MySQL uses backticks for quoting identifiers by default, ANSI-compliant SQL (and indeed MySQL in ANSI SQL mode, as noted here) uses double quotes for quoting identifiers. As such, queries that quote identifiers with backticks are less easily portable to other SQL dialects.

Purely for the sake of reducing the risk of future mistakes, this is usually a wiser course of action than backtick-quoting the identifier.

2. Use backticks

If renaming the table or column isn't possible, wrap the offending identifier in backticks (`) as described in the earlier quote from 10.2 Schema Object Names.

An example to demonstrate the usage (taken from 10.3 Keywords and Reserved Words):

mysql> CREATE TABLE interval (begin INT, end INT);
ERROR 1064 (42000): You have an error in your SQL syntax.
near 'interval (begin INT, end INT)'

mysql> CREATE TABLE `interval` (begin INT, end INT); Query OK, 0 rows affected (0.01 sec)

Similarly, the query from the question can be fixed by wrapping the keyword key in backticks, as shown below:

INSERT INTO user_details (username, location, `key`)
VALUES ('Tim', 'Florida', 42)";               ^   ^

Vertically aligning a checkbox

make input to block and float, Adjust margin top value.

HTML:

<div class="label">
<input type="checkbox" name="test" /> luke..
</div>

CSS:

/*
change margin-top, if your line-height is different.
*/
input[type=checkbox]{
height:18px;
width:18px;
padding:0;
margin-top:5px;
display:block;
float:left;
}
.label{
border:1px solid red;
}

Demo

css divide width 100% to 3 column

A perfect 1/3 cannot exist in CSS with full cross browser support (anything below IE9). I personally would do: (It's not the perfect solution, but it's about as good as you'll get for all browsers)

#c1, #c2 {
    width: 33%;
}

#c3 {
    width: auto;
}

Using headers with the Python requests library's get method

According to the API, the headers can all be passed in using requests.get:

import requests
r=requests.get("http://www.example.com/", headers={"content-type":"text"})

How can I assign the output of a function to a variable using bash?

I think init_js should use declare instead of local!

function scan3() {
    declare -n outvar=$1    # -n makes it a nameref.
    local nl=$'\x0a'
    outvar="output${nl}${nl}"  # two total. quotes preserve newlines
}

Stylesheet not loaded because of MIME-type

I had this problem with a site I knew worked online when I moved it to localhost and PhpStorm.

This worked fine online:

    <link rel="stylesheet" href="/css/additional.css">

But for localhost I needed to get rid of the slash:

    <link rel="stylesheet" href="css/additional.css">

So I am reinforcing a few answers provided here already - it is likely to be a path or spelling mistake rather than any complicated server setup problem. The error in the console is a red herring; the network tab needs to be checked for the 404 first.

Among the answers provided here are a few solutions that are not correct. The addition of type="text/html" or changing href to src is not the answer.

If you want to have all of the attributes so it validates on the pickiest of validators and your IDE then the media value should be provided and the rel should be stylesheet, e.g.:

    <link rel="stylesheet" href="css/additional.css" type="text/css" media="all">

How to label scatterplot points by name?

Another convoluted answer which should technically work and is ok for a small number of data points is to plot all your data points as 1 series in order to get your connecting line. Then plot each point as its own series. Then format data labels to display series name for each of the individual data points.

In short it works ok for a small data set or just key points from a data set.

Looking for a short & simple example of getters/setters in C#

Getters and Setters in C# are something that simplifies the code.

private string name = "spots";

public string Name
{
    get { return name; }
    set { name = value; }
}

And calling it (assume we have a person obj with a name property):

Console.WriteLine(Person.Name); //prints "spots"
Person.Name = "stops";
Console.Writeline(Person.Name); //prints "stops"

This simplifies your code. Where in Java you might have to have two methods, one to Get() and one to Set() the property, in C# it is all done in one spot. I usually do this at the start of my classes:

public string foobar {get; set;}

This creates a getter and setter for my foobar property. Calling it is the same way as shown before. Somethings to note are that you don't have to include both get and set. If you don't want the property being modified, don't include set!

How to round double to nearest whole number and then convert to a float?

float b = (float)Math.ceil(a); or float b = (float)Math.round(a);

Depending on whether you meant "round to the nearest whole number" (round) or "round up" (ceil).

Beware of loss of precision in converting a double to a float, but that shouldn't be an issue here.

Check a radio button with javascript

Easiest way would probably be with jQuery, as follows:

$(document).ready(function(){
  $("#_1234").attr("checked","checked");
})

This adds a new attribute "checked" (which in HTML does not need a value). Just remember to include the jQuery library:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

How to install plugin for Eclipse from .zip

It depends on what the zip contains. Take a look to see if it got content.jar and artifacts.jar. If it does, it is an archived updated site. Install from it the same way as you install from a remote site.

If the zip doesn't contain content.jar and artifacts.jar, go to your Eclipse install's dropins directory, create a subfolder (name doesn't matter) and expand your zip into that folder. Restart Eclipse.

Easy way of running the same junit test over and over?

This is essentially the answer that Yishai provided above, re-written in Kotlin :

@RunWith(Parameterized::class)
class MyTest {

    companion object {

        private const val numberOfTests = 200

        @JvmStatic
        @Parameterized.Parameters
        fun data(): Array<Array<Any?>> = Array(numberOfTests) { arrayOfNulls<Any?>(0) }
    }

    @Test
    fun testSomething() { }
}

What is a unix command for deleting the first N characters of a line?

sed 's/^.\{5\}//' logfile 

and you replace 5 by the number you want...it should do the trick...

EDIT if for each line sed 's/^.\{5\}//g' logfile

How can I break up this long line in Python?

You can use textwrap module to break it in multiple lines

import textwrap
str="ABCDEFGHIJKLIMNO"
print("\n".join(textwrap.wrap(str,8)))

ABCDEFGH
IJKLIMNO

From the documentation:

textwrap.wrap(text[, width[, ...]])
Wraps the single paragraph in text (a string) so every line is at most width characters long. Returns a list of output lines, without final newlines.

Optional keyword arguments correspond to the instance attributes of TextWrapper, documented below. width defaults to 70.

See the TextWrapper.wrap() method for additional details on how wrap() behaves.

How can I prevent the textarea from stretching beyond his parent DIV element? (google-chrome issue only)

To disable resizing completely:

textarea {
    resize: none;
}

To allow only vertical resizing:

textarea {
    resize: vertical;
}

To allow only horizontal resizing:

textarea {
    resize: horizontal;
}

Or you can limit size:

textarea {
    max-width: 100px; 
    max-height: 100px;
}

To limit size to parents width and/or height:

textarea {
    max-width: 100%; 
    max-height: 100%;
}

How to split a number into individual digits in c#?

Substring and Join methods are usable for this statement.

string no = "12345";
string [] numberArray = new string[no.Length];
int counter = 0;

   for (int i = 0; i < no.Length; i++)
   {
     numberArray[i] = no.Substring(counter, 1); // 1 is split length
     counter++;
   }

Console.WriteLine(string.Join(" ", numberArray)); //output >>> 0 1 2 3 4 5

How to send a pdf file directly to the printer using JavaScript?

Try this: Have a button/link which opens a webpage (in a new window) with just the pdf file embedded in it, and print the webpage.

In head of the main page:

<script type="text/javascript">
function printpdf() 
{
myWindow=window.open("pdfwebpage.html");
myWindow.close;  //optional, to close the new window as soon as it opens
//this ensures user doesn't have to close the pop-up manually
}
</script>

And in body of the main page:

<a href="printpdf()">Click to Print the PDF</a>

Inside pdfwebpage.html:

<html>
<head>    
</head>

<body onload="window.print()">
<embed src="pdfhere.pdf"/>

</body>
</html>

How to perform a LEFT JOIN in SQL Server between two SELECT statements?

SELECT [UserID] FROM [User] u LEFT JOIN (
SELECT [TailUser], [Weight] FROM [Edge] WHERE [HeadUser] = 5043) t on t.TailUser=u.USerID

How to use Java property files?

  • You can store the file anywhere you like. If you want to keep it in your jar file, you'll want to use Class.getResourceAsStream() or ClassLoader.getResourceAsStream() to access it. If it's on the file system it's slightly easier.

  • Any extension is fine, although .properties is more common in my experience

  • Load the file using Properties.load, passing in an InputStream or a StreamReader if you're using Java 6. (If you are using Java 6, I'd probably use UTF-8 and a Reader instead of the default ISO-8859-1 encoding for a stream.)

  • Iterate through it as you'd iterate through a normal Hashtable (which Properties derives from), e.g. using keySet(). Alternatively, you can use the enumeration returned by propertyNames().

BitBucket - download source as ZIP

In case you want to download the repo from your shell/terminal it should work like this:

wget https://user:[email protected]/user-name/repo-name/get/master.tar.bz2

or whatever download URL you might have.

Please make sure the user:password are both URL-encoded. So for instance if your username contains the @ symbol then replace it with %40.

how to "execute" make file

As paxdiablo said make -f pax.mk would execute the pax.mk makefile, if you directly execute it by typing ./pax.mk, then you would get syntax error.

Also you can just type make if your file name is makefile/Makefile.

Suppose you have two files named makefile and Makefile in the same directory then makefile is executed if make alone is given. You can even pass arguments to makefile.

Check out more about makefile at this Tutorial : Basic understanding of Makefile

Fixing slow initial load for IIS

Options A, B and D seem to be in the same category since they only influence the initial start time, they do warmup of the website like compilation and loading of libraries in memory.

Using C, setting the idle timeout, should be enough so that subsequent requests to the server are served fast (restarting the app pool takes quite some time - in the order of seconds).

As far as I know, the timeout exists to save memory that other websites running in parallel on that machine might need. The price being that one time slow load time.

Besides the fact that the app pool gets shutdown in case of user inactivity, the app pool will also recycle by default every 1740 minutes (29 hours).

From technet:

Internet Information Services (IIS) application pools can be periodically recycled to avoid unstable states that can lead to application crashes, hangs, or memory leaks.

As long as app pool recycling is left on, it should be enough. But if you really want top notch performance for most components, you should also use something like the Application Initialization Module you mentioned.

I get a "An attempt was made to load a program with an incorrect format" error on a SQL Server replication project

Change the value for Platform Target on your web project's property page to Any CPU.

enter image description here

UILabel - auto-size label to fit text?

Using [label sizeToFit]; will achieve the same result from Daniels Category.

Although I recommend to use autolayout and let the label resize itself based on constraints.

How should I multiple insert multiple records?

You can directly insert a DataTable if it is created correctly.

First make sure that the access table columns have the same column names and similar types. Then you can use this function which I believe is very fast and elegant.

public void AccessBulkCopy(DataTable table)
{
    foreach (DataRow r in table.Rows)
        r.SetAdded();

    var myAdapter = new OleDbDataAdapter("SELECT * FROM " + table.TableName, _myAccessConn);

    var cbr = new OleDbCommandBuilder(myAdapter);
    cbr.QuotePrefix = "[";
    cbr.QuoteSuffix = "]";
    cbr.GetInsertCommand(true);

    myAdapter.Update(table);
}

What is a .NET developer?

Most .NET jobs I've run across also either explicitly or implicitly assume some knowledge of SQL-based RDBMSes. While it's not "part of the description", it's usually part of the job.

Mapping over values in a python dictionary

To avoid doing indexing from inside lambda, like:

rval = dict(map(lambda kv : (kv[0], ' '.join(kv[1])), rval.iteritems()))

You can also do:

rval = dict(map(lambda(k,v) : (k, ' '.join(v)), rval.iteritems()))

Getting the PublicKeyToken of .Net assemblies

You can get this easily via c#

private static string GetPublicKeyTokenFromAssembly(Assembly assembly)
{
    var bytes = assembly.GetName().GetPublicKeyToken();
    if (bytes == null || bytes.Length == 0)
        return "None";

    var publicKeyToken = string.Empty;
    for (int i = 0; i < bytes.GetLength(0); i++)
        publicKeyToken += string.Format("{0:x2}", bytes[i]);

    return publicKeyToken;
}

How do I remove diacritics (accents) from a string in .NET?

The CodePage of Greek (ISO) can do it

The information about this codepage is into System.Text.Encoding.GetEncodings(). Learn about in: https://msdn.microsoft.com/pt-br/library/system.text.encodinginfo.getencoding(v=vs.110).aspx

Greek (ISO) has codepage 28597 and name iso-8859-7.

Go to the code... \o/

string text = "Você está numa situação lamentável";

string textEncode = System.Web.HttpUtility.UrlEncode(text, Encoding.GetEncoding("iso-8859-7"));
//result: "Voce+esta+numa+situacao+lamentavel"

string textDecode = System.Web.HttpUtility.UrlDecode(textEncode);
//result: "Voce esta numa situacao lamentavel"

So, write this function...

public string RemoveAcentuation(string text)
{
    return
        System.Web.HttpUtility.UrlDecode(
            System.Web.HttpUtility.UrlEncode(
                text, Encoding.GetEncoding("iso-8859-7")));
}

Note that... Encoding.GetEncoding("iso-8859-7") is equivalent to Encoding.GetEncoding(28597) because first is the name, and second the codepage of Encoding.

Printing the correct number of decimal points with cout

with templates

#include <iostream>

// d = decimal places
template<int d> 
std::ostream& fixed(std::ostream& os){
    os.setf(std::ios_base::fixed, std::ios_base::floatfield); 
    os.precision(d); 
    return os; 
}

int main(){
    double d = 122.345;
    std::cout << fixed<2> << d;
}

similar for scientific as well, with a width option also (useful for columns)

// d = decimal places
template<int d> 
std::ostream& f(std::ostream &os){
    os.setf(std::ios_base::fixed, std::ios_base::floatfield); 
    os.precision(d); 
    return os; 
}

// w = width, d = decimal places
template<int w, int d> 
std::ostream& f(std::ostream &os){
    os.setf(std::ios_base::fixed, std::ios_base::floatfield); 
    os.precision(d); 
    os.width(w);
    return os; 
}

// d = decimal places
template<int d> 
std::ostream& e(std::ostream &os){
    os.setf(std::ios_base::scientific, std::ios_base::floatfield); 
    os.precision(d); 
    return os; 
}

// w = width, d = decimal places
template<int w, int d> 
std::ostream& e(std::ostream &os){
    os.setf(std::ios_base::scientific, std::ios_base::floatfield); 
    os.precision(d); 
    os.width(w);
    return os; 
}

int main(){
    double d = 122.345;
    std::cout << f<10,2> << d << '\n'
        << e<10,2> << d << '\n';
}

Disable Proximity Sensor during call

I found my solution here. Basically use an app called Proximity Screen Off Lite and set it as below:

  1. Screen On/Off Modes Check "Cover and hold to turn on Screen" Timeout: 1 second Check "Disable Accidentla Lock" Timeout: 4 seconds

  2. All settings Check "Disable in Lanscape" Check "Lock phone on screen ON"

  3. [Advanced] Configure Sensore Select sensor: Proximity sensor Value when sensor covered: 0 Value when sensor un-covered: 1

How do you uninstall all dependencies listed in package.json (NPM)?

Even you don't need to run the loop for that.

You can delete all the node_modules by using the only single command:-

npm uninstall `ls -1 node_modules | tr '/\n' ' '`

Load a Bootstrap popover content with AJAX. Is this possible?

IN 2015, this is the best answer

$('.popup-ajax').mouseenter(function() {
   var i = this
   $.ajax({
      url: $(this).attr('data-link'), 
      dataType: "html", 
      cache:true, 
      success: function( data{
         $(i).popover({
            html:true,
            placement:'left',
            title:$(i).html(),
            content:data
         }).popover('show')
      }
   })
});

$('.popup-ajax').mouseout(function() {
  $('.popover:visible').popover('destroy')
});

How to get a URL parameter in Express?

If you want to grab the query parameter value in the URL, follow below code pieces

//url.localhost:8888/p?tagid=1234
req.query.tagid
OR
req.param.tagid

If you want to grab the URL parameter using Express param function

Express param function to grab a specific parameter. This is considered middleware and will run before the route is called.

This can be used for validations or grabbing important information about item.

An example for this would be:

// parameter middleware that will run before the next routes
app.param('tagid', function(req, res, next, tagid) {

// check if the tagid exists
// do some validations
// add something to the tagid
var modified = tagid+ '123';

// save name to the request
req.tagid= modified;

next();
});

// http://localhost:8080/api/tags/98
app.get('/api/tags/:tagid', function(req, res) {
// the tagid was found and is available in req.tagid
res.send('New tag id ' + req.tagid+ '!');
});

Should I declare Jackson's ObjectMapper as a static field?

Although ObjectMapper is thread safe, I would strongly discourage from declaring it as a static variable, especially in multithreaded application. Not even because it is a bad practice, but because you are running a heavy risk of deadlocking. I am telling it from my own experience. I created an application with 4 identical threads that were getting and processing JSON data from web services. My application was frequently stalling on the following command, according to the thread dump:

Map aPage = mapper.readValue(reader, Map.class);

Beside that, performance was not good. When I replaced static variable with the instance based variable, stalling disappeared and performance quadrupled. I.e. 2.4 millions JSON documents were processed in 40min.56sec., instead of 2.5 hours previously.

Plotting a 2D heatmap with Matplotlib

I would use matplotlib's pcolor/pcolormesh function since it allows nonuniform spacing of the data.

Example taken from matplotlib:

import matplotlib.pyplot as plt
import numpy as np

# generate 2 2d grids for the x & y bounds
y, x = np.meshgrid(np.linspace(-3, 3, 100), np.linspace(-3, 3, 100))

z = (1 - x / 2. + x ** 5 + y ** 3) * np.exp(-x ** 2 - y ** 2)
# x and y are bounds, so z should be the value *inside* those bounds.
# Therefore, remove the last value from the z array.
z = z[:-1, :-1]
z_min, z_max = -np.abs(z).max(), np.abs(z).max()

fig, ax = plt.subplots()

c = ax.pcolormesh(x, y, z, cmap='RdBu', vmin=z_min, vmax=z_max)
ax.set_title('pcolormesh')
# set the limits of the plot to the limits of the data
ax.axis([x.min(), x.max(), y.min(), y.max()])
fig.colorbar(c, ax=ax)

plt.show()

pcolormesh plot output

Download File Using jQuery

By stating window.location.href = 'uploads/file.doc'; you show where you store your files. You might of course use .htacess to force the required behaviour for stored files, but this might not always be handful....

It is better to create a server side php-file and place this content in it:

header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.$_REQUEST['f']);
readfile('../some_folder/some_subfolder/'.$_REQUEST['f']); 
exit;

This code will return ANY file as a download without showing where you actually store it.

You open this php-file via window.location.href = 'scripts/this_php_file.php?f=downloaded_file';

Cast IList to List

In my case I had to do this, because none of the suggested solutions were available:

List<SubProduct> subProducts = Model.subproduct.Cast<SubProduct>().ToList();

How to remove carriage return and newline from a variable in shell script

You can use sed as follows:

MY_NEW_VAR=$(echo $testVar | sed -e 's/\r//g')
echo ${MY_NEW_VAR} got it

By the way, try to do a dos2unix on your data file.

Javascript Click on Element by Class

If you want to click on all elements selected by some class, you can use this example (used on last.fm on the Loved tracks page to Unlove all).

var divs = document.querySelectorAll('.love-button.love-button--loved'); 

for (i = 0; i < divs.length; ++i) {
  divs[i].click();
};

With ES6 and Babel (cannot be run in the browser console directly)

[...document.querySelectorAll('.love-button.love-button--loved')]
   .forEach(div => { div.click(); })

Angular JS - angular.forEach - How to get key of the object?

The first parameter to the iterator in forEach is the value and second is the key of the object.

angular.forEach(objectToIterate, function(value, key) {
    /* do something for all key: value pairs */
});

In your example, the outer forEach is actually:

angular.forEach($scope.filters, function(filterObj , filterKey)

What is the difference between application server and web server?

As Rutesh and jmservera pointed out, the distinction is a fuzzy one. Historically, they were different, but through the 90's these two previously distinct categories blended features and effectively merged. At this point is is probably best to imagine that the "App Server" product category is a strict superset of the "web server" category.

Some history. In early days of the Mosaic browser and hyperlinked content, there evolved this thing called a "web server" that served web page content and images over HTTP. Most of the content was static, and the HTTP 1.0 protocol was just a way to ship files around. Quickly the "web server" category evolved to include CGI capability - effectively launching a process on each web request to generate dynamic content. HTTP also matured and the products became more sophisticated, with caching, security, and management features. As the technology matured, we got company-specific Java-based server-side technology from Kiva and NetDynamics, which eventually all merged into JSP. Microsoft added ASP, I think in 1996, to Windows NT 4.0. The static web server had learned some new tricks, so that it was an effective "app server" for many scenarios.

In a parallel category, the app server had evolved and existed for a long time. companies delivered products for Unix like Tuxedo, TopEnd, Encina that were philosophically derived from Mainframe application management and monitoring environments like IMS and CICS. Microsoft's offering was Microsoft Transaction Server (MTS), which later evolved into COM+. Most of these products specified "closed" product-specific communications protocols to interconnect "fat" clients to servers. (For Encina, the comms protocol was DCE RPC; for MTS it was DCOM; etc.) In 1995/96, these traditional app server products began to embed basic HTTP communication capability, at first via gateways. And the lines began to blur.

Web servers got more and more mature with respect to handling higher loads, more concurrency, and better features. App servers delivered more and more HTTP-based communication capability.

At this point the line between "app server" and "web server" is a fuzzy one. But people continue to use the terms differently, as a matter of emphasis. When someone says "web server" you often think HTTP-centric, web UI, oriented apps. When someone says "App server" you may think "heavier loads, enterprise features, transactions and queuing, multi-channel communication (HTTP + more). But often it is the same product that serves both sets of workload requirements.

  • WebSphere, IBM's "app server" has its own bundled web server.
  • WebLogic, another traditional app server, likewise.
  • Windows, which is Microsoft's App Server (in addition to being its File&Print Server, Media Server, etc.), bundles IIS.

What is the difference between single and double quotes in SQL?

A simple rule for us to remember what to use in which case:

  • [S]ingle quotes are for [S]trings ; [D]ouble quotes are for [D]atabase identifiers;

In MySQL and MariaDB, the ` (backtick) symbol is the same as the " symbol. You can use " when your SQL_MODE has ANSI_QUOTES enabled.

Instantiating a generic class in Java

Generics in Java are generally more powerful than in C#.

If you want to construct an object but without hardwiring a constructor/static method, use an abstract factory. You should be able to find detailed information and tutorials on the Abstract Factory Pattern in any basic design patterns book, introduction to OOP or all over the interwebs. It's not worth duplicating code here, other than to mention that Java's closure syntax sucks.

IIRC, C# has a special case for specifying a generic type has a no-args constructor. This irregularity, by definition, presupposes that client code wants to use this particular form of construction and encourages mutability.

Using reflection for this is just wrongheaded. Generics in Java are a compile-time, static-typing feature. Attempts to use them at runtime are a clear indication of something going wrong. Reflection causes verbose code, runtime failures, unchecked dependencies and security vulnerabilities. (Class.forName is particularly evil.)

Excel - Shading entire row based on change of value

In MS Excel, first save your workbook as a Macro Enabled file then go to the Developper Tab and click on Visual Basic. Copy and paste this code in the "ThisWorkbook" Excel Objects. Replace the 2 values of G = and C= by the number of the column containing the values being referenced.

In your case, if the number of the column named "File No" is the first column (namely column 1), replace G=6 by G=1 and C=6 by C-1. Finally click on Macro, Select and Run it. Voila! Works like a charm.

Sub color()
    Dim g As Long
    Dim c As Integer
    Dim colorIt As Boolean

    g = 6
    c = 6
    colorIt = True

    Do While Cells(g, c) <> ""
        test_value = Cells(g, c)
        Do While Cells(g, c) = test_value
            If colorIt Then
                Cells(g, c).EntireRow.Select
                Selection.Interior.ColorIndex = 15
            Else
                Cells(g, c).EntireRow.Select
                Selection.Interior.ColorIndex = x1None
            End If
            g = g + 1
        Loop
        colorIt = Not (colorIt)
    Loop
End Sub

What REST PUT/POST/DELETE calls should return by a convention?

Overall, the conventions are “think like you're just delivering web pages”.

For a PUT, I'd return the same view that you'd get if you did a GET immediately after; that would result in a 200 (well, assuming the rendering succeeds of course). For a POST, I'd do a redirect to the resource created (assuming you're doing a creation operation; if not, just return the results); the code for a successful create is a 201, which is really the only HTTP code for a redirect that isn't in the 300 range.

I've never been happy about what a DELETE should return (my code currently produces an HTTP 204 and an empty body in this case).

HTML Mobile -forcing the soft keyboard to hide

Scott S's answer worked perfectly.

I was coding a web-based phone dialpad for mobile, and every time the user would press a number on the keypad (composed of td span elements in a table), the softkeyboard would pop up. I also wanted the user to not be able to tap into the input box of the number being dialed. This actually solved both problems in 1 shot. The following was used:

<input type="text" id="phone-number" onfocus="blur();" />

Oracle 11g SQL to get unique values in one column of a multi-column query

This will be more efficient, plus you have control over the ordering it uses to pick a value:

SELECT DISTINCT
       FIRST_VALUE(person)
          OVER(PARTITION BY language
               ORDER BY person)
      ,language
FROM   tableA;

If you really don't care which person is picked for each language, you can omit the ORDER BY clause:

SELECT DISTINCT
       FIRST_VALUE(person)
          OVER(PARTITION BY language)
      ,language
FROM   tableA;

Google Chrome "window.open" workaround?

Why is this still so complicated in 2021? For me I wanted to open in a new chrome window fullscreen so I used the below:

window.open("http://my.url.com", "", "fullscreen=yes");

This worked as exepected opening a new chrome window. Without the options at the end it will only open a new tab

jQuery Ajax simple call

You could also make the ajax call more generic, reusable, so you can call it from different CRUD(create, read, update, delete) tasks for example and treat the success cases from those calls.

makePostCall = function (url, data) { // here the data and url are not hardcoded anymore
   var json_data = JSON.stringify(data);

    return $.ajax({
        type: "POST",
        url: url,
        data: json_data,
        dataType: "json",
        contentType: "application/json;charset=utf-8"
    });
}

// and here a call example
makePostCall("index.php?action=READUSERS", {'city' : 'Tokio'})
    .success(function(data){
               // treat the READUSERS data returned
   })
    .fail(function(sender, message, details){
           alert("Sorry, something went wrong!");
  });

Giving my function access to outside variable

$foo = 42;
$bar = function($x = 0) use ($foo){
    return $x + $foo;
};
var_dump($bar(10)); // int(52)

UPDATE: there is now support for arrow functions, but i will let for someone that used it more to create the answer

Split files using tar, gz, zip, or bzip2

use tar to split into multiple archives

there are plenty of programs that will work with tar files on windows, including cygwin.

UPDATE if exists else INSERT in SQL Server 2008

Many people will suggest you use MERGE, but I caution you against it. By default, it doesn't protect you from concurrency and race conditions any more than multiple statements, but it does introduce other dangers:

http://www.mssqltips.com/sqlservertip/3074/use-caution-with-sql-servers-merge-statement/

Even with this "simpler" syntax available, I still prefer this approach (error handling omitted for brevity):

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
UPDATE dbo.table SET ... WHERE PK = @PK;
IF @@ROWCOUNT = 0
BEGIN
  INSERT dbo.table(PK, ...) SELECT @PK, ...;
END
COMMIT TRANSACTION;

A lot of folks will suggest this way:

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
IF EXISTS (SELECT 1 FROM dbo.table WHERE PK = @PK)
BEGIN
  UPDATE ...
END
ELSE
BEGIN
  INSERT ...
END
COMMIT TRANSACTION;

But all this accomplishes is ensuring you may need to read the table twice to locate the row(s) to be updated. In the first sample, you will only ever need to locate the row(s) once. (In both cases, if no rows are found from the initial read, an insert occurs.)

Others will suggest this way:

BEGIN TRY
  INSERT ...
END TRY
BEGIN CATCH
  IF ERROR_NUMBER() = 2627
    UPDATE ...
END CATCH

However, this is problematic if for no other reason than letting SQL Server catch exceptions that you could have prevented in the first place is much more expensive, except in the rare scenario where almost every insert fails. I prove as much here:

Not sure what you think you gain by having a single statement; I don't think you gain anything. MERGE is a single statement but it still has to really perform multiple operations anyway - even though it makes you think it doesn't.

Android: Reverse geocoding - getFromLocation

It looks like there's two things happening here.

1) You've missed the new keyword from before calling the constructor.

2) The parameter you're passing in to the Geocoder constructor is incorrect. You're passing in a Locale where it's expecting a Context.

There are two Geocoder constructors, both of which require a Context, and one also taking a Locale:

Geocoder(Context context, Locale locale)
Geocoder(Context context)

Solution

Modify your code to pass in a valid Context and include new and you should be good to go.

Geocoder myLocation = new Geocoder(getApplicationContext(), Locale.getDefault());   
List<Address> myList = myLocation.getFromLocation(latPoint, lngPoint, 1);

Note

If you're still having problems it may be a permissioning issue. Geocoding implicitly uses the Internet to perform the lookups, so your application will require an INTERNET uses-permission tag in your manifest.

Add the following uses-permission node within the manifest node of your manifest.

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

Session timeout in ASP.NET

Are you using Forms authentication?

Forms authentication uses it own value for timeout (30 min. by default). A forms authentication timeout will send the user to the login page with the session still active. This may look like the behavior your app gives when session times out making it easy to confuse one with the other.

<system.web>
    <authentication mode="Forms">
          <forms timeout="50"/>
    </authentication>

    <sessionState timeout="60"  />
</system.web>

Setting the forms timeout to something less than the session timeout can give the user a window in which to log back in without losing any session data.

android lollipop toolbar: how to hide/show the toolbar while scrolling?

As far as I know there is nothing build in that does this for you. However you could have a look at the Google IO sourcecode, especially the BaseActivity. Search for "auto hide" or look at onMainContentScrolled

In order to hide the Toolbar your can just do something like this:

toolbar.animate().translationY(-toolbar.getBottom()).setInterpolator(new AccelerateInterpolator()).start();

If you want to show it again you call:

toolbar.animate().translationY(0).setInterpolator(new DecelerateInterpolator()).start();

How to completely uninstall Visual Studio 2010?

If I may give an answer to an old thread; You can use PC Decrapifier to select programs you want to uninstall. PC Decrapifier will uninstall them one by one for you so you don't have to click them all seperately.

This is very useful for removing all the 'junk' - like the SQL Database tools - Visual Studio leaves behind even when uninstalled.

Formatting a double to two decimal places

The problem is that when you are doing additions and multiplications of numbers all with two decimal places, you expect there will be no rounding errors, but remember the internal representation of double is in base 2, not in base 10 ! So a number like 0.1 in base 10 may be in base 2 : 0.101010101010110011... with an infinite number of decimals (the value stored in the double will be a number N with :

 0.1-Math.Pow(2,-64) < N < 0.1+Math.Pow(2,-64) 

As a consequence an operation like 12.3 + 0.1 may be not the same exact 64 bits double value as 12.4 (or 12.456 * 10 may be not the same as 124.56) because of rounding errors. For example if you store in a Database the result of 12.3 +0.1 into a table/column field of type double precision number and then SELECT WHERE xx=12.4 you may realize that you stored a number that is not exactly 12.4 and the Sql select will not return the record; So if you cannot use the decimal datatype (which has internal representation in base 10) and must use the 'double' datatype, you have to do some normalization after each addition or multiplication :

double freqMHz= freqkHz.MulRound(0.001); // freqkHz*0.001
double amountEuro= amountEuro.AddRound(delta); // amountEuro+delta


    public static double AddRound(this double d,double val)
    {
        return double.Parse(string.Format("{0:g14}", d+val));
    }
    public static double MulRound(this double d,double val)
    {
        return double.Parse(string.Format("{0:g14}", d*val));
    }

Facebook OAuth "The domain of this URL isn't included in the app's domain"

I had the same problem.....the issu is in the version PHP SDK 5.6.2 and the fix was editing the following file:

facebook\src\Facebook\Helpers\FacebookRedirectLoginHelper.php

change this line

$redirectUrl = FacebookUrlManipulator::removeParamsFromUrl($redirectUrl,['state','code']);

to

$redirectUrl = FacebookUrlManipulator::removeParamsFromUrl($redirectUrl,['state','code','enforce_https']);

In C#, why is String a reference type that behaves like a value type?

At the risk of getting yet another mysterious down-vote...the fact that many mention the stack and memory with respect to value types and primitive types is because they must fit into a register in the microprocessor. You cannot push or pop something to/from the stack if it takes more bits than a register has....the instructions are, for example "pop eax" -- because eax is 32 bits wide on a 32-bit system.

Floating-point primitive types are handled by the FPU, which is 80 bits wide.

This was all decided long before there was an OOP language to obfuscate the definition of primitive type and I assume that value type is a term that has been created specifically for OOP languages.

where is create-react-app webpack config and files?

Assuming you don't want to eject and you just want to look at the config you will find them in /node_modules/react-scripts/config

webpack.config.dev.js. //used by `npm start`
webpack.config.prod.js //used by `npm run build`

Using any() and all() to check if a list contains one set of values or another

Generally speaking:

all and any are functions that take some iterable and return True, if

  • in the case of all(), no values in the iterable are falsy;
  • in the case of any(), at least one value is truthy.

A value x is falsy iff bool(x) == False. A value x is truthy iff bool(x) == True.

Any non-booleans in the iterable will be fine — bool(x) will coerce any x according to these rules: 0, 0.0, None, [], (), [], set(), and other empty collections will yield False, anything else True. The docstring for bool uses the terms 'true'/'false' for 'truthy'/'falsy', and True/False for the concrete boolean values.


In your specific code samples:

You misunderstood a little bit how these functions work. Hence, the following does something completely not what you thought:

if any(foobars) == big_foobar:

...because any(foobars) would first be evaluated to either True or False, and then that boolean value would be compared to big_foobar, which generally always gives you False (unless big_foobar coincidentally happened to be the same boolean value).

Note: the iterable can be a list, but it can also be a generator/generator expression (˜ lazily evaluated/generated list) or any other iterator.

What you want instead is:

if any(x == big_foobar for x in foobars):

which basically first constructs an iterable that yields a sequence of booleans—for each item in foobars, it compares the item to big_foobar and emits the resulting boolean into the resulting sequence:

tmp = (x == big_foobar for x in foobars)

then any walks over all items in tmp and returns True as soon as it finds the first truthy element. It's as if you did the following:

In [1]: foobars = ['big', 'small', 'medium', 'nice', 'ugly']                                        

In [2]: big_foobar = 'big'                                                                          

In [3]: any(['big' == big_foobar, 'small' == big_foobar, 'medium' == big_foobar, 'nice' == big_foobar, 'ugly' == big_foobar])        
Out[3]: True

Note: As DSM pointed out, any(x == y for x in xs) is equivalent to y in xs but the latter is more readable, quicker to write and runs faster.

Some examples:

In [1]: any(x > 5 for x in range(4))
Out[1]: False

In [2]: all(isinstance(x, int) for x in range(10))
Out[2]: True

In [3]: any(x == 'Erik' for x in ['Erik', 'John', 'Jane', 'Jim'])
Out[3]: True

In [4]: all([True, True, True, False, True])
Out[4]: False

See also: http://docs.python.org/2/library/functions.html#all

How do I create a MongoDB dump of my database?

mongodump -h hostname -u dbusername -p dbpassword --db dbname --port portnumber --out /path/folder

mongodump -h hostname -u dbusername -p dbpassword --db dbname --port portnumber --out /path/folder.gz

How do I set the time zone of MySQL?

Simply run this on your MySQL server:

SET GLOBAL time_zone = '+8:00';

Where +8:00 will be your time zone.

CSS Always On Top

Ensure position is on your element and set the z-index to a value higher than the elements you want to cover.

element {
    position: fixed;
    z-index: 999;
}

div {
    position: relative;
    z-index: 99;
}

It will probably require some more work than that but it's a start since you didn't post any code.

ORA-06502: PL/SQL: numeric or value error: character string buffer too small

PL/SQL: numeric or value error: character string buffer too small

is due to the fact that you declare a string to be of a fixed length (say 20), and at some point in your code you assign it a value whose length exceeds what you declared.

for example:

myString VARCHAR2(20);
myString :='abcdefghijklmnopqrstuvwxyz'; --length 26

will fire such an error

Why does intellisense and code suggestion stop working when Visual Studio is open?

I had this problem when some of the dependent assemblies are changed but locked by an other instance of visual studio (2015).

Test if object implements interface

What worked for me is:

Assert.IsNotNull(typeof (YourClass).GetInterfaces().SingleOrDefault(i => i == typeof (ISomeInterface)));

Save file/open file dialog box, using Swing & Netbeans GUI editor

I think you face three problems:

  1. understanding the FileChooser
  2. writing/reading files
  3. understanding extensions and file formats

ad 1. Are you sure you've connected the FileChooser to a correct panel/container? I'd go for a simple tutorial on this matter and see if it works. That's the best way to learn - by making small but large enough steps forward. Breaking down an issue into such parts might be tricky sometimes ;)

ad. 2. After you save or open the file you should have methods to write or read the file. And again there are pretty neat examples on this matter and it's easy to understand topic.

ad. 3. There's a difference between a file having extension and file format. You can change the format of any file to anything you want but that doesn't affect it's contents. It might just render the file unreadable for the application associated with such extension. TXT files are easy - you read what you write. XLS, DOCX etc. require more work and usually framework is the best way to tackle these.

How does the Java 'for each' loop work?

The Java for each loop (aka enhanced for loop) is a simplified version of a for loop. The advantage is that there is less code to write and less variables to manage. The downside is that you have no control over the step value and no access to the loop index inside the loop body.

They are best used when the step value is a simple increment of 1 and when you only need access to the current loop element. For example, if you need to loop over every element in an array or Collection without peeking ahead or behind the current element.

There is no loop initialization, no boolean condition and the step value is implicit and is a simple increment. This is why they are considered so much simpler than regular for loops.

Enhanced for loops follow this order of execution:

1) loop body

2) repeat from step 1 until entire array or collection has been traversed

Example – Integer Array

int [] intArray = {1, 3, 5, 7, 9};
for(int currentValue : intArray) {
  System.out.println(currentValue);
}

The currentValue variable holds the current value being looped over in the intArray array. Notice there’s no explicit step value – it’s always an increment by 1.

The colon can be thought of to mean “in”. So the enhanced for loop declaration states: loop over intArray and store the current array int value in the currentValue variable.

Output:

1
3
5
7
9

Example – String Array

We can use the for-each loop to iterate over an array of strings. The loop declaration states: loop over myStrings String array and store the current String value in the currentString variable.

String [] myStrings  = {
  "alpha",
  "beta",
  "gamma",
  "delta"
};

for(String currentString : myStrings) {
  System.out.println(currentString);
}

Output:

alpha
beta
gamma
delta

Example – List

The enhanced for loop can also be used to iterate over a java.util.List as follows:

List<String> myList = new ArrayList<String>();
myList.add("alpha");
myList.add("beta");
myList.add("gamma");
myList.add("delta");

for(String currentItem : myList) {
  System.out.println(currentItem);
}

The loop declaration states: loop over myList List of Strings and store the current List value in the currentItem variable.

Output:

alpha
beta
gamma
delta

Example – Set

The enhanced for loop can also be used to iterate over a java.util.Set as follows:

Set<String> mySet = new HashSet<String>();
mySet.add("alpha");
mySet.add("alpha");
mySet.add("beta");
mySet.add("gamma");
mySet.add("gamma");
mySet.add("delta");

for(String currentItem : mySet) {
  System.out.println(currentItem);
}

The loop declaration states: loop over mySet Set of Strings and store the current Set value in the currentItem variable. Notice that since this is a Set, duplicate String values are not stored.

Output:

alpha
delta
beta
gamma

Source: Loops in Java – Ultimate Guide

How do I fix twitter-bootstrap on IE?

Internet Explorer has a maximum number of code lines for style sheet recognition.

This is Bootstrap navbar style rule that set the float property for navbar items:

.navbar-nav > li {
    float: left;
}

That rule in Bootstrap 3 (probably in early versions too) is on line 5247.

As it says here: Internet Explorer's CSS rules limits, a sheet may contain up to 4095 lines.

How to read from stdin line by line in Node

In my case the program (elinks) returned lines that looked empty, but in fact had special terminal characters, color control codes and backspace, so grep options presented in other answers did not work for me. So I wrote this small script in Node.js. I called the file tight, but that's just a random name.

#!/usr/bin/env node

function visible(a) {
    var R  =  ''
    for (var i = 0; i < a.length; i++) {
        if (a[i] == '\b') {  R -= 1; continue; }  
        if (a[i] == '\u001b') {
            while (a[i] != 'm' && i < a.length) i++
            if (a[i] == undefined) break
        }
        else R += a[i]
    }
    return  R
}

function empty(a) {
    a = visible(a)
    for (var i = 0; i < a.length; i++) {
        if (a[i] != ' ') return false
    }
    return  true
}

var readline = require('readline')
var rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: false })

rl.on('line', function(line) {
    if (!empty(line)) console.log(line) 
})

Java array reflection: isArray vs. instanceof

There is no difference in behavior that I can find between the two (other than the obvious null-case). As for which version to prefer, I would go with the second. It is the standard way of doing this in Java.

If it confuses readers of your code (because String[] instanceof Object[] is true), you may want to use the first to be more explicit if code reviewers keep asking about it.

How to run a Powershell script from the command line and pass a directory as a parameter

you are calling a script file not a command so you have to use -file eg :

powershell -executionPolicy bypass -noexit -file "c:\temp\test.ps1" "c:\test with space"

for PS V2

powershell.exe -noexit &'c:\my scripts\test.ps1'

(check bottom of this technet page http://technet.microsoft.com/en-us/library/ee176949.aspx )

How can I install a package with go get?

Command go

Download and install packages and dependencies

Usage:

go get [-d] [-f] [-t] [-u] [-v] [-fix] [-insecure] [build flags] [packages]

Get downloads the packages named by the import paths, along with their dependencies. It then installs the named packages, like 'go install'.

The -d flag instructs get to stop after downloading the packages; that is, it instructs get not to install the packages.

The -f flag, valid only when -u is set, forces get -u not to verify that each package has been checked out from the source control repository implied by its import path. This can be useful if the source is a local fork of the original.

The -fix flag instructs get to run the fix tool on the downloaded packages before resolving dependencies or building the code.

The -insecure flag permits fetching from repositories and resolving custom domains using insecure schemes such as HTTP. Use with caution.

The -t flag instructs get to also download the packages required to build the tests for the specified packages.

The -u flag instructs get to use the network to update the named packages and their dependencies. By default, get uses the network to check out missing packages but does not use it to look for updates to existing packages.

The -v flag enables verbose progress and debug output.

Get also accepts build flags to control the installation. See 'go help build'.

When checking out a new package, get creates the target directory GOPATH/src/. If the GOPATH contains multiple entries, get uses the first one. For more details see: 'go help gopath'.

When checking out or updating a package, get looks for a branch or tag that matches the locally installed version of Go. The most important rule is that if the local installation is running version "go1", get searches for a branch or tag named "go1". If no such version exists it retrieves the default branch of the package.

When go get checks out or updates a Git repository, it also updates any git submodules referenced by the repository.

Get never checks out or updates code stored in vendor directories.

For more about specifying packages, see 'go help packages'.

For more about how 'go get' finds source code to download, see 'go help importpath'.

This text describes the behavior of get when using GOPATH to manage source code and dependencies. If instead the go command is running in module-aware mode, the details of get's flags and effects change, as does 'go help get'. See 'go help modules' and 'go help module-get'.

See also: go build, go install, go clean.


For example, showing verbose output,

$ go get -v github.com/capotej/groupcache-db-experiment/...
github.com/capotej/groupcache-db-experiment (download)
github.com/golang/groupcache (download)
github.com/golang/protobuf (download)
github.com/capotej/groupcache-db-experiment/api
github.com/capotej/groupcache-db-experiment/client
github.com/capotej/groupcache-db-experiment/slowdb
github.com/golang/groupcache/consistenthash
github.com/golang/protobuf/proto
github.com/golang/groupcache/lru
github.com/capotej/groupcache-db-experiment/dbserver
github.com/capotej/groupcache-db-experiment/cli
github.com/golang/groupcache/singleflight
github.com/golang/groupcache/groupcachepb
github.com/golang/groupcache
github.com/capotej/groupcache-db-experiment/frontend
$ 

How to create a drop-down list?

enter image description here

Here is the code for it.

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<Spinner
    android:id="@+id/static_spinner"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="20dp"
    android:layout_marginTop="20dp" />

<Spinner
    android:id="@+id/dynamic_spinner"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />

strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Ahotbrew.com - Dropdown</string> 
<string-array name="brew_array">
    <item>Cappuccino</item>
    <item>Espresso</item>
    <item>Mocha</item>
    <item>Caffè Americano</item>
    <item>Cafe Zorro</item>
</string-array> 

MainActivity

Spinner staticSpinner = (Spinner) findViewById(R.id.static_spinner);

    // Create an ArrayAdapter using the string array and a default spinner
    ArrayAdapter<CharSequence> staticAdapter = ArrayAdapter
            .createFromResource(this, R.array.brew_array,
                    android.R.layout.simple_spinner_item);

    // Specify the layout to use when the list of choices appears
    staticAdapter
            .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    // Apply the adapter to the spinner
    staticSpinner.setAdapter(staticAdapter);

    Spinner dynamicSpinner = (Spinner) findViewById(R.id.dynamic_spinner);

    String[] items = new String[] { "Chai Latte", "Green Tea", "Black Tea" };

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_item, items);

    dynamicSpinner.setAdapter(adapter);

    dynamicSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view,
                int position, long id) {
            Log.v("item", (String) parent.getItemAtPosition(position));
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            // TODO Auto-generated method stub
        }
    });

This example is from http://www.ahotbrew.com/android-dropdown-spinner-example/

How can I declare a global variable in Angular 2 / Typescript?

I like the answer of @supercobra, but I would use the const keyword as it is in ES6 already available:

//
// ===== File globals.ts    
//
'use strict';

export const sep='/';
export const version: string="22.2.2"; 

How to read a PEM RSA private key from .NET

The stuff between the

-----BEGIN RSA PRIVATE KEY---- 

and

-----END RSA PRIVATE KEY----- 

is the base64 encoding of a PKCS#8 PrivateKeyInfo (unless it says RSA ENCRYPTED PRIVATE KEY in which case it is a EncryptedPrivateKeyInfo).

It is not that hard to decode manually, but otherwise your best bet is to P/Invoke to CryptImportPKCS8.


Update: The CryptImportPKCS8 function is no longer available for use as of Windows Server 2008 and Windows Vista. Instead, use the PFXImportCertStore function.

What do $? $0 $1 $2 mean in shell script?

They are called the Positional Parameters.

3.4.1 Positional Parameters

A positional parameter is a parameter denoted by one or more digits, other than the single digit 0. Positional parameters are assigned from the shell’s arguments when it is invoked, and may be reassigned using the set builtin command. Positional parameter N may be referenced as ${N}, or as $N when N consists of a single digit. Positional parameters may not be assigned to with assignment statements. The set and shift builtins are used to set and unset them (see Shell Builtin Commands). The positional parameters are temporarily replaced when a shell function is executed (see Shell Functions).

When a positional parameter consisting of more than a single digit is expanded, it must be enclosed in braces.

remove attribute display:none; so the item will be visible

You should remove "style" attribute instead of "display" property :

$("span").removeAttr("style");