Although this question has already been answered, I think this approach is better : http://jsfiddle.net/kjy112/3CvaD/ extract from this question on StackOverFlow google maps - open marker infowindow given the coordinates:
Each marker gets an "infowindow" entry :
function createMarker(lat, lon, html) {
var newmarker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lon),
map: map,
title: html
});
newmarker['infowindow'] = new google.maps.InfoWindow({
content: html
});
google.maps.event.addListener(newmarker, 'mouseover', function() {
this['infowindow'].open(map, this);
});
}
I was looking for a solution to this problem myself with no luck, so I had to roll my own which I would like to share here with you. (Please excuse my bad English) (It's a little crazy to answer another Czech guy in English :-) )
The first thing I tried was to use a good old PopupWindow
. It's quite easy - one only has to listen to the OnMarkerClickListener
and then show a custom PopupWindow
above the marker. Some other guys here on StackOverflow suggested this solution and it actually looks quite good at first glance. But the problem with this solution shows up when you start to move the map around. You have to move the PopupWindow
somehow yourself which is possible (by listening to some onTouch events) but IMHO you can't make it look good enough, especially on some slow devices. If you do it the simple way it "jumps" around from one spot to another. You could also use some animations to polish those jumps but this way the PopupWindow
will always be "a step behind" where it should be on the map which I just don't like.
At this point, I was thinking about some other solution. I realized that I actually don't really need that much freedom - to show my custom views with all the possibilities that come with it (like animated progress bars etc.). I think there is a good reason why even the google engineers don't do it this way in the Google Maps app. All I need is a button or two on the InfoWindow that will show a pressed state and trigger some actions when clicked. So I came up with another solution which splits up into two parts:
First part:
The first part is to be able to catch the clicks on the buttons to trigger some action. My idea is as follows:
MapFragment
(or MapView
) inside a custom ViewGroup (mine is called MapWrapperLayout)MapWrapperLayout
's dispatchTouchEvent and (if the InfoWindow is currently shown) first route the MotionEvents to the previously created InfoWindow. If it doesn't consume the MotionEvents (like because you didn't click on any clickable area inside InfoWindow etc.) then (and only then) let the events go down to the MapWrapperLayout's superclass so it will eventually be delivered to the map.Here is the MapWrapperLayout's source code:
package com.circlegate.tt.cg.an.lib.map;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.Marker;
import android.content.Context;
import android.graphics.Point;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RelativeLayout;
public class MapWrapperLayout extends RelativeLayout {
/**
* Reference to a GoogleMap object
*/
private GoogleMap map;
/**
* Vertical offset in pixels between the bottom edge of our InfoWindow
* and the marker position (by default it's bottom edge too).
* It's a good idea to use custom markers and also the InfoWindow frame,
* because we probably can't rely on the sizes of the default marker and frame.
*/
private int bottomOffsetPixels;
/**
* A currently selected marker
*/
private Marker marker;
/**
* Our custom view which is returned from either the InfoWindowAdapter.getInfoContents
* or InfoWindowAdapter.getInfoWindow
*/
private View infoWindow;
public MapWrapperLayout(Context context) {
super(context);
}
public MapWrapperLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MapWrapperLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
/**
* Must be called before we can route the touch events
*/
public void init(GoogleMap map, int bottomOffsetPixels) {
this.map = map;
this.bottomOffsetPixels = bottomOffsetPixels;
}
/**
* Best to be called from either the InfoWindowAdapter.getInfoContents
* or InfoWindowAdapter.getInfoWindow.
*/
public void setMarkerWithInfoWindow(Marker marker, View infoWindow) {
this.marker = marker;
this.infoWindow = infoWindow;
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
boolean ret = false;
// Make sure that the infoWindow is shown and we have all the needed references
if (marker != null && marker.isInfoWindowShown() && map != null && infoWindow != null) {
// Get a marker position on the screen
Point point = map.getProjection().toScreenLocation(marker.getPosition());
// Make a copy of the MotionEvent and adjust it's location
// so it is relative to the infoWindow left top corner
MotionEvent copyEv = MotionEvent.obtain(ev);
copyEv.offsetLocation(
-point.x + (infoWindow.getWidth() / 2),
-point.y + infoWindow.getHeight() + bottomOffsetPixels);
// Dispatch the adjusted MotionEvent to the infoWindow
ret = infoWindow.dispatchTouchEvent(copyEv);
}
// If the infoWindow consumed the touch event, then just return true.
// Otherwise pass this event to the super class and return it's result
return ret || super.dispatchTouchEvent(ev);
}
}
All this will make the views inside the InfoView "live" again - the OnClickListeners will start triggering etc.
Second part: The remaining problem is, that obviously, you can't see any UI changes of your InfoWindow on screen. To do that you have to manually call Marker.showInfoWindow. Now, if you perform some permanent change in your InfoWindow (like changing the label of your button to something else), this is good enough.
But showing a button pressed state or something of that nature is more complicated. The first problem is, that (at least) I wasn't able to make the InfoWindow show normal button's pressed state. Even if I pressed the button for a long time, it just remained unpressed on the screen. I believe this is something that is handled by the map framework itself which probably makes sure not to show any transient state in the info windows. But I could be wrong, I didn't try to find this out.
What I did is another nasty hack - I attached an OnTouchListener
to the button and manually switched it's background when the button was pressed or released to two custom drawables - one with a button in a normal state and the other one in a pressed state. This is not very nice, but it works :). Now I was able to see the button switching between normal to pressed states on the screen.
There is still one last glitch - if you click the button too fast, it doesn't show the pressed state - it just remains in its normal state (although the click itself is fired so the button "works"). At least this is how it shows up on my Galaxy Nexus. So the last thing I did is that I delayed the button in it's pressed state a little. This is also quite ugly and I'm not sure how would it work on some older, slow devices but I suspect that even the map framework itself does something like this. You can try it yourself - when you click the whole InfoWindow, it remains in a pressed state a little longer, then normal buttons do (again - at least on my phone). And this is actually how it works even on the original Google Maps app.
Anyway, I wrote myself a custom class which handles the buttons state changes and all the other things I mentioned, so here is the code:
package com.circlegate.tt.cg.an.lib.map;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import com.google.android.gms.maps.model.Marker;
public abstract class OnInfoWindowElemTouchListener implements OnTouchListener {
private final View view;
private final Drawable bgDrawableNormal;
private final Drawable bgDrawablePressed;
private final Handler handler = new Handler();
private Marker marker;
private boolean pressed = false;
public OnInfoWindowElemTouchListener(View view, Drawable bgDrawableNormal, Drawable bgDrawablePressed) {
this.view = view;
this.bgDrawableNormal = bgDrawableNormal;
this.bgDrawablePressed = bgDrawablePressed;
}
public void setMarker(Marker marker) {
this.marker = marker;
}
@Override
public boolean onTouch(View vv, MotionEvent event) {
if (0 <= event.getX() && event.getX() <= view.getWidth() &&
0 <= event.getY() && event.getY() <= view.getHeight())
{
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN: startPress(); break;
// We need to delay releasing of the view a little so it shows the pressed state on the screen
case MotionEvent.ACTION_UP: handler.postDelayed(confirmClickRunnable, 150); break;
case MotionEvent.ACTION_CANCEL: endPress(); break;
default: break;
}
}
else {
// If the touch goes outside of the view's area
// (like when moving finger out of the pressed button)
// just release the press
endPress();
}
return false;
}
private void startPress() {
if (!pressed) {
pressed = true;
handler.removeCallbacks(confirmClickRunnable);
view.setBackground(bgDrawablePressed);
if (marker != null)
marker.showInfoWindow();
}
}
private boolean endPress() {
if (pressed) {
this.pressed = false;
handler.removeCallbacks(confirmClickRunnable);
view.setBackground(bgDrawableNormal);
if (marker != null)
marker.showInfoWindow();
return true;
}
else
return false;
}
private final Runnable confirmClickRunnable = new Runnable() {
public void run() {
if (endPress()) {
onClickConfirmed(view, marker);
}
}
};
/**
* This is called after a successful click
*/
protected abstract void onClickConfirmed(View v, Marker marker);
}
Here is a custom InfoWindow layout file that I used:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginRight="10dp" >
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:text="Title" />
<TextView
android:id="@+id/snippet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="snippet" />
</LinearLayout>
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
Test activity layout file (MapFragment
being inside the MapWrapperLayout
):
<com.circlegate.tt.cg.an.lib.map.MapWrapperLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/map_relative_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<fragment
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.MapFragment" />
</com.circlegate.tt.cg.an.lib.map.MapWrapperLayout>
And finally source code of a test activity, which glues all this together:
package com.circlegate.testapp;
import com.circlegate.tt.cg.an.lib.map.MapWrapperLayout;
import com.circlegate.tt.cg.an.lib.map.OnInfoWindowElemTouchListener;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.InfoWindowAdapter;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private ViewGroup infoWindow;
private TextView infoTitle;
private TextView infoSnippet;
private Button infoButton;
private OnInfoWindowElemTouchListener infoButtonListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MapFragment mapFragment = (MapFragment)getFragmentManager().findFragmentById(R.id.map);
final MapWrapperLayout mapWrapperLayout = (MapWrapperLayout)findViewById(R.id.map_relative_layout);
final GoogleMap map = mapFragment.getMap();
// MapWrapperLayout initialization
// 39 - default marker height
// 20 - offset between the default InfoWindow bottom edge and it's content bottom edge
mapWrapperLayout.init(map, getPixelsFromDp(this, 39 + 20));
// We want to reuse the info window for all the markers,
// so let's create only one class member instance
this.infoWindow = (ViewGroup)getLayoutInflater().inflate(R.layout.info_window, null);
this.infoTitle = (TextView)infoWindow.findViewById(R.id.title);
this.infoSnippet = (TextView)infoWindow.findViewById(R.id.snippet);
this.infoButton = (Button)infoWindow.findViewById(R.id.button);
// Setting custom OnTouchListener which deals with the pressed state
// so it shows up
this.infoButtonListener = new OnInfoWindowElemTouchListener(infoButton,
getResources().getDrawable(R.drawable.btn_default_normal_holo_light),
getResources().getDrawable(R.drawable.btn_default_pressed_holo_light))
{
@Override
protected void onClickConfirmed(View v, Marker marker) {
// Here we can perform some action triggered after clicking the button
Toast.makeText(MainActivity.this, marker.getTitle() + "'s button clicked!", Toast.LENGTH_SHORT).show();
}
};
this.infoButton.setOnTouchListener(infoButtonListener);
map.setInfoWindowAdapter(new InfoWindowAdapter() {
@Override
public View getInfoWindow(Marker marker) {
return null;
}
@Override
public View getInfoContents(Marker marker) {
// Setting up the infoWindow with current's marker info
infoTitle.setText(marker.getTitle());
infoSnippet.setText(marker.getSnippet());
infoButtonListener.setMarker(marker);
// We must call this to set the current marker and infoWindow references
// to the MapWrapperLayout
mapWrapperLayout.setMarkerWithInfoWindow(marker, infoWindow);
return infoWindow;
}
});
// Let's add a couple of markers
map.addMarker(new MarkerOptions()
.title("Prague")
.snippet("Czech Republic")
.position(new LatLng(50.08, 14.43)));
map.addMarker(new MarkerOptions()
.title("Paris")
.snippet("France")
.position(new LatLng(48.86,2.33)));
map.addMarker(new MarkerOptions()
.title("London")
.snippet("United Kingdom")
.position(new LatLng(51.51,-0.1)));
}
public static int getPixelsFromDp(Context context, float dp) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int)(dp * scale + 0.5f);
}
}
That's it. So far I only tested this on my Galaxy Nexus (4.2.1) and Nexus 7 (also 4.2.1), I will try it on some Gingerbread phone when I have a chance. A limitation I found so far is that you can't drag the map from where is your button on the screen and move the map around. It could probably be overcome somehow but for now, I can live with that.
I know this is an ugly hack but I just didn't find anything better and I need this design pattern so badly that this would really be a reason to go back to the map v1 framework (which btw. I would really really like to avoid for a new app with fragments etc.). I just don't understand why Google doesn't offer developers some official way to have a button on InfoWindows. It's such a common design pattern, moreover this pattern is used even in the official Google Maps app :). I understand the reasons why they can't just make your views "live" in the InfoWindows - this would probably kill performance when moving and scrolling map around. But there should be some way how to achieve this effect without using views.
function setMarkers(map,locations){
for (var i = 0; i < locations.length; i++)
{
var loan = locations[i][0];
var lat = locations[i][1];
var long = locations[i][2];
var add = locations[i][3];
latlngset = new google.maps.LatLng(lat, long);
var marker = new google.maps.Marker({
map: map, title: loan , position: latlngset
});
map.setCenter(marker.getPosition());
marker.content = "<h3>Loan Number: " + loan + '</h3>' + "Address: " + add;
google.maps.events.addListener(marker,'click', function(map,marker){
map.infowindow.setContent(marker.content);
map.infowindow.open(map,marker);
});
}
}
Then move var infowindow = new google.maps.InfoWindow()
to the initialize()
function:
function initialize() {
var myOptions = {
center: new google.maps.LatLng(33.890542, 151.274856),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("default"),
myOptions);
map.infowindow = new google.maps.InfoWindow();
setMarkers(map,locations)
}
In JavaScript 1.8.5, Object.getOwnPropertyNames
returns an array of all properties found directly upon a given object.
Object.getOwnPropertyNames ( obj )
and another method Object.keys
, which returns an array containing the names of all of the given object's own enumerable properties.
Object.keys( obj )
I used forEach
to list values and keys in obj, same as for (var key in obj) ..
Object.keys(obj).forEach(function (key) {
console.log( key , obj[key] );
});
This all are new features in ECMAScript , the mothods getOwnPropertyNames
, keys
won't supports old browser's.
I defined an git alias to achieve just this (before I found this question).
It's a short bash function which saves the current path, switch to the git repo, does a checkout and return where it started.
git checkto develop ~/my_project_git
This e.g. would checkout the develop branch into "~/my_project_git" directory.
This is the alias code inside ~/.gitconfig
:
[alias]
checkTo = "!f(){ [ -z \"$1\" ] && echo \"Need to specify branch.\" && \
exit 1; [ -z \"$2\" ] && echo \"Need to specify target\
dir\" && exit 2; cDir=\"$(pwd)\"; cd \"$2\"; \
git checkout \"$1\"; cd \"$cDir\"; };f"
#ck-button:hover {
background:red;
}
Fiddle: http://jsfiddle.net/zAFND/4/
If we know there is a limitation on LEN and space, why cant we replace the space first? Then we know there is no space to confuse LEN.
len(replace(@string, ' ', '-')) - len(replace(replace(@string, ' ', '-'), ',', ''))
the best explanation i've found is this:
What is the difference betwen INTEGER and NUMBER? When should we use NUMBER and when should we use INTEGER? I just wanted to update my comments here...
NUMBER always stores as we entered. Scale is -84 to 127. But INTEGER rounds to whole number. The scale for INTEGER is 0. INTEGER is equivalent to NUMBER(38,0). It means, INTEGER is constrained number. The decimal place will be rounded. But NUMBER is not constrained.
INTEGER is always slower then NUMBER. Since integer is a number with added constraint. It takes additional CPU cycles to enforce the constraint. I never watched any difference, but there might be a difference when we load several millions of records on the INTEGER column. If we need to ensure that the input is whole numbers, then INTEGER is best option to go. Otherwise, we can stick with NUMBER data type.
Here is the link
Use the Distinct operator:
var idList = yourList.Select(x=> x.ID).Distinct();
You might also try giving the full path to the binary you're trying to run. That solved my problem when trying to use ImageMagick
.
[+]is simpler
String s = "ddjdjdj+kfkfkf";
if(s.contains ("+"))
{
String parts[] = s.split("[+]");
s = parts[0]; // i want to strip part after +
}
System.out.println(s);
std::copy
but without extra trailing separatorAn alternative/modified approach using std::copy
(as originally used in @JoshuaKravtiz answer) but without including an additional trailing separator after the last element:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
template <typename T>
void print_contents(const std::vector<T>& v, const char * const separator = " ")
{
if(!v.empty())
{
std::copy(v.begin(),
--v.end(),
std::ostream_iterator<T>(std::cout, separator));
std::cout << v.back() << "\n";
}
}
// example usage
int main() {
std::vector<int> v{1, 2, 3, 4};
print_contents(v); // '1 2 3 4'
print_contents(v, ":"); // '1:2:3:4'
v = {};
print_contents(v); // ... no std::cout
v = {1};
print_contents(v); // '1'
return 0;
}
Example usage applied to container of a custom POD type:
// includes and 'print_contents(...)' as above ...
class Foo
{
int i;
friend std::ostream& operator<<(std::ostream& out, const Foo& obj);
public:
Foo(const int i) : i(i) {}
};
std::ostream& operator<<(std::ostream& out, const Foo& obj)
{
return out << "foo_" << obj.i;
}
int main() {
std::vector<Foo> v{1, 2, 3, 4};
print_contents(v); // 'foo_1 foo_2 foo_3 foo_4'
print_contents(v, ":"); // 'foo_1:foo_2:foo_3:foo_4'
v = {};
print_contents(v); // ... no std::cout
v = {1};
print_contents(v); // 'foo_1'
return 0;
}
64-bit tools are not available on Visual C++ Express by default. To enable 64-bit tools on Visual C++ Express, install the Windows Software Development Kit (SDK) in addition to Visual C++ Express. Otherwise, an error occurs when you attempt to configure a project to target a 64-bit platform using Visual C++ Express.
How to: Configure Visual C++ Projects to Target 64-Bit Platforms
@Adorojan's
answer is almost correct. But addition of offset is not correct since offset value will be negative if browser date is ahead of GMT and vice versa.
Below is the solution which I came with and is working perfectly fine for me:
// Input time in UTC_x000D_
var inputInUtc = "6/29/2011 4:52:48";_x000D_
_x000D_
var dateInUtc = new Date(Date.parse(inputInUtc+" UTC"));_x000D_
//Print date in UTC time_x000D_
document.write("Date in UTC : " + dateInUtc.toISOString()+"<br>");_x000D_
_x000D_
var dateInLocalTz = convertUtcToLocalTz(dateInUtc);_x000D_
//Print date in local time_x000D_
document.write("Date in Local : " + dateInLocalTz.toISOString());_x000D_
_x000D_
function convertUtcToLocalTz(dateInUtc) {_x000D_
//Convert to local timezone_x000D_
return new Date(dateInUtc.getTime() - dateInUtc.getTimezoneOffset()*60*1000);_x000D_
}
_x000D_
Another solution, besides the ondes already mentioned (using layout
or par(xpd=TRUE)
) is to overlay your plot with a transparent plot over the entire device and then add the legend to that.
The trick is to overlay a (empty) graph over the complete plotting area and adding the legend to that. We can use the par(fig=...)
option. First we instruct R to create a new plot over the entire plotting device:
par(fig=c(0, 1, 0, 1), oma=c(0, 0, 0, 0), mar=c(0, 0, 0, 0), new=TRUE)
Setting oma
and mar
is needed since we want to have the interior of the plot cover the entire device. new=TRUE
is needed to prevent R from starting a new device. We can then add the empty plot:
plot(0, 0, type='n', bty='n', xaxt='n', yaxt='n')
And we are ready to add the legend:
legend("bottomright", ...)
will add a legend to the bottom right of the device. Likewise, we can add the legend to the top or right margin. The only thing we need to ensure is that the margin of the original plot is large enough to accomodate the legend.
Putting all this into a function;
add_legend <- function(...) {
opar <- par(fig=c(0, 1, 0, 1), oma=c(0, 0, 0, 0),
mar=c(0, 0, 0, 0), new=TRUE)
on.exit(par(opar))
plot(0, 0, type='n', bty='n', xaxt='n', yaxt='n')
legend(...)
}
And an example. First create the plot making sure we have enough space at the bottom to add the legend:
par(mar = c(5, 4, 1.4, 0.2))
plot(rnorm(50), rnorm(50), col=c("steelblue", "indianred"), pch=20)
Then add the legend
add_legend("topright", legend=c("Foo", "Bar"), pch=20,
col=c("steelblue", "indianred"),
horiz=TRUE, bty='n', cex=0.8)
Resulting in:
I suggest you do it through the GET request: for example, index.html:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<form action="result.php" method="post">
Answer 1 <input type="radio" name="ans" value="ans1" /><br />
Answer 2 <input type="radio" name="ans" value="ans2" /><br />
Answer 3 <input type="radio" name="ans" value="ans3" /><br />
Answer 4 <input type="radio" name="ans" value="ans4" /><br />
<input type="button" value="submit" onclick="sendPost()" />
</form>
<script type="text/javascript">
function sendPost(){
var value = $('input[name="ans"]:checked').val();
window.location.href = "sendpost.php?ans="+value;
};
</script>
this is sendpost.php:
<?php
if(isset($_GET["ans"]) AND !empty($_GET["ans"])){
echo $_GET["ans"];
}
?>
This does a trick for me:
bash -c 'for (( I=100000000000000000000 ; I>=0 ; I++ )) ; do echo $(( I+I*I )) & echo $(( I*I-I )) & echo $(( I-I*I*I )) & echo $(( I+I*I*I )) ; done' &>/dev/null
and it uses nothing except bash.
i had similar issues after upgrading my project to java 11, then what fixed it was upgrading to spring boot 2.1.1 which apparently has support for java 11, this helped
?php
/* Database config */
$db_host = 'localhost';
$db_user = '~';
$db_pass = '~';
$db_database = 'banners';
/* End config */
$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_database);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
?>
My Solution : https://codepen.io/SOLESHOE/pen/QqJXYj
{
display: inline-block;
border-bottom: 1px solid;
padding-bottom: 0;
line-height: 70%;
}
You can adjust underline position with line-height value, underline thickness and style with border-bottom.
Beware to disable default underline behavior if you want to underline an href.
Simply:
listPreference.setSummary("%s");
You need commas after end
finishing the case statement. And, the "as" goes after the case
statement, not inside it:
Insert into TblStuff(FullName, Address, City, Zip)
Select (Case When Middle is Null Then Fname + LName
Else Fname +' ' + Middle + ' '+ Lname
End) as FullName,
(Case When Address2 is Null Then Address1
else Address1 +', ' + Address2
End) as Address,
City as City,
Zip as Zip
from tblImport
It's O(V+E) because each visit to v of V must visit each e of E where |e| <= V-1. Since there are V visits to v of V then that is O(V). Now you have to add V * |e| = E => O(E). So total time complexity is O(V + E).
Just put in the function using GLOBAL keyword:
global $site_url;
This answer will help in case, If you are working with Data Bases then mostly take the help of try-catch block statement, which will help and guide you with your code. Here i am showing you that how to insert some values in Data Base with a Button Click Event.
private void button2_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
conn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;" +
@"Data source= C:\Users\pir fahim shah\Documents\TravelAgency.accdb";
try
{
conn.Open();
String ticketno=textBox1.Text.ToString();
String Purchaseprice=textBox2.Text.ToString();
String sellprice=textBox3.Text.ToString();
String my_querry = "INSERT INTO Table1(TicketNo,Sellprice,Purchaseprice)VALUES('"+ticketno+"','"+sellprice+"','"+Purchaseprice+"')";
OleDbCommand cmd = new OleDbCommand(my_querry, conn);
cmd.ExecuteNonQuery();
MessageBox.Show("Data saved successfuly...!");
}
catch (Exception ex)
{
MessageBox.Show("Failed due to"+ex.Message);
}
finally
{
conn.Close();
}
If the purpose is to obtain a bitmap, this is very simple:
Canvas canvas = new Canvas();
canvas.setBitmap(image);
canvas.drawBitmap(image2, new Matrix(), null);
In the end, image will contain the overlap of image and image2.
setText(Html.fromHtml(bodyData)) is deprecated after api 24. Now you have to do this:
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
tvDocument.setText(Html.fromHtml(bodyData,Html.FROM_HTML_MODE_LEGACY));
} else {
tvDocument.setText(Html.fromHtml(bodyData));
}
request.remote_ip
is an interpretation of all the available IP address information and it will make a best-guess. If you access the variables directly you assume responsibility for testing them in the correct precedence order. Proxies introduce a number of headers that create environment variables with different names.
its not .val() if you want to get file /home/user/default.png it will get with .val() just default.png
Let's say you have a shiny Foo class. Well you have 3 options:
1) You want to use the method (or attribute) of a class inside the definition of that class:
class Foo(object):
attribute1 = 1 # class attribute (those don't use 'self' in declaration)
def __init__(self):
self.attribute2 = 2 # instance attribute (those are accessible via first
# parameter of the method, usually called 'self'
# which will contain nothing but the instance itself)
def set_attribute3(self, value):
self.attribute3 = value
def sum_1and2(self):
return self.attribute1 + self.attribute2
2) You want to use the method (or attribute) of a class outside the definition of that class
def get_legendary_attribute1():
return Foo.attribute1
def get_legendary_attribute2():
return Foo.attribute2
def get_legendary_attribute1_from(cls):
return cls.attribute1
get_legendary_attribute1() # >>> 1
get_legendary_attribute2() # >>> AttributeError: type object 'Foo' has no attribute 'attribute2'
get_legendary_attribute1_from(Foo) # >>> 1
3) You want to use the method (or attribute) of an instantiated class:
f = Foo()
f.attribute1 # >>> 1
f.attribute2 # >>> 2
f.attribute3 # >>> AttributeError: 'Foo' object has no attribute 'attribute3'
f.set_attribute3(3)
f.attribute3 # >>> 3
Counting number of letters in a string using regex.
import re
s = 'The grey old fox is an idiot'
count = len(re.findall('[a-zA-Z]',s))
My favorite visual merge tool is SourceGear DiffMerge
public Configuration()
{
AutomaticMigrationsEnabled = false;
// register mysql code generator
SetSqlGenerator("MySql.Data.MySqlClient", new MySql.Data.Entity.MySqlMigrationSqlGenerator());
}
I find out that connector 6.6.4 will not work with Entity Framework 5 but with Entity Framework 4.3. So to downgrade issue the following commands in the package manager console:
Uninstall-Package EntityFramework
Install-Package EntityFramework -Version 4.3.1
Finally I do Update-Database -Verbose again and voila! The schema and tables are created. Wait for the next version of connector to use it with Entity Framework 5.
*import Foundation
import CoreData
extension Messages {
@nonobjc public class func fetchRequest() -> NSFetchRequest<Messages> {
return NSFetchRequest<Messages>(entityName: "Messages")
}
@NSManaged public var text: String?
@NSManaged public var date: Date?
@NSManaged public var friends: Friends?
}
//here arrMessage is the array you can sort this array as under bellow
var arrMessages = [Messages]()
arrMessages.sort { (arrMessages1, arrMessages2) -> Bool in
arrMessages1.date! > arrMessages2.date!
}*
For those guys who are tying to find the DatePickerDoneClick function... here is the simple code to dismiss the Action Sheet. Obviously aac should be an ivar (the one which goes in your implmentation .h file)
- (void)DatePickerDoneClick:(id)sender{
[aac dismissWithClickedButtonIndex:0 animated:YES];
}
Sorry with my English, When you create a new android project, you should choose api of high level, for example: from api 17 to api 21, It will not have appcompat and very easy to share project. If you did it with lower API, you just edit in Android Manifest to have upper API :), after that, you can delete Appcompat V7.
If I understand your problem well you want the following things:
Unfortunately there is no ultimate solution for what you want, but there are some things by which you can make your life easier.
First you should decide one important thing: do you want to store for every version in your project repository a reference to the version of the media files? So for example if you have a project called example.com, do you need know which style.css it used 2 weeks ago, or the latest is always (or mostly) the best?
If you don't need to know that, the solution is easy:
In most of the cases, however, you want to know this versioning information. In this case you have two choices:
Store every project in one big repository. The advantage of this solution is that you will have only 1 copy of the media repository. The big disadvantage is that it is much harder to switch between project versions (if you checkout to a different version you will always modify ALL projects)
Use submodules (as explained in answer 1). This way you will store the media files in one repository, and the projects will contain only a reference to a specific media repo version. But this way you will normally have many local copies of the media repository, and you cannot easily modify a media file in all projects.
If I were you I would probably choose the first or third solution (symbolic links or submodules). If you choose to use submodules you can still do a lot of things to make your life easier:
Before committing you can rename the submodule directory and put a symlink to a common media directory. When you're ready to commit, you can remove the symlink and remove the submodule back, and then commit.
You can add one of your copy of the media repository as a remote repository to all of your projects.
You can add local directories as a remote this way:
cd /my/project2/media
git remote add project1 /my/project1/media
If you modify a file in /my/project1/media, you can commit it and pull it from /my/project2/media without pushing it to a remote server:
cd /my/project1/media
git commit -a -m "message"
cd /my/project2/media
git pull project1 master
You are free to remove these commits later (with git reset) because you haven't shared them with other users.
2^8 = 256 Characters. A character in binary is a series of 8 ( 0 or 1).
|----------------------------------------------------------|
| |
| Type | Storage | Minimum Value | Maximum Value |
| | (Bytes) | (Signed/Unsigned) | (Signed/Unsigned)|
| | | | |
|---------|---------|-------------------|------------------|
| | | | |
| | | | |
| TINYINT | 1 | -128 - 0 | 127 - 255 |
| | | | |
|----------------------------------------------------------|
You could create a JsonConverter
. See here for an example thats similar to your question.
How about this:
src = [ 'one', 'two', 'three', 'two', 'three', 'three' ]
result_dict = dict( [ (i, src.count(i)) for i in set(src) ] )
This results in
{'one': 1, 'three': 3, 'two': 2}
According to the error message, you declared myLoc
as a pointer to an NSInteger (NSInteger *myLoc
) rather than an actual NSInteger (NSInteger myLoc
). It needs to be the latter.
You can use negated character classes to exclude certain characters: for example [^abcde]
will match anything but a,b,c,d,e characters.
Instead of specifying all the characters literally, you can use shorthands inside character classes: [\w]
(lowercase) will match any "word character" (letter, numbers and underscore), [\W]
(uppercase) will match anything but word characters; similarly, [\d]
will match the 0-9 digits while [\D]
matches anything but the 0-9 digits, and so on.
If you use PHP you can take a look at the regex character classes documentation.
Something like this will work, using Linq:
string result = "12345"
var intList = result.Select(digit => int.Parse(digit.ToString()));
This will give you an IEnumerable list of ints.
If you want an IEnumerable of strings:
var intList = result.Select(digit => digit.ToString());
or if you want a List of strings:
var intList = result.ToList();
It's my solution:
public void getBytes(int val) {
byte[] bytes = new byte[Integer.BYTES];
for (int i = 0;i < bytes.length; i ++) {
int j = val % Byte.MAX_VALUE;
bytes[i] = (j == 0 ? Byte.MAX_VALUE : j);
}
}
Also String
y method:
public void getBytes(int val) {
String hex = Integer.toHexString(val);
byte[] val = new byte[hex.length()/2]; // because byte is 2 hex chars
for (int i = 0; i < hex.length(); i+=2)
val[i] = Byte.parseByte("0x" + hex.substring(i, i+2), 16);
return val;
}
after 2 long days,
the solution was to add options +FollowSymLinks
to the top of my .htaccess
file.
Are you sure you are working in Java? 'cause Java gives -13 % 64 = -13 as expected. The sign of dividend!
In order to save the Fragment state you need to implement onSaveInstanceState()
:
"Also like an activity, you can retain the state of a fragment using a Bundle, in case the activity's process is killed and you need to restore the fragment state when the activity is recreated. You can save the state during the fragment's onSaveInstanceState()
callback and restore it during either onCreate()
, onCreateView()
, or onActivityCreated()
. For more information about saving state, see the Activities document."
http://developer.android.com/guide/components/fragments.html#Lifecycle
** Update**: 11/19/2019
Microsoft has released a new version of the control 150.1400.0
in their Nuget library. My short testing shows that it works again in the forms designer where 150.1357.0
and 150.1358.0
did not. This includes being able to resize and modify the ReportViewer Tasks on the control itself.
** Update**: 8/18/2019
Removing the latest version and rolling back to 150.900.148.0
seems to work on multiple computers I'm using with VS2017 and VS2019.
You can roll back to 150.900.148 in the Nuget solution package manager. It works similarly to the previous versions. Use the drop down box to select the older version.
It may be easier to manually delete references to post 150.900 versions of ReportViewer and readd them than it is to fix them.
Remember to restart Visual Studio after changing the toolbox entry.
Update: 8/7/2019
A newer version of the ReportViewer control has been released, probably coinciding with Visual Studio 2019. I was working with V150.1358.0.
Following the directions in this answer gets the control in the designer's toolbox. But once dropped on the form it doesn't display. The control shows up below the form as a non-visual component.
This is working as designed according to Microsoft SQL BI support. This is the group responsible for the control.
While you still cannot interact with the control directly, these additional steps give a workaround so the control can be sized on the form. While now visible, the designer treats the control as if it didn't exist.
I've created a feedback request at the suggestion of Microsoft SQL BI support. Please consider voting on it to get Microsoft's attention.
Microsoft Azure Feedback page - Restore Designtime features of the WinForms ReportViewer Control
Additional steps:
In the form's form.designer.cs file, add the Reportviewer control to the panel.
//
// panel1
//
this.panel1.Controls.Add(this.reportViewer1);
Return to the form's designer, you should see the reportViewer on the panel
Now you can position the reportViewer by actually interacting with the panel.
Update: Microsoft released a document on April 18, 2017 describing how to configure and use the reporting tool in Visual Studio 2017.
Visual Studio 2017 does not have the ReportViewer
tool installed by default in the ToolBox. Installing the extension Microsoft Rdlc Report Designer for Visual Studio and then adding that to the ToolBox results in a non-visual component that appears below the form.
Microsoft Support had told me this is a bug, but as of April 21, 2017 it is "working as designed".
The following steps need to be followed for each project that requires ReportViewer
.
ReportViewer
in the Toolbox, remove it. Highlight, right-click and delete.
Edited 8/7/2019 - It looks like the current version of the RDLC Report Designer extension no longer interferes. You need this to actually edit the reports.
If you have the Microsoft Rdlc Report Designer for Visual Studio extension installed, uninstall it.
Close your solution and restart Visual Studio. This is a crucial step, errors will occur if VS is not restarted when switching between solutions.
Tools/NuGet Package Manager/Package Manager Console
)At the PM> prompt enter this command, case matters.
Install-Package Microsoft.ReportingServices.ReportViewerControl.WinForms
You should see text describing the installation of the package.
Now we can temporarily add the ReportViewer
tool to the tool box.
Right-click in the toolbox and use Choose Items...
We need to browse to the proper DLL that is located in the solutions Packages
folder, so hit the browse button.
In our example we can paste in the packages folder as shown in the text of Package Manager Console.
C:\Users\jdoe\Documents\Projects\_Test\ReportViewerTest\WindowsFormsApp1\packages
Then double click on the folder named
Microsoft.ReportingServices.ReportViewerControl.Winforms.140.340.80
The version number will probably change in the future.
Then double-click on lib
and again on net40
.
Finally, double click on the file Microsoft.ReportViewer.WinForms.dll
You should see ReportViewer
checked in the dialog. Scroll to the right and you will see the version 14.0.0.0 associated to it.
Click OK.
ReportViewer
is now located in the ToolBox.
Drag the tool to the desired form(s).
Once completed, delete the ReportViewer
tool from the tool box. You can't use it with another project.
You may save the project and are good to go.
Remember to restart Visual Studio any time you need to open a project with ReportViewer
so that the DLL is loaded from the correct location. If you try and open a solution with a form with ReportViewer
without restarting you will see errors indicating that the “The variable 'reportViewer1' is either undeclared or was never assigned.
“.
If you add a new project to the same solution you need to create the project, save the solution, restart Visual Studio and then you should be able to add the ReportViewer
to the form. I have seen it not work the first time and show up as a non-visual component.
When that happens, removing the component from the form, deleting the Microsoft.ReportViewer.*
references from the project, saving and restarting usually works.
import sys
sys.path.append("..") # Adds higher directory to python modules path.
Try this. Worked for me.
Misspellings are irritating, aren't they? Check your spelling of empty
, but then also try this:
#!/bin/bash -e
if [ -s diff.txt ]
then
rm -f empty.txt
touch full.txt
else
rm -f full.txt
touch empty.txt
fi
I like shell scripting a lot, but one disadvantage of it is that the shell cannot help you when you misspell, whereas a compiler like your C++ compiler can help you.
Notice incidentally that I have swapped the roles of empty.txt
and full.txt
, as @Matthias suggests.
Don't worry so much framing the button from code, you can do that on the storyboard. This worked for me, one line...more simple.
[self.button setBackgroundImage:[UIImage imageNamed: @"yourPic.png"] forState:UIControlStateNormal];
import urllib.request
bank_pdf_list = ["https://www.hdfcbank.com/content/bbp/repositories/723fb80a-2dde-42a3-9793-7ae1be57c87f/?path=/Personal/Home/content/rates.pdf",
"https://www.yesbank.in/pdf/forexcardratesenglish_pdf",
"https://www.sbi.co.in/documents/16012/1400784/FOREX_CARD_RATES.pdf"]
def get_pdf(url):
user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'
#url = "https://www.yesbank.in/pdf/forexcardratesenglish_pdf"
headers={'User-Agent':user_agent,}
request=urllib.request.Request(url,None,headers) #The assembled request
response = urllib.request.urlopen(request)
#print(response.text)
data = response.read()
# print(type(data))
name = url.split("www.")[-1].split("//")[-1].split(".")[0]+"_FOREX_CARD_RATES.pdf"
f = open(name, 'wb')
f.write(data)
f.close()
for bank_url in bank_pdf_list:
try:
get_pdf(bank_url)
except:
pass
xhr.getResponseHeader('Set-Cookie');
It won't work for me.
I use this
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) != -1) return c.substring(name.length,c.length);
}
return "";
}
success: function(output, status, xhr) {
alert(getCookie("MyCookie"));
},
You can try this code
Dictionary<string,string> AllFields = new Dictionary<string,string>();
string value = (AllFields.TryGetValue(key, out index) ? AllFields[key] : null);
If the key is not present, it simply returns a null value.
Generics
can be defined using Wrapper
classes only. If you don't want to define using Wrapper types, you may use the Raw definition as below
@SuppressWarnings("rawtypes")
public HashMap buildMap(String letters)
{
HashMap checkSum = new HashMap();
for ( int i = 0; i < letters.length(); ++i )
{
checkSum.put(letters.charAt(i), primes[i]);
}
return checkSum;
}
Or define the HashMap using wrapper types, and store the primitive types. The primitive values will be promoted to their wrapper types.
public HashMap<Character, Integer> buildMap(String letters)
{
HashMap<Character, Integer> checkSum = new HashMap<Character, Integer>();
for ( int i = 0; i < letters.length(); ++i )
{
checkSum.put(letters.charAt(i), primes[i]);
}
return checkSum;
}
You must reference it. To do this, open the shortcut menu for the project in Solution Explorer, and then choose References. In the Property Pages dialog box, expand the Common Properties node, select Framework and References, and then choose the Add New Reference button.
Server-side validation won't fire if client-side validation is invalid, the postback is not send.
Don't you have some other validation that doesn't pass?
The client-side validation is not executed because you specified ClientValidationFunction="TextBoxDTownCityClient"
and this will look for a function named TextBoxDTownCityClient
as validation function, but the function name should be
TextBoxDAddress1Client
(as you wrote)
Turing-completeness is not only about "defining functions" or "have ifs/loops/etc". For example, Haskell doesn't have "loop", lambda-calculus don't have "ifs", etc...
For example, this site: http://experthuman.com/programming-with-nothing. The author uses Ruby and create a "FizzBuzz" program with only closures (no strings, numbers, or anything like that)...
There are examples when people compute some arithmetical functions on Scala using only the type system
So, yes, in my opinion, CSS3+HTML is turing-complete (even if you can't exactly do any real computation with then without becoming crazy)
When you want to create interval store promise to variable:
var p = $interval(function() { ... },1000);
And when you want to stop / clear the interval simply use:
$interval.cancel(p);
Try this:
/* Variable Declaration */
DECLARE @EmpID AS SMALLINT
DECLARE @SQLQuery AS NVARCHAR(500)
DECLARE @ParameterDefinition AS NVARCHAR(100)
DECLARE @TableName AS NVARCHAR(100)
/* set the parameter value */
SET @EmpID = 1001
SET @TableName = 'tblEmployees'
/* Build Transact-SQL String by including the parameter */
SET @SQLQuery = 'SELECT * FROM ' + @TableName + ' WHERE EmployeeID = @EmpID'
/* Specify Parameter Format */
SET @ParameterDefinition = '@EmpID SMALLINT'
/* Execute Transact-SQL String */
EXECUTE sp_executesql @SQLQuery, @ParameterDefinition, @EmpID
As myJSON
is an object you can just set its properties, for example:
myJSON.list1 = ["1","2"];
If you dont know the name of the properties, you have to use the array access syntax:
myJSON['list'+listnum] = ["1","2"];
If you want to add an element to one of the properties, you can do;
myJSON.list1.push("3");
Simple code to check pointer aliasing:
int main () {
int a = 10, b = 20;
int *p1, *p2, *p3, *p4;
p1 = &a;
p2 = &a;
if(p1 == p2){
std::cout<<"p1 and p2 alias each other"<<std::endl;
}
else{
std::cout<<"p1 and p2 do not alias each other"<<std::endl;
}
//------------------------
p3 = &a;
p4 = &b;
if(p3 == p4){
std::cout<<"p3 and p4 alias each other"<<std::endl;
}
else{
std::cout<<"p3 and p4 do not alias each other"<<std::endl;
}
return 0;
}
Output:
p1 and p2 alias each other
p3 and p4 do not alias each other
you can:
itemsCart.Select(c=>c.Price).Sum();
To hit the db only once do:
var itemsInCart = (from o in db.OrderLineItems
where o.OrderId == currentOrder.OrderId
select new { o.OrderLineItemId, ..., ..., o.WishListItem.Price}
).ToList();
var sum = itemsCart.Select(c=>c.Price).Sum();
The extra round-trip saved is worth it :)
Just simply use the encode function.
my_var = 'hello'
my_var_bytes = my_var.encode()
print(my_var_bytes)
And then to convert it back to a regular string do this
my_var_bytes = 'hello'
my_var = my_var_bytes.decode()
print(my_var)
--EDIT--
The following does not make the string raw but instead encodes it to bytes and decodes it.
Use Arrays.equals()
if you want to compare the actual content of arrays that contain primitive types values (like byte).
System.out.println(Arrays.equals(aa, bb));
Use Arrays.deepEquals
for comparison of arrays that contain objects.
<head>
<title>Test</title>
</head>
<body>
<h1>Hi there<span id="username"></span>!</h1>
<script>
let userName = prompt("What is your name?");
document.getElementById('username').innerHTML = userName;
</script>
</body>
A minor modification like below worked for me when using it from within perl and system() call:
sftp {user}@{host} <<< $'put {local_file_path} {remote_file_path}'
Just use word-wrap:break-word;
in the css. It works.
A stateless system can be seen as a box [black? ;)] where at any point in time the value of the output(s) depends only on the value of the input(s) [after a certain processing time]
A stateful system instead can be seen as a box where at any point in time the value of the output(s) depends on the value of the input(s) and of an internal state, so basicaly a stateful system is like a state machine with "memory" as the same set of input(s) value can generate different output(s) depending on the previous input(s) received by the system.
From the parallel programming point of view, a stateless system, if properly implemented, can be executed by multiple threads/tasks at the same time without any concurrency issue [as an example think of a reentrant function] A stateful system will requires that multiple threads of execution access and update the internal state of the system in an exclusive way, hence there will be a need for a serialization [synchronization] point.
ES6 will provide Map.prototype.forEach(callback) which can be used like this
myMap.forEach(function(value, key, myMap) {
// Do something
});
I think may be more automatic, grunt task usemin take care to do all this jobs for you, only need some configuration:
Use this.getClass().getCanonicalName()
to get the full class name.
Note that a package / class name ("a.b.C") is different from the path of the .class files (a/b/C.class), and that using the package name / class name to derive a path is typically bad practice. Sets of class files / packages can be in multiple different class paths, which can be directories or jar files.
If you are still having trouble and you are running something like EC2 AWS instance, it may just be a case of opening the port through the AWS console.
The shortcut that worked for me is
SHIFT+ALT+CMD+L
You can optimize imports to remove the ones you don't use, and auto import the new classes.
Whenever you create child class object then that object has all the features of parent class. Here Super() is the facilty for accession parent.
If you write super() at that time parents's default constructor is called. same if you write super.
this keyword refers the current object same as super key word facilty for accessing parents.
You could add your JSON file as an external using webpack config. Then you can load up that json in any of your react modules.
Take a look at this answer
We demonstrate features of lmfit
while solving both problems.
Given
import lmfit
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
np.random.seed(123)
# General Functions
def func_log(x, a, b, c):
"""Return values from a general log function."""
return a * np.log(b * x) + c
# Data
x_samp = np.linspace(1, 5, 50)
_noise = np.random.normal(size=len(x_samp), scale=0.06)
y_samp = 2.5 * np.exp(1.2 * x_samp) + 0.7 + _noise
y_samp2 = 2.5 * np.log(1.2 * x_samp) + 0.7 + _noise
Code
Approach 1 - lmfit
Model
Fit exponential data
regressor = lmfit.models.ExponentialModel() # 1
initial_guess = dict(amplitude=1, decay=-1) # 2
results = regressor.fit(y_samp, x=x_samp, **initial_guess)
y_fit = results.best_fit
plt.plot(x_samp, y_samp, "o", label="Data")
plt.plot(x_samp, y_fit, "k--", label="Fit")
plt.legend()
Approach 2 - Custom Model
Fit log data
regressor = lmfit.Model(func_log) # 1
initial_guess = dict(a=1, b=.1, c=.1) # 2
results = regressor.fit(y_samp2, x=x_samp, **initial_guess)
y_fit = results.best_fit
plt.plot(x_samp, y_samp2, "o", label="Data")
plt.plot(x_samp, y_fit, "k--", label="Fit")
plt.legend()
Details
You can determine the inferred parameters from the regressor object. Example:
regressor.param_names
# ['decay', 'amplitude']
To make predictions, use the ModelResult.eval()
method.
model = results.eval
y_pred = model(x=np.array([1.5]))
Note: the ExponentialModel()
follows a decay function, which accepts two parameters, one of which is negative.
See also ExponentialGaussianModel()
, which accepts more parameters.
Install the library via > pip install lmfit
.
I was able to install libc6 2.17
in Debian Wheezy
by editing the recommendations in perror's answer:
IMPORTANT
You need to exit out of your display manager by pressing CTRL-ALT-F1.
Then you can stop x (slim
) with sudo /etc/init.d/slim stop
(replace slim with mdm
or lightdm
or whatever)
Add the following line to the file /etc/apt/sources.list
:
deb http://ftp.debian.org/debian experimental main
Should be changed to:
deb http://ftp.debian.org/debian sid main
Then follow the rest of perror's post:
Update your package database:
apt-get update
Install the eglibc
package:
apt-get -t sid install libc6-amd64 libc6-dev libc6-dbg
IMPORTANT
After done updating libc6
, restart computer, and you should comment out or remove the sid source you just added (deb http://ftp.debian.org/debian sid main
), or else you risk upgrading your whole distro to sid.
Hope this helps. It took me a while to figure out.
var span = TimeSpan.FromMinutes(2);
var t = Task.Factory.StartNew(async delegate / () =>
{
this.SomeAsync();
await Task.Delay(span, source.Token);
}, source.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
source.Cancel(true/or not);
// or use ThreadPool(whit defaul options thread) like this
Task.Start(()=>{...}), source.Token)
if u like use some loop thread inside ...
public async void RunForestRun(CancellationToken token)
{
var t = await Task.Factory.StartNew(async delegate
{
while (true)
{
await Task.Delay(TimeSpan.FromSeconds(1), token)
.ContinueWith(task => { Console.WriteLine("End delay"); });
this.PrintConsole(1);
}
}, token) // drop thread options to default values;
}
// And somewhere there
source.Cancel();
//or
token.ThrowIfCancellationRequested(); // try/ catch block requred.
Use the ASCII table to pick a range of letters, where the: $range_start , $range_end is a value from the decimal column in the ASCII table.
I find that this method is nicer compared to the method described where the range of characters is specifically defined within another string.
// range is numbers (48) through capital and lower case letters (122)
$range_start = 48;
$range_end = 122;
$random_string = "";
$random_string_length = 10;
for ($i = 0; $i < $random_string_length; $i++) {
$ascii_no = round( mt_rand( $range_start , $range_end ) ); // generates a number within the range
// finds the character represented by $ascii_no and adds it to the random string
// study **chr** function for a better understanding
$random_string .= chr( $ascii_no );
}
echo $random_string;
See More:
Apparently it does not and I didn't quite expect it would. HOWEVER Ivan brings up a good possibility that has escaped Android people.
What is the purpose of an emulator? to EMULATE, right? I don't see why for testing purposes -provided the tester understands the limitations- the emulator might not add a Wifi emulator.
It could for example emulate WiFi access by using the underlying internet connection of the host. Obviously testing WPA/WEP differencess would not make sense but at least it could toggle access via WiFi.
Or some sort of emulator plugin where there would be a base WiFi emulator that would emulate WiFi access via the underlying connection but then via configuration it could emulate WPA/WEP by providing a list of fake WiFi networks and their corresponding fake passwords that would be matched against a configurable list of credentials.
After all the idea is to do initial testing on the emulator and then move on to the actual device.
The reason why EF framework prompt 'no key' is that EF framework needs a primary key in database. To declaratively tell EF which property the key is, you add a [Key]
annotation. Or, the quickest way, add an ID
property. Then, the EF framework will take ID
as the primary key by default.
In HTML:
<form onsubmit="return false">
</form>
in order to avoid refresh at all "buttons", even with onclick assigned.
Underscore has a _without() method perfect for removing an item from an array, especially if you have the object to remove.
Returns a copy of the array with all instances of the values removed.
_.without(["bob", "sam", "fred"], "sam");
=> ["bob", "fred"]
Works with more complex objects too.
var bob = { Name: "Bob", Age: 35 };
var sam = { Name: "Sam", Age: 19 };
var fred = { Name: "Fred", Age: 50 };
var people = [bob, sam, fred]
_.without(people, sam);
=> [{ Name: "Bob", Age: 35 }, { Name: "Fred", Age: 50 }];
If you don't have the item to remove, just a property of it, you can use _.findWhere
and then _.without
.
There are two ways to access an inner function. One, instance-level, like you want, another, static level.
You need to call the function on the return from React.render
. See below.
Take a look at ReactJS Statics. Note, however, that a static function cannot access instance-level data, so this
would be undefined
.
var onButtonClick = function () {
//call alertMessage method from the reference of a React Element!
HelloRendered.alertMessage();
//call static alertMessage method from the reference of a React Class!
Hello.alertMessage();
console.log("clicked!");
}
var Hello = React.createClass({
displayName: 'Hello',
statics: {
alertMessage: function () {
alert('static message');
}
},
alertMessage: function () {
alert(this.props.name);
},
render: function () {
return React.createElement("div", null, "Hello ", this.props.name);
}
});
var HelloElement = React.createElement(Hello, {
name: "World"
});
var HelloRendered = React.render(HelloElement, document.getElementById('container'));
Then do HelloRendered.alertMessage()
.
$j_decoded = utf8_decode(json_decode($j_encoded));
EDIT
or to be more correct $j_encoded = json_encode($j_encoded);
$j_decoded = json_decode($j_encoded);
no need for en/decoding utf8<meta charset="utf-8" />
.NET 4
string.Join(",", arr)
.NET earlier
string.Join(",", Array.ConvertAll(arr, x => x.ToString()))
It formats the string as two uppercase hexadecimal characters.
In more depth, the argument "X2"
is a "format string" that tells the ToString()
method how it should format the string. In this case, "X2" indicates the string should be formatted in Hexadecimal.
byte.ToString()
without any arguments returns the number in its natural decimal representation, with no padding.
Microsoft documents the standard numeric format strings which generally work with all primitive numeric types' ToString()
methods. This same pattern is used for other types as well: for example, standard date/time format strings can be used with DateTime.ToString()
.
Make sure the Excel file isn't open.
final View rootView = findViewById(android.R.id.content);
rootView.setBackgroundResource(...);
implements
means a behaviour will be defined for abstract
methods (except for abstract classes obviously), you define the implementation.
extends
means that a behaviour is inherited.
With interfaces it is possible to say that one interface should have that the same behaviour as another, there is not even an actual implementation. That's why it makes more sense for an interface to extends
another interface instead of implementing it.
On a side note, remember that even if an abstract
class can define abstract
methods (the sane way an interface does), it is still a class and still has to be inherited (extended) and not implemented.
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(OrientationDidChange:) name:UIDeviceOrientationDidChangeNotification object:nil];
}
-(void)OrientationDidChange:(NSNotification*)notification {
UIDeviceOrientation Orientation=[[UIDevice currentDevice]orientation];
if(Orientation==UIDeviceOrientationLandscapeLeft || Orientation==UIDeviceOrientationLandscapeRight) {
NSLog(@"Landscape");
} else if(Orientation==UIDeviceOrientationPortrait) {
NSLog(@"Potrait Mode");
}
}
NOTE: Just use this code to identify UIViewController is in which orientation
Following solution is very basic and simple approach to send data from VC2 to VC1 using delegate .
PS: This solution is made in Xcode 9.X and Swift 4
Declared a protocol and created a delegate var into ViewControllerB
import UIKit
//Declare the Protocol into your SecondVC
protocol DataDelegate {
func sendData(data : String)
}
class ViewControllerB : UIViewController {
//Declare the delegate property in your SecondVC
var delegate : DataDelegate?
var data : String = "Send data to ViewControllerA."
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func btnSendDataPushed(_ sender: UIButton) {
// Call the delegate method from SecondVC
self.delegate?.sendData(data:self.data)
dismiss(animated: true, completion: nil)
}
}
ViewControllerA confirms the protocol and expected to receive data via delegate method sendData
import UIKit
// Conform the DataDelegate protocol in ViewControllerA
class ViewControllerA : UIViewController , DataDelegate {
@IBOutlet weak var dataLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func presentToChild(_ sender: UIButton) {
let childVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier:"ViewControllerB") as! ViewControllerB
//Registered delegate
childVC.delegate = self
self.present(childVC, animated: true, completion: nil)
}
// Implement the delegate method in ViewControllerA
func sendData(data : String) {
if data != "" {
self.dataLabel.text = data
}
}
}
You can also solve this problem via Apache configuration using mod_remoteip, by adding the following to a conf.d file:
RemoteIPHeader X-Forwarded-For
RemoteIPInternalProxy 172.16.0.0/12
LogFormat "%a %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
Say you have number 1,2,3,4,5,6, in cell A1,A2,A3,A4,A5,A6 respectively. in cell A7 we calculate the sum of A1:Ax. x is specified in cell B1 (in this case, x can be any number from 1 to 6). in cell A7, you can write the following formular:
=SUM(A1:INDIRECT(CONCATENATE("A",B1)))
CONCATENATE will give you the index of the cell Ax(if you put 3 in B1, CONCATENATE("A",B1)) gives A3).
INDIRECT convert "A3" to a index.
see this link Using the value in a cell as a cell reference in a formula?
this error also occurs due to changed API URL. try hitting the URL you are using in postman and c if it's working properly. rechecking the APIs solved my problem
The special target .PHONY:
allows to declare phony targets, so that make
will not check them as actual file names: it will work all the time even if such files still exist.
You can put several .PHONY:
in your Makefile
:
.PHONY: all
all : prog1 prog2
...
.PHONY: clean distclean
clean :
...
distclean :
...
There is another way to declare phony targets : simply put ::
without prerequisites :
all :: prog1 prog2
...
clean ::
...
distclean ::
...
The ::
has other special meanings, see here, but without prerequisites it always execute the recipes, even if the target already exists, thus acting as a phony target.
div
's will naturally resize in accordance with their content.
If you set no height on your div, it will expand to contain its conent.
An exception to this rule is when the div contains floating elements. If this is the case you'll need to do a bit extra to ensure that the containing div (wrapper) clears the floats.
Here's some ways to do this:
#wrapper{
overflow:hidden;
}
Or
#wrapper:after
{
content:".";
display:block;
clear:both;
visibility:hidden;
}
For drawing just the arrow, there is an easier method:-
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_aspect("equal")
#draw the arrow
ax.quiver(0,0,0,1,1,1,length=1.0)
plt.show()
quiver can actually be used to plot multiple vectors at one go. The usage is as follows:- [ from http://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html?highlight=quiver#mpl_toolkits.mplot3d.Axes3D.quiver]
quiver(X, Y, Z, U, V, W, **kwargs)
Arguments:
X, Y, Z: The x, y and z coordinates of the arrow locations
U, V, W: The x, y and z components of the arrow vectors
The arguments could be array-like or scalars.
Keyword arguments:
length: [1.0 | float] The length of each quiver, default to 1.0, the unit is the same with the axes
arrow_length_ratio: [0.3 | float] The ratio of the arrow head with respect to the quiver, default to 0.3
pivot: [ ‘tail’ | ‘middle’ | ‘tip’ ] The part of the arrow that is at the grid point; the arrow rotates about this point, hence the name pivot. Default is ‘tail’
normalize: [False | True] When True, all of the arrows will be the same length. This defaults to False, where the arrows will be different lengths depending on the values of u,v,w.
If you want to remove \n
from the last element only, use this:
t[-1] = t[-1].strip()
If you want to remove \n
from all the elements, use this:
t = map(lambda s: s.strip(), t)
You might also consider removing \n
before splitting the line:
line = line.strip()
# split line...
Ok, finally found the solution.
Probably due to lack of experience with ReactJS and web development...
var Task = React.createClass({
render: function() {
var percentage = this.props.children + '%';
....
<div className="ui-progressbar-value ui-widget-header ui-corner-left" style={{width : percentage}}/>
...
I created the percentage variable outside in the render function.
It's simple while cloning please take the git URL with your username.While committing it will ask your new user password.
Eg:
or, on mozilla:
document.body.onselectstart = function() { return false; } // Or any html object
On IE,
document.body.onmousedown = function() { return false; } // valid for any html object as well
Mutex is to protect the shared resource.
Semaphore is to dispatch the threads.
Mutex:
Imagine that there are some tickets to sell. We can simulate a case where many people buy the tickets at the same time: each person is a thread to buy tickets. Obviously we need to use the mutex to protect the tickets because it is the shared resource.
Semaphore:
Imagine that we need to do a calculation as below:
c = a + b;
Also, we need a function geta()
to calculate a
, a function getb()
to calculate b
and a function getc()
to do the calculation c = a + b
.
Obviously, we can't do the c = a + b
unless geta()
and getb()
have been finished.
If the three functions are three threads, we need to dispatch the three threads.
int a, b, c;
void geta()
{
a = calculatea();
semaphore_increase();
}
void getb()
{
b = calculateb();
semaphore_increase();
}
void getc()
{
semaphore_decrease();
semaphore_decrease();
c = a + b;
}
t1 = thread_create(geta);
t2 = thread_create(getb);
t3 = thread_create(getc);
thread_join(t3);
With the help of the semaphore, the code above can make sure that t3
won't do its job untill t1
and t2
have done their jobs.
In a word, semaphore is to make threads execute as a logicial order whereas mutex is to protect shared resource.
So they are NOT the same thing even if some people always say that mutex is a special semaphore with the initial value 1. You can say like this too but please notice that they are used in different cases. Don't replace one by the other even if you can do that.
Yes, JavaScript variables will exist in the scope they are created.
var bannerID = 55;
<input id="EditBanner" type="button"
value="Edit Image" onclick="EditBanner(bannerID);"/>
function EditBanner(id) {
//Do something with id
}
If you use event handlers and jQuery it is simple also
$("#EditBanner").click(function() {
EditBanner(bannerID);
});
For git mv
the
manual page
says
The index is updated after successful completion, […]
So, at first, you have to update the index on your own
(by using git add mobile.css
). However
git status
will still show two different files
$ git status
# On branch master
warning: LF will be replaced by CRLF in index.html
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# modified: index.html
# new file: mobile.css
#
# Changed but not updated:
# (use "git add/rm <file>..." to update what will be committed)
# (use "git checkout -- <file>..." to discard changes in working directory)
#
# deleted: iphone.css
#
You can get a different output by running
git commit --dry-run -a
, which results in what you
expect:
Tanascius@H181 /d/temp/blo (master)
$ git commit --dry-run -a
# On branch master
warning: LF will be replaced by CRLF in index.html
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# modified: index.html
# renamed: iphone.css -> mobile.css
#
I can't tell you exactly why we see these differences
between git status
and
git commit --dry-run -a
, but
here is a hint from
Linus:
git really doesn't even care about the whole "rename detection" internally, and any commits you have done with renames are totally independent of the heuristics we then use to show the renames.
A dry-run
uses the real renaming mechanisms, while a
git status
probably doesn't.
If you use Nginx behind other balancer, for instance AWS Application Balancer, HTTP_X_FORWARDED_FOR returns list of addresses. It can be fixed like that:
if 'X-Forwarded-For' in request.headers:
proxy_data = request.headers['X-Forwarded-For']
ip_list = proxy_data.split(',')
user_ip = ip_list[0] # first address in list is User IP
else:
user_ip = request.remote_addr # For local development
Here's another way to be compatible with an IHttpActionResult return type. In this case I am asking it to use the XML Serializer(optional) instead of Data Contract serializer, I'm using return ResponseMessage(
so that I get a return compatible with IHttpActionResult:
return ResponseMessage(new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ObjectContent<SomeType>(objectToSerialize,
new System.Net.Http.Formatting.XmlMediaTypeFormatter {
UseXmlSerializer = true
})
});
Java 8 user can do that: list.removeIf(...)
List<String> list = new ArrayList<>(Arrays.asList("a", "b", "c"));
list.removeIf(e -> (someCondition));
It will remove elements in the list, for which someCondition is satisfied
Barring the CSS solution. The fastest possible way is to hide it immediatly with a script.
<div id="hideme"></div>
<script type="text/javascript">
$("#hideme").hide();
</script>
In this case I would recommend the CSS solution by Vega. But if you need something more complex (like an animation) you can use this approach.
This has some complications (see comments below). If you want this piece of script to really run as fast as possible you can't use jQuery, use native JS only and defer loading of all other scripts.
You can use pathlib.
For Python 3.5 and above:
from pathlib import Path
contents = Path(file_path).read_text()
For older versions of Python use pathlib2:
$ pip install pathlib2
Then:
from pathlib2 import Path
contents = Path(file_path).read_text()
This is the actual read_text
implementation:
def read_text(self, encoding=None, errors=None):
"""
Open the file in text mode, read it, and close the file.
"""
with self.open(mode='r', encoding=encoding, errors=errors) as f:
return f.read()
What worked for me:
int main()
{
char buff[1024] = {0};
FILE* cvt;
int status;
/* Launch converter and open a pipe through which the parent will write to it */
cvt = popen("converter", "w");
if (!cvt)
{
printf("couldn't open a pipe; quitting\n");
exit(1)
}
printf("enter Fahrenheit degrees: " );
fgets(buff, sizeof (buff), stdin); /*read user's input */
/* Send expression to converter for evaluation */
fprintf(cvt, "%s\n", buff);
fflush(cvt);
/* Close pipe to converter and wait for it to exit */
status=pclose(cvt);
/* Check the exit status of pclose() */
if (!WIFEXITED(status))
printf("error on closing the pipe\n");
return 0;
}
The important steps in this program are:
popen()
call which establishes the association between a child process and a pipe in the parent.fprintf()
call that uses the pipe as an ordinary file to write to the child process's stdin or read from its stdout.pclose()
call that closes the pipe and causes the child process to terminate.other method
INSERT INTO tableName (col1, col2, col3, col4, col5)
select * from table(
values
(val1, val2, val3, val4, val5),
(val1, val2, val3, val4, val5),
(val1, val2, val3, val4, val5),
(val1, val2, val3, val4, val5)
) tmp
Go to your Target or Project settings, click the Gear icon at the bottom left, and select "Add User-Defined Setting". The new setting name should be GCC_PREPROCESSOR_DEFINITIONS
, and you can type your definitions in the right-hand field.
Per Steph's comments, the full syntax is:
constant_1=VALUE constant_2=VALUE
Note that you don't need the '='s if you just want to #define a symbol, rather than giving it a value (for #ifdef
statements)
Use the method .rdd
like this:
rdd = df.rdd
As A4L mentioning, you can use StringWriter. Providing here example code:
private static String jaxbObjectToXML(Customer customer) {
String xmlString = "";
try {
JAXBContext context = JAXBContext.newInstance(Customer.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // To format XML
StringWriter sw = new StringWriter();
m.marshal(customer, sw);
xmlString = sw.toString();
} catch (JAXBException e) {
e.printStackTrace();
}
return xmlString;
}
Requests doesn't have an equivalent to Urlib2's read()
.
>>> import requests
>>> response = requests.get("http://www.google.com")
>>> print response.content
'<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage"><head>....'
>>> print response.content == response.text
True
It looks like the POST request you are making is returning no content. Which is often the case with a POST request. Perhaps it set a cookie? The status code is telling you that the POST succeeded after all.
Edit for Python 3:
Python now handles data types differently. response.content
returns a sequence of bytes
(integers that represent ASCII) while response.text
is a string
(sequence of chars).
Thus,
>>> print response.content == response.text
False
>>> print str(response.content) == response.text
True
AJAX does the magic:
$(document).ready(function(
$.ajax({ url: 'script.php?argument=value&foo=bar' });
));
You can do this with the following SQL:
SELECT STUFF
(
(
SELECT ',' + s.FirstName
FROM Employee s
ORDER BY s.FirstName FOR XML PATH('')
),
1, 1, ''
) AS Employees
My solution is , first decide the "id" ( @uids ) with select command and after update this id with @uids .
SET @uids := (SELECT id FROM table WHERE some = 0 LIMIT 1);
UPDATE table SET col = 1 WHERE id = @uids;SELECT @uids;
it worked on my project.
I like to do something like this:
String oneLetter = "" + someChar;
To enable USB debugging, go to settings, about phone and then at the bottom tap build number seven times. This will enable the developer settings where you can enable USB debugging.
This should work for you without changing program logic (by not outputting "Start error" on the top of each file) like the other answers do :) Remember to add exception handling code.
Dim filePath As String = String.Format("C:\ErrorLog_{0}.txt", DateTime.Today.ToString("dd-MMM-yyyy"))
Dim fileExists As Boolean = File.Exists(filePath)
Using writer As New StreamWriter(filePath, True)
If Not fileExists Then
writer.WriteLine("Start Error Log for today")
End If
writer.WriteLine("Error Message in Occured at-- " & DateTime.Now)
End Using
In case you would like to apply a simple transformation on all column names, this code does the trick: (I am replacing all spaces with underscore)
new_column_name_list= list(map(lambda x: x.replace(" ", "_"), df.columns))
df = df.toDF(*new_column_name_list)
Thanks to @user8117731 for toDf
trick.
In C char
gets promoted to int
in expressions. That pretty much explains every question, if you think about it.
Source: The C Programming Language by Brian W.Kernighan and Dennis M.Ritchie
A must read if you want to learn C.
Also see this stack overflow page, where people much more experienced then me can explain it much better then I ever can.
Or, you could use the margin attribute like this:
{
background:#222;
width:100%;
height:100px;
margin-left: 10px;
margin-right: 10px;
display:block;
}
With Joda-Time
DateTime dt = new DateTime();
DateTime added = dt.plusHours(6);
Environment.SetEnvironmentVariable("Variable name", value, EnvironmentVariableTarget.User);
In CakePHP you can get it by: Model::getInsertID() //Returns the ID of the last record this model inserted. Model::getLastInsertID() //Alias to getInsertID().
A simple function like below will help :
public string GetCurrentPageName()
{
string sPath = System.Web.HttpContext.Current.Request.Url.AbsolutePath;
System.IO.FileInfo oInfo = new System.IO.FileInfo(sPath);
string sRet = oInfo.Name;
return sRet;
}
<system.webServer>
<httpErrors errorMode="DetailedLocalOnly">
<remove statusCode="404" subStatusCode="-1" />
<error statusCode="404" prefixLanguageFilePath="" path="your page" responseMode="Redirect" />
</httpErrors>
</system.webServer>
Instead of
InputStream fstream = this.getClass().getResourceAsStream("abc.txt");
use
InputStream fstream = this.getClass().getClassLoader().getResourceAsStream("abc.txt");
In this way it will look from the root, not from the path of the current invoking class
Another way to filter on system apps (works with the example of king9981):
/**
* Return whether the given PackageInfo represents a system package or not.
* User-installed packages (Market or otherwise) should not be denoted as
* system packages.
*
* @param pkgInfo
* @return
*/
private boolean isSystemPackage(PackageInfo pkgInfo) {
return ((pkgInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
}
You can use LINQ:
String.Concat(str.OrderBy(c => c))
If you want to remove duplicates, add .Distinct()
.
NAs also appear if there are attributes with zero variance (with all elements equal); see for instance:
cor(cbind(a=runif(10),b=rep(1,10)))
which returns:
a b
a 1 NA
b NA 1
Warning message:
In cor(cbind(a = runif(10), b = rep(1, 10))) :
the standard deviation is zero
Try :
Configure in web config file
<system.web>
<globalization culture="ja-JP" uiCulture="zh-HK" />
</system.web>
eg: DateTime dt = DateTime.ParseExact("08/21/2013", "MM/dd/yyyy", null);
ref url : http://support.microsoft.com/kb/306162/
If you use cv2
, correct method is to use .copy()
method in Numpy. It will create a copy of the array you need. Otherwise it will produce only a view of that object.
eg:
In [1]: import numpy as np
In [2]: x = np.arange(10*10).reshape((10,10))
In [4]: y = x[3:7,3:7].copy()
In [6]: y[2,2] = 1000
In [8]: 1000 in x
Out[8]: False # see, 1000 in y doesn't change values in x, parent array.
Try calling label.Invalidate()
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.invalidate(VS.80).aspx
In real life, if you are using a ORM like LINQ-to-SQL
In both cases if you don't call a ToList()
or ToArray()
then query will be executed each time it is used, so, say, you have an IQueryable<T>
and you fill 4 list boxes from it, then the query will be run against the database 4 times.
Also if you extent your query:
q.Where(x.name = "a").ToList()
Then with a IQueryable the generated SQL will contains “where name = “a”, but with a IEnumerable many more roles will be pulled back from the database, then the x.name = “a” check will be done by .NET.
For "zip" files, you can use import zipfile
and your code will be working simply with these lines:
import zipfile
import pandas as pd
with zipfile.ZipFile("Crime_Incidents_in_2013.zip") as z:
with z.open("Crime_Incidents_in_2013.csv") as f:
train = pd.read_csv(f, header=0, delimiter="\t")
print(train.head()) # print the first 5 rows
And the result will be:
X,Y,CCN,REPORT_DAT,SHIFT,METHOD,OFFENSE,BLOCK,XBLOCK,YBLOCK,WARD,ANC,DISTRICT,PSA,NEIGHBORHOOD_CLUSTER,BLOCK_GROUP,CENSUS_TRACT,VOTING_PRECINCT,XCOORD,YCOORD,LATITUDE,LONGITUDE,BID,START_DATE,END_DATE,OBJECTID
0 -77.054968548763071,38.899775938598317,0925135...
1 -76.967309569035052,38.872119553647011,1003352...
2 -76.996184958456539,38.927921847721443,1101010...
3 -76.943077541353617,38.883686046653935,1104551...
4 -76.939209158039446,38.892278093281632,1125028...
If you want to convert to the new ES6 Map do this:
var kvArray = [['key1', 'value1'], ['key2', 'value2']];
var myMap = new Map(kvArray);
Why should you use this type of Map? Well that is up to you. Take a look at this.
Create a .o file:
g++ -c header.cpp
add this file to a library, creating library if necessary:
ar rvs header.a header.o
use library:
g++ main.cpp header.a
try use keyup.enter or keydown.enter
<button type="submit" (keyup.enter)="search(...)">Search</button>
You could create a dict comprehension of just the elements whose values are None, and then update back into the original:
tmp = dict((k,"") for k,v in mydict.iteritems() if v is None)
mydict.update(tmp)
Update - did some performance tests
Well, after trying dicts of from 100 to 10,000 items, with varying percentage of None values, the performance of Alex's solution is across-the-board about twice as fast as this solution.
// int year =2000; int month =9 ; int day=30;
public int getAge (int year, int month, int day) {
GregorianCalendar cal = new GregorianCalendar();
int y, m, d, noofyears;
y = cal.get(Calendar.YEAR);// current year ,
m = cal.get(Calendar.MONTH);// current month
d = cal.get(Calendar.DAY_OF_MONTH);//current day
cal.set(year, month, day);// here ur date
noofyears = y - cal.get(Calendar.YEAR);
if ((m < cal.get(Calendar.MONTH))
|| ((m == cal.get(Calendar.MONTH)) && (d < cal
.get(Calendar.DAY_OF_MONTH)))) {
--noofyears;
}
if(noofyears < 0)
throw new IllegalArgumentException("age < 0");
System.out.println(noofyears);
return noofyears;
ADT Plugin (UNSUPPORTED)
The Eclipse ADT plugin is no longer supported, as per this announcement in June 2015.
The Eclipse ADT plugin has many known bugs and potential security bugs that will not be fixed.
You should immediately switch to use Android Studio, the official IDE for Android.
For help transitioning your projects, read Migrate to Android Studio.
the settings below solved my issue
"editor.detectIndentation": false,
"editor.insertSpaces": false,
"editor.tabSize": 2,
How easy :)
date("F j, Y", strtotime( '-1 days' ) );
Example:
echo date("Y-m-j H:i:s", strtotime( '-1 days' ) ); // 2018-07-18 07:02:43
Output:
2018-07-17 07:02:43
In Selenium IDE you can do:
Command | clickAndWait Target | //input[@value='Next' and @title='next']
It should work fine.
You should prefer Object Mapper instead. Here is the link for the same : Object Mapper - Spring MVC way of Obect to JSON
If you want to completely abuse the data.frame (as I do) and like to keep the $ functionality, one way is to split you data.frame into one-line data.frames gathered in a list :
> df = data.frame(x=c('a','b','c'), y=3:1)
> df
x y
1 a 3
2 b 2
3 c 1
# 'convert' into a list of data.frames
ldf = lapply(as.list(1:dim(df)[1]), function(x) df[x[1],])
> ldf
[[1]]
x y
1 a 3
[[2]]
x y
2 b 2
[[3]]
x y
3 c 1
# and the 'coolest'
> ldf[[2]]$y
[1] 2
It is not only intellectual masturbation, but allows to 'transform' the data.frame into a list of its lines, keeping the $ indexation which can be useful for further use with lapply (assuming the function you pass to lapply uses this $ indexation)
It's called the carriage return, or \r
Use
print i/len(some_list)*100," percent complete \r",
The comma prevents print from adding a newline. (and the spaces will keep the line clear from prior output)
Also, don't forget to terminate with a print ""
to get at least a finalizing newline!
In case that you define your route like the one asked in the question (path: '/link/to/page'):
import Vue from 'vue'
import Router from 'vue-router'
import MyComponent from '@/components/MyComponent.vue';
Vue.use(Router)
export default new Router({
routes: [
{
path: '/link/to/page',
component: MyComponent
}
]
})
You can resolve the URL in your summary page and open your sub page as below:
<script>
export default {
methods: {
popup() {
let route = this.$router.resolve({path: '/link/to/page'});
// let route = this.$router.resolve('/link/to/page'); // This also works.
window.open(route.href, '_blank');
}
}
};
</script>
Of course if you've given your route a name, you can resolve the URL by name:
routes: [
{
path: '/link/to/page',
component: MyComponent,
name: 'subPage'
}
]
...
let route = this.$router.resolve({name: 'subPage'});
References:
Based on this blog, one could share a docker image without a docker registry by executing:
docker save --output latestversion-1.0.0.tar dockerregistry/latestversion:1.0.0
Once this command has been completed, one could copy the image to a server and import it as follows:
docker load --input latestversion-1.0.0.tar
If you're using more than one argument it has to be in a tuple (note the extra parentheses):
'%s in %s' % (unicode(self.author), unicode(self.publication))
As EOL points out, the unicode()
function usually assumes ascii encoding as a default, so if you have non-ASCII characters, it's safer to explicitly pass the encoding:
'%s in %s' % (unicode(self.author,'utf-8'), unicode(self.publication('utf-8')))
And as of Python 3.0, it's preferred to use the str.format()
syntax instead:
'{0} in {1}'.format(unicode(self.author,'utf-8'),unicode(self.publication,'utf-8'))
$(window).on("scroll", function() {
//get height of the (browser) window aka viewport
var scrollHeight = $(document).height();
// get height of the document
var scrollPosition = $(window).height() + $(window).scrollTop();
if ((scrollHeight - scrollPosition) / scrollHeight === 0) {
// code to run when scroll to bottom of the page
}
});
This is the code on github.
You can use the -R option to find the files along with those inside the recursive directories
ls -R | wc -l // to find all the files
ls -R | grep log | wc -l // to find the files which contains the word log
you can use patterns on the grep
But I can't figure out why should we use it like this?
I will compare how it works inside the function body if you use:
Object myObject;
Inside the function, your myObject
will get destroyed once this function returns. So this is useful if you don't need your object outside your function. This object will be put on current thread stack.
If you write inside function body:
Object *myObject = new Object;
then Object class instance pointed by myObject
will not get destroyed once the function ends, and allocation is on the heap.
Now if you are Java programmer, then the second example is closer to how object allocation works under java. This line: Object *myObject = new Object;
is equivalent to java: Object myObject = new Object();
. The difference is that under java myObject will get garbage collected, while under c++ it will not get freed, you must somewhere explicitly call `delete myObject;' otherwise you will introduce memory leaks.
Since c++11 you can use safe ways of dynamic allocations: new Object
, by storing values in shared_ptr/unique_ptr.
std::shared_ptr<std::string> safe_str = make_shared<std::string>("make_shared");
// since c++14
std::unique_ptr<std::string> safe_str = make_unique<std::string>("make_shared");
also, objects are very often stored in containers, like map-s or vector-s, they will automatically manage a lifetime of your objects.
@jasonk - if you want to have "or" then negate all conditions since (A and B) <=> ~(~A or ~B)
but if you have values other than boolean try using type converters:
<MultiDataTrigger.Conditions>
<Condition Value="True">
<Condition.Binding>
<MultiBinding Converter="{StaticResource conditionConverter}">
<Binding Path="Name" />
<Binding Path="State" />
</MultiBinding>
</Condition.Binding>
<Setter Property="Background" Value="Cyan" />
</Condition>
</MultiDataTrigger.Conditions>
you can use the values in Convert method any way you like to produce a condition which suits you.
Errr, it's a bit messy in the view. But I think I've gotten it to work with group (http://mongoid.org/docs/querying/)
Controller
@event_attendees = Activity.only(:user_id).where(:action => 'Attend').order_by(:created_at.desc).group
View
<% @event_attendees.each do |event_attendee| %>
<%= event_attendee['group'].first.user.first_name %>
<% end %>
The only way I have 100% consistently been able to avoid this flex-direction column bug is to use a min-width media query to assign a max-width to the child element on desktop sized screens.
.parent {
display: flex;
flex-direction: column;
}
//a media query targeting desktop sort of sized screens
@media screen and (min-width: 980px) {
.child {
display: block;
max-width: 500px;//maximimum width of the element on a desktop sized screen
}
}
You will need to set naturally inline child elements (eg. <span>
or <a>
) to something other than inline (mainly display:block or display:inline-block) for the fix to work.
return
in function return execution back to caller and exit
from function terminates the program.
in main
function return 0
or exit(0)
are same but if you write exit(0)
in different function then you program will exit from that position.
returning different values like return 1
or return -1
means that program is returning error .
When exit(0)
is used to exit from program, destructors for locally scoped non-static objects are not called. But destructors are called if return 0 is used.
I finished my time alert with a unwanted effect.... Browsers add stuff to windows. My script is an aptated one and I will show after the following text.
I found a CSS script for popups, which doesn't have unwanted browser stuff. This was written by Prakash:- https://codepen.io/imprakash/pen/GgNMXO. This script I will show after the following text.
This CSS script above looks professional and is alot more tidy. This button could be a clickable company logo image. By suppressing this button/image from running a function, this means you can run this function from inside javascript or call it with CSS, without it being run by clicking it.
This popup alert stays inside the window that popped it up. So if you are a multi-tasker you won't have trouble knowing what alert goes with what window.
The statements above are valid ones.... (Please allow). How these are achieved will be down to experimentation, as my knowledge of CSS is limited at the moment, but I learn fast.
CSS menus/DHTML use mouseover(valid statement).
I have a CSS menu script of my own which is adapted from 'Javascript for dummies' that pops up a menu alert. This works, but text size is limited. This hides under the top window banner. This could be set to be timed alert. This isn't great, but I will show this after the following text.
The Prakash script above I feel could be the answer if you can adapt it.
Scripts that follow:- My adapted timed window alert, Prakash's CSS popup script, my timed menu alert.
1.
<html>
<head>
<title></title>
<script language="JavaScript">
// Variables
leftposition=screen.width-350
strfiller0='<table border="1" cellspacing="0" width="98%"><tr><td><br>'+'Alert: '+'<br><hr width="98%"><br>'
strfiller1=' This alert is a timed one.'+'<br><br><br></td></tr></table>'
temp=strfiller0+strfiller1
// Javascript
// This code belongs to Stephen Mayes Date: 25/07/2016 time:8:32 am
function preview(){
preWindow= open("", "preWindow","status=no,toolbar=no,menubar=yes,width=350,height=180,left="+leftposition+",top=0");
preWindow.document.open();
preWindow.document.write(temp);
preWindow.document.close();
setTimeout(function(){preWindow.close()},4000);
}
</script>
</head>
<body>
<input type="button" value=" Open " onclick="preview()">
</body>
</html>
2.
<style>
body {
font-family: Arial, sans-serif;
background: url(http://www.shukatsu-note.com/wp-content/uploads/2014/12/computer-564136_1280.jpg) no-repeat;
background-size: cover;
height: 100vh;
}
h1 {
text-align: center;
font-family: Tahoma, Arial, sans-serif;
color: #06D85F;
margin: 80px 0;
}
.box {
width: 40%;
margin: 0 auto;
background: rgba(255,255,255,0.2);
padding: 35px;
border: 2px solid #fff;
border-radius: 20px/50px;
background-clip: padding-box;
text-align: center;
}
.button {
font-size: 1em;
padding: 10px;
color: #fff;
border: 2px solid #06D85F;
border-radius: 20px/50px;
text-decoration: none;
cursor: pointer;
transition: all 0.3s ease-out;
}
.button:hover {
background: #06D85F;
}
.overlay {
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
background: rgba(0, 0, 0, 0.7);
transition: opacity 500ms;
visibility: hidden;
opacity: 0;
}
.overlay:target {
visibility: visible;
opacity: 1;
}
.popup {
margin: 70px auto;
padding: 20px;
background: #fff;
border-radius: 5px;
width: 30%;
position: relative;
transition: all 5s ease-in-out;
}
.popup h2 {
margin-top: 0;
color: #333;
font-family: Tahoma, Arial, sans-serif;
}
.popup .close {
position: absolute;
top: 20px;
right: 30px;
transition: all 200ms;
font-size: 30px;
font-weight: bold;
text-decoration: none;
color: #333;
}
.popup .close:hover {
color: #06D85F;
}
.popup .content {
max-height: 30%;
overflow: auto;
}
@media screen and (max-width: 700px){
.box{
width: 70%;
}
.popup{
width: 70%;
}
}
</style>
<script>
// written by Prakash:- https://codepen.io/imprakash/pen/GgNMXO
</script>
<body>
<h1>Popup/Modal Windows without JavaScript</h1>
<div class="box">
<a class="button" href="#popup1">Let me Pop up</a>
</div>
<div id="popup1" class="overlay">
<div class="popup">
<h2>Here i am</h2>
<a class="close" href="#">×</a>
<div class="content">
Thank to pop me out of that button, but now i'm done so you can close this window.
</div>
</div>
</div>
</body>
3.
<HTML>
<HEAD>
<TITLE>Using DHTML to Create Sliding Menus (From JavaScript For Dummies, 4th Edition)</TITLE>
<SCRIPT LANGUAGE="JavaScript" TYPE="text/javascript">
<!-- Hide from older browsers
function displayMenu(currentPosition,nextPosition) {
// Get the menu object located at the currentPosition on the screen
var whichMenu = document.getElementById(currentPosition).style;
if (displayMenu.arguments.length == 1) {
// Only one argument was sent in, so we need to
// figure out the value for "nextPosition"
if (parseInt(whichMenu.top) == -5) {
// Only two values are possible: one for mouseover
// (-5) and one for mouseout (-90). So we want
// to toggle from the existing position to the
// other position: i.e., if the position is -5,
// set nextPosition to -90...
nextPosition = -90;
}
else {
// Otherwise, set nextPosition to -5
nextPosition = -5;
}
}
// Redisplay the menu using the value of "nextPosition"
whichMenu.top = nextPosition + "px";
}
// End hiding-->
</SCRIPT>
<STYLE TYPE="text/css">
<!--
.menu {position:absolute; font:10px arial, helvetica, sans-serif; background-color:#ffffcc; layer-background-color:#ffffcc; top:-90px}
#resMenu {right:10px; width:-130px}
A {text-decoration:none; color:#000000}
A:hover {background-color:pink; color:blue}
-->
</STYLE>
</HEAD>
<BODY BGCOLOR="white">
<div id="resMenu" class="menu" onmouseover="displayMenu('resMenu',-5)" onmouseout="displayMenu('resMenu',-90)"><br />
<a href="#"> Alert:</a><br>
<a href="#"> </a><br>
<a href="#"> You pushed that button again... Didn't yeah? </a><br>
<a href="#"> </a><br>
<a href="#"> </a><br>
<a href="#"> </a><br>
</div>
ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd
<input type="button" value="Wake that alert up" onclick="displayMenu('resMenu',-5)">
</BODY>
</HTML>
I don't think that you need to use each()
, you can use standard for loop
var children = $element.children().not(".pb-sortable-placeholder");
for (var i = 0; i < children.length; i++) {
var currentChild = children.eq(i);
// whatever logic you want
var oldPosition = currentChild.data("position");
}
this way you can have the standard for loop features like break
and continue
works by default
also, the debugging will be easier
//C# class
public class DashBoardViewModel
{
public int Id { get; set;}
public decimal TotalSales { get; set;}
public string Url { get; set;}
public string MyDate{ get; set;}
}
//JavaScript file
//Create dashboard.js file
$(document).ready(function () {
// See the html on the View below
$('.dashboardUrl').on('click', function(){
var url = $(this).attr("href");
});
$("#inpDateCompleted").change(function () {
// Construct your view model to send to the controller
// Pass viewModel to ajax function
// Date
var myDate = $('.myDate').val();
// IF YOU USE @Html.EditorFor(), the myDate is as below
var myDate = $('#MyDate').val();
var viewModel = { Id : 1, TotalSales: 50, Url: url, MyDate: myDate };
$.ajax({
type: 'GET',
dataType: 'json',
cache: false,
url: '/Dashboard/IndexPartial',
data: viewModel ,
success: function (data, textStatus, jqXHR) {
//Do Stuff
$("#DailyInvoiceItems").html(data.Id);
},
error: function (jqXHR, textStatus, errorThrown) {
//Do Stuff or Nothing
}
});
});
});
//ASP.NET 5 MVC 6 Controller
public class DashboardController {
[HttpGet]
public IActionResult IndexPartial(DashBoardViewModel viewModel )
{
// Do stuff with my model
var model = new DashBoardViewModel { Id = 23 /* Some more results here*/ };
return Json(model);
}
}
// MVC View
// Include jQuerylibrary
// Include dashboard.js
<script src="~/Scripts/jquery-2.1.3.js"></script>
<script src="~/Scripts/dashboard.js"></script>
// If you want to capture your URL dynamically
<div>
<a class="dashboardUrl" href ="@Url.Action("IndexPartial","Dashboard")"> LinkText </a>
</div>
<div>
<input class="myDate" type="text"/>
//OR
@Html.EditorFor(model => model.MyDate)
</div>
Append ll suffix to hex digits for 64-bit (long long int), or ull suffix for unsigned 64-bit (unsigned long long)
Solution for Windows 7 and Nexus 5 (should be applicable for any Nexus device):
I figured out that my system was installing the Nexus 5 default driver for windows automatically the moment I was connecting my Nexus 5 to my system through USB. So uninstalling the default driver was in vain and it gets installed automatically anyways.Moreover if you uninstall the default driver, you won't be able to locate Nexus 5 under Devices in Computer Management. So here is what i did and worked for me!
%APPDATA%\Local\Android\sdk\extras\google\usb_driver
In addition to @Bikesh M Annur's answer, be sure to update your support libraries. Previously I was using 23.1.1 and nothing happened. Updating it to 23.3.0 did the trick.
Position the cursor inside the class, then press ALT + Ins and select Getters and Setters
from the contextual menu.
This is work for me. Also work for Nougat and Marshmallow[[
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private final static int FCR = 1;
WebView webView;
private String mCM;
private ValueCallback<Uri> mUM;
private ValueCallback<Uri[]> mUMA;
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (Build.VERSION.SDK_INT >= 21) {
Uri[] results = null;
//Check if response is positive
if (resultCode == Activity.RESULT_OK) {
if (requestCode == FCR) {
if (null == mUMA) {
return;
}
if (intent == null) {
//Capture Photo if no image available
if (mCM != null) {
results = new Uri[]{Uri.parse(mCM)};
}
} else {
String dataString = intent.getDataString();
if (dataString != null) {
results = new Uri[]{Uri.parse(dataString)};
}
}
}
}
mUMA.onReceiveValue(results);
mUMA = null;
} else {
if (requestCode == FCR) {
if (null == mUM) return;
Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
mUM.onReceiveValue(result);
mUM = null;
}
}
}
@SuppressLint({"SetJavaScriptEnabled", "WrongViewCast"})
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= 23 && (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, 1);
}
webView = (WebView) findViewById(R.id.ifView);
assert webView != null;
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAllowFileAccess(true);
if (Build.VERSION.SDK_INT >= 21) {
webSettings.setMixedContentMode(0);
webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
} else if (Build.VERSION.SDK_INT >= 19) {
webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
} else if (Build.VERSION.SDK_INT < 19) {
webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
webView.setWebViewClient(new Callback());
webView.loadUrl("https://infeeds.com/");
webView.setWebChromeClient(new WebChromeClient() {
//For Android 3.0+
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
mUM = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
MainActivity.this.startActivityForResult(Intent.createChooser(i, "File Chooser"), FCR);
}
// For Android 3.0+, above method not supported in some android 3+ versions, in such case we use this
public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
mUM = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
MainActivity.this.startActivityForResult(
Intent.createChooser(i, "File Browser"),
FCR);
}
//For Android 4.1+
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
mUM = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
MainActivity.this.startActivityForResult(Intent.createChooser(i, "File Chooser"), MainActivity.FCR);
}
//For Android 5.0+
public boolean onShowFileChooser(
WebView webView, ValueCallback<Uri[]> filePathCallback,
WebChromeClient.FileChooserParams fileChooserParams) {
if (mUMA != null) {
mUMA.onReceiveValue(null);
}
mUMA = filePathCallback;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(MainActivity.this.getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
takePictureIntent.putExtra("PhotoPath", mCM);
} catch (IOException ex) {
Log.e(TAG, "Image file creation failed", ex);
}
if (photoFile != null) {
mCM = "file:" + photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
} else {
takePictureIntent = null;
}
}
Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType("*/*");
Intent[] intentArray;
if (takePictureIntent != null) {
intentArray = new Intent[]{takePictureIntent};
} else {
intentArray = new Intent[0];
}
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
startActivityForResult(chooserIntent, FCR);
return true;
}
});
}
// Create an image file
private File createImageFile() throws IOException {
@SuppressLint("SimpleDateFormat") String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "img_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
return File.createTempFile(imageFileName, ".jpg", storageDir);
}
@Override
public boolean onKeyDown(int keyCode, @NonNull KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (webView.canGoBack()) {
webView.goBack();
} else {
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
public class Callback extends WebViewClient {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(getApplicationContext(), "Failed loading app!", Toast.LENGTH_SHORT).show();
}
}
}
I found the following to be a working solution::
npm install aws-sdk
Once you've installed the aws-sdk , use the following code replacing values with your where needed.
var AWS = require('aws-sdk');
var fs = require('fs');
var s3 = new AWS.S3();
// Bucket names must be unique across all S3 users
var myBucket = 'njera';
var myKey = 'jpeg';
//for text file
//fs.readFile('demo.txt', function (err, data) {
//for Video file
//fs.readFile('demo.avi', function (err, data) {
//for image file
fs.readFile('demo.jpg', function (err, data) {
if (err) { throw err; }
params = {Bucket: myBucket, Key: myKey, Body: data };
s3.putObject(params, function(err, data) {
if (err) {
console.log(err)
} else {
console.log("Successfully uploaded data to myBucket/myKey");
}
});
});
I found the complete tutorial on the subject here in case you're looking for references ::
Try this :
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
public class FragmentOne extends Fragment{
View rootView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_one, container, false);
Button button = (Button) rootView.findViewById(R.id.buttonSayHi);
button.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
onButtonClicked(v);
}
});
return rootView;
}
public void onButtonClicked(View view)
{
//do your stuff here..
final FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.frameLayoutFragmentContainer, new FragmentTwo(), "NewFragmentTag");
ft.commit();
ft.addToBackStack(null);
}
}
check this : click here
Note: I have verified this in the latest version of IE, and other browsers like Mozilla and Chrome and this works for me. Hope it works for others as well.
if (data == "" || data == undefined) {
alert("Falied to open PDF.");
} else { //For IE using atob convert base64 encoded data to byte array
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
var byteCharacters = atob(data);
var byteNumbers = new Array(byteCharacters.length);
for (var i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
var blob = new Blob([byteArray], {
type: 'application/pdf'
});
window.navigator.msSaveOrOpenBlob(blob, fileName);
} else { // Directly use base 64 encoded data for rest browsers (not IE)
var base64EncodedPDF = data;
var dataURI = "data:application/pdf;base64," + base64EncodedPDF;
window.open(dataURI, '_blank');
}
}
Exception code 0xc0000005
is an Access Violation. An AV at fault offset 0x00000000
means that something in your service's code is accessing a nil
pointer. You will just have to debug the service while it is running to find out what it is accessing. If you cannot run it inside a debugger, then at least install a third-party exception logger framework, such as EurekaLog or MadExcept, to find out what your service was doing at the time of the AV.
You can build your HttpContent
using the combination of JObject
to avoid and JProperty
and then call ToString()
on it when building the StringContent
:
/*{
"agent": {
"name": "Agent Name",
"version": 1
},
"username": "Username",
"password": "User Password",
"token": "xxxxxx"
}*/
JObject payLoad = new JObject(
new JProperty("agent",
new JObject(
new JProperty("name", "Agent Name"),
new JProperty("version", 1)
),
new JProperty("username", "Username"),
new JProperty("password", "User Password"),
new JProperty("token", "xxxxxx")
)
);
using (HttpClient client = new HttpClient())
{
var httpContent = new StringContent(payLoad.ToString(), Encoding.UTF8, "application/json");
using (HttpResponseMessage response = await client.PostAsync(requestUri, httpContent))
{
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
return JObject.Parse(responseBody);
}
}
Did you try passwd -d root
? Most likely, this will do what you want.
You can also manually edit /etc/shadow
: (Create a backup copy. Be sure that you can log even if you mess up, for example from a rescue system.) Search for "root". Typically, the root entry looks similar to
root:$X$SK5xfLB1ZW:0:0...
There, delete the second field (everything between the first and second colon):
root::0:0...
Some systems will make you put an asterisk (*) in the password field instead of blank, where a blank field would allow no password (CentOS 8 for example)
root:*:0:0...
Save the file, and try logging in as root. It should skip the password prompt. (Like passwd -d
, this is a "no password" solution. If you are really looking for a "blank password", that is "ask for a password, but accept if the user just presses Enter", look at the manpage of mkpasswd
, and use mkpasswd
to create the second field for the /etc/shadow.)
Finding Object by reference without, strings, Note make sure the object you pass in is cloned , i use cloneDeep from lodash for that
if object looks like
const obj = {data: ['an Object',{person: {name: {first:'nick', last:'gray'} }]
path looks like
const objectPath = ['data',1,'person',name','last']
then call below method and it will return the sub object by path given
const child = findObjectByPath(obj, objectPath)
alert( child) // alerts "last"
const findObjectByPath = (objectIn: any, path: any[]) => {
let obj = objectIn
for (let i = 0; i <= path.length - 1; i++) {
const item = path[i]
// keep going up to the next parent
obj = obj[item] // this is by reference
}
return obj
}
Although Pascal's answer was detailed and informative it failed to mention some key information in the assumption that everyone knows how to use phpinfo()
For those that don't:
Navigate to your webservers root folder such as /var/www/
Within this folder create a text file called info.php
Edit the file and type phpinfo()
Navigate to the file such as: http://www.example.com/info.php
Here you will see the php.ini
path under Loaded Configuration File
:
Make sure you delete info.php
when you are done.
In order to resolve
Gem::Ext::BuildError: ERROR: Failed to build gem native extension error for mysql2,
I think libmysql-ruby got changed with ruby-mysql
Simply try with following commands,
sudo apt-get install ruby-mysql
& then
sudo apt-get install libmysqlclient-dev
Just remove all views of your layout Manager before notify. like:
myLayoutmanager.removeAllViews();
If you have a table with an IDENTITY column that you want to reset the next value for you can use the following command:
ALTER TABLE <table name>
ALTER COLUMN <column name>
RESTART WITH <new value to restart with>;
We can change the item by value, here is the trick:
radio1.ClearSelection();
radio1.Items.FindByValue("1").Selected = true;// 1 is the value of option2
The line starting ALREADYEXISTS
uses ’
as the closing quote, it should be using '
. The open quote on the next line (where the error is reported) is seen as the closing quote, and this mix up is causing the error.
From the title of this question I was expecting to find something like range()
, that would let me specify two dates and create a list with all the dates in between. That way one does not need to calculate the number of days between those two dates, if one does not know it beforehand.
So with the risk of being slightly off-topic, this one-liner does the job:
import datetime
start_date = datetime.date(2011, 01, 01)
end_date = datetime.date(2014, 01, 01)
dates_2011_2013 = [ start_date + datetime.timedelta(n) for n in range(int ((end_date - start_date).days))]
All credits to this answer!
How about something like this.
Test the live example: http://jsfiddle.net/6hBZU/1/
It assumes that the string will always end with the extension:
function openFile(file) {
var extension = file.substr( (file.lastIndexOf('.') +1) );
switch(extension) {
case 'jpg':
case 'png':
case 'gif':
alert('was jpg png gif'); // There's was a typo in the example where
break; // the alert ended with pdf instead of gif.
case 'zip':
case 'rar':
alert('was zip rar');
break;
case 'pdf':
alert('was pdf');
break;
default:
alert('who knows');
}
};
openFile("somestring.png");
EDIT: I mistakenly deleted part of the string in openFile("somestring.png");
. Corrected. Had it in the Live Example, though.
php_flag display_errors on
To turn the actual display of errors on.
To set the types of errors you are displaying, you will need to use:
php_value error_reporting <integer>
Combined with the integer values from this page: http://php.net/manual/en/errorfunc.constants.php
Note if you use -1 for your integer, it will show all errors, and be future proof when they add in new types of errors.
% notation is called a format specifier. For example, %d tells printf() to print an integer. %s to print a string (char *) etc. You should really look it up here: http://google.com/search?q=printf+format+specifiers
No, commas are not used for string concatenation. Commas are for separating arguments passed to a function.
Our HTML:
<div id="addnew">
<input type="text" id="id">
<input type="text" id="content">
<input type="button" value="Add" id="submit">
</div>
<div id="check">
<input type="text" id="input">
<input type="button" value="Search" id="search">
</div>
JS (writing to the txt file):
function writeToFile(d1, d2){
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fh = fso.OpenTextFile("data.txt", 8, false, 0);
fh.WriteLine(d1 + ',' + d2);
fh.Close();
}
var submit = document.getElementById("submit");
submit.onclick = function () {
var id = document.getElementById("id").value;
var content = document.getElementById("content").value;
writeToFile(id, content);
}
checking a particular row:
function readFile(){
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fh = fso.OpenTextFile("data.txt", 1, false, 0);
var lines = "";
while (!fh.AtEndOfStream) {
lines += fh.ReadLine() + "\r";
}
fh.Close();
return lines;
}
var search = document.getElementById("search");
search.onclick = function () {
var input = document.getElementById("input").value;
if (input != "") {
var text = readFile();
var lines = text.split("\r");
lines.pop();
var result;
for (var i = 0; i < lines.length; i++) {
if (lines[i].match(new RegExp(input))) {
result = "Found: " + lines[i].split(",")[1];
}
}
if (result) { alert(result); }
else { alert(input + " not found!"); }
}
}
Put these inside a .hta
file and run it. Tested on W7, IE11. It's working. Also if you want me to explain what's going on, say so.
The static
keyword in C is used in a compiled file (.c as opposed to .h) so that the function exists only in that file.
Normally, when you create a function, the compiler generates cruft the linker can use to, well, link a function call to that function. If you use the static keyword, other functions within the same file can call this function (because it can be done without resorting to the linker), while the linker has no information letting other files access the function.
db.collection_name.aggregate([
{ '$match' : { } },
{ '$sort' : { '_id' : -1 } },
{ '$facet' : {
metadata: [ { $count: "total" } ],
data: [ { $skip: 1 }, { $limit: 10 },{ '$project' : {"_id":0} } ] // add projection here wish you re-shape the docs
} }
] )
Instead of using two queries to find the total count and skip the matched record.
$facet is the best and optimized way.
If you only have one bean of type EmployeeService, and the interface EmployeeService does not have other implementations, you can simply put "@Service" before the EmployeeServiceImpl and "@Autowire" before the setter method. Otherwise, you should name the special bean like @Service("myspecial") and put "@autowire @Qualifier("myspecial") before the setter method.
use following LoadType method to use System.Reflection to load all registered(GAC) and referenced assemblies and check for typeName
public Type[] LoadType(string typeName)
{
return LoadType(typeName, true);
}
public Type[] LoadType(string typeName, bool referenced)
{
return LoadType(typeName, referenced, true);
}
private Type[] LoadType(string typeName, bool referenced, bool gac)
{
//check for problematic work
if (string.IsNullOrEmpty(typeName) || !referenced && !gac)
return new Type[] { };
Assembly currentAssembly = Assembly.GetExecutingAssembly();
List<string> assemblyFullnames = new List<string>();
List<Type> types = new List<Type>();
if (referenced)
{ //Check refrenced assemblies
foreach (AssemblyName assemblyName in currentAssembly.GetReferencedAssemblies())
{
//Load method resolve refrenced loaded assembly
Assembly assembly = Assembly.Load(assemblyName.FullName);
//Check if type is exists in assembly
var type = assembly.GetType(typeName, false, true);
if (type != null && !assemblyFullnames.Contains(assembly.FullName))
{
types.Add(type);
assemblyFullnames.Add(assembly.FullName);
}
}
}
if (gac)
{
//GAC files
string gacPath = Environment.GetFolderPath(System.Environment.SpecialFolder.Windows) + "\\assembly";
var files = GetGlobalAssemblyCacheFiles(gacPath);
foreach (string file in files)
{
try
{
//reflection only
Assembly assembly = Assembly.ReflectionOnlyLoadFrom(file);
//Check if type is exists in assembly
var type = assembly.GetType(typeName, false, true);
if (type != null && !assemblyFullnames.Contains(assembly.FullName))
{
types.Add(type);
assemblyFullnames.Add(assembly.FullName);
}
}
catch
{
//your custom handling
}
}
}
return types.ToArray();
}
public static string[] GetGlobalAssemblyCacheFiles(string path)
{
List<string> files = new List<string>();
DirectoryInfo di = new DirectoryInfo(path);
foreach (FileInfo fi in di.GetFiles("*.dll"))
{
files.Add(fi.FullName);
}
foreach (DirectoryInfo diChild in di.GetDirectories())
{
var files2 = GetGlobalAssemblyCacheFiles(diChild.FullName);
files.AddRange(files2);
}
return files.ToArray();
}
you really don't need quotes if let say use are using the image from your css file it can be
{background-image: url(your image.png/jpg etc);}
If you're using bash....
#!/bin/bash
pushd $(dirname "${0}") > /dev/null
basedir=$(pwd -L)
# Use "pwd -P" for the path without links. man bash for more info.
popd > /dev/null
echo "${basedir}"
From fragment to activty:
((YourActivityClassName)getActivity()).yourPublicMethod();
From activity to fragment:
FragmentManager fm = getSupportFragmentManager();
//if you added fragment via layout xml
YourFragmentClass fragment =
(YourFragmentClass)fm.findFragmentById(R.id.your_fragment_id);
fragment.yourPublicMethod();
If you added fragment via code and used a tag string when you added your fragment, use findFragmentByTag instead:
YourFragmentClass fragment = (YourFragmentClass)fm.findFragmentByTag("yourTag");
I couldn't find any other full solutions so I thought I would post mine. This may be a bit of a hack, but it resolved the issue to the above problem:
public void login(HttpServletRequest request, String userName, String password)
{
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(userName, password);
// Authenticate the user
Authentication authentication = authenticationManager.authenticate(authRequest);
SecurityContext securityContext = SecurityContextHolder.getContext();
securityContext.setAuthentication(authentication);
// Create a new session and add the security context.
HttpSession session = request.getSession(true);
session.setAttribute("SPRING_SECURITY_CONTEXT", securityContext);
}
Most of the time, you are not working in a MySQL client and you should batch inserts together using the appropriate API.
E.g. in JDBC:
connection con.setAutoCommit(false);
PreparedStatement prepStmt = con.prepareStatement("UPDATE DEPT SET MGRNO=? WHERE DEPTNO=?");
prepStmt.setString(1,mgrnum1);
prepStmt.setString(2,deptnum1);
prepStmt.addBatch();
prepStmt.setString(1,mgrnum2);
prepStmt.setString(2,deptnum2);
prepStmt.addBatch();
int [] numUpdates=prepStmt.executeBatch();
@@RowCount
will give you the number of records affected by a SQL Statement.
The @@RowCount
works only if you issue it immediately afterwards. So if you are trapping errors, you have to do it on the same line. If you split it up, you will miss out on whichever one you put second.
SELECT @NumRowsChanged = @@ROWCOUNT, @ErrorCode = @@ERROR
If you have multiple statements, you will have to capture the number of rows affected for each one and add them up.
SELECT @NumRowsChanged = @NumRowsChanged + @@ROWCOUNT, @ErrorCode = @@ERROR
The compatibility table given in the tensorflow site does not contain specific minor versions for cuda and cuDNN. However, if the specific versions are not met, there will be an error when you try to use tensorflow.
For tensorflow-gpu==1.12.0
and cuda==9.0
, the compatible cuDNN
version is 7.1.4
, which can be downloaded from here after registration.
You can check your cuda version using
nvcc --version
cuDNN version using
cat /usr/include/cudnn.h | grep CUDNN_MAJOR -A 2
tensorflow-gpu version using
pip freeze | grep tensorflow-gpu
UPDATE: Since tensorflow 2.0, has been released, I will share the compatible cuda and cuDNN versions for it as well (for Ubuntu 18.04).
tensorflow-gpu
= 2.0.0cuda
= 10.0cuDNN
= 7.6.0Best and easy way is just pass argument and create instance and call thread method
Call thread using create a thread object and send a runnable class object with parameter or without parameter and start method of thread object.
In my condition I am sending parameter and I will use in run method.
new Thread(new FCMThreadController("2", null, "3", "1")).start();
OR
new Thread(new FCMThreadController()).start();
public class FCMThreadController implements Runnable {
private String type;
private List<UserDeviceModel> devices;
private String message;
private String id;
public FCMThreadController(String type, List<UserDeviceModel> devices, String message, String id) {
this.type = type;
this.devices = devices;
this.message = message;
this.id = id;
}
public FCMThreadController( ) {
}
@Override
public void run() {
// TODO Auto-generated method stub
}
}
To answer the question literally (since GitHub is not in the question title), also be aware of this post over on superuser. EDIT: Answer copied here in relevant part, slightly modified for clarity in square brackets:
You're getting rejected because you're trying to delete the branch that your origin has currently "checked out".
If you have direct access to the repo, you can just open up a shell [in the bare repo] directory and use good old
git branch
to see what branch origin is currently on. To change it to another branch, you have to usegit symbolic-ref HEAD refs/heads/another-branch
.