simplifily, use:
pip install -r requirement.txt
it can install all listed in requirement file.
That is the mode with which you are opening the file. "wb" means that you are writing to the file (w), and that you are writing in binary mode (b).
Check out the documentation for more: clicky
Don't overuse Vue.component()
, it registers components globally. You can create file, name it MyTask.vue, export there Vue object
https://vuejs.org/v2/guide/single-file-components.html
and then import in your main file, and don't forget to register it:
new Vue({
...
components: { myTask }
...
})
this.$('#datepicker').datepicker({minDate: 1});
minDate:0
- Enable dates in the calender from the current date. MinDate:1
enable dates in the calender currentDate+1
To Restrict date between from tomorrow and the same day next month u need to give something like
$( "#datepicker" ).datepicker({ minDate: 1, maxDate: "+1M" });
You can use the following function to find the biggest [number]
in any string.
It returns the value of the biggest [number]
as an Integer.
var biggestNumber = function(str) {
var pattern = /\[([0-9]+)\]/g, match, biggest = 0;
while ((match = pattern.exec(str)) !== null) {
if (match.index === pattern.lastIndex) {
pattern.lastIndex++;
}
match[1] = parseInt(match[1]);
if(biggest < match[1]) {
biggest = match[1];
}
}
return biggest;
}
The following demo calculates the biggest number in your textarea every time you click the button.
It allows you to play around with the textarea and re-test the function with a different text.
var biggestNumber = function(str) {_x000D_
var pattern = /\[([0-9]+)\]/g, match, biggest = 0;_x000D_
_x000D_
while ((match = pattern.exec(str)) !== null) {_x000D_
if (match.index === pattern.lastIndex) {_x000D_
pattern.lastIndex++;_x000D_
}_x000D_
match[1] = parseInt(match[1]);_x000D_
if(biggest < match[1]) {_x000D_
biggest = match[1];_x000D_
}_x000D_
}_x000D_
return biggest;_x000D_
}_x000D_
_x000D_
document.getElementById("myButton").addEventListener("click", function() {_x000D_
alert(biggestNumber(document.getElementById("myTextArea").value));_x000D_
});
_x000D_
<div>_x000D_
<textarea rows="6" cols="50" id="myTextArea">_x000D_
this is a test [1] also this [2] is a test_x000D_
and again [18] this is a test. _x000D_
items[14].items[29].firstname too is a test!_x000D_
items[4].firstname too is a test!_x000D_
</textarea>_x000D_
</div>_x000D_
_x000D_
<div>_x000D_
<button id="myButton">Try me</button>_x000D_
</div>
_x000D_
See also this Fiddle!
I couldn't properly follow the other answers, here's more of a dummies guide...
You can do this either way round to go trunk -> branch
or branch -> trunk
. I always first do trunk -> branch
fix any conflicts there and then merge branch -> trunk
.
Abstract Method:
If an abstract method is defined in a class, then the class should declare as an abstract class.
An abstract method should contain only method definition, should not Contain the method body/implementation.
An abstract method must be over ride in the derived class.
Virtual Method:
Example:
public abstract class baseclass
{
public abstract decimal getarea(decimal Radius);
public virtual decimal interestpermonth(decimal amount)
{
return amount*12/100;
}
public virtual decimal totalamount(decimal Amount,decimal principleAmount)
{
return Amount + principleAmount;
}
}
public class derivedclass:baseclass
{
public override decimal getarea(decimal Radius)
{
return 2 * (22 / 7) * Radius;
}
public override decimal interestpermonth(decimal amount)
{
return amount * 14 / 100;
}
}
Did you try putting all your jars directly in the WEB-INF/lib
dir instead of sub-dirs of that?
No WEB-INF/lib/spring/org.springframework.aop-3.0.0.RELEASE.jar
, just WEB-INF/lib/org.springframework.aop-3.0.0.RELEASE.jar
Same with the rest of the jars.
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6);
int[] arr= stream.mapToInt(x->x.intValue()).toArray();
It should be noted that releasing an alpha app for the first time may take up to a few hours before an opt-in link is available and invitations are sent out to the email addresses in your testers list.
From Google support:
After publishing an alpha/beta app for the first time, it may take a few hours for your test link to be available to testers. If you publish additional changes, they may take several hours to be available for testers. [source]
You may want to wait until you have an initial opt-in link before publishing more changes to the app because doing so is likely to increase your wait time for receiving your tester link; or, may lead to your testers testing with the incorrect version.
Hope that clears things up for anyone confused about why they don't have an opt-in link as depicted in screenshots in this SO thread!
This is because after the nextInt() finished it's execution, when the nextLine() method is called, it scans the newline character of which was present after the nextInt(). You can do this in either of the following ways:
You can use the next method on the scanner object as
scan.next();
ToList
will always create a new list, which will not reflect any subsequent changes to the collection.
However, it will reflect changes to the objects themselves (Unless they're mutable structs).
In other words, if you replace an object in the original list with a different object, the ToList
will still contain the first object.
However, if you modify one of the objects in the original list, the ToList
will still contain the same (modified) object.
I'm 3 years late for the party :( However this could be useful for someone who might stumble upon this post.
I've written a library that caches Typefaces and also allow you to specify custom typefaces right from XML. You can find the library here.
Here is how your XML layout would look like, when you use it.
<com.mobsandgeeks.ui.TypefaceTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world"
geekui:customTypeface="fonts/custom_font.ttf" />
Both these will give you the first child node:
console.log(parentElement.firstChild); // or
console.log(parentElement.childNodes[0]);
If you need the first child that is an element node then use:
console.log(parentElement.children[0]);
Edit
Ah, I see your problem now; parentElement
is an array.
If you know that getElementsByClassName will only return one result, which it seems you do, you should use [0]
to dearray (yes, I made that word up) the element:
var parentElement = document.getElementsByClassName("uniqueClassName")[0];
If you want the charcode for each character in the string, you could do something like this:
char[] chars = "9quali52ty3".ToCharArray();
Use this query and then check the results.
$query = 'show tables like "test1"';
Because line magics are only supported by the IPython command line not by Python cl, use: 'exec(%matplotlib inline)'
instead of %matplotlib inline
Humm, what? ssh is not something built in to Windows like in most *nix cases.
You'd probably want to use Putty to begin with. And: http://kb.siteground.com/how_to_generate_an_ssh_key_on_windows_using_putty/
Swift Implementation of Android Toast using Alert which dissipate after 3 secs.
func showAlertView(title: String?, message: String?) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
let okAction = UIAlertAction(title: "OK", style: .Cancel, handler: nil)
alertController.addAction(okAction)
self.presentViewController(alertController, animated: true, completion: nil)
let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(3 * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue()) {
print("Bye. Lovvy")
alertController.dismissViewControllerAnimated(true, completion: nil)
}
}
To Call it simply :
self.showAlertView("Message sent...", message: nil)
I have the same error and it fixed it including in the file the following
#include <stdint.h>
at the beginning of your file.
This help to hide and show the sidebar, and the content take place of the empty space left by the sidebar.
<div id="A">Sidebar</div>
<div id="B"><button>toggle</button>
Content here: Bla, bla, bla
</div>
//Toggle Hide/Show sidebar slowy
$(document).ready(function(){
$('#B').click(function(e) {
e.preventDefault();
$('#A').toggle('slow');
$('#B').toggleClass('extended-panel');
});
});
html, body {
margin: 0;
padding: 0;
border: 0;
}
#A, #B {
position: absolute;
}
#A {
top: 0px;
width: 200px;
bottom: 0px;
background:orange;
}
#B {
top: 0px;
left: 200px;
right: 0;
bottom: 0px;
background:green;
}
/* makes the content take place of the SIDEBAR
which is empty when is hided */
.extended-panel {
left: 0px !important;
}
<android.support.v7.widget.RecyclerView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layoutManager="android.support.v7.widget.LinearLayoutManager" />
Is that an actual compiler error or a Code Analysis error? Some times the code analysis can be a bit sketchy and report non-valid errors.
To turn off code analysis for the project, right click on your project in the Project Explorer, click on Properties, then go to the C/C++ General tab, then Code Analysis. Then click on "Use Project Settings" and disable the ones that you do not wish for.
Also, are you sure you are compiling with the C++11 compiler?
I would not suggest to use sll
or srl
with std_logic_vector.
During simulation sll
gave me 'U' value for those bits, where I expected 0's.
Use shift_left()
, shift_right()
functions.
For example:
OP1 : in std_logic_vector(7 downto 0);
signal accum: std_logic_vector(7 downto 0);
accum <= std_logic_vector(shift_left(unsigned(accum), to_integer(unsigned(OP1))));
accum <= std_logic_vector(shift_right(unsigned(accum), to_integer(unsigned(OP1))));
UseParNewGC usually knowns as "parallel young generation collector" is same in all ways as the parallel garbage collector (-XX:+UseParallelGC), except that its more sophiscated and effiecient. Also it can be used with a "concurrent low pause collector".
See Java GC FAQ, question 22 for more information.
Note that there are some known bugs with UseParNewGC
Just adding here that [[
also is equipped for recursive indexing.
This was hinted at in the answer by @JijoMatthew but not explored.
As noted in ?"[["
, syntax like x[[y]]
, where length(y) > 1
, is interpreted as:
x[[ y[1] ]][[ y[2] ]][[ y[3] ]] ... [[ y[length(y)] ]]
Note that this doesn't change what should be your main takeaway on the difference between [
and [[
-- namely, that the former is used for subsetting, and the latter is used for extracting single list elements.
For example,
x <- list(list(list(1), 2), list(list(list(3), 4), 5), 6)
x
# [[1]]
# [[1]][[1]]
# [[1]][[1]][[1]]
# [1] 1
#
# [[1]][[2]]
# [1] 2
#
# [[2]]
# [[2]][[1]]
# [[2]][[1]][[1]]
# [[2]][[1]][[1]][[1]]
# [1] 3
#
# [[2]][[1]][[2]]
# [1] 4
#
# [[2]][[2]]
# [1] 5
#
# [[3]]
# [1] 6
To get the value 3, we can do:
x[[c(2, 1, 1, 1)]]
# [1] 3
Getting back to @JijoMatthew's answer above, recall r
:
r <- list(1:10, foo=1, far=2)
In particular, this explains the errors we tend to get when mis-using [[
, namely:
r[[1:3]]
Error in
r[[1:3]]
: recursive indexing failed at level 2
Since this code actually tried to evaluate r[[1]][[2]][[3]]
, and the nesting of r
stops at level one, the attempt to extract through recursive indexing failed at [[2]]
, i.e., at level 2.
Error in
r[[c("foo", "far")]]
: subscript out of bounds
Here, R was looking for r[["foo"]][["far"]]
, which doesn't exist, so we get the subscript out of bounds error.
It probably would be a bit more helpful/consistent if both of these errors gave the same message.
Simple solution, just one line..
var obj = {
"set1": [1, 2, 3],
"set2": [4, 5, 6, 7, 8],
"set3": [9, 10, 11, 12]
};
obj = Object.values(obj);
obj[1]....
Go into Tools -> Options -> Designers-> Uncheck "Prevent saving changes that require table re-creation". Voila.
That happens because sometimes it is necessary to drop and recreate a table in order to change something. This can take a while, since all data must be copied to a temp table and then re-inserted in the new table. Since SQL Server by default doesn't trust you, you need to say "OK, I know what I'm doing, now let me do my work."
It might be useful to make an extension in Swift for this.
Swift 4 and Swift 5:
Swift extension (e.g. in a UITableViewExtension.swift file):
import UIKit
extension UITableView {
func deselectSelectedRow(animated: Bool)
{
if let indexPathForSelectedRow = self.indexPathForSelectedRow {
self.deselectRow(at: indexPathForSelectedRow, animated: animated)
}
}
}
Use e.g.:
override func viewWillAppear(_ animated: Bool)
{
super.viewWillAppear(animated)
self.tableView.deselectSelectedRow(animated: true)
}
I had this same issue and realised it was because I was calling res.redirect
without a return
statement, so the next
function was also being called immediately afterwards:
auth.annonymousOnly = function(req, res, next) {
if (req.user) res.redirect('/');
next();
};
Which should have been:
auth.annonymousOnly = function(req, res, next) {
if (req.user) return res.redirect('/');
next();
};
what is the exec function and its family.
The exec
function family is all functions used to execute a file, such as execl
, execlp
, execle
, execv
, and execvp
.They are all frontends for execve
and provide different methods of calling it.
why is this function used
Exec functions are used when you want to execute (launch) a file (program).
and how does it work.
They work by overwriting the current process image with the one that you launched. They replace (by ending) the currently running process (the one that called the exec command) with the new process that has launched.
For more details: see this link.
If the string is fixed you can simply use:
if line.startswith("Path="):
return line[5:]
which gives you everything from position 5 on in the string (a string is also a sequence so these sequence operators work here, too).
Or you can split the line at the first =
:
if "=" in line:
param, value = line.split("=",1)
Then param is "Path" and value is the rest after the first =.
Assume your original xml is:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true"
android:drawable="@drawable/tick_img" />
<item android:state_checked="false"
android:drawable="@drawable/untick_img" />
</selector>
then simply remove android:button="@drawable/xml_above"
in your checkbox xml, and do drawable scaling programmatically in java (decrease the 150
big size to your desired dp):
CheckBox tickRememberPasswd = findViewById(R.id.remember_tick);
//custom selector size
Drawable drawableTick = ContextCompat.getDrawable(this, R.drawable.tick_img);
Drawable drawableUntick = ContextCompat.getDrawable(this, R.drawable.untick_img);
Bitmap bitmapTick = null;
if (drawableTick != null && drawableUntick != null) {
int desiredPixels = Math.round(convertDpToPixel(150, this));
bitmapTick = ((BitmapDrawable) drawableTick).getBitmap();
Drawable dTick = new BitmapDrawable(getResources()
, Bitmap.createScaledBitmap(bitmapTick, desiredPixels, desiredPixels, true));
Bitmap bitmapUntick = ((BitmapDrawable) drawableUntick).getBitmap();
Drawable dUntick = new BitmapDrawable(getResources()
, Bitmap.createScaledBitmap(bitmapUntick, desiredPixels, desiredPixels, true));
final StateListDrawable statesTick = new StateListDrawable();
statesTick.addState(new int[] {android.R.attr.state_checked},
dTick);
statesTick.addState(new int[] { }, //else state_checked false
dUntick);
tickRememberPasswd.setButtonDrawable(statesTick);
}
the convertDpToPixel
method:
public static float convertDpToPixel(float dp, Context context) {
Resources resources = context.getResources();
DisplayMetrics metrics = resources.getDisplayMetrics();
float px = dp * (metrics.densityDpi / 160f);
return px;
}
If you are using a certificate signed by a Certificate Authority that is not included in the Java cacerts file by default, you need to complete the following configuration for HTTPS connections. To import certificates into cacerts:
Use:
call msbuild.bat
call unit-tests.bat
call deploy.bat
When not using CALL, the current batch file stops and the called batch file starts executing. It's a peculiar behavior dating back to the early MS-DOS days.
It is indeed possible.
Here is an example calling the Weather SOAP Service using plain requests lib:
import requests
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
#headers = {'content-type': 'application/soap+xml'}
headers = {'content-type': 'text/xml'}
body = """<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:ns0="http://ws.cdyne.com/WeatherWS/" xmlns:ns1="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/>
<ns1:Body><ns0:GetWeatherInformation/></ns1:Body>
</SOAP-ENV:Envelope>"""
response = requests.post(url,data=body,headers=headers)
print response.content
Some notes:
application/soap+xml
is probably the more correct header to use (but the weatherservice prefers text/xml
For example:
from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('myapp', 'templates'))
template = env.get_template('soaprequests/WeatherSericeRequest.xml')
body = template.render()
Some people have mentioned the suds library. Suds is probably the more correct way to be interacting with SOAP, but I often find that it panics a little when you have WDSLs that are badly formed (which, TBH, is more likely than not when you're dealing with an institution that still uses SOAP ;) ).
You can do the above with suds like so:
from suds.client import Client
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
client = Client(url)
print client ## shows the details of this service
result = client.service.GetWeatherInformation()
print result
Note: when using suds, you will almost always end up needing to use the doctor!
Finally, a little bonus for debugging SOAP; TCPdump is your friend. On Mac, you can run TCPdump like so:
sudo tcpdump -As 0
This can be helpful for inspecting the requests that actually go over the wire.
The above two code snippets are also available as gists:
if you're turned off by the extra line, you can use a wrapper function like so:
def with_iter(iterable):
with iterable as iter:
for item in iter:
yield item
for line in with_iter(open('...')):
...
in Python 3.3, the yield from
statement would make this even shorter:
def with_iter(iterable):
with iterable as iter:
yield from iter
You probably want to use some Unicode character encoding, for example UTF-8, and htmlspecialchars. Because there isn't any need to generate "HTML entities" for "all [the] applicable characters" (that is what htmlentities does according to the documentation) if it's already in your character set.
I have IIS 7 and installed PHP using Microsoft Web Platform Installer on Windows 7. In IIS, go to PHP Manager in settings main page -> PHP Extensions -> Enable or Disable an Extension. Intl extension is disabled by default.
I hope this helps
There are 3 location providers in Android.
They are:
gps –> (GPS, AGPS): Name of the GPS location provider. This provider determines location using satellites. Depending on conditions, this provider may take a while to return a location fix. Requires the permission android.permission.ACCESS_FINE_LOCATION.
network –> (AGPS, CellID, WiFi MACID): Name of the network location provider. This provider determines location based on availability of cell tower and WiFi access points. Results are retrieved by means of a network lookup. Requires either of the permissions android.permission.ACCESS_COARSE_LOCATION or android.permission.ACCESS_FINE_LOCATION.
passive –> (CellID, WiFi MACID): A special location provider for receiving locations without actually initiating a location fix. This provider can be used to passively receive location updates when other applications or services request them without actually requesting the locations yourself. This provider will return locations generated by other providers. Requires the permission android.permission.ACCESS_FINE_LOCATION, although if the GPS is not enabled this provider might only return coarse fixes. This is what Android calls these location providers, however, the underlying technologies to make this stuff work is mapped to the specific set of hardware and telco provided capabilities (network service).
The best way is to use the “network” or “passive” provider first, and then fallback on “gps”, and depending on the task, switch between providers. This covers all cases, and provides a lowest common denominator service (in the worst case) and great service (in the best case).
Article Reference : Android Location Providers - gps, network, passive By Nazmul Idris
Code Reference : https://stackoverflow.com/a/3145655/28557
-----------------------Update-----------------------
Now Android have Fused location provider
The Fused Location Provider intelligently manages the underlying location technology and gives you the best location according to your needs. It simplifies ways for apps to get the user’s current location with improved accuracy and lower power usage
Fused location provider provide three ways to fetch location
References :
Official site : http://developer.android.com/google/play-services/location.html
Fused location provider example: GIT : https://github.com/kpbird/fused-location-provider-example
http://blog.lemberg.co.uk/fused-location-provider
--------------------------------------------------------
You can try with
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
For those who are green programmers in .NET, to add the DLL reference as MarcGravell noted, you follow these steps:
To add a reference in Visual C#
From the MSDN Article, How to: Add or Remove References By Using the Add Reference Dialog Box.
SELECT table1.col_a, table1.col_b, table2.col_c
FROM table1
INNER JOIN table2 ON table1.col_a = table2.col_a
It depends on wether the locatoin is detected by different DNS resolution from different locations, or by IP address that you are browsing from.
If its by DNS, you could just modify your hosts file to point at the server used in europe. Get your friend to ping the address, to see if its different from the one yours resolves to.
To browse from a different IP address:
You can rent a VPS server. You can use putty / SSH to act as a proxy. I use this from time to time to brows from the US using a VPS server I rent in the US.
Having an account on a remote host may or may not be enough. Sadly, my dreamhost account, even though I have ssh access, does not allow proxying.
Unchecking "Enable JavaScript debugging for ASP.NET (Chrome and IE)" in Tools->Options->Debugging->General resolved my case with unavailability to launch VS2017 debugger with pre-set breakpoints.
You can use the following if you want to specify tricky formats:
df['date_col'] = pd.to_datetime(df['date_col'], format='%d/%m/%Y')
More details on format
here:
Something has deleted your ibdata1 file where InnoDB keeps the dictionary. Definitely it's not MySQL who does it.
UPDATE: I made a tutorial on how to fix the error - https://youtu.be/014KbCYayuE
if you run node index.js
,Node will use 3000
If you run PORT=4444 node index.js
, Node will use process.env.PORT
which equals to 4444
in this example. Run with sudo
for ports below 1024.
Here's how to find the current and latest available versions:
try {
String curVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
String newVersion = curVersion;
newVersion = Jsoup.connect("https://play.google.com/store/apps/details?id=" + getPackageName() + "&hl=en")
.timeout(30000)
.userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6")
.referrer("http://www.google.com")
.get()
.select("div.hAyfc:nth-child(4) .IQ1z0d .htlgb")
.first()
.ownText();
Log.d("Curr Version" , curVersion);
Log.d("New Version" , newVersion);
} catch (Exception e) {
e.printStackTrace();
return false;
}
In my experience, most often this error message means that you have put an accidental closing brace somewhere, leaving the rest of your statements outside the function.
Example:
function a() {
if (global_block) //syntax error is actually here - missing opening brace
return;
} //this unintentionally ends the function
if (global_somethingelse) {
//Chrome will show the error occurring here,
//but actually the error is in the previous statement
return;
}
//do something
}
Case: If you need to ignore the merge commit created by default, follow these steps.
Say, a new feature branch is checked out from master having 2 commits already,
Checkout a new feature_branch
Feature branch then adds two commits-->
Now if you want to merge feature_branch changes to master, Do git merge feature_branch
sitting on the master.
This will add all commits into master branch (4 in master + 2 in feature_branch = total 6) + an extra merge commit something like 'Merge branch 'feature_branch'
' as the master is diverged.
If you really need to ignore these commits (those made in FB) and add the whole changes made in feature_branch as a single commit like 'Integrated feature branch changes into master'
, Run git merge feature_merge --no-commit
.
With --no-commit, it perform the merge and stop just before creating a merge commit, We will have all the added changes in feature branch now in master and get a chance to create a new commit as our own.
Read here for more : https://git-scm.com/docs/git-merge
This is an old post but still a problem within the Chrome dev tools. I find the best way to check mobile source locally is to open the site locally in Xcode's iOS Simulator. Then from there you open the Safari browser and enable dev tools, if you have not already done this (go to preferences -> advanced -> show develop menu in menu bar). Now you will see the develop option in the main menu and can go to develop -> iOS Simulator -> and the page you have open in Xcode's iOS Simulator will be there. Once you click on it, it will open the web inspector and you can edit as you would normally in the browser dev tools.
I'm afraid this solution will only work on a Mac though as it uses Xcode.
Dan Benjamin's Hivelogic article Installing Ruby, RubyGems, and Rails on Snow Leopard is the recommended place to go although the article is for 1.8, so here's a Ruby 1.9-specific install on Snow Leopard. Watch out for the 64-bit thing... either go all 64-bit 'fat' (as is - for example - Apache on OS X, which can cause problems with 32-bit libraries) or check any gems you're likely to use to make sure they're okay for 64-bit.
Just for the purpose of mentioning underscore's find method works in IE with no problem.
Use the propertyregex task from Ant Contrib.
I think you want:
<propertyregex property="propB"
input="${propA}"
regexp=" "
replace="_"
global="true" />
Unfortunately the examples given aren't terribly clear, but it's worth trying that. You should also check what happens if there aren't any underscores - you may need to use the defaultValue
option as well.
In Layout,to change background use this.
android:background="@color/your_color"
In Program can be use this. For eg: Texview background color
TextView tvName = (TextView) findViewById(R.id.tvName);
tvName.setBackgroundColor(getResources().getColor(R.color.your_color));
Nowadays you can do...
switch ([$group1, $group2]){
case ["users", "location"]:
case ["users", "online"]:
Ju_le_do_the_thing();
break;
case ["forum", $group2]:
Foo_the_bar();
break;
}
For supporting all UTF-16 (also non-BMP/supplementary characters) from ES6 the string.codePointAt() method is available;
This method is an improved version of charCodeAt which could support only unicode codepoints < 65536 ( 216 - a single 16bit ) .
Add the -v
option to your grep
command to invert the results.
Checkboxes being children of Button you can just give your checkbox a background image with several states as described here, under "Button style":
...and exemplified here:
try Array.prototype.some()
function isBiggerThan10(element, index, array) {
return element > 10;
}
[2, 5, 8, 1, 4].some(isBiggerThan10); // false
[12, 5, 8, 1, 4].some(isBiggerThan10); // true
You can also use ddms for logcat logs where just giving search of the app name you will all info but you have to select Info instead of verbose or other options. check this below image.
request.getContextPath()-
returns root path of your application, while
../
- returns parent directory of a file.
You use request.getContextPath(), as it will always points to root of your application. If you were to move your jsp file from one directory to another, nothing needs to be changed. Now, consider the second approach. If you were to move your jsp files from one folder to another, you'd have to make changes at every location where you are referring your files.
Also, better approach of using request.getContextPath() will be to set 'request.getContextPath()' in a variable and use that variable for referring your path.
<c:set var="context" value="${pageContext.request.contextPath}" />
<script src="${context}/themes/js/jquery.js"></script>
PS- This is the one reason I can figure out. Don't know if there is any more significance to it.
Use this code for IE9 and above:
window.frames["printf"].focus();
window.frames["printf"].print();
For IE8:
window.frames[0].focus();
window.frames[0].print();
I like to use:
git diff HEAD^
Or if I only want to diff a specific file:
git diff HEAD^ -- /foo/bar/baz.txt
In httpd.conf
LoadModule headers_module modules/mod_headers.so
LoadModule rewrite_module modules/mod_rewrite.so
<Directory "**/usr/local/PATH**">
AllowOverride None
Require all granted
Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"
Header always set Access-Control-Expose-Headers "Content-Security-Policy, Location"
Header always set Access-Control-Max-Age "600"
RewriteEngine On
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L]
</Directory>
If running outside container, you may need to restart apache service.
Public SUB test()
Dim mdate As Date
mdate = now()
MsgBox (Round(CDbl(mdate), 0))
End SUB
April 11, 2019
None of the answers above solved my problem so I wanted to include a current solution (as of April 2019) for people using Ubuntu 18.04. This is how I solved the question above...
/usr/lib/Android/
Search for where the SDK is installed and the version. In my case it was here:
/usr/lib/Android/Sdk/build-tools/28.0.3
Note: that I am using version 28.0.3, your version may differ.
Add ANDROID_HOME
to the environment path. To do this, open /etc/environment with a text editor:
sudo nano /etc/environment
Add a line for ANDROID_HOME
for your specific version and path. In my case it was:
ANDROID_HOME="/usr/lib/Android/Sdk/build-tools/28.0.3"
Finally, source the updated environment with: source /etc/environment
Confirm this by trying: echo $ANDROID_HOME
in the terminal. You should get the path of your newly created variable.
One additionally note about sourcing, I did have to restart my computer for the VScode terminal to recognize my changes. After the restart, the environment was set and I haven't had any issues since.
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
Row row = sheet.getRow(0);
Cell cell = row.getCell(0);
if(cell.getCellTypeEnum() == CellType.NUMERIC||cell.getCellTypeEnum() == CellType.FORMULA)
{
String cellValue=String.valueOf(cell.getNumericCellValue());
if(HSSFDateUtil.isCellDateFormatted(cell))
{
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
Date date = cell.getDateCellValue();
cellValue = df.format(date);
}
System.out.println(cellValue);
}
Simply use an image extension like .jpeg
or .png
.
You can compare with the original exception Class using getCause() method like this :
try{
...
} catch(Exception e){
if(e.getCause().getClass().equals(AssertionError.class)){
// handle your exception 1
} else {
// handle the rest of the world exception
}
}
I'd use JSON as the format and Ajax (really XMLHttpRequest) as the client->server mechanism.
You need to merge the remote branch into your current branch by running git pull
.
If your local branch is already up-to-date, you may also need to run git pull --rebase
.
A quick google search also turned up this same question asked by another SO user: Cannot push to GitHub - keeps saying need merge. More details there.
add the activity in your manifest file
<activity android:name=".OrderScreen" />
This is more narrowly-tailored. When I do this I usually have a comma-delimited list of unique ids (INT or BIGINT), which I want to cast as a table to use as an inner join to another table that has a primary key of INT or BIGINT. I want an in-line table-valued function returned so that I have the most efficient join possible.
Sample usage would be:
DECLARE @IDs VARCHAR(1000);
SET @IDs = ',99,206,124,8967,1,7,3,45234,2,889,987979,';
SELECT me.Value
FROM dbo.MyEnum me
INNER JOIN dbo.GetIntIdsTableFromDelimitedString(@IDs) ids ON me.PrimaryKey = ids.ID
I stole the idea from http://sqlrecords.blogspot.com/2012/11/converting-delimited-list-to-table.html, changing it to be in-line table-valued and cast as INT.
create function dbo.GetIntIDTableFromDelimitedString
(
@IDs VARCHAR(1000) --this parameter must start and end with a comma, eg ',123,456,'
--all items in list must be perfectly formatted or function will error
)
RETURNS TABLE AS
RETURN
SELECT
CAST(SUBSTRING(@IDs,Nums.number + 1,CHARINDEX(',',@IDs,(Nums.number+2)) - Nums.number - 1) AS INT) AS ID
FROM
[master].[dbo].[spt_values] Nums
WHERE Nums.Type = 'P'
AND Nums.number BETWEEN 1 AND DATALENGTH(@IDs)
AND SUBSTRING(@IDs,Nums.number,1) = ','
AND CHARINDEX(',',@IDs,(Nums.number+1)) > Nums.number;
GO
This simplistic version also works.
public void UploadMultipart(byte[] file, string filename, string contentType, string url)
{
var webClient = new WebClient();
string boundary = "------------------------" + DateTime.Now.Ticks.ToString("x");
webClient.Headers.Add("Content-Type", "multipart/form-data; boundary=" + boundary);
var fileData = webClient.Encoding.GetString(file);
var package = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n{3}\r\n--{0}--\r\n", boundary, filename, contentType, fileData);
var nfile = webClient.Encoding.GetBytes(package);
byte[] resp = webClient.UploadData(url, "POST", nfile);
}
Add any extra required headers if needed.
While using Google reCaptcha with reCaptcha DLL file, we can validate it in C# as follows :
RecaptchaControl1.Validate();
bool _Varify = RecaptchaControl1.IsValid;
if (_Varify)
{
// Pice of code after validation.
}
Its works for me.
In addition to the answer, you can't directly use output redirection operators in the set part of for
loop (e.g. if you wanna hide stderror output from a user and provide a nicer error message). Instead, you have to escape them with a caret character (^
):
for /f %%O in ('some-erroring-command 2^> nul') do (echo %%O)
Reference: Redirect output of command in for loop of batch script
I recently stumbled upon this great Gist that gives a working implementation of a drag sort ListView
, with no external dependencies needed.
Basically it consists on creating your custom Adapter extending ArrayAdapter
as an inner class to the activity containing your ListView
. On this adapter one then sets an onTouchListener
to your List Items that will signal the start of the drag.
In that Gist they set the listener to a specific part of the layout of the List Item (the "handle" of the item), so one does not accidentally move it by pressing any part of it. Personally, I preferred to go with an onLongClickListener
instead, but that is up to you to decide. Here an excerpt of that part:
public class MyArrayAdapter extends ArrayAdapter<String> {
private ArrayList<String> mStrings = new ArrayList<String>();
private LayoutInflater mInflater;
private int mLayout;
//constructor, clear, remove, add, insert...
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
View view = convertView;
//inflate, etc...
final String string = mStrings.get(position);
holder.title.setText(string);
// Here the listener is set specifically to the handle of the layout
holder.handle.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
startDrag(string);
return true;
}
return false;
}
});
// change color on dragging item and other things...
return view;
}
}
This also involves adding an onTouchListener
to the ListView
, which checks if an item is being dragged, handles the swapping and invalidation, and stops the drag state. An excerpt of that part:
mListView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent event) {
if (!mSortable) { return false; }
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
break;
}
case MotionEvent.ACTION_MOVE: {
// get positions
int position = mListView.pointToPosition((int) event.getX(),
(int) event.getY());
if (position < 0) {
break;
}
// check if it's time to swap
if (position != mPosition) {
mPosition = position;
mAdapter.remove(mDragString);
mAdapter.insert(mDragString, mPosition);
}
return true;
}
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_OUTSIDE: {
//stop drag state
stopDrag();
return true;
}
}
return false;
}
});
Finally, here is how the stopDrag
and startDrag
methods look like, which handle the enabling and disabling of the drag process:
public void startDrag(String string) {
mPosition = -1;
mSortable = true;
mDragString = string;
mAdapter.notifyDataSetChanged();
}
public void stopDrag() {
mPosition = -1;
mSortable = false;
mDragString = null;
mAdapter.notifyDataSetChanged();
}
GNU parallel
I was making a synthetic compilation benchmark and couldn't be bothered to write a Makefile, so I used:
sudo apt-get install parallel
ls | grep -E '\.c$' | parallel -t --will-cite "gcc -c -o '{.}.o' '{}'"
Explanation:
{.}
takes the input argument and removes its extension-t
prints out the commands being run to give us an idea of progress--will-cite
removes the request to cite the software if you publish results using it...parallel
is so convenient that I could even do a timestamp check myself:
ls | grep -E '\.c$' | parallel -t --will-cite "\
if ! [ -f '{.}.o' ] || [ '{}' -nt '{.}.o' ]; then
gcc -c -o '{.}.o' '{}'
fi
"
xargs -P
can also run jobs in parallel, but it is a bit less convenient to do the extension manipulation or run multiple commands with it: Calling multiple commands through xargs
Parallel linking was asked at: Can gcc use multiple cores when linking?
TODO: I think I read somewhere that compilation can be reduced to matrix multiplication, so maybe it is also possible to speed up single file compilation for large files. But I can't find a reference now.
Tested in Ubuntu 18.10.
Try it :
$(function () {
$('#datetimepicker').datetimepicker({ minDate:new Date()});
});
Ok, I figured it out. I just wrapped it in a try catch and send back null.
public String test() {
String cert=null;
String sql = "select ID_NMB_SRZ from codb_owner.TR_LTM_SLS_RTN
where id_str_rt = '999' and ID_NMB_SRZ = '60230009999999'";
try {
Object o = (String) jdbc.queryForObject(sql, String.class);
cert = (String) o;
} catch (EmptyResultDataAccessException e) {
e.printStackTrace();
}
return cert;
}
If you want to bind an event like 'click' for all the elements having same class in the rendered DOM element then you can set up an event listener by using following parts of the code in components.ts file.
import { Component, OnInit, Renderer, ElementRef} from '@angular/core';
constructor( elementRef: ElementRef, renderer: Renderer) {
dragulaService.drop.subscribe((value) => {
this.onDrop(value.slice(1));
});
}
public onDrop(args) {
let [e, el] = args;
this.toggleClassComTitle(e,'checked');
}
public toggleClassComTitle(el: any, name: string) {
el.querySelectorAll('.com-item-title-anchor').forEach( function ( item ) {
item.addEventListener('click', function(event) {
console.log("item-clicked");
});
});
}
You can use map
:
List<String> names =
personList.stream()
.map(Person::getName)
.collect(Collectors.toList());
EDIT :
In order to combine the Lists of friend names, you need to use flatMap
:
List<String> friendNames =
personList.stream()
.flatMap(e->e.getFriends().stream())
.collect(Collectors.toList());
(Using Web Forms ASP.NET)
My issue was I was trying to fire Ajax off the click event of a submit button that had a server side click event setup. I had to make the button just a simple button (i.e. <input type="button">
)
This is what the res.locals object is for. Setting variables directly on the request object is not supported or documented. res.locals is guaranteed to hold state over the life of a request.
An object that contains response local variables scoped to the request, and therefore available only to the view(s) rendered during that request / response cycle (if any). Otherwise, this property is identical to app.locals.
This property is useful for exposing request-level information such as the request path name, authenticated user, user settings, and so on.
app.use(function(req, res, next) {
res.locals.user = req.user;
res.locals.authenticated = !req.user.anonymous;
next();
});
To retrieve the variable in the next middleware:
app.use(function(req, res, next) {
if (res.locals.authenticated) {
console.log(res.locals.user.id);
}
next();
});
We have come with a great solution. This solution is practically done in Laravel 6. If you want to remove any package from your Laravel Project then you can easily remove the package by following below steps:
Step 1: You must know the package name which you want to remove. If you don't know complete package name then you can open your project folder and go to composer.json
file and check name in require an array
"require": {
"php": "^7.2",
"fideloper/proxy": "^4.0",
"laravel/framework": "^6.2",
"laravel/passport": "^8.3",
"laravel/tinker": "^2.0"
},
Suppose, here I am going to remove "fideloper/proxy" package.
Step 2: Open command prompt with your project root folder directory Step 3: First of all clear all cache by following commands. Run commands one by one.
php artisan cache:clear
php artisan config:clear
Step 4: Now write the following command to remove the package. Here you need to change your package name instead of my example package.
composer remove fideloper/proxy
Now, wait for a few seconds your package is removing.
There is collection of Func<...>
classes - Func that is probably what you are looking for:
void MyMethod(Func<int> param1 = null)
This defines method that have parameter param1
with default value null
(similar to AS), and a function that returns int
. Unlike AS in C# you need to specify type of the function's arguments.
So if you AS usage was
MyMethod(function(intArg, stringArg) { return true; })
Than in C# it would require param1
to be of type Func<int, siring, bool>
and usage like
MyMethod( (intArg, stringArg) => { return true;} );
I have implemented a tiny benchmark (please find the code on Gist) to evaluate the pandas' concat
and append
. I updated the code snippet and the results after the comment by ssk08
- thanks alot!
The benchmark ran on a Mac OS X 10.13 system with Python 3.6.2 and pandas 0.20.3.
+--------+---------------------------------+---------------------------------+ | | ignore_index=False | ignore_index=True | +--------+---------------------------------+---------------------------------+ | size | append | concat | append/concat | append | concat | append/concat | +--------+--------+--------+---------------+--------+--------+---------------+ | small | 0.4635 | 0.4891 | 94.77 % | 0.4056 | 0.3314 | 122.39 % | +--------+--------+--------+---------------+--------+--------+---------------+ | medium | 0.5532 | 0.6617 | 83.60 % | 0.3605 | 0.3521 | 102.37 % | +--------+--------+--------+---------------+--------+--------+---------------+ | large | 0.9558 | 0.9442 | 101.22 % | 0.6670 | 0.6749 | 98.84 % | +--------+--------+--------+---------------+--------+--------+---------------+
Using ignore_index=False
append
is slightly faster, with ignore_index=True
concat
is slightly faster.
tl;dr
No significant difference between concat
and append
.
Spring annotations will work fine if you remove enctype="multipart/form-data"
.
@RequestParam(value="txtEmail", required=false)
You can even get the parameters from the request
object .
request.getParameter(paramName);
Use a form in case the number of attributes are large. It will be convenient. Tutorial to get you started.
Configure the Multi-part resolver if you want to receive enctype="multipart/form-data"
.
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="250000"/>
</bean>
Refer the Spring documentation.
It is up to the browser but they behave in similar ways.
I have tested FF, IE7, Opera and Chrome.
F5 usually updates the page only if it is modified. The browser usually tries to use all types of cache as much as possible and adds an "If-modified-since" header to the request. Opera differs by sending a "Cache-Control: no-cache".
CTRL-F5 is used to force an update, disregarding any cache. IE7 adds an "Cache-Control: no-cache", as does FF, which also adds "Pragma: no-cache". Chrome does a normal "If-modified-since" and Opera ignores the key.
If I remember correctly it was Netscape which was the first browser to add support for cache-control by adding "Pragma: No-cache" when you pressed CTRL-F5.
Edit: Updated table
The table below is updated with information on what will happen when the browser's refresh-button is clicked (after a request by Joel Coehoorn), and the "max-age=0" Cache-control-header.
Updated table, 27 September 2010
+------------------------------------------------------------+
¦ UPDATED ¦ Firefox 3.x ¦
¦27 SEP 2010 ¦ +--------------------------------------------¦
¦ ¦ ¦ MSIE 8, 7 ¦
¦ Version 3 ¦ ¦ +-----------------------------------------¦
¦ ¦ ¦ ¦ Chrome 6.0 ¦
¦ ¦ ¦ ¦ +--------------------------------------¦
¦ ¦ ¦ ¦ ¦ Chrome 1.0 ¦
¦ ¦ ¦ ¦ ¦ +-----------------------------------¦
¦ ¦ ¦ ¦ ¦ ¦ Opera 10, 9 ¦
¦ ¦ ¦ ¦ ¦ ¦ +--------------------------------¦
¦ ¦ ¦ ¦ ¦ ¦ ¦ ¦
+------------+--+--+--+--+--+--------------------------------¦
¦ F5¦IM¦I ¦IM¦IM¦C ¦ ¦
¦ SHIFT-F5¦- ¦- ¦CP¦IM¦- ¦ Legend: ¦
¦ CTRL-F5¦CP¦C ¦CP¦IM¦- ¦ I = "If-Modified-Since" ¦
¦ ALT-F5¦- ¦- ¦- ¦- ¦*2¦ P = "Pragma: No-cache" ¦
¦ ALTGR-F5¦- ¦I ¦- ¦- ¦- ¦ C = "Cache-Control: no-cache" ¦
+------------+--+--+--+--+--¦ M = "Cache-Control: max-age=0" ¦
¦ CTRL-R¦IM¦I ¦IM¦IM¦C ¦ - = ignored ¦
¦CTRL-SHIFT-R¦CP¦- ¦CP¦- ¦- ¦ ¦
+------------+--+--+--+--+--¦ ¦
¦ Click¦IM¦I ¦IM¦IM¦C ¦ With 'click' I refer to a ¦
¦ Shift-Click¦CP¦I ¦CP¦IM¦C ¦ mouse click on the browsers ¦
¦ Ctrl-Click¦*1¦C ¦CP¦IM¦C ¦ refresh-icon. ¦
¦ Alt-Click¦IM¦I ¦IM¦IM¦C ¦ ¦
¦ AltGr-Click¦IM¦I ¦- ¦IM¦- ¦ ¦
+------------------------------------------------------------+
Versions tested:
Notes:
Version 3.0.6 sends I and C, but 3.1.6 opens the page in a new tab, making a normal request with only "I".
Version 10.62 does nothing. 9.61 might do C unless it was a typo in my old table.
Note about Chrome 6.0.472: If you do a forced reload (like CTRL-F5) it behaves like the url is internally marked to always do a forced reload. The flag is cleared if you go to the address bar and press enter.
The length of an array is available as
int l = array.length;
The size of a List
is availabe as
int s = list.size();
I'm setting up a dev server to play with that mirrors our outdated live one, I used The Perfect Server - Ubuntu 14.04 (nginx, BIND, MySQL, PHP, Postfix, Dovecot and ISPConfig 3)
After experiencing the same issue, I came across this post and nothing was working. I changed the value in every recommended file (nginx.conf, ispconfig.vhost, /sites-available/default, etc.)
Finally, changing client_max_body_size
in my /etc/nginx/sites-available/apps.vhost
and restarting nginx is what did the trick. Hopefully it helps someone else.
Here is how I did it with python 3.5.2:
from tkinter import *
root=Tk()
def retrieve_input():
inputValue=textBox.get("1.0","end-1c")
print(inputValue)
textBox=Text(root, height=2, width=10)
textBox.pack()
buttonCommit=Button(root, height=1, width=10, text="Commit",
command=lambda: retrieve_input())
#command=lambda: retrieve_input() >>> just means do this when i press the button
buttonCommit.pack()
mainloop()
with that, when i typed "blah blah" in the text widget and pressed the button, whatever i typed got printed out. So i think that is the answer for storing user input from Text widget to variable.
You have to cast one (or both) of the arguments to the division operator to double
:
double firstSolution = (b1 * a22 - b2 * a12) / (double)(a11 * a22 - a12 * a21);
Since you are performing the same calculation twice I'd recommend refactoring your code:
double determinant = a11 * a22 - a12 * a21;
double firstSolution = (b1 * a22 - b2 * a12) / determinant;
double secondSolution = (b2 * a11 - b1 * a21) / determinant;
This works in the same way, but now there is an implicit cast to double. This conversion from int
to double
is an example of a widening primitive conversion.
Disabling "Google App Engine Support" in pycharm preferences fixed this issue for me.
//As an HTTP redirect (back button will not work )
window.location.replace("http://www.google.com");
//like if you click on a link (it will be saved in the session history,
//so the back button will work as expected)
window.location.href = "http://www.google.com";
There is no inherent reason that a simple batch file would run in XP but not Windows 10. It is possible you are referencing a command or a 3rd party utility that no longer exists. To know more about what is actually happening, you will need to do one of the following:
pause
to the batch file so that you can see what is happening before it exits.
.bat
files and select "edit". This will open the file in notepad.pause
.- OR -
.bat
files are located, hold down the "shift" key and right click in the white space.Once you have done this, I recommend creating a new question with the output you see after using one of the methods above.
In this answer I am using an example posted by Justin Grammens.
JSON stands for JavaScript Object Notation. In JavaScript properties can be referenced both like this object1.name
and like this object['name'];
. The example from the article uses this bit of JSON.
The Parts
A fan object with email as a key and [email protected] as a value
{
fan:
{
email : '[email protected]'
}
}
So the object equivalent would be fan.email;
or fan['email'];
. Both would have the same value
of '[email protected]'
.
The following is what our author used to make a HttpClient Request. I do not claim to be an expert at all this so if anyone has a better way to word some of the terminology feel free.
public static HttpResponse makeRequest(String path, Map params) throws Exception
{
//instantiates httpclient to make request
DefaultHttpClient httpclient = new DefaultHttpClient();
//url with the post data
HttpPost httpost = new HttpPost(path);
//convert parameters into JSON object
JSONObject holder = getJsonObjectFromMap(params);
//passes the results to a string builder/entity
StringEntity se = new StringEntity(holder.toString());
//sets the post request as the resulting string
httpost.setEntity(se);
//sets a request header so the page receving the request
//will know what to do with it
httpost.setHeader("Accept", "application/json");
httpost.setHeader("Content-type", "application/json");
//Handles what is returned from the page
ResponseHandler responseHandler = new BasicResponseHandler();
return httpclient.execute(httpost, responseHandler);
}
If you are not familiar with the Map
data structure please take a look at the Java Map reference. In short, a map is similar to a dictionary or a hash.
private static JSONObject getJsonObjectFromMap(Map params) throws JSONException {
//all the passed parameters from the post request
//iterator used to loop through all the parameters
//passed in the post request
Iterator iter = params.entrySet().iterator();
//Stores JSON
JSONObject holder = new JSONObject();
//using the earlier example your first entry would get email
//and the inner while would get the value which would be '[email protected]'
//{ fan: { email : '[email protected]' } }
//While there is another entry
while (iter.hasNext())
{
//gets an entry in the params
Map.Entry pairs = (Map.Entry)iter.next();
//creates a key for Map
String key = (String)pairs.getKey();
//Create a new map
Map m = (Map)pairs.getValue();
//object for storing Json
JSONObject data = new JSONObject();
//gets the value
Iterator iter2 = m.entrySet().iterator();
while (iter2.hasNext())
{
Map.Entry pairs2 = (Map.Entry)iter2.next();
data.put((String)pairs2.getKey(), (String)pairs2.getValue());
}
//puts email and '[email protected]' together in map
holder.put(key, data);
}
return holder;
}
Please feel free to comment on any questions that arise about this post or if I have not made something clear or if I have not touched on something that your still confused about... etc whatever pops in your head really.
(I will take down if Justin Grammens does not approve. But if not then thanks Justin for being cool about it.)
I just happend to get a comment about how to use the code and realized that there was a mistake in the return type. The method signature was set to return a string but in this case it wasnt returning anything. I changed the signature to HttpResponse and will refer you to this link on Getting Response Body of HttpResponse the path variable is the url and I updated to fix a mistake in the code.
UTF-8 version of @Alejandro Iglesias answer, will work for non-latin characters:
function get_string_between($string, $start, $end){
$string = ' ' . $string;
$ini = mb_strpos($string, $start, 0, 'UTF-8');
if ($ini == 0) return '';
$ini += mb_strlen($start, 'UTF-8');
$len = mb_strpos($string, $end, $ini, 'UTF-8') - $ini;
return mb_substr($string, $ini, $len, 'UTF-8');
}
$fullstring = 'this is my [tag]dog[/tag]';
$parsed = get_string_between($fullstring, '[tag]', '[/tag]');
echo $parsed; // (result = dog)
You can use the getchar routine.
From the above link:
/* getchar example : typewriter */
#include <stdio.h>
int main ()
{
char c;
puts ("Enter text. Include a dot ('.') in a sentence to exit:");
do {
c=getchar();
putchar (c);
} while (c != '.');
return 0;
}
:nth-last-child(-n+2)
should do the trick
It's actually much easier with jQuery's promise API:
$.ajax(
type: "GET",
url: requestURL,
).then((success) =>
console.dir(success)
).failure((failureResponse) =>
console.dir(failureResponse)
)
Alternatively, you can pass in of bind
functions to each result callback; the order of parameters is: (success, failure)
. So long as you specify a function with at least 1 parameter, you get access to the response. So, for example, if you wanted to check the response text, you could simply do:
$.ajax(
type: "GET",
url: @get("url") + "logout",
beforeSend: (xhr) -> xhr.setRequestHeader("token", currentToken)
).failure((response) -> console.log "Request was unauthorized" if response.status is 401
You can do this:
DECLARE @maxval TINYINT, @minval TINYINT
select @maxval=24,@minval=5
SELECT CAST(((@maxval + 1) - @minval) *
RAND(CHECKSUM(NEWID())) + @minval AS TINYINT)
And that was taken directly from this link, I don't really know how to give proper credit for this answer.
This can be solved elegantly using Metaclasses:
import unittest
l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]]
class TestSequenceMeta(type):
def __new__(mcs, name, bases, dict):
def gen_test(a, b):
def test(self):
self.assertEqual(a, b)
return test
for tname, a, b in l:
test_name = "test_%s" % tname
dict[test_name] = gen_test(a,b)
return type.__new__(mcs, name, bases, dict)
class TestSequence(unittest.TestCase):
__metaclass__ = TestSequenceMeta
if __name__ == '__main__':
unittest.main()
None of the answers worked for me, but this is what finally worked after I set:
android:fitsSystemWindows="false"
In parent activity layout file it's not suggested at many places but it's work for me and saves my day
EDIT: Maybe your class for sending emails has an option for HTML emails and then you can use <br />
1) Double-quotes
$output = "Good news! The item# $item_number on which you placed a bid of \$ $bid_price is now available for purchase at your bid price.\nThe seller, $bid_user is making this offer.\n\nItem Title : $title\n\nAll the best,\n $bid_user\n$email\n";
If you use double-quotes then \n will work (there will be no newline in browser but see the source code in your browser - the \n characters will be replaced for newlines)
2) Single quotes doesn't have the effect as the double-quotes above:
$output = 'Good news! The item# $item_number on which you placed a bid of \$ $bid_price is now available for purchase at your bid price.\nThe seller, $bid_user is making this offer.\n\nItem Title : $title\n\nAll the best,\n $bid_user\n$email\n';
all characters will be printed as is (even variables!)
3) Line breaks in HTML
$html_output = "Good news! The item# $item_number on which you placed a bid of <br />$ $bid_price is now available for purchase at your bid price.<br />The seller, $bid_user is making this offer.<br /><br />Item Title : $title<br /><br />All the best,<br /> $bid_user<br />$email<br />";
You can use in Content-security-policy add "img-src 'self' data:;" And Use outline CSS.Don't use Inline CSS.It's secure from attackers.
A version in Kotlin, in this algorithm I created a decorator that allows you to set and get variables from the environment.
import java.util.Collections
import kotlin.reflect.KProperty
?
class EnvironmentDelegate {
operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
return System.getenv(property.name) ?: "-"
}
?
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
val key = property.name
?
val classes: Array<Class<*>> = Collections::class.java.declaredClasses
val env = System.getenv()
?
val cl = classes.first { "java.util.Collections\$UnmodifiableMap" == it.name }
?
val field = cl.getDeclaredField("m")
field.isAccessible = true
val obj = field[env]
val map = obj as MutableMap<String, String>
map.putAll(mapOf(key to value))
}
}
?
class KnownProperties {
var JAVA_HOME: String by EnvironmentDelegate()
var sample: String by EnvironmentDelegate()
}
?
fun main() {
val knowProps = KnownProperties()
knowProps.sample = "2"
?
println("Java Home: ${knowProps.JAVA_HOME}")
println("Sample: ${knowProps.sample}")
}
Looking at the web I find some simple way to style scrollbars.
This is THE guy! http://almaer.com/blog/creating-custom-scrollbars-with-css-how-css-isnt-great-for-every-task
And here my implementation! https://dl.dropbox.com/u/1471066/cloudBI/cssScrollbars.png
/* Turn on a 13x13 scrollbar */
::-webkit-scrollbar {
width: 10px;
height: 13px;
}
::-webkit-scrollbar-button:vertical {
background-color: silver;
border: 1px solid gray;
}
/* Turn on single button up on top, and down on bottom */
::-webkit-scrollbar-button:start:decrement,
::-webkit-scrollbar-button:end:increment {
display: block;
}
/* Turn off the down area up on top, and up area on bottom */
::-webkit-scrollbar-button:vertical:start:increment,
::-webkit-scrollbar-button:vertical:end:decrement {
display: none;
}
/* Place The scroll down button at the bottom */
::-webkit-scrollbar-button:vertical:increment {
display: none;
}
/* Place The scroll up button at the up */
::-webkit-scrollbar-button:vertical:decrement {
display: none;
}
/* Place The scroll down button at the bottom */
::-webkit-scrollbar-button:horizontal:increment {
display: none;
}
/* Place The scroll up button at the up */
::-webkit-scrollbar-button:horizontal:decrement {
display: none;
}
::-webkit-scrollbar-track:vertical {
background-color: blue;
border: 1px dashed pink;
}
/* Top area above thumb and below up button */
::-webkit-scrollbar-track-piece:vertical:start {
border: 0px;
}
/* Bottom area below thumb and down button */
::-webkit-scrollbar-track-piece:vertical:end {
border: 0px;
}
/* Track below and above */
::-webkit-scrollbar-track-piece {
background-color: silver;
}
/* The thumb itself */
::-webkit-scrollbar-thumb:vertical {
height: 50px;
background-color: gray;
}
/* The thumb itself */
::-webkit-scrollbar-thumb:horizontal {
height: 50px;
background-color: gray;
}
/* Corner */
::-webkit-scrollbar-corner:vertical {
background-color: black;
}
/* Resizer */
::-webkit-scrollbar-resizer:vertical {
background-color: gray;
}
like often when you have a boolean numpy array like mask
[mylist[i] for i in np.arange(len(mask), dtype=int)[mask]]
A lambda that works for any sequence or np.array:
subseq = lambda myseq, mask : [myseq[i] for i in np.arange(len(mask), dtype=int)[mask]]
newseq = subseq(myseq, mask)
When the normType
is NORM_MINMAX
, cv::normalize
normalizes _src
in such a way that the min value of dst
is alpha
and max value of dst
is beta
. cv::normalize
does its magic using only scales and shifts (i.e. adding constants and multiplying by constants).
CV_8UC1
says how many channels dst
has.
The documentation here is pretty clear: http://docs.opencv.org/modules/core/doc/operations_on_arrays.html#normalize
You can sum numbers in a list simply with the sum() built-in:
sum(your_list)
It will sum as many number items as you have. Example:
my_list = range(10, 17)
my_list
[10, 11, 12, 13, 14, 15, 16]
sum(my_list)
91
For your specific case:
For your data convert the numbers into int
first and then sum the numbers:
data = ['5', '4', '9']
sum(int(i) for i in data)
18
This will work for undefined number of elements in your list (as long as they are "numbers")
Thanks for @senderle's comment re conversion in case the data is in string format.
Your classes should look like this
[XmlRoot("StepList")]
public class StepList
{
[XmlElement("Step")]
public List<Step> Steps { get; set; }
}
public class Step
{
[XmlElement("Name")]
public string Name { get; set; }
[XmlElement("Desc")]
public string Desc { get; set; }
}
Here is my testcode.
string testData = @"<StepList>
<Step>
<Name>Name1</Name>
<Desc>Desc1</Desc>
</Step>
<Step>
<Name>Name2</Name>
<Desc>Desc2</Desc>
</Step>
</StepList>";
XmlSerializer serializer = new XmlSerializer(typeof(StepList));
using (TextReader reader = new StringReader(testData))
{
StepList result = (StepList) serializer.Deserialize(reader);
}
If you want to read a text file you should load the file into a FileStream and deserialize this.
using (FileStream fileStream = new FileStream("<PathToYourFile>", FileMode.Open))
{
StepList result = (StepList) serializer.Deserialize(fileStream);
}
Take note: I have seen other posts that say 

will give you a paragraph break, which oddly enough works in the Android xml String.xml
file, but will NOT show up in a device when testing (no breaks at all show up). Therefore, the \n
shows up on both.
Enabling SQL Server Service Broker requires a database lock. Stop the SQL Server Agent and then execute the following:
USE master ;
GO
ALTER DATABASE [MyDatabase] SET ENABLE_BROKER ;
GO
Change [MyDatabase] with the name of your database in question and then start SQL Server Agent.
If you want to see all the databases that have Service Broker enabled or disabled, then query sys.databases, for instance:
SELECT
name, database_id, is_broker_enabled
FROM sys.databases
I use the following to detect different mobile devices, viewport and screen. Works quite well for me, might be helpful to others:
var pixelRatio = window.devicePixelRatio || 1;
var viewport = {
width: window.innerWidth,
height: window.innerHeight
};
var screen = {
width: window.screen.availWidth * pixelRatio,
height: window.screen.availHeight * pixelRatio
};
var iPhone = /iPhone/i.test(navigator.userAgent);
var iPhone4 = (iPhone && pixelRatio == 2);
var iPhone5 = /iPhone OS 5_0/i.test(navigator.userAgent);
var iPad = /iPad/i.test(navigator.userAgent);
var android = /android/i.test(navigator.userAgent);
var webos = /hpwos/i.test(navigator.userAgent);
var iOS = iPhone || iPad;
var mobile = iOS || android || webos;
window.devicePixelRatio
is the ratio between physical pixels and device-independent pixels (dips) on the device.
window.devicePixelRatio
= physical pixels / dips.
More info here.
map[key] = value
is provided for easier syntax. It is easier to read and write.
The reason for which you need to have default constructor is that map[key]
is evaluated before assignment. If key wasn't present in map, new one is created (with default constructor) and reference to it is returned from operator[]
.
You don't need to pass the parameter, you can get it using .attr()
method
$(function(){
$('elements-to-match').click(function(){
alert("The id is "+ $(this).attr("id") );
});
});
git config --global diff.tool vimdiff
git config --global difftool.prompt false
Typing git difftool
yields the expected behavior.
:qa
in vim cycles to the next file in the changeset without saving anything.git config --global alias.d difftool
.. will let you type git d
to invoke vimdiff.
:wq
in vim cycles to the next file in the changeset with changes saved./**
* Method to get the index of the given item from the list
* @param stringArray
* @param name
* @return index of the item if item exists else return -1
*/
public static int getIndexOfItemInArray(String[] stringArray, String name) {
if (stringArray != null && stringArray.length > 0) {
ArrayList<String> list = new ArrayList<String>(Arrays.asList(stringArray));
int index = list.indexOf(name);
list.clear();
return index;
}
return -1;
}
I have tried both of online jsbeautifier(jsbeautifier, jsnice), these tools gave me beautiful js code,
but couldn't copy for very large js (must be bug, when i copy, copied buffer contains only one character '-').
I found that only working solution was prettyjs:
I created this category implementation and added it to the top of the .m
file.
@implementation UITextField (custom)
- (CGRect)textRectForBounds:(CGRect)bounds {
return CGRectMake(bounds.origin.x + 10, bounds.origin.y + 8,
bounds.size.width - 20, bounds.size.height - 16);
}
- (CGRect)editingRectForBounds:(CGRect)bounds {
return [self textRectForBounds:bounds];
}
@end
Based off the link Piotr Blasiak provided. It seemed simpler then creating a whole new subclass, and also simpler then adding the additional UIView
. Still, it seems like something is missing to not be able to control the padding inside a text field.
Swift 4 solution:
class CustomTextField: UITextField {
struct Constants {
static let sidePadding: CGFloat = 10
static let topPadding: CGFloat = 8
}
override func textRect(forBounds bounds: CGRect) -> CGRect {
return CGRect(
x: bounds.origin.x + Constants.sidePadding,
y: bounds.origin.y + Constants.topPadding,
width: bounds.size.width - Constants.sidePadding * 2,
height: bounds.size.height - Constants.topPadding * 2
)
}
override func editingRect(forBounds bounds: CGRect) -> CGRect {
return self.textRect(forBounds: bounds)
}
}
You can also use dictionaries that allows you to have more control over the plots:
import matplotlib.pyplot as plt
# plot 0 plot 1 plot 2 plot 3
x=[[1,2,3,4],[1,4,3,4],[1,2,3,4],[9,8,7,4]]
y=[[3,2,3,4],[3,6,3,4],[6,7,8,9],[3,2,2,4]]
plots = zip(x,y)
def loop_plot(plots):
figs={}
axs={}
for idx,plot in enumerate(plots):
figs[idx]=plt.figure()
axs[idx]=figs[idx].add_subplot(111)
axs[idx].plot(plot[0],plot[1])
return figs, axs
figs, axs = loop_plot(plots)
Now you can select the plot that you want to modify easily:
axs[0].set_title("Now I can control it!")
Of course, is up to you to decide what to do with the plots. You can either save them to disk figs[idx].savefig("plot_%s.png" %idx)
or show them plt.show()
. Use the argument block=False
only if you want to pop up all the plots together (this could be quite messy if you have a lot of plots). You can do this inside the loop_plot
function or in a separate loop using the dictionaries that the function provided.
Simply pass the desired value as first argument, like 0
, math.inf
or, here, np.nan
. The constructor then initializes and fills the value array to the size specified by arguments index
and columns
:
>>> import numpy as np
>>> import pandas as pd
>>> df = pd.DataFrame(np.nan, index=[0, 1, 2, 3], columns=['A', 'B'])
>>> df.dtypes
A float64
B float64
dtype: object
>>> df.values
array([[nan, nan],
[nan, nan],
[nan, nan],
[nan, nan]])
Decode the string to Unicode. Assuming it's UTF-8-encoded:
str.decode("utf-8")
Call the replace
method and be sure to pass it a Unicode string as its first argument:
str.decode("utf-8").replace(u"\u2022", "*")
Encode back to UTF-8, if needed:
str.decode("utf-8").replace(u"\u2022", "*").encode("utf-8")
(Fortunately, Python 3 puts a stop to this mess. Step 3 should really only be performed just prior to I/O. Also, mind you that calling a string str
shadows the built-in type str
.)
I like Jon Skeet's answer, but would like to add one thing. I'm not sure if Jon was expecting the ctor to always be passed in the Local timezone. But I want to use it for cases where it's something other then local.
I'm reading values from a database, and I know what timezone that database is in. So in the ctor, I'll pass in the timezone of the database. But then I would like the value in local time. Jon's LocalTime does not return the original date converted into a local timezone date. It returns the date converted into the original timezone (whatever you had passed into the ctor).
I think these property names clear it up...
public DateTime TimeInOriginalZone { get { return TimeZoneInfo.ConvertTime(utcDateTime, timeZone); } }
public DateTime TimeInLocalZone { get { return TimeZoneInfo.ConvertTime(utcDateTime, TimeZoneInfo.Local); } }
public DateTime TimeInSpecificZone(TimeZoneInfo tz)
{
return TimeZoneInfo.ConvertTime(utcDateTime, tz);
}
I recently wanted to do this and found that I was not happy with any of the answers here.
If you follow Marc's advice and set the output-type to Console Application there are two problems:
1) If you launch the application from Explorer, you get an annoying console window behind your Form which doesn't go away until your program exits. We can mitigate this problem by calling FreeConsole prior to showing the GUI (Application.Run). The annoyance here is that the console window still appears. It immediately goes away, but is there for a moment none-the-less.
2) If you launch it from a console, and display a GUI, the console is blocked until the GUI exits. This is because the console (cmd.exe) thinks it should launch Console apps synchronously and Windows apps asynchronously (the unix equivalent of "myprocess &").
If you leave the output-type as Windows Application, but correctly call AttachConsole, you don't get a second console window when invoked from a console and you don't get the unnecessary console when invoked from Explorer. The correct way to call AttachConsole is to pass -1 to it. This causes our process to attach to the console of our parent process (the console window that launched us).
However, this has two different problems:
1) Because the console launches Windows apps in the background, it immediately displays the prompt and allows further input. On the one hand this is good news, the console is not blocked on your GUI app, but in the case where you want to dump output to the console and never show the GUI, your program's output comes after the prompt and no new prompt is displayed when you're done. This looks a bit confusing, not to mention that your "console app" is running in the background and the user is free to execute other commands while it's running.
2) Stream redirection gets messed up as well, e.g. "myapp some parameters > somefile" fails to redirect. The stream redirection problem requires a significant amount of p/Invoke to fixup the standard handles, but it is solvable.
After many hours of hunting and experimenting, I've come to the conclusion that there is no way to do this perfectly. You simply cannot get all the benefits of both console and window without any side effects. It's a matter of picking which side effects are least annoying for your application's purposes.
No, there are no dictionaries in php. The closest thing you have is an array. However, an array is different than a dictionary in that arrays have both an index and a key. Dictionaries only have keys and no index. What do I mean by that?
$array = array(
"foo" => "bar",
"bar" => "foo"
);
// as of PHP 5.4
$array = [
"foo" => "bar",
"bar" => "foo",
];
The following line is allowed with the above array but would give an error if it was a dictionary.
print $array[0]
Python has both arrays and dictionaries.
You need to use v-bind:
or its alias :
. For example,
<a v-bind:href="'/job/'+ r.id">
or
<a :href="'/job/' + r.id">
In Typescript use the For Each like below.
selectChildren(data, $event) {
let parentChecked = data.checked;
for(var obj in this.hierarchicalData)
{
for (var childObj in obj )
{
value.checked = parentChecked;
}
}
}
GRANT
s on different objects are separate. GRANT
ing on a database doesn't GRANT
rights to the schema within. Similiarly, GRANT
ing on a schema doesn't grant rights on the tables within.
If you have rights to SELECT
from a table, but not the right to see it in the schema that contains it then you can't access the table.
The rights tests are done in order:
Do you have `USAGE` on the schema?
No: Reject access.
Yes: Do you also have the appropriate rights on the table?
No: Reject access.
Yes: Check column privileges.
Your confusion may arise from the fact that the public
schema has a default GRANT
of all rights to the role public
, which every user/group is a member of. So everyone already has usage on that schema.
The phrase:
(assuming that the objects' own privilege requirements are also met)
Is saying that you must have USAGE
on a schema to use objects within it, but having USAGE
on a schema is not by itself sufficient to use the objects within the schema, you must also have rights on the objects themselves.
It's like a directory tree. If you create a directory somedir
with file somefile
within it then set it so that only your own user can access the directory or the file (mode rwx------
on the dir, mode rw-------
on the file) then nobody else can list the directory to see that the file exists.
If you were to grant world-read rights on the file (mode rw-r--r--
) but not change the directory permissions it'd make no difference. Nobody could see the file in order to read it, because they don't have the rights to list the directory.
If you instead set rwx-r-xr-x
on the directory, setting it so people can list and traverse the directory but not changing the file permissions, people could list the file but could not read it because they'd have no access to the file.
You need to set both permissions for people to actually be able to view the file.
Same thing in Pg. You need both schema USAGE
rights and object rights to perform an action on an object, like SELECT
from a table.
(The analogy falls down a bit in that PostgreSQL doesn't have row-level security yet, so the user can still "see" that the table exists in the schema by SELECT
ing from pg_class
directly. They can't interact with it in any way, though, so it's just the "list" part that isn't quite the same.)
To follow up on Ron's answer if using JQuery and putting it in application.js or the head section you need to wrap it in a ready() section...
$(document).ready(function() {
$('#my-link').click(function(event){
alert('Hooray!');
event.preventDefault(); // Prevent link from following its href
});
});
Also you can do like this:
<select class="form-control postType" ng-model="selectedProd">
<option ng-repeat="product in productList" value="{{product}}">{{product.name}}</option>
</select>
where "selectedProd" will be selected product.
You should definitely avoid using <jsp:...>
tags. They're relics from the past and should always be avoided now.
Use the JSTL.
Now, wether you use the JSTL or any other tag library, accessing to a bean property needs your bean to have this property. A property is not a private instance variable. It's an information accessible via a public getter (and setter, if the property is writable). To access the questionPaperID property, you thus need to have a
public SomeType getQuestionPaperID() {
//...
}
method in your bean.
Once you have that, you can display the value of this property using this code :
<c:out value="${Questions.questionPaperID}" />
or, to specifically target the session scoped attributes (in case of conflicts between scopes) :
<c:out value="${sessionScope.Questions.questionPaperID}" />
Finally, I encourage you to name scope attributes as Java variables : starting with a lowercase letter.
Since the Logical Address space is 32-bit long that means program size is 2^32 bytes i.e. 4GB. Now we have the page size of 4KB i.e.2^12 bytes.Thus the number of pages in program are 2^20.(no. of pages in program = program size/page size).Now the size of page table entry is 4 byte hence the size of page table is 2^20*4 = 4MB(size of page table = no. of pages in program * page table entry size). Hence 4MB space is required in Memory to store the page table.
Delegates do the same thing as interface-based callbacks in C++ (COM uses these), although are much simpler to use.
Note that Microsoft put delegates into its Java implementation (J++) but Sun doesn't like them [java.sun.com] so don't expect to see them in the official version of Java any time soon. I've hacked together a preprocessor to let you use them in C++, so don't feel left out if you're not programming in C# or on the .NET platform (i.e. in Managed C++ or Visual Basic.NET).
If you're used to function pointers in C, a delegate is basically a pair of pointers rolled into one:
That means a single delegate passes all the information needed to locate a function in your program, whether it's a static method or associated with an object.
You define them like this in C#:
public delegate void FooCallbackType( int a, int b, int c );
When you want to use them, you make delegate out of the function you want to call:
class CMyClass
{
public void FunctionToCall( int a, int b, int c )
{
// This is the callback
}
public void Foo()
{
FooCallbackType myDelegate = new FooCallbackType(
this.FunctionToCall );
// Now you can pass that to the function
// that needs to call you back.
}
}
If you want to make a delegate to point to a static method, it just looks the same:
class CMyClassWithStaticCallback
{
public static void StaticFunctionToCall( int a, int b, int c )
{
// This is the callback
}
public static void Foo()
{
FooCallbackType myDelegate = new FooCallbackType(
CMyClass.StaticFunctionToCall );
}
}
All in all, they do the same thing as interface-based callbacks in C++, but cause a bit less trouble because you don't need to worry about naming your functions or making helper objects, and you can make delegates out of any method. They're more flexible.
attr("dominant-baseline", "central")
you can write multiple lines in case of different minutes, for example you want to run at 10:01 AM and 2:30 PM
1 10 * * * php -f /var/www/package/index.php controller function
30 14 * * * php -f /var/www/package/index.php controller function
but the following is the best solution for running cron multiple times in a day as minutes are same, you can mention hours like 10,30
.
30 10,14 * * * php -f /var/www/package/index.php controller function
For the background color - the fill
property can be accessed like so:
svgElement.style.fill = '#fff';
To set the border color, do the same for the stroke
property.
Please refer to the W3C reference on SVG, as it's a broad issue.
A tridend based approach would be better. Here is a quick function for checking IE 8.
<?php
function is_IE8(){
if(strpos(str_replace(' ', '', $_SERVER['HTTP_USER_AGENT']),'Trident/4.0')!== FALSE){
return TRUE;
};
return FALSE;
}
?>
string saveStaff = "INSERT into student (stud_id,stud_name) " + " VALUES ('" + SI+ "', '" + SN + "');";
cmd = new SqlCommand(saveStaff,con);
cmd.ExecuteNonQuery();
$.get("/folder_name/filename.xml", function (xml) {_x000D_
var xmlInnerhtml = xml.documentElement.innerHTML;_x000D_
});
_x000D_
When you want monitor specified process, usually it is done by scripting. Here is perl example. This put percents as the same way as top, scalling it to one CPU. Then when some process is active working with 2 threads, cpu usage can be more than 100%. Specially look how cpu cores are counted :D then let me show my example:
#!/usr/bin/perl
my $pid=1234; #insert here monitored process PID
#returns current process time counters or single undef if unavailable
#returns: 1. process counter , 2. system counter , 3. total system cpu cores
sub GetCurrentLoads {
my $pid=shift;
my $fh;
my $line;
open $fh,'<',"/proc/$pid/stat" or return undef;
$line=<$fh>;
close $fh;
return undef unless $line=~/^\d+ \([^)]+\) \S \d+ \d+ \d+ \d+ -?\d+ \d+ \d+ \d+ \d+ \d+ (\d+) (\d+)/;
my $TimeApp=$1+$2;
my $TimeSystem=0;
my $CpuCount=0;
open $fh,'<',"/proc/stat" or return undef;
while (defined($line=<$fh>)) {
if ($line=~/^cpu\s/) {
foreach my $nr ($line=~/\d+/g) { $TimeSystem+=$nr; };
next;
};
$CpuCount++ if $line=~/^cpu\d/;
}
close $fh;
return undef if $TimeSystem==0;
return $TimeApp,$TimeSystem,$CpuCount;
}
my ($currApp,$currSys,$lastApp,$lastSys,$cores);
while () {
($currApp,$currSys,$cores)=GetCurrentLoads($pid);
printf "Load is: %5.1f\%\n",($currApp-$lastApp)/($currSys-$lastSys)*$cores*100 if defined $currApp and defined $lastApp and defined $currSys and defined $lastSys;
($lastApp,$lastSys)=($currApp,$currSys);
sleep 1;
}
I hope it will help you in any monitoring. Of course you should use scanf or other C functions for converting any perl regexpes I've used to C source. Of course 1 second for sleeping is not mandatory. you can use any time. effect is, you will get averrage load on specfied time period. When you will use it for monitoring, of course last values you should put outside. It is needed, because monitoring usually calls scripts periodically, and script should finish his work asap.
Just use:
for (int i = 0; i < v.size(); i++)
{
v[i] -= valueToSubstract;
}
Or its equivalent (and more readable?):
for (int i = 0; i < v.size(); i++)
v[i] = v[i] - valueToSubstract;
You technically have two options when speaking of ISO dates.
In general, if you're filtering specifically on Date values alone OR looking to persist date in a neutral fashion. Microsoft recommends using the language neutral format of ymd
or y-m-d
. Which are both valid ISO formats.
Note that the form '2007-02-12' is considered language-neutral only for the data types DATE, DATETIME2, and DATETIMEOFFSET.
Because of this, your safest bet is to persist/filter based on the always netural ymd
format.
The code:
select convert(char(10), getdate(), 126) -- ISO YYYY-MM-DD
select convert(char(8), getdate(), 112) -- ISO YYYYMMDD (safest)
VM Player runs a virtual instance, but can't create the vm. [Edit: Now it can.] Workstation allows for the creation and administration of virtual machines. If you have a second machine, you can create the vm on one and run it with the player the other machine. I bought Workstation and I use it setup testing vms that the player runs. Hope this explains it for you.
Edit: According to the FAQ:
VMware Workstation is much more advanced and comes with powerful features including snapshots, cloning, remote connections to vSphere, sharing VMs, advanced Virtual Machines settings and much more. Workstation is designed to be used by technical professionals such as developers, quality assurance engineers, systems engineers, IT administrators, technical support representatives, trainers, etc.
AS per my understanding most probable will cover by..
/^([a-z0-9_-]+)(@[a-z0-9-]+)(\.[a-z]+|\.[a-z]+\.[a-z]+)?$/is
Inspired by user Brent Self:
lsof -i 4 -a | grep LISTEN
You can use input text with "list" attribute, which refers to the datalist of values.
<input type="text" name="city" list="cityname">_x000D_
<datalist id="cityname">_x000D_
<option value="Boston">_x000D_
<option value="Cambridge">_x000D_
</datalist>
_x000D_
This creates a free text input field that also has a drop-down to select predefined choices. Attribution for example and more information: https://www.w3.org/wiki/HTML/Elements/datalist
I found the product key for Visual Studio 2008 Professional under a slightly different key:
HKLM\SOFTWARE\Wow6432Node\Microsoft\MSDN\8.0\Registration\PIDKEY
it was listed without the dashes as stated above.
An old thread, nonetheless someone may benefit from this:
li:not(:last-child)::after { content: ","; }
li:last-child::after { content: "."; }
This should work in CSS3 and [untested] CSS2.
==
is a bash-specific alias for =
and it performs a string (lexical) comparison instead of a numeric comparison. eq
being a numeric comparison of course.
Finally, I usually prefer to use the form if [ "$a" == "$b" ]
I use the following code to change the endpoint address in the App.Config file. You may want to modify or remove the namespace before usage.
using System;
using System.Xml;
using System.Configuration;
using System.Reflection;
//...
namespace Glenlough.Generations.SupervisorII
{
public class ConfigSettings
{
private static string NodePath = "//system.serviceModel//client//endpoint";
private ConfigSettings() { }
public static string GetEndpointAddress()
{
return ConfigSettings.loadConfigDocument().SelectSingleNode(NodePath).Attributes["address"].Value;
}
public static void SaveEndpointAddress(string endpointAddress)
{
// load config document for current assembly
XmlDocument doc = loadConfigDocument();
// retrieve appSettings node
XmlNode node = doc.SelectSingleNode(NodePath);
if (node == null)
throw new InvalidOperationException("Error. Could not find endpoint node in config file.");
try
{
// select the 'add' element that contains the key
//XmlElement elem = (XmlElement)node.SelectSingleNode(string.Format("//add[@key='{0}']", key));
node.Attributes["address"].Value = endpointAddress;
doc.Save(getConfigFilePath());
}
catch( Exception e )
{
throw e;
}
}
public static XmlDocument loadConfigDocument()
{
XmlDocument doc = null;
try
{
doc = new XmlDocument();
doc.Load(getConfigFilePath());
return doc;
}
catch (System.IO.FileNotFoundException e)
{
throw new Exception("No configuration file found.", e);
}
}
private static string getConfigFilePath()
{
return Assembly.GetExecutingAssembly().Location + ".config";
}
}
}
Just to add to the existing great answers here - building on the code in the accepted one, which uses a delegate void MyEventHandler(string foo)
...
Because the compiler knows the delegate type of the SomethingHappened event, this:
myObj.SomethingHappened += HandleSomethingHappened;
Is totally equivalent to:
myObj.SomethingHappened += new MyEventHandler(HandleSomethingHappened);
And handlers can also be unregistered with -=
like this:
// -= removes the handler from the event's list of "listeners":
myObj.SomethingHappened -= HandleSomethingHappened;
For completeness' sake, raising the event can be done like this, only in the class that owns the event:
//Firing the event is done by simply providing the arguments to the event:
var handler = SomethingHappened; // thread-local copy of the event
if (handler != null) // the event is null if there are no listeners!
{
handler("Hi there!");
}
The thread-local copy of the handler is needed to make sure the invocation is thread-safe - otherwise a thread could go and unregister the last handler for the event immediately after we checked if it was null
, and we would have a "fun" NullReferenceException
there.
C# 6 introduced a nice short hand for this pattern. It uses the null propagation operator.
SomethingHappened?.Invoke("Hi there!");
SQL Server Management Studio provides an Import/Export wizard tool which have an option to automatically create tables.
You can access it by right clicking on the Database in Object Explorer and selecting Tasks->Import Data...
From there wizard should be self-explanatory and easy to navigate. You choose your CSV as source, desired destination, configure columns and run the package.
If you need detailed guidance, there are plenty of guides online, here is a nice one: http://www.mssqltips.com/sqlservertutorial/203/simple-way-to-import-data-into-sql-server/
Ahh. Because I missed the point of you initial post, here is an example which also ITERATES. The first example did not. In this case, I retreive an ADODB recordset, then load the data into a collection, which is returned by the function to client code:
EDIT: Not sure what I screwed up in pasting the code, but the formatting is a little screwball. Sorry!
Public Function StatesCollection() As Collection
Dim cn As ADODB.Connection
Dim cmd As ADODB.Command
Dim rs As ADODB.Recordset
Dim colReturn As New Collection
Set colReturn = New Collection
Dim SQL As String
SQL = _
"SELECT tblState.State, tblState.StateName " & _
"FROM tblState"
Set cn = New ADODB.Connection
Set cmd = New ADODB.Command
With cn
.Provider = DataConnection.MyADOProvider
.ConnectionString = DataConnection.MyADOConnectionString
.Open
End With
With cmd
.CommandText = SQL
.ActiveConnection = cn
End With
Set rs = cmd.Execute
With rs
If Not .EOF Then
Do Until .EOF
colReturn.Add Nz(!State, "")
.MoveNext
Loop
End If
.Close
End With
cn.Close
Set rs = Nothing
Set cn = Nothing
Set StatesCollection = colReturn
End Function
if($("#checkbox1").prop('checked') == false){
alert('checkbox is not checked');
//do something
}
else
{
alert('checkbox is checked');
}
There are some great answers here but I wanted to point out the jvm is free to store a char value in any size space >= 2 bytes.
On many architectures there is a penalty for performing unaligned memory access so a char might easily be padded to 4 bytes. A volatile char might even be padded to the size of the CPU cache line to prevent false sharing. https://en.wikipedia.org/wiki/False_sharing
It might be non-intuitive to new Java programmers that a character array or a string is NOT simply multiple characters. You should learn and think about strings and arrays distinctly from "multiple characters".
I also want to point out that java characters are often misused. People don't realize they are writing code that won't properly handle codepoints over 16 bits in length.
socket.isConnected()
returns always true once the client connects (and even after the disconnect) weird !!socket.getInputStream().read()
returns -1
if the client disconnectedsocket.getInetAddress().isReachable(int timeout)
: From isReachable(int timeout)
Test whether that address is reachable. Best effort is made by the implementation to try to reach the host, but firewalls and server configuration may block requests resulting in a unreachable status while some specific ports may be accessible. A typical implementation will use ICMP ECHO REQUESTs if the privilege can be obtained, otherwise it will try to establish a TCP connection on port 7 (Echo) of the destination host.
Unfortunately for MSForms list box looping through the list items and checking their Selected property is the only way. However, here is an alternative. I am storing/removing the selected item in a variable, you can do this in some remote cell and keep track of it :)
Dim StrSelection As String
Private Sub ListBox1_Change()
If ListBox1.Selected(ListBox1.ListIndex) Then
If StrSelection = "" Then
StrSelection = ListBox1.List(ListBox1.ListIndex)
Else
StrSelection = StrSelection & "," & ListBox1.List(ListBox1.ListIndex)
End If
Else
StrSelection = Replace(StrSelection, "," & ListBox1.List(ListBox1.ListIndex), "")
End If
End Sub
For Mac Terminal
cd .. # one up
cd ../ # two up
cd # home directory
cd / # root directory
cd "yaya-13" # use quotes if the file name contains punctuation or spaces
The way of changing the name for iOS and Android is clearly mentioned in the documentation as follows:
But, the case of iOS after you change the Display Name from Xcode, you are not able to run the application in the Flutter way, like flutter run
.
Because the Flutter run expects the app name as Runner. Even if you change the name in Xcode, it doesn't work.
So, I fixed this as follows:
Move to the location on your Flutter project, ios/Runner.xcodeproj/project.pbxproj, and find and replace all instances of your new name with Runner.
Then everything should work in the flutter run
way.
But don't forget to change the name display name on your next release time. Otherwise, the App Store rejects your name.
In javascript use the preventDefault() method of the event args parameter.
<a href="no-script.html">Download now!</a>
$('a').click(function(e) {
e.preventDefault(); // stop the browser from following
window.location.href = 'downloads/file.pdf';
});
String s = "java is an object oriented programming language.";
final StringBuilder result = new StringBuilder(s.length());
String words[] = s.split("\\ "); // space found then split it
for (int i = 0; i < words.length; i++)
{
if (i > 0){
result.append(" ");
}
result.append(Character.toUpperCase(words[i].charAt(0))).append(
words[i].substring(1));
}
System.out.println(result);
Output: Java Is An Object Oriented Programming Language.
I can show you an example of uploading a .txt file to a server with NSMutableURLRequest
and NSURLSessionUploadTask
with help of a php script.
-(void)uploadFileToServer : (NSString *) filePath
{
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://YourURL.com/YourphpScript.php"]];
[request setHTTPMethod:@"POST"];
[request addValue:@"File Name" forHTTPHeaderField:@"FileName"];
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultConfigObject];
NSURLSessionUploadTask* uploadTask = [defaultSession uploadTaskWithRequest:request fromFile:[NSURL URLWithString:filePath] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
if (error || [httpResponse statusCode]!=202)
{
//Error
}
else
{
//Success
}
[defaultSession invalidateAndCancel];
}];
[uploadTask resume];
}
php Script
<?php
$request_body = @file_get_contents('php://input');
foreach (getallheaders() as $name => $value)
{
if ($FileName=="FileName")
{
$header=$value;
break;
}
}
$uploadedDir = "directory/";
@mkdir($uploadedDir);
file_put_contents($uploadedDir."/".$FileName.".txt",
$request_body.PHP_EOL, FILE_APPEND);
header('X-PHP-Response-Code: 202', true, 202);
?>
CMake honors the environment variables CC
and CXX
upon detecting the C and C++ compiler to use:
$ export CC=/usr/bin/clang
$ export CXX=/usr/bin/clang++
$ cmake ..
-- The C compiler identification is Clang
-- The CXX compiler identification is Clang
The compiler specific flags can be overridden by putting them into a make override file and pointing the CMAKE_USER_MAKE_RULES_OVERRIDE
variable to it. Create a file ~/ClangOverrides.txt
with the following contents:
SET (CMAKE_C_FLAGS_INIT "-Wall -std=c99")
SET (CMAKE_C_FLAGS_DEBUG_INIT "-g")
SET (CMAKE_C_FLAGS_MINSIZEREL_INIT "-Os -DNDEBUG")
SET (CMAKE_C_FLAGS_RELEASE_INIT "-O3 -DNDEBUG")
SET (CMAKE_C_FLAGS_RELWITHDEBINFO_INIT "-O2 -g")
SET (CMAKE_CXX_FLAGS_INIT "-Wall")
SET (CMAKE_CXX_FLAGS_DEBUG_INIT "-g")
SET (CMAKE_CXX_FLAGS_MINSIZEREL_INIT "-Os -DNDEBUG")
SET (CMAKE_CXX_FLAGS_RELEASE_INIT "-O3 -DNDEBUG")
SET (CMAKE_CXX_FLAGS_RELWITHDEBINFO_INIT "-O2 -g")
The suffix _INIT
will make CMake initialize the corresponding *_FLAGS
variable with the given value. Then invoke cmake
in the following way:
$ cmake -DCMAKE_USER_MAKE_RULES_OVERRIDE=~/ClangOverrides.txt ..
Finally to force the use of the LLVM binutils, set the internal variable _CMAKE_TOOLCHAIN_PREFIX
. This variable is honored by the CMakeFindBinUtils
module:
$ cmake -D_CMAKE_TOOLCHAIN_PREFIX=llvm- ..
Putting this all together you can write a shell wrapper which sets up the environment variables CC
and CXX
and then invokes cmake
with the mentioned variable overrides.
Also see this CMake FAQ on make override files.
Pointers are important in many data structures whose design requires the ability to link or chain one "node" to another efficiently. You would not "choose" a pointer over say a normal data type like float, they simply have different purposes.
Pointers are useful where you require high performance and/or compact memory footprint.
The address of the first element in your array can be assigned to a pointer. This then allows you to access the underlying allocated bytes directly. The whole point of an array is to avoid you needing to do this though.
Here is my answer:
var options = ["1", "2", "3", "4", "5"];
for(m = 0 ; m <= options.length-1; m++){
var opt= document.createElement("OPTION");
opt.text = options[m];
opt.value = (m+1);
if(options[m] == "5"){
opt.selected = true;}
document.getElementById("selectNum").options.add(opt);}
Try this link format: https://t.me/[YourUserName]
I was looking for such a thing, BUT with text in (like the one that WhatsApp got)
The max length of a string on my machine is 1,073,741,791.
You see, Strings aren't limited by integer as is commonly believed.
Memory restrictions aside, Strings cannot have more than 230 (1,073,741,824) characters, since a 2GB limit is imposed by the Microsoft CLR (Common Language Runtime). 33 more than my computer allowed.
Now, here's something you're welcome to try yourself.
Create a new C# console app in Visual Studio and then copy/paste the main method here:
static void Main(string[] args)
{
Console.WriteLine("String test, by Nicholas John Joseph Taylor");
Console.WriteLine("\nTheoretically, C# should support a string of int.MaxValue, but we run out of memory before then.");
Console.WriteLine("\nThis is a quickish test to narrow down results to find the max supported length of a string.");
Console.WriteLine("\nThe test starts ...now:\n");
int Length = 0;
string s = "";
int Increment = 1000000000; // We know that s string with the length of 1000000000 causes an out of memory exception.
LoopPoint:
// Make a string appendage the length of the value of Increment
StringBuilder StringAppendage = new StringBuilder();
for (int CharacterPosition = 0; CharacterPosition < Increment; CharacterPosition++)
{
StringAppendage.Append("0");
}
// Repeatedly append string appendage until an out of memory exception is thrown.
try
{
if (Increment > 0)
while (Length < int.MaxValue)
{
Length += Increment;
s += StringAppendage.ToString(); // Append string appendage the length of the value of Increment
Console.WriteLine("s.Length = " + s.Length + " at " + DateTime.Now.ToString("dd/MM/yyyy HH:mm"));
}
}
catch (OutOfMemoryException ex) // Note: Any other exception will crash the program.
{
Console.WriteLine("\n" + ex.Message + " at " + DateTime.Now.ToString("dd/MM/yyyy HH:mm") + ".");
Length -= Increment;
Increment /= 10;
Console.WriteLine("After decimation, the value of Increment is " + Increment + ".");
}
catch (Exception ex2)
{
Console.WriteLine("\n" + ex2.Message + " at " + DateTime.Now.ToString("dd/MM/yyyy HH:mm") + ".");
Console.WriteLine("Press a key to continue...");
Console.ReadKey();
}
if (Increment > 0)
{
goto LoopPoint;
}
Console.WriteLine("Test complete.");
Console.WriteLine("\nThe max length of a string is " + s.Length + ".");
Console.WriteLine("\nPress any key to continue.");
Console.ReadKey();
}
My results were as follows:
String test, by Nicholas John Joseph Taylor
Theoretically, C# should support a string of int.MaxValue, but we run out of memory before then.
This is a quickish test to narrow down results to find the max supported length of a string.
The test starts ...now:
s.Length = 1000000000 at 08/05/2019 12:06
Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:06. After decimation, the value of Increment is 100000000.
Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:06. After decimation, the value of Increment is 10000000. s.Length = 1010000000 at 08/05/2019 12:06 s.Length = 1020000000 at 08/05/2019 12:06 s.Length = 1030000000 at 08/05/2019 12:06 s.Length = 1040000000 at 08/05/2019 12:06 s.Length = 1050000000 at 08/05/2019 12:06 s.Length = 1060000000 at 08/05/2019 12:06 s.Length = 1070000000 at 08/05/2019 12:06
Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:06. After decimation, the value of Increment is 1000000. s.Length = 1071000000 at 08/05/2019 12:06 s.Length = 1072000000 at 08/05/2019 12:06 s.Length = 1073000000 at 08/05/2019 12:06
Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:06. After decimation, the value of Increment is 100000. s.Length = 1073100000 at 08/05/2019 12:06 s.Length = 1073200000 at 08/05/2019 12:06 s.Length = 1073300000 at 08/05/2019 12:06 s.Length = 1073400000 at 08/05/2019 12:06 s.Length = 1073500000 at 08/05/2019 12:06 s.Length = 1073600000 at 08/05/2019 12:06 s.Length = 1073700000 at 08/05/2019 12:06
Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:06. After decimation, the value of Increment is 10000. s.Length = 1073710000 at 08/05/2019 12:06 s.Length = 1073720000 at 08/05/2019 12:06 s.Length = 1073730000 at 08/05/2019 12:06 s.Length = 1073740000 at 08/05/2019 12:06
Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:06. After decimation, the value of Increment is 1000. s.Length = 1073741000 at 08/05/2019 12:06
Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:06. After decimation, the value of Increment is 100. s.Length = 1073741100 at 08/05/2019 12:06 s.Length = 1073741200 at 08/05/2019 12:06 s.Length = 1073741300 at 08/05/2019 12:07 s.Length = 1073741400 at 08/05/2019 12:07 s.Length = 1073741500 at 08/05/2019 12:07 s.Length = 1073741600 at 08/05/2019 12:07 s.Length = 1073741700 at 08/05/2019 12:07
Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:07. After decimation, the value of Increment is 10. s.Length = 1073741710 at 08/05/2019 12:07 s.Length = 1073741720 at 08/05/2019 12:07 s.Length = 1073741730 at 08/05/2019 12:07 s.Length = 1073741740 at 08/05/2019 12:07 s.Length = 1073741750 at 08/05/2019 12:07 s.Length = 1073741760 at 08/05/2019 12:07 s.Length = 1073741770 at 08/05/2019 12:07 s.Length = 1073741780 at 08/05/2019 12:07 s.Length = 1073741790 at 08/05/2019 12:07
Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:07. After decimation, the value of Increment is 1. s.Length = 1073741791 at 08/05/2019 12:07
Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:07. After decimation, the value of Increment is 0. Test complete.
The max length of a string is 1073741791.
Press any key to continue.
The max length of a string on my machine is 1073741791.
I'd appreciate it very much if people could post their results as a comment below.
It will be interesting to learn if people get the same or different results.
Try something like this
select Cast((SPGI09_EARLY_OVER_T – (SPGI09_OVER_WK_EARLY_ADJUST_T) / (SPGI09_EARLY_OVER_T + SPGR99_LATE_CM_T + SPGR99_ON_TIME_Q)) as varchar(20) + '%' as percentageAmount
from CSPGI09_OVERSHIPMENT
I presume the value is a representation in percentage - if not convert it to a valid percentage total, then add the % sign and convert the column to varchar.
I also faced this problem . You can try any of these steps :
ps -A
)This issue is caused by the URL bars shrinking/sliding out of the way and changing the size of the #bg1 and #bg2 divs since they are 100% height and "fixed". Since the background image is set to "cover" it will adjust the image size/position as the containing area is larger.
Based on the responsive nature of the site, the background must scale. I entertain two possible solutions:
1) Set the #bg1, #bg2 height to 100vh. In theory, this an elegant solution. However, iOS has a vh bug (http://thatemil.com/blog/2013/06/13/viewport-relative-unit-strangeness-in-ios-6/). I attempted using a max-height to prevent the issue, but it remained.
2) The viewport size, when determined by Javascript, is not affected by the URL bar. Therefore, Javascript can be used to set a static height on the #bg1 and #bg2 based on the viewport size. This is not the best solution as it isn't pure CSS and there is a slight image jump on page load. However, it is the only viable solution I see considering iOS's "vh" bugs (which do not appear to be fixed in iOS 7).
var bg = $("#bg1, #bg2");
function resizeBackground() {
bg.height($(window).height());
}
$(window).resize(resizeBackground);
resizeBackground();
On a side note, I've seen so many issues with these resizing URL bars in iOS and Android. I understand the purpose, but they really need to think through the strange functionality and havoc they bring to websites. The latest change, is you can no longer "hide" the URL bar on page load on iOS or Chrome using scroll tricks.
EDIT: While the above script works perfectly for keeping the background from resizing, it causes a noticeable gap when users scroll down. This is because it is keeping the background sized to 100% of the screen height minus the URL bar. If we add 60px to the height, as swiss suggests, this problem goes away. It does mean we don't get to see the bottom 60px of the background image when the URL bar is present, but it prevents users from ever seeing a gap.
function resizeBackground() {
bg.height( $(window).height() + 60);
}
boolean turnedOn;
if(turnedOn)
{
//do stuff when the condition is true - i.e, turnedOn is true
}
else
{
//do stuff when the condition is false - i.e, turnedOn is false
}
even there is no right or wrong answer for this question , but I personally prefer 960px width . since all modern monitors support at least 1024 × 768 pixel resolution. 960 is divisible by 2, 3, 4, 5, 6, 8, 10, 12, 15, 16, 20, 24, 30, 32, 40, 48, 60, 64, 80, 96, 120, 160, 192, 240, 320 and 480. This makes it a highly flexible base number to work with.
see this article that shows most popular screens resolutions 2013-2014 in US and UK : http://www.hobo-web.co.uk/best-screen-size/
I'll focus on two things:
OP clearly states
I have the edited column names stored it in a list, but I don't know how to replace the column names.
I do not want to solve the problem of how to replace '$'
or strip the first character off of each column header. OP has already done this step. Instead I want to focus on replacing the existing columns
object with a new one given a list of replacement column names.
df.columns = new
where new
is the list of new columns names is as simple as it gets. The drawback of this approach is that it requires editing the existing dataframe's columns
attribute and it isn't done inline. I'll show a few ways to perform this via pipelining without editing the existing dataframe.
Setup 1
To focus on the need to rename of replace column names with a pre-existing list, I'll create a new sample dataframe df
with initial column names and unrelated new column names.
df = pd.DataFrame({'Jack': [1, 2], 'Mahesh': [3, 4], 'Xin': [5, 6]})
new = ['x098', 'y765', 'z432']
df
Jack Mahesh Xin
0 1 3 5
1 2 4 6
Solution 1
pd.DataFrame.rename
It has been said already that if you had a dictionary mapping the old column names to new column names, you could use pd.DataFrame.rename
.
d = {'Jack': 'x098', 'Mahesh': 'y765', 'Xin': 'z432'}
df.rename(columns=d)
x098 y765 z432
0 1 3 5
1 2 4 6
However, you can easily create that dictionary and include it in the call to rename
. The following takes advantage of the fact that when iterating over df
, we iterate over each column name.
# Given just a list of new column names
df.rename(columns=dict(zip(df, new)))
x098 y765 z432
0 1 3 5
1 2 4 6
This works great if your original column names are unique. But if they are not, then this breaks down.
Setup 2
Non-unique columns
df = pd.DataFrame(
[[1, 3, 5], [2, 4, 6]],
columns=['Mahesh', 'Mahesh', 'Xin']
)
new = ['x098', 'y765', 'z432']
df
Mahesh Mahesh Xin
0 1 3 5
1 2 4 6
Solution 2
pd.concat
using the keys
argument
First, notice what happens when we attempt to use solution 1:
df.rename(columns=dict(zip(df, new)))
y765 y765 z432
0 1 3 5
1 2 4 6
We didn't map the new
list as the column names. We ended up repeating y765
. Instead, we can use the keys
argument of the pd.concat
function while iterating through the columns of df
.
pd.concat([c for _, c in df.items()], axis=1, keys=new)
x098 y765 z432
0 1 3 5
1 2 4 6
Solution 3
Reconstruct. This should only be used if you have a single dtype
for all columns. Otherwise, you'll end up with dtype
object
for all columns and converting them back requires more dictionary work.
Single dtype
pd.DataFrame(df.values, df.index, new)
x098 y765 z432
0 1 3 5
1 2 4 6
Mixed dtype
pd.DataFrame(df.values, df.index, new).astype(dict(zip(new, df.dtypes)))
x098 y765 z432
0 1 3 5
1 2 4 6
Solution 4
This is a gimmicky trick with transpose
and set_index
. pd.DataFrame.set_index
allows us to set an index inline, but there is no corresponding set_columns
. So we can transpose, then set_index
, and transpose back. However, the same single dtype
versus mixed dtype
caveat from solution 3 applies here.
Single dtype
df.T.set_index(np.asarray(new)).T
x098 y765 z432
0 1 3 5
1 2 4 6
Mixed dtype
df.T.set_index(np.asarray(new)).T.astype(dict(zip(new, df.dtypes)))
x098 y765 z432
0 1 3 5
1 2 4 6
Solution 5
Use a lambda
in pd.DataFrame.rename
that cycles through each element of new
.
In this solution, we pass a lambda that takes x
but then ignores it. It also takes a y
but doesn't expect it. Instead, an iterator is given as a default value and I can then use that to cycle through one at a time without regard to what the value of x
is.
df.rename(columns=lambda x, y=iter(new): next(y))
x098 y765 z432
0 1 3 5
1 2 4 6
And as pointed out to me by the folks in sopython chat, if I add a *
in between x
and y
, I can protect my y
variable. Though, in this context I don't believe it needs protecting. It is still worth mentioning.
df.rename(columns=lambda x, *, y=iter(new): next(y))
x098 y765 z432
0 1 3 5
1 2 4 6
There is Ints.tryParse()
in Guava. It doesn't throw exception on non-numeric string, however it does throw exception on null string.
I had the same problem and I think I have the solution.
If your field Application
in table Library
has a foreign key that references a field in another table (named Application
I would bet), then your field Application
in table Library
has to have a foreign key to table Application
too.
After that you can do your composed foreign key.
Excuse my poor english, and sorry if I'm wrong.
As Bergi noticed, I think the best and clear solution is use BlueBird.each, code below:
const BlueBird = require('bluebird');
BlueBird.each(files, fs.readFileAsync);
As the error says you have not correctly indented code, check_exists_sql
is not aligned with line above it cursor = db.cursor()
.
Also use 4 spaces for indentation.
Read this http://diveintopython.net/getting_to_know_python/indenting_code.html
Try not to do it!
From http://www.research.att.com/~bs/JSF-AV-rules.pdf:
AV Rule 199
The increment expression in a for loop will perform no action other than to change a single loop parameter to the next value for the loop.Rationale: Readability.
I am getting this issue when using owl carousal and scrolling the images.
So get solved just adding below CSS in your page.
.owl-carousel {
-ms-touch-action: pan-y;
touch-action: pan-y;
}
or
.owl-carousel {
-ms-touch-action: none;
touch-action: none;
}
great.. its the issue with empty directory only nothing else. I got my issue resolved by creating one binary file in each directory and then added them.
I found my I had built my object incorrectly. I used http://json2csharp.com/ to generate me my object class from the JSON. Once I had the correct Oject I was able to cast without issue. Norbit, Noob mistake. Thought I'd add it in case you have the same issue.
You can use an IF to test:
check:
@[ "${var}" ] || ( echo ">> var is not set"; exit 1 )
Result:
$ make check
>> var is not set
Makefile:2: recipe for target 'check' failed
make: *** [check] Error 1
ADDENDUM: For Windows 8 this will not work; see this excellent answer instead.
Found this solution here: http://www.robvanderwoude.com/clevertricks.php
AT > NUL
IF %ERRORLEVEL% EQU 0 (
ECHO you are Administrator
) ELSE (
ECHO you are NOT Administrator. Exiting...
PING 127.0.0.1 > NUL 2>&1
EXIT /B 1
)
Assuming that doesn't work and since we're talking Win7 you could use the following in Powershell if that's suitable:
$principal = new-object System.Security.Principal.WindowsPrincipal([System.Security.Principal.WindowsIdentity]::GetCurrent())
$principal.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
If not (and probably not, since you explicitly proposed batch files) then you could write the above in .NET and return an exit code from an exe based on the result for your batch file to use.
Unrelated to the question (Mehrdad's answer should get you going), and I hope this isn't taken as nitpicky: classes don't inherit interfaces, they implement them.
.NET does not support multiple-inheritance, so keeping the terms straight can help in communication. A class can inherit from one superclass and can implement as many interfaces as it wishes.
In response to Eric's comment... I had a discussion with another developer about whether or not interfaces "inherit", "implement", "require", or "bring along" interfaces with a declaration like:
public interface ITwo : IOne
The technical answer is that ITwo
does inherit IOne
for a few reasons:
ITwo
implements IOne
is flat wrongITwo
inherits IOne
methods, if MethodOne()
exists on IOne
then it is also accesible from ITwo
. i.e: ((ITwo)someObject).MethodOne())
is valid, even though ITwo
does not explicitly contain a definition for MethodOne()
typeof(IOne).IsAssignableFrom(typeof(ITwo))
returns true
We finally agreed that interfaces support true/full inheritance. The missing inheritance features (such as overrides, abstract/virtual accessors, etc) are missing from interfaces, not from interface inheritance. It still doesn't make the concept simple or clear, but it helps understand what's really going on under the hood in Eric's world :-)
The following example Web.config file will configure IIS to deny access for HTTP requests where the length of the "Content-type" header is greater than 100 bytes.
<configuration>
<system.webServer>
<security>
<requestFiltering>
<requestLimits>
<headerLimits>
<add header="Content-type" sizeLimit="100" />
</headerLimits>
</requestLimits>
</requestFiltering>
</security>
</system.webServer>
</configuration>
Source: http://www.iis.net/configreference/system.webserver/security/requestfiltering/requestlimits
As of 3.6 (probably works with slightly older 3.x as well), this is my solution:
import locale
locale.setlocale(locale.LC_ALL, '')
def number_format(n, dec_precision=4):
precision = len(str(round(n))) + dec_precision
return format(float(n), f'.{precision}n')
The purpose of the precision
calculation is to ensure we have enough precision to keep out of scientific notation (default precision is still 6).
The dec_precision
argument adds additional precision to use for decimal points. Since this makes use of the n
format, no insignificant zeros will be added (unlike f
formats). n
also will take care of rendering already-round integers without a decimal.
n
does require float
input, thus the cast.
IEnumerable
and IEnumerator
both are interfaces in C#.
IEnumerable
is an interface defining a single method GetEnumerator()
that returns an IEnumerator
interface.
This works for read-only access to a collection that implements that IEnumerable
can be used with a foreach
statement.
IEnumerator
has two methods, MoveNext
and Reset
. It also has a property called Current
.
The following shows the implementation of IEnumerable and IEnumerator.
Below is a slightly improved version of Dídac Pérez's answer, with both directions implemented, along with a demo of these functions' usages using unsigned char and unsigned long long values. Several notes:
cout << +value
trick for tersely outputting an unsigned char numerically that I found here: https://stackoverflow.com/a/28414758/1599699<put the type here>
syntax for clarity and safety.The result of a shift operation is undefined if additive-expression is negative or if additive-expression is greater than or equal to the number of bits in the (promoted) shift-expression.
Here's the code I'm using:
#include <iostream>
using namespace std;
template <typename T>
inline T rotateAndCarryLeft(T rotateMe, unsigned char shiftNum)
{
static const unsigned char TBitCount = sizeof(T) * 8U;
return (rotateMe << shiftNum) | (rotateMe >> (TBitCount - shiftNum));
}
template <typename T>
inline T rotateAndCarryRight(T rotateMe, unsigned char shiftNum)
{
static const unsigned char TBitCount = sizeof(T) * 8U;
return (rotateMe >> shiftNum) | (rotateMe << (TBitCount - shiftNum));
}
void main()
{
//00010100 == (unsigned char)20U
//00000101 == (unsigned char)5U == rotateAndCarryLeft(20U, 6U)
//01010000 == (unsigned char)80U == rotateAndCarryRight(20U, 6U)
cout << "unsigned char " << 20U << " rotated left by 6 bits == " << +rotateAndCarryLeft<unsigned char>(20U, 6U) << "\n";
cout << "unsigned char " << 20U << " rotated right by 6 bits == " << +rotateAndCarryRight<unsigned char>(20U, 6U) << "\n";
cout << "\n";
for (unsigned char shiftNum = 0U; shiftNum <= sizeof(unsigned char) * 8U; ++shiftNum)
{
cout << "unsigned char " << 21U << " rotated left by " << +shiftNum << " bit(s) == " << +rotateAndCarryLeft<unsigned char>(21U, shiftNum) << "\n";
}
cout << "\n";
for (unsigned char shiftNum = 0U; shiftNum <= sizeof(unsigned char) * 8U; ++shiftNum)
{
cout << "unsigned char " << 21U << " rotated right by " << +shiftNum << " bit(s) == " << +rotateAndCarryRight<unsigned char>(21U, shiftNum) << "\n";
}
cout << "\n";
for (unsigned char shiftNum = 0U; shiftNum <= sizeof(unsigned long long) * 8U; ++shiftNum)
{
cout << "unsigned long long " << 3457347ULL << " rotated left by " << +shiftNum << " bit(s) == " << rotateAndCarryLeft<unsigned long long>(3457347ULL, shiftNum) << "\n";
}
cout << "\n";
for (unsigned char shiftNum = 0U; shiftNum <= sizeof(unsigned long long) * 8U; ++shiftNum)
{
cout << "unsigned long long " << 3457347ULL << " rotated right by " << +shiftNum << " bit(s) == " << rotateAndCarryRight<unsigned long long>(3457347ULL, shiftNum) << "\n";
}
cout << "\n\n";
system("pause");
}
You may treat window as a service (eg. UI service) and pass itself to viewmodel via an interface, as such:
public interface IMainWindowAccess
{
void Close(bool result);
}
public class MainWindow : IMainWindowAccess
{
// (...)
public void Close(bool result)
{
DialogResult = result;
Close();
}
}
public class MainWindowViewModel
{
private IMainWindowAccess access;
public MainWindowViewModel(IMainWindowAccess access)
{
this.access = access;
}
public void DoClose()
{
access.Close(true);
}
}
This solution have most upsides of passing the view itself to viewmodel without having downside of breaking MVVM, because though physically view is passed to viewmodel, the latter still don't know about the former, it sees only some IMainWindowAccess
. So for instance if we wanted to migrate this solution to other platform, it would be only a matter of implementing IMainWindowAccess
properly for, say, an Activity
.
I'm posting the solution here to propose a different approach than events (though it's actually very similar), because it seems a little bit simpler than events to implement (attaching/detaching etc.), but still aligns nicely with MVVM pattern.
If you're using glib
, then you can use g_file_get_contents;
gchar *contents;
GError *err = NULL;
g_file_get_contents ("foo.txt", &contents, NULL, &err);
g_assert ((contents == NULL && err != NULL) || (contents != NULL && err == NULL));
if (err != NULL)
{
// Report error to user, and free error
g_assert (contents == NULL);
fprintf (stderr, "Unable to read file: %s\n", err->message);
g_error_free (err);
}
else
{
// Use file contents
g_assert (contents != NULL);
}
}
You can pass parameters in a function like this also:
function FunctionName()
{
Param ([string]$ParamName);
# Operations
}
Just pass var2 as an extra argument to one of the apply functions.
mylist <- list(a=1,b=2,c=3)
myfxn <- function(var1,var2){
var1*var2
}
var2 <- 2
sapply(mylist,myfxn,var2=var2)
This passes the same var2
to every call of myfxn
. If instead you want each call of myfxn
to get the 1st/2nd/3rd/etc. element of both mylist
and var2
, then you're in mapply
's domain.
I am using Bootstrap v3.3.4 and using the code:
$('.datepicker').datepicker({
dateFormat: 'dd-mm-yy'
});
Output is: 16-07-2015
Note: only need "yy" for full year.
With jooR it's merely:
on(obj).call(methodName /*params*/).get()
Here is a more elaborate example:
public class TestClass {
public int add(int a, int b) { return a + b; }
private int mul(int a, int b) { return a * b; }
static int sub(int a, int b) { return a - b; }
}
import static org.joor.Reflect.*;
public class JoorTest {
public static void main(String[] args) {
int add = on(new TestClass()).call("add", 1, 2).get(); // public
int mul = on(new TestClass()).call("mul", 3, 4).get(); // private
int sub = on(TestClass.class).call("sub", 6, 5).get(); // static
System.out.println(add + ", " + mul + ", " + sub);
}
}
This prints:
3, 12, 1
But I need the match result to be ... not in a match group...
For what you are trying to do, this should work. \K
resets the starting point of the match.
\bObject Name:\s+\K\S+
You can do the same for getting your Security ID
matches.
\bSecurity ID:\s+\K\S+