Programs & Examples On #Dataflow

Dataflow programming is a programming paradigm in which computations are modeled through directed graphs: nodes are instructions and data flows through the connections between them.

SSIS Excel Connection Manager failed to Connect to the Source

you can try this:

Uninstall office365

then install only Access Database Engine 2016 Redistributable 64 bit

Also set Project Configuration Properties for Debugging Run64BitRuntime = False

It should work.

How to create a temporary table in SSIS control flow task and then use it in data flow task?

Solution:

Set the property RetainSameConnection on the Connection Manager to True so that temporary table created in one Control Flow task can be retained in another task.

Here is a sample SSIS package written in SSIS 2008 R2 that illustrates using temporary tables.

Walkthrough:

Create a stored procedure that will create a temporary table named ##tmpStateProvince and populate with few records. The sample SSIS package will first call the stored procedure and then will fetch the temporary table data to populate the records into another database table. The sample package will use the database named Sora Use the below create stored procedure script.

USE Sora;
GO

CREATE PROCEDURE dbo.PopulateTempTable
AS
BEGIN
    
    SET NOCOUNT ON;

    IF OBJECT_ID('TempDB..##tmpStateProvince') IS NOT NULL
        DROP TABLE ##tmpStateProvince;

    CREATE TABLE ##tmpStateProvince
    (
            CountryCode     nvarchar(3)         NOT NULL
        ,   StateCode       nvarchar(3)         NOT NULL
        ,   Name            nvarchar(30)        NOT NULL
    );

    INSERT INTO ##tmpStateProvince 
        (CountryCode, StateCode, Name)
    VALUES
        ('CA', 'AB', 'Alberta'),
        ('US', 'CA', 'California'),
        ('DE', 'HH', 'Hamburg'),
        ('FR', '86', 'Vienne'),
        ('AU', 'SA', 'South Australia'),
        ('VI', 'VI', 'Virgin Islands');
END
GO

Create a table named dbo.StateProvince that will be used as the destination table to populate the records from temporary table. Use the below create table script to create the destination table.

USE Sora;
GO

CREATE TABLE dbo.StateProvince
(
        StateProvinceID int IDENTITY(1,1)   NOT NULL
    ,   CountryCode     nvarchar(3)         NOT NULL
    ,   StateCode       nvarchar(3)         NOT NULL
    ,   Name            nvarchar(30)        NOT NULL
    CONSTRAINT [PK_StateProvinceID] PRIMARY KEY CLUSTERED
        ([StateProvinceID] ASC)
) ON [PRIMARY];
GO

Create an SSIS package using Business Intelligence Development Studio (BIDS). Right-click on the Connection Managers tab at the bottom of the package and click New OLE DB Connection... to create a new connection to access SQL Server 2008 R2 database.

Connection Managers - New OLE DB Connection

Click New... on Configure OLE DB Connection Manager.

Configure OLE DB Connection Manager - New

Perform the following actions on the Connection Manager dialog.

  • Select Native OLE DB\SQL Server Native Client 10.0 from Provider since the package will connect to SQL Server 2008 R2 database
  • Enter the Server name, like MACHINENAME\INSTANCE
  • Select Use Windows Authentication from Log on to the server section or whichever you prefer.
  • Select the database from Select or enter a database name, the sample uses the database name Sora.
  • Click Test Connection
  • Click OK on the Test connection succeeded message.
  • Click OK on Connection Manager

Connection Manager

The newly created data connection will appear on Configure OLE DB Connection Manager. Click OK.

Configure OLE DB Connection Manager - Created

OLE DB connection manager KIWI\SQLSERVER2008R2.Sora will appear under the Connection Manager tab at the bottom of the package. Right-click the connection manager and click Properties

Connection Manager Properties

Set the property RetainSameConnection on the connection KIWI\SQLSERVER2008R2.Sora to the value True.

RetainSameConnection Property on Connection Manager

Right-click anywhere inside the package and then click Variables to view the variables pane. Create the following variables.

  • A new variable named PopulateTempTable of data type String in the package scope SO_5631010 and set the variable with the value EXEC dbo.PopulateTempTable.

  • A new variable named FetchTempData of data type String in the package scope SO_5631010 and set the variable with the value SELECT CountryCode, StateCode, Name FROM ##tmpStateProvince

Variables

Drag and drop an Execute SQL Task on to the Control Flow tab. Double-click the Execute SQL Task to view the Execute SQL Task Editor.

On the General page of the Execute SQL Task Editor, perform the following actions.

  • Set the Name to Create and populate temp table
  • Set the Connection Type to OLE DB
  • Set the Connection to KIWI\SQLSERVER2008R2.Sora
  • Select Variable from SQLSourceType
  • Select User::PopulateTempTable from SourceVariable
  • Click OK

Execute SQL Task Editor

Drag and drop a Data Flow Task onto the Control Flow tab. Rename the Data Flow Task as Transfer temp data to database table. Connect the green arrow from the Execute SQL Task to the Data Flow Task.

Control Flow Tab

Double-click the Data Flow Task to switch to Data Flow tab. Drag and drop an OLE DB Source onto the Data Flow tab. Double-click OLE DB Source to view the OLE DB Source Editor.

On the Connection Manager page of the OLE DB Source Editor, perform the following actions.

  • Select KIWI\SQLSERVER2008R2.Sora from OLE DB Connection Manager
  • Select SQL command from variable from Data access mode
  • Select User::FetchTempData from Variable name
  • Click Columns page

OLE DB Source Editor - Connection Manager

Clicking Columns page on OLE DB Source Editor will display the following error because the table ##tmpStateProvince specified in the source command variable does not exist and SSIS is unable to read the column definition.

Error message

To fix the error, execute the statement EXEC dbo.PopulateTempTable using SQL Server Management Studio (SSMS) on the database Sora so that the stored procedure will create the temporary table. After executing the stored procedure, click Columns page on OLE DB Source Editor, you will see the column information. Click OK.

OLE DB Source Editor - Columns

Drag and drop OLE DB Destination onto the Data Flow tab. Connect the green arrow from OLE DB Source to OLE DB Destination. Double-click OLE DB Destination to open OLE DB Destination Editor.

On the Connection Manager page of the OLE DB Destination Editor, perform the following actions.

  • Select KIWI\SQLSERVER2008R2.Sora from OLE DB Connection Manager
  • Select Table or view - fast load from Data access mode
  • Select [dbo].[StateProvince] from Name of the table or the view
  • Click Mappings page

OLE DB Destination Editor - Connection Manager

Click Mappings page on the OLE DB Destination Editor would automatically map the columns if the input and output column names are same. Click OK. Column StateProvinceID does not have a matching input column and it is defined as an IDENTITY column in database. Hence, no mapping is required.

OLE DB Destination Editor - Mappings

Data Flow tab should look something like this after configuring all the components.

Data Flow tab

Click the OLE DB Source on Data Flow tab and press F4 to view Properties. Set the property ValidateExternalMetadata to False so that SSIS would not try to check for the existence of the temporary table during validation phase of the package execution.

Set ValidateExternalMetadata

Execute the query select * from dbo.StateProvince in the SQL Server Management Studio (SSMS) to find the number of rows in the table. It should be empty before executing the package.

Rows in table before package execution

Execute the package. Control Flow shows successful execution.

Package Execution  - Control Flow tab

In Data Flow tab, you will notice that the package successfully processed 6 rows. The stored procedure created early in this posted inserted 6 rows into the temporary table.

Package Execution  - Data Flow tab

Execute the query select * from dbo.StateProvince in the SQL Server Management Studio (SSMS) to find the 6 rows successfully inserted into the table. The data should match with rows founds in the stored procedure.

Rows in table after package execution

The above example illustrated how to create and use temporary table within a package.

Options for HTML scraping?

I know and love Screen-Scraper.

Screen-Scraper is a tool for extracting data from websites. Screen-Scraper automates:

* Clicking links on websites
* Entering data into forms and submitting
* Iterating through search result pages
* Downloading files (PDF, MS Word, images, etc.)

Common uses:

* Download all products, records from a website
* Build a shopping comparison site
* Perform market research
* Integrate or migrate data

Technical:

* Graphical interface--easy automation
* Cross platform (Linux, Mac, Windows, etc.)
* Integrates with most programming languages (Java, PHP, .NET, ASP, Ruby, etc.)
* Runs on workstations or servers

Three editions of screen-scraper:

* Enterprise: The most feature-rich edition of screen-scraper. All capabilities are enabled.
* Professional: Designed to be capable of handling most common scraping projects.
* Basic: Works great for simple projects, but not nearly as many features as its two older brothers.

How to copy only a single worksheet to another workbook using vba

Sub ActiveSheet_toDESKTOP_As_Workbook()

Dim Oldname As String
Dim MyRange As Range
Dim MyWS As String

MyWS = ActiveCell.Parent.Name

    Application.DisplayAlerts = False 'hide confirmation from user
    Application.ScreenUpdating = False
    Oldname = ActiveSheet.Name
    'Sheets.Add(Before:=Sheets(1)).Name = "FirstSheet"
    
    'Get path for desktop of user PC
    Path = Environ("USERPROFILE") & "\Desktop"
    

    ActiveSheet.Cells.Copy
    Sheets.Add(After:=Sheets(Sheets.Count)).Name = "TransferSheet"
    ActiveSheet.Cells.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
    ActiveSheet.Cells.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
    ActiveSheet.Cells.Copy
    
    'Create new workbook and past copied data in new workbook & save to desktop
    Workbooks.Add (xlWBATWorksheet)
    ActiveSheet.Cells.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
    ActiveSheet.Cells.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
    ActiveSheet.Cells(1, 1).Select
    ActiveWorkbook.ActiveSheet.Name = Oldname    '"report"
    ActiveWorkbook.SaveAs Filename:=Path & "\" & Oldname & " WS " & Format(CStr(Now()), "dd-mmm (hh.mm.ss AM/PM)") & ".xlsx"
    ActiveWorkbook.Close SaveChanges:=True

    
    Sheets("TransferSheet").Delete
    
    
   Application.DisplayAlerts = True
    Application.ScreenUpdating = True
    Worksheets(MyWS).Activate
    'MsgBox "Exported to Desktop"

End Sub

List of all special characters that need to be escaped in a regex

on the other side of the coin, you should use "non-char" regex that looks like this if special characters = allChars - number - ABC - space in your app context.

String regepx = "[^\\s\\w]*";

Roblox Admin Command Script

for i=1,#target do
    game.Players.target[i].Character:BreakJoints()
end

Is incorrect, if "target" contains "FakeNameHereSoNoStalkers" then the run code would be:

game.Players.target.1.Character:BreakJoints()

Which is completely incorrect.


c = game.Players:GetChildren()

Never use "Players:GetChildren()", it is not guaranteed to return only players.

Instead use:

c = Game.Players:GetPlayers()

if msg:lower()=="me" then
    table.insert(people, source)
    return people

Here you add the player's name in the list "people", where you in the other places adds the player object.


Fixed code:

local Admins = {"FakeNameHereSoNoStalkers"}

function Kill(Players)
    for i,Player in ipairs(Players) do
        if Player.Character then
            Player.Character:BreakJoints()
        end
    end
end

function IsAdmin(Player)
    for i,AdminName in ipairs(Admins) do
        if Player.Name:lower() == AdminName:lower() then return true end
    end
    return false
end

function GetPlayers(Player,Msg)
    local Targets = {}
    local Players = Game.Players:GetPlayers()

    if Msg:lower() == "me" then
        Targets = { Player }
    elseif Msg:lower() == "all" then
        Targets = Players
    elseif Msg:lower() == "others" then
        for i,Plr in ipairs(Players) do
            if Plr ~= Player then
                table.insert(Targets,Plr)
            end
        end
    else
        for i,Plr in ipairs(Players) do
            if Plr.Name:lower():sub(1,Msg:len()) == Msg then
                table.insert(Targets,Plr)
            end
        end
    end
    return Targets
end

Game.Players.PlayerAdded:connect(function(Player)
    if IsAdmin(Player) then
        Player.Chatted:connect(function(Msg)
            if Msg:lower():sub(1,6) == ":kill " then
                Kill(GetPlayers(Player,Msg:sub(7)))
            end
        end)
    end
end)

Display milliseconds in Excel

I did this in Excel 2000.

This statement should be: ms = Round(temp - Int(temp), 3) * 1000

You need to create a custom format for the result cell of [h]:mm:ss.000

Text file with 0D 0D 0A line breaks

This typically stems from a bug in revision control system, or similar. This was a product from CVS, if a file was checked in from Windows to Unix server, and then checked out again...

In other words, it is just broken...

curl error 18 - transfer closed with outstanding read data remaining

The error string is quite simply exactly what libcurl sees: since it is receiving a chunked encoding stream it knows when there is data left in a chunk to receive. When the connection is closed, libcurl knows that the last received chunk was incomplete. Then you get this error code.

There's nothing you can do to avoid this error with the request unmodified, but you can try to work around it by issuing a HTTP 1.0 request instead (since chunked encoding won't happen then) but the fact is that this is most likely a flaw in the server or in your network/setup somehow.

How to get ID of the last updated row in MySQL?

Further more to the Above Accepted Answer
For those who were wondering about := & =

Significant difference between := and =, and that is that := works as a variable-assignment operator everywhere, while = only works that way in SET statements, and is a comparison operator everywhere else.

So SELECT @var = 1 + 1; will leave @var unchanged and return a boolean (1 or 0 depending on the current value of @var), while SELECT @var := 1 + 1; will change @var to 2, and return 2. [Source]

What is Dependency Injection?

The best analogy I can think of is the surgeon and his assistant(s) in an operation theater, where the surgeon is the main person and his assistant who provides the various surgical components when he needs it so that the surgeon can concentrate on the one thing he does best (surgery). Without the assistant the surgeon has to get the components himself every time he needs one.

DI for short, is a technique to remove a common additional responsibility (burden) on components to fetch the dependent components, by providing them to it.

DI brings you closer to the Single Responsibility (SR) principle, like the surgeon who can concentrate on surgery.

When to use DI : I would recommend using DI in almost all production projects ( small/big), particularly in ever changing business environments :)

Why : Because you want your code to be easily testable, mockable etc so that you can quickly test your changes and push it to the market. Besides why would you not when you there are lots of awesome free tools/frameworks to support you in your journey to a codebase where you have more control.

Passing struct to function

This is how to pass the struct by reference. This means that your function can access the struct outside of the function and modify its values. You do this by passing a pointer to the structure to the function.

#include <stdio.h>
/* card structure definition */
struct card
{
    int face; // define pointer face
}; // end structure card

typedef struct card Card ;

/* prototype */
void passByReference(Card *c) ;

int main(void)
{
    Card c ;
    c.face = 1 ;
    Card *cptr = &c ; // pointer to Card c

    printf("The value of c before function passing = %d\n", c.face);
    printf("The value of cptr before function = %d\n",cptr->face);

    passByReference(cptr);

    printf("The value of c after function passing = %d\n", c.face);

    return 0 ; // successfully ran program
}

void passByReference(Card *c)
{
    c->face = 4;
}

This is how you pass the struct by value so that your function receives a copy of the struct and cannot access the exterior structure to modify it. By exterior I mean outside the function.

#include <stdio.h>


/* global card structure definition */
struct card
{
    int face ; // define pointer face
};// end structure card

typedef struct card Card ;

/* function prototypes */
void passByValue(Card c);

int main(void)
{
    Card c ;
    c.face = 1;

    printf("c.face before passByValue() = %d\n", c.face);

    passByValue(c);

    printf("c.face after passByValue() = %d\n",c.face);
    printf("As you can see the value of c did not change\n");
    printf("\nand the Card c inside the function has been destroyed"
        "\n(no longer in memory)");
}


void passByValue(Card c)
{
    c.face = 5;
}

Is there a conditional ternary operator in VB.NET?

If() is the closest equivalent but beware of implicit conversions going on if you have set "Option Strict off"

For example, if your not careful you may be tempted to try something like:

Dim foo As Integer? = If(someTrueExpression, Nothing, 2)

Will give "foo" a value of 0!

I think the '?' operator equivalent in C# would instead fail compilation

How to add image in a TextView text?

com/xyz/customandroid/ TextViewWithImages .java:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Context;
import android.text.Spannable;
import android.text.style.ImageSpan;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.TextView;

public class TextViewWithImages extends TextView {

    public TextViewWithImages(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }
    public TextViewWithImages(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    public TextViewWithImages(Context context) {
        super(context);
    }
    @Override
    public void setText(CharSequence text, BufferType type) {
        Spannable s = getTextWithImages(getContext(), text);
        super.setText(s, BufferType.SPANNABLE);
    }

    private static final Spannable.Factory spannableFactory = Spannable.Factory.getInstance();

    private static boolean addImages(Context context, Spannable spannable) {
        Pattern refImg = Pattern.compile("\\Q[img src=\\E([a-zA-Z0-9_]+?)\\Q/]\\E");
        boolean hasChanges = false;

        Matcher matcher = refImg.matcher(spannable);
    while (matcher.find()) {
        boolean set = true;
        for (ImageSpan span : spannable.getSpans(matcher.start(), matcher.end(), ImageSpan.class)) {
            if (spannable.getSpanStart(span) >= matcher.start()
             && spannable.getSpanEnd(span) <= matcher.end()
               ) {
                spannable.removeSpan(span);
            } else {
                set = false;
                break;
            }
        }
        String resname = spannable.subSequence(matcher.start(1), matcher.end(1)).toString().trim();
        int id = context.getResources().getIdentifier(resname, "drawable", context.getPackageName());
        if (set) {
            hasChanges = true;
            spannable.setSpan(  new ImageSpan(context, id),
                                matcher.start(),
                                matcher.end(),
                                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
                             );
        }
    }

        return hasChanges;
    }
    private static Spannable getTextWithImages(Context context, CharSequence text) {
        Spannable spannable = spannableFactory.newSpannable(text);
        addImages(context, spannable);
        return spannable;
    }
}

Use:

in res/layout/mylayout.xml:

            <com.xyz.customandroid.TextViewWithImages
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#FFFFFF00"
                android:text="@string/can_try_again"
                android:textSize="12dip"
                style=...
                />

Note that if you place TextViewWithImages.java in some location other than com/xyz/customandroid/, you also must change the package name, com.xyz.customandroid above.

in res/values/strings.xml:

<string name="can_try_again">Press [img src=ok16/] to accept or [img src=retry16/] to retry</string>

where ok16.png and retry16.png are icons in the res/drawable/ folder

How to generate a GUID in Oracle?

It is not clear what you mean by auto-generate a guid into an insert statement but at a guess, I think you are trying to do something like the following:

INSERT INTO MY_TAB (ID, NAME) VALUES (SYS_GUID(), 'Adams');
INSERT INTO MY_TAB (ID, NAME) VALUES (SYS_GUID(), 'Baker');

In that case I believe the ID column should be declared as RAW(16);

I am doing this off the top of my head. I don't have an Oracle instance handy to test against, but I think that is what you want.

Iterating over dictionaries using 'for' loops

To iterate over keys, it is slower but better to use my_dict.keys(). If you tried to do something like this:

for key in my_dict:
    my_dict[key+"-1"] = my_dict[key]-1

it would create a runtime error because you are changing the keys while the program is running. If you are absolutely set on reducing time, use the for key in my_dict way, but you have been warned.

Error QApplication: no such file or directory

To start things off, the error QApplication: no such file or directory means your compiler was not able to find this header. It is not related to the linking process as you mentioned in the question.

The -I flag (uppercase i) is used to specify the include (headers) directory (which is what you need to do), while the -L flag is used to specify the libraries directory. The -l flag (lowercase L) is used to link your application with a specified library.

But you can use Qt to your advantage: Qt has a build system named qmake which makes things easier. For instance, when I want to compile main.cpp I create a main.pro file. For educational purposes, let's say this source code is a simple project that uses only QApplication and QDeclarativeView. An appropriate .pro file would be:

TEMPLATE += app
QT += gui declarative
SOURCES += main.cpp

Then, execute the qmake inside that directory to create the Makefile that will be used to compile your application, and finally execute make to get the job done.

On my system this make outputs:

g++ -c -pipe -O2 -Wall -W -D_REENTRANT -DQT_NO_DEBUG -DQT_DECLARATIVE_LIB -DQT_GUI_LIB -DQT_CORE_LIB -DQT_SHARED -I/opt/qt_47x/mkspecs/linux-g++ -I. -I/opt/qt_47x/include/QtCore -I/opt/qt_47x/include/QtGui -I/opt/qt_47x/include/QtDeclarative -I/opt/qt_47x/include -I/usr/X11R6/include -I. -o main.o main.cpp
g++ -Wl,-O1 -Wl,-rpath,/opt/qt_47x/lib -o main main.o -L/opt/qt_47x/lib -L/usr/X11R6/lib -lQtDeclarative -L/opt/qt_47x/lib -lQtScript -lQtSvg -L/usr/X11R6/lib -lQtSql -lQtXmlPatterns -lQtNetwork -lQtGui -lQtCore -lpthread

Note: I installed Qt in another directory --> /opt/qt_47x

Edit: Qt 5.x and later

Add QT += widgets to the .pro file and solve this problem.

ASP.net Repeater get current index, pointer, or counter

Add a label control to your Repeater's ItemTemplate. Handle OnItemCreated event.

ASPX

<asp:Repeater ID="rptr" runat="server" OnItemCreated="RepeaterItemCreated">
    <ItemTemplate>
        <div id="width:50%;height:30px;background:#0f0a0f;">
            <asp:Label ID="lblSr" runat="server" 
               style="width:30%;float:left;text-align:right;text-indent:-2px;" />
            <span 
               style="width:65%;float:right;text-align:left;text-indent:-2px;" >
            <%# Eval("Item") %>
            </span>
        </div>
    </ItemTemplate>
</asp:Repeater>

Code Behind:

    protected void RepeaterItemCreated(object sender, RepeaterItemEventArgs e)
    {
        Label l = e.Item.FindControl("lblSr") as Label;
        if (l != null)
            l.Text = e.Item.ItemIndex + 1+"";
    }

Should I use string.isEmpty() or "".equals(string)?

One thing you might want to consider besides the other issues mentioned is that isEmpty() was introduced in 1.6, so if you use it you won't be able to run the code on Java 1.5 or below.

Nested ng-repeat

It's better to have a proper JSON format instead of directly using the one converted from XML.

[
  {
    "number": "2013-W45",
    "days": [
      {
        "dow": "1",
        "templateDay": "Monday",
        "jobs": [
          {
            "name": "Wakeup",
            "jobs": [
              {
                "name": "prepare breakfast",

              }
            ]
          },
          {
            "name": "work 9-5",

          }
        ]
      },
      {
        "dow": "2",
        "templateDay": "Tuesday",
        "jobs": [
          {
            "name": "Wakeup",
            "jobs": [
              {
                "name": "prepare breakfast",

              }
            ]
          }
        ]
      }
    ]
  }
]

This will make things much easier and easy to loop through.

Now you can write the loop as -

<div ng-repeat="week in myData">
   <div ng-repeat="day in week.days">
      {{day.dow}} - {{day.templateDay}}
      <b>Jobs:</b><br/> 
       <ul>
         <li ng-repeat="job in day.jobs"> 
           {{job.name}} 
         </li>
       </ul>
   </div>
</div>

Best design for a changelog / auditing database table?

According to the principle of separation:

  1. Auditing data tables need to be separate from the main database. Because audit databases can have a lot of historical data, it makes sense from a memory utilization standpoint to keep them separate.

  2. Do not use triggers to audit the whole database, because you will end up with a mess of different databases to support. You will have to write one for DB2, SQLServer, Mysql, etc.

How to set image for bar button with swift?

An easy solution may be the following

barButtonItem.image = UIImage(named: "image")

then go to your Assets.xcassets select the image and go to the Attribute Inspector and select "Original Image" in Reder as option.

Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $

There was an error in understanding of return Type Just add Header and it will solve your problem

@Headers("Content-Type: application/json")

Change onClick attribute with javascript

You want to do this - set a function that will be executed to respond to the onclick event:

document.getElementById('buttonLED'+id).onclick = function(){ writeLED(1,1); } ;

The things you are doing don't work because:

  1. The onclick event handler expects to have a function, here you are assigning a string

    document.getElementById('buttonLED'+id).onclick = "writeLED(1,1)";
    
  2. In this, you are assigning as the onclick event handler the result of executing the writeLED(1,1) function:

    document.getElementById('buttonLED'+id).onclick = writeLED(1,1);
    

How do I 'foreach' through a two-dimensional array?

It depends on how you define your multi-dimensional array. Here are two options:

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            // First
            string[,] arr1 = {
                       { "aa", "aaa" },
                       { "bb", "bbb" }
                   };

            // Second
            string[][] arr2 = new[] {
                new[] { "aa", "aaa" },
                new[] { "bb", "bbb" }
            };

            // Iterate through first
            for (int x = 0; x <= arr1.GetUpperBound(0); x++)
                for (int y = 0; y <= arr1.GetUpperBound(1); y++)
                    Console.Write(arr1[x, y] + "; ");

            Console.WriteLine(Environment.NewLine);

            // Iterate through second second
            foreach (string[] entry in arr2)
                foreach (string element in entry)
                    Console.Write(element + "; ");

            Console.WriteLine(Environment.NewLine);
            Console.WriteLine("Press any key to finish");
            Console.ReadKey();
        }
    }
}

How can I set the color of a selected row in DataGrid

Some of the reason which I experienced the row selected event not working

  1. Style is set up for DataGridCell
  2. Using Templated columns
  3. Trigger is set up at the DataGridRow

This is what helped me. Setting the Style for DataGridCell

<Style TargetType="{x:Type DataGridCell}">
  <Style.Triggers>
    <Trigger Property="IsSelected" Value="True">
      <Setter Property="Background" Value="Green"/>
      <Setter Property="Foreground" Value="White"/>
    </Trigger>
  </Style.Triggers> 
</Style>

And since I was using a template column with a label inside, I bound the Foreground property to the container Foreground using RelativeSource binding:

<DataGridTemplateColumn>
  <DataGridTemplateColumn.CellTemplate>
    <DataTemplate>
      <Label Content="{Binding CategoryName,
                 Mode=TwoWay,
                 UpdateSourceTrigger=LostFocus}"
             Foreground="{Binding Foreground,
                 RelativeSource={RelativeSource Mode=FindAncestor,
                     AncestorLevel=1, 
                     AncestorType={x:Type DataGridCell}}}"
             Width="150"/>
    </DataTemplate>
  </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

How to configure ChromeDriver to initiate Chrome browser in Headless mode through Selenium?

So after correcting my code to:

options = webdriver.ChromeOptions()
options.add_experimental_option("excludeSwitches",["ignore-certificate-errors"])
options.add_argument('--disable-gpu')
options.add_argument('--headless')
chrome_driver_path = "C:\Python27\Scripts\chromedriver.exe"

The .exe file still came up when running the script. Although this did get rid of some extra output telling me "Failed to launch GPU process".

What ended up working is running my Python script using a .bat file

So basically,

  1. Save python script if a folder
  2. Open text editor, and dump the following code (edit to your script of course)

    c:\python27\python.exe c:\SampleFolder\ThisIsMyScript.py %*

  3. Save the .txt file and change the extension to .bat

  4. Double click this to run the file

So this just opened the script in Command Prompt and ChromeDriver seems to be operating within this window without popping out to the front of my screen and thus solving the problem.

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

In order to append to a file you'll need to use a slightly different approach. You can still redirect an individual process' standard error and standard output to a file, but in order to append it to a file you'll need to do one of these things:

  1. Read the stdout/stderr file contents created by Start-Process
  2. Not use Start-Process and use the call operator, &
  3. Not use Start-Process and start the process with .NET objects

The first way would look like this:

$myLog = "C:\File.log"
$stdErrLog = "C:\stderr.log"
$stdOutLog = "C:\stdout.log"
Start-Process -File myjob.bat -RedirectStandardOutput $stdOutLog -RedirectStandardError $stdErrLog -wait
Get-Content $stdErrLog, $stdOutLog | Out-File $myLog -Append

The second way would look like this:

& myjob.bat 2>&1 >> C:\MyLog.txt

Or this:

& myjob.bat 2>&1 | Out-File C:\MyLog.txt -Append

The third way:

$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.FileName = "myjob.bat"
$pinfo.RedirectStandardError = $true
$pinfo.RedirectStandardOutput = $true
$pinfo.UseShellExecute = $false
$pinfo.Arguments = ""
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $pinfo
$p.Start() | Out-Null
$p.WaitForExit()
$output = $p.StandardOutput.ReadToEnd()
$output += $p.StandardError.ReadToEnd()
$output | Out-File $myLog -Append

Get checkbox values using checkbox name using jquery

$("input[name='bla[]']").each( function () {
    alert($(this).val());
});

How to convert local time string to UTC?

import time

import datetime

def Local2UTC(LocalTime):

    EpochSecond = time.mktime(LocalTime.timetuple())
    utcTime = datetime.datetime.utcfromtimestamp(EpochSecond)

    return utcTime

>>> LocalTime = datetime.datetime.now()

>>> UTCTime = Local2UTC(LocalTime)

>>> LocalTime.ctime()

'Thu Feb  3 22:33:46 2011'

>>> UTCTime.ctime()

'Fri Feb  4 05:33:46 2011'

Xpath for href element

This will get you the generic link:

selenium.FindElement(By.XPath("xpath=//a[contains(@href,'listDetails.do')")).Click();

If you want to have it specify a parameter then you will have to test for each one:

...
int i = 1;

selenium.FindElement(By.XPath("xpath=//a[contains(@href,'listDetails.do?camp=" + i.ToString() + "')")).Click();
...

The above could utilize a for loop which navigates to and from each camp numbers' page, which could verify a static list of camps.

Please excuse if the code is not perfect, I have not tested myself.

Showing loading animation in center of page while making a call to Action method in ASP .NET MVC

This is how did it works like a charm.

CSS

#loader {
position:fixed;
left:1px;
top:1px;
width: 100%;
height: 100%;
z-index: 9999;

background: url('../images/ajax-loader100X100.gif') 50% 50% no-repeat rgb(249,249,249);
}  

in _layout file inside body tag but outside the container div. Every time page loads it shows loading. Once page is loaded JS fadeout(second)


<div id="loader">
</div>

JS at the bottom of _layout file


<script type="text/javascript">
// With the element initially shown, we can hide it slowly:
 $("#loader").fadeOut(1000);
</script>  

R apply function with multiple parameters

Just pass var2 as an extra argument to one of the apply functions.

mylist <- list(a=1,b=2,c=3)
myfxn <- function(var1,var2){
  var1*var2
}
var2 <- 2

sapply(mylist,myfxn,var2=var2)

This passes the same var2 to every call of myfxn. If instead you want each call of myfxn to get the 1st/2nd/3rd/etc. element of both mylist and var2, then you're in mapply's domain.

Send Message in C#

It doesn't sound like a good idea to use send message. I think you should try to work around the problem that the DLLs can't reference each other...

Different ways of loading a file as an InputStream

Plain old Java on plain old Java 7 and no other dependencies demonstrates the difference...

I put file.txt in c:\temp\ and I put c:\temp\ on the classpath.

There is only one case where there is a difference between the two call.

class J {

 public static void main(String[] a) {
    // as "absolute"

    // ok   
    System.err.println(J.class.getResourceAsStream("/file.txt") != null); 

    // pop            
    System.err.println(J.class.getClassLoader().getResourceAsStream("/file.txt") != null); 

    // as relative

    // ok
    System.err.println(J.class.getResourceAsStream("./file.txt") != null); 

    // ok
    System.err.println(J.class.getClassLoader().getResourceAsStream("./file.txt") != null); 

    // no path

    // ok
    System.err.println(J.class.getResourceAsStream("file.txt") != null); 

   // ok
   System.err.println(J.class.getClassLoader().getResourceAsStream("file.txt") != null); 
  }
}

object==null or null==object?

This is not of much value in Java (1.5+) except when the type of object is Boolean. In which case, this can still be handy.

if (object = null) will not cause compilation failure in Java 1.5+ if object is Boolean but would throw a NullPointerException at runtime.

Enabling/Disabling Microsoft Virtual WiFi Miniport

From accepted answer:

You go to your "device manager", find your "network adapters", then should find the virtual wifi adapter, then right click it and enable it

Maybe your device is hidden - first you should unhide it from the device manger, then re-enable the adapter from the device manger tools.

VBA - how to conditionally skip a for loop iteration

Maybe try putting it all in the end if and use a else to skip the code this will make it so that you are able not use the GoTo.

                        If 6 - ((Int_height(Int_Column - 1) - 1) + Int_direction(e, 1)) = 7 Or (Int_Column - 1) + Int_direction(e, 0) = -1 Or (Int_Column - 1) + Int_direction(e, 0) = 7 Then
                Else
                    If Grid((Int_Column - 1) + Int_direction(e, 0), 6 - ((Int_height(Int_Column - 1) - 1) + Int_direction(e, 1))) = "_" Then
                        Console.ReadLine()
                    End If
                End If

Add Marker function with Google Maps API

<div id="map" style="width:100%;height:500px"></div>

<script>
function myMap() {
  var myCenter = new google.maps.LatLng(51.508742,-0.120850);
  var mapCanvas = document.getElementById("map");
  var mapOptions = {center: myCenter, zoom: 5};
  var map = new google.maps.Map(mapCanvas, mapOptions);
  var marker = new google.maps.Marker({position:myCenter});
  marker.setMap(map);
}
</script>

<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBu-916DdpKAjTmJNIgngS6HL_kDIKU0aU&callback=myMap"></script>

Plotting of 1-dimensional Gaussian distribution function

You are missing a parantheses in the denominator of your gaussian() function. As it is right now you divide by 2 and multiply with the variance (sig^2). But that is not true and as you can see of your plots the greater variance the more narrow the gaussian is - which is wrong, it should be opposit.

So just change the gaussian() function to:

def gaussian(x, mu, sig):
    return np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.)))

Split string to equal length substrings in Java

You can use substring from String.class (handling exceptions) or from Apache lang commons (it handles exceptions for you)

static String   substring(String str, int start, int end) 

Put it inside a loop and you are good to go.

Replace all non Alpha Numeric characters, New Lines, and multiple White Space with one Space

For anyone still strugging (like me...) after the above more expert replies, this works in Visual Studio 2019:

outputString = Regex.Replace(inputString, @"\W", "_");

Remember to add

using System.Text.RegularExpressions;

How to delete duplicate lines in a file without sorting it in Unix?

The first solution is also from http://sed.sourceforge.net/sed1line.txt

$ echo -e '1\n2\n2\n3\n3\n3\n4\n4\n4\n4\n5' |sed -nr '$!N;/^(.*)\n\1$/!P;D'
1
2
3
4
5

the core idea is:

print ONLY once of each duplicate consecutive lines at its LAST appearance and use D command to implement LOOP.

Explains:

  1. $!N;: if current line is NOT the last line, use N command to read the next line into pattern space.
  2. /^(.*)\n\1$/!P: if the contents of current pattern space is two duplicate string separated by \n, which means the next line is the same with current line, we can NOT print it according to our core idea; otherwise, which means current line is the LAST appearance of all of its duplicate consecutive lines, we can now use P command to print the chars in current pattern space util \n (\n also printed).
  3. D: we use D command to delete the chars in current pattern space util \n (\n also deleted), then the content of pattern space is the next line.
  4. and D command will force sed to jump to its FIRST command $!N, but NOT read the next line from file or standard input stream.

The second solution is easy to understood (from myself):

$ echo -e '1\n2\n2\n3\n3\n3\n4\n4\n4\n4\n5' |sed -nr 'p;:loop;$!N;s/^(.*)\n\1$/\1/;tloop;D'
1
2
3
4
5

the core idea is:

print ONLY once of each duplicate consecutive lines at its FIRST appearance and use : command & t command to implement LOOP.

Explains:

  1. read a new line from input stream or file and print it once.
  2. use :loop command set a label named loop.
  3. use N to read next line into the pattern space.
  4. use s/^(.*)\n\1$/\1/ to delete current line if the next line is same with current line, we use s command to do the delete action.
  5. if the s command is executed successfully, then use tloop command force sed to jump to the label named loop, which will do the same loop to the next lines util there are no duplicate consecutive lines of the line which is latest printed; otherwise, use D command to delete the line which is the same with thelatest-printed line, and force sed to jump to first command, which is the p command, the content of current pattern space is the next new line.

Why does adb return offline after the device string?

if non of the steps work from the above. my device still offline after connected through wifi. i did the following:

go to your device...

  1. go to settings.

  2. go to developer options.

  3. Allow adb debugging in charge mode only.

  4. repeat the steps as you always do . which is:

    a. connet your usb on chargemode only. b. open command write: - adb tcpip 4455 - adb connect 192.168.1.11:4455 b. disconnect usb.

now everythings work for me .

How to determine whether code is running in DEBUG / RELEASE build?

Most answers said that how to set #ifdef DEBUG and none of them saying how to determinate debug/release build.

My opinion:

  1. Edit scheme -> run -> build configuration :choose debug / release . It can control the simulator and your test iPhone's code status.

  2. Edit scheme -> archive -> build configuration :choose debug / release . It can control the test package app and App Store app 's code status. enter image description here

Get text of the selected option with jQuery

You could actually put the value = to the text and then do

$j(document).ready(function(){
    $j("select#select_2").change(function(){
        val = $j("#select_2 option:selected").html();
        alert(val);
    });
});

Or what I did on a similar case was

<select name="options[2]" id="select_2" onChange="JavascriptMethod()">
  with you're options here
</select>

With this second option you should have a undefined. Give me feedback if it worked :)

Patrick

Show diff between commits

Accepted answer is good.

Just putting it again here, so its easy to understand & try in future

git diff c1...c2 > mypatch_1.patch  
git diff c1..c2  > mypatch_2.patch  
git diff c1^..c2 > mypatch_3.patch  

I got the same diff for all the above commands.

Above helps in
1. seeing difference of between commit c1 & another commit c2
2. also making a patch file that shows diff and can be used to apply changes to another branch

If it not showing difference correctly
then c1 & c2 may be taken wrong
so adjust them to a before commit like c1 to c0, or to one after like c2 to c3

Use gitk to see the commits SHAs, 1st 8 characters are enough to use them as c0, c1, c2 or c3. You can also see the commits ids from Gitlab > Repository > Commits, etc.

Hope that helps.

Postgresql : Connection refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

The error you quote has nothing to do with pg_hba.conf; it's failing to connect, not failing to authorize the connection.

Do what the error message says:

Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

You haven't shown the command that produces the error. Assuming you're connecting on localhost port 5432 (the defaults for a standard PostgreSQL install), then either:

  • PostgreSQL isn't running

  • PostgreSQL isn't listening for TCP/IP connections (listen_addresses in postgresql.conf)

  • PostgreSQL is only listening on IPv4 (0.0.0.0 or 127.0.0.1) and you're connecting on IPv6 (::1) or vice versa. This seems to be an issue on some older Mac OS X versions that have weird IPv6 socket behaviour, and on some older Windows versions.

  • PostgreSQL is listening on a different port to the one you're connecting on

  • (unlikely) there's an iptables rule blocking loopback connections

(If you are not connecting on localhost, it may also be a network firewall that's blocking TCP/IP connections, but I'm guessing you're using the defaults since you didn't say).

So ... check those:

  • ps -f -u postgres should list postgres processes

  • sudo lsof -n -u postgres |grep LISTEN or sudo netstat -ltnp | grep postgres should show the TCP/IP addresses and ports PostgreSQL is listening on

BTW, I think you must be on an old version. On my 9.3 install, the error is rather more detailed:

$ psql -h localhost -p 12345
psql: could not connect to server: Connection refused
        Is the server running on host "localhost" (::1) and accepting
        TCP/IP connections on port 12345?

Removing a Fragment from the back stack

You add to the back state from the FragmentTransaction and remove from the backstack using FragmentManager pop methods:

FragmentManager manager = getActivity().getSupportFragmentManager();
FragmentTransaction trans = manager.beginTransaction();
trans.remove(myFrag);
trans.commit();
manager.popBackStack();

Sonar properties files

You can define a Multi-module project structure, then you can set the configuration for sonar in one properties file in the root folder of your project, (Way #1)

How do I hide the PHP explode delimiter from submitted form results?

You could try a different approach like read the file line by line instead of dealing with all this nl2br / explode stuff.

$fh = fopen("employees.txt", "r"); if ($fh) {     while (($line = fgets($fh)) !== false) {         $line = trim($line);         echo "<option value='".$line."'>".$line."</option>";     } } else {     // error opening the file, do something } 

Also maybe just doing a trim (remove whitespace from beginning/end of string) is your issue?

And maybe people are just misunderstanding what you mean by "submitting results to a spreadsheet" -- are you doing this with code? or a copy/paste from an HTML page into a spreadsheet? Maybe you can explain that in more detail. The delimiter for which you split the lines of the file shouldn't be displaying in the output anyway unless you have unexpected output for some other reason.

Keeping it simple and how to do multiple CTE in a query

You can have multiple CTEs in one query, as well as reuse a CTE:

WITH    cte1 AS
        (
        SELECT  1 AS id
        ),
        cte2 AS
        (
        SELECT  2 AS id
        )
SELECT  *
FROM    cte1
UNION ALL
SELECT  *
FROM    cte2
UNION ALL
SELECT  *
FROM    cte1

Note, however, that SQL Server may reevaluate the CTE each time it is accessed, so if you are using values like RAND(), NEWID() etc., they may change between the CTE calls.

Best way to format integer as string with leading zeros?

For Python 3 and beyond: str.zfill() is still the most readable option

But it is a good idea to look into the new and powerful str.format(), what if you want to pad something that is not 0?

    # if we want to pad 22 with zeros in front, to be 5 digits in length:
    str_output = '{:0>5}'.format(22)
    print(str_output)
    # >>> 00022
    # {:0>5} meaning: ":0" means: pad with 0, ">" means move 22 to right most, "5" means the total length is 5

    # another example for comparision
    str_output = '{:#<4}'.format(11)
    print(str_output)
    # >>> 11##

    # to put it in a less hard-coded format:
    int_inputArg = 22
    int_desiredLength = 5
    str_output = '{str_0:0>{str_1}}'.format(str_0=int_inputArg, str_1=int_desiredLength)
    print(str_output)
    # >>> 00022

How to update Ruby Version 2.0.0 to the latest version in Mac OSX Yosemite?

I recommend rbenv* https://github.com/rbenv/rbenv

* If this meets your criteria: https://github.com/rbenv/rbenv/wiki/Why-rbenv?:

rbenv does…

  • Provide support for specifying application-specific Ruby versions.
  • Let you change the global Ruby version on a per-user basis.
  • Allow you to override the Ruby version with an environment variable.

In contrast with RVM, rbenv does not…

  • Need to be loaded into your shell. Instead, rbenv's shim approach works by adding a directory to your $PATH.
  • Override shell commands like cd or require prompt hacks. That's dangerous and error-prone.
  • Have a configuration file. There's nothing to configure except which version of Ruby you want to use.
  • Install Ruby. You can build and install Ruby yourself, or use ruby-build to automate the process.
  • Manage gemsets. Bundler is a better way to manage application dependencies. If you have projects that are not yet using Bundler you can install the rbenv-gemset plugin.
  • Require changes to Ruby libraries for compatibility. The simplicity of rbenv means as long as it's in your $PATH, nothing else needs to know about it.

INSTALLATION

Install Homebrew http://brew.sh

Then:

$ brew update
$ brew install rbenv 
$ brew install rbenv ruby-build

# Add rbenv to bash so that it loads every time you open a terminal
echo 'if which rbenv > /dev/null; then eval "$(rbenv init -)"; fi' >> ~/.bash_profile
source ~/.bash_profile

UPDATE
There's one additional step after brew install rbenv Run rbenv init and add one line to .bash_profile as it states. After that reopen your terminal window […] SGI Sep 30 at 12:01 —https://stackoverflow.com/users/119770

$ rbenv install --list
Available versions:
 1.8.5-p113
 1.8.5-p114
 […]
 2.3.1
 2.4.0-dev
 jruby-1.5.6
 […]
$ rbenv install 2.3.1
[…]

Set the global version:

$ rbenv global 2.3.1
$ ruby -v
ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-darwin15]

Set the local version of your repo by adding .ruby-version to your repo's root dir:

$ cd ~/whatevs/projects/new_repo
$ echo "2.3.1" > .ruby-version

For MacOS visit this link

Easiest way to make lua script wait/pause/sleep/block for a few seconds?

You can use:

os.execute("sleep 1") -- I think you can do every command of CMD using os.execute("command")

or you can use:

function wait(waitTime)
    timer = os.time()
    repeat until os.time() > timer + waitTime
end

wait(YourNumberHere)

Get the height and width of the browser viewport without scrollbars using jquery?

Using jQuery ...

$(document).height() & $(window).height() will return the same values ... the key is to reset body's padding and margin so that you get no scrolling.

<!--

body {
    padding: 0px;
    margin: 0px;
    position: relative;
}

-->

Hope this helps.

How to specify function types for void (not Void) methods in Java8?

When you need to accept a function as argument which takes no arguments and returns no result (void), in my opinion it is still best to have something like

  public interface Thunk { void apply(); }

somewhere in your code. In my functional programming courses the word 'thunk' was used to describe such functions. Why it isn't in java.util.function is beyond my comprehension.

In other cases I find that even when java.util.function does have something that matches the signature I want - it still doesn't always feel right when the naming of the interface doesn't match the use of the function in my code. I guess it's a similar point that is made elsewhere here regarding 'Runnable' - which is a term associated with the Thread class - so while it may have he signature I need, it is still likely to confuse the reader.

replace \n and \r\n with <br /> in java

It works for me. The Java code works exactly as you wrote it. In the tester, the input string should be:

This is a string.
This is a long string.

...with a real linefeed. You can't use:

This is a string.\nThis is a long string.

...because it treats \n as the literal sequence backslash 'n'.

How to get 'System.Web.Http, Version=5.2.3.0?

In Package Manager Console

Install-Package Microsoft.AspNet.WebApi.Core -version 5.2.3

Git "error: The branch 'x' is not fully merged"

If you made a merge on Github and are seeing the error below. You need to pull (fetch and commit) the changes from the remote server before it will recognize the merge on your local. After doing this, Git will allow you to delete the branch without giving you the error.

error: The branch 'x' is not fully merged. If you are sure you want to delete it, run 'git branch -D 'x'.

Make hibernate ignore class variables that are not mapped

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

private String name;

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

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

Calling a javascript function in another js file

// module.js
export function hello() {
  return "Hello";
}

// main.js
import {hello} from 'module'; // or './module'
let val = hello(); // val is "Hello";

reference from https://hype.codes/how-include-js-file-another-js-file

Is there any way to kill a Thread?

As others have mentioned, the norm is to set a stop flag. For something lightweight (no subclassing of Thread, no global variable), a lambda callback is an option. (Note the parentheses in if stop().)

import threading
import time

def do_work(id, stop):
    print("I am thread", id)
    while True:
        print("I am thread {} doing something".format(id))
        if stop():
            print("  Exiting loop.")
            break
    print("Thread {}, signing off".format(id))


def main():
    stop_threads = False
    workers = []
    for id in range(0,3):
        tmp = threading.Thread(target=do_work, args=(id, lambda: stop_threads))
        workers.append(tmp)
        tmp.start()
    time.sleep(3)
    print('main: done sleeping; time to stop the threads.')
    stop_threads = True
    for worker in workers:
        worker.join()
    print('Finis.')

if __name__ == '__main__':
    main()

Replacing print() with a pr() function that always flushes (sys.stdout.flush()) may improve the precision of the shell output.

(Only tested on Windows/Eclipse/Python3.3)

How to make a progress bar

I used this progress bar. For more information on this you can go through this link i.e customization, coding etc.

<script type="text/javascript">

var myProgressBar = null
var timerId = null

function loadProgressBar(){
myProgressBar = new ProgressBar("my_progress_bar_1",{
    borderRadius: 10,
    width: 300,
    height: 20,
    maxValue: 100,
    labelText: "Loaded in {value,0} %",
    orientation: ProgressBar.Orientation.Horizontal,
    direction: ProgressBar.Direction.LeftToRight,
    animationStyle: ProgressBar.AnimationStyle.LeftToRight1,
    animationSpeed: 1.5,
    imageUrl: 'images/v_fg12.png',
    backgroundUrl: 'images/h_bg2.png',
    markerUrl: 'images/marker2.png'
});

timerId = window.setInterval(function() {
    if (myProgressBar.value >= myProgressBar.maxValue)
        myProgressBar.setValue(0);
    else
        myProgressBar.setValue(myProgressBar.value+1);

},
100);
}

loadProgressBar();
</script>

Hope this may be helpful to somenone.

python save image from url

It is the simplest way to download and save the image from internet using urlib.request package.

Here, you can simply pass the image URL(from where you want to download and save the image) and directory(where you want to save the download image locally, and give the image name with .jpg or .png) Here I given "local-filename.jpg" replace with this.

Python 3

import urllib.request
imgURL = "http://site.meishij.net/r/58/25/3568808/a3568808_142682562777944.jpg"

urllib.request.urlretrieve(imgURL, "D:/abc/image/local-filename.jpg")

You can download multiple images as well if you have all the image URLs from the internet. Just pass those image URLs in for loop, and the code automatically download the images from the internet.

Sending intent to BroadcastReceiver from adb

You need not specify receiver. You can use adb instead.

adb shell am broadcast -a com.whereismywifeserver.intent.TEST 
--es sms_body "test from adb"

For more arguments such as integer extras, see the documentation.

How do I convert ticks to minutes?

You can do this way :

TimeSpan duration = new TimeSpan(tickCount)
double minutes = duration.TotalMinutes;

Omitting all xsi and xsd namespaces when serializing an object in .NET?

After reading Microsoft's documentation and several solutions online, I have discovered the solution to this problem. It works with both the built-in XmlSerializer and custom XML serialization via IXmlSerialiazble.

To wit, I'll use the same MyTypeWithNamespaces XML sample that's been used in the answers to this question so far.

[XmlRoot("MyTypeWithNamespaces", Namespace="urn:Abracadabra", IsNullable=false)]
public class MyTypeWithNamespaces
{
    // As noted below, per Microsoft's documentation, if the class exposes a public
    // member of type XmlSerializerNamespaces decorated with the 
    // XmlNamespacesDeclarationAttribute, then the XmlSerializer will utilize those
    // namespaces during serialization.
    public MyTypeWithNamespaces( )
    {
        this._namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
            // Don't do this!! Microsoft's documentation explicitly says it's not supported.
            // It doesn't throw any exceptions, but in my testing, it didn't always work.

            // new XmlQualifiedName(string.Empty, string.Empty),  // And don't do this:
            // new XmlQualifiedName("", "")

            // DO THIS:
            new XmlQualifiedName(string.Empty, "urn:Abracadabra") // Default Namespace
            // Add any other namespaces, with prefixes, here.
        });
    }

    // If you have other constructors, make sure to call the default constructor.
    public MyTypeWithNamespaces(string label, int epoch) : this( )
    {
        this._label = label;
        this._epoch = epoch;
    }

    // An element with a declared namespace different than the namespace
    // of the enclosing type.
    [XmlElement(Namespace="urn:Whoohoo")]
    public string Label
    {
        get { return this._label; }
        set { this._label = value; }
    }
    private string _label;

    // An element whose tag will be the same name as the property name.
    // Also, this element will inherit the namespace of the enclosing type.
    public int Epoch
    {
        get { return this._epoch; }
        set { this._epoch = value; }
    }
    private int _epoch;

    // Per Microsoft's documentation, you can add some public member that
    // returns a XmlSerializerNamespaces object. They use a public field,
    // but that's sloppy. So I'll use a private backed-field with a public
    // getter property. Also, per the documentation, for this to work with
    // the XmlSerializer, decorate it with the XmlNamespaceDeclarations
    // attribute.
    [XmlNamespaceDeclarations]
    public XmlSerializerNamespaces Namespaces
    {
        get { return this._namespaces; }
    }
    private XmlSerializerNamespaces _namespaces;
}

That's all to this class. Now, some objected to having an XmlSerializerNamespaces object somewhere within their classes; but as you can see, I neatly tucked it away in the default constructor and exposed a public property to return the namespaces.

Now, when it comes time to serialize the class, you would use the following code:

MyTypeWithNamespaces myType = new MyTypeWithNamespaces("myLabel", 42);

/******
   OK, I just figured I could do this to make the code shorter, so I commented out the
   below and replaced it with what follows:

// You have to use this constructor in order for the root element to have the right namespaces.
// If you need to do custom serialization of inner objects, you can use a shortened constructor.
XmlSerializer xs = new XmlSerializer(typeof(MyTypeWithNamespaces), new XmlAttributeOverrides(),
    new Type[]{}, new XmlRootAttribute("MyTypeWithNamespaces"), "urn:Abracadabra");

******/
XmlSerializer xs = new XmlSerializer(typeof(MyTypeWithNamespaces),
    new XmlRootAttribute("MyTypeWithNamespaces") { Namespace="urn:Abracadabra" });

// I'll use a MemoryStream as my backing store.
MemoryStream ms = new MemoryStream();

// This is extra! If you want to change the settings for the XmlSerializer, you have to create
// a separate XmlWriterSettings object and use the XmlTextWriter.Create(...) factory method.
// So, in this case, I want to omit the XML declaration.
XmlWriterSettings xws = new XmlWriterSettings();
xws.OmitXmlDeclaration = true;
xws.Encoding = Encoding.UTF8; // This is probably the default
// You could use the XmlWriterSetting to set indenting and new line options, but the
// XmlTextWriter class has a much easier method to accomplish that.

// The factory method returns a XmlWriter, not a XmlTextWriter, so cast it.
XmlTextWriter xtw = (XmlTextWriter)XmlTextWriter.Create(ms, xws);
// Then we can set our indenting options (this is, of course, optional).
xtw.Formatting = Formatting.Indented;

// Now serialize our object.
xs.Serialize(xtw, myType, myType.Namespaces);

Once you have done this, you should get the following output:

<MyTypeWithNamespaces>
    <Label xmlns="urn:Whoohoo">myLabel</Label>
    <Epoch>42</Epoch>
</MyTypeWithNamespaces>

I have successfully used this method in a recent project with a deep hierachy of classes that are serialized to XML for web service calls. Microsoft's documentation is not very clear about what to do with the publicly accesible XmlSerializerNamespaces member once you've created it, and so many think it's useless. But by following their documentation and using it in the manner shown above, you can customize how the XmlSerializer generates XML for your classes without resorting to unsupported behavior or "rolling your own" serialization by implementing IXmlSerializable.

It is my hope that this answer will put to rest, once and for all, how to get rid of the standard xsi and xsd namespaces generated by the XmlSerializer.

UPDATE: I just want to make sure I answered the OP's question about removing all namespaces. My code above will work for this; let me show you how. Now, in the example above, you really can't get rid of all namespaces (because there are two namespaces in use). Somewhere in your XML document, you're going to need to have something like xmlns="urn:Abracadabra" xmlns:w="urn:Whoohoo. If the class in the example is part of a larger document, then somewhere above a namespace must be declared for either one of (or both) Abracadbra and Whoohoo. If not, then the element in one or both of the namespaces must be decorated with a prefix of some sort (you can't have two default namespaces, right?). So, for this example, Abracadabra is the defalt namespace. I could inside my MyTypeWithNamespaces class add a namespace prefix for the Whoohoo namespace like so:

public MyTypeWithNamespaces
{
    this._namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
        new XmlQualifiedName(string.Empty, "urn:Abracadabra"), // Default Namespace
        new XmlQualifiedName("w", "urn:Whoohoo")
    });
}

Now, in my class definition, I indicated that the <Label/> element is in the namespace "urn:Whoohoo", so I don't need to do anything further. When I now serialize the class using my above serialization code unchanged, this is the output:

<MyTypeWithNamespaces xmlns:w="urn:Whoohoo">
    <w:Label>myLabel</w:Label>
    <Epoch>42</Epoch>
</MyTypeWithNamespaces>

Because <Label> is in a different namespace from the rest of the document, it must, in someway, be "decorated" with a namespace. Notice that there are still no xsi and xsd namespaces.

Composer could not find a composer.json

I encountered the same error, and was able to solve it as follows:

  1. composer diagnose to see if something is wrong with the version of composer installed
  2. composer self-update to install the latest version
  3. composer update to update your composer.json file.

Python exit commands - why so many and when should each be used?

The functions* quit(), exit(), and sys.exit() function in the same way: they raise the SystemExit exception. So there is no real difference, except that sys.exit() is always available but exit() and quit() are only available if the site module is imported.

The os._exit() function is special, it exits immediately without calling any cleanup functions (it doesn't flush buffers, for example). This is designed for highly specialized use cases... basically, only in the child after an os.fork() call.

Conclusion

  • Use exit() or quit() in the REPL.

  • Use sys.exit() in scripts, or raise SystemExit() if you prefer.

  • Use os._exit() for child processes to exit after a call to os.fork().

All of these can be called without arguments, or you can specify the exit status, e.g., exit(1) or raise SystemExit(1) to exit with status 1. Note that portable programs are limited to exit status codes in the range 0-255, if you raise SystemExit(256) on many systems this will get truncated and your process will actually exit with status 0.

Footnotes

* Actually, quit() and exit() are callable instance objects, but I think it's okay to call them functions.

Ruby: character to ascii from a string

"a"[0]

or

?a

Both would return their ASCII equivalent.

How to access my localhost from another PC in LAN?

Actualy you don't need an internet connection to use ip address. Each computer in LAN has an internal IP address you can discover by runing

ipconfig /all

in cmd.

You can use the ip address of the server (probabily something like 192.168.0.x or 10.0.0.x) to access the website remotely.

If you found the ip and still cannot access the website, it means WAMP is not configured to respond to that name ( what did you call me? 192.168.0.3? That's not my name. I'm Localhost ) and you have to modify ....../apache/config/httpd.conf

Listen *:80

Escaping ampersand in URL

I would like to add a minor comment on Blender solution.

You can do the following:

var link = 'http://example.com?candy_name=' + encodeURIComponent('M&M');

That outputs:

http://example.com?candy_name=M%26M

The great thing about this it does not only work for & but for any especial character.

For instance:

var link = 'http://example.com?candy_name=' + encodeURIComponent('M&M?><')

Outputs:

"http://example.com?candy_name=M%26M%3F%3E%3C"

Sort tuples based on second parameter

    def findMaxSales(listoftuples):
        newlist = []
        tuple = ()
        for item in listoftuples:
             movie = item[0]
             value = (item[1])
             tuple = value, movie

             newlist += [tuple]
             newlist.sort()
             highest = newlist[-1]
             result = highest[1]
       return result

             movieList = [("Finding Dory", 486), ("Captain America: Civil                      

             War", 408), ("Deadpool", 363), ("Zootopia", 341), ("Rogue One", 529), ("The  Secret Life of Pets", 368), ("Batman v Superman", 330), ("Sing", 268), ("Suicide Squad", 325), ("The Jungle Book", 364)]
             print(findMaxSales(movieList))

output --> Rogue One

PHP header redirect 301 - what are the implications?

Just a tip: using http_response_code is much easier to remember than writing the full header:

http_response_code(301);
header('Location: /option-a'); 
exit;

Replacing NULL with 0 in a SQL server query

UPDATE TableName SET ColumnName= ISNULL(ColumnName, 0 ) WHERE Id = 10

<input type="file"> limit selectable files by extensions

Honestly, the best way to limit files is on the server side. People can spoof file type on the client so taking in the full file name at server transfer time, parsing out the file type, and then returning a message is usually the best bet.

Connect over ssh using a .pem file

For AWS if the user is ubuntu use the following to connect to remote server.

chmod 400 mykey.pem

ssh -i mykey.pem ubuntu@your-ip

How to execute raw SQL in Flask-SQLAlchemy app

Have you tried using connection.execute(text( <sql here> ), <bind params here> ) and bind parameters as described in the docs? This can help solve many parameter formatting and performance problems. Maybe the gateway error is a timeout? Bind parameters tend to make complex queries execute substantially faster.

Extracting text from HTML file using Python

Perl way (sorry mom, i'll never do it in production).

import re

def html2text(html):
    res = re.sub('<.*?>', ' ', html, flags=re.DOTALL | re.MULTILINE)
    res = re.sub('\n+', '\n', res)
    res = re.sub('\r+', '', res)
    res = re.sub('[\t ]+', ' ', res)
    res = re.sub('\t+', '\t', res)
    res = re.sub('(\n )+', '\n ', res)
    return res

How do I change db schema to dbo

I just posted this to a similar question: In sql server 2005, how do I change the "schema" of a table without losing any data?


A slight improvement to sAeid's excellent answer...

I added an exec to have this code self-execute, and I added a union at the top so that I could change the schema of both tables AND stored procedures:

DECLARE cursore CURSOR FOR 


select specific_schema as 'schema', specific_name AS 'name'
FROM INFORMATION_SCHEMA.routines
WHERE specific_schema <> 'dbo' 

UNION ALL

SELECT TABLE_SCHEMA AS 'schema', TABLE_NAME AS 'name'
FROM INFORMATION_SCHEMA.TABLES 
WHERE TABLE_SCHEMA <> 'dbo' 



DECLARE @schema sysname, 
 @tab sysname, 
 @sql varchar(500) 


OPEN cursore     
FETCH NEXT FROM cursore INTO @schema, @tab 

WHILE @@FETCH_STATUS = 0     
BEGIN 
 SET @sql = 'ALTER SCHEMA dbo TRANSFER [' + @schema + '].[' + @tab +']'    
 PRINT @sql   
 exec (@sql)  
 FETCH NEXT FROM cursore INTO @schema, @tab     
END 

CLOSE cursore     
DEALLOCATE cursore

I too had to restore a dbdump, and found that the schema wasn't dbo - I spent hours trying to get Sql Server management studio or visual studio data transfers to alter the destination schema... I ended up just running this against the restored dump on the new server to get things the way I wanted.

Call external javascript functions from java code

try {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("JavaScript");
        System.out.println("okay1");
        FileInputStream fileInputStream = new FileInputStream("C:/Users/Kushan/eclipse-workspace/sureson.lk/src/main/webapp/js/back_end_response.js");
        System.out.println("okay2");
        if (fileInputStream != null){
         BufferedReader reader = new BufferedReader(new InputStreamReader(fileInputStream));
         engine.eval(reader);
         System.out.println("okay3");
        // Invocable javascriptEngine = null;
         System.out.println("okay4");
        Invocable invocableEngine = (Invocable)engine;
         System.out.println("okay5");
         int x=0;
         System.out.println("invocableEngine is : "+invocableEngine);
         Object object = invocableEngine.invokeFunction("backend_message",x);

         System.out.println("okay6");
        }
        }catch(Exception e) {
            System.out.println("erroe when calling js function"+ e);
        }

ReactJS - Add custom event listener to component

I recommend using React.createRef() and ref=this.elementRef to get the DOM element reference instead of ReactDOM.findDOMNode(this). This way you can get the reference to the DOM element as an instance variable.

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

class MenuItem extends Component {

  constructor(props) {
    super(props);

    this.elementRef = React.createRef();
  }

  handleNVFocus = event => {
      console.log('Focused: ' + this.props.menuItem.caption.toUpperCase());
  }
    
  componentDidMount() {
    this.elementRef.addEventListener('nv-focus', this.handleNVFocus);
  }

  componentWillUnmount() {
    this.elementRef.removeEventListener('nv-focus', this.handleNVFocus);
  }

  render() {
    return (
      <element ref={this.elementRef} />
    )
  }

}

export default MenuItem;

Convert Python dictionary to JSON array

ensure_ascii=False really only defers the issue to the decoding stage:

>>> dict2 = {'LeafTemps': '\xff\xff\xff\xff',}
>>> json1 = json.dumps(dict2, ensure_ascii=False)
>>> print(json1)
{"LeafTemps": "????"}
>>> json.loads(json1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/json/__init__.py", line 328, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python2.7/json/decoder.py", line 365, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python2.7/json/decoder.py", line 381, in raw_decode
    obj, end = self.scan_once(s, idx)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xff in position 0: invalid start byte

Ultimately you can't store raw bytes in a JSON document, so you'll want to use some means of unambiguously encoding a sequence of arbitrary bytes as an ASCII string - such as base64.

>>> import json
>>> from base64 import b64encode, b64decode
>>> my_dict = {'LeafTemps': '\xff\xff\xff\xff',} 
>>> my_dict['LeafTemps'] = b64encode(my_dict['LeafTemps'])
>>> json.dumps(my_dict)
'{"LeafTemps": "/////w=="}'
>>> json.loads(json.dumps(my_dict))
{u'LeafTemps': u'/////w=='}
>>> new_dict = json.loads(json.dumps(my_dict))
>>> new_dict['LeafTemps'] = b64decode(new_dict['LeafTemps'])
>>> print new_dict
{u'LeafTemps': '\xff\xff\xff\xff'}

Why is my locally-created script not allowed to run under the RemoteSigned execution policy?

This is an IDE issue. Change the setting in the PowerShell GUI. Go to the Tools tab and select Options, and then Debugging options. Then check the box Turn off requirement for scripts to be signed. Done.

MVC4 Passing model from view to controller

I hope this complete example will help you.

This is the TaxiInfo class which holds information about a taxi ride:

namespace Taxi.Models
{
    public class TaxiInfo
    {
        public String Driver { get; set; }
        public Double Fare { get; set; }
        public Double Distance { get; set; }
        public String StartLocation { get; set; }
        public String EndLocation { get; set; }
    }
}

We also have a convenience model which holds a List of TaxiInfo(s):

namespace Taxi.Models
{
    public class TaxiInfoSet
    {
        public List<TaxiInfo> TaxiInfoList { get; set; }

        public TaxiInfoSet(params TaxiInfo[] TaxiInfos)
        {
            TaxiInfoList = new List<TaxiInfo>();

            foreach(var TaxiInfo in TaxiInfos)
            {
                TaxiInfoList.Add(TaxiInfo);
            }
        }
    }
}

Now in the home controller we have the default Index action which for this example makes two taxi drivers and adds them to the list contained in a TaxiInfo:

public ActionResult Index()
{
    var taxi1 = new TaxiInfo() { Fare = 20.2, Distance = 15, Driver = "Billy", StartLocation = "Perth", EndLocation = "Brisbane" };
    var taxi2 = new TaxiInfo() { Fare = 2339.2, Distance = 1500, Driver = "Smith", StartLocation = "Perth", EndLocation = "America" };

    return View(new TaxiInfoSet(taxi1,taxi2));
}

The code for the view is as follows:

@model Taxi.Models.TaxiInfoSet
@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

@foreach(var TaxiInfo in Model.TaxiInfoList){
    <form>
        <h1>Cost: [email protected]</h1>
        <h2>Distance: @(TaxiInfo.Distance) km</h2>
        <p>
            Our diver, @TaxiInfo.Driver will take you from @TaxiInfo.StartLocation to @TaxiInfo.EndLocation
        </p>
        @Html.ActionLink("Home","Booking",TaxiInfo)
    </form>
}

The ActionLink is responsible for the re-directing to the booking action of the Home controller (and passing in the appropriate TaxiInfo object) which is defiend as follows:

    public ActionResult Booking(TaxiInfo Taxi)
    {
        return View(Taxi);
    }

This returns a the following view:

@model Taxi.Models.TaxiInfo

@{
    ViewBag.Title = "Booking";
}

<h2>Booking For</h2>
<h1>@Model.Driver, going from @Model.StartLocation to @Model.EndLocation (a total of @Model.Distance km) for [email protected]</h1>

A visual tour:

The Index view

The Booking view

Count Vowels in String Python

Use a Counter

>>> from collections import Counter
>>> c = Counter('gallahad')
>>> print c
Counter({'a': 3, 'l': 2, 'h': 1, 'g': 1, 'd': 1})
>>> c['a']    # count of "a" characters
3

Counter is only available in Python 2.7+. A solution that should work on Python 2.5 would utilize defaultdict

>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> for c in s:
...     d[c] = d[c] + 1
... 
>>> print dict(d)
{'a': 3, 'h': 1, 'l': 2, 'g': 1, 'd': 1}

Oracle SQL Developer - tables cannot be seen

I have tried both the options suggested by Michael Munsey and works for me.

I wanted to provide another option to view the filtered tables. Mouse Right Click your table trees node and Select "Apply Filter" and check "Include Synonyms" check box and click Okay. That's it, you should be able to view the tables right there. It works for me.

Courtesy: http://www.thatjeffsmith.com/archive/2013/03/why-cant-i-see-my-tables-in-oracle-sql-developer/

How to create custom exceptions in Java?

To define a checked exception you create a subclass (or hierarchy of subclasses) of java.lang.Exception. For example:

public class FooException extends Exception {
  public FooException() { super(); }
  public FooException(String message) { super(message); }
  public FooException(String message, Throwable cause) { super(message, cause); }
  public FooException(Throwable cause) { super(cause); }
}

Methods that can potentially throw or propagate this exception must declare it:

public void calculate(int i) throws FooException, IOException;

... and code calling this method must either handle or propagate this exception (or both):

try {
  int i = 5;
  myObject.calculate(5);
} catch(FooException ex) {
  // Print error and terminate application.
  ex.printStackTrace();
  System.exit(1);
} catch(IOException ex) {
  // Rethrow as FooException.
  throw new FooException(ex);
}

You'll notice in the above example that IOException is caught and rethrown as FooException. This is a common technique used to encapsulate exceptions (typically when implementing an API).

Sometimes there will be situations where you don't want to force every method to declare your exception implementation in its throws clause. In this case you can create an unchecked exception. An unchecked exception is any exception that extends java.lang.RuntimeException (which itself is a subclass of java.lang.Exception):

public class FooRuntimeException extends RuntimeException {
  ...
}

Methods can throw or propagate FooRuntimeException exception without declaring it; e.g.

public void calculate(int i) {
  if (i < 0) {
    throw new FooRuntimeException("i < 0: " + i);
  }
}

Unchecked exceptions are typically used to denote a programmer error, for example passing an invalid argument to a method or attempting to breach an array index bounds.

The java.lang.Throwable class is the root of all errors and exceptions that can be thrown within Java. java.lang.Exception and java.lang.Error are both subclasses of Throwable. Anything that subclasses Throwable may be thrown or caught. However, it is typically bad practice to catch or throw Error as this is used to denote errors internal to the JVM that cannot usually be "handled" by the programmer (e.g. OutOfMemoryError). Likewise you should avoid catching Throwable, which could result in you catching Errors in addition to Exceptions.

How to replace multiple patterns at once with sed?

Maybe something like this:

sed 's/ab/~~/g; s/bc/ab/g; s/~~/bc/g'

Replace ~ with a character that you know won't be in the string.

Creating a folder if it does not exists - "Item already exists"

With New-Item you can add the Force parameter

New-Item -Force -ItemType directory -Path foo

Or the ErrorAction parameter

New-Item -ErrorAction Ignore -ItemType directory -Path foo

C#: How would I get the current time into a string?

DateTime.Now.ToString("h:mm tt")
DateTime.Now.ToString("MM/dd/yyyy")

Here are some common format strings

Set a variable if undefined in JavaScript

It seems to me, that for current javascript implementations,

var [result='default']=[possiblyUndefinedValue]

is a nice way to do this (using object deconstruction).

Code line wrapping - how to handle long lines

IMHO this is the best way to write your line :

private static final Map<Class<? extends Persistent>, PersistentHelper> class2helper =
        new HashMap<Class<? extends Persistent>, PersistentHelper>();

This way the increased indentation without any braces can help you to see that the code was just splited because the line was too long. And instead of 4 spaces, 8 will make it clearer.

The role of #ifdef and #ifndef

The code looks strange because the printf are not in any function blocks.

Where/how can I download (and install) the Microsoft.Jet.OLEDB.4.0 for Windows 8, 64 bit?

Make sure to target x86 on your project in Visual Studio. This should fix your trouble.

How to remove a package in sublime text 2

There are several answers, First IF you are using Package Control simply use Package Control's Remove Package command...

Ctrl+Shift+P

Package Control: Remove Package

If you installed the package manually, and are on a Windows machine...have no fear; Just modify the files manually.

First navigate to

C:\users\[Name]\AppData\Roaming\Sublime Text [version]\

There will be 4 directories:

  1. Installed Packages (Holds the Package Control config file, ignore)
  2. Packages (Holds Package source)
  3. Pristine Packages (Holds the versioning info, ignore)
  4. Settings (Sublime Setting Info, ignore)

First open ..\Packages folder and locate the folder named the same as your package; Delete it.

Secondly, open Sublime and navigate to the Preferences > Package Settings > Package Control > Settings-user

Third, locate the line where the package name you want to "uninstall"

{
    "installed_packages":
    [
        "Alignment",
        "All Autocomplete",
        "AngularJS",
        "AutoFileName",
        "BracketHighlighter",
        "Browser Support",
        "Case Conversion",
        "ColorPicker",
        "Emmet",
        "FileDiffs",
        "Format SQL",
        "Git",
        "Github Tools",
        "HTML-CSS-JS Prettify",
        "HTML5",
        "HTMLBeautify",
        "jQuery",
        "JsFormat",
        "JSHint",
        "JsMinifier",
        "LiveReload",
        "LoremIpsum",
        "LoremPixel",
        "Oracle PL SQL",
        "Package Control",
        "Placehold.it Image Tag Generator",
        "Placeholders",
        "Prefixr",
        "Search Stack Overflow",
        "SublimeAStyleFormatter",
        "SublimeCodeIntel",
        "Tag",
        "Theme - Centurion",
        "TortoiseSVN",
        "Zen Tabs"
    ]
}

NOTE Say the package you are removing is "Zen Tabs", you MUST also remove the , after "TortoiseSVN" or it will error.

Thus concludes the easiest way to remove or Install a Sublime Text Package.

How to use sed to replace only the first occurrence in a file?

i would do this with an awk script:

BEGIN {i=0}
(i==0) && /#include/ {print "#include \"newfile.h\""; i=1}
{print $0}    
END {}

then run it with awk:

awk -f awkscript headerfile.h > headerfilenew.h

might be sloppy, I'm new to this.

changing visibility using javascript

If you just want to display it when you get a response add this to your loadpage()

function loadpage(page_request, containerid){
   if (page_request.readyState == 4 && page_request.status==200) { 
      var container = document.getElementById(containerid);
      container.innerHTML=page_request.responseText;
      container.style.visibility = 'visible';
      // or 
      container.style.display = 'block';
}

but this depend entirely on how you hid the div in the first place

Event system in Python

Here is a minimal design that should work fine. What you have to do is to simply inherit Observer in a class and afterwards use observe(event_name, callback_fn) to listen for a specific event. Whenever that specific event is fired anywhere in the code (ie. Event('USB connected')), the corresponding callback will fire.

class Observer():
    _observers = []
    def __init__(self):
        self._observers.append(self)
        self._observed_events = []
    def observe(self, event_name, callback_fn):
        self._observed_events.append({'event_name' : event_name, 'callback_fn' : callback_fn})


class Event():
    def __init__(self, event_name, *callback_args):
        for observer in Observer._observers:
            for observable in observer._observed_events:
                if observable['event_name'] == event_name:
                    observable['callback_fn'](*callback_args)

Example:

class Room(Observer):
    def __init__(self):
        print("Room is ready.")
        Observer.__init__(self) # DON'T FORGET THIS
    def someone_arrived(self, who):
        print(who + " has arrived!")

# Observe for specific event
room = Room()
room.observe('someone arrived',  room.someone_arrived)

# Fire some events
Event('someone left',    'John')
Event('someone arrived', 'Lenard') # will output "Lenard has arrived!"
Event('someone Farted',  'Lenard')

Git push hangs when pushing to Github?

Will usually see myself running into this problem when pushing a large quantity of files.

If you can be patient and let the files finishing uploading, you might not need to do anything at all. Good luck –

How to create a GUID / UUID

broofa's answer is pretty slick, indeed - impressively clever, really... rfc4122 compliant, somewhat readable, and compact. Awesome!

But if you're looking at that regular expression, those many replace() callbacks, toString()'s and Math.random() function calls (where he's only using 4 bits of the result and wasting the rest), you may start to wonder about performance. Indeed, joelpt even decided to toss out RFC for generic GUID speed with generateQuickGUID.

But, can we get speed and RFC compliance? I say, YES! Can we maintain readability? Well... Not really, but it's easy if you follow along.

But first, my results, compared to broofa, guid (the accepted answer), and the non-rfc-compliant generateQuickGuid:

                  Desktop   Android
           broofa: 1617ms   12869ms
               e1:  636ms    5778ms
               e2:  606ms    4754ms
               e3:  364ms    3003ms
               e4:  329ms    2015ms
               e5:  147ms    1156ms
               e6:  146ms    1035ms
               e7:  105ms     726ms
             guid:  962ms   10762ms
generateQuickGuid:  292ms    2961ms
  - Note: 500k iterations, results will vary by browser/cpu.

So by my 6th iteration of optimizations, I beat the most popular answer by over 12X, the accepted answer by over 9X, and the fast-non-compliant answer by 2-3X. And I'm still rfc4122 compliant.

Interested in how? I've put the full source on http://jsfiddle.net/jcward/7hyaC/3/ and on http://jsperf.com/uuid-generator-opt/4

For an explanation, let's start with broofa's code:

_x000D_
_x000D_
function broofa() {_x000D_
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {_x000D_
        var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);_x000D_
        return v.toString(16);_x000D_
    });_x000D_
}_x000D_
_x000D_
console.log(broofa())
_x000D_
_x000D_
_x000D_

So it replaces x with any random hex digit, y with random data (except forcing the top 2 bits to 10 per the RFC spec), and the regex doesn't match the - or 4 characters, so he doesn't have to deal with them. Very, very slick.

The first thing to know is that function calls are expensive, as are regular expressions (though he only uses 1, it has 32 callbacks, one for each match, and in each of the 32 callbacks it calls Math.random() and v.toString(16)).

The first step toward performance is to eliminate the RegEx and its callback functions and use a simple loop instead. This means we have to deal with the - and 4 characters whereas broofa did not. Also, note that we can use String Array indexing to keep his slick String template architecture:

_x000D_
_x000D_
function e1() {_x000D_
    var u='',i=0;_x000D_
    while(i++<36) {_x000D_
        var c='xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'[i-1],r=Math.random()*16|0,v=c=='x'?r:(r&0x3|0x8);_x000D_
        u+=(c=='-'||c=='4')?c:v.toString(16)_x000D_
    }_x000D_
    return u;_x000D_
}_x000D_
_x000D_
console.log(e1())
_x000D_
_x000D_
_x000D_

Basically, the same inner logic, except we check for - or 4, and using a while loop (instead of replace() callbacks) gets us an almost 3X improvement!

The next step is a small one on the desktop but makes a decent difference on mobile. Let's make fewer Math.random() calls and utilize all those random bits instead of throwing 87% of them away with a random buffer that gets shifted out each iteration. Let's also move that template definition out of the loop, just in case it helps:

_x000D_
_x000D_
function e2() {_x000D_
    var u='',m='xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx',i=0,rb=Math.random()*0xffffffff|0;_x000D_
    while(i++<36) {_x000D_
        var c=m[i-1],r=rb&0xf,v=c=='x'?r:(r&0x3|0x8);_x000D_
        u+=(c=='-'||c=='4')?c:v.toString(16);rb=i%8==0?Math.random()*0xffffffff|0:rb>>4_x000D_
    }_x000D_
    return u_x000D_
}_x000D_
_x000D_
console.log(e2())
_x000D_
_x000D_
_x000D_

This saves us 10-30% depending on platform. Not bad. But the next big step gets rid of the toString function calls altogether with an optimization classic - the look-up table. A simple 16-element lookup table will perform the job of toString(16) in much less time:

_x000D_
_x000D_
function e3() {_x000D_
    var h='0123456789abcdef';_x000D_
    var k='xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx';_x000D_
    /* same as e4() below */_x000D_
}_x000D_
function e4() {_x000D_
    var h=['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'];_x000D_
    var k=['x','x','x','x','x','x','x','x','-','x','x','x','x','-','4','x','x','x','-','y','x','x','x','-','x','x','x','x','x','x','x','x','x','x','x','x'];_x000D_
    var u='',i=0,rb=Math.random()*0xffffffff|0;_x000D_
    while(i++<36) {_x000D_
        var c=k[i-1],r=rb&0xf,v=c=='x'?r:(r&0x3|0x8);_x000D_
        u+=(c=='-'||c=='4')?c:h[v];rb=i%8==0?Math.random()*0xffffffff|0:rb>>4_x000D_
    }_x000D_
    return u_x000D_
}_x000D_
_x000D_
console.log(e4())
_x000D_
_x000D_
_x000D_

The next optimization is another classic. Since we're only handling 4-bits of output in each loop iteration, let's cut the number of loops in half and process 8-bits each iteration. This is tricky since we still have to handle the RFC compliant bit positions, but it's not too hard. We then have to make a larger lookup table (16x16, or 256) to store 0x00 - 0xff, and we build it only once, outside the e5() function.

_x000D_
_x000D_
var lut = []; for (var i=0; i<256; i++) { lut[i] = (i<16?'0':'')+(i).toString(16); }_x000D_
function e5() {_x000D_
    var k=['x','x','x','x','-','x','x','-','4','x','-','y','x','-','x','x','x','x','x','x'];_x000D_
    var u='',i=0,rb=Math.random()*0xffffffff|0;_x000D_
    while(i++<20) {_x000D_
        var c=k[i-1],r=rb&0xff,v=c=='x'?r:(c=='y'?(r&0x3f|0x80):(r&0xf|0x40));_x000D_
        u+=(c=='-')?c:lut[v];rb=i%4==0?Math.random()*0xffffffff|0:rb>>8_x000D_
    }_x000D_
    return u_x000D_
}_x000D_
_x000D_
console.log(e5())
_x000D_
_x000D_
_x000D_

I tried an e6() that processes 16-bits at a time, still using the 256-element LUT, and it showed the diminishing returns of optimization. Though it had fewer iterations, the inner logic was complicated by the increased processing, and it performed the same on desktop, and only ~10% faster on mobile.

The final optimization technique to apply - unroll the loop. Since we're looping a fixed number of times, we can technically write this all out by hand. I tried this once with a single random variable r that I kept re-assigning, and performance tanked. But with four variables assigned random data up front, then using the lookup table, and applying the proper RFC bits, this version smokes them all:

_x000D_
_x000D_
var lut = []; for (var i=0; i<256; i++) { lut[i] = (i<16?'0':'')+(i).toString(16); }_x000D_
function e7()_x000D_
{_x000D_
    var d0 = Math.random()*0xffffffff|0;_x000D_
    var d1 = Math.random()*0xffffffff|0;_x000D_
    var d2 = Math.random()*0xffffffff|0;_x000D_
    var d3 = Math.random()*0xffffffff|0;_x000D_
    return lut[d0&0xff]+lut[d0>>8&0xff]+lut[d0>>16&0xff]+lut[d0>>24&0xff]+'-'+_x000D_
    lut[d1&0xff]+lut[d1>>8&0xff]+'-'+lut[d1>>16&0x0f|0x40]+lut[d1>>24&0xff]+'-'+_x000D_
    lut[d2&0x3f|0x80]+lut[d2>>8&0xff]+'-'+lut[d2>>16&0xff]+lut[d2>>24&0xff]+_x000D_
    lut[d3&0xff]+lut[d3>>8&0xff]+lut[d3>>16&0xff]+lut[d3>>24&0xff];_x000D_
}_x000D_
_x000D_
console.log(e7())
_x000D_
_x000D_
_x000D_

Modualized: http://jcward.com/UUID.js - UUID.generate()

The funny thing is, generating 16 bytes of random data is the easy part. The whole trick is expressing it in String format with RFC compliance, and it's most tightly accomplished with 16 bytes of random data, an unrolled loop and lookup table.

I hope my logic is correct -- it's very easy to make a mistake in this kind of tedious bit-work. But the outputs look good to me. I hope you enjoyed this mad ride through code optimization!

Be advised: my primary goal was to show and teach potential optimization strategies. Other answers cover important topics such as collisions and truly random numbers, which are important for generating good UUIDs.

How to use bootstrap-theme.css with bootstrap 3?

For an example of the css styles have a look at: http://getbootstrap.com/examples/theme/

If you want to see how the example looks without the bootstrap-theme.css file open up your browser developer tools and delete the link from the <head> of the example and then you can compare it.

I know this is an old question but posted it just in case anyone is looking for an example of how it looks like I was.

Update

bootstrap.css = main css framework (grids, basic styles, etc)

bootstrap-theme.css = extended styling (3D buttons, gradients etc). This file is optional and does not effect the functionality of bootstrap at all, it only enhances the appearance.

Update 2

With the release of v3.2.0 Bootstrap have added an option to view the theme css on the doc pages. If you go to one of the doc pages (css, components, javascript) you should see a "Preview theme" link at the bottom of the side nav which you can use to turn the theme css on and off.

how to load CSS file into jsp

You can write like that. This is for whenever you change context path you don't need to modify your jsp file.

<link rel="stylesheet" href="${pageContext.request.contextPath}/css/styles.css" />

Getting Textarea Value with jQuery

change id="#message" to id="message" on your textarea element.

and by the way, just use this:

$('#send-thoughts')

remember that you should only use ID's once and you can use classes over and over.

https://css-tricks.com/the-difference-between-id-and-class/

Swift programmatically navigate to another view controller/scene

So If you present a view controller it will not show in navigation controller. It will just take complete screen. For this case you have to create another navigation controller and add your nextViewController as root for this and present this new navigationController.

Another way is to just push the view controller.

self.presentViewController(nextViewController, animated:true, completion:nil)

For more info check Apple documentation:- https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIViewController_Class/#//apple_ref/doc/uid/TP40006926-CH3-SW96

Pipe to/from the clipboard in Bash script

xsel on Debian/Ubuntu/Mint

# append to clipboard:
cat 'the file with content' | xsel -ib

# or type in the happy face :) and ...
echo 'the happy face :) and content' | xsel -ib

# show clipboard
xsel -b

# Get more info:
man xsel

Install

sudo apt-get install xsel

How to install plugin for Eclipse from .zip

To install the plug-in, unzip the file into the Eclipse installation directory (or the plug-in directory depending on how the plug-in is packaged). The plug-in will not appear until you have restarted your workspace (Reboot Eclipse).

How to unzip gz file using Python

from sh import gunzip

gunzip('/tmp/file1.gz')

Using only CSS, show div on hover over <a>

This answer doesn't require that you know the what type of display (inline, etc.) the hideable element is supposed to be when being shown:

_x000D_
_x000D_
.hoverable:not(:hover) + .show-on-hover {_x000D_
    display: none;_x000D_
}
_x000D_
<a class="hoverable">Hover over me!</a>_x000D_
<div class="show-on-hover">I'm a block element.</div>_x000D_
_x000D_
<hr />_x000D_
_x000D_
<a class="hoverable">Hover over me also!</a>_x000D_
<span class="show-on-hover">I'm an inline element.</span>
_x000D_
_x000D_
_x000D_

This uses the adjacent sibling selector and the not selector.

Spring MVC - Why not able to use @RequestBody and @RequestParam together

You could also just change the @RequestParam default required status to false so that HTTP response status code 400 is not generated. This will allow you to place the Annotations in any order you feel like.

@RequestParam(required = false)String name

WARNING: API 'variant.getJavaCompile()' is obsolete and has been replaced with 'variant.getJavaCompileProvider()'

keep you Project(not app) Build.gradle dependncies classpath version code is new

 dependencies {
    classpath 'com.android.tools.build:gradle:3.5.0-beta01'
    classpath 'com.novoda:bintray-release:0.8.1'
    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}

How do I get the directory that a program is running from?

For Windows system at console you can use system(dir) command. And console gives you information about directory and etc. Read about the dir command at cmd. But for Unix-like systems, I don't know... If this command is run, read bash command. ls does not display directory...

Example:

int main()
{
    system("dir");
    system("pause"); //this wait for Enter-key-press;
    return 0;
}

Docker official registry (Docker Hub) URL

It's just docker pull busybox, are you using an up to date version of the docker client. I think they stopped supporting clients lower than 1.5.

Incidentally that curl works for me:

$ curl -k https://registry.hub.docker.com/v1/repositories/busybox/tags
[{"layer": "fc0db02f", "name": "latest"}, {"layer": "fc0db02f", "name": "1"}, {"layer": "a6dbc8d6", "name": "1-ubuntu"}, {"layer": "a6dbc8d6", "name": "1.21-ubuntu"}, {"layer": "a6dbc8d6", "name": "1.21.0-ubuntu"}, {"layer": "d7057cb0", "name": "1.23"}, {"layer": "d7057cb0", "name": "1.23.2"}, {"layer": "fc0db02f", "name": "1.24"}, {"layer": "3d5bcd78", "name": "1.24.0"}, {"layer": "fc0db02f", "name": "1.24.1"}, {"layer": "1c677c87", "name": "buildroot-2013.08.1"}, {"layer": "0f864637", "name": "buildroot-2014.02"}, {"layer": "a6dbc8d6", "name": "ubuntu"}, {"layer": "ff8f955d", "name": "ubuntu-12.04"}, {"layer": "633fcd11", "name": "ubuntu-14.04"}]

Interesting enough if you sniff the headers you get a HTTP 405 (Method not allowed). I think this might be to do with the fact that Docker have deprecated their Registry API.

How to list the tables in a SQLite database file that was opened with ATTACH?

To list the tables you can also do:

SELECT name FROM sqlite_master
WHERE type='table';

Load local javascript file in chrome for testing?

If you still need to do this, I ran across the same problem. Somehow, EDGE renders all the scripts even if they are not via HTTP, HTTPS etc... Open the html/js file directly from the filesystem with Edge, and it will work.

How can I send and receive WebSocket messages on the server side?

C++ Implementation (not by me) here. Note that when your bytes are over 65535, you need to shift with a long value as shown here.

Python: Get the first character of the first string in a list?

You almost had it right. The simplest way is

mylist[0][0]   # get the first character from the first item in the list

but

mylist[0][:1]  # get up to the first character in the first item in the list

would also work.

You want to end after the first character (character zero), not start after the first character (character zero), which is what the code in your question means.

Something better than .NET Reflector?

In my opinion, there are three serious alternatives to keep an eye on, all of which are free:

  • ILSpy: This is from the same people who make the (also free) SharpDevelop IDE. As well as being free, it is also open source. An additional extension they are working on is the ability to debug decompiled code (something which the pro version of Reflector can do), which works surprisingly well.
  • JustDecompile: A standalone decompiler from Telerik (announced today, currently in Beta).
  • dotPeek: A standalone decompiler from JetBrains (available standalone as part of an EAP at the moment).

All of these approach the problem in slightly different ways with differing UIs. I would suggest giving them all a try and seeing which one you prefer.

How to break long string to multiple lines

You cannot use the VB line-continuation character inside of a string.

SqlQueryString = "Insert into Employee values(" & txtEmployeeNo.Value & _
"','" & txtContractStartDate.Value &  _
"','" & txtSeatNo.Value & _
"','" & txtFloor.Value & "','" & txtLeaves.Value & "')"

Escape a string in SQL Server so that it is safe to use in LIKE expression

Alternative escaping syntax:

LIKE Wildcard Literals

The JDBC driver supports the {escape 'escape character'} syntax for using LIKE clause wildcards as literals.

SELECT *
FROM tab
WHERE col LIKE 'a\_c' {escape '\'};

db<>fiddle demo

Passing parameter via url to sql server reporting service

http://desktop-qr277sp/Reports01/report/Reports/reportName?Log%In%Name=serverUsername&paramName=value

Pass parameter to the report with server authentication

How can I quickly sum all numbers in a file?

Another option is to use jq:

$ seq 10|jq -s add
55

-s (--slurp) reads the input lines into an array.

Read file from line 2 or skip header row

If slicing could work on iterators...

from itertools import islice
with open(fname) as f:
    for line in islice(f, 1, None):
        pass

How to change the text color of first select option

For Option 1 used as the placeholder:

select:invalid { color:grey; }

All other options:

select:valid { color:black; }

Configure Log4Net in web application

I also had the similar issue. Logs were not creating.

Please check logger attribute name should match with your LogManager.GetLogger("name")

<logger name="Mylog">
      <level value="All"></level>
      <appender-ref ref="RollingLogFileAppender" />
    </logger>



private static readonly ILog Log = LogManager.GetLogger("Mylog");

Session TimeOut in web.xml

you can declare time in two ways for this problem..

1) either give too long time that your file reading is complete in between that time.

<session-config>
    <session-timeout> 1000 </session-timeout>
</session-config>

2)declare time which is never expires your session.

<session-config>
    <session-timeout>-1</session-timeout>
</session-config>

UDP vs TCP, how much faster is it?

When speaking of "what is faster" - there are at least two very different aspects: throughput and latency.

If speaking about throughput - TCP's flow control (as mentioned in other answers), is extremely important and doing anything comparable over UDP, while certainly possible, would be a Big Headache(tm). As a result - using UDP when you need throughput, rarely qualifies as a good idea (unless you want to get an unfair advantage over TCP).

However, if speaking about latencies - the whole thing is completely different. While in the absence of packet loss TCP and UDP behave extremely similar (any differences, if any, being marginal) - after the packet is lost, the whole pattern changes drastically.

After any packet loss, TCP will wait for retransmit for at least 200ms (1sec per paragraph 2.4 of RFC6298, but practical modern implementations tend to reduce it to 200ms). Moreover, with TCP, even those packets which did reach destination host - will not be delivered to your app until the missing packet is received (i.e., the whole communication is delayed by ~200ms) - BTW, this effect, known as Head-of-Line Blocking, is inherent to all reliable ordered streams, whether TCP or reliable+ordered UDP. To make things even worse - if the retransmitted packet is also lost, then we'll be speaking about delay of ~600ms (due to so-called exponential backoff, 1st retransmit is 200ms, and second one is 200*2=400ms). If our channel has 1% packet loss (which is not bad by today's standards), and we have a game with 20 updates per second - such 600ms delays will occur on average every 8 minutes. And as 600ms is more than enough to get you killed in a fast-paced game - well, it is pretty bad for gameplay. These effects are exactly why gamedevs often prefer UDP over TCP.

However, when using UDP to reduce latencies - it is important to realize that merely "using UDP" is not sufficient to get substantial latency improvement, it is all about HOW you're using UDP. In particular, while RUDP libraries usually avoid that "exponential backoff" and use shorter retransmit times - if they are used as a "reliable ordered" stream, they still have to suffer from Head-of-Line Blocking (so in case of a double packet loss, instead of that 600ms we'll get about 1.5*2*RTT - or for a pretty good 80ms RTT, it is a ~250ms delay, which is an improvement, but it is still possible to do better). On the other hand, if using techniques discussed in http://gafferongames.com/networked-physics/snapshot-compression/ and/or http://ithare.com/udp-from-mog-perspective/#low-latency-compression , it IS possible to eliminate Head-of-Line blocking entirely (so for a double-packet loss for a game with 20 updates/second, the delay will be 100ms regardless of RTT).

And as a side note - if you happen to have access only to TCP but no UDP (such as in browser, or if your client is behind one of 6-9% of ugly firewalls blocking UDP) - there seems to be a way to implement UDP-over-TCP without incurring too much latencies, see here: http://ithare.com/almost-zero-additional-latency-udp-over-tcp/ (make sure to read comments too(!)).

How to insert newline in string literal?

Well, simple options are:

  • string.Format:

    string x = string.Format("first line{0}second line", Environment.NewLine);
    
  • String concatenation:

    string x = "first line" + Environment.NewLine + "second line";
    
  • String interpolation (in C#6 and above):

    string x = $"first line{Environment.NewLine}second line";
    

You could also use \n everywhere, and replace:

string x = "first line\nsecond line\nthird line".Replace("\n",
                                                         Environment.NewLine);

Note that you can't make this a string constant, because the value of Environment.NewLine will only be available at execution time.

How to return a struct from a function in C++?

Here is an edited version of your code which is based on ISO C++ and which works well with G++:

#include <string.h>
#include <iostream>
using namespace std;

#define NO_OF_TEST 1

struct studentType {
    string studentID;
    string firstName;
    string lastName;
    string subjectName;
    string courseGrade;
    int arrayMarks[4];
    double avgMarks;
};

studentType input() {
    studentType newStudent;
    cout << "\nPlease enter student information:\n";

    cout << "\nFirst Name: ";
    cin >> newStudent.firstName;

    cout << "\nLast Name: ";
    cin >> newStudent.lastName;

    cout << "\nStudent ID: ";
    cin >> newStudent.studentID;

    cout << "\nSubject Name: ";
    cin >> newStudent.subjectName;

    for (int i = 0; i < NO_OF_TEST; i++) {
        cout << "\nTest " << i+1 << " mark: ";
        cin >> newStudent.arrayMarks[i];
    }

    return newStudent;
}

int main() {
    studentType s;
    s = input();

    cout <<"\n========"<< endl << "Collected the details of "
        << s.firstName << endl;

    return 0;
}

How to check if a json key exists?

JSONObject class has a method named "has":

http://developer.android.com/reference/org/json/JSONObject.html#has(java.lang.String)

Returns true if this object has a mapping for name. The mapping may be NULL.

Exit codes in Python

You're looking for calls to sys.exit() in the script. The argument to that method is returned to the environment as the exit code.

It's fairly likely that the script is never calling the exit method, and that 0 is the default exit code.

trigger body click with jQuery

You should have something like this:

$('body').click(function() {
   // do something here
});

The callback function will be called when the user clicks somewhere on the web page. You can trigger the callback programmatically with:

$('body').trigger('click');

_DEBUG vs NDEBUG

Visual Studio defines _DEBUG when you specify the /MTd or /MDd option, NDEBUG disables standard-C assertions. Use them when appropriate, ie _DEBUG if you want your debugging code to be consistent with the MS CRT debugging techniques and NDEBUG if you want to be consistent with assert().

If you define your own debugging macros (and you don't hack the compiler or C runtime), avoid starting names with an underscore, as these are reserved.

What should be the package name of android app?

Visit https://developers.google.com/mobile/add and try to fill "Android package name". In some cases it can write error: "Invalid Android package name".

In https://developer.android.com/studio/build/application-id.html it is written:

And although the application ID looks like a traditional Java package name, the naming rules for the application ID are a bit more restrictive:

  • It must have at least two segments (one or more dots).
  • Each segment must start with a letter.
  • All characters must be alphanumeric or an underscore [a-zA-Z0-9_].

So, "0com.example.app" and "com.1example.app" are errors.

adding directory to sys.path /PYTHONPATH

This is working as documented. Any paths specified in PYTHONPATH are documented as normally coming after the working directory but before the standard interpreter-supplied paths. sys.path.append() appends to the existing path. See here and here. If you want a particular directory to come first, simply insert it at the head of sys.path:

import sys
sys.path.insert(0,'/path/to/mod_directory')

That said, there are usually better ways to manage imports than either using PYTHONPATH or manipulating sys.path directly. See, for example, the answers to this question.

How to convert a column of DataTable to a List

I do just like below, after you set your column AsEnumarable you can sort, order or how you want.

 _dataTable.AsEnumerable().Select(p => p.Field<string>("ColumnName")).ToList();

How to SFTP with PHP?

I found that "phpseclib" should help you with this (SFTP and many more features). http://phpseclib.sourceforge.net/

To Put the file to the server, simply call (Code example from http://phpseclib.sourceforge.net/sftp/examples.html#put)

<?php
include('Net/SFTP.php');

$sftp = new Net_SFTP('www.domain.tld');
if (!$sftp->login('username', 'password')) {
    exit('Login Failed');
}

// puts a three-byte file named filename.remote on the SFTP server
$sftp->put('filename.remote', 'xxx');
// puts an x-byte file named filename.remote on the SFTP server,
// where x is the size of filename.local
$sftp->put('filename.remote', 'filename.local', NET_SFTP_LOCAL_FILE);

npm install hangs

I was having the same problem. I tried a

npm config set registry http://registry.npmjs.org/

to turn off https. I also tried

npm set progress=false 

to turn off the progress bar (it has been reported to slow down downloads).

The problem was with my network driver. I just needed to reboot and the lag went away.

How do I convert a numpy array to (and display) an image?

this could be a possible code solution:

from skimage import io
import numpy as np
data=np.random.randn(5,2)
io.imshow(data)

How can I access global variable inside class in Python

I understand using a global variable is sometimes the most convenient thing to do, especially in cases where usage of class makes the easiest thing so much harder (e.g., multiprocessing). I ran into the same problem with declaring global variables and figured it out with some experiments.

The reason that g_c was not changed by the run function within your class is that the referencing to the global name within g_c was not established precisely within the function. The way Python handles global declaration is in fact quite tricky. The command global g_c has two effects:

  1. Preconditions the entrance of the key "g_c" into the dictionary accessible by the built-in function, globals(). However, the key will not appear in the dictionary until after a value is assigned to it.

  2. (Potentially) alters the way Python looks for the variable g_c within the current method.

The full understanding of (2) is particularly complex. First of all, it only potentially alters, because if no assignment to the name g_c occurs within the method, then Python defaults to searching for it among the globals(). This is actually a fairly common thing, as is the case of referencing within a method modules that are imported all the way at the beginning of the code.

However, if an assignment command occurs anywhere within the method, Python defaults to finding the name g_c within local variables. This is true even when a referencing occurs before an actual assignment, which will lead to the classic error:

UnboundLocalError: local variable 'g_c' referenced before assignment

Now, if the declaration global g_c occurs anywhere within the method, even after any referencing or assignment, then Python defaults to finding the name g_c within global variables. However, if you are feeling experimentative and place the declaration after a reference, you will be rewarded with a warning:

SyntaxWarning: name 'g_c' is used prior to global declaration

If you think about it, the way the global declaration works in Python is clearly woven into and consistent with how Python normally works. It's just when you actually want a global variable to work, the norm becomes annoying.

Here is a code that summarizes what I just said (with a few more observations):

g_c = 0
print ("Initial value of g_c: " + str(g_c))
print("Variable defined outside of method automatically global? "
      + str("g_c" in globals()))

class TestClass():
    def direct_print(self):
        print("Directly printing g_c without declaration or modification: "
              + str(g_c))
        #Without any local reference to the name
        #Python defaults to search for the variable in globals()
        #This of course happens for all the module names you import

    def mod_without_dec(self):
        g_c = 1
        #A local assignment without declaring reference to global variable
        #makes Python default to access local name
        print ("After mod_without_dec, local g_c=" + str(g_c))
        print ("After mod_without_dec, global g_c=" + str(globals()["g_c"]))


    def mod_with_late_dec(self):
        g_c = 2
        #Even with a late declaration, the global variable is accessed
        #However, a syntax warning will be issued
        global g_c
        print ("After mod_with_late_dec, local g_c=" + str(g_c))
        print ("After mod_with_late_dec, global g_c=" + str(globals()["g_c"]))

    def mod_without_dec_error(self):
        try:
            print("This is g_c" + str(g_c))
        except:
            print("Error occured while accessing g_c")
            #If you try to access g_c without declaring it global
            #but within the method you also alter it at some point
            #then Python will not search for the name in globals()
            #!!!!!Even if the assignment command occurs later!!!!!
        g_c = 3

    def sound_practice(self):
        global g_c
        #With correct declaration within the method
        #The local name g_c becomes an alias for globals()["g_c"]
        g_c = 4
        print("In sound_practice, the name g_c points to: " + str(g_c))


t = TestClass()
t.direct_print()
t.mod_without_dec()
t.mod_with_late_dec()
t.mod_without_dec_error()
t.sound_practice()

How to add time to DateTime in SQL

You can do:

SELECT GETDATE()+'03:30:00'

Notepad++: Multiple words search in a file (may be in different lines)?

If you are using Notepad++ editor (like the tag of the question suggests), you can use the great "Find in Files" functionality.

Go to SearchFind in Files (Ctrl+Shift+F for the keyboard addicted) and enter:

  • Find What = (cat|town)

  • Filters = *.txt

  • Directory = enter the path of the directory you want to search in. You can check Follow current doc. to have the path of the current file to be filled.

  • Search mode = Regular Expression

Use grep to report back only line numbers

using only grep:

grep -n "text to find" file.ext | grep -Po '^[^:]+'

How to Get a Layout Inflater Given a Context?

You can also use this code to get LayoutInflater:

LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)

Fix CSS hover on iPhone/iPad/iPod

I"m not sure if this will have a huge impact on performance but this has done the trick for me in the past:

var mobileHover = function () {
    $('*').on('touchstart', function () {
        $(this).trigger('hover');
    }).on('touchend', function () {
        $(this).trigger('hover');
    });
};

mobileHover();

"Fade" borders in CSS

Add this class css to your style sheet

.border_gradient {
border: 8px solid #000;
-moz-border-bottom-colors:#897048 #917953 #a18a66 #b6a488 #c5b59b #d4c5ae #e2d6c4 #eae1d2;
-moz-border-top-colors:#897048 #917953 #a18a66 #b6a488 #c5b59b #d4c5ae #e2d6c4 #eae1d2;
-moz-border-left-colors:#897048 #917953 #a18a66 #b6a488 #c5b59b #d4c5ae #e2d6c4 #eae1d2;
-moz-border-right-colors:#897048 #917953 #a18a66 #b6a488 #c5b59b #d4c5ae #e2d6c4 #eae1d2;
padding: 5px 5px 5px 15px;
width: 300px;
}

set width to the width of your image. and use this html for image

<div class="border_gradient">
        <img src="image.png" />
</div>

though it may not give the same exact border, it will some gradient looks on the border.

source: CSS3 Borders

Singleton in Android

You are copying singleton's customVar into a singletonVar variable and changing that variable does not affect the original value in singleton.

// This does not update singleton variable
// It just assigns value of your local variable
Log.d("Test",singletonVar);
singletonVar="World";
Log.d("Test",singletonVar);

// This actually assigns value of variable in singleton
Singleton.customVar = singletonVar;

How to pass parameters to a partial view in ASP.NET MVC?

Just:

@Html.Partial("PartialName", Model);

Unit testing void methods?

Presumably the method does something, and doesn't simply return?

Assuming this is the case, then:

  1. If it modifies the state of it's owner object, then you should test that the state changed correctly.
  2. If it takes in some object as a parameter and modifies that object, then your should test the object is correctly modified.
  3. If it throws exceptions is certain cases, test that those exceptions are correctly thrown.
  4. If its behaviour varies based on the state of its own object, or some other object, preset the state and test the method has the correct Ithrough one of the three test methods above).

If youy let us know what the method does, I could be more specific.

Why does flexbox stretch my image rather than retaining aspect ratio?

It is stretching because align-self default value is stretch. there is two solution for this case : 1. set img align-self : center OR 2. set parent align-items : center

img {

   align-self: center
}

OR

.parent {
  align-items: center
}

Angularjs: input[text] ngChange fires while the value is changing

This is about recent additions to AngularJS, to serve as future answer (also for another question).

Angular newer versions (now in 1.3 beta), AngularJS natively supports this option, using ngModelOptions, like

ng-model-options="{ updateOn: 'default blur', debounce: { default: 500, blur: 0 } }"

NgModelOptions docs

Example:

<input type="text" name="username"
       ng-model="user.name"
       ng-model-options="{updateOn: 'default blur', debounce: {default: 500, blur: 0} }" />

How to calculate the difference between two dates using PHP?

An easy function

function time_difference($time_1, $time_2, $limit = null)
{

    $val_1 = new DateTime($time_1);
    $val_2 = new DateTime($time_2);

    $interval = $val_1->diff($val_2);

    $output = array(
        "year" => $interval->y,
        "month" => $interval->m,
        "day" => $interval->d,
        "hour" => $interval->h,
        "minute" => $interval->i,
        "second" => $interval->s
    );

    $return = "";
    foreach ($output AS $key => $value) {

        if ($value == 1)
            $return .= $value . " " . $key . " ";
        elseif ($value >= 1)
            $return .= $value . " " . $key . "s ";

        if ($key == $limit)
            return trim($return);
    }
    return trim($return);
}

Use like

echo time_difference ($time_1, $time_2, "day");

Will return like 2 years 8 months 2 days

text box input height

I came here looking for making an input that's actually multiple lines. Turns out I didn't want an input, I wanted a textarea. You can set height or line-height as other answers specify, but it'll still just be one line of a textbox. If you want actual multiple lines, use a textarea instead. The following is an example of a 3-row textarea with a width of 500px (should be a good part of the page, not necessary to set this and will have to change it based on your requirements).

<textarea name="roleExplanation" style="width: 500px" rows="3">This role is for facility managers and holds the highest permissions in the application.</textarea>

How do I post form data with fetch api?

// Write Data

async function write(param) {
  var zahl = param.getAttribute("data-role");

  let mood = {
    appId: app_ID,
    key: "",
    value: zahl
  };

  let response = await fetch(web_api, {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify(mood)
  });
  console.log(currentMood);

// Get Data

async function get() {

  let response = await fetch(web_api + "/App/" + app_ID, {
    method: "GET",
    headers: {
      "Content-Typ": "application/jason"
    }
  });

  let todos = await response.json();

// Remove Data

function remove(id) {
  return fetch(web_api" + id, {
    method: "DELETE"
  }).then(response => {
    if (!response.ok) {
      throw new Error("Todo konnte nicht entfernt werden.");
    }
  });
}


async function removeAll() {
  let response = await fetch(web_api + "/App/" + app_ID, {
    method: "GET",
    headers: {
      "Content-Typ": "application/jason"
    }
  });
  let todos = await response.json();
  console.log(todos);

  for (let todo of todos) {
    await remove(todo.id);
  }
}

// Update Data

  function updateTodo(todo) {
return fetch(`https://__________________/api/items/${todo.id}`, {
  method: "PUT",
  body: JSON.stringify(todo),
  headers: {
    "Content-Type": "application/json",
  },
}).then((response) => {
  if (!response.ok) {
    throw new Error("Todo konnte nicht upgedated werden.");
  }
});

}

Programmatically set TextBlock Foreground Color

To get the Color from Hex.

using System.Windows.Media;

Color color = (Color)ColorConverter.ConvertFromString("#FFDFD991");

and then set the foreground

textBlock.Foreground = new System.Windows.Media.SolidColorBrush(color); 

Python: Continuing to next iteration in outer loop

I think you could do something like this:

for ii in range(200):
    restart = False
    for jj in range(200, 400):
        ...block0...
        if something:
            restart = True
            break
    if restart:
        continue
    ...block1...

Directory-tree listing in Python

FYI Add a filter of extension or ext file import os

path = '.'
for dirname, dirnames, filenames in os.walk(path):
    # print path to all filenames with extension py.
    for filename in filenames:
        fname_path = os.path.join(dirname, filename)
        fext = os.path.splitext(fname_path)[1]
        if fext == '.py':
            print fname_path
        else:
            continue

How do you use the ? : (conditional) operator in JavaScript?

It's an if statement all on one line.

So

var x=1;
(x == 1) ? y="true" : y="false";
alert(y);

The expression to be evaluated is in the ( )

If it matches true, execute the code after the ?

If it matches false, execute the code after the :

Cannot start MongoDB as a service

I had same issue on windows 8.1

The solution which worked for me is to specify config file path correctly

Going to HKEY_LOCAL_MACHINE > SYSTEM > CurrentControlSet > services > MongoDB > imagePath the value was like the following:

"C:\Program Files\MongoDB 2.6 Standard\bin\mongod.exe" --config mongod.cfg --service

Then just I corrected config file path to match my actual path:

"C:\Program Files\MongoDB 2.6 Standard\bin\mongod.exe" --config "d:\mongodb\mongod.cfg" --service

How to pass credentials to the Send-MailMessage command for sending emails

And here is a simple Send-MailMessage example with username/password for anyone looking for just that

$secpasswd = ConvertTo-SecureString "PlainTextPassword" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ("username", $secpasswd)
Send-MailMessage -SmtpServer mysmptp -Credential $cred -UseSsl -From '[email protected]' -To '[email protected]' -Subject 'TEST'

How to center align the ActionBar title in Android?

This code will not hide back button, Same time will align the title in centre.

call this method in oncreate

centerActionBarTitle();



getSupportActionBar().setDisplayHomeAsUpEnabled(true);
myActionBar.setIcon(new ColorDrawable(Color.TRANSPARENT));

private void centerActionBarTitle() {
    int titleId = 0;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        titleId = getResources().getIdentifier("action_bar_title", "id", "android");
    } else {
        // This is the id is from your app's generated R class when 
        // ActionBarActivity is used for SupportActionBar
        titleId = R.id.action_bar_title;
    }

    // Final check for non-zero invalid id
    if (titleId > 0) {
        TextView titleTextView = (TextView) findViewById(titleId);
        DisplayMetrics metrics = getResources().getDisplayMetrics();

        // Fetch layout parameters of titleTextView 
        // (LinearLayout.LayoutParams : Info from HierarchyViewer)
        LinearLayout.LayoutParams txvPars = (LayoutParams) titleTextView.getLayoutParams();
        txvPars.gravity = Gravity.CENTER_HORIZONTAL;
        txvPars.width = metrics.widthPixels;
        titleTextView.setLayoutParams(txvPars);
        titleTextView.setGravity(Gravity.CENTER);
    }
}

Convert a string to a datetime

Nobody mentioned this, but in some cases the other method fails to recognize the datetime...

You can try this instead, which will convert the specified string representation of a date and time to an equivalent date and time value

string iDate = "05/05/2005";
DateTime oDate = Convert.ToDateTime(iDate);
MessageBox.Show(oDate.Day + " " + oDate.Month + "  " + oDate.Year );

@Autowired and static method

It sucks but you can get the bean by using the ApplicationContextAware interface. Something like :

public class Boo implements ApplicationContextAware {

    private static ApplicationContext appContext;

    @Autowired
    Foo foo;

    public static void randomMethod() {
         Foo fooInstance = appContext.getBean(Foo.class);
         fooInstance.doStuff();
    }

    @Override
    public void setApplicationContext(ApplicationContext appContext) {
        Boo.appContext = appContext;
    }
}

The best way to calculate the height in a binary search tree? (balancing an AVL-tree)

  • Height is easily implemented by recursion, take the maximum of the height of the subtrees plus one.

  • The "balance factor of R" refers to the right subtree of the tree which is out of balance, I suppose.

Python if not == vs if !=

It's about your way of reading it. not operator is dynamic, that's why you are able to apply it in

if not x == 'val':

But != could be read in a better context as an operator which does the opposite of what == does.

java calling a method from another class

You have to initialise the object (create the object itself) in order to be able to call its methods otherwise you would get a NullPointerException.

WordList words = new WordList();

Accessing Session Using ASP.NET Web API

MVC

For an MVC project make the following changes (WebForms and Dot Net Core answer down below):

WebApiConfig.cs

public static class WebApiConfig
{
    public static string UrlPrefix         { get { return "api"; } }
    public static string UrlPrefixRelative { get { return "~/api"; } }

    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: WebApiConfig.UrlPrefix + "/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

Global.asax.cs

public class MvcApplication : System.Web.HttpApplication
{
    ...

    protected void Application_PostAuthorizeRequest()
    {
        if (IsWebApiRequest())
        {
            HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
        }
    }

    private bool IsWebApiRequest()
    {
        return HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath.StartsWith(WebApiConfig.UrlPrefixRelative);
    }

}

This solution has the added bonus that we can fetch the base URL in javascript for making the AJAX calls:

_Layout.cshtml

<body>
    @RenderBody()

    <script type="text/javascript">
        var apiBaseUrl = '@Url.Content(ProjectNameSpace.WebApiConfig.UrlPrefixRelative)';
    </script>

    @RenderSection("scripts", required: false) 

and then within our Javascript files/code we can make our webapi calls that can access the session:

$.getJSON(apiBaseUrl + '/MyApi')
   .done(function (data) {
       alert('session data received: ' + data.whatever);
   })
);

WebForms

Do the above but change the WebApiConfig.Register function to take a RouteCollection instead:

public static void Register(RouteCollection routes)
{
    routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: WebApiConfig.UrlPrefix + "/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
}

And then call the following in Application_Start:

WebApiConfig.Register(RouteTable.Routes);

Dot Net Core

Add the Microsoft.AspNetCore.Session NuGet package and then make the following code changes:

Startup.cs

Call the AddDistributedMemoryCache and AddSession methods on the services object within the ConfigureServices function:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    ...

    services.AddDistributedMemoryCache();
    services.AddSession();

and in the Configure function add a call to UseSession:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, 
ILoggerFactory loggerFactory)
{
    app.UseSession();
    app.UseMvc();

SessionController.cs

Within your controller, add a using statement at the top:

using Microsoft.AspNetCore.Http;

and then use the HttpContext.Session object within your code like so:

    [HttpGet("set/{data}")]
    public IActionResult setsession(string data)
    {
        HttpContext.Session.SetString("keyname", data);
        return Ok("session data set");
    }

    [HttpGet("get")]
    public IActionResult getsessiondata()
    {
        var sessionData = HttpContext.Session.GetString("keyname");
        return Ok(sessionData);
    }

you should now be able to hit:

http://localhost:1234/api/session/set/thisissomedata

and then going to this URL will pull it out:

http://localhost:1234/api/session/get

Plenty more info on accessing session data within dot net core here: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state

Performance Concerns

Read Simon Weaver's answer below regarding performance. If you're accessing session data inside a WebApi project it can have very serious performance consequence - I have seen ASP.NET enforce a 200ms delay for concurrent requests. This could add up and become disastrous if you have many concurrent requests.


Security Concerns

Make sure you are locking down resources per user - an authenticated user shouldn't be able to retrieve data from your WebApi that they don't have access to.

Read Microsoft's article on Authentication and Authorization in ASP.NET Web API - https://www.asp.net/web-api/overview/security/authentication-and-authorization-in-aspnet-web-api

Read Microsoft's article on avoiding Cross-Site Request Forgery hack attacks. (In short, check out the AntiForgery.Validate method) - https://www.asp.net/web-api/overview/security/preventing-cross-site-request-forgery-csrf-attacks

How do I declare a namespace in JavaScript?

In JavaScript there are no predefined methods to use namespaces. In JavaScript we have to create our own methods to define NameSpaces. Here is a procedure we follow in Oodles technologies.

Register a NameSpace Following is the function to register a name space

//Register NameSpaces Function
function registerNS(args){
 var nameSpaceParts = args.split(".");
 var root = window;

 for(var i=0; i < nameSpaceParts.length; i++)
 {
  if(typeof root[nameSpaceParts[i]] == "undefined")
   root[nameSpaceParts[i]] = new Object();

  root = root[nameSpaceParts[i]];
 }
}

To register a Namespace just call the above function with the argument as name space separated by '.' (dot). For Example Let your application name is oodles. You can make a namespace by following method

registerNS("oodles.HomeUtilities");
registerNS("oodles.GlobalUtilities");
var $OHU = oodles.HomeUtilities;
var $OGU = oodles.GlobalUtilities;

Basically it will create your NameSpaces structure like below in backend:

var oodles = {
    "HomeUtilities": {},
    "GlobalUtilities": {}
};

In the above function you have register a namespace called "oodles.HomeUtilities" and "oodles.GlobalUtilities". To call these namespaces we make an variable i.e. var $OHU and var $OGU.

These variables are nothing but an alias to Intializing the namespace. Now, Whenever you declare a function that belong to HomeUtilities you will declare it like following:

$OHU.initialization = function(){
    //Your Code Here
};

Above is the function name initialization and it is put into an namespace $OHU. and to call this function anywhere in the script files. Just use following code.

$OHU.initialization();

Similarly, with the another NameSpaces.

Hope it helps.

When to use Hadoop, HBase, Hive and Pig?

MapReduce is just a computing framework. HBase has nothing to do with it. That said, you can efficiently put or fetch data to/from HBase by writing MapReduce jobs. Alternatively you can write sequential programs using other HBase APIs, such as Java, to put or fetch the data. But we use Hadoop, HBase etc to deal with gigantic amounts of data, so that doesn't make much sense. Using normal sequential programs would be highly inefficient when your data is too huge.

Coming back to the first part of your question, Hadoop is basically 2 things: a Distributed FileSystem (HDFS) + a Computation or Processing framework (MapReduce). Like all other FS, HDFS also provides us storage, but in a fault tolerant manner with high throughput and lower risk of data loss (because of the replication). But, being a FS, HDFS lacks random read and write access. This is where HBase comes into picture. It's a distributed, scalable, big data store, modelled after Google's BigTable. It stores data as key/value pairs.

Coming to Hive. It provides us data warehousing facilities on top of an existing Hadoop cluster. Along with that it provides an SQL like interface which makes your work easier, in case you are coming from an SQL background. You can create tables in Hive and store data there. Along with that you can even map your existing HBase tables to Hive and operate on them.

While Pig is basically a dataflow language that allows us to process enormous amounts of data very easily and quickly. Pig basically has 2 parts: the Pig Interpreter and the language, PigLatin. You write Pig script in PigLatin and using Pig interpreter process them. Pig makes our life a lot easier, otherwise writing MapReduce is always not easy. In fact in some cases it can really become a pain.

I had written an article on a short comparison of different tools of the Hadoop ecosystem some time ago. It's not an in depth comparison, but a short intro to each of these tools which can help you to get started. (Just to add on to my answer. No self promotion intended)

Both Hive and Pig queries get converted into MapReduce jobs under the hood.

HTH

How do I deserialize a complex JSON object in C# .NET?

You can solve your problem like below bunch of codes

public class Response
{
    public string loopa { get; set; }
    public string drupa{ get; set; }
    public Image[] images { get; set; }
}

public class RootObject<T>
    {
        public List<T> response{ get; set; }

    }

var des = (RootObject<Response>)Newtonsoft.Json.JsonConvert.DeserializeObject(Your JSon String, typeof(RootObject<Response>));

How to create a fixed sidebar layout with Bootstrap 4?

My version:

div#dashmain { margin-left:150px; }
div#dashside {position:fixed; width:150px; height:100%; }
<div id="dashside"></div>
<div id="dashmain">                        
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-12">Content</div>
        </div>            
    </div>        
</div>

Returning data from Axios API

You can use Async - Await:

async function axiosTest() {
  const response = await axios.get(url);
  const data = await response.json();  
}

Trim a string based on the string length

tl;dr

You seem to be asking for an ellipsis () character in the last place, when truncating. Here is a one-liner to manipulate your input string.

String input = "abcdefghijkl";
String output = ( input.length () > 10 ) ? input.substring ( 0 , 10 - 1 ).concat ( "…" ) : input;

See this code run live at IdeOne.com.

abcdefghi…

Ternary operator

We can make a one-liner by using the ternary operator.

String input = "abcdefghijkl" ;

String output = 
    ( input.length() > 10 )          // If too long…
    ?                                
    input     
    .substring( 0 , 10 - 1 )         // Take just the first part, adjusting by 1 to replace that last character with an ellipsis.
    .concat( "…" )                   // Add the ellipsis character.
    :                                // Or, if not too long…
    input                            // Just return original string.
;

See this code run live at IdeOne.com.

abcdefghi…

Java streams

The Java Streams facility makes this interesting, as of Java 9 and later. Interesting, but maybe not the best approach.

We use code points rather than char values. The char type is legacy, and is limited to the a subset of all possible Unicode characters.

String input = "abcdefghijkl" ;
int limit = 10 ;
String output =
        input
                .codePoints()
                .limit( limit )
                .collect(                                    // Collect the results of processing each code point.
                        StringBuilder::new,                  // Supplier<R> supplier
                        StringBuilder::appendCodePoint,      // ObjIntConsumer<R> accumulator
                        StringBuilder::append                // BiConsumer<R,?R> combiner
                )
                .toString()
        ;

If we had excess characters truncated, replace the last character with an ellipsis.

if ( input.length () > limit )
{
    output = output.substring ( 0 , output.length () - 1 ) + "…";
}

If only I could think of a way to put together the stream line with the "if over limit, do ellipsis" part.

If REST applications are supposed to be stateless, how do you manage sessions?

REST is very abstract. It helps to have some good, simple, real-world examples.

Take for example all major social media apps -- Tumblr, Instagram, Facebook, and Twitter. They all have a forever-scrolling view where the farther you scroll down, the more content you see, further and further back in time. However, we've all experienced that moment where you lose where you were scrolled to, and the app resets you back to the top. Like if you quit the app, then when you reopen it, you're back at the top again.

The reason why, is because the server did not store your session state. Sadly, your scroll position was just stored in RAM on the client.

Fortunately you don't have to log back in when you reconnect, but that's only because your client-side also stored login certificate has not expired. Delete and reinstall the app, and you're going to have to log back in, because the server did not associate your IP address with your session.

You don't have a login session on the server, because they abide by REST.


Now the above examples don't involve a web browser at all, but on the back end, the apps are communicating via HTTPS with their host servers. My point is that REST does not have to involve cookies and browsers etc. There are various means of storing client-side session state.

But lets talk about web browsers for a second, because that brings up another major advantage of REST that nobody here is talking about.

If the server tried to store session state, how is it supposed to identify each individual client?

It could not use their IP address, because many people could be using that same address on a shared router. So how, then?

It can't use MAC address for many reasons, not the least of which because you can be logged into multiple different Facebook accounts simultaneously on different browsers plus the app. One browser can easily pretend to be another one, and MAC addresses are just as easy to spoof.

If the server has to store some client-side state to identify you, it has to store it in RAM longer than just the time it takes to process your requests, or else it has to cache that data. Servers have limited amounts of RAM and cache, not to mention processor speed. Server-side state adds to all three, exponentially. Plus if the server is going to store any state about your sessions then it has to store it separately for each browser and app you're currently logged in with, and also for each different device you use.


So... I hope that you see now why REST is so important for scalability. I hope you can start to see why server-side session state is to server scalability what welded-on anvils are to car acceleration.


Where people get confused is by thinking that "state" refers to, like, information stored in a database. No, it refers to any information that needs to be in the RAM of the server when you're using it.

How to use radio buttons in ReactJS?

Based on what React Docs say:

Handling Multiple Inputs. When you need to handle multiple controlled input elements, you can add a name attribute to each element and let the handler function choose what to do based on the value of event.target.name.

For example:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  handleChange = e => {
    const { name, value } = e.target;

    this.setState({
      [name]: value
    });
  };

  render() {
    return (
      <div className="radio-buttons">
        Windows
        <input
          id="windows"
          value="windows"
          name="platform"
          type="radio"
          onChange={this.handleChange}
        />
        Mac
        <input
          id="mac"
          value="mac"
          name="platform"
          type="radio"
          onChange={this.handleChange}
        />
        Linux
        <input
          id="linux"
          value="linux"
          name="platform"
          type="radio"
          onChange={this.handleChange}
        />
      </div>
    );
  }
}

Link to example: https://codesandbox.io/s/6l6v9p0qkr

At first, none of the radio buttons is selected so this.state is an empty object, but whenever the radio button is selected this.state gets a new property with the name of the input and its value. It eases then to check whether user selected any radio-button like:

const isSelected = this.state.platform ? true : false;

EDIT:

With version 16.7-alpha of React there is a proposal for something called hooks which will let you do this kind of stuff easier:

In the example below there are two groups of radio-buttons in a functional component. Still, they have controlled inputs:

function App() {
  const [platformValue, plaftormInputProps] = useRadioButtons("platform");
  const [genderValue, genderInputProps] = useRadioButtons("gender");
  return (
    <div>
      <form>
        <fieldset>
          Windows
          <input
            value="windows"
            checked={platformValue === "windows"}
            {...plaftormInputProps}
          />
          Mac
          <input
            value="mac"
            checked={platformValue === "mac"}
            {...plaftormInputProps}
          />
          Linux
          <input
            value="linux"
            checked={platformValue === "linux"}
            {...plaftormInputProps}
          />
        </fieldset>
        <fieldset>
          Male
          <input
            value="male"
            checked={genderValue === "male"}
            {...genderInputProps}
          />
          Female
          <input
            value="female"
            checked={genderValue === "female"}
            {...genderInputProps}
          />
        </fieldset>
      </form>
    </div>
  );
}

function useRadioButtons(name) {
  const [value, setState] = useState(null);

  const handleChange = e => {
    setState(e.target.value);
  };

  const inputProps = {
    name,
    type: "radio",
    onChange: handleChange
  };

  return [value, inputProps];
}

Working example: https://codesandbox.io/s/6l6v9p0qkr

auto refresh for every 5 mins

Auto reload with target of your choice. In this case target is _self set to every 5 minutes.

300000 milliseconds = 300 seconds = 5 minutes

as 60000 milliseconds = 60 seconds = 1 minute.

This is how you do it:

<script type="text/javascript">
function load()
{
setTimeout("window.open('http://YourPage.com', '_self');", 300000);
}
</script>
<body onload="load()">

Or this if it is the same page to reload itself:

<script type="text/javascript">
function load()
{
setTimeout("window.open(self.location, '_self');", 300000);
}
</script>
<body onload="load()">

Select distinct values from a list using LINQ in C#

You could implement a custom IEqualityComparer<Employee>:

public class Employee
{
    public string empName { get; set; }
    public string empID { get; set; }
    public string empLoc { get; set; }
    public string empPL { get; set; }
    public string empShift { get; set; }

    public class Comparer : IEqualityComparer<Employee>
    {
        public bool Equals(Employee x, Employee y)
        {
            return x.empLoc == y.empLoc
                && x.empPL == y.empPL
                && x.empShift == y.empShift;
        }

        public int GetHashCode(Employee obj)
        {
            unchecked  // overflow is fine
            {
                int hash = 17;
                hash = hash * 23 + (obj.empLoc ?? "").GetHashCode();
                hash = hash * 23 + (obj.empPL ?? "").GetHashCode();
                hash = hash * 23 + (obj.empShift ?? "").GetHashCode();
                return hash;
            }
        }
    }
}

Now you can use this overload of Enumerable.Distinct:

var distinct = employees.Distinct(new Employee.Comparer());

The less reusable, robust and efficient approach, using an anonymous type:

var distinctKeys = employees.Select(e => new { e.empLoc, e.empPL, e.empShift })
                            .Distinct();
var joined = from e in employees
             join d in distinctKeys
             on new { e.empLoc, e.empPL, e.empShift } equals d
             select e;
// if you want to replace the original collection
employees = joined.ToList();

Why is vertical-align: middle not working on my span or div?

It's simple. Just add display:table-cell in your main class.

.main {
  height: 72px;
  vertical-align: middle;
  display:table-cell;
  border: 1px solid #000000;
}

Check out this jsfiddle!

Getting current device language in iOS?

Translating language codes such as en_US into English (United States) is a built in feature of NSLocale and NSLocale does not care where you get the language codes from. So there really is no reason to implement your own translation as the accepted answer suggests.

// Example code - try changing the language codes and see what happens
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en"];
NSString *l1 = [locale displayNameForKey:NSLocaleIdentifier value:@"en"];
NSString *l2 = [locale displayNameForKey:NSLocaleIdentifier value:@"de"];
NSString *l3 = [locale displayNameForKey:NSLocaleIdentifier value:@"sv"];
NSLog(@"%@, %@, %@", l1, l2, l3);

Prints: English, German, Swedish

How do I make a semi transparent background?

div.main{
     width:100%;
     height:550px;
     background: url('https://images.unsplash.com/photo-1503135935062-
     b7d1f5a0690f?ixlib=rb-enter code here0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=cf4d0c234ecaecd14f51a2343cc89b6c&dpr=1&auto=format&fit=crop&w=376&h=564&q=60&cs=tinysrgb') no-repeat;
     background-position:center;
     background-size:cover 
}
 div.main>div{
     width:100px;
     height:320px;
     background:transparent;
     background-attachment:fixed;
     border-top:25px solid orange;
     border-left:120px solid orange;
     border-bottom:25px solid orange;
     border-right:10px solid orange;
     margin-left:150px 
}

enter image description here

How to solve the system.data.sqlclient.sqlexception (0x80131904) error

You also need to change the DataSource of the connection string. KELVIN-PC is the name of your local machine and the sql server is running on the default instance.

If you are sure the the server is running as the default instance, you can always use . in the DataSource, eg.

connectionString="Data Source=.;Initial Catalog=LMS;User ID=sa;Password=temperament"

otherwise, you need to specify the name of the instance of the server,

connectionString="Data Source=.\INSTANCENAME;Initial Catalog=LMS;User ID=sa;Password=temperament"

show icon in actionbar/toolbar with AppCompat-v7 21

In Xamarin.Android you can use these:

SupportActionBar.SetHomeButtonEnabled(true);
SupportActionBar.SetDisplayShowHomeEnabled(true);
SupportActionBar.SetDisplayUseLogoEnabled(true);
SupportActionBar.SetIcon(Resource.Drawable.ic_launcher);
SupportActionBar.SetDisplayShowTitleEnabled(false);

using Android.Support.V7.App.AppCompatActivity is required.

z-index not working with fixed positioning

the behaviour of fixed elements (and absolute elements) as defined in CSS Spec:

They behave as they are detached from document, and placed in the nearest fixed/absolute positioned parent. (not a word by word quote)

This makes zindex calculation a bit complicated, I solved my problem (the same situation) by dynamically creating a container in body element and moving all such elements (which are class-ed as "my-fixed-ones" inside that body-level element)

'DataFrame' object has no attribute 'sort'

Pandas Sorting 101

sort has been replaced in v0.20 by DataFrame.sort_values and DataFrame.sort_index. Aside from this, we also have argsort.

Here are some common use cases in sorting, and how to solve them using the sorting functions in the current API. First, the setup.

# Setup
np.random.seed(0)
df = pd.DataFrame({'A': list('accab'), 'B': np.random.choice(10, 5)})    
df                                                                                                                                        
   A  B
0  a  7
1  c  9
2  c  3
3  a  5
4  b  2

Sort by Single Column

For example, to sort df by column "A", use sort_values with a single column name:

df.sort_values(by='A')

   A  B
0  a  7
3  a  5
4  b  2
1  c  9
2  c  3

If you need a fresh RangeIndex, use DataFrame.reset_index.

Sort by Multiple Columns

For example, to sort by both col "A" and "B" in df, you can pass a list to sort_values:

df.sort_values(by=['A', 'B'])

   A  B
3  a  5
0  a  7
4  b  2
2  c  3
1  c  9

Sort By DataFrame Index

df2 = df.sample(frac=1)
df2

   A  B
1  c  9
0  a  7
2  c  3
3  a  5
4  b  2

You can do this using sort_index:

df2.sort_index()

   A  B
0  a  7
1  c  9
2  c  3
3  a  5
4  b  2

df.equals(df2)                                                                                                                            
# False
df.equals(df2.sort_index())                                                                                                               
# True

Here are some comparable methods with their performance:

%timeit df2.sort_index()                                                                                                                  
%timeit df2.iloc[df2.index.argsort()]                                                                                                     
%timeit df2.reindex(np.sort(df2.index))                                                                                                   

605 µs ± 13.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
610 µs ± 24.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
581 µs ± 7.63 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Sort by List of Indices

For example,

idx = df2.index.argsort()
idx
# array([0, 7, 2, 3, 9, 4, 5, 6, 8, 1])

This "sorting" problem is actually a simple indexing problem. Just passing integer labels to iloc will do.

df.iloc[idx]

   A  B
1  c  9
0  a  7
2  c  3
3  a  5
4  b  2

Split String by delimiter position using oracle SQL

You want to use regexp_substr() for this. This should work for your example:

select regexp_substr(val, '[^/]+/[^/]+', 1, 1) as part1,
       regexp_substr(val, '[^/]+$', 1, 1) as part2
from (select 'F/P/O' as val from dual) t

Here, by the way, is the SQL Fiddle.

Oops. I missed the part of the question where it says the last delimiter. For that, we can use regex_replace() for the first part:

select regexp_replace(val, '/[^/]+$', '', 1, 1) as part1,
       regexp_substr(val, '[^/]+$', 1, 1) as part2
from (select 'F/P/O' as val from dual) t

And here is this corresponding SQL Fiddle.

How do I move a table into a schema in T-SQL

ALTER SCHEMA TargetSchema 
    TRANSFER SourceSchema.TableName;

If you want to move all tables into a new schema, you can use the undocumented (and to be deprecated at some point, but unlikely!) sp_MSforeachtable stored procedure:

exec sp_MSforeachtable "ALTER SCHEMA TargetSchema TRANSFER ?"

Ref.: ALTER SCHEMA

SQL 2008: How do I change db schema to dbo

`getchar()` gives the same output as the input string

Strings, by C definition, are terminated by '\0'. You have no "C strings" in your program.

Your program reads characters (buffered till ENTER) from the standard input (the keyboard) and writes them back to the standard output (the screen). It does this no matter how many characters you type or for how long you do this.

To stop the program you have to indicate that the standard input has no more data (huh?? how can a keyboard have no more data?).

You simply press Ctrl+D (Unix) or Ctrl+Z (Windows) to pretend the file has reached its end.
Ctrl+D (or Ctrl+Z) are not really characters in the C sense of the word.

If you run your program with input redirection, the EOF is the actual end of file, not a make belief one
./a.out < source.c

How can I directly view blobs in MySQL Workbench

I pieced a few of the other posts together, as the workbench 'preferences' fix did not work for me. (WB 6.3)

SELECT CAST(`column` AS CHAR(10000) CHARACTER SET utf8) FROM `table`;

java.net.URL read stream to byte[]

I am very surprised that nobody here has mentioned the problem of connection and read timeout. It could happen (especially on Android and/or with some crappy network connectivity) that the request will hang and wait forever.

The following code (which also uses Apache IO Commons) takes this into account, and waits max. 5 seconds until it fails:

public static byte[] downloadFile(URL url)
{
    try {
        URLConnection conn = url.openConnection();
        conn.setConnectTimeout(5000);
        conn.setReadTimeout(5000);
        conn.connect(); 

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        IOUtils.copy(conn.getInputStream(), baos);

        return baos.toByteArray();
    }
    catch (IOException e)
    {
        // Log error and return null, some default or throw a runtime exception
    }
}

SQL not a single-group group function

Well the problem simply-put is that the SUM(TIME) for a specific SSN on your query is a single value, so it's objecting to MAX as it makes no sense (The maximum of a single value is meaningless).

Not sure what SQL database server you're using but I suspect you want a query more like this (Written with a MSSQL background - may need some translating to the sql server you're using):

SELECT TOP 1 SSN, SUM(TIME)
FROM downloads
GROUP BY SSN
ORDER BY 2 DESC

This will give you the SSN with the highest total time and the total time for it.

Edit - If you have multiple with an equal time and want them all you would use:

SELECT
SSN, SUM(TIME)
FROM downloads
GROUP BY SSN
HAVING SUM(TIME)=(SELECT MAX(SUM(TIME)) FROM downloads GROUP BY SSN))

Commenting out a set of lines in a shell script

The most versatile and safe method is putting the comment into a void quoted here-document, like this:

<<"COMMENT"
    This long comment text includes ${parameter:=expansion}
    `command substitution` and $((arithmetic++ + --expansion)).
COMMENT

Quoting the COMMENT delimiter above is necessary to prevent parameter expansion, command substitution and arithmetic expansion, which would happen otherwise, as Bash manual states and POSIX shell standard specifies.

In the case above, not quoting COMMENT would result in variable parameter being assigned text expansion, if it was empty or unset, executing command command substitution, incrementing variable arithmetic and decrementing variable expansion.

Comparing other solutions to this:

Using if false; then comment text fi requires the comment text to be syntactically correct Bash code whereas natural comments are often not, if only for possible unbalanced apostrophes. The same goes for : || { comment text } construct.

Putting comments into a single-quoted void command argument, as in :'comment text', has the drawback of inability to include apostrophes. Double-quoted arguments, as in :"comment text", are still subject to parameter expansion, command substitution and arithmetic expansion, the same as unquoted here-document contents and can lead to the side-effects described above.

Using scripts and editor facilities to automatically prefix each line in a block with '#' has some merit, but doesn't exactly answer the question.

How to construct a set out of list items in python?

You can do

my_set = set(my_list)

or, in Python 3,

my_set = {*my_list}

to create a set from a list. Conversely, you can also do

my_list = list(my_set)

or, in Python 3,

my_list = [*my_set]

to create a list from a set.

Just note that the order of the elements in a list is generally lost when converting the list to a set since a set is inherently unordered. (One exception in CPython, though, seems to be if the list consists only of non-negative integers, but I assume this is a consequence of the implementation of sets in CPython and that this behavior can vary between different Python implementations.)

What is __gxx_personality_v0 for?

The answers above are correct: it is used in exception handling. The manual for GCC version 6 has more information (which is no longer present in the version 7 manual). The error can arise when linking an external function that - unknown to GCC - throws Java exceptions.

Allowing the "Enter" key to press the submit button, as opposed to only using MouseClick

 switch(KEYEVENT.getKeyCode()){
      case KeyEvent.VK_ENTER:
           // I was trying to use case 13 from the ascii table.
           //Krewn Generated method stub... 
           break;
 }

How can I concatenate a string and a number in Python?

If it worked the way you expected it to (resulting in "abc9"), what would "9" + 9 deliver? 18 or "99"?

To remove this ambiguity, you are required to make explicit what you want to convert in this case:

"abc" + str(9)

Can someone explain __all__ in Python?

Linked to, but not explicitly mentioned here, is exactly when __all__ is used. It is a list of strings defining what symbols in a module will be exported when from <module> import * is used on the module.

For example, the following code in a foo.py explicitly exports the symbols bar and baz:

__all__ = ['bar', 'baz']

waz = 5
bar = 10
def baz(): return 'baz'

These symbols can then be imported like so:

from foo import *

print(bar)
print(baz)

# The following will trigger an exception, as "waz" is not exported by the module
print(waz)

If the __all__ above is commented out, this code will then execute to completion, as the default behaviour of import * is to import all symbols that do not begin with an underscore, from the given namespace.

Reference: https://docs.python.org/tutorial/modules.html#importing-from-a-package

NOTE: __all__ affects the from <module> import * behavior only. Members that are not mentioned in __all__ are still accessible from outside the module and can be imported with from <module> import <member>.

How to change the status bar background color and text color on iOS 7?

Goto your app info.plist

1) Set View controller-based status bar appearance to NO
2) Set Status bar style to UIStatusBarStyleLightContent

Then Goto your app delegate and paste the following code where you set your Windows's RootViewController.

#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)

if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0"))
{
    UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0, 0,[UIScreen mainScreen].bounds.size.width, 20)];
    view.backgroundColor=[UIColor blackColor];
    [self.window.rootViewController.view addSubview:view];
}

Hope it helps.

App can't be opened because it is from an unidentified developer

Try looking into Gatekeeper. I am not sure of too much Mac stuff, but I heard that you can enable it in there.