Google Maps basics
Zoom Level - zoom
0 - 19
0 lowest zoom (whole world)
19 highest zoom (individual buildings, if available) Retrieve current zoom level using mapObject.getZoom()
Here is an extended version to Josh Lee's answer. If you want the div to be on sidebar to the right, and float within a range (i.e., you need to specify top and bottom anchor positions). It also fixes a bug when you view this on mobile devices (you need to check left scroll position otherwise the div will move off screen).
function moveScroller() {
var move = function() {
var st = $(window).scrollTop();
var sl = $(window).scrollLeft();
var ot = $("#scroller-anchor-top").offset().top;
var ol = $("#scroller-anchor-top").offset().left;
var bt = $("#scroller-anchor-bottom").offset().top;
var s = $("#scroller");
if(st > ot) {
if (st < bt - 280) //280px is the approx. height for the sticky div
{
s.css({
position: "fixed",
top: "0px",
left: ol-sl
});
}
else
{
s.css({
position: "fixed",
top: bt-st-280,
left: ol-sl
});
}
} else {
s.css({
position: "relative",
top: "",
left: ""
});
}
};
$(window).scroll(move);
move();
}
Here's how you should do it:
change_column :users, :admin, :boolean, :default => false
But some databases, like PostgreSQL, will not update the field for rows previously created, so make sure you update the field manaully on the migration too.
Note that with Doxygen release 1.8.0 you can also add Markdown formated pages. For this to work you need to create pages with a .md
or .markdown
extension, and add the following to the config file:
INPUT += your_page.md
FILE_PATTERNS += *.md *.markdown
See http://www.doxygen.nl/manual/markdown.html#md_page_header for details.
It's important to note that using viewDidLoad for positioning is a bit risky and should be avoided since the bounds are not set. this may cause unexpected results (I had a variety of issues...)
This post describes quite well the different methods and what happens in each of them.
currently for one-time init and positioning I'm thinking of using viewDidAppear with a flag, if anyone has any other recommendation please let me know.
It shows how an algorithm scales based on input size.
O(n2): known as Quadratic complexity
Notice that the number of items increases by a factor of 10, but the time increases by a factor of 102. Basically, n=10 and so O(n2) gives us the scaling factor n2 which is 102.
O(n): known as Linear complexity
This time the number of items increases by a factor of 10, and so does the time. n=10 and so O(n)'s scaling factor is 10.
O(1): known as Constant complexity
The number of items is still increasing by a factor of 10, but the scaling factor of O(1) is always 1.
O(log n): known as Logarithmic complexity
The number of computations is only increased by a log of the input value. So in this case, assuming each computation takes 1 second, the log of the input n
is the time required, hence log n
.
That's the gist of it. They reduce the maths down so it might not be exactly n2 or whatever they say it is, but that'll be the dominating factor in the scaling.
As Dave Webb mentions, the Android Developer Blog has an article that covers this.
I spoke with someone at Google to get some additional clarification on a few items. Here's what I discovered that's NOT mentioned in the aforementioned blog post:
Based on Google's recommendations, I implemented a class that will generate a unique UUID for each device, using ANDROID_ID as the seed where appropriate, falling back on TelephonyManager.getDeviceId() as necessary, and if that fails, resorting to a randomly generated unique UUID that is persisted across app restarts (but not app re-installations).
import android.content.Context;
import android.content.SharedPreferences;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;
import java.io.UnsupportedEncodingException;
import java.util.UUID;
public class DeviceUuidFactory {
protected static final String PREFS_FILE = "device_id.xml";
protected static final String PREFS_DEVICE_ID = "device_id";
protected static volatile UUID uuid;
public DeviceUuidFactory(Context context) {
if (uuid == null) {
synchronized (DeviceUuidFactory.class) {
if (uuid == null) {
final SharedPreferences prefs = context
.getSharedPreferences(PREFS_FILE, 0);
final String id = prefs.getString(PREFS_DEVICE_ID, null);
if (id != null) {
// Use the ids previously computed and stored in the
// prefs file
uuid = UUID.fromString(id);
} else {
final String androidId = Secure.getString(
context.getContentResolver(), Secure.ANDROID_ID);
// Use the Android ID unless it's broken, in which case
// fallback on deviceId,
// unless it's not available, then fallback on a random
// number which we store to a prefs file
try {
if (!"9774d56d682e549c".equals(androidId)) {
uuid = UUID.nameUUIDFromBytes(androidId
.getBytes("utf8"));
} else {
final String deviceId = ((TelephonyManager)
context.getSystemService(
Context.TELEPHONY_SERVICE))
.getDeviceId();
uuid = deviceId != null ? UUID
.nameUUIDFromBytes(deviceId
.getBytes("utf8")) : UUID
.randomUUID();
}
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
// Write the value out to the prefs file
prefs.edit()
.putString(PREFS_DEVICE_ID, uuid.toString())
.commit();
}
}
}
}
}
/**
* Returns a unique UUID for the current android device. As with all UUIDs,
* this unique ID is "very highly likely" to be unique across all Android
* devices. Much more so than ANDROID_ID is.
*
* The UUID is generated by using ANDROID_ID as the base key if appropriate,
* falling back on TelephonyManager.getDeviceID() if ANDROID_ID is known to
* be incorrect, and finally falling back on a random UUID that's persisted
* to SharedPreferences if getDeviceID() does not return a usable value.
*
* In some rare circumstances, this ID may change. In particular, if the
* device is factory reset a new device ID may be generated. In addition, if
* a user upgrades their phone from certain buggy implementations of Android
* 2.2 to a newer, non-buggy version of Android, the device ID may change.
* Or, if a user uninstalls your app on a device that has neither a proper
* Android ID nor a Device ID, this ID may change on reinstallation.
*
* Note that if the code falls back on using TelephonyManager.getDeviceId(),
* the resulting ID will NOT change after a factory reset. Something to be
* aware of.
*
* Works around a bug in Android 2.2 for many devices when using ANDROID_ID
* directly.
*
* @see http://code.google.com/p/android/issues/detail?id=10603
*
* @return a UUID that may be used to uniquely identify your device for most
* purposes.
*/
public UUID getDeviceUuid() {
return uuid;
}
}
The language standard simply doesn't allow for it. Labels can only be followed by statements, and declarations do not count as statements in C. The easiest way to get around this is by inserting an empty statement after your label, which relieves you from keeping track of the scope the way you would need to inside a block.
#include <stdio.h>
int main ()
{
printf("Hello ");
goto Cleanup;
Cleanup: ; //This is an empty statement.
char *str = "World\n";
printf("%s\n", str);
}
Xcode Workspace vs Project
- What is the difference between the two of them?
Workspace
is a set of projects
- What are they responsible for?
Workspace
is responsible for dependencies between projects.
Project
is responsible for the source code.
- Which one of them should I work with when I'm developing my Apps in team/alone?
You choice should depends on a type of your project. For example if your project relies on CocoaPods dependency manager it creates a workspace.
- Is there anything else I should be aware of in matter of these two files?
A competitor of workspace is cross-project references
[About]
In templates, you can separate filter arguments by colons.
{{ yourExpression | yourFilter: arg1:arg2:... }}
From Javascript, you call it as
$filter('yourFilter')(yourExpression, arg1, arg2, ...)
There is actually an example hidden in the orderBy filter docs.
Example:
Let's say you make a filter that can replace things with regular expressions:
myApp.filter("regexReplace", function() { // register new filter
return function(input, searchRegex, replaceRegex) { // filter arguments
return input.replace(RegExp(searchRegex), replaceRegex); // implementation
};
});
Invocation in a template to censor out all digits:
<p>{{ myText | regexReplace: '[0-9]':'X' }}</p>
This is more readable for me
awk '{if ($2 ~ /findtext/) print $3}' <infile>
I used the following solution:
.svg
image to JSX with https://svg2jsx.herokuapp.com/react-native-svg
component with https://svgr.now.sh/ (check the "React Native checkbox)Ad-hoc Statments are just T-SQL Statements that it has a Where Clause , and that Where clause can actualy have a literal like :
Select * from member where member_no=285;
or a variable :
declare @mno INT=285;
Select * from member where member_no=@mno
put the following in the site's .htaccess file (in the /var/www/XXX):
Header set Access-Control-Allow-Origin "*"
instead of the .conf file.
You'll also want to use
AllowOverride All
in your .conf file for the domain so Apache looks at it.
The modern way is to use ParentNode.append()
, like so:
let element = document.createElement('div');_x000D_
element.style.cssText = 'position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000;';_x000D_
document.body.append(element);
_x000D_
git rev-parse
is an ancillary plumbing
command primarily used for manipulation.
One common usage of git rev-parse
is to print the SHA1 hashes given a revision specifier. In addition, it has various options to format this output such as --short
for printing a shorter unique SHA1.
There are other use cases as well (in scripts and other tools built on top of git) that I've used for:
--verify
to verify that the specified object is a valid git object.--git-dir
for displaying the abs/relative path of the the .git
directory.--is-inside-git-dir
or within a work-tree using --is-inside-work-tree
--is-bare-repository
--branches
), tags (--tags
) and the refs can also be filtered based on the remote (using --remote
)--parse-opt
to normalize arguments in a script (kind of similar to getopt
) and print an output string that can be used with eval
Massage
just implies that it is possible to convert the info from one form into another i.e. a transformation command. These are some quick examples I can think of:
A..B
for git log
or git diff
into the equivalent arguments for the underlying plumbing command as B ^A
When you're doing this
var model = @Html.Raw(Json.Encode(Model));
You're probably getting a JSON string, and not a JavaScript object.
You need to parse it in to an object:
var model = JSON.parse(model); //or $.parseJSON() since if jQuery is included
console.log(model.Sections);
The question did not state precisely what output is expected but assuming that for month you want the month number (January = 1) and for the year you want the numeric 4 digit year then assuming that we have just run the code in the question:
cycle(date1)
## [1] 3
as.integer(date1)
## [1] 2012
A summary of tests.
[ -n "$var" ] && echo "var is set and not empty"
[ -z "$var" ] && echo "var is unset or empty"
[ "${var+x}" = "x" ] && echo "var is set" # may or may not be empty
[ -n "${var+x}" ] && echo "var is set" # may or may not be empty
[ -z "${var+x}" ] && echo "var is unset"
[ -z "${var-x}" ] && echo "var is set and empty"
Why not just use the else ?
if (child is IContainer)
{
//
}
else
{
// Do what you want here
}
Its neat it familiar and simple ?
The iBeacon output power is measured (calibrated) at a distance of 1 meter. Let's suppose that this is -59 dBm (just an example). The iBeacon will include this number as part of its LE advertisment.
The listening device (iPhone, etc), will measure the RSSI of the device. Let's suppose, for example, that this is, say, -72 dBm.
Since these numbers are in dBm, the ratio of the power is actually the difference in dB. So:
ratio_dB = txCalibratedPower - RSSI
To convert that into a linear ratio, we use the standard formula for dB:
ratio_linear = 10 ^ (ratio_dB / 10)
If we assume conservation of energy, then the signal strength must fall off as 1/r^2. So:
power = power_at_1_meter / r^2
. Solving for r, we get:
r = sqrt(ratio_linear)
In Javascript, the code would look like this:
function getRange(txCalibratedPower, rssi) {
var ratio_db = txCalibratedPower - rssi;
var ratio_linear = Math.pow(10, ratio_db / 10);
var r = Math.sqrt(ratio_linear);
return r;
}
Note, that, if you're inside a steel building, then perhaps there will be internal reflections that make the signal decay slower than 1/r^2. If the signal passes through a human body (water) then the signal will be attenuated. It's very likely that the antenna doesn't have equal gain in all directions. Metal objects in the room may create strange interference patterns. Etc, etc... YMMV.
All the above solutions have deficiencies where the last search string is repeated elsewhere in the string. I found it best to write a bash function.
function str_str {
local str
str="${1#*${2}}"
str="${str%%$3*}"
echo -n "$str"
}
# test it ...
mystr="this is a string"
str_str "$mystr" "this " " string"
Most of the aspects are covered. But there could be a requirement to find the aggregation of other data types apart from Integer, Long(for which specialized stream support is already present). For e.g. stram with BigInteger For such a type we can use reduce operation like
list.stream().reduce((bigInteger1, bigInteger2) -> bigInteger1.add(bigInteger2))
String myFormat= "yyyy-MM-dd";
String finalString = "";
try {
DateFormat formatter = new SimpleDateFormat("yyyy MMM dd");
Date date = (Date) formatter .parse("2015 Oct 09");
SimpleDateFormat newFormat = new SimpleDateFormat(myFormat);
finalString= newFormat .format(date );
newDate.setText(finalString);
} catch (Exception e) {
}
You turn off pack_propagate
by setting pack_propagate(0)
Turning off pack_propagate
here basically says don't let the widgets inside the frame control it's size. So you've set it's width and height to be 500. Turning off propagate stills allows it to be this size without the widgets changing the size of the frame to fill their respective width / heights which is what would happen normally
To turn off resizing the root window, you can set root.resizable(0, 0)
, where resizing is allowed in the x
and y
directions respectively.
To set a maxsize to window, as noted in the other answer you can set the maxsize
attribute or minsize
although you could just set the geometry of the root window and then turn off resizing. A bit more flexible imo.
Whenever you set grid
or pack
on a widget it will return None
. So, if you want to be able to keep a reference to the widget object you shouldn't be setting a variabe to a widget where you're calling grid
or pack
on it. You should instead set the variable to be the widget Widget(master, ....)
and then call pack
or grid
on the widget instead.
import tkinter as tk
def startgame():
pass
mw = tk.Tk()
#If you have a large number of widgets, like it looks like you will for your
#game you can specify the attributes for all widgets simply like this.
mw.option_add("*Button.Background", "black")
mw.option_add("*Button.Foreground", "red")
mw.title('The game')
#You can set the geometry attribute to change the root windows size
mw.geometry("500x500") #You want the size of the app to be 500x500
mw.resizable(0, 0) #Don't allow resizing in the x or y direction
back = tk.Frame(master=mw,bg='black')
back.pack_propagate(0) #Don't allow the widgets inside to determine the frame's width / height
back.pack(fill=tk.BOTH, expand=1) #Expand the frame to fill the root window
#Changed variables so you don't have these set to None from .pack()
go = tk.Button(master=back, text='Start Game', command=startgame)
go.pack()
close = tk.Button(master=back, text='Quit', command=mw.destroy)
close.pack()
info = tk.Label(master=back, text='Made by me!', bg='red', fg='black')
info.pack()
mw.mainloop()
Pull changes first:
git pull origin branch_name
your string is NOT a valid json to start with.
a valid json will be,
{
"area": [
{
"area": "kothrud"
},
{
"area": "katraj"
}
]
}
if you do a json_decode
, it will yield,
stdClass Object
(
[area] => Array
(
[0] => stdClass Object
(
[area] => kothrud
)
[1] => stdClass Object
(
[area] => katraj
)
)
)
Update: to use
$string = '
{
"area": [
{
"area": "kothrud"
},
{
"area": "katraj"
}
]
}
';
$area = json_decode($string, true);
foreach($area['area'] as $i => $v)
{
echo $v['area'].'<br/>';
}
Output:
kothrud
katraj
Update #2:
for that true
:
When TRUE, returned objects will be converted into associative arrays. for more information, click here
A lot of the old TextFX operations like removing empty lines and sorting are available under:
Menu Edit ? Line Operations
Is this what you are looking for? Otherwise, let me know and I will remove this post.
Try this jQuery plugin: http://archive.plugins.jquery.com/project/client-detect
Demo: http://www.stoimen.com/jquery.client.plugin/
This is based on quirksmode BrowserDetect a wrap for jQuery browser/os detection plugin.
For keen readers:
http://www.stoimen.com/blog/2009/07/16/jquery-browser-and-os-detection-plugin/
http://www.quirksmode.org/js/support.html
And more code around the plugin resides here: http://www.stoimen.com/jquery.client.plugin/jquery.client.js
Using Bash you may insert a TAB character programmatically like so:
TAB=$'\t'
echo 'line' | sed "s/.*/${TAB}&/g"
echo 'line' | sed 's/.*/'"${TAB}"'&/g' # use of Bash string concatenation
Thought I'd give a full answer combining some of the possible intricacies required for completeness.
w3wp.exe
. If it's showing as w3wp*32.exe
then it's 32-bit.Sample DF:
In [79]: df = pd.DataFrame(np.random.randint(5, 15, (10, 3)), columns=list('abc'))
In [80]: df
Out[80]:
a b c
0 6 11 11
1 14 7 8
2 13 5 11
3 13 7 11
4 13 5 9
5 5 11 9
6 9 8 6
7 5 11 10
8 8 10 14
9 7 14 13
present only those rows where b > 10
In [81]: df[df.b > 10]
Out[81]:
a b c
0 6 11 11
5 5 11 9
7 5 11 10
9 7 14 13
Minimums (for all columns) for the rows satisfying b > 10
condition
In [82]: df[df.b > 10].min()
Out[82]:
a 5
b 11
c 9
dtype: int32
Minimum (for the b
column) for the rows satisfying b > 10
condition
In [84]: df.loc[df.b > 10, 'b'].min()
Out[84]: 11
UPDATE: starting from Pandas 0.20.1 the .ix indexer is deprecated, in favor of the more strict .iloc and .loc indexers.
put anyfile on the directories you wanted to find, in this case, place 'root' at public_html
/home/user/public_html/root <- note that 'root' is not a folder (you can use root.txt if u want)
And use this function
function findThis($get){
$d = '';
for($i = 0; $i < 20; $i++){//this will try 20 times recursively on upper folder
if(file_exists($d.$get)){
return $d;
}else{
$d.="../";
}
}
}
and get the value by calling it
$pathToRoot = findThis('root');
And it will return, for example the the dir of php script is
/home/user/public_html/test/another-dir/test.php
so the $pathToRoot will be
$pathToRoot => "../../../"
Is this the one you want??
Once you have cloned the repo, you have everything: you can then hg up branchname
or hg up tagname
to update your working copy.
UP: hg up
is a shortcut of hg update
, which also has hg checkout
alias for people with git
habits.
SQL>
SELECT interview.qtrcode QTR, interview.companyname "Company Name", interview.division Division
FROM interview
JOIN jobsdev.employer
ON (interview.companyname = employer.companyname AND employer.zipcode like '100%')
GROUP BY interview.qtrcode, interview.companyname, interview.division
ORDER BY interview.qtrcode;
Zoom level 0 is the most zoomed out zoom level available and each integer step in zoom level halves the X and Y extents of the view and doubles the linear resolution.
Google Maps was built on a 256x256 pixel tile system where zoom level 0 was a 256x256 pixel image of the whole earth. A 256x256 tile for zoom level 1 enlarges a 128x128 pixel region from zoom level 0.
As correctly stated by bkaid, the available zoom range depends on where you are looking and the kind of map you are using:
Note that these values are for the Google Static Maps API which seems to give one more zoom level than the Javascript API. It appears that the extra zoom level available for Static Maps is just an upsampled version of the max-resolution image from the Javascript API.
Google Maps uses a Mercator projection so the scale varies substantially with latitude. A formula for calculating the correct scale based on latitude is:
meters_per_pixel = 156543.03392 * Math.cos(latLng.lat() * Math.PI / 180) / Math.pow(2, zoom)
Formula is from Chris Broadfoot's comment.
Google Maps basics
Zoom Level - zoom
0 - 19
0 lowest zoom (whole world)
19 highest zoom (individual buildings, if available) Retrieve current zoom level using mapObject.getZoom()
What you're looking for are the scales for each zoom level. Use these:
20 : 1128.497220
19 : 2256.994440
18 : 4513.988880
17 : 9027.977761
16 : 18055.955520
15 : 36111.911040
14 : 72223.822090
13 : 144447.644200
12 : 288895.288400
11 : 577790.576700
10 : 1155581.153000
9 : 2311162.307000
8 : 4622324.614000
7 : 9244649.227000
6 : 18489298.450000
5 : 36978596.910000
4 : 73957193.820000
3 : 147914387.600000
2 : 295828775.300000
1 : 591657550.500000
I add aliases to the .bash_alaises to switch to a different project.
alias switch_proj1="gcloud config set project ************"
Here is a script to generate aliases :) for all projects listed. Please update the switch_proj to unique project aliases that you can remember.
gcloud projects list | awk '{print "alias switch_proj=\"gcloud config set project " $1 "\""}'
Finally, I've defeated my CiSCO EAP-FAST corporate wifi network, and all our Android devices are now able to connect to it.
The walk-around I've performed in order to gain access to this kind of networks from an Android device are easiest than you can imagine.
There's a Wifi Config Editor in the Google Play Store you can use to "activate" the secondary CISCO Protocols when you are setting up a EAP wifi connection.
Its name is Wifi Config Advanced Editor.
First, you have to setup your wireless network manually as close as you can to your "official" corporate wifi parameters.
Save it.
Go to the WCE and edit the parameters of the network you have created in the previous step.
There are 3 or 4 series of settings you should activate in order to force the Android device to use them as a way to connect (the main site I think you want to visit is Enterprise Configuration, but don't forget to check all the parameters to change them if needed.
As a suggestion, even if you have a WPA2 EAP-FAST Cipher, try LEAP in your setup. It worked for me as a charm.
When you finished to edit the config, go to the main Android wifi controller, and force to connect to this network.
Do not Edit the network again with the Android wifi interface.
I have tested it on Samsung Galaxy 1 and 2, Note mobile devices, and on a Lenovo Thinkpad Tablet.
Just a followup to smashery's answer. The ephemeral port range (on Linux at least, and I suspect other Unices as well) is not a fixed. This can be controlled by writing to
/proc/sys/net/ipv4/ip_local_port_range
The only restriction (as far as IANA is concerned) is that ports below 1024 are designated to be well-known ports. Ports above that are free for use. Often you'll find that ports below 1024 are restricted to superuser access, I believe for this very reason.
You can add property to your model as follows:
public string DetailsClass { get { return Details.Count > 0 ? "show" : "hide" } }
and then your view will be simpler and will contain no logic at all:
<div class="details @Model.DetailsClass"/>
This will work even with many classes and will not render class if it is null:
<div class="@Model.Class1 @Model.Class2"/>
with 2 not null properties will render:
<div class="class1 class2"/>
if class1 is null
<div class=" class2"/>
There is a LARGE collection of attributes you can't set in IE using .setAttribute() which includes every inline event handler.
See here for details:
http://webbugtrack.blogspot.com/2007/08/bug-242-setattribute-doesnt-always-work.html
If your grep supports -R
, do:
grep -R 'string' dir/
If not, then use find
:
find dir/ -type f -exec grep -H 'string' {} +
I assume you want to link to a library called foo, its filename is usually something link foo.dll
or libfoo.so
.
1. Find the library
You have to find the library. This is a good idea, even if you know the path to your library. CMake will error out if the library vanished or got a new name. This helps to spot error early and to make it clear to the user (may yourself) what causes a problem.
To find a library foo and store the path in FOO_LIB
use
find_library(FOO_LIB foo)
CMake will figure out itself how the actual file name is. It checks the usual places like /usr/lib
, /usr/lib64
and the paths in PATH
.
You already know the location of your library. Add it to the CMAKE_PREFIX_PATH
when you call CMake, then CMake will look for your library in the passed paths, too.
Sometimes you need to add hints or path suffixes, see the documentation for details: https://cmake.org/cmake/help/latest/command/find_library.html
2. Link the library
From 1. you have the full library name in FOO_LIB
. You use this to link the library to your target GLBall
as in
target_link_libraries(GLBall PRIVATE "${FOO_LIB}")
You should add PRIVATE
, PUBLIC
, or INTERFACE
after the target, cf. the documentation:
https://cmake.org/cmake/help/latest/command/target_link_libraries.html
If you don't add one of these visibility specifiers, it will either behave like PRIVATE
or PUBLIC
, depending on the CMake version and the policies set.
3. Add includes (This step might be not mandatory.)
If you also want to include header files, use find_path
similar to find_library
and search for a header file. Then add the include directory with target_include_directories
similar to target_link_libraries
.
Documentation: https://cmake.org/cmake/help/latest/command/find_path.html and https://cmake.org/cmake/help/latest/command/target_include_directories.html
If available for the external software, you can replace find_library
and find_path
by find_package
.
You do not need it.
If your action has the HttpPost
attribute, then you do not need to bother with setting the JsonRequestBehavior
and use the overload without it. There is an overload for each method without the JsonRequestBehavior
enum. Here they are:
Without JsonRequestBehavior
protected internal JsonResult Json(object data);
protected internal JsonResult Json(object data, string contentType);
protected internal virtual JsonResult Json(object data, string contentType, Encoding contentEncoding);
With JsonRequestBehavior
protected internal JsonResult Json(object data, JsonRequestBehavior behavior);
protected internal JsonResult Json(object data, string contentType,
JsonRequestBehavior behavior);
protected internal virtual JsonResult Json(object data, string contentType,
Encoding contentEncoding, JsonRequestBehavior behavior);
Like it's already mentioned, I would highly recommend using regular expression (in System.Text) to get this kind of job done.
In combo with a solid tool like RegexBuddy, you are looking at handling any complex text record parsing situations, as well as getting results quickly. The tool makes it real easy.
Hope that helps.
>>> L = ['apple','red','apple','red','red','pear']
>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> for i in L:
... d[i] += 1
>>> d
defaultdict(<type 'int'>, {'pear': 1, 'apple': 2, 'red': 3})
This is just debugging message. You can switch that off by right clicking into the output window and uncheck Thread Exit Messages
.
http://msdn.microsoft.com/en-us/library/bs4c1wda.aspx
In addition to program out from your application, the Output window can display the information about:
Modules the debugger has loaded or unloaded.
Exceptions that are thrown.
Processes that exit.
Threads that exit.
The easier one for newbies:
Button button = new Button();
button.Click += new EventHandler(button_Click);
protected void button_Click (object sender, EventArgs e)
{
Button button = sender as Button;
// identify which button was clicked and perform necessary actions
}
I think you are intended to contain ALL YOUR LOGIC under your if
statement. Basically:
' PRINTS EVERYTHING EXCEPT 4
For i = 0 To 10
' you want to say
' If i = 4 CONTINUE but VBScript has no continue
If i <> 4 Then ' just invert the logic
WSH.Echo( i )
End If
Next
This can make the code a bit longer, but some people don't like break
or continue
anyway.
Simply you could use:
PartialView("../ABC/XXX")
Another way would be adding __getitem__, __setitem__ function
def __getitem__(self, key):
return getattr(self, key)
You can use self[key] to access now.
You don't have the namespace the Login class is in as a reference.
Add the following to the form that uses the Login
class:
using FootballLeagueSystem;
When you want to use a class in another namespace, you have to tell the compiler where to find it. In this case, Login
is inside the FootballLeagueSystem
namespace, or : FootballLeagueSystem.Login
is the fully qualified namespace.
As a commenter pointed out, you declare the Login class inside the FootballLeagueSystem
namespace, but you're using it in the FootballLeague
namespace.
REPLACE(<your xml column>,'&',chr(38)||'amp;')
With this code you can open the whatsapp chat with the given number.
void openWhatsappContact(String number) {
Uri uri = Uri.parse("smsto:" + number);
Intent i = new Intent(Intent.ACTION_SENDTO, uri);
i.setPackage("com.whatsapp");
startActivity(Intent.createChooser(i, ""));
}
jeues answer helped me nothing :-( after hours I finally found the solution for my system and I think this will help other people too. I had to set the LD_LIBRARY_PATH like this:
export LD_LIBRARY_PATH=/usr/lib/x86_64-linux-gnu/
after that everything worked very well, even without any "-extension RANDR" switch.
TL;DR Log all your queries and tail the mysql log.
These directions are for my install of Ubuntu 14.04. Issue command lsb_release -a
to get your version. Your install might be different.
cd /etc/mysql
. You should see a file called my.cnf
. That’s the file we’re gonna change.cat my.cnf | grep general_log
. This filters the my.cnf
file for you. You should see two entries: #general_log_file = /var/log/mysql/mysql.log
&& #general_log = 1
.sudo service mysql restart
. sudo service nginx restart
.Nice work! You’re all set. Now all you have to do is tail the log file so you can see the PDO queries your app makes in real time.
Enter this cmd tail -f /var/log/mysql/mysql.log
.
Your output will look something like this:
73 Connect xyz@localhost on your_db
73 Query SET NAMES utf8mb4
74 Connect xyz@localhost on your_db
75 Connect xyz@localhost on your_db
74 Quit
75 Prepare SELECT email FROM customer WHERE email=? LIMIT ?
75 Execute SELECT email FROM customer WHERE email='[email protected]' LIMIT 5
75 Close stmt
75 Quit
73 Quit
Any new queries your app makes will automatically pop into view, as long as you continue tailing the log. To exit the tail, hit cmd/ctrl c
.
truncate --size 0 mysql.log
.Huge shout out to Nathan Long’s answer above for the inspo to figure this out on Ubuntu. Also to dikirill for his comment on Nathan’s post which lead me to this solution.
Love you stackoverflow!
If the commit you want to revert is a merged commit (has been merged already), then you should either -m 1
or -m 2
option as shown below. This will let git know which parent commit of the merged commit to use. More details can be found HERE.
git revert <commit> -m 1
git revert <commit> -m 2
Following code is doing the job using reflection. It assumes you have getters for the properties you want to serialize
<?php
/**
* Serialize a simple PHP object into json
* Should be used for POPO that has getter methods for the relevant properties to serialize
* A property can be simple or by itself another POPO object
*
* Class CleanJsonSerializer
*/
class CleanJsonSerializer {
/**
* Local cache of a property getters per class - optimize reflection code if the same object appears several times
* @var array
*/
private $classPropertyGetters = array();
/**
* @param mixed $object
* @return string|false
*/
public function serialize($object)
{
return json_encode($this->serializeInternal($object));
}
/**
* @param $object
* @return array
*/
private function serializeInternal($object)
{
if (is_array($object)) {
$result = $this->serializeArray($object);
} elseif (is_object($object)) {
$result = $this->serializeObject($object);
} else {
$result = $object;
}
return $result;
}
/**
* @param $object
* @return \ReflectionClass
*/
private function getClassPropertyGetters($object)
{
$className = get_class($object);
if (!isset($this->classPropertyGetters[$className])) {
$reflector = new \ReflectionClass($className);
$properties = $reflector->getProperties();
$getters = array();
foreach ($properties as $property)
{
$name = $property->getName();
$getter = "get" . ucfirst($name);
try {
$reflector->getMethod($getter);
$getters[$name] = $getter;
} catch (\Exception $e) {
// if no getter for a specific property - ignore it
}
}
$this->classPropertyGetters[$className] = $getters;
}
return $this->classPropertyGetters[$className];
}
/**
* @param $object
* @return array
*/
private function serializeObject($object) {
$properties = $this->getClassPropertyGetters($object);
$data = array();
foreach ($properties as $name => $property)
{
$data[$name] = $this->serializeInternal($object->$property());
}
return $data;
}
/**
* @param $array
* @return array
*/
private function serializeArray($array)
{
$result = array();
foreach ($array as $key => $value) {
$result[$key] = $this->serializeInternal($value);
}
return $result;
}
}
The main difference is ::
npm install is a npm cli-command which does the predefined thing i.e, as written by Churro, to install dependencies specified inside package.json
npm run command-name or npm run-script command-name ( ex. npm run build ) is also a cli-command predefined to run your custom scripts with the name specified in place of "command-name". So, in this case npm run build is a custom script command with the name "build" and will do anything specified inside it (for instance echo 'hello world' given in below example package.json).
Ponits to note::
One more thing, npm build
and npm run build
are two different things, npm run build
will do custom work written inside package.json
and npm build
is a pre-defined script (not available to use directly)
You cannot specify some thing inside custom build script (npm run build
) script and expect npm build
to do the same. Try following thing to verify in your package.json
:
{ "name": "demo", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "build":"echo 'hello build'" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": {}, "dependencies": {} }
and run npm run build
and npm build
one by one and you will see the difference. For more about commands kindly follow npm documentation.
Cheers!!
This header is defined in RFC 2183, so that would be the best place to start reading.
Permitted values are those registered with the Internet Assigned Numbers Authority (IANA); their registry of values should be seen as the definitive source.
my sample code
wv = (WebView) findViewById(R.id.mywebview);
wv.getLayoutParams().height = LayoutParams.MATCH_PARENT; // LayoutParams: android.view.ViewGroup.LayoutParams
// wv.getLayoutParams().height = LayoutParams.WRAP_CONTENT;
wv.requestLayout();//It is necesary to refresh the screen
Best way to do what you want is to add another server block:
server {
#implemented by default, change if you need different ip or port
#listen *:80 | *:8000;
server_name test.com;
return 301 $scheme://www.test.com$request_uri;
}
And edit your main server block server_name variable as following:
server_name www.test.com;
Important: New server
block is the right way to do this, if
is evil. You must use locations and servers instead of if
if it's possible. Rewrite
is sometimes evil too, so replaced it with return
.
Use JSON.
In the following example $php_variable
can be any PHP variable.
<script type="text/javascript">
var obj = <?php echo json_encode($php_variable); ?>;
</script>
In your code, you could use like the following:
drawChart(600/50, <?php echo json_encode($day); ?>, ...)
In cases where you need to parse out an object from JSON-string (like in an AJAX request), the safe way is to use JSON.parse(..)
like the below:
var s = "<JSON-String>";
var obj = JSON.parse(s);
just put chart
$('#container').highcharts({
colors: ['#31BFA2'], // change color here
chart: {
type: 'column'
}, .... Continue chart
ffmpeg
and not usingOne-liner solution using ls
ls video1.mp4 video2.mp4 | while read line; do echo file \'$line\'; done | ffmpeg -protocol_whitelist file,pipe -f concat -i - -c copy output.mp4
Function which takes 0 or 2+ arguments
#######################################
# Merge mp4 files into one output mp4 file
# usage:
# mergemp4 #merges all mp4 in current directory
# mergemp4 video1.mp4 video2.mp4
# mergemp4 video1.mp4 video2.mp4 [ video3.mp4 ...] output.mp4
#######################################
function mergemp4() {
if [ $# = 1 ]; then return; fi
outputfile="output.mp4"
#if no arguments we take all mp4 in current directory as array
if [ $# = 0 ]; then inputfiles=($(ls -1v *.mp4)); fi
if [ $# = 2 ]; then inputfiles=($1 $2); fi
if [ $# -ge 3 ]; then
outputfile=${@: -1} # Get the last argument
inputfiles=(${@:1:$# - 1}) # Get all arguments besides last one as array
fi
# -y: automatically overwrite output file if exists
# -loglevel quiet: disable ffmpeg logs
ffmpeg -y \
-loglevel quiet \
-f concat \
-safe 0 \
-i <(for f in $inputfiles; do echo "file '$PWD/$f'"; done) \
-c copy $outputfile
if test -f "$outputfile"; then echo "$outputfile created"; fi
}
Note: had tried some solutions in this thread and none satisfied me
Just try with
$("._statusDDL").val("2");
and not with
$("._statusDDL").val(2);
As of Python 3.7 the following code works fine:
from json import dumps
result = {"symbol": "ƒ"}
json_string = dumps(result, sort_keys=True, indent=2, ensure_ascii=False)
print(json_string)
Output:
{"symbol": "ƒ"}
Sometimes if the update application is abruptly stopped, then the lock remains stuck.
Then running
UPDATE DATABASECHANGELOGLOCK SET LOCKED=0, LOCKGRANTED=null, LOCKEDBY=null where ID=1;
against the database helps.
You may also need to replace LOCKED=0
with LOCKED=FALSE
.
Or you can simply drop the DATABASECHANGELOGLOCK
table, it will be recreated.
This should help.
Integer startIn = null;
// (optional below but a good practice, to prevent errors.)
boolean dontContinue = false;
try {
Integer.parseInt (startField.getText());
} catch (NumberFormatException e){
e.printStackTrace();
}
// in java = assigns a boolean in if statements oddly.
// Thus double equal must be used. So if startIn is null, display the message
if (startIn == null) {
JOptionPane.showMessageDialog(null,
"You must enter a number between 0-16.","Input Error",
JOptionPane.ERROR_MESSAGE);
}
// (again optional)
if (dontContinue == true) {
//Do-some-error-fix
}
My answer builds on top of given answers but makes regex matching more robust by adding additional support:
do/catch
by not printing to the console and makes use of the guard
constructmatchingStrings
as an extension to String
Swift 4.2
//: Playground - noun: a place where people can play
import Foundation
extension String {
func matchingStrings(regex: String) -> [[String]] {
guard let regex = try? NSRegularExpression(pattern: regex, options: []) else { return [] }
let nsString = self as NSString
let results = regex.matches(in: self, options: [], range: NSMakeRange(0, nsString.length))
return results.map { result in
(0..<result.numberOfRanges).map {
result.range(at: $0).location != NSNotFound
? nsString.substring(with: result.range(at: $0))
: ""
}
}
}
}
"prefix12 aaa3 prefix45".matchingStrings(regex: "fix([0-9])([0-9])")
// Prints: [["fix12", "1", "2"], ["fix45", "4", "5"]]
"prefix12".matchingStrings(regex: "(?:prefix)?([0-9]+)")
// Prints: [["prefix12", "12"]]
"12".matchingStrings(regex: "(?:prefix)?([0-9]+)")
// Prints: [["12", "12"]], other answers return an empty array here
// Safely accessing the capture of the first match (if any):
let number = "prefix12suffix".matchingStrings(regex: "fix([0-9]+)su").first?[1]
// Prints: Optional("12")
Swift 3
//: Playground - noun: a place where people can play
import Foundation
extension String {
func matchingStrings(regex: String) -> [[String]] {
guard let regex = try? NSRegularExpression(pattern: regex, options: []) else { return [] }
let nsString = self as NSString
let results = regex.matches(in: self, options: [], range: NSMakeRange(0, nsString.length))
return results.map { result in
(0..<result.numberOfRanges).map {
result.rangeAt($0).location != NSNotFound
? nsString.substring(with: result.rangeAt($0))
: ""
}
}
}
}
"prefix12 aaa3 prefix45".matchingStrings(regex: "fix([0-9])([0-9])")
// Prints: [["fix12", "1", "2"], ["fix45", "4", "5"]]
"prefix12".matchingStrings(regex: "(?:prefix)?([0-9]+)")
// Prints: [["prefix12", "12"]]
"12".matchingStrings(regex: "(?:prefix)?([0-9]+)")
// Prints: [["12", "12"]], other answers return an empty array here
// Safely accessing the capture of the first match (if any):
let number = "prefix12suffix".matchingStrings(regex: "fix([0-9]+)su").first?[1]
// Prints: Optional("12")
Swift 2
extension String {
func matchingStrings(regex: String) -> [[String]] {
guard let regex = try? NSRegularExpression(pattern: regex, options: []) else { return [] }
let nsString = self as NSString
let results = regex.matchesInString(self, options: [], range: NSMakeRange(0, nsString.length))
return results.map { result in
(0..<result.numberOfRanges).map {
result.rangeAtIndex($0).location != NSNotFound
? nsString.substringWithRange(result.rangeAtIndex($0))
: ""
}
}
}
}
Use extend to add a list comprehension to the end.
l.extend([x for i in range(100)])
See the Python docs for more information.
For future searchers, if none of the above worked, for me, python was trying to open a folder as a file.
Missing the 'implements' keyword in the impl classes might also be the issue
Unfortunately none of these answers worked for me... here was the error I was seeing:
"Multiple commands produce '/Users/.../.../.../Frameworks/abcdef.framework"
Adding this line to the Podfile and doing a " Pod Install " was the ONLY thing that worked.
install! 'cocoapods', :disable_input_output_paths => true
I really hope this helps someone. I spent hours trying to fix this and finally got it.
Sometimes I just wish Xcode was as efficient as IntelliJ / Android Studio :(
Goodluck!
In my case, the port that tomcat was running on was defined in an application.properties file for 8000, not 8080. In my case, it looked like the same problem described here. Just leaving this here in case anyone has a similar setup and issue! :)
Unchecked the content type in Postman and postman automatically detect the content type based on your input in the run time.
My share
I have tested print(-(-101 // 5)) = 21
given example above.
Now for rounding up:
101 * 19% = 19.19
I can not use **
so I spread the multiply to division:
(-(-101 //(1/0.19))) = 20
The correct answer:
<form role="search" method="get" action="" target="_blank"></form>
Supported in all major browsers :)
Here's one possible method.
function isMouseInBox(e) {
var textbox = document.getElementById('textbox');
// Box position & sizes
var boxX = textbox.offsetLeft;
var boxY = textbox.offsetTop;
var boxWidth = textbox.offsetWidth;
var boxHeight = textbox.offsetHeight;
// Mouse position comes from the 'mousemove' event
var mouseX = e.pageX;
var mouseY = e.pageY;
if(mouseX>=boxX && mouseX<=boxX+boxWidth) {
if(mouseY>=boxY && mouseY<=boxY+boxHeight){
// Mouse is in the box
return true;
}
}
}
document.addEventListener('mousemove', function(e){
isMouseInBox(e);
})
I use the following vba code where filename is a string containing the filename I want, and Function RemoveSpecialCharactersAndTruncate is defined below:
worksheet1.Name = RemoveSpecialCharactersAndTruncate(filename)
'Function to remove special characters from file before saving
Private Function RemoveSpecialCharactersAndTruncate$(ByVal FormattedString$)
Dim IllegalCharacterSet$
Dim i As Integer
'Set of illegal characters
IllegalCharacterSet$ = "*." & Chr(34) & "//\[]:;|=,"
'Iterate through illegal characters and replace any instances
For i = 1 To Len(IllegalCharacterSet) - 1
FormattedString$ = Replace(FormattedString$, Mid(IllegalCharacterSet, i, 1), "")
Next
'Return the value capped at 31 characters (Excel limit)
RemoveSpecialCharactersAndTruncate$ = Left(FormattedString$, _
Application.WorksheetFunction.Min(Len(FormattedString), 31))
End Function
For an excellent resource on how bash invocation works, what dotfiles do what, and how you should use/configure them, read this:
The only half-way proper way to do this is
<p>
<span style="float: right">Text on the right</span>
<span style="float: left">Text on the left</span>
</p>
however, this will get you into trouble if the text overflows. If you can, use div
s (block level elements) and give them a fixed width
.
A table (or a number of div
s with the according display: table / table-row / table-cell
properties) would in fact be the safest solution for this - it will be impossible to break, even if you have lots of difficult content.
Set the max-width:1250px;
that is currently on your body on your #container. This way your header will be 100% of his parent (body) :)
If data already exists in the column you should do:
ALTER TABLE tbl_name ALTER COLUMN col_name TYPE integer USING col_name::integer;
As pointed out by @nobu and @jonathan-porter in comments to @derek-kromm's answer.
A other users suggested,
.empty()
is good enought, because it removes all descendant nodes (both tag-nodes and text-nodes) AND all kind of data stored inside those nodes. See the JQuery's API empty documentation.
If you wish to keep data, like event handlers for example, you should use
.detach()
as described on the JQuery's API detach documentation.
The method .remove() could be usefull for similar purposes.
PS: Take backup of your code in case it changes App.js
If you are starting the python interpreter from a shell on Linux or similar systems (BSD, not sure about Mac), you should also check the default encoding for the shell.
Call locale charmap
from the shell (not the python interpreter) and you should see
[user@host dir] $ locale charmap
UTF-8
[user@host dir] $
If this is not the case, and you see something else, e.g.
[user@host dir] $ locale charmap
ANSI_X3.4-1968
[user@host dir] $
Python will (at least in some cases such as in mine) inherit the shell's encoding and will not be able to print (some? all?) unicode characters. Python's own default encoding that you see and control via sys.getdefaultencoding()
and sys.setdefaultencoding()
is in this case ignored.
If you find that you have this problem, you can fix that by
[user@host dir] $ export LC_CTYPE="en_EN.UTF-8"
[user@host dir] $ locale charmap
UTF-8
[user@host dir] $
(Or alternatively choose whichever keymap you want instead of en_EN.) You can also edit /etc/locale.conf
(or whichever file governs the locale definition in your system) to correct this.
Font type always be set in code and nib/storyboard.
For the code,just like Hugues BR said,do it in catagory can solve the problem.
For the nib/storyboard,we can Method Swizzling awakeFromNib to change font type since UI element from nib/storyboard always call it before show in the screen.
I suppose you know Aspects.It's a library for AOP programing,based on Method Swizzling. We create catagory for UILabel,UIButton,UITextView to implement it.
UILabel:
#import "UILabel+OverrideBaseFont.h"
#import "Aspects.h"
@implementation UILabel (OverrideBaseFont)
+ (void)load {
[[self class]aspect_hookSelector:@selector(awakeFromNib) withOptions:AspectPositionAfter usingBlock:^(id<AspectInfo> aspectInfo) {
UILabel* instance = [aspectInfo instance];
UIFont* font = [UIFont fontWithName:@"HelveticaNeue-light" size:instance.font.pointSize];
instance.font = font;
}error:nil];
}
@end
UIButton:
#import "UIButton+OverrideBaseFont.h"
#import "Aspects.h"
@implementation UIButton (OverrideBaseFont)
+ (void)load {
[[self class]aspect_hookSelector:@selector(awakeFromNib) withOptions:AspectPositionAfter usingBlock:^(id<AspectInfo> aspectInfo) {
UIButton* instance = [aspectInfo instance];
UILabel* label = instance.titleLabel;
UIFont* font = [UIFont fontWithName:@"HelveticaNeue-light" size:label.font.pointSize];
instance.titleLabel.font = font;
}error:nil];
}
@end
UITextField:
#import "UITextField+OverrideBaseFont.h"
#import "Aspects.h"
@implementation UITextField (OverrideBaseFont)
+ (void)load {
[[self class]aspect_hookSelector:@selector(awakeFromNib) withOptions:AspectPositionAfter usingBlock:^(id<AspectInfo> aspectInfo) {
UITextField* instance = [aspectInfo instance];
UIFont* font = [UIFont fontWithName:@"HelveticaNeue-light" size:instance.font.pointSize];
instance.font = font;
}error:nil];
}
@end
UITextView:
#import "UITextView+OverrideBaseFont.h"
#import "Aspects.h"
@implementation UITextView (OverrideBaseFont)
+ (void)load {
[[self class]aspect_hookSelector:@selector(awakeFromNib) withOptions:AspectPositionAfter usingBlock:^(id<AspectInfo> aspectInfo) {
UITextView* instance = [aspectInfo instance];
UIFont* font = [UIFont fontWithName:@"HelveticaNeue-light" size:instance.font.pointSize];
instance.font = font;
}error:nil];
}
@end
That's all,you can change HelveticaNeue-light to a macro with your font name.
You can also do what the "Service Reference" generated code does
public class ServiceXClient : ClientBase<IServiceX>, IServiceX
{
public ServiceXClient() { }
public ServiceXClient(string endpointConfigurationName) :
base(endpointConfigurationName) { }
public ServiceXClient(string endpointConfigurationName, string remoteAddress) :
base(endpointConfigurationName, remoteAddress) { }
public ServiceXClient(string endpointConfigurationName, EndpointAddress remoteAddress) :
base(endpointConfigurationName, remoteAddress) { }
public ServiceXClient(Binding binding, EndpointAddress remoteAddress) :
base(binding, remoteAddress) { }
public bool ServiceXWork(string data, string otherParam)
{
return base.Channel.ServiceXWork(data, otherParam);
}
}
Where IServiceX is your WCF Service Contract
Then your client code:
var client = new ServiceXClient(new WSHttpBinding(SecurityMode.None), new EndpointAddress("http://localhost:911"));
client.ServiceXWork("data param", "otherParam param");
If you are using Jackson, then you can use the @JsonProperty
annotation to customize the name of a given JSON property.
Therefore, you just have to annotate the entity fields with the @JsonProperty
annotation and provide a custom JSON property name, like this:
@Entity
public class City {
@Id
@JsonProperty("value")
private Long id;
@JsonProperty("label")
private String name;
//Getters and setters omitted for brevity
}
JSON-B is the standard binding layer for converting Java objects to and from JSON. If you are using JSON-B, then you can override the JSON property name via the @JsonbProperty
annotation:
@Entity
public class City {
@Id
@JsonbProperty("value")
private Long id;
@JsonbProperty("label")
private String name;
//Getters and setters omitted for brevity
}
If you're using Swift, it's as simple as:
subviews.map { $0.removeFromSuperview }
It's similar in philosophy to the makeObjectsPerformSelector
approach, however with a little more type safety.
▲
▼
I usually use the excellent Gucharmap to look up Unicode characters. It's installed on all recent Linux installations with Gnome under the name "Character Map". I don't know of any equivalent tools for Windows or Mac OS X, but its homepage lists a few.
As far as the Python languages is concerned, _
has no special meaning. It is a valid identifier just like _foo
, foo_
or _f_o_o_
.
Any special meaning of _
is purely by convention. Several cases are common:
A dummy name when a variable is not intended to be used, but a name is required by syntax/semantics.
# iteration disregarding content
sum(1 for _ in some_iterable)
# unpacking disregarding specific elements
head, *_ = values
# function disregarding its argument
def callback(_): return True
Many REPLs/shells store the result of the last top-level expression to builtins._
.
The special identifier
_
is used in the interactive interpreter to store the result of the last evaluation; it is stored in thebuiltins
module. When not in interactive mode,_
has no special meaning and is not defined. [source]
Due to the way names are looked up, unless shadowed by a global or local _
definition the bare _
refers to builtins._
.
>>> 42
42
>>> f'the last answer is {_}'
'the last answer is 42'
>>> _
'the last answer is 42'
>>> _ = 4 # shadow ``builtins._`` with global ``_``
>>> 23
23
>>> _
4
Note: Some shells such as ipython
do not assign to builtins._
but special-case _
.
In the context internationalization and localization, _
is used as an alias for the primary translation function.
Return the localized translation of message, based on the current global domain, language, and locale directory. This function is usually aliased as _() in the local namespace (see examples below).
I've found a temporary solution that will at least let me process this job. I wrote a short AutoIt script that waits for the "Update Links" window to appear, then clicks the "Don't Update" button. Code is as follows:
while 1
if winexists("Microsoft Excel","This workbook contains links to other data sources.") Then
controlclick("Microsoft Excel","This workbook contains links to other data sources.",2)
EndIf
WEnd
So far this seems to be working. I'd really like to find a solution that's entirely VBA, however, so that I can make this a standalone application.
Well I found nobody mentioned this trick.
Without redirection, you can still prevent the form confirmation when refresh.
By default, form code is like this:
<form method="post" action="test.php">
now, change it to
<form method="post" action="test.php?nonsense=1">
You will see the magic.
I guess its because browsers won't trigger the confirmation alert popup if it gets a GET method (query string) in the url.
Be forwarned... I am using jQuery Mobile 1.0b2 with PhoneGap 1.0.0 on an Android 2.2 (Cyanogen 7.0.1) phone (T-Mobile G2) and could not get the .append() method to work at all. I had to use .html() like follows:
var options;
$.each(data, function(index, object) {
options += '<option value="' + object.id + '">' + object.stop + '</option>';
});
$('#selectMenu').html(options);
Try either
sudo apt-get install php-zip
orsudo apt-get install php5.6-zip
Then, you might have to restart your web server.
sudo service apache2 restart
orsudo service nginx restart
If you are installing on centos or fedora OS then use yum in place of apt-get. example:-
sudo yum install php-zip
or
sudo yum install php5.6-zip
and
sudo service httpd restart
Deadlock occurs when two threads aquire locks which prevent either of them from progressing. The best way to avoid them is with careful development. Many embedded systems protect against them by using a watchdog timer (a timer which resets the system whenever if it hangs for a certain period of time).
IF EXISTS (
SELECT * FROM sysobjects WHERE id = object_id(N'function_name')
AND xtype IN (N'FN', N'IF', N'TF')
)
DROP FUNCTION function_name
GO
If you want to avoid the sys* tables, you could instead do (from here in example A):
IF object_id(N'function_name', N'FN') IS NOT NULL
DROP FUNCTION function_name
GO
The main thing to catch is what type of function you are trying to delete (denoted in the top sql by FN, IF and TF):
For a fully transparent background use:
background: transparent;
Otherwise for a semi-transparent color fill use:
background: rgba(255,255,255,0.5); // or hsla(0, 0%, 100%, 0.5)
where the values are:
background: rgba(red,green,blue,opacity); // or hsla(hue, saturation, lightness, opacity)
You can also use rgba values for gradient backgrounds.
To get transparency on an image background simply reduce the opacity of the image in an image editor of you choice beforehand.
This Error mainly came when the SQL Service is stopped.You need to Restart the service.To go to this window you have to search the Services like this-
Then Search for SQLSERVER(MSSQLSERVER) and Restart the service.
Hope this will work.
Yes, your conclusion is correct. socket.recv
is a blocking call.
socket.recv(1024)
will read at most 1024 bytes, blocking if no data is waiting to be read. If you don't read all data, an other call to socket.recv
won't block.
socket.recv
will also end with an empty string if the connection is closed or there is an error.
If you want a non-blocking socket, you can use the select module (a bit more complicated than just using sockets) or you can use socket.setblocking
.
I had issues with socket.setblocking
in the past, but feel free to try it if you want.
You can do it using javascript
Plain javascript
var iframe = document.getElementsByTagName('iframe')[0];
iframe.style.background = 'white';
iframe.contentWindow.document.body.style.backgroundColor = 'white';
jQuery
$('iframe').css('background', 'white');
$('iframe').contents().find('body').css('backgroundColor', 'white');
Use the following css:
* {
font: Verdana, Arial, 'sans-serif' !important;/* <-- fonts */
}
The *
-selector means any/all elements, but will obviously be on the bottom of the food chain when it comes to overriding more specific selectors.
Note that the !important
-flag will render the font
-style for *
to be absolute, even if other selectors have been used to set the text (for example, the body
or maybe a p
).
For those who are using Visual Studio 2017 version, it seems like the preprocessor definition required to run unsafe operations has changed. Use instead:
#define _CRT_SECURE_NO_WARNINGS
It will compile then.
This might work for you:
OIFS=$IFS; IFS=$'\n'; array=($(ls -ls)); IFS=$OIFS; echo "${array[1]}"
<!DOCTYPE html>
<?php
$con = new mysqli("localhost","root","","form");
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script type="text/javascript">
$(document).ready(function(){
//$("form").submit(function(e){
$("#btn1").click(function(e){
e.preventDefault();
// alert('here');
$(".apnew").append('<input type="text" placeholder="Enter youy Name" name="e1[]"/><br>');
});
//}
});
</script>
</head>
<body>
<h2><b>Register Form<b></h2>
<form method="post" enctype="multipart/form-data">
<table>
<tr><td>Name:</td><td><input type="text" placeholder="Enter youy Name" name="e1[]"/>
<div class="apnew"></div><button id="btn1">Add</button></td></tr>
<tr><td>Image:</td><td><input type="file" name="e5[]" multiple="" accept="image/jpeg,image/gif,image/png,image/jpg"/></td></tr>
<tr><td>Address:</td><td><textarea cols="20" rows="4" name="e2"></textarea></td></tr>
<tr><td>Contact:</td><td><div id="textnew"><input type="number" maxlength="10" name="e3"/></div></td></tr>
<tr><td>Gender:</td><td><input type="radio" name="r1" value="Male" checked="checked"/>Male<input type="radio" name="r1" value="feale"/>Female</td></tr>
<tr><td><input id="submit" type="submit" name="t1" value="save" /></td></tr>
</table>
<?php
//echo '<pre>';print_r($_FILES);exit();
if(isset($_POST['t1']))
{
$values = implode(", ", $_POST['e1']);
$imgarryimp=array();
foreach($_FILES["e5"]["tmp_name"] as $key=>$val){
move_uploaded_file($_FILES["e5"]["tmp_name"][$key],"images/".$_FILES["e5"]["name"][$key]);
$fname = $_FILES['e5']['name'][$key];
$imgarryimp[]=$fname;
//echo $fname;
if(strlen($fname)>0)
{
$img = $fname;
}
$d="insert into form(name,address,contact,gender,image)values('$values','$_POST[e2]','$_POST[e3]','$_POST[r1]','$img')";
if($con->query($d)==TRUE)
{
echo "Yoy Data Save Successfully!!!";
}
}
exit;
// echo $values;exit;
//foreach($_POST['e1'] as $row)
//{
$d="insert into form(name,address,contact,gender,image)values('$values','$_POST[e2]','$_POST[e3]','$_POST[r1]','$img')";
if($con->query($d)==TRUE)
{
echo "Yoy Data Save Successfully!!!";
}
//}
//exit;
}
?>
</form>
<table>
<?php
$t="select * from form";
$y=$con->query($t);
foreach ($y as $q);
{
?>
<tr>
<td>Name:<?php echo $q['name'];?></td>
<td>Address:<?php echo $q['address'];?></td>
<td>Contact:<?php echo $q['contact'];?></td>
<td>Gender:<?php echo $q['gender'];?></td>
</tr>
<?php }?>
</table>
</body>
</html>
Yes, generally the best way to store a file in a database is to save the byte array in a BLOB column. You will probably want a couple of columns to additionally store the file's metadata such as name, extension, and so on.
It is not always a good idea to store files in the database - for instance, the database size will grow fast if you store files in it. But that all depends on your usage scenario.
Setting the following git setting fixed this for me
git config --global --add http.sslVersion tlsv1.0
I'm guessing the corporate proxy server did not like the default encryption protocol.
The legend titles can be labeled by specific aesthetic.
This can be achieved using the guides()
or labs()
functions from ggplot2
(more here and here). It allows you to add guide/legend properties using the aesthetic mapping.
Here's an example using the mtcars
data set and labs()
:
ggplot(mtcars, aes(x=mpg, y=disp, size=hp, col=as.factor(cyl), shape=as.factor(gear))) +
geom_point() +
labs(x="miles per gallon", y="displacement", size="horsepower",
col="# of cylinders", shape="# of gears")
Answering the OP's question using guides()
:
# transforming the data from wide to long
require(reshape2)
dfm <- melt(df, id="TY")
# creating a scatterplot
ggplot(data = dfm, aes(x=TY, y=value, color=variable)) +
geom_point(size=5) +
labs(title="Temperatures\n", x="TY [°C]", y="Txxx") +
scale_color_manual(labels = c("T999", "T888"), values = c("blue", "red")) +
theme_bw() +
guides(color=guide_legend("my title")) # add guide properties by aesthetic
If you are running python 3 then you need to change the print statements to print functions, i.e. put things in brackets () after print statements.
The only thing that you will see the above do is the prints unless you have something listening on 127.0.0.1 port 5005
as you are sending a packet not receiving it - so you need to implement and start the other part of the example in another console window first so it is waiting for the message.
The prompt command will echo text to the output:
prompt A useful comment.
select(*) from TableA;
Will be displayed as:
SQL> A useful comment.
SQL>
COUNT(*)
----------
0
Like this:
yourString = yourString.replaceAll("\\s+", " ");
For example
System.out.println("lorem ipsum dolor \n sit.".replaceAll("\\s+", " "));
outputs
lorem ipsum dolor sit.
What does that \s+
mean?
\s+
is a regular expression. \s
matches a space, tab, new line, carriage return, form feed or vertical tab, and +
says "one or more of those". Thus the above code will collapse all "whitespace substrings" longer than one character, with a single space character.
To achieve what you want without removing any styles you have to make the z-index of the '.parent' class bigger then the '.wholePage' class.
.parent {
position: relative;
z-index: 4; /*matters since it's sibling to wholePage*/
}
.child {
position: relative;
z-index:1; /*doesn't matter */
background-color: white;
padding: 5px;
}
jsFiddle: http://jsfiddle.net/ZjXMR/2/
I used a check if (!a.isFinishing())
and it seems to do what i need. a
is the activity instance. Is this incorrect? Why didn't anyone try this?
exec sp_addlinkedserver
@server = 'local',
@srvproduct = '',
@provider='SQLNCLI',
@datasrc = @@SERVERNAME
go
create view ViewTest
as
select * from openquery(local, 'sp_who')
go
select * from ViewTest
go
For me it was the line: fastcgi_pass unix:/var/run/php5-fpm.sock;
which had to be just: fastcgi_pass unix:/run/php5-fpm.sock;
Try removing package-lock.json file first
I had actually done this from Django a while back. Open up a legitimate GMail account & enter the credentials here. Here's my code -
from email import Encoders
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.MIMEMultipart import MIMEMultipart
def sendmail(to, subject, text, attach=[], mtype='html'):
ok = True
gmail_user = settings.EMAIL_HOST_USER
gmail_pwd = settings.EMAIL_HOST_PASSWORD
msg = MIMEMultipart('alternative')
msg['From'] = gmail_user
msg['To'] = to
msg['Cc'] = '[email protected]'
msg['Subject'] = subject
msg.attach(MIMEText(text, mtype))
for a in attach:
part = MIMEBase('application', 'octet-stream')
part.set_payload(open(attach, 'rb').read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition','attachment; filename="%s"' % os.path.basename(a))
msg.attach(part)
try:
mailServer = smtplib.SMTP("smtp.gmail.com", 687)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(gmail_user, gmail_pwd)
mailServer.sendmail(gmail_user, [to,msg['Cc']], msg.as_string())
mailServer.close()
except:
ok = False
return ok
It seems however that splitting in the middle of the values of a for loop doesn't need a caret(and actually trying to use one will be considered a syntax error). For example,
for %n in (hello
bye) do echo %n
Note that no space is even needed after hello or before bye.
I just ran into this annoying problem today. We use SmartAssembly to pack/obfuscate our .NET assemblies, but suddenly the final product wasn't working on our test systems. I didn't even think I had .NET 4.5, but apparently something installed it about a month ago.
I uninstalled 4.5 and reinstalled 4.0, and now everything is working again. Not too impressed with having blown an afternoon on this.
you use script in php..
<?php
$num = 1;
echo $num;
echo '<input type="button"
name="lol"
value="Click to increment"
onclick="Inc()" />
<br>
<script>
function Inc()
{';
$num = 2;
echo $num;
echo '}
</script>';
?>
Just set all the selected time unit's displayFormat
to MMM DD
options: {
scales: {
xAxes: [{
type: 'time',
time: {
displayFormats: {
'millisecond': 'MMM DD',
'second': 'MMM DD',
'minute': 'MMM DD',
'hour': 'MMM DD',
'day': 'MMM DD',
'week': 'MMM DD',
'month': 'MMM DD',
'quarter': 'MMM DD',
'year': 'MMM DD',
}
...
Notice that I've set all the unit's display format to MMM DD
. A better way, if you have control over the range of your data and the chart size, would be force a unit, like so
options: {
scales: {
xAxes: [{
type: 'time',
time: {
unit: 'day',
unitStepSize: 1,
displayFormats: {
'day': 'MMM DD'
}
...
Fiddle - http://jsfiddle.net/prfd1m8q/
Perhaps you should check NLS_DATE_FORMAT
and use the date string conforming the format.
Or you can use to_date
function within the INSERT
statement, like the following:
insert into visit
values(123456,
to_date('19-JUN-13', 'dd-mon-yy'),
to_date('13-AUG-13 12:56 A.M.', 'dd-mon-yyyy hh:mi A.M.'));
Additionally, Oracle DATE
stores date and time information together.
found a working solution here: https://codepen.io/hoanghals/pen/dZrWLZ
JS here:
var gifElements = document.querySelectorAll('img.gif');
for(var e in gifElements) {
var element = gifElements[e];
if(element.nodeName == 'IMG') {
var supergif = new SuperGif({
gif: element,
progressbar_height: 0,
auto_play: false,
});
var controlElement = document.createElement("div");
controlElement.className = "gifcontrol loading g"+e;
supergif.load((function(controlElement) {
controlElement.className = "gifcontrol paused";
var playing = false;
controlElement.addEventListener("click", function(){
if(playing) {
this.pause();
playing = false;
controlElement.className = "gifcontrol paused";
} else {
this.play();
playing = true;
controlElement.className = "gifcontrol playing";
}
}.bind(this, controlElement));
}.bind(supergif))(controlElement));
var canvas = supergif.get_canvas();
controlElement.style.width = canvas.width+"px";
controlElement.style.height = canvas.height+"px";
controlElement.style.left = canvas.offsetLeft+"px";
var containerElement = canvas.parentNode;
containerElement.appendChild(controlElement);
}
}
hg commit --amend
:This also works from TortoiseHG's GUI (I'm using v2.5):
Swich to the 'Commit' view or, in the workbench view, select the 'working directory' entry. The 'Commit' button has an option named 'Amend current revision' (click the button's drop-down arrow to find it).
||
||
\/
Caveat emptor:
This extra option will only be enabled if the mercurial version is at least 2.2.0, and if the current revision is not public, is not a patch and has no children. [...]
Clicking the button will call 'commit --amend' to 'amend' the revision.
More info about this on the THG dev channel
You want reorder()
. Here is an example with dummy data
set.seed(42)
df <- data.frame(Category = sample(LETTERS), Count = rpois(26, 6))
require("ggplot2")
p1 <- ggplot(df, aes(x = Category, y = Count)) +
geom_bar(stat = "identity")
p2 <- ggplot(df, aes(x = reorder(Category, -Count), y = Count)) +
geom_bar(stat = "identity")
require("gridExtra")
grid.arrange(arrangeGrob(p1, p2))
Giving:
Use reorder(Category, Count)
to have Category
ordered from low-high.
For all databases query sys.sysprocesses
SELECT * FROM sys.sysprocesses WHERE open_tran = 1
For the current database use:
DBCC OPENTRAN
"That's just the way TCP works and you have to live with it."
Yup, you're right. It's a fact of life I've come to realize. You will see the same behavior exhibited even in professional applications utilizing this protocol (and even others). I've even seen it occur in online games; you're buddy says "goodbye", and he appears to be online for another 1-2 minutes until the server "cleans house".
You can use the suggested methods here, or implement a "heartbeat", as also suggested. I choose the former. But if I did choose the latter, I'd simply have the server "ping" each client every so often with a single byte, and see if we have a timeout or no response. You could even use a background thread to achieve this with precise timing. Maybe even a combination could be implemented in some sort of options list (enum flags or something) if you're really worried about it. But it's no so big a deal to have a little delay in updating the server, as long as you DO update. It's the internet, and no one expects it to be magic! :)
Create your shell script as login.sh
in your $HOME folder.
Paste the following one-line script into Script Editor:
do shell script "$HOME/login.sh"
Then save it as an application.
Finally add the application to your login items.
If you want to make the script output visual, you can swap step 2 for this:
tell application "Terminal"
activate
do script "$HOME/login.sh"
end tell
If multiple commands are needed something like this can be used:
tell application "Terminal"
activate
do script "cd $HOME"
do script "./login.sh" in window 1
end tell
Using simple html,
<div>
<object type="text/html" data="http://validator.w3.org/" width="800px" height="600px" style="overflow:auto;border:5px ridge blue">
</object>
</div>
Or jquery,
<script>
$("#mydiv")
.html('<object data="http://your-website-domain"/>');
</script>
This is how sed
and mv
can be used together to do rename:
for f in fgh*; do mv "$f" $(echo "$f" | sed 's/^fgh/jkl/g'); done
As per comment below, if the file names have spaces in them, quotes may need to surround the sub-function that returns the name to move the files to:
for f in fgh*; do mv "$f" "$(echo $f | sed 's/^fgh/jkl/g')"; done
In Chrome, go to options (Customize and Control, the 3 dots/bars at top right) ---> More Tools ---> save page as
save page as
filename : any_name.html
save as type : webpage complete.
Then you will get any_name.html
and any_name folder
.
One option is using Object.keys()
:
Object.keys(driversCounter)
It works fine for modern browsers (however, Internet Explorer supports it starting from version 9 only).
To add compatible support you can copy the code snippet provided in MDN.
A slightly simplified version of Oglester's solution (the sequence doesn't require a select from DUAL:
INSERT INTO account_type_standard
(account_type_Standard_id, tax_status_id, recipient_id)
VALUES(
account_type_standard_seq.nextval,
(SELECT tax_status_id FROM tax_status WHERE tax_status_code = ?),
(SELECT recipient_id FROM recipient WHERE recipient_code = ?)
)
In 2017, the thing closest to Javadoc would probably DocFx which was developed by Microsoft and comes as a Commmand-Line-Tool as well as a VS2017 plugin.
It's still a little rough around the edges but it looks promising.
Another alternative would be Wyam which has a documentation recipe suitable for net aplications. Look at the cake documentation for an example.
This might be your script-free solution: http://davidwalsh.name/css-transform-rotate
It's supported in all browsers prefixed and, in IE10-11 and all still-used Firefox versions, unprefixed.
That means that if you don't care for old IEs (the bane of web designers) you can skip the -ms-
and -moz-
prefixes to economize space.
However, the Webkit browsers (Chrome, Safari, most mobile navigators) still need -webkit-
, and there's a still-big cult following of pre-Next Opera and using -o-
is sensate.
A nicer implementation could be to use the category method below on NSMutableArray.
@implementation NSMutableArray(BMCommons)
- (void)removeObjectsWithPredicate:(BOOL (^)(id obj))predicate {
if (predicate != nil) {
NSMutableArray *newArray = [[NSMutableArray alloc] initWithCapacity:self.count];
for (id obj in self) {
BOOL shouldRemove = predicate(obj);
if (!shouldRemove) {
[newArray addObject:obj];
}
}
[self setArray:newArray];
}
}
@end
The predicate block can be implemented to do processing on each object in the array. If the predicate returns true the object is removed.
An example for a date array to remove all dates that lie in the past:
NSMutableArray *dates = ...;
[dates removeObjectsWithPredicate:^BOOL(id obj) {
NSDate *date = (NSDate *)obj;
return [date timeIntervalSinceNow] < 0;
}];
You simply compare your object to null
using the ==
(or !=
) operator. E.g.:
public static double calculateInventoryTotal(Book[] books) {
// First null check - the entire array
if (books == null) {
return 0;
}
double total = 0;
for (int i = 0; i < books.length; i++) {
// second null check - each individual element
if (books[i] != null) {
total += books[i].getPrice();
}
}
return total;
}
Assuming MySQL (EDIT: posted before the SQL variant was supplied):
ALTER TABLE myTable ADD myNewColumn VARCHAR(255) AFTER myOtherColumn
The AFTER keyword tells MySQL where to place the new column. You can also use FIRST to flag the new column as the first column in the table.
CSS is called Cascading Style Sheets because the rules are inherited. Using the following selector, will select just the direct child of the parent, but its rules will be inherited by that div
's children divs
:
div.section > div { color: red }
Now, both that div
and its children will be red
. You need to cancel out whatever you set on the parent if you don't want it to inherit:
div.section > div { color: red }
div.section > div div { color: black }
Now only that single div
that is a direct child of div.section
will be red, but its children divs
will still be black.
Below is how I got this working.
The Key point was: I needed to use the ViewModel associated with the view in order for the runtime to be able to resolve the object in the request.
[I know that that there is a way to bind an object other than the default ViewModel object but ended up simply populating the necessary properties for my needs as I could not get it to work]
[HttpPost]
public ActionResult GetDataForInvoiceNumber(MyViewModel myViewModel)
{
var invoiceNumberQueryResult = _viewModelBuilder.HydrateMyViewModelGivenInvoiceDetail(myViewModel.InvoiceNumber, myViewModel.SelectedCompanyCode);
return Json(invoiceNumberQueryResult, JsonRequestBehavior.DenyGet);
}
The JQuery script used to call this action method:
var requestData = {
InvoiceNumber: $.trim(this.value),
SelectedCompanyCode: $.trim($('#SelectedCompanyCode').val())
};
$.ajax({
url: '/en/myController/GetDataForInvoiceNumber',
type: 'POST',
data: JSON.stringify(requestData),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
error: function (xhr) {
alert('Error: ' + xhr.statusText);
},
success: function (result) {
CheckIfInvoiceFound(result);
},
async: true,
processData: false
});
The following works for me (Excel 2010)
Dim b1 As Button
Set b1 = ActiveSheet.Buttons("Button 1")
b1.Font.ColorIndex = 15
b1.Enabled = False
Application.Cursor = xlWait
Call aLongAction
b1.Enabled = True
b1.Font.ColorIndex = 1
Application.Cursor = xlDefault
Be aware that
.enabled = False
does not gray out a button.
The font color has to be set explicitely to get it grayed.
<input type = "button" style ="background-color:green"/>
Yes with Virtual Host you can have as many parallel programs as you want:
Open
/etc/httpd/conf/httpd.conf
Listen 81
Listen 82
Listen 83
<VirtualHost *:81>
ServerAdmin [email protected]
DocumentRoot /var/www/site1/html
ServerName site1.com
ErrorLog logs/site1-error_log
CustomLog logs/site1-access_log common
ScriptAlias /cgi-bin/ "/var/www/site1/cgi-bin/"
</VirtualHost>
<VirtualHost *:82>
ServerAdmin [email protected]
DocumentRoot /var/www/site2/html
ServerName site2.com
ErrorLog logs/site2-error_log
CustomLog logs/site2-access_log common
ScriptAlias /cgi-bin/ "/var/www/site2/cgi-bin/"
</VirtualHost>
<VirtualHost *:83>
ServerAdmin [email protected]
DocumentRoot /var/www/site3/html
ServerName site3.com
ErrorLog logs/site3-error_log
CustomLog logs/site3-access_log common
ScriptAlias /cgi-bin/ "/var/www/site3/cgi-bin/"
</VirtualHost>
Restart apache
service httpd restart
You can now refer Site1 :
http://<ip-address>:81/
http://<ip-address>:81/cgi-bin/
Site2 :
http://<ip-address>:82/
http://<ip-address>:82/cgi-bin/
Site3 :
http://<ip-address>:83/
http://<ip-address>:83/cgi-bin/
If path is not hardcoded in any script then your websites should work seamlessly.
ALLOW-FROM is not supported in Chrome or Safari. See MDN article: https://developer.mozilla.org/en-US/docs/Web/HTTP/X-Frame-Options
You are already doing the work to make a custom header and send it with the correct data, can you not just exclude the header when you detect it is from a valid partner and add DENY to every other request? I don't see the benefit of AllowFrom when you are already dynamically building the logic up?
An alternative to @Steve's code.
DECLARE
CURSOR foo_cur IS
SELECT NEEDED_FIELD WHERE condition ;
BEGIN
FOR foo_rec IN foo_cur LOOP
...
END LOOP;
EXCEPTION
WHEN OTHERS THEN
RAISE;
END ;
The loop is not executed if there is no data. Cursor FOR loops are the way to go - they help avoid a lot of housekeeping. An even more compact solution:
DECLARE
BEGIN
FOR foo_rec IN (SELECT NEEDED_FIELD WHERE condition) LOOP
...
END LOOP;
EXCEPTION
WHEN OTHERS THEN
RAISE;
END ;
Which works if you know the complete select statement at compile time.
For Atom you can do
git config --global core.editor "atom --wait"
and similar for Visual Studio Code
git config --global core.editor "code --wait"
which will open up an Atom or Visual Studio Code window for you to commit through,
or for Sublime Text:
git config --global core.editor "subl -n -w"
IF EXISTS (SELECT name FROM master.sys.databases WHERE name = N'YourDatabaseName')
Do your thing...
By the way, this came directly from SQL Server Studio, so if you have access to this tool, I recommend you start playing with the various "Script xxxx AS" functions that are available. Will make your life easier! :)
Using a comma may not be sufficient if you have multiple jQuery objects that need to be joined.
The .add() method adds the selected elements to the result set:
// classA OR classB
jQuery('.classA').add('.classB');
It's more verbose than '.classA, .classB'
, but lets you build more complex selectors like the following:
// (classA which has <p> descendant) OR (<div> ancestors of classB)
jQuery('.classA').has('p').add(jQuery('.classB').parents('div'));
Two ways I know of:
export class SomeComponent implements OnInit
{
public localVar:any;
ngOnInit(){
this.http.get(Path).map(res => res.json()).subscribe(res => this.localVar = res);
}
}
This will assign your result into local variable once information is returned just like in a promise. Then you just do {{ localVar }}
Another Way is to get a observable as a localVariable.
export class SomeComponent
{
public localVar:any;
constructor()
{
this.localVar = this.http.get(path).map(res => res.json());
}
}
This way you're exposing a observable at which point you can do in your html is to use AsyncPipe {{ localVar | async }}
Please try it out and let me know if it works. Also, since angular 2 is pretty new, feel free to comment if something is wrong.
Hope it helps
For anyone else who comes here looking, I'm afraid I'm with @usama sulaiman here.
Using the enqueue function provides a safe way to load style sheets and scripts according to the script dependencies and is WordPress' recommended method of achieving what the original poster was trying to achieve. Just think of all the plugins trying to load their own copy of jQuery for instance; you better hope they're using enqueue :D.
Also, wherever possible create a plugin; as adding custom code to your functions file can be pita if you don't have a back-up and you upgrade your theme and overwrite your functions file in the process.
Having a plugin handle this and other custom functions also means you can switch them off if you think their code is clashing with some other plugin or functionality.
Something along the following in a plugin file is what you are looking for:
<?php
/*
Plugin Name: Your plugin name
Description: Your description
Version: 1.0
Author: Your name
Author URI:
Plugin URI:
*/
function $yourJS() {
wp_enqueue_script(
'custom_script',
plugins_url( '/js/your-script.js', __FILE__ ),
array( 'jquery' )
);
}
add_action( 'wp_enqueue_scripts', '$yourJS' );
add_action( 'wp_enqueue_scripts', 'prefix_add_my_stylesheet' );
function prefix_add_my_stylesheet() {
wp_register_style( 'prefix-style', plugins_url( '/css/your-stylesheet.css', __FILE__ ) );
wp_enqueue_style( 'prefix-style' );
}
?>
Structure your folders as follows:
Plugin Folder
|_ css folder
|_ js folder
|_ plugin.php ...contains the above code - modified of course ;D
Then zip it up and upload it to your WordPress installation using your add plugins interface, activate it and Bob's your uncle.
In JavaScript, an object is a standalone entity, with properties and type.
For fetching values from Object in form of array: Object.values(obj) // obj is object name that you used Result -> ["value1", "value2", "value3", "value4"]
For fetching keys from Object in form of array: Object.keys(obj) // obj is object name that you used Result -> ["key1", "key2", "key3", "key4"]
As both functions are returning array you can get the length of keys or value by using length property. For instance - Object.values(obj).length or Object.keys(obj).length
I benefited a lot from 'Dive into HTML 5'. The explanation and demo are easier and to the point. History chapter - http://diveintohtml5.info/history.html and history demo - http://diveintohtml5.info/examples/history/fer.html
select * from information_schema.REFERENTIAL_CONSTRAINTS where
UNIQUE_CONSTRAINT_SCHEMA = 'TABLE_NAME'
This will list the column with TABLE_NAME
and REFERENCED_COLUMN_NAME
.
You can also use the following alternative realpath.
Create a file called path.php
Put the following code inside by specifying the name of the created file.
<?php
echo realpath('path.php');
?>
A php file that you can move to all your folders to always have the absolute path from where the executed file is located.
;-)
Java objects reside in an area called the heap, while metadata such as class objects and method objects reside in the permanent generation or Perm Gen area. The permanent generation is not part of the heap.
The heap is created when the JVM starts up and may increase or decrease in size while the application runs. When the heap becomes full, garbage is collected. During the garbage collection objects that are no longer used are cleared, thus making space for new objects.
-Xmssize Specifies the initial heap size.
-Xmxsize Specifies the maximum heap size.
-XX:MaxPermSize=size Sets the maximum permanent generation space size. This option was deprecated in JDK 8, and superseded by the -XX:MaxMetaspaceSize option.
Sizes are expressed in bytes. Append the letter k
or K
to indicate kilobytes, m
or M
to indicate megabytes, g
or G
to indicate gigabytes.
How is the java memory pool divided?
Java (JVM) Memory Model – Memory Management in Java
You may find an answer with this example : errorbar_demo_features.py
"""
Demo of errorbar function with different ways of specifying error bars.
Errors can be specified as a constant value (as shown in `errorbar_demo.py`),
or as demonstrated in this example, they can be specified by an N x 1 or 2 x N,
where N is the number of data points.
N x 1:
Error varies for each point, but the error values are symmetric (i.e. the
lower and upper values are equal).
2 x N:
Error varies for each point, and the lower and upper limits (in that order)
are different (asymmetric case)
In addition, this example demonstrates how to use log scale with errorbar.
"""
import numpy as np
import matplotlib.pyplot as plt
# example data
x = np.arange(0.1, 4, 0.5)
y = np.exp(-x)
# example error bar values that vary with x-position
error = 0.1 + 0.2 * x
# error bar values w/ different -/+ errors
lower_error = 0.4 * error
upper_error = error
asymmetric_error = [lower_error, upper_error]
fig, (ax0, ax1) = plt.subplots(nrows=2, sharex=True)
ax0.errorbar(x, y, yerr=error, fmt='-o')
ax0.set_title('variable, symmetric error')
ax1.errorbar(x, y, xerr=asymmetric_error, fmt='o')
ax1.set_title('variable, asymmetric error')
ax1.set_yscale('log')
plt.show()
Which plots this:
Try this . Works for subplots too .
axes = plt.gca()
axes.set_xlim([xmin,xmax])
axes.set_ylim([ymin,ymax])
To get uppercase letters in addition to lower case letters, you could also do the following:
String alphabetWithUpper = "abcdefghijklmnopqrstuvwxyz" + "abcdefghijklmnopqrstuvwxyz".toUpperCase();
char[] letters = alphabetWithUpper.toCharArray();
I would use Celery to handle the asynchronous task for you. You'll need to install a broker to serve as your task queue (RabbitMQ and Redis are recommended).
app.py
:
from flask import Flask
from celery import Celery
broker_url = 'amqp://guest@localhost' # Broker URL for RabbitMQ task queue
app = Flask(__name__)
celery = Celery(app.name, broker=broker_url)
celery.config_from_object('celeryconfig') # Your celery configurations in a celeryconfig.py
@celery.task(bind=True)
def some_long_task(self, x, y):
# Do some long task
...
@app.route('/render/<id>', methods=['POST'])
def render_script(id=None):
...
data = json.loads(request.data)
text_list = data.get('text_list')
final_file = audio_class.render_audio(data=text_list)
some_long_task.delay(x, y) # Call your async task and pass whatever necessary variables
return Response(
mimetype='application/json',
status=200
)
Run your Flask app, and start another process to run your celery worker.
$ celery worker -A app.celery --loglevel=debug
I would also refer to Miguel Gringberg's write up for a more in depth guide to using Celery with Flask.
I just checked the status of the response object:
$promise.then( function successCallback(response) {
console.log(response);
if (response.status === 200) { ... }
});
In contrast to Matt J his answer, I use a simple object. This gives me the possibily to parse this handler to all the threads that needs to be stopped securlery.
class SIGINT_handler():
def __init__(self):
self.SIGINT = False
def signal_handler(self, signal, frame):
print('You pressed Ctrl+C!')
self.SIGINT = True
handler = SIGINT_handler()
signal.signal(signal.SIGINT, handler.signal_handler)
Elsewhere
while True:
# task
if handler.SIGINT:
break
2>&1
is a POSIX shell construct. Here is a breakdown, token by token:
2
: "Standard error" output file descriptor.
>&
: Duplicate an Output File Descriptor operator (a variant of Output Redirection operator >
). Given [x]>&[y]
, the file descriptor denoted by x
is made to be a copy of the output file descriptor y
.
1
"Standard output" output file descriptor.
The expression 2>&1
copies file descriptor 1
to location 2
, so any output written to 2
("standard error") in the execution environment goes to the same file originally described by 1
("standard output").
Further explanation:
File Descriptor: "A per-process unique, non-negative integer used to identify an open file for the purpose of file access."
Standard output/error: Refer to the following note in the Redirection section of the shell documentation:
Open files are represented by decimal numbers starting with zero. The largest possible value is implementation-defined; however, all implementations shall support at least 0 to 9, inclusive, for use by the application. These numbers are called "file descriptors". The values 0, 1, and 2 have special meaning and conventional uses and are implied by certain redirection operations; they are referred to as standard input, standard output, and standard error, respectively. Programs usually take their input from standard input, and write output on standard output. Error messages are usually written on standard error. The redirection operators can be preceded by one or more digits (with no intervening characters allowed) to designate the file descriptor number.
I know this question was asked a long time ago, but I wanted to provide another way to do this that I found useful for an issue I just worked on:
lshw -c memory
lshw is a small tool to extract detailed information on the hardware configuration of the machine. It can report exact memory configuration, firmware version, mainboard configuration, CPU version and speed, cache configuration, bus speed, etc. on DMI-capable x86 or IA-64 systems and on some PowerPC machines (PowerMac G4 is known to work).
Exception may also help:
try {
//define your myString
}
catch (Exception e) {
//in that case, you may affect "" to myString
myString="";
}
The question doesn't explicitly state that you just want the characters 0 to 9 but it wouldn't be a stretch to believe that is true from your example set and comments. So here is the code that does that.
string digitsOnly = String.Empty;
foreach (char c in s)
{
// Do not use IsDigit as it will include more than the characters 0 through to 9
if (c >= '0' && c <= '9') digitsOnly += c;
}
Why you don't want to use Char.IsDigit() - Numbers include characters such as fractions, subscripts, superscripts, Roman numerals, currency numerators, encircled numbers, and script-specific digits.
If you have a QMainWindow
you can override closeEvent
method.
#include <QCloseEvent>
void MainWindow::closeEvent (QCloseEvent *event)
{
QMessageBox::StandardButton resBtn = QMessageBox::question( this, APP_NAME,
tr("Are you sure?\n"),
QMessageBox::Cancel | QMessageBox::No | QMessageBox::Yes,
QMessageBox::Yes);
if (resBtn != QMessageBox::Yes) {
event->ignore();
} else {
event->accept();
}
}
If you're subclassing a QDialog
, the closeEvent
will not be called and so you have to override reject()
:
void MyDialog::reject()
{
QMessageBox::StandardButton resBtn = QMessageBox::Yes;
if (changes) {
resBtn = QMessageBox::question( this, APP_NAME,
tr("Are you sure?\n"),
QMessageBox::Cancel | QMessageBox::No | QMessageBox::Yes,
QMessageBox::Yes);
}
if (resBtn == QMessageBox::Yes) {
QDialog::reject();
}
}
Using ES6 syntax in React does not bind this
to user-defined functions however it will bind this
to the component lifecycle methods.
So the function that you declared will not have the same context as the class and trying to access this
will not give you what you are expecting.
For getting the context of class you have to bind the context of class to the function or use arrow functions.
Method 1 to bind the context:
class MyContainer extends Component {
constructor(props) {
super(props);
this.onMove = this.onMove.bind(this);
this.testVarible= "this is a test";
}
onMove() {
console.log(this.testVarible);
}
}
Method 2 to bind the context:
class MyContainer extends Component {
constructor(props) {
super(props);
this.testVarible= "this is a test";
}
onMove = () => {
console.log(this.testVarible);
}
}
Method 2 is my preferred way but you are free to choose your own.
Update: You can also create the properties on class without constructor:
class MyContainer extends Component {
testVarible= "this is a test";
onMove = () => {
console.log(this.testVarible);
}
}
Note If you want to update the view as well, you should use state
and setState
method when you set or change the value.
Example:
class MyContainer extends Component {
state = { testVarible: "this is a test" };
onMove = () => {
console.log(this.state.testVarible);
this.setState({ testVarible: "new value" });
}
}
This method works in 2.x as long as each element in the list is only a single digit. But you shouldn't actually use this. It's horrible.
>>> magic = lambda l:int(`l`[1::3])
>>> magic([3,1,3,3,7])
31337
Update
Based on Manipulating the browser history, passing the empty string as second parameter of pushState
method (aka title) should be safe against future changes to the method, so it's better to use pushState
like this:
history.pushState(null, '', '/en/step2');
You can read more about that in mentioned article
Original Answer
Use history.pushState
like this:
history.pushState(null, null, '/en/step2');
Update 2 to answer Idan Dagan's comment:
Why not using
history.replaceState()
?
From MDN
history.replaceState() operates exactly like history.pushState() except that replaceState() modifies the current history entry instead of creating a new one
That means if you use replaceState
, yes the url will be changed but user can not use Browser's Back button to back to prev. state(s) anymore (because replaceState
doesn't add new entry to history) and it's not recommended and provide bad UX.
Update 3 to add window.onpopstate
So, as this answer got your attention, here is additional info about manipulating the browser history, after using pushState
, you can detect the back/forward button navigation by using window.onpopstate
like this:
window.onpopstate = function(e) {
// ...
};
As the first argument of pushState
is an object, if you passed an object
instead of null
, you can access that object in onpopstate
which is very handy, here is how:
window.onpopstate = function(e) {
if(e.state) {
console.log(e.state);
}
};
Update 4 to add Reading the current state:
When your page loads, it might have a non-null state object, you can read the state of the current history entry without waiting for a popstate
event using the history.state
property like this:
console.log(history.state);
Bonus: Use following to check history.pushState
support:
if (history.pushState) {
// \o/
}
You need to have
#include <string>
in the header file too.The forward declaration on it's own doesn't do enough.
Also strongly consider header guards for your header files to avoid possible future problems as your project grows. So at the top do something like:
#ifndef THE_FILE_NAME_H
#define THE_FILE_NAME_H
/* header goes in here */
#endif
This will prevent the header file from being #included multiple times, if you don't have such a guard then you can have issues with multiple declarations.
Here's another way of doing it with a WHS script:
Set objWMIService = GetObject("Winmgmts:root\cimv2")
For Each objComputer in _
objWMIService.InstancesOf("Win32_ComputerSystem")
objComputer.rename "NewComputerName", NULL, NULL
Next
Here it is:
function call_func(input) {
var evaled = eval('(' + input + ')');
var newDiv = document.createElement('div');
var id = evaled.id;
var name = evaled.Student_name;
var dob = evaled.student_dob;
var html = '<b>ID:</b>';
html += '<a href="/learningyii/index.php?r=student/view& id=' + id + '">' + id + '</a>';
html += '<br/>';
html += '<b>Student Name:</b>';
html += name;
html += '<br/>';
html += '<b>Student DOB:</b>';
html += dob;
html += '<br/>';
newDiv.innerHTML = html;
newDiv.setAttribute('class', 'view');
$('#StudentGridViewId').find('.items').prepend(newDiv);
};
Another 2 cents : Starting with Java 7, there is now a class for this in standard Lib : javafx.util.Pair.
And Yes, It is standard Java, now that JavaFx is included in the JDK :)
If you don't want to edit each file
PYTHONPATH
to your lib
or if you are willing to add a single line to each file, add a import statement at top e.g.
import import_my_lib
keep import_my_lib.py
in bin and import_my_lib
can correctly set the python path to whatever lib
you want
This code is used to multiply the values of one column
select exp(sum(log(column))) from table
For me the problem was that 'adb' was not recognised - check this answer.
To fix this add C:\Users\USERNAME\AppData\Local\Android\sdk\platform-tools to Environment Variables
This solution may good for looking
var some_other_function = someVar => function() {
}
someObj.addEventListener('click', some_other_function(someVar));
or bind valiables will be also good
Change Deployment Target
to newer version and then solved
If .DS_Store was never added to your git repository, simply add it to your .gitignore file.
If you don't have one, create a file called
.gitignore
In the root directory of your app and simply write
**/.DS_Store
In it. This will never allow the .DS_Store file to sneak in your git.
But, if it's already there, write in your terminal:
find . -name .DS_Store -print0 | xargs -0 git rm -f --ignore-unmatch
then commit and push the changes to remove the .DS_Store from your remote repo:
git commit -m "Remove .DS_Store from everywhere"
git push origin master
And now add .DS_Store to your .gitignore file, and then again commit and push with the 2 last pieces of code (git commit..., git push...)
Escape the quotes with backslashes:
printf("She said \"time flies like an arrow, but fruit flies like a banana\".");
There are special escape characters that you can use in string literals, and these are denoted with a leading backslash.
@ binds a local/directive scope property to the evaluated value of the DOM attribute. = binds a local/directive scope property to a parent scope property. & binding is for passing a method into your directive's scope so that it can be called within your directive.
@ Attribute string binding = Two-way model binding & Callback method binding
These days, socket.on('connect', ...) is not working for me. I use the below code to check at 1st connecting.
if (socket.connected)
console.log('socket.io is connected.')
and use this code when reconnected.
socket.on('reconnect', ()=>{
//Your Code Here
});
If you use divmod, you are immune to different flavors of integer division:
# show time strings for 3800 seconds
# easy way to get mm:ss
print "%02d:%02d" % divmod(3800, 60)
# easy way to get hh:mm:ss
print "%02d:%02d:%02d" % \
reduce(lambda ll,b : divmod(ll[0],b) + ll[1:],
[(3800,),60,60])
# function to convert floating point number of seconds to
# hh:mm:ss.sss
def secondsToStr(t):
return "%02d:%02d:%02d.%03d" % \
reduce(lambda ll,b : divmod(ll[0],b) + ll[1:],
[(round(t*1000),),1000,60,60])
print secondsToStr(3800.123)
Prints:
63:20
01:03:20
01:03:20.123
you could use something like
<select ng-model="myselect">
<option ng-repeat="o in options" ng-selected="{{o==myselect}}" value="{{o}}">
{{o}}
</option>
</select>
using ng-selected you preselect the option in case myselect was prefilled.
I prefer this method over ng-options anyway, as ng-options only works with arrays. ng-repeat also works with json-like objects.
If you look for POSIX compliant solution:
cd DirsRoot && find . -type f -print -o -name . -o -prune
-maxdepth is not POSIX compliant option.
You need to make sure the IIS Management Console is installed.
An alternative approach would be to register an event handler on the pagination link like so:
$("#dataTableID_paginate").on("click", "a", function() { alert("clicked") });
Replace "#dataTableID_" with the ID of your table, of course. And I'm using JQuery's ON method as that is the current best practice.
Using @Adrian Frühwirth answer:
function strip {
local STRING=${1#$"$2"}
echo ${STRING%$"$2"}
}
use it like this
HELLO=":hello:"
HELLO=$(strip "$HELLO" ":")
echo $HELLO # hello
"You can store as many objects as you want within a bucket, and write, read, and delete objects in your bucket. Objects can be up to 5 terabytes in size."
from http://aws.amazon.com/s3/details/ (as of Mar 4th 2015)
I have been working on an open source project that allows you to hot replace classes over and above what hot swap allows: https://github.com/fakereplace/fakereplace
It may or may not work for you, but any feedback is appreciated
To make @Raghavendra's answer more specific:
Once you've downloaded 2 zip files,
copy ALL the contents of "win64_11gR2_database_2of2.zip -> Database -> Stage -> Components" folder to "win64_11gR2_database_1of2.zip -> Database -> Stage -> Components" folder.
You'll still get the same warning, however, the installation will run completely without generating any errors.
SELECT * FROM table ORDER BY id DESC,datechat desc LIMIT 50
If you have a date field that is storing the date(and time) on which the chat was sent or any field that is filled with incrementally(order by DESC) or desinscrementally( order by ASC) data per row put it as second column on which the data should be order.
That's what worked for me!!!! hope it will help!!!!
The question does not contain a nested loop, just a single loop. But THIS nested version works, too:
# for i in c d; do for j in a b; do echo $i $j; done; done
c a
c b
d a
d b
with the help of below commands your application will work as you aspected run each command as I mention
1.npm list -g --depth=0
2.npm i npm-check-updates
3.npm install
and finally, run the below command to open your project in browser
ng serve --open
I had the same issue and none of the above answers solved the problem, so I tried something very straight-forward: I just putted in my strings.xml
\n\t
The complete String looks like this <string name="premium_features_listing_3">- Automatische Aktualisierung der\n\tDatenbank</string>
Results in:
Automatische Aktualisierung der
Datenbank
(with no extra line in between)
Maybe it will help others. Regards
Oops, can't comment yet (!) but re: Nick and logic analyser, beware: RS232 signal levels not typically Logic Analyser compatible unless you get/make a special serial probe. A 'proper' RS232/Serial port can use +/-12v swings (on all signals) and sometimes more. A laptop sometimes uses 0-5v swings (and often won't work with real serial interfaces) so could work with a vbasic 'ttl-level' LA interface.
Your query translates to
SELECT * FROM table WHERE id='1' or id='2' or id='3' or id='4';
It will only return the results that match it.
One way of solving it avoiding the complexity would be, chaning the datatype to SET
.
Then you could use, FIND_IN_SET
SELECT * FROM table WHERE FIND_IN_SET('1', id);
OAuth 2.0 defines a protocol, i.e. specifies how tokens are transferred, JWT defines a token format.
OAuth 2.0 and "JWT authentication" have similar appearance when it comes to the (2nd) stage where the Client presents the token to the Resource Server: the token is passed in a header.
But "JWT authentication" is not a standard and does not specify how the Client obtains the token in the first place (the 1st stage). That is where the perceived complexity of OAuth comes from: it also defines various ways in which the Client can obtain an access token from something that is called an Authorization Server.
So the real difference is that JWT is just a token format, OAuth 2.0 is a protocol (that may use a JWT as a token format).