Programs & Examples On #Inline scripting

error::make_unique is not a member of ‘std’

1.gcc version >= 5
2.CXXFLAGS += -std=c++14
3. #include <memory>

How to send a html email with the bash command "sendmail"?

To follow up on the previous answer using mail :

Often times one's html output is interpreted by the client mailer, which may not format things using a fixed-width font. Thus your nicely formatted ascii alignment gets all messed up. To send old-fashioned fixed-width the way the God intended, try this:

{ echo -e "<pre>"
echo "Descriptive text here."
shell_command_1_here
another_shell_command
cat <<EOF

This is the ending text.
</pre><br>
</div>
EOF
} | mail -s "$(echo -e 'Your subject.\nContent-Type: text/html')" [email protected]

You don't necessarily need the "Descriptive text here." line, but I have found that sometimes the first line may, depending on its contents, cause the mail program to interpret the rest of the file in ways you did not intend. Try the script with simple descriptive text first, before fine tuning the output in the way that you want.

Checking if a string can be converted to float in Python

'1.43'.replace('.','',1).isdigit()

which will return true only if there is one or no '.' in the string of digits.

'1.4.3'.replace('.','',1).isdigit()

will return false

'1.ww'.replace('.','',1).isdigit()

will return false

Can an Android Toast be longer than Toast.LENGTH_LONG?

I know I am a bit late, but I took Regis_AG's answer and wrapped it in a helper class and it works great.

public class Toaster {
  private static final int SHORT_TOAST_DURATION = 2000;

  private Toaster() {}

  public static void makeLongToast(String text, long durationInMillis) {
    final Toast t = Toast.makeText(App.context(), text, Toast.LENGTH_SHORT);
    t.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0);

    new CountDownTimer(Math.max(durationInMillis - SHORT_TOAST_DURATION, 1000), 1000) {
      @Override
      public void onFinish() {
        t.show();
      }

      @Override
      public void onTick(long millisUntilFinished) {
        t.show();
      }
    }.start();
  }
}

In your application code, just do something like this:

    Toaster.makeLongToast("Toasty!", 8000);

Format XML string to print friendly XML string

Use XmlTextWriter...

public static string PrintXML(string xml)
{
    string result = "";

    MemoryStream mStream = new MemoryStream();
    XmlTextWriter writer = new XmlTextWriter(mStream, Encoding.Unicode);
    XmlDocument document = new XmlDocument();

    try
    {
        // Load the XmlDocument with the XML.
        document.LoadXml(xml);

        writer.Formatting = Formatting.Indented;

        // Write the XML into a formatting XmlTextWriter
        document.WriteContentTo(writer);
        writer.Flush();
        mStream.Flush();

        // Have to rewind the MemoryStream in order to read
        // its contents.
        mStream.Position = 0;

        // Read MemoryStream contents into a StreamReader.
        StreamReader sReader = new StreamReader(mStream);

        // Extract the text from the StreamReader.
        string formattedXml = sReader.ReadToEnd();

        result = formattedXml;
    }
    catch (XmlException)
    {
        // Handle the exception
    }

    mStream.Close();
    writer.Close();

    return result;
}

Add border-bottom to table row <tr>

I had a problem like this before. I don't think tr can take a border styling directly. My workaround was to style the tds in the row:

<tr class="border_bottom">

CSS:

tr.border_bottom td {
  border-bottom: 1px solid black;
}

Cut Java String at a number of character

StringUtils.abbreviate("abcdefg", 6);

This will give you the following result: abc...

Where 6 is the needed length, and "abcdefg" is the string that needs to be abbrevieted.

Oracle error : ORA-00905: Missing keyword

Though this is not directly related to the OP's exact question but I just found out that using a Oracle reserved word in your query (in my case the alias IN) can cause the same error.

Example:

SELECT * FROM TBL_INDEPENTS IN
JOIN TBL_VOTERS VO on IN.VOTERID = VO.VOTERID

Or if its in the query itself as a field name

 SELECT ..., ...., IN, ..., .... FROM SOMETABLE

That would also throw that error. I hope this helps someone.

Java swing application, close one window and open another when button is clicked

Use this.dispose for current window to close and next_window.setVisible(true) to show next window behind button property ActionPerformed , Example is shown below in pic for your help.

enter image description here

How can I stop the browser back button using JavaScript?

I had this problem with React (class component).

And I solved it easily:

componentDidMount() {
    window.addEventListener("popstate", e => {
        this.props.history.goForward();
    }
}

I've used HashRouter from react-router-dom.

Any good, visual HTML5 Editor or IDE?

Try the HTML5 editor written in HTML5 itself

http://www.mobdis.com

What does flex: 1 mean?

Here is the explanation:

https://www.w3.org/TR/css-flexbox-1/#flex-common

flex: <positive-number>
Equivalent to flex: <positive-number> 1 0. Makes the flex item flexible and sets the flex basis to zero, resulting in an item that receives the specified proportion of the free space in the flex container. If all items in the flex container use this pattern, their sizes will be proportional to the specified flex factor.

Therefore flex:1 is equivalent to flex: 1 1 0

ObservableCollection Doesn't support AddRange method, so I get notified for each item added, besides what about INotifyCollectionChanging?

You can also use this code to extend ObservableCollection:

public static class ObservableCollectionExtend
{
    public static void AddRange<TSource>(this ObservableCollection<TSource> source, IEnumerable<TSource> items)
    {
        foreach (var item in items)
        {
            source.Add(item);
        }
    }
}

Then you don't need to change class in existing code.

How do I set the default font size in Vim?

The other answers are what you asked about, but in case it’s useful to anyone else, here’s how to set the font conditionally from the screen DPI (Windows only):

set guifont=default
if has('windows')
    "get dpi, strip out utf-16 garbage and new lines
    "system() converts 0x00 to 0x01 for 'platform independence'
    "should return something like 'PixelsPerXLogicalInch=192'
    "get the part from the = to the end of the line (eg '=192') and strip
    "the first character
    "and convert to a number
    let dpi = str2nr(strpart(matchstr(substitute(
        \system('wmic desktopmonitor get PixelsPerXLogicalInch /value'),
        \'\%x01\|\%x0a\|\%x0a\|\%xff\|\%xfe', '', 'g'),
        \'=.*$'), 1))
    if dpi > 100
        set guifont=high_dpi_font
    endif
endif

Accessing member of base class

You are incorrectly using the super and this keyword. Here is an example of how they work:

class Animal {
    public name: string;
    constructor(name: string) { 
        this.name = name;
    }
    move(meters: number) {
        console.log(this.name + " moved " + meters + "m.");
    }
}

class Horse extends Animal {
    move() {
        console.log(super.name + " is Galloping...");
        console.log(this.name + " is Galloping...");
        super.move(45);
    }
}

var tom: Animal = new Horse("Tommy the Palomino");

Animal.prototype.name = 'horseee'; 

tom.move(34);
// Outputs:

// horseee is Galloping...
// Tommy the Palomino is Galloping...
// Tommy the Palomino moved 45m.

Explanation:

  1. The first log outputs super.name, this refers to the prototype chain of the object tom, not the object tom self. Because we have added a name property on the Animal.prototype, horseee will be outputted.
  2. The second log outputs this.name, the this keyword refers to the the tom object itself.
  3. The third log is logged using the move method of the Animal base class. This method is called from Horse class move method with the syntax super.move(45);. Using the super keyword in this context will look for a move method on the prototype chain which is found on the Animal prototype.

Remember TS still uses prototypes under the hood and the class and extends keywords are just syntactic sugar over prototypical inheritance.

Check key exist in python dict

Use the in keyword.

if 'apples' in d:
    if d['apples'] == 20:
        print('20 apples')
    else:
        print('Not 20 apples')

If you want to get the value only if the key exists (and avoid an exception trying to get it if it doesn't), then you can use the get function from a dictionary, passing an optional default value as the second argument (if you don't pass it it returns None instead):

if d.get('apples', 0) == 20:
    print('20 apples.')
else:
    print('Not 20 apples.')

What's the difference between a POST and a PUT HTTP REQUEST?

Only semantics.

An HTTP PUT is supposed to accept the body of the request, and then store that at the resource identified by the URI.

An HTTP POST is more general. It is supposed to initiate an action on the server. That action could be to store the request body at the resource identified by the URI, or it could be a different URI, or it could be a different action.

PUT is like a file upload. A put to a URI affects exactly that URI. A POST to a URI could have any effect at all.

How to pass an object into a state using UI-router?

There are two parts of this problem

1) using a parameter that would not alter an url (using params property):

$stateProvider
    .state('login', {
        params: [
            'toStateName',
            'toParamsJson'
        ],
        templateUrl: 'partials/login/Login.html'
    })

2) passing an object as parameter: Well, there is no direct way how to do it now, as every parameter is converted to string (EDIT: since 0.2.13, this is no longer true - you can use objects directly), but you can workaround it by creating the string on your own

toParamsJson = JSON.stringify(toStateParams);

and in target controller deserialize the object again

originalParams = JSON.parse($stateParams.toParamsJson);

Jquery UI Datepicker not displaying

Seems to happen with some themes (cupertino/theme.css) in my case.

And the problem is the .ui-helper-hidden-accessible class which have clip property, like previous users said.

Just Overwrite it and it will be fine

$(document).ready(function() {
    $("#datePicker").datepicker({ dateFormat: "yy-m-d" });
    $('#ui-datepicker-div').css('clip', 'auto');
});

Using R to download zipped data file, extract, and import data

Try this code. It works for me:

unzip(zipfile="<directory and filename>",
      exdir="<directory where the content will be extracted>")

Example:

unzip(zipfile="./data/Data.zip",exdir="./data")

Add button to a layout programmatically

If you just have included a layout file at the beginning of onCreate() inside setContentView and want to get this layout to add new elements programmatically try this:

ViewGroup linearLayout = (ViewGroup) findViewById(R.id.linearLayoutID);

then you can create a new Button for example and just add it:

Button bt = new Button(this);
bt.setText("A Button");
bt.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 
                                    LayoutParams.WRAP_CONTENT));
linerLayout.addView(bt);

How can you zip or unzip from the script using ONLY Windows' built-in capabilities?

I have a problem with all these solutions.

They're not exactly the same, and they all create files that have a slight size difference compared to the RMB --> send to --> compressed (zipped) folder when made from the same source folder. The closest size-difference I have had is 300 KB difference (script > manual), made with:

powershell Compress-Archive -Path C:\sourceFolder -CompressionLevel Fastest -DestinationPath C:\destinationArchive.zip

(Notice the -CompressionLevel. There are three possible values: Fastest, NoCompression & Optimal, (Default: Optimal))

I wanted to make a .bat file that should automatically compress a WordPress plugin folder I'm working on, into a .zip archive, so I can upload it into the WordPress site and test the plugin.

But for some reason it doesn't work with any of these automatic compressions, but it does work with the manual RMB compression, witch I find really strange.

And the script-generated .zip files actually break the WordPress plugins to the point where they can't be activated, and they can also not be deleted from inside WordPress. I have to SSH into the "back side" of the server and delete the uploaded plugin files themselves, manually. While the manually RMB-generated files work normally.

Select records from today, this week, this month php mysql

Try using date and time functions (MONTH(), YEAR(), DAY(), MySQL Manual)

This week:

SELECT * FROM jokes WHERE WEEKOFYEAR(date)=WEEKOFYEAR(NOW());

Last week:

SELECT * FROM jokes WHERE WEEKOFYEAR(date)=WEEKOFYEAR(NOW())-1;

What does the 'standalone' directive mean in XML?

The standalone declaration is a way of telling the parser to ignore any markup declarations in the DTD. The DTD is thereafter used for validation only.

As an example, consider the humble <img> tag. If you look at the XHTML 1.0 DTD, you see a markup declaration telling the parser that <img> tags must be EMPTY and possess src and alt attributes. When a browser is going through an XHTML 1.0 document and finds an <img> tag, it should notice that the DTD requires src and alt attributes and add them if they are not present. It will also self-close the <img> tag since it is supposed to be EMPTY. This is what the XML specification means by "markup declarations can affect the content of the document." You can then use the standalone declaration to tell the parser to ignore these rules.

Whether or not your parser actually does this is another question, but a standards-compliant validating parser (like a browser) should.

Note that if you do not specify a DTD, then the standalone declaration "has no meaning," so there's no reason to use it unless you also specify a DTD.

Can a CSV file have a comment?

A Comma Separated File is really just a text file where the lines consist of values separated by commas.

There is no standard which defines the contents of a CSV file, so there is no defined way of indicating a comment. It depends on the program which will be importing the CSV file.

Of course, this is usually Excel. You should ask yourself how does Excel define a comment? In other words, what would make Excel ignore a line (or part of a line) in the CSV file? I'm not aware of anything which would do this.

curl error 18 - transfer closed with outstanding read data remaining

Seeing this error during the use of Guzzle as well. The following header fixed it for me:

'headers' => [
    'accept-encoding' => 'gzip, deflate',
],

I issued the request with Postman which gave me a complete response and no error. Then I started adding the headers that Postman sends to the Guzzle request and this was the one that fixed it.

Primefaces valueChangeListener or <p:ajax listener not firing for p:selectOneMenu

this works for me:

It can be used inside the dialog, but the dialog can´t be inside any componet such as panels, accordion, etc.

How to Find the Default Charset/Encoding in Java?

First, Latin-1 is the same as ISO-8859-1, so, the default was already OK for you. Right?

You successfully set the encoding to ISO-8859-1 with your command line parameter. You also set it programmatically to "Latin-1", but, that's not a recognized value of a file encoding for Java. See http://java.sun.com/javase/6/docs/technotes/guides/intl/encoding.doc.html

When you do that, looks like Charset resets to UTF-8, from looking at the source. That at least explains most of the behavior.

I don't know why OutputStreamWriter shows ISO8859_1. It delegates to closed-source sun.misc.* classes. I'm guessing it isn't quite dealing with encoding via the same mechanism, which is weird.

But of course you should always be specifying what encoding you mean in this code. I'd never rely on the platform default.

Mapping composite keys using EF code first

For Mapping Composite primary key using Entity framework we can use two approaches.

1) By Overriding the OnModelCreating() Method

For ex: I have the model class named VehicleFeature as shown below.

public class VehicleFeature
{
    public int VehicleId { get; set; }
    public int FeatureId{get;set;}
    public Vehicle Vehicle{get;set;}
    public Feature Feature{get;set;}
}

The Code in my DBContext would be like ,

public class VegaDbContext : DbContext
{
    public DbSet<Make> Makes{get;set;}

    public DbSet<Feature> Features{get;set;}
    public VegaDbContext(DbContextOptions<VegaDbContext> options):base(options)        
    {           

    }
    // we override the OnModelCreating method here.
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<VehicleFeature>().HasKey(vf=> new {vf.VehicleId, vf.FeatureId});
    }
}

2) By Data Annotations.

public class VehicleFeature
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]  
    [Key]
    public int VehicleId { get; set; }
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]   
    [Key]
    public int FeatureId{get;set;}
    public Vehicle Vehicle{get;set;}
    public Feature Feature{get;set;}
}

Please refer the below links for the more information.

1) https://msdn.microsoft.com/en-us/library/jj591617(v=vs.113).aspx

2) How to add a composite unique key using EF 6 Fluent Api?

removing html element styles via javascript

Use

particular_node.classList.remove("<name-of-class>")

For native javascript

How to debug a GLSL shader?

The existing answers are all good stuff, but I wanted to share one more little gem that has been valuable in debugging tricky precision issues in a GLSL shader. With very large int numbers represented as a floating point, one needs to take care to use floor(n) and floor(n + 0.5) properly to implement round() to an exact int. It is then possible to render a float value that is an exact int by the following logic to pack the byte components into R, G, and B output values.

  // Break components out of 24 bit float with rounded int value
  // scaledWOB = (offset >> 8) & 0xFFFF
  float scaledWOB = floor(offset / 256.0);
  // c2 = (scaledWOB >> 8) & 0xFF
  float c2 = floor(scaledWOB / 256.0);
  // c0 = offset - (scaledWOB << 8)
  float c0 = offset - floor(scaledWOB * 256.0);
  // c1 = scaledWOB - (c2 << 8)
  float c1 = scaledWOB - floor(c2 * 256.0);

  // Normalize to byte range
  vec4 pix;  
  pix.r = c0 / 255.0;
  pix.g = c1 / 255.0;
  pix.b = c2 / 255.0;
  pix.a = 1.0;
  gl_FragColor = pix;

A cycle was detected in the build path of project xxx - Build Path Problem

As well as the Require-Bundle form of dependency management (most similar to Maven's pom dependencies), it's also possible to have Import-Package dependencies. It's much easier to introduce circular dependencies with Import-Package than Require-Bundle, but YMMV.

Also, Eclipse projects have a 'project references' which says which other projects it depends on. Eclipse uses this at a high level to decide what projects to build, and in which order, so it's quite possible that your Manifest.MF lists everything correctly but the project references are out of whack. Right click on a project and then go to properties - you'll see which projects you depend on. If you're a text kind of person, open up the .project files and see which ones you depend on there - it's probable that a project cyclic link is being defined at that level instead (often caused when you have an A-B dependency and then flipped from B-A but without updating the .project references).

Resize command prompt through commands

Although the answers given here can be used to temporarily change window size, they don't seem to affect font size (at least not on my PC). I have an alternative way. I don't know if this what you're looking for but if you want to make changes automatically/permanently to Console font/window size, you can always do a script that edits the registry:

HKEY_CURRENT_USER\Console
HKEY_CURRENT_USER\Console\%%SystemRoot%%_system32_cmd.exe
HKEY_CURRENT_USER\Console\%%SystemRoot%%_system32_WindowsPowerShell_v1.0_powershell.exe

Those keys deal with the consoles that come up when your run a script or press shift and select "open command prompt here". The Command Prompt entry in your start menu does not use the registry to store it's preferences but stores the prefs in the shortcut itself.

I have a monitor that I can run in 720p native or 1440p supersampling. I needed a quick way to change my console's font/window size, so I made these scripts. These scripts do two things: (1) change the font/window sizes in the registry and (2) swap out the shortcuts in the Start menu with ones that have a different window and font size. I basically made two sets of copies of the Command Prompt and Power Shell shortcuts and stored them in Documents. One set of shortcuts was configured with Consolas font size at 16 for my monitor is in 720p (called it "Command Prompt.720pRes.lnk") and another version of the same shortcut was configure with font size at 36 (called it "Command Prompt.HighRes.lnk"). The script will copy from the set I want to use to overwrite the Start menu one.

console-1440p.cmd:

::Assign New Window and Font Size for Windows Command Prompt
set CMDpNewFont=00240000
set CMDpNewWindowSize=000f0078
set commandPromptLinkFlag=highRes



 ::Make temporary .reg file to resize command console

>%temp%\consoleSIZEchanger.reg ECHO Windows Registry Editor Version 5.00
>>%temp%\consoleSIZEchanger.reg ECHO.
>>%temp%\consoleSIZEchanger.reg ECHO [HKEY_CURRENT_USER\Console]
>>%temp%\consoleSIZEchanger.reg ECHO "WindowSize"=dword:%CMDpNewWindowSize%
>>%temp%\consoleSIZEchanger.reg ECHO "FontSize"=dword:%CMDpNewFont%
>>%temp%\consoleSIZEchanger.reg ECHO.
>>%temp%\consoleSIZEchanger.reg ECHO [HKEY_CURRENT_USER\Console\%%SystemRoot%%_system32_cmd.exe]
>>%temp%\consoleSIZEchanger.reg ECHO "WindowSize"=dword:%CMDpNewWindowSize%
>>%temp%\consoleSIZEchanger.reg ECHO "FontSize"=dword:%CMDpNewFont%
>>%temp%\consoleSIZEchanger.reg ECHO.
>>%temp%\consoleSIZEchanger.reg ECHO [HKEY_CURRENT_USER\Console\%%SystemRoot%%_system32_WindowsPowerShell_v1.0_powershell.exe]
>>%temp%\consoleSIZEchanger.reg ECHO "WindowSize"=dword:%CMDpNewWindowSize%
>>%temp%\consoleSIZEchanger.reg ECHO "FontSize"=dword:%CMDpNewFont%


::Merge and delete consoleSIZEchanger.reg
REGEDIT /S %temp%\consoleSIZEchanger.reg 
del %temp%\consoleSIZEchanger.reg 

::Copy Preconfigured Command Prompt/PowerShell shortcuts to Pinned Start Menu, Accessories and any other Custom Location you would define
copy "%homedrive%%homepath%\Documents\Command Prompt.%commandPromptLinkFlag%.lnk" "%homedrive%%homepath%\AppData\Roaming\Microsoft\Internet Explorer\Quick Launch\User Pinned\StartMenu\Command Prompt.lnk"
copy "%homedrive%%homepath%\Documents\Command Prompt.%commandPromptLinkFlag%.lnk" "%homedrive%%homepath%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Accessories\Command Prompt.lnk"
copy "%homedrive%%homepath%\Documents\Windows PowerShell.%commandPromptLinkFlag%.lnk" "%homedrive%\ProgramData\Microsoft\Windows\Start Menu\Programs\Accessories\Windows PowerShell\Windows PowerShell.lnk"
copy "%homedrive%%homepath%\Documents\Windows PowerShell.%commandPromptLinkFlag%.lnk" "%homedrive%%homepath%\AppData\Roaming\Microsoft\Internet Explorer\Quick Launch\User Pinned\StartMenu\Windows PowerShell.lnk"                 
copy "%homedrive%%homepath%\Documents\Windows PowerShell (x86).%commandPromptLinkFlag%.lnk" "%homedrive%\ProgramData\Microsoft\Windows\Start Menu\Programs\Accessories\Windows PowerShell\Windows PowerShell (x86).lnk"
copy "%homedrive%%homepath%\Documents\Windows PowerShell (x86).%commandPromptLinkFlag%.lnk" "%homedrive%%homepath%\AppData\Roaming\Microsoft\Internet Explorer\Quick Launch\User Pinned\StartMenu\Windows PowerShell (x86).lnk"

console-720p.cmd:

::Assign New Window and Font Size for Windows Command Prompt
set CMDpNewFont=00100000
set CMDpNewWindowSize=0014007d
set commandPromptLinkFlag=720Res



 ::Make temporary .reg file to resize command console
>%temp%\consoleSIZEchanger.reg ECHO Windows Registry Editor Version 5.00
>>%temp%\consoleSIZEchanger.reg ECHO.
>>%temp%\consoleSIZEchanger.reg ECHO [HKEY_CURRENT_USER\Console]
>>%temp%\consoleSIZEchanger.reg ECHO "WindowSize"=dword:%CMDpNewWindowSize%
>>%temp%\consoleSIZEchanger.reg ECHO "FontSize"=dword:%CMDpNewFont%
>>%temp%\consoleSIZEchanger.reg ECHO.
>>%temp%\consoleSIZEchanger.reg ECHO [HKEY_CURRENT_USER\Console\%%SystemRoot%%_system32_cmd.exe]
>>%temp%\consoleSIZEchanger.reg ECHO "WindowSize"=dword:%CMDpNewWindowSize%
>>%temp%\consoleSIZEchanger.reg ECHO "FontSize"=dword:%CMDpNewFont%
>>%temp%\consoleSIZEchanger.reg ECHO.
>>%temp%\consoleSIZEchanger.reg ECHO [HKEY_CURRENT_USER\Console\%%SystemRoot%%_system32_WindowsPowerShell_v1.0_powershell.exe]
>>%temp%\consoleSIZEchanger.reg ECHO "WindowSize"=dword:%CMDpNewWindowSize%
>>%temp%\consoleSIZEchanger.reg ECHO "FontSize"=dword:%CMDpNewFont%


::Merge and delete consoleSIZEchanger.reg
REGEDIT /S %temp%\consoleSIZEchanger.reg 
del %temp%\consoleSIZEchanger.reg 

::Copy Preconfigured Command Prompt/PowerShell shortcuts to Pinned Start Menu, Accessories and any other Custom Location you would define
copy "%homedrive%%homepath%\Documents\Command Prompt.%commandPromptLinkFlag%.lnk" "%homedrive%%homepath%\AppData\Roaming\Microsoft\Internet Explorer\Quick Launch\User Pinned\StartMenu\Command Prompt.lnk"
copy "%homedrive%%homepath%\Documents\Command Prompt.%commandPromptLinkFlag%.lnk" "%homedrive%%homepath%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Accessories\Command Prompt.lnk"
copy "%homedrive%%homepath%\Documents\Windows PowerShell.%commandPromptLinkFlag%.lnk" "%homedrive%\ProgramData\Microsoft\Windows\Start Menu\Programs\Accessories\Windows PowerShell\Windows PowerShell.lnk"
copy "%homedrive%%homepath%\Documents\Windows PowerShell.%commandPromptLinkFlag%.lnk" "%homedrive%%homepath%\AppData\Roaming\Microsoft\Internet Explorer\Quick Launch\User Pinned\StartMenu\Windows PowerShell.lnk"                 
copy "%homedrive%%homepath%\Documents\Windows PowerShell (x86).%commandPromptLinkFlag%.lnk" "%homedrive%\ProgramData\Microsoft\Windows\Start Menu\Programs\Accessories\Windows PowerShell\Windows PowerShell (x86).lnk"
copy "%homedrive%%homepath%\Documents\Windows PowerShell (x86).%commandPromptLinkFlag%.lnk" "%homedrive%%homepath%\AppData\Roaming\Microsoft\Internet Explorer\Quick Launch\User Pinned\StartMenu\Windows PowerShell (x86).lnk"

Why was the name 'let' chosen for block-scoped variable declarations in JavaScript?

The most likely possibility is that it was the most idiomatic choice. Not only is it easy to speak, but rather intuitive to understand. Some could argue, even more so than var.

But I reckon there's a little more history to this.

From Wikipedia:

Dana Scott's LCF language was a stage in the evolution of lambda calculus into modern functional languages. This language introduced the let expression, which has appeared in most functional languages since that time.

State-full imperative languages such as ALGOL and Pascal essentially implement a let expression, to implement restricted scope of functions, in block structures.

I would like to believe this was an inspiration too, for the let in Javascript.

How to use `@ts-ignore` for a block

You can't.

As a workaround you can use a // @ts-nocheck comment at the top of a file to disable type-checking for that file: https://devblogs.microsoft.com/typescript/announcing-typescript-3-7-beta/

So to disable checking for a block (function, class, etc.), you can move it into its own file, then use the comment/flag above. (This isn't as flexible as block-based disabling of course, but it's the best option available at the moment.)

How to have a a razor action link open in a new tab?

<a href="@Url.Action("RunReport", "Performance", new { reportView = Model.ReportView.ToString() })" type="submit" id="runReport" target="_blank" class="button Secondary"> @Reports.RunReport </a>

How do you tell if a checkbox is selected in Selenium for Java?

If you are using Webdriver then the item you are looking for is Selected.

Often times in the render of the checkbox doesn't actually apply the attribute checked unless specified.

So what you would look for in Selenium Webdriver is this

isChecked = e.findElement(By.tagName("input")).Selected;

As there is no Selected in WebDriver Java API, the above code should be as follows:

isChecked = e.findElement(By.tagName("input")).isSelected();

PHP error: php_network_getaddresses: getaddrinfo failed: (while getting information from other site.)

I faced a similar issue on Docker for Ubuntu. It's a DNS issue. You will have to add Google Public DNS Settings into your network. Instruction for adding those settings is OS dependant. In my case, I was using Ubuntu so I added via network manager. Visit this site for more info.

enter image description here

Calling a stored procedure in Oracle with IN and OUT parameters

I had the same problem. I used a trigger and in that trigger I called a procedure which computed some values into 2 OUT variables. When I tried to print the result in the trigger body, nothing showed on screen. But then I solved this problem by making 2 local variables in a function, computed what I need with them and finally, copied those variables in your OUT procedure variables. I hope it'll be useful and successful!

Iterator over HashMap in Java

Can we see your import block? because it seems that you have imported the wrong Iterator class.

The one you should use is java.util.Iterator

To make sure, try:

java.util.Iterator iter = hm.keySet().iterator();

I personally suggest the following:

Map Declaration using Generics and declaration using the Interface Map<K,V> and instance creation using the desired implementation HashMap<K,V>

Map<Integer, String> hm = new HashMap<>();

and for the loop:

for (Integer key : hm.keySet()) {
    System.out.println("Key = " + key + " - " + hm.get(key));
}

UPDATE 3/5/2015

Found out that iterating over the Entry set will be better performance wise:

for (Map.Entry<Integer, String> entry : hm.entrySet()) {
    Integer key = entry.getKey();
    String value = entry.getValue();

}

UPDATE 10/3/2017

For Java8 and streams, your solution will be (Thanks @Shihe Zhang)

 hm.forEach((key, value) -> System.out.println(key + ": " + value))

Cannot simply use PostgreSQL table name ("relation does not exist")

I had a similar problem on OSX but tried to play around with double and single quotes. For your case, you could try something like this

$query = 'SELECT * FROM "sf_bands"'; // NOTE: double quotes on "sf_Bands"

Installing PIL (Python Imaging Library) in Win7 64 bits, Python 2.6.4

If you installed a win64 python, you need a win64 PIL. The official PIL download site only has win32, as far as I can tell. The win32 installer will not see your 64-bit python installation.

No amount of tinkering with permissions or redistributables will fix this. You could use the win32 python instead (the Win64 python is mutant anyhow; Microsoft decided that C 'long' should be 32 bits in their 64-bit world, so python 'ints' are only 32 bits in Win64 python).

Since sizeof(long)!=sizeof(ptr) in win64, porting C extensions can be problematic, and will not be the same as porting them to linux 64. E.g. it seems that Win64 numpy is experimental/broken whereas linux64 numpy has been fine for years. My recommendation is if you use win64, stick with win32 python. If you want 64-bit python use linux.

Does Java SE 8 have Pairs or Tuples?

UPDATE: This answer is in response to the original question, Does Java SE 8 have Pairs or Tuples? (And implicitly, if not, why not?) The OP has updated the question with a more complete example, but it seems like it can be solved without using any kind of Pair structure. [Note from OP: here is the other correct answer.]


The short answer is no. You either have to roll your own or bring in one of the several libraries that implements it.

Having a Pair class in Java SE was proposed and rejected at least once. See this discussion thread on one of the OpenJDK mailing lists. The tradeoffs are not obvious. On the one hand, there are many Pair implementations in other libraries and in application code. That demonstrates a need, and adding such a class to Java SE will increase reuse and sharing. On the other hand, having a Pair class adds to the temptation of creating complicated data structures out of Pairs and collections without creating the necessary types and abstractions. (That's a paraphrase of Kevin Bourillion's message from that thread.)

I recommend everybody read that entire email thread. It's remarkably insightful and has no flamage. It's quite convincing. When it started I thought, "Yeah, there should be a Pair class in Java SE" but by the time the thread reached its end I had changed my mind.

Note however that JavaFX has the javafx.util.Pair class. JavaFX's APIs evolved separately from the Java SE APIs.

As one can see from the linked question What is the equivalent of the C++ Pair in Java? there is quite a large design space surrounding what is apparently such a simple API. Should the objects be immutable? Should they be serializable? Should they be comparable? Should the class be final or not? Should the two elements be ordered? Should it be an interface or a class? Why stop at pairs? Why not triples, quads, or N-tuples?

And of course there is the inevitable naming bikeshed for the elements:

  • (a, b)
  • (first, second)
  • (left, right)
  • (car, cdr)
  • (foo, bar)
  • etc.

One big issue that has hardly been mentioned is the relationship of Pairs to primitives. If you have an (int x, int y) datum that represents a point in 2D space, representing this as Pair<Integer, Integer> consumes three objects instead of two 32-bit words. Furthermore, these objects must reside on the heap and will incur GC overhead.

It would seem clear that, like Streams, it would be essential for there to be primitive specializations for Pairs. Do we want to see:

Pair
ObjIntPair
ObjLongPair
ObjDoublePair
IntObjPair
IntIntPair
IntLongPair
IntDoublePair
LongObjPair
LongIntPair
LongLongPair
LongDoublePair
DoubleObjPair
DoubleIntPair
DoubleLongPair
DoubleDoublePair

Even an IntIntPair would still require one object on the heap.

These are, of course, reminiscent of the proliferation of functional interfaces in the java.util.function package in Java SE 8. If you don't want a bloated API, which ones would you leave out? You could also argue that this isn't enough, and that specializations for, say, Boolean should be added as well.

My feeling is that if Java had added a Pair class long ago, it would have been simple, or even simplistic, and it wouldn't have satisfied many of the use cases we are envisioning now. Consider that if Pair had been added in the JDK 1.0 time frame, it probably would have been mutable! (Look at java.util.Date.) Would people have been happy with that? My guess is that if there were a Pair class in Java, it would be kinda-sort-not-really-useful and everybody will still be rolling their own to satisfy their needs, there would be various Pair and Tuple implementations in external libraries, and people would still be arguing/discussing about how to fix Java's Pair class. In other words, kind of in the same place we're at today.

Meanwhile, some work is going on to address the fundamental issue, which is better support in the JVM (and eventually the Java language) for value types. See this State of the Values document. This is preliminary, speculative work, and it covers only issues from the JVM perspective, but it already has a fair amount of thought behind it. Of course there are no guarantees that this will get into Java 9, or ever get in anywhere, but it does show the current direction of thinking on this topic.

How to include PHP files that require an absolute path?

@Flubba, does this allow me to have folders inside my include directory? flat include directories give me nightmares. as the whole objects directory should be in the inc directory.

Oh yes, absolutely. So for example, we use a single layer of subfolders, generally:

require_once('library/string.class.php')

You need to be careful with relying on the include path too much in really high traffic sites, because php has to hunt through the current directory and then all the directories on the include path in order to see if your file is there and this can slow things up if you're getting hammered.

So for example if you're doing MVC, you'd put the path to your application directoy in the include path and then specify refer to things in the form

'model/user.class'
'controllers/front.php'

or whatever.

But generally speaking, it just lets you work with really short paths in your PHP that will work from anywhere and it's a lot easier to read than all that realpath document root malarkey.

The benefit of those script-based alternatives others have suggested is they work anywhere, even on shared boxes; setting the include path requires a little more thought and effort but as I mentioned lets you start using __autoload which just the coolest.

HTML iframe - disable scroll

For this frame:

    <iframe src="" name="" id=""></iframe>

I tried this on my css code:

    iframe#put the value of id here::-webkit-scrollbar {
         display: none;
    }

How to BULK INSERT a file into a *temporary* table where the filename is a variable?

You could always construct the #temp table in dynamic SQL. For example, right now I guess you have been trying:

CREATE TABLE #tmp(a INT, b INT, c INT);

DECLARE @sql NVARCHAR(1000);

SET @sql = N'BULK INSERT #tmp ...' + @variables;

EXEC master.sys.sp_executesql @sql;

SELECT * FROM #tmp;

This makes it tougher to maintain (readability) but gets by the scoping issue:

DECLARE @sql NVARCHAR(MAX);

SET @sql = N'CREATE TABLE #tmp(a INT, b INT, c INT);

BULK INSERT #tmp ...' + @variables + ';

SELECT * FROM #tmp;';

EXEC master.sys.sp_executesql @sql;

EDIT 2011-01-12

In light of how my almost 2-year old answer was suddenly deemed incomplete and unacceptable, by someone whose answer was also incomplete, how about:

CREATE TABLE #outer(a INT, b INT, c INT);

DECLARE @sql NVARCHAR(MAX);

SET @sql = N'SET NOCOUNT ON; 

CREATE TABLE #inner(a INT, b INT, c INT);

BULK INSERT #inner ...' + @variables + ';

SELECT * FROM #inner;';

INSERT #outer EXEC master.sys.sp_executesql @sql;

What is 'Context' on Android?

Think of Context as a box with different resources: string, colors, and fonts. If you need a resource, you turn to this box. When you rotate the screen, this box changes because the orientation changes to landscape.

Left align block of equations

Try to use the fleqn document class option.

\documentclass[fleqn]{article}

(See also http://en.wikibooks.org/wiki/LaTeX/Basics for a list of other options.)

How to pass multiple parameters from ajax to mvc controller?

function toggleCheck(employeeId) {
    var data =  'referenceid= '+ employeeId +'&referencestatus=' 1;
    console.log(data);
    $.ajax({
        type : 'POST',
        url : 'edit',
        data : data,
        cache: false,
        async : false,
        success : function(employeeId) {
            alert("Success");
            window.redirect = "Users.jsp";
        }
    });

}

Why is my Spring @Autowired field null?

This is the culprit of giving NullPointerException MileageFeeCalculator calc = new MileageFeeCalculator(); We are using Spring - don't need to create object manually. Object creation will be taken care of by IoC container.

Detecting when a div's height changes using jQuery

In response to user007:

If the height of your element is changing due to items being appended to it using .append() you shouldn't need to detect the change in height. Simply add the reposition of your second element in the same function where you are appending the new content to your first element.

As in:

Working Example

$('.class1').click(function () {
    $('.class1').append("<div class='newClass'><h1>This is some content</h1></div>");
    $('.class2').css('top', $('.class1').offset().top + $('.class1').outerHeight());
});

Start systemd service after specific service?

After= dependency is only effective when service including After= and service included by After= are both scheduled to start as part of your boot up.

Ex:

a.service
[Unit]
After=b.service

This way, if both a.service and b.service are enabled, then systemd will order b.service after a.service.

If I am not misunderstanding, what you are asking is how to start b.service when a.service starts even though b.service is not enabled.

The directive for this is Wants= or Requires= under [Unit].

website.service
[Unit]
Wants=mongodb.service
After=mongodb.service

The difference between Wants= and Requires= is that with Requires=, a failure to start b.service will cause the startup of a.service to fail, whereas with Wants=, a.service will start even if b.service fails. This is explained in detail on the man page of .unit.

mongo - couldn't connect to server 127.0.0.1:27017

Remove mongod.lock file. And run "mongod -repair". uninstall/reinstall mongod service fixed that problem for me.

Thanks.

Javascript to display the current date and time

Get the data you need and combine it in the String;

getDate(): Returns the date
getMonth(): Returns the month
getFullYear(): Returns the year
getHours();
getMinutes();

Check out : Working With Dates

Check for a substring in a string in Oracle without LIKE

You can do it this way using INSTR:

SELECT * FROM users WHERE INSTR(LOWER(last_name), 'z') > 0;

INSTR returns zero if the substring is not in the string.

Out of interest, why don't you want to use like?

Edit: I took the liberty of making the search case insensitive so you don't miss Bob Zebidee. :-)

How many bytes in a JavaScript string?

String values are not implementation dependent, according the ECMA-262 3rd Edition Specification, each character represents a single 16-bit unit of UTF-16 text:

4.3.16 String Value

A string value is a member of the type String and is a finite ordered sequence of zero or more 16-bit unsigned integer values.

NOTE Although each value usually represents a single 16-bit unit of UTF-16 text, the language does not place any restrictions or requirements on the values except that they be 16-bit unsigned integers.

Android emulator doesn't take keyboard input - SDK tools rev 20

I have used an emulator for API Level 23, which does not take keyboard input for installed apk. So I have created new emulator for API Level 29, and then it works. Following is the step to install new emulator.

  1. Open "Android Virtual Device Manager"
  2. Create new Virtual Device.
  3. When you select a system image, please choose and download the last version(API Level29) on "Virtual Device Configuration" window

Unknown URL content://downloads/my_downloads

The exception is caused by disabled Download Manager. And there is no way to activate/deactivate Download Manager directly, since it's system application and we don't have access to it.

Only alternative way is redirect user to settings of Download Manager Application.

try {
     //Open the specific App Info page:
     Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
     intent.setData(Uri.parse("package:" + "com.android.providers.downloads"));
     startActivity(intent);

} catch ( ActivityNotFoundException e ) {
     e.printStackTrace();

     //Open the generic Apps page:
     Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS);
     startActivity(intent);
}

Set color of text in a Textbox/Label to Red and make it bold in asp.net C#

Try using the property ForeColor. Like this :

TextBox1.ForeColor = Color.Red;

How do I convert a C# List<string[]> to a Javascript array?

You could directly inject the values into JavaScript:

//View.cshtml
<script type="text/javascript">
    var arrayOfArrays = JSON.parse('@Html.Raw(Model.Addresses)');
</script>

See JSON.parse, Html.Raw

Alternatively you can get the values via Ajax:

public ActionResult GetValues()
{
    // logic
    // Edit you don't need to serialize it just return the object

    return Json(new { Addresses: lAddressGeocodeModel });
}

<script type="text/javascript">
$(function() {
    $.ajax({
        type: 'POST',
        url: '@Url.Action("GetValues")',
        success: function(result) {
            // do something with result
        }
    });
});
</script>

See jQuery.ajax

How to print variable addresses in C?

When you intend to print the memory address of any variable or a pointer, using %d won't do the job and will cause some compilation errors, because you're trying to print out a number instead of an address, and even if it does work, you'd have an intent error, because a memory address is not a number. the value 0xbfc0d878 is surely not a number, but an address.

What you should use is %p. e.g.,

#include<stdio.h>

int main(void) {

    int a;
    a = 5;
    printf("The memory address of a is: %p\n", (void*) &a);
    return 0;
}

Good luck!

How to use getJSON, sending data with post method?

I just used post and an if:

data = getDataObjectByForm(form);
var jqxhr = $.post(url, data, function(){}, 'json')
    .done(function (response) {
        if (response instanceof Object)
            var json = response;
        else
            var json = $.parseJSON(response);
        // console.log(response);
        // console.log(json);
        jsonToDom(json);
        if (json.reload != undefined && json.reload)
            location.reload();
        $("body").delay(1000).css("cursor", "default");
    })
    .fail(function (jqxhr, textStatus, error) {
        var err = textStatus + ", " + error;
        console.log("Request Failed: " + err);
        alert("Fehler!");
    });

How to get class object's name as a string in Javascript?

Some time ago, I used this.

Perhaps you could try:

+function(){
    var my_var = function get_this_name(){
        alert("I " + this.init());
    };
    my_var.prototype.init = function(){
        return my_var.name;
    }
    new my_var();
}();

Pop an Alert: "I get_this_name".

foreach for JSON array , syntax

You can do something like

for(var k in result) {
   console.log(k, result[k]);
}

which loops over all the keys in the returned json and prints the values. However, if you have a nested structure, you will need to use

typeof result[k] === "object"

to determine if you have to loop over the nested objects. Most APIs I have used, the developers know the structure of what is being returned, so this is unnecessary. However, I suppose it's possible that this expectation is not good for all cases.

'Missing contentDescription attribute on image' in XML

This warning tries to improve accessibility of your application.

To disable missing content description warning in the whole project, you can add this to your application module build.gradle

android {

    ...

    lintOptions {
        disable 'ContentDescription'
    }
}

How does Zalgo text work?

Zalgo text works because of combining characters. These are special characters that allow to modify character that comes before.

enter image description here

OR

y + ̆ = y̆ which actually is

y + &#x0306; = y&#x0306;

Since you can stack them one atop the other you can produce the following:


y̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆

which actually is:

y&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;

The same goes for putting stuff underneath:


y̰̰̰̰̰̰̰̰̰̰̰̰̰̰̰̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆



that in fact is:

y&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;

In Unicode, the main block of combining diacritics for European languages and the International Phonetic Alphabet is U+0300–U+036F.

More about it here

To produce a list of combining diacritical marks you can use the following script (since links keep on dying)

_x000D_
_x000D_
for(var i=768; i<879; i++){console.log(new DOMParser().parseFromString("&#"+i+";", "text/html").documentElement.textContent +"  "+"&#"+i+";");}
_x000D_
_x000D_
_x000D_

Also check em out



Mͣͭͣ̾ Vͣͥͭ͛ͤͮͥͨͥͧ̾

how to take user input in Array using java?

You can do the following:

    import java.util.Scanner;

    public class Test {

            public static void main(String[] args) {

            int arr[];
            Scanner scan = new Scanner(System.in);
            // If you want to take 5 numbers for user and store it in an int array
            for(int i=0; i<5; i++) {
                System.out.print("Enter number " + (i+1) + ": ");
                arr[i] = scan.nextInt();    // Taking user input
            }

            // For printing those numbers
            for(int i=0; i<5; i++) 
                System.out.println("Number " + (i+1) + ": " + arr[i]);
        }
    }

Remove lines that contain certain string

The else is only connected to the last if. You want elif:

if 'bad' in line:
    pass
elif 'naughty' in line:
    pass
else:
    newopen.write(line)

Also note that I removed the line substitution, as you don't write those lines anyway.

How to get commit history for just one branch?

You can use only git log --oneline

Strip off URL parameter with PHP

This should do it:

public function removeQueryParam(string $url, string $param): string
{
    $parsedUrl = parse_url($url);

    if (isset($parsedUrl[$param])) {
        $baseUrl = strtok($url, '?');
        parse_str(parse_url($url)['query'], $query);
        unset($query[$param]);
        return sprintf('%s?%s',
            $baseUrl,
            http_build_query($query)
        );
    }

    return $url;
}

Difference between one-to-many and many-to-one relationship

Example

Two tables with one relation

SQL

In SQL, there is only one kind of relationship, it is called a Reference. (Your front end may do helpful or confusing things [such as in some of the Answers], but that is a different story.)

  • A Foreign Key in one table (the referencing table)
    References
    a Primary Key in another table (the referenced table)
  • In SQL terms, Bar references Foo
    Not the other way around

    CREATE TABLE Foo (
        Foo   CHAR(10)  NOT NULL, -- primary key
        Name  CHAR(30)  NOT NULL
        CONSTRAINT PK             -- constraint name
            PRIMARY KEY (Foo)     -- pk
        )  
    CREATE TABLE Bar (
        Bar   CHAR(10)  NOT NULL, -- primary key
        Foo   CHAR(10)  NOT NULL, -- foreign key to Foo
        Name  CHAR(30)  NOT NULL
        CONSTRAINT PK                -- constraint name
            PRIMARY KEY (Bar),       -- pk
        CONSTRAINT Foo_HasMany_Bars  -- constraint name
            FOREIGN KEY   (Foo)      -- fk in (this) referencing table
            REFERENCES Foo(Foo)      -- pk in referenced table
        )
    
  • Since Foo.Foo is a Primary Key, it is unique, there is only one row for any given value of Foo

  • Since Bar.Foo is a Reference, a Foreign Key, and there is no unique index on it, there can be many rows for any given value of Foo
  • Therefore the relation Foo::Bar is one-to-many
  • Now you can perceive (look at) the relation the other way around, Bar::Foo is many-to-one
    • But do not let that confuse you: for any one Bar row, there is just one Foo row that it References
  • In SQL, that is all we have. That is all that is necessary.

What is the real difference between one to many and many to one relationship?

There is only one relation, therefore there is no difference. Perception (from one "end" or the other "end") or reading it backwards, does not change the relation.

Cardinality

Cardinality is declared first in the data model, which means Logical and Physical (the intent), and then in the implementation (the intent realised).

Cardinality

One to zero-to-many
In SQL that (the above) is all that is required.

One to one-to-many
You need a Transaction to enforce the one in the Referencing table.

One to zero-to-one
You need in Bar:

CONSTRAINT AK    -- constraint name
    UNIQUE (Foo) -- unique column, which makes it an Alternate Key

One to one
You need a Transaction to enforce the one in the Referencing table.

Many to many
There is no such thing at the Physical level (recall, there is only one type of relation in SQL).

At the early Logical levels during the modelling exercise, it is convenient to draw such a relation. Before the model gets close to implementation, it had better be elevated to using only things that can exist. Such a relation is resolved by implementing an Associative Table.

Many-to-many Resolved

Collision resolution in Java HashMap

First of all, you have got the concept of hashing a little wrong and it had been rectified by Mr. Sanjay.

And yes, Java indeed implement a collision resolution technique. When two keys get hashed to a same value (as the internal array used is finite in size and at some point the hashcode() method will return same hash value for two different keys) at this time, a linked list is formed at the bucket location where all the informations are entered as an Map.Entry object that contains a key-value pair. Accessing an object via a key will at worst require O(n) if the entry in present in such a lists. Comparison between the key you passed with each key in such list will be done by the equals() method.

Although, from Java 8 , the linked lists are replaced with trees (O(log n))

What Are The Best Width Ranges for Media Queries

Try this one with retina display

/* Smartphones (portrait and landscape) ----------- */
@media only screen 
and (min-device-width : 320px) 
and (max-device-width : 480px) {
/* Styles */
}

/* Smartphones (landscape) ----------- */
@media only screen 
and (min-width : 321px) {
/* Styles */
}

/* Smartphones (portrait) ----------- */
@media only screen 
and (max-width : 320px) {
/* Styles */
}

/* iPads (portrait and landscape) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) {
/* Styles */
}

/* iPads (landscape) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : landscape) {
/* Styles */
}

/* iPads (portrait) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : portrait) {
/* Styles */
}

/* Desktops and laptops ----------- */
@media only screen 
and (min-width : 1224px) {
/* Styles */
}

/* Large screens ----------- */
@media only screen 
and (min-width : 1824px) {
/* Styles */
}

/* iPhone 4 ----------- */
@media
only screen and (-webkit-min-device-pixel-ratio : 1.5),
only screen and (min-device-pixel-ratio : 1.5) {
/* Styles */
}

Update

/* Smartphones (portrait and landscape) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-width: 480px) {
  /* Styles */
}

/* Smartphones (landscape) ----------- */
@media only screen and (min-width: 321px) {
  /* Styles */
}

/* Smartphones (portrait) ----------- */
@media only screen and (max-width: 320px) {
  /* Styles */
}

/* iPads (portrait and landscape) ----------- */
@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) {
  /* Styles */
}

/* iPads (landscape) ----------- */
@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (orientation: landscape) {
  /* Styles */
}

/* iPads (portrait) ----------- */
@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (orientation: portrait) {
  /* Styles */
}

/* iPad 3 (landscape) ----------- */
@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (orientation: landscape) and (-webkit-min-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPad 3 (portrait) ----------- */
@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (orientation: portrait) and (-webkit-min-device-pixel-ratio: 2) {
  /* Styles */
}

/* Desktops and laptops ----------- */
@media only screen and (min-width: 1224px) {
  /* Styles */
}

/* Large screens ----------- */
@media only screen and (min-width: 1824px) {
  /* Styles */
}

/* iPhone 4 (landscape) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-width: 480px) and (orientation: landscape) and (-webkit-min-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 4 (portrait) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-width: 480px) and (orientation: portrait) and (-webkit-min-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 5 (landscape) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 5 (portrait) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 6 (landscape) ----------- */
@media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 6 (portrait) ----------- */
@media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 6+ (landscape) ----------- */
@media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 6+ (portrait) ----------- */
@media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* Samsung Galaxy S3 (landscape) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* Samsung Galaxy S3 (portrait) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* Samsung Galaxy S4 (landscape) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 3) {
  /* Styles */
}

/* Samsung Galaxy S4 (portrait) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 3) {
  /* Styles */
}

/* Samsung Galaxy S5 (landscape) ----------- */
@media only screen and (min-device-width: 360px) and (max-device-height: 640px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 3) {
  /* Styles */
}

/* Samsung Galaxy S5 (portrait) ----------- */
@media only screen and (min-device-width: 360px) and (max-device-height: 640px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 3) {
  /* Styles */
}

Search in lists of lists by given index

>>> the_list =[ ['a','b'], ['a','c'], ['b''d'] ]
>>> any('c' == x[1] for x in the_list)
True

How do I efficiently iterate over each entry in a Java Map?

This is the easiest way of doing it I believe...

/* For example, this could be a map object */
Map<String, Integer> MAP = new Map<>();

// Do something like put keys/value pairs into the map, etc...
MAP.put("Denver", 35);
MAP.put("Patriots", 14);

/* Then, simply use a for each loop like this to iterate */
for (Object o : MAP.entrySet()) {
    Map.Entry pair = (Map.Entry) o;
    // Do whatever with the pair here (i.e. pair.getKey(), or pair.getValue();
}

splitting a number into the integer and decimal parts

I have come up with two statements that can divide positive and negative numbers into integers and fractions without compromising accuracy (bit overflow) and speed.

x = 100.1323 # A number to be divided into integers and fractions

# The two statement to divided a number into integers and fractions
i = int(x) # A positive or negative integer
f = (x*1e17-i*1e17)/1e17 # A positive or negative fraction

E.g. 100.1323 -> 100, 0.1323 or -100.1323 -> -100, -0.1323

Speedtest

The performance test shows that the two statements are faster than math.modf, as long as they are not put into their own function or method.

test.py:

#!/usr/bin/env python
import math
import cProfile

""" Get the performance of both statements and math.modf. """

X = -100.1323 # The number to be divided into integers and fractions
LOOPS = range(5*10**6) # Number of loops

def scenario_a():
    """ The integers (i) and the fractions (f)
        come out as integer and float. """
    for _ in LOOPS:
        i = int(X) # -100
        f = (X*1e17-i*1e17)/1e17 # -0.1323

def scenario_b():
    """ The integers (i) and the fractions (f)
        come out as float.
        NOTE: The only difference between this
              and math.modf is the accuracy. """
    for _ in LOOPS:
        i = int(X) # -100
        i, f = float(i), (X*1e17-i*1e17)/1e17 # (-100.0, -0.1323)

def scenario_c():
    """ Performance test of the statements in a function. """
    def modf(x):
        i = int(x)
        return i, (x*1e17-i*1e17)/1e17

    for _ in LOOPS:
        i, f = modf(X) # (-100, -0.1323)

def scenario_d():
    for _ in LOOPS:
        f, i = math.modf(X) # (-100.0, -0.13230000000000075)

def scenario_e():
    """ Convert the integer part to real integer. """
    for _ in LOOPS:
        f, i = math.modf(X) # (-100.0, -0.13230000000000075)
        i = int(i) # -100

if __name__ == '__main__':
    cProfile.run('scenario_a()')
    cProfile.run('scenario_b()')
    cProfile.run('scenario_c()')
    cProfile.run('scenario_d()')
    cProfile.run('scenario_e()')

Output:

         4 function calls in 1.312 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    1.312    1.312 <string>:1(<module>)
        1    1.312    1.312    1.312    1.312 test.py:10(scenario_a)
        1    0.000    0.000    1.312    1.312 {built-in method builtins.exec}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}


         4 function calls in 1.887 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    1.887    1.887 <string>:1(<module>)
        1    1.887    1.887    1.887    1.887 test.py:18(scenario_b)
        1    0.000    0.000    1.887    1.887 {built-in method builtins.exec}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}


         5000004 function calls in 2.797 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    2.797    2.797 <string>:1(<module>)
        1    1.261    1.261    2.797    2.797 test.py:27(scenario_c)
  5000000    1.536    0.000    1.536    0.000 test.py:31(modf)
        1    0.000    0.000    2.797    2.797 {built-in method builtins.exec}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}


         5000004 function calls in 1.852 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    1.852    1.852 <string>:1(<module>)
        1    1.050    1.050    1.852    1.852 test.py:38(scenario_d)
        1    0.000    0.000    1.852    1.852 {built-in method builtins.exec}
  5000000    0.802    0.000    0.802    0.000 {built-in method math.modf}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}


         5000004 function calls in 2.467 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    2.467    2.467 <string>:1(<module>)
        1    1.652    1.652    2.467    2.467 test.py:42(scenario_e)
        1    0.000    0.000    2.467    2.467 {built-in method builtins.exec}
  5000000    0.815    0.000    0.815    0.000 {built-in method math.modf}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

NOTE:

The statement can be faster with modulo, but modulo can not be used to split negative numbers into integer and fraction parts.

i, f = int(x), x*1e17%1e17/1e17 # x can not be negative

Remove empty array elements

$linksArray = array_filter($linksArray);

"If no callback is supplied, all entries of input equal to FALSE will be removed." -- http://php.net/manual/en/function.array-filter.php

Delegates in swift?

In swift 4.0

Create a delegate on class that need to send some data or provide some functionality to other classes

Like

protocol GetGameStatus {
    var score: score { get }
    func getPlayerDetails()
}

After that in the class that going to confirm to this delegate

class SnakesAndLadders: GetGameStatus {
    func getPlayerDetails() {

 }
}

Understanding MongoDB BSON Document size limit

To post a clarification answer here for those who get directed here by Google.

The document size includes everything in the document including the subdocuments, nested objects etc.

So a document of:

{
  "_id": {},
  "na": [1, 2, 3],
  "naa": [
    { "w": 1, "v": 2, "b": [1, 2, 3] },
    { "w": 5, "b": 2, "h": [{ "d": 5, "g": 7 }, {}] }
  ]
}

Has a maximum size of 16 MB.

Subdocuments and nested objects are all counted towards the size of the document.

How to paste text to end of every line? Sublime 2

Use column selection. Column selection is one of the unique features of Sublime2; it is used to give you multiple matched cursors (tutorial here). To get multiple cursors, do one of the following:

Mouse:

  • Hold down the shift (Windows/Linux) or option key (Mac) while selecting a region with the mouse.

  • Clicking middle mouse button (or scroll) will select as a column also.

Keyboard:

  • Select the desired region.
  • Type control+shift+L (Windows/Linux) or command+shift+L (Mac)

You now have multiple lines selected, so you could type a quotation mark at the beginning and end of each line. It would be better to take advantage of Sublime's capabilities, and just type ". When you do this, Sublime automatically quotes the selected text.

Type esc to exit multiple cursor mode.

Where can I download JSTL jar

You can download JSTL 1.1 here and JSTL 1.2 here.

See also:

How to use LINQ Distinct() with multiple fields

Employee emp1 = new Employee() { ID = 1, Name = "Narendra1", Salary = 11111, Experience = 3, Age = 30 };Employee emp2 = new Employee() { ID = 2, Name = "Narendra2", Salary = 21111, Experience = 10, Age = 38 };
Employee emp3 = new Employee() { ID = 3, Name = "Narendra3", Salary = 31111, Experience = 4, Age = 33 };
Employee emp4 = new Employee() { ID = 3, Name = "Narendra4", Salary = 41111, Experience = 7, Age = 33 };

List<Employee> lstEmployee = new List<Employee>();

lstEmployee.Add(emp1);
lstEmployee.Add(emp2);
lstEmployee.Add(emp3);
lstEmployee.Add(emp4);

var eemmppss=lstEmployee.Select(cc=>new {cc.ID,cc.Age}).Distinct();

In C++, what is a virtual base class?

About the memory layout

As a side note, the problem with the Dreaded Diamond is that the base class is present multiple times. So with regular inheritance, you believe you have:

  A
 / \
B   C
 \ /
  D

But in the memory layout, you have:

A   A
|   |
B   C
 \ /
  D

This explain why when call D::foo(), you have an ambiguity problem. But the real problem comes when you want to use a member variable of A. For example, let's say we have:

class A
{
    public :
       foo() ;
       int m_iValue ;
} ;

When you'll try to access m_iValue from D, the compiler will protest, because in the hierarchy, it'll see two m_iValue, not one. And if you modify one, say, B::m_iValue (that is the A::m_iValue parent of B), C::m_iValue won't be modified (that is the A::m_iValue parent of C).

This is where virtual inheritance comes handy, as with it, you'll get back to a true diamond layout, with not only one foo() method only, but also one and only one m_iValue.

What could go wrong?

Imagine:

  • A has some basic feature.
  • B adds to it some kind of cool array of data (for example)
  • C adds to it some cool feature like an observer pattern (for example, on m_iValue).
  • D inherits from B and C, and thus from A.

With normal inheritance, modifying m_iValue from D is ambiguous and this must be resolved. Even if it is, there are two m_iValues inside D, so you'd better remember that and update the two at the same time.

With virtual inheritance, modifying m_iValue from D is ok... But... Let's say that you have D. Through its C interface, you attached an observer. And through its B interface, you update the cool array, which has the side effect of directly changing m_iValue...

As the change of m_iValue is done directly (without using a virtual accessor method), the observer "listening" through C won't be called, because the code implementing the listening is in C, and B doesn't know about it...

Conclusion

If you're having a diamond in your hierarchy, it means that you have 95% probability to have done something wrong with said hierarchy.

Multi-gradient shapes

Have you tried to overlay one gradient with a nearly-transparent opacity for the highlight on top of another image with an opaque opacity for the green gradient?

Autoplay audio files on an iPad with HTML5

I handled this by attaching an event handler for all the events for which you are allowed to trigger audio to the body element which triggers any html audio elements with autoplay to play once.

var mobile = /iPad|iPhone|iPod|android/.test(navigator.userAgent) && !window.MSStream;
if (mobile) {
    $('body').on('touchstart click doubleclick keydown', function() {
        $("audio[autoplay='autoplay']").each(
            function(){
                this.play();
                this.removeAttribute('autoplay');
            });
    });
}

How to check if element in groovy array/hash/collection/list?

For lists, use contains:

[1,2,3].contains(1) == true

Command-line Tool to find Java Heap Size and Memory Used (Linux)?

First get the process id, the first number from the process listed, from one of the following: (or just use ps aux | grep java, if you prefer that)

jps -lvm

Then use the process ID here:

jmap -heap $MY_PID 2>/dev/null | sed -ne '/Heap Configuration/,$p';
jmap -permstat $MY_PID

How to initialize a static array?

Nope, no difference. It's just syntactic sugar. Arrays.asList(..) creates an additional list.

Entity framework code-first null foreign key

I prefer this (below):

public class User
{
    public int Id { get; set; }
    public int? CountryId { get; set; }
    [ForeignKey("CountryId")]
    public virtual Country Country { get; set; }
}

Because EF was creating 2 foreign keys in the database table: CountryId, and CountryId1, but the code above fixed that.

How to convert a JSON string to a Map<String, String> with Jackson JSON

Try TypeFactory. Here's the code for Jackson JSON (2.8.4).

Map<String, String> result;
ObjectMapper mapper;
TypeFactory factory;
MapType type;

factory = TypeFactory.defaultInstance();
type    = factory.constructMapType(HashMap.class, String.class, String.class);
mapper  = new ObjectMapper();
result  = mapper.readValue(data, type);

Here's the code for an older version of Jackson JSON.

Map<String, String> result = new ObjectMapper().readValue(
    data, TypeFactory.mapType(HashMap.class, String.class, String.class));

Get POST data in C#/ASP.NET

I'm a little surprised that this question has been asked so many times before, but the most reuseable and friendly solution hasn't been documented.

I often have webpages using AngularJS, and when I click on a Save button, I'll "POST" this data back to my .aspx page or .ashx handler to save this back to the database. The data will be in the form of a JSON record.

On the server, to turn the raw posted data back into a C# class, here's what I would do.

First, define a C# class which will contain the posted data.

Supposing my webpage is posting JSON data like this:

{
    "UserID" : 1,
    "FirstName" : "Mike",
    "LastName" : "Mike",
    "Address1" : "10 Really Street",
    "Address2" : "London"
}

Then I'd define a C# class like this...

public class JSONRequest
{
    public int UserID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Address1 { get; set; }
    public string Address2 { get; set; }
}

(These classes can be nested, but the structure must match the format of the JSON data. So, if you're posting a JSON User record, with a list of Order records within it, your C# class should also contain a List<> of Order records.)

Now, in my .aspx.cs or .ashx file, I just need to do this, and leave JSON.Net to do the hard work...

    protected void Page_Load(object sender, EventArgs e)
    {
        string jsonString = "";
        HttpContext.Current.Request.InputStream.Position = 0;
        using (StreamReader inputStream = new StreamReader(this.Request.InputStream))
        {
            jsonString = inputStream.ReadToEnd();
        }
        JSONRequest oneQuestion = JsonConvert.DeserializeObject<JSONRequest>(jsonString);

And that's it. You now have a JSONRequest class containing the various fields which were POSTed to your server.

Calling filter returns <filter object at ... >

It's an iterator returned by the filter function.

If you want a list, just do

list(filter(f, range(2, 25)))

Nonetheless, you can just iterate over this object with a for loop.

for e in filter(f, range(2, 25)):
    do_stuff(e)

CSS : center form in page horizontally and vertically

If you want to do a horizontal centering, just put the form inside a DIV tag and apply align="center" attribute to it. So even if the form width is changed, your centering will remain the same.

<div align="center"><form id="form_login"><!--form content here--></form></div>

UPDATE

@G-Cyr is right. align="center" attribute is now obsolete. You can use text-align attribute for this as following.

<div style="text-align:center"><form id="form_login"><!--form content here--></form></div>

This will center all the content inside the parent DIV. An optional way is to use margin: auto CSS attribute with predefined widths and heights. Please follow the following thread for more information.

How to horizontally center a in another ?

Vertical centering is little difficult than that. To do that, you can do the following stuff.

html

<body>
<div id="parent">
    <form id="form_login">
     <!--form content here-->
    </form>
</div>
</body>

Css

#parent {
   display: table;
   width: 100%;
}
#form_login {
   display: table-cell;
   text-align: center;
   vertical-align: middle;
}

How to display UTF-8 characters in phpMyAdmin?

ALTER TABLE table_name CONVERT to CHARACTER SET utf8;

*IMPORTANT: Back-up first, execute after

How can I get all sequences in an Oracle database?

select sequence_owner, sequence_name from dba_sequences;


DBA_SEQUENCES -- all sequences that exist 
ALL_SEQUENCES  -- all sequences that you have permission to see 
USER_SEQUENCES  -- all sequences that you own

Note that since you are, by definition, the owner of all the sequences returned from USER_SEQUENCES, there is no SEQUENCE_OWNER column in USER_SEQUENCES.

How to add leading zeros for for-loop in shell?

I'm not interested in outputting it to the screen (that's what printf is mainly used for, right?) The variable $num is going to be used as a parameter for another program but let me see what I can do with this.

You can still use printf:

for num in {1..5}
do
   value=$(printf "%02d" $num)
   ... Use $value for your purposes
done

package javax.mail and javax.mail.internet do not exist

I just resolved this for myself, so hope this helps. My project runs on GlassFish 4, Eclipse MARS, with JDK 1.8 and JavaEE 7.

Firstly, you can find javax.mail.jar in the extracted glassfish folder: glassfish4->glassfish->modules

Next, in Eclipse, Right Click on your project in the explorer and navigate the following: Properties->Java Build Path->Libraries->Add External JARs-> Go to the aforementioned folder to add javax.mail.jar

Round float to x decimals?

Default rounding in python and numpy:

In: [round(i) for i in np.arange(10) + .5]
Out: [0, 2, 2, 4, 4, 6, 6, 8, 8, 10]

I used this to get integer rounding to be applied to a pandas series:

import decimal

and use this line to set the rounding to "half up" a.k.a rounding as taught in school: decimal.getcontext().rounding = decimal.ROUND_HALF_UP

Finally I made this function to apply it to a pandas series object

def roundint(value):
    return value.apply(lambda x: int(decimal.Decimal(x).to_integral_value()))

So now you can do roundint(df.columnname)

And for numbers:

In: [int(decimal.Decimal(i).to_integral_value()) for i in np.arange(10) + .5]
Out: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Credit: kares

Already defined in .obj - no double inclusions

This is one of the method to overcome this issue.

  • Just put the prototype in the header files and include the header files in the .cpp files as shown below.

client.cpp

#ifndef SOCKET_CLIENT_CLASS
#define SOCKET_CLIENT_CLASS
#ifndef BOOST_ASIO_HPP
#include <boost/asio.hpp>
#endif

class SocketClient // Or whatever the name is... {

// ...

    bool read(int, char*); // Or whatever the name is...

//  ... };

#endif

client.h

bool SocketClient::read(int, char*)
{
    // Implementation  goes here...
}

main.cpp

#include <iostream>
#include <string>
#include <sstream>
#include <boost/asio.hpp>
#include <boost/thread/thread.hpp>
#include "client.h"
//              ^^ Notice this!

main.h

int main()

Why can't I do <img src="C:/localfile.jpg">?

Browsers aren't allowed to access the local file system unless you're accessing a local html page. You have to upload the image somewhere. If it's in the same directory as the html file, then you can use <img src="localfile.jpg"/>

Stock ticker symbol lookup API

Use YQL and you don't need to worry. It's a query language by Yahoo and you can get all the stock data including the name of the company for the ticker. It's a REST API and it returns the results via XML or JSON. I have a full tutorial and source code on my site take a look: http://www.jarloo.com/yahoo-stock-symbol-lookup/

Why do people hate SQL cursors so much?

In general, because on a relational database, the performance of code using cursors is an order of magnitude worse than set-based operations.

How do I reset a jquery-chosen select option with jQuery?

from above solutions, Nothing worked for me. This worked:

$('#client_filter').html(' '); //this worked

Why is that? :)

$.ajax({ 
        type: 'POST', 
        url: xyz_ajax,
        dataType: "json",
        data : { csrfmiddlewaretoken: csrftoken,
                instancess : selected_instances }, 
        success: function(response) { 
            //clear the client DD       
            $('#client_filter').val('').trigger('change') ; //not working
            $('#client_filter').val('').trigger('chosen:updated') ; //not working
            $('#client_filter').val('').trigger('liszt:updated') ; //not working
             $('#client_filter').html(' '); //this worked
             jQuery.each(response, function(index, item) {
                  $('#client_filter').append('<option value="'+item.id+'">' + item.text + '</option>');
                });                 
           $('#client_filter').trigger("chosen:updated");
        }
      });
     } 

How to add a custom HTTP header to every WCF call?

This works for me

TestService.ReconstitutionClient _serv = new TestService.TestClient();

using (OperationContextScope contextScope = new OperationContextScope(_serv.InnerChannel))
{
   HttpRequestMessageProperty requestMessage = new HttpRequestMessageProperty();

   requestMessage.Headers["apiKey"] = ConfigurationManager.AppSettings["apikey"]; 
   OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = 
      requestMessage;
   _serv.Method(Testarg);
}

Best way to remove items from a collection

The best way to do it is by using linq.

Example class:

 public class Product
    {
        public string Name { get; set; }
        public string Price { get; set; }      
    }

Linq query:

var subCollection = collection1.RemoveAll(w => collection2.Any(q => q.Name == w.Name));

This query will remove all elements from collection1 if Name match any element Name from collection2

Remember to use: using System.Linq;

Requested registry access is not allowed

As a temporary fix, users can right click the utility and select "Run as administrator."

How to remove all callbacks from a Handler?

Please note that one should define a Handler and a Runnable in class scope, so that it is created once.removeCallbacks(Runnable) works correctly unless one defines them multiple times. Please look at following examples for better understanding:

Incorrect way :

    public class FooActivity extends Activity {
           private void handleSomething(){
                Handler handler = new Handler();
                Runnable runnable = new Runnable() {
                   @Override
                   public void run() {
                      doIt();
                  }
               };
              if(shouldIDoIt){
                  //doIt() works after 3 seconds.
                  handler.postDelayed(runnable, 3000);
              } else {
                  handler.removeCallbacks(runnable);
              }
           }

          public void onClick(View v){
              handleSomething();
          }
    } 

If you call onClick(..) method, you never stop doIt() method calling before it call. Because each time creates new Handler and new Runnable instances. In this way, you lost necessary references which belong to handler and runnable instances.

Correct way :

 public class FooActivity extends Activity {
        Handler handler = new Handler();
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                doIt();
            }
        };
        private void handleSomething(){
            if(shouldIDoIt){
                //doIt() works after 3 seconds.
                handler.postDelayed(runnable, 3000);
            } else {
                handler.removeCallbacks(runnable);
            }
       }

       public void onClick(View v){
           handleSomething();
       }
 } 

In this way, you don't lost actual references and removeCallbacks(runnable) works successfully.

Key sentence is that 'define them as global in your Activity or Fragment what you use'.

Which language uses .pde extension?

pde is extesion for:

  • Processing: Java derived language

  • Wiring: C/C++ derived language (Wiring is derived from Processing)

  • Early versions of Arduino: C/C++ derived (Arduino IDE is derived from Wiring)

For Arduino for example the IDE preprocessor is adding some #defines and some C/C++ files before giving all to gcc.

How to initialize a vector with fixed length in R

If you want to initialize a vector with numeric values other than zero, use rep

n <- 10
v <- rep(0.05, n)
v

which will give you:

[1] 0.05 0.05 0.05 0.05 0.05 0.05 0.05 0.05 0.05 0.05

How to force a web browser NOT to cache images

I would use:

<img src="picture.jpg?20130910043254">

where "20130910043254" is the modification time of the file.

When uploading an image, its filename is not kept in the database. It is renamed as Image.jpg (to simply things out when using it). When replacing the existing image with a new one, the name doesn't change either. Just the content of the image file changes.

I think there are two types of simple solutions: 1) those which come to mind first (straightforward solutions, because they are easy to come up with), 2) those which you end up with after thinking things over (because they are easy to use). Apparently, you won't always benefit if you chose to think things over. But the second options is rather underestimated, I believe. Just think why php is so popular ;)

How do I update the element at a certain position in an ArrayList?

arrayList.set(location,newValue); location= where u wnna insert, newValue= new element you are inserting.

notify is optional, depends on conditions.

What is the difference between a var and val definition in Scala?

"val means immutable and var means mutable."

To paraphrase, "val means value and var means variable".

A distinction that happens to be extremely important in computing (because those two concepts define the very essence of what programming is all about), and that OO has managed to blur almost completely, because in OO, the only axiom is that "everything is an object". And that as a consequence, lots of programmers these days tend not to understand/appreciate/recognize, because they have been brainwashed into "thinking the OO way" exclusively. Often leading to variable/mutable objects being used like everywhere, when value/immutable objects might/would often have been better.

How to get numbers after decimal point?

What about:

a = 1.3927278749291
b = a - int(a)

b
>> 0.39272787492910011

Or, using numpy:

import numpy
a = 1.3927278749291
b = a - numpy.fix(a)

How to Get the Query Executed in Laravel 5? DB::getQueryLog() Returning Empty Array

I think the answer located in this article: https://arjunphp.com/laravel-5-5-log-eloquent-queries/

is fast and simple to achieve query logging.

You just have to add to the AppServiceProvider in the boot method a callback to listen to DB queries:

namespace App\Providers;

use DB;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        DB::listen(function($query) {
            logger()->info($query->sql . print_r($query->bindings, true));
        });
    }
}

How to Parse JSON Array with Gson

in Kotlin :

val jsonArrayString = "['A','B','C']"

val gson = Gson()

val listType: Type = object : TypeToken<List<String?>?>() {}.getType()

val stringList : List<String> = gson.fromJson(
                            jsonArrayString,
                            listType)

How to fill in form field, and submit, using javascript?

document.getElementById('username').value = 'foo';
document.getElementById('login_form').submit();

SQL ORDER BY multiple columns

yes,the sorting proceed differently. in first scenario, orders based on column1 and in addition to that process further by sorting colmun2 based on column1 .. in second scenario ,it orders completely based on column 1 only... please proceed with a simple example...u will get quickly..

chart.js load totally new data

I had loads of trouble with this too. I have data and labels in separate arrays then I reinitialise the chart data. I added the line.destroy(); as suggested above which has done the trick

_x000D_
_x000D_
var ctx = document.getElementById("canvas").getContext("2d");_x000D_
if(window.myLine){_x000D_
 window.myLine.destroy();_x000D_
}_x000D_
window.myLine = new Chart(ctx).Line(lineChartData, {_x000D_
  etc_x000D_
  etc
_x000D_
_x000D_
_x000D_

Read text from response

response.GetResponseStream() should be used to return the response stream. And don't forget to close the Stream and Response objects.

Disable Rails SQL logging in console

To turn it off:

old_logger = ActiveRecord::Base.logger
ActiveRecord::Base.logger = nil

To turn it back on:

ActiveRecord::Base.logger = old_logger

What is a raw type and why shouldn't we use it?

What is a raw type?

The Java Language Specification defines a raw type as follows:

JLS 4.8 Raw Types

A raw type is defined to be one of:

  • The reference type that is formed by taking the name of a generic type declaration without an accompanying type argument list.

  • An array type whose element type is a raw type.

  • A non-static member type of a raw type R that is not inherited from a superclass or superinterface of R.

Here's an example to illustrate:

public class MyType<E> {
    class Inner { }
    static class Nested { }
    
    public static void main(String[] args) {
        MyType mt;          // warning: MyType is a raw type
        MyType.Inner inn;   // warning: MyType.Inner is a raw type

        MyType.Nested nest; // no warning: not parameterized type
        MyType<Object> mt1; // no warning: type parameter given
        MyType<?> mt2;      // no warning: type parameter given (wildcard OK!)
    }
}

Here, MyType<E> is a parameterized type (JLS 4.5). It is common to colloquially refer to this type as simply MyType for short, but technically the name is MyType<E>.

mt has a raw type (and generates a compilation warning) by the first bullet point in the above definition; inn also has a raw type by the third bullet point.

MyType.Nested is not a parameterized type, even though it's a member type of a parameterized type MyType<E>, because it's static.

mt1, and mt2 are both declared with actual type parameters, so they're not raw types.


What's so special about raw types?

Essentially, raw types behaves just like they were before generics were introduced. That is, the following is entirely legal at compile-time.

List names = new ArrayList(); // warning: raw type!
names.add("John");
names.add("Mary");
names.add(Boolean.FALSE); // not a compilation error!

The above code runs just fine, but suppose you also have the following:

for (Object o : names) {
    String name = (String) o;
    System.out.println(name);
} // throws ClassCastException!
  //    java.lang.Boolean cannot be cast to java.lang.String

Now we run into trouble at run-time, because names contains something that isn't an instanceof String.

Presumably, if you want names to contain only String, you could perhaps still use a raw type and manually check every add yourself, and then manually cast to String every item from names. Even better, though is NOT to use a raw type and let the compiler do all the work for you, harnessing the power of Java generics.

List<String> names = new ArrayList<String>();
names.add("John");
names.add("Mary");
names.add(Boolean.FALSE); // compilation error!

Of course, if you DO want names to allow a Boolean, then you can declare it as List<Object> names, and the above code would compile.

See also


How's a raw type different from using <Object> as type parameters?

The following is a quote from Effective Java 2nd Edition, Item 23: Don't use raw types in new code:

Just what is the difference between the raw type List and the parameterized type List<Object>? Loosely speaking, the former has opted out generic type checking, while the latter explicitly told the compiler that it is capable of holding objects of any type. While you can pass a List<String> to a parameter of type List, you can't pass it to a parameter of type List<Object>. There are subtyping rules for generics, and List<String> is a subtype of the raw type List, but not of the parameterized type List<Object>. As a consequence, you lose type safety if you use raw type like List, but not if you use a parameterized type like List<Object>.

To illustrate the point, consider the following method which takes a List<Object> and appends a new Object().

void appendNewObject(List<Object> list) {
   list.add(new Object());
}

Generics in Java are invariant. A List<String> is not a List<Object>, so the following would generate a compiler warning:

List<String> names = new ArrayList<String>();
appendNewObject(names); // compilation error!

If you had declared appendNewObject to take a raw type List as parameter, then this would compile, and you'd therefore lose the type safety that you get from generics.

See also


How's a raw type different from using <?> as a type parameter?

List<Object>, List<String>, etc are all List<?>, so it may be tempting to just say that they're just List instead. However, there is a major difference: since a List<E> defines only add(E), you can't add just any arbitrary object to a List<?>. On the other hand, since the raw type List does not have type safety, you can add just about anything to a List.

Consider the following variation of the previous snippet:

static void appendNewObject(List<?> list) {
    list.add(new Object()); // compilation error!
}
//...

List<String> names = new ArrayList<String>();
appendNewObject(names); // this part is fine!

The compiler did a wonderful job of protecting you from potentially violating the type invariance of the List<?>! If you had declared the parameter as the raw type List list, then the code would compile, and you'd violate the type invariant of List<String> names.


A raw type is the erasure of that type

Back to JLS 4.8:

It is possible to use as a type the erasure of a parameterized type or the erasure of an array type whose element type is a parameterized type. Such a type is called a raw type.

[...]

The superclasses (respectively, superinterfaces) of a raw type are the erasures of the superclasses (superinterfaces) of any of the parameterizations of the generic type.

The type of a constructor, instance method, or non-static field of a raw type C that is not inherited from its superclasses or superinterfaces is the raw type that corresponds to the erasure of its type in the generic declaration corresponding to C.

In simpler terms, when a raw type is used, the constructors, instance methods and non-static fields are also erased.

Take the following example:

class MyType<E> {
    List<String> getNames() {
        return Arrays.asList("John", "Mary");
    }

    public static void main(String[] args) {
        MyType rawType = new MyType();
        // unchecked warning!
        // required: List<String> found: List
        List<String> names = rawType.getNames();
        // compilation error!
        // incompatible types: Object cannot be converted to String
        for (String str : rawType.getNames())
            System.out.print(str);
    }
}

When we use the raw MyType, getNames becomes erased as well, so that it returns a raw List!

JLS 4.6 continues to explain the following:

Type erasure also maps the signature of a constructor or method to a signature that has no parameterized types or type variables. The erasure of a constructor or method signature s is a signature consisting of the same name as s and the erasures of all the formal parameter types given in s.

The return type of a method and the type parameters of a generic method or constructor also undergo erasure if the method or constructor's signature is erased.

The erasure of the signature of a generic method has no type parameters.

The following bug report contains some thoughts from Maurizio Cimadamore, a compiler dev, and Alex Buckley, one of the authors of the JLS, on why this sort of behavior ought to occur: https://bugs.openjdk.java.net/browse/JDK-6400189. (In short, it makes the specification simpler.)


If it's unsafe, why is it allowed to use a raw type?

Here's another quote from JLS 4.8:

The use of raw types is allowed only as a concession to compatibility of legacy code. The use of raw types in code written after the introduction of genericity into the Java programming language is strongly discouraged. It is possible that future versions of the Java programming language will disallow the use of raw types.

Effective Java 2nd Edition also has this to add:

Given that you shouldn't use raw types, why did the language designers allow them? To provide compatibility.

The Java platform was about to enter its second decade when generics were introduced, and there was an enormous amount of Java code in existence that did not use generics. It was deemed critical that all this code remains legal and interoperable with new code that does use generics. It had to be legal to pass instances of parameterized types to methods that were designed for use with ordinary types, and vice versa. This requirement, known as migration compatibility, drove the decision to support raw types.

In summary, raw types should NEVER be used in new code. You should always use parameterized types.


Are there no exceptions?

Unfortunately, because Java generics are non-reified, there are two exceptions where raw types must be used in new code:

  • Class literals, e.g. List.class, not List<String>.class
  • instanceof operand, e.g. o instanceof Set, not o instanceof Set<String>

See also

How to revert to origin's master branch's version of file

Assuming you did not commit the file, or add it to the index, then:

git checkout -- filename

Assuming you added it to the index, but did not commit it, then:

git reset HEAD filename
git checkout -- filename

Assuming you did commit it, then:

git checkout origin/master filename

Assuming you want to blow away all commits from your branch (VERY DESTRUCTIVE):

git reset --hard origin/master

No connection could be made because the target machine actively refused it (PHP / WAMP)

Please check your hosts file in etc folder and add below comments then run wamp server.

127.0.0.1 localhost

Path : C:\Windows\System32\drivers\etc

Tick symbol in HTML/XHTML

I normally use the fontawesome font(http://fontawesome.io/icon/check/), you can use it in html files:

 <i class="fa fa-check"></i>

or in css:

content: "\f00c";
font-family: FontAwesome;

Get webpage contents with Python?

Because you're using Python 3.1, you need to use the new Python 3.1 APIs.

Try:

urllib.request.urlopen('http://www.python.org/')

Alternately, it looks like you're working from Python 2 examples. Write it in Python 2, then use the 2to3 tool to convert it. On Windows, 2to3.py is in \python31\tools\scripts. Can someone else point out where to find 2to3.py on other platforms?

Edit

These days, I write Python 2 and 3 compatible code by using six.

from six.moves import urllib
urllib.request.urlopen('http://www.python.org')

Assuming you have six installed, that runs on both Python 2 and Python 3.

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

The value you have passed as the file descriptor is not valid. It is either negative or does not represent a currently open file or socket.

So you have either closed the socket before calling write() or you have corrupted the value of 'sockfd' somewhere in your code.

It would be useful to trace all calls to close(), and the value of 'sockfd' prior to the write() calls.

Your technique of only printing error messages in debug mode seems to me complete madness, and in any case calling another function between a system call and perror() is invalid, as it may disturb the value of errno. Indeed it may have done so in this case, and the real underlying error may be different.

Which variable size to use (db, dw, dd) with x86 assembly?

The full list is:

DB, DW, DD, DQ, DT, DDQ, and DO (used to declare initialized data in the output file.)

See: http://www.tortall.net/projects/yasm/manual/html/nasm-pseudop.html

They can be invoked in a wide range of ways: (Note: for Visual-Studio - use "h" instead of "0x" syntax - eg: not 0x55 but 55h instead):

    db      0x55                ; just the byte 0x55
    db      0x55,0x56,0x57      ; three bytes in succession
    db      'a',0x55            ; character constants are OK
    db      'hello',13,10,'$'   ; so are string constants
    dw      0x1234              ; 0x34 0x12
    dw      'A'                 ; 0x41 0x00 (it's just a number)
    dw      'AB'                ; 0x41 0x42 (character constant)
    dw      'ABC'               ; 0x41 0x42 0x43 0x00 (string)
    dd      0x12345678          ; 0x78 0x56 0x34 0x12
    dq      0x1122334455667788  ; 0x88 0x77 0x66 0x55 0x44 0x33 0x22 0x11
    ddq     0x112233445566778899aabbccddeeff00
    ; 0x00 0xff 0xee 0xdd 0xcc 0xbb 0xaa 0x99
    ; 0x88 0x77 0x66 0x55 0x44 0x33 0x22 0x11
    do      0x112233445566778899aabbccddeeff00 ; same as previous
    dd      1.234567e20         ; floating-point constant
    dq      1.234567e20         ; double-precision float
    dt      1.234567e20         ; extended-precision float

DT does not accept numeric constants as operands, and DDQ does not accept float constants as operands. Any size larger than DD does not accept strings as operands.

Why do I get an error instantiating an interface?

It is what it says, you just cannot instantiate an abstract class. You need to implement it first, then instantiate that class.

IUser user = new User();

How to get enum value by string or int

No, you don't want a generic method. This is much easier:

MyEnum myEnum = (MyEnum)myInt;

MyEnum myEnum = (MyEnum)Enum.Parse(typeof(MyEnum), myString);

I think it will also be faster.

Cross field validation with Hibernate Validator (JSR 303)

I'm surprised this isn't available out of the box. Anyway, here is a possible solution.

I've created a class level validator, not the field level as described in the original question.

Here is the annotation code:

package com.moa.podium.util.constraints;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.*;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;

@Target({TYPE, ANNOTATION_TYPE})
@Retention(RUNTIME)
@Constraint(validatedBy = MatchesValidator.class)
@Documented
public @interface Matches {

  String message() default "{com.moa.podium.util.constraints.matches}";

  Class<?>[] groups() default {};

  Class<? extends Payload>[] payload() default {};

  String field();

  String verifyField();
}

And the validator itself:

package com.moa.podium.util.constraints;

import org.mvel2.MVEL;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class MatchesValidator implements ConstraintValidator<Matches, Object> {

  private String field;
  private String verifyField;


  public void initialize(Matches constraintAnnotation) {
    this.field = constraintAnnotation.field();
    this.verifyField = constraintAnnotation.verifyField();
  }

  public boolean isValid(Object value, ConstraintValidatorContext context) {
    Object fieldObj = MVEL.getProperty(field, value);
    Object verifyFieldObj = MVEL.getProperty(verifyField, value);

    boolean neitherSet = (fieldObj == null) && (verifyFieldObj == null);

    if (neitherSet) {
      return true;
    }

    boolean matches = (fieldObj != null) && fieldObj.equals(verifyFieldObj);

    if (!matches) {
      context.disableDefaultConstraintViolation();
      context.buildConstraintViolationWithTemplate("message")
          .addNode(verifyField)
          .addConstraintViolation();
    }

    return matches;
  }
}

Note that I've used MVEL to inspect the properties of the object being validated. This could be replaced with the standard reflection APIs or if it is a specific class you are validating, the accessor methods themselves.

The @Matches annotation can then be used used on a bean as follows:

@Matches(field="pass", verifyField="passRepeat")
public class AccountCreateForm {

  @Size(min=6, max=50)
  private String pass;
  private String passRepeat;

  ...
}

As a disclaimer, I wrote this in the last 5 minutes, so I probably haven't ironed out all the bugs yet. I'll update the answer if anything goes wrong.

Chart creating dynamically. in .net, c#

Yep.

// FakeChart.cs
// ------------------------------------------------------------------
//
// A Winforms app that produces a contrived chart using
// DataVisualization (MSChart).  Requires .net 4.0.
//
// Author: Dino
//
// ------------------------------------------------------------------
//
// compile: \net4.0\csc.exe /t:winexe /debug+ /R:\net4.0\System.Windows.Forms.DataVisualization.dll FakeChart.cs
//

using System;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;


namespace Dino.Tools.WebMonitor
{
    public class FakeChartForm1 : Form
    {
        private System.ComponentModel.IContainer components = null;
        System.Windows.Forms.DataVisualization.Charting.Chart chart1;

        public FakeChartForm1 ()
        {
            InitializeComponent();
        }

        private double f(int i)
        {
            var f1 = 59894 - (8128 * i) + (262 * i * i) - (1.6 * i * i * i);
            return f1;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            chart1.Series.Clear();
            var series1 = new System.Windows.Forms.DataVisualization.Charting.Series
            {
                Name = "Series1",
                Color = System.Drawing.Color.Green,
                IsVisibleInLegend = false,
                IsXValueIndexed = true,
                ChartType = SeriesChartType.Line
            };

            this.chart1.Series.Add(series1);

            for (int i=0; i < 100; i++)
            {
                series1.Points.AddXY(i, f(i));
            }
            chart1.Invalidate();
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            System.Windows.Forms.DataVisualization.Charting.ChartArea chartArea1 = new System.Windows.Forms.DataVisualization.Charting.ChartArea();
            System.Windows.Forms.DataVisualization.Charting.Legend legend1 = new System.Windows.Forms.DataVisualization.Charting.Legend();
            this.chart1 = new System.Windows.Forms.DataVisualization.Charting.Chart();
            ((System.ComponentModel.ISupportInitialize)(this.chart1)).BeginInit();
            this.SuspendLayout();
            //
            // chart1
            //
            chartArea1.Name = "ChartArea1";
            this.chart1.ChartAreas.Add(chartArea1);
            this.chart1.Dock = System.Windows.Forms.DockStyle.Fill;
            legend1.Name = "Legend1";
            this.chart1.Legends.Add(legend1);
            this.chart1.Location = new System.Drawing.Point(0, 50);
            this.chart1.Name = "chart1";
            // this.chart1.Size = new System.Drawing.Size(284, 212);
            this.chart1.TabIndex = 0;
            this.chart1.Text = "chart1";
            //
            // Form1
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(284, 262);
            this.Controls.Add(this.chart1);
            this.Name = "Form1";
            this.Text = "FakeChart";
            this.Load += new System.EventHandler(this.Form1_Load);
            ((System.ComponentModel.ISupportInitialize)(this.chart1)).EndInit();
            this.ResumeLayout(false);
        }

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new FakeChartForm1());
        }
    }
}

UI:

enter image description here

What is meant with "const" at end of function declaration?

A "const function", denoted with the keyword const after a function declaration, makes it a compiler error for this class function to change a member variable of the class. However, reading of a class variables is okay inside of the function, but writing inside of this function will generate a compiler error.

Another way of thinking about such "const function" is by viewing a class function as a normal function taking an implicit this pointer. So a method int Foo::Bar(int random_arg) (without the const at the end) results in a function like int Foo_Bar(Foo* this, int random_arg), and a call such as Foo f; f.Bar(4) will internally correspond to something like Foo f; Foo_Bar(&f, 4). Now adding the const at the end (int Foo::Bar(int random_arg) const) can then be understood as a declaration with a const this pointer: int Foo_Bar(const Foo* this, int random_arg). Since the type of this in such case is const, no modifications of member variables are possible.

It is possible to loosen the "const function" restriction of not allowing the function to write to any variable of a class. To allow some of the variables to be writable even when the function is marked as a "const function", these class variables are marked with the keyword mutable. Thus, if a class variable is marked as mutable, and a "const function" writes to this variable then the code will compile cleanly and the variable is possible to change. (C++11)

As usual when dealing with the const keyword, changing the location of the const key word in a C++ statement has entirely different meanings. The above usage of const only applies when adding const to the end of the function declaration after the parenthesis.

const is a highly overused qualifier in C++: the syntax and ordering is often not straightforward in combination with pointers. Some readings about const correctness and the const keyword:

Const correctness

The C++ 'const' Declaration: Why & How

How to make a simple rounded button in Storyboard?

You can connect IBOutlet of yur button from storyboard.

Then you can set corner radius of your button to make it's corner round.

for example, your outlet is myButton then,

Obj - C

 self.myButton.layer.cornerRadius = 5.0 ;

Swift

  myButton.layer.cornerRadius = 5.0

If you want exact round button then your button's width and height must be equal and cornerRadius must be equal to height or width / 2 (half of the width or height).

jQuery.animate() with css class only, without explicit styles

Check out James Padolsey's animateToSelector

Intro: This jQuery plugin will allow you to animate any element to styles specified in your stylesheet. All you have to do is pass a selector and the plugin will look for that selector in your StyleSheet and will then apply it as an animation.

Make HTML5 video poster be same size as video itself

height:500px;
min-width:100%;
-webkit-background-size: 100% 100%;
-moz-background-size: 100% 100%;
-o-background-size: 100% 100%;
background-size:100% 100%;
object-fit:cover;

-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size:cover;

How do you query for "is not null" in Mongo?

Thanks for providing a solution, I noticed in MQL, sometimes $ne:null doesn't work instead we need to use syntax $ne:"" i.e. in the context of above example we would need to use db.mycollection.find({"IMAGE URL":{"$ne":""}}) - Not sure why this occurs, I have posted this question in the MongoDB forum.

following is the snapshot showing example:

enter image description here

Highcharts - how to have a chart with dynamic height?

What if you hooked the window resize event:

$(window).resize(function() 
{    
    chart.setSize(
       $(document).width(), 
       $(document).height()/2,
       false
    );   
});

See example fiddle here.

Highcharts API Reference : setSize().

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

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

How to check if a process is running via a batch script

I'm assuming windows here. So, you'll need to use WMI to get that information. Check out The Scripting Guy's archives for a lot of examples on how to use WMI from a script.

reStructuredText tool support

Salvaging (and extending) the list from an old version of the Wikipedia page:

Documentation

Implementations

Although the reference implementation of reStructuredText is written in Python, there are reStructuredText parsers in other languages too.

Python - Docutils

The main distribution of reStructuredText is the Python Docutils package. It contains several conversion tools:

  • rst2html - from reStructuredText to HTML
  • rst2xml - from reStructuredText to XML
  • rst2latex - from reStructuredText to LaTeX
  • rst2odt - from reStructuredText to ODF Text (word processor) document.
  • rst2s5 - from reStructuredText to S5, a Simple Standards-based Slide Show System
  • rst2man - from reStructuredText to Man page

Haskell - Pandoc

Pandoc is a Haskell library for converting from one markup format to another, and a command-line tool that uses this library. It can read Markdown and (subsets of) reStructuredText, HTML, and LaTeX, and it can write Markdown, reStructuredText, HTML, LaTeX, ConTeXt, PDF, RTF, DocBook XML, OpenDocument XML, ODT, GNU Texinfo, MediaWiki markup, groff man pages, and S5 HTML slide shows.

There is an Pandoc online tool (POT) to try this library. Unfortunately, compared to the reStructuredText online renderer (ROR),

  • POT truncates input rather more shortly. The POT user must render input in chunks that could be rendered whole by the ROR.
  • POT output lacks the helpful error messages displayed by the ROR (and generated by docutils)

Java - JRst

JRst is a Java reStructuredText parser. It can currently output HTML, XHTML, DocBook xdoc and PDF, BUT seems to have serious problems: neither PDF or (X)HTML generation works using the current full download, result pages in (X)HTML are empty and PDF generation fails on IO problems with XSL files (not bundled??). Note that the original JRst has been removed from the website; a fork is found on GitHub.

Scala - Laika

Laika is a new library for transforming markup languages to other output formats. Currently it supports input from Markdown and reStructuredText and produce HTML output. The library is written in Scala but should be also usable from Java.

Perl

PHP

C#/.NET

Nim/C

The Nim compiler features the commands rst2htmland rst2tex which transform reStructuredText files to HTML and TeX files. The standard library provides the following modules (used by the compiler) to handle reStructuredText files programmatically:

  • rst - implements a reStructuredText parser
  • rstast - implements an AST for the reStructuredText parser
  • rstgen - implements a generator of HTML/Latex from reStructuredText

Other 3rd party converters

Most (but not all) of these tools are based on Docutils (see above) and provide conversion to or from formats that might not be supported by the main distribution.

From reStructuredText

  • restview - This pip-installable python package requires docutils, which does the actual rendering. restview's major ease-of-use feature is that, when you save changes to your document(s), it automagically re-renders and re-displays them. restview
    1. starts a small web server
    2. calls docutils to render your document(s) to HTML
    3. calls your device's browser to display the output HTML.
  • rst2pdf - from reStructuredText to PDF
  • rst2odp - from reStructuredText to ODF Presentation
  • rst2beamer - from reStructuredText to LaTeX beamer Presentation class
  • Wikir - from reStructuredText to a Google (and possibly other) Wiki formats
  • rst2qhc - Convert a collection of reStructuredText files into a Qt (toolkit) Help file and (optional) a Qt Help Project file

To reStructuredText

  • xml2rst is an XSLT script to convert Docutils internal XML representation (back) to reStructuredText
  • Pandoc (see above) can also convert from Markdown, HTML and LaTeX to reStructuredText
  • db2rst is a simple and limited DocBook to reStructuredText translator
  • pod2rst - convert .pod files to reStructuredText files

Extensions

Some projects use reStructuredText as a baseline to build on, or provide extra functionality extending the utility of the reStructuredText tools.

Sphinx

The Sphinx documentation generator translates a set of reStructuredText source files into various output formats, automatically producing cross-references, indices etc.

rest2web

rest2web is a simple tool that lets you build your website from a single template (or as many as you want), and keep the contents in reStructuredText.

Pygments

Pygments is a generic syntax highlighter for general use in all kinds of software such as forum systems, Wikis or other applications that need to prettify source code. See Using Pygments in reStructuredText documents.

Free Editors

While any plain text editor is suitable to write reStructuredText documents, some editors have better support than others.

Emacs

The Emacs support via rst-mode comes as part of the Docutils package under /docutils/tools/editors/emacs/rst.el

Vim

The vim-common package for that comes with most GNU/Linux distributions has reStructuredText syntax highlight and indentation support of reStructuredText out of the box:

Jed

There is a rst mode for the Jed programmers editor.

gedit

gedit, the official text editor of the GNOME desktop environment. There is a gedit reStructuredText plugin.

Geany

Geany, a small and lightweight Integrated Development Environment include support for reStructuredText from version 0.12 (October 10, 2007).

Leo

Leo, an outlining editor for programmers, supports reStructuredText via rst-plugin or via "@auto-rst" nodes (it's not well-documented, but @auto-rst nodes allow editing rst files directly, parsing the structure into the Leo outline).

It also provides a way to preview the resulting HTML, in a "viewrendered" pane.

FTE

The FTE Folding Text Editor - a free (licensed under the GNU GPL) text editor for developers. FTE has a mode for reStructuredText support. It provides color highlighting of basic RSTX elements and special menu that provide easy way to insert most popular RSTX elements to a document.

PyK

PyK is a successor of PyEdit and reStInPeace, written in Python with the help of the Qt4 toolkit.

Eclipse

The Eclipse IDE with the ReST Editor plug-in provides support for editing reStructuredText files.

NoTex

NoTex is a browser based (general purpose) text editor, with integrated project management and syntax highlighting. Plus it enables to write books, reports, articles etc. using rST and convert them to LaTex, PDF or HTML. The PDF files are of high publication quality and are produced via Sphinx with the Texlive LaTex suite.

Notepad++

Notepad++ is a general purpose text editor for Windows. It has syntax highlighting for many languages built-in and support for reStructuredText via a user defined language for reStructuredText.

Visual Studio Code

Visual Studio Code is a general purpose text editor for Windows/macOS/Linux. It has syntax highlighting for many languages built-in and supports reStructuredText via an extension from LeXtudio.

Dedicated reStructuredText Editors

Proprietary editors

Sublime Text

Sublime Text is a completely customizable and extensible source code editor available for Windows, OS X, and Linux. Registration is required for long-term use, but all functions are available in the unregistered version, with occasional reminders to purchase a license. Versions 2 and 3 (currently in beta) support reStructuredText syntax highlighting by default, and several plugins are available through the package manager Package Control to provide snippets and code completion, additional syntax highlighting, conversion to/from RST and other formats, and HTML preview in the browser.

BBEdit / TextWrangler

BBEdit (and its free variant TextWrangler) for Mac can syntax-highlight reStructuredText using this codeless language module.

TextMate

TextMate, a proprietary general-purpose GUI text editor for Mac OS X, has a bundle for reStructuredText.

Intype

Intype is a proprietary text editor for Windows, that support reStructuredText out of the box.

E Text Editor

E is a proprietary Text Editor licensed under the "Open Company License". It supports TextMate's bundles, so it should support reStructuredText the same way TextMate does.

PyCharm

PyCharm (and other IntelliJ platform IDEs?) has ReST/Sphinx support (syntax highlighting, autocomplete and preview).instant preview)

Wiki

here are some Wiki programs that support the reStructuredText markup as the native markup syntax, or as an add-on:

MediaWiki

MediaWiki reStructuredText extension allows for reStructuredText markup in MediaWiki surrounded by <rst> and </rst>.

MoinMoin

MoinMoin is an advanced, easy to use and extensible WikiEngine with a large community of users. Said in a few words, it is about collaboration on easily editable web pages.

There is a reStructuredText Parser for MoinMoin.

Trac

Trac is an enhanced wiki and issue tracking system for software development projects. There is a reStructuredText Support in Trac.

This Wiki

This Wiki is a Webware for Python Wiki written by Ian Bicking. This wiki uses ReStructuredText for its markup.

rstiki

rstiki is a minimalist single-file personal wiki using reStructuredText syntax (via docutils) inspired by pwyky. It does not support authorship indication, versioning, hierarchy, chrome/framing/templating or styling. It leverages docutils/reStructuredText as the wiki syntax. As such, it's under 200 lines of code, and in a single file. You put it in a directory and it runs.

ikiwiki

Ikiwiki is a wiki compiler. It converts wiki pages into HTML pages suitable for publishing on a website. Ikiwiki stores pages and history in a revision control system such as Subversion or Git. There are many other features, including support for blogging, as well as a large array of plugins. It's reStructuredText plugin, however is somewhat limited and is not recommended as its' main markup language at this time.

Web Services

Sandbox

An Online reStructuredText editor can be used to play with the markup and see the results immediately.

Blogging frameworks

WordPress

WordPreSt reStructuredText plugin for WordPress. (PHP)

Zine

reStructuredText parser plugin for Zine (will become obsolete in version 0.2 when Zine is scheduled to get a native reStructuredText support). Zine is discontinued. (Python)

pelican

Pelican is a static blog generator that supports writing articles in ReST. (Python)

hyde

Hyde is a static website generator that supports ReST. (Python)

Acrylamid

Acrylamid is a static blog generator that supports writing articles in ReST. (Python)

Nikola

Nikola is a Static Site and Blog Generator that supports ReST. (Python)

ipsum genera

Ipsum genera is a static blog generator written in Nim.

Yozuch

Yozuch is a static blog generator written in Python.

More

How to delete from a table where ID is in a list of IDs?

Your question almost spells the SQL for this:

DELETE FROM table WHERE id IN (1, 4, 6, 7)

Validate phone number using angular js

Use ng-pattern, in this example you can validate a simple patern with 10 numbers, when the patern is not matched ,the message is show and the button is disabled.

 <form  name="phoneNumber">

        <label for="numCell" class="text-strong">Phone number</label>

        <input id="numCell" type="text" name="inputCelular"  ng-model="phoneNumber" 
            class="form-control" required  ng-pattern="/^[0-9]{10,10}$/"></input>
        <div class="alert-warning" ng-show="phoneNumber.inputCelular.$error.pattern">
            <p> write a phone number</p>
        </div>

    <button id="button"  class="btn btn-success" click-once ng-disabled="!phoneNumber.$valid" ng-click="callDigitaliza()">Buscar</button>

Also you can use another complex patern like

^+?\d{1,3}?[- .]?(?(?:\d{2,3}))?[- .]?\d\d\d[- .]?\d\d\d\d$

, for more complex phone numbers

Truncating Text in PHP?

$mystring = "this is the text I would like to truncate";

// Pass your variable to the function
$mystring = truncate($mystring);

// Truncated tring printed out;
echo $mystring;

//truncate text function
public function truncate($text) {

    //specify number fo characters to shorten by
    $chars = 25;

    $text = $text." ";
    $text = substr($text,0,$chars);
    $text = substr($text,0,strrpos($text,' '));
    $text = $text."...";
    return $text;
}

How to install the Six module in Python2.7

You need to install this

https://pypi.python.org/pypi/six

If you still don't know what pip is , then please also google for pip install

Python has it's own package manager which is supposed to help you finding packages and their dependencies: http://www.pip-installer.org/en/latest/

Remove First and Last Character C++

My BASIC interpreter chops beginning and ending quotes with

str->pop_back();
str->erase(str->begin());

Of course, I always expect well-formed BASIC style strings, so I will abort with failed assert if not:

assert(str->front() == '"' && str->back() == '"');

Just my two cents.

AngularJS access scope from outside js function

we can call it after loaded

http://jsfiddle.net/gentletech/s3qtv/3/

<div id="wrap" ng-controller="Ctrl">
    {{message}}<br>
    {{info}}
    </div>
    <a  onClick="hi()">click me </a>

    function Ctrl($scope) {
        $scope.message = "hi robi";
        $scope.updateMessage = function(_s){
            $scope.message = _s;    
        };
    }

function hi(){
    var scope = angular.element(document.getElementById("wrap")).scope();
        scope.$apply(function() {
        scope.info = "nami";
        scope.updateMessage("i am new fans like nami");
    });
}

How to make an Android device vibrate? with different frequency?

Above answers are perfect. However I wanted to vibrate my app exactly twice on button click and this small information is missing here, hence posting for future readers like me. :)

We have to follow as mentioned above and the only change will be in the vibrate pattern as below,

long[] pattern = {0, 100, 1000, 300};
v.vibrate(pattern, -1); //-1 is important

This will exactly vibrate twice. As we already know

  1. 0 is for delay
  2. 100 says vibrate for 100ms for the first time
  3. next comes delay of 1000ms
  4. and post that vibrate again for 300ms

One can go on and on mentioning delay and vibration alternatively (e.g. 0, 100, 1000, 300, 1000, 300 for 3 vibrations and so on..) but remember @Dave's word use it responsibly. :)

Also note here that the repeat parameter is set to -1 which means the vibration will happen exactly as mentioned in the pattern. :)

Finding the indices of matching elements in list in Python

if you're doing a lot of this kind of thing you should consider using numpy.

In [56]: import random, numpy

In [57]: lst = numpy.array([random.uniform(0, 5) for _ in range(1000)]) # example list

In [58]: a, b = 1, 3

In [59]: numpy.flatnonzero((lst > a) & (lst < b))[:10]
Out[59]: array([ 0, 12, 13, 15, 18, 19, 23, 24, 26, 29])

In response to Seanny123's question, I used this timing code:

import numpy, timeit, random

a, b = 1, 3

lst = numpy.array([random.uniform(0, 5) for _ in range(1000)])

def numpy_way():
    numpy.flatnonzero((lst > 1) & (lst < 3))[:10]

def list_comprehension():
    [e for e in lst if 1 < e < 3][:10]

print timeit.timeit(numpy_way)
print timeit.timeit(list_comprehension)

The numpy version is over 60 times faster.

How to make rounded percentages add up to 100%

Since none of the answers here seem to solve it properly, here's my semi-obfuscated version using underscorejs:

function foo(l, target) {
    var off = target - _.reduce(l, function(acc, x) { return acc + Math.round(x) }, 0);
    return _.chain(l).
            sortBy(function(x) { return Math.round(x) - x }).
            map(function(x, i) { return Math.round(x) + (off > i) - (i >= (l.length + off)) }).
            value();
}

foo([13.626332, 47.989636, 9.596008, 28.788024], 100) // => [48, 29, 14, 9]
foo([16.666, 16.666, 16.666, 16.666, 16.666, 16.666], 100) // => [17, 17, 17, 17, 16, 16]
foo([33.333, 33.333, 33.333], 100) // => [34, 33, 33]
foo([33.3, 33.3, 33.3, 0.1], 100) // => [34, 33, 33, 0]

Adding horizontal spacing between divs in Bootstrap 3

Do you mean something like this? JSFiddle

Attribute used:

margin-left: 50px;

Find out how much memory is being used by an object in Python

There's no easy way to find out the memory size of a python object. One of the problems you may find is that Python objects - like lists and dicts - may have references to other python objects (in this case, what would your size be? The size containing the size of each object or not?). There are some pointers overhead and internal structures related to object types and garbage collection. Finally, some python objects have non-obvious behaviors. For instance, lists reserve space for more objects than they have, most of the time; dicts are even more complicated since they can operate in different ways (they have a different implementation for small number of keys and sometimes they over allocate entries).

There is a big chunk of code (and an updated big chunk of code) out there to try to best approximate the size of a python object in memory.

You may also want to check some old description about PyObject (the internal C struct that represents virtually all python objects).

How to set default value to the input[type="date"]

<input type="date" id="myDate" />

Then in js :

_today: function () {
  var myDate = document.querySelector(myDate);
  var today = new Date();
  myDate.value = today.toISOString().substr(0, 10);
},

Is there a good JSP editor for Eclipse?

You could check out JBoss Tools plugin.

Replace Multiple String Elements in C#

I'm doing something similar, but in my case I'm doing serialization/De-serialization so I need to be able to go both directions. I find using a string[][] works nearly identically to the dictionary, including initialization, but you can go the other direction too, returning the substitutes to their original values, something that the dictionary really isn't set up to do.

Edit: You can use Dictionary<Key,List<Values>> in order to obtain same result as string[][]

Passing a varchar full of comma delimited values to a SQL Server IN function

The simplest way i found was to use FIND_IN_SET

FIND_IN_SET(column_name, values)

values=(1,2,3)

SELECT name WHERE FIND_IN_SET(id, values)

How to create a function in a cshtml template?

If your method doesn't have to return html and has to do something else then you can use a lambda instead of helper method in Razor

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

    Func<int,int,int> Sum = (a, b) => a + b;
}

<h2>Index</h2>

@Sum(3,4)

Resizing image in Java

If you have an java.awt.Image, rezising it doesn't require any additional libraries. Just do:

Image newImage = yourImage.getScaledInstance(newWidth, newHeight, Image.SCALE_DEFAULT);

Ovbiously, replace newWidth and newHeight with the dimensions of the specified image.
Notice the last parameter: it tells to the runtime the algorithm you want to use for resizing.

There are algorithms that produce a very precise result, however these take a large time to complete.
You can use any of the following algorithms:

See the Javadoc for more info.

Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)

I faced the similar issue on new server that I built through automated scripts via vcenter api. Looks like the "Remote Procedure Call (RPC)" service may not be running on the remote machine. you need to wait for the service to come up to use the Get-WmiObject command. Hence I simply put the script into sleep for sometime and it worked.

Where does System.Diagnostics.Debug.Write output appear?

The solution for my case is:

  1. Right click the output window;
  2. Check the 'Program Output'

build maven project with propriatery libraries included

A good way to achieve this is to have a Maven mirror server such as Sonatype Nexus. It is free and very easy to setup (Java web app). With Nexus one can have private (team, corporate etc) repository with a capability of deploying third party and internal apps into it, while also registering other Maven repositories as part of the same server. This way the local Maven settings would reference only the one private Nexus server and all the dependencies will be resolved using it.

How to make PDF file downloadable in HTML link?

Don't loop through every file line. Use readfile instead, its faster. This is off the php site: http://php.net/manual/en/function.readfile.php

$file = $_GET["file"];
if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header("Content-Type: application/force-download");
    header('Content-Disposition: attachment; filename=' . urlencode(basename($file)));
    // header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    exit;
}

Make sure to sanitize your get variable as someone could download some php files...

How to update ruby on linux (ubuntu)?

On Ubuntu 12.04 (Precise Pangolin), I got this working with the following command:

sudo apt-get install ruby1.9.1
sudo apt-get install ruby1.9.3

JavaScript checking for null vs. undefined and difference between == and ===

How do I check a variable if it's null or undefined...

Is the variable null:

if (a === null)
// or
if (a == null) // but see note below

...but note the latter will also be true if a is undefined.

Is it undefined:

if (typeof a === "undefined")
// or
if (a === undefined)
// or
if (a == undefined) // but see note below

...but again, note that the last one is vague; it will also be true if a is null.

Now, despite the above, the usual way to check for those is to use the fact that they're falsey:

if (!a) {
    // `a` is falsey, which includes `undefined` and `null`
    // (and `""`, and `0`, and `NaN`, and [of course] `false`)
}

This is defined by ToBoolean in the spec.

...and what is the difference between the null and undefined?

They're both values usually used to indicate the absence of something. undefined is the more generic one, used as the default value of variables until they're assigned some other value, as the value of function arguments that weren't provided when the function was called, and as the value you get when you ask an object for a property it doesn't have. But it can also be explicitly used in all of those situations. (There's a difference between an object not having a property, and having the property with the value undefined; there's a difference between calling a function with the value undefined for an argument, and leaving that argument off entirely.)

null is slightly more specific than undefined: It's a blank object reference. JavaScript is loosely typed, of course, but not all of the things JavaScript interacts with are loosely typed. If an API like the DOM in browsers needs an object reference that's blank, we use null, not undefined. And similarly, the DOM's getElementById operation returns an object reference — either a valid one (if it found the DOM element), or null (if it didn't).

Interestingly (or not), they're their own types. Which is to say, null is the only value in the Null type, and undefined is the only value in the Undefined type.

What is the difference between "==" and "==="

The only difference between them is that == will do type coercion to try to get the values to match, and === won't. So for instance "1" == 1 is true, because "1" coerces to 1. But "1" === 1 is false, because the types don't match. ("1" !== 1 is true.) The first (real) step of === is "Are the types of the operands the same?" and if the answer is "no", the result is false. If the types are the same, it does exactly what == does.

Type coercion uses quite complex rules and can have surprising results (for instance, "" == 0 is true).

More in the spec:

CSS to line break before/after a particular `inline-block` item

I know you didn't want to use floats and the question was just theory but in case anyone finds this useful, here's a solution using floats.

Add a class of left to your li elements that you want to float:

<li class="left"><img src="http://phrogz.net/tmp/alphaball.png">Smells Good</li>

and amend your CSS as follows:

li { text-align:center; float: left; clear: left; padding:0.1em 1em }
.left {float: left; clear: none;}

http://jsfiddle.net/chut319/xJ3pe/

You don't need to specify widths or inline-blocks and works as far back as IE6.

How to make an array of arrays in Java

try

String[][] arrays = new String[5][];

how to fix groovy.lang.MissingMethodException: No signature of method:

To help other bug-hunters. I had this error because the function didn't exist.

I had a spelling error.

A fatal error occurred while creating a TLS client credential. The internal error state is 10013

Basically we had to enable TLS 1.2 for .NET 4.x. Making this registry changed worked for me, and stopped the event log filling up with the Schannel error.

More information on the answer can be found here

Linked Info Summary

Enable TLS 1.2 at the system (SCHANNEL) level:

Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2]
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client]
"DisabledByDefault"=dword:00000000
"Enabled"=dword:00000001
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server]
"DisabledByDefault"=dword:00000000
"Enabled"=dword:00000001

(equivalent keys are probably also available for other TLS versions)

Tell .NET Framework to use the system TLS versions:

Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319]
"SystemDefaultTlsVersions"=dword:00000001
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319]
"SystemDefaultTlsVersions"=dword:00000001

This may not be desirable for edge cases where .NET Framework 4.x applications need to have different protocols enabled and disabled than the OS does.

Returning anonymous type in C#

C# compiler is a two phase compiler. In the first phase it just checks namespaces, class hierarchies, Method signatures etc. Method bodies are compiled only during the second phase.

Anonymous types are not determined until the method body is compiled.

So the compiler has no way of determining the return type of the method during the first phase.

That is the reason why anonymous types can not be used as return type.

As others have suggested if you are using .net 4.0 or grater, you can use Dynamic.

If I were you I would probably create a type and return that type from the method. That way it is easy for the future programmers who maintains your code and more readable.

How to get the current logged in user Id in ASP.NET Core

you have to import Microsoft.AspNetCore.Identity & System.Security.Claims

// to get current user ID
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);

// to get current user info
var user = await _userManager.FindByIdAsync(userId);

Bad Request - Invalid Hostname IIS7

For Visual Studio 2017 and Visual Studio 2015, IIS Express settings is stored in the hidden .vs directory and the path is something like this .vs\config\applicationhost.config, add binding like below will work

<bindings>
    <binding protocol="http" bindingInformation="*:8802:localhost" />
    <binding protocol="http" bindingInformation="*:8802:127.0.0.1" />
</bindings>

Syntax: https://docs.microsoft.com/en-us/dotnet/api/microsoft.web.administration.binding.bindinginformation?view=iis-dotnet

Get the current fragment object

This will give you the current fragment class name -->

String fr_name = getSupportFragmentManager().findFragmentById(R.id.fragment_container).getClass().getSimpleName();

How to declare string constants in JavaScript?

You can use freeze method of Object to create a constant. For example:

var configObj ={timeOut :36000};
Object.freeze(configObj);

In this way you can not alter the configObj.

Adding local .aar files to Gradle build using "flatDirs" is not working

Building upon Josiah's answer, here's how I got it to work.

Following his instructions (under edit) (File -> New-> New Module -> Import .JAR/.AAR) and import your .AAR.

Then in your project build.gradle (not the top level one, the one under 'app') add the following (in the dependencies section):

dependencies {
    compile project(':Name-Of-Your-Project')
}

Note Name-Of-Your-Project should match the name of the folder that was added after you imported the AAR file (at the same level as app/.idea under the top most level folder). Or to put it another way...

MyApplication
  .idea
  app
  build.gradle (here's where to add compile project(':ProjectName') to dependency section)
  ProjectName (added automatically after importing, matching the name of your aar file)
  build
  gradle
  etc

This worked for me running Android Studio 0.8.0. Don't forget to synchronize gradle (using toolbar button or in File->Synchronize) after you do this.

(Thanks to Josiah for getting me going in the right direction)

(Note: prior to this I tried adding it to the libs folder, trying to manipulate the top level build.gradle and the app level build.gradle, but none of that worked for my aars files--jar's will work fine, but not the aar files)

AssertContains on strings in jUnit

Use the new assertThat syntax together with Hamcrest.

It is available starting with JUnit 4.4.

ALTER TABLE on dependent column

I believe that you will have to drop the foreign key constraints first. Then update all of the appropriate tables and remap them as they were.

ALTER TABLE [dbo.Details_tbl] DROP CONSTRAINT [FK_Details_tbl_User_tbl];
-- Perform more appropriate alters
ALTER TABLE [dbo.Details_tbl] ADD FOREIGN KEY (FK_Details_tbl_User_tbl) 
    REFERENCES User_tbl(appId);
-- Perform all appropriate alters to bring the key constraints back

However, unless memory is a really big issue, I would keep the identity as an INT. Unless you are 100% positive that your keys will never grow past the TINYINT restraints. Just a word of caution :)

How can I get the last day of the month in C#?

Another way of doing it:

DateTime today = DateTime.Today;
DateTime endOfMonth = new DateTime(today.Year, 
                                   today.Month, 
                                   DateTime.DaysInMonth(today.Year, 
                                                        today.Month));

CSS Calc Viewport Units Workaround?

Before I answer this, I'd like to point out that Chrome and IE 10+ actually supports calc with viewport units.

FIDDLE (In IE10+)

Solution (for other browsers): box-sizing

1) Start of by setting your height as 100vh.

2) With box-sizing set to border-box - add a padding-top of 75vw. This means that the padding will be part f the inner height.

3) Just offset the extra padding-top with a negative margin-top

FIDDLE

div
{
    /*height: calc(100vh - 75vw);*/
    height: 100vh;
    margin-top: -75vw;
    padding-top: 75vw;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    background: pink;
}

Is Android using NTP to sync time?

Not an exact answer to your question, but a bit of information: if your device does use NTP for time (eg. if it is a tablet with no 3G or GPS capabilities), the server can be configured in /system/etc/gps.conf - obviously this file can only be edited with root access, but is viewable on non-rooted devices.

git - pulling from specific branch

It's often clearer to separate the two actions git pull does. The first thing it does is update the local tracking branc that corresponds to the remote branch. This can be done with git fetch. The second is that it then merges in changes, which can of course be done with git merge, though other options such as git rebase are occasionally useful.

adding child nodes in treeview

You may do as follows to Populate treeView with parent and child node. And also with display and value member of parent and child nodes:

   arrayRoot = taskData.GetRocordForRoot();  // iterate through database table
    for (int j = 0; j <arrayRoot.length; j++) { 
                TreeNode root = new TreeNode();  // Creating new root node
                root.Text = "displayString";
                root.Tag = "valueString";
                treeView1.Nodes.Add(root); //Adding the root node

             arrayChild = taskData.GetRocordForChild();// iterate through database table
                for (int i = 0; i < arrayChild.length; i++) {
                    TreeNode child = new TreeNode(); // creating child node
                    child.Text = "displayString"
                    child.Tag = "valueString";
                    root.Nodes.Add(child); // adding child node
                }

            }

How to find if a given key exists in a C++ std::map

Use map::find

if ( m.find("f") == m.end() ) {
  // not found
} else {
  // found
}

Imply bit with constant 1 or 0 in SQL Server

No, but you could cast the whole expression rather than the sub-components of that expression. Actually, that probably makes it less readable in this case.

Parse error: syntax error, unexpected T_ECHO in

Missing ; after var_dump($row)

Does the 'mutable' keyword have any purpose other than allowing the variable to be modified by a const function?

The mutable keyword is very useful when creating stubs for class test purposes. You can stub a const function and still be able to increase (mutable) counters or whatever test functionality you have added to your stub. This keeps the interface of the stubbed class intact.

Check if a number is odd or even in python

One of the simplest ways is to use de modulus operator %. If n % 2 == 0, then your number is even.

Hope it helps,

How to uninstall a windows service and delete its files without rebooting

Should it be necessary to manually remove a service:

  1. Run Regedit or regedt32.
  2. Find the registry key entry for your service under the following key: HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/Services
  3. Delete the Registry Key

You will have to reboot before the list gets updated in services

What does the function then() mean in JavaScript?

Here is a small JS_Fiddle.

then is a method callback stack which is available after a promise is resolved it is part of library like jQuery but now it is available in native JavaScript and below is the detail explanation how it works

You can do a Promise in native JavaScript : just like there are promises in jQuery, Every promise can be stacked and then can be called with Resolve and Reject callbacks, This is how you can chain asynchronous calls.

I forked and Edited from MSDN Docs on Battery charging status..

What this does is try to find out if user laptop or device is charging battery. then is called and you can do your work post success.

navigator
    .getBattery()
    .then(function(battery) {
       var charging = battery.charging;
       alert(charging);
    })
    .then(function(){alert("YeoMan : SINGH is King !!");});

Another es6 Example

function fetchAsync (url, timeout, onData, onError) {
    …
}
let fetchPromised = (url, timeout) => {
    return new Promise((resolve, reject) => {
        fetchAsync(url, timeout, resolve, reject)
    })
}
Promise.all([
    fetchPromised("http://backend/foo.txt", 500),
    fetchPromised("http://backend/bar.txt", 500),
    fetchPromised("http://backend/baz.txt", 500)
]).then((data) => {
    let [ foo, bar, baz ] = data
    console.log(`success: foo=${foo} bar=${bar} baz=${baz}`)
}, (err) => {
    console.log(`error: ${err}`)
})

Definition :: then is a method used to solve Asynchronous callbacks

this is introduced in ES6

Please find the proper documentation here Es6 Promises

How can I know if Object is String type object?

 object instanceof Type

is true if the object is a Type or a subclass of Type

 object.getClass().equals(Type.class) 

is true only if the object is a Type

MVC Redirect to View from jQuery with parameters

This would also work I believe:

$('#results').on('click', '.item', function () {
            var NestId = $(this).data('id');
            var url = '@Html.Raw(Url.Action("Artists", new { NestId = @NestId }))';
            window.location.href = url; 
        })

What is the difference between HTTP and REST?

HTTP is a contract, a communication protocol and REST is a concept, an architectural style which may use HTTP, FTP or other communication protocols but is widely used with HTTP.

REST implies a series of constraints about how Server and Client should interact. HTTP is a communication protocol with a given mechanism for server-client data transfer, it's most commonly used in REST API just because REST was inspired by WWW (world wide web) which largely used HTTP before REST was defined, so it's easier to implement REST API style with HTTP.

There are three major constraints in REST (but there are more):

1. Interaction between server and client should be described via hypertext only.

2. Server and client should be loosely coupled and make no assumptions about each other. Client should only know resource entry point. Interaction data should be provided by the server in the response.

3. Server shouldn't store any information about request context. Requests must be independent and idempotent (means if same request is repeated infinitely, exactly same result is retrieved)

And HTTP is just a communication protocol (a tool) that can help to achieve this.

For more info check these links:

https://martinfowler.com/articles/richardsonMaturityModel.html http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven

len() of a numpy array in python

Easy. Use .shape.

>>> nparray.shape
(5, 6) #Returns a tuple of array dimensions.

Insert array into MySQL database with PHP

Maybe it will be to complex for this question but it surely do the job for you. I have created two classes to handle not only array insertion but also querying the database, updating and deleting files. "MySqliConnection" class is used to create only one instance of db connection (to prevent duplication of new objects).

    <?php
    /**
     *
     * MySQLi database connection: only one connection is allowed
     */
    class MySqliConnection{
        public static $_instance;
        public $_connection;

        public function __construct($host, $user, $password, $database){
            $this->_connection = new MySQLi($host, $user, $password, $database);
            if (isset($mysqli->connect_error)) {
                echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
                echo $mysqli->host_info . "\n";
            }
        }

        /*
        * Gets instance of connection to database
        * @return (MySqliConnection) Object
        */
        public static function getInstance($host, $user, $password, $database){
            if(!self::$_instance){ 
                self::$_instance = new self($host, $user, $password, $database); //if no instance were created - new one will be initialize
            }
            return self::$_instance; //return already exsiting instance of the database connection
        }

        /*
        * Prevent database connection from bing copied while assignig the object to new wariable
        * @return (MySqliConnection) Object
        */
        public function getConnection(){
            return $this->_connection;
        }

        /*
        * Prevent database connection from bing copied/duplicated while assignig the object to new wariable
        * @return nothing
        */
        function __clone(){

        }
    }


    /*// CLASS USE EXAMPLE 
        $db = MySqliConnection::getInstance('localhost', 'root', '', 'sandbox');
        $mysqli = $db->getConnection();
        $sql_query = 'SELECT * FROM users;
            $this->lastQuery = $sql_query;
            $result = $mysqli->query($sql_query);
        while($row = $result->fetch_array(MYSQLI_ASSOC)){
            echo $row['ID'];
        }

    */

The second "TableManager" class is little bit more complex. It also make use of the MySqliConnection class which I posted above. So you would have to include both of them in your project. TableManager will allow you to easy make insertion updates and deletions. Class have separate placeholder for read and write.

<?php

/*
* DEPENDENCIES:
* include 'class.MySqliConnection.inc'; //custom class
*
*/

class TableManager{

    private $lastQuery;
    private $lastInsertId;
    private $tableName;
    private $tableIdName;
    private $columnNames = array();
    private $lastResult = array();
    private $curentRow = array();
    private $newPost = array();

    /*
    * Class constructor 
    * [1] (string) $tableName // name of the table which you want to work with
    * [2] (string) $tableIdName // name of the ID field which will be used to delete and update records
    * @return void
    */
    function __construct($tableName, $tableIdName){
        $this->tableIdName = $tableIdName;
        $this->tableName = $tableName;
        $this->getColumnNames();
        $this->curentRow = $this->columnNames;
    }

public function getColumnNames(){
    $sql_query = 'SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = "'.$this->tableName.'"';
    $mysqli = $this->connection();
    $this->lastQuery = $sql_query;
    $result = $mysqli->query($sql_query);
    if (!$result) {
        throw new Exception("Database Error [{$this->database->errno}] {$this->database->error}");
    }
    while($row = $result->fetch_array(MYSQLI_ASSOC)){           
        $this->columnNames[$row['COLUMN_NAME']] = null;
    }
}

    /*
    * Used by a Constructor to set native parameters or virtual array curentRow of the class
    * [1] (array) $v
    * @return void
    */
    function setRowValues($v){

        if(!is_array($v)){
            $this->curentRow = $v;
            return true;    
        }
        foreach ($v as $a => $b) {
            $method = 'set'.ucfirst($a);
            if(is_callable(array($this, $method))){
                //if method is callable use setSomeFunction($k, $v) to filter the value
                $this->$method($b);
            }else{
                $this->curentRow[$a] = $b;
            }
        }

    }

    /*
    * Used by a constructor to set native parameters or virtual array curentRow of the class
    * [0]
    * @return void
    */
    function __toString(){
        var_dump($this);
    }

    /*
    * Query Database for information - Select column in table where column = somevalue
    * [1] (string) $column_name // name od a column
    * [2] (string) $quote_pos // searched value in a specified column
    * @return void
    */
    public function getRow($column_name = false, $quote_post = false){
        $mysqli = $this->connection();
        $quote_post = $mysqli->real_escape_string($quote_post);
        $this->tableName = $mysqli->real_escape_string($this->tableName);
        $column_name = $mysqli->real_escape_string($column_name);
        if($this->tableName && $column_name && $quote_post){
            $sql_query = 'SELECT * FROM '.$this->tableName.' WHERE '.$column_name.' = "'.$quote_post.'"';
            $this->lastQuery = $sql_query;
            $result = $mysqli->query($sql_query);
            if (!$result) {
                throw new Exception("Database Error [{$this->database->errno}] {$this->database->error}");
            }
            while($row = $result->fetch_array(MYSQLI_ASSOC)){
                $this->lastResult[$row['ID']] = $row;
                $this->setRowValues($row);
            }
        }
        if($this->tableName && $column_name && !$quote_post){
            $sql_query = 'SELECT '.$column_name.' FROM '.$this->tableName.'';
            $this->lastQuery = $sql_query;
            $result = $mysqli->query($sql_query);
            if (!$result) {
                throw new Exception("Database Error [{$this->database->errno}] {$this->database->error}");
            }
            while($row = $result->fetch_array(MYSQLI_ASSOC)){           
                $this->lastResult[] = $row;
                $this->setRowValues($row);
            }       
        }
        if($this->tableName && !$column_name && !$quote_post){
            $sql_query = 'SELECT * FROM '.$this->tableName.'';
            $this->lastQuery = $sql_query;
            $result = $mysqli->query($sql_query);
            if (!$result) {
                throw new Exception("Database Error [{$this->database->errno}] {$this->database->error}");
            }
            while($row = $result->fetch_array(MYSQLI_ASSOC)){           
                $this->lastResult[$row['ID']] = $row;
                $this->setRowValues($row);
            }       
        }
    }


    /*
    * Connection class gets instance of db connection or if not exsist creats one
    * [0]
    * @return $mysqli
    */
    private function connection(){
        $this->lastResult = "";
        $db = MySqliConnection::getInstance('localhost', 'root', '', 'sandbox');
        $mysqli = $db->getConnection();
        return $mysqli;
    }

    /*
    * ...
    * [1] (string) $getMe
    * @return void
    */
    function __get($getMe){
        if(isset($this->curentRow[$getMe])){
            return $this->curentRow[$getMe];
        }else{
            throw new Exception("Error Processing Request - No such a property in (array) $this->curentRow", 1);
        }

    }

    /*
    * ...
    * [2] (string) $setMe, (string) $value
    * @return void
    */
    function __set($setMe, $value){
        $temp = array($setMe=>$value);
        $this->setRowValues($temp);
    }

    /*
    * Dumps the object
    * [0] 
    * @return void
    */
    function dump(){
        echo "<hr>";
        var_dump($this);
        echo "<hr>";
    }

    /*
    * Sets Values for $this->newPost array which will be than inserted by insertNewPost() function
    * [1] (array) $newPost //array of avlue that will be inserted to $this->newPost
    * @return bolean
    */
    public function setNewRow($arr){

        if(!is_array($arr)){
            $this->newPost = $arr;
            return false;   
        }
        foreach ($arr as $k => $v) {
            if(array_key_exists($k, $this->columnNames)){
                $method = 'set'.ucfirst($k);
                if(is_callable(array($this, $method))){
                    if($this->$method($v) == false){ //if something go wrong
                        $this->newPost = array(); //empty the newPost array and return flase
                        throw new Exception("There was a problem in setting up New Post parameters. [Cleaning array]", 1);
                    }
                }else{
                    $this->newPost[$k] = $v;
                }
            }else{
                $this->newPost = array(); //empty the newPost array and return flase
                throw new Exception("The column does not exsist in this table. [Cleaning array]", 1);
            }
        }

    }


    /*
    * Inserts new post held in $this->newPost
    * [0]
    * @return bolean
    */
    public function insertNewRow(){
        // check if is set, is array and is not null
        if(isset($this->newPost) && !is_null($this->newPost) && is_array($this->newPost)){
            $mysqli = $this->connection();
            $count_lenght_of_array = count($this->newPost);

            // preper insert query
            $sql_query = 'INSERT INTO '.$this->tableName.' (';
            $i = 1;
            foreach ($this->newPost as $key => $value) {
                $sql_query .=$key;
                if ($i < $count_lenght_of_array) {
                    $sql_query .=', ';
                }

                $i++;
             } 

            $i = 1;  
            $sql_query .=') VALUES (';
            foreach ($this->newPost as $key => $value) {
                $sql_query .='"'.$value.'"';
                if ($i < $count_lenght_of_array) {
                    $sql_query .=', ';
                }

                $i++;
             }  

            $sql_query .=')';
            var_dump($sql_query);
            if($mysqli->query($sql_query)){
                $this->lastInsertId = $mysqli->insert_id;
                $this->lastQuery = $sql_query;
            }

            $this->getInsertedPost($this->lastInsertId);
        }
    }   

    /*
    * getInsertedPost function query the last inserted id and assigned it to the object.
    * [1] (integer) $id // last inserted id from insertNewRow fucntion
    * @return void
    */
    private function getInsertedPost($id){
        $mysqli = $this->connection();
        $sql_query = 'SELECT * FROM '.$this->tableName.' WHERE '.$this->tableIdName.' = "'.$id.'"';
        $result = $mysqli->query($sql_query);
        while($row = $result->fetch_array(MYSQLI_ASSOC)){
            $this->lastResult[$row['ID']] = $row;
            $this->setRowValues($row);
        }       
    }

    /*
    * getInsertedPost function query the last inserted id and assigned it to the object.
    * [0]
    * @return bolean // if deletion was successful return true
    */
    public function deleteLastInsertedPost(){
        $mysqli = $this->connection();
        $sql_query = 'DELETE FROM '.$this->tableName.' WHERE '.$this->tableIdName.' = '.$this->lastInsertId.'';
        $result = $mysqli->query($sql_query);
        if($result){
            $this->lastResult[$this->lastInsertId] = "deleted";
            return true;
        }else{
            throw new Exception("We could not delete last inserted row by ID [{$mysqli->errno}] {$mysqli->error}");

        }
        var_dump($sql_query);       
    }

    /*
    * deleteRow function delete the row with from a table based on a passed id
    * [1] (integer) $id // id of the table row to be delated
    * @return bolean // if deletion was successful return true
    */
    public function deleteRow($id){
        $mysqli = $this->connection();
        $sql_query = 'DELETE FROM '.$this->tableName.' WHERE '.$this->tableIdName.' = '.$id.'';
        $result = $mysqli->query($sql_query);
        if($result){
            $this->lastResult[$this->lastInsertId] = "deleted";
            return true;
        }else{
            return false;
        }
        var_dump($sql_query);       
    }

    /*
    * deleteAllRows function deletes all rows from a table
    * [0]
    * @return bolean // if deletion was successful return true
    */
    public function deleteAllRows(){
        $mysqli = $this->connection();
        $sql_query = 'DELETE FROM '.$this->tableName.'';
        $result = $mysqli->query($sql_query);
        if($result){
            return true;
        }else{
            return false;
        }       
    }

    /*
    * updateRow function updates all values to object values in a row with id
    * [1] (integer) $id
    * @return bolean // if deletion was successful return true
    */
    public function updateRow($update_where = false){
        $id = $this->curentRow[$this->tableIdName];
        $mysqli = $this->connection();
        $updateMe = $this->curentRow;
        unset($updateMe[$this->tableIdName]);
        $count_lenght_of_array = count($updateMe);
        // preper insert query
        $sql_query = 'UPDATE '.$this->tableName.' SET ';
        $i = 1;
        foreach ($updateMe as $k => $v) {
            $sql_query .= $k.' = "'.$v.'"';
            if ($i < $count_lenght_of_array) {
                $sql_query .=', ';
            }

            $i++;
         }
        if($update_where == false){ 
            //update row only for this object id
            $sql_query .=' WHERE '.$this->tableIdName.' = '.$this->curentRow[$this->tableIdName].'';
        }else{
            //add your custom update where query
            $sql_query .=' WHERE '.$update_where.'';
        }

        var_dump($sql_query);
        if($mysqli->query($sql_query)){
            $this->lastQuery = $sql_query;
        }
        $result = $mysqli->query($sql_query);
        if($result){
            return true;
        }else{
            return false;
        }       
    }

}



/*TO DO

1 insertPost(X, X) write function to isert data and in to database;
2 get better query system and display data from database;
3 write function that displays data of a object not databsae;
object should be precise and alocate only one instance of the post at a time. 
// Updating the Posts to curent object $this->curentRow values
->updatePost();

// Deleting the curent post by ID

// Add new row to database

*/





/*
USE EXAMPLE
$Post = new TableManager("post_table", "ID"); // New Object

// Getting posts from the database based on pased in paramerters
$Post->getRow('post_name', 'SOME POST TITLE WHICH IS IN DATABASE' );
$Post->getRow('post_name');
$Post->getRow();



MAGIC GET will read current object  $this->curentRow parameter values by refering to its key as in a varible name
echo $Post->ID.
echo $Post->post_name;
echo $Post->post_description;
echo $Post->post_author;


$Task = new TableManager("table_name", "table_ID_name"); // creating new TableManager object

$addTask = array( //just an array [colum_name] => [values]
    'task_name' => 'New Post',
    'description' => 'New Description Post',
    'person' => 'New Author',
    );
$Task->setNewRow($addTask); //preper new values for insertion to table
$Task->getRow('ID', '12'); //load value from table to object

$Task->insertNewRow(); //inserts new row
$Task->dump(); //diplays object properities

$Task->person = "John"; //magic __set() method will look for setPerson(x,y) method firs if non found will assign value as it is. 
$Task->description = "John Doe is a funny guy"; //magic __set() again
$Task->task_name = "John chellange"; //magic __set() again

$test = ($Task->updateRow("ID = 5")) ? "WORKS FINE" : "ERROR"; //update cutom row with object values
echo $test;
$test = ($Task->updateRow()) ? "WORKS FINE" : "ERROR"; //update curent data loaded in object
echo $test;
*/

Nested Recycler view height doesn't wrap its content

Simply wrap the content using RecyclerView with the Grid Layout

Image: Recycler as GridView layout

Just use the GridLayoutManager like this:

RecyclerView.LayoutManager mRecyclerGrid=new GridLayoutManager(this,3,LinearLayoutManager.VERTICAL,false);
mRecyclerView.setLayoutManager(mRecyclerGrid);

You can set how many items should appear on a row (replace the 3).

Remove char at specific index - python

Slicing works (and is the preferred approach), but just an alternative if more operations are needed (but then converting to a list wouldn't hurt anyway):

>>> a = '123456789'
>>> b = bytearray(a)
>>> del b[3]
>>> b
bytearray(b'12356789')
>>> str(b)
'12356789'