Programs & Examples On #Freetype2

How to use requirements.txt to install all dependencies in a python project

pip install -r requirements.txt for python 2.x

pip3 install -r requirements.txt for python 3.x (in case multiple versions are installed)

Forward X11 failed: Network error: Connection refused

fill in the "X display location" did not work for me. but install MobaXterm did the job.

setting content between div tags using javascript

Try the following:

document.getElementById("successAndErrorMessages").innerHTML="someContent"; 

msdn link for detail : innerHTML Property

React native ERROR Packager can't listen on port 8081

Try to run in another port like 3131. Run the command:

react-native run-android --port=3131

iOS Remote Debugging

You cannot directly remote debug Chrome on iOS currently. It uses a uiWebView that may act subtly different than Mobile Safari.

You have a few options.

Option 1: Remote-debug Mobile Safari using Safari's inspector. If your issue reproduces in Mobile Safari, this is definitely the best way to go. In fact, going through the iOS simulator is even easier.

Option 2: Use Weinre for a slimmed down debugging experience. Weinre doesn't have much features but sometimes it's good enough.

Option 3: Remote debug a proper uiWebView that functions the same.

Here's the best way to do this. You'll need to install XCode.

  1. Go to github.com/paulirish/iOS-WebView-App and "Download Zip" or clone.
  2. Open XCode, open existing project, and choose the project you just downloaded.
  3. Open WebViewAppDelegate.m and change the urlString to be the URL you want to test.
  4. Run the app in the iOS Simulator.
  5. Open Safari, Open the Develop Menu, Choose iOS Simulator and select your webview.
  6. Safari Inspector will now be inspecting your uiWebView.

enter image description here

enter image description here

enter image description here

How to split a String by space

Since it's been a while since these answers were posted, here's another more current way to do what's asked:

List<String> output = new ArrayList<>();
try (Scanner sc = new Scanner(inputString)) {
    while (sc.hasNext()) output.add(sc.next());
}

Now you have a list of strings (which is arguably better than an array); if you do need an array, you can do output.toArray(new String[0]);

how to always round up to the next integer

Math.Ceiling((double)list.Count() / 10);

JavaScript: filter() for Objects

How about:

function filterObj(keys, obj) {
  const newObj = {};
  for (let key in obj) {
    if (keys.includes(key)) {
      newObj[key] = obj[key];
    }
  }
  return newObj;
}

Or...

function filterObj(keys, obj) {
  const newObj = {};
  Object.keys(obj).forEach(key => {
    if (keys.includes(key)) {
      newObj[key] = obj[key];
    }
  });
  return newObj;
}

MySQL OPTIMIZE all tables?

Do all the necessary procedures for fixing all tables in all the databases with a simple shell script:

#!/bin/bash
mysqlcheck --all-databases
mysqlcheck --all-databases -o
mysqlcheck --all-databases --auto-repair
mysqlcheck --all-databases --analyze

How do I search within an array of hashes by hash values in ruby?

(Adding to previous answers (hope that helps someone):)

Age is simpler but in case of string and with ignoring case:

  • Just to verify the presence:

@fathers.any? { |father| father[:name].casecmp("john") == 0 } should work for any case in start or anywhere in the string i.e. for "John", "john" or "JoHn" and so on.

  • To find first instance/index:

@fathers.find { |father| father[:name].casecmp("john") == 0 }

  • To select all such indices:

@fathers.select { |father| father[:name].casecmp("john") == 0 }

plot different color for different categorical levels using matplotlib

I had the same question, and have spent all day trying out different packages.

I had originally used matlibplot: and was not happy with either mapping categories to predefined colors; or grouping/aggregating then iterating through the groups (and still having to map colors). I just felt it was poor package implementation.

Seaborn wouldn't work on my case, and Altair ONLY works inside of a Jupyter Notebook.

The best solution for me was PlotNine, which "is an implementation of a grammar of graphics in Python, and based on ggplot2".

Below is the plotnine code to replicate your R example in Python:

from plotnine import *
from plotnine.data import diamonds

g = ggplot(diamonds, aes(x='carat', y='price', color='color')) + geom_point(stat='summary')
print(g)

plotnine diamonds example

So clean and simple :)

Converting serial port data to TCP/IP in a Linux environment

I stumbled upon this question via a Google search for a very similar one (using the serial port on a server from a Linux client over TCP/IP), so, even though this is not an answer to exact original question, some of the code might be useful to the original poster, I think:

  • Making a Linux box with a serial port listen on the TCP port to share the modem: ser2net
  • Using this "shared" modem from another Linux workstation: remtty

How to create a collapsing tree table in html/css/js?

You can try jQuery treegrid (http://maxazan.github.io/jquery-treegrid/) or jQuery treetable (http://ludo.cubicphuse.nl/jquery-treetable/)

Both are using HTML <table> tag format and styled the as tree.

The jQuery treetable is using data-tt-id and data-tt-parent-id for determining the parent and child of the tree. Usage example:

<table id="tree">
  <tr data-tt-id="1">
    <td>Parent</td>
  </tr>
  <tr data-tt-id="2" data-tt-parent-id="1">
    <td>Child</td>
  </tr>
</table>
$("#tree").treetable({ expandable: true });

Meanwhile, jQuery treegrid is using only class for styling the tree. Usage example:

<table class="tree">
    <tr class="treegrid-1">
        <td>Root node</td><td>Additional info</td>
    </tr>
    <tr class="treegrid-2 treegrid-parent-1">
        <td>Node 1-1</td><td>Additional info</td>
    </tr>
    <tr class="treegrid-3 treegrid-parent-1">
        <td>Node 1-2</td><td>Additional info</td>
    </tr>
    <tr class="treegrid-4 treegrid-parent-3">
        <td>Node 1-2-1</td><td>Additional info</td>
    </tr>
</table>
<script type="text/javascript">
  $('.tree').treegrid();
</script>

Have a variable in images path in Sass?

Adding something to the above correct answers. I am using netbeans IDE and it shows error while using url(#{$assetPath}/site/background.jpg) this method. It was just netbeans error and no error in sass compiling. But this error break code formatting in netbeans and code become ugly. But when I use it inside quotes like below, it show wonder!

url("#{$assetPath}/site/background.jpg")

Pass a variable to a PHP script running from the command line

I strongly recommend the use of getopt.

If you want help to print out for your options then take a look at GetOptionKit.

SQL Add foreign key to existing column

Error indicates that there is no UserID column in your Employees table. Try adding the column first and then re-run the statement.

ALTER TABLE Employees
ADD CONSTRAINT FK_ActiveDirectories_UserID FOREIGN KEY (UserID)
    REFERENCES ActiveDirectories(id);

insert a NOT NULL column to an existing table

ALTER TABLE `MY_TABLE` ADD COLUMN `STAGE` INTEGER UNSIGNED NOT NULL AFTER `PREV_COLUMN`;

Copy struct to struct in C

Also a good example.....

struct point{int x,y;};
typedef struct point point_t;
typedef struct
{
    struct point ne,se,sw,nw;
}rect_t;
rect_t temp;


int main()
{
//rotate
    RotateRect(&temp);
    return 0;
}

void RotateRect(rect_t *givenRect)
{
    point_t temp_point;
    /*Copy struct data from struct to struct within a struct*/
    temp_point = givenRect->sw;
    givenRect->sw = givenRect->se;
    givenRect->se = givenRect->ne;
    givenRect->ne = givenRect->nw;
    givenRect->nw = temp_point;
}

What are the safe characters for making URLs?

From the context you describe, I suspect that what you're actually trying to make is something called an 'SEO slug'. The best general known practice for those is:

  1. Convert to lower-case
  2. Convert entire sequences of characters other than a-z and 0-9 to one hyphen (-) (not underscores)
  3. Remove 'stop words' from the URL, i.e. not-meaningfully-indexable words like 'a', 'an', and 'the'; Google 'stop words' for extensive lists

So, as an example, an article titled "The Usage of !@%$* to Represent Swearing In Comics" would get a slug of "usage-represent-swearing-comics".

How can I change the default Django date template format?

What you need is a date template filter.

e.g:

<td>Joined {{user.date_created|date:"F Y" }}<td>

This returns Joined December 2018

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

TL;DR: This would very likely work:

python mypkg/tests/test_module.py MyCase.testItIsHot

The explanation:

  • The convenient way

      python mypkg/tests/test_module.py MyCase.testItIsHot
    

    would work, but its unspoken assumption is you already have this conventional code snippet inside (typically at the end of) your test file.

    if __name__ == "__main__":
        unittest.main()
    
  • The inconvenient way

      python -m unittest mypkg.tests.test_module.TestClass.test_method
    

    would always work, without requiring you to have that if __name__ == "__main__": unittest.main() code snippet in your test source file.

So why is the second method considered inconvenient? Because it would be a pain in the <insert one of your body parts here> to type that long, dot-delimited path by hand. While in the first method, the mypkg/tests/test_module.py part can be auto-completed, either by a modern shell, or by your editor.

Reload the page after ajax success

use this Reload page

success: function(data){
   if(data.success == true){ // if true (1)
      setTimeout(function(){// wait for 5 secs(2)
           location.reload(); // then reload the page.(3)
      }, 5000); 
   }
}

Is there a function to copy an array in C/C++?

You can use the memcpy(),

void * memcpy ( void * destination, const void * source, size_t num );

memcpy() copies the values of num bytes from the location pointed by source directly to the memory block pointed by destination.

If the destination and source overlap, then you can use memmove().

void * memmove ( void * destination, const void * source, size_t num );

memmove() copies the values of num bytes from the location pointed by source to the memory block pointed by destination. Copying takes place as if an intermediate buffer were used, allowing the destination and source to overlap.

How to use LINQ Distinct() with multiple fields

I assume that you use distinct like a method call on a list. You need to use the result of the query as datasource for your DropDownList, for example by materializing it via ToList.

var distinctCategories = product
                        .Select(m => new {m.CategoryId, m.CategoryName})
                        .Distinct()
                        .ToList();
DropDownList1.DataSource     = distinctCategories;
DropDownList1.DataTextField  = "CategoryName";
DropDownList1.DataValueField = "CategoryId";

Another way if you need the real objects instead of the anonymous type with only few properties is to use GroupBy with an anonymous type:

List<Product> distinctProductList = product
    .GroupBy(m => new {m.CategoryId, m.CategoryName})
    .Select(group => group.First())  // instead of First you can also apply your logic here what you want to take, for example an OrderBy
    .ToList();

A third option is to use MoreLinq's DistinctBy.

git error: failed to push some refs to remote

I had faced same problem,fixed with below steps .

  1. git init
  2. git add .
  3. git commit -m 'Add your commit message'
  4. git remote add origin https://[email protected]/User_name/sample.git

    (Above url https://[email protected]/User_name/sample.git refers to your bit bucket project url )

  5. git push -u origin master

hint

check if your git hub account link with your local git by using:

git config --global user.email "[email protected]"
git config --global user.name "Your Name"

How to get start and end of day in Javascript?

It might be a little tricky, but you can make use of Intl.DateTimeFormat.

The snippet bellow can help you convert any date with any timezone to its begining/end time.

_x000D_
_x000D_
const beginingOfDay = (options = {}) => {
  const { date = new Date(), timeZone } = options;
  const parts = Intl.DateTimeFormat("en-US", {
    timeZone,
    hourCycle: "h23",
    hour: "numeric",
    minute: "numeric",
    second: "numeric",
  }).formatToParts(date);
  const hour = parseInt(parts.find((i) => i.type === "hour").value);
  const minute = parseInt(parts.find((i) => i.type === "minute").value);
  const second = parseInt(parts.find((i) => i.type === "second").value);
  return new Date(
    1000 *
      Math.floor(
        (date - hour * 3600000 - minute * 60000 - second * 1000) / 1000
      )
  );
};

const endOfDay = (...args) =>
  new Date(beginingOfDay(...args).getTime() + 86399999);

const beginingOfYear = () => {};

console.log(beginingOfDay({ timeZone: "GMT" }));
console.log(endOfDay({ timeZone: "GMT" }));
console.log(beginingOfDay({ timeZone: "Asia/Tokyo" }));
console.log(endOfDay({ timeZone: "Asia/Tokyo" }));
_x000D_
_x000D_
_x000D_

Turning off some legends in a ggplot

You can simply add show.legend=FALSE to geom to suppress the corresponding legend

Where do I get servlet-api.jar from?

Make sure that you're using the same Servlet API specification that your Web container supports. Refer to this chart if you're using Tomcat: http://tomcat.apache.org/whichversion.html

The Web container that you use will definitely have the API jars you require.

Tomcat 6 for example has it in apache-tomcat-6.0.26/lib/servlet-api.jar

How do you tell if caps lock is on using JavaScript?

Javascript Code

<script type="text/javascript">
   function isCapLockOn(e){
   kc = e.keyCode?e.keyCode:e.which;
   sk = e.shiftKey?e.shiftKey:((kc == 16)?true:false);
   if(((kc >= 65 && kc <= 90) && !sk)||((kc >= 97 && kc <= 122) && sk))
       document.getElementById('alert').style.visibility = 'visible';
   else
       document.getElementById('alert').style.visibility = 'hidden';
   }
</script>

We now need to associate this script using Html

<input type="password" name="txtPassword" onkeypress="isCapLockOn(event)" />
<div id="alert" style="visibility:hidden">Caps Lock is on.</div> 

C++ Pass A String

You can write your function to take a const std::string&:

void print(const std::string& input)
{
    cout << input << endl;
}

or a const char*:

void print(const char* input)
{
    cout << input << endl;
}

Both ways allow you to call it like this:

print("Hello World!\n"); // A temporary is made
std::string someString = //...
print(someString); // No temporary is made

The second version does require c_str() to be called for std::strings:

print("Hello World!\n"); // No temporary is made
std::string someString = //...
print(someString.c_str()); // No temporary is made

Getting assembly name

You can use the AssemblyName class to get the assembly name, provided you have the full name for the assembly:

AssemblyName.GetAssemblyName(Assembly.GetExecutingAssembly().FullName).Name

or

AssemblyName.GetAssemblyName(e.Source).Name

MSDN Reference - AssemblyName Class

PHP - auto refreshing page

you can use

<meta http-equiv="refresh" content="10" > 

just add it after the head tags

where 10 is the time your page will refresh itself

Inline onclick JavaScript variable

<script>var myVar = 15;</script>
<input id="EditBanner" type="button" value="Edit Image" onclick="EditBanner(myVar);"/>

ORA-28001: The password has expired

I had same problem even after changing the password, it wasn't getting reflected in SQLDEVELOPER.

Atlast following solved my problem :

  1. Open Command Propmt
  2. Type sqlplus
  3. login as sysdba
  4. Run following command : alter user USERNAME identified by NEW_PASSWORD;

Has been blocked by CORS policy: Response to preflight request doesn’t pass access control check

The CORS issue should be fixed in the backend. Temporary workaround uses this option.

  1. Go to C:\Program Files\Google\Chrome\Application

  2. Open command prompt

  3. Execute the command chrome.exe --disable-web-security --user-data-dir="c:/ChromeDevSession"

Using the above option, you can able to open new chrome without security. this chrome will not throw any cors issue.

enter image description here

Adding external resources (CSS/JavaScript/images etc) in JSP

The reason that you get the 404 File Not Found error, is that your path to CSS given as a value to the href attribute is missing context path.

An HTTP request URL contains the following parts:

http://[host]:[port][request-path]?[query-string]

The request path is further composed of the following elements:

  • Context path: A concatenation of a forward slash (/) with the context root of the servlet's web application. Example: http://host[:port]/context-root[/url-pattern]

  • Servlet path: The path section that corresponds to the component alias that activated this request. This path starts with a forward slash (/).

  • Path info: The part of the request path that is not part of the context path or the servlet path.

Read more here.


Solutions

There are several solutions to your problem, here are some of them:

1) Using <c:url> tag from JSTL

In my Java web applications I usually used <c:url> tag from JSTL when defining the path to CSS/JavaScript/image and other static resources. By doing so you can be sure that those resources are referenced always relative to the application context (context path).

If you say, that your CSS is located inside WebContent folder, then this should work:

<link type="text/css" rel="stylesheet" href="<c:url value="/globalCSS.css" />" />

The reason why it works is explained in the "JavaServer Pages™ Standard Tag Library" version 1.2 specification chapter 7.5 (emphasis mine):

7.5 <c:url>
Builds a URL with the proper rewriting rules applied.
...
The URL must be either an absolute URL starting with a scheme (e.g. "http:// server/context/page.jsp") or a relative URL as defined by JSP 1.2 in JSP.2.2.1 "Relative URL Specification". As a consequence, an implementation must prepend the context path to a URL that starts with a slash (e.g. "/page2.jsp") so that such URLs can be properly interpreted by a client browser.

NOTE
Don't forget to use Taglib directive in your JSP to be able to reference JSTL tags. Also see an example JSP page here.


2) Using JSP Expression Language and implicit objects

An alternative solution is using Expression Language (EL) to add application context:

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

Here we have retrieved the context path from the request object. And to access the request object we have used the pageContext implicit object.


3) Using <c:set> tag from JSTL

DISCLAIMER
The idea of this solution was taken from here.

To make accessing the context path more compact than in the solution ?2, you can first use the JSTL <c:set> tag, that sets the value of an EL variable or the property of an EL variable in any of the JSP scopes (page, request, session, or application) for later access.

<c:set var="root" value="${pageContext.request.contextPath}"/>
...
<link type="text/css" rel="stylesheet" href="${root}/globalCSS.css" />

IMPORTANT NOTE
By default, in order to set the variable in such manner, the JSP that contains this set tag must be accessed at least once (including in case of setting the value in the application scope using scope attribute, like <c:set var="foo" value="bar" scope="application" />), before using this new variable. For instance, you can have several JSP files where you need this variable. So you must ether a) both set the new variable holding context path in the application scope AND access this JSP first, before using this variable in other JSP files, or b) set this context path holding variable in EVERY JSP file, where you need to access to it.


4) Using ServletContextListener

The more effective way to make accessing the context path more compact is to set a variable that will hold the context path and store it in the application scope using a Listener. This solution is similar to solution ?3, but the benefit is that now the variable holding context path is set right at the start of the web application and is available application wide, no need for additional steps.

We need a class that implements ServletContextListener interface. Here is an example of such class:

package com.example.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class AppContextListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent event) {
        ServletContext sc = event.getServletContext();
        sc.setAttribute("ctx", sc.getContextPath());
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {}

}

Now in a JSP we can access this global variable using EL:

<link type="text/css" rel="stylesheet" href="${ctx}/globalCSS.css" />

NOTE
@WebListener annotation is available since Servlet version 3.0. If you use a servlet container or application server that supports older Servlet specifications, remove the @WebServlet annotation and instead configure the listener in the deployment descriptor (web.xml). Here is an example of web.xml file for the container that supports maximum Servlet version 2.5 (other configurations are omitted for the sake of brevity):

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                        http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    version="2.5">
    ...  
    <listener>
        <listener-class>com.example.listener.AppContextListener</listener-class>
    </listener>
    ...
</webapp>


5) Using scriptlets

As suggested by user @gavenkoa you can also use scriptlets like this:

<%= request.getContextPath() %>

For such a small thing it is probably OK, just note that generally the use of scriptlets in JSP is discouraged.


Conclusion

I personally prefer either the first solution (used it in my previous projects most of the time) or the second, as they are most clear, intuitive and unambiguous (IMHO). But you choose whatever suits you most.


Other thoughts

You can deploy your web app as the default application (i.e. in the default root context), so it can be accessed without specifying context path. For more info read the "Update" section here.

How do I add PHP code/file to HTML(.html) files?

By default you can't use PHP in HTML pages.

To do that, modify your .htacccess file with the following:

AddType application/x-httpd-php .html

How to align an indented line in a span that wraps into multiple lines?

display:block;

then you've got a block element and the margin is added to all lines.

While it's true that a span is semantically not a block element, there are cases where you don't have control of the pages DOM. This answer is inteded for those.

How to deserialize a list using GSON or another JSON library in Java?

With Gson, you'd just need to do something like:

List<Video> videos = gson.fromJson(json, new TypeToken<List<Video>>(){}.getType());

You might also need to provide a no-arg constructor on the Video class you're deserializing to.

HTML-Tooltip position relative to mouse pointer

We can achieve the same using "Directive" in Angularjs.

            //Bind mousemove event to the element which will show tooltip
            $("#tooltip").mousemove(function(e) {
                //find X & Y coodrinates
                x = e.clientX,
                y = e.clientY;

                //Set tooltip position according to mouse position
                tooltipSpan.style.top = (y + 20) + 'px';
                tooltipSpan.style.left = (x + 20) + 'px';
            });

You can check this post for further details. http://www.ufthelp.com/2014/12/Tooltip-Directive-AngularJS.html

Undo a particular commit in Git that's been pushed to remote repos

If the commit you want to revert is a merged commit (has been merged already), then you should either -m 1 or -m 2 option as shown below. This will let git know which parent commit of the merged commit to use. More details can be found HERE.

  • git revert <commit> -m 1
  • git revert <commit> -m 2

How can I set a DateTimePicker control to a specific date?

FYI: If you are setting the value, and not seeing anything - you might check to see if you have a 'CustomFormat' set - I just hit this and it was set to ' ' for the 1/1/1900 value (our 'not set' value) and set to MM/dd/yyyy if not.

Show Image View from file path?

You can also use:



    File imgFile = new  File(“filepath”);
    if(imgFile.exists())
    {
        ImageView myImage = new ImageView(this);
        myImage.setImageURI(Uri.fromFile(imgFile));

    }

This does the bitmap decoding implicit for you.

Putty: Getting Server refused our key Error

For those receiving this error from Windows Server, I received this same error and it was a user account issue. With many organizations, group policy for Administrators may not allow setting up SSH Server and connections. With that type of setup, this must be done from Local Admin account. Might be worth looking into if you have confirmed there are not any typos in the public key.

How to run ~/.bash_profile in mac terminal

You would never want to run that, but you may want to source it.

. ~/.bash_profile
source ~/.bash_profile

both should work. But this is an odd request, because that file should be sourced automatically when you start bash, unless you're explicitly starting it non-interactively. From the man page:

When bash is invoked as an interactive login shell, or as a non-interactive shell with the --login option, it first reads and executes commands from the file /etc/profile, if that file exists. After reading that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile, in that order, and reads and executes commands from the first one that exists and is readable. The --noprofile option may be used when the shell is started to inhibit this behavior.

Why does git status show branch is up-to-date when changes exist upstream?

While these are all viable answers, I decided to give my way of checking if local repo is in line with the remote, whithout fetching or pulling. In order to see where my branches are I use simply:

git remote show origin

What it does is return all the current tracked branches and most importantly - the info whether they are up to date, ahead or behind the remote origin ones. After the above command, this is an example of what is returned:

  * remote origin
  Fetch URL: https://github.com/xxxx/xxxx.git
  Push  URL: https://github.com/xxxx/xxxx.git
  HEAD branch: master
  Remote branches:
    master      tracked
    no-payments tracked
  Local branches configured for 'git pull':
    master      merges with remote master
    no-payments merges with remote no-payments
  Local refs configured for 'git push':
    master      pushes to master      (local out of date)
    no-payments pushes to no-payments (local out of date)

Hope this helps someone.

How do I replicate a \t tab space in HTML?

&nbsp;&nbsp;&nbsp;&nbsp; would be a work around if you're only after the spacing.

Git push error: "origin does not appear to be a git repository"

I had this problem cause i had already origin remote defined locally. So just change "origin" into another name:

git remote add originNew https://github.com/UAwebM...

git push -u originNew

or u can remove your local origin. to check your remote name type:

git remote

to remove remote - log in your clone repository and type:

git remote remove origin(depending on your remote's name)

How to get the <html> tag HTML with JavaScript / jQuery?

This is how to get the html DOM element purely with JS:

var htmlElement = document.getElementsByTagName("html")[0];

or

var htmlElement = document.querySelector("html");

And if you want to use jQuery to get attributes from it...

$(htmlElement).attr(INSERT-ATTRIBUTE-NAME);

Javascript - Append HTML to container element without innerHTML

<div id="Result">
</div>

<script>
for(var i=0; i<=10; i++){
var data = "<b>vijay</b>";
 document.getElementById('Result').innerHTML += data;
}
</script>

assign the data for div with "+=" symbol you can append data including previous html data

Filtering JSON array using jQuery grep()

var data = {
    "items": [{
        "id": 1,
        "category": "cat1"
    }, {
        "id": 2,
        "category": "cat2"
    }, {
        "id": 3,
        "category": "cat1"
    }]
};

var returnedData = $.grep(data.items, function (element, index) {
    return element.id == 1;
});


alert(returnedData[0].id + "  " + returnedData[0].category);

The returnedData is returning an array of objects, so you can access it by array index.

http://jsfiddle.net/wyfr8/913/

Convert List(of object) to List(of string)

Not possible without iterating to build a new list. You can wrap the list in a container that implements IList.

You can use LINQ to get a lazy evaluated version of IEnumerable<string> from an object list like this:

var stringList = myList.OfType<string>();

SQL Server SELECT INTO @variable?

you can do this:

SELECT 
    CustomerId, 
    FirstName, 
    LastName, 
    Email
INTO #tempCustomer 
FROM 
    Customer
WHERE 
    CustomerId = @CustomerId

then later

SELECT CustomerId FROM #tempCustomer

you doesn't need to declare the structure of #tempCustomer

Change background color of selected item on a ListView

For those wondering what EXACTLY needs to be done to keep rows selected even as you scroll up down. It's the state_activated The rest is taken care of by internal functionality, you don't have to worry about toggle, and can select multiple items. I didn't need to use notifyDataSetChanged() or setSelected(true) methods.

Add this line to your selector file, for me drawable\row_background.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@android:color/holo_blue_light"/>

    <item android:state_enabled="true" android:state_pressed="true" android:drawable="@android:color/holo_blue_light" />
    <item android:state_enabled="true" android:state_focused="true" android:drawable="@android:color/holo_blue_bright" />
    <item android:state_enabled="true" android:state_selected="true" android:drawable="@android:color/holo_blue_light" />
    <item android:state_activated="true" android:drawable="@android:color/holo_blue_light" />

    <item android:drawable="@android:color/transparent"/>
</selector>

Then in layout\custom_row.xml

<?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="10dip"
        android:background="@drawable/row_background"
        android:orientation="vertical">
  <TextView
        android:id="@+id/line1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

For more information, I'm using this with ListView Adapter, using myList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL); and myList.setMultiChoiceModeListener(new MultiChoiceModeListener()...

from this example: http://www.androidbegin.com/tutorial/android-delete-multiple-selected-items-listview-tutorial/

Also, you (should) use this structure for your list-adapter coupling: List myList = new ArrayList();

instead of: ArrayList myList = new ArrayList();

Explanation: Type List vs type ArrayList in Java

PHPMailer AddAddress()

You need to call the AddAddress method once for every recipient. Like so:

$mail->AddAddress('[email protected]', 'Person One');
$mail->AddAddress('[email protected]', 'Person Two');
// ..

To make things easy, you should loop through an array to do this.

$recipients = array(
   '[email protected]' => 'Person One',
   '[email protected]' => 'Person Two',
   // ..
);
foreach($recipients as $email => $name)
{
   $mail->AddAddress($email, $name);
}

Better yet, add them as Carbon Copy recipients.

$mail->AddCC('[email protected]', 'Person One');
$mail->AddCC('[email protected]', 'Person Two');
// ..

To make things easy, you should loop through an array to do this.

$recipients = array(
   '[email protected]' => 'Person One',
   '[email protected]' => 'Person Two',
   // ..
);
foreach($recipients as $email => $name)
{
   $mail->AddCC($email, $name);
}

$(document).ready equivalent without jQuery

If you don't have to support very old browsers, here is a way to do it even when your external script is loaded with async attribute:

HTMLDocument.prototype.ready = new Promise(function(resolve) {
   if(document.readyState != "loading")
      resolve();
   else
      document.addEventListener("DOMContentLoaded", function() {
         resolve();
      });
});

document.ready.then(function() {
   console.log("document.ready");
});

Invoke(Delegate)

A control or window object in Windows Forms is just a wrapper around a Win32 window identified by a handle (sometimes called HWND). Most things you do with the control will eventually result in a Win32 API call that uses this handle. The handle is owned by the thread that created it (typically the main thread), and shouldn't be manipulated by another thread. If for some reason you need to do something with the control from another thread, you can use Invoke to ask the main thread to do it on your behalf.

For instance, if you want to change the text of a label from a worker thread, you can do something like this:

theLabel.Invoke(new Action(() => theLabel.Text = "hello world from worker thread!"));

How to load local file in sc.textFile, instead of HDFS

I have a file called NewsArticle.txt on my Desktop.

In Spark, I typed:

val textFile= sc.textFile(“file:///C:/Users/582767/Desktop/NewsArticle.txt”)

I needed to change all the \ to / character for the filepath.

To test if it worked, I typed:

textFile.foreach(println)

I'm running Windows 7 and I don't have Hadoop installed.

How do you change the colour of each category within a highcharts column chart?

Also you can set option:

  {plotOptions: {column: {colorByPoint: true}}}

for more information read docs

How to uninstall an older PHP version from centOS7

yum -y remove php* to remove all php packages then you can install the 5.6 ones.

SQLPLUS error:ORA-12504: TNS:listener was not given the SERVICE_NAME in CONNECT_DATA

Just a small observation: you keep mentioning conn usr\pass, and this is a typo, right? Cos it should be conn usr/pass. Or is it different on a Unix based OS?

Furthermore, just to be sure: if you use tnsnames, your login string will look different from when you use the login method you started this topic out with.

tnsnames.ora should be in $ORACLE_HOME$\network\admin. That is the Oracle home on the machine from which you are trying to connect, so in your case your PC. If you have multiple oracle_homes and wish to use only one tnsnames.ora, you can set environment variable tns_admin (e.g. set TNS_ADMIN=c:\oracle\tns), and place tnsnames.ora in that directory.

Your original method of logging on (usr/[email protected]:port/servicename) should always work. So far I think you have all the info, except for the port number, which I am sure your DBA will be able to give you. If this method still doesn't work, either the server's IP address is not available from your client, or it is a firewall issue (blocking a certain port), or something else not (directly) related to Oracle or SQL*Plus.

hth! Regards, Remco

openCV program compile error "libopencv_core.so.2.4: cannot open shared object file: No such file or directory" in ubuntu 12.04

Add this link:

/usr/local/lib/*.so.*

The total is:

g++ -o main.out main.cpp -I /usr/local/include -I /usr/local/include/opencv -I /usr/local/include/opencv2 -L /usr/local/lib /usr/local/lib/*.so /usr/local/lib/*.so.*

What is the difference between char, nchar, varchar, and nvarchar in SQL Server?

  • nchar is fixed-length and can hold unicode characters. it uses two bytes storage per character.

  • varchar is of variable length and cannot hold unicode characters. it uses one byte storage per character.

List All Google Map Marker Images

var pinIcon = new google.maps.MarkerImage(
    "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|00D900",
    null, /* size is determined at runtime */
    null, /* origin is 0,0 */
    null, /* anchor is bottom center of the scaled image */
    new google.maps.Size(12, 18)
);

port 8080 is already in use and no process using 8080 has been listed

If no other process is using the port 8080, Eventhough eclipse shows the port 8080 is used while starting the server in eclipse, first you have to stop the server by hitting the stop button in "Configure Tomcat"(which you can find in your start menu under tomcat folder), then try to start the server in eclipse then it will be started.

If any other process is using the port 8080 and as well as you no need to disturb it. then you can change the port.

Initialising a multidimensional array in Java

I'll add that if you want to read the dimensions, you can do this:

int[][][] a = new int[4][3][2];

System.out.println(a.length);  // 4
System.out.println(a[0].length); // 3
System.out.println(a[0][0].length); //2

You can also have jagged arrays, where different rows have different lengths, so a[0].length != a[1].length.

Toolbar navigation icon never set

(The answer to user802421)

private void setToolbar() {
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    if (toolbar != null) {
        setSupportActionBar(toolbar);
        toolbar.setNavigationIcon(R.drawable.ic_action_back);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
    }
}

toolbar.xml

<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="@dimen/toolbar_height"
    android:background="?attr/colorPrimaryDark" />

OpenCV C++/Obj-C: Detecting a sheet of paper / Square Detection

Well, I'm late.


In your image, the paper is white, while the background is colored. So, it's better to detect the paper is Saturation(???) channel in HSV color space. Take refer to wiki HSL_and_HSV first. Then I'll copy most idea from my answer in this Detect Colored Segment in an image.


Main steps:

  1. Read into BGR
  2. Convert the image from bgr to hsv space
  3. Threshold the S channel
  4. Then find the max external contour(or do Canny, or HoughLines as you like, I choose findContours), approx to get the corners.

This is my result:

enter image description here


The Python code(Python 3.5 + OpenCV 3.3):

#!/usr/bin/python3
# 2017.12.20 10:47:28 CST
# 2017.12.20 11:29:30 CST

import cv2
import numpy as np

##(1) read into  bgr-space
img = cv2.imread("test2.jpg")

##(2) convert to hsv-space, then split the channels
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
h,s,v = cv2.split(hsv)

##(3) threshold the S channel using adaptive method(`THRESH_OTSU`) or fixed thresh
th, threshed = cv2.threshold(s, 50, 255, cv2.THRESH_BINARY_INV)

##(4) find all the external contours on the threshed S
#_, cnts, _ = cv2.findContours(threshed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cv2.findContours(threshed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]

canvas  = img.copy()
#cv2.drawContours(canvas, cnts, -1, (0,255,0), 1)

## sort and choose the largest contour
cnts = sorted(cnts, key = cv2.contourArea)
cnt = cnts[-1]

## approx the contour, so the get the corner points
arclen = cv2.arcLength(cnt, True)
approx = cv2.approxPolyDP(cnt, 0.02* arclen, True)
cv2.drawContours(canvas, [cnt], -1, (255,0,0), 1, cv2.LINE_AA)
cv2.drawContours(canvas, [approx], -1, (0, 0, 255), 1, cv2.LINE_AA)

## Ok, you can see the result as tag(6)
cv2.imwrite("detected.png", canvas)

Related answers:

  1. How to detect colored patches in an image using OpenCV?
  2. Edge detection on colored background using OpenCV
  3. OpenCV C++/Obj-C: Detecting a sheet of paper / Square Detection
  4. How to use `cv2.findContours` in different OpenCV versions?

C# - How to convert string to char?

var theString = "TEST";
char[] myChar = theString.ToCharArray();

I tested this in the C# interactive window of Visual Studio 2019 and got:

char[4] { 'T', 'E', 'S', 'T' }

Disabling of EditText in Android

Disable = FOCUS+CLICK+CURSOR

Disabling focus, click, and cursor visibility does the trick for me.

Here is the code in XML

<EditText
    android:id="@+id/name"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:focusable="false"
    android:cursorVisible="false"
    android:clickable="false"
    />

Round double in two decimal places in C#?

Another easy way is to use ToString with a parameter. Example:

float d = 54.9700F;    
string s = d.ToString("N2");
Console.WriteLine(s);

Result:

54.97

Post request with Wget?

Wget currently only supports x-www-form-urlencoded data. --post-file is not for transmitting files as form attachments, it expects data with the form: key=value&otherkey=example.

--post-data and --post-file work the same way: the only difference is that --post-data allows you to specify the data in the command line, while --post-file allows you to specify the path of the file that contain the data to send.

Here's the documentation:

 --post-data=string
       --post-file=file
           Use POST as the method for all HTTP requests and send the specified data
           in the request body.  --post-data sends string as data, whereas
           --post-file sends the contents of file.  Other than that, they work in
           exactly the same way. In particular, they both expect content of the
           form "key1=value1&key2=value2", with percent-encoding for special
           characters; the only difference is that one expects its content as a
           command-line parameter and the other accepts its content from a file. In
           particular, --post-file is not for transmitting files as form
           attachments: those must appear as "key=value" data (with appropriate
           percent-coding) just like everything else. Wget does not currently
           support "multipart/form-data" for transmitting POST data; only
           "application/x-www-form-urlencoded". Only one of --post-data and
           --post-file should be specified.

Regarding your authentication token, it should either be provided in the header, in the path of the url, or in the data itself. This must be indicated somewhere in the documentation of the service you use. In a POST request, as in a GET request, you must specify the data using keys and values. This way the server will be able to receive multiple information with specific names. It's similar with variables.

Hence, you can't just send a magic token to the server, you also need to specify the name of the key. If the key is "token", then it should be token=YOUR_TOKEN.

wget --post-data 'user=foo&password=bar' http://example.com/auth.php

Also, you should consider using curl if you can because it is easier to send files using it. There are many examples on the Internet for that.

WebAPI to Return XML

Here's another way to be compatible with an IHttpActionResult return type. In this case I am asking it to use the XML Serializer(optional) instead of Data Contract serializer, I'm using return ResponseMessage( so that I get a return compatible with IHttpActionResult:

return ResponseMessage(new HttpResponseMessage(HttpStatusCode.OK)
       {
           Content = new ObjectContent<SomeType>(objectToSerialize, 
              new System.Net.Http.Formatting.XmlMediaTypeFormatter { 
                  UseXmlSerializer = true 
              })
       });

What exactly does stringstream do?

You entered an alphanumeric and int, blank delimited in mystr.

You then tried to convert the first token (blank delimited) into an int.

The first token was RS which failed to convert to int, leaving a zero for myprice, and we all know what zero times anything yields.

When you only entered int values the second time, everything worked as you expected.

It was the spurious RS that caused your code to fail.

UIView touch event in controller

Updating @Chackle's answer for Swift 2.x:

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    if let touch = touches.first {
        let currentPoint = touch.locationInView(self)
        // do something with your currentPoint
    }
}

override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
    if let touch = touches.first {
        let currentPoint = touch.locationInView(self)
        // do something with your currentPoint
    }
}

override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
    if let touch = touches.first {
        let currentPoint = touch.locationInView(self)
        // do something with your currentPoint
    }
}

How do I revert an SVN commit?

Alex, try this: svn merge [WorkingFolderPath] -r 1944:1943

Unable to compile simple Java 10 / Java 11 project with Maven

If you are using spring boot then add these tags in pom.xml.

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
</plugin>

and

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    `<maven.compiler.release>`10</maven.compiler.release>
</properties>

You can change java version to 11 or 13 as well in <maven.compiler.release> tag.

Just add below tags in pom.xml

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <maven.compiler.release>11</maven.compiler.release>
</properties>

You can change the 11 to 10, 13 as well to change java version. I am using java 13 which is latest. It works for me.

PHPUnit assert that an exception was thrown?

An alternative way can be the following:

$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('Expected Exception Message');

Please ensure that your test class extents \PHPUnit_Framework_TestCase.

Flask - Calling python function on button OnClick event

Easiest solution

<button type="button" onclick="window.location.href='{{ url_for( 'move_forward') }}';">Forward</button>

Is there a download function in jsFiddle?

You have to put /show a after the URL you're working on:

For example:

"http://jsfiddle.net/rkw79/PagTJ/show/"

for Field URL :

"http://jsfiddle.net/rkw79/PagTJ/"

after that save the file and go to the show folder(or the file name you have saved with) under that folder u will get a html file show_resource.HTML .that is your actual file.now open it in browser and view the source code. Best of luck--------Ujjwal Gupta

how to assign a block of html code to a javascript variable

 var test = "<div class='saved' >"+
 "<div >test.test</div> <div class='remove'>[Remove]</div></div>";

You can add "\n" if you require line-break.

Configure active profile in SpringBoot via Maven

You should use the Spring Boot Maven Plugin:

<project>  
  ...
  <build>
    ...
    <plugins>
      ...
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <version>1.5.1.RELEASE</version>
        <configuration>
          <profiles>
            <profile>foo</profile>
            <profile>bar</profile>
          </profiles>
        </configuration>
        ...
      </plugin>
      ...
    </plugins>
    ...
  </build>
  ...
</project>

How to use jQuery to call an ASP.NET web service?

SPServices is a jQuery library which abstracts SharePoint's Web Services and makes them easier to use

It is certified for SharePoint 2007

The list of supported operations for Lists.asmx could be found here

Example

In this example, we're grabbing all of the items in the Announcements list and displaying the Titles in a bulleted list in the tasksUL div:

<script type="text/javascript" src="filelink/jquery-1.6.1.min.js"></script>
<script type="text/javascript" src="filelink/jquery.SPServices-0.6.2.min.js"></script>
<script language="javascript" type="text/javascript">

$(document).ready(function() {
  $().SPServices({
    operation: "GetListItems",
    async: false,
    listName: "Announcements",
    CAMLViewFields: "<ViewFields><FieldRef Name='Title' /></ViewFields>",
    completefunc: function (xData, Status) {
      $(xData.responseXML).SPFilterNode("z:row").each(function() {
        var liHtml = "<li>" + $(this).attr("ows_Title") + "</li>";
        $("#tasksUL").append(liHtml);
      });
    }
  });
});
</script>
<ul id="tasksUL"/>

How many socket connections can a web server handle?

It looks like the answer is at least 12 million if you have a beefy server, your server software is optimized for it, you have enough clients. If you test from one client to one server, the number of port numbers on the client will be one of the obvious resource limits (Each TCP connection is defined by the unique combination of IP and port number at the source and destination).

(You need to run multiple clients as otherwise you hit the 64K limit on port numbers first)

When it comes down to it, this is a classic example of the witticism that "the difference between theory and practise is much larger in practise than in theory" - in practise achieving the higher numbers seems to be a cycle of a. propose specific configuration/architecture/code changes, b. test it till you hit a limit, c. Have I finished? If not then d. work out what was the limiting factor, e. go back to step a (rinse and repeat).

Here is an example with 2 million TCP connections onto a beefy box (128GB RAM and 40 cores) running Phoenix http://www.phoenixframework.org/blog/the-road-to-2-million-websocket-connections - they ended up needing 50 or so reasonably significant servers just to provide the client load (their initial smaller clients maxed out to early, eg "maxed our 4core/15gb box @ 450k clients").

Here is another reference for go this time at 10 million: http://goroutines.com/10m.

This appears to be java based and 12 million connections: https://mrotaru.wordpress.com/2013/06/20/12-million-concurrent-connections-with-migratorydata-websocket-server/

How to Use UTF-8 Collation in SQL Server database?

Two UDF to deal with UTF-8 in T-SQL:

CREATE Function UcsToUtf8(@src nvarchar(MAX)) returns varchar(MAX) as
begin
    declare @res varchar(MAX)='', @pi char(8)='%[^'+char(0)+'-'+char(127)+']%', @i int, @j int
    select @i=patindex(@pi,@src collate Latin1_General_BIN)
    while @i>0
    begin
        select @j=unicode(substring(@src,@i,1))
        if @j<0x800     select @res=@res+left(@src,@i-1)+char((@j&1984)/64+192)+char((@j&63)+128)
        else            select @res=@res+left(@src,@i-1)+char((@j&61440)/4096+224)+char((@j&4032)/64+128)+char((@j&63)+128)
        select @src=substring(@src,@i+1,datalength(@src)-1), @i=patindex(@pi,@src collate Latin1_General_BIN)
    end
    select @res=@res+@src
    return @res
end

CREATE Function Utf8ToUcs(@src varchar(MAX)) returns nvarchar(MAX) as
begin
    declare @i int, @res nvarchar(MAX)=@src, @pi varchar(18)
    select @pi='%[à-ï][€-¿][€-¿]%',@i=patindex(@pi,@src collate Latin1_General_BIN)
    while @i>0 select @res=stuff(@res,@i,3,nchar(((ascii(substring(@src,@i,1))&31)*4096)+((ascii(substring(@src,@i+1,1))&63)*64)+(ascii(substring(@src,@i+2,1))&63))), @src=stuff(@src,@i,3,'.'), @i=patindex(@pi,@src collate Latin1_General_BIN)
    select @pi='%[Â-ß][€-¿]%',@i=patindex(@pi,@src collate Latin1_General_BIN)
    while @i>0 select @res=stuff(@res,@i,2,nchar(((ascii(substring(@src,@i,1))&31)*64)+(ascii(substring(@src,@i+1,1))&63))), @src=stuff(@src,@i,2,'.'),@i=patindex(@pi,@src collate Latin1_General_BIN)
    return @res
end

Execute a command line binary with Node.js

Since version 4 the closest alternative is child_process.execSync method:

const {execSync} = require('child_process');

let output = execSync('prince -v builds/pdf/book.html -o builds/pdf/book.pdf');

?? Note that execSync call blocks event loop.

Load different application.yml in SpringBoot Test

Spring-boot framework allows us to provide YAML files as a replacement for the .properties file and it is convenient.The keys in property files can be provided in YAML format in application.yml file in the resource folder and spring-boot will automatically take it up.Keep in mind that the yaml format has to keep the spaces correct for the value to be read correctly.

You can use the @Value("${property}") to inject the values from the YAML files. Also Spring.active.profiles can be given to differentiate between different YAML for different environments for convenient deployment.

For testing purposes, the test YAML file can be named like application-test.yml and placed in the resource folder of the test directory.

If you are specifying the application-test.yml and provide the spring test profile in the .yml, then you can use the @ActiveProfiles('test') annotation to direct spring to take the configurations from the application-test.yml that you have specified.

@RunWith(SpringRunner.class)
@SpringBootTest(classes = ApplicationTest.class)
@ActiveProfiles("test")
public class MyTest {
 ...
}

If you are using JUnit 5 then no need for other annotations as @SpringBootTest already include the springrunner annotation. Keeping a separate main ApplicationTest.class enables us to provide separate configuration classes for tests and we can prevent the default configuration beans from loading by excluding them from a component scan in the test main class. You can also provide the profile to be loaded there.

@SpringBootApplication(exclude=SecurityAutoConfiguration.class)
public class ApplicationTest {
 
    public static void main(String[] args) {
        SpringApplication.run(ApplicationTest.class, args);
    }
}

Here is the link for Spring documentation regarding the use of YAML instead of .properties file(s): https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html

How to use the new Material Design Icon themes: Outlined, Rounded, Two-Tone and Sharp?

I ended up using IcoMoon app to create a custom font using only the new themed icons I required for a recent web app build. It's not perfect but you can mimic the existing Google Font functionality pretty nicely with a little bit of setup. Here's a writeup:

https://medium.com/@leemartin/how-to-use-material-icon-outlined-rounded-two-tone-and-sharp-themes-92276f2415d2

If someone is feeling daring, they could convert the entire theme using IcoMoon. Hell, IcoMoon probably has an internal process that would make it easy since they already have the original Material Icons set in their library.

Anyway, this isn't a perfect solution, but it worked for me.

Update query with PDO and MySQL

  1. Your UPDATE syntax is wrong
  2. You probably meant to update a row not all of them so you have to use WHERE clause to target your specific row

Change

UPDATE `access_users`   
      (`contact_first_name`,`contact_surname`,`contact_email`,`telephone`) 
      VALUES (:firstname, :surname, :telephone, :email)

to

UPDATE `access_users`   
   SET `contact_first_name` = :firstname,
       `contact_surname` = :surname,
       `contact_email` = :email,
       `telephone` = :telephone 
 WHERE `user_id` = :user_id -- you probably have some sort of id 

SignalR - Sending a message to a specific user using (IUserIdProvider) *NEW 2.0.0*

Old thread, but just came across this in a sample:

services.AddSignalR()
            .AddAzureSignalR(options =>
        {
            options.ClaimsProvider = context => new[]
            {
                new Claim(ClaimTypes.NameIdentifier, context.Request.Query["username"])
            };
        });

bash, extract string before a colon

This works for me you guys can try it out

INPUT='ubuntu:x:1000:1000:Ubuntu:/home/ubuntu:/bin/bash'
SUBSTRING=$(echo $INPUT| cut -d: -f1)
echo $SUBSTRING

What's the difference between django OneToOneField and ForeignKey?

Be careful to realize that there are some differences between OneToOneField(SomeModel) and ForeignKey(SomeModel, unique=True). As stated in The Definitive Guide to Django:

OneToOneField

A one-to-one relationship. Conceptually, this is similar to a ForeignKey with unique=True, but the "reverse" side of the relation will directly return a single object.

In contrast to the OneToOneField "reverse" relation, a ForeignKey "reverse" relation returns a QuerySet.

Example

For example, if we have the following two models (full model code below):

  1. Car model uses OneToOneField(Engine)
  2. Car2 model uses ForeignKey(Engine2, unique=True)

From within python manage.py shell execute the following:

OneToOneField Example

>>> from testapp.models import Car, Engine
>>> c = Car.objects.get(name='Audi')
>>> e = Engine.objects.get(name='Diesel')
>>> e.car
<Car: Audi>

ForeignKey with unique=True Example

>>> from testapp.models import Car2, Engine2
>>> c2 = Car2.objects.get(name='Mazda')
>>> e2 = Engine2.objects.get(name='Wankel')
>>> e2.car2_set.all()
[<Car2: Mazda>]

Model Code

from django.db import models

class Engine(models.Model):
    name = models.CharField(max_length=25)

    def __unicode__(self):
        return self.name

class Car(models.Model):
    name = models.CharField(max_length=25)
    engine = models.OneToOneField(Engine)

    def __unicode__(self):
        return self.name

class Engine2(models.Model):
    name = models.CharField(max_length=25)

    def __unicode__(self):
        return self.name

class Car2(models.Model):
    name = models.CharField(max_length=25)
    engine = models.ForeignKey(Engine2, unique=True, on_delete=models.CASCADE)

    def __unicode__(self):
        return self.name

How to encode URL to avoid special characters in Java?

URL construction is tricky because different parts of the URL have different rules for what characters are allowed: for example, the plus sign is reserved in the query component of a URL because it represents a space, but in the path component of the URL, a plus sign has no special meaning and spaces are encoded as "%20".

RFC 2396 explains (in section 2.4.2) that a complete URL is always in its encoded form: you take the strings for the individual components (scheme, authority, path, etc.), encode each according to its own rules, and then combine them into the complete URL string. Trying to build a complete unencoded URL string and then encode it separately leads to subtle bugs, like spaces in the path being incorrectly changed to plus signs (which an RFC-compliant server will interpret as real plus signs, not encoded spaces).

In Java, the correct way to build a URL is with the URI class. Use one of the multi-argument constructors that takes the URL components as separate strings, and it'll escape each component correctly according to that component's rules. The toASCIIString() method gives you a properly-escaped and encoded string that you can send to a server. To decode a URL, construct a URI object using the single-string constructor and then use the accessor methods (such as getPath()) to retrieve the decoded components.

Don't use the URLEncoder class! Despite the name, that class actually does HTML form encoding, not URL encoding. It's not correct to concatenate unencoded strings to make an "unencoded" URL and then pass it through a URLEncoder. Doing so will result in problems (particularly the aforementioned one regarding spaces and plus signs in the path).

Save each sheet in a workbook to separate CSV files

Use Visual Basic to loop through worksheets and save .csv files.

  1. Open up .xlsx file in Excel.

  2. Press option+F11

  3. Insert ? Module

  4. Insert this into the module code:

    Public Sub SaveWorksheetsAsCsv()
    
     Dim WS As Excel.Worksheet
     Dim SaveToDirectory As String
    
     SaveToDirectory = "./"
    
     For Each WS In ThisWorkbook.Worksheets
        WS.SaveAs SaveToDirectory & WS.Name & ".csv", xlCSV
     Next
    
    End Sub
    
  5. Find your .csv files in ~/Library/Containers/com.microsoft.Excel/Data.

    open ~/Library/Containers/com.microsoft.Excel/Data
    
  6. Close .xlsx file.

  7. Rinse and repeat for other .xlsx files.

Detect if a jQuery UI dialog box is open

jQuery dialog has an isOpen property that can be used to check if a jQuery dialog is open or not.

You can see example at this link: http://www.codegateway.com/2012/02/detect-if-jquery-dialog-box-is-open.html

Return list of items in list greater than some value

Since your desired output is sorted, you also need to sort it:

>>> j=[4, 5, 6, 7, 1, 3, 7, 5]
>>> sorted(x for x in j if x >= 5)
[5, 5, 6, 7, 7]

Normalizing a list of numbers in Python

If working with data, many times pandas is the simple key

This particular code will put the raw into one column, then normalize by column per row. (But we can put it into a row and do it by row per column, too! Just have to change the axis values where 0 is for row and 1 is for column.)

import pandas as pd


raw = [0.07, 0.14, 0.07]  

raw_df = pd.DataFrame(raw)
normed_df = raw_df.div(raw_df.sum(axis=0), axis=1)
normed_df

where normed_df will display like:

    0
0   0.25
1   0.50
2   0.25

and then can keep playing with the data, too!

How to cancel/abort jQuery AJAX request?

The jquery ajax method returns a XMLHttpRequest object. You can use this object to cancel the request.

The XMLHttpRequest has a abort method, which cancels the request, but if the request has already been sent to the server then the server will process the request even if we abort the request but the client will not wait for/handle the response.

The xhr object also contains a readyState which contains the state of the request(UNSENT-0, OPENED-1, HEADERS_RECEIVED-2, LOADING-3 and DONE-4). we can use this to check whether the previous request was completed.

$(document).ready(
    var xhr;

    var fn = function(){
        if(xhr && xhr.readyState != 4){
            xhr.abort();
        }
        xhr = $.ajax({
            url: 'ajax/progress.ftl',
            success: function(data) {
                //do something
            }
        });
    };

    var interval = setInterval(fn, 500);
);

Laravel Carbon subtract days from current date

Use subDays() method:

$users = Users::where('status_id', 'active')
           ->where( 'created_at', '>', Carbon::now()->subDays(30))
           ->get();

Error: Jump to case label

C++11 standard on jumping over some initializations

JohannesD gave an explanation, now for the standards.

The C++11 N3337 standard draft 6.7 "Declaration statement" says:

3 It is possible to transfer into a block, but not in a way that bypasses declarations with initialization. A program that jumps (87) from a point where a variable with automatic storage duration is not in scope to a point where it is in scope is ill-formed unless the variable has scalar type, class type with a trivial default constructor and a trivial destructor, a cv-qualified version of one of these types, or an array of one of the preceding types and is declared without an initializer (8.5).

87) The transfer from the condition of a switch statement to a case label is considered a jump in this respect.

[ Example:

void f() {
   // ...
  goto lx;    // ill-formed: jump into scope of a
  // ...
ly:
  X a = 1;
  // ...
lx:
  goto ly;    // OK, jump implies destructor
              // call for a followed by construction
              // again immediately following label ly
}

— end example ]

As of GCC 5.2, the error message now says:

crosses initialization of

C

C allows it: c99 goto past initialization

The C99 N1256 standard draft Annex I "Common warnings" says:

2 A block with initialization of an object that has automatic storage duration is jumped into

master branch and 'origin/master' have diverged, how to 'undiverge' branches'?

Met this problem when I created a branch based on branch A by

git checkout -b a

and then I set the up stream of branch a to origin branch B by

git branch -u origin/B

Then I got the error message above.

One way to solve this problem for me was,

  • Delete the branch a
  • Create a new branch b by
git checkout -b b origin/B

How to use JavaScript source maps (.map files)?

Just wanted to focus on the last part of the question; How source map files are created? by listing the build tools I know that can create source maps.

  1. Grunt: using plugin grunt-contrib-uglify
  2. Gulp: using plugin gulp-uglify
  3. Google closure: using parameter --create_source_map

How to use jQuery to get the current value of a file input field

its not .val() if you want to get file /home/user/default.png it will get with .val() just default.png

Difference between subprocess.Popen and os.system

Subprocess is based on popen2, and as such has a number of advantages - there's a full list in the PEP here, but some are:

  • using pipe in the shell
  • better newline support
  • better handling of exceptions

Spring MVC @PathVariable with dot (.) is getting truncated

Here's an approach that relies purely on java configuration:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

@Configuration
public class MvcConfig extends WebMvcConfigurationSupport{

    @Bean
    public RequestMappingHandlerMapping requestMappingHandlerMapping() {
        RequestMappingHandlerMapping handlerMapping = super.requestMappingHandlerMapping();
        handlerMapping.setUseSuffixPatternMatch(false);
        handlerMapping.setUseTrailingSlashMatch(false);
        return handlerMapping;
    }
}

How do I specify different Layouts in the ASP.NET MVC 3 razor ViewStart file?

One more method is to Define the Layout inside the View:

   @{
    Layout = "~/Views/Shared/_MyAdminLayout.cshtml";
    }

More Ways to do, can be found here, hope this helps someone.

BehaviorSubject vs Observable?

Observable and subject both are observable's means an observer can track them. but both of them have some unique characteristics. Further there are total 3 type of subjects each of them again have unique characteristics. lets try to to understand each of them.

you can find the practical example here on stackblitz. (You need to check the console to see the actual output)

enter image description here

Observables

They are cold: Code gets executed when they have at least a single observer.

Creates copy of data: Observable creates copy of data for each observer.

Uni-directional: Observer can not assign value to observable(origin/master).

Subject

They are hot: code gets executed and value gets broadcast even if there is no observer.

Shares data: Same data get shared between all observers.

bi-directional: Observer can assign value to observable(origin/master).

If are using using subject then you miss all the values that are broadcast before creation of observer. So here comes Replay Subject

ReplaySubject

They are hot: code gets executed and value get broadcast even if there is no observer.

Shares data: Same data get shared between all observers.

bi-directional: Observer can assign value to observable(origin/master). plus

Replay the message stream: No matter when you subscribe the replay subject you will receive all the broadcasted messages.

In subject and replay subject you can not set the initial value to observable. So here comes Behavioral Subject

BehaviorSubject

They are hot: code gets executed and value get broadcast even if there is no observer.

Shares data: Same data get shared between all observers.

bi-directional: Observer can assign value to observable(origin/master). plus

Replay the message stream: No matter when you subscribe the replay subject you will receive all the broadcasted messages.

You can set initial value: You can initialize the observable with default value.

How to select all rows which have same value in some column

select *
from Table1 as t1
where
    exists (
        select *
        from Table1 as t2 
        where t2.Phone = t1.Phone and t2.id <> t1.id
    )

sql fiddle demo

Python Decimals format

Only first part of Justin's answer is correct. Using "%.3g" will not work for all cases as .3 is not the precision, but total number of digits. Try it for numbers like 1000.123 and it breaks.

So, I would use what Justin is suggesting:

>>> ('%.4f' % 12340.123456).rstrip('0').rstrip('.')
'12340.1235'
>>> ('%.4f' % -400).rstrip('0').rstrip('.')
'-400'
>>> ('%.4f' % 0).rstrip('0').rstrip('.')
'0'
>>> ('%.4f' % .1).rstrip('0').rstrip('.')
'0.1'

How to resolve 'unrecognized selector sent to instance'?

Very weird, but. You have to declare the class for your application instance as myApplication: UIApplication instead of myApplication: NSObject . It seems that the UIApplicationDelegate protocol doesn't implement the +registerForSystemEvents message. Crazy Apple APIs, again.

Mapping two integers to one, in a unique and deterministic way

Say you have a 32 bit integer, why not just move A into the first 16 bit half and B into the other?

def vec_pack(vec):
    return vec[0] + vec[1] * 65536;


def vec_unpack(number):
    return [number % 65536, number // 65536];

Other than this being as space efficient as possible and cheap to compute, a really cool side effect is that you can do vector math on the packed number.

a = vec_pack([2,4])
b = vec_pack([1,2])

print(vec_unpack(a+b)) # [3, 6] Vector addition
print(vec_unpack(a-b)) # [1, 2] Vector subtraction
print(vec_unpack(a*2)) # [4, 8] Scalar multiplication

Extract file basename without path and extension in bash

Here are oneliners:

  1. $(basename "${s%.*}")
  2. $(basename "${s}" ".${s##*.}")

I needed this, the same as asked by bongbang and w4etwetewtwet.

How to disable horizontal scrolling of UIScrollView?

I had the tableview contentInset set in viewDidLoad (as below) that what causing the horizontal scrolling

self.tableView.contentInset = UIEdgeInsetsMake(0, 30, 0, 0);

Check if there are any tableview contentInset set for different reasons and disable it

In LaTeX, how can one add a header/footer in the document class Letter?

With regard to Brent.Longborough's answer (appering only on page 2 onward), perhaps you need to set the \thispagestyle{} after \begin{document}. I wonder if the letter class is setting the first page style to empty.

Escaping ampersand character in SQL string

straight from oracle sql fundamentals book

SET DEFINE OFF
select 'Coda & Sid' from dual;
SET DEFINE ON

how would one escape it without setting define.

How to center cards in bootstrap 4?

Add the css for .card

.card {
        margin: 0 auto; /* Added */
        float: none; /* Added */
        margin-bottom: 10px; /* Added */
}

here is the pen

UPDATE: You can use the class .mx-auto available in bootstrap 4 to center cards.

HttpContext.Current.Request.Url.Host what it returns?

Try this:

string callbackurl = Request.Url.Host != "localhost" 
    ? Request.Url.Host : Request.Url.Authority;

This will work for local as well as production environment. Because the local uses url with port no that is possible using Url.Host.

call a static method inside a class?

Let's assume this is your class:

class Test
{
    private $baz = 1;

    public function foo() { ... }

    public function bar() 
    {
        printf("baz = %d\n", $this->baz);
    }

    public static function staticMethod() { echo "static method\n"; }
}

From within the foo() method, let's look at the different options:

$this->staticMethod();

So that calls staticMethod() as an instance method, right? It does not. This is because the method is declared as public static the interpreter will call it as a static method, so it will work as expected. It could be argued that doing so makes it less obvious from the code that a static method call is taking place.

$this::staticMethod();

Since PHP 5.3 you can use $var::method() to mean <class-of-$var>::; this is quite convenient, though the above use-case is still quite unconventional. So that brings us to the most common way of calling a static method:

self::staticMethod();

Now, before you start thinking that the :: is the static call operator, let me give you another example:

self::bar();

This will print baz = 1, which means that $this->bar() and self::bar() do exactly the same thing; that's because :: is just a scope resolution operator. It's there to make parent::, self:: and static:: work and give you access to static variables; how a method is called depends on its signature and how the caller was called.

To see all of this in action, see this 3v4l.org output.

Delete specific values from column with where condition?

You don't want to delete if you're wanting to leave the row itself intact. You want to update the row, and change the column value.

The general form for this would be an UPDATE statement:

UPDATE <table name>
SET
    ColumnA = <NULL, or '', or whatever else is suitable for the new value for the column>
WHERE
    ColumnA = <bad value> /* or any other search conditions */

Directory.GetFiles of certain extension

If you would like to do your filtering in LINQ, you can do it like this:

var ext = new List<string> { "jpg", "gif", "png" };
var myFiles = Directory
    .EnumerateFiles(dir, "*.*", SearchOption.AllDirectories)
    .Where(s => ext.Contains(Path.GetExtension(s).TrimStart(".").ToLowerInvariant()));

Now ext contains a list of allowed extensions; you can add or remove items from it as necessary for flexible filtering.

Flask Value error view function did not return a response

You are not returning a response object from your view my_form_post. The function ends with implicit return None, which Flask does not like.

Make the function my_form_post return an explicit response, for example

return 'OK'

at the end of the function.

How to query a CLOB column in Oracle

If you are using SQL*Plus try the following...

set long 8000

select ...

What exactly do "u" and "r" string flags do, and what are raw string literals?

Unicode string literals

Unicode string literals (string literals prefixed by u) are no longer used in Python 3. They are still valid but just for compatibility purposes with Python 2.

Raw string literals

If you want to create a string literal consisting of only easily typable characters like english letters or numbers, you can simply type them: 'hello world'. But if you want to include also some more exotic characters, you'll have to use some workaround. One of the workarounds are Escape sequences. This way you can for example represent a new line in your string simply by adding two easily typable characters \n to your string literal. So when you print the 'hello\nworld' string, the words will be printed on separate lines. That's very handy!

On the other hand, there are some situations when you want to create a string literal that contains escape sequences but you don't want them to be interpreted by Python. You want them to be raw. Look at these examples:

'New updates are ready in c:\windows\updates\new'
'In this lesson we will learn what the \n escape sequence does.'

In such situations you can just prefix the string literal with the r character like this: r'hello\nworld' and no escape sequences will be interpreted by Python. The string will be printed exactly as you created it.

Raw string literals are not completely "raw"?

Many people expect the raw string literals to be raw in a sense that "anything placed between the quotes is ignored by Python". That is not true. Python still recognizes all the escape sequences, it just does not interpret them - it leaves them unchanged instead. It means that raw string literals still have to be valid string literals.

From the lexical definition of a string literal:

string     ::=  "'" stringitem* "'"
stringitem ::=  stringchar | escapeseq
stringchar ::=  <any source character except "\" or newline or the quote>
escapeseq  ::=  "\" <any source character>

It is clear that string literals (raw or not) containing a bare quote character: 'hello'world' or ending with a backslash: 'hello world\' are not valid.

How do I get the domain originating the request in express.js?

Instead of:

var host = req.get('host');
var origin = req.get('origin');

you can also use:

var host = req.headers.host;
var origin = req.headers.origin;

How to select the first, second, or third element with a given class name?

This isn't so much an answer as a non-answer, i.e. an example showing why one of the highly voted answers above is actually wrong.

I thought that answer looked good. In fact, it gave me what I was looking for: :nth-of-type which, for my situation, worked. (So, thanks for that, @Bdwey.)

I initially read the comment by @BoltClock (which says that the answer is essentially wrong) and dismissed it, as I had checked my use case, and it worked. Then I realized @BoltClock had a reputation of 300,000+(!) and has a profile where he claims to be a CSS guru. Hmm, I thought, maybe I should look a little closer.

Turns out as follows: div.myclass:nth-of-type(2) does NOT mean "the 2nd instance of div.myclass". Rather, it means "the 2nd instance of div, and it must also have the 'myclass' class". That's an important distinction when there are intervening divs between your div.myclass instances.

It took me some time to get my head around this. So, to help others figure it out more quickly, I've written an example which I believe demonstrates the concept more clearly than a written description: I've hijacked the h1, h2, h3 and h4 elements to essentially be divs. I've put an A class on some of them, grouped them in 3's, and then colored the 1st, 2nd and 3rd instances blue, orange and green using h?.A:nth-of-type(?). (But, if you're reading carefully, you should be asking "the 1st, 2nd and 3rd instances of what?"). I also interjected a dissimilar (i.e. different h level) or similar (i.e. same h level) un-classed element into some of the groups.

Note, in particular, the last grouping of 3. Here, an un-classed h3 element is inserted between the first and second h3.A elements. In this case, no 2nd color (i.e. orange) appears, and the 3rd color (i.e. green) shows up on the 2nd instance of h3.A. This shows that the n in h3.A:nth-of-type(n) is counting the h3s, not the h3.As.

Well, hope that helps. And thanks, @BoltClock.

_x000D_
_x000D_
div {_x000D_
  margin-bottom: 2em;_x000D_
  border: red solid 1px;_x000D_
  background-color: lightyellow;_x000D_
}_x000D_
_x000D_
h1,_x000D_
h2,_x000D_
h3,_x000D_
h4 {_x000D_
  font-size: 12pt;_x000D_
  margin: 5px;_x000D_
}_x000D_
_x000D_
h1.A:nth-of-type(1),_x000D_
h2.A:nth-of-type(1),_x000D_
h3.A:nth-of-type(1) {_x000D_
  background-color: cyan;_x000D_
}_x000D_
_x000D_
h1.A:nth-of-type(2),_x000D_
h2.A:nth-of-type(2),_x000D_
h3.A:nth-of-type(2) {_x000D_
  background-color: orange;_x000D_
}_x000D_
_x000D_
h1.A:nth-of-type(3),_x000D_
h2.A:nth-of-type(3),_x000D_
h3.A:nth-of-type(3) {_x000D_
  background-color: lightgreen;_x000D_
}
_x000D_
<div>_x000D_
  <h1 class="A">h1.A #1</h1>_x000D_
  <h1 class="A">h1.A #2</h1>_x000D_
  <h1 class="A">h1.A #3</h1>_x000D_
</div>_x000D_
_x000D_
<div>_x000D_
  <h2 class="A">h2.A #1</h2>_x000D_
  <h4>this intervening element is a different type, i.e. h4 not h2</h4>_x000D_
  <h2 class="A">h2.A #2</h2>_x000D_
  <h2 class="A">h2.A #3</h2>_x000D_
</div>_x000D_
_x000D_
<div>_x000D_
  <h3 class="A">h3.A #1</h3>_x000D_
  <h3>this intervening element is the same type, i.e. h3, but has no class</h3>_x000D_
  <h3 class="A">h3.A #2</h3>_x000D_
  <h3 class="A">h3.A #3</h3>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Is it possible to use 'else' in a list comprehension?

Yes, else can be used in Python inside a list comprehension with a Conditional Expression ("ternary operator"):

>>> [("A" if b=="e" else "c") for b in "comprehension"]
['c', 'c', 'c', 'c', 'c', 'A', 'c', 'A', 'c', 'c', 'c', 'c', 'c']

Here, the parentheses "()" are just to emphasize the conditional expression, they are not necessarily required (Operator precedence).

Additionaly, several expressions can be nested, resulting in more elses and harder to read code:

>>> ["A" if b=="e" else "d" if True else "x" for b in "comprehension"]
['d', 'd', 'd', 'd', 'd', 'A', 'd', 'A', 'd', 'd', 'd', 'd', 'd']
>>>

On a related note, a comprehension can also contain its own if condition(s) at the end:

>>> ["A" if b=="e" else "c" for b in "comprehension" if False]
[]
>>> ["A" if b=="e" else "c" for b in "comprehension" if "comprehension".index(b)%2]
['c', 'c', 'A', 'A', 'c', 'c']

Conditions? Yes, multiple ifs are possible, and actually multiple fors, too:

>>> [i for i in range(3) for _ in range(3)]
[0, 0, 0, 1, 1, 1, 2, 2, 2]
>>> [i for i in range(3) if i for _ in range(3) if _ if True if True]
[1, 1, 2, 2]

(The single underscore _ is a valid variable name (identifier) in Python, used here just to show it's not actually used. It has a special meaning in interactive mode)

Using this for an additional conditional expression is possible, but of no real use:

>>> [i for i in range(3)]
[0, 1, 2]
>>> [i for i in range(3) if i]
[1, 2]
>>> [i for i in range(3) if (True if i else False)]
[1, 2]

Comprehensions can also be nested to create "multi-dimensional" lists ("arrays"):

>>> [[i for j in range(i)] for i in range(3)]
[[], [1], [2, 2]]

Last but not least, a comprehension is not limited to creating a list, i.e. else and if can also be used the same way in a set comprehension:

>>> {i for i in "set comprehension"}
{'o', 'p', 'm', 'n', 'c', 'r', 'i', 't', 'h', 'e', 's', ' '}

and a dictionary comprehension:

>>> {k:v for k,v in [("key","value"), ("dict","comprehension")]}
{'key': 'value', 'dict': 'comprehension'}

The same syntax is also used for Generator Expressions:

>>> for g in ("a" if b else "c" for b in "generator"):
...     print(g, end="")
...
aaaaaaaaa>>>

which can be used to create a tuple (there is no tuple comprehension).


Further reading:

dyld: Library not loaded: /usr/local/opt/openssl/lib/libssl.1.0.0.dylib

first, list the details of the installed openssl version(or other programs) by:

$ls -al /usr/local/Cellar/openssl*
/usr/local/Cellar/openssl:
total 0
drwxr-xr-x    3 mba  staff    96 Nov 30 17:18 .
drwxrwxr-x  170 mba  admin  5440 Apr  8 02:03 ..
drwxr-xr-x   13 mba  staff   416 Nov 21 03:13 1.0.2t

/usr/local/Cellar/[email protected]:
total 0
drwxr-xr-x    4 mba  staff   128 Apr  7 18:35 .
drwxrwxr-x  170 mba  admin  5440 Apr  8 02:03 ..
drwxr-xr-x   14 mba  staff   448 Oct  1  2019 1.1.1d
drwxr-xr-x   14 mba  staff   448 Apr  7 18:35 1.1.1f

as above output, there are only one "right" versions "openssl" in my mac. then, switch to it:

$brew switch openssl 1.0.2t                                 
Cleaning /usr/local/Cellar/openssl/1.0.2t
Opt link created for /usr/local/Cellar/openssl/1.0.2t

How to convert Rows to Columns in Oracle?

You can do it with a pivot query, like this:

select * from (
   select LOAN_NUMBER, DOCUMENT_TYPE, DOCUMENT_ID
   from my_table t
)
pivot 
(
   MIN(DOCUMENT_ID)
   for DOCUMENT_TYPE in ('Voters ID','Pan card','Drivers licence')
)

Here is a demo on sqlfiddle.com.

How to Exit a Method without Exiting the Program?

If the function is a void, ending the function will return. Otherwise, you need to do an explicit return someValue. As Mark mentioned, you can also throw an exception. What's the context of your question? Do you have a larger code sample with which to show you some ways to exit the function?

Convert SVG to image (JPEG, PNG, etc.) in the browser

There are several ways to convert SVG to PNG using the Canvg library.

In my case, I needed to get the PNG blob from inline SVG.

The library documentation provides an example (see OffscreenCanvas example).

But this method does not work at the moment in Firefox. Yes, you can enable the gfx.offscreencanvas.enabled option in the settings. But will every user on the site do this? :)

However, there is another way that will work in Firefox too.

const el = document.getElementById("some-svg"); //this is our inline SVG

var canvas = document.createElement('canvas'); //create a canvas for the SVG render
canvas.width = el.clientWidth; //set canvas sizes
canvas.height = el.clientHeight;

const svg = new XMLSerializer().serializeToString(el); //convert SVG to string

//render SVG inside canvas
const ctx = canvas.getContext('2d');
const v = await Canvg.fromString(ctx, svg);
await v.render();

let canvasBlob = await new Promise(resolve => canvas.toBlob(resolve));

For the last line thanks to this answer

Foreach in a Foreach in MVC View

Assuming your controller's action method is something like this:

public ActionResult AllCategories(int id = 0)
{
    return View(db.Categories.Include(p => p.Products).ToList());
}

Modify your models to be something like this:

public class Product
{
    [Key]
    public int ID { get; set; }
    public int CategoryID { get; set; }
    //new code
    public virtual Category Category { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public string Path { get; set; }

    //remove code below
    //public virtual ICollection<Category> Categories { get; set; }
}

public class Category
{
    [Key]
    public int CategoryID { get; set; }
    public string Name { get; set; }
    //new code
    public virtual ICollection<Product> Products{ get; set; }
}

Then your since now the controller takes in a Category as Model (instead of a Product):

foreach (var category in Model)
{
    <h3><u>@category.Name</u></h3>
    <div>
        <ul>    
            @foreach (var product in Model.Products)
            {
                // cut for brevity, need to add back more code from original
                <li>@product.Title</li>
            }
        </ul>
    </div>
}

UPDATED: Add ToList() to the controller return statement.

Bind class toggle to window scroll event

This is my solution, it's not that tricky and allow you to use it for several markup throught a simple ng-class directive. Like so you can choose the class and the scrollPos for each case.

Your App.js :

angular.module('myApp',[])
    .controller('mainCtrl',function($window, $scope){
        $scope.scrollPos = 0;

        $window.onscroll = function(){
            $scope.scrollPos = document.body.scrollTop || document.documentElement.scrollTop || 0;
            $scope.$apply(); //or simply $scope.$digest();
        };
    });

Your index.html :

<html ng-app="myApp">
    <head></head>
    <body>
        <section ng-controller="mainCtrl">
            <p class="red" ng-class="{fix:scrollPos >= 100}">fix me when scroll is equals to 100</p>
            <p class="blue" ng-class="{fix:scrollPos >= 150}">fix me when scroll is equals to 150</p>
        </section>
    </body>
</html>

working JSFiddle here

EDIT :

As $apply() is actually calling $rootScope.$digest() you can directly use $scope.$digest() instead of $scope.$apply() for better performance depending on context.
Long story short : $apply() will always work but force the $digest on all scopes that may cause perfomance issue.

What is the meaning of {...this.props} in Reactjs

You will use props in your child component

for example

if your now component props is

{
   booking: 4,
   isDisable: false
}

you can use this props in your child compoenet

 <div {...this.props}> ... </div>

in you child component, you will receive all your parent props.

How can I delete an item from an array in VB.NET?

Seems like this sounds more complicated than it is...

    Dim myArray As String() = TextBox1.Lines
    'First we count how many null elements there are...
    Dim Counter As Integer = 0
    For x = 0 To myArray.Count - 1
        If Len(myArray(x)) < 1 Then
            Counter += 1
        End If
    Next
    'Then we dimension an array to be the size of the last array
    'minus the amount of nulls found...
    Dim tempArr(myArray.Count - Counter) As String

    'Indexing starts at zero, so let's set the stage for that...
    Counter = -1

    For x = 0 To myArray.Count - 1
        'Set the conditions for the new array as in
        'It .contains("word"), has no value, length is less than 1, ect.
        If Len(myArray(x)) > 1 Then
            Counter += 1
            'So if a value is present, we move that value over to
            'the new array.
            tempArr(Counter) = myArray(x)
        End If
    Next

Now you can assign tempArr back to the original or what ever you need done with it as in...

TextBox1.Lines = tempArr (You now have a textbox void of blank lines)

download a file from Spring boot rest service

Option 1 using an InputStreamResource

Resource implementation for a given InputStream.

Should only be used if no other specific Resource implementation is > applicable. In particular, prefer ByteArrayResource or any of the file-based Resource implementations where possible.

@RequestMapping(path = "/download", method = RequestMethod.GET)
public ResponseEntity<Resource> download(String param) throws IOException {

    // ...

    InputStreamResource resource = new InputStreamResource(new FileInputStream(file));

    return ResponseEntity.ok()
            .headers(headers)
            .contentLength(file.length())
            .contentType(MediaType.APPLICATION_OCTET_STREAM)
            .body(resource);
}

Option2 as the documentation of the InputStreamResource suggests - using a ByteArrayResource:

@RequestMapping(path = "/download", method = RequestMethod.GET)
public ResponseEntity<Resource> download(String param) throws IOException {

    // ...

    Path path = Paths.get(file.getAbsolutePath());
    ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(path));

    return ResponseEntity.ok()
            .headers(headers)
            .contentLength(file.length())
            .contentType(MediaType.APPLICATION_OCTET_STREAM)
            .body(resource);
}

How do I get the last four characters from a string in C#?

mystring.Substring(Math.Max(0, mystring.Length - 4)); //how many lines is this?

If you're positive the length of your string is at least 4, then it's even shorter:

mystring.Substring(mystring.Length - 4);

How to set upload_max_filesize in .htaccess?

php_value upload_max_filesize 30M is correct.

You will have to contact your hosters -- some don't allow you to change values in php.ini

C# ASP.NET Send Email via TLS

TLS (Transport Level Security) is the slightly broader term that has replaced SSL (Secure Sockets Layer) in securing HTTP communications. So what you are being asked to do is enable SSL.

.htaccess: Invalid command 'RewriteEngine', perhaps misspelled or defined by a module not included in the server configuration

I can see that your using AppServ, mod_rewrite is disabled by default on that WAMP package (just googled it)

Solution:

Find: C:/AppServ/Apache/conf/httpd.conf file.

and un-comment this line #LoadModule rewrite_module modules/mod_rewrite.so

Restart apache... Simplez

How to show "Done" button on iPhone number pad

The trick I've seen used is to make a custom transparent button the size of the whole view and then in its click method, have the text field resign first responder. So the user can click anywhere outside of the field to dismiss the keypad.

Remove all special characters from a string in R?

Instead of using regex to remove those "crazy" characters, just convert them to ASCII, which will remove accents, but will keep the letters.

astr <- "Ábcdêãçoàúü"
iconv(astr, from = 'UTF-8', to = 'ASCII//TRANSLIT')

which results in

[1] "Abcdeacoauu"

How to install and use "make" in Windows?

Another alternative is if you already installed minGW and added the bin folder the to Path environment variable, you can use "mingw32-make" instead of "make".

You can also create a symlink from "make" to "mingw32-make", or copying and changing the name of the file. I would not recommend the options before, they will work until you do changes on the minGW.

How to find the .NET framework version of a Visual Studio project?

It's as easy as in your Visual studio.

  1. go to the 4th menu option on top, 'website'.
  2. under websites go to option, 'start options'.
  3. under start options, go to 'build' option.
  4. change the target framework there to what so ever framework.

Best way to serialize/unserialize objects in JavaScript?

I am the author of https://github.com/joonhocho/seri.

Seri is JSON + custom (nested) class support.

You simply need to provide toJSON and fromJSON to serialize and deserialize any class instances.

Here's an example with nested class objects:

import seri from 'seri';

class Item {
  static fromJSON = (name) => new Item(name)

  constructor(name) {
    this.name = name;
  }

  toJSON() {
    return this.name;
  }
}

class Bag {
  static fromJSON = (itemsJson) => new Bag(seri.parse(itemsJson))

  constructor(items) {
    this.items = items;
  }

  toJSON() {
    return seri.stringify(this.items);
  }
}

// register classes
seri.addClass(Item);
seri.addClass(Bag);


const bag = new Bag([
  new Item('apple'),
  new Item('orange'),
]);


const bagClone = seri.parse(seri.stringify(bag));


// validate
bagClone instanceof Bag;

bagClone.items[0] instanceof Item;
bagClone.items[0].name === 'apple';

bagClone.items[1] instanceof Item;
bagClone.items[1].name === 'orange';

Hope it helps address your problem.

How do I get and set Environment variables in C#?

If the purpose of reading environment variable is to override the values in the appsetting.json or any other config file, you can archive it through EnvironmentVariablesExtensions.

var builder = new ConfigurationBuilder()
                .AddJsonFile("appSettings.json")
                .AddEnvironmentVariables(prefix: "ABC_")

var config = builder.Build();

enter image description here

According to this example, Url for the environment is read from the appsettings.json. but when the AddEnvironmentVariables(prefix: "ABC_") line is added to the ConfigurationBuilder the value appsettings.json will be override by in the environement varibale value.

Excel VBA Code: Compile Error in x64 Version ('PtrSafe' attribute required)

I think all you need to do for your function is just add PtrSafe: i.e. the first line of your first function should look like this:

Private Declare PtrSafe Function swe_azalt Lib "swedll32.dll" ......

Generate Row Serial Numbers in SQL Query

Sometime we might don't want to apply ordering on our result set to add serial number. But if we are going to use ROW_NUMBER() then we have to have a ORDER BY clause. So, for that we can simply apply a tricks to avoid any ordering on the result set.

SELECT ROW_NUMBER() OVER(ORDER BY (SELECT 1)) AS ItemNo, ItemName FROM ItemMastetr

For that we don't need to apply order by on our result set. We'll just add ItemNo on our given result set.

Conversion of System.Array to List

You can do like this basically:

int[] ints = new[] { 10, 20, 10, 34, 113 };

this is your array, and than you can call your new list like this:

 var newList = new List<int>(ints);

You can do this for complex object too.

What is the difference between document.location.href and document.location?

The document.location is an object that contains properties for the current location.

The href property is one of these properties, containing the complete URL, i.e. all the other properties put together.

Some browsers allow you to assign an URL to the location object and acts as if you assigned it to the href property. Some other browsers are more picky, and requires you to use the href property. Thus, to make the code work in all browsers, you have to use the href property.

Both the window and document objects has a location object. You can set the URL using either window.location.href or document.location.href. However, logically the document.location object should be read-only (as you can't change the URL of a document; changing the URL loads a new document), so to be on the safe side you should rather use window.location.href when you want to set the URL.

What is a database transaction?

I would suggest that a definition of 'transaction processing' would be more useful, as it covers transactions as a concept in computer science.

From wikipedia:

In computer science, transaction processing is information processing that is divided into individual, indivisible operations, called transactions. Each transaction must succeed or fail as a complete unit; it cannot remain in an intermediate state.

http://en.wikipedia.org/wiki/Transaction_processing#Implementations

Git will not init/sync/update new submodules

I had the same problem but none of the solutions above helped. The entries in the .gitmodules and in .git/config were right but the command git submodules update --init --recursive was doing nothing. I also removed the submodule directory and did run git submodules update --init --recursive and got the submodule directory back but with exactly the same commit as before.

I found the answer on this page. The command is:git submodule update --remote

URL encoding in Android

For android, I would use String android.net.Uri.encode(String s)

Encodes characters in the given string as '%'-escaped octets using the UTF-8 scheme. Leaves letters ("A-Z", "a-z"), numbers ("0-9"), and unreserved characters ("_-!.~'()*") intact. Encodes all other characters.

Ex/

String urlEncoded = "http://stackoverflow.com/search?q=" + Uri.encode(query);

getElementById in React

import React, { useState } from 'react';

function App() {
  const [apes , setap] = useState('yo');
  const handleClick = () =>{
    setap(document.getElementById('name').value)
  };
  return (
    <div>
      <input id='name' />
      <h2> {apes} </h2>
      <button onClick={handleClick} />
  </div>
  );
}

export default App;

Connect to Oracle DB using sqlplus

tnsping xe --if you have installed express edition
tnsping orcl --or if you have installed enterprise or standard edition then try to run
--if you get a response with your description then you will write the below command
sqlplus  --this will prompt for user
hr --user that you have created or use system
password --inputted at the time of user creation for hr, or put the password given at the time of setup for system user
hope this will connect if db run at your localhost.
--if db host in a remote host then you must use tns name for our example orcl or xe
try this to connect remote
hr/pass...@orcl or hr/pass...@xe --based on what edition you have installed

Can I call curl_setopt with CURLOPT_HTTPHEADER multiple times to set multiple headers?

Following what curl does internally for the request (via the method outlined in this answer to "Php - Debugging Curl") answers the question: No, it is not possible to use the curl_setopt call with CURLOPT_HTTPHEADER. The second call will overwrite the headers of the first call.

Instead the function needs to be called once with all headers:

$headers = array(
    'Content-type: application/xml',
    'Authorization: gfhjui',
);
curl_setopt($curlHandle, CURLOPT_HTTPHEADER, $headers);

Related (but different) questions are:

pip connection failure: cannot fetch index base URL http://pypi.python.org/simple/

I had the same issue with pip 1.5.6.

I just deleted the ~/.pip folder and it worked like a charm.

rm -r ~/.pip/

close fxml window by code, javafx

Hide doesn't close the window, just put in visible mode. The best solution was:

@FXML
private void exitButtonOnAction(ActionEvent event){
        ((Stage)(((Button)event.getSource()).getScene().getWindow())).close();      
}

What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?

In addition to keeping the variables local, one very handy use is when writing a library using a global variable, you can give it a shorter variable name to use within the library. It's often used in writing jQuery plugins, since jQuery allows you to disable the $ variable pointing to jQuery, using jQuery.noConflict(). In case it is disabled, your code can still use $ and not break if you just do:

(function($) { ...code...})(jQuery);

How to start an Android application from the command line?

You can use:

adb shell monkey -p com.package.name -c android.intent.category.LAUNCHER 1

This will start the LAUNCHER Activity of the application using monkeyrunner test tool.

How to read from standard input in the console?

Another way to read multiple inputs within a loop which can handle an input with spaces:

package main
import (
    "fmt"
    "bufio"
    "os"
)

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    var text string
    for text != "q" {  // break the loop if text == "q"
        fmt.Print("Enter your text: ")
        scanner.Scan()
        text = scanner.Text()
        if text != "q" {
            fmt.Println("Your text was: ", text)
        }
    }
}

Output:

Enter your text: Hello world!
Your text was:  Hello world!
Enter your text: Go is awesome!
Your text was:  Go is awesome!
Enter your text: q

How to evaluate a math expression given in string form?

Try the following sample code using JDK1.6's Javascript engine with code injection handling.

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

public class EvalUtil {
private static ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
public static void main(String[] args) {
    try {
        System.out.println((new EvalUtil()).eval("(((5+5)/2) > 5) || 5 >3 "));
        System.out.println((new EvalUtil()).eval("(((5+5)/2) > 5) || true"));
    } catch (Exception e) {
        e.printStackTrace();
    }
}
public Object eval(String input) throws Exception{
    try {
        if(input.matches(".*[a-zA-Z;~`#$_{}\\[\\]:\\\\;\"',\\.\\?]+.*")) {
            throw new Exception("Invalid expression : " + input );
        }
        return engine.eval(input);
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }
 }
}

A select query selecting a select statement

I was over-complicating myself. After taking a long break and coming back, the desired output could be accomplished by this simple query:

SELECT Sandwiches.[Sandwich Type], Sandwich.Bread, Count(Sandwiches.[SandwichID]) AS [Total Sandwiches]
FROM Sandwiches
GROUP BY Sandwiches.[Sandwiches Type], Sandwiches.Bread;

Thanks for answering, it helped my train of thought.

Extension gd is missing from your system - laravel composer Update

The solution is quite simple.

In your php.ini, just uncomment the line extension=php_gd2.dll (or .so extension for unix systems.)

Hope it helps.

In PANDAS, how to get the index of a known value?

Using the .loc[] accessor:

In [25]: a.loc[a['c1'] == 8].index[0]
Out[25]: 4

Can also use the get_loc() by setting 'c1' as the index. This will not change the original dataframe.

In [17]: a.set_index('c1').index.get_loc(8)
Out[17]: 4

What is a race condition?

There is an important technical difference between race conditions and data races. Most answers seem to make the assumption that these terms are equivalent, but they are not.

A data race occurs when 2 instructions access the same memory location, at least one of these accesses is a write and there is no happens before ordering among these accesses. Now what constitutes a happens before ordering is subject to a lot of debate, but in general ulock-lock pairs on the same lock variable and wait-signal pairs on the same condition variable induce a happens-before order.

A race condition is a semantic error. It is a flaw that occurs in the timing or the ordering of events that leads to erroneous program behavior.

Many race conditions can be (and in fact are) caused by data races, but this is not necessary. As a matter of fact, data races and race conditions are neither the necessary, nor the sufficient condition for one another. This blog post also explains the difference very well, with a simple bank transaction example. Here is another simple example that explains the difference.

Now that we nailed down the terminology, let us try to answer the original question.

Given that race conditions are semantic bugs, there is no general way of detecting them. This is because there is no way of having an automated oracle that can distinguish correct vs. incorrect program behavior in the general case. Race detection is an undecidable problem.

On the other hand, data races have a precise definition that does not necessarily relate to correctness, and therefore one can detect them. There are many flavors of data race detectors (static/dynamic data race detection, lockset-based data race detection, happens-before based data race detection, hybrid data race detection). A state of the art dynamic data race detector is ThreadSanitizer which works very well in practice.

Handling data races in general requires some programming discipline to induce happens-before edges between accesses to shared data (either during development, or once they are detected using the above mentioned tools). this can be done through locks, condition variables, semaphores, etc. However, one can also employ different programming paradigms like message passing (instead of shared memory) that avoid data races by construction.

changing iframe source with jquery

Using attr() pointing to an external domain may trigger an error like this in Chrome: "Refused to display document because display forbidden by X-Frame-Options". The workaround to this can be to move the whole iframe HTML code into the script (eg. using .html() in jQuery).

Example:

var divMapLoaded = false;
$("#container").scroll(function() {
    if ((!divMapLoaded) && ($("#map").position().left <= $("#map").width())) {
    $("#map-iframe").html("<iframe id=\"map-iframe\" " +
        "width=\"100%\" height=\"100%\" frameborder=\"0\" scrolling=\"no\" " +
        "marginheight=\"0\" marginwidth=\"0\" " +
        "src=\"http://www.google.it/maps?t=m&amp;cid=0x3e589d98063177ab&amp;ie=UTF8&amp;iwloc=A&amp;brcurrent=5,0,1&amp;ll=41.123115,16.853177&amp;spn=0.005617,0.009943&amp;output=embed\"" +
        "></iframe>");
    divMapLoaded = true;
}

How to replace plain URLs with links?

Keep it simple! Say what you cannot have, rather than what you can have :)

As mentioned above, URLs can be quite complex, especially after the '?', and not all of them start with a 'www.' e.g. maps.bing.com/something?key=!"£$%^*()&lat=65&lon&lon=20

So, rather than have a complex regex that wont meet all edge cases, and will be hard to maintain, how about this much simpler one, which works well for me in practise.

Match

http(s):// (anything but a space)+

www. (anything but a space)+

Where 'anything' is [^'"<>\s] ... basically a greedy match, carrying on to you meet a space, quote, angle bracket, or end of line

Also:

Remember to check that it is not already in URL format, e.g. the text contains href="..." or src="..."

Add ref=nofollow (if appropriate)

This solution isn't as "good" as the libraries mentioned above, but is much simpler, and works well in practise.

if html.match( /(href)|(src)/i )) {
    return html; // text already has a hyper link in it
    }

html = html.replace( 
            /\b(https?:\/\/[^\s\(\)\'\"\<\>]+)/ig, 
            "<a ref='nofollow' href='$1'>$1</a>" 
            );

html = html.replace( 
            /\s(www\.[^\s\(\)\'\"\<\>]+)/ig, 
            "<a ref='nofollow' href='http://$1'>$1</a>" 
            );

html = html.replace( 
             /^(www\.[^\s\(\)\'\"\<\>]+)/ig, 
            "<a ref='nofollow' href='http://$1'>$1</a>" 
            );

return html;

How to have Java method return generic list of any type?

Another option is doing the following:

public class UserList extends List<User>{

}

public <T> T magicalListGetter(Class<T> clazz) {
    List<?> list = doMagicalVooDooHere();
    return (T)list;
}

List<User> users = magicalListGetter(UserList.class);

`

No generated R.java file in my project

According to my experince i can summarize :

1.The problem is mainly refering to syntax issues that can be occured on xml files.

2.You might copy the AndroidManifest.xml accidently to subfolders .

1.One file is an extension undefined .

After checking all of these Go to Project->Clean or just remove the /bin and /gen folders.

Button Center CSS

I realize this is a very old question, but I stumbled across this problem today and I got it to work with

<div style="text-align:center;">
    <button>button1</button>
    <button>button2</button>
</div>

Cheers, Mark

Twitter Bootstrap carousel different height images cause bouncing arrows

More recently I am testing this CSS source for the Bootstrap carousel

The height set to 380 should be set equal to the biggest/tallest image being displayed...

Please Vote up/down this answer based on usability testing with the following CSS thanks.

/* CUSTOMIZE THE CAROUSEL
-------------------------------------------------- */

/* Carousel base class */
.carousel {
  max-height: 100%;
  max-height: 380px;
  margin-bottom: 60px;
  height:auto;
}
/* Since positioning the image, we need to help out the caption */
.carousel-caption {
  z-index: 10;
    background: rgba(0, 0, 0, 0.45);
}

/* Declare heights because of positioning of img element */
.carousel .item {
  max-height: 100%;
  max-height: 380px;
  background-color: #777;
}
.carousel-inner > .item > img {
 /*  position: absolute;*/
  top: 0;
  left: 0;
  min-width: 40%;
  max-width: 100%;
  max-height: 380px;
  width: auto;
  margin-right:auto;
  margin-left:auto;
  height:auto;

}

SSRS 2008 R2 - SSRS 2012 - ReportViewer: Reports are blank in Safari and Chrome

Here is the solution I used for Report Server 2008 R2

It should work regardless of what the Report Server will output for use for in its "id" attribute of the table. I don't think you can always assume it will be "ctl31_fixedTable"

I used a mix of the suggestion above and some ways to dynamically load jquery libraries into a page from javascript file found here

On the server go to the directory: C:\Program Files\Microsoft SQL Server\MSRS10_50.MSSQLSERVER\Reporting Services\ReportManager\js

Copy the jquery library jquery-1.6.2.min.js into the directory

Create a backup copy of the file ReportingServices.js Edit the file. And append this to the bottom of it:

var jQueryScriptOutputted = false;
function initJQuery() {

    //if the jQuery object isn't available
    if (typeof(jQuery) == 'undefined') {


        if (! jQueryScriptOutputted) {
            //only output the script once..
            jQueryScriptOutputted = true;

            //output the script 
            document.write("<scr" + "ipt type=\"text/javascript\" src=\"../js/jquery-1.6.2.min.js\"></scr" + "ipt>");
         }
        setTimeout("initJQuery()", 50);
    } else {

        $(function() {     

        // Bug-fix on Chrome and Safari etc (webkit)
        if ($.browser.webkit) {

            // Start timer to make sure overflow is set to visible
             setInterval(function () {
                var div = $('table[id*=_fixedTable] > tbody > tr:last > td:last > div')

                div.css('overflow', 'visible');
            }, 1000);
        }

        });
    }        
}

initJQuery();

html 5 audio tag width

For those looking for an inline example, here is one:

<audio controls style="width: 200px;">
   <source src="http://somewhere.mp3" type="audio/mpeg">
</audio>

It doesn't seem to respect a "height" setting, at least not awesomely. But you can always "customize" the controls but creating your own controls (instead of using the built-in ones) or using somebody's widget that similarly creates its own :)

How to calculate an age based on a birthday?

Stackoverflow uses such function to determine the age of a user.

Calculate age in C#

The given answer is

DateTime now = DateTime.Today;
int age = now.Year - bday.Year;
if (now < bday.AddYears(age)) age--;

So your helper method would look like

public static string Age(this HtmlHelper helper, DateTime birthday)
{
    DateTime now = DateTime.Today;
    int age = now.Year - birthday.Year;
    if (now < birthday.AddYears(age)) age--;

    return age.ToString();
}

Today, I use a different version of this function to include a date of reference. This allow me to get the age of someone at a future date or in the past. This is used for our reservation system, where the age in the future is needed.

public static int GetAge(DateTime reference, DateTime birthday)
{
    int age = reference.Year - birthday.Year;
    if (reference < birthday.AddYears(age)) age--;

    return age;
}

How can I add a key/value pair to a JavaScript object?

arr.key3 = value3;

because your arr is not really an array... It's a prototype object. The real array would be:

var arr = [{key1: value1}, {key2: value2}];

but it's still not right. It should actually be:

var arr = [{key: key1, value: value1}, {key: key2, value: value2}];

Clearing the terminal screen?

the best way I can think of is using processing there are a few introductions on the net like displaying serial data, arduino graph and arduino radar
Since Arduino is based on processing its not that hard to learn

Save bitmap to location

Some formats, like PNG which is lossless, will ignore the quality setting.

How to use an array list in Java?

A three line solution, but works quite well:

int[] source_array = {0,1,2,3,4,5,6,7,8,9,10,11};
ArrayList<Integer> target_list = new ArrayList<Integer>();
for(int i = 0; i < source_array.length; i++){
    target_list.add(random_array[i]);
}

Create a OpenSSL certificate on Windows

You can certainly use putty (puttygen.exe) to do that.

Or you can get Cygwin to use the utilities you just described.

How do I write stderr to a file while using "tee" with a pipe?

Like the accepted answer well explained by lhunath, you can use

command > >(tee -a stdout.log) 2> >(tee -a stderr.log >&2)

Beware than if you use bash you could have some issue.

Let me take the matthew-wilcoxson exemple.

And for those who "seeing is believing", a quick test:

(echo "Test Out";>&2 echo "Test Err") > >(tee stdout.log) 2> >(tee stderr.log >&2)

Personally, when I try, I have this result :

user@computer:~$ (echo "Test Out";>&2 echo "Test Err") > >(tee stdout.log) 2> >(tee stderr.log >&2)
user@computer:~$ Test Out
Test Err

Both message does not appear at the same level. Why Test Out seem to be put like if it is my previous command ?
Prompt is on a blank line, let me think the process is not finished, and when I press Enter this fix it.
When I check the content of the files, it is ok, redirection works.

Let take another test.

function outerr() {
  echo "out"     # stdout
  echo >&2 "err" # stderr
}

user@computer:~$ outerr
out
err

user@computer:~$ outerr >/dev/null
err

user@computer:~$ outerr 2>/dev/null
out

Trying again the redirection, but with this function.

function test_redirect() {
  fout="stdout.log"
  ferr="stderr.log"
  echo "$ outerr"
  (outerr) > >(tee "$fout") 2> >(tee "$ferr" >&2)
  echo "# $fout content :"
  cat "$fout"
  echo "# $ferr content :"
  cat "$ferr"
}

Personally, I have this result :

user@computer:~$ test_redirect
$ outerr
# stdout.log content :
out
out
err
# stderr.log content :
err
user@computer:~$

No prompt on a blank line, but I don't see normal output, stdout.log content seem to be wrong, only stderr.log seem to be ok. If I relaunch it, output can be different...

So, why ?

Because, like explained here :

Beware that in bash, this command returns as soon as [first command] finishes, even if the tee commands are still executed (ksh and zsh do wait for the subprocesses)

So, if you use bash, prefer use the better exemple given in this other answer :

{ { outerr | tee "$fout"; } 2>&1 1>&3 | tee "$ferr"; } 3>&1 1>&2

It will fix the previous issues.

Now, the question is, how to retrieve exit status code ?
$? does not works.
I have no found better solution than switch on pipefail with set -o pipefail (set +o pipefail to switch off) and use ${PIPESTATUS[0]} like this

function outerr() {
  echo "out"
  echo >&2 "err"
  return 11
}

function test_outerr() {
  local - # To preserve set option
  ! [[ -o pipefail ]] && set -o pipefail; # Or use second part directly
  local fout="stdout.log"
  local ferr="stderr.log"
  echo "$ outerr"
  { { outerr | tee "$fout"; } 2>&1 1>&3 | tee "$ferr"; } 3>&1 1>&2
  # First save the status or it will be lost
  local status="${PIPESTATUS[0]}" # Save first, the second is 0, perhaps tee status code.
  echo "==="
  echo "# $fout content :"
  echo "<==="
  cat "$fout"
  echo "===>"
  echo "# $ferr content :"
  echo "<==="
  cat "$ferr"
  echo "===>"
  if (( status > 0 )); then
    echo "Fail $status > 0"
    return "$status" # or whatever
  fi
}
user@computer:~$ test_outerr
$ outerr
err
out
===
# stdout.log content :
<===
out
===>
# stderr.log content :
<===
err
===>
Fail 11 > 0

Object of class stdClass could not be converted to string

What I was looking for is a way to fetch the data

so I used this $data = $this->db->get('table_name')->result_array();

and then fetched my data just as you operate on array objects.

$data[0]['field_name']

No need to worry about type casting or anything just straight to the point.

So it worked for me.

Window.open as modal popup?

I agree with both previous answers. Basically, you want to use what is known as a "lightbox" - http://en.wikipedia.org/wiki/Lightbox_(JavaScript)

It is essentially a div than is created within the DOM of your current window/tab. In addition to the div that contains your dialog, a transparent overlay blocks the user from engaging all underlying elements. This can effectively create a modal dialog (i.e. user MUST make some kind of decision before moving on).

Making an array of integers in iOS

C array:

NSInteger array[6] = {1, 2, 3, 4, 5, 6};

Objective-C Array:

NSArray *array = @[@1, @2, @3, @4, @5, @6];
// numeric values must in that case be wrapped into NSNumbers

Swift Array:

var array = [1, 2, 3, 4, 5, 6]

This is correct too:

var array = Array(1...10)

NB: arrays are strongly typed in Swift; in that case, the compiler infers from the content that the array is an array of integers. You could use this explicit-type syntax, too:

var array: [Int] = [1, 2, 3, 4, 5, 6]

If you wanted an array of Doubles, you would use :

var array = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0] // implicit type-inference

or:

var array: [Double] = [1, 2, 3, 4, 5, 6] // explicit type

Proxy with express.js

You want to use http.request to create a similar request to the remote API and return its response.

Something like this:

const http = require('http');
// or use import http from 'http';


/* your app config here */

app.post('/api/BLABLA', (oreq, ores) => {
  const options = {
    // host to forward to
    host: 'www.google.com',
    // port to forward to
    port: 80,
    // path to forward to
    path: '/api/BLABLA',
    // request method
    method: 'POST',
    // headers to send
    headers: oreq.headers,
  };

  const creq = http
    .request(options, pres => {
      // set encoding
      pres.setEncoding('utf8');

      // set http status code based on proxied response
      ores.writeHead(pres.statusCode);

      // wait for data
      pres.on('data', chunk => {
        ores.write(chunk);
      });

      pres.on('close', () => {
        // closed, let's end client request as well
        ores.end();
      });

      pres.on('end', () => {
        // finished, let's finish client request as well
        ores.end();
      });
    })
    .on('error', e => {
      // we got an error
      console.log(e.message);
      try {
        // attempt to set error message and http status
        ores.writeHead(500);
        ores.write(e.message);
      } catch (e) {
        // ignore
      }
      ores.end();
    });

  creq.end();
});

Notice: I haven't really tried the above, so it might contain parse errors hopefully this will give you a hint as to how to get it to work.

Looking for a good Python Tree data structure

Roll your own. For example, just model your tree as list of list. You should detail your specific need before people can provide better recommendation.

In response to HelloGoodbye's question, this is a sample code to iterate a tree.

def walk(node):
    """ iterate tree in pre-order depth-first search order """
    yield node
    for child in node.children:
        for n in walk(child):
            yield n

One catch is this recursive implementation is O(n log n). It works fine for all trees I have to deal with. Maybe the subgenerator in Python 3 would help.

mysqld: Can't change dir to data. Server doesn't start

In my case, I had installed the data directory to a different location. So the data directory really wasn't in the default location. Therefore, when I ran the mysqld command from the command prompt, I had to specify the data directory manually:

mysqld --datadir=D:/MySQLData/Data

Here's the documentation for mysqld command-line arguments.

Are PHP Variables passed by value or by reference?

It seems a lot of people get confused by the way objects are passed to functions and what passing by reference means. Object are still passed by value, it's just the value that is passed in PHP5 is a reference handle. As proof:

<?php
class Holder {
    private $value;

    public function __construct($value) {
        $this->value = $value;
    }

    public function getValue() {
        return $this->value;
    }
}

function swap($x, $y) {
    $tmp = $x;
    $x = $y;
    $y = $tmp;
}

$a = new Holder('a');
$b = new Holder('b');
swap($a, $b);

echo $a->getValue() . ", " . $b->getValue() . "\n";

Outputs:

a, b

To pass by reference means we can modify the variables that are seen by the caller, which clearly the code above does not do. We need to change the swap function to:

<?php
function swap(&$x, &$y) {
    $tmp = $x;
    $x = $y;
    $y = $tmp;
}

$a = new Holder('a');
$b = new Holder('b');
swap($a, $b);

echo $a->getValue() . ", " . $b->getValue() . "\n";

Outputs:

b, a

in order to pass by reference.

PHP - find entry by object property from an array of objects

I posted what I use to solve this very issue efficiently here using a quick Binary Search Algorithm: https://stackoverflow.com/a/52786742/1678210

I didn't want to copy the same answer. Someone else had asked it slightly differently but the answer is the same.

How can I declare dynamic String array in Java

What your looking for is the DefaultListModel - Dynamic String List Variable.

Here is a whole class that uses the DefaultListModel as though it were the TStringList of Delphi. The difference is that you can add Strings to the list without limitation and you have the same ability at getting a single entry by specifying the entry int.

FileName: StringList.java

package YOUR_PACKAGE_GOES_HERE;

//This is the StringList Class by i2programmer
//You may delete these comments
//This code is offered freely at no requirements
//You may alter the code as you wish
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;

public class StringList {

    public static String OutputAsString(DefaultListModel list, int entry) {
        return GetEntry(list, entry);
    }

    public static Object OutputAsObject(DefaultListModel list, int entry) {
        return GetEntry(list, entry);
    }

    public static int OutputAsInteger(DefaultListModel list, int entry) {
        return Integer.parseInt(list.getElementAt(entry).toString());
    }

    public static double OutputAsDouble(DefaultListModel list, int entry) {
        return Double.parseDouble(list.getElementAt(entry).toString());
    }

    public static byte OutputAsByte(DefaultListModel list, int entry) {
        return Byte.parseByte(list.getElementAt(entry).toString());
    }

    public static char OutputAsCharacter(DefaultListModel list, int entry) {
        return list.getElementAt(entry).toString().charAt(0);
    }

    public static String GetEntry(DefaultListModel list, int entry) {
        String result = "";
        result = list.getElementAt(entry).toString();
        return result;
    }

    public static void AddEntry(DefaultListModel list, String entry) {
        list.addElement(entry);
    }

    public static void RemoveEntry(DefaultListModel list, int entry) {
        list.removeElementAt(entry);
    }

    public static DefaultListModel StrToList(String input, String delimiter) {
        DefaultListModel dlmtemp = new DefaultListModel();
        input = input.trim();
        delimiter = delimiter.trim();
        while (input.toLowerCase().contains(delimiter.toLowerCase())) {
            int index = input.toLowerCase().indexOf(delimiter.toLowerCase());
            dlmtemp.addElement(input.substring(0, index).trim());
            input = input.substring(index + delimiter.length(), input.length()).trim();
        }
        return dlmtemp;
    }

    public static String ListToStr(DefaultListModel list, String delimiter) {
        String result = "";
        for (int i = 0; i < list.size(); i++) {
            result = list.getElementAt(i).toString() + delimiter;
        }
        result = result.trim();
        return result;
    }

    public static String LoadFile(String inputfile) throws IOException {
        int len;
        char[] chr = new char[4096];
        final StringBuffer buffer = new StringBuffer();
        final FileReader reader = new FileReader(new File(inputfile));
        try {
            while ((len = reader.read(chr)) > 0) {
                buffer.append(chr, 0, len);
            }
        } finally {
            reader.close();
        }
        return buffer.toString();
    }

    public static void SaveFile(String outputfile, String outputstring) {
        try {
            FileWriter f0 = new FileWriter(new File(outputfile));
            f0.write(outputstring);
            f0.flush();
            f0.close();
        } catch (IOException ex) {
            Logger.getLogger(StringList.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

OutputAs methods are for outputting an entry as int, double, etc... so that you don't have to convert from string on the other side.

SaveFile & LoadFile are to save and load strings to and from files.

StrToList & ListToStr are to place delimiters between each entry.

ex. 1<>2<>3<>4<> if "<>" is the delimiter and 1 2 3 & 4 are the entries.

AddEntry & GetEntry are to add and get strings to and from the DefaultListModel.

RemoveEntry is to delete a string from the DefaultListModel.

You use the DefaultListModel instead of an array here like this:

DefaultListModel list = new DefaultListModel();
//now that you have a list, you can run it through the above class methods.

@property retain, assign, copy, nonatomic in Objective-C

The article linked to by MrMage is no longer working. So, here is what I've learned in my (very) short time coding in Objective-C:

nonatomic vs. atomic - "atomic" is the default. Always use "nonatomic". I don't know why, but the book I read said there is "rarely a reason" to use "atomic". (BTW: The book I read is the BNR "iOS Programming" book.)

readwrite vs. readonly - "readwrite" is the default. When you @synthesize, both a getter and a setter will be created for you. If you use "readonly", no setter will be created. Use it for a value you don't want to ever change after the instantiation of the object.

retain vs. copy vs. assign

  • "assign" is the default. In the setter that is created by @synthesize, the value will simply be assigned to the attribute. My understanding is that "assign" should be used for non-pointer attributes.
  • "retain" is needed when the attribute is a pointer to an object. The setter generated by @synthesize will retain (aka add a retain count) the object. You will need to release the object when you are finished with it.
  • "copy" is needed when the object is mutable. Use this if you need the value of the object as it is at this moment, and you don't want that value to reflect any changes made by other owners of the object. You will need to release the object when you are finished with it because you are retaining the copy.

Determining the current foreground application from a background task or service

i had to figure out the right solution the hard way. the below code is part of cyanogenmod7 (the tablet tweaks) and is tested on android 2.3.3 / gingerbread.

methods:

  • getForegroundApp - returns the foreground application.
  • getActivityForApp - returns the activity of the found app.
  • isStillActive - determines if a earlier found app is still the active app.
  • isRunningService - a helper function for getForegroundApp

this hopefully answers this issue in all extend (:

private RunningAppProcessInfo getForegroundApp() {
    RunningAppProcessInfo result=null, info=null;

    if(mActivityManager==null)
        mActivityManager = (ActivityManager)mContext.getSystemService(Context.ACTIVITY_SERVICE);
    List <RunningAppProcessInfo> l = mActivityManager.getRunningAppProcesses();
    Iterator <RunningAppProcessInfo> i = l.iterator();
    while(i.hasNext()){
        info = i.next();
        if(info.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND
                && !isRunningService(info.processName)){
            result=info;
            break;
        }
    }
    return result;
}

private ComponentName getActivityForApp(RunningAppProcessInfo target){
    ComponentName result=null;
    ActivityManager.RunningTaskInfo info;

    if(target==null)
        return null;

    if(mActivityManager==null)
        mActivityManager = (ActivityManager)mContext.getSystemService(Context.ACTIVITY_SERVICE);
    List <ActivityManager.RunningTaskInfo> l = mActivityManager.getRunningTasks(9999);
    Iterator <ActivityManager.RunningTaskInfo> i = l.iterator();

    while(i.hasNext()){
        info=i.next();
        if(info.baseActivity.getPackageName().equals(target.processName)){
            result=info.topActivity;
            break;
        }
    }

    return result;
}

private boolean isStillActive(RunningAppProcessInfo process, ComponentName activity)
{
    // activity can be null in cases, where one app starts another. for example, astro
    // starting rock player when a move file was clicked. we dont have an activity then,
    // but the package exits as soon as back is hit. so we can ignore the activity
    // in this case
    if(process==null)
        return false;

    RunningAppProcessInfo currentFg=getForegroundApp();
    ComponentName currentActivity=getActivityForApp(currentFg);

    if(currentFg!=null && currentFg.processName.equals(process.processName) &&
            (activity==null || currentActivity.compareTo(activity)==0))
        return true;

    Slog.i(TAG, "isStillActive returns false - CallerProcess: " + process.processName + " CurrentProcess: "
            + (currentFg==null ? "null" : currentFg.processName) + " CallerActivity:" + (activity==null ? "null" : activity.toString())
            + " CurrentActivity: " + (currentActivity==null ? "null" : currentActivity.toString()));
    return false;
}

private boolean isRunningService(String processname){
    if(processname==null || processname.isEmpty())
        return false;

    RunningServiceInfo service;

    if(mActivityManager==null)
        mActivityManager = (ActivityManager)mContext.getSystemService(Context.ACTIVITY_SERVICE);
    List <RunningServiceInfo> l = mActivityManager.getRunningServices(9999);
    Iterator <RunningServiceInfo> i = l.iterator();
    while(i.hasNext()){
        service = i.next();
        if(service.process.equals(processname))
            return true;
    }

    return false;
}

Printing a 2D array in C

First you need to input the two numbers say num_rows and num_columns perhaps using argc and argv then do a for loop to print the dots.

int j=0;
int k=0;
for (k=0;k<num_columns;k++){
   for (j=0;j<num_rows;j++){
       printf(".");
   }
 printf("\n");
 }

you'd have to replace the dot with something else later.

How to call a function from another controller in angularjs?

I wouldn't use function from one controller into another. A better approach would be to move the common function to a service and then inject the service in both controllers.

How to dynamically add a class to manual class names?

You can either do this, normal JavaScript:

className={'wrapper searchDiv ' + this.state.something}

or the string template version, with backticks:

className={`wrapper searchDiv ${this.state.something}`}

Both types are of course just JavaScript, but the first pattern is the traditional kind.

Anyway, in JSX, anything enclosed in curly brackets is executed as JavaScript, so you can basically do whatever you want there. But combining JSX strings and curly brackets is a no-go for attributes.

Credit card expiration dates - Inclusive or exclusive?

It took me a couple of minutes to find a site that I could source for this.

The card is valid until the last day of the month indicated, after the last [sic]1 day of the next month; the card cannot be used to make a purchase if the merchant attempts to obtain an authorization. - Source

Also, while looking this up, I found an interesting article on Microsoft's website using an example like this, exec summary: Access 2000 for a month/year defaults to the first day of the month, here's how to override that to calculate the end of the month like you'd want for a credit card.

Additionally, this page has everything you ever wanted to know about credit cards.


  1. This is assumed to be a typo and that it should read "..., after the first day of the next month; ..."

Batch command to move files to a new directory

this will also work, if you like

 xcopy  C:\Test\Log "c:\Test\Backup-%date:~4,2%-%date:~7,2%-%date:~10,4%_%time:~0,2%%time:~3,2%" /s /i
 del C:\Test\Log

Split and join C# string

You can use string.Split and string.Join:

string theString = "Some Very Large String Here";
var array = theString.Split(' ');
string firstElem = array.First();
string restOfArray = string.Join(" ", array.Skip(1));

If you know you always only want to split off the first element, you can use:

var array = theString.Split(' ', 2);

This makes it so you don't have to join:

string restOfArray = array[1];

Google Maps shows "For development purposes only"

Google Maps is no longer free. You have to associate a credit card so that you can get billed if your site has requests that exceed the $200 credit they give you monthly for free. That is why you get the watermarked maps.

For more information, see: https://cloud.google.com/maps-platform/pricing/

Update: A common problem with the new billing system is that you now have to activate each API separately. They all have different pricing (some are even free), so Google makes a point of having you enable them individually for your domain. I was never a heavy user of Google Maps, but I get the feeling that there are many more APIs now than there used to be.

So if you're still getting a restricted usage message after you've enabled billing, find out what API you need exactly for the features you want to offer, and check if it's enabled. The API settings are annoyingly hard to find.

  1. Go to this link: https://console.developers.google.com/apis/dashboard.
  2. Then you select your project in the dropdown.
  3. Go to library on the left pane.
  4. Browse the available APIs and enable the one you need.

Get first letter of a string from column

.str.get

This is the simplest to specify string methods

# Setup
df = pd.DataFrame({'A': ['xyz', 'abc', 'foobar'], 'B': [123, 456, 789]})
df

        A    B
0     xyz  123
1     abc  456
2  foobar  789

df.dtypes

A    object
B     int64
dtype: object

For string (read:object) type columns, use

df['C'] = df['A'].str[0]
# Similar to,
df['C'] = df['A'].str.get(0)

.str handles NaNs by returning NaN as the output.

For non-numeric columns, an .astype conversion is required beforehand, as shown in @Ed Chum's answer.

# Note that this won't work well if the data has NaNs. 
# It'll return lowercase "n"
df['D'] = df['B'].astype(str).str[0]

df
        A    B  C  D
0     xyz  123  x  1
1     abc  456  a  4
2  foobar  789  f  7

List Comprehension and Indexing

There is enough evidence to suggest a simple list comprehension will work well here and probably be faster.

# For string columns
df['C'] = [x[0] for x in df['A']]

# For numeric columns
df['D'] = [str(x)[0] for x in df['B']]

df
        A    B  C  D
0     xyz  123  x  1
1     abc  456  a  4
2  foobar  789  f  7

If your data has NaNs, then you will need to handle this appropriately with an if/else in the list comprehension,

df2 = pd.DataFrame({'A': ['xyz', np.nan, 'foobar'], 'B': [123, 456, np.nan]})
df2

        A      B
0     xyz  123.0
1     NaN  456.0
2  foobar    NaN

# For string columns
df2['C'] = [x[0] if isinstance(x, str) else np.nan for x in df2['A']]

# For numeric columns
df2['D'] = [str(x)[0] if pd.notna(x) else np.nan for x in df2['B']]

        A      B    C    D
0     xyz  123.0    x    1
1     NaN  456.0  NaN    4
2  foobar    NaN    f  NaN

Let's do some timeit tests on some larger data.

df_ = df.copy()
df = pd.concat([df_] * 5000, ignore_index=True) 

%timeit df.assign(C=df['A'].str[0])
%timeit df.assign(D=df['B'].astype(str).str[0])

%timeit df.assign(C=[x[0] for x in df['A']])
%timeit df.assign(D=[str(x)[0] for x in df['B']])

12 ms ± 253 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
27.1 ms ± 1.38 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

3.77 ms ± 110 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
7.84 ms ± 145 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

List comprehensions are 4x faster.

Update some specific field of an entity in android Room

after trying to fix a similar problem my self, where I had changed from @PrimaryKey(autoGenerate = true) to int UUID, I couldn't find how to write my migration so I changed the table name, it's an easy fix, and ok if you working with a personal/small app

Determining whether an object is a member of a collection in VBA

Isn't it good enough?

Public Function Contains(col As Collection, key As Variant) As Boolean
Dim obj As Variant
On Error GoTo err
    Contains = True
    obj = col(key)
    Exit Function
err:

    Contains = False
End Function