You have prevent the default browser behaviour. But you don’t need to create a directive to accomplish that.
It’s easy as the following example:
my.component.html
<a href="" (click)="goToPage(pageIndex, $event)">Link</a>
my.component.ts
goToPage(pageIndex, event) {
event.preventDefault();
console.log(pageIndex);
}
Function RemoveCharacter(ByVal stringToCleanUp, ByVal characterToRemove)
' replace the target with nothing
' Replace() returns a new String and does not modify the current one
Return stringToCleanUp.Replace(characterToRemove, "")
End Function
Here's more information about VB's Replace function
I had compatibility issues with several plugins I tried, this seems to me to be the simplest way of supporting placeholders on text inputs:
function placeholders(){
//On Focus
$(":text").focus(function(){
//Check to see if the user has modified the input, if not then remove the placeholder text
if($(this).val() == $(this).attr("placeholder")){
$(this).val("");
}
});
//On Blur
$(":text").blur(function(){
//Check to see if the use has modified the input, if not then populate the placeholder back into the input
if( $(this).val() == ""){
$(this).val($(this).attr("placeholder"));
}
});
}
Maximum is 2097151, If you try set more error occurred.
I had the same problem of "gpg: keyserver timed out" with a couple of different servers. Finally, it turned out that I didn't need to do that manually at all. On a Debian system, the simple solution which fixed it was just (as root or precede with sudo):
aptitude install debian-archive-keyring
In case it is some other keyring you need, check out
apt-cache search keyring | grep debian
My squeeze system shows all these:
debian-archive-keyring - GnuPG archive keys of the Debian archive
debian-edu-archive-keyring - GnuPG archive keys of the Debian Edu archive
debian-keyring - GnuPG keys of Debian Developers
debian-ports-archive-keyring - GnuPG archive keys of the debian-ports archive
emdebian-archive-keyring - GnuPG archive keys for the emdebian repository
Set force Portrait or Landscape mode, Add lines respectively.
Import below line:
import android.content.pm.ActivityInfo;
Add Below line just above setContentView(R.layout.activity_main);
For Portrait:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//Set Portrait
For Landscap:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);//Set Landscape
This will definitely work.
I fixed this problem changing the order of the routes.
BLOB
primarily intended to hold non-traditional data, such as images,videos,voice or mixed media. CLOB
intended to retain character-based data.
I can't believe nobody suggested this:
int i = 9;
i.ToString("D2"); // Will give you the string "09"
or
i.ToString("D8"); // Will give you the string "00000009"
If you want hexadecimal:
byte b = 255;
b.ToString("X2"); // Will give you the string "FF"
You can even use just "C" to display as currency if you locale currency symbol. See here: https://docs.microsoft.com/en-us/dotnet/api/system.int32.tostring?view=netframework-4.7.2#System_Int32_ToString_System_String_
A common way to approach this is to add your own ForEach
generic method on IEnumerable<T>
. Here's the one we've got in MoreLINQ:
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
source.ThrowIfNull("source");
action.ThrowIfNull("action");
foreach (T element in source)
{
action(element);
}
}
(Where ThrowIfNull
is an extension method on any reference type, which does the obvious thing.)
It'll be interesting to see if this is part of .NET 4.0. It goes against the functional style of LINQ, but there's no doubt that a lot of people find it useful.
Once you've got that, you can write things like:
people.Where(person => person.Age < 21)
.ForEach(person => person.EjectFromBar());
You should not be updating 10k rows in a set unless you are certain that the operation is getting Page Locks (due to multiple rows per page being part of the UPDATE
operation). The issue is that Lock Escalation (from either Row or Page to Table locks) occurs at 5000 locks. So it is safest to keep it just below 5000, just in case the operation is using Row Locks.
You should not be using SET ROWCOUNT to limit the number of rows that will be modified. There are two issues here:
It has that been deprecated since SQL Server 2005 was released (11 years ago):
Using SET ROWCOUNT will not affect DELETE, INSERT, and UPDATE statements in a future release of SQL Server. Avoid using SET ROWCOUNT with DELETE, INSERT, and UPDATE statements in new development work, and plan to modify applications that currently use it. For a similar behavior, use the TOP syntax
It can affect more than just the statement you are dealing with:
Setting the SET ROWCOUNT option causes most Transact-SQL statements to stop processing when they have been affected by the specified number of rows. This includes triggers. The ROWCOUNT option does not affect dynamic cursors, but it does limit the rowset of keyset and insensitive cursors. This option should be used with caution.
Instead, use the TOP () clause.
There is no purpose in having an explicit transaction here. It complicates the code and you have no handling for a ROLLBACK, which isn't even needed since each statement is its own transaction (i.e. auto-commit).
Assuming you find a reason to keep the explicit transaction, then you do not have a TRY / CATCH structure. Please see my answer on DBA.StackExchange for a TRY / CATCH template that handles transactions:
Are we required to handle Transaction in C# Code as well as in Store procedure
I suspect that the real WHERE clause is not being shown in the example code in the Question, so simply relying upon what has been shown, a better model would be:
DECLARE @Rows INT,
@BatchSize INT; -- keep below 5000 to be safe
SET @BatchSize = 2000;
SET @Rows = @BatchSize; -- initialize just to enter the loop
BEGIN TRY
WHILE (@Rows = @BatchSize)
BEGIN
UPDATE TOP (@BatchSize) tab
SET tab.Value = 'abc1'
FROM TableName tab
WHERE tab.Parameter1 = 'abc'
AND tab.Parameter2 = 123
AND tab.Value <> 'abc1' COLLATE Latin1_General_100_BIN2;
-- Use a binary Collation (ending in _BIN2, not _BIN) to make sure
-- that you don't skip differences that compare the same due to
-- insensitivity of case, accent, etc, or linguistic equivalence.
SET @Rows = @@ROWCOUNT;
END;
END TRY
BEGIN CATCH
RAISERROR(stuff);
RETURN;
END CATCH;
By testing @Rows
against @BatchSize
, you can avoid that final UPDATE query (in most cases) because the final set is typically some number of rows less than @BatchSize
, in which case we know that there are no more to process (which is what you see in the output shown in your answer). Only in those cases where the final set of rows is equal to @BatchSize
will this code run a final UPDATE affecting 0 rows.
I also added a condition to the WHERE
clause to prevent rows that have already been updated from being updated again.
<Button Background="#FF4148" BorderThickness="0" BorderBrush="Transparent">
<Border HorizontalAlignment="Right" BorderBrush="#FF6A6A" BorderThickness="0>
<Border.Style>
<Style TargetType="Border">
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="#FF6A6A" />
</Trigger>
</Style.Triggers>
</Style>
</Border.Style>
<StackPanel Orientation="Horizontal">
<Image RenderOptions.BitmapScalingMode="HighQuality" Source="//ImageName.png" />
</StackPanel>
</Border>
</Button>
I used these options to convert to the H.264/AAC .mp4 format for HTML5 playback (I think it may help other guys with this problem in some way):
ffmpeg -i input.flv -vcodec mpeg4 -acodec aac output.mp4
UPDATE
As @LordNeckbeard mentioned, the previous line will produce MPEG-4 Part 2
(back in 2012 that worked somehow, I don't remember/understand why). Use the libx264
encoder to produce the proper video with H.264/AAC. To test the output file you can just drag it to a browser window and it should playback just fine.
ffmpeg -i input.flv -vcodec libx264 -acodec aac output.mp4
I don't have Visual Studio installed on my machine anymore (and I'm using Linux), but I do remember that there was an wizard hidden somewhere inside one of the menus that gave access to a class builder.
With this wizard, you could define all your classes' details, including methods and attributes. If I remember well, there was an option through which you could ask Visual Studio to create the setters and getters automatically for you.
I know it's quite vague, but check it out and you might find it.
Just try this in razor
@{
var selectList = new SelectList(
new List<SelectListItem>
{
new SelectListItem {Text = "Google", Value = "Google"},
new SelectListItem {Text = "Other", Value = "Other"},
}, "Value", "Text");
}
and then
@Html.DropDownListFor(m => m.YourFieldName, selectList, "Default label", new { @class = "css-class" })
or
@Html.DropDownList("ddlDropDownList", selectList, "Default label", new { @class = "css-class" })
I was looking for same answer and finally I found this link. You can find explained three different ways how to add bootstrap css into your angular 2 project. It helped me.
Here is the link: http://codingthesmartway.com/using-bootstrap-with-angular/
I made two examples from what I think your question might be:
Check this out for storing additional values. It uses data attributes to store the other value:
Installing docker doesn't mean that you've installed docker-compose. It has as prerequisitions that you've already installed the docker engine which you've already done. After that you're able to install docker-compose following this link for Centos 7.
You can also use google-collections (guava) Joiner class if you want to customize the print format
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
var height:CGFloat = CGFloat()
if indexPath.row == 1 {
height = 150
}
else {
height = 50
}
return height
}
this is the shortest way I know with negative integers enabled:
Object myObject = "-1";
if(Pattern.matches("\\-?\\d+", (CharSequence) myObject);)==true)
{
System.out.println("It's an integer!");
}
And this is the way with negative integers disabled:
Object myObject = "1";
if(Pattern.matches("\\d+", (CharSequence) myObject);)==true)
{
System.out.println("It's an integer!");
}
In my case, the files were already copied, I found the easiest way to follow the steps in this guide: https://www.ryadel.com/en/exporting-importing-app-pools-and-websites-configuration-between-multiple-iis-instances/
I exported AppPools/Websites, copied the xml files to the destination server and Imported AppPools then Websites. Worked very well. This is also another excellent option for this question.
I would use .*
. .
matches any character, *
signifies 0 or more occurrences. You might need a DOTALL switch to the regex to capture new lines with .
.
Crazy amount of complicated answers here. If you don't intend to process nodeJS files/database but just want to serve static html/css/js/images as your question suggest then simply install the pushstate-server module or similar;
Here's a "one liner" that will create and launch a mini site. Simply paste that entire block in your terminal in the appropriate directory.
mkdir mysite; \
cd mysite; \
npm install pushstate-server --save; \
mkdir app; \
touch app/index.html; \
echo '<h1>Hello World</h1>' > app/index.html; \
touch server.js; \
echo "var server = require('pushstate-server');server.start({ port: 3000, directory: './app' });" > server.js; \
node server.js
Open browser and go to http://localhost:3000. Done.
The server will use the app
dir as the root to serve files from. To add additional assets just place them inside that directory.
This was the simplest solution for horizontal view. Tried with bunch of examples. Works well for my purpose. Updated from @nitin-k 's answer.
public void print(String prefix, BTNode n, boolean isLeft) {
if (n != null) {
print(prefix + " ", n.right, false);
System.out.println (prefix + ("|-- ") + n.data);
print(prefix + " ", n.left, true);
}
}
Call:
bst.print("", bst.root, false);
Solution:
|-- 80
|-- 70
|-- 60
|-- 50
|-- 40
|-- 30
|-- 20
|-- 10
Apache
, as usual, has a good answer from Apache Commons-Lang
in the form of
NumberUtils.isCreatable(String)
.
Handles null
s, no try
/catch
block required.
If you push for example image to some API and want the result address(response) back you could do:
import requests
url = 'https://uguu.se/api.php?d=upload-tool'
data = {"name": filename}
files = {'file': open(full_file_path, 'rb')}
response = requests.post(url, data=data, files=files)
current_url = response.text
print(response.text)
std::vector<std::string> parse(std::string str,std::string delim){
std::vector<std::string> tokens;
char *str_c = strdup(str.c_str());
char* token = NULL;
token = strtok(str_c, delim.c_str());
while (token != NULL) {
tokens.push_back(std::string(token));
token = strtok(NULL, delim.c_str());
}
delete[] str_c;
return tokens;
}
Ok, I propose this solution, very simple, using ngx-translate
import { DatePipe } from '@angular/common';
import { Pipe, PipeTransform } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
@Pipe({
name: 'localizedDate',
pure: false
})
export class LocalizedDatePipe implements PipeTransform {
constructor(private translateService: TranslateService) {
}
transform(value: any): any {
const date = new Date(value);
const options = { weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
};
return date.toLocaleString(this.translateService.currentLang, options);
}
}
I do it like this in python 3:
with open('myfile.txt', 'w') as f:
print(mydictionary, file=f)
alter table User
add constraint userProperties
foreign key (properties)
references Properties(ID)
Probably you can go with this code to take actions as the checkbox is checked or unchecked.
$('#chk').on('click',function(){
if(this.checked==true){
alert('yes');
}else{
alert('no');
}
});
Here is an extension function for C#:
public static BitmapImage GetElementImage(this IWebDriver webDriver, By by)
{
var elements = webDriver.FindElements(by);
if (elements.Count == 0)
return null;
var element = elements[0];
var screenShot = (webDriver as ITakesScreenshot).GetScreenshot();
using (var ms = new MemoryStream(screenShot.AsByteArray))
{
Bitmap screenBitmap;
screenBitmap = new Bitmap(ms);
return screenBitmap.Clone(
new Rectangle(
element.Location.X,
element.Location.Y,
element.Size.Width,
element.Size.Height
),
screenBitmap.PixelFormat
).ToBitmapImage();
}
}
Now you can use it to take the image of any element like this:
var image = webDriver.GetElementImage(By.Id("someId"));
From application perspective, if one needs only to avoid duplicates then HashSet
is what you are looking for since it's Lookup, Insert and Remove complexities are O(1) - constant. What this means it does not matter how many elements HashSet
has it will take same amount of time to check if there's such element or not, plus since you are inserting elements at O(1) too it makes it perfect for this sort of thing.
Use Shell "program file path file path you want to open"
.
Example:
Shell "c:\windows\system32\mspaint.exe c:users\admin\x.jpg"
Verify the length
property of the array to be greater than 0
:
<p ng-if="post.capabilities.items.length > 0">
<strong>Topics</strong>:
<span ng-repeat="topic in post.capabilities.items">
{{topic.name}}
</span>
</p>
Arrays (objects) in JavaScript are truthy values, so your initial verification <p ng-if="post.capabilities.items">
evaluates always to true
, even if the array is empty.
You can find the full list here.
\t
Insert a tab in the text at this point.\b
Insert a backspace in the text at this point.\n
Insert a newline in the text at this point.\r
Insert a carriage return in the text at this point.\f
Insert a formfeed in the text at this point.\'
Insert a single quote character in the text at this point.\"
Insert a double quote character in the text at this point.\\
Insert a backslash character in the text at this point.I've personally always used boost.regex (although I don't have much need for regex in C++). Microsoft Labs has a regex library too, called GRETA: http://research.microsoft.com/projects/greta/. Apparently it's very fast and features a whole Perl 5 syntax. I haven't used it, but you may want to test it out.
iterate LinkedList by using iterator
LinkedList<String> linkedList = new LinkedList<String>();
linkedList.add(“Mumbai”);
linkedList.add(“Delhi”);
linkedList.add(“Noida”);
linkedList.add(“Gao”);
linkedList.add(“Patna”);
Iterator<String> itr = linkedList.iterator();
while (itr.hasNext()) {
System.out.println(“Element is =”+itr.next());
}
Reference : Java Linkedlist Examples
Step 1 :- GO to My Apps App in iTunes Connect
Here you can see your all app which are currently on Appstore.
Step 2 :- Select your app which you want to delete.(click on app-name)
Step 3 :- Select Pricing and Availability Tab.
Step 4 :- Select Remove from sale option.
Step 5 :- Click on save Button.
Now you will see below your app like , Developer Removed it from sale in Red Symbol in place of Green.
Step 6 :- Now again Select your app and Go to App information Tab. you will see Delete App option. (need to scroll bit bottom)
Step 7 :- After clicking on Delete button you will get warning like this ,
Step 8 :- Click on Delete button.
Congratulation , You have Permanently deleted your app successfully from appstore. Now , you cant able to see app on appstore aswellas in your developer account.
Note :-
When you have selected only Remove from sale option you have not deleted app permanently. You can able to make your app live again by clicking on Available in all territories option Again.
SELECT VIEW_NAME
FROM INFORMATION_SCHEMA.VIEW_TABLE_USAGE
WHERE TABLE_NAME = 'Your Table'
I was also interested in this and I've compared all the suggested answers with perfplot. (Disclaimer: I'm the author of perfplot.)
If you know that the array you're looking through is already sorted, then
numpy.searchsorted(a, alpha)
is for you. It's O(log(n)) operation, i.e., the speed hardly depends on the size of the array. You can't get faster than that.
If you don't know anything about your array, you're not going wrong with
numpy.argmax(a > alpha)
Already sorted:
Unsorted:
Code to reproduce the plot:
import numpy
import perfplot
alpha = 0.5
numpy.random.seed(0)
def argmax(data):
return numpy.argmax(data > alpha)
def where(data):
return numpy.where(data > alpha)[0][0]
def nonzero(data):
return numpy.nonzero(data > alpha)[0][0]
def searchsorted(data):
return numpy.searchsorted(data, alpha)
perfplot.save(
"out.png",
# setup=numpy.random.rand,
setup=lambda n: numpy.sort(numpy.random.rand(n)),
kernels=[argmax, where, nonzero, searchsorted],
n_range=[2 ** k for k in range(2, 23)],
xlabel="len(array)",
)
Try GraphIT from TechNewLogic, you can find it on CodePlex here: http://graphit.codeplex.com
Full Disclosure: I am the developer of GraphIT and owner of the developing company.
just found out there are some similarities between my question and yours. Aparrently if you want to pass arguments into commands
test.sh "Cherry Hill" "New York City"
to print them out in order
for SOME_ARG in "$@"
do
echo "$SOME_ARG";
done;
notice the $@ is surrounded by double quotes, some notes here
I changed scrollable div to be with absolute position, and everything works for me
div.sidebar {
overflow: hidden;
background-color: green;
padding: 5px;
position: fixed;
right: 20px;
width: 40%;
top: 30px;
padding: 20px;
bottom: 30%;
}
div#fixed {
background: #76a7dc;
color: #fff;
height: 30px;
}
div#scrollable {
overflow-y: scroll;
background: lightblue;
position: absolute;
top:55px;
left:20px;
right:20px;
bottom:10px;
}
The 1
s are because everything is perfectly correlated with itself, and the NA
s are because there are NA
s in your variables.
You will have to specify how you want R to compute the correlation when there are missing values, because the default is to only compute a coefficient with complete information.
You can change this behavior with the use
argument to cor
, see ?cor
for details.
First you add the Navigation back button
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
Then, add the Method in your HostActivity.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId()==android.R.id.home)
{
super.onBackPressed();
Toast.makeText(this, "OnBAckPressed Works", Toast.LENGTH_SHORT).show();
}
return super.onOptionsItemSelected(item);
}
Try this, definitely work.
To change bottom line color, you can use this in your app theme:
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="colorControlNormal">#c5c5c5</item>
<item name="colorControlActivated">#ffe100</item>
<item name="colorControlHighlight">#ffe100</item>
</style>
To change floating label color write following theme:
<style name="TextAppearence.App.TextInputLayout" parent="@android:style/TextAppearance">
<item name="android:textColor">#4ffd04[![enter image description here][1]][1]</item>
</style>
and use this theme in your layout:
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp"
app:hintTextAppearance="@style/TextAppearence.App.TextInputLayout">
<EditText
android:id="@+id/edtTxtFirstName_CompleteProfileOneActivity"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:capitalize="characters"
android:hint="User Name"
android:imeOptions="actionNext"
android:inputType="text"
android:singleLine="true"
android:textColor="@android:color/white" />
</android.support.design.widget.TextInputLayout>
If you have assigned a certain controller to your view, then your controller will be invoked every time your view loads. In that case, you can execute some code in your controller as soon as it is invoked, for example this way:
<ion-nav-view ng-controller="indexController" name="other" ng-init="doSomething()"></ion-nav-view>
And in your controller:
app.controller('indexController', function($scope) {
/*
Write some code directly over here without any function,
and it will be executed every time your view loads.
Something like this:
*/
$scope.xyz = 1;
});
Edit: You might try to track state changes and then execute some code when the route is changed and a certain route is visited, for example:
$rootScope.$on('$stateChangeSuccess',
function(event, toState, toParams, fromState, fromParams){ ... })
You can find more details here: State Change Events.
Ctrl+P and Type "ext install cpptools" it will install everything you need to debug c and c++.
Debugging in VS code is very complete, but if you just need to compile and run: https://code.visualstudio.com/docs/languages/cpp
Look in the debugging section and it will explain everything
You can use the --unset
flag of git config
to do this like so:
git config --global --unset user.name
git config --global --unset user.email
If you have more variables for one config you can use:
git config --global --unset-all user.name
A trunk is considered your main code base, a branch offshoot of the trunk. Like, you create a branch if you want to implement a new feature, but don't want to affect the main trunk.
TortoiseSVN has good documentation, and a great diff tool.
I use Visual studio, and I use VisualSVN and TortoiseSVN.
SuSE Linux Enterprise Server
Make sure you are editing the right file https://www.suse.com/documentation/sles11/book_sle_admin/data/sec_apache2_configuration.html
httpd.conf
The main Apache server configuration file. Avoid changing this file. It primarily contains include statements and global settings. Overwrite global settings in the pertinent configuration files listed here. Change host-specific settings (such as document root) in your virtual host configuration.
In such case vhosts.d/*.conf
must be edited
Here's a couple of suggestions:
Use date_range
for the index:
import datetime
import pandas as pd
import numpy as np
todays_date = datetime.datetime.now().date()
index = pd.date_range(todays_date-datetime.timedelta(10), periods=10, freq='D')
columns = ['A','B', 'C']
Note: we could create an empty DataFrame (with NaN
s) simply by writing:
df_ = pd.DataFrame(index=index, columns=columns)
df_ = df_.fillna(0) # with 0s rather than NaNs
To do these type of calculations for the data, use a numpy array:
data = np.array([np.arange(10)]*3).T
Hence we can create the DataFrame:
In [10]: df = pd.DataFrame(data, index=index, columns=columns)
In [11]: df
Out[11]:
A B C
2012-11-29 0 0 0
2012-11-30 1 1 1
2012-12-01 2 2 2
2012-12-02 3 3 3
2012-12-03 4 4 4
2012-12-04 5 5 5
2012-12-05 6 6 6
2012-12-06 7 7 7
2012-12-07 8 8 8
2012-12-08 9 9 9
Here are some solutions for all types of dialogs including a solution for AlertDialog.Builder that will work on all API levels (works below API 8, which the other answer here does not). There are solutions for AlertDialogs using AlertDialog.Builder, DialogFragment, and DialogPreference.
Below are the code examples showing how to override the default common button handler and prevent the dialog from closing for these different forms of dialogs. All the examples show how to prevent the positive button from closing the dialog.
Note: A description of how the dialog closing works under the hood for the base android classes and why the following approaches are chosen follows after the examples, for those who want more details
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Test for preventing dialog close");
builder.setPositiveButton("Test",
new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
//Do nothing here because we override this button later to change the close behaviour.
//However, we still need this because on older versions of Android unless we
//pass a handler the button doesn't get instantiated
}
});
final AlertDialog dialog = builder.create();
dialog.show();
//Overriding the handler immediately after show is probably a better approach than OnShowListener as described below
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Boolean wantToCloseDialog = false;
//Do stuff, possibly set wantToCloseDialog to true then...
if(wantToCloseDialog)
dialog.dismiss();
//else dialog stays open. Make sure you have an obvious way to close the dialog especially if you set cancellable to false.
}
});
@Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Test for preventing dialog close");
builder.setPositiveButton("Test",
new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
//Do nothing here because we override this button later to change the close behaviour.
//However, we still need this because on older versions of Android unless we
//pass a handler the button doesn't get instantiated
}
});
return builder.create();
}
//onStart() is where dialog.show() is actually called on
//the underlying dialog, so we have to do it there or
//later in the lifecycle.
//Doing it in onResume() makes sure that even if there is a config change
//environment that skips onStart then the dialog will still be functioning
//properly after a rotation.
@Override
public void onResume()
{
super.onResume();
final AlertDialog d = (AlertDialog)getDialog();
if(d != null)
{
Button positiveButton = (Button) d.getButton(Dialog.BUTTON_POSITIVE);
positiveButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Boolean wantToCloseDialog = false;
//Do stuff, possibly set wantToCloseDialog to true then...
if(wantToCloseDialog)
d.dismiss();
//else dialog stays open. Make sure you have an obvious way to close the dialog especially if you set cancellable to false.
}
});
}
}
@Override
protected void onPrepareDialogBuilder(Builder builder)
{
super.onPrepareDialogBuilder(builder);
builder.setPositiveButton("Test", this); //Set the button here so it gets created
}
@Override
protected void showDialog(Bundle state)
{
super.showDialog(state); //Call show on default first so we can override the handlers
final AlertDialog d = (AlertDialog) getDialog();
d.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Boolean wantToCloseDialog = false;
//Do stuff, possibly set wantToCloseDialog to true then...
if(wantToCloseDialog)
d.dismiss();
//else dialog stays open. Make sure you have an obvious way to close the dialog especially if you set cancellable to false.
}
});
}
Explanation of approaches:
Looking through Android source code the AlertDialog default implementation works by registering a common button handler to all the actual buttons in OnCreate(). When a button is clicked the common button handler forwards the click event to whatever handler you passed in setButton() then calls dismisses the dialog.
If you wish to prevent a dialog box from closing when one of these buttons is pressed you must replace the common button handler for the actual view of the button. Because it is assigned in OnCreate(), you must replace it after the default OnCreate() implementation is called. OnCreate is called in the process of the show() method. You could create a custom Dialog class and override OnCreate() to call the super.OnCreate() then override the button handlers, but if you make a custom dialog you don't get the Builder for free, in which case what is the point?
So, in using a dialog the way it is designed but with controlling when it is dismissed, one approach is to call dialog.Show() first, then obtain a reference to the button using dialog.getButton() to override the click handler. Another approach is to use setOnShowListener() and implement finding the button view and replacing the handler in the OnShowListener. The functional difference between the two is 'almost' nill, depending on what thread originally creates the dialog instance. Looking through the source code, the onShowListener gets called by a message posted to a handler running on the thread that created that dialog. So, since your OnShowListener is called by a message posted on the message queue it is technically possible that calling your listener is delayed some time after show completes.
Therefore, I believe the safest approach is the first: to call show.Dialog(), then immediately in the same execution path replace the button handlers. Since your code that calls show() will be operating on the main GUI thread, it means whatever code you follow show() with will be executed before any other code on that thread, whereas the timing of the OnShowListener method is at the mercy of the message queue.
When I try:
<input type="button" id="moreFields" onclick="alert('The text will be show!!'); return false;" value="Give me more fields!" />
It's worked well. So I think the problem is position of moreFields() function. Ensure that function will be define before your input tag.
Pls try:
<script type="text/javascript">
function moreFields() {
alert("The text will be show");
}
</script>
<input type="button" id="moreFields" onclick="moreFields()" value="Give me more fields!" />
Hope it helped.
For bootstrap 4 version this code working;
$('#payment-date-time-select').datetimepicker({
startView:2,
minView:2,
});
Compiled some answers from here into re-usable ClaimsManager class with my additions.
Claims got persisted, user cookie updated, sign in refreshed.
Please note that ApplicationUser can be substituted with IdentityUser if you didn't customize former. Also in my case it needs to have slightly different logic in Development environment, so you might want to remove IWebHostEnvironment dependency.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using YourMvcCoreProject.Models;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Hosting;
namespace YourMvcCoreProject.Identity
{
public class ClaimsManager
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly IWebHostEnvironment _env;
private readonly ClaimsPrincipalAccessor _currentPrincipalAccessor;
public ClaimsManager(
ClaimsPrincipalAccessor currentPrincipalAccessor,
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
IWebHostEnvironment env)
{
_currentPrincipalAccessor = currentPrincipalAccessor;
_userManager = userManager;
_signInManager = signInManager;
_env = env;
}
/// <param name="refreshSignin">Sometimes (e.g. when adding multiple claims at once) it is desirable to refresh cookie only once, for the last one </param>
public async Task AddUpdateClaim(string claimType, string claimValue, bool refreshSignin = true)
{
await AddClaim(
_currentPrincipalAccessor.ClaimsPrincipal,
claimType,
claimValue,
async user =>
{
await RemoveClaim(_currentPrincipalAccessor.ClaimsPrincipal, user, claimType);
},
refreshSignin);
}
public async Task AddClaim(string claimType, string claimValue, bool refreshSignin = true)
{
await AddClaim(_currentPrincipalAccessor.ClaimsPrincipal, claimType, claimValue, refreshSignin);
}
/// <summary>
/// At certain stages of user auth there is no user yet in context but there is one to work with in client code (e.g. calling from ClaimsTransformer)
/// that's why we have principal as param
/// </summary>
public async Task AddClaim(ClaimsPrincipal principal, string claimType, string claimValue, bool refreshSignin = true)
{
await AddClaim(
principal,
claimType,
claimValue,
async user =>
{
// allow reassignment in dev
if (_env.IsDevelopment())
await RemoveClaim(principal, user, claimType);
if (GetClaim(principal, claimType) != null)
throw new ClaimCantBeReassignedException(claimType);
},
refreshSignin);
}
public async Task RemoveClaims(IEnumerable<string> claimTypes, bool refreshSignin = true)
{
await RemoveClaims(_currentPrincipalAccessor.ClaimsPrincipal, claimTypes, refreshSignin);
}
public async Task RemoveClaims(ClaimsPrincipal principal, IEnumerable<string> claimTypes, bool refreshSignin = true)
{
AssertAuthenticated(principal);
foreach (var claimType in claimTypes)
{
await RemoveClaim(principal, claimType);
}
// reflect the change in the Identity cookie
if (refreshSignin)
await _signInManager.RefreshSignInAsync(await _userManager.GetUserAsync(principal));
}
public async Task RemoveClaim(string claimType, bool refreshSignin = true)
{
await RemoveClaim(_currentPrincipalAccessor.ClaimsPrincipal, claimType, refreshSignin);
}
public async Task RemoveClaim(ClaimsPrincipal principal, string claimType, bool refreshSignin = true)
{
AssertAuthenticated(principal);
var user = await _userManager.GetUserAsync(principal);
await RemoveClaim(principal, user, claimType);
// reflect the change in the Identity cookie
if (refreshSignin)
await _signInManager.RefreshSignInAsync(user);
}
private async Task AddClaim(ClaimsPrincipal principal, string claimType, string claimValue, Func<ApplicationUser, Task> processExistingClaims, bool refreshSignin)
{
AssertAuthenticated(principal);
var user = await _userManager.GetUserAsync(principal);
await processExistingClaims(user);
var claim = new Claim(claimType, claimValue);
ClaimsIdentity(principal).AddClaim(claim);
await _userManager.AddClaimAsync(user, claim);
// reflect the change in the Identity cookie
if (refreshSignin)
await _signInManager.RefreshSignInAsync(user);
}
/// <summary>
/// Due to bugs or as result of debug it can be more than one identity of the same type.
/// The method removes all the claims of a given type.
/// </summary>
private async Task RemoveClaim(ClaimsPrincipal principal, ApplicationUser user, string claimType)
{
AssertAuthenticated(principal);
var identity = ClaimsIdentity(principal);
var claims = identity.FindAll(claimType).ToArray();
if (claims.Length > 0)
{
await _userManager.RemoveClaimsAsync(user, claims);
foreach (var c in claims)
{
identity.RemoveClaim(c);
}
}
}
private static Claim GetClaim(ClaimsPrincipal principal, string claimType)
{
return ClaimsIdentity(principal).FindFirst(claimType);
}
/// <summary>
/// This kind of bugs has to be found during testing phase
/// </summary>
private static void AssertAuthenticated(ClaimsPrincipal principal)
{
if (!principal.Identity.IsAuthenticated)
throw new InvalidOperationException("User should be authenticated in order to update claims");
}
private static ClaimsIdentity ClaimsIdentity(ClaimsPrincipal principal)
{
return (ClaimsIdentity) principal.Identity;
}
}
public class ClaimCantBeReassignedException : Exception
{
public ClaimCantBeReassignedException(string claimType) : base($"{claimType} can not be reassigned")
{
}
}
public class ClaimsPrincipalAccessor
{
private readonly IHttpContextAccessor _httpContextAccessor;
public ClaimsPrincipalAccessor(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public ClaimsPrincipal ClaimsPrincipal => _httpContextAccessor.HttpContext.User;
}
// to register dependency put this into your Startup.cs and inject ClaimsManager into Controller constructor (or other class) the in same way as you do for other dependencies
public class Startup
{
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddTransient<ClaimsPrincipalAccessor>();
services.AddTransient<ClaimsManager>();
}
}
}
You can see the results in MB format, with the division of 1024 x 1024 which is equal to 1 MB.
int dataSize = 1024 * 1024;
System.out.println("Used Memory : " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory())/dataSize + " MB");
System.out.println("Free Memory : " + Runtime.getRuntime().freeMemory()/dataSize + " MB");
System.out.println("Total Memory : " + Runtime.getRuntime().totalMemory()/dataSize + " MB");
System.out.println("Max Memory : " + Runtime.getRuntime().maxMemory()/dataSize + " MB");
Simply replace
print $image;
with
echo '<img src=".$image." >';
I prefer to do this via a script nowadays
REM install the needed Windows IIS features for WCF
dism /Online /Enable-Feature /FeatureName:WAS-WindowsActivationService
dism /Online /Enable-Feature /FeatureName:WAS-ProcessModel
dism /Online /Enable-Feature /FeatureName:WAS-NetFxEnvironment
dism /Online /Enable-Feature /FeatureName:WAS-ConfigurationAPI
dism /Online /Enable-Feature /FeatureName:WCF-HTTP-Activation
dism /Online /Enable-Feature /FeatureName:WCF-HTTP-Activation45
REM Feature Install Complete
pause
Use HttpWebRequest.BeginGetResponse()
HttpWebRequest webRequest;
void StartWebRequest()
{
webRequest.BeginGetResponse(new AsyncCallback(FinishWebRequest), null);
}
void FinishWebRequest(IAsyncResult result)
{
webRequest.EndGetResponse(result);
}
The callback function is called when the asynchronous operation is complete. You need to at least call EndGetResponse()
from this function.
Python 3
class MyClass(object):
= New-style classclass MyClass:
= New-style class (implicitly inherits from object
)Python 2
class MyClass(object):
= New-style classclass MyClass:
= OLD-STYLE CLASSExplanation:
When defining base classes in Python 3.x, you’re allowed to drop the object
from the definition. However, this can open the door for a seriously hard to track problem…
Python introduced new-style classes back in Python 2.2, and by now old-style classes are really quite old. Discussion of old-style classes is buried in the 2.x docs, and non-existent in the 3.x docs.
The problem is, the syntax for old-style classes in Python 2.x is the same as the alternative syntax for new-style classes in Python 3.x. Python 2.x is still very widely used (e.g. GAE, Web2Py), and any code (or coder) unwittingly bringing 3.x-style class definitions into 2.x code is going to end up with some seriously outdated base objects. And because old-style classes aren’t on anyone’s radar, they likely won’t know what hit them.
So just spell it out the long way and save some 2.x developer the tears.
Lazy simple version for forgetfuls like me:
git rebase -i HEAD~3
or however many commits instead of 3.
Turn this
pick YourCommitMessageWhatever
pick YouGetThePoint
pick IdkManItsACommitMessage
into this
pick YourCommitMessageWhatever
s YouGetThePoint
s IdkManItsACommitMessage
and do some action where you hit esc
then enter
to save the changes. [1]
When the next screen comes up, get rid of those garbage # lines [2] and create a new commit message or something, and do the same escape
enter
action. [1]
Wowee, you have fewer commits. Or you just broke everything.
[1] - or whatever works with your git configuration. This is just a sequence that's efficient given my setup.
[2] - you'll see some stuff like # this is your n'th commit
a few times, with your original commits right below these message. You want to remove these lines, and create a commit message to reflect the intentions of the n commits that you're combining into 1.
Void return types / Subroutines are old news. I haven't made a Void return type (Unless I was being extremely lazy) in like 8 years (From the time of this answer, so just a bit before this question was asked).
Instead of a method like:
public void SendEmailToCustomer()
Make a method that follows Microsoft's int.TryParse() paradigm:
public bool TrySendEmailToCustomer()
Maybe there isn't any information your method needs to return for usage in the long-run, but returning the state of the method after it performs its job is a huge use to the caller.
Also, bool isn't the only state type. There are a number of times when a previously-made Subroutine could actually return three or more different states (Good, Normal, Bad, etc). In those cases, you'd just use
public StateEnum TrySendEmailToCustomer()
However, while the Try-Paradigm somewhat answers this question on how to test a void return, there are other considerations too. For example, during/after a "TDD" cycle, you would be "Refactoring" and notice you are doing two things with your method... thus breaking the "Single Responsibility Principle." So that should be taken care of first. Second, you might have idenetified a dependency... you're touching "Persistent" Data.
If you are doing the data access stuff in the method-in-question, you need to refactor into an n-tier'd or n-layer'd architecture. But we can assume that when you say "The strings are then inserted into a database", you actually mean you're calling a business logic layer or something. Ya, we'll assume that.
When your object is instantiated, you now understand that your object has dependencies. This is when you need to decide if you are going to do Dependency Injection on the Object, or on the Method. That means your Constructor or the method-in-question needs a new Parameter:
public <Constructor/MethodName> (IBusinessDataEtc otherLayerOrTierObject, string[] stuffToInsert)
Now that you can accept an interface of your business/data tier object, you can mock it out during Unit Tests and have no dependencies or fear of "Accidental" integration testing.
So in your live code, you pass in a REAL IBusinessDataEtc
object. But in your Unit Testing, you pass in a MOCK IBusinessDataEtc
object. In that Mock, you can include Non-Interface Properties like int XMethodWasCalledCount
or something whose state(s) are updated when the interface methods are called.
So your Unit Test will go through your Method(s)-In-Question, perform whatever logic they have, and call one or two, or a selected set of methods in your IBusinessDataEtc
object. When you do your Assertions at the end of your Unit Test you have a couple of things to test now.
IBusinessDataEtc
object.For more information on Dependency Injection ideas on the Construction-level... as they pertain to Unit Testing... look into Builder design patterns. It adds one more interface and class for each current interface/class you have, but they are very tiny and provide HUGE functionality increases for better Unit-Testing.
Here are a couple of quick functions I use when bash scripting Kafka Data Load into Demo Environments. In this example I use HDP with no security, but it is easily modified to other environments and intended to be quick and functional rather than particularly robust.
The first retrieves the address of the first ZooKeeper node from the config:
ZKS1=$(cat /usr/hdp/current/zookeeper-client/conf/zoo.cfg | grep server.1)
[[ ${ZKS1} =~ server.1=(.*?):[0-9]*:[0-9]* ]]
export ZKADDR=${BASH_REMATCH[1]}:2181
echo "using ZooKeeper Server $ZKADDR"
The second retrieves the Broker IDs from ZooKeeper:
echo "Fetching list of Kafka Brokers"
export BROKERIDS=$(/usr/hdp/current/kafka-broker/bin/zookeeper-shell.sh ${ZKADDR} <<< 'ls /brokers/ids' | tail -1)
export BROKERIDS=${BROKERIDS//[!0-9 ]/}
echo "Found Kafka Broker IDS: $BROKERIDS"
The third parses ZooKeeper again to retrieve the list of Kafka Brokers Host:port ready for use in the command-line client:
unset BROKERS
for i in $BROKERIDS
do
DETAIL=$(/usr/hdp/current/kafka-broker/bin/zookeeper-shell.sh ${ZKADDR} <<< "get /brokers/ids/$i")
[[ $DETAIL =~ PLAINTEXT:\/\/(.*?)\"\] ]]
if [ -z ${BROKERS+x} ]; then BROKERS=${BASH_REMATCH[1]}; else
BROKERS="${BROKERS},${BASH_REMATCH[1]}"; fi
done
echo "Found Brokerlist: $BROKERS"
You are 90% of the way there.
^[0-9,;]+$
Starting with the carat ^
indicates a beginning of line.
The [
indicates a character set
The 0-9
indicates characters 0 through 9, the comma ,
indicates comma, and the semicolon indicates a ;
.
The closing ]
indicates the end of the character set.
The plus +
indicates that one or more of the "previous item" must be present. In this case it means that you must have one or more of the characters in the previously declared character set.
The dollar $
indicates the end of the line.
Just read a single character
f.read(1)
As a complement to @JoshuaUlrich answer, here is the definition of function as.Date.character
:
as.Date.character
function (x, format = "", ...)
{
charToDate <- function(x) {
xx <- x[1L]
if (is.na(xx)) {
j <- 1L
while (is.na(xx) && (j <- j + 1L) <= length(x)) xx <- x[j]
if (is.na(xx))
f <- "%Y-%m-%d"
}
if (is.na(xx) || !is.na(strptime(xx, f <- "%Y-%m-%d",
tz = "GMT")) || !is.na(strptime(xx, f <- "%Y/%m/%d",
tz = "GMT")))
return(strptime(x, f))
stop("character string is not in a standard unambiguous format")
}
res <- if (missing(format))
charToDate(x)
else strptime(x, format, tz = "GMT")
as.Date(res)
}
<bytecode: 0x265b0ec>
<environment: namespace:base>
So basically if both strptime(x, format="%Y-%m-%d")
and strptime(x, format="%Y/%m/%d")
throws an NA
it is considered ambiguous and if not unambiguous.
this one seems to work for me in chrome
$("#selectid span option").unwrap();
$("#selectid option:not([filterattr=filtervalue])").wrap('<span/>');
Maybe you could find that out by looking at the query log.
I just had the same problem after accepting a Java update--scores of build errors and android import not recognized. On checking the build path in Project=>Properties, I found that the check box for Android 4.3 had somehow gotten cleared. Checking it resolved all the import errors without my even having to restart the IDE or run a project clean.
Complete working code would look like this:
<script>
$(document).ready(function(){
setInterval(function(){
$("#here").load(window.location.href + " #here" );
}, 3000);
});
</script>
<div id="here">dynamic content ?</div>
self reloading div container refreshing every 3 sec.
Call this function onclick of button
/*pass whatever you want instead of id */
function doConfirm(id) {
var ok = confirm("Are you sure to Delete?");
if (ok) {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
window.location = "create_dealer.php";
}
}
xmlhttp.open("GET", "delete_dealer.php?id=" + id);
// file name where delete code is written
xmlhttp.send();
}
}
I had a similar issue where I was receiving NoSuchBeanDefinitionException
in Spring Boot (basically while working on CRUD repository), I had to put the below annotations on the main class:
@SpringBootApplication
@EnableAutoConfiguration
@ComponentScan(basePackages={"<base package name>"})
@EnableJpaRepositories(basePackages="<repository package name>")
@EnableTransactionManagement
@EntityScan(basePackages="<entity package name>")
Also, make sure you have the @Component
annotations in place on the implementations.
I had a similar issue when not using inline
for my global function that was included in two places.
<?php
$variable1 = "foo";
$variable2 = "bar";
header('Location: http://linkhere.com?fieldname1=$variable1&fieldname2=$variable2&fieldname3=$variable3);
?>
This works without any quotations.
As of SLF4J 1.6.0, in the presence of multiple parameters and if the last argument in a logging statement is an exception, then SLF4J will presume that the user wants the last argument to be treated as an exception and not a simple parameter. See also the relevant FAQ entry.
So, writing (in SLF4J version 1.7.x and later)
logger.error("one two three: {} {} {}", "a", "b",
"c", new Exception("something went wrong"));
or writing (in SLF4J version 1.6.x)
logger.error("one two three: {} {} {}", new Object[] {"a", "b",
"c", new Exception("something went wrong")});
will yield
one two three: a b c
java.lang.Exception: something went wrong
at Example.main(Example.java:13)
at java.lang.reflect.Method.invoke(Method.java:597)
at ...
The exact output will depend on the underlying framework (e.g. logback, log4j, etc) as well on how the underlying framework is configured. However, if the last parameter is an exception it will be interpreted as such regardless of the underlying framework.
The quickest way would be to use an already-existing implementation, like uthash.
And, if you really want to code it yourself, the algorithms from uthash
can be examined and re-used. It's BSD-licensed so, other than the requirement to convey the copyright notice, you're pretty well unlimited in what you can do with it.
I'd like to make it simple for you. the reason of " 'DataFrame' object has no attribute 'Number'/'Close'/or any col name " is because you are looking at the col name and it seems to be "Number" but in reality it is " Number" or "Number " , that extra space is because in the excel sheet col name is written in that format. You can change it in excel or you can write data.columns = data.columns.str.strip() / df.columns = df.columns.str.strip() but the chances are that it will throw the same error in particular in some cases after the query. changing name in excel sheet will work definitely.
We need a JSON file which we need to export in the controller of angularjs and we should be able to call from the HTML file. We will look at both. But before we start, we need to first add two files in our angular library. Those two files are json-export-excel.js and filesaver.js. Moreover, we need to include the dependency in the angular module. So the first two steps can be summarised as follows -
1) Add json-export.js and filesaver.js in your angular library.
2) Include the dependency of ngJsonExportExcel in your angular module.
var myapp = angular.module('myapp', ['ngJsonExportExcel'])
Now that we have included the necessary files we can move on to the changes which need to be made in the HTML file and the controller. We assume that a json is being created on the controller either manually or by making a call to the backend.
HTML :
Current Page as Excel
All Pages as Excel
In the application I worked, I brought paginated results from the backend. Therefore, I had two options for exporting to excel. One for the current page and one for all data. Once the user selects an option, a call goes to the controller which prepares a json (list). Each object in the list forms a row in the excel.
Read more at - https://www.oodlestechnologies.com/blogs/Export-to-excel-using-AngularJS
I would prefer forceScheme
instead of doing it on a web server. So Laravel app should be responsible for it.
So right way is to add if statement inside boot
function in your app/Providers/AppServiceProvider.php
if (env('APP_ENV') === 'production') {
\Illuminate\Support\Facades\URL::forceScheme('https');
}
Tip: to prove that you have APP_ENV configured correctly. Go to your Linux server, type env
This was tested on Laravel 5, specifically 5.6.
After 2 hours of searching, I found a way to fix it with just one line of command. You need to know the version of the package (Just search up PACKAGE version).
Command:
python3 -m pip install --pre --upgrade PACKAGE==VERSION.VERSION.VERSION
It is possible to upack without node installed using the following 7-Zip plugin:
http://www.tc4shell.com/en/7zip/asar/
Thanks @MayaPosch for mentioning that in this comment.
Try:
SELECT A.id FROM
(
SELECT table1.id FROM table1
LEFT JOIN table2 ON table1.id = table2.user_one
WHERE table2.user_one IS NULL
) A
JOIN (
SELECT table1.id FROM table1
LEFT JOIN table2 ON table1.id = table2.user_two
WHERE table2.user_two IS NULL
) B
ON A.id = B.id
See Demo
Or you could use two LEFT JOINS
with aliases like:
SELECT table1.id FROM table1
LEFT JOIN table2 A ON table1.id = A.user_one
LEFT JOIN table2 B ON table1.id = B.user_two
WHERE A.user_one IS NULL
AND B.user_two IS NULL
See 2nd Demo
<a id="reset-authenticator" asp-page="./ResetAuthenticator"><input type="button" class="btn btn-primary" value="Reset app" /></a>
_x000D_
You can also use momentjs for this sort of things. Momentjs is best at parse, validate, manipulate, and display dates in JavaScript.
I used this pipe from Urish, which works fine for me:
https://github.com/urish/angular2-moment/blob/master/src/DateFormatPipe.ts
In the args parameter you can put your date format like: "dd/mm/yyyy"
Python3.x
The best aproach I could reach with my knowledge was this.
Note that this code treat set() too.
This approach is generic just needing the extension of class (in the second example).
Note that I'm just doing it to files, but it's easy to modify the behavior to your taste.
However this is a CoDec.
With a little more work you can construct your class in other ways. I assume a default constructor to instance it, then I update the class dict.
import json
import collections
class JsonClassSerializable(json.JSONEncoder):
REGISTERED_CLASS = {}
def register(ctype):
JsonClassSerializable.REGISTERED_CLASS[ctype.__name__] = ctype
def default(self, obj):
if isinstance(obj, collections.Set):
return dict(_set_object=list(obj))
if isinstance(obj, JsonClassSerializable):
jclass = {}
jclass["name"] = type(obj).__name__
jclass["dict"] = obj.__dict__
return dict(_class_object=jclass)
else:
return json.JSONEncoder.default(self, obj)
def json_to_class(self, dct):
if '_set_object' in dct:
return set(dct['_set_object'])
elif '_class_object' in dct:
cclass = dct['_class_object']
cclass_name = cclass["name"]
if cclass_name not in self.REGISTERED_CLASS:
raise RuntimeError(
"Class {} not registered in JSON Parser"
.format(cclass["name"])
)
instance = self.REGISTERED_CLASS[cclass_name]()
instance.__dict__ = cclass["dict"]
return instance
return dct
def encode_(self, file):
with open(file, 'w') as outfile:
json.dump(
self.__dict__, outfile,
cls=JsonClassSerializable,
indent=4,
sort_keys=True
)
def decode_(self, file):
try:
with open(file, 'r') as infile:
self.__dict__ = json.load(
infile,
object_hook=self.json_to_class
)
except FileNotFoundError:
print("Persistence load failed "
"'{}' do not exists".format(file)
)
class C(JsonClassSerializable):
def __init__(self):
self.mill = "s"
JsonClassSerializable.register(C)
class B(JsonClassSerializable):
def __init__(self):
self.a = 1230
self.c = C()
JsonClassSerializable.register(B)
class A(JsonClassSerializable):
def __init__(self):
self.a = 1
self.b = {1, 2}
self.c = B()
JsonClassSerializable.register(A)
A().encode_("test")
b = A()
b.decode_("test")
print(b.a)
print(b.b)
print(b.c.a)
Edit
With some more of research I found a way to generalize without the need of the SUPERCLASS register method call, using a metaclass
import json
import collections
REGISTERED_CLASS = {}
class MetaSerializable(type):
def __call__(cls, *args, **kwargs):
if cls.__name__ not in REGISTERED_CLASS:
REGISTERED_CLASS[cls.__name__] = cls
return super(MetaSerializable, cls).__call__(*args, **kwargs)
class JsonClassSerializable(json.JSONEncoder, metaclass=MetaSerializable):
def default(self, obj):
if isinstance(obj, collections.Set):
return dict(_set_object=list(obj))
if isinstance(obj, JsonClassSerializable):
jclass = {}
jclass["name"] = type(obj).__name__
jclass["dict"] = obj.__dict__
return dict(_class_object=jclass)
else:
return json.JSONEncoder.default(self, obj)
def json_to_class(self, dct):
if '_set_object' in dct:
return set(dct['_set_object'])
elif '_class_object' in dct:
cclass = dct['_class_object']
cclass_name = cclass["name"]
if cclass_name not in REGISTERED_CLASS:
raise RuntimeError(
"Class {} not registered in JSON Parser"
.format(cclass["name"])
)
instance = REGISTERED_CLASS[cclass_name]()
instance.__dict__ = cclass["dict"]
return instance
return dct
def encode_(self, file):
with open(file, 'w') as outfile:
json.dump(
self.__dict__, outfile,
cls=JsonClassSerializable,
indent=4,
sort_keys=True
)
def decode_(self, file):
try:
with open(file, 'r') as infile:
self.__dict__ = json.load(
infile,
object_hook=self.json_to_class
)
except FileNotFoundError:
print("Persistence load failed "
"'{}' do not exists".format(file)
)
class C(JsonClassSerializable):
def __init__(self):
self.mill = "s"
class B(JsonClassSerializable):
def __init__(self):
self.a = 1230
self.c = C()
class A(JsonClassSerializable):
def __init__(self):
self.a = 1
self.b = {1, 2}
self.c = B()
A().encode_("test")
b = A()
b.decode_("test")
print(b.a)
# 1
print(b.b)
# {1, 2}
print(b.c.a)
# 1230
print(b.c.c.mill)
# s
list comprehension formula:
[<value_when_condition_true> if <condition> else <value_when_condition_false> for value in list_name]
thus you can do it like this:
[y for y in a if y not in b]
Only for demonstration purpose : [y if y not in b else False for y in a ]
drop duplicate b_id
c = a.join(b, a.a_id == b.b_id).drop(b.b_id)
No need for basename, and especially no need for a subshell running pwd (which adds an extra, and expensive, fork operation); the shell can do this internally using parameter expansion:
result=${PWD##*/} # to assign to a variable
printf '%s\n' "${PWD##*/}" # to print to stdout
# ...more robust than echo for unusual names
# (consider a directory named -e or -n)
printf '%q\n' "${PWD##*/}" # to print to stdout, quoted for use as shell input
# ...useful to make hidden characters readable.
Note that if you're applying this technique in other circumstances (not PWD
, but some other variable holding a directory name), you might need to trim any trailing slashes. The below uses bash's extglob support to work even with multiple trailing slashes:
dirname=/path/to/somewhere//
shopt -s extglob # enable +(...) glob syntax
result=${dirname%%+(/)} # trim however many trailing slashes exist
result=${result##*/} # remove everything before the last / that still remains
printf '%s\n' "$result"
Alternatively, without extglob
:
dirname="/path/to/somewhere//"
result="${dirname%"${dirname##*[!/]}"}" # extglob-free multi-trailing-/ trim
result="${result##*/}" # remove everything before the last /
You have to use active in the label to make it work as mentioned above. But you can use checked="checked" and it will work too. It's not necessary but it's more legible and makes more sense as it is more html format compliance.
You could try using Linq to project the list:
var output = lst.Select(x => x % 2 == 0).ToList();
This will return a new list of bools such that {1, 2, 3, 4, 5}
will map to {false, true, false, true, false}
.
Try this code, it works for me.
public class Third extends ListActivity {
private ArrayAdapter<String> adapter;
private List<String> liste;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
"Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
"Linux", "OS/2" };
liste = new ArrayList<String>();
Collections.addAll(liste, values);
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, liste);
setListAdapter(adapter);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
liste.remove(position);
adapter.notifyDataSetChanged();
}
}
As a general rule, converting a Web Forms or MVC5 application to ASP.NET Core will require a significant amount of refactoring.
HttpContext.Current
was removed in ASP.NET Core. Accessing the current HTTP context from a separate class library is the type of messy architecture that ASP.NET Core tries to avoid. There are a few ways to re-architect this in ASP.NET Core.
You can access the current HTTP context via the HttpContext
property on any controller. The closest thing to your original code sample would be to pass HttpContext
into the method you are calling:
public class HomeController : Controller
{
public IActionResult Index()
{
MyMethod(HttpContext);
// Other code
}
}
public void MyMethod(Microsoft.AspNetCore.Http.HttpContext context)
{
var host = $"{context.Request.Scheme}://{context.Request.Host}";
// Other code
}
If you're writing custom middleware for the ASP.NET Core pipeline, the current request's HttpContext
is passed into your Invoke
method automatically:
public Task Invoke(HttpContext context)
{
// Do something with the current HTTP context...
}
Finally, you can use the IHttpContextAccessor
helper service to get the HTTP context in any class that is managed by the ASP.NET Core dependency injection system. This is useful when you have a common service that is used by your controllers.
Request this interface in your constructor:
public MyMiddleware(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
You can then access the current HTTP context in a safe way:
var context = _httpContextAccessor.HttpContext;
// Do something with the current HTTP context...
IHttpContextAccessor
isn't always added to the service container by default, so register it in ConfigureServices
just to be safe:
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpContextAccessor();
// if < .NET Core 2.2 use this
//services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
// Other code...
}
conda create -n py37 -c anaconda anaconda=5.3
seems to be working.
Hopefully, it will work for you.
startActivityForResult( intent, 1 , ActivityOptions.makeCustomAnimation(getActivity(),R.anim.slide_out_bottom,R.anim.slide_in_bottom).toBundle());
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:@"Title"
message:@"Message"
delegate:nil //or self
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
[alert autorelease];
I simplified the code Mikael Svensson provided which is correct for many countries in Europe.
public static DateTime FirstDateOfWeekIso8601(int year, int week)
{
var firstThursdayOfYear = new DateTime(year, 1, 1);
while (firstThursdayOfYear.DayOfWeek != DayOfWeek.Thursday)
{
firstThursdayOfYear = firstThursdayOfYear.AddDays(1);
}
var startDateOfWeekOne = firstThursdayOfYear.AddDays(-(DayOfWeek.Thursday - DayOfWeek.Monday));
return startDateOfWeekOne.AddDays(7 * (week - 1));
}
Great question, and great answer by Benjamin, Kris, et al - many thanks!
I'm using this in a project and have created a module based on Benjamin Gruenwald's code. It's available on npmjs:
npm i -S promise-spread
Then in your code, do
require('promise-spread');
If you're using a library such as any-promise
var Promise = require('any-promise');
require('promise-spread')(Promise);
Maybe others find this useful, too!
In the event that you already have a class and need to alternate between classes as oppose to add a class, you can chain toggle events:
$('li.multi').click(function(e) {
$(this).toggleClass('opened').toggleClass('multi-opened');
});
I handled this by attaching an event handler for all the events for which you are allowed to trigger audio to the body element which triggers any html audio elements with autoplay to play once.
var mobile = /iPad|iPhone|iPod|android/.test(navigator.userAgent) && !window.MSStream;
if (mobile) {
$('body').on('touchstart click doubleclick keydown', function() {
$("audio[autoplay='autoplay']").each(
function(){
this.play();
this.removeAttribute('autoplay');
});
});
}
The \
on it's own is used to escape special characters, such as \n
(new line), \t
(tabulation), \"
(quotes) when typing these specific values in a System.out.println()
statement.
Thus, if you want to print a backslash, \
, you can't have it on it's own since the compiler will be expecting a special character (such as the ones above). Thus, to print a backslash you need to escape it, since itself is also one of these special characters, thus, \\
yields \
.
in a Visual Basic Macro you would use
pName = ActiveWorkbook.Path ' the path of the currently active file
wbName = ActiveWorkbook.Name ' the file name of the currently active file
shtName = ActiveSheet.Name ' the name of the currently selected worksheet
The first sheet in a workbook can be referenced by
ActiveWorkbook.Worksheets(1)
so after deleting the [Report] tab you would use
ActiveWorkbook.Worksheets("Report").Delete
shtName = ActiveWorkbook.Worksheets(1).Name
to "work on that sheet later on" you can create a range object like
Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(shtName).[A1]
and continue working on MySheet(rowNum, colNum)
etc. ...
shortcut creation of a range object without defining shtName:
Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(1).[A1]
Here is a link to the official Docker documentation for proxy HTTP: https://docs.docker.com/config/daemon/systemd/#httphttps-proxy
A quick outline:
First, create a systemd drop-in directory for the Docker service:
mkdir /etc/systemd/system/docker.service.d
Now create a file called /etc/systemd/system/docker.service.d/http-proxy.conf
that adds the HTTP_PROXY
environment variable:
[Service]
Environment="HTTP_PROXY=http://proxy.example.com:80/"
If you have internal Docker registries that you need to contact without proxying you can specify them via the NO_PROXY
environment variable:
Environment="HTTP_PROXY=http://proxy.example.com:80/"
Environment="NO_PROXY=localhost,127.0.0.0/8,docker-registry.somecorporation.com"
Flush changes:
$ sudo systemctl daemon-reload
Verify that the configuration has been loaded:
$ sudo systemctl show --property Environment docker
Environment=HTTP_PROXY=http://proxy.example.com:80/
Restart Docker:
$ sudo systemctl restart docker
Yes (although it's a nasty hack). You can use a heredoc thus:
#!/bin/sh
# do valuable stuff here
touch /tmp/a
# now comment out all the stuff below up to the EOF
echo <<EOF
...
...
...
EOF
What's this doing ? A heredoc
feeds all the following input up to the terminator (in this case, EOF) into the nominated command. So you can surround the code you wish to comment out with
echo <<EOF
...
EOF
and it'll take all the code contained between the two EOFs and feed them to echo
(echo
doesn't read from stdin so it all gets thrown away).
Note that with the above you can put anything in the heredoc
. It doesn't have to be valid shell code (i.e. it doesn't have to parse properly).
This is very nasty, and I offer it only as a point of interest. You can't do the equivalent of C's /* ... */
Much easier way to view the signing certificate:
jarsigner.exe -verbose -verify -certs myapk.apk
This will only show the DN, so if you have two certs with the same DN, you might have to compare by fingerprint.
jQuery is required ;-)
<html>
<head>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<!-- THIS LINE -->
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="panel-group" id="accordion">
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#collapseOne">
Collapsible Group Item #1
</a>
</h4>
</div>
<div id="collapseOne" class="panel-collapse collapse in">
<div class="panel-body">
Anim pariatur cliche reprehenderit
</div>
</div>
</div>
</div>
</body>
</html>
You should look at the File method of the Controller. This is exactly what it's for. It returns a FilePathResult instead of an ActionResult.
With my solution you're able to get something similar:
Here is bulletproff solution:
Your html:
<input class='calendarIcon'/>
Your SVG: i used fa-calendar-alt
(any IDE may open svg image as shown below)
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><path d="M148 288h-40c-6.6 0-12-5.4-12-12v-40c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v40c0 6.6-5.4 12-12 12zm108-12v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm96 0v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm-96 96v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm-96 0v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm192 0v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm96-260v352c0 26.5-21.5 48-48 48H48c-26.5 0-48-21.5-48-48V112c0-26.5 21.5-48 48-48h48V12c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v52h128V12c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v52h48c26.5 0 48 21.5 48 48zm-48 346V160H48v298c0 3.3 2.7 6 6 6h340c3.3 0 6-2.7 6-6z"/></svg>
To use it at css background-image you gotta encode the svg to address valid string. I used this tool
As far as you got all stuff you need, you're coming to css
.calendarIcon{
//your url will be something like this:
background-image: url("data:image/svg+xml,***<here place encoded svg>***");
background-repeat: no-repeat;
}
Note: these styling wont have any effect on encoded svg image
.{
fill: #f00; //neither this
background-color: #f00; //nor this
}
because all changes over the image must be applied directly to its svg code
<svg xmlns="" path="" fill="#f00"/></svg>
To achive the location righthand i copied some Bootstrap spacing and my final css get the next look:
.calendarIcon{
background-image: url("data:image/svg+xml,%3Csvg...svg%3E");
background-repeat: no-repeat;
padding-right: calc(1.5em + 0.75rem);
background-position: center right calc(0.375em + 0.1875rem);
background-size: calc(0.75em + 0.375rem) calc(0.75em + 0.375rem);
}
I had just upgraded to VS 2013 from VS 2012 and the current user identity (HttpContext.User.Identity) was coming through as anonymous.
I tried changing the IIS express applicationhost.config, no difference.
The solution was to look at the properties of the web project, hit F4 to get the project properties when you have the top level of the project selected. Do not right click on the project and select properties, this is something entirely different.
Change Anonymous Authentication to be Disabled and Windows Authentication to be Enabled.
Works like gravy :)
For what it's worth, I had this problem - and the cause was invalid DWARF 3 info in the binary in the selected project (which didn't have any runnable binaries).
The way it work was something like this: I had two projects Main
and Library
. Main
depended on the Library
project and the former had an executable, while the latter just produced a static library (that Main
linked against).
My run option was set to "Run/Debug -> Launch" setting was set to "launch current, otherwise last" as follows (see bottom right):
If I had the Main
project selected, everything would work fine: it would launch the main project. If I had the Library
project selected1 it would fail with the error message given by the OP. The reason seemed to be this: since I had the Library
project selected, the PE scanner would scan the binary files in the project to see if any were launchable, and because scanning was failing due to this bug the error message popped up before it ever got to "Launch the previously launched application".
I could work around it by:
1 I wouldn't usually select the project directly, of course, it would be indirectly selected because I was working in one of the source files it contained.
:: savevars.bat
:: Use $ to prefix any important variable to save it for future runs.
@ECHO OFF
SETLOCAL
REM Load variables
IF EXIST config.txt FOR /F "delims=" %%A IN (config.txt) DO SET "%%A"
REM Change variables
IF NOT DEFINED $RunCount (
SET $RunCount=1
) ELSE SET /A $RunCount+=1
REM Display variables
SET $
REM Save variables
SET $>config.txt
ENDLOCAL
PAUSE
EXIT /B
Output:
$RunCount=1
$RunCount=2
$RunCount=3
The technique outlined above can also be used to share variables among multiple batch files.
I believe (and I am hardly well-versed in Python) that the main difference is that a tuple is immutable (it can't be changed in place after assignment) and a list is mutable (you can append, change, subtract, etc).
So, I tend to make my tuples things that shouldn't change after assignment and my lists things that can.
More portable to use ed; some systems don't support \n in sed
printf "/^lorem ipsum dolor sit amet/a\nconsectetur adipiscing elit\n.\nw\nq\n" |\
/bin/ed $filename
I know this question has many answers But these are not helped me. Below solution that helped me to resolve the error.
You have to go into your settings and allow this particular app.
Source “launchPackager.command” cannot be opened because it is from an unidentified developer
Say you naively wrote a student creation method like this:
void createStudent(String name) {
database.execute("INSERT INTO students (name) VALUES ('" + name + "')");
}
And someone enters the name Robert'); DROP TABLE STUDENTS; --
What gets run on the database is this query:
INSERT INTO students (name) VALUES ('Robert'); DROP TABLE STUDENTS --')
The semicolon ends the insert command and starts another; the -- comments out the rest of the line. The DROP TABLE command is executed...
This is why bind parameters are a good thing.
Try this
pd.set_option('display.height',1000)
pd.set_option('display.max_rows',500)
pd.set_option('display.max_columns',500)
pd.set_option('display.width',1000)
The arrow is a border.
You need to change for each arrow the color depending on the 'data-placement' of the tooltip.
.tooltip.top .tooltip-arrow {
border-top-color: @color;
}
.tooltip.top-left .tooltip-arrow {
border-top-color: @color;
}
.tooltip.top-right .tooltip-arrow {
border-top-color:@color;
}
.tooltip.right .tooltip-arrow {
border-right-color: @color;
}
.tooltip.left .tooltip-arrow {
border-left-color: @color;
}
.tooltip.bottom .tooltip-arrow {
border-bottom-color: @color;
}
.tooltip.bottom-left .tooltip-arrow {
border-bottom-color: @color;
}
.tooltip.bottom-right .tooltip-arrow {
border-bottom-color: @color;
}
.tooltip > .tooltip-inner {
background-color: @color;
}
Yes it's possible to change it to gray (no custom colors) but this only works from API 23 and above you only need to add this in your values-v23/styles.xml
<item name="android:windowLightStatusBar">true</item>
When you print a string in console(Eclipse),\n,\r and \r\n have the same effect,all of them will give you a new line;but \n\r(also \n\n,\r\r) will give you two new lines;when you write a string to a file,only \r\n can give you a new line.
This happens when you are trying to run application on emulator. Emulator does not have shared google maps library.
If your purpose is the isolation, I think Docker is what you want.
Vagrant is a virtual machine manager. It allows you to script the virtual machine configuration as well as the provisioning. However, it is still a virtual machine depending on VirtualBox (or others) with a huge overhead. It requires you to have a hard drive file that can be huge, it takes a lot of ram, and performance may be not very good.
Docker on the other hand uses kernel cgroup and namespacing via LXC. It means that you are using the same kernel as the host and the same file system.
You can use Dockerfile with the docker build
command in order to handle the provisioning and configuration of your container. You have an example at docs.docker.com on how to make your Dockerfile; it is very intuitive.
The only reason you could want to use Vagrant is if you need to do BSD, Windows or other non-Linux development on your Ubuntu box. Otherwise, go for Docker.
off topic but here is the formula for middle value.. just in case someone is looking for it
Math.Min(Math.Min(Math.Max(x,y), Math.Max(y,z)), Math.Max(x,z));
An alternate method that limits the scope of the lambda rather than giving it access to the whole this
is to pass in a local reference to the member variable, e.g.
auto& localGrid = grid;
int i;
for_each(groups.cbegin(),groups.cend(),[localGrid,&i](pair<int,set<int>> group){
i++;
cout<<i<<endl;
});
As discussed somewhat in the question comments, this is one way you could do it:
<input ... ng-model="$parent.storeDefault" value="{{location.id}}">
The above assumes that each location has a field (e.g., id) that holds a unique value.
Note that $parent.storeDefault is used because ng-repeat creates a child scope, and we want to manipulate the storeDefault parameter on the parent scope.
An interface is a contract that says “this object is able to do this thing”, whereas a trait is giving the object the ability to do the thing.
A trait is essentially a way to “copy and paste” code between classes.
I too got similar error when i misplaced the code
text=(TextView)findViewById(R.id.text);// this line has to be below setcontentview
setContentView(R.layout.activity_my_otype);
//this is the correct place
text.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
}
});
I got it working on placing the code in right order as shown below
setContentView(R.layout.activity_my_otype);
text=(TextView)findViewById(R.id.text);
text.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
}
});
You can parse the text as a string, which creates an Element, and create an ElementTree using that Element.
import xml.etree.ElementTree as ET
tree = ET.ElementTree(ET.fromstring(xmlstring))
I just came across this issue and the documentation, while complete, is not very straightforward on the difference in usage between the parse()
and fromstring()
methods.
PUT ing
PUT /binders/{id}/docs
Create or update, and relate a single document to a binder
e.g.:
PUT /binders/1/docs HTTP/1.1
{
"docNumber" : 1
}
PATCH ing
PATCH /docs
Create docs if they do not exist and relate them to binders
e.g.:
PATCH /docs HTTP/1.1
[
{ "op" : "add", "path" : "/binder/1/docs", "value" : { "doc_number" : 1 } },
{ "op" : "add", "path" : "/binder/8/docs", "value" : { "doc_number" : 8 } },
{ "op" : "add", "path" : "/binder/3/docs", "value" : { "doc_number" : 6 } }
]
I'll include additional insights later, but in the meantime if you want to, have a look at RFC 5789, RFC 6902 and William Durand's Please. Don't Patch Like an Idiot blog entry.
From:
http://hivelogic.com/articles/converting-from-mercurial-to-git
Migrating
It’s a relatively simple process. First we download fast-export (the best way is via its Git repository, which I’ll clone right to the desktop), then we create a new git repository, perform the migration, and check out the HEAD. On the command line, it goes like this:
cd ~/Desktop
git clone git://repo.or.cz/fast-export.git
git init git_repo
cd git_repo
~/Desktop/fast-export/hg-fast-export.sh -r /path/to/old/mercurial_repo
git checkout HEAD
You should see a long listing of commits fly by as your project is migrated after running fast-export. If you see errors, they are likely related to an improperly specified Python path (see the note above and customize for your system).
That’s it, you’re done.
If you are only concern about showing/hiding, this code would work just fine:
$("#leftDiv").hover(function(){$(this).css("overflow","scroll");},function(){$(this).css("overflow","hidden");});
However, it might modify some elements in your design, in case you are using width=100%, considering that when you hide the scrollbar, it creates a little bit of more room for your width.
Even if you are using IIS or apache, in my guess you are using static html page as a landing page, and by default the web server doesn't allow POST or GET verb on .html page, facebook calls your page via POST/GET verb
the solution would be to rename the page into .php or .aspx and you should be good to go :)
The +
allow 'select' only first not nested element , the >
select nested elements only - the better is to use ~
which allow to select arbitrary element which is child of parent hovered element. Using opacity/width and transition you can provide smooth appear
div { transition: all 1s }_x000D_
.ccc, .ggg { opacity: 0; color: red}_x000D_
.ccc { height: 0 }_x000D_
_x000D_
.aaa:hover ~ .bbb .ccc { opacity: 1; height: 34px }_x000D_
.aaa:hover ~ .eee .fff .ggg { opacity: 1 }
_x000D_
<div class="aaa">Hover me... to see<br><br> </div>_x000D_
_x000D_
<div class='bbb'>BBBBB_x000D_
<div class='ccc'>CCCCC_x000D_
<div class='ddd'>DDDDD</div>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<div class='eee'>EEEEE_x000D_
<div class='fff'>FFFFF_x000D_
<div class='ggg'>GGGGG</div>_x000D_
<div class='hhh'>HHHHH</div>_x000D_
</div>_x000D_
</div>
_x000D_
This problem is caused when including <windows.h>
before <winsock2.h>
. Try arrange your include list that <windows.h>
is included after <winsock2.h>
or define _WINSOCKAPI_
first:
#define _WINSOCKAPI_ // stops windows.h including winsock.h
#include <windows.h>
// ...
#include "MyClass.h" // Which includes <winsock2.h>
See also this.
You can use DataFrame.any
with parameter axis=1
for check at least one True
in row by DataFrame.isna
with boolean indexing
:
df1 = df[df.isna().any(axis=1)]
d = {'filename': ['M66_MI_NSRh35d32kpoints.dat', 'F71_sMI_DMRI51d.dat', 'F62_sMI_St22d7.dat', 'F41_Car_HOC498d.dat', 'F78_MI_547d.dat'], 'alpha1': [0.8016, 0.0, 1.721, 1.167, 1.897], 'alpha2': [0.9283, 0.0, 3.833, 2.809, 5.459], 'gamma1': [1.0, np.nan, 0.23748000000000002, 0.36419, 0.095319], 'gamma2': [0.074804, 0.0, 0.15, 0.3, np.nan], 'chi2min': [39.855990000000006, 1e+25, 10.91832, 7.966335000000001, 25.93468]}
df = pd.DataFrame(d).set_index('filename')
print (df)
alpha1 alpha2 gamma1 gamma2 chi2min
filename
M66_MI_NSRh35d32kpoints.dat 0.8016 0.9283 1.000000 0.074804 3.985599e+01
F71_sMI_DMRI51d.dat 0.0000 0.0000 NaN 0.000000 1.000000e+25
F62_sMI_St22d7.dat 1.7210 3.8330 0.237480 0.150000 1.091832e+01
F41_Car_HOC498d.dat 1.1670 2.8090 0.364190 0.300000 7.966335e+00
F78_MI_547d.dat 1.8970 5.4590 0.095319 NaN 2.593468e+01
Explanation:
print (df.isna())
alpha1 alpha2 gamma1 gamma2 chi2min
filename
M66_MI_NSRh35d32kpoints.dat False False False False False
F71_sMI_DMRI51d.dat False False True False False
F62_sMI_St22d7.dat False False False False False
F41_Car_HOC498d.dat False False False False False
F78_MI_547d.dat False False False True False
print (df.isna().any(axis=1))
filename
M66_MI_NSRh35d32kpoints.dat False
F71_sMI_DMRI51d.dat True
F62_sMI_St22d7.dat False
F41_Car_HOC498d.dat False
F78_MI_547d.dat True
dtype: bool
df1 = df[df.isna().any(axis=1)]
print (df1)
alpha1 alpha2 gamma1 gamma2 chi2min
filename
F71_sMI_DMRI51d.dat 0.000 0.000 NaN 0.0 1.000000e+25
F78_MI_547d.dat 1.897 5.459 0.095319 NaN 2.593468e+01
yeah you're not going to have much luck i think. Typically across the 3 drawing methods the major browsers use (Canvas, SVG, VML), text support is poor, I believe. If you want to rotate an image, then it's all good, but if you've got mixed content with formatting and styles, probably not.
Check out RaphaelJS for a cross-browser drawing API.
I hope this doesn't get downvoted, because in special circumstances it is the most reliable way to solve the problem. Any time the server allows you to get a Javascript resource using CORS (http://en.wikipedia.org/wiki/Cross-origin_resource_sharing), you have a rich array of options to do so.
Using XMLHttpRequest to fetch resources will work across all modern browsers, including IE. Since you are looking to load Javascript, you have Javascript available to you in the first place. You can track the progress using the readyState (http://en.wikipedia.org/wiki/XMLHttpRequest#The_onreadystatechange_event_listener). Finally, once you receive the content of the file, you can execute it with eval ( ). Yes, I said eval -- because security-wise it is no different from loading the script normally. In fact, a similar technique is suggested by John Resig to have nicer tags (http://ejohn.org/blog/degrading-script-tags/).
This method also lets you separate the loading from the eval, and execute functions before and after the eval happens. It becomes very useful when loading scripts in parallel but evaluating them one after the other -- something browsers can do easily when you place the tags in HTML, but don't let you by adding scripts at run-time with Javascript.
CORS is also preferable to JSONP for loading scripts (http://en.wikipedia.org/wiki/XMLHttpRequest#Cross-domain_requests). However, if you are developing your own third-party widgets to be embedded in other sites, you should actually load the Javascript files from your own domain in your own iframe (again, using AJAX)
In short:
Try to see if you can load the resource using AJAX GET
Use eval after it has successfully loaded
To improve it:
Check out the cache-control headers being sent
Look into otherwise caching the content in localStorage, if you need to
Check out Resig's "degrading javascript" for cleaner code
Check out require.js
static bool IsWholeNumber(double x)
{
return Math.Abs(x % 1) < double.Epsilon;
}
Swift version
Only trims spaces at the end of the String:
private func removingSpacesAtTheEndOfAString(var str: String) -> String {
var i: Int = countElements(str) - 1, j: Int = i
while(i >= 0 && str[advance(str.startIndex, i)] == " ") {
--i
}
return str.substringWithRange(Range<String.Index>(start: str.startIndex, end: advance(str.endIndex, -(j - i))))
}
Trims spaces on both sides of the String:
var str: String = " Yolo "
var trimmedStr: String = str.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
You started with ManyToOne mapping , then you put OneToMany mapping as well for BiDirectional way. Then at OneToMany side (usually your parent table/class), you have to mention "mappedBy" (mapping is done by and in child table/class), so hibernate will not create EXTRA mapping table in DB (like TableName = parent_child).
I faced same exception in eclipse neon version exception is like below
org.apache.jasper.JasperException: Unable to compile class for JSP:
An error occurred at line: 1 in the generated java file
The type java.io.ObjectInputStream cannot be resolved. It is indirectly referenced from required .class files
Stacktrace:
org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:92)
org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:330)
org.apache.jasper.compiler.JDTCompiler.generateClass(JDTCompiler.java:439)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:349)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:327)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:314)
org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:592)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:317)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
I using Apache tomcat 8 of maven plugin and i tried to update that but face same issue.
After i download new external apache tomcat version 8.5.14 and run project using this its will success for me
I hope some one to useful this for resolve above exception
Use below bash command to locate all virtual env in your system. You can modify the command according to your need to get in your desired format.
locate --regex "bin/activate"$ | sed 's/bin\/activate$//'
I had the same issue. And in my case the fix was pretty simple. The trick is to simply add the ".exe" to your compilers path. So, instead of :
SET(CMAKE_C_COMPILER C:/MinGW/bin/gcc)
It should be
SET(CMAKE_C_COMPILER C:/MinGW/bin/gcc.exe)
The same applies for g++.
lines2 = lines.split.join("\n")
Something like
select *
from foo
where regexp_like( col1, '[^[:alpha:]]' ) ;
should work
SQL> create table foo( col1 varchar2(100) );
Table created.
SQL> insert into foo values( 'abc' );
1 row created.
SQL> insert into foo values( 'abc123' );
1 row created.
SQL> insert into foo values( 'def' );
1 row created.
SQL> select *
2 from foo
3 where regexp_like( col1, '[^[:alpha:]]' ) ;
COL1
--------------------------------------------------------------------------------
abc123
Github Enterprise Solution
HTTPS_DOMAIN=https://git.your-company.com
ORGANISATION=org
REPO_NAME=my-amazing-library
FILE_PATH=path/to/some/file
BRANCH=develop
GITHUB_PERSONAL_ACCESS_TOKEN=<your-access-token>
URL="${HTTPS_DOMAIN}/raw/${ORGANISATION}/${REPO_NAME}/${BRANCH}/${FILE_PATH}"
curl -H "Authorization: token ${GITHUB_PERSONAL_ACCESS_TOKEN}" ${URL} > "${FILE_PATH}"
There is a nice example in Stoyan Stefanov's book JavaScript Patterns which suppose to handle all possible problems as well as utilize ECMAScript 5 method Array.isArray().
So here it is:
if (typeof Array.isArray === "undefined") {
Array.isArray = function (arg) {
return Object.prototype.toString.call(arg) === "[object Array]";
};
}
By the way, if you are using jQuery, you can use it's method $.isArray()
We make Webapps statefull by overriding HTTP stateless behaviour by using session objects.When we use session objets state is carried but we still use HTTP only.
Very interested problem. In my case this problem was caused when I tried to debug my tests on this similar line:
Boolean fooBar;
when(bar.getFoo()).thenReturn(fooBar);
The important note is that the tests were running correctly without debugging.
In any way, when I replaced above code with below code snippet then I was able to debug the problem line without problems.
doReturn(fooBar).when(bar).getFoo();
Use file this code
function move_file($path,$to){
if(copy($path, $to)){
unlink($path);
return true;
} else {
return false;
}
}
Consider building an Add-on that has an actual button and not using the outdated method of linking an image to a script function.
In the script editor, under the Help menu >> Welcome Screen >> link to Google Sheets Add-on - will give you sample code to use.
First, have program 1 write the string to stdout
(as if you'd like it to appear in screen). Then the second program should read a string from stdin
, as if a user was typing from a keyboard. then you run:
$ program_1 | program_2
Another way to do this without revert (traces of undo):
Don't do it if someone else has pushed other commits
Create a backup of your branch, being in your branch my-branch
. So in case something goes wrong, you can restart the process without losing any work done.
git checkout -b my-branch-temp
Go back to your branch.
git checkout my-branch
Reset, to discard your last commit (to undo it):
git reset --hard HEAD^
Remove the branch on remote (ex. origin
remote).
git push origin :my-branch
Repush your branch (without the unwanted commit) to the remote.
git push origin my-branch
Done!
I hope that helps! ;)
For those doing the upgrade path without also switching to TypeScript use:
ng.core.enableProdMode()
For me (in javascript) this looks like:
var upgradeAdapter = new ng.upgrade.UpgradeAdapter();
ng.core.enableProdMode()
upgradeAdapter.bootstrap(document.body, ['fooApp']);
Your XML is not entirely clear, but arrays XML can cause force closes if you make them numbers, and/or put white space in their definition.
Make sure they are defined like No Leading or Trailing Whitespace
This worked for me:
<?php
setlocale(LC_ALL, "en_US.utf8");
$val = iconv('UTF-8','ASCII//TRANSLIT',$val);
?>
The following uses EventTrigger
to show the Popup
. This means we don't need a ToggleButton
for state binding.
In this example the Click
event of a Button
is used. You can adapt it to use another element/event combination.
<Button x:Name="OpenPopup">Popup
<Button.Triggers>
<EventTrigger RoutedEvent="Button.Click">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<BooleanAnimationUsingKeyFrames
Storyboard.TargetName="ContextPopup"
Storyboard.TargetProperty="IsOpen">
<DiscreteBooleanKeyFrame KeyTime="0:0:0" Value="True" />
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
</Button.Triggers>
</Button>
<Popup x:Name="ContextPopup"
PlacementTarget="{Binding ElementName=OpenPopup}"
StaysOpen="False">
<Label>Popupcontent...</Label>
</Popup>
Please note that the Popup
is referencing the Button
by name and vice versa. So x:Name="..."
is required on both, the Popup
and the Button
.
It can actually be further simplified by replacing the Storyboard
stuff with a custom SetProperty
EventTrigger Action described in this SO Answer
This is expanding upon the answer from @Dunc . See xml doc comments
// ReSharper disable CheckNamespace
using System.Linq;
using System.Web.Mvc;
public static class Debugg
{
/// <summary>
/// This class is for debugging ModelState errors either in the quick watch
/// window or the immediate window.
/// When the model state contains dozens and dozens of properties,
/// it is impossible to inspect why a model state is invalid.
/// This method will pull up the errors
/// </summary>
/// <param name="modelState">modelState</param>
/// <returns></returns>
public static ModelError[] It(ModelStateDictionary modelState)
{
var errors = modelState.Values.SelectMany(x => x.Errors).ToArray();
return errors;
}
}
If someone wants to implement using directives then, identify (or create) a div in the index.html (just under the body tag, or at same DOM level)
<div class="google-analytics"/>
and then add the following code in the directive
myApp.directive('googleAnalytics', function ( $location, $window ) {
return {
scope: true,
link: function (scope) {
scope.$on( '$routeChangeSuccess', function () {
$window._gaq.push(['_trackPageview', $location.path()]);
});
}
};
});
To expound on Stephane's answer.
I got this error when I tried to grant remote connections privileges of a particular database to a root
user on MySQL server by running the command:
USE database_name;
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%';
This gave an error:
ERROR 1133 (42000): Can't find any matching row in the user table
Here's how I fixed it:
First, confirm that your MySQL server allows for remote connections. Use your preferred text editor to open the MySQL server configuration file:
sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf
Scroll down to the bind-address line and ensure that is either commented out or replaced with 0.0.0.0
(to allow all remote connections) or replaced with Ip-Addresses that you want remote connections from.
Once you make the necessary changes, save and exit the configuration file. Apply the changes made to the MySQL config file by restarting the MySQL service:
sudo systemctl restart mysql
Next, log into the MySQL server console on the server it was installed:
mysql -u root -p
Enter your mysql user password
Check the hosts that the user you want has access to already. In my case the user is root
:
SELECT host FROM mysql.user WHERE user = "root";
This gave me this output:
+-----------+
| host |
+-----------+
| localhost |
+-----------+
Next, I ran the command below which is similar to the previous one that was throwing errors, but notice that I added a password to it this time:
USE database_name;
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'my-password';
Note: %
grants a user remote access from all hosts on a network. You can specify the Ip-Address of the individual hosts that you want to grant the user access from using the command - GRANT ALL PRIVILEGES ON *.* TO 'root'@'Ip-Address' IDENTIFIED BY 'my-password';
Afterwhich I checked the hosts that the user now has access to. In my case the user is root
:
SELECT host FROM mysql.user WHERE user = "root";
This gave me this output:
+-----------+
| host |
+-----------+
| % |
| localhost |
+-----------+
Finally, you can try connecting to the MySQL server from another server using the command:
mysql -u username -h mysql-server-ip-address -p
Where u represents user, h represents mysql-server-ip-address and p represents password. So in my case it was:
mysql -u root -h 34.69.261.158 -p
Enter your mysql user password
You should get this output depending on your MySQL server version:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 4
Server version: 5.7.31 MySQL Community Server (GPL)
Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
Resources: How to Allow Remote Connections to MySQL
That's all.
I hope this helps
The problem:
java.lang.ClassNotFoundException: org.glassfish.jersey.servlet.ServletContainer
indicates that you try to use the Jersey 2.x servlet, but you are supplying the Jersey 1.x libs.
For Jersey 1.x you have to do it like this:
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>
com.sun.jersey.spi.container.servlet.ServletContainer
</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>sample.hello.resources</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
For more information check the Jersey 1.x documentation.
If you instead want to use Jersey 2.x then you'll have to supply the Jersey 2.x libs. In a maven based project you can use the following:
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>2.xx</version>
</dependency>
<!-- if you are using Jersey client specific features without the server side -->
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.xx</version>
</dependency>
For Jersey 2.x you don't need to setup anything in your web.xml
, it is sufficient to supply a class similar to this:
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
@ApplicationPath("rest")
public class ApplicationConfig extends Application {
}
For more information, check the Jersey documentation.
See also:
many answers above, i will try a different way:
if you are looking for bitwise operations use only one of the marks like:
3 & 1 //==1 - and 4 | 1 //==5 - or
This works i tried it my self i thought i post it here in case someone need it...
document.getElementById("newSkill").options[document.getElementById('newSkill').selectedIndex].text;
I don't know if it's entirely possible to do your ideal pattern. But I found a way to do your first way: CountIF
+-------+-------------------+
| A | B |
+-------+-------------------+
| GL15 | =COUNTIF(A:A, A1) |
+-------+-------------------+
| GL15 | =COUNTIF(A:A, A2) |
+-------+-------------------+
| GL15 | =COUNTIF(A:A, A3) |
+-------+-------------------+
| GL16 | =COUNTIF(A:A, A4) |
+-------+-------------------+
| GL17 | =COUNTIF(A:A, A5) |
+-------+-------------------+
| GL17 | =COUNTIF(A:A, A6) |
+-------+-------------------+
This will find the first parent with class box
then find the first child class with regex matching something
and get the id.
$(".mylink").closest(".box").find('[class*="something"]').first().attr("id")
You could use a colormap such as HSV to generate a set of colors. For example:
cc=hsv(12);
figure;
hold on;
for i=1:12
plot([0 1],[0 i],'color',cc(i,:));
end
MATLAB has 13 different named colormaps ('doc colormap' lists them all).
Another option for plotting lines in different colors is to use the LineStyleOrder property; see Defining the Color of Lines for Plotting in the MATLAB documentation for more information.
Non of the above mentioned solutions worked for me. Below is what finally worked:
#yum update
#yum install phpmyadmin
Be advised, phpmyadmin was working a few hours earlier. I don't know what happened.
After this, going to the browser, I got an error that said ./config.inic.php can't be accessed
#cd /usr/share/phpmyadmin/
#stat -c %a config.inic.php
#640
#chmod 644 config.inic.php
This shows that the file permissions were 640, then I changed them to 644. Finially, it worked.
Remember to restart httpd.
#service httpd restart
CFGregorianDate currentDate = CFAbsoluteTimeGetGregorianDate(CFAbsoluteTimeGetCurrent(), CFTimeZoneCopySystem());
countdownLabel.text = [NSString stringWithFormat:@"%02d:%02d:%2.0f", currentDate.hour, currentDate.minute, currentDate.second];
Mark was right this code is MUCH more efficient to manage dates hours min and secs. But he forgot the @ at the beginning of format string declaration.
For something reusable:
template<template <typename> class P = std::less >
struct compare_pair_second {
template<class T1, class T2> bool operator()(const std::pair<T1, T2>& left, const std::pair<T1, T2>& right) {
return P<T2>()(left.second, right.second);
}
};
You can use it as
std::sort(foo.begin(), foo.end(), compare_pair_second<>());
or
std::sort(foo.begin(), foo.end(), compare_pair_second<std::less>());
Documentation of Math.round
says:
Returns the result of rounding the argument to an integer. The result is equivalent to
(int) Math.floor(f+0.5)
.
No need to cast to int
. Maybe it was changed from the past.
I think this is nature of tcp connections, in that standards it takes about 6 minutes of silence in transmission before we conclude that out connection is gone! So I don`t think you can find an exact solution for this problem. Maybe the better way is to write some handy code to guess when server should suppose a user connection is closed.
Just a note: if you use arrow functions you don't need the const that = this part. It might look like this:
fetch('http://jsonplaceholder.typicode.com/posts')
.then((response) => { return response.json(); })
.then((myJson) => {
this.setState({data: myJson}); // for example
});
I have found simpler solution:
$('#clickToCreate').live('click', function() {
$('#yourDialogId')
.dialog({
title: "Set the title to Create"
})
.dialog('open');
});
$('#clickToEdit').live('click', function() {
$('#yourDialogId')
.dialog({
title: "Set the title To Edit"
})
.dialog('open');
});
Hope that helps!
Note: The placement of cross_origin should be right and dependencies are installed. On the client side, ensure to specify kind of data server is consuming. For example application/json or text/html
For me the code written below did magic
from flask import Flask,request,jsonify
from flask_cors import CORS,cross_origin
app=Flask(__name__)
CORS(app, support_credentials=True)
@app.route('/api/test', methods=['POST', 'GET','OPTIONS'])
@cross_origin(supports_credentials=True)
def index():
if(request.method=='POST'):
some_json=request.get_json()
return jsonify({"key":some_json})
else:
return jsonify({"GET":"GET"})
if __name__=="__main__":
app.run(host='0.0.0.0', port=5000)
Here is a Python function that splits a Pandas dataframe into train, validation, and test dataframes with stratified sampling. It performs this split by calling scikit-learn's function train_test_split()
twice.
import pandas as pd
from sklearn.model_selection import train_test_split
def split_stratified_into_train_val_test(df_input, stratify_colname='y',
frac_train=0.6, frac_val=0.15, frac_test=0.25,
random_state=None):
'''
Splits a Pandas dataframe into three subsets (train, val, and test)
following fractional ratios provided by the user, where each subset is
stratified by the values in a specific column (that is, each subset has
the same relative frequency of the values in the column). It performs this
splitting by running train_test_split() twice.
Parameters
----------
df_input : Pandas dataframe
Input dataframe to be split.
stratify_colname : str
The name of the column that will be used for stratification. Usually
this column would be for the label.
frac_train : float
frac_val : float
frac_test : float
The ratios with which the dataframe will be split into train, val, and
test data. The values should be expressed as float fractions and should
sum to 1.0.
random_state : int, None, or RandomStateInstance
Value to be passed to train_test_split().
Returns
-------
df_train, df_val, df_test :
Dataframes containing the three splits.
'''
if frac_train + frac_val + frac_test != 1.0:
raise ValueError('fractions %f, %f, %f do not add up to 1.0' % \
(frac_train, frac_val, frac_test))
if stratify_colname not in df_input.columns:
raise ValueError('%s is not a column in the dataframe' % (stratify_colname))
X = df_input # Contains all columns.
y = df_input[[stratify_colname]] # Dataframe of just the column on which to stratify.
# Split original dataframe into train and temp dataframes.
df_train, df_temp, y_train, y_temp = train_test_split(X,
y,
stratify=y,
test_size=(1.0 - frac_train),
random_state=random_state)
# Split the temp dataframe into val and test dataframes.
relative_frac_test = frac_test / (frac_val + frac_test)
df_val, df_test, y_val, y_test = train_test_split(df_temp,
y_temp,
stratify=y_temp,
test_size=relative_frac_test,
random_state=random_state)
assert len(df_input) == len(df_train) + len(df_val) + len(df_test)
return df_train, df_val, df_test
Below is a complete working example.
Consider a dataset that has a label upon which you want to perform the stratification. This label has its own distribution in the original dataset, say 75% foo
, 15% bar
and 10% baz
. Now let's split the dataset into train, validation, and test into subsets using a 60/20/20 ratio, where each split retains the same distribution of the labels. See the illustration below:
Here is the example dataset:
df = pd.DataFrame( { 'A': list(range(0, 100)),
'B': list(range(100, 0, -1)),
'label': ['foo'] * 75 + ['bar'] * 15 + ['baz'] * 10 } )
df.head()
# A B label
# 0 0 100 foo
# 1 1 99 foo
# 2 2 98 foo
# 3 3 97 foo
# 4 4 96 foo
df.shape
# (100, 3)
df.label.value_counts()
# foo 75
# bar 15
# baz 10
# Name: label, dtype: int64
Now, let's call the split_stratified_into_train_val_test()
function from above to get train, validation, and test dataframes following a 60/20/20 ratio.
df_train, df_val, df_test = \
split_stratified_into_train_val_test(df, stratify_colname='label', frac_train=0.60, frac_val=0.20, frac_test=0.20)
The three dataframes df_train
, df_val
, and df_test
contain all the original rows but their sizes will follow the above ratio.
df_train.shape
#(60, 3)
df_val.shape
#(20, 3)
df_test.shape
#(20, 3)
Further, each of the three splits will have the same distribution of the label, namely 75% foo
, 15% bar
and 10% baz
.
df_train.label.value_counts()
# foo 45
# bar 9
# baz 6
# Name: label, dtype: int64
df_val.label.value_counts()
# foo 15
# bar 3
# baz 2
# Name: label, dtype: int64
df_test.label.value_counts()
# foo 15
# bar 3
# baz 2
# Name: label, dtype: int64
Github did this using the HTML canvas element.
This specification defines the 2D Context for the HTML canvas element. The 2D Context provides objects, methods, and properties to draw and manipulate graphics on a canvas drawing surface.
If you use a browser inspector, you see inside every list element a div with a canvas element.
<div class="participation-graph">
<canvas class="bars" data-color-all="#F5F5F5" data-color-owner="#F5F5F5" data-source="/mxcl/homebrew/graphs/owner_participation" height="80" width="640"></canvas>
</div>
With CSS (z-index, position...) you can put that canvas in the background of a li element or table, in your case.
Do a search about jquery pluggins that fit your requirement.
Hope this pointers help you to achieve that.
Volatile is also useful, when you want to force the compiler not to optimize a specific code sequence (e.g. for writing a micro-benchmark).
This will re-size any image using the best quality with support for 32bpp with alpha. The new image will have the original image centered inside the new one at the original aspect ratio.
#Region " ResizeImage "
Public Overloads Shared Function ResizeImage(SourceImage As Drawing.Image, TargetWidth As Int32, TargetHeight As Int32) As Drawing.Bitmap
Dim bmSource = New Drawing.Bitmap(SourceImage)
Return ResizeImage(bmSource, TargetWidth, TargetHeight)
End Function
Public Overloads Shared Function ResizeImage(bmSource As Drawing.Bitmap, TargetWidth As Int32, TargetHeight As Int32) As Drawing.Bitmap
Dim bmDest As New Drawing.Bitmap(TargetWidth, TargetHeight, Drawing.Imaging.PixelFormat.Format32bppArgb)
Dim nSourceAspectRatio = bmSource.Width / bmSource.Height
Dim nDestAspectRatio = bmDest.Width / bmDest.Height
Dim NewX = 0
Dim NewY = 0
Dim NewWidth = bmDest.Width
Dim NewHeight = bmDest.Height
If nDestAspectRatio = nSourceAspectRatio Then
'same ratio
ElseIf nDestAspectRatio > nSourceAspectRatio Then
'Source is taller
NewWidth = Convert.ToInt32(Math.Floor(nSourceAspectRatio * NewHeight))
NewX = Convert.ToInt32(Math.Floor((bmDest.Width - NewWidth) / 2))
Else
'Source is wider
NewHeight = Convert.ToInt32(Math.Floor((1 / nSourceAspectRatio) * NewWidth))
NewY = Convert.ToInt32(Math.Floor((bmDest.Height - NewHeight) / 2))
End If
Using grDest = Drawing.Graphics.FromImage(bmDest)
With grDest
.CompositingQuality = Drawing.Drawing2D.CompositingQuality.HighQuality
.InterpolationMode = Drawing.Drawing2D.InterpolationMode.HighQualityBicubic
.PixelOffsetMode = Drawing.Drawing2D.PixelOffsetMode.HighQuality
.SmoothingMode = Drawing.Drawing2D.SmoothingMode.AntiAlias
.CompositingMode = Drawing.Drawing2D.CompositingMode.SourceOver
.DrawImage(bmSource, NewX, NewY, NewWidth, NewHeight)
End With
End Using
Return bmDest
End Function
#End Region
The problem with Threading.Thread.SLeep(2000)
is that it executes first in my VB.Net program. This
Imports VB = Microsoft.VisualBasic
Public Sub wait(ByVal seconds As Single)
Static start As Single
start = VB.Timer()
Do While VB.Timer() < start + seconds
System.Windows.Forms.Application.DoEvents()
Loop
End Sub
worked flawlessly.
As others have pointed out one could just delete all the files in the repo and then check them out. I prefer this method and it can be done with the code below
git ls-files -z | xargs -0 rm
git checkout -- .
or one line
git ls-files -z | xargs -0 rm ; git checkout -- .
I use it all the time and haven't found any down sides yet!
For some further explanation, the -z
appends a null character onto the end of each entry output by ls-files
, and the -0
tells xargs
to delimit the output it was receiving by those null characters.
Finally after comparing all solution, I think starting from build.gradle
file can be convenient.
Gradle distribution has samples
folder with a lot of examples, and there is gradle init --type basic
comand see Chapter 47. Build Init Plugin. But they all needs some editing.
You can use template below as well, then run gradle initSourceFolders eclipse
/*
* Nodeclipse/Enide build.gradle template for basic Java project
* https://github.com/Nodeclipse/nodeclipse-1/blob/master/org.nodeclipse.enide.editors.gradle/docs/java/basic/build.gradle
* Initially asked on
* http://stackoverflow.com/questions/14017364/how-to-create-java-gradle-project
* Usage
* 1. create folder (or general Eclipse project) and put this file inside
* 2. run `gradle initSourceFolders eclipse` or `gradle initSourceFolders idea`
* @author Paul Verest;
* based on `gradle init --type basic`, that does not create source folders
*/
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
task initSourceFolders { // add << before { to prevent executing during configuration phase
sourceSets*.java.srcDirs*.each { it.mkdirs() }
sourceSets*.resources.srcDirs*.each { it.mkdirs() }
}
task wrapper(type: Wrapper) {
gradleVersion = '1.11'
}
// In this section you declare where to find the dependencies of your project
repositories {
// Use Maven Central for resolving your dependencies.
// You can declare any Maven/Ivy/file repository here.
mavenCentral()
}
// In this section you declare the dependencies for your production and test code
dependencies {
//compile fileTree(dir: 'libs', include: '*.jar')
// The production code uses the SLF4J logging API at compile time
//compile 'org.slf4j:slf4j-api:1.7.5'
// Declare the dependency for your favourite test framework you want to use in your tests.
// TestNG is also supported by the Gradle Test task. Just change the
// testCompile dependency to testCompile 'org.testng:testng:6.8.1' and add
// 'test.useTestNG()' to your build script.
testCompile "junit:junit:4.11"
}
The result is like below.
That can be used without any Gradle plugin for Eclipse,
or with (Enide) Gradle for Eclipse, Jetty, Android alternative to Gradle Integration for Eclipse
You don't have JSON. You have a JavaScript data structure consisting of objects, an array, some strings and some numbers.
Use JSON.stringify(object)
to turn it into (a string of) JSON text.
in your Xcode:
The name of an array is the address of its first element, so name
is a pointer to memory containing the string "siva".
Also you don't need a pointer to display a character; you are just electing to use it directly from the array in this case. You could do this instead:
char c = *name;
printf("%c\n", c);
In my case I wasn't sure what had caused this to happen, but I knew I just wanted the submodules to be reset to their latest remote commit and be done with it. This involved combining answers from a couple of different questions on here:
git submodule update --recursive --remote --init
Sources:
You can use function closures as data in larger expressions as well, as in this method of determining browser support for some of the html5 objects.
navigator.html5={
canvas: (function(){
var dc= document.createElement('canvas');
if(!dc.getContext) return 0;
var c= dc.getContext('2d');
return typeof c.fillText== 'function'? 2: 1;
})(),
localStorage: (function(){
return !!window.localStorage;
})(),
webworkers: (function(){
return !!window.Worker;
})(),
offline: (function(){
return !!window.applicationCache;
})()
}
Using SQL Server Management Studio
To configure the default language option
English
.Using Transact-SQL
To configure the default language option
This example shows how to use sp_configure to configure the default language option to French
USE AdventureWorks2012 ;
GO
EXEC sp_configure 'default language', 2 ;
GO
RECONFIGURE ;
GO
The 33 languages of SQL Server
| LANGID | ALIAS |
|--------|---------------------|
| 0 | English |
| 1 | German |
| 2 | French |
| 3 | Japanese |
| 4 | Danish |
| 5 | Spanish |
| 6 | Italian |
| 7 | Dutch |
| 8 | Norwegian |
| 9 | Portuguese |
| 10 | Finnish |
| 11 | Swedish |
| 12 | Czech |
| 13 | Hungarian |
| 14 | Polish |
| 15 | Romanian |
| 16 | Croatian |
| 17 | Slovak |
| 18 | Slovenian |
| 19 | Greek |
| 20 | Bulgarian |
| 21 | Russian |
| 22 | Turkish |
| 23 | British English |
| 24 | Estonian |
| 25 | Latvian |
| 26 | Lithuanian |
| 27 | Brazilian |
| 28 | Traditional Chinese |
| 29 | Korean |
| 30 | Simplified Chinese |
| 31 | Arabic |
| 32 | Thai |
| 33 | Bokmål |
spring.data.mongodb.host
and spring.data.mongodb.port
are not supported if you’re using the Mongo 3.0 Java driver. In such cases, spring.data.mongodb.uri
should be used to provide all of the configuration, like this:
spring.data.mongodb.uri=mongodb://user:[email protected]:12345
this might help. It worked for me. try it in the terminal
setenforce 0
Just call getTime on each, take the difference, and divide by the number of milliseconds in a day.
Box-Muller implementation:
#include <cstdlib>
#include <cmath>
#include <ctime>
#include <iostream>
using namespace std;
// return a uniformly distributed random number
double RandomGenerator()
{
return ( (double)(rand()) + 1. )/( (double)(RAND_MAX) + 1. );
}
// return a normally distributed random number
double normalRandom()
{
double y1=RandomGenerator();
double y2=RandomGenerator();
return cos(2*3.14*y2)*sqrt(-2.*log(y1));
}
int main(){
double sigma = 82.;
double Mi = 40.;
for(int i=0;i<100;i++){
double x = normalRandom()*sigma+Mi;
cout << " x = " << x << endl;
}
return 0;
}
Just to add - Safari 2 and earlier definitely didn't support PUT and DELETE. I get the impression 3 did, but I don't have it around to test anymore. Safari 4 definitely does support PUT and DELETE.
This works:
SELECT STR_TO_DATE(dateColumn, '%c/%e/%Y %r') FROM tabbleName WHERE 1
You must define the class before creating an instance of the class. Move the invocation of Something
to the end of the script.
You can try to put the cart before the horse and invoke procedures before they are defined, but it will be an ugly hack and you will have to roll your own as defined here:
I had the same problem, and solved it as follows:
Actually I want to show Message and close it automatically after 2 second. For that I had to generate (dynamically) simple form and one label showing message, stop message for 1500 ms so user read it. And Close dynamically created form. Shown event occur After load event. So code is
Form MessageForm = new Form();
MessageForm.Shown += (s, e1) => {
Thread t = new Thread(() => Thread.Sleep(1500));
t.Start();
t.Join();
MessageForm.Close();
};
In the final version of Angular 2.x / 4.x - here's the docs https://angular.io/api/common/Location
/* typescript */
import { Location } from '@angular/common';
// import stuff here
@Component({
// declare component here
})
export class MyComponent {
// inject location into component constructor
constructor(private location: Location) { }
cancel() {
this.location.back(); // <-- go back to previous location on cancel
}
}
You have "int* arr" so "arr[n]" is an int, right? Then your "[M - 1 + 1]" bit is trying to use that int as an array/pointer/vector.
There are two problems in your code:
visibility
and not visiblity
..style
property.It's easy to fix. Simple replace this:
document.getElementById("remember").visiblity
with this:
document.getElementById("remember").style.visibility