How do you set the document title in React?
If you're a beginner you can just save yourself from all that by going to the public folder of your react project folder and edit the title in "index.html" and put yours. Don't forget to save so it will reflect.
How do I check if string contains substring?
You can use this Polyfill in ie and chrome
if (!('contains' in String.prototype)) {
String.prototype.contains = function (str, startIndex) {
"use strict";
return -1 !== String.prototype.indexOf.call(this, str, startIndex);
};
}
Http Post request with content type application/x-www-form-urlencoded not working in Spring
Remove @ResponseBody annotation from your use parameters in method. Like this;
@Autowired
ProjectService projectService;
@RequestMapping(path = "/add", method = RequestMethod.POST)
public ResponseEntity<Project> createNewProject(Project newProject){
Project project = projectService.save(newProject);
return new ResponseEntity<Project>(project,HttpStatus.CREATED);
}
Check if a Windows service exists and delete in PowerShell
For single PC:
if (Get-Service "service_name" -ErrorAction 'SilentlyContinue'){(Get-WmiObject -Class Win32_Service -filter "Name='service_name'").delete()}
else{write-host "No service found."}
Macro for list of PCs:
$name = "service_name"
$list = get-content list.txt
foreach ($server in $list) {
if (Get-Service "service_name" -computername $server -ErrorAction 'SilentlyContinue'){
(Get-WmiObject -Class Win32_Service -filter "Name='service_name'" -ComputerName $server).delete()}
else{write-host "No service $name found on $server."}
}
What is the LD_PRELOAD trick?
As many people mentioned, using LD_PRELOAD
to preload library. BTW, you can CHECK if the setting is available by ldd
command.
Example: suppose you need to preload your own libselinux.so.1
.
> ldd /bin/ls
...
libselinux.so.1 => /lib/x86_64-linux-gnu/libselinux.so.1 (0x00007f3927b1d000)
libacl.so.1 => /lib/x86_64-linux-gnu/libacl.so.1 (0x00007f3927914000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f392754f000)
libpcre.so.3 => /lib/x86_64-linux-gnu/libpcre.so.3 (0x00007f3927311000)
libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007f392710c000)
/lib64/ld-linux-x86-64.so.2 (0x00007f3927d65000)
libattr.so.1 => /lib/x86_64-linux-gnu/libattr.so.1 (0x00007f3926f07000)
Thus, set your preload environment:
export LD_PRELOAD=/home/patric/libselinux.so.1
Check your library again:
>ldd /bin/ls
...
libselinux.so.1 =>
/home/patric/libselinux.so.1 (0x00007fb9245d8000)
...
Deserializing JSON data to C# using JSON.NET
Building off of bbant's answer, this is my complete solution for deserializing JSON from a remote URL.
using Newtonsoft.Json;
using System.Net.Http;
namespace Base
{
public class ApiConsumer<T>
{
public T data;
private string url;
public CalendarApiConsumer(string url)
{
this.url = url;
this.data = getItems();
}
private T getItems()
{
T result = default(T);
HttpClient client = new HttpClient();
// This allows for debugging possible JSON issues
var settings = new JsonSerializerSettings
{
Error = (sender, args) =>
{
if (System.Diagnostics.Debugger.IsAttached)
{
System.Diagnostics.Debugger.Break();
}
}
};
using (HttpResponseMessage response = client.GetAsync(this.url).Result)
{
if (response.IsSuccessStatusCode)
{
result = JsonConvert.DeserializeObject<T>(response.Content.ReadAsStringAsync().Result, settings);
}
}
return result;
}
}
}
Usage would be like:
ApiConsumer<FeedResult> feed = new ApiConsumer<FeedResult>("http://example.info/feeds/feeds.aspx?alt=json-in-script");
Where FeedResult
is the class generated using the Xamasoft JSON Class Generator
Here is a screenshot of the settings I used, allowing for weird property names which the web version could not account for.
How to copy directories in OS X 10.7.3?
Is there something special with that directory or are you really just asking how to copy directories?
Copy recursively via CLI:
cp -R <sourcedir> <destdir>
If you're only seeing the files under the sourcedir
being copied (instead of sourcedir
as well), that's happening because you kept the trailing slash for sourcedir
:
cp -R <sourcedir>/ <destdir>
The above only copies the files and their directories inside of sourcedir
. Typically, you want to include the directory you're copying, so drop the trailing slash:
cp -R <sourcedir> <destdir>
Pandas read_sql with parameters
The read_sql
docs say this params
argument can be a list, tuple or dict (see docs).
To pass the values in the sql query, there are different syntaxes possible: ?
, :1
, :name
, %s
, %(name)s
(see PEP249).
But not all of these possibilities are supported by all database drivers, which syntax is supported depends on the driver you are using (psycopg2
in your case I suppose).
In your second case, when using a dict, you are using 'named arguments', and according to the psycopg2
documentation, they support the %(name)s
style (and so not the :name
I suppose), see http://initd.org/psycopg/docs/usage.html#query-parameters.
So using that style should work:
df = psql.read_sql(('select "Timestamp","Value" from "MyTable" '
'where "Timestamp" BETWEEN %(dstart)s AND %(dfinish)s'),
db,params={"dstart":datetime(2014,6,24,16,0),"dfinish":datetime(2014,6,24,17,0)},
index_col=['Timestamp'])
Finding duplicate values in MySQL
As a variation on Levik's answer that allows you to find also the ids of the duplicate results, I used the following:
SELECT * FROM table1 WHERE column1 IN (SELECT column1 AS duplicate_value FROM table1 GROUP BY column1 HAVING COUNT(*) > 1)
How do I force a favicon refresh?
This is a workaround for the chrome bug: change the rel attribute to stylesheet! Keep the original link though. Works like a charm:
I came up with this workaround because we also have a requirement to be able to update customer's sites / production code and I didn't find any of the other solutions to work.
Redirect all to index.php using htaccess
I just had to face the same kind of issue with my Laravel 7 project, in Debian 10 shared hosting. I have to add RewriteBase /
to my .htaccess within /public/ directory. So the .htaccess looks a like
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ /index.php [L,QSA]
Using jquery to get element's position relative to viewport
The easiest way to determine the size and position of an element is to call its
getBoundingClientRect() method. This method returns element positions in viewport coordinates. It expects no arguments and returns an object with
properties left, right, top, and bottom. The left and top properties give the X and Y
coordinates of the upper-left corner of the element and the right and bottom properties
give the coordinates of the lower-right corner.
element.getBoundingClientRect(); // Get position in viewport coordinates
Supported everywhere.
Exec : display stdout "live"
I'd just like to add that one small issue with outputting the buffer strings from a spawned process with console.log()
is that it adds newlines, which can spread your spawned process output over additional lines. If you output stdout
or stderr
with process.stdout.write()
instead of console.log()
, then you'll get the console output from the spawned process 'as is'.
I saw that solution here:
Node.js: printing to console without a trailing newline?
Hope that helps someone using the solution above (which is a great one for live output, even if it is from the documentation).
Get table name by constraint name
SELECT constraint_name, constraint_type, column_name
from user_constraints natural join user_cons_columns
where table_name = "my_table_name";
will give you what you need
equals vs Arrays.equals in Java
The equals()
of arrays is inherited from Object
, so it does not look at the contents of the arrrays, it only considers each array equal to itself.
The Arrays.equals()
methods do compare the arrays' contents. There's overloads for all primitive types, and the one for objects uses the objects' own equals()
methods.
How do I extract part of a string in t-sql
substring(field, 1,3) will work on your examples.
select substring(field, 1,3) from table
Also, if the alphabetic part is of variable length, you can do this to extract the alphabetic part:
select substring(field, 1, PATINDEX('%[1234567890]%', field) -1)
from table
where PATINDEX('%[1234567890]%', field) > 0
How to convert a list into data table
private DataTable CreateDataTable(IList<T> item)
{
Type type = typeof(T);
var properties = type.GetProperties();
DataTable dataTable = new DataTable();
foreach (PropertyInfo info in properties)
{
dataTable.Columns.Add(new DataColumn(info.Name, Nullable.GetUnderlyingType(info.PropertyType) ?? info.PropertyType));
}
foreach (T entity in item)
{
object[] values = new object[properties.Length];
for (int i = 0; i < properties.Length; i++)
{
values[i] = properties[i].GetValue(entity);
}
dataTable.Rows.Add(values);
}
return dataTable;
}
Converting newline formatting from Mac to Windows
You probably want unix2dos:
$ man unix2dos
NAME
dos2unix - DOS/MAC to UNIX and vice versa text file format converter
SYNOPSIS
dos2unix [options] [-c CONVMODE] [-o FILE ...] [-n INFILE OUTFILE ...]
unix2dos [options] [-c CONVMODE] [-o FILE ...] [-n INFILE OUTFILE ...]
DESCRIPTION
The Dos2unix package includes utilities "dos2unix" and "unix2dos" to convert plain text files in DOS or MAC format to UNIX format and vice versa. Binary files and non-
regular files, such as soft links, are automatically skipped, unless conversion is forced.
Dos2unix has a few conversion modes similar to dos2unix under SunOS/Solaris.
In DOS/Windows text files line endings exist out of a combination of two characters: a Carriage Return (CR) followed by a Line Feed (LF). In Unix text files line
endings exists out of a single Newline character which is equal to a DOS Line Feed (LF) character. In Mac text files, prior to Mac OS X, line endings exist out of a
single Carriage Return character. Mac OS X is Unix based and has the same line endings as Unix.
You can either run unix2dos
on your DOS/Windows machine using cygwin or on your Mac using MacPorts.
Cloning an array in Javascript/Typescript
The following line in your code creates a new array, copies all object references from genericItems
into that new array, and assigns it to backupData
:
this.backupData = this.genericItems.slice();
So while backupData
and genericItems
are different arrays, they contain the same exact object references.
You could bring in a library to do deep copying for you (as @LatinWarrior mentioned).
But if Item
is not too complex, maybe you can add a clone
method to it to deep clone the object yourself:
class Item {
somePrimitiveType: string;
someRefType: any = { someProperty: 0 };
clone(): Item {
let clone = new Item();
// Assignment will copy primitive types
clone.somePrimitiveType = this.somePrimitiveType;
// Explicitly deep copy the reference types
clone.someRefType = {
someProperty: this.someRefType.someProperty
};
return clone;
}
}
Then call clone()
on each item:
this.backupData = this.genericItems.map(item => item.clone());
Why SQL Server throws Arithmetic overflow error converting int to data type numeric?
Precision and scale are often misunderstood. In numeric(3,2) you want 3 digits overall, but 2 to the right of the decimal. If you want 15 => 15.00 so the leading 1 causes the overflow (since if you want 2 digits to the right of the decimal, there is only room on the left for one more digit). With 4,2 there is no problem because all 4 digits fit.
Why do we need middleware for async flow in Redux?
To answer the question that is asked in the beginning:
Why can't the container component call the async API, and then dispatch the actions?
Keep in mind that those docs are for Redux, not Redux plus React. Redux stores hooked up to React components can do exactly what you say, but a Plain Jane Redux store with no middleware doesn't accept arguments to dispatch
except plain ol' objects.
Without middleware you could of course still do
const store = createStore(reducer);
MyAPI.doThing().then(resp => store.dispatch(...));
But it's a similar case where the asynchrony is wrapped around Redux rather than handled by Redux. So, middleware allows for asynchrony by modifying what can be passed directly to dispatch
.
That said, the spirit of your suggestion is, I think, valid. There are certainly other ways you could handle asynchrony in a Redux + React application.
One benefit of using middleware is that you can continue to use action creators as normal without worrying about exactly how they're hooked up. For example, using redux-thunk
, the code you wrote would look a lot like
function updateThing() {
return dispatch => {
dispatch({
type: ActionTypes.STARTED_UPDATING
});
AsyncApi.getFieldValue()
.then(result => dispatch({
type: ActionTypes.UPDATED,
payload: result
}));
}
}
const ConnectedApp = connect(
(state) => { ...state },
{ update: updateThing }
)(App);
which doesn't look all that different from the original — it's just shuffled a bit — and connect
doesn't know that updateThing
is (or needs to be) asynchronous.
If you also wanted to support promises, observables, sagas, or crazy custom and highly declarative action creators, then Redux can do it just by changing what you pass to dispatch
(aka, what you return from action creators). No mucking with the React components (or connect
calls) necessary.
Angular2 - Radio Button Binding
This Issue is solved in version Angular 2.0.0-rc.4, respectively in forms.
Include "@angular/forms": "0.2.0"
in package.json.
Then extend your bootstrap in main. Relevant part:
...
import { AppComponent } from './app/app.component';
import { disableDeprecatedForms, provideForms } from '@angular/forms';
bootstrap(AppComponent, [
disableDeprecatedForms(),
provideForms(),
appRouterProviders
]);
I have this in .html and works perfectly:
value: {{buildTool}}
<form action="">
<input type="radio" [(ngModel)]="buildTool" name="buildTool" value="gradle">Gradle <br>
<input type="radio" [(ngModel)]="buildTool" name="buildTool" value="maven">Maven
</form>
How do I clear inner HTML
Take a look at this. a clean and simple solution using jQuery.
http://jsfiddle.net/ma2Yd/
<h1 onmouseover="go('The dog is in its shed')" onmouseout="clear()">lalala</h1>
<div id="goy"></div>
<script type="text/javascript">
$(function() {
$("h1").on('mouseover', function() {
$("#goy").text('The dog is in its shed');
}).on('mouseout', function() {
$("#goy").text("");
});
});
What is the difference between Forking and Cloning on GitHub?
Another weird subtle difference on GitHub is that changes to forks are not counted in your activity log until your changes are pulled into the original repo. What's more, to change a fork into a proper clone, you have to contact Github support, apparently.
From Why are my contributions not showing up:
Commit was made in a fork
Commits made in a fork will not count toward your contributions. To make them count, you must do one of the following:
Open a pull request to have your changes merged into the parent repository.
To detach the fork and turn it into a standalone repository on GitHub, contact GitHub Support. If the fork has forks of its own, let support know if the forks should move with your repository into a new network or remain in the current network. For more information, see "About forks."
Possible to restore a backup of SQL Server 2014 on SQL Server 2012?
You CANNOT do this - you cannot attach/detach or backup/restore a database from a newer version of SQL Server down to an older version - the internal file structures are just too different to support backwards compatibility. This is still true in SQL Server 2014 - you cannot restore a 2014 backup on anything other than another 2014 box (or something newer).
You can either get around this problem by
using the same version of SQL Server on all your machines - then you can easily backup/restore databases between instances
otherwise you can create the database scripts for both structure (tables, view, stored procedures etc.) and for contents (the actual data contained in the tables) either in SQL Server Management Studio (Tasks > Generate Scripts
) or using a third-party tool
or you can use a third-party tool like Red-Gate's SQL Compare and SQL Data Compare to do "diffing" between your source and target, generate update scripts from those differences, and then execute those scripts on the target platform; this works across different SQL Server versions.
The compatibility mode setting just controls what T-SQL features are available to you - which can help to prevent accidentally using new features not available in other servers. But it does NOT change the internal file format for the .mdf
files - this is NOT a solution for that particular problem - there is no solution for restoring a backup from a newer version of SQL Server on an older instance.
JPA entity without id
I guess your entity_property
has a composite key (entity_id, name)
where entity_id
is a foreign key to entity
. If so, you can map it as follows:
@Embeddable
public class EntityPropertyPK {
@Column(name = "name")
private String name;
@ManyToOne
@JoinColumn(name = "entity_id")
private Entity entity;
...
}
@Entity
@Table(name="entity_property")
public class EntityProperty {
@EmbeddedId
private EntityPropertyPK id;
@Column(name = "value")
private String value;
...
}
AngularJS not detecting Access-Control-Allow-Origin header?
CROS needs to be resolved from server side.
Create Filters as per requirement to allow access and add filters in web.xml
Example using spring:
Filter Class:
@Component
public class SimpleFilter implements Filter {
@Override
public void init(FilterConfig arg0) throws ServletException {}
@Override
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
HttpServletResponse response=(HttpServletResponse) resp;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
chain.doFilter(req, resp);
}
@Override
public void destroy() {}
}
Web.xml:
<filter>
<filter-name>simpleCORSFilter</filter-name>
<filter-class>
com.abc.web.controller.general.SimpleFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>simpleCORSFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Find the min/max element of an array in JavaScript
The following code works for me :
var valueList = [10,4,17,9,3];
var maxValue = valueList.reduce(function(a, b) { return Math.max(a, b); });
var minValue = valueList.reduce(function(a, b) { return Math.min(a, b); });
Multiple WHERE clause in Linq
@Theo
The LINQ translator is smart enough to execute:
.Where(r => r.UserName !="XXXX" && r.UsernName !="YYYY")
I've test this in LinqPad
==> YES, Linq translator is smart enough :))
How can I split a shell command over multiple lines when using an IF statement?
The line-continuation will fail if you have whitespace (spaces or tab characters[1]) after the backslash and before the newline. With no such whitespace, your example works fine for me:
$ cat test.sh
if ! fab --fabfile=.deploy/fabfile.py \
--forward-agent \
--disable-known-hosts deploy:$target; then
echo failed
else
echo succeeded
fi
$ alias fab=true; . ./test.sh
succeeded
$ alias fab=false; . ./test.sh
failed
Some detail promoted from the comments: the line-continuation backslash in the shell is not really a special case; it is simply an instance of the general rule that a backslash "quotes" the immediately-following character, preventing any special treatment it would normally be subject to. In this case, the next character is a newline, and the special treatment being prevented is terminating the command. Normally, a quoted character winds up included literally in the command; a backslashed newline is instead deleted entirely. But otherwise, the mechanism is the same. Most importantly, the backslash only quotes the immediately-following character; if that character is a space or tab, you just get a literal space or tab, and any subsequent newline remains unquoted.
[1] or carriage returns, for that matter, as Czechnology points out. Bash does not get along with Windows-formatted text files, not even in WSL. Or Cygwin, but at least their Bash port has added a set -o igncr
option that you can set to make it carriage-return-tolerant.
How can I trigger a Bootstrap modal programmatically?
In order to manually show the modal pop up you have to do this
$('#myModal').modal('show');
You previously need to initialize it with show: false
so it won't show until you manually do it.
$('#myModal').modal({ show: false})
Where myModal
is the id of the modal container.
Build the full path filename in Python
If you are fortunate enough to be running Python 3.4+, you can use pathlib
:
>>> from pathlib import Path
>>> dirname = '/home/reports'
>>> filename = 'daily'
>>> suffix = '.pdf'
>>> Path(dirname, filename).with_suffix(suffix)
PosixPath('/home/reports/daily.pdf')
How to change default text color using custom theme?
You can't use @android:style/TextAppearance
as the parent for the whole app's theme; that's why koopaking3's solution seems quite broken.
To change default text colour everywhere in your app using a custom theme, try something like this.
Works at least on Android 4.0+ (API level 14+).
res/values/themes.xml
:
<resources>
<style name="MyAppTheme" parent="android:Theme.Holo.Light">
<!-- Change default text colour from dark grey to black -->
<item name="android:textColor">@android:color/black</item>
</style>
</resources>
Manifest:
<application
...
android:theme="@style/MyAppTheme">
Update
A shortcoming with the above is that also disabled Action Bar overflow menu items use the default colour, instead of being greyed out. (Of course, if you don't use disabled menu items anywhere in your app, this may not matter.)
As I learned by asking this question, a better way is to define the colour using a drawable:
<item name="android:textColor">@drawable/default_text_color</item>
...with res/drawable/default_text_color.xml
specifying separate state_enabled="false"
colour:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="false" android:color="@android:color/darker_gray"/>
<item android:color="@android:color/black"/>
</selector>
Display date/time in user's locale format and time offset
I mix the answers so far and add to it, because I had to read all of them and investigate additionally for a while to display a date time string from db in a user's local timezone format.
The datetime string comes from a python/django db in the format: 2016-12-05T15:12:24.215Z
Reliable detection of the browser language in JavaScript doesn't seem to work in all browsers (see JavaScript for detecting browser language preference), so I get the browser language from the server.
Python/Django: send request browser language as context parameter:
language = request.META.get('HTTP_ACCEPT_LANGUAGE')
return render(request, 'cssexy/index.html', { "language": language })
HTML: write it in a hidden input:
<input type="hidden" id="browserlanguage" value={{ language }}/>
JavaScript: get value of hidden input e.g. en-GB,en-US;q=0.8,en;q=0.6/ and then take the first language in the list only via replace and regular expression
const browserlanguage = document.getElementById("browserlanguage").value;
var defaultlang = browserlanguage.replace(/(\w{2}\-\w{2}),.*/, "$1");
JavaScript: convert to datetime and format it:
var options = { hour: "2-digit", minute: "2-digit" };
var dt = (new Date(str)).toLocaleDateString(defaultlang, options);
See: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
The result is (browser language is en-gb): 05/12/2016, 14:58
Java array assignment (multiple values)
Yes:
float[] values = {0.1f, 0.2f, 0.3f};
This syntax is only permissible in an initializer. You cannot use it in an assignment, where the following is the best you can do:
values = new float[3];
or
values = new float[] {0.1f, 0.2f, 0.3f};
Trying to find a reference in the language spec for this, but it's as unreadable as ever. Anyone else find one?
What is the best/simplest way to read in an XML file in Java application?
The simplest by far will be Simple http://simple.sourceforge.net, you only need to annotate a single object like so
@Root
public class Entry {
@Attribute
private String a
@Attribute
private int b;
@Element
private Date c;
public String getSomething() {
return a;
}
}
@Root
public class Configuration {
@ElementList(inline=true)
private List<Entry> entries;
public List<Entry> getEntries() {
return entries;
}
}
Then all you have to do to read the whole file is specify the location and it will parse and populate the annotated POJO's. This will do all the type conversions and validation. You can also annotate for persister callbacks if required. Reading it can be done like so.
Serializer serializer = new Persister();
Configuration configuraiton = serializer.read(Configuration.class, fileLocation);
Allow scroll but hide scrollbar
Try this:
HTML:
<div id="container">
<div id="content">
// Content here
</div>
</div>
CSS:
#container{
height: 100%;
width: 100%;
overflow: hidden;
}
#content{
width: 100%;
height: 99%;
overflow: auto;
padding-right: 15px;
}
html, body{
height: 99%;
overflow:hidden;
}
JSFiddle Demo
Tested on FF and Safari.
Using LINQ to group by multiple properties and sum
Linus is spot on in the approach, but a few properties are off. It looks like 'AgencyContractId' is your Primary Key, which is unrelated to the output you want to give the user. I think this is what you want (assuming you change your ViewModel to match the data you say you want in your view).
var agencyContracts = _agencyContractsRepository.AgencyContracts
.GroupBy(ac => new
{
ac.AgencyID,
ac.VendorID,
ac.RegionID
})
.Select(ac => new AgencyContractViewModel
{
AgencyId = ac.Key.AgencyID,
VendorId = ac.Key.VendorID,
RegionId = ac.Key.RegionID,
Total = ac.Sum(acs => acs.Amount) + ac.Sum(acs => acs.Fee)
});
How can I show a hidden div when a select option is selected?
Try handling the change event of the select
and using this.value
to determine whether it's 'Yes' or not.
jsFiddle
JS
document.getElementById('test').addEventListener('change', function () {
var style = this.value == 1 ? 'block' : 'none';
document.getElementById('hidden_div').style.display = style;
});
HTML
<select id="test" name="form_select">
<option value="0">No</option>
<option value ="1">Yes</option>
</select>
<div id="hidden_div" style="display: none;">Hello hidden content</div>
Android read text raw resource file
Here is a simple method to read the text file from the raw folder:
public static String readTextFile(Context context,@RawRes int id){
InputStream inputStream = context.getResources().openRawResource(id);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte buffer[] = new byte[1024];
int size;
try {
while ((size = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, size);
}
outputStream.close();
inputStream.close();
} catch (IOException e) {
}
return outputStream.toString();
}
Passing arguments to angularjs filters
You can simply use | filter:yourFunction:arg
<div ng-repeat="group in groups | filter:weDontLike:group">...</div>
And in js
$scope.weDontLike = function(group) {
//here your condition/criteria
return !!group
}
Remove blank values from array using C#
I write below code to remove the blank value in the array string.
string[] test={"1","","2","","3"};
test= test.Except(new List<string> { string.Empty }).ToArray();
How do you convert Html to plain text?
HTTPUtility.HTMLEncode()
is meant to handle encoding HTML tags as strings. It takes care of all the heavy lifting for you. From the MSDN Documentation:
If characters such as blanks and punctuation are passed in an HTTP stream, they might be misinterpreted at the receiving end. HTML encoding converts characters that are not allowed in HTML into character-entity equivalents; HTML decoding reverses the encoding. For example, when embedded in a block of text, the characters <
and >
, are encoded as <
and >
for HTTP transmission.
HTTPUtility.HTMLEncode()
method, detailed here:
public static void HtmlEncode(
string s,
TextWriter output
)
Usage:
String TestString = "This is a <Test String>.";
StringWriter writer = new StringWriter();
Server.HtmlEncode(TestString, writer);
String EncodedString = writer.ToString();
Creating/writing into a new file in Qt
That is weird, everything looks fine, are you sure it does not work for you? Because this main
surely works for me, so I would look somewhere else for the source of your problem.
#include <QFile>
#include <QTextStream>
int main()
{
QString filename = "Data.txt";
QFile file(filename);
if (file.open(QIODevice::ReadWrite)) {
QTextStream stream(&file);
stream << "something" << endl;
}
}
The code you provided is also almost the same as the one provided in detailed description of QTextStream so I am pretty sure, that the problem is elsewhere :)
Also note, that the file is not called Data
but Data.txt
and should be created/located in the directory from which the program was run (not necessarily the one where the executable is located).
Best way to handle multiple constructors in Java
You need to specify what are the class invariants, i.e. properties which will always be true for an instance of the class (for example, the title of a book will never be null, or the size of a dog will always be > 0).
These invariants should be established during construction, and be preserved along the lifetime of the object, which means that methods shall not break the invariants. The constructors can set these invariants either by having compulsory arguments, or by setting default values:
class Book {
private String title; // not nullable
private String isbn; // nullable
// Here we provide a default value, but we could also skip the
// parameterless constructor entirely, to force users of the class to
// provide a title
public Book()
{
this("Untitled");
}
public Book(String title) throws IllegalArgumentException
{
if (title == null)
throw new IllegalArgumentException("Book title can't be null");
this.title = title;
// leave isbn without value
}
// Constructor with title and isbn
}
However, the choice of these invariants highly depends on the class you're writing, how you'll use it, etc., so there's no definitive answer to your question.
What is the difference between Scala's case class and class?
According to Scala's documentation:
Case classes are just regular classes that are:
- Immutable by default
- Decomposable through pattern matching
- Compared by structural equality instead of by reference
- Succinct to instantiate and operate on
Another feature of the case keyword is the compiler automatically generates several methods for us, including the familiar toString, equals, and hashCode methods in Java.
Remove tracking branches no longer on remote
I found the answer here:
How can I delete all git branches which have been merged?
git branch --merged | grep -v "\*" | xargs -n 1 git branch -d
Make sure we keep master
You can ensure that master
, or any other branch for that matter, doesn't get removed by adding another grep
after the first one. In that case you would go:
git branch --merged | grep -v "\*" | grep -v "YOUR_BRANCH_TO_KEEP" | xargs -n 1 git branch -d
So if we wanted to keep master
, develop
and staging
for instance, we would go:
git branch --merged | grep -v "\*" | grep -v "master" | grep -v "develop" | grep -v "staging" | xargs -n 1 git branch -d
Make this an alias
Since it's a bit long, you might want to add an alias to your .zshrc
or .bashrc
. Mine is called gbpurge
(for git branches purge
):
alias gbpurge='git branch --merged | grep -v "\*" | grep -v "master" | grep -v "develop" | grep -v "staging" | xargs -n 1 git branch -d'
Then reload your .bashrc
or .zshrc
:
. ~/.bashrc
or
. ~/.zshrc
YYYY-MM-DD format date in shell script
With recent Bash (version = 4.2), you can use the builtin printf
with the format modifier %(strftime_format)T
:
$ printf '%(%Y-%m-%d)T\n' -1 # Get YYYY-MM-DD (-1 stands for "current time")
2017-11-10
$ printf '%(%F)T\n' -1 # Synonym of the above
2017-11-10
$ printf -v date '%(%F)T' -1 # Capture as var $date
printf
is much faster than date
since it's a Bash builtin while date
is an external command.
As well, printf -v date ...
is faster than date=$(printf ...)
since it doesn't require forking a subshell.
R plot: size and resolution
If you'd like to use base graphics, you may have a look at this. An extract:
You can correct this with the res= argument to png, which specifies the number of pixels per inch. The smaller this number, the larger the plot area in inches, and the smaller the text relative to the graph itself.
Running a single test from unittest.TestCase via the command line
If you check out the help of the unittest module it tells you about several combinations that allow you to run test case classes from a module and test methods from a test case class.
python3 -m unittest -h
[...]
Examples:
python3 -m unittest test_module - run tests from test_module
python3 -m unittest module.TestClass - run tests from module.TestClass
python3 -m unittest module.Class.test_method - run specified test method
```lang-none
It does not require you to define a `unittest.main()` as the default behaviour of your module.
align right in a table cell with CSS
What worked for me now is:
CSS:
.right {
text-align: right;
margin-right: 1em;
}
.left {
text-align: left;
margin-left: 1em;
}
HTML:
<table width="100%">
<tbody>
<tr>
<td class="left">
<input id="abort" type="submit" name="abort" value="Back">
<input id="save" type="submit" name="save" value="Save">
</td>
<td class="right">
<input id="delegate" type="submit" name="delegate" value="Delegate">
<input id="unassign" type="submit" name="unassign" value="Unassign">
<input id="complete" type="submit" name="complete" value="Complete">
</td>
</tr>
</tbody>
</table>
See the following fiddle:
http://jsfiddle.net/Joysn/3u3SD/
How can I align text directly beneath an image?
In order to be able to justify the text, you need to know the width of the image. You can just use the normal width of the image, or use a different width, but IE 6 might get cranky at you and not scale.
Here's what you need:
<style type="text/css">
#container { width: 100px; //whatever width you want }
#image {width: 100%; //fill up whole div }
#text { text-align: justify; }
</style>
<div id="container">
<img src="" id="image" />
<p id="text">oooh look! text!</p>
</div>
adding child nodes in treeview
May i add to Stormenet example some KISS (Keep It Simple & Stupid):
If you already have a treeView or just created an instance of it:
Let's populate with some data - Ex. One parent two child's :
treeView1.Nodes.Add("ParentKey","Parent Text");
treeView1.Nodes["ParentKey"].Nodes.Add("Child-1 Text");
treeView1.Nodes["ParentKey"].Nodes.Add("Child-2 Text");
Another Ex. two parent's first have two child's second one child:
treeView1.Nodes.Add("ParentKey1","Parent-1 Text");
treeView1.Nodes.Add("ParentKey2","Parent-2 Text");
treeView1.Nodes["ParentKey1"].Nodes.Add("Child-1 Text");
treeView1.Nodes["ParentKey1"].Nodes.Add("Child-2 Text");
treeView1.Nodes["ParentKey2"].Nodes.Add("Child-3 Text");
Take if farther - sub child of child 2:
treeView1.Nodes.Add("ParentKey1","Parent-1 Text");
treeView1.Nodes["ParentKey1"].Nodes.Add("Child-1 Text");
treeView1.Nodes["ParentKey1"].Nodes.Add("ChildKey2","Child-2 Text");
treeView1.Nodes["ParentKey1"].Nodes["ChildKey2"].Nodes.Add("Child-3 Text");
As you see you can have as many child's and parent's as you want and those can have sub child's of child's and so on....
Hope i help!
Sorting std::map using value
Another solution would be the usage of std::make_move_iterator to build a new vector (C++11 )
int main(){
std::map<std::string, int> map;
//Populate map
std::vector<std::pair<std::string, int>> v {std::make_move_iterator(begin(map)),
std::make_move_iterator(end(map))};
// Create a vector with the map parameters
sort(begin(v), end(v),
[](auto p1, auto p2){return p1.second > p2.second;});
// Using sort + lambda function to return an ordered vector
// in respect to the int value that is now the 2nd parameter
// of our newly created vector v
}
Code line wrapping - how to handle long lines
In general, I break lines before operators, and indent the subsequent lines:
Map<long parameterization> longMap
= new HashMap<ditto>();
String longString = "some long text"
+ " some more long text";
To me, the leading operator clearly conveys that "this line was continued from something else, it doesn't stand on its own." Other people, of course, have different preferences.
How can I display a modal dialog in Redux that performs asynchronous actions?
Update: React 16.0 introduced portals through ReactDOM.createPortal
link
Update: next versions of React (Fiber: probably 16 or 17) will include a method to create portals: ReactDOM.unstable_createPortal()
link
Use portals
Dan Abramov answer first part is fine, but involves a lot of boilerplate. As he said, you can also use portals. I'll expand a bit on that idea.
The advantage of a portal is that the popup and the button remain very close into the React tree, with very simple parent/child communication using props: you can easily handle async actions with portals, or let the parent customize the portal.
What is a portal?
A portal permits you to render directly inside document.body
an element that is deeply nested in your React tree.
The idea is that for example you render into body the following React tree:
<div className="layout">
<div className="outside-portal">
<Portal>
<div className="inside-portal">
PortalContent
</div>
</Portal>
</div>
</div>
And you get as output:
<body>
<div class="layout">
<div class="outside-portal">
</div>
</div>
<div class="inside-portal">
PortalContent
</div>
</body>
The inside-portal
node has been translated inside <body>
, instead of its normal, deeply-nested place.
When to use a portal
A portal is particularly helpful for displaying elements that should go on top of your existing React components: popups, dropdowns, suggestions, hotspots
Why use a portal
No z-index problems anymore: a portal permits you to render to <body>
. If you want to display a popup or dropdown, this is a really nice idea if you don't want to have to fight against z-index problems. The portal elements get added do document.body
in mount order, which means that unless you play with z-index
, the default behavior will be to stack portals on top of each others, in mounting order. In practice, it means that you can safely open a popup from inside another popup, and be sure that the 2nd popup will be displayed on top of the first, without having to even think about z-index
.
In practice
Most simple: use local React state: if you think, for a simple delete confirmation popup, it's not worth to have the Redux boilerplate, then you can use a portal and it greatly simplifies your code. For such a use case, where the interaction is very local and is actually quite an implementation detail, do you really care about hot-reloading, time-traveling, action logging and all the benefits Redux brings you? Personally, I don't and use local state in this case. The code becomes as simple as:
class DeleteButton extends React.Component {
static propTypes = {
onDelete: PropTypes.func.isRequired,
};
state = { confirmationPopup: false };
open = () => {
this.setState({ confirmationPopup: true });
};
close = () => {
this.setState({ confirmationPopup: false });
};
render() {
return (
<div className="delete-button">
<div onClick={() => this.open()}>Delete</div>
{this.state.confirmationPopup && (
<Portal>
<DeleteConfirmationPopup
onCancel={() => this.close()}
onConfirm={() => {
this.close();
this.props.onDelete();
}}
/>
</Portal>
)}
</div>
);
}
}
Simple: you can still use Redux state: if you really want to, you can still use connect
to choose whether or not the DeleteConfirmationPopup
is shown or not. As the portal remains deeply nested in your React tree, it is very simple to customize the behavior of this portal because your parent can pass props to the portal. If you don't use portals, you usually have to render your popups at the top of your React tree for z-index
reasons, and usually have to think about things like "how do I customize the generic DeleteConfirmationPopup I built according to the use case". And usually you'll find quite hacky solutions to this problem, like dispatching an action that contains nested confirm/cancel actions, a translation bundle key, or even worse, a render function (or something else unserializable). You don't have to do that with portals, and can just pass regular props, since DeleteConfirmationPopup
is just a child of the DeleteButton
Conclusion
Portals are very useful to simplify your code. I couldn't do without them anymore.
Note that portal implementations can also help you with other useful features like:
- Accessibility
- Espace shortcuts to close the portal
- Handle outside click (close portal or not)
- Handle link click (close portal or not)
- React Context made available in portal tree
react-portal or react-modal are nice for popups, modals, and overlays that should be full-screen, generally centered in the middle of the screen.
react-tether is unknown to most React developers, yet it's one of the most useful tools you can find out there. Tether permits you to create portals, but will position automatically the portal, relative to a given target. This is perfect for tooltips, dropdowns, hotspots, helpboxes... If you have ever had any problem with position absolute
/relative
and z-index
, or your dropdown going outside of your viewport, Tether will solve all that for you.
You can, for example, easily implement onboarding hotspots, that expands to a tooltip once clicked:
Real production code here. Can't be any simpler :)
<MenuHotspots.contacts>
<ContactButton/>
</MenuHotspots.contacts>
Edit: just discovered react-gateway which permits to render portals into the node of your choice (not necessarily body)
Edit: it seems react-popper can be a decent alternative to react-tether. PopperJS is a library that only computes an appropriate position for an element, without touching the DOM directly, letting the user choose where and when he wants to put the DOM node, while Tether appends directly to the body.
Edit: there's also react-slot-fill which is interesting and can help solve similar problems by allowing to render an element to a reserved element slot that you put anywhere you want in your tree
Cannot install packages using node package manager in Ubuntu
I fixed it unlinking /usr/sbin/node (which is linked to ax25-node package), then I have create a link to nodejs using this on command line
sudo ln -s /usr/bin/nodejs /usr/bin/node
Because package such as karma doesn't work with nodejs name, however changing the first line of karma script from node to nodejs, but I prefer resolve this issue once and for all
How to use the ProGuard in Android Studio?
The other answers here are great references on using proguard. However, I haven't seen an issue discussed that I ran into that was a mind bender. After you generate a signed release .apk, it's put in the /release
folder in your app but my app had an apk that wasn't in the /release
folder. Hence, I spent hours decompiling the wrong apk wondering why my proguard changes were having no affect. Hope this helps someone!
How to make type="number" to positive numbers only
Try this:
- Tested in Angular 8
- values are positive
- This code also handels
null
and negitive
values.
<input
type="number"
min="0"
(input)="funcCall()" -- Optional
oninput="value == '' ? value = 0 : value < 0 ? value = value * -1 : false"
formControlName="RateQty"
[(value)]="some.variable" -- Optional
/>
Permutations between two lists of unequal length
Answering the question "given two lists, find all possible permutations of pairs of one item from each list" and using basic Python functionality (i.e., without itertools) and, hence, making it easy to replicate for other programming languages:
def rec(a, b, ll, size):
ret = []
for i,e in enumerate(a):
for j,f in enumerate(b):
l = [e+f]
new_l = rec(a[i+1:], b[:j]+b[j+1:], ll, size)
if not new_l:
ret.append(l)
for k in new_l:
l_k = l + k
ret.append(l_k)
if len(l_k) == size:
ll.append(l_k)
return ret
a = ['a','b','c']
b = ['1','2']
ll = []
rec(a,b,ll, min(len(a),len(b)))
print(ll)
Returns
[['a1', 'b2'], ['a1', 'c2'], ['a2', 'b1'], ['a2', 'c1'], ['b1', 'c2'], ['b2', 'c1']]
C# Remove object from list of objects
There are two problems with this code:
Capacity
represents the number of items the list can contain before resizing is required, not the actual count; you need to use Count
instead, and
- When you remove from the list, you should go backwards, otherwise you could skip the second item when two identical items are next to each other.
Spring Data JPA map the native query result to Non-Entity POJO
I think Michal's approach is better. But, there is one more way to get the result out of the native query.
@Query(value = "SELECT g.*, gm.* FROM group g LEFT JOIN group_members gm ON g.group_id = gm.group_id and gm.user_id = :userId WHERE g.group_id = :groupId", nativeQuery = true)
String[][] getGroupDetails(@Param("userId") Integer userId, @Param("groupId") Integer groupId);
Now, you can convert this 2D string array into your desired entity.
How to locate the git config file in Mac
The solution to the problem is:
Find the .gitconfig file
[user]
name = 1wQasdTeedFrsweXcs234saS56Scxs5423
email = [email protected]
[credential]
helper = osxkeychain
[url ""]
insteadOf = git://
[url "https://"]
[url "https://"]
insteadOf = git://
there would be a blank url=""
replace it with url="https://"
[user]
name = 1wQasdTeedFrsweXcs234saS56Scxs5423
email = [email protected]
[credential]
helper = osxkeychain
[url "https://"]
insteadOf = git://
[url "https://"]
[url "https://"]
insteadOf = git://
This will work :)
Happy Bower-ing
calling javascript function on OnClientClick event of a Submit button
OnClientClick="SomeMethod()"
event of that BUTTON, it return by default "true
" so after that function it do postback
for solution use
//use this code in BUTTON ==> OnClientClick="return SomeMethod();"
//and your function like this
<script type="text/javascript">
function SomeMethod(){
// put your code here
return false;
}
</script>
How to kill/stop a long SQL query immediately?
A simple answer, if the red "stop" box is not working, is to try pressing the "Ctrl + Break" buttons on the keyboard.
If you are running SQL Server on Linux, there is an app you can add to your systray called "killall"
Just click on the "killall" button and then click on the program that is caught in a loop and it will terminate the program.
Hope that helps.
SQL Query - SUM(CASE WHEN x THEN 1 ELSE 0) for multiple columns
I would change the query in the following ways:
- Do the aggregation in subqueries. This can take advantage of more information about the table for optimizing the
group by
.
- Combine the second and third subqueries. They are aggregating on the same column. This requires using a
left outer join
to ensure that all data is available.
- By using
count(<fieldname>)
you can eliminate the comparisons to is null
. This is important for the second and third calculated values.
- To combine the second and third queries, it needs to count an id from the
mde
table. These use mde.mdeid
.
The following version follows your example by using union all
:
SELECT CAST(Detail.ReceiptDate AS DATE) AS "Date",
SUM(TOTALMAILED) as TotalMailed,
SUM(TOTALUNDELINOTICESRECEIVED) as TOTALUNDELINOTICESRECEIVED,
SUM(TRACEUNDELNOTICESRECEIVED) as TRACEUNDELNOTICESRECEIVED
FROM ((select SentDate AS "ReceiptDate", COUNT(*) as TotalMailed,
NULL as TOTALUNDELINOTICESRECEIVED, NULL as TRACEUNDELNOTICESRECEIVED
from MailDataExtract
where SentDate is not null
group by SentDate
) union all
(select MDE.ReturnMailDate AS ReceiptDate, 0,
COUNT(distinct mde.mdeid) as TOTALUNDELINOTICESRECEIVED,
SUM(case when sd.ReturnMailTypeId = 1 then 1 else 0 end) as TRACEUNDELNOTICESRECEIVED
from MailDataExtract MDE left outer join
DTSharedData.dbo.ScanData SD
ON SD.ScanDataID = MDE.ReturnScanDataID
group by MDE.ReturnMailDate;
)
) detail
GROUP BY CAST(Detail.ReceiptDate AS DATE)
ORDER BY 1;
The following does something similar using full outer join
:
SELECT coalesce(sd.ReceiptDate, mde.ReceiptDate) AS "Date",
sd.TotalMailed, mde.TOTALUNDELINOTICESRECEIVED,
mde.TRACEUNDELNOTICESRECEIVED
FROM (select cast(SentDate as date) AS "ReceiptDate", COUNT(*) as TotalMailed
from MailDataExtract
where SentDate is not null
group by cast(SentDate as date)
) sd full outer join
(select cast(MDE.ReturnMailDate as date) AS ReceiptDate,
COUNT(distinct mde.mdeID) as TOTALUNDELINOTICESRECEIVED,
SUM(case when sd.ReturnMailTypeId = 1 then 1 else 0 end) as TRACEUNDELNOTICESRECEIVED
from MailDataExtract MDE left outer join
DTSharedData.dbo.ScanData SD
ON SD.ScanDataID = MDE.ReturnScanDataID
group by cast(MDE.ReturnMailDate as date)
) mde
on sd.ReceiptDate = mde.ReceiptDate
ORDER BY 1;
What is an IIS application pool?
Application pools are used to separate set of IIS worker processes that share the same configuration.
Application pools enable us to isolate our web application for better security, reliability, and availability
AngularJS. How to call controller function from outside of controller component
I am an Ionic framework user and the one I found that would consistently provide the current controller's $scope is:
angular.element(document.querySelector('ion-view[nav-view="active"]')).scope()
I suspect this can be modified to fit most scenarios regardless of framework (or not) by finding the query that will target the specific DOM element(s) that are available only during a given controller instance.
How to convert integer to string in C?
Making your own itoa
is also easy, try this :
char* itoa(int i, char b[]){
char const digit[] = "0123456789";
char* p = b;
if(i<0){
*p++ = '-';
i *= -1;
}
int shifter = i;
do{ //Move to where representation ends
++p;
shifter = shifter/10;
}while(shifter);
*p = '\0';
do{ //Move back, inserting digits as u go
*--p = digit[i%10];
i = i/10;
}while(i);
return b;
}
or use the standard sprintf()
function.
How to define the css :hover state in a jQuery selector?
I know this has an accepted answer but if anyone comes upon this, my solution may help.
I found this question because I have a use-case where I wanted to turn off the :hover state for elements individually. Since there is no way to do this in the DOM, another good way to do it is to define a class in CSS that overrides the hover state.
For instance, the css:
.nohover:hover {
color: black !important;
}
Then with jQuery:
$("#elm").addClass("nohover");
With this method, you can override as many DOM elements as you would like without binding tons of onHover events.
How to use the CSV MIME-type?
You could try to force the browser to open a "Save As..." dialog by doing something like:
header('Content-type: text/csv');
header('Content-disposition: attachment;filename=MyVerySpecial.csv');
echo "cell 1, cell 2";
Which should work across most major browsers.
Grep to find item in Perl array
I could happen that if your array contains the string "hello", and if you are searching for "he", grep returns true, although, "he" may not be an array element.
Perhaps,
if (grep(/^$match$/, @array))
more apt.
Why doesn't Java offer operator overloading?
Sometimes it would be nice to have operator overloading, friend classes and multiple inheritance.
However I still think it was a good decision. If Java would have had operator overloading then we could never be sure of operator meanings without looking through source code. At present that's not necessary. And I think your example of using methods instead of operator overloading is also quite readable. If you want to make things more clear you could always add a comment above hairy statements.
// a = b + c
Complex a, b, c; a = b.add(c);
In PHP how can you clear a WSDL cache?
Edit your php.ini
file, search for soap.wsdl_cache_enabled
and set the value to 0
[soap]
; Enables or disables WSDL caching feature.
; http://php.net/soap.wsdl-cache-enabled
soap.wsdl_cache_enabled=0
Selenium WebDriver and DropDown Boxes
Just wrap your WebElement into Select Object as shown below
Select dropdown = new Select(driver.findElement(By.id("identifier")));
Once this is done you can select the required value in 3 ways. Consider an HTML file like this
<html>
<body>
<select id = "designation">
<option value = "MD">MD</option>
<option value = "prog"> Programmer </option>
<option value = "CEO"> CEO </option>
</option>
</select>
<body>
</html>
Now to identify dropdown do
Select dropdown = new Select(driver.findElement(By.id("designation")));
To select its option say 'Programmer' you can do
dropdown.selectByVisibleText("Programmer ");
or
dropdown.selectByIndex(1);
or
dropdown.selectByValue("prog");
Happy Coding :)
How to hide iOS status bar
To hide status bar in iOS7 you need 2 lines of code
in application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions write
[[UIApplication sharedApplication] setStatusBarHidden:YES];
in info.plist add this
View-Controller Based Status Bar Appearance = NO
BeautifulSoup getText from between <p>, not picking up subsequent paragraphs
This works well for specific articles where the text is all wrapped in <p>
tags. Since the web is an ugly place, it's not always the case.
Often, websites will have text scattered all over, wrapped in different types of tags (e.g. maybe in a <span>
or a <div>
, or an <li>
).
To find all text nodes in the DOM, you can use soup.find_all(text=True)
.
This is going to return some undesired text, like the contents of <script>
and <style>
tags. You'll need to filter out the text contents of elements you don't want.
blacklist = [
'style',
'script',
# other elements,
]
text_elements = [t for t in soup.find_all(text=True) if t.parent.name not in blacklist]
If you are working with a known set of tags, you can tag the opposite approach:
whitelist = [
'p'
]
text_elements = [t for t in soup.find_all(text=True) if t.parent.name in whitelist]
How do I determine whether an array contains a particular value in Java?
Just simply implement it by hand:
public static <T> boolean contains(final T[] array, final T v) {
for (final T e : array)
if (e == v || v != null && v.equals(e))
return true;
return false;
}
Improvement:
The v != null
condition is constant inside the method. It always evaluates to the same Boolean value during the method call. So if the input array
is big, it is more efficient to evaluate this condition only once, and we can use a simplified/faster condition inside the for
loop based on the result. The improved contains()
method:
public static <T> boolean contains2(final T[] array, final T v) {
if (v == null) {
for (final T e : array)
if (e == null)
return true;
}
else {
for (final T e : array)
if (e == v || v.equals(e))
return true;
}
return false;
}
Which SchemaType in Mongoose is Best for Timestamp?
First : npm install mongoose-timestamp
Next: let Timestamps = require('mongoose-timestamp')
Next: let MySchema = new Schema
Next: MySchema.plugin(Timestamps)
Next : const Collection = mongoose.model('Collection',MySchema)
Then you can use the Collection.createdAt
or Collection.updatedAt
anywhere your want.
Created on: Date Of The Week Month Date Year 00:00:00 GMT
Time is in this format.
Unsigned values in C
In the hexadecimal it can't get a negative value. So it shows it like ffffffff.
The advantage to using the unsigned version (when you know the values contained will be non-negative) is that sometimes the computer will spot errors for you (the program will "crash" when a negative value is assigned to the variable).
Cross-Origin Read Blocking (CORB)
Cross-Origin Read Blocking (CORB), an algorithm by which dubious cross-origin resource loads may be identified and blocked by web browsers before they reach the web page..It is designed to prevent the browser from delivering certain cross-origin network responses to a web page.
First Make sure these resources are served with a correct "Content-Type
", i.e, for JSON MIME type - "text/json
", "application/json
", HTML MIME type - "text/html
".
Second: set mode to cors i.e, mode:cors
The fetch would look something like this
fetch("https://example.com/api/request", {
method: 'POST',
body: JSON.stringify(data),
mode: 'cors',
headers: {
'Content-Type': 'application/json',
"Accept": 'application/json',
}
})
.then((data) => data.json())
.then((resp) => console.log(resp))
.catch((err) => console.log(err))
references: https://chromium.googlesource.com/chromium/src/+/master/services/network/cross_origin_read_blocking_explainer.md
https://www.chromium.org/Home/chromium-security/corb-for-developers
How to append data to a json file?
You aren't ever writing anything to do with the data you read in. Do you want to be adding the data structure in feeds to the new one you're creating?
Or perhaps you want to open the file in append mode open(filename, 'a')
and then add your string, by writing the string produced by json.dumps
instead of using json.dump
- but nneonneo points out that this would be invalid json.
Why am I getting this redefinition of class error?
You're defining the same class twice is why.
If your intent is to implement the methods in the CPP file then do so something like this:
gameObject::gameObject()
{
x = 0;
y = 0;
}
gameObject::~gameObject()
{
//
}
int gameObject::add()
{
return x+y;
}
When to use Hadoop, HBase, Hive and Pig?
For a Comparison Between Hadoop Vs Cassandra/HBase read this post.
Basically HBase enables really fast read and writes with scalability. How fast and scalable? Facebook uses it to manage its user statuses, photos, chat messages etc. HBase is so fast sometimes stacks have been developed by Facebook to use HBase as the data store for Hive itself.
Where As Hive is more like a Data Warehousing solution. You can use a syntax similar to SQL to query Hive contents which results in a Map Reduce job. Not ideal for fast, transactional systems.
Failed to execute 'createObjectURL' on 'URL':
This error is caused because the function createObjectURL
is deprecated for Google Chrome
I changed this:
video.src=vendorUrl.createObjectURL(stream);
video.play();
to this:
video.srcObject=stream;
video.play();
This worked for me.
Copy Image from Remote Server Over HTTP
If you have PHP5 and the HTTP stream wrapper enabled on your server, it's incredibly simple to copy it to a local file:
copy('http://somedomain.com/file.jpeg', '/tmp/file.jpeg');
This will take care of any pipelining etc. that's needed. If you need to provide some HTTP parameters there is a third 'stream context' parameter you can provide.
How would one write object-oriented code in C?
You can fake it using function pointers, and in fact, I think it is theoretically possible to compile C++ programs into C.
However, it rarely makes sense to force a paradigm on a language rather than to pick a language that uses a paradigm.
How can I make a program wait for a variable change in javascript?
Super dated, but certainly good ways to accomodate this. Just wrote this up
for a project and figured I'd share. Similar to some of the others, varied in style.
var ObjectListener = function(prop, value) {
if (value === undefined) value = null;
var obj = {};
obj.internal = value;
obj.watcher = (function(x) {});
obj.emit = function(fn) {
obj.watch = fn;
};
var setter = {};
setter.enumerable = true;
setter.configurable = true;
setter.set = function(x) {
obj.internal = x;
obj.watcher(x);
};
var getter = {};
getter.enumerable = true;
getter.configurable = true;
getter.get = function() {
return obj.internal;
};
return (obj,
Object.defineProperty(obj, prop, setter),
Object.defineProperty(obj, prop, getter),
obj.emit, obj);
};
user._licenseXYZ = ObjectListener(testProp);
user._licenseXYZ.emit(testLog);
function testLog() {
return function() {
return console.log([
'user._licenseXYZ.testProp was updated to ', value
].join('');
};
}
user._licenseXYZ.testProp = 123;
What's the most elegant way to cap a number to a segment?
a less "Math" oriented approach ,but should also work , this way, the < / > test is exposed (maybe more understandable than minimaxing) but it really depends on what you mean by "readable"
function clamp(num, min, max) {
return num <= min ? min : num >= max ? max : num;
}
Splitting String and put it on int array
Something like this:
public static void main(String[] args) {
String N = "ABCD";
char[] array = N.toCharArray();
// and as you can see:
System.out.println(array[0]);
System.out.println(array[1]);
System.out.println(array[2]);
}
How to quickly clear a JavaScript Object?
The short answer to your question, I think, is no (you can just create a new object).
In this example, I believe setting the length to 0 still leaves all of the elements for garbage collection.
You could add this to Object.prototype if it's something you'd frequently use. Yes it's linear in complexity, but anything that doesn't do garbage collection later will be.
This is the best solution. I know it's not related to your question - but for how long do we need to continue supporting IE6? There are many campaigns to discontinue the usage of it.
Feel free to correct me if there's anything incorrect above.
MVC 4 - Return error message from Controller - Show in View
The Return View(model) returns you error because you don't fill the model with the values in your post method and the model data for the dropdown is empty. Please provide the Get method to explain further how to manage displaying the error. In order to the error to be shown you should use this:
[HttpPost]
public ActionResult form_edit(FormModels model)
{
if(ModelState.IsValid())
{
--- operations
return Redirect("OtherAction", "SomeController");
}
// here you can use a little trick
//fill the model property that holds the information for the dropdown with the data
// you haven't provided the get method but it should look something like this
model.Countries = ... some data goes here;
model.dd_value = ... some other data;
model.dd_text = ... other data;
ModelState.AddModelError("", "adfdghdghgdhgdhdgda");
return View(model);
}
and then in the view just use :
@model mvc_cs.Models.FormModels
@using ctrlr = mvc_cs.Controllers.FormController
@using (Html.BeginForm("form_edit", "Form", FormMethod.Post))
{
<table>
<tr>
<td>
@Html.ValidationSummary(true)
</td>
</tr>
<tr>
<th>
@Html.DisplayNameFor(model => model.content_name)
@Html.DropDownListFor(x => x.selectedvalue, new SelectList(Model.Countries, Model.dd_value, Model.dd_text), "-- Select Product--")
</th>
</tr>
</table>
<table>
<tr>
<td>
<input type="submit" value="Submit" />
</td>
</tr>
</table>
}
This should work okay.
If you just use RedirectToAction it will redirect you to the get method --> you will have no error but the view will be just reloaded and no error would be shown.
other way around is that you can pass the error not by ModelState.AddError, but with ViewData["error"] like this:
[HttpPost]
public ActionResult form_edit(FormModels model)
{
TempData["error"] = "someErrorMessage";
return RedirectToAction("form_Post", "Form");
}
[HttpGet]
public ActionResult form_edit()
{
do stuff here ----
ViewData["error"] = TempData["error"];
return View();
}
@model mvc_cs.Models.FormModels
@using ctrlr = mvc_cs.Controllers.FormController
@using (Html.BeginForm("form_edit", "Form", FormMethod.Post))
{
<table>
<tr>
<td>
<div>@ViewData["error"]</div>
</td>
</tr>
<tr>
<th>
@Html.DisplayNameFor(model => model.content_name)
@Html.DropDownListFor(x => x.selectedvalue, new SelectList(Model.Countries, Model.dd_value, Model.dd_text), "-- Select Product--")
</th>
</tr>
</table>
<table>
<tr>
<td>
<input type="submit" value="Submit" />
</td>
</tr>
</table>
}
How to remove all elements in String array in java?
Usually someone uses collections if something frequently changes.
E.g.
List<String> someList = new ArrayList<String>();
// initialize list
someList.add("Mango");
someList.add("....");
// remove all elements
someList.clear();
// empty list
An ArrayList
for example uses a backing Array
. The resizing and this stuff is handled automatically. In most cases this is the appropriate way.
Parsing XML with namespace in Python via 'ElementTree'
I've been using similar code to this and have found it's always worth reading the documentation... as usual!
findall() will only find elements which are direct children of the current tag. So, not really ALL.
It might be worth your while trying to get your code working with the following, especially if you're dealing with big and complex xml files so that that sub-sub-elements (etc.) are also included.
If you know yourself where elements are in your xml, then I suppose it'll be fine! Just thought this was worth remembering.
root.iter()
ref: https://docs.python.org/3/library/xml.etree.elementtree.html#finding-interesting-elements
"Element.findall() finds only elements with a tag which are direct children of the current element. Element.find() finds the first child with a particular tag, and Element.text accesses the element’s text content. Element.get() accesses the element’s attributes:"
Most efficient way to check for DBNull and then assign to a variable?
There is the troublesome case where the object could be a string. The below extension method code handles all cases. Here's how you would use it:
static void Main(string[] args)
{
object number = DBNull.Value;
int newNumber = number.SafeDBNull<int>();
Console.WriteLine(newNumber);
}
public static T SafeDBNull<T>(this object value, T defaultValue)
{
if (value == null)
return default(T);
if (value is string)
return (T) Convert.ChangeType(value, typeof(T));
return (value == DBNull.Value) ? defaultValue : (T)value;
}
public static T SafeDBNull<T>(this object value)
{
return value.SafeDBNull(default(T));
}
SQL Query to find missing rows between two related tables
SELECT A.ABC_ID, A.VAL FROM A WHERE NOT EXISTS
(SELECT * FROM B WHERE B.ABC_ID = A.ABC_ID AND B.VAL = A.VAL)
or
SELECT A.ABC_ID, A.VAL FROM A WHERE VAL NOT IN
(SELECT VAL FROM B WHERE B.ABC_ID = A.ABC_ID)
or
SELECT A.ABC_ID, A.VAL LEFT OUTER JOIN B
ON A.ABC_ID = B.ABC_ID AND A.VAL = B.VAL FROM A WHERE B.VAL IS NULL
Please note that these queries do not require that ABC_ID be in table B at all. I think that does what you want.
How do I pipe a subprocess call to a text file?
The options for popen
can be used in call
args,
bufsize=0,
executable=None,
stdin=None,
stdout=None,
stderr=None,
preexec_fn=None,
close_fds=False,
shell=False,
cwd=None,
env=None,
universal_newlines=False,
startupinfo=None,
creationflags=0
So...
subprocess.call(["/home/myuser/run.sh", "/tmp/ad_xml", "/tmp/video_xml"], stdout=myoutput)
Then you can do what you want with myoutput
(which would need to be a file btw).
Also, you can do something closer to a piped output like this.
dmesg | grep hda
would be:
p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
output = p2.communicate()[0]
There's plenty of lovely, useful info on the python manual page.
Py_Initialize fails - unable to load the file system codec
For those working in Visual Studio
simply add the include
, Lib
and libs
directories to the Include Directories
and Library Directories
under
Projects Properties -> Configuration Properties > VC++ Directories
:
For example I have Anaconda3
on my system and working with Visual Studio 2015
This is how the settings looks like (note the Include and Library directories) :
Edit:
As also pointed out by bossi setting PYTHONPATH
in your user Environment Variables
section seems necessary.
a sample input can be like this (in my case):
C:\Users\Master\Anaconda3\Lib;C:\Users\Master\Anaconda3\libs;C:\Users\Master\Anaconda3\Lib\site-packages;C:\Users\Master\Anaconda3\DLLs
is necessary it seems.
Also, you need to restart Visual Studio
after you set up the PYTHONPATH
in your user Environment Variables for the changes to take effect.
Also note that :
Make sure the PYTHONHOME
environment variable is set to the Python
interpreter you want to use. The C++ projects in Visual Studio rely on
this variable to locate files such as python.h
, which are used when
creating a Python extension.
Quickest way to convert a base 10 number to any base in .NET?
Very late to the party on this one, but I wrote the following helper class recently for a project at work. It was designed to convert short strings into numbers and back again (a simplistic perfect hash function), however it will also perform number conversion between arbitrary bases. The Base10ToString
method implementation answers the question that was originally posted.
The shouldSupportRoundTripping
flag passed to the class constructor is needed to prevent the loss of leading digits from the number string during conversion to base-10 and back again (crucial, given my requirements!). Most of the time the loss of leading 0s from the number string probably won't be an issue.
Anyway, here's the code:
using System;
using System.Collections.Generic;
using System.Linq;
namespace StackOverflow
{
/// <summary>
/// Contains methods used to convert numbers between base-10 and another numbering system.
/// </summary>
/// <remarks>
/// <para>
/// This conversion class makes use of a set of characters that represent the digits used by the target
/// numbering system. For example, binary would use the digits 0 and 1, whereas hex would use the digits
/// 0 through 9 plus A through F. The digits do not have to be numerals.
/// </para>
/// <para>
/// The first digit in the sequence has special significance. If the number passed to the
/// <see cref="StringToBase10"/> method has leading digits that match the first digit, then those leading
/// digits will effectively be 'lost' during conversion. Much of the time this won't matter. For example,
/// "0F" hex will be converted to 15 decimal, but when converted back to hex it will become simply "F",
/// losing the leading "0". However, if the set of digits was A through Z, and the number "ABC" was
/// converted to base-10 and back again, then the leading "A" would be lost. The <see cref="System.Boolean"/>
/// flag passed to the constructor allows 'round-tripping' behaviour to be supported, which will prevent
/// leading digits from being lost during conversion.
/// </para>
/// <para>
/// Note that numeric overflow is probable when using longer strings and larger digit sets.
/// </para>
/// </remarks>
public class Base10Converter
{
const char NullDigit = '\0';
public Base10Converter(string digits, bool shouldSupportRoundTripping = false)
: this(digits.ToCharArray(), shouldSupportRoundTripping)
{
}
public Base10Converter(IEnumerable<char> digits, bool shouldSupportRoundTripping = false)
{
if (digits == null)
{
throw new ArgumentNullException("digits");
}
if (digits.Count() == 0)
{
throw new ArgumentException(
message: "The sequence is empty.",
paramName: "digits"
);
}
if (!digits.Distinct().SequenceEqual(digits))
{
throw new ArgumentException(
message: "There are duplicate characters in the sequence.",
paramName: "digits"
);
}
if (shouldSupportRoundTripping)
{
digits = (new[] { NullDigit }).Concat(digits);
}
_digitToIndexMap =
digits
.Select((digit, index) => new { digit, index })
.ToDictionary(keySelector: x => x.digit, elementSelector: x => x.index);
_radix = _digitToIndexMap.Count;
_indexToDigitMap =
_digitToIndexMap
.ToDictionary(keySelector: x => x.Value, elementSelector: x => x.Key);
}
readonly Dictionary<char, int> _digitToIndexMap;
readonly Dictionary<int, char> _indexToDigitMap;
readonly int _radix;
public long StringToBase10(string number)
{
Func<char, int, long> selector =
(c, i) =>
{
int power = number.Length - i - 1;
int digitIndex;
if (!_digitToIndexMap.TryGetValue(c, out digitIndex))
{
throw new ArgumentException(
message: String.Format("Number contains an invalid digit '{0}' at position {1}.", c, i),
paramName: "number"
);
}
return Convert.ToInt64(digitIndex * Math.Pow(_radix, power));
};
return number.Select(selector).Sum();
}
public string Base10ToString(long number)
{
if (number < 0)
{
throw new ArgumentOutOfRangeException(
message: "Value cannot be negative.",
paramName: "number"
);
}
string text = string.Empty;
long remainder;
do
{
number = Math.DivRem(number, _radix, out remainder);
char digit;
if (!_indexToDigitMap.TryGetValue((int) remainder, out digit) || digit == NullDigit)
{
throw new ArgumentException(
message: "Value cannot be converted given the set of digits used by this converter.",
paramName: "number"
);
}
text = digit + text;
}
while (number > 0);
return text;
}
}
}
This can also be subclassed to derive custom number converters:
namespace StackOverflow
{
public sealed class BinaryNumberConverter : Base10Converter
{
public BinaryNumberConverter()
: base(digits: "01", shouldSupportRoundTripping: false)
{
}
}
public sealed class HexNumberConverter : Base10Converter
{
public HexNumberConverter()
: base(digits: "0123456789ABCDEF", shouldSupportRoundTripping: false)
{
}
}
}
And the code would be used like this:
using System.Diagnostics;
namespace StackOverflow
{
class Program
{
static void Main(string[] args)
{
{
var converter = new Base10Converter(
digits: "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz",
shouldSupportRoundTripping: true
);
long number = converter.StringToBase10("Atoz");
string text = converter.Base10ToString(number);
Debug.Assert(text == "Atoz");
}
{
var converter = new HexNumberConverter();
string text = converter.Base10ToString(255);
long number = converter.StringToBase10(text);
Debug.Assert(number == 255);
}
}
}
}
How do I set the eclipse.ini -vm option?
-startup
plugins/org.eclipse.equinox.launcher_1.3.0.v20140415-2008.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.200.v20140603-1326
-product
org.eclipse.epp.package.jee.product
--launcher.defaultAction
openFile
--launcher.XXMaxPermSize
512M
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
512m
--launcher.defaultAction
openFile
--launcher.appendVmargs
-vmargs
-Dosgi.requiredJavaVersion=1.6
-Xms2000m
-Xmx3512m
Classes cannot be accessed from outside package
closeDrawers(boolean)
is not public in android.support.v4.widget.DrawerLayout
. Cannot be accessed from outside package
@Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
Instagram API to fetch pictures with specific hashtags
Firstly, the Instagram API endpoint "tags" required OAuth authentication.
You can query results for a particular hashtag (snowy in this case) using the following url
It is rate limited to 5000 (X-Ratelimit-Limit:5000) per hour
https://api.instagram.com/v1/tags/snowy/media/recent
Sample response
{
"pagination": {
"next_max_tag_id": "1370433362010",
"deprecation_warning": "next_max_id and min_id are deprecated for this endpoint; use min_tag_id and max_tag_id instead",
"next_max_id": "1370433362010",
"next_min_id": "1370443976800",
"min_tag_id": "1370443976800",
"next_url": "https://api.instagram.com/v1/tags/snowy/media/recent?access_token=40480112.1fb234f.4866541998fd4656a2e2e2beaa5c4bb1&max_tag_id=1370433362010"
},
"meta": {
"code": 200
},
"data": [
{
"attribution": null,
"tags": [
"snowy"
],
"type": "image",
"location": null,
"comments": {
"count": 0,
"data": []
},
"filter": null,
"created_time": "1370418343",
"link": "http://instagram.com/p/aK1yrGRi3l/",
"likes": {
"count": 1,
"data": [
{
"username": "iri92lol",
"profile_picture": "http://images.ak.instagram.com/profiles/profile_404174490_75sq_1370417509.jpg",
"id": "404174490",
"full_name": "Iri"
}
]
},
"images": {
"low_resolution": {
"url": "http://distilleryimage1.s3.amazonaws.com/ecf272a2cdb311e2990322000a9f192c_6.jpg",
"width": 306,
"height": 306
},
"thumbnail": {
"url": "http://distilleryimage1.s3.amazonaws.com/ecf272a2cdb311e2990322000a9f192c_5.jpg",
"width": 150,
"height": 150
},
"standard_resolution": {
"url": "http://distilleryimage1.s3.amazonaws.com/ecf272a2cdb311e2990322000a9f192c_7.jpg",
"width": 612,
"height": 612
}
},
"users_in_photo": [],
"caption": {
"created_time": "1370418353",
"text": "#snowy",
"from": {
"username": "iri92lol",
"profile_picture": "http://images.ak.instagram.com/profiles/profile_404174490_75sq_1370417509.jpg",
"id": "404174490",
"full_name": "Iri"
},
"id": "471425773832908504"
},
"user_has_liked": false,
"id": "471425689728724453_404174490",
"user": {
"username": "iri92lol",
"website": "",
"profile_picture": "http://images.ak.instagram.com/profiles/profile_404174490_75sq_1370417509.jpg",
"full_name": "Iri",
"bio": "",
"id": "404174490"
}
}
}
You can play around here :
https://apigee.com/console/instagram?req=%7B%22resource%22%3A%22get_tags_media_recent%22%2C%22params%22%3A%7B%22query%22%3A%7B%7D%2C%22template%22%3A%7B%22tag-name%22%3A%22snowy%22%7D%2C%22headers%22%3A%7B%7D%2C%22body%22%3A%7B%22attachmentFormat%22%3A%22mime%22%2C%22attachmentContentDisposition%22%3A%22form-data%22%7D%7D%2C%22verb%22%3A%22get%22%7D
You need to use "Authentication" as OAuth 2 and will be prompted to signin via Instagram.
Post that you might have to reneter the "tag-name" in "Template" section.
All the pagination related data is available in the "pagination" parameter in the response and use it's "next_url" to query for the next set of result.
How to set MouseOver event/trigger for border in XAML?
Yes, this is confusing...
According to this blog post, it looks like this is an omission from WPF.
To make it work you need to use a style:
<Border Name="ClearButtonBorder" Grid.Column="1" CornerRadius="0,3,3,0">
<Border.Style>
<Style>
<Setter Property="Border.Background" Value="Blue"/>
<Style.Triggers>
<Trigger Property="Border.IsMouseOver" Value="True">
<Setter Property="Border.Background" Value="Green" />
</Trigger>
</Style.Triggers>
</Style>
</Border.Style>
<TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="X" />
</Border>
I guess this problem isn't that common as most people tend to factor out this sort of thing into a style, so it can be used on multiple controls.
Oracle PL/SQL - Raise User-Defined Exception With Custom SQLERRM
Yes. You just have to use the RAISE_APPLICATION_ERROR
function. If you also want to name your exception, you'll need to use the EXCEPTION_INIT
pragma in order to associate the error number to the named exception. Something like
SQL> ed
Wrote file afiedt.buf
1 declare
2 ex_custom EXCEPTION;
3 PRAGMA EXCEPTION_INIT( ex_custom, -20001 );
4 begin
5 raise_application_error( -20001, 'This is a custom error' );
6 exception
7 when ex_custom
8 then
9 dbms_output.put_line( sqlerrm );
10* end;
SQL> /
ORA-20001: This is a custom error
PL/SQL procedure successfully completed.
Make Div Draggable using CSS
I found this is really helpful:
_x000D_
_x000D_
// Make the DIV element draggable:_x000D_
dragElement(document.getElementById("mydiv"));_x000D_
_x000D_
function dragElement(elmnt) {_x000D_
var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;_x000D_
if (document.getElementById(elmnt.id + "header")) {_x000D_
// if present, the header is where you move the DIV from:_x000D_
document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;_x000D_
} else {_x000D_
// otherwise, move the DIV from anywhere inside the DIV:_x000D_
elmnt.onmousedown = dragMouseDown;_x000D_
}_x000D_
_x000D_
function dragMouseDown(e) {_x000D_
e = e || window.event;_x000D_
e.preventDefault();_x000D_
// get the mouse cursor position at startup:_x000D_
pos3 = e.clientX;_x000D_
pos4 = e.clientY;_x000D_
document.onmouseup = closeDragElement;_x000D_
// call a function whenever the cursor moves:_x000D_
document.onmousemove = elementDrag;_x000D_
}_x000D_
_x000D_
function elementDrag(e) {_x000D_
e = e || window.event;_x000D_
e.preventDefault();_x000D_
// calculate the new cursor position:_x000D_
pos1 = pos3 - e.clientX;_x000D_
pos2 = pos4 - e.clientY;_x000D_
pos3 = e.clientX;_x000D_
pos4 = e.clientY;_x000D_
// set the element's new position:_x000D_
elmnt.style.top = (elmnt.offsetTop - pos2) + "px";_x000D_
elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";_x000D_
}_x000D_
_x000D_
function closeDragElement() {_x000D_
// stop moving when mouse button is released:_x000D_
document.onmouseup = null;_x000D_
document.onmousemove = null;_x000D_
}_x000D_
}
_x000D_
#mydiv {_x000D_
position: absolute;_x000D_
z-index: 9;_x000D_
background-color: #f1f1f1;_x000D_
border: 1px solid #d3d3d3;_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
#mydivheader {_x000D_
padding: 10px;_x000D_
cursor: move;_x000D_
z-index: 10;_x000D_
background-color: #2196F3;_x000D_
color: #fff;_x000D_
}
_x000D_
<!-- Draggable DIV -->_x000D_
<div id="mydiv">_x000D_
<!-- Include a header DIV with the same name as the draggable DIV, followed by "header" -->_x000D_
<div id="mydivheader">Click here to move</div>_x000D_
<p>Move</p>_x000D_
<p>this</p>_x000D_
<p>DIV</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_
I hope you can use it to!
Converting milliseconds to minutes and seconds with Javascript
My solution:
Input: 11381 (in ms)
Output: 00 : 00 : 11.381
timeformatter(time) {
console.log(time);
let miliSec = String(time%1000);
time = (time - miliSec)/1000;
let seconds = String(time%60);
time = (time - seconds)/60;
let minutes = String(time%60);
time = (time-minutes)/60;
let hours = String(time)
while(miliSec.length != 3 && miliSec.length<3 && miliSec.length >=0) {
miliSec = '0'+miliSec;
}
while(seconds.length != 2 && seconds.length<3 && seconds.length >=0) {
seconds = '0'+seconds;
}
while(minutes.length != 2 && minutes.length<3 && minutes.length >=0) {
minutes = '0'+minutes;
}
while(hours.length != 2 && hours.length<3 && hours.length >=0) {
hours = '0'+hours;
}
return `${hours} : ${minutes} : ${seconds}.${miliSec}`
}
sed fails with "unknown option to `s'" error
The problem is with slashes: your variable contains them and the final command will be something like sed "s/string/path/to/something/g"
, containing way too many slashes.
Since sed
can take any char as delimiter (without having to declare the new delimiter), you can try using another one that doesn't appear in your replacement string:
replacement="/my/path"
sed --expression "s@pattern@$replacement@"
Note that this is not bullet proof: if the replacement string later contains @
it will break for the same reason, and any backslash sequences like \1
will still be interpreted according to sed
rules. Using |
as a delimiter is also a nice option as it is similar in readability to /
.
Am I trying to connect to a TLS-enabled daemon without TLS?
TLDR: This got my Python meetup group past this problem when I was running a clinic on installing docker and most of the users were on OS X:
boot2docker init
boot2docker up
run the export
commands the output gives you, then
docker info
should tell you it works.
The Context (what brought us to the problem)
I led a clinic on installing docker and most attendees had OS X, and we ran into this problem and I overcame it on several machines. Here's the steps we followed:
First, we installed homebrew (yes, some attendees didn't have it):
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
Then we got cask, which we used to install virtualbox, and then used brew to install docker and boot2docker (all required for OS X) Don't use sudo for brew.:
brew install caskroom/cask/brew-cask
brew cask install virtualbox
brew install docker
brew install boot2docker
The Solution
That was when we ran into the problem the asker here got. The following fixed it. I understand init
was a one-time deal, but you'll probably have to run up
every time you start docker:
boot2docker init
boot2docker up
Then when up
has been run, it gives several export
commands. Copy-paste and run those.
Finally docker info
should tell you it's properly installed.
To Demo
The rest of the commands should demo it. (on Ubuntu linux I required sudo.)
docker run hello-world
docker run -it ubuntu bash
Then you should be on a root shell in the container:
apt-get install nano
exit
Back to your native user bash:
docker ps -l
Look for the about 12 digit hexadecimal (0-9 or a-f) identifier under "Container ID", e.g. 456789abcdef
. You can then commit your change and name it some descriptive name, like descriptivename
:
docker commit 456789abcdef descriptivename`
Remove files from Git commit
Something that worked for me, but still think there should be a better solution:
$ git revert <commit_id>
$ git reset HEAD~1 --hard
Just leave the change you want to discard in the other commit, check others out
$ git commit --amend // or stash and rebase to <commit_id> to amend changes
virtualenvwrapper and Python 3
You can make virtualenvwrapper use a custom Python binary instead of the one virtualenvwrapper is run with. To do that you need to use VIRTUALENV_PYTHON variable which is utilized by virtualenv:
$ export VIRTUALENV_PYTHON=/usr/bin/python3
$ mkvirtualenv -a myproject myenv
Running virtualenv with interpreter /usr/bin/python3
New python executable in myenv/bin/python3
Also creating executable in myenv/bin/python
(myenv)$ python
Python 3.2.3 (default, Oct 19 2012, 19:53:16)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
Difference between ${} and $() in Bash
your understanding is right. For detailed info on {} see bash ref - parameter expansion
'for' and 'while' have different syntax and offer different styles of programmer control for an iteration. Most non-asm languages offer a similar syntax.
With while, you would probably write i=0; while [ $i -lt 10 ]; do echo $i; i=$(( i + 1 )); done
in essence manage everything about the iteration yourself
How to iterate over arguments in a Bash script
For simple cases you can also use shift
.
It treats the argument list like a queue. Each shift
throws the first argument out and the
index of each of the remaining arguments is decremented.
#this prints all arguments
while test $# -gt 0
do
echo "$1"
shift
done
Java Comparator class to sort arrays
[...] How should Java Comparator class be declared to sort the arrays by their first elements in decreasing order [...]
Here's a complete example using Java 8:
import java.util.*;
public class Test {
public static void main(String args[]) {
int[][] twoDim = { {1, 2}, {3, 7}, {8, 9}, {4, 2}, {5, 3} };
Arrays.sort(twoDim, Comparator.comparingInt(a -> a[0])
.reversed());
System.out.println(Arrays.deepToString(twoDim));
}
}
Output:
[[8, 9], [5, 3], [4, 2], [3, 7], [1, 2]]
For Java 7 you can do:
Arrays.sort(twoDim, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return Integer.compare(o2[0], o1[0]);
}
});
If you unfortunate enough to work on Java 6 or older, you'd do:
Arrays.sort(twoDim, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return ((Integer) o2[0]).compareTo(o1[0]);
}
});
Change string color with NSAttributedString?
In Swift 4:
// Custom color
let greenColor = UIColor(red: 10/255, green: 190/255, blue: 50/255, alpha: 1)
// create the attributed colour
let attributedStringColor = [NSAttributedStringKey.foregroundColor : greenColor];
// create the attributed string
let attributedString = NSAttributedString(string: "Hello World!", attributes: attributedStringColor)
// Set the label
label.attributedText = attributedString
In Swift 3:
// Custom color
let greenColor = UIColor(red: 10/255, green: 190/255, blue: 50/255, alpha: 1)
// create the attributed color
let attributedStringColor : NSDictionary = [NSForegroundColorAttributeName : greenColor];
// create the attributed string
let attributedString = NSAttributedString(string: "Hello World!", attributes: attributedStringColor as? [String : AnyObject])
// Set the label
label.attributedText = attributedString
Enjoy.
Access multiple viewchildren using @viewchild
Use @ViewChildren
from @angular/core
to get a reference to the components
template
<div *ngFor="let v of views">
<customcomponent #cmp></customcomponent>
</div>
component
import { ViewChildren, QueryList } from '@angular/core';
/** Get handle on cmp tags in the template */
@ViewChildren('cmp') components:QueryList<CustomComponent>;
ngAfterViewInit(){
// print array of CustomComponent objects
console.log(this.components.toArray());
}
l?i?v?e? ?d?e?m?o?
Handlebars.js Else If
The spirit of handlebars is that it is "logicless". Sometimes this makes us feel like we are fighting with it, and sometimes we end up with ugly nested if/else logic. You could write a helper; many people augment handlebars with a "better" conditional operator or believe that it should be part of the core. I think, though, that instead of this,
{{#if FriendStatus.IsFriend}}
<div class="ui-state-default ui-corner-all" title=".ui-icon-mail-closed"><span class="ui-icon ui-icon-mail-closed"></span></div>
{{else}}
{{#if FriendStatus.FriendRequested}}
<div class="ui-state-default ui-corner-all" title=".ui-icon-check"><span class="ui-icon ui-icon-check"></span></div>
{{else}}
<div class="ui-state-default ui-corner-all" title=".ui-icon-plusthick"><span class="ui-icon ui-icon-plusthick"></span></div>
{{/if}}
{{/if}}
you might want to arrange things in your model so that you can have this,
{{#if is_friend }}
<div class="ui-state-default ui-corner-all" title=".ui-icon-mail-closed"><span class="ui-icon ui-icon-mail-closed"></span></div>
{{/if}}
{{#if is_not_friend_yet }}
<div class="ui-state-default ui-corner-all" title=".ui-icon-check"><span class="ui-icon ui-icon-check"></span></div>
{{/if}}
{{#if will_never_be_my_friend }}
<div class="ui-state-default ui-corner-all" title=".ui-icon-plusthick"><span class="ui-icon ui-icon-plusthick"></span></div>
{{/if}}
Just make sure that only one of these flags is ever true. Chances are, if you are using this if/elsif/else
in your view, you are probably using it somewhere else too, so these variables might not end up being superfluous.
Keep it lean.
Spring JDBC Template for calling Stored Procedures
There are a number of ways to call stored procedures in Spring.
If you use CallableStatementCreator
to declare parameters, you will be using Java's standard interface of CallableStatement
, i.e register out parameters and set them separately. Using SqlParameter
abstraction will make your code cleaner.
I recommend you looking at SimpleJdbcCall
. It may be used like this:
SimpleJdbcCall jdbcCall = new SimpleJdbcCall(jdbcTemplate)
.withSchemaName(schema)
.withCatalogName(package)
.withProcedureName(procedure)();
...
jdbcCall.addDeclaredParameter(new SqlParameter(paramName, OracleTypes.NUMBER));
...
jdbcCall.execute(callParams);
For simple procedures you may use jdbcTemplate
's update
method:
jdbcTemplate.update("call SOME_PROC (?, ?)", param1, param2);
Differences between MySQL and SQL Server
Both are DBMS's Product Sql server is an commercial application while MySql is an opensouces application.Both the product include similar feature,however sql server should be used for an enterprise solution ,while mysql might suit a smaller implementation.if you need feature like recovery,replication,granalar security and significant,you need sql server
MySql takes up less spaces on disk, and uses less memory and cpu than does sql server
Returning JSON object as response in Spring Boot
More correct create DTO for API queries, for example entityDTO:
- Default response OK with list of entities:
@GetMapping(produces=MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.OK)
public List<EntityDto> getAll() {
return entityService.getAllEntities();
}
But if you need return different Map parameters you can use next two examples
2. For return one parameter like map:
@GetMapping(produces=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> getOneParameterMap() {
return ResponseEntity.status(HttpStatus.CREATED).body(
Collections.singletonMap("key", "value"));
}
- And if you need return map of some parameters(since Java 9):
@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> getSomeParameters() {
return ResponseEntity.status(HttpStatus.OK).body(Map.of(
"key-1", "value-1",
"key-2", "value-2",
"key-3", "value-3"));
}
C++ getters/setters coding style
Using a getter method is a better design choice for a long-lived class as it allows you to replace the getter method with something more complicated in the future. Although this seems less likely to be needed for a const value, the cost is low and the possible benefits are large.
As an aside, in C++, it's an especially good idea to give both the getter and setter for a member the same name, since in the future you can then actually change the the pair of methods:
class Foo {
public:
std::string const& name() const; // Getter
void name(std::string const& newName); // Setter
...
};
Into a single, public member variable that defines an operator()()
for each:
// This class encapsulates a fancier type of name
class fancy_name {
public:
// Getter
std::string const& operator()() const {
return _compute_fancy_name(); // Does some internal work
}
// Setter
void operator()(std::string const& newName) {
_set_fancy_name(newName); // Does some internal work
}
...
};
class Foo {
public:
fancy_name name;
...
};
The client code will need to be recompiled of course, but no syntax changes are required! Obviously, this transformation works just as well for const values, in which only a getter is needed.
ALTER TABLE DROP COLUMN failed because one or more objects access this column
You need to do a few things:
- You first need to check if the constrain exits in the information schema
- then you need to query by joining the sys.default_constraints and sys.columns
if the columns and default_constraints have the same object ids
- When you join in step 2, you would get the constraint name from default_constraints. You drop that constraint. Here is an example of one such drops I did.
-- 1. Remove constraint and drop column
IF EXISTS(SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = N'TABLE_NAME'
AND COLUMN_NAME = N'LOWER_LIMIT')
BEGIN
DECLARE @sql NVARCHAR(MAX)
WHILE 1=1
BEGIN
SELECT TOP 1 @sql = N'alter table [TABLE_NAME] drop constraint ['+dc.name+N']'
FROM sys.default_constraints dc
JOIN sys.columns c
ON c.default_object_id = dc.object_id
WHERE dc.parent_object_id = OBJECT_ID('[TABLE_NAME]') AND c.name = N'LOWER_LIMIT'
IF @@ROWCOUNT = 0
BEGIN
PRINT 'DELETED Constraint on column LOWER_LIMIT'
BREAK
END
EXEC (@sql)
END;
ALTER TABLE TABLE_NAME DROP COLUMN LOWER_LIMIT;
PRINT 'DELETED column LOWER_LIMIT'
END
ELSE
PRINT 'Column LOWER_LIMIT does not exist'
GO
How to transfer some data to another Fragment?
Complete code of passing data using fragment to fragment
Fragment fragment = new Fragment(); // replace your custom fragment class
Bundle bundle = new Bundle();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
bundle.putString("key","value"); // use as per your need
fragment.setArguments(bundle);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.replace(viewID,fragment);
fragmentTransaction.commit();
In custom fragment class
Bundle mBundle = new Bundle();
mBundle = getArguments();
mBundle.getString(key); // key must be same which was given in first fragment
How do I configure Apache 2 to run Perl CGI scripts?
There are two ways to handle CGI scripts, SetHandler
and AddHandler
.
SetHandler cgi-script
applies to all files in a given context, no matter how they are named, even index.html
or style.css
.
AddHandler cgi-script .pl
is similar, but applies to files ending in .pl
, in a given context. You may choose another extension or several, if you like.
Additionally, the CGI module must be loaded and Options +ExecCGI
configured. To activate the module, issue
a2enmod cgi
and restart or reload Apache. Finally, the Perl CGI script must be executable. So the execute bits must be set
chmod a+x script.pl
and it should start with
#! /usr/bin/perl
as its first line.
When you use SetHandler
or AddHandler
(and Options +ExecCGI
) outside of any directive, it is applied globally to all files. But you may restrict the context to a subset by enclosing these directives inside, e.g. Directory
<Directory /path/to/some/cgi-dir>
SetHandler cgi-script
Options +ExecCGI
</Directory>
Now SetHandler
applies only to the files inside /path/to/some/cgi-dir instead of all files of the web site. Same is with AddHandler
inside a Directory
or Location
directive, of course. It then applies to the files inside /path/to/some/cgi-dir, ending in .pl
.
Convert serial.read() into a useable string using Arduino?
From Help with Serial.Read() getting string:
char inData[20]; // Allocate some space for the string
char inChar=-1; // Where to store the character read
byte index = 0; // Index into array; where to store the character
void setup() {
Serial.begin(9600);
Serial.write("Power On");
}
char Comp(char* This) {
while (Serial.available() > 0) // Don't read unless
// there you know there is data
{
if(index < 19) // One less than the size of the array
{
inChar = Serial.read(); // Read a character
inData[index] = inChar; // Store it
index++; // Increment where to write next
inData[index] = '\0'; // Null terminate the string
}
}
if (strcmp(inData,This) == 0) {
for (int i=0;i<19;i++) {
inData[i]=0;
}
index=0;
return(0);
}
else {
return(1);
}
}
void loop()
{
if (Comp("m1 on")==0) {
Serial.write("Motor 1 -> Online\n");
}
if (Comp("m1 off")==0) {
Serial.write("Motor 1 -> Offline\n");
}
}
How to stop a goroutine
EDIT: I wrote this answer up in haste, before realizing that your question is about sending values to a chan inside a goroutine. The approach below can be used either with an additional chan as suggested above, or using the fact that the chan you have already is bi-directional, you can use just the one...
If your goroutine exists solely to process the items coming out of the chan, you can make use of the "close" builtin and the special receive form for channels.
That is, once you're done sending items on the chan, you close it. Then inside your goroutine you get an extra parameter to the receive operator that shows whether the channel has been closed.
Here is a complete example (the waitgroup is used to make sure that the process continues until the goroutine completes):
package main
import "sync"
func main() {
var wg sync.WaitGroup
wg.Add(1)
ch := make(chan int)
go func() {
for {
foo, ok := <- ch
if !ok {
println("done")
wg.Done()
return
}
println(foo)
}
}()
ch <- 1
ch <- 2
ch <- 3
close(ch)
wg.Wait()
}
How to increase Maximum Upload size in cPanel?
The solution is to create the php.ini file under your root directory. If the site is the wordpress installation then create the php.ini under your/path/to/wordpress/wp-admin/php.ini and add the following line of codes
[PHP]
post_max_size=120M
upload_max_filesize=132M