How to tell if a <script> tag failed to load
The script from Erwinus works great, but isn't very clearly coded. I took the liberty to clean it up and decipher what it was doing. I've made these changes:
- Meaningful variable names
- Use of
prototype
.
require()
uses an argument variable
- No
alert()
messages are returned by default
- Fixed some syntax errors and scope issues I was getting
Thanks again to Erwinus, the functionality itself is spot on.
function ScriptLoader() {
}
ScriptLoader.prototype = {
timer: function (times, // number of times to try
delay, // delay per try
delayMore, // extra delay per try (additional to delay)
test, // called each try, timer stops if this returns true
failure, // called on failure
result // used internally, shouldn't be passed
) {
var me = this;
if (times == -1 || times > 0) {
setTimeout(function () {
result = (test()) ? 1 : 0;
me.timer((result) ? 0 : (times > 0) ? --times : times, delay + ((delayMore) ? delayMore : 0), delayMore, test, failure, result);
}, (result || delay < 0) ? 0.1 : delay);
} else if (typeof failure == 'function') {
setTimeout(failure, 1);
}
},
addEvent: function (el, eventName, eventFunc) {
if (typeof el != 'object') {
return false;
}
if (el.addEventListener) {
el.addEventListener(eventName, eventFunc, false);
return true;
}
if (el.attachEvent) {
el.attachEvent("on" + eventName, eventFunc);
return true;
}
return false;
},
// add script to dom
require: function (url, args) {
var me = this;
args = args || {};
var scriptTag = document.createElement('script');
var headTag = document.getElementsByTagName('head')[0];
if (!headTag) {
return false;
}
setTimeout(function () {
var f = (typeof args.success == 'function') ? args.success : function () {
};
args.failure = (typeof args.failure == 'function') ? args.failure : function () {
};
var fail = function () {
if (!scriptTag.__es) {
scriptTag.__es = true;
scriptTag.id = 'failed';
args.failure(scriptTag);
}
};
scriptTag.onload = function () {
scriptTag.id = 'loaded';
f(scriptTag);
};
scriptTag.type = 'text/javascript';
scriptTag.async = (typeof args.async == 'boolean') ? args.async : false;
scriptTag.charset = 'utf-8';
me.__es = false;
me.addEvent(scriptTag, 'error', fail); // when supported
// when error event is not supported fall back to timer
me.timer(15, 1000, 0, function () {
return (scriptTag.id == 'loaded');
}, function () {
if (scriptTag.id != 'loaded') {
fail();
}
});
scriptTag.src = url;
setTimeout(function () {
try {
headTag.appendChild(scriptTag);
} catch (e) {
fail();
}
}, 1);
}, (typeof args.delay == 'number') ? args.delay : 1);
return true;
}
};
$(document).ready(function () {
var loader = new ScriptLoader();
loader.require('resources/templates.js', {
async: true, success: function () {
alert('loaded');
}, failure: function () {
alert('NOT loaded');
}
});
});
HTML/Javascript: how to access JSON data loaded in a script tag with src set
While it's not currently possible with the script
tag, it is possible with an iframe
if it's from the same domain.
<iframe
id="mySpecialId"
src="/my/link/to/some.json"
onload="(()=>{if(!window.jsonData){window.jsonData={}}try{window.jsonData[this.id]=JSON.parse(this.contentWindow.document.body.textContent.trim())}catch(e){console.warn(e)}this.remove();})();"
onerror="((err)=>console.warn(err))();"
style="display: none;"
></iframe>
To use the above, simply replace the id
and src
attribute with what you need. The id
(which we'll assume in this situation is equal to mySpecialId
) will be used to store the data in window.jsonData["mySpecialId"]
.
In other words, for every iframe that has an id
and uses the onload
script will have that data synchronously loaded into the window.jsonData
object under the id
specified.
I did this for fun and to show that it's "possible' but I do not recommend that it be used.
Here is an alternative that uses a callback instead.
<script>
function someCallback(data){
/** do something with data */
console.log(data);
}
function jsonOnLoad(callback){
const raw = this.contentWindow.document.body.textContent.trim();
try {
const data = JSON.parse(raw);
/** do something with data */
callback(data);
}catch(e){
console.warn(e.message);
}
this.remove();
}
</script>
<!-- I frame with src pointing to json file on server, onload we apply "this" to have the iframe context, display none as we don't want to show the iframe -->
<iframe src="your/link/to/some.json" onload="jsonOnLoad.apply(this, someCallback)" style="display: none;"></iframe>
Tested in chrome and should work in firefox. Unsure about IE or Safari.
How to force a script reload and re-execute?
Use this function to find all script elements containing some word and refresh them.
_x000D_
_x000D_
function forceReloadJS(srcUrlContains) {_x000D_
$.each($('script:empty[src*="' + srcUrlContains + '"]'), function(index, el) {_x000D_
var oldSrc = $(el).attr('src');_x000D_
var t = +new Date();_x000D_
var newSrc = oldSrc + '?' + t;_x000D_
_x000D_
console.log(oldSrc, ' to ', newSrc);_x000D_
_x000D_
$(el).remove();_x000D_
$('<script/>').attr('src', newSrc).appendTo('head');_x000D_
});_x000D_
}_x000D_
_x000D_
forceReloadJS('/libs/');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
_x000D_
_x000D_
_x000D_
How to dynamically insert a <script> tag via jQuery after page load?
Here's the correct way to do it with modern (2014) JQuery:
$(function () {
$('<script>')
.attr('type', 'text/javascript')
.text('some script here')
.appendTo('head');
})
or if you really want to replace a div you could do:
$(function () {
$('<script>')
.attr('type', 'text/javascript')
.text('some script here')
.replaceAll('#someelement');
});
How to pass parameters to a Script tag?
Another way is to use meta tags. Whatever data is supposed to be passed to your JavaScript can be assigned like this:
<meta name="yourdata" content="whatever" />
<meta name="moredata" content="more of this" />
The data can then be pulled from the meta tags like this (best done in a DOMContentLoaded event handler):
var data1 = document.getElementsByName('yourdata')[0].content;
var data2 = document.getElementsByName('moredata')[0].content;
Absolutely no hassle with jQuery or the likes, no hacks and workarounds necessary, and works with any HTML version that supports meta tags...
Getting path relative to the current working directory?
If you don't mind the slashes being switched, you could [ab]use Uri
:
Uri file = new Uri(@"c:\foo\bar\blop\blap.txt");
// Must end in a slash to indicate folder
Uri folder = new Uri(@"c:\foo\bar\");
string relativePath =
Uri.UnescapeDataString(
folder.MakeRelativeUri(file)
.ToString()
.Replace('/', Path.DirectorySeparatorChar)
);
As a function/method:
string GetRelativePath(string filespec, string folder)
{
Uri pathUri = new Uri(filespec);
// Folders must end in a slash
if (!folder.EndsWith(Path.DirectorySeparatorChar.ToString()))
{
folder += Path.DirectorySeparatorChar;
}
Uri folderUri = new Uri(folder);
return Uri.UnescapeDataString(folderUri.MakeRelativeUri(pathUri).ToString().Replace('/', Path.DirectorySeparatorChar));
}
How many characters in varchar(max)
From http://msdn.microsoft.com/en-us/library/ms176089.aspx
varchar [ ( n | max ) ]
Variable-length, non-Unicode character
data. n can be a value from 1 through
8,000. max indicates that the maximum
storage size is 2^31-1 bytes. The
storage size is the actual length of
data entered + 2 bytes. The data
entered can be 0 characters in length.
The ISO synonyms for varchar are char
varying or character varying.
1 character = 1 byte. And don't forget 2 bytes for the termination. So, 2^31-3 characters.
fetch gives an empty response body
This requires changes to the frontend JS and the headers sent from the backend.
Frontend
Remove "mode":"no-cors"
in the fetch options.
fetch(
"http://example.com/api/docs",
{
// mode: "no-cors",
method: "GET"
}
)
.then(response => response.text())
.then(data => console.log(data))
Backend
When your server responds to the request, include the CORS headers specifying the origin from where the request is coming. If you don't care about the origin, specify the *
wildcard.
The raw response should include a header like this.
Access-Control-Allow-Origin: *
Removing "http://" from a string
preg_replace('/^[^:\/?]+:\/\//','',$url);
some results:
input: http://php.net/preg_replace output: php.net/preg_replace input: https://www.php.net/preg_replace output: www.php.net/preg_replace input: ftp://www.php.net/preg_replace output: www.php.net/preg_replace input: https://php.net/preg_replace?url=http://whatever.com output: php.net/preg_replace?url=http://whatever.com input: php.net/preg_replace?url=http://whatever.com output: php.net/preg_replace?url=http://whatever.com input: php.net?site=http://whatever.com output: php.net?site=http://whatever.com
Const in JavaScript: when to use it and is it necessary?
I am not an expert in the JS compiling business, but it makes sense to say, that v8 makes use from the const flag
Normally a after declaring and changing a bunch of variables, the memory gets fragmented, and v8 is stopping to execute, makes a pause some time of a few seconds, to make gc, or garbage collection.
if a variable is declared with const v8 can be confident to put it in a tight fixed size container between other const variables, since it will never change.
It can also save the proper operations for that datatypes since the type will not change.
Spring boot - Not a managed type
In my case the problem was due to my forgetting to have annotated my Entity classes with @javax.persistence.Entity
annotation. Doh!
//The class reported as "not a amanaged type"
@javax.persistence.Entity
public class MyEntityClass extends my.base.EntityClass {
....
}
How can I pass selected row to commandLink inside dataTable or ui:repeat?
As to the cause, the <f:attribute>
is specific to the component itself (populated during view build time), not to the iterated row (populated during view render time).
There are several ways to achieve the requirement.
If your servletcontainer supports a minimum of Servlet 3.0 / EL 2.2, then just pass it as an argument of action/listener method of UICommand
component or AjaxBehavior
tag. E.g.
<h:commandLink action="#{bean.insert(item.id)}" value="insert" />
In combination with:
public void insert(Long id) {
// ...
}
This only requires that the datamodel is preserved for the form submit request. Best is to put the bean in the view scope by @ViewScoped
.
You can even pass the entire item object:
<h:commandLink action="#{bean.insert(item)}" value="insert" />
with:
public void insert(Item item) {
// ...
}
On Servlet 2.5 containers, this is also possible if you supply an EL implementation which supports this, like as JBoss EL. For configuration detail, see this answer.
Use <f:param>
in UICommand
component. It adds a request parameter.
<h:commandLink action="#{bean.insert}" value="insert">
<f:param name="id" value="#{item.id}" />
</h:commandLink>
If your bean is request scoped, let JSF set it by @ManagedProperty
@ManagedProperty(value="#{param.id}")
private Long id; // +setter
Or if your bean has a broader scope or if you want more fine grained validation/conversion, use <f:viewParam>
on the target view, see also f:viewParam vs @ManagedProperty:
<f:viewParam name="id" value="#{bean.id}" required="true" />
Either way, this has the advantage that the datamodel doesn't necessarily need to be preserved for the form submit (for the case that your bean is request scoped).
Use <f:setPropertyActionListener>
in UICommand
component. The advantage is that this removes the need for accessing the request parameter map when the bean has a broader scope than the request scope.
<h:commandLink action="#{bean.insert}" value="insert">
<f:setPropertyActionListener target="#{bean.id}" value="#{item.id}" />
</h:commandLink>
In combination with
private Long id; // +setter
It'll be just available by property id
in action method. This only requires that the datamodel is preserved for the form submit request. Best is to put the bean in the view scope by @ViewScoped
.
Bind the datatable value to DataModel<E>
instead which in turn wraps the items.
<h:dataTable value="#{bean.model}" var="item">
with
private transient DataModel<Item> model;
public DataModel<Item> getModel() {
if (model == null) {
model = new ListDataModel<Item>(items);
}
return model;
}
(making it transient
and lazily instantiating it in the getter is mandatory when you're using this on a view or session scoped bean since DataModel
doesn't implement Serializable
)
Then you'll be able to access the current row by DataModel#getRowData()
without passing anything around (JSF determines the row based on the request parameter name of the clicked command link/button).
public void insert() {
Item item = model.getRowData();
Long id = item.getId();
// ...
}
This also requires that the datamodel is preserved for the form submit request. Best is to put the bean in the view scope by @ViewScoped
.
Use Application#evaluateExpressionGet()
to programmatically evaluate the current #{item}
.
public void insert() {
FacesContext context = FacesContext.getCurrentInstance();
Item item = context.getApplication().evaluateExpressionGet(context, "#{item}", Item.class);
Long id = item.getId();
// ...
}
Which way to choose depends on the functional requirements and whether the one or the other offers more advantages for other purposes. I personally would go ahead with #1 or, when you'd like to support servlet 2.5 containers as well, with #2.
What is the proof of of (N–1) + (N–2) + (N–3) + ... + 1= N*(N–1)/2
Start with the triangle...
*
**
***
****
representing 1+2+3+4 so far. Cut the triangle in half along one dimension...
*
**
* **
** **
Rotate the smaller part 180 degrees, and stick it on top of the bigger part...
**
*
*
**
**
**
Close the gap to get a rectangle.
At first sight this only works if the base of the rectangle has an even length - but if it has an odd length, you just cut the middle column in half - it still works with a half-unit-wide twice-as-tall (still integer area) strip on one side of your rectangle.
Whatever the base of the triangle, the width of your rectangle is (base / 2)
and the height is (base + 1)
, giving ((base + 1) * base) / 2
.
However, my base
is your n-1
, since the bubble sort compares a pair of items at a time, and therefore iterates over only (n-1) positions for the first loop.
display html page with node.js
This did the trick for me:
var express = require('express'),
app = express();
app.use('/', express.static(__dirname + '/'));
app.listen(8080);
How do you split and unsplit a window/view in Eclipse IDE?
This is possible with the menu items Window>Editor>Toggle Split Editor.
Current shortcut for splitting is:
Azerty keyboard:
- Ctrl + _ for split horizontally, and
- Ctrl + { for split vertically.
Qwerty US keyboard:
- Ctrl + Shift + - (accessing _) for split horizontally, and
- Ctrl + Shift + [ (accessing {) for split vertically.
MacOS - Qwerty US keyboard:
- ⌘ + Shift + - (accessing _) for split horizontally, and
- ⌘ + Shift + [ (accessing {) for split vertically.
On any other keyboard if a required key is unavailable (like { on a german Qwertz keyboard), the following generic approach may work:
- Alt + ASCII code + Ctrl then release Alt
Example: ASCII for '{' = 123, so press 'Alt', '1', '2', '3', 'Ctrl' and release 'Alt', effectively typing '{' while 'Ctrl' is pressed, to split vertically.
Example of vertical split:
PS:
- The menu items Window>Editor>Toggle Split Editor were added with Eclipse Luna 4.4 M4, as mentioned by Lars Vogel in "Split editor implemented in Eclipse M4 Luna"
- The split editor is one of the oldest and most upvoted Eclipse bug! Bug 8009
- The split editor functionality has been developed in Bug 378298, and will be available as of Eclipse Luna M4. The Note & Newsworthy of Eclipse Luna M4 will contain the announcement.
what is trailing whitespace and how can I handle this?
This is just a warning and it doesn't make problem for your project to run, you can just ignore it and continue coding.
But if you're obsessed about clean coding, same as me, you have two options:
- Hover the mouse on warning in VS Code or any IDE and use quick fix to remove white spaces.
- Press
f1
then type trim trailing whitespace
.
What are metaclasses in Python?
Python 3 update
There are (at this point) two key methods in a metaclass:
__prepare__
lets you supply a custom mapping (such as an OrderedDict
) to be used as the namespace while the class is being created. You must return an instance of whatever namespace you choose. If you don't implement __prepare__
a normal dict
is used.
__new__
is responsible for the actual creation/modification of the final class.
A bare-bones, do-nothing-extra metaclass would like:
class Meta(type):
def __prepare__(metaclass, cls, bases):
return dict()
def __new__(metacls, cls, bases, clsdict):
return super().__new__(metacls, cls, bases, clsdict)
A simple example:
Say you want some simple validation code to run on your attributes -- like it must always be an int
or a str
. Without a metaclass, your class would look something like:
class Person:
weight = ValidateType('weight', int)
age = ValidateType('age', int)
name = ValidateType('name', str)
As you can see, you have to repeat the name of the attribute twice. This makes typos possible along with irritating bugs.
A simple metaclass can address that problem:
class Person(metaclass=Validator):
weight = ValidateType(int)
age = ValidateType(int)
name = ValidateType(str)
This is what the metaclass would look like (not using __prepare__
since it is not needed):
class Validator(type):
def __new__(metacls, cls, bases, clsdict):
# search clsdict looking for ValidateType descriptors
for name, attr in clsdict.items():
if isinstance(attr, ValidateType):
attr.name = name
attr.attr = '_' + name
# create final class and return it
return super().__new__(metacls, cls, bases, clsdict)
A sample run of:
p = Person()
p.weight = 9
print(p.weight)
p.weight = '9'
produces:
9
Traceback (most recent call last):
File "simple_meta.py", line 36, in <module>
p.weight = '9'
File "simple_meta.py", line 24, in __set__
(self.name, self.type, value))
TypeError: weight must be of type(s) <class 'int'> (got '9')
Note: This example is simple enough it could have also been accomplished with a class decorator, but presumably an actual metaclass would be doing much more.
The 'ValidateType' class for reference:
class ValidateType:
def __init__(self, type):
self.name = None # will be set by metaclass
self.attr = None # will be set by metaclass
self.type = type
def __get__(self, inst, cls):
if inst is None:
return self
else:
return inst.__dict__[self.attr]
def __set__(self, inst, value):
if not isinstance(value, self.type):
raise TypeError('%s must be of type(s) %s (got %r)' %
(self.name, self.type, value))
else:
inst.__dict__[self.attr] = value
How to maximize a plt.show() window using Python
Here is a function based on @Pythonio's answer. I encapsulate it into a function that automatically detects which backend is it using and do the corresponding actions.
def plt_set_fullscreen():
backend = str(plt.get_backend())
mgr = plt.get_current_fig_manager()
if backend == 'TkAgg':
if os.name == 'nt':
mgr.window.state('zoomed')
else:
mgr.resize(*mgr.window.maxsize())
elif backend == 'wxAgg':
mgr.frame.Maximize(True)
elif backend == 'Qt4Agg':
mgr.window.showMaximized()
How to pre-populate the sms body text via an html link
Neither Android nor iPhones currently support the body copy element in a Tap to SMS hyperlink.
It can be done programmatically though,
MFMessageComposeViewController *picker = [[MFMessageComposeViewController alloc] init];
picker.messageComposeDelegate = self;
picker.recipients = [NSArray arrayWithObject:@"48151623"];
picker.body = @"Body text.";
[self presentModalViewController:picker animated:YES];
[picker release];
Kill all processes for a given user
Just (temporarily) killed my Macbook with
killall -u pu -m .
where pu is my userid. Watch the dot at the end of the command.
Also try
pkill -u pu
or
ps -o pid -u pu | xargs kill -1
Get top 1 row of each group
It is checked in SQLite that you can use the following simple query with GROUP BY
SELECT MAX(DateCreated), *
FROM DocumentStatusLogs
GROUP BY DocumentID
Here MAX help to get the maximum DateCreated FROM each group.
But it seems that MYSQL doesn't associate *-columns with the value of max DateCreated :(
How to remove all subviews of a view in Swift?
For iOS/Swift, to get rid of all subviews I use:
for v in view.subviews{
v.removeFromSuperview()
}
to get rid of all subviews of a particular class (like UILabel) I use:
for v in view.subviews{
if v is UILabel{
v.removeFromSuperview()
}
}
XML Carriage return encoding
xml:space="preserve"
has to work for all compliant XML parsers.
However, note that in HTML the line break is just whitespace and NOT a line break (this is represented with the <br />
(X)HTML tag, maybe this is the problem which you are facing.
You can also add
and/or
to insert CR/LF characters.
Does WGET timeout?
According to the man page of wget, there are a couple of options related to timeouts -- and there is a default read timeout of 900s -- so I say that, yes, it could timeout.
Here are the options in question :
-T seconds
--timeout=seconds
Set the network timeout to seconds
seconds. This is equivalent to
specifying --dns-timeout
,
--connect-timeout
, and
--read-timeout
, all at the same
time.
And for those three options :
--dns-timeout=seconds
Set the DNS lookup timeout to seconds
seconds.
DNS lookups that don't
complete within the specified time
will fail.
By default, there is no
timeout on DNS lookups, other than
that implemented by system libraries.
--connect-timeout=seconds
Set the connect timeout to seconds
seconds.
TCP connections that take
longer to establish will be aborted.
By default, there is no connect
timeout, other than that implemented
by system libraries.
--read-timeout=seconds
Set the read (and write) timeout to
seconds seconds.
The "time" of
this timeout refers to idle time: if,
at any point in the download, no data
is received for more than the
specified number of seconds, reading
fails and the download is restarted.
This option does not directly
affect the duration of the entire
download.
I suppose using something like
wget -O - -q -t 1 --timeout=600 http://www.example.com/cron/run
should make sure there is no timeout before longer than the duration of your script.
(Yeah, that's probably the most brutal solution possible ^^ )
Error during installing HAXM, VT-X not working
If your emulators were working and now they aren't due to Avast...
Avast no longer has the option for "Enable Hardware-assisted Virtualization" in Troubleshooting. (it's now March 2017)
Avast captures "emulator.exe", which disables emulators,and stows it in the Virus chest. Open the chest, "Restore and add to exclusions" and your emulator works again...
How do I set the rounded corner radius of a color drawable using xml?
Try below code
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners
android:bottomLeftRadius="30dp"
android:bottomRightRadius="30dp"
android:topLeftRadius="30dp"
android:topRightRadius="30dp" />
<solid android:color="#1271BB" />
<stroke
android:width="5dp"
android:color="#1271BB" />
<padding
android:bottom="1dp"
android:left="1dp"
android:right="1dp"
android:top="1dp" /></shape>
Creating a generic method in C#
What if you specified the default value to return, instead of using default(T)?
public static T GetQueryString<T>(string key, T defaultValue) {...}
It makes calling it easier too:
var intValue = GetQueryString("intParm", Int32.MinValue);
var strValue = GetQueryString("strParm", "");
var dtmValue = GetQueryString("dtmPatm", DateTime.Now); // eg use today's date if not specified
The downside being you need magic values to denote invalid/missing querystring values.
jQuery - replace all instances of a character in a string
RegEx is the way to go in most cases.
In some cases, it may be faster to specify more elements or the specific element to perform the replace on:
$(document).ready(function () {
$('.myclass').each(function () {
$('img').each(function () {
$(this).attr('src', $(this).attr('src').replace('_s.jpg', '_n.jpg'));
})
})
});
This does the replace once on each string, but it does it using a more specific selector.
How to perform keystroke inside powershell?
function Do-SendKeys {
param (
$SENDKEYS,
$WINDOWTITLE
)
$wshell = New-Object -ComObject wscript.shell;
IF ($WINDOWTITLE) {$wshell.AppActivate($WINDOWTITLE)}
Sleep 1
IF ($SENDKEYS) {$wshell.SendKeys($SENDKEYS)}
}
Do-SendKeys -WINDOWTITLE Print -SENDKEYS '{TAB}{TAB}'
Do-SendKeys -WINDOWTITLE Print
Do-SendKeys -SENDKEYS '%{f4}'
More Pythonic Way to Run a Process X Times
The for loop is definitely more pythonic, as it uses Python's higher level built in functionality to convey what you're doing both more clearly and concisely. The overhead of range vs xrange, and assigning an unused i
variable, stem from the absence of a statement like Verilog's repeat
statement. The main reason to stick to the for range solution is that other ways are more complex. For instance:
from itertools import repeat
for unused in repeat(None, 10):
del unused # redundant and inefficient, the name is clear enough
print "This is run 10 times"
Using repeat instead of range here is less clear because it's not as well known a function, and more complex because you need to import it. The main style guides if you need a reference are PEP 20 - The Zen of Python and PEP 8 - Style Guide for Python Code.
We also note that the for range version is an explicit example used in both the language reference and tutorial, although in that case the value is used. It does mean the form is bound to be more familiar than the while expansion of a C-style for loop.
How to compare two java objects
You need to implement the equals() method in your MyClass
.
The reason that ==
didn't work is this is checking that they refer to the same instance. Since you did new
for each, each one is a different instance.
The reason that equals()
didn't work is because you didn't implement it yourself yet. I believe it's default behavior is the same thing as ==
.
Note that you should also implement hashcode()
if you're going to implement equals()
because a lot of java.util Collections expect that.
Where does one get the "sys/socket.h" header/source file?
Since you've labeled the question C++, you might be interested in using boost::asio, ACE, or some other cross-platform socket library for C++ or for C. Some other cross-platform libraries may be found in the answers to C++ sockets library for cross-platform and Cross platform Networking API.
Assuming that using a third party cross-platform sockets library is not an option for you...
The header <sys/socket.h> is defined in IEEE Std. 1003.1 (POSIX), but sadly Windows is non-compliant with the POSIX standard. The MinGW compiler is a port of GCC for compiling Windows applications, and therefore does not include these POSIX system headers. If you install GCC using Cygwin, then it will include these system headers to emulate a POSIX environment on Windows. Be aware, however, that if you use Cygwin for sockets that a.) you will need to put the cygwin DLL in a place where your application can read it and b.) Cygwin headers and Windows headers don't interact very well (so if you plan on including windows.h
, then you probably don't want to be including sys/socket.h
).
My personal recommendation would be to download a copy of VirtualBox, download a copy of Ubuntu, install Ubuntu into VirtualBox, and then do your coding and testing on Ubuntu. Alternatively, I am told that Microsoft sells a "UNIX subsystem" and that it is pre-installed on certain higher-end editions of Windows, although I have no idea how compliant this system is (and, if it is compliant, with which edition of the UNIX standard it is compliant). Winsockets are also an option, although they can behave in subtly different ways than their POSIX counterparts, even though the signatures may be similar.
Prevent text selection after double click
FWIW, I set user-select: none
to the parent element of those child elements that I don't want somehow selected when double clicking anywhere on the parent element. And it works! Cool thing is contenteditable="true"
, text selection and etc. still works on the child elements!
So like:
<div style="user-select: none">
<p>haha</p>
<p>haha</p>
<p>haha</p>
<p>haha</p>
</div>
Load a UIView from nib in Swift
My contribution:
extension UIView {
class func fromNib<T: UIView>() -> T {
return Bundle(for: T.self).loadNibNamed(String(describing: T.self), owner: nil, options: nil)![0] as! T
}
}
Then call it like this:
let myCustomView: CustomView = UIView.fromNib()
..or even:
let myCustomView: CustomView = .fromNib()
Which sort algorithm works best on mostly sorted data?
Splaysort is an obscure sorting method based on splay trees, a type of adaptive binary tree. Splaysort is good not only for partially sorted data, but also partially reverse-sorted data, or indeed any data that has any kind of pre-existing order. It is O(nlogn) in the general case, and O(n) in the case where the data is sorted in some way (forward, reverse, organ-pipe, etc.).
Its great advantage over insertion sort is that it doesn't revert to O(n^2) behaviour when the data isn't sorted at all, so you don't need to be absolutely sure that the data is partially sorted before using it.
Its disadvantage is the extra space overhead of the splay tree structure it needs, as well as the time required to build and destroy the splay tree. But depending on the size of data and amount of pre-sortedness that you expect, the overhead may be worth it for the increase in speed.
A paper on splaysort was published in Software--Practice & Experience.
jQuery animate margin top
use 'marginTop'
instead of MarginTop
$(this).find('.info').animate({ 'marginTop': '-50px', opacity: 0.5 }, 1000);
Which is faster: multiple single INSERTs or one multiple-row INSERT?
A major factor will be whether you're using a transactional engine and whether you have autocommit on.
Autocommit is on by default and you probably want to leave it on; therefore, each insert that you do does its own transaction. This means that if you do one insert per row, you're going to be committing a transaction for each row.
Assuming a single thread, that means that the server needs to sync some data to disc for EVERY ROW. It needs to wait for the data to reach a persistent storage location (hopefully the battery-backed ram in your RAID controller). This is inherently rather slow and will probably become the limiting factor in these cases.
I'm of course assuming that you're using a transactional engine (usually innodb) AND that you haven't tweaked the settings to reduce durability.
I'm also assuming that you're using a single thread to do these inserts. Using multiple threads muddies things a bit because some versions of MySQL have working group-commit in innodb - this means that multiple threads doing their own commits can share a single write to the transaction log, which is good because it means fewer syncs to persistent storage.
On the other hand, the upshot is, that you REALLY WANT TO USE multi-row inserts.
There is a limit over which it gets counter-productive, but in most cases it's at least 10,000 rows. So if you batch them up to 1,000 rows, you're probably safe.
If you're using MyISAM, there's a whole other load of things, but I'll not bore you with those. Peace.
what is the basic difference between stack and queue?
STACK is a LIFO (last in, first out) list. means suppose 3 elements are inserted in stack i.e 10,20,30.
10 is inserted first & 30 is inserted last so 30 is first deleted from stack & 10 is last
deleted from stack.this is an LIFO list(Last In First Out).
QUEUE is FIFO list(First In First Out).means one element is inserted first which is to be
deleted first.e.g queue of peoples.
What does "javascript:void(0)" mean?
It's worth mentioning that you'll sometimes see void 0
when checking for undefined, simply because it requires fewer characters.
For example:
if (something === undefined) {
doSomething();
}
Compared to:
if (something === void 0) {
doSomething();
}
Some minification methods replace undefined
with void 0
for this reason.
Are iframes considered 'bad practice'?
The original frameset model (Frameset and Frame-elements) were very bad from a usability standpoint. IFrame vas a later invention which didn't have as many problems as the original frameset model, but it does have its drawback.
If you allow the user to navigate inside the IFrame, then links and bookmarks will not work as expected (because you bookmark the URL of the outer page, but not the URL of the iframe).
How to convert a date to milliseconds
You don't have a Date
, you have a String
representation of a date. You should convert the String
into a Date
and then obtain the milliseconds. To convert a String
into a Date
and vice versa you should use SimpleDateFormat
class.
Here's an example of what you want/need to do (assuming time zone is not involved here):
String myDate = "2014/10/29 18:10:45";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = sdf.parse(myDate);
long millis = date.getTime();
Still, be careful because in Java the milliseconds obtained are the milliseconds between the desired epoch and 1970-01-01 00:00:00.
Using the new Date/Time API available since Java 8:
String myDate = "2014/10/29 18:10:45";
LocalDateTime localDateTime = LocalDateTime.parse(myDate,
DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss") );
/*
With this new Date/Time API, when using a date, you need to
specify the Zone where the date/time will be used. For your case,
seems that you want/need to use the default zone of your system.
Check which zone you need to use for specific behaviour e.g.
CET or America/Lima
*/
long millis = localDateTime
.atZone(ZoneId.systemDefault())
.toInstant().toEpochMilli();
Ruby, remove last N characters from a string?
if you are using rails, try:
"my_string".last(2) # => "ng"
[EDITED]
To get the string WITHOUT the last 2 chars:
n = "my_string".size
"my_string"[0..n-3] # => "my_stri"
Note: the last string char is at n-1. So, to remove the last 2, we use n-3.
How do you debug PHP scripts?
Komodo IDE works well with xdebug, even for the remore debugging. It needs minimum amount of configuration. All you need is a version of php that Komodo can use locally to step through the code on a breakpoint. If you have the script imported into komodo project, then you can set breakpoints with a mouse-click just how you would set it inside eclipse for debugging a java program.
Remote debugging is obviously more tricky to get it to work correctly ( you might have to map the remote url with a php script in your workspace ) than a local debugging setup which is pretty easy to configure if you are on a MAC or a linux desktop.
Shortcuts in Objective-C to concatenate NSStrings
You can use NSArray as
NSString *string1=@"This"
NSString *string2=@"is just"
NSString *string3=@"a test"
NSArray *myStrings = [[NSArray alloc] initWithObjects:string1, string2, string3,nil];
NSString *fullLengthString = [myStrings componentsJoinedByString:@" "];
or
you can use
NSString *imageFullName=[NSString stringWithFormat:@"%@ %@ %@.", string1,string2,string3];
Simple dynamic breadcrumb
use parse_url
and then output the result in a loop:
$urlinfo = parse_url($the_url);
echo makelink($urlinfo['hostname']);
foreach($breadcrumb in $urlinfo['path']) {
echo makelink($breadcrumb);
}
function makelink($str) {
return '<a href="'.urlencode($str).'" title="'.htmlspecialchars($str).'">'.htmlspecialchars($str).'</a>';
}
(pseudocode)
How can I start and check my MySQL log?
Enable general query log by the following query in mysql command line
SET GLOBAL general_log = 'ON';
Now open C:/xampp/mysql/data/mysql.log
and check query log
If it fails, open your my.cnf
file. For windows its my.ini
file and enable it there. Just make sure its in the [mysqld]
section
[mysqld]
general_log = 1
Note: In xampp my.ini
file can be either found in xampp\mysql
or in c:\windows
directory
How to succinctly write a formula with many variables from a data frame?
An extension of juba's method is to use reformulate
, a function which is explicitly designed for such a task.
## Create a formula for a model with a large number of variables:
xnam <- paste("x", 1:25, sep="")
reformulate(xnam, "y")
y ~ x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 + x10 + x11 +
x12 + x13 + x14 + x15 + x16 + x17 + x18 + x19 + x20 + x21 +
x22 + x23 + x24 + x25
For the example in the OP, the easiest solution here would be
# add y variable to data.frame d
d <- cbind(y, d)
reformulate(names(d)[-1], names(d[1]))
y ~ x1 + x2 + x3
or
mod <- lm(reformulate(names(d)[-1], names(d[1])), data=d)
Note that adding the dependent variable to the data.frame in d <- cbind(y, d)
is preferred not only because it allows for the use of reformulate
, but also because it allows for future use of the lm
object in functions like predict
.
Jquery resizing image
Modifying Aleksandar's answer to make it as jquery plugin and accepts maxwidth and maxheight as arguments, suggested by Nathan.
$.fn.resize = function(maxWidth,maxHeight) {
return this.each(function() {
var ratio = 0;
var width = $(this).width();
var height = $(this).height();
if(width > maxWidth){
ratio = maxWidth / width;
$(this).css("width", maxWidth);
$(this).css("height", height * ratio);
height = height * ratio;
}
var width = $(this).width();
var height = $(this).height();
if(height > maxHeight){
ratio = maxHeight / height;
$(this).css("height", maxHeight);
$(this).css("width", width * ratio);
width = width * ratio;
}
});
};
Used as $('.imgClass').resize(300,50);
Smooth scrolling with just pure css
You can do this with pure CSS but you will need to hard code the offset scroll amounts, which may not be ideal should you be changing page content- or should dimensions of your content change on say window resize.
You're likely best placed to use e.g. jQuery, specifically:
$('html, body').stop().animate({
scrollTop: element.offset().top
}, 1000);
A complete implementation may be:
$('#up, #down').on('click', function(e){
e.preventDefault();
var target= $(this).get(0).id == 'up' ? $('#down') : $('#up');
$('html, body').stop().animate({
scrollTop: target.offset().top
}, 1000);
});
Where element
is the target element to scroll to and 1000
is the delay in ms before completion.
The benefit being, no matter what changes to your content dimensions, the function will not need to be altered.
How to count lines in a document?
If all you want is the number of lines (and not the number of lines and the stupid file name coming back):
wc -l < /filepath/filename.ext
As previously mentioned these also work (but are inferior for other reasons):
awk 'END{print NR}' file # not on all unixes
sed -n '$=' file # (GNU sed) also not on all unixes
grep -c ".*" file # overkill and probably also slower
How to get height of Keyboard?
Swift
You can get the keyboard height by subscribing to the UIKeyboardWillShowNotification
notification. (Assuming you want to know what the height will be before it's shown).
Swift 4
NotificationCenter.default.addObserver(
self,
selector: #selector(keyboardWillShow),
name: UIResponder.keyboardWillShowNotification,
object: nil
)
@objc func keyboardWillShow(_ notification: Notification) {
if let keyboardFrame: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {
let keyboardRectangle = keyboardFrame.cgRectValue
let keyboardHeight = keyboardRectangle.height
}
}
Swift 3
NotificationCenter.default.addObserver(
self,
selector: #selector(keyboardWillShow),
name: NSNotification.Name.UIKeyboardWillShow,
object: nil
)
@objc func keyboardWillShow(_ notification: Notification) {
if let keyboardFrame: NSValue = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue {
let keyboardRectangle = keyboardFrame.cgRectValue
let keyboardHeight = keyboardRectangle.height
}
}
Swift 2
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
func keyboardWillShow(notification: NSNotification) {
let userInfo: NSDictionary = notification.userInfo!
let keyboardFrame: NSValue = userInfo.valueForKey(UIKeyboardFrameEndUserInfoKey) as! NSValue
let keyboardRectangle = keyboardFrame.CGRectValue()
let keyboardHeight = keyboardRectangle.height
}
Convert a String of Hex into ASCII in Java
Easiest way to do it with javax.xml.bind.DatatypeConverter
:
String hex = "75546f7272656e745c436f6d706c657465645c6e667375635f6f73745f62795f6d757374616e675c50656e64756c756d2d392c303030204d696c65732e6d7033006d7033006d7033004472756d202620426173730050656e64756c756d00496e2053696c69636f00496e2053696c69636f2a3b2a0050656e64756c756d0050656e64756c756d496e2053696c69636f303038004472756d2026204261737350656e64756c756d496e2053696c69636f30303800392c303030204d696c6573203c4d757374616e673e50656e64756c756d496e2053696c69636f3030380050656e64756c756d50656e64756c756d496e2053696c69636f303038004d50330000";
byte[] s = DatatypeConverter.parseHexBinary(hex);
System.out.println(new String(s));
Insert a line break in mailto body
<a href="mailto:[email protected]?subject=Request&body=Hi,%0DName:[your name] %0DGood day " target="_blank"></a>
Try adding %0D to break the line. This will definitely work.
Above code will display the following:
Hi,
Name:[your name]
Good day
Enum ToString with user friendly strings
I do this with extension methods:
public enum ErrorLevel
{
None,
Low,
High,
SoylentGreen
}
public static class ErrorLevelExtensions
{
public static string ToFriendlyString(this ErrorLevel me)
{
switch(me)
{
case ErrorLevel.None:
return "Everything is OK";
case ErrorLevel.Low:
return "SNAFU, if you know what I mean.";
case ErrorLevel.High:
return "Reaching TARFU levels";
case ErrorLevel.SoylentGreen:
return "ITS PEOPLE!!!!";
default:
return "Get your damn dirty hands off me you FILTHY APE!";
}
}
}
Jquery - How to make $.post() use contentType=application/json?
I know this is a late answer, I actually have a shortcut method that I use for posting/reading to/from MS based services.. it works with MVC as well as ASMX etc...
Use:
$.msajax(
'/services/someservice.asmx/SomeMethod'
,{} /*empty object for nothing, or object to send as Application/JSON */
,function(data,jqXHR) {
//use the data from the response.
}
,function(err,jqXHR) {
//additional error handling.
}
);
//sends a json request to an ASMX or WCF service configured to reply to JSON requests.
(function ($) {
var tries = 0; //IE9 seems to error out the first ajax call sometimes... will retry up to 5 times
$.msajax = function (url, data, onSuccess, onError) {
return $.ajax({
'type': "POST"
, 'url': url
, 'contentType': "application/json"
, 'dataType': "json"
, 'data': typeof data == "string" ? data : JSON.stringify(data || {})
,beforeSend: function(jqXHR) {
jqXHR.setRequestHeader("X-MicrosoftAjax","Delta=true");
}
, 'complete': function(jqXHR, textStatus) {
handleResponse(jqXHR, textStatus, onSuccess, onError, function(){
setTimeout(function(){
$.msajax(url, data, onSuccess, onError);
}, 100 * tries); //try again
});
}
});
}
$.msajax.defaultErrorMessage = "Error retreiving data.";
function logError(err, errorHandler, jqXHR) {
tries = 0; //reset counter - handling error response
//normalize error message
if (typeof err == "string") err = { 'Message': err };
if (console && console.debug && console.dir) {
console.debug("ERROR processing jQuery.msajax request.");
console.dir({ 'details': { 'error': err, 'jqXHR':jqXHR } });
}
try {
errorHandler(err, jqXHR);
} catch (e) {}
return;
}
function handleResponse(jqXHR, textStatus, onSuccess, onError, onRetry) {
var ret = null;
var reterr = null;
try {
//error from jqXHR
if (textStatus == "error") {
var errmsg = $.msajax.defaultErrorMessage || "Error retreiving data.";
//check for error response from the server
if (jqXHR.status >= 300 && jqXHR.status < 600) {
return logError( jqXHR.statusText || msg, onError, jqXHR);
}
if (tries++ < 5) return onRetry();
return logError( msg, onError, jqXHR);
}
//not an error response, reset try counter
tries = 0;
//check for a redirect from server (usually authentication token expiration).
if (jqXHR.responseText.indexOf("|pageRedirect||") > 0) {
location.href = decodeURIComponent(jqXHR.responseText.split("|pageRedirect||")[1].split("|")[0]).split('?')[0];
return;
}
//parse response using ajax enabled parser (if available)
ret = ((JSON && JSON.parseAjax) || $.parseJSON)(jqXHR.responseText);
//invalid response
if (!ret) throw jqXHR.responseText;
// d property wrap as of .Net 3.5
if (ret.d) ret = ret.d;
//has an error
reterr = (ret && (ret.error || ret.Error)) || null; //specifically returned an "error"
if (ret && ret.ExceptionType) { //Microsoft Webservice Exception Response
reterr = ret
}
} catch (err) {
reterr = {
'Message': $.msajax.defaultErrorMessage || "Error retreiving data."
,'debug': err
}
}
//perform final logic outside try/catch, was catching error in onSuccess/onError callbacks
if (reterr) {
logError(reterr, onError, jqXHR);
return;
}
onSuccess(ret, jqXHR);
}
} (jQuery));
NOTE: I also have a JSON.parseAjax method that is modified from json.org's JS file, that adds handling for the MS "/Date(...)/" dates...
The modified json2.js file isn't included, it uses the script based parser in the case of IE8, as there are instances where the native parser breaks when you extend the prototype of array and/or object, etc.
I've been considering revamping this code to implement the promises interfaces, but it's worked really well for me.
Is it better to use NOT or <> when comparing values?
Because "not ... =" is two operations and "<>" is only one, it is faster to use "<>".
Here is a quick experiment to prove it:
StartTime = Timer
For x = 1 to 100000000
If 4 <> 3 Then
End if
Next
WScript.echo Timer-StartTime
StartTime = Timer
For x = 1 to 100000000
If Not (4 = 3) Then
End if
Next
WScript.echo Timer-StartTime
The results I get on my machine:
4.783203
5.552734
What is an idempotent operation?
In short, Idempotent operations means that the operation will not result in different results no matter how many times you operate the idempotent operations.
For example, according to the definition of the spec of HTTP, GET, HEAD, PUT, and DELETE
are idempotent operations; however POST and PATCH
are not. That's why sometimes POST
is replaced by PUT
.
How to change legend title in ggplot
Just to add to the list (the other options here didn't work for me), you can also use the function update_labels for ggplot:
p <- ggplot(df, aes(x=rating, fill=cond)) +
geom_density(alpha=.3) +
xlab("NEW RATING TITLE") +
ylab("NEW DENSITY TITLE")
update_labels(p, list(colour="MY NEW LEGEND TITLE")
This will also allow you to change x- and y-axis labels, with separate lines:
update_labels(p, list(x="NEW X LABEL",y="NEW Y LABEL")
How to use onClick event on react Link component?
You should use this:
<Link to={this.props.myroute} onClick={hello}>Here</Link>
Or (if method hello
lays at this class):
<Link to={this.props.myroute} onClick={this.hello}>Here</Link>
Update: For ES6 and latest if you want to bind some param with click method, you can use this:
const someValue = 'some';
....
<Link to={this.props.myroute} onClick={() => hello(someValue)}>Here</Link>
Saving to CSV in Excel loses regional date format
Change the date and time settings for your computer in the "short date" format under calendar settings. This will change the format for everything yyyy-mm-dd or however you want it to display; but remember it will look like that even for files saved on your computer.
At least it works.
Is calculating an MD5 hash less CPU intensive than SHA family functions?
sha1sum is quite a bit faster on Power9 than md5sum
$ uname -mov
#1 SMP Mon May 13 12:16:08 EDT 2019 ppc64le GNU/Linux
$ cat /proc/cpuinfo
processor : 0
cpu : POWER9, altivec supported
clock : 2166.000000MHz
revision : 2.2 (pvr 004e 1202)
$ ls -l linux-master.tar
-rw-rw-r-- 1 x x 829685760 Jan 29 14:30 linux-master.tar
$ time sha1sum linux-master.tar
10fbf911e254c4fe8e5eb2e605c6c02d29a88563 linux-master.tar
real 0m1.685s
user 0m1.528s
sys 0m0.156s
$ time md5sum linux-master.tar
d476375abacda064ae437a683c537ec4 linux-master.tar
real 0m2.942s
user 0m2.806s
sys 0m0.136s
$ time sum linux-master.tar
36928 810240
real 0m2.186s
user 0m1.917s
sys 0m0.268s
Removing duplicates from a String in Java
To me it looks like everyone is trying way too hard to accomplish this task. All we are concerned about is that it copies 1 copy of each letter if it repeats. Then because we are only concerned if those characters repeat one after the other the nested loops become arbitrary as you can just simply compare position n to position n + 1. Then because this only copies things down when they're different, to solve for the last character you can either append white space to the end of the original string, or just get it to copy the last character of the string to your result.
String removeDuplicate(String s){
String result = "";
for (int i = 0; i < s.length(); i++){
if (i + 1 < s.length() && s.charAt(i) != s.charAt(i+1)){
result = result + s.charAt(i);
}
if (i + 1 == s.length()){
result = result + s.charAt(i);
}
}
return result;
}
How to convert a string to lower case in Bash?
This is a far faster variation of JaredTS486's approach that uses native Bash capabilities (including Bash versions <4.0) to optimize his approach.
I've timed 1,000 iterations of this approach for a small string (25 characters) and a larger string (445 characters), both for lowercase and uppercase conversions. Since the test strings are predominantly lowercase, conversions to lowercase are generally faster than to uppercase.
I've compared my approach with several other answers on this page that are compatible with Bash 3.2. My approach is far more performant than most approaches documented here, and is even faster than tr
in several cases.
Here are the timing results for 1,000 iterations of 25 characters:
Timing results for 1,000 iterations of 445 characters (consisting of the poem "The Robin" by Witter Bynner):
- 2s for my approach to lowercase; 12s for uppercase
- 4s for
tr
to lowercase; 4s for uppercase
- 20s for Orwellophile's approach to lowercase; 29s for uppercase
- 75s for ghostdog74's approach to lowercase; 669s for uppercase. It's interesting to note how dramatic the performance difference is between a test with predominant matches vs. a test with predominant misses
- 467s for technosaurus' approach to lowercase; 449s for uppercase
- 660s for JaredTS486's approach to lowercase; 660s for uppercase. It's interesting to note that this approach generated continuous page faults (memory swapping) in Bash
Solution:
#!/bin/bash
set -e
set -u
declare LCS="abcdefghijklmnopqrstuvwxyz"
declare UCS="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
function lcase()
{
local TARGET="${1-}"
local UCHAR=''
local UOFFSET=''
while [[ "${TARGET}" =~ ([A-Z]) ]]
do
UCHAR="${BASH_REMATCH[1]}"
UOFFSET="${UCS%%${UCHAR}*}"
TARGET="${TARGET//${UCHAR}/${LCS:${#UOFFSET}:1}}"
done
echo -n "${TARGET}"
}
function ucase()
{
local TARGET="${1-}"
local LCHAR=''
local LOFFSET=''
while [[ "${TARGET}" =~ ([a-z]) ]]
do
LCHAR="${BASH_REMATCH[1]}"
LOFFSET="${LCS%%${LCHAR}*}"
TARGET="${TARGET//${LCHAR}/${UCS:${#LOFFSET}:1}}"
done
echo -n "${TARGET}"
}
The approach is simple: while the input string has any remaining uppercase letters present, find the next one, and replace all instances of that letter with its lowercase variant. Repeat until all uppercase letters are replaced.
Some performance characteristics of my solution:
- Uses only shell builtin utilities, which avoids the overhead of invoking external binary utilities in a new process
- Avoids sub-shells, which incur performance penalties
- Uses shell mechanisms that are compiled and optimized for performance, such as global string replacement within variables, variable suffix trimming, and regex searching and matching. These mechanisms are far faster than iterating manually through strings
- Loops only the number of times required by the count of unique matching characters to be converted. For example, converting a string that has three different uppercase characters to lowercase requires only 3 loop iterations. For the preconfigured ASCII alphabet, the maximum number of loop iterations is 26
UCS
and LCS
can be augmented with additional characters
MySQL Query GROUP BY day / month / year
If your search is over several years, and you still want to group monthly, I suggest:
version #1:
SELECT SQL_NO_CACHE YEAR(record_date), MONTH(record_date), COUNT(*)
FROM stats
GROUP BY DATE_FORMAT(record_date, '%Y%m')
version #2 (more efficient):
SELECT SQL_NO_CACHE YEAR(record_date), MONTH(record_date), COUNT(*)
FROM stats
GROUP BY YEAR(record_date)*100 + MONTH(record_date)
I compared these versions on a big table with 1,357,918 rows (innodb),
and the 2nd version appears to have better results.
version1 (average of 10 executes): 1.404 seconds
version2 (average of 10 executes): 0.780 seconds
(SQL_NO_CACHE
key added to prevent MySQL from CACHING to queries.)
Using Razor within JavaScript
A simple and a good straight-forward example:
<script>
// This gets the username from the Razor engine and puts it
// in JavaScript to create a variable I can access from the
// client side.
//
// It's an odd workaraound, but it works.
@{
var outScript = "var razorUserName = " + "\"" + @User.Identity.Name + "\"";
}
@MvcHtmlString.Create(outScript);
</script>
This creates a script in your page at the location you place the code above which looks like the following:
<script>
// This gets the username from the Razor engine and puts it
// in JavaScript to create a variable I can access from
// client side.
//
// It's an odd workaraound, but it works.
var razorUserName = "daylight";
</script>
Now you have a global JavaScript variable named razorUserName
which you can access and use on the client. The Razor engine has obviously extracted the value from @User.Identity.Name
(server-side variable) and put it in the code it writes to your script tag.
Style bottom Line in Android
I think you do not need to use shape if I understood you.
If you are looking as shown in following image then use following layout.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:background="#1bd4f6"
android:paddingBottom="4dp" >
<TextView
android:layout_width="200dp"
android:layout_height="wrap_content"
android:background="#ababb2"
android:padding="5dp"
android:text="Hello Android" />
</RelativeLayout>
</RelativeLayout>
EDIT
play with these properties you will get result
android:top="dimension"
android:right="dimension"
android:bottom="dimension"
android:left="dimension"
try like this
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape android:shape="rectangle" >
<solid android:color="#1bd4f6" />
</shape>
</item>
<item android:top="20px"
android:left="0px">
<shape android:shape="line" >
<padding android:bottom="1dp" />
<stroke
android:dashGap="10px"
android:dashWidth="10px"
android:width="1dp"
android:color="#ababb2" />
</shape>
</item>
</layer-list>
Google Spreadsheet, Count IF contains a string
You should use
=COUNTIF(A2:A51, "*iPad*")/COUNTA(A2:A51)
Additionally, if you wanted to count more than one element, like iPads OR Kindles, you would use
=SUM(COUNTIF(A2:A51, {"*iPad*", "*kindle*"}))/COUNTA(A2:A51)
in the numerator.
What is the difference between sscanf or atoi to convert a string to an integer?
*scanf()
family of functions return the number of values converted. So you should check to make sure sscanf()
returns 1 in your case. EOF
is returned for "input failure", which means that ssacnf()
will never return EOF
.
For sscanf()
, the function has to parse the format string, and then decode an integer. atoi()
doesn't have that overhead. Both suffer from the problem that out-of-range values result in undefined behavior.
You should use strtol()
or strtoul()
functions, which provide much better error-detection and checking. They also let you know if the whole string was consumed.
If you want an int
, you can always use strtol()
, and then check the returned value to see if it lies between INT_MIN
and INT_MAX
.
Inline IF Statement in C#
The literal answer is:
return (value == 1 ? Periods.VariablePeriods : Periods.FixedPeriods);
Note that the inline if statement, just like an if statement, only checks for true or false. If (value == 1) evaluates to false, it might not necessarily mean that value == 2. Therefore it would be safer like this:
return (value == 1
? Periods.VariablePeriods
: (value == 2
? Periods.FixedPeriods
: Periods.Unknown));
If you add more values an inline if will become unreadable and a switch would be preferred:
switch (value)
{
case 1:
return Periods.VariablePeriods;
case 2:
return Periods.FixedPeriods;
}
The good thing about enums is that they have a value, so you can use the values for the mapping, as user854301 suggested. This way you can prevent unnecessary branches thus making the code more readable and extensible.
how to bind datatable to datagridview in c#
for example we want to set a DataTable 'Users' to DataGridView by followig 2 steps :
step 1 - get all Users by :
public DataTable getAllUsers()
{
OracleConnection Connection = new OracleConnection(stringConnection);
Connection.ConnectionString = stringConnection;
Connection.Open();
DataSet dataSet = new DataSet();
OracleCommand cmd = new OracleCommand("semect * from Users");
cmd.CommandType = CommandType.Text;
cmd.Connection = Connection;
using (OracleDataAdapter dataAdapter = new OracleDataAdapter())
{
dataAdapter.SelectCommand = cmd;
dataAdapter.Fill(dataSet);
}
return dataSet.Tables[0];
}
step 2- set the return result to DataGridView :
public void setTableToDgv(DataGridView DGV, DataTable table)
{
DGV.DataSource = table;
}
using example:
setTableToDgv(dgv_client,getAllUsers());
Write to .txt file?
Well, you need to first get a good book on C and understand the language.
FILE *fp;
fp = fopen("c:\\test.txt", "wb");
if(fp == null)
return;
char x[10]="ABCDEFGHIJ";
fwrite(x, sizeof(x[0]), sizeof(x)/sizeof(x[0]), fp);
fclose(fp);
Assign keyboard shortcut to run procedure
The problem that I had with the above is that I wanted to associate a short cut key with a macro in an xlam which has no visible interface. I found that the folllowing worked
To associate a short cut key with a macro
In Excel (not VBA) on the Developer Tab
click Macros - no macros will be shown
Type the name of the Sub
The Options button should then be enabled
Click it
Ctrl will be the default
Hold down Shift and press the letter you want
eg Shift and A
will associate Ctrl-Shift-A with the Sub
Git push existing repo to a new and different remote repo server?
I found a solution using set-url which is concise and fairly easy to understand:
- create a new repo at Github
cd
into the existing repository on your local machine (if you haven't cloned it yet, then do this first)
git remote set-url origin https://github.com/user/example.git
git push -u origin master
Static vs class functions/variables in Swift classes?
class
vs static
class
is used inside Reference Type
(class):
- computed property
- method
- can be overridden by subclass
static
is used inside Reference Type
and Value Type
(class, enum):
- computed property and stored property
- method
- cannot be changed by subclass
protocol MyProtocol {
// class var protocolClassVariable : Int { get }//ERROR: Class properties are only allowed within classes
static var protocolStaticVariable : Int { get }
// class func protocolClassFunc()//ERROR: Class methods are only allowed within classes
static func protocolStaticFunc()
}
struct ValueTypeStruct: MyProtocol {
//MyProtocol implementation begin
static var protocolStaticVariable: Int = 1
static func protocolStaticFunc() {
}
//MyProtocol implementation end
// class var classVariable = "classVariable"//ERROR: Class properties are only allowed within classes
static var staticVariable = "staticVariable"
// class func classFunc() {} //ERROR: Class methods are only allowed within classes
static func staticFunc() {}
}
class ReferenceTypeClass: MyProtocol {
//MyProtocol implementation begin
static var protocolStaticVariable: Int = 2
static func protocolStaticFunc() {
}
//MyProtocol implementation end
var variable = "variable"
// class var classStoredPropertyVariable = "classVariable"//ERROR: Class stored properties not supported in classes
class var classComputedPropertyVariable: Int {
get {
return 1
}
}
static var staticStoredPropertyVariable = "staticVariable"
static var staticComputedPropertyVariable: Int {
get {
return 1
}
}
class func classFunc() {}
static func staticFunc() {}
}
final class FinalSubReferenceTypeClass: ReferenceTypeClass {
override class var classComputedPropertyVariable: Int {
get {
return 2
}
}
override class func classFunc() {}
}
//class SubFinalSubReferenceTypeClass: FinalSubReferenceTypeClass {}// ERROR: Inheritance from a final class
[Reference vs Value Type]
How to scroll to bottom in a ScrollView on activity startup
After initializing your UI component and fill it with data. add those line to your on create method
Runnable runnable=new Runnable() {
@Override
public void run() {
scrollView.fullScroll(ScrollView.FOCUS_DOWN);
}
};
scrollView.post(runnable);
multiprocessing.Pool: When to use apply, apply_async or map?
Here is an overview in a table format in order to show the differences between Pool.apply
, Pool.apply_async
, Pool.map
and Pool.map_async
. When choosing one, you have to take multi-args, concurrency, blocking, and ordering into account:
| Multi-args Concurrence Blocking Ordered-results
---------------------------------------------------------------------
Pool.map | no yes yes yes
Pool.map_async | no yes no yes
Pool.apply | yes no yes no
Pool.apply_async | yes yes no no
Pool.starmap | yes yes yes yes
Pool.starmap_async| yes yes no no
Notes:
Pool.imap
and Pool.imap_async
– lazier version of map and map_async.
Pool.starmap
method, very much similar to map method besides it acceptance of multiple arguments.
Async
methods submit all the processes at once and retrieve the results once they are finished. Use get method to obtain the results.
Pool.map
(or Pool.apply
)methods are very much similar to Python built-in map(or apply). They block the main process until all the processes complete and return the result.
Examples:
map
Is called for a list of jobs in one time
results = pool.map(func, [1, 2, 3])
apply
Can only be called for one job
for x, y in [[1, 1], [2, 2]]:
results.append(pool.apply(func, (x, y)))
def collect_result(result):
results.append(result)
map_async
Is called for a list of jobs in one time
pool.map_async(func, jobs, callback=collect_result)
apply_async
Can only be called for one job and executes a job in the background in parallel
for x, y in [[1, 1], [2, 2]]:
pool.apply_async(worker, (x, y), callback=collect_result)
starmap
Is a variant of pool.map
which support multiple arguments
pool.starmap(func, [(1, 1), (2, 1), (3, 1)])
starmap_async
A combination of starmap() and map_async() that iterates over iterable of iterables and calls func with the iterables unpacked. Returns a result object.
pool.starmap_async(calculate_worker, [(1, 1), (2, 1), (3, 1)], callback=collect_result)
Reference:
Find complete documentation here: https://docs.python.org/3/library/multiprocessing.html
Returning a value from callback function in Node.js
I am facing small trouble in returning a value from callback function in Node.js
This is not a "small trouble", it is actually impossible to "return" a value in the traditional sense from an asynchronous function.
Since you cannot "return the value" you must call the function that will need the value once you have it. @display_name already answered your question, but I just wanted to point out that the return in doCall is not returning the value in the traditional way. You could write doCall as follow:
function doCall(urlToCall, callback) {
urllib.request(urlToCall, { wd: 'nodejs' }, function (err, data, response) {
var statusCode = response.statusCode;
finalData = getResponseJson(statusCode, data.toString());
// call the function that needs the value
callback(finalData);
// we are done
return;
});
}
Line callback(finalData);
is what calls the function that needs the value that you got from the async function. But be aware that the return statement is used to indicate that the function ends here, but it does not mean that the value is returned to the caller (the caller already moved on.)
ClientScript.RegisterClientScriptBlock?
See if the below helps you:
I was using the following earlier:
ClientScript.RegisterClientScriptBlock(Page.GetType(), "AlertMsg", "<script language='javascript'>alert('The Web Policy need to be accepted to submit the new assessor information.');</script>");
After implementing AJAX in this page, it stopped working. After reading your blog, I changed the above to:
ScriptManager.RegisterClientScriptBlock(imgBtnSubmit, this.GetType(), "AlertMsg", "<script language='javascript'>alert('The Web Policy need to be accepted to submit the new assessor information.');</script>", false);
This is working perfectly fine.
(It’s .NET 2.0 Framework, I am using)
Xcode couldn't find any provisioning profiles matching
What fixed it for me was plugging my iPhone and allowing it as a simulator destination. Doing so required my to register my iPhone in Apple Dev account and once that was done and I ran my project from Xcode on my iPhone everything fixed itself.
- Connect your iPhone to your Mac
- Xcode>Window>Devices & Simulators
- Add new under Devices and make sure "show are run destination" is ticked
- Build project and run it on your iPhone
How to determine the Schemas inside an Oracle Data Pump Export file
You need to search for OWNER_NAME.
cat -v dumpfile.dmp | grep -o '<OWNER_NAME>.*</OWNER_NAME>' | uniq -u
cat -v turn the dumpfile into visible text.
grep -o shows only the match so we don't see really long lines
uniq -u removes duplicate lines so you see less output.
This works pretty well, even on large dump files, and could be tweaked for usage in a script.
How can foreign key constraints be temporarily disabled using T-SQL?
One script to rule them all: this combines truncate and delete commands with sp_MSforeachtable so that you can avoid dropping and recreating constraints - just specify the tables that need to be deleted rather than truncated and for my purposes I have included an extra schema filter for good measure (tested in 2008r2)
declare @schema nvarchar(max) = 'and Schema_Id=Schema_id(''Value'')'
declare @deletiontables nvarchar(max) = '(''TableA'',''TableB'')'
declare @truncateclause nvarchar(max) = @schema + ' and o.Name not in ' + + @deletiontables;
declare @deleteclause nvarchar(max) = @schema + ' and o.Name in ' + @deletiontables;
exec sp_MSforeachtable 'alter table ? nocheck constraint all', @whereand=@schema
exec sp_MSforeachtable 'truncate table ?', @whereand=@truncateclause
exec sp_MSforeachtable 'delete from ?', @whereand=@deleteclause
exec sp_MSforeachtable 'alter table ? with check check constraint all', @whereand=@schema
How to generate unique IDs for form labels in React?
The id should be placed inside of componentWillMount (update for 2018) constructor
, not render
. Putting it in render
will re-generate new ids unnecessarily.
If you're using underscore or lodash, there is a uniqueId
function, so your resulting code should be something like:
constructor(props) {
super(props);
this.id = _.uniqueId("prefix-");
}
render() {
const id = this.id;
return (
<div>
<input id={id} type="checkbox" />
<label htmlFor={id}>label</label>
</div>
);
}
2019 Hooks update:
import React, { useState } from 'react';
import _uniqueId from 'lodash/uniqueId';
const MyComponent = (props) => {
// id will be set once when the component initially renders, but never again
// (unless you assigned and called the second argument of the tuple)
const [id] = useState(_uniqueId('prefix-'));
return (
<div>
<input id={id} type="checkbox" />
<label htmlFor={id}>label</label>
</div>
);
}
How to copy a file to another path?
string directoryPath = Path.GetDirectoryName(destinationFileName);
// If directory doesn't exist create one
if (!Directory.Exists(directoryPath))
{
DirectoryInfo di = Directory.CreateDirectory(directoryPath);
}
File.Copy(sourceFileName, destinationFileName);
Import an existing git project into GitLab?
Moving a project from GitHub to GitLab including issues, pull requests Wiki, Milestones, Labels, Release notes and comments
There is a thorough instruction on GitLab Docs:
https://docs.gitlab.com/ee/user/project/import/github.html
tl;dr
Ensure that any GitHub users who you want to map to GitLab users have either:
- A GitLab account that has logged in using the GitHub icon - or -
- A GitLab account with an email address that matches the public email address of the GitHub user
From the top navigation bar, click + and select New project.
- Select the Import project tab and then select GitHub.
- Select the first button to List your GitHub repositories. You are redirected to a page on github.com to authorize the GitLab application.
- Click Authorize gitlabhq. You are redirected back to GitLab's Import page and all of your GitHub repositories are listed.
- Continue on to selecting which repositories to import.
But Please read the GitLab Docs page for details and hooks!
(it's not much)
Comparing strings in Java
You need both getText() - which returns an Editable and toString() - to convert that to a String for matching.
So instead of: passw1.toString().equalsIgnoreCase("1234")
you need passw1.getText().toString().equalsIgnoreCase("1234")
.
How to get the selected radio button’s value?
Since jQuery 1.8, the correct syntax for the query is
$('input[name="genderS"]:checked').val();
Not $('input[@name="genderS"]:checked').val();
anymore, which was working in jQuery 1.7 (with the @).
Ruby on Rails: Clear a cached page
If you're doing fragment caching, you can manually break the cache by updating your cache key, like so:
Version #1
<% cache ['cool_name_for_cache_key', 'v1'] do %>
Version #2
<% cache ['cool_name_for_cache_key', 'v2'] do %>
Or you can have the cache automatically reset based on the state of a non-static object, such as an ActiveRecord object, like so:
<% cache @user_object do %>
With this ^ method, any time the user object is updated, the cache will automatically be reset.
Find when a file was deleted in Git
Git log but you need to prefix the path with --
Eg:
dan-mac:test dani$ git log file1.txt
fatal: ambiguous argument 'file1.txt': unknown revision or path not in the working tree.
dan-mac:test dani$ git log -- file1.txt
commit 0f7c4e1c36e0b39225d10b26f3dea40ad128b976
Author: Daniel Palacio <[email protected]>
Date: Tue Jul 26 23:32:20 2011 -0500
foo
java.lang.ClassNotFoundException: org.eclipse.core.runtime.adaptor.EclipseStarter
In your config.ini
file of eclipse eclipse\configuration\config.ini
check this three things:
osgi.framework=file\:plugins\\org.eclipse.osgi_3.4.2.R34x_v20080826-1230.jar
osgi.bundles=reference\:file\:org.eclipse.equinox.simpleconfigurator_1.0.0.v20080604.jar@1\:start
org.eclipse.equinox.simpleconfigurator.configUrl=file\:org.eclipse.equinox.simpleconfigurator\\bundles.info
And check whether these jars are in place or not, the jar files depend upon your version of eclipse .
ssh : Permission denied (publickey,gssapi-with-mic)
Tried a lot of things, it did not help.
It get access in a simple way:
eval $(ssh-agent) > /dev/null
killall ssh-agent
eval `ssh-agent`
ssh-add ~/.ssh/id_rsa
Note that at the end of the ssh-add -L
output must be not a path to the key, but your email.
Get current URL from IFRAME
Hope this will help some how in your case,
I suffered with the exact same problem, and just used localstorage to share the data between parent window and iframe.
So in parent window you can:
localStorage.setItem("url", myUrl);
And in code where iframe source is just get this data from localstorage:
localStorage.getItem('url');
Saved me a lot of time.
As far as i can see the only condition is access to the parent page code.
Hope this will help someone.
vector vs. list in STL
Preserving the validity of iterators is one reason to use a list. Another is when you don't want a vector to reallocate when pushing items. This can be managed by an intelligent use of reserve(), but in some cases it might be easier or more feasible to just use a list.
error code 1292 incorrect date value mysql
I was having the same issue in Workbench plus insert query from C# application.
In my case using ISO format solve the issue
string value = date.ToString("yyyy-MM-dd HH:mm:ss");
Checking if sys.argv[x] is defined
Pretty close to what the originator was trying to do. Here is a function I use:
def get_arg(index):
try:
sys.argv[index]
except IndexError:
return ''
else:
return sys.argv[index]
So a usage would be something like:
if __name__ == "__main__":
banner(get_arg(1),get_arg(2))
get next and previous day with PHP
Php script -1****its to Next Date
<?php
$currentdate=date('Y-m-d');
$date_arr=explode('-',$currentdate);
$next_date=
Date("Y-m-d",mktime(0,0,0,$date_arr[1],$date_arr[2]+1,$date_arr[0]));
echo $next_date;
?>**
**Php script -1****its to Next year**
<?php
$currentdate=date('Y-m-d');
$date_arr=explode('-',$currentdate);
$next_date=
Date("Y-m-d",mktime(0,0,0,$date_arr[1],$date_arr[2],$date_arr[0]+1));
echo $next_date;
?>
How to uninstall jupyter
If you are using jupyter notebook, You can remove it like this:
pip uninstall notebook
You should use conda uninstall if you installed it with conda.
Maven command to determine which settings.xml file Maven is using
Start maven with -X option (debug) and examine the beginning of the output. There should be something like this:
...
[INFO] Error stacktraces are turned on.
[DEBUG] Reading global settings from c:\....\apache-maven-3.0.3\conf\settings.xml
[DEBUG] Reading user settings from c:\....\.m2\settings.xml
[DEBUG] Using local repository at C:\....\repository
...
(Original directory names are removed by me)
How to create a user in Django?
Have you confirmed that you are passing actual values and not None
?
from django.shortcuts import render
def createUser(request):
userName = request.REQUEST.get('username', None)
userPass = request.REQUEST.get('password', None)
userMail = request.REQUEST.get('email', None)
# TODO: check if already existed
if userName and userPass and userMail:
u,created = User.objects.get_or_create(userName, userMail)
if created:
# user was created
# set the password here
else:
# user was retrieved
else:
# request was empty
return render(request,'home.html')
Best practice for storing and protecting private API keys in applications
Another approach is to not have the secret on the device in the first place! See Mobile API Security Techniques (especially part 3).
Using the time honored tradition of indirection, share the secret between your API endpoint and an app authentication service.
When your client wants to make an API call, it asks the app auth service to authenticate it (using strong remote attestation techniques), and it receives a time limited (usually JWT) token signed by the secret.
The token is sent with each API call where the endpoint can verify its signature before acting on the request.
The actual secret is never present on the device; in fact, the app never has any idea if it is valid or not, it juts requests authentication and passes on the resulting token. As a nice benefit from indirection, if you ever want to change the secret, you can do so without requiring users to update their installed apps.
So if you want to protect your secret, not having it in your app in the first place is a pretty good way to go.
MySQL: #126 - Incorrect key file for table
Try to run a repair command for each one of the tables involved in the query.
Use MySQL administrator, go to Catalog -> Select your Catalog -> Select a table -> Click the Maintenance button -> Repair -> Use FRM.
find all subsets that sum to a particular value
This my program in ruby . It will return arrays, each holding the subsequences summing to the provided target value.
array = [1, 3, 4, 2, 7, 8, 9]
0..array.size.times.each do |i|
array.combination(i).to_a.each { |a| print a if a.inject(:+) == 9}
end
How ViewBag in ASP.NET MVC works
It's a dynamic object, meaning you can add properties to it in the controller, and read them later in the view, because you are essentially creating the object as you do, a feature of the dynamic type. See this MSDN article on dynamics. See this article on it's usage in relation to MVC.
If you wanted to use this for web forms, add a dynamic property to a base page class like so:
public class BasePage : Page
{
public dynamic ViewBagProperty
{
get;
set;
}
}
Have all of your pages inherit from this. You should be able to, in your ASP.NET markup, do:
<%= ViewBagProperty.X %>
That should work. If not, there are ways to work around it.
Clear android application user data
The command pm clear com.android.browser
requires root permission.
So, run su
first.
Here is the sample code:
private static final String CHARSET_NAME = "UTF-8";
String cmd = "pm clear com.android.browser";
ProcessBuilder pb = new ProcessBuilder().redirectErrorStream(true).command("su");
Process p = pb.start();
// We must handle the result stream in another Thread first
StreamReader stdoutReader = new StreamReader(p.getInputStream(), CHARSET_NAME);
stdoutReader.start();
out = p.getOutputStream();
out.write((cmd + "\n").getBytes(CHARSET_NAME));
out.write(("exit" + "\n").getBytes(CHARSET_NAME));
out.flush();
p.waitFor();
String result = stdoutReader.getResult();
The class StreamReader
:
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.concurrent.CountDownLatch;
class StreamReader extends Thread {
private InputStream is;
private StringBuffer mBuffer;
private String mCharset;
private CountDownLatch mCountDownLatch;
StreamReader(InputStream is, String charset) {
this.is = is;
mCharset = charset;
mBuffer = new StringBuffer("");
mCountDownLatch = new CountDownLatch(1);
}
String getResult() {
try {
mCountDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
return mBuffer.toString();
}
@Override
public void run() {
InputStreamReader isr = null;
try {
isr = new InputStreamReader(is, mCharset);
int c = -1;
while ((c = isr.read()) != -1) {
mBuffer.append((char) c);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (isr != null)
isr.close();
} catch (IOException e) {
e.printStackTrace();
}
mCountDownLatch.countDown();
}
}
}
Copy map values to vector in STL
Here is what I would do.
Also I would use a template function to make the construction of select2nd easier.
#include <map>
#include <vector>
#include <algorithm>
#include <memory>
#include <string>
/*
* A class to extract the second part of a pair
*/
template<typename T>
struct select2nd
{
typename T::second_type operator()(T const& value) const
{return value.second;}
};
/*
* A utility template function to make the use of select2nd easy.
* Pass a map and it automatically creates a select2nd that utilizes the
* value type. This works nicely as the template functions can deduce the
* template parameters based on the function parameters.
*/
template<typename T>
select2nd<typename T::value_type> make_select2nd(T const& m)
{
return select2nd<typename T::value_type>();
}
int main()
{
std::map<int,std::string> m;
std::vector<std::string> v;
/*
* Please note: You must use std::back_inserter()
* As transform assumes the second range is as large as the first.
* Alternatively you could pre-populate the vector.
*
* Use make_select2nd() to make the function look nice.
* Alternatively you could use:
* select2nd<std::map<int,std::string>::value_type>()
*/
std::transform(m.begin(),m.end(),
std::back_inserter(v),
make_select2nd(m)
);
}
LINQ Joining in C# with multiple conditions
As far as I know you can only join this way:
var query = from obj_i in set1
join obj_j in set2 on
new {
JoinProperty1 = obj_i.SomeField1,
JoinProperty2 = obj_i.SomeField2,
JoinProperty3 = obj_i.SomeField3,
JoinProperty4 = obj_i.SomeField4
}
equals
new {
JoinProperty1 = obj_j.SomeOtherField1,
JoinProperty2 = obj_j.SomeOtherField2,
JoinProperty3 = obj_j.SomeOtherField3,
JoinProperty4 = obj_j.SomeOtherField4
}
The main requirements are:
Property names, types and order in the anonymous objects you're joining on must match.
You CAN'T use ANDs, ORs, etc. in joins. Just object1 equals object2.
More advanced stuff in this LinqPad example:
class c1
{
public int someIntField;
public string someStringField;
}
class c2
{
public Int64 someInt64Property {get;set;}
private object someField;
public string someStringFunction(){return someField.ToString();}
}
void Main()
{
var set1 = new List<c1>();
var set2 = new List<c2>();
var query = from obj_i in set1
join obj_j in set2 on
new {
JoinProperty1 = (Int64) obj_i.someIntField,
JoinProperty2 = obj_i.someStringField
}
equals
new {
JoinProperty1 = obj_j.someInt64Property,
JoinProperty2 = obj_j.someStringFunction()
}
select new {obj1 = obj_i, obj2 = obj_j};
}
Addressing names and property order is straightforward, addressing types can be achieved via casting/converting/parsing/calling methods etc. This might not always work with LINQ to EF or SQL or NHibernate, most method calls definitely won't work and will fail at run-time, so YMMV (Your Mileage May Vary).
This is because they are copied to public read-only properties in the anonymous objects, so as long as your expression produces values of correct type the join property - you should be fine.
What is the simplest C# function to parse a JSON string into an object?
DataContractJsonSerializer serializer =
new DataContractJsonSerializer(typeof(YourObjectType));
YourObjectType yourObject = (YourObjectType)serializer.ReadObject(jsonStream);
You could also use the JavaScriptSerializer
, but DataContractJsonSerializer
is supposedly better able to handle complex types.
Oddly enough JavaScriptSerializer was once deprecated (in 3.5) and then resurrected because of ASP.NET MVC (in 3.5 SP1). That would definitely be enough to shake my confidence and lead me to use DataContractJsonSerializer
since it is hard baked for WCF.
How to make cross domain request
If you're willing to transmit some data and that you don't need to be secured (any public infos) you can use a CORS proxy, it's very easy, you'll not have to change anything in your code or in server side (especially of it's not your server like the Yahoo API or OpenWeather).
I've used it to fetch JSON files with an XMLHttpRequest and it worked fine.
Return HTTP status code 201 in flask
You can use Response to return any http status code.
> from flask import Response
> return Response("{'a':'b'}", status=201, mimetype='application/json')
Convert NaN to 0 in javascript
Something simpler and effective for anything :
function getNum(val) {
val = +val || 0
return val;
}
...which will convert a from any "falsey" value to 0
.
The "falsey" values are:
false
null
undefined
0
""
( empty string )
NaN
( Not a Number )
Fill drop down list on selection of another drop down list
Model:
namespace MvcApplicationrazor.Models
{
public class CountryModel
{
public List<State> StateModel { get; set; }
public SelectList FilteredCity { get; set; }
}
public class State
{
public int Id { get; set; }
public string StateName { get; set; }
}
public class City
{
public int Id { get; set; }
public int StateId { get; set; }
public string CityName { get; set; }
}
}
Controller:
public ActionResult Index()
{
CountryModel objcountrymodel = new CountryModel();
objcountrymodel.StateModel = new List<State>();
objcountrymodel.StateModel = GetAllState();
return View(objcountrymodel);
}
//Action result for ajax call
[HttpPost]
public ActionResult GetCityByStateId(int stateid)
{
List<City> objcity = new List<City>();
objcity = GetAllCity().Where(m => m.StateId == stateid).ToList();
SelectList obgcity = new SelectList(objcity, "Id", "CityName", 0);
return Json(obgcity);
}
// Collection for state
public List<State> GetAllState()
{
List<State> objstate = new List<State>();
objstate.Add(new State { Id = 0, StateName = "Select State" });
objstate.Add(new State { Id = 1, StateName = "State 1" });
objstate.Add(new State { Id = 2, StateName = "State 2" });
objstate.Add(new State { Id = 3, StateName = "State 3" });
objstate.Add(new State { Id = 4, StateName = "State 4" });
return objstate;
}
//collection for city
public List<City> GetAllCity()
{
List<City> objcity = new List<City>();
objcity.Add(new City { Id = 1, StateId = 1, CityName = "City1-1" });
objcity.Add(new City { Id = 2, StateId = 2, CityName = "City2-1" });
objcity.Add(new City { Id = 3, StateId = 4, CityName = "City4-1" });
objcity.Add(new City { Id = 4, StateId = 1, CityName = "City1-2" });
objcity.Add(new City { Id = 5, StateId = 1, CityName = "City1-3" });
objcity.Add(new City { Id = 6, StateId = 4, CityName = "City4-2" });
return objcity;
}
View:
@model MvcApplicationrazor.Models.CountryModel
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script language="javascript" type="text/javascript">
function GetCity(_stateId) {
var procemessage = "<option value='0'> Please wait...</option>";
$("#ddlcity").html(procemessage).show();
var url = "/Test/GetCityByStateId/";
$.ajax({
url: url,
data: { stateid: _stateId },
cache: false,
type: "POST",
success: function (data) {
var markup = "<option value='0'>Select City</option>";
for (var x = 0; x < data.length; x++) {
markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
}
$("#ddlcity").html(markup).show();
},
error: function (reponse) {
alert("error : " + reponse);
}
});
}
</script>
<h4>
MVC Cascading Dropdown List Using Jquery</h4>
@using (Html.BeginForm())
{
@Html.DropDownListFor(m => m.StateModel, new SelectList(Model.StateModel, "Id", "StateName"), new { @id = "ddlstate", @style = "width:200px;", @onchange = "javascript:GetCity(this.value);" })
<br />
<br />
<select id="ddlcity" name="ddlcity" style="width: 200px">
</select>
<br /><br />
}
How to restart Postgresql
On Windows :
1-Open Run Window by Winkey + R
2-Type services.msc
3-Search Postgres service based on version installed.
4-Click stop, start or restart the service option.
On Linux :
sudo systemctl restart postgresql
also instead of "restart" you can replace : status, stop or status.
Deserializing a JSON file with JavaScriptSerializer()
For .Net 4+:
string s = "{ \"user\" : { \"id\" : 12345, \"screen_name\" : \"twitpicuser\"}}";
var serializer = new JavaScriptSerializer();
dynamic usr = serializer.DeserializeObject(s);
var UserId = usr["user"]["id"];
For .Net 2/3.5:
This code should work on JSON with 1 level
samplejson.aspx
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Globalization" %>
<%@ Import Namespace="System.Web.Script.Serialization" %>
<%@ Import Namespace="System.Collections.Generic" %>
<%
string s = "{ \"id\" : 12345, \"screen_name\" : \"twitpicuser\"}";
var serializer = new JavaScriptSerializer();
Dictionary<string, object> result = (serializer.DeserializeObject(s) as Dictionary<string, object>);
var UserId = result["id"];
%>
<%=UserId %>
And for a 2 level JSON:
sample2.aspx
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Globalization" %>
<%@ Import Namespace="System.Web.Script.Serialization" %>
<%@ Import Namespace="System.Collections.Generic" %>
<%
string s = "{ \"user\" : { \"id\" : 12345, \"screen_name\" : \"twitpicuser\"}}";
var serializer = new JavaScriptSerializer();
Dictionary<string, object> result = (serializer.DeserializeObject(s) as Dictionary<string, object>);
Dictionary<string, object> usr = (result["user"] as Dictionary<string, object>);
var UserId = usr["id"];
%>
<%= UserId %>
What is this Javascript "require"?
Alright, so let's first start with making the distinction between Javascript in a web browser, and Javascript on a server (CommonJS and Node).
Javascript is a language traditionally confined to a web browser with a limited global context defined mostly by what came to be known as the Document Object Model (DOM) level 0 (the Netscape Navigator Javascript API).
Server-side Javascript eliminates that restriction and allows Javascript to call into various pieces of native code (like the Postgres library) and open sockets.
Now require()
is a special function call defined as part of the CommonJS spec. In node, it resolves libraries and modules in the Node search path, now usually defined as node_modules
in the same directory (or the directory of the invoked javascript file) or the system-wide search path.
To try to answer the rest of your question, we need to use a proxy between the code running in the the browser and the database server.
Since we are discussing Node and you are already familiar with how to run a query from there, it would make sense to use Node as that proxy.
As a simple example, we're going to make a URL that returns a few facts about a Beatle, given a name, as JSON.
/* your connection code */
var express = require('express');
var app = express.createServer();
app.get('/beatles/:name', function(req, res) {
var name = req.params.name || '';
name = name.replace(/[^a-zA_Z]/, '');
if (!name.length) {
res.send({});
} else {
var query = client.query('SELECT * FROM BEATLES WHERE name =\''+name+'\' LIMIT 1');
var data = {};
query.on('row', function(row) {
data = row;
res.send(data);
});
};
});
app.listen(80, '127.0.0.1');
How do I invoke a Java method when given the method name as a string?
To complete my colleague's answers, You might want to pay close attention to:
- static or instance calls (in one case, you do not need an instance of the class, in the other, you might need to rely on an existing default constructor that may or may not be there)
- public or non-public method call (for the latter,you need to call setAccessible on the method within an doPrivileged block, other findbugs won't be happy)
- encapsulating into one more manageable applicative exception if you want to throw back the numerous java system exceptions (hence the CCException in the code below)
Here is an old java1.4 code which takes into account those points:
/**
* Allow for instance call, avoiding certain class circular dependencies. <br />
* Calls even private method if java Security allows it.
* @param aninstance instance on which method is invoked (if null, static call)
* @param classname name of the class containing the method
* (can be null - ignored, actually - if instance if provided, must be provided if static call)
* @param amethodname name of the method to invoke
* @param parameterTypes array of Classes
* @param parameters array of Object
* @return resulting Object
* @throws CCException if any problem
*/
public static Object reflectionCall(final Object aninstance, final String classname, final String amethodname, final Class[] parameterTypes, final Object[] parameters) throws CCException
{
Object res;// = null;
try {
Class aclass;// = null;
if(aninstance == null)
{
aclass = Class.forName(classname);
}
else
{
aclass = aninstance.getClass();
}
//Class[] parameterTypes = new Class[]{String[].class};
final Method amethod = aclass.getDeclaredMethod(amethodname, parameterTypes);
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
amethod.setAccessible(true);
return null; // nothing to return
}
});
res = amethod.invoke(aninstance, parameters);
} catch (final ClassNotFoundException e) {
throw new CCException.Error(PROBLEM_TO_ACCESS+classname+CLASS, e);
} catch (final SecurityException e) {
throw new CCException.Error(PROBLEM_TO_ACCESS+classname+GenericConstants.HASH_DIESE+ amethodname + METHOD_SECURITY_ISSUE, e);
} catch (final NoSuchMethodException e) {
throw new CCException.Error(PROBLEM_TO_ACCESS+classname+GenericConstants.HASH_DIESE+ amethodname + METHOD_NOT_FOUND, e);
} catch (final IllegalArgumentException e) {
throw new CCException.Error(PROBLEM_TO_ACCESS+classname+GenericConstants.HASH_DIESE+ amethodname + METHOD_ILLEGAL_ARGUMENTS+String.valueOf(parameters)+GenericConstants.CLOSING_ROUND_BRACKET, e);
} catch (final IllegalAccessException e) {
throw new CCException.Error(PROBLEM_TO_ACCESS+classname+GenericConstants.HASH_DIESE+ amethodname + METHOD_ACCESS_RESTRICTION, e);
} catch (final InvocationTargetException e) {
throw new CCException.Error(PROBLEM_TO_ACCESS+classname+GenericConstants.HASH_DIESE+ amethodname + METHOD_INVOCATION_ISSUE, e);
}
return res;
}
NumPy first and last element from array
How about:
In [10]: arr = numpy.array([1,23,4,6,7,8])
In [11]: [(arr[i], arr[-i-1]) for i in range(len(arr) // 2)]
Out[11]: [(1, 8), (23, 7), (4, 6)]
Depending on the size of arr
, writing the entire thing in NumPy may be more performant:
In [41]: arr = numpy.array([1,23,4,6,7,8]*100)
In [42]: %timeit [(arr[i], arr[-i-1]) for i in range(len(arr) // 2)]
10000 loops, best of 3: 167 us per loop
In [43]: %timeit numpy.vstack((arr, arr[::-1]))[:,:len(arr)//2]
100000 loops, best of 3: 16.4 us per loop
LaTeX source code listing like in professional books
Have a try on the listings
package. Here is an example of what I used some time ago to have a coloured Java listing:
\usepackage{listings}
[...]
\lstset{language=Java,captionpos=b,tabsize=3,frame=lines,keywordstyle=\color{blue},commentstyle=\color{darkgreen},stringstyle=\color{red},numbers=left,numberstyle=\tiny,numbersep=5pt,breaklines=true,showstringspaces=false,basicstyle=\footnotesize,emph={label}}
[...]
\begin{lstlisting}
public void here() {
goes().the().code()
}
[...]
\end{lstlisting}
You may want to customize that. There are several references of the listings package. Just google them.
Create a txt file using batch file in a specific folder
This code written above worked for me as well. Although, you can use the code I am writing here:
@echo off
@echo>"d:\testing\dblank.txt
If you want to write some text to dblank.txt then add the following line in the end of your code
@echo Writing text to dblank.txt> dblank.txt
How do I copy an entire directory of files into an existing directory using Python?
Try This:
import os,shutil
def copydir(src, dst):
h = os.getcwd()
src = r"{}".format(src)
if not os.path.isdir(dst):
print("\n[!] No Such directory: ["+dst+"] !!!")
exit(1)
if not os.path.isdir(src):
print("\n[!] No Such directory: ["+src+"] !!!")
exit(1)
if "\\" in src:
c = "\\"
tsrc = src.split("\\")[-1:][0]
else:
c = "/"
tsrc = src.split("/")[-1:][0]
os.chdir(dst)
if os.path.isdir(tsrc):
print("\n[!] The Directory Is already exists !!!")
exit(1)
try:
os.mkdir(tsrc)
except WindowsError:
print("\n[!] Error: In[ {} ]\nPlease Check Your Dirctory Path !!!".format(src))
exit(1)
os.chdir(h)
files = []
for i in os.listdir(src):
files.append(src+c+i)
if len(files) > 0:
for i in files:
if not os.path.isdir(i):
shutil.copy2(i, dst+c+tsrc)
print("\n[*] Done ! :)")
copydir("c:\folder1", "c:\folder2")
Angular HTML binding
On [email protected]:
Html-Binding will not work when using an {{interpolation}}
, use an "Expression" instead:
invalid
<p [innerHTML]="{{item.anleser}}"></p>
-> throws an error (Interpolation instead of expected Expression)
correct
<p [innerHTML]="item.anleser"></p>
-> this is the correct way.
you may add additional elements to the expression, like:
<p [innerHTML]="'<b>'+item.anleser+'</b>'"></p>
hint
HTML added using [innerHTML]
(or added dynamically by other means like element.appenChild()
or similar) won't be processed by Angular in any way except sanitization for security purposed.
Such things work only when the HTML is added statically to a components template. If you need this, you can create a component at runtime like explained in How can I use/create dynamic template to compile dynamic Component with Angular 2.0?
Build error, This project references NuGet
First I would check if your MusicKarma project has Microsoft.Net.Compilers in its packages.config file. If not then you could remove everything to do with that NuGet package from your MusicKarma.csproj.
If you are using the Microsoft.Net.Compilers NuGet package then my guess is that the path is incorrect. Looking at the directory name in the error message I would guess that the MusicKarma solution file (.sln) is in the same directory as the MusicKarma.csproj. If so then the packages directory is probably wrong since by default the packages directory would be inside the solution directory. So I am assuming that your packages directory is:
C:\Users\Bryan\Documents\Visual Studio 2015\Projects\MusicKarma\packages
Whilst your MusicKarma.csproj file is looking for the props file in:
C:\Users\Bryan\Documents\Visual Studio 2015\Projects\packages\Microsoft.Net.Compilers.1.1.1\build
So if that is the case then you can fix the problem by editing the path in your MusicKarma.csproj file or by reinstalling the NuGet package.
How can I add comments in MySQL?
You can use single line comments:
-- this is a comment
# this is also a comment
Or a multiline comment:
/*
multiline
comment
*/
Does Java have an exponential operator?
To do this with user input:
public static void getPow(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter first integer: "); // 3
int first = sc.nextInt();
System.out.println("Enter second integer: "); // 2
int second = sc.nextInt();
System.out.println(first + " to the power of " + second + " is " +
(int) Math.pow(first, second)); // outputs 9
What is the instanceof operator in JavaScript?
I think it's worth noting that instanceof is defined by the use of the "new" keyword when declaring the object. In the example from JonH;
var color1 = new String("green");
color1 instanceof String; // returns true
var color2 = "coral";
color2 instanceof String; // returns false (color2 is not a String object)
What he didn't mention is this;
var color1 = String("green");
color1 instanceof String; // returns false
Specifying "new" actually copied the end state of the String constructor function into the color1 var, rather than just setting it to the return value. I think this better shows what the new keyword does;
function Test(name){
this.test = function(){
return 'This will only work through the "new" keyword.';
}
return name;
}
var test = new Test('test');
test.test(); // returns 'This will only work through the "new" keyword.'
test // returns the instance object of the Test() function.
var test = Test('test');
test.test(); // throws TypeError: Object #<Test> has no method 'test'
test // returns 'test'
Using "new" assigns the value of "this" inside the function to the declared var, while not using it assigns the return value instead.
Android: how do I check if activity is running?
This is code for checking whether a particular service is running. I'm fairly sure it can work for an activity too as long as you change getRunningServices with getRunningAppProcesses() or getRunningTasks(). Have a look here http://developer.android.com/reference/android/app/ActivityManager.html#getRunningAppProcesses()
Change Constants.PACKAGE and Constants.BACKGROUND_SERVICE_CLASS accordingly
public static boolean isServiceRunning(Context context) {
Log.i(TAG, "Checking if service is running");
ActivityManager activityManager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE);
boolean isServiceFound = false;
for (int i = 0; i < services.size(); i++) {
if (Constants.PACKAGE.equals(services.get(i).service.getPackageName())){
if (Constants.BACKGROUND_SERVICE_CLASS.equals(services.get(i).service.getClassName())){
isServiceFound = true;
}
}
}
Log.i(TAG, "Service was" + (isServiceFound ? "" : " not") + " running");
return isServiceFound;
}
Using jQuery to center a DIV on the screen
This is untested, but something like this should work.
var myElement = $('#myElement');
myElement.css({
position: 'absolute',
left: '50%',
'margin-left': 0 - (myElement.width() / 2)
});
How can I display a pdf document into a Webview?
String webviewurl = "http://test.com/testing.pdf";
webView.getSettings().setJavaScriptEnabled(true);
if(webviewurl.contains(".pdf")){
webviewurl = "http://docs.google.com/gview?embedded=true&url=" + webviewurl; }
webview.loadUrl(webviewurl);
Could not load type 'System.ServiceModel.Activation.HttpModule' from assembly 'System.ServiceModel
Hello Thanks for the question;
To resolve: "Could not load type 'System.ServiceModel.Activation.HttpModule' from assembly 'System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'"
In Windows Features check all for .NET 4 Advanced Services & .NET 3.5
Just like Nicolas Gago I tried aspnet_regiis.exe -iru but it didn't work. After the features were on then it yellow screen error was gone. Thanks;
SQL Server: Examples of PIVOTing String data
Well, for your sample and any with a limited number of unique columns, this should do it.
select
distinct a,
(select distinct t2.b from t t2 where t1.a=t2.a and t2.b='VIEW'),
(select distinct t2.b from t t2 where t1.a=t2.a and t2.b='EDIT')
from t t1
How to stop default link click behavior with jQuery
I've just wasted an hour on this. I tried everything - it turned out (and I can hardly believe this) that giving my cancel button and element id of cancel meant that any attempt to prevent event propagation would fail! I guess an HTML page must treat this as someone pressing ESC?
How to check if DST (Daylight Saving Time) is in effect, and if so, the offset?
This code uses the fact that getTimezoneOffset
returns a greater value during Standard Time versus Daylight Saving Time (DST). Thus it determines the expected output during Standard Time, and it compares whether the output of the given date the same (Standard) or less (DST).
Note that getTimezoneOffset
returns positive numbers of minutes for zones west of UTC, which are usually stated as negative hours (since they're "behind" UTC). For example, Los Angeles is UTC–8h Standard, UTC-7h DST. getTimezoneOffset
returns 480
(positive 480 minutes) in December (winter, Standard Time), rather than -480
. It returns negative numbers for the Eastern Hemisphere (such -600
for Sydney in winter, despite this being "ahead" (UTC+10h).
Date.prototype.stdTimezoneOffset = function () {
var jan = new Date(this.getFullYear(), 0, 1);
var jul = new Date(this.getFullYear(), 6, 1);
return Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset());
}
Date.prototype.isDstObserved = function () {
return this.getTimezoneOffset() < this.stdTimezoneOffset();
}
var today = new Date();
if (today.isDstObserved()) {
alert ("Daylight saving time!");
}
How to split/partition a dataset into training and test datasets for, e.g., cross validation?
There is another option that just entails using scikit-learn. As scikit's wiki describes, you can just use the following instructions:
from sklearn.model_selection import train_test_split
data, labels = np.arange(10).reshape((5, 2)), range(5)
data_train, data_test, labels_train, labels_test = train_test_split(data, labels, test_size=0.20, random_state=42)
This way you can keep in sync the labels for the data you're trying to split into training and test.
How to Count Duplicates in List with LINQ
You can use "group by" + "orderby". See LINQ 101 for details
var list = new List<string> {"a", "b", "a", "c", "a", "b"};
var q = from x in list
group x by x into g
let count = g.Count()
orderby count descending
select new {Value = g.Key, Count = count};
foreach (var x in q)
{
Console.WriteLine("Value: " + x.Value + " Count: " + x.Count);
}
In response to this post (now deleted):
If you have a list of some custom objects then you need to use custom comparer or group by specific property.
Also query can't display result. Show us complete code to get a better help.
Based on your latest update:
You have this line of code:
group xx by xx into g
Since xx is a custom object system doesn't know how to compare one item against another.
As I already wrote, you need to guide compiler and provide some property that will be used in objects comparison or provide custom comparer. Here is an example:
Note that I use Foo.Name as a key - i.e. objects will be grouped based on value of Name property.
There is one catch - you treat 2 objects to be duplicate based on their names, but what about Id ? In my example I just take Id of the first object in a group. If your objects have different Ids it can be a problem.
//Using extension methods
var q = list.GroupBy(x => x.Name)
.Select(x => new {Count = x.Count(),
Name = x.Key,
ID = x.First().ID})
.OrderByDescending(x => x.Count);
//Using LINQ
var q = from x in list
group x by x.Name into g
let count = g.Count()
orderby count descending
select new {Name = g.Key, Count = count, ID = g.First().ID};
foreach (var x in q)
{
Console.WriteLine("Count: " + x.Count + " Name: " + x.Name + " ID: " + x.ID);
}
Displaying one div on top of another
There are many ways to do it, but this is pretty simple and avoids issues with disrupting inline content positioning. You might need to adjust for margins/padding, too.
#backdrop, #curtain {
height: 100px;
width: 200px;
}
#curtain {
position: relative;
top: -100px;
}
PHP expects T_PAAMAYIM_NEKUDOTAYIM?
For me this happened within a class function.
In PHP 5.3 and above $this::$defaults
worked fine; when I swapped the code into a server that for whatever reason had a lower version number it threw this error.
The solution, in my case, was to use the keyword self
instead of $this
:
self::$defaults
works just fine.
If Radio Button is selected, perform validation on Checkboxes
Full validation example with javascript:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Radio button: full validation example with javascript</title>
<script>
function send() {
var genders = document.getElementsByName("gender");
if (genders[0].checked == true) {
alert("Your gender is male");
} else if (genders[1].checked == true) {
alert("Your gender is female");
} else {
// no checked
var msg = '<span style="color:red;">You must select your gender!</span><br /><br />';
document.getElementById('msg').innerHTML = msg;
return false;
}
return true;
}
function reset_msg() {
document.getElementById('msg').innerHTML = '';
}
</script>
</head>
<body>
<form action="" method="POST">
<label>Gender:</label>
<br />
<input type="radio" name="gender" value="m" onclick="reset_msg();" />Male
<br />
<input type="radio" name="gender" value="f" onclick="reset_msg();" />Female
<br />
<div id="msg"></div>
<input type="submit" value="send>>" onclick="return send();" />
</form>
</body>
</html>
Regards,
Fernando
Instagram API: How to get all user media?
You're right, the Instagram API will only return 20 images per call. So you'll have to use the pagination feature.
If you're trying to use the API console. You'll want to first allow the API console to authenticate via your Instagram login. To do this you'll want to select OAUTH2 under the Authentication dropdown.
Once Authenticated, use the left hand side menu to select the users/{user-id}/media/recent endpoint. So for the sake of this post for {user-id} you can just replace it with self. This will then use your account to retrieve information.
At a bare minimum that is what's needed to do a GET for this endpoint. Once you send, you'll get some json returned to you. At the very top of the returned information after all the server info, you'll see a pagination portion with next_url and next_max_id.
next_max_id is what you'll use as a parameter for your query. Remember max_id is the id of the image that is the oldest of the 20 that was first returned. This will be used to return images earlier than this image.
You don't have to use the max_id if you don't want to. You can actually just grab the id of the image where you'd like to start querying more images from.
So from the returned data, copy the max_id into the parameter max_id. The request URL should look something like this https://api.instagram.com/v1/users/self/media/recent?max_id=XXXXXXXXXXX where XXXXXXXXXXX is the max_id. Hit send again and you should get the next 20 photos.
From there you'll also receive an updated max_id. You can then use that again to get the next set of 20 photos until eventually going through all of the user's photos.
What I've done in the project I'm working on is to load the first 20 photos returned from the initial recent media request. I then, assign the images with a data-id (-id can actually be whatever you'd like it to be). Then added a load more button on the bottom of the photo set.
When the button is clicked, I use jQuery to grab the last image and it's data-id attribute and use that to create a get call via ajax and append the results to the end of the photos already on the page. Instead of a button you could just replace it to have a infinite scrolling effect.
Hope that helps.