To reset a specific file to the last-committed state (to discard uncommitted changes in a specific file):
git checkout thefiletoreset.txt
This is mentioned in the git status
output:
(use "git checkout -- <file>..." to discard changes in working directory)
To reset the entire repository to the last committed state:
git reset --hard
To remove untracked files, I usually just delete all files in the working copy (but not the .git/
folder!), then do git reset --hard
which leaves it with only committed files.
A better way is to use git clean
(warning: using the -x
flag as below will cause Git to delete ignored files):
git clean -d -x -f
will remove untracked files, including directories (-d
) and files ignored by git (-x
). Replace the -f
argument with -n
to perform a dry-run or -i
for interactive mode, and it will tell you what will be removed.
Relevant links:
I'm astonished by the second number you mention (and confirm by your requested rounding) -- at first I thought my instinct for mental arithmetic was starting to fail me (I am getting older, after all, so that might be going the same way as my once-sharp memory!-)... but then I confirmed it hasn't, yet, by using, as I imagine you are, Python 3.1, and copying and pasting..:
>>> def input_meal():
... mealPrice = input('Enter the meal subtotal: $')
... mealPrice = float (mealPrice)
... return mealPrice
...
>>> def calc_tax(mealPrice):
... tax = mealPrice*.06
... return tax
...
>>> m = input_meal()
Enter the meal subtotal: $34.45
>>> print(calc_tax(m))
2.067
>>>
...as expected -- yet, you say it instead "returns a display of $ 2.607"... which might be a typo, just swapping two digits, except that you then ask "How can I set that to $2.61 instead?" so it really seems you truly mean 2.607
(which might be rounded to 2.61 in various ways) and definitely not the arithmetically correct result, 2.067
(which at best might be rounded to 2.07... definitely not to 2.61 as you request).
I imagine you first had the typo occur in transcription, and then mentally computed the desired rounding from the falsified-by-typo 2.607
rather than the actual original result -- is that what happened? It sure managed to confuse me for a while!-)
Anyway, to round a float to two decimal digits, simplest approach is the built-in function round with a second argument of 2
:
>>> round(2.067, 2)
2.07
>>> round(2.607, 2)
2.61
For numbers exactly equidistant between two possibilities, it rounds-to-even:
>>> round(2.605, 2)
2.6
>>> round(2.615, 2)
2.62
or, as the docs put it (exemplifying with the single-argument form of round
, which rounds to the closest integer):
if two multiples are equally close, rounding is done toward the even choice (so, for example, both round(0.5) and round(-0.5) are 0, and round(1.5) is 2).
However, for computations on money, I second the recommendation, already given in other answers, to stick with what the decimal module offers, instead of float
numbers.
In javascript:
var str = "abcdaaaaaabcdaabbccddabcd";
document.write(str.replace(/(abcd)/g,"----"));
//example output: ----aaaaa----aabbccdd----
In other languages, it would be something similar. Remember to enable global matches.
Try the following
download HAXM from Intel https://software.intel.com/en-us/android/articles/intel-hardware-accelerated-execution-manager.
Unzip the file and Run intelhaxm-android.exe.
Run silent_install.bat.
In my computer Win10 x64 - VS2015 it worked
There are two possible scenario,
If you application run on .net framework 4.5 or less than that and you can easily deploy new code to the production then you can use of below solution.
You can add below line of code before making api call,
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; // .NET 4.5
If you cannot deploy new code and you want to resolve with the same code which is present in the production, then you have two options.
Option 1 :
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001
then create a file with extension .reg and install.
Note : This setting will apply at registry level and is applicable to all application present on that machine and if you want to restrict to only single application then you can use Option 2
Option 2 : This can be done by changing some configuration setting in config file. You can add either of one in your config file.
<runtime>
<AppContextSwitchOverrides value="Switch.System.Net.DontEnableSchUseStrongCrypto=false"/>
</runtime>
or
<runtime>
<AppContextSwitchOverrides value="Switch.System.Net.DontEnableSystemDefaultTlsVersions=false"
</runtime>
Within your component, you can define an array of number (ES6) as described below:
export class SampleComponent {
constructor() {
this.numbers = Array(5).fill(0).map((x,i)=>i);
}
}
See this link for the array creation: Tersest way to create an array of integers from 1..20 in JavaScript.
You can then iterate over this array with ngFor
:
@View({
template: `
<ul>
<li *ngFor="let number of numbers">{{number}}</li>
</ul>
`
})
export class SampleComponent {
(...)
}
Or shortly:
@View({
template: `
<ul>
<li *ngFor="let number of [0,1,2,3,4]">{{number}}</li>
</ul>
`
})
export class SampleComponent {
(...)
}
Hope it helps you, Thierry
Edit: Fixed the fill statement and template syntax.
There might be another solution to this:
Your code was:
geom_point(aes(..., show.legend = FALSE))
You can specify the show.legend
parameter after the aes
call:
geom_point(aes(...), show.legend = FALSE)
then the corresponding legend should disappear
For parsing version numbers that follow these rules: - Are only digits and dots - Cannot start or end with a dot - Cannot be two dots together
This one did the trick to me.
^(\d+)((\.{1}\d+)*)(\.{0})$
Valid cases are:
1, 0.1, 1.2.1
This post suggests that you should be able to get the IE Developer Toolbar to show you the XPath for an element you click on if you turn on the "select element by click" option. http://blog.balfes.net/?p=62
Alternatively this post suggests either bookmarklets, or IE debugbar: Equivalent of Firebug's "Copy XPath" in Internet Explorer?
To do this, I had to come up with an intermediate data structure:
class KeyDataPoint {
String key;
DateTime timestamp;
Number data;
// obvious constructor and getters
}
With this in place, the approach is to "flatten" each MultiDataPoint into a list of (timestamp, key, data) triples and stream together all such triples from the list of MultiDataPoint.
Then, we apply a groupingBy
operation on the string key in order to gather the data for each key together. Note that a simple groupingBy
would result in a map from each string key to a list of the corresponding KeyDataPoint triples. We don't want the triples; we want DataPoint instances, which are (timestamp, data) pairs. To do this we apply a "downstream" collector of the groupingBy
which is a mapping
operation that constructs a new DataPoint by getting the right values from the KeyDataPoint triple. The downstream collector of the mapping
operation is simply toList
which collects the DataPoint objects of the same group into a list.
Now we have a Map<String, List<DataPoint>>
and we want to convert it to a collection of DataSet objects. We simply stream out the map entries and construct DataSet objects, collect them into a list, and return it.
The code ends up looking like this:
Collection<DataSet> convertMultiDataPointToDataSet(List<MultiDataPoint> multiDataPoints) {
return multiDataPoints.stream()
.flatMap(mdp -> mdp.getData().entrySet().stream()
.map(e -> new KeyDataPoint(e.getKey(), mdp.getTimestamp(), e.getValue())))
.collect(groupingBy(KeyDataPoint::getKey,
mapping(kdp -> new DataPoint(kdp.getTimestamp(), kdp.getData()), toList())))
.entrySet().stream()
.map(e -> new DataSet(e.getKey(), e.getValue()))
.collect(toList());
}
I took some liberties with constructors and getters, but I think they should be obvious.
As rcs stated, cex
will do the job in base graphics package. I reckon that you're not willing to do your graph in ggplot2
but if you do, there's a size
aesthetic attribute, that you can easily control (ggplot2
has user-friendly function arguments: instead of typing cex
(character expansion), in ggplot2
you can type e.g. size = 2
and you'll get 2mm point).
Here's the example:
### base graphics ###
plot(mpg ~ hp, data = mtcars, pch = 16, cex = .9)
### ggplot2 ###
# with qplot()
qplot(mpg, hp, data = mtcars, size = I(2))
# or with ggplot() + geom_point()
ggplot(mtcars, aes(mpg, hp), size = 2) + geom_point()
# or another solution:
ggplot(mtcars, aes(mpg, hp)) + geom_point(size = 2)
You can't have an hash map with multiple keys, but you can have an object that takes multiple parameters as the key.
Create an object called Index that takes an x and y value.
public class Index {
private int x;
private int y;
public Index(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int hashCode() {
return this.x ^ this.y;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Index other = (Index) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}
}
Then have your HashMap<Index, Value>
to get your result. :)
Here is code to get line number and column position
function getLineNumber(tArea) {
return tArea.value.substr(0, tArea.selectionStart).split("\n").length;
}
function getCursorPos() {
var me = $("textarea[name='documenttext']")[0];
var el = $(me).get(0);
var pos = 0;
if ('selectionStart' in el) {
pos = el.selectionStart;
} else if ('selection' in document) {
el.focus();
var Sel = document.selection.createRange();
var SelLength = document.selection.createRange().text.length;
Sel.moveStart('character', -el.value.length);
pos = Sel.text.length - SelLength;
}
var ret = pos - prevLine(me);
alert(ret);
return ret;
}
function prevLine(me) {
var lineArr = me.value.substr(0, me.selectionStart).split("\n");
var numChars = 0;
for (var i = 0; i < lineArr.length-1; i++) {
numChars += lineArr[i].length+1;
}
return numChars;
}
tArea is the text area DOM element
If I understand you correctly, this should do the trick. You'll need add using System.IO
at the top of your file if you don't already have it.
public bool ByteArrayToFile(string fileName, byte[] byteArray)
{
try
{
using (var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
{
fs.Write(byteArray, 0, byteArray.Length);
return true;
}
}
catch (Exception ex)
{
Console.WriteLine("Exception caught in process: {0}", ex);
return false;
}
}
This might work:
div{
display:inline-block;
width:100%;
float:left;
}
def grade(inlist):
grade_1, grade_2, grade_3, average =inlist
print (grade_1)
print (grade_2)
mark=[1,2,3,4]
grade(mark)
For simulating keyboard events in Chrome:
There is a related bug in webkit that keyboard events when initialized with initKeyboardEvent get an incorrect keyCode and charCode of 0: https://bugs.webkit.org/show_bug.cgi?id=16735
A working solution for it is posted in this SO answer.
Your specified folderName must be on C:\Program Files\Java\jdk1.7.0_02\bin
path
Foldername having class files.
C:\Program Files\Java\jdk1.7.0_02\bin>jar cvf program1.jar Foldername
Now program1.jar will create in C:\Program Files\Java\jdk1.7.0_02\bin path
You can use the is_a?
method
>> 1.is_a? Integer
=> true
>> "[email protected]".is_a? Integer
=> false
>> nil.is_a? Integer
=> false
For those who recommended pyd3, it is no longer under active development and points you to vincent. vincent is also no longer under active development and recommends using altair.
So if you want a pythonic d3, use altair.
If you're using Visual Studio 2015 and you're encountering this problem, you can install MS Office Developer Tools for VS2015 here.
I needed an iframe that would embed a portion of an external page with a vertical scroll bar, cropping out the navigation menus on the top and left of the page. I was able to do it with some simple HTML and CSS.
HTML
<div id="container">
<iframe id="embed" src="http://www.example.com"></iframe>
</div>
CSS
div#container
{
width:840px;
height:317px;
overflow:scroll; /* if you don't want a scrollbar, set to hidden */
overflow-x:hidden; /* hides horizontal scrollbar on newer browsers */
/* resize and min-height are optional, allows user to resize viewable area */
-webkit-resize:vertical;
-moz-resize:vertical;
resize:vertical;
min-height:317px;
}
iframe#embed
{
width:1000px; /* set this to approximate width of entire page you're embedding */
height:2000px; /* determines where the bottom of the page cuts off */
margin-left:-183px; /* clipping left side of page */
margin-top:-244px; /* clipping top of page */
overflow:hidden;
/* resize seems to inherit in at least Firefox */
-webkit-resize:none;
-moz-resize:none;
resize:none;
}
I have created an approximation of what I think you are looking for just using the Collections Framework in Java. Frankly, I think it is probably overkill as @Mike Deck points out. For such a small set of items to compare and process I think arrays would be a better choice from a procedural standpoint but here is my pseudo-coded (because I'm lazy) solution. I have an assumption that the Foo class is comparable based on it's unique id and not all of the data in it's contents:
Collection<Foo> oldSet = ...;
Collection<Foo> newSet = ...;
private Collection difference(Collection a, Collection b) {
Collection result = a.clone();
result.removeAll(b)
return result;
}
private Collection intersection(Collection a, Collection b) {
Collection result = a.clone();
result.retainAll(b)
return result;
}
public doWork() {
// if foo is in(*) oldSet but not newSet, call doRemove(foo)
Collection removed = difference(oldSet, newSet);
if (!removed.isEmpty()) {
loop removed {
Foo foo = removedIter.next();
doRemove(foo);
}
}
//else if foo is not in oldSet but in newSet, call doAdd(foo)
Collection added = difference(newSet, oldSet);
if (!added.isEmpty()) {
loop added {
Foo foo = addedIter.next();
doAdd(foo);
}
}
// else if foo is in both collections but modified, call doUpdate(oldFoo, newFoo)
Collection matched = intersection(oldSet, newSet);
Comparator comp = new Comparator() {
int compare(Object o1, Object o2) {
Foo f1, f2;
if (o1 instanceof Foo) f1 = (Foo)o1;
if (o2 instanceof Foo) f2 = (Foo)o2;
return f1.activated == f2.activated ? f1.startdate.compareTo(f2.startdate) == 0 ? ... : f1.startdate.compareTo(f2.startdate) : f1.activated ? 1 : 0;
}
boolean equals(Object o) {
// equal to this Comparator..not used
}
}
loop matched {
Foo foo = matchedIter.next();
Foo oldFoo = oldSet.get(foo);
Foo newFoo = newSet.get(foo);
if (comp.compareTo(oldFoo, newFoo ) != 0) {
doUpdate(oldFoo, newFoo);
} else {
//else if !foo.activated && foo.startDate >= now, call doStart(foo)
if (!foo.activated && foo.startDate >= now) doStart(foo);
// else if foo.activated && foo.endDate <= now, call doEnd(foo)
if (foo.activated && foo.endDate <= now) doEnd(foo);
}
}
}
As far as your questions: If I convert oldSet and newSet into HashMap (order is not of concern here), with the IDs as keys, would it made the code easier to read and easier to compare? How much of time & memory performance is loss on the conversion? I think that you would probably make the code more readable by using a Map BUT...you would probably use more memory and time during the conversion.
Would iterating the two sets and perform the appropriate operation be more efficient and concise? Yes, this would be the best of both worlds especially if you followed @Mike Sharek 's advice of Rolling your own List with the specialized methods or following something like the Visitor Design pattern to run through your collection and process each item.
You need to access the matches in order to get at the SDI number. Here is a function that will do it (assuming there is only 1 SDI number per cell).
For the regex, I used "sdi followed by a space and one or more numbers". You had "sdi followed by a space and zero or more numbers". You can simply change the + to * in my pattern to go back to what you had.
Function ExtractSDI(ByVal text As String) As String
Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
RE.pattern = "(sdi \d+)"
RE.Global = True
RE.IgnoreCase = True
Set allMatches = RE.Execute(text)
If allMatches.count <> 0 Then
result = allMatches.Item(0).submatches.Item(0)
End If
ExtractSDI = result
End Function
If a cell may have more than one SDI number you want to extract, here is my RegexExtract function. You can pass in a third paramter to seperate each match (like comma-seperate them), and you manually enter the pattern in the actual function call:
Ex) =RegexExtract(A1, "(sdi \d+)", ", ")
Here is:
Function RegexExtract(ByVal text As String, _
ByVal extract_what As String, _
Optional seperator As String = "") As String
Dim i As Long, j As Long
Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
RE.pattern = extract_what
RE.Global = True
Set allMatches = RE.Execute(text)
For i = 0 To allMatches.count - 1
For j = 0 To allMatches.Item(i).submatches.count - 1
result = result & seperator & allMatches.Item(i).submatches.Item(j)
Next
Next
If Len(result) <> 0 Then
result = Right(result, Len(result) - Len(seperator))
End If
RegexExtract = result
End Function
*Please note that I have taken "RE.IgnoreCase = True" out of my RegexExtract, but you could add it back in, or even add it as an optional 4th parameter if you like.
Non recursive solution according to Knuth, Python example:
def nextPermutation(perm):
k0 = None
for i in range(len(perm)-1):
if perm[i]<perm[i+1]:
k0=i
if k0 == None:
return None
l0 = k0+1
for i in range(k0+1, len(perm)):
if perm[k0] < perm[i]:
l0 = i
perm[k0], perm[l0] = perm[l0], perm[k0]
perm[k0+1:] = reversed(perm[k0+1:])
return perm
perm=list("12345")
while perm:
print perm
perm = nextPermutation(perm)
The way with the least space overhead is to use the Concat extension method.
var combined = list1.Concat(list2);
It creates an instance of IEnumerable<T>
which will enumerate the elements of list1 and list2 in that order.
We can check Update by Add these Code:
First we need to add dependencies :
implementation 'org.jsoup:jsoup:1.10.2'
Second we need to create Java File :
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.widget.Toast;
import org.jsoup.Jsoup;
public class CurrentVersion{
private Activity activity;
public CurrentVersion(Activity activity) {
this.activity = activity;
}
//current version of app installed in the device
private String getCurrentVersion(){
PackageManager pm = activity.getPackageManager();
PackageInfo pInfo = null;
try {
pInfo = pm.getPackageInfo(activity.getPackageName(),0);
} catch (PackageManager.NameNotFoundException e1) {
e1.printStackTrace();
}
return pInfo.versionName;
}
private class GetLatestVersion extends AsyncTask<String, String, String> {
private String latestVersion;
private ProgressDialog progressDialog;
private boolean manualCheck;
GetLatestVersion(boolean manualCheck) {
this.manualCheck = manualCheck;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (manualCheck)
{
if (progressDialog!=null)
{
if (progressDialog.isShowing())
{
progressDialog.dismiss();
}
}
}
String currentVersion = getCurrentVersion();
//If the versions are not the same
if(!currentVersion.equals(latestVersion)&&latestVersion!=null){
final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle("An Update is Available");
builder.setMessage("Its better to update now");
builder.setPositiveButton("Update", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//Click button action
activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id="+activity.getPackageName())));
dialog.dismiss();
}
});
builder.setCancelable(false);
builder.show();
}
else {
if (manualCheck) {
Toast.makeText(activity, "No Update Available", Toast.LENGTH_SHORT).show();
}
}
}
@Override
protected String doInBackground(String... params) {
try {
//It retrieves the latest version by scraping the content of current version from play store at runtime
latestVersion = Jsoup.connect("https://play.google.com/store/apps/details?id=" + activity.getPackageName() + "&hl=it")
.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(".hAyfc .htlgb")
.get(7)
.ownText();
return latestVersion;
} catch (Exception e) {
return latestVersion;
}
}
}
public void checkForUpdate(boolean manualCheck)
{
new GetLatestVersion(manualCheck).execute();
}
}
_x000D_
Third We need to add this class in your main class where you want to show the update:
AppUpdateChecker appUpdateChecker=new AppUpdateChecker(this);
appUpdateChecker.checkForUpdate(false);
I Hope it will Help you
I think the MatTableDataSource
object is some way linked with the data array that you pass to MatTableDataSource
constructor.
For instance:
dataTable: string[];
tableDS: MatTableDataSource<string>;
ngOnInit(){
// here your pass dataTable to the dataSource
this.tableDS = new MatTableDataSource(this.dataTable);
}
So, when you have to change data; change on the original list dataTable
and then reflect the change on the table by call _updateChangeSubscription()
method on tableDS
.
For instance:
this.dataTable.push('testing');
this.tableDS._updateChangeSubscription();
That's work with me through Angular 6.
You may usually if you have multiple keys setup via ssh on your system (my device is running Windows 10), you will encounter this issue, the fix is to:
Precondition: Setup up your SSH Keys as indicated by GitLab
Please note, there is a space before the second line, very important to avoid this solution not working.
If you are using an array data source you can do something like below -
$(".select").select2({
data: data_names
});
data_names.forEach(function(name) {
if (name.selected) {
$(".select").select2('val', name.id);
}
});
This assumes that out of your data set the one item which you want to set as default has an additional attribute called selected and we use that to set the value.
Apart from using @MvcHtmlString.Create(ViewBag.Stuff)
as suggested by Dommer, I suggest you to also use AntiXSS library as suggested phill http://haacked.com/archive/2010/04/06/using-antixss-as-the-default-encoder-for-asp-net.aspx
It encodes almost all the possible XSS attack string.
Instead of using $_POST, use $_REQUEST:
HTML:
<form action="" method="post">
<input type="text" name="firstname">
<input type="submit" name="submit" value="Submit">
</form>
PHP:
if(isset($_REQUEST['submit'])){
$test = $_REQUEST['firstname'];
echo $test;
}
Use for a date three days ago:
WHERE t.date >= DATE_ADD(CURDATE(), INTERVAL -3 DAY);
Check the DATE_ADD documentation.
Or you can use:
WHERE t.date >= ( CURDATE() - INTERVAL 3 DAY )
@JsonFormat only work for standard format supported by the jackson version that you are using.
Ex :- compatible with any of standard forms ("yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd")) for jackson 2.8.6
yourTextView.setTextColor(color);
Or, in your case: yourTextView.setTextColor(0xffbdbdbd);
I don't try to answer all of my questions, as I believe it is too broad. Just a couple of notes:
there are cases when object construction is a task complex enough to justify its extraction to another class.
That class is in fact a Builder, rather than a Factory.
In the general case, I don't want to force the users of the factory to be restrained to dynamic allocation.
Then you could have your factory encapsulate it in a smart pointer. I believe this way you can have your cake and eat it too.
This also eliminates the issues related to return-by-value.
Conclusion: Making a factory by returning an object is indeed a solution for some cases (such as the 2-D vector previously mentioned), but still not a general replacement for constructors.
Indeed. All design patterns have their (language specific) constraints and drawbacks. It is recommended to use them only when they help you solve your problem, not for their own sake.
If you are after the "perfect" factory implementation, well, good luck.
For anyone completely new to Qt Creator like me, you can modify your project's .pro file from within Qt Creator:
Just double-click on "your project name".pro in the Projects window and add the include path at the bottom of the .pro file like I've done.
del .\*
This Command delete all files & folders from current navigation in your command line.
You have to define void swapCase before the main definition.
A new option is Jexus Manager for IIS Express,
https://blog.lextudio.com/2014/10/jexus-manager-for-iis-express/
It is just the management tool you know how to use.
On my device TimeZone.getDefault()
is always returning UTC time zone.
I need to do this to get user configured time zone :
TimeZone.setDefault(null)
val tz = TimeZone.getDefault()
It will return user selected timezone.
UPDATE:
Since the version 22.1.0, the class ActionBarActivity is deprecated, so instead use AppCompatActivity. For more details see here
Using ActionBarActivity:
In Eclipse:
1 - Make sure library project(appcompat_v7) is open & is proper referenced (added as library) in your application project.
2 - Delete android-support-v4.jar from your project's libs folder(if jar is present).
3 - Appcompat_v7 must have android-support-v4.jar & android-support-v7-appcompat.jar inside it's libs folder. (If jars are not present copy them from /sdk/extras/android/support/v7/appcompat/libs folder of your installed android sdk location)
4- Check whether ActionBarActivity is properly imported.
import android.support.v7.app.ActionBarActivity;
In Android Studio
Just add compile dependencies to app's build.gradle
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:22.1.1'
}
figlegend may be what you're looking for: http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.figlegend
Example here: http://matplotlib.org/examples/pylab_examples/figlegend_demo.html
Another example:
plt.figlegend( lines, labels, loc = 'lower center', ncol=5, labelspacing=0. )
or:
fig.legend( lines, labels, loc = (0.5, 0), ncol=5 )
Well, if you study the structure of how the application life-cycle works,here , then you'll come to know that onPause()
is called when another activity gains focus, and onStop()
is called when the activity is no longer visible.
From what I have learned yet, you can call finish()
only from the activity which is active and/or has the focus. If you're calling finish()
from the onPause()
method that means you're calling it when the activity is no longer active. thus an exception is thrown.
When you're calling finish()
from onStop()
then the activity is being sent to background, thus will no longer be visible, then this exception.
When you press the back
button, onStop()
is called.
Most probably, Android will automatically do for you what you are currently wanting to do.
Use:
var os = require('os');
var networkInterfaces = os.networkInterfaces();
var arr = networkInterfaces['Local Area Connection 3']
var ip = arr[1].address;
To compare, there are more options:
import (
"fmt"
"regexp"
"strings"
)
const (
str = "something"
substr = "some"
)
// 1. Contains
res := strings.Contains(str, substr)
fmt.Println(res) // true
// 2. Index: check the index of the first instance of substr in str, or -1 if substr is not present
i := strings.Index(str, substr)
fmt.Println(i) // 0
// 3. Split by substr and check len of the slice, or length is 1 if substr is not present
ss := strings.Split(str, substr)
fmt.Println(len(ss)) // 2
// 4. Check number of non-overlapping instances of substr in str
c := strings.Count(str, substr)
fmt.Println(c) // 1
// 5. RegExp
matched, _ := regexp.MatchString(substr, str)
fmt.Println(matched) // true
// 6. Compiled RegExp
re = regexp.MustCompile(substr)
res = re.MatchString(str)
fmt.Println(res) // true
Benchmarks:
Contains
internally calls Index
, so the speed is almost the same (btw Go 1.11.5 showed a bit bigger difference than on Go 1.14.3).
BenchmarkStringsContains-4 100000000 10.5 ns/op 0 B/op 0 allocs/op
BenchmarkStringsIndex-4 117090943 10.1 ns/op 0 B/op 0 allocs/op
BenchmarkStringsSplit-4 6958126 152 ns/op 32 B/op 1 allocs/op
BenchmarkStringsCount-4 42397729 29.1 ns/op 0 B/op 0 allocs/op
BenchmarkStringsRegExp-4 461696 2467 ns/op 1326 B/op 16 allocs/op
BenchmarkStringsRegExpCompiled-4 7109509 168 ns/op 0 B/op 0 allocs/op
You seem to assume that WebSocket is a replacement for HTTP. It is not. It's an extension.
The main use-case of WebSockets are Javascript applications which run in the web browser and receive real-time data from a server. Games are a good example.
Before WebSockets, the only method for Javascript applications to interact with a server was through XmlHttpRequest
. But these have a major disadvantage: The server can't send data unless the client has explicitly requested it.
But the new WebSocket feature allows the server to send data whenever it wants. This allows to implement browser-based games with a much lower latency and without having to use ugly hacks like AJAX long-polling or browser plugins.
So why not use normal HTTP with streamed requests and responses
In a comment to another answer you suggested to just stream the client request and response body asynchronously.
In fact, WebSockets are basically that. An attempt to open a WebSocket connection from the client looks like a HTTP request at first, but a special directive in the header (Upgrade: websocket
) tells the server to start communicating in this asynchronous mode. First drafts of the WebSocket protocol weren't much more than that and some handshaking to ensure that the server actually understands that the client wants to communicate asynchronously. But then it was realized that proxy servers would be confused by that, because they are used to the usual request/response model of HTTP. A potential attack scenario against proxy servers was discovered. To prevent this it was necessary to make WebSocket traffic look unlike any normal HTTP traffic. That's why the masking keys were introduced in the final version of the protocol.
empty
is an operator:
The
empty
operator is a prefix operation that can be used to determine whether a value is null or empty.
<c:if test="${empty myObject.featuresList}">
Try something like this:
SELECT
*
FROM
(SELECT ks, COUNT(*) AS '# Tasks' FROM Table GROUP BY ks) t1
INNER JOIN
(SELECT ks, COUNT(*) AS '# Late' FROM Table WHERE Age > Palt GROUP BY ks) t2
ON t1.ks = t2.ks
You need to set a constraint on the table to trigger a "conflict" which you then resolve by doing a replace:
CREATE TABLE data (id INTEGER PRIMARY KEY, event_id INTEGER, track_id INTEGER, value REAL);
CREATE UNIQUE INDEX data_idx ON data(event_id, track_id);
Then you can issue:
INSERT OR REPLACE INTO data VALUES (NULL, 1, 2, 3);
INSERT OR REPLACE INTO data VALUES (NULL, 2, 2, 3);
INSERT OR REPLACE INTO data VALUES (NULL, 1, 2, 5);
The "SELECT * FROM data" will give you:
2|2|2|3.0
3|1|2|5.0
Note that the data.id is "3" and not "1" because REPLACE does a DELETE and INSERT, not an UPDATE. This also means that you must ensure that you define all necessary columns or you will get unexpected NULL values.
If you are using windows, you can use installr. Example usage here
It's an old question, but if you wanted to catch a backspace event on input, and not keydown, keypress, or keyup—as I've noticed any one of these break certain functions I've written and cause awkward delays with automated text formatting—you can catch a backspace using inputType:
document.getElementsByTagName('input')[0].addEventListener('input', function(e) {
if (e.inputType == "deleteContentBackward") {
// your code here
}
});
I have created Delayed component using Hooks and TypeScript
import React, { useState, useEffect } from 'react';
type Props = {
children: React.ReactNode;
waitBeforeShow?: number;
};
const Delayed = ({ children, waitBeforeShow = 500 }: Props) => {
const [isShown, setIsShown] = useState(false);
useEffect(() => {
setTimeout(() => {
setIsShown(true);
}, waitBeforeShow);
}, [waitBeforeShow]);
return isShown ? children : null;
};
export default Delayed;
Just wrap another component into Delayed
export function LoadingScreen = () => {
return (
<Delayed>
<div />
</Delayed>
);
};
You can change it by going File
=> Settings
(Shortcut CTRL+ ALT+ S) , from Left panel Choose Appearance
, Now from Right Panel choose theme.
Android Studio 2.1
Preference -> Search for Appearance -> UI options , Click on DropDown Theme
Android 2.2
Android studio -> File -> Settings -> Appearance & Behavior -> Look for UI Options
EDIT :
Import External Themes
You can download custom theme from this website. Choose your theme, download it. To set theme Go to Android studio -> File -> Import Settings -> Choose the
.jar
file downloaded.
I had this problem and the solution was namespaces. The included file was included in its own namespace. Obvious thing, easy to overlook.
For anyone that finds this question looking for how to access custom properties in ASP.NET Core 2.1 - it's much easier: You'll have a UserManager, e.g. in _LoginPartial.cshtml, and then you can simply do (assuming "ScreenName" is a property that you have added to your own AppUser which inherits from IdentityUser):
@using Microsoft.AspNetCore.Identity
@using <namespaceWhereYouHaveYourAppUser>
@inject SignInManager<AppUser> SignInManager
@inject UserManager<AppUser> UserManager
@if (SignInManager.IsSignedIn(User)) {
<form asp-area="Identity" asp-page="/Account/Logout" asp-route-returnUrl="@Url.Action("Index", "Home", new { area = "" })"
method="post" id="logoutForm"
class="form-inline my-2 my-lg-0">
<ul class="nav navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" asp-area="Identity" asp-page="/Account/Manage/Index" title="Manage">
Hello @((await UserManager.GetUserAsync(User)).ScreenName)!
<!-- Original code, shows Email-Address: @UserManager.GetUserName(User)! -->
</a>
</li>
<li class="nav-item">
<button type="submit" class="btn btn-link nav-item navbar-link nav-link">Logout</button>
</li>
</ul>
</form>
} else {
<ul class="navbar-nav ml-auto">
<li class="nav-item"><a class="nav-link" asp-area="Identity" asp-page="/Account/Register">Register</a></li>
<li class="nav-item"><a class="nav-link" asp-area="Identity" asp-page="/Account/Login">Login</a></li>
</ul>
}
$ postgres -V # Or --version. Use "locate bin/postgres" if not found.
postgres (PostgreSQL) 9.6.1
$ postgres -V | awk '{print $NF}' # Last column is version.
9.6.1
$ postgres -V | egrep -o '[0-9]{1,}\.[0-9]{1,}' # Major.Minor version
9.6
If having more than one installation of PostgreSQL, or if getting the "postgres: command not found
" error:
$ locate bin/postgres | xargs -i xargs -t '{}' -V # xargs is intentionally twice.
/usr/pgsql-9.3/bin/postgres -V
postgres (PostgreSQL) 9.3.5
/usr/pgsql-9.6/bin/postgres -V
postgres (PostgreSQL) 9.6.1
If locate
doesn't help, try find
:
$ sudo find / -wholename '*/bin/postgres' 2>&- | xargs -i xargs -t '{}' -V # xargs is intentionally twice.
/usr/pgsql-9.6/bin/postgres -V
postgres (PostgreSQL) 9.6.1
Although postmaster
can also be used instead of postgres
, using postgres
is preferable because postmaster
is a deprecated alias of postgres
.
As relevant, login as postgres
.
$ psql -V # Or --version
psql (PostgreSQL) 9.6.1
If having more than one installation of PostgreSQL:
$ locate bin/psql | xargs -i xargs -t '{}' -V # xargs is intentionally twice.
/usr/bin/psql -V
psql (PostgreSQL) 9.3.5
/usr/pgsql-9.2/bin/psql -V
psql (PostgreSQL) 9.2.9
/usr/pgsql-9.3/bin/psql -V
psql (PostgreSQL) 9.3.5
=> SELECT version();
version
--------------------------------------------------------------------------------------------------------------
PostgreSQL 9.2.9 on x86_64-unknown-linux-gnu, compiled by gcc (GCC) 4.4.7 20120313 (Red Hat 4.4.7-4), 64-bit
=> SHOW server_version;
server_version
----------------
9.2.9
=> SHOW server_version_num;
server_version_num
--------------------
90209
If more curious, try => SHOW all;
.
For what it's worth, a shell command can be executed within psql
to show the client version of the psql
executable in the path. Note that the running psql
can potentially be different from the one in the path.
=> \! psql -V
psql (PostgreSQL) 9.2.9
If you change baudrate for example back and forth it clears the Serial Monitor window in version 1.5.3 of Arduino IDE for Intel Galileo development
Use animation-fill-mode: forwards;
animation-fill-mode: forwards;
The element will retain the style values that is set by the last keyframe (depends on animation-direction and animation-iteration-count).
Note: The @keyframes rule is not supported in Internet Explorer 9 and earlier versions.
Working example
div {_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
background: red;_x000D_
position :relative;_x000D_
-webkit-animation: mymove 3ss forwards; /* Safari 4.0 - 8.0 */_x000D_
animation: bubble 3s forwards;_x000D_
/* animation-name: bubble; _x000D_
animation-duration: 3s;_x000D_
animation-fill-mode: forwards; */_x000D_
}_x000D_
_x000D_
/* Safari */_x000D_
@-webkit-keyframes bubble {_x000D_
0% { transform:scale(0.5); opacity:0.0; left:0}_x000D_
50% { transform:scale(1.2); opacity:0.5; left:100px}_x000D_
100% { transform:scale(1.0); opacity:1.0; left:200px}_x000D_
}_x000D_
_x000D_
/* Standard syntax */_x000D_
@keyframes bubble {_x000D_
0% { transform:scale(0.5); opacity:0.0; left:0}_x000D_
50% { transform:scale(1.2); opacity:0.5; left:100px}_x000D_
100% { transform:scale(1.0); opacity:1.0; left:200px}_x000D_
}
_x000D_
<h1>The keyframes </h1>_x000D_
<div></div>
_x000D_
You can use numpy.asarray, for example to convert a list into an array:
>>> a = [1, 2]
>>> np.asarray(a)
array([1, 2])
As of PHP 5.3.0 you can use __DIR__
for this purpose.
The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname(__ FILE__).
See PHP Magic constants.
C:\www>php --version
PHP 5.5.6 (cli) (built: Nov 12 2013 11:33:44)
Copyright (c) 1997-2013 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2013 Zend Technologies
C:\www>php -r "echo __DIR__;"
C:\www
Have a go with these code:
>>> import pyexcel as pe
>>> sheet = pe.Sheet(data)
>>> data=[[1, 2], [2, 3], [4, 5]]
>>> sheet
Sheet Name: pyexcel
+---+---+
| 1 | 2 |
+---+---+
| 2 | 3 |
+---+---+
| 4 | 5 |
+---+---+
>>> sheet.save_as("one.csv")
>>> b = [[126, 125, 123, 122, 123, 125, 128, 127, 128, 129, 130, 130, 128, 126, 124, 126, 126, 128, 129, 130, 130, 130, 130, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 134, 134, 134, 134, 134, 134, 134, 134, 133, 134, 135, 134, 133, 133, 134, 135, 136], [135, 135, 136, 137, 137, 136, 134, 135, 135, 135, 134, 134, 133, 133, 133, 134, 134, 134, 133, 133, 132, 132, 132, 135, 135, 133, 133, 133, 133, 135, 135, 131, 135, 136, 134, 133, 136, 137, 136, 133, 134, 135, 136, 136, 135, 134, 133, 133, 134, 135, 136, 136, 136, 135, 134, 135, 138, 138, 135, 135, 138, 138, 135, 139], [137, 135, 136, 138, 139, 137, 135, 142, 139, 137, 139, 138, 136, 137, 141, 138, 138, 139, 139, 139, 139, 138, 138, 138, 138, 137, 137, 137, 137, 138, 138, 136, 137, 137, 137, 137, 137, 137, 138, 148, 144, 140, 138, 137, 138, 138, 138, 137, 137, 137, 137, 137, 138, 139, 140, 141, 141, 141, 141, 141, 141, 141, 141, 141], [141, 141, 141, 141, 141, 141, 141, 139, 139, 139, 140, 140, 141, 141, 141, 140, 140, 140, 140, 140, 141, 142, 143, 138, 138, 138, 139, 139, 140, 140, 140, 141, 140, 139, 139, 141, 141, 140, 139, 145, 137, 137, 145, 145, 137, 137, 144, 141, 139, 146, 134, 145, 140, 149, 144, 145, 142, 140, 141, 144, 145, 142, 139, 140]]
>>> s2 = pe.Sheet(b)
>>> s2
Sheet Name: pyexcel
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
| 126 | 125 | 123 | 122 | 123 | 125 | 128 | 127 | 128 | 129 | 130 | 130 | 128 | 126 | 124 | 126 | 126 | 128 | 129 | 130 | 130 | 130 | 130 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 134 | 134 | 134 | 134 | 134 | 134 | 134 | 134 | 133 | 134 | 135 | 134 | 133 | 133 | 134 | 135 | 136 |
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
| 135 | 135 | 136 | 137 | 137 | 136 | 134 | 135 | 135 | 135 | 134 | 134 | 133 | 133 | 133 | 134 | 134 | 134 | 133 | 133 | 132 | 132 | 132 | 135 | 135 | 133 | 133 | 133 | 133 | 135 | 135 | 131 | 135 | 136 | 134 | 133 | 136 | 137 | 136 | 133 | 134 | 135 | 136 | 136 | 135 | 134 | 133 | 133 | 134 | 135 | 136 | 136 | 136 | 135 | 134 | 135 | 138 | 138 | 135 | 135 | 138 | 138 | 135 | 139 |
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
| 137 | 135 | 136 | 138 | 139 | 137 | 135 | 142 | 139 | 137 | 139 | 138 | 136 | 137 | 141 | 138 | 138 | 139 | 139 | 139 | 139 | 138 | 138 | 138 | 138 | 137 | 137 | 137 | 137 | 138 | 138 | 136 | 137 | 137 | 137 | 137 | 137 | 137 | 138 | 148 | 144 | 140 | 138 | 137 | 138 | 138 | 138 | 137 | 137 | 137 | 137 | 137 | 138 | 139 | 140 | 141 | 141 | 141 | 141 | 141 | 141 | 141 | 141 | 141 |
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
| 141 | 141 | 141 | 141 | 141 | 141 | 141 | 139 | 139 | 139 | 140 | 140 | 141 | 141 | 141 | 140 | 140 | 140 | 140 | 140 | 141 | 142 | 143 | 138 | 138 | 138 | 139 | 139 | 140 | 140 | 140 | 141 | 140 | 139 | 139 | 141 | 141 | 140 | 139 | 145 | 137 | 137 | 145 | 145 | 137 | 137 | 144 | 141 | 139 | 146 | 134 | 145 | 140 | 149 | 144 | 145 | 142 | 140 | 141 | 144 | 145 | 142 | 139 | 140 |
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
>>> s2[0,0]
126
>>> s2.save_as("two.csv")
For windows quotes are required and ; should be used as separator. e.g.:
java -cp "target\\*;target\\dependency\\*" my.package.Main
These are literals and are described in section 3.10 of the Java language spec.
@robertc has it right, but you also need to notice that svg, #container
causes the svg to be scaled exponentially for anything but 100% (once for #container
and once for svg
).
In other words, if I applied 50% h/w to both elements, it's actually 50% of 50%, or .5 * .5, which equals .25, or 25% scale.
One selector works fine when used as @robertc suggests.
svg {
width:50%;
height:50%;
}
I know it is not Dictionary<TKey, TValue>
class, however you can avoid KeyNotFoundException
while incrementing a value like:
dictionary[key]++; // throws `KeyNotFoundException` if there is no such key
by using ConcurrentDictionary<TKey, TValue> and its really nice method AddOrUpdate()..
Let me show an example:
var str = "Hellooo!!!";
var characters = new ConcurrentDictionary<char, int>();
foreach (var ch in str)
characters.AddOrUpdate(ch, 1, (k, v) => v + 1);
Scott Meyers tells you to prefer prefix except on those occasions where logic would dictate that postfix is appropriate.
"More Effective C++" item #6 - that's sufficient authority for me.
For those who don't own the book, here are the pertinent quotes. From page 32:
From your days as a C programmer, you may recall that the prefix form of the increment operator is sometimes called "increment and fetch", while the postfix form is often known as "fetch and increment." The two phrases are important to remember, because they all but act as formal specifications...
And on page 34:
If you're the kind who worries about efficiency, you probably broke into a sweat when you first saw the postfix increment function. That function has to create a temporary object for its return value and the implementation above also creates an explicit temporary object that has to be constructed and destructed. The prefix increment function has no such temporaries...
Update August 2019
In Android Studio 3.5 Instant Run was replaced with Apply Changes. And it works in different way: APK is not modified on the fly anymore but instead runtime instrumentation is used to redefine classes on the fly (more info). So since Android Studio 3.5 instant run settings are replaced with Deployment (Settings -> Build, Execution, Deployment -> Deployment):
For all practical purposes, and with no import at all, one can use:
x = float("inf")
More detail on this related question: How can I represent an infinite number in Python?
You can use a CSS3 transition
for this. Have a look at this example:
Here is the main code:
#box {
position : relative;
width : 100px;
height : 100px;
background-color : gray;
border : 5px solid black;
-webkit-transition : border 500ms ease-out;
-moz-transition : border 500ms ease-out;
-o-transition : border 500ms ease-out;
transition : border 500ms ease-out;
}
#box:hover {
border : 10px solid red;
}
I found a super simple explanation about class << self
, Eigenclass
and different type of methods.
In Ruby, there are three types of methods that can be applied to a class:
Instance methods and class methods are almost similar to their homonymous in other programming languages.
class Foo
def an_instance_method
puts "I am an instance method"
end
def self.a_class_method
puts "I am a class method"
end
end
foo = Foo.new
def foo.a_singleton_method
puts "I am a singletone method"
end
Another way of accessing an Eigenclass
(which includes singleton methods) is with the following syntax (class <<
):
foo = Foo.new
class << foo
def a_singleton_method
puts "I am a singleton method"
end
end
now you can define a singleton method for self
which is the class Foo
itself in this context:
class Foo
class << self
def a_singleton_and_class_method
puts "I am a singleton method for self and a class method for Foo"
end
end
end
Add this to your python script.
import os
os.system("exec /path/to/another/script")
This executes that command as if it were typed into the shell.
Use reduce()
to traverse the dictionary:
from functools import reduce # forward compatibility for Python 3
import operator
def getFromDict(dataDict, mapList):
return reduce(operator.getitem, mapList, dataDict)
and reuse getFromDict
to find the location to store the value for setInDict()
:
def setInDict(dataDict, mapList, value):
getFromDict(dataDict, mapList[:-1])[mapList[-1]] = value
All but the last element in mapList
is needed to find the 'parent' dictionary to add the value to, then use the last element to set the value to the right key.
Demo:
>>> getFromDict(dataDict, ["a", "r"])
1
>>> getFromDict(dataDict, ["b", "v", "y"])
2
>>> setInDict(dataDict, ["b", "v", "w"], 4)
>>> import pprint
>>> pprint.pprint(dataDict)
{'a': {'r': 1, 's': 2, 't': 3},
'b': {'u': 1, 'v': {'w': 4, 'x': 1, 'y': 2, 'z': 3}, 'w': 3}}
Note that the Python PEP8 style guide prescribes snake_case names for functions. The above works equally well for lists or a mix of dictionaries and lists, so the names should really be get_by_path()
and set_by_path()
:
from functools import reduce # forward compatibility for Python 3
import operator
def get_by_path(root, items):
"""Access a nested object in root by item sequence."""
return reduce(operator.getitem, items, root)
def set_by_path(root, items, value):
"""Set a value in a nested object in root by item sequence."""
get_by_path(root, items[:-1])[items[-1]] = value
And for completion's sake, a function to delete a key:
def del_by_path(root, items):
"""Delete a key-value in a nested object in root by item sequence."""
del get_by_path(root, items[:-1])[items[-1]]
create another class and increase the with size with 2px example
.enquiry_fld_normal{
width:278px !important;
}
.enquiry_fld_normal_select{
width:280px !important;
}
..and to detect a change in resolution to handle it (once you're using Docking and Anchoring like SwDevMan81 suggested) use the SystemEvents.DisplaySettingsChanged event in Microsoft.Win32.
you need to store the token while creating for 1st registration. When you retrieve data from login table you need to differentiate entered date with current date if it is more than 1 day (24 hours) you need to display message like your token is expired.
To generate key refer here
8B 5D 32
is machine code
mov ebx, [ebp+32h]
is assembly
lmylib.so
containing 8B 5D 32
is object code
I've found using cmd works well as an alternative, especially when you need to pipe the output from the called application (espeically when it doesn't have built in logging, unlike msbuild)
cmd /C "$msbuild $args" >> $outputfile
The solution is to add this to the beginning of your .htaccess
<Files wp-login.php>
Order Deny,Allow
Deny from all
Allow from all
</Files>
It's because many hosts were under attack, using the wordpress from their clients.
You can use justify-content: space-between
in .test
like so:
.test {_x000D_
display: flex;_x000D_
justify-content: space-between;_x000D_
width: 20rem;_x000D_
border: .1rem red solid;_x000D_
}
_x000D_
<div class="test">_x000D_
<button>test</button>_x000D_
<button>test</button>_x000D_
</div>
_x000D_
For those who want to use Bootstrap 4 can use justify-content-between
:
div {_x000D_
width: 20rem;_x000D_
border: .1rem red solid;_x000D_
}
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<div class="d-flex justify-content-between">_x000D_
<button>test</button>_x000D_
<button>test</button>_x000D_
</div>
_x000D_
iOS 8.0 introduces the layoutMargins property on cells AND table views.
This property isn't available on iOS 7.0 so you need to make sure you check before assigning it!
The easy fix is to subclass your cell and override the layout margins property as suggested by @user3570727. However you will lose any system behavior like inheriting margins from the Safe Area so I do not recommend the below solution:
(ObjectiveC)
-(UIEdgeInsets)layoutMargins {
return UIEdgeInsetsZero // override any margins inc. safe area
}
(swift 4.2):
override var layoutMargins: UIEdgeInsets { get { return .zero } set { } }
If you don't want to override the property, or need to set it conditionally, keep reading.
In addition to the layoutMargins
property, Apple has added a property to your cell that will prevent it from inheriting your Table View's margin settings. When this property is set, your cells are allowed to configure their own margins independently of the table view. Think of it as an override.
This property is called preservesSuperviewLayoutMargins
, and setting it to NO
will allow the cell's layoutMargin
setting to override whatever layoutMargin
is set on your TableView. It both saves time (you don't have to modify the Table View's settings), and is more concise. Please refer to Mike Abdullah's answer for a detailed explanation.
NOTE: what follows is a clean implementation for a cell-level margin setting, as expressed in Mike Abdullah's answer. Setting your cell's preservesSuperviewLayoutMargins=NO
will ensure that your Table View does not override the cell settings. If you actually want your entire table view to have consistent margins, please adjust your code accordingly.
Setup your cell margins:
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
// Remove seperator inset
if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
[cell setSeparatorInset:UIEdgeInsetsZero];
}
// Prevent the cell from inheriting the Table View's margin settings
if ([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]) {
[cell setPreservesSuperviewLayoutMargins:NO];
}
// Explictly set your cell's layout margins
if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
[cell setLayoutMargins:UIEdgeInsetsZero];
}
}
Swift 4:
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
// Remove seperator inset
if cell.responds(to: #selector(setter: UITableViewCell.separatorInset)) {
cell.separatorInset = .zero
}
// Prevent the cell from inheriting the Table View's margin settings
if cell.responds(to: #selector(setter: UITableViewCell.preservesSuperviewLayoutMargins)) {
cell.preservesSuperviewLayoutMargins = false
}
// Explictly set your cell's layout margins
if cell.responds(to: #selector(setter: UITableViewCell.layoutMargins)) {
cell.layoutMargins = .zero
}
}
Setting the preservesSuperviewLayoutMargins
property on your cell to NO should prevent your table view from overriding your cell margins. In some cases, it seems to not function properly.
If all fails, you may brute-force your Table View margins:
-(void)viewDidLayoutSubviews
{
[super viewDidLayoutSubviews];
// Force your tableview margins (this may be a bad idea)
if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
[self.tableView setSeparatorInset:UIEdgeInsetsZero];
}
if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
[self.tableView setLayoutMargins:UIEdgeInsetsZero];
}
}
Swift 4:
func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// Force your tableview margins (this may be a bad idea)
if tableView.responds(to: #selector(setter: UITableView.separatorInset)) {
tableView.separatorInset = .zero
}
if tableView.responds(to: #selector(setter: UITableView.layoutMargins)) {
tableView.layoutMargins = .zero
}
}
...and there you go! This should work on iOS 7 and 8.
EDIT: Mohamed Saleh brought to my attention a possible change in iOS 9. You may need to set the Table View's cellLayoutMarginsFollowReadableWidth
to NO
if you want to customize insets or margins. Your mileage may vary, this is not documented very well.
This property only exists in iOS 9 so be sure to check before setting.
if([myTableView respondsToSelector:@selector(setCellLayoutMarginsFollowReadableWidth:)])
{
myTableView.cellLayoutMarginsFollowReadableWidth = NO;
}
Swift 4:
if myTableView.responds(to: #selector(setter: self.cellLayoutMarginsFollowReadableWidth)) {
myTableView.cellLayoutMarginsFollowReadableWidth = false
}
(above code from iOS 8 UITableView separator inset 0 not working)
EDIT: Here's a pure Interface Builder approach:
NOTE: iOS 11 changes & simplifies much of this behavior, an update will be forthcoming...
Here's the Swift 3.0 update to peacetype's comment:
textField.addTarget(nil, action:Selector(("firstResponderAction:")), for:.editingDidEndOnExit)
git log origin/master..master
or, more generally:
git log <since>..<until>
You can use this with grep to check for a specific, known commit:
git log <since>..<until> | grep <commit-hash>
Or you can also use git-rev-list to search for a specific commit:
git rev-list origin/master | grep <commit-hash>
One area where I found mmap() to not be an advantage was when reading small files (under 16K). The overhead of page faulting to read the whole file was very high compared with just doing a single read() system call. This is because the kernel can sometimes satisify a read entirely in your time slice, meaning your code doesn't switch away. With a page fault, it seemed more likely that another program would be scheduled, making the file operation have a higher latency.
Considering you're on a feature branch and you want to check which files have changed compared to master... just this:
git diff --name-only master
The 2nd parameter in the get
call is a config object. You want something like this:
$http
.get('accept.php', {
params: {
source: link,
category_id: category
}
})
.success(function (data,status) {
$scope.info_show = data
});
See the Arguments section of http://docs.angularjs.org/api/ng.$http for more detail
If your are trying to do this for a user name that you cannot hard code, it can be challenging. Sure echo ~rbronosky
would tell you the path to my home dir /home/rbronosky
, but what if rbronosky is in a variable? If you do name=rbronosky; echo ~$name
you get ~rbronosky
Here is a real world case and the solution:
You have a script that the user has to run via sudo. The script has to access the user's home folder. You can't reference ~/.ssh
or else it will expand to /root/.ssh
. Instead you do:
# Up near the top of your script add
export HOME=$(bash <<< "echo ~${SUDO_USER:-}")
# Then you can use $HOME like you would expect
cat rsa_key.pub >> $HOME/.ssh/authorized_keys
The beauty of it is that if the script is not run as sudo then $SUDO_USER is empty, so it's basically the same thing as doing "echo ~". It still works as you' expect.
If you use set -o nounset
, which you should be using, the variable reference ${SUDO_USER:-}
will default to blank, where $SUDO_USER
or ${SUDO_USER}
would give an error (because it is unset) if not run via sudo
.
As of 10. July 2017, the issue of Bootstrap 4 support with bootstrap-select
is still open. In the open issue, there are some ad-hoc solutions which you could try with your project.
Or you could use a library like Select2 and add a theme to match Bootstrap 4. Here is an example: Select 2 with Bootstrap 4 (disclaimer: I'm not the author of this blog post and I haven't verified if this still works with the all versions of Bootstrap 4).
DEMO : https://jsfiddle.net/ipsjolly/xygr065w/
$(function(){
$("#submit").click(function(){
alert($('input:radio:checked').val());
});
});
You can call the indexer directly on the datatable variable as well:
var cellValue = dt[i].ColumnName
MSI is an installer file which installs your program on the executing system.
Setup.exe is an application (executable file) which has msi file(s) as its one of the resources. Executing Setup.exe will in turn execute msi (the installer) which writes your application to the system.
Edit (as suggested in comment): Setup executable files don't necessarily have an MSI resource internally
If you have properties specific to the view, and not related to the DB/Service/Data store, it is a good practice to use ViewModels. Say, you want to leave a checkbox selected based on a DB field (or two) but the DB field itself isn't a boolean. While it is possible to create these properties in the Model itself and keep it hidden from the binding to data, you may not want to clutter the Model depending on the amount of such fields and transactions.
If there are too few view-specific data and/or transformations, you can use the Model itself
You only need the async
pipe:
<li *ngFor="let afd of afdeling | async">
{{afd.patientid}}
</li>
always use the async
pipe when dealing with Observables directly without explicitly unsubscribe.
I had the same error but I am using Perforce version control. Here's how I fixed it.
Floating point numbers in C use IEEE 754 encoding.
This type of encoding uses a sign, a significand, and an exponent.
Because of this encoding, many numbers will have small changes to allow them to be stored.
Also, the number of significant digits can change slightly since it is a binary representation, not a decimal one.
Single precision (float) gives you 23 bits of significand, 8 bits of exponent, and 1 sign bit.
Double precision (double) gives you 52 bits of significand, 11 bits of exponent, and 1 sign bit.
What exactly is the structure of your HTML?
The previous CSS will work if the HTML is as such:
CSS
.foo:nth-child(2)
HTML
<div>
<div class="foo"></div>
<div class="foo">Find me</div>
...
</div>
But if you have the following HTML it will not work.
<div>
<div class="other"></div>
<div class="foo"></div>
<div class="foo">Find me</div>
...
</div>
Simple put, there is no selector for the getting the index of the matches from the rest of the selector before it.
It is a string formatting syntax (which it borrows from C).
Please see "PyFormat":
Python supports formatting values into strings. Although this can include very complicated expressions, the most basic usage is to insert values into a string with the
%s
placeholder.
Edit: Here is a really simple example:
#Python2
name = raw_input("who are you? ")
print "hello %s" % (name,)
#Python3+
name = input("who are you? ")
print("hello %s" % (name,))
The %s
token allows me to insert (and potentially format) a string. Notice that the %s
token is replaced by whatever I pass to the string after the %
symbol. Notice also that I am using a tuple here as well (when you only have one string using a tuple is optional) to illustrate that multiple strings can be inserted and formatted in one statement.
You can use this
lblTime.Text = DateTime.Now.TimeOfDay.ToString();
It is realtime with milliseconds value and it sets to time only.
Reading quickly through the source it seems that you're not far off. The following link should help (I did something similar but for FTP). For a file send from server to client, you start off with a file instance and an array of bytes. You then read the File into the byte array and write the byte array to the OutputStream which corresponds with the InputStream on the client's side.
http://www.rgagnon.com/javadetails/java-0542.html
Edit: Here's a working ultra-minimalistic file sender and receiver. Make sure you understand what the code is doing on both sides.
package filesendtest;
import java.io.*;
import java.net.*;
class TCPServer {
private final static String fileToSend = "C:\\test1.pdf";
public static void main(String args[]) {
while (true) {
ServerSocket welcomeSocket = null;
Socket connectionSocket = null;
BufferedOutputStream outToClient = null;
try {
welcomeSocket = new ServerSocket(3248);
connectionSocket = welcomeSocket.accept();
outToClient = new BufferedOutputStream(connectionSocket.getOutputStream());
} catch (IOException ex) {
// Do exception handling
}
if (outToClient != null) {
File myFile = new File( fileToSend );
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = null;
try {
fis = new FileInputStream(myFile);
} catch (FileNotFoundException ex) {
// Do exception handling
}
BufferedInputStream bis = new BufferedInputStream(fis);
try {
bis.read(mybytearray, 0, mybytearray.length);
outToClient.write(mybytearray, 0, mybytearray.length);
outToClient.flush();
outToClient.close();
connectionSocket.close();
// File sent, exit the main method
return;
} catch (IOException ex) {
// Do exception handling
}
}
}
}
}
package filesendtest;
import java.io.*;
import java.io.ByteArrayOutputStream;
import java.net.*;
class TCPClient {
private final static String serverIP = "127.0.0.1";
private final static int serverPort = 3248;
private final static String fileOutput = "C:\\testout.pdf";
public static void main(String args[]) {
byte[] aByte = new byte[1];
int bytesRead;
Socket clientSocket = null;
InputStream is = null;
try {
clientSocket = new Socket( serverIP , serverPort );
is = clientSocket.getInputStream();
} catch (IOException ex) {
// Do exception handling
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (is != null) {
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
fos = new FileOutputStream( fileOutput );
bos = new BufferedOutputStream(fos);
bytesRead = is.read(aByte, 0, aByte.length);
do {
baos.write(aByte);
bytesRead = is.read(aByte);
} while (bytesRead != -1);
bos.write(baos.toByteArray());
bos.flush();
bos.close();
clientSocket.close();
} catch (IOException ex) {
// Do exception handling
}
}
}
}
Related
Byte array of unknown length in java
Edit: The following could be used to fingerprint small files before and after transfer (use SHA if you feel it's necessary):
public static String md5String(File file) {
try {
InputStream fin = new FileInputStream(file);
java.security.MessageDigest md5er = MessageDigest.getInstance("MD5");
byte[] buffer = new byte[1024];
int read;
do {
read = fin.read(buffer);
if (read > 0) {
md5er.update(buffer, 0, read);
}
} while (read != -1);
fin.close();
byte[] digest = md5er.digest();
if (digest == null) {
return null;
}
String strDigest = "0x";
for (int i = 0; i < digest.length; i++) {
strDigest += Integer.toString((digest[i] & 0xff)
+ 0x100, 16).substring(1).toUpperCase();
}
return strDigest;
} catch (Exception e) {
return null;
}
}
You can also check the default buffer size by calling the read only DEFAULT_BUFFER_SIZE attribute from io module.
import io
print (io.DEFAULT_BUFFER_SIZE)
Use git ls-remote git://github.com/<user>/<project>.git
. For example, my trac-backlog project gives:
:: git ls-remote git://github.com/jszakmeister/trac-backlog.git
5d6a3c973c254378738bdbc85d72f14aefa316a0 HEAD
4652257768acef90b9af560295b02d0ac6e7702c refs/heads/0.1.x
35af07bc99c7527b84e11a8632bfb396823326f3 refs/heads/0.2.x
5d6a3c973c254378738bdbc85d72f14aefa316a0 refs/heads/master
520dcebff52506682d6822ade0188d4622eb41d1 refs/pull/11/head
6b2c1ed650a7ff693ecd8ab1cb5c124ba32866a2 refs/pull/11/merge
51088b60d66b68a565080eb56dbbc5f8c97c1400 refs/pull/12/head
127c468826c0c77e26a5da4d40ae3a61e00c0726 refs/pull/12/merge
2401b5537224fe4176f2a134ee93005a6263cf24 refs/pull/15/head
8aa9aedc0e3a0d43ddfeaf0b971d0ae3a23d57b3 refs/pull/15/merge
d96aed93c94f97d328fc57588e61a7ec52a05c69 refs/pull/7/head
f7c1e8dabdbeca9f9060de24da4560abc76e77cd refs/pull/7/merge
aa8a935f084a6e1c66aa939b47b9a5567c4e25f5 refs/pull/8/head
cd258b82cc499d84165ea8d7a23faa46f0f2f125 refs/pull/8/merge
c10a73a8b0c1809fcb3a1f49bdc1a6487927483d refs/tags/0.1.0
a39dad9a1268f7df256ba78f1166308563544af1 refs/tags/0.2.0
2d559cf785816afd69c3cb768413c4f6ca574708 refs/tags/0.2.1
434170523d5f8aad05dc5cf86c2a326908cf3f57 refs/tags/0.2.2
d2dfe40cb78ddc66e6865dcd2e76d6bc2291d44c refs/tags/0.3.0
9db35263a15dcdfbc19ed0a1f7a9e29a40507070 refs/tags/0.3.0^{}
Just grep for the one you need and cut it out:
:: git ls-remote git://github.com/jszakmeister/trac-backlog.git | \
grep refs/heads/master | cut -f 1
5d6a3c973c254378738bdbc85d72f14aefa316a0
Or, you can specify which refs you want on the command line and avoid the grep with:
:: git ls-remote git://github.com/jszakmeister/trac-backlog.git refs/heads/master | \
cut -f 1
5d6a3c973c254378738bdbc85d72f14aefa316a0
Note: it doesn't have to be the git://
URL. It could be https://
or [email protected]:
too.
Originally, this was geared towards finding out the latest commit of a remote branch (not just from your last fetch, but the actual latest commit in the branch on the remote repository). If you need the commit hash for something locally, the best answer is:
git rev-parse branch-name
It's fast, easy, and a single command. If you want the commit hash for the current branch, you can look at HEAD:
git rev-parse HEAD
I had a similar problem, when I wanted to create a command, \dx
, to abbreviate \;\mathrm{d}x
(i.e. put an extra space before the differential of the integral and have the "d" upright as well). But then I also wanted to make it flexible enough to include the variable of integration as an optional argument. I put the following code in the preamble.
\usepackage{ifthen}
\newcommand{\dx}[1][]{%
\ifthenelse{ \equal{#1}{} }
{\ensuremath{\;\mathrm{d}x}}
{\ensuremath{\;\mathrm{d}#1}}
}
Then
\begin{document}
$$\int x\dx$$
$$\int t\dx[t]$$
\end{document}
I have use @Mirko N. answser using made the new Custom EditText
public class EditViewCustom extends EditText {
Button cancelBtn;
RelativeLayout titleReleLayout;
public EditViewCustom(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public EditViewCustom(Context context, AttributeSet attrs) {
super(context, attrs);
}
public EditViewCustom(Context context) {
super(context);
}
public void setViews(Button cancelBtn,RelativeLayout titleReleLayout){
this.cancelBtn = cancelBtn;
this.titleReleLayout = titleReleLayout;
}
@Override
public boolean onKeyPreIme(int keyCode, KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
Log.d("KEYCODE_BACK","KEYCODE_BACK");
cancelBtn.setVisibility(View.GONE);
this.setFocusableInTouchMode(false);
this.setFocusable(false);
titleReleLayout.setVisibility(View.VISIBLE);
return super.onKeyPreIme(keyCode, event);
}
return super.onKeyPreIme(keyCode, event);
}
}
Then set data from your activity
searchEditView.setViews(cancelBtn, titleRelativeLayout);
Thank you.
None of the answers will solve your problem permanently. If you go to the path of adding XSD (From Xml menu, select "Create schema"), you will end up having problems with the package manager as it will clean up your packages.config file when you add a new package.
The best solution is just ignore by closing the file when you don't use it.
As @impulsgraw wrote. You need to check for undefined after the pipes:
<div ng-show="foo || undefined">
Show this if foo is defined!
</div>
<div ng-show="boo || !undefined">
Show this if boo is undefined!
</div>
I had this error after fresh Oracle installation.
To fix this I've launched Net configuration assistant (from start menu or netca.bat in the bin folder) and simply added a Listener.
You need to close all your connexions for example: If you make an INSERT INTO statement you need to close the statement and your connexion in this way:
statement.close();
Connexion.close():
And if you make a SELECT statement you need to close the statement, the connexion and the resultset in this way:
resultset.close();
statement.close();
Connexion.close();
I did this and it worked
With C#6.0 you also have a new way of formatting date when using string interpolation e.g.
$"{DateTime.Now:yyyy-MM-dd HH:mm:ss}"
Can't say its any better, but it is slightly cleaner if including the formatted DateTime in a longer string.
you can still use
String Item = getIntent().getExtras().getString("name");
in the fragment
, you just need call getActivity()
first:
String Item = getActivity().getIntent().getExtras().getString("name");
This saves you having to write some code.
Here is the reason why it happens, i.e. your local directory in the host OS where you are running the docker should have the file, otherwise you get this error
One solution is to :
use RUN cp <src> <dst>
instead of
COPY <src> <dst>
then run the command it works!
You could also use React's useState
hook to declare local state for a function component. The initial state of the variable toggled
has been passed as an argument to the method .useState
.
import { render } from 'react-dom';
import React from "react";
type Props = {
text: string,
onClick(event: React.MouseEvent<HTMLButtonElement>): void,
};
export function HelloWorldButton(props: Props) {
const [toggled, setToggled] = React.useState(false); // returns a stateful value, and a function to update it
return <button
onClick={(event) => {
setToggled(!toggled);
props.onClick(event);
}}
>{props.text} (toggled: {toggled.toString()})</button>;
}
render(<HelloWorldButton text='Hello World' onClick={() => console.log('clicked!')} />, document.getElementById('root'));
It sounds like some of your styles are being reset.
By default in most browsers, ul
s and ol
s have margin
and padding
added to them.
You can override this (and many do) by adding a line to your css like so
ul, ol { //THERE MAY BE OTHER ELEMENTS IN THE LIST
margin:0;
padding:0;
}
In this case, you would remove the element from this list or add a margin
/padding
back, like so
ul{
margin:1em;
}
I encountered difficulties with Roi-Kyi Bryant's solution when multiple add-ins tried to modify the ribbon. I also don't have admin access on my work-computer, which ruled out installing the Custom UI Editor
. So, if you're in the same boat as me, here's an alternative example to customising the ribbon using only Excel. Note, my solution is derived from the Microsoft guide.
.xlam
files, Chart Tools.xlam
and Priveleged UDFs.xlam
, to demonstrate how multiple add-ins can interact with the Ribbon. customUI
and _rels
folder.customUI
folder, create a customUI.xml
file. The customUI.xml
file details how Excel files interact with the ribbon. Part 2 of the Microsoft guide covers the elements in the customUI.xml
file.My customUI.xml
file for Chart Tools.xlam
looks like this
<customUI xmlns="http://schemas.microsoft.com/office/2006/01/customui" xmlns:x="sao">
<ribbon>
<tabs>
<tab idQ="x:chartToolsTab" label="Chart Tools">
<group id="relativeChartMovementGroup" label="Relative Chart Movement" >
<button id="moveChartWithRelativeLinksButton" label="Copy and Move" imageMso="ResultsPaneStartFindAndReplace" onAction="MoveChartWithRelativeLinksCallBack" visible="true" size="normal"/>
<button id="moveChartToManySheetsWithRelativeLinksButton" label="Copy and Distribute" imageMso="OutlineDemoteToBodyText" onAction="MoveChartToManySheetsWithRelativeLinksCallBack" visible="true" size="normal"/>
</group >
<group id="chartDeletionGroup" label="Chart Deletion">
<button id="deleteAllChartsInWorkbookSharingAnAddressButton" label="Delete Charts" imageMso="CancelRequest" onAction="DeleteAllChartsInWorkbookSharingAnAddressCallBack" visible="true" size="normal"/>
</group>
</tab>
</tabs>
</ribbon>
</customUI>
My customUI.xml
file for Priveleged UDFs.xlam
looks like this
<customUI xmlns="http://schemas.microsoft.com/office/2006/01/customui" xmlns:x="sao">
<ribbon>
<tabs>
<tab idQ="x:privelgedUDFsTab" label="Privelged UDFs">
<group id="privelgedUDFsGroup" label="Toggle" >
<button id="initialisePrivelegedUDFsButton" label="Activate" imageMso="TagMarkComplete" onAction="InitialisePrivelegedUDFsCallBack" visible="true" size="normal"/>
<button id="deInitialisePrivelegedUDFsButton" label="De-Activate" imageMso="CancelRequest" onAction="DeInitialisePrivelegedUDFsCallBack" visible="true" size="normal"/>
</group >
</tab>
</tabs>
</ribbon>
</customUI>
.zip
to their file name. In my case, I renamed Chart Tools.xlam
to Chart Tools.xlam.zip
, and Privelged UDFs.xlam
to Priveleged UDFs.xlam.zip
..zip
file, and navigate to the _rels
folder. Copy the .rels
file to the _rels
folder you created in Step 3. Edit each .rels
file with a text editor. From the Microsoft guideBetween the final
<Relationship>
element and the closing<Relationships>
element, add a line that creates a relationship between the document file and the customization file. Ensure that you specify the folder and file names correctly.
<Relationship Type="http://schemas.microsoft.com/office/2006/
relationships/ui/extensibility" Target="/customUI/customUI.xml"
Id="customUIRelID" />
My .rels
file for Chart Tools.xlam
looks like this
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
<Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties" Target="docProps/app.xml"/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="docProps/core.xml"/>
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/>
<Relationship Type="http://schemas.microsoft.com/office/2006/relationships/ui/extensibility" Target="/customUI/customUI.xml" Id="chartToolsCustomUIRel" />
</Relationships>
My .rels
file for Priveleged UDFs
looks like this.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
<Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties" Target="docProps/app.xml"/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="docProps/core.xml"/>
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/>
<Relationship Type="http://schemas.microsoft.com/office/2006/relationships/ui/extensibility" Target="/customUI/customUI.xml" Id="privelegedUDFsCustomUIRel" />
</Relationships>
.rels
files in each .zip
file with the .rels
file/files you modified in the previous step..customUI
folder you created into the home directory of the .zip
file/files..zip
file extension from the Excel files you created..xlam
files, back in Excel, add them to your Excel add-ins.onAction
keywords in my buttons. The onAction
keyword indicates that, when the containing element is triggered, the Excel application will trigger the sub-routine encased in quotation marks directly after the onAction
keyword. This is known as a callback. In my .xlam
files, I have a module called CallBacks
where I've included my callback sub-routines.My CallBacks
module for Chart Tools.xlam
looks like
Option Explicit
Public Sub MoveChartWithRelativeLinksCallBack(ByRef control As IRibbonControl)
MoveChartWithRelativeLinks
End Sub
Public Sub MoveChartToManySheetsWithRelativeLinksCallBack(ByRef control As IRibbonControl)
MoveChartToManySheetsWithRelativeLinks
End Sub
Public Sub DeleteAllChartsInWorkbookSharingAnAddressCallBack(ByRef control As IRibbonControl)
DeleteAllChartsInWorkbookSharingAnAddress
End Sub
My CallBacks
module for Priveleged UDFs.xlam
looks like
Option Explicit
Public Sub InitialisePrivelegedUDFsCallBack(ByRef control As IRibbonControl)
ThisWorkbook.InitialisePrivelegedUDFs
End Sub
Public Sub DeInitialisePrivelegedUDFsCallBack(ByRef control As IRibbonControl)
ThisWorkbook.DeInitialisePrivelegedUDFs
End Sub
Different elements have a different callback sub-routine signature. For buttons, the required sub-routine parameter is ByRef control As IRibbonControl
. If you don't conform to the required callback signature, you will receive an error while compiling your VBA project/projects. Part 3 of the Microsoft guide defines all the callback signatures.
Here's what my finished example looks like
Some closing tips
idQ
and xlmns:
keyword. In my example, the Chart Tools.xlam
and Priveleged UDFs.xlam
both have access to the elements with idQ
's equal to x:chartToolsTab
and x:privelgedUDFsTab
. For this to work, the x:
is required, and, I've defined its namespace in the first line of my customUI.xml
file, <customUI xmlns="http://schemas.microsoft.com/office/2006/01/customui" xmlns:x="sao">
. The section Two Ways to Customize the Fluent UI in the Microsoft guide gives some more details.isMSO
keyword. The section Two Ways to Customize the Fluent UI in the Microsoft guide gives some more details.Cast from string using float()
:
>>> float('NaN')
nan
>>> float('Inf')
inf
>>> -float('Inf')
-inf
>>> float('Inf') == float('Inf')
True
>>> float('Inf') == 1
False
The WPF equivalent would be the System.Windows.MessageBox
. It has a quite similar interface, but uses other enumerations for parameters and return value.
For me, I defined column type as BIT (e.g. "boolean")
When I tried to set column value "1" via UI (Workbench), I was getting a "Data too long for column" error.
Turns out that there is a special syntax for setting BIT values, which is:
b'1'
Or if you already have the data in a list and prefer the other Linq format :)
List<string> uids = new List<string>(){"1", "45", "20", "10"};
List<user> table = GetDataFromSomewhere();
List<user> newTable = table.Where(xx => uids.Contains(xx.uid)).ToList();
extension UIImage {
enum ContentMode {
case contentFill
case contentAspectFill
case contentAspectFit
}
func resize(withSize size: CGSize, contentMode: ContentMode = .contentAspectFill) -> UIImage? {
let aspectWidth = size.width / self.size.width
let aspectHeight = size.height / self.size.height
switch contentMode {
case .contentFill:
return resize(withSize: size)
case .contentAspectFit:
let aspectRatio = min(aspectWidth, aspectHeight)
return resize(withSize: CGSize(width: self.size.width * aspectRatio, height: self.size.height * aspectRatio))
case .contentAspectFill:
let aspectRatio = max(aspectWidth, aspectHeight)
return resize(withSize: CGSize(width: self.size.width * aspectRatio, height: self.size.height * aspectRatio))
}
}
private func resize(withSize size: CGSize) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(size, false, self.scale)
defer { UIGraphicsEndImageContext() }
draw(in: CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height))
return UIGraphicsGetImageFromCurrentImageContext()
}
}
and to use you can do the following:
let image = UIImage(named: "image.png")!
let newImage = image.resize(withSize: CGSize(width: 200, height: 150), contentMode: .contentAspectFill)
Thanks to abdullahselek for his original solution.
I have discovered that you cannot have conditionals outside of the stored procedure in mysql. This is why the syntax error. As soon as I put the code that I needed between
BEGIN
SELECT MONTH(CURDATE()) INTO @curmonth;
SELECT MONTHNAME(CURDATE()) INTO @curmonthname;
SELECT DAY(LAST_DAY(CURDATE())) INTO @totaldays;
SELECT FIRST_DAY(CURDATE()) INTO @checkweekday;
SELECT DAY(@checkweekday) INTO @checkday;
SET @daycount = 0;
SET @workdays = 0;
WHILE(@daycount < @totaldays) DO
IF (WEEKDAY(@checkweekday) < 5) THEN
SET @workdays = @workdays+1;
END IF;
SET @daycount = @daycount+1;
SELECT ADDDATE(@checkweekday, INTERVAL 1 DAY) INTO @checkweekday;
END WHILE;
END
Just for others:
If you are not sure how to create a routine in phpmyadmin you can put this in the SQL query
delimiter ;;
drop procedure if exists test2;;
create procedure test2()
begin
select ‘Hello World’;
end
;;
Run the query. This will create a stored procedure or stored routine named test2. Now go to the routines tab and edit the stored procedure to be what you want. I also suggest reading http://net.tutsplus.com/tutorials/an-introduction-to-stored-procedures/ if you are beginning with stored procedures.
The first_day function you need is: How to get first day of every corresponding month in mysql?
Showing the Procedure is working Simply add the following line below END WHILE and above END
SELECT @curmonth,@curmonthname,@totaldays,@daycount,@workdays,@checkweekday,@checkday;
Then use the following code in the SQL Query Window.
call test2 /* or whatever you changed the name of the stored procedure to */
NOTE: If you use this please keep in mind that this code does not take in to account nationally observed holidays (or any holidays for that matter).
Use FromResult Method
public async Task<string> GetString()
{
System.Threading.Thread.Sleep(5000);
return await Task.FromResult("Hello");
}
If you are already connected, simply type this in the javascript console:
FB.getAuthResponse()['accessToken']
Shouldn't this also work for Rails?
"30/Nov/2009 16:29:30 +0100".to_datetime
a = np.array([1,2,3])
b = np.array([4,5,6])
np.array((a,b))
works just as well as
np.array([[1,2,3], [4,5,6]])
Regardless of whether it is a list of lists or a list of 1d arrays, np.array
tries to create a 2d array.
But it's also a good idea to understand how np.concatenate
and its family of stack
functions work. In this context concatenate
needs a list of 2d arrays (or any anything that np.array
will turn into a 2d array) as inputs.
np.vstack
first loops though the inputs making sure they are at least 2d, then does concatenate. Functionally it's the same as expanding the dimensions of the arrays yourself.
np.stack
is a new function that joins the arrays on a new dimension. Default behaves just like np.array
.
Look at the code for these functions. If written in Python you can learn quite a bit. For vstack
:
return _nx.concatenate([atleast_2d(_m) for _m in tup], 0)
You are setting the extra with an array. You are then trying to get a single int.
Your code should be:
int[] arrayB = extras.getIntArray("numbers");
You can include the user and password as part of the URL:
http://user:[email protected]/index.html
see this URL, for more
HTTP Basic Authentication credentials passed in URL and encryption
of course, you'll need the username password, it's not 'Basic hashstring
.
hope this helps...
Sku is an int, can't be defaulted to string "sku". Please check Optional URI Parameters and Default Values
scope: false
transclude: false
and you will have the same scope(with parent element)
$scope.$watch(...
There are a lot of ways how to access parent scope depending on this two options scope& transclude.
function urlExists($url=NULL)
{
if($url == NULL) return false;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if($httpcode>=200 && $httpcode<300){
return true;
} else {
return false;
}
}
This was grabbed from this post on how to check if a URL exists. Because Twitter should provide an error message above 300 when it is in maintenance, or a 404, this should work perfectly.
For personal teams
grep DEVELOPMENT_TEAM MyProject.xcodeproj/project.pbxproj
should give you the team ID
DEVELOPMENT_TEAM = ZU88ND8437;
New-style classes are ones that subclass "object" (directly or indirectly). They have a __new__
class method in addition to __init__
and have somewhat more rational low-level behavior.
Usually, you'll want to override __getattr__
(if you're overriding either), otherwise you'll have a hard time supporting "self.foo" syntax within your methods.
Extra info: http://www.devx.com/opensource/Article/31482/0/page/4
look for param type
Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers.
Try like below,
$('input[type=text]').val (function () {
return this.value.toUpperCase();
})
You should use input[type=text]
instead of :input
or input
as I believe your intention are to operate on textbox only.
If you're using .NET, in the solutions explorer right click your program and select properties. Under the resource section select Icon and manifest, then browse to the location of your icon.
It doesn't look like you can do this with a single command, but here's the closest thing to it that I could find.
think of FINAL as the "End of the line" - that guy cannot produce offspring anymore. So when you see it this way, there are ton of real world scenarios that you will come across that requires you to flag an 'end of line' marker to the class. It is Domain Driven Design - if your domain demands that a given ENTITY (class) cannot create sub-classes, then mark it as FINAL.
I should note that there is nothing stopping you from inheriting a "should be tagged as final" class. But that is generally classified as "abuse of inheritance", and done because most often you would like to inherit some function from the base class in your class.
The best approach is to look at the domain and let it dictate your design decisions.
Use the border-spacing
property on the table
element to set the spacing between cells.
Make sure border-collapse
is set to separate
(or there will be a single border between each cell instead of a separate border around each one that can have spacing between them).
$getyear = explode("-", $value['users_dob']);
$dob = date('Y') - $getyear[0];
$value['users_dob']
is the database value with format yyyy-mm-dd
I had an issue using this in a user control (in a page this worked fine); the Button1 is inside an updatepanel
, and the scriptmanager
is on the usercontrol
.
protected void Button1_Click(object sender, EventArgs e)
{
string scriptstring = "alert('Welcome');";
ScriptManager.RegisterStartupScript(this, this.GetType(), "alertscript", scriptstring, true);
}
Now it seems you have to be careful with the first two arguments, they need to reference your page, not your control
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "alertscript", scriptstring, true);
The best way to do this is avoid base *apply
functions, which coerces the entire data frame to an array, possibly losing information.
If you wanted to apply a function as.numeric
to every column, a simple way is using mutate_all
from dplyr:
t %>% mutate_all(as.numeric)
Alternatively use colwise
from plyr, which will "turn a function that operates on a vector into a function that operates column-wise on a data.frame."
t %>% (colwise(as.numeric))
In the special case of reading in a data table of character vectors and coercing columns into the correct data type, use type.convert
or type_convert
from readr.
Less interesting answer: we can apply on each column with a for-loop:
for (i in 1:nrow(t)) { t[, i] <- parse_guess(t[, i]) }
I don't know of a good way of doing assignment with *apply while preserving data frame structure.
I personally use Style It for inline-style in React or keep my style separately in a CSS or SASS file...
But if you are really interested doing it inline, look at the library, I share some of the usages below:
In the component:
import React from 'react';
import Style from 'style-it';
class Intro extends React.Component {
render() {
return (
<Style>
{`
.intro {
font-size: 40px;
}
`}
<p className="intro">CSS-in-JS made simple -- just Style It.</p>
</Style>
);
}
}
export default Intro;
Output:
<p class="intro _scoped-1">
<style type="text/css">
._scoped-1.intro {
font-size: 40px;
}
</style>
CSS-in-JS made simple -- just Style It.
</p>
Also you can use JavaScript variables with hover in your CSS as below :
import React from 'react';
import Style from 'style-it';
class Intro extends React.Component {
render() {
const fontSize = 13;
return Style.it(`
.intro {
font-size: ${ fontSize }px; // ES2015 & ES6 Template Literal string interpolation
}
.package {
color: blue;
}
.package:hover {
color: aqua;
}
`,
<p className="intro">CSS-in-JS made simple -- just Style It.</p>
);
}
}
export default Intro;
And the result as below:
<p class="intro _scoped-1">
<style type="text/css">
._scoped-1.intro {
font-size: 13px;
}
._scoped-1 .package {
color: blue;
}
._scoped-1 .package:hover {
color: aqua;
}
</style>
CSS-in-JS made simple -- just Style It.
</p>
github adds a reference to the commit if it contains #issuenbr (discovered this by chance).
Try
$query = mysql_query("SELECT * FROM users WHERE name = 'Admin' ")or die(mysql_error());
and check if this throw any error.
Then use while($rows = mysql_fetch_assoc($query)):
And finally display it as
echo $name . "<br/>" . $address . "<br/>" . $email . "<br/>" . $subject . "<br/>" . $comment . "<br/><br/>" . ;
Do not user mysql_*
as its deprecated.
In .ts :
today: Date;
constructor() {
this.today =new Date();
}
.html:
<input type="date"
[ngModel]="today | date:'yyyy-MM-dd'"
(ngModelChange)="today = $event"
name="dt"
class="form-control form-control-rounded" #searchDate
>
I had a similar issue. I resolved it by changing
<basicHttpBinding>
to
<basicHttpsBinding>
and also changed my URL to use https:// instead of http://.
Also in <endpoint> node, change
binding="basicHttpBinding"
to
binding="basicHttpsBinding"
This worked.
change your output from
echo '<script language="javascript>';
to
echo '<script type="text/javascript">';
you forgot double quotes... and use the type tag
Answer above did not work for me on Chrome. The change event was been fired after I clicked out of the field somewhere, which did not help because the datepicker window is also closed too when you click out of the field.
I did use this code and it worked pretty well. You can place it after calling .datepicker();
HTML
<input type="text" class="datepicker-input" placeholder="click to show datepicker" />
JavaScript
$(".datepicker-input").each(function() {
$(this).datepicker();
});
$(".datepicker-input").click(function() {
$(".datepicker-days .day").click(function() {
$('.datepicker').hide();
});
});
Ok. I found problem.
It was not on the Angular side. To be honest, there were no problem at all.
Reason why I was unable to perform my request succesfuly was that my server app was not properly handling OPTIONS request.
Why OPTIONS, not POST? My server app is on different host, then frontend. Because of CORS my browser was converting POST to OPTION: http://restlet.com/blog/2015/12/15/understanding-and-using-cors/
With help of this answer: Standalone Spring OAuth2 JWT Authorization Server + CORS
I implemented proper filter on my server-side app.
Thanks to @Supamiu - the person which fingered me that I am not sending POST at all.
There isn't a plain CSS method for this. You might have to go with JavaScript + Regex to pop in a span.
Ideally, there would be a pseudo-element for first-word, but you're out of luck as that doesn't appear to work. We do have :first-letter and :first-line.
You might be able to use a combination of :after or :before to get at it without using a span.
You should run:
composer dump-autoload
and if does not work you should:
re-install composer
You can try this if you want to override
var newArray= [444,555,666];
var oldArray =[11,22,33];
oldArray.forEach((name, index) => oldArray [index] = newArray[index]);
console.log(newArray);
I think the answers are below
List<string> aa = (from char c in source
select c.ToString() ).ToList();
List<string> aa2 = (from char c1 in source
from char c2 in source
select string.Concat(c1, ".", c2)).ToList();
If you have fixed the conflicts you need to add the files to the stage with git add [filename]
, then commit as normal.
I have found a nice way around it:
// The test, BDD style
it ("unsupported site", () => {
The.function(myFunc)
.with.arguments({url:"https://www.ebay.com/"})
.should.throw(/unsupported/);
});
// The function that does the magic: (lang:TypeScript)
export const The = {
'function': (func:Function) => ({
'with': ({
'arguments': function (...args:any) {
return () => func(...args);
}
})
})
};
It's much more readable then my old version:
it ("unsupported site", () => {
const args = {url:"https://www.ebay.com/"}; //Arrange
function check_unsupported_site() { myFunc(args) } //Act
check_unsupported_site.should.throw(/unsupported/) //Assert
});
There are two primary ways that pandas makes selections from a DataFrame.
The documentation uses the term position for referring to integer location. I do not like this terminology as I feel it is confusing. Integer location is more descriptive and is exactly what .iloc
stands for. The key word here is INTEGER - you must use integers when selecting by integer location.
Before showing the summary let's all make sure that ...
There are three primary indexers for pandas. We have the indexing operator itself (the brackets []
), .loc
, and .iloc
. Let's summarize them:
[]
- Primarily selects subsets of columns, but can select rows as well. Cannot simultaneously select rows and columns..loc
- selects subsets of rows and columns by label only.iloc
- selects subsets of rows and columns by integer location onlyI almost never use .at
or .iat
as they add no additional functionality and with just a small performance increase. I would discourage their use unless you have a very time-sensitive application. Regardless, we have their summary:
.at
selects a single scalar value in the DataFrame by label only.iat
selects a single scalar value in the DataFrame by integer location onlyIn addition to selection by label and integer location, boolean selection also known as boolean indexing exists.
.loc
, .iloc
, boolean selection and .at
and .iat
are shown belowWe will first focus on the differences between .loc
and .iloc
. Before we talk about the differences, it is important to understand that DataFrames have labels that help identify each column and each row. Let's take a look at a sample DataFrame:
df = pd.DataFrame({'age':[30, 2, 12, 4, 32, 33, 69],
'color':['blue', 'green', 'red', 'white', 'gray', 'black', 'red'],
'food':['Steak', 'Lamb', 'Mango', 'Apple', 'Cheese', 'Melon', 'Beans'],
'height':[165, 70, 120, 80, 180, 172, 150],
'score':[4.6, 8.3, 9.0, 3.3, 1.8, 9.5, 2.2],
'state':['NY', 'TX', 'FL', 'AL', 'AK', 'TX', 'TX']
},
index=['Jane', 'Nick', 'Aaron', 'Penelope', 'Dean', 'Christina', 'Cornelia'])
All the words in bold are the labels. The labels, age
, color
, food
, height
, score
and state
are used for the columns. The other labels, Jane
, Nick
, Aaron
, Penelope
, Dean
, Christina
, Cornelia
are used as labels for the rows. Collectively, these row labels are known as the index.
The primary ways to select particular rows in a DataFrame are with the .loc
and .iloc
indexers. Each of these indexers can also be used to simultaneously select columns but it is easier to just focus on rows for now. Also, each of the indexers use a set of brackets that immediately follow their name to make their selections.
We will first talk about the .loc
indexer which only selects data by the index or column labels. In our sample DataFrame, we have provided meaningful names as values for the index. Many DataFrames will not have any meaningful names and will instead, default to just the integers from 0 to n-1, where n is the length(number of rows) of the DataFrame.
There are many different inputs you can use for .loc
three out of them are
Selecting a single row with .loc with a string
To select a single row of data, place the index label inside of the brackets following .loc
.
df.loc['Penelope']
This returns the row of data as a Series
age 4
color white
food Apple
height 80
score 3.3
state AL
Name: Penelope, dtype: object
Selecting multiple rows with .loc with a list of strings
df.loc[['Cornelia', 'Jane', 'Dean']]
This returns a DataFrame with the rows in the order specified in the list:
Selecting multiple rows with .loc with slice notation
Slice notation is defined by a start, stop and step values. When slicing by label, pandas includes the stop value in the return. The following slices from Aaron to Dean, inclusive. Its step size is not explicitly defined but defaulted to 1.
df.loc['Aaron':'Dean']
Complex slices can be taken in the same manner as Python lists.
Let's now turn to .iloc
. Every row and column of data in a DataFrame has an integer location that defines it. This is in addition to the label that is visually displayed in the output. The integer location is simply the number of rows/columns from the top/left beginning at 0.
There are many different inputs you can use for .iloc
three out of them are
Selecting a single row with .iloc with an integer
df.iloc[4]
This returns the 5th row (integer location 4) as a Series
age 32
color gray
food Cheese
height 180
score 1.8
state AK
Name: Dean, dtype: object
Selecting multiple rows with .iloc with a list of integers
df.iloc[[2, -2]]
This returns a DataFrame of the third and second to last rows:
Selecting multiple rows with .iloc with slice notation
df.iloc[:5:3]
One excellent ability of both .loc/.iloc
is their ability to select both rows and columns simultaneously. In the examples above, all the columns were returned from each selection. We can choose columns with the same types of inputs as we do for rows. We simply need to separate the row and column selection with a comma.
For example, we can select rows Jane, and Dean with just the columns height, score and state like this:
df.loc[['Jane', 'Dean'], 'height':]
This uses a list of labels for the rows and slice notation for the columns
We can naturally do similar operations with .iloc
using only integers.
df.iloc[[1,4], 2]
Nick Lamb
Dean Cheese
Name: food, dtype: object
.ix
was used to make selections simultaneously with labels and integer location which was useful but confusing and ambiguous at times and thankfully it has been deprecated. In the event that you need to make a selection with a mix of labels and integer locations, you will have to make both your selections labels or integer locations.
For instance, if we want to select rows Nick
and Cornelia
along with columns 2 and 4, we could use .loc
by converting the integers to labels with the following:
col_names = df.columns[[2, 4]]
df.loc[['Nick', 'Cornelia'], col_names]
Or alternatively, convert the index labels to integers with the get_loc
index method.
labels = ['Nick', 'Cornelia']
index_ints = [df.index.get_loc(label) for label in labels]
df.iloc[index_ints, [2, 4]]
The .loc indexer can also do boolean selection. For instance, if we are interested in finding all the rows where age is above 30 and return just the food
and score
columns we can do the following:
df.loc[df['age'] > 30, ['food', 'score']]
You can replicate this with .iloc
but you cannot pass it a boolean series. You must convert the boolean Series into a numpy array like this:
df.iloc[(df['age'] > 30).values, [2, 4]]
It is possible to use .loc/.iloc
for just column selection. You can select all the rows by using a colon like this:
df.loc[:, 'color':'score':2]
[]
, can slice can select rows and columns too but not simultaneously.Most people are familiar with the primary purpose of the DataFrame indexing operator, which is to select columns. A string selects a single column as a Series and a list of strings selects multiple columns as a DataFrame.
df['food']
Jane Steak
Nick Lamb
Aaron Mango
Penelope Apple
Dean Cheese
Christina Melon
Cornelia Beans
Name: food, dtype: object
Using a list selects multiple columns
df[['food', 'score']]
What people are less familiar with, is that, when slice notation is used, then selection happens by row labels or by integer location. This is very confusing and something that I almost never use but it does work.
df['Penelope':'Christina'] # slice rows by label
df[2:6:2] # slice rows by integer location
The explicitness of .loc/.iloc
for selecting rows is highly preferred. The indexing operator alone is unable to select rows and columns simultaneously.
df[3:5, 'color']
TypeError: unhashable type: 'slice'
.at
and .iat
Selection with .at
is nearly identical to .loc
but it only selects a single 'cell' in your DataFrame. We usually refer to this cell as a scalar value. To use .at
, pass it both a row and column label separated by a comma.
df.at['Christina', 'color']
'black'
Selection with .iat
is nearly identical to .iloc
but it only selects a single scalar value. You must pass it an integer for both the row and column locations
df.iat[2, 5]
'FL'
This is my solution, wish useful for you:
public class Sheet : Grid
{
public static readonly DependencyProperty BorderBrushProperty = DependencyProperty.Register(nameof(BorderBrush), typeof(Brush), typeof(Sheet), new FrameworkPropertyMetadata(Brushes.Transparent, FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsRender, OnBorderBrushChanged));
public static readonly DependencyProperty BorderThicknessProperty = DependencyProperty.Register(nameof(BorderThickness), typeof(double), typeof(Sheet), new FrameworkPropertyMetadata(1D, FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsRender, OnBorderThicknessChanged, CoerceBorderThickness));
public static readonly DependencyProperty CellSpacingProperty = DependencyProperty.Register(nameof(CellSpacing), typeof(double), typeof(Sheet), new FrameworkPropertyMetadata(0D, FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsRender, OnCellSpacingChanged, CoerceCellSpacing));
public Brush BorderBrush
{
get => this.GetValue(BorderBrushProperty) as Brush;
set => this.SetValue(BorderBrushProperty, value);
}
public double BorderThickness
{
get => (double)this.GetValue(BorderThicknessProperty);
set => this.SetValue(BorderThicknessProperty, value);
}
public double CellSpacing
{
get => (double)this.GetValue(CellSpacingProperty);
set => this.SetValue(CellSpacingProperty, value);
}
protected override Size ArrangeOverride(Size arrangeSize)
{
Size size = base.ArrangeOverride(arrangeSize);
double border = this.BorderThickness;
double doubleBorder = border * 2D;
double spacing = this.CellSpacing;
double halfSpacing = spacing * 0.5D;
if (border > 0D || spacing > 0D)
{
foreach (UIElement child in this.InternalChildren)
{
this.GetChildBounds(child, out double left, out double top, out double width, out double height);
left += halfSpacing + border;
top += halfSpacing + border;
height -= spacing + doubleBorder;
width -= spacing + doubleBorder;
if (width < 0D)
{
width = 0D;
}
if (height < 0D)
{
height = 0D;
}
left -= left % 0.5D;
top -= top % 0.5D;
width -= width % 0.5D;
height -= height % 0.5D;
child.Arrange(new Rect(left, top, width, height));
}
if (border > 0D && this.BorderBrush != null)
{
this.InvalidateVisual();
}
}
return size;
}
protected override void OnRender(DrawingContext dc)
{
base.OnRender(dc);
if (this.BorderThickness > 0D && this.BorderBrush != null)
{
if (this.CellSpacing == 0D)
{
this.DrawCollapsedBorder(dc);
}
else
{
this.DrawSeperatedBorder(dc);
}
}
}
private void DrawSeperatedBorder(DrawingContext dc)
{
double spacing = this.CellSpacing;
double halfSpacing = spacing * 0.5D;
#region draw border
Pen pen = new Pen(this.BorderBrush, this.BorderThickness);
UIElementCollection children = this.InternalChildren;
foreach (UIElement child in children)
{
this.GetChildBounds(child, out double left, out double top, out double width, out double height);
left += halfSpacing;
top += halfSpacing;
width -= spacing;
height -= spacing;
dc.DrawRectangle(null, pen, new Rect(left, top, width, height));
}
#endregion
}
private void DrawCollapsedBorder(DrawingContext dc)
{
RowDefinitionCollection rows = this.RowDefinitions;
ColumnDefinitionCollection columns = this.ColumnDefinitions;
int rowCount = rows.Count;
int columnCount = columns.Count;
const byte BORDER_LEFT = 0x08;
const byte BORDER_TOP = 0x04;
const byte BORDER_RIGHT = 0x02;
const byte BORDER_BOTTOM = 0x01;
byte[,] borderState = new byte[rowCount, columnCount];
int column = columnCount - 1;
int columnSpan;
int row = rowCount - 1;
int rowSpan;
#region generate main border data
for (int i = 0; i < rowCount; i++)
{
borderState[i, 0] = BORDER_LEFT;
borderState[i, column] = BORDER_RIGHT;
}
for (int i = 0; i < columnCount; i++)
{
borderState[0, i] |= BORDER_TOP;
borderState[row, i] |= BORDER_BOTTOM;
}
#endregion
#region generate child border data
UIElementCollection children = this.InternalChildren;
foreach (UIElement child in children)
{
this.GetChildLayout(child, out row, out rowSpan, out column, out columnSpan);
for (int i = 0; i < rowSpan; i++)
{
borderState[row + i, column] |= BORDER_LEFT;
borderState[row + i, column + columnSpan - 1] |= BORDER_RIGHT;
}
for (int i = 0; i < columnSpan; i++)
{
borderState[row, column + i] |= BORDER_TOP;
borderState[row + rowSpan - 1, column + i] |= BORDER_BOTTOM;
}
}
#endregion
#region draw border
Pen pen = new Pen(this.BorderBrush, this.BorderThickness);
double left;
double top;
double width, height;
for (int r = 0; r < rowCount; r++)
{
RowDefinition v = rows[r];
top = v.Offset;
height = v.ActualHeight;
for (int c = 0; c < columnCount; c++)
{
byte state = borderState[r, c];
ColumnDefinition h = columns[c];
left = h.Offset;
width = h.ActualWidth;
if ((state & BORDER_LEFT) == BORDER_LEFT)
{
dc.DrawLine(pen, new Point(left, top), new Point(left, top + height));
}
if ((state & BORDER_TOP) == BORDER_TOP)
{
dc.DrawLine(pen, new Point(left, top), new Point(left + width, top));
}
if ((state & BORDER_RIGHT) == BORDER_RIGHT && (c + 1 >= columnCount || (borderState[r, c + 1] & BORDER_LEFT) == 0))
{
dc.DrawLine(pen, new Point(left + width, top), new Point(left + width, top + height));
}
if ((state & BORDER_BOTTOM) == BORDER_BOTTOM && (r + 1 >= rowCount || (borderState[r + 1, c] & BORDER_TOP) == 0))
{
dc.DrawLine(pen, new Point(left, top + height), new Point(left + width, top + height));
}
}
}
#endregion
}
private void GetChildBounds(UIElement child, out double left, out double top, out double width, out double height)
{
ColumnDefinitionCollection columns = this.ColumnDefinitions;
RowDefinitionCollection rows = this.RowDefinitions;
int rowCount = rows.Count;
int row = (int)child.GetValue(Grid.RowProperty);
if (row >= rowCount)
{
row = rowCount - 1;
}
int rowSpan = (int)child.GetValue(Grid.RowSpanProperty);
if (row + rowSpan > rowCount)
{
rowSpan = rowCount - row;
}
int columnCount = columns.Count;
int column = (int)child.GetValue(Grid.ColumnProperty);
if (column >= columnCount)
{
column = columnCount - 1;
}
int columnSpan = (int)child.GetValue(Grid.ColumnSpanProperty);
if (column + columnSpan > columnCount)
{
columnSpan = columnCount - column;
}
left = columns[column].Offset;
top = rows[row].Offset;
ColumnDefinition right = columns[column + columnSpan - 1];
width = right.Offset + right.ActualWidth - left;
RowDefinition bottom = rows[row + rowSpan - 1];
height = bottom.Offset + bottom.ActualHeight - top;
if (width < 0D)
{
width = 0D;
}
if (height < 0D)
{
height = 0D;
}
}
private void GetChildLayout(UIElement child, out int row, out int rowSpan, out int column, out int columnSpan)
{
int rowCount = this.RowDefinitions.Count;
row = (int)child.GetValue(Grid.RowProperty);
if (row >= rowCount)
{
row = rowCount - 1;
}
rowSpan = (int)child.GetValue(Grid.RowSpanProperty);
if (row + rowSpan > rowCount)
{
rowSpan = rowCount - row;
}
int columnCount = this.ColumnDefinitions.Count;
column = (int)child.GetValue(Grid.ColumnProperty);
if (column >= columnCount)
{
column = columnCount - 1;
}
columnSpan = (int)child.GetValue(Grid.ColumnSpanProperty);
if (column + columnSpan > columnCount)
{
columnSpan = columnCount - column;
}
}
private static void OnBorderBrushChanged(DependencyObject d, DependencyPropertyChangedEventArgs args)
{
if (d is UIElement element)
{
element.InvalidateVisual();
}
}
private static void OnBorderThicknessChanged(DependencyObject d, DependencyPropertyChangedEventArgs args)
{
if (d is UIElement element)
{
element.InvalidateArrange();
}
}
private static void OnCellSpacingChanged(DependencyObject d, DependencyPropertyChangedEventArgs args)
{
if (d is UIElement element)
{
element.InvalidateArrange();
}
}
private static object CoerceBorderThickness(DependencyObject d, object baseValue)
{
if (baseValue is double value)
{
return value < 0D || double.IsNaN(value) || double.IsInfinity(value) ? 0D : value;
}
return 0D;
}
private static object CoerceCellSpacing(DependencyObject d, object baseValue)
{
if (baseValue is double value)
{
return value < 0D || double.IsNaN(value) || double.IsInfinity(value) ? 0D : value;
}
return 0D;
}
}
we could open html file from linux/unix by using firefox .html
First you should use print_r($_FILES)
to debug, and see what it contains. :
your uploads.php
would look like:
//This is the directory where images will be saved
$target = "pics/";
$target = $target . basename( $_FILES['Filename']['name']);
//This gets all the other information from the form
$Filename=basename( $_FILES['Filename']['name']);
$Description=$_POST['Description'];
//Writes the Filename to the server
if(move_uploaded_file($_FILES['Filename']['tmp_name'], $target)) {
//Tells you if its all ok
echo "The file ". basename( $_FILES['Filename']['name']). " has been uploaded, and your information has been added to the directory";
// Connects to your Database
mysql_connect("localhost", "root", "") or die(mysql_error()) ;
mysql_select_db("altabotanikk") or die(mysql_error()) ;
//Writes the information to the database
mysql_query("INSERT INTO picture (Filename,Description)
VALUES ('$Filename', '$Description')") ;
} else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?>
EDIT: Since this is old post, currently it is strongly recommended to use either mysqli or pdo instead mysql_ functions in php
Your regex matches (and removes) only subsequent square brackets. Use this instead:
str = str.replaceAll("\\[|\\]", "");
If you only want to replace bracket pairs with content in between, you could use this:
str = str.replaceAll("\\[(.*?)\\]", "$1");
myList.GroupBy(test => test.id)
.Select(grp => grp.First());
Edit: as getting this IEnumerable<>
into a List<>
seems to be a mystery to many people, you can simply write:
var result = myList.GroupBy(test => test.id)
.Select(grp => grp.First())
.ToList();
But one is often better off working with the IEnumerable
rather than IList
as the Linq above is lazily evaluated: it doesn't actually do all of the work until the enumerable is iterated. When you call ToList
it actually walks the entire enumerable forcing all of the work to be done up front. (And may take a little while if your enumerable is infinitely long.)
The flipside to this advice is that each time you enumerate such an IEnumerable
the work to evaluate it has to be done afresh. So you need to decide for each case whether it is better to work with the lazily evaluated IEnumerable
or to realize it into a List
, Set
, Dictionary
or whatnot.
Check this code based on the article Geo-Distance-Search-with-MySQL:
Example: find the 10 nearest hotels to my current location in a 10 miles radius:
#Please notice that (lat,lng) values mustn't be negatives to perform all calculations
set @my_lat=34.6087674878572;
set @my_lng=58.3783670308302;
set @dist=10; #10 miles radius
SELECT dest.id, dest.lat, dest.lng, 3956 * 2 * ASIN(SQRT(POWER(SIN((@my_lat -abs(dest.lat)) * pi()/180 / 2),2) + COS(@my_lat * pi()/180 ) * COS(abs(dest.lat) * pi()/180) * POWER(SIN((@my_lng - abs(dest.lng)) * pi()/180 / 2), 2))
) as distance
FROM hotel as dest
having distance < @dist
ORDER BY distance limit 10;
#Also notice that distance are expressed in terms of radius.
In case someone else ends up here struggling to customize admin form Many2Many saving behaviour, you can't call self.instance.my_m2m.add(obj)
in your ModelForm.save
override, as ModelForm.save
later populates your m2m from self.cleaned_data['my_m2m']
which overwrites your changes. Instead call:
my_m2ms = list(self.cleaned_data['my_m2ms'])
my_m2ms.extend(my_custom_new_m2ms)
self.cleaned_data['my_m2ms'] = my_m2ms
(It is fine to convert the incoming QuerySet to a list - the ManyToManyField
does that anyway.)
Here's the script, rewritten to use the suggestions above and a change to your no-cache method.
<?php
// Simpler way of making sure all no-cache headers get sent
// and understood by all browsers, including IE.
session_cache_limiter('nocache');
header('Expires: ' . gmdate('r', 0));
header('Content-type: application/json');
// set to return response=error
$arr = array ('response'=>'error','comment'=>'test comment here');
echo json_encode($arr);
?>
//the script above returns this:
{"response":"error","comment":"test comment here"}
<script type="text/javascript">
$.ajax({
type: "POST",
url: "process.php",
data: dataString,
dataType: "json",
success: function (data) {
if (data.response == 'captcha') {
alert('captcha');
} else if (data.response == 'success') {
alert('success');
} else {
alert('sorry there was an error');
}
}
}); // Semi-colons after all declarations, IE is picky on these things.
</script>
The main issue here was that you had a typo in the JSON you were returning ("resonse" instead of "response". This meant that you were looking for the wrong property in the JavaScript code. One way of catching these problems in the future is to console.log
the value of data
and make sure the property you are looking for is there.
Learning how to use the Chrome debugger tools (or similar tools in Firefox/Safari/Opera/etc.) will also be invaluable.
public SmartSaverCals(Context context)
{
this.context= context;
}
add public to Your constructor.in my case problem solved
Same concept as a .jar
file in Java, it is a .zip
file with some metadata files renamed .egg
, for distributing code as bundles.
Specifically: The Internal Structure of Python Eggs
A "Python egg" is a logical structure embodying the release of a specific version of a Python project, comprising its code, resources, and metadata. There are multiple formats that can be used to physically encode a Python egg, and others can be developed. However, a key principle of Python eggs is that they should be discoverable and importable. That is, it should be possible for a Python application to easily and efficiently find out what eggs are present on a system, and to ensure that the desired eggs' contents are importable.
The
.egg
format is well-suited to distribution and the easy uninstallation or upgrades of code, since the project is essentially self-contained within a single directory or file, unmingled with any other projects' code or resources. It also makes it possible to have multiple versions of a project simultaneously installed, such that individual programs can select the versions they wish to use.
Simplifying/elaborating on Nick Sotiros' answer (which I think is awesome), I think it's best to describe how one would start coding with yield
.
In my opinion, the biggest advantage of using yield
is that it will eliminate all the nested callback problems we see in code. It's hard to see how at first, which is why I decided to write this answer (for myself, and hopefully others!)
The way it does it is by introducing the idea of a co-routine, which is a function that can voluntarily stop/pause until it gets what it needs. In javascript, this is denoted by function*
. Only function*
functions can use yield
.
Here's some typical javascript:
loadFromDB('query', function (err, result) {
// Do something with the result or handle the error
})
This is clunky because now all of your code (which obviously needs to wait for this loadFromDB
call) needs to be inside this ugly looking callback. This is bad for a few reasons...
})
which you need to keep track of everywherefunction (err, result)
jargonresult
On the other hand, with yield
, all of this can be done in one line with the help of the nice co-routine framework.
function* main() {
var result = yield loadFromDB('query')
}
And so now your main function will yield where necessary when it needs to wait for variables and things to load. But now, in order to run this, you need to call a normal (non-coroutine function). A simple co-routine framework can fix this problem so that all you have to do is run this:
start(main())
And start is defined (from Nick Sotiro' answer)
function start(routine, data) {
result = routine.next(data);
if(!result.done) {
result.value(function(err, data) {
if(err) routine.throw(err); // continue next iteration of routine with an exception
else start(routine, data); // continue next iteration of routine normally
});
}
}
And now, you can have beautiful code that is much more readable, easy to delete, and no need to fiddle with indents, functions, etc.
An interesting observation is that in this example, yield
is actually just a keyword you can put before a function with a callback.
function* main() {
console.log(yield function(cb) { cb(null, "Hello World") })
}
Would print "Hello World". So you can actually turn any callback function into using yield
by simply creating the same function signature (without the cb) and returning function (cb) {}
, like so:
function yieldAsyncFunc(arg1, arg2) {
return function (cb) {
realAsyncFunc(arg1, arg2, cb)
}
}
Hopefully with this knowledge you can write cleaner, more readable code that is easy to delete!
I'm on Windows 7 x64 and Visual Studio 2017. I get this error trying to compile a cython script. That's how I solved: I copied and pasted rc.exe and rcdll.dll from:
C:\Program Files (x86)\Windows Kits\8.1\bin\x86
to
C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\bin\x86_amd64
Got the same problem, found the following bug report in SQL Server 2012 If still relevant see conditions that cause the issue - there are some workarounds there as well (didn't try though). Failover or Restart Results in Reseed of Identity
I have also used following link as others have suggested you for bluetooth communication.
http://developer.android.com/guide/topics/connectivity/bluetooth.html
The thing is all you need is a class BluetoothChatService.java
this class has following threads:
Now when you call start function of the BluetoothChatService like:
mChatService.start();
It starts accept thread which means it will start looking for connection.
Now when you call
mChatService.connect(<deviceObject>,false/true);
Here first argument is device object that you can get from paired devices list or when you scan for devices you will get all the devices in range you can pass that object to this function and 2nd argument is a boolean to make secure or insecure connection.
connect
function will start connecting thread which will look for any device which is running accept thread.
When such a device is found both accept thread and connecting thread will call connected function in BluetoothChatService:
connected(mmSocket, mmDevice, mSocketType);
this method starts connected thread in both the devices:
Using this socket object connected thread obtains the input and output stream to the other device.
And calls read
function on inputstream in a while loop so that it's always trying read from other device so that whenever other device send a message this read function returns that message.
BluetoothChatService also has a write
method which takes byte[]
as input and calls write method on connected thread.
mChatService.write("your message".getByte());
write method in connected thread just write this byte data to outputsream of the other device.
public void write(byte[] buffer) {
try {
mmOutStream.write(buffer);
// Share the sent message back to the UI Activity
// mHandler.obtainMessage(
// BluetoothGameSetupActivity.MESSAGE_WRITE, -1, -1,
// buffer).sendToTarget();
} catch (IOException e) {
Log.e(TAG, "Exception during write", e);
}
}
Now to communicate between two devices just call write function on mChatService and handle the message that you will receive on the other device.
From swift programming guide
If Statements and Forced Unwrapping
You can use an if statement to find out whether an optional contains a value. If an optional does have a value, it evaluates to true; if it has no value at all, it evaluates to false.
So the best way to do this is
// swift > 3
if xyz != nil {}
and if you are using the xyz
in if statement.Than you can unwrap xyz
in if statement in constant variable .So you do not need to unwrap every place in if statement where xyz
is used.
if let yourConstant = xyz{
//use youtConstant you do not need to unwrap `xyz`
}
This convention is suggested by apple
and it will be followed by devlopers.
select products.product_id, product_name, price, created_at, image_name, categories.category_id, category_name,brands.brand_id, brand_name
FROM products INNER JOIN categories USING (category_id) INNER JOIN brands USING(brand_id)
A short example to sort dictionary is desending order for Python3.
a1 = {'a':1, 'b':13, 'd':4, 'c':2, 'e':30}
a1_sorted_keys = sorted(a1, key=a1.get, reverse=True)
for r in a1_sorted_keys:
print(r, a1[r])
Following will be the output
e 30
b 13
d 4
c 2
a 1
If you don't have permissions to change your default DB you could manually select a different DB at the top of your queries...
USE [SomeOtherDb]
SELECT 'I am now using a different DB'
Will work as long as you have permission to the other DB
If you use jQuery, u can do it like this:
<form action="example" method="post" id="loginform">
...
<input id="btnin" type="button" value="login"/>
<input id="btnreg" type="button" value="regist"/>
</form>
And js will be:
$("#btnin").click(function(){
$("#loginform").attr("action", "user_login");
$("#loginform").submit();
}
$("#btnreg").click(function(){
$("#loginform").attr("action", "user_regist");
$("#loginform").submit();
}
You can convert your empty row to integer value and check zero?.
"".to_i.zero? => true
nil.to_i.zero? => true
for i in $(ls); do cp -r "$i" "$i"_dev; done;
getView()
method create new View
or ViewGroup
for each row of Listview
or Spinner . You can define this View
or ViewGroup
in a Layout XML
file in res/layout
folder and can give the reference it to Adapter
class Object.
if you have 4 item in a Array passed to Adapter. getView()
method will create 4 View for 4 rows of Adaper.
LayoutInflater class has a Method inflate() whic create View Object from XML resource layout.
One way to do it:
in .git/config fetch for the remote repo should be set to fetch any branch:
[remote "origin"]
fetch = +refs/heads/*:refs/remotes/origin/*
to fetch the remote branch:
git fetch origin branch-name
to create a local branch 'branch-name' set up to track remote branch 'branch-name' from origin.
git checkout -b branch-name origin/branch-name
to list all branches
git branch -a
I was having the same problem while importing the certificate in local keystore. Whenever i issue the keytool command i got the following error.
Certificate was added to keystore keytool error: java.io.FileNotFoundException: C:\Program Files\Java\jdk1.8.0_151\jre\lib\security (Access is denied)
Following solution work for me.
1) make sure you are running command prompt in Rus as Administrator mode
2) Change your current directory to %JAVA_HOME%\jre\lib\security
3) then Issue the below command
keytool -import -alias "mycertificatedemo" -file "C:\Users\name\Downloads\abc.crt" -keystore cacerts
3) give the password changeit
4) enter y
5) you will see the following message on successful "Certificate was added to keystore"
Make sure you are giving the "cacerts" only in -keystore param value , as i was giving the full path like "C**:\Program Files\Java\jdk1.8.0_151\jre\lib\security**".
Hope this will work
Using java.time
framework built into Java 8:
import java.time.LocalDate;
LocalDate now = LocalDate.now(); // 2015-11-24
LocalDate earlier = now.minusMonths(1); // 2015-10-24
earlier.getMonth(); // java.time.Month = OCTOBER
earlier.getMonth.getValue(); // 10
earlier.getYear(); // 2015
What it does:
if set to "true", any cached data used by the OSGi framework and eclipse runtime will be wiped clean. This will clean the caches used to store bundle dependency resolution and eclipse extension registry data. Using this option will force eclipse to reinitialize these caches.
How to use it:
eclipse.ini
file located in your Eclipse install directory and insert -clean
as the first line. -clean
as the first argument. -clean
argument. The advantage to this step is you can keep the script around and use it each time you want to clean out the workspace. You can name it something like eclipse-clean.bat
(or eclipse-clean.sh
). (From: http://www.eclipsezone.com/eclipse/forums/t61566.html)
Other eclipse command line options: http://help.eclipse.org/indigo/index.jsp?topic=%2Forg.eclipse.platform.doc.isv%2Freference%2Fmisc%2Fruntime-options.html
axwebbrowser1.Silent = true;
You can simply simply achieve it with any python module that gives you an interaction with command line(cmd
) like subprocess
, os
, etc.
but here I came up with examples on only two modules.
Here is syntax (command) cmd /c start browser_name "URL"
import os
# or open with iexplore
os.system('cmd /c start iexplore "http://your_url"')
# or open with chrome
os.system('cmd /c start chrome "http://your_url"')
__import__('subprocess').getoutput('cmd /c start iexplore "http://your_url"')
You can also run the command in the cmd it will work to or use other module call
click
which mainly used for writing command line utilities.
import click
click.launch('http://your_url')
I know this is an old question, but how about just binding to Command
if using MVVM?
ex:
<CheckBox Content="Case Sensitive" Command="{Binding bSearchCaseSensitive}"/>
For me it triggers on both Check
and Uncheck
.
In iOS 8:
add NavigationController.NavigationBar.BarStyle = UIBarStyle.Black;
to viewDidLoad
check this masterfull timestamp detector regex I built to look for a user-specified timestamp, examples of what it will pickup include, but is most definitely NOT limited to;
8:30-9:40
09:40-09 : 50
09 : 40-09 : 50
09:40 - 09 : 50
08:00to05:00
08 : 00to05 : 00
08:00 to 05:00
8am-09pm
08h00 till 17h00
8pm-5am
08h00,21h00
06pm untill 9am
It'll also pickup many more, as long as the times include digits
The reason why you are able to access the drive in when you normally run the executable from command prompt is that when u are executing it as normal exe you are running that application in the User account from which you have logged on . And that user has the privileges to access the network. But , when you install the executable as a service , by default if you see in the task manage it runs under 'SYSTEM' account . And you might be knowing that the 'SYSTEM' doesn't have rights to access network resources.
There can be two solutions to this problem.
To map the drive as persistent as already pointed above.
There is one more approach that can be followed. If you open the service manager by typing in the 'services.msc'you can go to your service and in the properties of your service there is a logOn tab where you can specify the account as any other account than 'System' you can either start service from your own logged on user account or through 'Network Service'. When you do this .. the service can access any network component and drive even if they are not persistent also. To achieve this programmatically you can look into 'CreateService' function at http://msdn.microsoft.com/en-us/library/ms682450(v=vs.85).aspx and can set the parameter 'lpServiceStartName ' to 'NT AUTHORITY\NetworkService'. This will start your service under 'Network Service' account and then you are done.
You can also try by making the service as interactive by specifying SERVICE_INTERACTIVE_PROCESS in the servicetype parameter flag of your CreateService() function but this will be limited only till XP as Vista and 7 donot support this feature.
Hope the solutions help you.. Let me know if this worked for you .
Control Center already got the feature of that. It's just below the table list.
Try this, it's pure Ruby so there's no need to add any peripheral frameworks
if @players.include?(p.name) == false do
...
end
I was struggling with a similar logic for a few days, and after checking several forums and Q&A boards to little avail it turns out the solution was actually pretty simple.
You can put the following code on the default value of the timestamp column:
CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
, so on update the two columns take the same value.
For those using python 2.7, should try:
apt-get install -y python-numpy
Instead of pip install numpy
Another cause is accidentally putting the data=...
inside the aes(...)
instead of outside:
RIGHT:
ggplot(data=df[df$var7=='9-06',], aes(x=lifetime,y=rep_rate,group=mdcp,color=mdcp) ...)
WRONG:
ggplot(aes(data=df[df$var7=='9-06',],x=lifetime,y=rep_rate,group=mdcp,color=mdcp) ...)
In particular this can happen when you prototype your plot command with qplot()
, which doesn't use an explicit aes()
, then edit/copy-and-paste it into a ggplot()
qplot(data=..., x=...,y=..., ...)
ggplot(data=..., aes(x=...,y=...,...))
It's a pity ggplot's error message isn't Missing 'data' argument! instead of this cryptic nonsense, because that's what this message often means.
Look at the yesno helper
Eg:
{{ myValue|yesno:"itwasTrue,itWasFalse,itWasNone" }}
You can use the dynamic object ViewBag
to pass data from Controllers to Views.
Add the following to your controller:
ViewBag.MyList = myList;
Then you can acces it from your view:
@ViewBag.MyList
// e.g.
@foreach (var item in ViewBag.MyList) { ... }
I agree with yossi's example, stretch the image to fit the div but in a slightly different way (without background-image as this is a little inflexible in css 2.1). Show full image:
<div id="yourdiv">
<img id="theimage" src="image.jpg" alt="" />
</div>
#yourdiv img {
width:100%;
/*height will be automatic to remain aspect ratio*/
}
Show part of the image using background-position:
#yourdiv
{
background-image: url(image.jpg);
background-repeat: no-repeat;
background-position: 10px 25px;
}
Same as the first part of (1) the image will scale to the div so bigger or smaller will both work
Same as yossi's.
just combine the value and the stud_name e.g. 1_sre and split the value when get it into php. Javascript seems like hammer to crack a nut. N.B. this method assumes you can edit the the html. Here is what the html might look like:
<form name='add'>
Age: <select name='age'>
<option value='1_sre'>23</option>
<option value='2_sam>24</option>
<option value='5_john>25</option>
</select>
<input type='submit' name='submit'/>
</form>
In iOS 9.1 and lower, go to Settings - General - Profiles - tap on your Profile - tap on Trust button.