Programs & Examples On #Entityobject

What does EntityManager.flush do and why do I need to use it?

So when you call EntityManager.persist(), it only makes the entity get managed by the EntityManager and adds it (entity instance) to the Persistence Context. An Explicit flush() will make the entity now residing in the Persistence Context to be moved to the database (using a SQL).

Without flush(), this (moving of entity from Persistence Context to the database) will happen when the Transaction to which this Persistence Context is associated is committed.

Excel VBA date formats

To ensure that a cell will return a date value and not just a string that looks like a date, first you must set the NumberFormat property to a Date format, then put a real date into the cell's content.

Sub test_date_or_String()
 Set c = ActiveCell
 c.NumberFormat = "@"
 c.Value = CDate("03/04/2014")
   Debug.Print c.Value & " is a " & TypeName(c.Value) 'C is a String
 c.NumberFormat = "m/d/yyyy"
   Debug.Print c.Value & " is a " & TypeName(c.Value) 'C is still a String
 c.Value = CDate("03/04/2014")
   Debug.Print c.Value & " is a " & TypeName(c.Value) 'C is a date    
End Sub

What is a segmentation fault?

Wikipedia's Segmentation_fault page has a very nice description about it, just pointing out the causes and reasons. Have a look into the wiki for a detailed description.

In computing, a segmentation fault (often shortened to segfault) or access violation is a fault raised by hardware with memory protection, notifying an operating system (OS) about a memory access violation.

The following are some typical causes of a segmentation fault:

  • Dereferencing NULL pointers – this is special-cased by memory management hardware
  • Attempting to access a nonexistent memory address (outside process's address space)
  • Attempting to access memory the program does not have rights to (such as kernel structures in process context)
  • Attempting to write read-only memory (such as code segment)

These in turn are often caused by programming errors that result in invalid memory access:

  • Dereferencing or assigning to an uninitialized pointer (wild pointer, which points to a random memory address)

  • Dereferencing or assigning to a freed pointer (dangling pointer, which points to memory that has been freed/deallocated/deleted)

  • A buffer overflow.

  • A stack overflow.

  • Attempting to execute a program that does not compile correctly. (Some compilers will output an executable file despite the presence of compile-time errors.)

What is setBounds and how do I use it?

The way that Java Swing UIs work is that for each JPanel there is always a LayoutManager that decides on where to exactly place your components. Each layout managers works differently, so if you use for example a BorderLayout, setBounds() is not used by the LayoutManager, instead component placement is decided by East,West,South,North,Center.

For the NullLayoutManager (in case you used new JPanel(null)) however, each component has to have an x and y coordinate. Stupid Sidenote: if your UI would be three-dimensional there would also be a z coordinate.

So with public void Component.setBounds(int x, int y, int width, int height) you specify where your component is placed and how many pixel it is wide and high.

Here's an example:

import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class JTableInNullLayout
{
  public static void main(String[] argv) throws Exception {

      JPanel panel = new JPanel(null);

      JLabel helloLabel = new JLabel("Hello world!");
      helloLabel.setBounds( 10, 50, 60, 20 ); // x, y, width, height
      panel.add(helloLabel);

      JFrame frame = new JFrame();
      frame.add(panel);
      frame.setPreferredSize( new Dimension(200,200));
      frame.pack();
      frame.setVisible(true);
  }
}

Simple if else onclick then do?

You may use jQuery in it like

$('#yesh').click(function(){
     *****HERE GOES THE FUNCTION*****
});

Besides jQuery is easy to use.

You can make changes in colors etc using simple jQUery or Javascript.

django change default runserver port

In Pycharm you can simply add the port to the parameters

enter image description here

The SELECT permission was denied on the object 'sysobjects', database 'mssqlsystemresource', schema 'sys'

I solved this by referring properties of login user under the security, logins. then go to User Mapping and select the database then check db_datareader and db_dataweriter options.

How to set-up a favicon?

Below given some information about fav Icon

What Is FavIcon? ? FavIcon is nothing but small image which appears top left along with the application address bar title.Standard size specification for favicon.ico is 16 by 16 pixel. Please see below attached figure.

enter image description here

How It Works ? ? Usually we add our FavIcon.ico image in the route solution folder and automatically application picks it while running. But most of the time we might have to use below both link reference.

               <link rel="icon" href="favicon.ico" type="image/ico"/>
               <link rel="shortcut icon" href="favicon.ico" type="image/x-icon"/>

Some browser expect one (rel="icon") Some other browser expect other rel="shortcut icon"

? Type=”image/x-icon” OR Type=”image/ico”: once expect exact ico image and one expect any image even formatted from .jpg or .pn ..etc.

? We have to use above two tags to the common pages like – Master page , Main frame which is getting used in all the pages

Inserting values into a SQL Server database using ado.net via C#

As I said in comments - you should always use parameters in your query - NEVER EVER concatenate together your SQL statements yourself.

Also: I would recommend to separate the click event handler from the actual code to insert the data.

So I would rewrite your code to be something like

In your web page's code-behind file (yourpage.aspx.cs)

private void button1_Click(object sender, EventArgs e)
{
      string connectionString = "Data Source=DELL-PC;initial catalog=AdventureWorks2008R2 ; User ID=sa;Password=sqlpass;Integrated Security=SSPI;";

      InsertData(connectionString,
                 textBox1.Text.Trim(),  -- first name
                 textBox2.Text.Trim(),  -- last name
                 textBox3.Text.Trim(),  -- user name
                 textBox4.Text.Trim(),  -- password
                 Convert.ToInt32(comboBox1.Text),  -- age
                 comboBox2.Text.Trim(), -- gender
                 textBox7.Text.Trim() );  -- contact
}

In some other code (e.g. a databaselayer.cs):

private void InsertData(string connectionString, string firstName, string lastname, string username, string password
                        int Age, string gender, string contact)
{
    // define INSERT query with parameters
    string query = "INSERT INTO dbo.regist (FirstName, Lastname, Username, Password, Age, Gender,Contact) " + 
                   "VALUES (@FirstName, @Lastname, @Username, @Password, @Age, @Gender, @Contact) ";

    // create connection and command
    using(SqlConnection cn = new SqlConnection(connectionString))
    using(SqlCommand cmd = new SqlCommand(query, cn))
    {
        // define parameters and their values
        cmd.Parameters.Add("@FirstName", SqlDbType.VarChar, 50).Value = firstName;
        cmd.Parameters.Add("@Lastname", SqlDbType.VarChar, 50).Value = lastName;
        cmd.Parameters.Add("@Username", SqlDbType.VarChar, 50).Value = userName;
        cmd.Parameters.Add("@Password", SqlDbType.VarChar, 50).Value = password;
        cmd.Parameters.Add("@Age", SqlDbType.Int).Value = age;
        cmd.Parameters.Add("@Gender", SqlDbType.VarChar, 50).Value = gender;
        cmd.Parameters.Add("@Contact", SqlDbType.VarChar, 50).Value = contact;

        // open connection, execute INSERT, close connection
        cn.Open();
        cmd.ExecuteNonQuery();
        cn.Close();
    }
}

Code like this:

  • is not vulnerable to SQL injection attacks
  • performs much better on SQL Server (since the query is parsed once into an execution plan, then cached and reused later on)
  • separates the event handler (code-behind file) from your actual database code (putting things where they belong - helping to avoid "overweight" code-behinds with tons of spaghetti code, doing everything from handling UI events to database access - NOT a good design!)

How To Raise Property Changed events on a Dependency Property?

I think the OP is asking the wrong question. The code below will show that it not necessary to manually raise the PropertyChanged EVENT from a dependency property to achieve the desired result. The way to do it is handle the PropertyChanged CALLBACK on the dependency property and set values for other dependency properties there. The following is a working example. In the code below, MyControl has two dependency properties - ActiveTabInt and ActiveTabString. When the user clicks the button on the host (MainWindow), ActiveTabString is modified. The PropertyChanged CALLBACK on the dependency property sets the value of ActiveTabInt. The PropertyChanged EVENT is not manually raised by MyControl.

MainWindow.xaml.cs

/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window, INotifyPropertyChanged
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = this;
        ActiveTabString = "zero";
    }

    private string _ActiveTabString;
    public string ActiveTabString
    {
        get { return _ActiveTabString; }
        set
        {
            if (_ActiveTabString != value)
            {
                _ActiveTabString = value;
                RaisePropertyChanged("ActiveTabString");
            }
        }
    }

    private int _ActiveTabInt;
    public int ActiveTabInt
    {
        get { return _ActiveTabInt; }
        set
        {
            if (_ActiveTabInt != value)
            {
                _ActiveTabInt = value;
                RaisePropertyChanged("ActiveTabInt");
            }
        }
    }

    #region INotifyPropertyChanged implementation
    public event PropertyChangedEventHandler PropertyChanged;

    public void RaisePropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
    #endregion

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        ActiveTabString = (ActiveTabString == "zero") ? "one" : "zero";
    }

}

public class MyControl : Control
{
    public static List<string> Indexmap = new List<string>(new string[] { "zero", "one" });


    public string ActiveTabString
    {
        get { return (string)GetValue(ActiveTabStringProperty); }
        set { SetValue(ActiveTabStringProperty, value); }
    }

    public static readonly DependencyProperty ActiveTabStringProperty = DependencyProperty.Register(
        "ActiveTabString",
        typeof(string),
        typeof(MyControl), new FrameworkPropertyMetadata(
            null,
            FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
            ActiveTabStringChanged));


    public int ActiveTabInt
    {
        get { return (int)GetValue(ActiveTabIntProperty); }
        set { SetValue(ActiveTabIntProperty, value); }
    }
    public static readonly DependencyProperty ActiveTabIntProperty = DependencyProperty.Register(
        "ActiveTabInt",
        typeof(Int32),
        typeof(MyControl), new FrameworkPropertyMetadata(
            new Int32(),
            FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));


    static MyControl()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(MyControl), new FrameworkPropertyMetadata(typeof(MyControl)));

    }

    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();
    }


    private static void ActiveTabStringChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        MyControl thiscontrol = sender as MyControl;

        if (Indexmap[thiscontrol.ActiveTabInt] != thiscontrol.ActiveTabString)
            thiscontrol.ActiveTabInt = Indexmap.IndexOf(e.NewValue.ToString());

    }
}

MainWindow.xaml

    <StackPanel Orientation="Vertical">
    <Button Content="Change Tab Index" Click="Button_Click" Width="110" Height="30"></Button>
    <local:MyControl x:Name="myControl" ActiveTabInt="{Binding ActiveTabInt, Mode=TwoWay}" ActiveTabString="{Binding ActiveTabString}"></local:MyControl>
</StackPanel>

App.xaml

<Style TargetType="local:MyControl">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="local:MyControl">
                    <TabControl SelectedIndex="{Binding ActiveTabInt, Mode=TwoWay}">
                        <TabItem Header="Tab Zero">
                            <TextBlock Text="{Binding ActiveTabInt}"></TextBlock>
                        </TabItem>
                        <TabItem Header="Tab One">
                            <TextBlock Text="{Binding ActiveTabInt}"></TextBlock>
                        </TabItem>
                    </TabControl>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

Apple Mach-O Linker Error when compiling for device

In my case i has include .m file thats why compiler shows this type of error.

you should check the latest file import that is not .m file " Sometime i"

How to convert String into Hashmap in java

try this out :)

public static HashMap HashMapFrom(String s){
    HashMap base = new HashMap(); //result
    int dismiss = 0; //dismiss tracker
    StringBuilder tmpVal = new StringBuilder(); //each val holder
    StringBuilder tmpKey = new StringBuilder(); //each key holder

    for (String next:s.split("")){ //each of vale
        if(dismiss==0){ //if not writing value
            if (next.equals("=")) //start writing value
                dismiss=1; //update tracker
            else
                tmpKey.append(next); //writing key
        } else {
            if (next.equals("{")) //if it's value so need to dismiss
                dismiss++;
            else if (next.equals("}")) //value closed so need to focus
                dismiss--;
            else if (next.equals(",") //declaration ends
                    && dismiss==1) {
                //by the way you have to create something to correct the type
                Object ObjVal = object.valueOf(tmpVal.toString()); //correct the type of object
                base.put(tmpKey.toString(),ObjVal);//declaring
                tmpKey = new StringBuilder();
                tmpVal = new StringBuilder();
                dismiss--;
                continue; //next :)
            }
            tmpVal.append(next); //writing value
        }
    }
    Object objVal = object.valueOf(tmpVal.toString()); //same as here
    base.put(tmpKey.toString(), objVal); //leftovers
    return base;
}

examples input : "a=0,b={a=1},c={ew={qw=2}},0=a" output : {0=a,a=0,b={a=1},c={ew={qw=2}}}

Bash mkdir and subfolders

FWIW,

Poor mans security folder (to protect a public shared folder from little prying eyes ;) )

mkdir -p {0..9}/{0..9}/{0..9}/{0..9}

Now you can put your files in a pin numbered folder. Not exactly waterproof, but it's a barrier for the youngest.

how to convert a string date to date format in oracle10g

You need to use the TO_DATE function.

SELECT TO_DATE('01/01/2004', 'MM/DD/YYYY') FROM DUAL;

How do I modify a MySQL column to allow NULL?

You want the following:

ALTER TABLE mytable MODIFY mycolumn VARCHAR(255);

Columns are nullable by default. As long as the column is not declared UNIQUE or NOT NULL, there shouldn't be any problems.

Detect Click into Iframe using JavaScript

This works for me on all browsers (included Firefox)

https://gist.github.com/jaydson/1780598

https://jsfiddle.net/sidanmor/v6m9exsw/

_x000D_
_x000D_
var myConfObj = {_x000D_
  iframeMouseOver : false_x000D_
}_x000D_
window.addEventListener('blur',function(){_x000D_
  if(myConfObj.iframeMouseOver){_x000D_
    console.log('Wow! Iframe Click!');_x000D_
  }_x000D_
});_x000D_
_x000D_
document.getElementById('idanmorblog').addEventListener('mouseover',function(){_x000D_
   myConfObj.iframeMouseOver = true;_x000D_
});_x000D_
document.getElementById('idanmorblog').addEventListener('mouseout',function(){_x000D_
    myConfObj.iframeMouseOver = false;_x000D_
});
_x000D_
<iframe id="idanmorblog" src="https://sidanmor.com/" style="width:400px;height:600px" ></iframe>
_x000D_
_x000D_
_x000D_

<iframe id="idanmorblog" src="https://sidanmor.com/" style="width:400px;height:600px" ></iframe>

How to join multiple collections with $lookup in mongodb

First add the collections and then apply lookup on these collections. Don't use $unwind as unwind will simply separate all the documents of each collections. So apply simple lookup and then use $project for projection. Here is mongoDB query:

db.userInfo.aggregate([
    {
        $lookup: {
           from: "userRole",
           localField: "userId",
           foreignField: "userId",
           as: "userRole"
        }
    },
    {
        $lookup: {
            from: "userInfo",
            localField: "userId",
            foreignField: "userId",
            as: "userInfo"
        }
    },
    {$project: {
        "_id":0,
        "userRole._id":0,
        "userInfo._id":0
        }
        } ])

Here is the output:

/* 1 */ {
    "userId" : "AD",
    "phone" : "0000000000",
    "userRole" : [ 
        {
            "userId" : "AD",
            "role" : "admin"
        }
    ],
    "userInfo" : [ 
        {
            "userId" : "AD",
            "phone" : "0000000000"
        }
    ] }

Thanks.

How to find duplicate records in PostgreSQL

The basic idea will be using a nested query with count aggregation:

select * from yourTable ou
where (select count(*) from yourTable inr
where inr.sid = ou.sid) > 1

You can adjust the where clause in the inner query to narrow the search.


There is another good solution for that mentioned in the comments, (but not everyone reads them):

select Column1, Column2, count(*)
from yourTable
group by Column1, Column2
HAVING count(*) > 1

Or shorter:

SELECT (yourTable.*)::text, count(*)
FROM yourTable
GROUP BY yourTable.*
HAVING count(*) > 1

is there a css hack for safari only NOT chrome?

When using this safari-only filter I could target Safari (iOS and Mac), but exclude Chrome (and other browsers):

@supports (-webkit-backdrop-filter: blur(1px)) {
  .safari-only {
    background-color: rgb(76,80,84);
  }
}

How to wait 5 seconds with jQuery?

$( "#foo" ).slideUp( 300 ).delay( 5000 ).fadeIn( 400 );

"while :" vs. "while true"

The colon is a built-in command that does nothing, but returns 0 (success). Thus, it's shorter (and faster) than calling an actual command to do the same thing.

Currently running queries in SQL Server

Depending on your privileges, this query might work:

SELECT sqltext.TEXT,
req.session_id,
req.status,
req.command,
req.cpu_time,
req.total_elapsed_time
FROM sys.dm_exec_requests req
CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS sqltext

Ref: http://blog.sqlauthority.com/2009/01/07/sql-server-find-currently-running-query-t-sql

Working Copy Locked

Is your BitLocker disk encryption running? In my case, it locked the whole drive of the disk for encryption, and SVN failed with this error.

Trigger css hover with JS

You can't. It's not a trusted event.

Events that are generated by the user agent, either as a result of user interaction, or as a direct result of changes to the DOM, are trusted by the user agent with privileges that are not afforded to events generated by script through the DocumentEvent.createEvent("Event") method, modified using the Event.initEvent() method, or dispatched via the EventTarget.dispatchEvent() method. The isTrusted attribute of trusted events has a value of true, while untrusted events have a isTrusted attribute value of false.

Most untrusted events should not trigger default actions, with the exception of click or DOMActivate events.

You have to add a class and add/remove that on the mouseover/mouseout events manually.


Side note, I'm answering this here after I marked this as a duplicate since no answer here really covers the issue from what I see. Hopefully, one day it'll be merged.

Fix height of a table row in HTML Table

the bottom cell will grow as you enter more text ... setting the table width will help too

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

<head>
</head>
<body>
<table id="content" style="min-height:525px; height:525px; width:100%; border:0px; margin:0; padding:0; border-collapse:collapse;">
<tr><td style="height:10px; background-color:#900;">Upper</td></tr>
<tr><td style="min-height:515px; height:515px; background-color:#909;">lower<br/>
</td></tr>
</table>
</body>
</html>

Error: Generic Array Creation

You can't create arrays with a generic component type.

Create an array of an explicit type, like Object[], instead. You can then cast this to PCB[] if you want, but I don't recommend it in most cases.

PCB[] res = (PCB[]) new Object[list.size()]; /* Not type-safe. */

If you want type safety, use a collection like java.util.List<PCB> instead of an array.

By the way, if list is already a java.util.List, you should use one of its toArray() methods, instead of duplicating them in your code. This doesn't get your around the type-safety problem though.

Make an HTTP request with android

Use Volley as suggested above. Add following into build.gradle (Module: app)

implementation 'com.android.volley:volley:1.1.1'

Add following into AndroidManifest.xml:

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

And add following to you Activity code:

public void httpCall(String url) {

    RequestQueue queue = Volley.newRequestQueue(this);

    StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    // enjoy your response
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    // enjoy your error status
                }
    });

    queue.add(stringRequest);
}

It replaces http client and it is very simple.

Add table row in jQuery

$('#myTable').append('<tr><td>my data</td><td>more data</td></tr>');

will add a new row to the first TBODY of the table, without depending of any THEAD or TFOOT present. (I didn't find information from which version of jQuery .append() this behavior is present.)

You may try it in these examples:

<table class="t"> <!-- table with THEAD, TBODY and TFOOT -->
<thead>
  <tr><th>h1</th><th>h2</th></tr>
</thead>
<tbody>
  <tr><td>1</td><td>2</td></tr>
</tbody>
<tfoot>
  <tr><th>f1</th><th>f2</th></tr>
</tfoot>
</table><br>

<table class="t"> <!-- table with two TBODYs -->
<thead>
  <tr><th>h1</th><th>h2</th></tr>
</thead>
<tbody>
  <tr><td>1</td><td>2</td></tr>
</tbody>
<tbody>
  <tr><td>3</td><td>4</td></tr>
</tbody>
<tfoot>
  <tr><th>f1</th><th>f2</th></tr>
</tfoot>
</table><br>

<table class="t">  <!-- table without TBODY -->
<thead>
  <tr><th>h1</th><th>h2</th></tr>
</thead>
</table><br>

<table class="t">  <!-- table with TR not in TBODY  -->
  <tr><td>1</td><td>2</td></tr>
</table>
<br>
<table class="t">
</table>

<script>
$('.t').append('<tr><td>a</td><td>a</td></tr>');
</script>

In which example a b row is inserted after 1 2, not after 3 4 in second example. If the table were empty, jQuery creates TBODY for a new row.

Android intent for playing video?

I have come across this with the Hero, using what I thought was a published API. In the end, I used a test to see if the intent could be received:

private boolean isCallable(Intent intent) {
    List<ResolveInfo> list = getPackageManager().queryIntentActivities(intent, 
        PackageManager.MATCH_DEFAULT_ONLY);
    return list.size() > 0;
}

In use when I would usually just start the activity:

final Intent intent = new Intent("com.android.camera.action.CROP");
intent.setClassName("com.android.camera", "com.android.camera.CropImage");
if (isCallable(intent)) {
    // call the intent as you intended.
} else {
    // make alternative arrangements.
}

obvious: If you go down this route - using non-public APIs - you must absolutely provide a fallback which you know definitely works. It doesn't have to be perfect, it can be a Toast saying that this is unsupported for this handset/device, but you should avoid an uncaught exception. end obvious.


I find the Open Intents Registry of Intents Protocols quite useful, but I haven't found the equivalent of a TCK type list of intents which absolutely must be supported, and examples of what apps do different handsets.

How can I make a time delay in Python?

Delays can be also implemented by using the following methods.

The first method:

import time
time.sleep(5) # Delay for 5 seconds.

The second method to delay would be using the implicit wait method:

 driver.implicitly_wait(5)

The third method is more useful when you have to wait until a particular action is completed or until an element is found:

self.wait.until(EC.presence_of_element_located((By.ID, 'UserName'))

Unsigned keyword in C++

Integer Types:

short            -> signed short
signed short
unsigned short
int              -> signed int
signed int
unsigned int
signed           -> signed int
unsigned         -> unsigned int
long             -> signed long
signed long
unsigned long

Be careful of char:

char  (is signed or unsigned depending on the implmentation)
signed char
unsigned char

"Proxy server connection failed" in google chrome

Try following these steps:

  1. Run Chrome as Administrator.
  2. Go to the settings in Chrome.
  3. Go to Advanced Settings (its all the way down).
  4. Scroll to Network Section and click on ''Change proxy settings''.
  5. A window will pop up with the name ''Internet Properties''
  6. Click on ''LAN settings''
  7. Un-check ''Use a proxy server for your LAN''
  8. Check ''Automatically detect settings''
  9. Click everything ''OK'' and you are done!

Does Ruby have a string.startswith("abc") built in method?

It's called String#start_with?, not String#startswith: In Ruby, the names of boolean-ish methods end with ? and the words in method names are separated with an _. Not sure where the s went, personally, I'd prefer String#starts_with? over the actual String#start_with?

Disable copy constructor

Make SymbolIndexer( const SymbolIndexer& ) private. If you're assigning to a reference, you're not copying.

When using Trusted_Connection=true and SQL Server authentication, will this affect performance?

If your web application is configured to impersonate a client, then using a trusted connection will potentially have a negative performance impact. This is because each client must use a different connection pool (with the client's credentials).

Most web applications don't use impersonation / delegation, and hence don't have this problem.

See this MSDN article for more information.

Exception : mockito wanted but not invoked, Actually there were zero interactions with this mock

You need to inject mock inside the class you're testing. At the moment you're interacting with the real object, not with the mock one. You can fix the code in a following way:

void testAbc(){
     myClass.myObj = myInteface;
     myClass.abc();
     verify(myInterface).myMethodToBeVerified(new String("a"), new String("b"));
}

although it would be a wiser choice to extract all initialization code into @Before

@Before
void setUp(){
     myClass = new myClass();
     myClass.myObj = myInteface;
}

@Test
void testAbc(){
     myClass.abc();
     verify(myInterface).myMethodToBeVerified(new String("a"), new String("b"));
}

Difference between `Optional.orElse()` and `Optional.orElseGet()`

First of all check the declaration of both the methods.

1) OrElse: Execute logic and pass result as argument.

public T orElse(T other) {    
 return value != null ? value : other;
}

2) OrElseGet: Execute logic if value inside the optional is null

public T orElseGet(Supplier<? extends T> other) {
  return value != null ? value : other.get(); 
}

Some explanation on above declaration: The argument of “Optional.orElse” always gets executed irrespective of the value of the object in optional (null, empty or with value). Always consider the above-mentioned point in mind while using “Optional.orElse”, otherwise use of “Optional.orElse” can be very risky in the following situation.

Risk-1) Logging Issue: If content inside orElse contains any log statement: In this case, you will end up logging it every time.

Optional.of(getModel())
   .map(x -> {
      //some logic
   })
  .orElse(getDefaultAndLogError());

getDefaultAndLogError() {
  log.error("No Data found, Returning default");
  return defaultValue;
}

Risk-2) Performance Issue: If content inside orElse is time-intensive: Time intensive content can be any i/o operations DB call, API call, file reading. If we put such content in orElse(), the system will end up executing a code of no use.

Optional.of(getModel())
   .map(x -> //some logic)
   .orElse(getDefaultFromDb());

getDefaultFromDb() {
   return dataBaseServe.getDefaultValue(); //api call, db call.
}

Risk-3) Illegal State or Bug Issue: If content inside orElse is mutating some object state: We might be using the same object at another place let say inside Optional.map function and it can put us in a critical bug.

List<Model> list = new ArrayList<>();
Optional.of(getModel())
  .map(x -> {
  })
  .orElse(get(list));

get(List < String > list) {
   log.error("No Data found, Returning default");
   list.add(defaultValue);
   return defaultValue;
}

Then, When can we go with orElse()? Prefer using orElse when the default value is some constant object, enum. In all above cases we can go with Optional.orElseGet() (which only executes when Optional contains non empty value)instead of Optional.orElse(). Why?? In orElse, we pass default result value, but in orElseGet we pass Supplier and method of Supplier only executes if the value in Optional is null.

Key takeaways from this:

  1. Do not use “Optional.orElse” if it contains any log statement.
  2. Do not use “Optional.orElse” if it contains time-intensive logic.
  3. Do not use “Optional.orElse” if it is mutating some object state.
  4. Use “Optional.orElse” if we have to return a constant, enum.
  5. Prefer “Optional.orElseGet” in the situations mentioned in 1,2 and 3rd points.

I have explained this in point-2 (“Optional.map/Optional.orElse” != “if/else”) my medium blog. Use Java8 as a programmer not as a coder

How to change ProgressBar's progress indicator color in Android

I copied this from one of my apps, so there's prob a few extra attributes, but should give you the idea. This is from the layout that has the progress bar:

<ProgressBar
    android:id="@+id/ProgressBar"
    style="?android:attr/progressBarStyleHorizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:indeterminate="false"
    android:maxHeight="10dip"
    android:minHeight="10dip"
    android:progress="50"
    android:progressDrawable="@drawable/greenprogress" />

Then create a new drawable with something similar to the following (In this case greenprogress.xml):

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@android:id/background">
        <shape>
            <corners android:radius="5dip" />
            <gradient
                android:angle="270"
                android:centerColor="#ff5a5d5a"
                android:centerY="0.75"
                android:endColor="#ff747674"
                android:startColor="#ff9d9e9d" />
        </shape>
    </item>

    <item android:id="@android:id/secondaryProgress">
        <clip>
            <shape>
                <corners android:radius="5dip" />
                <gradient
                    android:angle="270"
                    android:centerColor="#80ffb600"
                    android:centerY="0.75"
                    android:endColor="#a0ffcb00"
                    android:startColor="#80ffd300" />
            </shape>
        </clip>
    </item>
    <item android:id="@android:id/progress">
        <clip>
            <shape>
                <corners android:radius="5dip" />
                <gradient
                    android:angle="270"
                    android:endColor="#008000"
                    android:startColor="#33FF33" />
            </shape>
        </clip>
    </item>

</layer-list>

You can change up the colors as needed, this will give you a green progress bar.

How to filter data in dataview

DataView view = new DataView();
view.Table = DataSet1.Tables["Suppliers"];
view.RowFilter = "City = 'Berlin'";
view.RowStateFilter = DataViewRowState.ModifiedCurrent;
view.Sort = "CompanyName DESC";

// Simple-bind to a TextBox control
Text1.DataBindings.Add("Text", view, "CompanyName");

Ref: http://www.csharp-examples.net/dataview-rowfilter/

http://msdn.microsoft.com/en-us/library/system.data.dataview.rowfilter.aspx

ImportError: Couldn't import Django

If you are using python 3 use py in front of cmd code, like this

py manage.py runserver

Pass array to mvc Action via AJAX

You should be able to do this just fine:

$.ajax({
   url: 'controller/myaction',
   data: JSON.stringify({
      myKey: myArray
   }),
   success: function(data) { /* Whatever */ }
});

Then your action method would be like so:

public ActionResult(List<int> myKey)
{
    // Do Stuff
}

For you, it looks like you just need to stringify your values. The JSONValueProvider in MVC will convert that back into an IEnumerable for you.

Rounding integer division (instead of truncating)

A code that works for any sign in dividend and divisor:

int divRoundClosest(const int n, const int d)
{
  return ((n < 0) ^ (d < 0)) ? ((n - d/2)/d) : ((n + d/2)/d);
}

In response to a comment "Why is this actually working?", we can break this apart. First, observe that n/d would be the quotient, but it is truncated towards zero, not rounded. You get a rounded result if you add half of the denominator to the numerator before dividing, but only if numerator and denominator have the same sign. If the signs differ, you must subtract half of the denominator before dividing. Putting all that together:

(n < 0) is false (zero) if n is non-negative
(d < 0) is false (zero) if d is non-negative
((n < 0) ^ (d < 0)) is true if n and d have opposite signs
(n + d/2)/d is the rounded quotient when n and d have the same sign
(n - d/2)/d is the rounded quotient when n and d have opposite signs

If you prefer a macro:

#define DIV_ROUND_CLOSEST(n, d) ((((n) < 0) ^ ((d) < 0)) ? (((n) - (d)/2)/(d)) : (((n) + (d)/2)/(d)))

The linux kernel macro DIV_ROUND_CLOSEST doesn't work for negative divisors!

EDIT: This will work without overflow:

int divRoundClosest( int A, int B )
{
if(A<0)
    if(B<0)
        return (A + (-B+1)/2) / B + 1;
    else
        return (A + ( B+1)/2) / B - 1;
else
    if(B<0)
        return (A - (-B+1)/2) / B - 1;
    else
        return (A - ( B+1)/2) / B + 1;
}

Convert string to BigDecimal in java

BigDecimal b = BigDecimal.valueOf(d);

import java.math.*; 

public class Test { 

    public static void main(String[] args) 
    { 

        // Creating a Double Object 
        Double d = new Double("785.254"); 

        /// Assigning the bigdecimal value of ln to b 
        BigDecimal b = BigDecimal.valueOf(d); 

        // Displaying BigDecimal value 
        System.out.println("The Converted BigDecimal value is: " + b); 
    } 
}

Send a base64 image in HTML email

Support, unfortunately, is brutal at best. Here's a post on the topic:

https://www.campaignmonitor.com/blog/email-marketing/2013/02/embedded-images-in-html-email/

And the post content: enter image description here

Java current machine name and logged in user?

To get the currently logged in user:

System.getProperty("user.name"); //platform independent 

and the hostname of the machine:

java.net.InetAddress localMachine = java.net.InetAddress.getLocalHost();
System.out.println("Hostname of local machine: " + localMachine.getHostName());

How do I point Crystal Reports at a new database

Use the Database menu and "Set Datasource Location" menu option to change the name or location of each table in a report.

This works for changing the location of a database, changing to a new database, and changing the location or name of an individual table being used in your report.

To change the datasource connection, go the Database menu and click Set Datasource Location.

  1. Change the Datasource Connection:
    1. From the Current Data Source list (the top box), click once on the datasource connection that you want to change.
    2. In the Replace with list (the bottom box), click once on the new datasource connection.
    3. Click Update.
  2. Change Individual Tables:
    1. From the Current Data Source list (the top box), expand the datasource connection that you want to change.
    2. Find the table for which you want to update the location or name.
    3. In the Replace with list (the bottom box), expand the new datasource connection.
    4. Find the new table you want to update to point to.
    5. Click Update.
    6. Note that if the table name has changed, the old table name will still appear in the Field Explorer even though it is now using the new table. (You can confirm this be looking at the Table Name of the table's properties in Current Data Source in Set Datasource Location. Screenshot http://i.imgur.com/gzGYVTZ.png) It's possible to rename the old table name to the new name from the context menu in Database Expert -> Selected Tables.
  3. Change Subreports:
    1. Repeat each of the above steps for any subreports you might have embedded in your report.
    2. Close the Set Datasource Location window.
  4. Any Commands or SQL Expressions:
    1. Go to the Database menu and click Database Expert.
    2. If the report designer used "Add Command" to write custom SQL it will be shown in the Selected Tables box on the right.
    3. Right click that command and choose "Edit Command".
    4. Check if that SQL is specifying a specific database. If so you might need to change it.
    5. Close the Database Expert window.
    6. In the Field Explorer pane on the right, right click any SQL Expressions.
    7. Check if the SQL Expressions are specifying a specific database. If so you might need to change it also.
    8. Save and close your Formula Editor window when you're done editing.

And try running the report again.

The key is to change the datasource connection first, then any tables you need to update, then the other stuff. The connection won't automatically change the tables underneath. Those tables are like goslings that've imprinted on the first large goose-like animal they see. They'll continue to bypass all reason and logic and go to where they've always gone unless you specifically manually change them.

To make it more convenient, here's a tip: You can "Show SQL Query" in the Database menu, and you'll see table names qualified with the database (like "Sales"."dbo"."Customers") for any tables that go straight to a specific database. That might make the hunting easier if you have a lot of stuff going on. When I tackled this problem I had to change each and every table to point to the new table in the new database.

R adding days to a date

In addition to the simple addition shown by others, you can also use seq.Date or seq.POSIXt to find other increments or decrements (the POSIXt version does seconds, minutes, hours, etc.):

> seq.Date( Sys.Date(), length=2, by='3 months' )[2]
[1] "2012-07-25"

Imply bit with constant 1 or 0 in SQL Server

Unfortunately, no. You will have to cast each value individually.

How can I wait for 10 second without locking application UI in android

You can use this:

Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    public void run() {
     // Actions to do after 10 seconds
    }
}, 10000);

For Stop the Handler, You can try this: handler.removeCallbacksAndMessages(null);

How can I format the output of a bash command in neat columns

column(1) is your friend.

$ column -t <<< '"option-y"      yank-pop
> "option-z"      execute-last-named-cmd
> "option-|"      vi-goto-column
> "option-~"      _bash_complete-word
> "option-control-?"      backward-kill-word
> "control-_"     undo
> "control-?"     backward-delete-char
> '
"option-y"          yank-pop
"option-z"          execute-last-named-cmd
"option-|"          vi-goto-column
"option-~"          _bash_complete-word
"option-control-?"  backward-kill-word
"control-_"         undo
"control-?"         backward-delete-char

How to open the terminal in Atom?

  1. Open your Atom IDE
  2. press ctrl+shift+P and search for "platformio-ide-terminal" package
  3. press install
  4. once installed press ctrl+~ (tilde above tab key in a standard keyboard)
  5. terminal opens enjoy!!!

How to get just the parent directory name of a specific file

File f = new File("C:/aaa/bbb/ccc/ddd/test.java");
System.out.println(f.getParentFile().getName())

f.getParentFile() can be null, so you should check it.

How to implement linear interpolation?

Instead of extrapolating off the ends, you could return the extents of the y_list. Most of the time your application is well behaved, and the Interpolate[x] will be in the x_list. The (presumably) linear affects of extrapolating off the ends may mislead you to believe that your data is well behaved.

  • Returning a non-linear result (bounded by the contents of x_list and y_list) your program's behavior may alert you to an issue for values greatly outside x_list. (Linear behavior goes bananas when given non-linear inputs!)

  • Returning the extents of the y_list for Interpolate[x] outside of x_list also means you know the range of your output value. If you extrapolate based on x much, much less than x_list[0] or x much, much greater than x_list[-1], your return result could be outside of the range of values you expected.

    def __getitem__(self, x):
        if x <= self.x_list[0]:
            return self.y_list[0]
        elif x >= self.x_list[-1]:
            return self.y_list[-1]
        else:
            i = bisect_left(self.x_list, x) - 1
            return self.y_list[i] + self.slopes[i] * (x - self.x_list[i])
    

How do I handle ImeOptions' done button click?

Kotlin Solution

The base way to handle it in Kotlin is:

edittext.setOnEditorActionListener { _, actionId, _ ->
    if (actionId == EditorInfo.IME_ACTION_DONE) {
        callback.invoke()
        true
    }
    false
}

Kotlin Extension

Use this to just call edittext.onDone{/*action*/} in your main code. Makes your code far more readable and maintainable

fun EditText.onDone(callback: () -> Unit) {
    setOnEditorActionListener { _, actionId, _ ->
        if (actionId == EditorInfo.IME_ACTION_DONE) {
            callback.invoke()
            true
        }
        false
    }
}

Don't forget to add these options to your edittext

<EditText ...
    android:imeOptions="actionDone"
    android:inputType="text"/>

If you need inputType="textMultiLine" support, read this post

Select All Rows Using Entity Framework

Here is a few ways to do it (Just assume I'm using Dependency Injection for the DbConext)

public class Example
{
    private readonly DbContext Context;

    public Example(DbContext context)
    {
        Context = context;
    }

    public DbSetSampleOne[] DbSamples { get; set; }

    public void ExampleMethod DoSomething()
    {
        // Example 1: This will select everything from the entity you want to select
        DbSamples = Context.DbSetSampleOne.ToArray();

        // Example 2: If you want to apply some filtering use the following example
        DbSamples = Context.DbSetSampleOne.ToArray().Where(p => p.Field.Equals("some filter"))

    }

Hibernate Criteria Query to get specific columns

You can map another entity based on this class (you should use entity-name in order to distinct the two) and the second one will be kind of dto (dont forget that dto has design issues ). you should define the second one as readonly and give it a good name in order to be clear that this is not a regular entity. by the way select only few columns is called projection , so google with it will be easier.

alternative - you can create named query with the list of fields that you need (you put them in the select ) or use criteria with projection

How to bring an activity to foreground (top of stack)?

FLAG_ACTIVITY_REORDER_TO_FRONT: If set in an Intent passed to Context.startActivity(), this flag will cause the launched activity to be brought to the front of its task's history stack if it is already running.

Intent i = new Intent(context, AActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(i);

Left align and right align within div in Bootstrap

bootstrap 5.0

_x000D_
_x000D_
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">

<div class="row">
  <div class="col-sm-6"><p class="float-start">left</p></div>  
  <div class="col-sm-6"><p class="float-end">right</p></div>  
</div>
_x000D_
_x000D_
_x000D_

A whole column can accommodate 12, 6 (col-sm-6) is exactly half, and in this half, one to the left(float-start) and one to the right(float-end).

more example

  • fontawesome-button

    _x000D_
    _x000D_
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
    
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.2/css/all.min.css" integrity="sha512-HK5fgLBL+xu6dm/Ii3z4xhlSUyZgTT9tuc/hSrtw6uzJOvgRr2a9jyxxT1ely+B+xFAmJKVSTbpM/CuL7qxO8w==" crossorigin="anonymous" />
    
    <div class="row">
      <div class=col-sm-6>
        <p class="float-start text-center">  <!-- text-center can help you put the icon at the center -->
          <a class="text-decoration-none" href="https://www.google.com/"
          ><i class="fas fa-arrow-circle-left fa-3x"></i><br>Left
          </a>
        </p>
      </div>
      <div class=col-sm-6>
        <p class="float-end text-center">
          <a class="text-decoration-none" href="https://www.google.com/"
          ><i class="fas fa-arrow-circle-right fa-3x"></i><br>Right
          </a>
        </p>
      </div>  
    _x000D_
    _x000D_
    _x000D_

Dropdown using javascript onchange

It does not work because your script in JSFiddle is running inside it's own scope (see the "OnLoad" drop down on the left?).

One way around this is to bind your event handler in javascript (where it should be):

document.getElementById('optionID').onchange = function () {
    document.getElementById("message").innerHTML = "Having a Baby!!";
};

Another way is to modify your code for the fiddle environment and explicitly declare your function as global so it can be found by your inline event handler:

window.changeMessage() {
    document.getElementById("message").innerHTML = "Having a Baby!!";
};

?

How to launch PowerShell (not a script) from the command line

Set the default console colors and fonts:

http://poshcode.org/2220
From Windows PowerShell Cookbook (O'Reilly)
by Lee Holmes (http://www.leeholmes.com/guide)

Set-StrictMode -Version Latest

Push-Location
Set-Location HKCU:\Console
New-Item '.\%SystemRoot%_system32_WindowsPowerShell_v1.0_powershell.exe'
Set-Location '.\%SystemRoot%_system32_WindowsPowerShell_v1.0_powershell.exe'

New-ItemProperty . ColorTable00 -type DWORD -value 0x00562401
New-ItemProperty . ColorTable07 -type DWORD -value 0x00f0edee
New-ItemProperty . FaceName -type STRING -value "Lucida Console"
New-ItemProperty . FontFamily -type DWORD -value 0x00000036
New-ItemProperty . FontSize -type DWORD -value 0x000c0000
New-ItemProperty . FontWeight -type DWORD -value 0x00000190
New-ItemProperty . HistoryNoDup -type DWORD -value 0x00000000
New-ItemProperty . QuickEdit -type DWORD -value 0x00000001
New-ItemProperty . ScreenBufferSize -type DWORD -value 0x0bb80078
New-ItemProperty . WindowSize -type DWORD -value 0x00320078
Pop-Location

How to Automatically Close Alerts using Twitter Bootstrap

Calling window.setTimeout(function, delay) will allow you to accomplish this. Here's an example that will automatically close the alert 2 seconds (or 2000 milliseconds) after it is displayed.

$(".alert-message").alert();
window.setTimeout(function() { $(".alert-message").alert('close'); }, 2000);

If you want to wrap it in a nifty function you could do this.

function createAutoClosingAlert(selector, delay) {
   var alert = $(selector).alert();
   window.setTimeout(function() { alert.alert('close') }, delay);
}

Then you could use it like so...

createAutoClosingAlert(".alert-message", 2000);

I am certain there are more elegant ways to accomplish this.

Reading all files in a directory, store them in objects, and send the object

This is a modern Promise version of the previous one, using a Promise.all approach to resolve all promises when all files have been read:

/**
 * Promise all
 * @author Loreto Parisi (loretoparisi at gmail dot com)
 */
function promiseAllP(items, block) {
    var promises = [];
    items.forEach(function(item,index) {
        promises.push( function(item,i) {
            return new Promise(function(resolve, reject) {
                return block.apply(this,[item,index,resolve,reject]);
            });
        }(item,index))
    });
    return Promise.all(promises);
} //promiseAll

/**
 * read files
 * @param dirname string
 * @return Promise
 * @author Loreto Parisi (loretoparisi at gmail dot com)
 * @see http://stackoverflow.com/questions/10049557/reading-all-files-in-a-directory-store-them-in-objects-and-send-the-object
 */
function readFiles(dirname) {
    return new Promise((resolve, reject) => {
        fs.readdir(dirname, function(err, filenames) {
            if (err) return reject(err);
            promiseAllP(filenames,
            (filename,index,resolve,reject) =>  {
                fs.readFile(path.resolve(dirname, filename), 'utf-8', function(err, content) {
                    if (err) return reject(err);
                    return resolve({filename: filename, contents: content});
                });
            })
            .then(results => {
                return resolve(results);
            })
            .catch(error => {
                return reject(error);
            });
        });
  });
}

How to Use It:

Just as simple as doing:

readFiles( EMAIL_ROOT + '/' + folder)
.then(files => {
    console.log( "loaded ", files.length );
    files.forEach( (item, index) => {
        console.log( "item",index, "size ", item.contents.length);
    });
})
.catch( error => {
    console.log( error );
});

Supposed that you have another list of folders you can as well iterate over this list, since the internal promise.all will resolve each of then asynchronously:

var folders=['spam','ham'];
folders.forEach( folder => {
    readFiles( EMAIL_ROOT + '/' + folder)
    .then(files => {
        console.log( "loaded ", files.length );
        files.forEach( (item, index) => {
            console.log( "item",index, "size ", item.contents.length);
        });
    })
    .catch( error => {
        console.log( error );
    });
});

How it Works

The promiseAll does the magic. It takes a function block of signature function(item,index,resolve,reject), where item is the current item in the array, index its position in the array, and resolve and reject the Promise callback functions. Each promise will be pushed in a array at the current index and with the current item as arguments through a anonymous function call:

promises.push( function(item,i) {
        return new Promise(function(resolve, reject) {
            return block.apply(this,[item,index,resolve,reject]);
        });
    }(item,index))

Then all promises will be resolved:

return Promise.all(promises);

Index of duplicates items in a python list

I'll mention the more obvious way of dealing with duplicates in lists. In terms of complexity, dictionaries are the way to go because each lookup is O(1). You can be more clever if you're only interested in duplicates...

my_list = [1,1,2,3,4,5,5]
my_dict = {}
for (ind,elem) in enumerate(my_list):
    if elem in my_dict:
        my_dict[elem].append(ind)
    else:
        my_dict.update({elem:[ind]})

for key,value in my_dict.iteritems():
    if len(value) > 1:
        print "key(%s) has indices (%s)" %(key,value)

which prints the following:

key(1) has indices ([0, 1])
key(5) has indices ([5, 6])

How to concatenate two strings in SQL Server 2005

DECLARE @COMBINED_STRINGS AS VARCHAR(50),
        @STRING1 AS VARCHAR(20),
        @STRING2 AS VARCHAR(20);

SET @STRING1 = 'rupesh''s';
SET @STRING2 = 'malviya';
SET @COMBINED_STRINGS = @STRING1 + @STRING2;

SELECT @COMBINED_STRINGS;

SELECT '2' + '3';

I typed this in a sql file named TEST.sql and I run it. I got the following out put.

+-------------------+
| @COMBINED_STRINGS |
+-------------------+
|                 0 |
+-------------------+
1 row in set (0.00 sec)

+-----------+
| '2' + '3' |
+-----------+
|         5 |
+-----------+
1 row in set (0.00 sec)

After looking into this issue a bit more I found the best and sure sort way for string concatenation in SQL is by using CONCAT method. So I made the following changes in the same file.

#DECLARE @COMBINED_STRINGS AS VARCHAR(50),
 #       @STRING1 AS VARCHAR(20),
 #       @STRING2 AS VARCHAR(20);

SET @STRING1 = 'rupesh''s';
SET @STRING2 = 'malviya';
#SET @COMBINED_STRINGS = @STRING1 + @STRING2;
SET @COMBINED_STRINGS = (SELECT CONCAT(@STRING1, @STRING2));

SELECT @COMBINED_STRINGS;

#SELECT '2' + '3';
SELECT CONCAT('2','3');

and after executing the file this was the output.

+-------------------+
| @COMBINED_STRINGS |
+-------------------+
| rupesh'smalviya   |
+-------------------+
1 row in set (0.00 sec)

+-----------------+
| CONCAT('2','3') |
+-----------------+
| 23              |
+-----------------+
1 row in set (0.00 sec)

SQL version I am using is: 14.14

The EntityManager is closed

I faced the same problem while testing the changes in Symfony 4.3.2

I lowered the log level to INFO

And ran the test again

And the logged showed this:

console.ERROR: Error thrown while running command "doctrine:schema:create". Message: "[Semantical Error] The annotation "@ORM\Id" in property App\Entity\Common::$id was never imported. Did you maybe forget to add a "use" statement for this annotation?" {"exception":"[object] (Doctrine\\Common\\Annotations\\AnnotationException(code: 0): [Semantical Error] The annotation \"@ORM\\Id\" in property App\\Entity\\Common::$id was never imported. Did you maybe forget to add a \"use\" statement for this annotation? at C:\\xampp\\htdocs\\dirty7s\\vendor\\doctrine\\annotations\\lib\\Doctrine\\Common\\Annotations\\AnnotationException.php:54)","command":"doctrine:schema:create","message":"[Semantical Error] The annotation \"@ORM\\Id\" in property App\\Entity\\Common::$id was never imported. Did you maybe forget to add a \"use\" statement for this annotation?"} []

This means that some error in the code causes the:

Doctrine\ORM\ORMException: The EntityManager is closed.

So it is a good idea to check the log

Text file in VBA: Open/Find Replace/SaveAs/Close File

Just add this line

sFileName = "C:\someotherfilelocation"

right before this line

Open sFileName For Output As iFileNum

The idea is to open and write to a different file than the one you read earlier (C:\filelocation).

If you want to get fancy and show a real "Save As" dialog box, you could do this instead:

sFileName = Application.GetSaveAsFilename()

Serialize an object to string

I felt a like I needed to share this manipulated code to the accepted answer - as I have no reputation, I'm unable to comment..

using System;
using System.Xml.Serialization;
using System.IO;

namespace ObjectSerialization
{
    public static class ObjectSerialization
    {
        // THIS: (C): https://stackoverflow.com/questions/2434534/serialize-an-object-to-string
        /// <summary>
        /// A helper to serialize an object to a string containing XML data of the object.
        /// </summary>
        /// <typeparam name="T">An object to serialize to a XML data string.</typeparam>
        /// <param name="toSerialize">A helper method for any type of object to be serialized to a XML data string.</param>
        /// <returns>A string containing XML data of the object.</returns>
        public static string SerializeObject<T>(this T toSerialize)
        {
            // create an instance of a XmlSerializer class with the typeof(T)..
            XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType());

            // using is necessary with classes which implement the IDisposable interface..
            using (StringWriter stringWriter = new StringWriter())
            {
                // serialize a class to a StringWriter class instance..
                xmlSerializer.Serialize(stringWriter, toSerialize); // a base class of the StringWriter instance is TextWriter..
                return stringWriter.ToString(); // return the value..
            }
        }

        // THIS: (C): VPKSoft, 2018, https://www.vpksoft.net
        /// <summary>
        /// Deserializes an object which is saved to an XML data string. If the object has no instance a new object will be constructed if possible.
        /// <note type="note">An exception will occur if a null reference is called an no valid constructor of the class is available.</note>
        /// </summary>
        /// <typeparam name="T">An object to deserialize from a XML data string.</typeparam>
        /// <param name="toDeserialize">An object of which XML data to deserialize. If the object is null a a default constructor is called.</param>
        /// <param name="xmlData">A string containing a serialized XML data do deserialize.</param>
        /// <returns>An object which is deserialized from the XML data string.</returns>
        public static T DeserializeObject<T>(this T toDeserialize, string xmlData)
        {
            // if a null instance of an object called this try to create a "default" instance for it with typeof(T),
            // this will throw an exception no useful constructor is found..
            object voidInstance = toDeserialize == null ? Activator.CreateInstance(typeof(T)) : toDeserialize;

            // create an instance of a XmlSerializer class with the typeof(T)..
            XmlSerializer xmlSerializer = new XmlSerializer(voidInstance.GetType());

            // construct a StringReader class instance of the given xmlData parameter to be deserialized by the XmlSerializer class instance..
            using (StringReader stringReader = new StringReader(xmlData))
            {
                // return the "new" object deserialized via the XmlSerializer class instance..
                return (T)xmlSerializer.Deserialize(stringReader);
            }
        }

        // THIS: (C): VPKSoft, 2018, https://www.vpksoft.net
        /// <summary>
        /// Deserializes an object which is saved to an XML data string.
        /// </summary>
        /// <param name="toDeserialize">A type of an object of which XML data to deserialize.</param>
        /// <param name="xmlData">A string containing a serialized XML data do deserialize.</param>
        /// <returns>An object which is deserialized from the XML data string.</returns>
        public static object DeserializeObject(Type toDeserialize, string xmlData)
        {
            // create an instance of a XmlSerializer class with the given type toDeserialize..
            XmlSerializer xmlSerializer = new XmlSerializer(toDeserialize);

            // construct a StringReader class instance of the given xmlData parameter to be deserialized by the XmlSerializer class instance..
            using (StringReader stringReader = new StringReader(xmlData))
            {
                // return the "new" object deserialized via the XmlSerializer class instance..
                return xmlSerializer.Deserialize(stringReader);
            }
        }
    }
}

No Persistence provider for EntityManager named

I had the same problem, I removed "@ManagedBean" from my bean class now working.

How to convert date in to yyyy-MM-dd Format?

UPDATE My Answer here is now outdated. The Joda-Time project is now in maintenance mode, advising migration to the java.time classes. See the modern solution in the Answer by Ole V.V..

Joda-Time

The accepted answer by NidhishKrishnan is correct.

For fun, here is the same kind of code in Joda-Time 2.3.

// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;

java.util.Date date = new Date(); // A Date object coming from other code.

// Pass the java.util.Date object to constructor of Joda-Time DateTime object.
DateTimeZone kolkataTimeZone = DateTimeZone.forID( "Asia/Kolkata" );
DateTime dateTimeInKolkata = new DateTime( date, kolkataTimeZone );

DateTimeFormatter formatter = DateTimeFormat.forPattern( "yyyy-MM-dd");
System.out.println( "dateTimeInKolkata formatted for date: " + formatter.print( dateTimeInKolkata ) );
System.out.println( "dateTimeInKolkata formatted for ISO 8601: " + dateTimeInKolkata );

When run…

dateTimeInKolkata formatted for date: 2013-12-17
dateTimeInKolkata formatted for ISO 8601: 2013-12-17T14:56:46.658+05:30

What does "hashable" mean in Python?

From the Python glossary:

An object is hashable if it has a hash value which never changes during its lifetime (it needs a __hash__() method), and can be compared to other objects (it needs an __eq__() or __cmp__() method). Hashable objects which compare equal must have the same hash value.

Hashability makes an object usable as a dictionary key and a set member, because these data structures use the hash value internally.

All of Python’s immutable built-in objects are hashable, while no mutable containers (such as lists or dictionaries) are. Objects which are instances of user-defined classes are hashable by default; they all compare unequal, and their hash value is their id().

Android load from URL to Bitmap

Please try this following steps.

1) Create AsyncTask in class or adapter(if you want to change the list item image).

public class AsyncTaskLoadImage extends AsyncTask<String, String, Bitmap> {
        private final static String TAG = "AsyncTaskLoadImage";
        private ImageView imageView;

        public AsyncTaskLoadImage(ImageView imageView) {
            this.imageView = imageView;
        }

        @Override
        protected Bitmap doInBackground(String... params) {
            Bitmap bitmap = null;
            try {
                URL url = new URL(params[0]);
                bitmap = BitmapFactory.decodeStream((InputStream) url.getContent());
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            try {
                int width, height;
                height = bitmap.getHeight();
                width = bitmap.getWidth();

                Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
                Canvas c = new Canvas(bmpGrayscale);
                Paint paint = new Paint();
                ColorMatrix cm = new ColorMatrix();
                cm.setSaturation(0);
                ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
                paint.setColorFilter(f);
                c.drawBitmap(bitmap, 0, 0, paint);
                imageView.setImageBitmap(bmpGrayscale);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

2) Call the AsyncTask from your activity, fragment or adapter(inside onBindViewHolder).

2.a) For adapter:

    String src = current.getProductImage();
    new AsyncTaskLoadImage(holder.icon).execute(src);

2.b) For activity and fragment:

**Activity:**
  ImageView imagview= (ImageView) findViewById(R.Id.imageview);
  String src = (your image string);
  new AsyncTaskLoadImage(imagview).execute(src);

**Fragment:**
  ImageView imagview= (ImageView)view.findViewById(R.Id.imageview);
  String src = (your image string);
  new AsyncTaskLoadImage(imagview).execute(src);

3) Kindly run the app and check the image.

Happy coding....:)

Convert a list to a string in C#

The direct answer to your question is String.Join as others have mentioned.

However, if you need some manipulations, you can use Aggregate:

List<string> employees = new List<string>();
employees.Add("e1");
employees.Add("e2");
employees.Add("e3");

string employeesString = "'" + employees.Aggregate((x, y) => x + "','" + y) + "'";
Console.WriteLine(employeesString);
Console.ReadLine();

.append(), prepend(), .after() and .before()

Imagine the DOM (HTML page) as a tree right. The HTML elements are the nodes of this tree.

The append() adds a new node to the child of the node you called it on.

Example:$("#mydiv").append("<p>Hello there</p>") 

creates a child node <p> to <div>

The after() adds a new node as a sibling or at the same level or child to the parent of the node you called it on.

The import android.support cannot be resolved

andorid-support-v4.jar is an external jar file that you have to import into your project.

This is how you do it in Android Studio:

Go to File -> Project Structure enter image description here

Go to "Dependencies" Tab -> Click on the Plus sign -> Go to "Library dependency" enter image description here

Select the support library "support-v4 (com.android.support:support-v4:23.0.1)" enter image description here

Now to go your "build.gradle" file in your app and make sure the android support library has been added to your dependencies. Alternatively, you could've also just typed compile 'com.android.support:support-v4:23.0.1' directly into your dependencies{} instead of doing it through the GUI.

enter image description here

Rebuild your project and now everything should work. enter image description here

How to push files to an emulator instance using Android Studio

Open command prompt and give the platform-tools path of the sdk. Eg:- C:\Android\sdk\platform-tools> Then type 'adb push' command like below,

C:\Android\sdk\platform-tools>adb push C:\MyFiles\fileName.txt /sdcard/fileName.txt

This command push the file to the root folder of the emulator.

SQL to LINQ Tool

Edit 7/17/2020: I cannot delete this accepted answer. It used to be good, but now it isn't. Beware really old posts, guys. I'm removing the link.

[Linqer] is a SQL to LINQ converter tool. It helps you to learn LINQ and convert your existing SQL statements.

Not every SQL statement can be converted to LINQ, but Linqer covers many different types of SQL expressions. Linqer supports both .NET languages - C# and Visual Basic.

Get the string representation of a DOM node

I've found that for my use-cases I don't always want the entire outerHTML. Many nodes just have too many children to show.

Here's a function (minimally tested in Chrome):

/**
 * Stringifies a DOM node.
 * @param {Object} el - A DOM node.
 * @param {Number} truncate - How much to truncate innerHTML of element.
 * @returns {String} - A stringified node with attributes
 *                     retained.
 */
function stringifyEl(el, truncate) {
    var truncateLen = truncate || 50;
    var outerHTML = el.outerHTML;
    var ret = outerHTML;
    ret = ret.substring(0, truncateLen);

    // If we've truncated, add an elipsis.
    if (outerHTML.length > truncateLen) {
      ret += "...";
    }
    return ret;
}

https://gist.github.com/kahunacohen/467f5cc259b5d4a85eb201518dcb15ec

What's the function like sum() but for multiplication? product()?

Actually, Guido vetoed the idea: http://bugs.python.org/issue1093

But, as noted in that issue, you can make one pretty easily:

from functools import reduce # Valid in Python 2.6+, required in Python 3
import operator

reduce(operator.mul, (3, 4, 5), 1)

Using LIKE in an Oracle IN clause

select * from tbl
 where exists (select 1 from all_likes where all_likes.value = substr(tbl.my_col,0, length(tbl.my_col)))

Where is the list of predefined Maven properties

Looking at the "effective POM" will probably help too. For instance, if you wanted to know what the path is for ${project.build.sourceDirectory}

you would find the related XML in the effective POM, such as: <project> <build> <sourceDirectory>/my/path</sourceDirectory>

Also helpful - you can do a real time evaluation of properties via the command line execution of mvn help:evaluate while in the same dir as the POM.

How to get input text length and validate user in javascript

JavaScript validation is not secure as anybody can change what your script does in the browser. Using it for enhancing the visual experience is ok though.

var textBox = document.getElementById("myTextBox");
var textLength = textBox.value.length;
if(textLength > 5)
{
    //red
    textBox.style.backgroundColor = "#FF0000";
}
else
{
    //green
    textBox.style.backgroundColor = "#00FF00";
}

What is the proper way to test if a parameter is empty in a batch file?

One of the best semi solutions is to copy %1 into a variable and then use delayed expansion, as delayedExp. is always safe against any content.

set "param1=%~1"
setlocal EnableDelayedExpansion
if "!param1!"=="" ( echo it is empty )
rem ... or use the DEFINED keyword now
if defined param1 echo There is something

The advantage of this is that dealing with param1 is absolutly safe.

And the setting of param1 will work in many cases, like

test.bat hello"this is"a"test
test.bat you^&me

But it still fails with strange contents like

test.bat ^&"&

To be able to get a 100% correct answer for the existence

It detects if %1 is empty, but for some content it can't fetch the content.
This can be also be useful to distinguish between an empty %1 and one with "".
It uses the ability of the CALL command to fail without aborting the batch file.

@echo off
setlocal EnableDelayedExpansion
set "arg1="
call set "arg1=%%1"

if defined arg1 goto :arg_exists

set "arg1=#"
call set "arg1=%%1"
if "!arg1!" EQU "#" (
    echo arg1 exists, but can't assigned to a variable
    REM Try to fetch it a second time without quotes
    (call set arg1=%%1)
    goto :arg_exists
)

echo arg1 is missing
exit /b

:arg_exists
echo arg1 exists, perhaps the content is '!arg1!'

If you want to be 100% bullet proof to fetch the content, you could read How to receive even the strangest command line parameters?

CS1617: Invalid option ‘6’ for /langversion; must be ISO-1, ISO-2, 3, 4, 5 or Default

I just the changed the langversion to default and it worked for me. VS 2015

<system.codedom>
<compilers>
  <compiler language=”c#;cs;csharp” extension=”.cs” type=”Microsoft.CSharp.CSharpCodeProvider, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" warningLevel=”4" compilerOptions=”/langversion:default /nowarn:1659;1699;1701">
    <providerOption name=”CompilerVersion” value=”v4.0"/>
  </compiler>
  <compiler language=”vb;vbs;visualbasic;vbscript” extension=”.vb” type=”Microsoft.VisualBasic.VBCodeProvider, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" warningLevel=”4" compilerOptions=”/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+”>
      <providerOption name=”CompilerVersion” value=”v4.0"/>
  </compiler>
</compilers>

JUnit 5: How to assert an exception is thrown?

You can use assertThrows(), which allows you to test multiple exceptions within the same test. With support for lambdas in Java 8, this is the canonical way to test for exceptions in JUnit.

Per the JUnit docs:

import static org.junit.jupiter.api.Assertions.assertThrows;

@Test
void exceptionTesting() {
    MyException thrown = assertThrows(
           MyException.class,
           () -> myObject.doThing(),
           "Expected doThing() to throw, but it didn't"
    );

    assertTrue(thrown.getMessage().contains("Stuff"));
}

Saving and loading objects and using pickle

You didn't open the file in binary mode.

open("Fruits.obj",'rb')

Should work.

For your second error, the file is most likely empty, which mean you inadvertently emptied it or used the wrong filename or something.

(This is assuming you really did close your session. If not, then it's because you didn't close the file between the write and the read).

I tested your code, and it works.

Eclipse fonts and background color

To change background colour

  1. Open menu *Windows ? Preferences ? General ? Editors ? Text Editors
    • Browse Appearance color options
    • Select background color options, uncheck default, change to black
    • Select background color options, uncheck default, change to colour of choice

To change text colours

  1. Open Java ? Editor ? Syntax Colouring
    • Select element from Java
    • Change colour
    • List item

To change Java editor font

  1. Open menu Windows ? Preferences ? General ? Appearance ? Colors and Fonts
    • Select Java ? Java Editor Text font from list
    • Click on change and select font

Finding all cycles in a directed graph

Start at node X and check for all child nodes (parent and child nodes are equivalent if undirected). Mark those child nodes as being children of X. From any such child node A, mark it's children of being children of A, X', where X' is marked as being 2 steps away.). If you later hit X and mark it as being a child of X'', that means X is in a 3 node cycle. Backtracking to it's parent is easy (as-is, the algorithm has no support for this so you'd find whichever parent has X').

Note: If graph is undirected or has any bidirectional edges, this algorithm gets more complicated, assuming you don't want to traverse the same edge twice for a cycle.

Using pointer to char array, values in that array can be accessed?

When you want to access an element, you have to first dereference your pointer, and then index the element you want (which is also dereferncing). i.e. you need to do:

printf("\nvalue:%c", (*ptr)[0]); , which is the same as *((*ptr)+0)

Note that working with pointer to arrays are not very common in C. instead, one just use a pointer to the first element in an array, and either deal with the length as a separate element, or place a senitel value at the end of the array, so one can learn when the array ends, e.g.

char arr[5] = {'a','b','c','d','e',0}; 
char *ptr = arr; //same as char *ptr = &arr[0]

printf("\nvalue:%c", ptr[0]);

What are the JavaScript KeyCodes?

http://keycodes.atjayjo.com/

This app is just awesome. It is essentially a virtual keyboard that immediately shows you the keycode pressed on a standard US keyboard.

The most sophisticated way for creating comma-separated Strings from a Collection/Array/List?

The nice thing about the IN expression is that if you have repeated values, it does not change the result. So, just duplicate the first item and process the entire list. This assumes that there is at least one item in the list. If there are no items, I'd suggest checking for that first and then not executing the SQL at all.

This will do the trick, is obvious in what it is doing and does not rely on any external libraries:

StringBuffer inString = new StringBuffer(listOfIDs.get(0).toString());
for (Long currentID : listOfIDs) {
  inString.append(",").append(currentID);
}

Insert into C# with SQLCommand

You can use dapper library:

conn2.Execute(@"INSERT INTO klant(klant_id,naam,voornaam) VALUES (@p1,@p2,@p3)", 
                new { p1 = klantId, p2 = klantNaam, p3 = klantVoornaam });

BTW Dapper is a Stack Overflow project :)

UPDATE: I believe you can't do it simpler without something like EF. Also try to use using statements when you are working with database connections. This will close connection automatically, even in case of exception. And connection will be returned to connections pool.

private readonly string _spionshopConnectionString;

private void Form1_Load(object sender, EventArgs e)
{            
    _spionshopConnectionString = ConfigurationManager
          .ConnectionStrings["connSpionshopString"].ConnectionString;
}

private void button4_Click(object sender, EventArgs e)
{
    using(var connection = new SqlConnection(_spionshopConnectionString))
    {
         connection.Execute(@"INSERT INTO klant(klant_id,naam,voornaam) 
                              VALUES (@klantId,@klantNaam,@klantVoornaam)",
                              new { 
                                      klantId = Convert.ToInt32(textBox1.Text), 
                                      klantNaam = textBox2.Text, 
                                      klantVoornaam = textBox3.Text 
                                  });
    }
}

jQuery `.is(":visible")` not working in Chrome

If an item is child of an item that is hidden is(":visible") will return true, which is incorrect.

I just fixed this by added "display:inherit" to the child item. This will fixed it for me:

<div class="parent">
   <div class="child">
   </div>
<div>

and the CSS:

.parent{
   display: hidden;
}
.child{
   display: inherit;
}

Now the item can be effectively switched on and off by changing the visibility of the parent, and $(element).is(":visible") will return the visibility of the parent item

Command to get time in milliseconds

When you use GNU AWK since version 4.1, you can load the time library and do:

$ awk '@load "time"; BEGIN{printf "%.6f", gettimeofday()}'

This will print the current time in seconds since 1970-01-01T00:00:00 in sub second accuracy.

the_time = gettimeofday() Return the time in seconds that has elapsed since 1970-01-01 UTC as a floating-point value. If the time is unavailable on this platform, return -1 and set ERRNO. The returned time should have sub-second precision, but the actual precision may vary based on the platform. If the standard C gettimeofday() system call is available on this platform, then it simply returns the value. Otherwise, if on MS-Windows, it tries to use GetSystemTimeAsFileTime().

source: GNU awk manual

On Linux systems, the standard C function getimeofday() returns the time in microsecond accuracy.

GridLayout (not GridView) how to stretch all children evenly

Here is what I did and I'm happy to say that this worked for me. I too wanted a 2x2, 3x3 etc. grid of items to cover the entire screen. Gridlayouts do not adhere to the width of the screen. LinearLayouts kind of work but you cant use nested weights.

The best option for me was to use Fragments I used this tutorial to get started with what I wanted to do.

Here is some code:

Main Activity:

public class GridHolderActivity extends Activity {

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

        setContentView(R.layout.activity_main_6);
    }
}

activity_main_6 XML (inflates 3 fragments)

<?xml version="1.0" encoding="utf-8"?>

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

    <fragment
        android:id="@+id/frag1"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:name=".TwoHorizontalGridFragment"
        tools:layout="@layout/two_horiz" />
    <fragment
        android:id="@+id/frag2"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:name=".TwoHorizontalGridFragment"
        tools:layout="@layout/two_horiz" />
    <fragment
        android:id="@+id/frag3"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:name=".Grid.TwoHorizontalGridFragment"
        tools:layout="@layout/two_horiz" />

Base fragment layout

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

    <ImageQueue
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:id="@+id/img1"
        android:layout_weight="1"/>


    <ImageQueue
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:id="@+id/img2"
        android:layout_weight="1"/>
</LinearLayout>

Fragment Class (only handles initialization of a custom view) inflates 2 tiles per fragment

public class TwoHorizontalGridFragment extends Fragment {
private View rootView;

private ImageQueue imageQueue1;
private ImageQueue imageQueue2;

@Override
public View onCreateView(LayoutInflater inflater,
                         ViewGroup container, Bundle savedInstanceState) {
    /**
     * Inflate the layout for this fragment
     */
    rootView = inflater.inflate(
            R.layout.two_horiz, container, false);
    return rootView;
}

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

    imageQueue1 = (ImageQueue)rootView.findViewById(R.id.img1);
    imageQueue2 = (ImageQueue)rootView.findViewById(R.id.img2);
    imageQueue1.updateFiles();
    imageQueue2.updateFiles();
}

}

Thats it!

This is a weird work around to using nested weights, essentially. It gives me a perfect 2x3 grid that fills the entire screen of both my 10 inch tablet and my HTC droid DNA. Let me know how it goes for you!

Change image source with JavaScript

function changeImage(a) so there is no such thing as a.src => just use a.

demo here

Java: how do I get a class literal from a generic type?

To expound on cletus' answer, at runtime all record of the generic types is removed. Generics are processed only in the compiler and are used to provide additional type safety. They are really just shorthand that allows the compiler to insert typecasts at the appropriate places. For example, previously you'd have to do the following:

List x = new ArrayList();
x.add(new SomeClass());
Iterator i = x.iterator();
SomeClass z = (SomeClass) i.next();

becomes

List<SomeClass> x = new ArrayList<SomeClass>();
x.add(new SomeClass());
Iterator<SomeClass> i = x.iterator();
SomeClass z = i.next();

This allows the compiler to check your code at compile-time, but at runtime it still looks like the first example.

How to scroll to specific item using jQuery?

I did a combination of what others have posted. Its simple and smooth

 $('#myButton').click(function(){
        $('html, body').animate({
            scrollTop: $('#scroll-to-this-element').position().top },
            1000
        );
    });

Is it possible to compile a program written in Python?

If you really want, you could always compile with Cython. This will generate C code, which you can then compile with any C compiler such as GCC.

?: operator (the 'Elvis operator') in PHP

See the docs:

Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

How to fix the Hibernate "object references an unsaved transient instance - save the transient instance before flushing" error

There are so many possibilities of this error some other possibilities are also on add page or edit page. In my case I was trying to save a object AdvanceSalary. The problem is that in edit the AdvanceSalary employee.employee_id is null Because on edit I was not set the employee.employee_id. I have make a hidden field and set it. my code working absolutely fine.

    @Entity(name = "ic_advance_salary")
    @Table(name = "ic_advance_salary")
    public class AdvanceSalary extends BaseDO{

        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Column(name = "id")
        private Integer id;

        @ManyToOne(fetch = FetchType.EAGER)
        @JoinColumn(name = "employee_id", nullable = false)
        private Employee employee;

        @Column(name = "employee_id", insertable=false, updatable=false)
        @NotNull(message="Please enter employee Id")
        private Long employee_id;

        @Column(name = "advance_date")
        @DateTimeFormat(pattern = "dd-MMM-yyyy")
        @NotNull(message="Please enter advance date")
        private Date advance_date;

        @Column(name = "amount")
        @NotNull(message="Please enter Paid Amount")
        private Double amount;

        @Column(name = "cheque_date")
        @DateTimeFormat(pattern = "dd-MMM-yyyy")
        private Date cheque_date;

        @Column(name = "cheque_no")
        private String cheque_no;

        @Column(name = "remarks")
        private String remarks;

        public AdvanceSalary() {
        }

        public AdvanceSalary(Integer advance_salary_id) {
            this.id = advance_salary_id;
        }

        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }

        public Employee getEmployee() {
            return employee;
        }

        public void setEmployee(Employee employee) {
            this.employee = employee;
        }


        public Long getEmployee_id() {
            return employee_id;
        }

        public void setEmployee_id(Long employee_id) {
            this.employee_id = employee_id;
        }

    }

How do I install PIL/Pillow for Python 3.6?

Pillow is released with installation wheels on Windows:

We provide Pillow binaries for Windows compiled for the matrix of supported Pythons in both 32 and 64-bit versions in wheel, egg, and executable installers. These binaries have all of the optional libraries included

https://pillow.readthedocs.io/en/3.3.x/installation.html#basic-installation

Update: Python 3.6 is now supported by Pillow. Install with pip install pillow and check https://pillow.readthedocs.io/en/latest/installation.html for more information.


However, Python 3.6 is still in alpha and not officially supported yet, although the tests do all pass for the nightly Python builds (currently 3.6a4).

https://travis-ci.org/python-pillow/Pillow/jobs/155605577

If it's somehow possible to install the 3.5 wheel for 3.6, that's your best bet. Otherwise, zlib notwithstanding, you'll need to build from source, requiring an MS Visual C++ compiler, and which isn't straightforward. For tips see:

https://pillow.readthedocs.io/en/3.3.x/installation.html#building-from-source

And also see how it's built for Windows on AppVeyor CI (but not yet 3.5 or 3.6):

https://github.com/python-pillow/Pillow/tree/master/winbuild

Failing that, downgrade to Python 3.5 or wait until 3.6 is supported by Pillow, probably closer to the 3.6's official release.

How to normalize a signal to zero mean and unit variance?

If you have the stats toolbox, then you can compute

Z = zscore(S);

JavaScript - Use variable in string match

Example. To find number of vowels within the string

var word='Web Development Tutorial';
var vowels='[aeiou]'; 
var re = new RegExp(vowels, 'gi');
var arr = word.match(re);
document.write(arr.length);

Using numpy to build an array of all combinations of two arrays

Pandas merge offers a naive, fast solution to the problem:

# given the lists
x, y, z = [1, 2, 3], [4, 5], [6, 7]

# get dfs with same, constant index 
x = pd.DataFrame({'x': x}, index=np.repeat(0, len(x))
y = pd.DataFrame({'y': y}, index=np.repeat(0, len(y))
z = pd.DataFrame({'z': z}, index=np.repeat(0, len(z))

# get all permutations stored in a new df
df = pd.merge(x, pd.merge(y, z, left_index=True, righ_index=True),
              left_index=True, right_index=True)

How to fix "containing working copy admin area is missing" in SVN?

I tried svn rm --force /path/to/dir to no avail but ended up just running svn up and it fixed it for me.

How to find out what character key is pressed?

There are a million duplicates of this question on here, but here goes again anyway:

document.onkeypress = function(evt) {
    evt = evt || window.event;
    var charCode = evt.keyCode || evt.which;
    var charStr = String.fromCharCode(charCode);
    alert(charStr);
};

The best reference on key events I've seen is http://unixpapa.com/js/key.html.

Indenting code in Sublime text 2?

No one seems to love mac re-indentation, So here How I do it:

[
   { "keys": ["command+shift+i"], "command": "reindent"}
]

In Preferences > Key Binding - User

One more extra tip: add

{ "keys": ["command+0"], "command": "focus_side_bar" }

to have sidebar file tree view navigation using keyboard.

Note: Add , at the end of each {}, if you have more than one {} set of objects

Change Git repository directory location.

Simply copy the entire working directory contents (including the hidden .git directory). This will move the entire working directory to the new directory and will not affect the remote repository on GitHub.

If you are using GitHub for Windows, you may move the repository using the method as above. However, when you click on the repository in the application it will be unable to find it. To resolve this simply click on the blue circle with the !, select Find It and then browse to the new directory.

Powershell v3 Invoke-WebRequest HTTPS error

An alternative implementation in pure (without Add-Type of source):

#requires -Version 5
#requires -PSEdition Desktop

class TrustAllCertsPolicy : System.Net.ICertificatePolicy {
    [bool] CheckValidationResult([System.Net.ServicePoint] $a,
                                 [System.Security.Cryptography.X509Certificates.X509Certificate] $b,
                                 [System.Net.WebRequest] $c,
                                 [int] $d) {
        return $true
    }
}
[System.Net.ServicePointManager]::CertificatePolicy = [TrustAllCertsPolicy]::new()

Convert an integer to a float number

There is no float type. Looks like you want float64. You could also use float32 if you only need a single-precision floating point value.

package main

import "fmt"

func main() {
    i := 5
    f := float64(i)
    fmt.Printf("f is %f\n", f)
}

How do you list all triggers in a MySQL database?

The command for listing all triggers is:

show triggers;

or you can access the INFORMATION_SCHEMA table directly by:

select trigger_schema, trigger_name, action_statement
from information_schema.triggers

DNS caching in linux

You have here available an example of DNS Caching in Debian using dnsmasq.

Configuration summary:

/etc/default/dnsmasq

# Ensure you add this line
DNSMASQ_OPTS="-r /etc/resolv.dnsmasq"

/etc/resolv.dnsmasq

# Your preferred servers
nameserver 1.1.1.1
nameserver 8.8.8.8
nameserver 2001:4860:4860::8888

/etc/resolv.conf

nameserver 127.0.0.1

Then just restart dnsmasq.

Benchmark test using DNS 1.1.1.1:

for i in {1..100}; do time dig slashdot.org @1.1.1.1; done 2>&1 | grep ^real | sed -e s/.*m// | awk '{sum += $1} END {print sum / NR}'

Benchmark test using you local cached DNS:

for i in {1..100}; do time dig slashdot.org; done 2>&1 | grep ^real | sed -e s/.*m// | awk '{sum += $1} END {print sum / NR}'

How do I force Postgres to use a particular index?

Assuming you're asking about the common "index hinting" feature found in many databases, PostgreSQL doesn't provide such a feature. This was a conscious decision made by the PostgreSQL team. A good overview of why and what you can do instead can be found here. The reasons are basically that it's a performance hack that tends to cause more problems later down the line as your data changes, whereas PostgreSQL's optimizer can re-evaluate the plan based on the statistics. In other words, what might be a good query plan today probably won't be a good query plan for all time, and index hints force a particular query plan for all time.

As a very blunt hammer, useful for testing, you can use the enable_seqscan and enable_indexscan parameters. See:

These are not suitable for ongoing production use. If you have issues with query plan choice, you should see the documentation for tracking down query performance issues. Don't just set enable_ params and walk away.

Unless you have a very good reason for using the index, Postgres may be making the correct choice. Why?

  • For small tables, it's faster to do sequential scans.
  • Postgres doesn't use indexes when datatypes don't match properly, you may need to include appropriate casts.
  • Your planner settings might be causing problems.

See also this old newsgroup post.

Set content of iframe

$('#myiframe').contents().find('html').html(s); 

you can check from here http://jsfiddle.net/Y9beh/

How to drop unique in MySQL?

Simply you can use the following SQL Script to delete the index in MySQL:

alter table fuinfo drop index email;

How to Install Windows Phone 8 SDK on Windows 7

Here is a link from developer.nokia.com wiki pages, which explains how to install Windows Phone 8 SDK on a Virtual Machine with Working Emulator

And another link here

AFAIK, it is not possible to directly install WP8 SDK in Windows 7, because WP8 sdk is VS 2012 supported and also its emulator works on a Hyper-V (which is integrated into the Windows 8).

Hot to get all form elements values using jQuery?

You can use a serialize() function of JQuery:

    var datastring = $("#preview_form").serialize();
        $.ajax({
            type: "POST",
            url: "your url.php",
            data: datastring,
            success: function(data) {
                 alert('Data send');
            }
        });

And read in PHP:

echo $_POST['datastring']['dialog_box_textarea_1'];
echo $_POST['datastring']['radiobutton_1'];
........

And get ***data-**** to tag HTML5 you can see this example:

<div id="texto" data-author="Ricardo Miranda" data-date="2012-06-21">
<h4>Lorem ipsum</h4>
  <p>
    Lorem ipsum dolor sit amet, ius integre eligendi et,
    sea ut expetendis conclusionemque,
    mel at ornatus invenire. His ad moderatius definiebas omittantur,
    liber saepe albucius sea cu.
    Audire tamquam dolores vis ne, mediocrem consulatu eum ex.
    Duo te agam saepe convenire, et fugit iisque his.
 </p>

<script type="text/javascript">
$(function() {
    alert("The text is write " + $('#texto').data('author'));
});

And

<div id="texto" data-author='{"nombre":"Ricardo","apellido":"Miranda"}' data-date="2012-06-21">
   ...
</div>

<script type="text/javascript">
$(function() {
    alert("The text is write " + $('#texto').data('author').apellido + ", " +
        ('#texto').data('author').nombre);
});
</script>

Xcode warning: "Multiple build commands for output file"

another version of this situation can occur when there are duplicates in the Headers build phase.

to fix this …

  1. go to your project target
  2. choose Build Phases
  3. choose the Headers build phase
  4. enter the name shown in the warning
  5. notice the two (or more) items
  6. find the +|- boxes in the lower left corner
  7. select one of the items, and click the - button

How to position the Button exactly in CSS

I'd use absolute positioning:

#play_button {
    position:absolute;
transition: .5s ease;
    left: 202px;
    top: 198px;

}

How to check if a double is null?

I would recommend using a Double not a double as your type then you check against null.

NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equalsIgnoreCase(java.lang.String)' on a null object reference

The exception occurs due to this statement,

called_from.equalsIgnoreCase("add")

It seem that the previous statement

String called_from = getIntent().getStringExtra("called");

returned a null reference.

You can check whether the intent to start this activity contains such a key "called".

Is <div style="width: ;height: ;background: "> CSS?

1)Yes it is, when there is style then it is styling your code(css).2) is belong to html it is like a container that keep your css.

VBoxManage: error: Failed to create the host-only adapter

Got the error in Mac after the update to Mojave. Probably you have an older version of virtual box.

Update to a recent version of virtualbox. (5.2 at the time of wrting this post)

Edit: adding @lsimonetti's comment.

In addition to that upgrade to Virtualbox 5.2, you need Vagrant >= 2.0.1

How do I verify/check/test/validate my SSH passphrase?

You can verify your SSH key passphrase by attempting to load it into your SSH agent. With OpenSSH this is done via ssh-add.

Once you're done, remember to unload your SSH passphrase from the terminal by running ssh-add -d.

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

From docs TWIG docs:

Unlike in PHP, it's not possible to break or continue in a loop.

But still:

You can however filter the sequence during iteration which allows you to skip items.

Example 1 (for huge lists you can filter posts using slice, slice(start, length)):

{% for post in posts|slice(0,10) %}
    <h2>{{ post.heading }}</h2>
{% endfor %}

Example 2:

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

You can even use own TWIG filters for more complexed conditions, like:

{% for post in posts|onlySuperPosts %}
    <h2>{{ post.heading }}</h2>
{% endfor %}

How do I get the SelectedItem or SelectedIndex of ListView in vb.net?

VB6: Listview1.selecteditem

VB10: Listview1.FocusedItem.Text

How can I create an object based on an interface file definition in TypeScript?

Here another solution what i am using frequently. However I am not sure is good practice or not, please comment below if not.

/// Interface
export default interface BookInterface {
  title: string,
  author: string,
  id: any
}

/// Creating Class
export class BookClass implements BookInterface {
  title: string;
  author: string;
  id: any;

  constructor(title: string, author: string, id: any) {
    this.title = title;
    this.author = author;
    this.id = id;
  }
}

/// How to use it
let book: BookInterface = new BookClass(title, author, id);

Thanks :)

Eclipse shows errors but I can't find them

Based on the error you showed ('footballforum' is missing required Java project: 'ApiDemos'), I would check your build path. Right-click the footballforum project and choose Build Path > Configure Build Path. Make sure ApiDemos is on the projects tab of the build path options.

SELECT * FROM in MySQLi

I was looking for a nice and complete example of how to bind multiple query parameters dynamically to any SELECT, INSERT, UPDATE and DELETE query. Alec mentions in his answer a way of how to bind result, for me the get_result() after execute() function for SELECT queries works just fine, and am able to retrieve all the selected results into an array of associative arrays.

Anyway, I ended up creating a function where I am able to dynamically bind any amount of parameters to a parametrized query ( using call_user_func_array function) and obtain a result of the query execution. Below is the function with its documentation (please read before it before using - especially the $paremetersTypes - Type specification chars parameter is important to understand)

     /**
     * Prepares and executes a parametrized QUERY (SELECT, INSERT, UPDATE, DELETE)
     *
     * @param[in] $dbConnection mysqli database connection to be used for query execution
     * @param[in] $dbQuery parametrized query to be bind parameters for and then execute
     * @param[in] $isDMQ boolean value, should be set to TRUE for (DELETE, INSERT, UPDATE - Data manipulaiton queries), FALSE for SELECT queries
     * @param[in] $paremetersTypes String representation for input parametrs' types as per http://php.net/manual/en/mysqli-stmt.bind-param.php
     * @param[in] $errorOut A variable to be passed by reference where a string representation of an error will be present if a FAUILURE occurs
     * @param[in] $arrayOfParemetersToBind Parameters to be bind to the parametrized query, parameters need to be specified in an array in the correct order 
     * @return array of feched records associative arrays for SELECT query on SUCCESS, TRUE for INSERT, UPDATE, DELETE queries on SUCCESS, on FAIL sets the error and returns NULL 
     */
    function ExecuteMySQLParametrizedQuery($dbConnection, $dbQuery, $isDMQ, $paremetersTypes, &$errorOut, $arrayOfParemetersToBind)
    {
        $stmt = $dbConnection->prepare($dbQuery);

        $outValue = NULL;

        if ($stmt === FALSE)
            $errorOut = 'Failed to prepare statement for query: ' . $dbQuery;
        else if ( call_user_func_array(array($stmt, "bind_param"), array_merge(array($paremetersTypes), $arrayOfParemetersToBind)) === FALSE)
            $errorOut = 'Failed to bind required parameters to query: ' . $dbQuery . '  , parameters :' . json_encode($arrayOfParemetersToBind);
        else if (!$stmt->execute())
            $errorOut = "Failed to execute query [$dbQuery] , erorr:" . $stmt->error;
        else
        {
            if ($isDMQ)
               $outValue = TRUE;
            else
            {
                $result = $stmt->get_result();

                if ($result === FALSE) 
                     $errorOut = 'Failed to obtain result from statement for query ' . $dbQuery;
                else
                    $outValue = $result->fetch_all(MYSQLI_ASSOC);
            }
        }

        $stmt->close();

        return $outValue;
    }

usage:

    $param1 = "128989";
    $param2 = "some passcode";


    $insertQuery = "INSERT INTO Cards (Serial, UserPin) VALUES (?, ?)";
    $rowsInserted = ExecuteMySQLParametrizedQuery($dbConnection, $insertQuery, TRUE, 'ss', $errorOut, array(&$param1, &$param2) ); // Make sure the parameters in an array are passed by reference

    if ($rowsInserted === NULL)
        echo 'error ' . $errorOut;
    else
        echo "successfully inserted row";


    $selectQuery = "SELECT CardID FROM Cards WHERE Serial like ? AND UserPin like ?";
    $arrayOfCardIDs = ExecuteMySQLParametrizedQuery($dbConnection, $selectQuery, FALSE, 'ss', $errorOut, array(&$param1, &$param2) ); // Make sure the parameters in an array are passed by reference

    if ($arrayOfCardIDs === NULL) 
        echo 'error ' . $errorOut;
    else
    {
        echo 'obtained result array of ' . count($arrayOfCardIDs) . 'selected rows';

        if (count($arrayOfCardIDs) > 0) 
            echo 'obtained card id = ' . $arrayOfCardIDs[0]['CardID'];
    }

PHP mail function doesn't complete sending of e-mail

Maybe the problem is the configuration of the mail server. To avoid this type of problems or you do not have to worry about the mail server problem, I recommend you use PHPMailer.

It is a plugin that has everything necessary to send mail, and the only thing you have to take into account is to have the SMTP port (Port: 25 and 465), enabled.

require_once 'PHPMailer/PHPMailer.php';
require_once '/servicios/PHPMailer/SMTP.php';
require_once '/servicios/PHPMailer/Exception.php';

$mail = new \PHPMailer\PHPMailer\PHPMailer(true);
try {
    //Server settings
    $mail->SMTPDebug = 0;
    $mail->isSMTP();
    $mail->Host = 'smtp.gmail.com';
    $mail->SMTPAuth = true;
    $mail->Username = '[email protected]';
    $mail->Password = 'contrasenia';
    $mail->SMTPSecure = 'ssl';
    $mail->Port = 465;

    // Recipients
    $mail->setFrom('[email protected]', 'my name');
    $mail->addAddress('[email protected]');

    // Attachments
    $mail->addAttachment('optional file');         // Add files, is optional

    // Content
    $mail->isHTML(true);// Set email format to HTML
    $mail->Subject = utf8_decode("subject");
    $mail->Body    = utf8_decode("mail content");
    $mail->AltBody = '';
    $mail->send();
}
catch (Exception $e) {
    $error = $mail->ErrorInfo;
}

Single Result from Database by using mySQLi

If you assume just one result you could do this as in Edwin suggested by using specific users id.

$someUserId = 'abc123';

$stmt = $mysqli->prepare("SELECT ssfullname, ssemail FROM userss WHERE user_id = ?");
$stmt->bind_param('s', $someUserId);

$stmt->execute();

$stmt->bind_result($ssfullname, $ssemail);
$stmt->store_result();
$stmt->fetch();

ChromePhp::log($ssfullname, $ssemail); //log result in chrome if ChromePhp is used.

OR as "Your Common Sense" which selects just one user.

$stmt = $mysqli->prepare("SELECT ssfullname, ssemail FROM userss ORDER BY ssid LIMIT 1");

$stmt->execute();
$stmt->bind_result($ssfullname, $ssemail);
$stmt->store_result();
$stmt->fetch();

Nothing really different from the above except for PHP v.5

How do I empty an input value with jQuery?

You could try:

$('input.class').removeAttr('value');
$('#inputID').removeAttr('value');

Uninitialized constant ActiveSupport::Dependencies::Mutex (NameError)

If you're using Radiant CMS, simply add

require 'thread'

to the top of config/boot.rb.

(Kudos to Aaron's and nathanvda's responses.)

How to remove backslash on json_encode() function?

As HungryDB said the easier way for do that is:

$mystring = json_encode($my_json,JSON_UNESCAPED_SLASHES);

Have a look at your php version because this parameter has been added in version 5.4.0

json_encode documentation

Easiest way to mask characters in HTML(5) text input

Look up the new HTML5 Input Types. These instruct browsers to perform client-side filtering of data, but the implementation is incomplete across different browsers. The pattern attribute will do regex-style filtering, but, again, browsers don't fully (or at all) support it.

However, these won't block the input itself, it will simply prevent submitting the form with the invalid data. You'll still need to trap the onkeydown event to block key input before it displays on the screen.

How to get exact browser name and version?

Use get_browser()

From Manual:

echo $_SERVER['HTTP_USER_AGENT'] . "\n\n";

$browser = get_browser(null, true);
print_r($browser);

Will return:

Array
(
    [browser_name_regex] => ^mozilla/5\.0 (windows; .; windows nt 5\.1; .*rv:.*) gecko/.* firefox/0\.9.*$
    [browser_name_pattern] => Mozilla/5.0 (Windows; ?; Windows NT 5.1; *rv:*) Gecko/* Firefox/0.9*/
    [parent] => Firefox 0.9
    [platform] => WinXP
    [browser] => Firefox
    [version] => 0.9
    [majorver] => 0
    [minorver] => 9
    [cssversion] => 2
    [frames] => 1
    [iframes] => 1
    [tables] => 1
    [cookies] => 1
    [backgroundsounds] =>
    [vbscript] =>
    [javascript] => 1
    [javaapplets] => 1
    [activexcontrols] =>
    [cdf] =>
    [aol] =>
    [beta] => 1
    [win16] =>
    [crawler] =>
    [stripper] =>
    [wap] =>
    [netclr] =>
)

Reverse each individual word of "Hello World" string with Java

You need to do this on each word after you split into an array of words.

public String reverse(String word) {
    char[] chs = word.toCharArray();

    int i=0, j=chs.length-1;
    while (i < j) {
        // swap chs[i] and chs[j]
        char t = chs[i];
        chs[i] = chs[j];
        chs[j] = t;
       i++; j--;
    }
    return String.valueOf(chs);
}

Writing your own square root function

Here's a way of obtaining a square root using trigonometry. It's not the fastest algorithm by a longshot, but it is precise. Code is in javascript:

var n = 5; //number to get the square root of
var icr = ((n+1)/2); //intersecting circle radius
var sqrt = Math.cos(Math.asin((icr-1)/icr))*icr; //square root of n
alert(sqrt);

Add Twitter Bootstrap icon to Input box

Since the glyphicons image is a sprite, you really can't do that: fundamentally what you want is to limit the size of the background, but there's no way to specify how big the background is. Either you cut out the icon you want, size it down and use it, or use something like the input field prepend/append option (http://twitter.github.io/bootstrap/base-css.html#forms and then search for prepended inputs).

How to get current date time in milliseconds in android

Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
int mSec = calendar.get(Calendar.MILLISECOND);

successful/fail message pop up box after submit?

You are echoing outside the body tag of your HTML. Put your echos there, and you should be fine.

Also, remove the onclick="alert()" from your submit. This is the cause for your first undefined message.

<?php
  $posted = false;
  if( $_POST ) {
    $posted = true;

    // Database stuff here...
    // $result = mysql_query( ... )
    $result = $_POST['name'] == "danny"; // Dummy result
  }
?>

<html>
  <head></head>
  <body>

  <?php
    if( $posted ) {
      if( $result ) 
        echo "<script type='text/javascript'>alert('submitted successfully!')</script>";
      else
        echo "<script type='text/javascript'>alert('failed!')</script>";
    }
  ?>
    <form action="" method="post">
      Name:<input type="text" id="name" name="name"/>
      <input type="submit" value="submit" name="submit"/>
    </form>
  </body>
</html>

How to find children of nodes using BeautifulSoup

Yet another method - create a filter function that returns True for all desired tags:

def my_filter(tag):
    return (tag.name == 'a' and
        tag.parent.name == 'li' and
        'test' in tag.parent['class'])

Then just call find_all with the argument:

for a in soup(my_filter): # or soup.find_all(my_filter)
    print a

Prevent users from submitting a form by hitting Enter

ONLY BLOCK SUBMIT but not other, important functionality of enter key, such as creating a new paragraph in a <textarea>:

_x000D_
_x000D_
window.addEventListener('keydown', function(event) {_x000D_
  //set default value for variable that will hold the status of keypress_x000D_
  pressedEnter = false;_x000D_
_x000D_
  //if user pressed enter, set the variable to true_x000D_
  if (event.keyCode == 13)_x000D_
    pressedEnter = true;_x000D_
_x000D_
  //we want forms to disable submit for a tenth of a second only_x000D_
  setTimeout(function() {_x000D_
    pressedEnter = false;_x000D_
  }, 100)_x000D_
_x000D_
})_x000D_
_x000D_
//find all forms_x000D_
var forms = document.getElementsByTagName('form')_x000D_
_x000D_
//loop through forms_x000D_
for (i = 0; i < forms.length; i++) {_x000D_
  //listen to submit event_x000D_
  forms[i].addEventListener('submit', function(e) {_x000D_
    //if user just pressed enter, stop the submit event_x000D_
    if (pressedEnter == true) {_x000D_
      updateLog('Form prevented from submit.')_x000D_
      e.preventDefault();_x000D_
      return false;_x000D_
    }_x000D_
_x000D_
    updateLog('Form submitted.')_x000D_
  })_x000D_
}_x000D_
_x000D_
var log = document.getElementById('log')_x000D_
updateLog = function(msg) {_x000D_
  log.innerText = msg_x000D_
}
_x000D_
input,_x000D_
textarea {_x000D_
  display: inline-block;_x000D_
  margin-bottom: 1em;_x000D_
  border: 1px solid #6f6f6f;_x000D_
  padding: 5px;_x000D_
  border-radius: 2px;_x000D_
  width: 90%;_x000D_
  font-size: 14px;_x000D_
}_x000D_
_x000D_
input[type=submit] {_x000D_
  background: lightblue;_x000D_
  color: #fff;_x000D_
}
_x000D_
<form>_x000D_
  <p>Sample textarea (try enter key):</p>_x000D_
  <textarea rows="4">Hit enter, a new line will be added. But the form won't submit</textarea><br/>_x000D_
  <p>Sample textfield (try enter key):</p>_x000D_
  <input type="text" placeholder="" />_x000D_
  <br/>_x000D_
  <input type="submit" value="Save" />_x000D_
  <h3 id="log"></h3>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Tomcat: java.lang.IllegalArgumentException: Invalid character found in method name. HTTP method names must be tokens

I got this error resolved by doing 2 things in chrome browser:

  1. Pressed Ctrl + Shift + Delete and cleared all browsing data from beginning.
  2. Go to Chrome's : Settings ->Advanced Settings -> Open proxy settings -> Internet Properties then Go to the Content window and click on the Clear SSL State Button.

This site has this information and other options as well : https://www.thesslstore.com/blog/fix-err-ssl-protocol-error/

How to parse this string in Java?

String s = "prefix/dir1/dir2/dir3/dir4"

String parts[] = s.split("/");

System.out.println(s[0]); // "prefix"
System.out.println(s[1]); // "dir1"
...

Argparse: Required arguments listed under "optional arguments"?

Since I prefer to list required arguments before optional, I hack around it via:

    parser = argparse.ArgumentParser()
    parser._action_groups.pop()
    required = parser.add_argument_group('required arguments')
    optional = parser.add_argument_group('optional arguments')
    required.add_argument('--required_arg', required=True)
    optional.add_argument('--optional_arg')
    return parser.parse_args()

and this outputs:

usage: main.py [-h] [--required_arg REQUIRED_ARG]
               [--optional_arg OPTIONAL_ARG]

required arguments:
  --required_arg REQUIRED_ARG

optional arguments:
  --optional_arg OPTIONAL_ARG

I can live without 'help' showing up in the optional arguments group.

How to show/hide an element on checkbox checked/unchecked states using jQuery?

Try this

<script>
    $().ready(function(){
        $('.coupon_question').live('click',function() 
        {
            if ($('.coupon_question').is(':checked')) {
                $(".answer").show();
            } else {
                $(".answer").hide();
            } 
        });
    });
</script>

Lock screen orientation (Android)

inside the Android manifest file of your project, find the activity declaration of whose you want to fix the orientation and add the following piece of code ,

android:screenOrientation="landscape"

for landscape orientation and for portrait add the following code,

android:screenOrientation="portrait"

CSS: Fix row height

I haven't tried it but if you put a div in your table cell set so that it will have scrollbars if needed, then you could insert in there, with a fixed height on the div and it should keep your table row to a fixed height.

Is it possible to add an array or object to SharedPreferences on Android

Shared preferences introduced a getStringSet and putStringSet methods in API Level 11, but that's not compatible with older versions of Android (which are still popular), and also is limited to sets of strings.

Android does not provide better methods, and looping over maps and arrays for saving and loading them is not very easy and clean, specially for arrays. But a better implementation isn't that hard:

package com.example.utils;

import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONException;

import android.content.Context;
import android.content.SharedPreferences;

public class JSONSharedPreferences {
    private static final String PREFIX = "json";

    public static void saveJSONObject(Context c, String prefName, String key, JSONObject object) {
        SharedPreferences settings = c.getSharedPreferences(prefName, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString(JSONSharedPreferences.PREFIX+key, object.toString());
        editor.commit();
    }

    public static void saveJSONArray(Context c, String prefName, String key, JSONArray array) {
        SharedPreferences settings = c.getSharedPreferences(prefName, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString(JSONSharedPreferences.PREFIX+key, array.toString());
        editor.commit();
    }

    public static JSONObject loadJSONObject(Context c, String prefName, String key) throws JSONException {
        SharedPreferences settings = c.getSharedPreferences(prefName, 0);
        return new JSONObject(settings.getString(JSONSharedPreferences.PREFIX+key, "{}"));
    }

    public static JSONArray loadJSONArray(Context c, String prefName, String key) throws JSONException {
        SharedPreferences settings = c.getSharedPreferences(prefName, 0);
        return new JSONArray(settings.getString(JSONSharedPreferences.PREFIX+key, "[]"));
    }

    public static void remove(Context c, String prefName, String key) {
        SharedPreferences settings = c.getSharedPreferences(prefName, 0);
        if (settings.contains(JSONSharedPreferences.PREFIX+key)) {
            SharedPreferences.Editor editor = settings.edit();
            editor.remove(JSONSharedPreferences.PREFIX+key);
            editor.commit();
        }
    }
}

Now you can save any collection in shared preferences with this five methods. Working with JSONObject and JSONArray is very easy. You can use JSONArray (Collection copyFrom) public constructor to make a JSONArray out of any Java collection and use JSONArray's get methods to access the elements.

There is no size limit for shared preferences (besides device's storage limits), so these methods can work for most of usual cases where you want a quick and easy storage for some collection in your app. But JSON parsing happens here, and preferences in Android are stored as XMLs internally, so I recommend using other persistent data store mechanisms when you're dealing with megabytes of data.

How to create unique keys for React elements?

I am using this:

<div key={+new Date() + Math.random()}>

Updating the list view when the adapter data changes

Change this line:

mMyListView.setAdapter(new ArrayAdapter<String>(this, 
                           android.R.layout.simple_list_item_1, 
                           listItems));

to:

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                                   android.R.layout.simple_list_item_1, 
                                   listItems)
mMyListView.setAdapter(adapter);

and after updating the value of a list item, call:

adapter.notifyDataSetChanged();

HTML5 pattern for formatting input box to take date mm/dd/yyyy?

I use this website and this pattern do leap year validation as well.

<input type="text" pattern="(?:19|20)[0-9]{2}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-9])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:30))|(?:(?:0[13578]|1[02])-31))" required />

simple Jquery hover enlarge

To create simple hover enlarge plugin, try this. (DEMO)

HTML

     <div id="content">
     <img src="http://www.freevectorgallery.com/wp-content/uploads/2011/10/Vintage-Microphone- 11395-large.jpg" style="width:50%;" />
     </div>

js

        $(function () {
          $('#content img').hover(function () {
          $(this).toggle(function () {
          $(this).width('70%');
                   });
              });
         });

Working with $scope.$emit and $scope.$on

Scope(s) can be used to propagate, dispatch event to the scope children or parent.

$emit - propagates the event to parent. $broadcast - propagates the event to children. $on - method to listen the events, propagated by $emit and $broadcast.

example index.html:

<div ng-app="appExample" ng-controller="EventCtrl">
      Root(Parent) scope count: {{count}}
  <div>
      <button ng-click="$emit('MyEvent')">$emit('MyEvent')</button>
      <button ng-click="$broadcast('MyEvent')">$broadcast('MyEvent')</button><br>

      Childrent scope count: {{count}} 
  </div>
</div>

example app.js:

angular.module('appExample', [])
.controller('EventCtrl', ['$scope', function($scope) {
  $scope.count = 0;
  $scope.$on('MyEvent', function() {
    $scope.count++;
  });
}]);

Here u can test code: http://jsfiddle.net/zp6v0rut/41/

How to draw a circle with text in the middle?

Draw a circle with text in middle with HTML Tag and without CSS

HTML having SVG tag for this. You can follow this standard approach if you don't want to go for CSS.

 <svg width="100" height="100">
   <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="white" />
     Sorry, your browser does not support inline SVG.
   <text fill="#000000" font-size="18" font-family="Verdana"
     x="15" y="60">ASHISH</text>
 </svg>

enter image description here

Getting full URL of action in ASP.NET MVC

This what you need to do.

@Url.Action(action,controller, null, Request.Url.Scheme)

How to get value in the session in jQuery

Sessions are stored on the server and are set from server side code, not client side code such as JavaScript.

What you want is a cookie, someone's given a brilliant explanation in this Stack Overflow question here: How do I set/unset cookie with jQuery?

You could potentially use sessions and set/retrieve them with jQuery and AJAX, but it's complete overkill if Cookies will do the trick.

A button to start php script, how?

I know this question is 5 years old, but for anybody wondering how to do this without re-rendering the main page. This solution uses the dart editor/scripting language.

You could have an <object> tag that contains a data attribute. Make the <object> 1px by 1px and then use something like dart to dynamically change the <object>'s data attribute which re-renders the data in the 1px by 1px object.

HTML Script:

<object id="external_source" type="text/html" data="" width="1px" height="1px">
</object>

<button id="button1" type="button">Start Script</button>

<script async type="application/dart" src="dartScript.dart"></script>
<script async src="packages/browser/dart.js"></script>

someScript.php:

<?php
echo 'hello world';
?>

dartScript.dart:

import 'dart:html';

InputElement button1;
ObjectElement externalSource;

void main() {
    button1 = querySelector('#button1')
        ..onClick.listen(runExternalSource);

    externalSource = querySelector('#external_source');
}

void runExternalSource(Event e) {
    externalSource.setAttribute('data', 'someScript.php');
}

So long as you aren't posting any information and you are just looking to run a script, this should work just fine.

Just build the dart script using "pub Build(generate JS)" and then upload the package onto your server.

git still shows files as modified after adding to .gitignore

  1. Git add .

  2. Git status //Check file that being modified

    // git reset HEAD --- replace to which file you want to ignore

  3. git reset HEAD .idea/ <-- Those who wanted to exclude .idea from before commit // git check status and the idea file will be gone, and you're ready to go!

  4. git commit -m ''

  5. git push

java.util.zip.ZipException: error in opening zip file

I solved this by clearing the jboss-x.y.z/server[config]/tmp and jboss-x.y.z/server/[config]/work directories.

Styling JQuery UI Autocomplete

You can overwrite the classes in your own css using !important, e.g. if you want to get rid of the rounded corners.

.ui-corner-all
{
border-radius: 0px !important;
}

Overflow:hidden dots at the end

Hide text on load and show on hover

_x000D_
_x000D_
.hide-text {
  width: 70px;
  display: inline-block;
  white-space: nowrap;
  overflow: hidden !important;
  text-overflow: ellipsis;
}

span:hover {
   white-space: unset;
   text-overflow: unset;
}
_x000D_
<span class="hide-text"> How to hide text by dots and show text on hover</span>
_x000D_
_x000D_
_x000D_

How do I find out which process is locking a file using .NET?

It is very complex to invoke Win32 from C#.

You should use the tool Handle.exe.

After that your C# code have to be the following:

string fileName = @"c:\aaa.doc";//Path to locked file

Process tool = new Process();
tool.StartInfo.FileName = "handle.exe";
tool.StartInfo.Arguments = fileName+" /accepteula";
tool.StartInfo.UseShellExecute = false;
tool.StartInfo.RedirectStandardOutput = true;
tool.Start();           
tool.WaitForExit();
string outputTool = tool.StandardOutput.ReadToEnd();

string matchPattern = @"(?<=\s+pid:\s+)\b(\d+)\b(?=\s+)";
foreach(Match match in Regex.Matches(outputTool, matchPattern))
{
    Process.GetProcessById(int.Parse(match.Value)).Kill();
}

Check if a file exists in jenkins pipeline

You need to use brackets when using the fileExists step in an if condition or assign the returned value to a variable

Using variable:

def exists = fileExists 'file'

if (exists) {
    echo 'Yes'
} else {
    echo 'No'
}

Using brackets:

if (fileExists('file')) {
    echo 'Yes'
} else {
    echo 'No'
}

How to compile and run a C/C++ program on the Android system

If you want to compile and run Java/C/C++ apps directly on your Android device, I recommend the Terminal IDE environment from Google Play. It's a very slick package to develop and compile Android APKs, Java, C and C++ directly on your device. The interface is all command line and "vi" based, so it has real Linux feel. It comes with the gnu C/C++ implementation.

Additionally, there is a telnet and telnet server application built in, so you can do all the programming with your PC and big keyboard, but working on the device. No root permission is needed.

Javascript How to define multiple variables on a single line?

Why not doing it in two lines?

var a, b, c, d;    // All in the same scope
a = b = c = d = 1; // Set value to all.

The reason why, is to preserve the local scope on variable declarations, as this:

var a = b = c = d = 1;

will lead to the implicit declarations of b, c and d on the window scope.

Cannot get OpenCV to compile because of undefined references?

I have tried all solution. The -lopencv_core -lopencv_imgproc -lopencv_highgui in comments solved my problem. And know my command line looks like this in geany:

g++ -lopencv_core -lopencv_imgproc -lopencv_highgui  -o "%e" "%f"

When I build:

g++ -lopencv_core -lopencv_imgproc -lopencv_highgui  -o "opencv" "opencv.cpp" (in directory: /home/fedora/Desktop/Implementations)

The headers are:

#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"

Using HTML5/Canvas/JavaScript to take in-browser screenshots

Here is a complete screenshot example that works with chrome in 2021. The end result is a blob ready to be transmitted. Flow is: request media > grab frame > draw to canvas > transfer to blob. If you want to do it more memory efficient explore OffscreenCanvas or possibly ImageBitmapRenderingContext

https://jsfiddle.net/v24hyd3q/1/

// Request media
navigator.mediaDevices.getDisplayMedia().then(stream => 
{
  // Grab frame from stream
  let track = stream.getVideoTracks()[0];
  let capture = new ImageCapture(track);
  capture.grabFrame().then(bitmap => 
  {
    // Stop sharing
    track.stop();
      
    // Draw the bitmap to canvas
    canvas.width = bitmap.width;
    canvas.height = bitmap.height;
    canvas.getContext('2d').drawImage(bitmap, 0, 0);
      
    // Grab blob from canvas
    canvas.toBlob(blob => {
        // Do things with blob here
        console.log('output blob:', blob);
    });
  });
})
.catch(e => console.log(e));

How to jQuery clone() and change id?

Update: As Roko C.Bulijan pointed out.. you need to use .insertAfter to insert it after the selected div. Also see updated code if you want it appended to the end instead of beginning when cloned multiple times. DEMO

Code:

   var cloneCount = 1;;
   $("button").click(function(){
      $('#id')
          .clone()
          .attr('id', 'id'+ cloneCount++)
          .insertAfter('[id^=id]:last') 
           //            ^-- Use '#id' if you want to insert the cloned 
           //                element in the beginning
          .text('Cloned ' + (cloneCount-1)); //<--For DEMO
   }); 

Try,

$("#id").clone().attr('id', 'id1').after("#id");

If you want a automatic counter, then see below,

   var cloneCount = 1;
   $("button").click(function(){
      $("#id").clone().attr('id', 'id'+ cloneCount++).insertAfter("#id");
   }); 

Android: how to make keyboard enter button say "Search" and handle its click?

This answer is for TextInputEditText :

In the layout XML file set your input method options to your required type. for example done.

<com.google.android.material.textfield.TextInputLayout
        android:id="@+id/textInputLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <com.google.android.material.textfield.TextInputEditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:imeOptions="actionGo"/>

</com.google.android.material.textfield.TextInputLayout>

Similarly, you can also set imeOptions to actionSubmit, actionSearch, etc

In the java add the editor action listener.

TextInputLayout textInputLayout = findViewById(R.id.textInputLayout);

textInputLayout.getEditText().setOnEditorActionListener(new 

    TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_GO) {
                performYourAction();
                return true;
            }
            return false;
        }
    });

If you're using kotlin :

textInputLayout.editText.setOnEditorActionListener { _, actionId, _ ->
    if (actionId == EditorInfo.IME_ACTION_GO) {
        performYourAction()
    }
    true
}

What is the python "with" statement designed for?

The Python with statement is built-in language support of the Resource Acquisition Is Initialization idiom commonly used in C++. It is intended to allow safe acquisition and release of operating system resources.

The with statement creates resources within a scope/block. You write your code using the resources within the block. When the block exits the resources are cleanly released regardless of the outcome of the code in the block (that is whether the block exits normally or because of an exception).

Many resources in the Python library that obey the protocol required by the with statement and so can used with it out-of-the-box. However anyone can make resources that can be used in a with statement by implementing the well documented protocol: PEP 0343

Use it whenever you acquire resources in your application that must be explicitly relinquished such as files, network connections, locks and the like.

webpack: Module not found: Error: Can't resolve (with relative path)

If you have a typescript file, you have to instruct the webpack to resolve them by using below code in webpack.config.js

module.exports={
   ...
   resolve:{
      extensions:['.ts','.tsx';]
   }
}

Share data between html pages

possibly if you want to just transfer data to be used by JavaScript then you can use Hash Tags like this

http://localhost/project/index.html#exist

so once when you are done retriving the data show the message and change the window.location.hash to a suitable value.. now whenever you ll refresh the page the hashtag wont be present
NOTE: when you will use this instead ot query strings the data being sent cannot be retrived/read by the server

CSS, Images, JS not loading in IIS

For me adding this in the web.config resolved the problem

<system.webServer>
    <modules runAllManagedModulesForAllRequests="true" >
      <remove name="UrlRoutingModule"/>    
    </modules>
</system.webServer>

How to get the absolute coordinates of a view

First you have to get the localVisible rectangle of the view

For eg:

Rect rectf = new Rect();

//For coordinates location relative to the parent
anyView.getLocalVisibleRect(rectf);

//For coordinates location relative to the screen/display
anyView.getGlobalVisibleRect(rectf);

Log.d("WIDTH        :", String.valueOf(rectf.width()));
Log.d("HEIGHT       :", String.valueOf(rectf.height()));
Log.d("left         :", String.valueOf(rectf.left));
Log.d("right        :", String.valueOf(rectf.right));
Log.d("top          :", String.valueOf(rectf.top));
Log.d("bottom       :", String.valueOf(rectf.bottom));

Hope this will help

Importing lodash into angular2 + typescript application

You can also go ahead and import via good old require, ie:

const _get: any = require('lodash.get');

This is the only thing that worked for us. Of course, make sure any require() calls come after imports.

random.seed(): What does it do?

Pseudo-random number generators work by performing some operation on a value. Generally this value is the previous number generated by the generator. However, the first time you use the generator, there is no previous value.

Seeding a pseudo-random number generator gives it its first "previous" value. Each seed value will correspond to a sequence of generated values for a given random number generator. That is, if you provide the same seed twice, you get the same sequence of numbers twice.

Generally, you want to seed your random number generator with some value that will change each execution of the program. For instance, the current time is a frequently-used seed. The reason why this doesn't happen automatically is so that if you want, you can provide a specific seed to get a known sequence of numbers.

dlib installation on Windows 10

I have recently installed dlib on python 3.7. First I have installed cmake from anaconda navigator (cmake version 3.14.0) Next i installed visual studio 2019 and installed Desktop development with C++ . Then I do pip install dlib and now its working

Test only if variable is not null in if statement

I don't believe the expression is sensical as it is.

Elvis means "if truthy, use the value, else use this other thing."

Your "other thing" is a closure, and the value is status != null, neither of which would seem to be what you want. If status is null, Elvis says true. If it's not, you get an extra layer of closure.

Why can't you just use:

(it.description == desc) && ((status == null) || (it.status == status))

Even if that didn't work, all you need is the closure to return the appropriate value, right? There's no need to create two separate find calls, just use an intermediate variable.

ValueError: could not broadcast input array from shape (224,224,3) into shape (224,224)

This method does not need to modify dtype or ravel your numpy array.

The core idea is: 1.initialize with one extra row. 2.change the list(which has one more row) to array 3.delete the extra row in the result array e.g.

>>> a = [np.zeros((10,224)), np.zeros((10,))]
>>> np.array(a)
# this will raise error,
ValueError: could not broadcast input array from shape (10,224) into shape (10)

# but below method works
>>> a = [np.zeros((11,224)), np.zeros((10,))]
>>> b = np.array(a)
>>> b[0] = np.delete(b[0],0,0)
>>> print(b.shape,b[0].shape,b[1].shape)
# print result:(2,) (10,224) (10,)

Indeed, it's not necessarily to add one more row, as long as you can escape from the gap stated in @aravk33 and @user707650 's answer and delete the extra item later, it will be fine.

Oracle Trigger ORA-04098: trigger is invalid and failed re-validation

in my case, this error is raised due to sequence was not created..

CREATE SEQUENCE  J.SOME_SEQ  MINVALUE 1 MAXVALUE 9999999999999999999999999999 INCREMENT BY 1 START WITH 1 CACHE 20 NOORDER  NOCYCLE ;

Core dump file analysis

Steps to debug coredump using GDB:

Some generic help:

gdb start GDB, with no debugging les

gdb program begin debugging program

gdb program core debug coredump core produced by program

gdb --help describe command line options

  1. First of all, find the directory where the corefile is generated.

  2. Then use ls -ltr command in the directory to find the latest generated corefile.

  3. To load the corefile use

    gdb binary path of corefile
    

    This will load the corefile.

  4. Then you can get the information using the bt command.

    For a detailed backtrace use bt full.

  5. To print the variables, use print variable-name or p variable-name

  6. To get any help on GDB, use the help option or use apropos search-topic

  7. Use frame frame-number to go to the desired frame number.

  8. Use up n and down n commands to select frame n frames up and select frame n frames down respectively.

  9. To stop GDB, use quit or q.

How can I add a .npmrc file?

Assuming you are using VSTS run vsts-npm-auth -config .npmrc to generate new .npmrc file with the auth token

How can I throw CHECKED exceptions from inside Java 8 streams?

Here is a different view or solution for the original problem. Here I show that we have an option to write a code that will process only a valid subset of values with an option to detect and handle caseses when the exception was thrown.

    @Test
    public void getClasses() {

        String[] classNames = {"java.lang.Object", "java.lang.Integer", "java.lang.Foo"};
        List<Class> classes =
                Stream.of(classNames)
                        .map(className -> {
                            try {
                                return Class.forName(className);
                            } catch (ClassNotFoundException e) {
                                // log the error
                                return null;
                            }
                        })
                        .filter(c -> c != null)
                        .collect(Collectors.toList());

        if (classes.size() != classNames.length) {
            // add your error handling here if needed or process only the resulting list
            System.out.println("Did not process all class names");
        }

        classes.forEach(System.out::println);
    }

Troubleshooting "program does not contain a static 'Main' method" when it clearly does...?

That's odd. Does your program compile and run successfully and only fail on 'Publish' or does it fail on every compile now?

Also, have you perhaps changed the file's properties' Build Action to something other than Compile?

Installing OpenCV for Python on Ubuntu, getting ImportError: No module named cv2.cv

I found a solution in the guide here:

http://www.samontab.com/web/2014/06/installing-opencv-2-4-9-in-ubuntu-14-04-lts/

I resorted to compiling and installing from source. The process was very smooth, had I known, I would have started with that instead of trying to find a more simple way to install. Hopefully this information is helpful to someone.

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

#!/bin/sed -f
1,/^#include/ {
    /^#include/i\
#include "newfile.h"
}

How this script works: For lines between 1 and the first #include (after line 1), if the line starts with #include, then prepend the specified line.

However, if the first #include is in line 1, then both line 1 and the next subsequent #include will have the line prepended. If you are using GNU sed, it has an extension where 0,/^#include/ (instead of 1,) will do the right thing.

Using "super" in C++

After migrating from Turbo Pascal to C++ back in the day, I used to do this in order to have an equivalent for the Turbo Pascal "inherited" keyword, which works the same way. However, after programming in C++ for a few years I stopped doing it. I found I just didn't need it very much.

Getting Error:JRE_HOME variable is not defined correctly when trying to run startup.bat of Apache-Tomcat

Got the solution and it's working fine. Set the environment variables as:

  • CATALINA_HOME=C:\Program Files\Java\apache-tomcat-7.0.59\apache-tomcat-7.0.59 (path where your Apache Tomcat is)
  • JAVA_HOME=C:\Program Files\Java\jdk1.8.0_25; (path where your JDK is)
  • JRE_Home=C:\Program Files\Java\jre1.8.0_25; (path where your JRE is)
  • CLASSPATH=%JAVA_HOME%\bin;%JRE_HOME%\bin;%CATALINA_HOME%\lib

Why is Visual Studio 2013 very slow?

Resolve this issue by installing Microsoft SQL Server Compact 4.0

Microsoft SQL Server Compact 4.0

visual Studio 2013 performance issue due to missing Microsoft SQL Server Compact 4.0

SOAP vs REST (differences)

A lot of these answers entirely forgot to mention hypermedia controls (HATEOAS) which is completely fundamental to REST. A few others touched on it, but didn't really explain it so well.

This article should explain the difference between the concepts, without getting into the weeds on specific SOAP features.

"could not find stored procedure"

If the error message only occurs locally, try opening the sql file and press the play button.

Difference between os.getenv and os.environ.get

In Python 2.7 with iPython:

>>> import os
>>> os.getenv??
Signature: os.getenv(key, default=None)
Source:
def getenv(key, default=None):
    """Get an environment variable, return None if it doesn't exist.
    The optional second argument can specify an alternate default."""
    return environ.get(key, default)
File:      ~/venv/lib/python2.7/os.py
Type:      function

So we can conclude os.getenv is just a simple wrapper around os.environ.get.

How to clear jQuery validation error messages?

If you want to simply hide the errors:

$("#clearButton").click(function() {
  $("label.error").hide();
  $(".error").removeClass("error");
});

If you specified the errorClass, call that class to hide instead error (the default) I used above.

Convert xlsx file to csv using batch

Try in2csv!

Usage:

in2csv file.xlsx > file.csv

Positioning the colorbar

The best way to get good control over the colorbar position is to give it its own axis. Like so:

# What I imagine your plotting looks like so far
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(your_data)

# Now adding the colorbar
cbaxes = fig.add_axes([0.8, 0.1, 0.03, 0.8]) 
cb = plt.colorbar(ax1, cax = cbaxes)  

The numbers in the square brackets of add_axes refer to [left, bottom, width, height], where the coordinates are just fractions that go from 0 to 1 of the plotting area.