cant say why, but the es5/6 syntax doesnt work
elem.onclick = (ev) => {console.log(this);}
not working
elem.onclick = function(ev) {console.log(this);}
working
The best and easiest way to clear a JLIST is:
myJlist.setListData(new String[0]);
Using Stream
in Java 8:
String[] both = Stream.concat(Arrays.stream(a), Arrays.stream(b))
.toArray(String[]::new);
Or like this, using flatMap
:
String[] both = Stream.of(a, b).flatMap(Stream::of)
.toArray(String[]::new);
To do this for a generic type you have to use reflection:
@SuppressWarnings("unchecked")
T[] both = Stream.concat(Arrays.stream(a), Arrays.stream(b)).toArray(
size -> (T[]) Array.newInstance(a.getClass().getComponentType(), size));
git add
adds your modified files to the queue to be committed later. Files are not committed
git commit
commits the files that have been added and creates a new revision with a log... If you do not add any files, git will not commit anything. You can combine both actions with git commit -a
git push
pushes your changes to the remote repository.
This figure from this git cheat sheet gives a good idea of the work flow
git add
isn't on the figure because the suggested way to commit is the combined git commit -a
, but you can mentally add a git add
to the change block to understand the flow.
Lastly, the reason why push
is a separate command is because of git
's philosophy. git
is a distributed versioning system, and your local working directory is your repository! All changes you commit are instantly reflected and recorded. push
is only used to update the remote repo (which you might share with others) when you're done with whatever it is that you're working on. This is a neat way to work and save changes locally (without network overhead) and update it only when you want to, instead of at every commit. This indirectly results in easier commits/branching etc (why not, right? what does it cost you?) which leads to more save points, without messing with the repository.
I'd say:
<a href="#"id="buttonOne">
<div id="linkedinB">
<img src="img/linkedinB.png" width="40" height="40">
</div>
</div>
However, it will still be a link. If you want to change your link into a button, you should rename the #buttonone to #buttonone a { your css here }.
var map:Map[String, String] = Map()
var map1 = map + ("red" -> "#FF0000")
println(map1)
That should work. Better if you pass a function to val
:
$('#replyBox').val(function(i, text) {
return text + quote;
});
This way you avoid searching the element and calling val
twice.
$(function () {_x000D_
$('#Add').click(function () {_x000D_
$('<p>Text</p>').appendTo('#Content');_x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div id="Content">_x000D_
<button id="Add">Add<button>_x000D_
</div>
_x000D_
You have to use new operator here to instantiate. For example:
Contacts.add(new Data(name, address, contact));
ALTER TABLE `stor` ADD `buy_price` INT(20) NOT NULL ;
Assuming you have an ArrayList
that contains characters, you could do this:
List<Character> list = new ArrayList<Character>();
list.addAll(Arrays.asList('+', '-', '*', '^'));
First add your item to mItems
and then use:
mAdapter.notifyItemInserted(mItems.size() - 1);
this method is better than using:
mAdapter.notifyDataSetChanged();
in performance.
IF NOT EXISTS (SELECT * FROM syscolumns
WHERE ID=OBJECT_ID('[db].[Employee]') AND NAME='EmpName')
ALTER TABLE [db].[Employee]
ADD [EmpName] VARCHAR(10)
GO
I Hope this would help. More info
Mathew's answer works for the terminal python shell, but it didn't work for IDLE shell in my case because many versions of python existed before I replaced them all with Python2.7.7. How I solved the problem with IDLE.
cd /Applications/Python\ 2.7/IDLE.app/Contents/Resources/
sudo nano idlemain.py
, enter password if required.os.chdir(os.path.expanduser('~/Documents'))
this line, I added sys.path.append("/Users/admin/Downloads....")
NOTE: replace contents of the quotes with the directory where python module to be addedvar jsonIssues = []; // new Array
jsonIssues.push( { ID:1, "Name":"whatever" } );
// "push" some more here
You can add days in different formats:
// Normal adding
moment().add(7, 'days');
// Short Hand
moment().add(7, 'd');
// Literal Object
moment().add({days:7, months:1});
See more about it on Moment.js docs: https://momentjs.com/docs/#/manipulating/add/
DateTime is immutable. That means you cannot change it's state and have to assign the result of an operation to a variable.
endDate = endDate.AddDays(addedDays);
Animuson gives a decent way to do it, but no help on understanding it. I kept looking and came across a forum thread with this commands:
Echo Off
IF Not EXIST n:\dbfs\doekasp.txt GOTO DoNothing
copy n:\dbfs\doekasp.txt n:\history\doekasp.txt
Rem rename command is done twice (2) to allow for 1 or 2 digit hour,
Rem If before 10am (1digit) hour Rename starting at location (0) for (2) chars,
Rem will error out, as location (0) will have a space
Rem and space is invalid character for file name,
Rem so second remame will be used.
Rem
Rem if equal 10am or later (2 digit hour) then first remame will work and second will not
Rem as doekasp.txt will not be found (remamed)
ren n:\history\doekasp.txt doekasp-%date:~4,2%-%date:~7,2%-%date:~10,4%_@_%time:~0,2%h%time:~3,2%m%time:~6,2%s%.txt
ren n:\history\doekasp.txt doekasp-%date:~4,2%-%date:~7,2%-%date:~10,4%_@_%time:~1,1%h%time:~3,2%m%time:~6,2%s%.txt
I always name year first YYYYMMDD, but wanted to add time. Here you will see that he has given a reason why 0,2 will not work and 1,1 will, because (space) is an invalid character. This opened my eyes to the issue. Also, by default you're in 24hr mode.
I ended up with:
ren Logs.txt Logs-%date:~10,4%%date:~7,2%%date:~4,2%_%time:~0,2%%time:~3,2%.txt
ren Logs.txt Logs-%date:~10,4%%date:~7,2%%date:~4,2%_%time:~1,1%%time:~3,2%.txt
Output:
Logs-20121707_1019
You will first need to create a custom layout xml which will represent a single item in your list. You will add your two buttons to this layout along with any other items you want to display from your list.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/list_item_string"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:paddingLeft="8dp"
android:textSize="18sp"
android:textStyle="bold" />
<Button
android:id="@+id/delete_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="5dp"
android:text="Delete" />
<Button
android:id="@+id/add_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="@id/delete_btn"
android:layout_centerVertical="true"
android:layout_marginRight="10dp"
android:text="Add" />
</RelativeLayout>
Next you will need to create a Custom ArrayAdapter Class which you will use to inflate your xml layout, as well as handle your buttons and on click events.
public class MyCustomAdapter extends BaseAdapter implements ListAdapter {
private ArrayList<String> list = new ArrayList<String>();
private Context context;
public MyCustomAdapter(ArrayList<String> list, Context context) {
this.list = list;
this.context = context;
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int pos) {
return list.get(pos);
}
@Override
public long getItemId(int pos) {
return list.get(pos).getId();
//just return 0 if your list items do not have an Id variable.
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.my_custom_list_layout, null);
}
//Handle TextView and display string from your list
TextView listItemText = (TextView)view.findViewById(R.id.list_item_string);
listItemText.setText(list.get(position));
//Handle buttons and add onClickListeners
Button deleteBtn = (Button)view.findViewById(R.id.delete_btn);
Button addBtn = (Button)view.findViewById(R.id.add_btn);
deleteBtn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
//do something
list.remove(position); //or some other task
notifyDataSetChanged();
}
});
addBtn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
//do something
notifyDataSetChanged();
}
});
return view;
}
}
Finally, in your activity you can instantiate your custom ArrayAdapter class and set it to your listview.
public class MyActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_activity);
//generate list
ArrayList<String> list = new ArrayList<String>();
list.add("item1");
list.add("item2");
//instantiate custom adapter
MyCustomAdapter adapter = new MyCustomAdapter(list, this);
//handle listview and assign adapter
ListView lView = (ListView)findViewById(R.id.my_listview);
lView.setAdapter(adapter);
}
Hope this helps!
Import datetime and timedelta:
>>> from datetime import datetime, timedelta
>>> str(datetime.now() + timedelta(hours=9))[11:19]
'01:41:44'
But the better way is:
>>> (datetime.now() + timedelta(hours=9)).strftime('%H:%M:%S')
'01:42:05'
You can refer strptime
and strftime
behavior to better understand how python processes dates and time field
Yes, it is possible since lists are mutable.
Look at the built-in enumerate()
function to get an idea how to iterate over the list and find each entry's index (which you can then use to assign to the specific list item).
In addition to the other answers, note that a multidimensional array is allocated as one big chunky object on the heap. This has some implications:
<gcAllowVeryLargeObjects>
for multidimensional arrays way before the issue will ever come up if you only ever use jagged arrays.private void textBox1_TextChanged(object sender, EventArgs e)
{
try
{
textBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
AutoCompleteStringCollection col = new AutoCompleteStringCollection();
con.Open();
sql = "select *from Table_Name;
cmd = new SqlCommand(sql, con);
SqlDataReader sdr = null;
sdr = cmd.ExecuteReader();
while (sdr.Read())
{
col.Add(sdr["Column_Name"].ToString());
}
sdr.Close();
textBox1.AutoCompleteCustomSource = col;
con.Close();
}
catch
{
}
}
Delete 'Web.Debug.config' and 'Web.Release.config' file for your solution directory,it should remove all errors
You can find the number of members in a Javascript array by using its length
property:
var number = $scope.names.length;
Docs - Array.prototype.length
Here's a set of properties i made that feel more intuitive to use than the built in stuff. The conditions are based off of the truth table supplied above by ahmd0.
<!-- truth table for installer varables (install vs uninstall vs repair vs upgrade) https://stackoverflow.com/a/17608049/1721136 -->
<SetProperty Id="_INSTALL" After="FindRelatedProducts" Value="1"><![CDATA[Installed="" AND PREVIOUSVERSIONSINSTALLED=""]]></SetProperty>
<SetProperty Id="_UNINSTALL" After="FindRelatedProducts" Value="1"><![CDATA[PREVIOUSVERSIONSINSTALLED="" AND REMOVE="ALL"]]></SetProperty>
<SetProperty Id="_CHANGE" After="FindRelatedProducts" Value="1"><![CDATA[Installed<>"" AND REINSTALL="" AND PREVIOUSVERSIONSINSTALLED<>"" AND REMOVE=""]]></SetProperty>
<SetProperty Id="_REPAIR" After="FindRelatedProducts" Value="1"><![CDATA[REINSTALL<>""]]></SetProperty>
<SetProperty Id="_UPGRADE" After="FindRelatedProducts" Value="1"><![CDATA[PREVIOUSVERSIONSINSTALLED<>"" ]]></SetProperty>
Here's some sample usage:
<Custom Action="CaptureExistingLocalSettingsValues" After="InstallInitialize">NOT _UNINSTALL</Custom>
<Custom Action="GetConfigXmlToPersistFromCmdLineArgs" After="InstallInitialize">_INSTALL OR _UPGRADE</Custom>
<Custom Action="ForgetProperties" Before="InstallFinalize">_UNINSTALL OR _UPGRADE</Custom>
<Custom Action="SetInstallCustomConfigSettingsArgs" Before="InstallCustomConfigSettings">NOT _UNINSTALL</Custom>
<Custom Action="InstallCustomConfigSettings" Before="InstallFinalize">NOT _UNINSTALL</Custom>
Issues:
from datetime import datetime, timedelta
nine_hours_from_now = datetime.now() + timedelta(hours=9)
#datetime.datetime(2012, 12, 3, 23, 24, 31, 774118)
And then use string formatting to get the relevant pieces:
>>> '{:%H:%M:%S}'.format(nine_hours_from_now)
'23:24:31'
If you're only formatting the datetime then you can use:
>>> format(nine_hours_from_now, '%H:%M:%S')
'23:24:31'
Or, as @eumiro has pointed out in comments - strftime
I would try
Sheets("Sheet1").Activate
Set Ticker = Range(Cells(2, 1), Cells(65, 1))
Ticker.Copy
Worksheets("Sheet2").Range("A1").Offset(0,0).Cells.Select
Worksheets("Sheet2").paste
Is something like this what you want to do?
$return_arr = array();
$fetch = mysql_query("SELECT * FROM table");
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
$row_array['id'] = $row['id'];
$row_array['col1'] = $row['col1'];
$row_array['col2'] = $row['col2'];
array_push($return_arr,$row_array);
}
echo json_encode($return_arr);
It returns a json string in this format:
[{"id":"1","col1":"col1_value","col2":"col2_value"},{"id":"2","col1":"col1_value","col2":"col2_value"}]
OR something like this:
$year = date('Y');
$month = date('m');
$json_array = array(
//Each array below must be pulled from database
//1st record
array(
'id' => 111,
'title' => "Event1",
'start' => "$year-$month-10",
'url' => "http://yahoo.com/"
),
//2nd record
array(
'id' => 222,
'title' => "Event2",
'start' => "$year-$month-20",
'end' => "$year-$month-22",
'url' => "http://yahoo.com/"
)
);
echo json_encode($json_array);
You need to use the string concatenation operator +
String both = name + "-" + dest;
A corresponding cross for ✓ ✓
would be ✗ ✗
I think (Dingbats).
USE A TOOLBAR
You can set a custom toolbar item color dynamically by creating a custom toolbar class:
package view;
import android.app.Activity;
import android.content.Context;
import android.graphics.ColorFilter;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.support.v7.internal.view.menu.ActionMenuItemView;
import android.support.v7.widget.ActionMenuView;
import android.support.v7.widget.Toolbar;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomToolbar extends Toolbar{
public CustomToolbar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
// TODO Auto-generated constructor stub
}
public CustomToolbar(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public CustomToolbar(Context context) {
super(context);
// TODO Auto-generated constructor stub
ctxt = context;
}
int itemColor;
Context ctxt;
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
Log.d("LL", "onLayout");
super.onLayout(changed, l, t, r, b);
colorizeToolbar(this, itemColor, (Activity) ctxt);
}
public void setItemColor(int color){
itemColor = color;
colorizeToolbar(this, itemColor, (Activity) ctxt);
}
/**
* Use this method to colorize toolbar icons to the desired target color
* @param toolbarView toolbar view being colored
* @param toolbarIconsColor the target color of toolbar icons
* @param activity reference to activity needed to register observers
*/
public static void colorizeToolbar(Toolbar toolbarView, int toolbarIconsColor, Activity activity) {
final PorterDuffColorFilter colorFilter
= new PorterDuffColorFilter(toolbarIconsColor, PorterDuff.Mode.SRC_IN);
for(int i = 0; i < toolbarView.getChildCount(); i++) {
final View v = toolbarView.getChildAt(i);
doColorizing(v, colorFilter, toolbarIconsColor);
}
//Step 3: Changing the color of title and subtitle.
toolbarView.setTitleTextColor(toolbarIconsColor);
toolbarView.setSubtitleTextColor(toolbarIconsColor);
}
public static void doColorizing(View v, final ColorFilter colorFilter, int toolbarIconsColor){
if(v instanceof ImageButton) {
((ImageButton)v).getDrawable().setAlpha(255);
((ImageButton)v).getDrawable().setColorFilter(colorFilter);
}
if(v instanceof ImageView) {
((ImageView)v).getDrawable().setAlpha(255);
((ImageView)v).getDrawable().setColorFilter(colorFilter);
}
if(v instanceof AutoCompleteTextView) {
((AutoCompleteTextView)v).setTextColor(toolbarIconsColor);
}
if(v instanceof TextView) {
((TextView)v).setTextColor(toolbarIconsColor);
}
if(v instanceof EditText) {
((EditText)v).setTextColor(toolbarIconsColor);
}
if (v instanceof ViewGroup){
for (int lli =0; lli< ((ViewGroup)v).getChildCount(); lli ++){
doColorizing(((ViewGroup)v).getChildAt(lli), colorFilter, toolbarIconsColor);
}
}
if(v instanceof ActionMenuView) {
for(int j = 0; j < ((ActionMenuView)v).getChildCount(); j++) {
//Step 2: Changing the color of any ActionMenuViews - icons that
//are not back button, nor text, nor overflow menu icon.
final View innerView = ((ActionMenuView)v).getChildAt(j);
if(innerView instanceof ActionMenuItemView) {
int drawablesCount = ((ActionMenuItemView)innerView).getCompoundDrawables().length;
for(int k = 0; k < drawablesCount; k++) {
if(((ActionMenuItemView)innerView).getCompoundDrawables()[k] != null) {
final int finalK = k;
//Important to set the color filter in seperate thread,
//by adding it to the message queue
//Won't work otherwise.
//Works fine for my case but needs more testing
((ActionMenuItemView) innerView).getCompoundDrawables()[finalK].setColorFilter(colorFilter);
// innerView.post(new Runnable() {
// @Override
// public void run() {
// ((ActionMenuItemView) innerView).getCompoundDrawables()[finalK].setColorFilter(colorFilter);
// }
// });
}
}
}
}
}
}
}
then refer to it in your layout file. Now you can set a custom color using
toolbar.setItemColor(Color.Red);
Sources:
I found the information to do this here: How to dynamicaly change Android Toolbar icons color
and then I edited it, improved upon it, and posted it here: GitHub:AndroidDynamicToolbarItemColor
ng set --global defaults.styleExt=scss
is deprecated since ng6. You will get this message:
get/set have been deprecated in favor of the config command
You should use:
ng config schematics.@schematics/angular:component '{ styleext: "scss"}'
If you want to target a specific project (replace {project} with your project's name):
ng config projects.{project}.schematics.@schematics/angular:component '{ styleext: "scss"}'
You could do the following:
Of course this isn't actually live.
What would be more sensible is that you could generate preview images for certain URLs e.g. every day or every week and use them. I image that you don't want to do this manually and you don't want to show the users of your service a preview that looks completely different than what the site currently looks like.
Ok, so the answer was derived from some other posts about this problem and it is:
If your ViewData
contains a SelectList
with the same name as your DropDownList
i.e. "submarket_0", the Html helper will automatically populate your DropDownList
with that data if you don't specify the 2nd parameter which in this case is the source SelectList.
What happened with my error was:
Because the table containing the drop down lists was in a partial view and the ViewData
had been changed and no longer contained the SelectList
I had referenced, the HtmlHelper
(instead of throwing an error) tried to find the SelectList called "submarket_0" in the ViewData (GRRRR!!!) which it STILL couldnt find, and then threw an error on that :)
Please correct me if im wrong
I had some columns that had multiple default constraints created, so I create the following stored procedure:
CREATE PROCEDURE [dbo].[RemoveDefaultConstraints] @table_name nvarchar(256), @column_name nvarchar(256)
AS
BEGIN
DECLARE @ObjectName NVARCHAR(100)
START: --Start of loop
SELECT
@ObjectName = OBJECT_NAME([default_object_id])
FROM
SYS.COLUMNS
WHERE
[object_id] = OBJECT_ID(@table_name)
AND [name] = @column_name;
-- Don't drop the constraint unless it exists
IF @ObjectName IS NOT NULL
BEGIN
EXEC ('ALTER TABLE '+@table_name+' DROP CONSTRAINT ' + @ObjectName)
GOTO START; --Used to loop in case of multiple default constraints
END
END
GO
-- How to run the stored proc. This removes the default constraint(s) for the enabled column on the User table.
EXEC [dbo].[RemoveDefaultConstraints] N'[dbo].[User]', N'enabled'
GO
-- If you hate the proc, just get rid of it
DROP PROCEDURE [dbo].[RemoveDefaultConstraints]
GO
You should not include commands.c in your header file. In general, you should not include .c files. Rather, commands.c should include commands.h. As defined here, the C preprocessor is inserting the contents of commands.c into commands.h where the include is. You end up with two definitions of f123 in commands.h.
commands.h
#ifndef COMMANDS_H_
#define COMMANDS_H_
void f123();
#endif
commands.c
#include "commands.h"
void f123()
{
/* code */
}
Adding to the mix: the OI File Manager has a public api registered at openintents.org
http://www.openintents.org/filemanager
http://www.openintents.org/action/org-openintents-action-pick-file/
I know this is late answer but I have to make a comment about most voted answer that says to use generate scripts option in SSMS.
Problem with that is this option doesn’t necessarily generate script in correct execution order because it doesn't take dependencies into account.
For small databases this is not an issue but for larger ones it certainly is because it requires to manually re-order that script. Try that on 500 object database ;)
Unfortunately in this case the only solution are third party tools.
I successfully used comparison tools from ApexSQL (Diff and Data Diff) for similar tasks but you can’t go wrong with any other already mentioned here, especially Red Gate.
Sorry EMS, but I actually just got another response from the matplotlib mailling list (Thanks goes out to Benjamin Root).
The code I am looking for is adjusting the savefig call to:
fig.savefig('samplefigure', bbox_extra_artists=(lgd,), bbox_inches='tight')
#Note that the bbox_extra_artists must be an iterable
This is apparently similar to calling tight_layout, but instead you allow savefig to consider extra artists in the calculation. This did in fact resize the figure box as desired.
import matplotlib.pyplot as plt
import numpy as np
plt.gcf().clear()
x = np.arange(-2*np.pi, 2*np.pi, 0.1)
fig = plt.figure(1)
ax = fig.add_subplot(111)
ax.plot(x, np.sin(x), label='Sine')
ax.plot(x, np.cos(x), label='Cosine')
ax.plot(x, np.arctan(x), label='Inverse tan')
handles, labels = ax.get_legend_handles_labels()
lgd = ax.legend(handles, labels, loc='upper center', bbox_to_anchor=(0.5,-0.1))
text = ax.text(-0.2,1.05, "Aribitrary text", transform=ax.transAxes)
ax.set_title("Trigonometry")
ax.grid('on')
fig.savefig('samplefigure', bbox_extra_artists=(lgd,text), bbox_inches='tight')
This produces:
[edit] The intent of this question was to completely avoid the use of arbitrary coordinate placements of arbitrary text as was the traditional solution to these problems. Despite this, numerous edits recently have insisted on putting these in, often in ways that led to the code raising an error. I have now fixed the issues and tidied the arbitrary text to show how these are also considered within the bbox_extra_artists algorithm.
I have written detailed tutorial covering current location here on demonuts.com.You can find more description here and also you can download whole demo source code for better understanding.
There are already many answers there but I want to show latest way to get location using Google API, so new programmers can use new method:
First of all, put this in gradle file
compile 'com.google.android.gms:play-services:8.4.0'
then implement necessary interfaces
public class MainActivity extends BaseActivitiy implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener
declare instances
private GoogleApiClient mGoogleApiClient;
private Location mLocation;
private LocationManager locationManager;
private LocationRequest mLocationRequest;
put this in onCreate()
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
At last, override necessary methods
@Override
public void onConnected(Bundle bundle) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(mLocation == null){
startLocationUpdates();
}
if (mLocation != null) {
double latitude = mLocation.getLatitude();
double longitude = mLocation.getLongitude();
} else {
// Toast.makeText(this, "Location not Detected", Toast.LENGTH_SHORT).show();
}
}
protected void startLocationUpdates() {
// Create the location request
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(UPDATE_INTERVAL)
.setFastestInterval(FASTEST_INTERVAL);
// Request location updates
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
mLocationRequest, this);
Log.d("reque", "--->>>>");
}
@Override
public void onConnectionSuspended(int i) {
Log.i(TAG, "Connection Suspended");
mGoogleApiClient.connect();
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.i(TAG, "Connection failed. Error: " + connectionResult.getErrorCode());
}
@Override
public void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
@Override
public void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
@Override
public void onLocationChanged(Location location) {
}
Don't forget to start GPS in your device before running app.
Just a guess, but I think with the SYSTEM_ALERT_WINDOW permission (displayed as "Draw over other apps", see here) it could be possible: display your app as a fullscreen, system alert type window. This way it will hide any other apps, even the homescreen so if you press Home, it won't really be disabled, just without any visible effect.
MX Player has this permission declared, and Facebook Messenger has it too for displaying "chat heads" over anything - so it might be the solution.
Update (added from my comments): Next, use SYSTEM_UI_FLAG_HIDE_NAVIGATION in conjunction with capturing touch events/using OnSystemUiVisibilityChangeListener to override the default behaviour (navbar appearing on touch). Also, since you said exit immersive gesture does not work, you could try setting SYSTEM_UI_FLAG_IMMERSIVE_STICKY too (with SYSTEM_UI_FLAG_FULLSCREEN and SYSTEM_UI_FLAG_HIDE_NAVIGATION).
The accepted answer is correct in all means and I stumbled upon this thread after I couldn't get the Google Map render in one of my app components.
Now, if you are on a recent angular version i.e. 7+ of angular then you will have to deal with the following ViewChild declaration i.e.
@ViewChild(selector: string | Function | Type<any>, opts: {
read?: any;
static: boolean;
})
Now, the interesting part is the static value, which by definition says
Now for rendering a map, I used the following ,
@ViewChild('map', { static: true }) mapElement: any;
map: google.maps.Map;
$(window).bind("load", function() {
// write your code here
});
pids=$(pgrep <name>)
will get you the pids of all processes with the given name. To kill them all, use
kill -9 $pids
To refrain from using a variable and directly kill all processes with a given name issue
pkill -9 <name>
"Obliberating" contents from a svn repository, i.e. wiping this contents from the disc, can be done as described in this article http://www.limilabs.com/blog/how-to-permanently-remove-svn-folder
It requires access to the server side svn repository, thus you must have some admin privileges.
It works by (a) dumping the repository content into a file, (b) excluding some contents and (c) wiping and re-creating the plain repository again and eventually by (d) loading the filtered repository contents:
svnadmin dump "path/to/svnrepo" > svnrepo.txt // (a)
svndumpfilter exclude "my/folder" < svnrepo.txt > filtered.txt // (b)
rm -rf "path/to/svnrepo" && svnadmin create "path/to/svnrepo" // (c)
svnadmin load "path/to/svnrepo" < filtered.txt // (d)
The repository counter is unchanged by this operations. However, your repository is now "missing" all those revision numbers used to create that contents you removed in step (b).
Subversion 1.7.5 appears to handle this "missing" revisions pretty well. Using "svn ls -r $missing" for example, reports the very same as "svn ls -r $(( missing - 1))".
Contrary to this, my (pretty old) VIEWVC reports "no contents" when querying a "missing" revision.
Thanks for the above script. One little modification to add in the file ending correctly. Try this ...
$filenameFormat = "MyFileName" + " " + (Get-Date -Format "yyyy-MM-dd") **+ ".txt"**
Rename-Item -Path "C:\temp\MyFileName.txt" -NewName $filenameFormat
For me, upgrading eslint-plugin-react to the latest version 7.21.5 fixed this
I found that I had to use .setAttribute('crossOrigin', '')
and had to append a timestamp to the URL's query string to avoid a 304 response lacking the Access-Control-Allow-Origin
header.
This gives me
var url = 'http://lorempixel.com/g/400/200/';
var imgObj = new Image();
imgObj.src = url + '?' + new Date().getTime();
imgObj.setAttribute('crossOrigin', '');
I didn't see the link here, but there's a beta .NET Connector for MySql. Click "Development Releases" to download 6.3.2 beta, which has EF4/VS2010 integration:
http://dev.mysql.com/downloads/connector/net/5.0.html#downloads
overflow-x: scroll;
overflow-y: hidden;
EDIT:
It works for me:
<div style='overflow-x:scroll;overflow-y:hidden;width:250px;height:200px'>
<div style='width:400px;height:250px'></div>
</div>
CSS min() and max() have fairly good usage rates in 2020.
The code below uses max() to get the largest of the [variablevalue] and [minimumvalue] and then passes that through to min() against the [maximumvalue] to get the smaller of the two. This creates an allowable font range (3.5rem is minimum, 6.5rem is maximum, 6vw is used only when in between).
font-size: min(max([variablevalue], [minimumvalue]), [maximumvalue]);
font-size: min(max(6vw, 3.5rem), 6.5rem);
I'm using this specifically with font-awesome as a video-play icon over an image within a bootstrap container element where max-width is set.
This works:
myWindow = window.open('http://www.yahoo.com','myWindow', "width=200, height=200");
I had the same problem. Adding include path does work for all except std::string.
I noticed in the mingw-Toolchain many system header files *.tcc
I added filetype *.tcc as "C++ Header File" in Preferences > C/C++/ File Types. Now std::string can be resolved from the internal index and Code Analyzer. Perhaps this is added to Eclipse CDT by default in feature.
I hope this helps to someone...
PS: I'm using Eclipse Mars, mingw gcc 4.8.1, Own Makefile, no Eclipse Makefilebuilder.
SQLite doesn't define any particular extension for this, it's your own choice. Personally, I name them with the .sqlite
extension, just so there isn't any ambiguity when I'm looking at my files later.
I have tried all the above answers but still the same error was throwing up. Later I found this in WAMP Forum and finally my WAMP works !!!
If you are using WampServer 2.5 on a 64bit Windows You will need both the 32bit and 64bit versions of this runtime.
Microsoft Visual C++ 2012 (www.microsoft.com)
Press the Download button and on the following screen select VSU_4\vcredist_x86.exe Press the Download button and on the following screen select VSU_4\vcredist_x64.exe
What is happening here is that database route does not accept any url methods.
I would try putting the url methods in the app route just like you have in the entry_page function:
@app.route('/entry', methods=['GET', 'POST'])
def entry_page():
if request.method == 'POST':
date = request.form['date']
title = request.form['blog_title']
post = request.form['blog_main']
post_entry = models.BlogPost(date = date, title = title, post = post)
db.session.add(post_entry)
db.session.commit()
return redirect(url_for('database'))
else:
return render_template('entry.html')
@app.route('/database', methods=['GET', 'POST'])
def database():
query = []
for i in session.query(models.BlogPost):
query.append((i.title, i.post, i.date))
return render_template('database.html', query = query)
Or, once it's already in SSIS, you could create a derived column (as part of some data flow task) with:
(DT_I8)FLOOR((DT_R8)systemDateTime)
But you'd have to test to doublecheck.
Since Google seems to like this answer...
If you're looking to match Bootstrap 4's naming convention, i.e. offset-*-#, here's that modification:
.offset-right-12 {
margin-right: 100%;
}
.offset-right-11 {
margin-right: 91.66666667%;
}
.offset-right-10 {
margin-right: 83.33333333%;
}
.offset-right-9 {
margin-right: 75%;
}
.offset-right-8 {
margin-right: 66.66666667%;
}
.offset-right-7 {
margin-right: 58.33333333%;
}
.offset-right-6 {
margin-right: 50%;
}
.offset-right-5 {
margin-right: 41.66666667%;
}
.offset-right-4 {
margin-right: 33.33333333%;
}
.offset-right-3 {
margin-right: 25%;
}
.offset-right-2 {
margin-right: 16.66666667%;
}
.offset-right-1 {
margin-right: 8.33333333%;
}
.offset-right-0 {
margin-right: 0;
}
@media (min-width: 576px) {
.offset-sm-right-12 {
margin-right: 100%;
}
.offset-sm-right-11 {
margin-right: 91.66666667%;
}
.offset-sm-right-10 {
margin-right: 83.33333333%;
}
.offset-sm-right-9 {
margin-right: 75%;
}
.offset-sm-right-8 {
margin-right: 66.66666667%;
}
.offset-sm-right-7 {
margin-right: 58.33333333%;
}
.offset-sm-right-6 {
margin-right: 50%;
}
.offset-sm-right-5 {
margin-right: 41.66666667%;
}
.offset-sm-right-4 {
margin-right: 33.33333333%;
}
.offset-sm-right-3 {
margin-right: 25%;
}
.offset-sm-right-2 {
margin-right: 16.66666667%;
}
.offset-sm-right-1 {
margin-right: 8.33333333%;
}
.offset-sm-right-0 {
margin-right: 0;
}
}
@media (min-width: 768px) {
.offset-md-right-12 {
margin-right: 100%;
}
.offset-md-right-11 {
margin-right: 91.66666667%;
}
.offset-md-right-10 {
margin-right: 83.33333333%;
}
.offset-md-right-9 {
margin-right: 75%;
}
.offset-md-right-8 {
margin-right: 66.66666667%;
}
.offset-md-right-7 {
margin-right: 58.33333333%;
}
.offset-md-right-6 {
margin-right: 50%;
}
.offset-md-right-5 {
margin-right: 41.66666667%;
}
.offset-md-right-4 {
margin-right: 33.33333333%;
}
.offset-md-right-3 {
margin-right: 25%;
}
.offset-md-right-2 {
margin-right: 16.66666667%;
}
.offset-md-right-1 {
margin-right: 8.33333333%;
}
.offset-md-right-0 {
margin-right: 0;
}
}
@media (min-width: 992px) {
.offset-lg-right-12 {
margin-right: 100%;
}
.offset-lg-right-11 {
margin-right: 91.66666667%;
}
.offset-lg-right-10 {
margin-right: 83.33333333%;
}
.offset-lg-right-9 {
margin-right: 75%;
}
.offset-lg-right-8 {
margin-right: 66.66666667%;
}
.offset-lg-right-7 {
margin-right: 58.33333333%;
}
.offset-lg-right-6 {
margin-right: 50%;
}
.offset-lg-right-5 {
margin-right: 41.66666667%;
}
.offset-lg-right-4 {
margin-right: 33.33333333%;
}
.offset-lg-right-3 {
margin-right: 25%;
}
.offset-lg-right-2 {
margin-right: 16.66666667%;
}
.offset-lg-right-1 {
margin-right: 8.33333333%;
}
.offset-lg-right-0 {
margin-right: 0;
}
}
@media (min-width: 1200px) {
.offset-xl-right-12 {
margin-right: 100%;
}
.offset-xl-right-11 {
margin-right: 91.66666667%;
}
.offset-xl-right-10 {
margin-right: 83.33333333%;
}
.offset-xl-right-9 {
margin-right: 75%;
}
.offset-xl-right-8 {
margin-right: 66.66666667%;
}
.offset-xl-right-7 {
margin-right: 58.33333333%;
}
.offset-xl-right-6 {
margin-right: 50%;
}
.offset-xl-right-5 {
margin-right: 41.66666667%;
}
.offset-xl-right-4 {
margin-right: 33.33333333%;
}
.offset-xl-right-3 {
margin-right: 25%;
}
.offset-xl-right-2 {
margin-right: 16.66666667%;
}
.offset-xl-right-1 {
margin-right: 8.33333333%;
}
.offset-xl-right-0 {
margin-right: 0;
}
}
Here's a solution using Java 11's Files.readString
:
public class Utils {
public static String readResource(String name) throws URISyntaxException, IOException {
var uri = Utils.class.getResource("/" + name).toURI();
var path = Paths.get(uri);
return Files.readString(path);
}
}
So I created an account just so I could help fix this problem that is plaguing a lot of people and where the fixes above aren't working.
If you get this error and nothing here helps. Try clicking the "Resume program play button" until the program finishes past the error. Then click in the console tab next to debug and read the red text.
I was getting that source code error even though my issue was trying to insert a value into a null Array. Step 1 Click the resume button
In case anyone wants to have a responsive flexbox with percentages (%) it is much easier for media queries.
flex-basis: 25%;
This will be a lot smoother when testing.
// VARIABLES
$screen-xs: 480px;
$screen-sm: 768px;
$screen-md: 992px;
$screen-lg: 1200px;
$screen-xl: 1400px;
$screen-xxl: 1600px;
// QUERIES
@media screen (max-width: $screen-lg) {
flex-basis: 25%;
}
@media screen (max-width: $screen-md) {
flex-basis: 33.33%;
}
ECMAScript5 provides a map
method for Array
s, applying a function to all elements of an array.
Here is an example:
var a = ['1','2','3']
var result = a.map(function (x) {
return parseInt(x, 10);
});
console.log(result);
_x000D_
Although Adrien's answer is correct, you can do this all in single line. No need for extra function or mess.
It works I checked it in ASP.NET Core 1.0
var user = await _userManager.GetUserAsync(HttpContext.User);
then you can get other properties of the variable like user.Email
. I hope this helps someone.
@RequestMapping(value="/") public String home(HttpServletRequest request){
System.out.println("My Attribute :: "+request.getAttribute("YourAttributeName"));
return "home";
}
Microsoft explains it in the KB305703 article on How to start the default Internet browser programmatically by using Visual C#.
Don't forget to check the Troubleshooting section.
For my style, I always use @ModelAttribute to catch object from spring form jsp. for example, I design form on jsp page, that form exist with commandName
<form:form commandName="Book" action="" methon="post">
<form:input type="text" path="title"></form:input>
</form:form>
and I catch the object on controller with follow code
public String controllerPost(@ModelAttribute("Book") Book book)
and every field name of book must be match with path in sub-element of form
Remember that your img is not really a DOM element but a javascript expression.
This is a JSX attribute expression. Put curly braces around the src string expression and it will work. See http://facebook.github.io/react/docs/jsx-in-depth.html#attribute-expressions
In javascript, the class attribute is reference using className. See the note in this section: http://facebook.github.io/react/docs/jsx-in-depth.html#react-composite-components
/** @jsx React.DOM */
var Hello = React.createClass({
render: function() {
return <div><img src={'http://placehold.it/400x20&text=slide1'} alt="boohoo" className="img-responsive"/><span>Hello {this.props.name}</span></div>;
}
});
React.renderComponent(<Hello name="World" />, document.body);
I try many things and finally found that the last parameter must be false and you must add <SCRIPT>
tag to the java script :
string script = "< SCRIPT >alert('hello!');< /SCRIPT>";
ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), key, script, **false**);
I think your date data should look like 2013-08-14.
<?php
$yrdata= strtotime('2013-08-14');
echo date('M-Y', $yrdata);
?>
// Output is Aug-2013
def jsonFile = new File('File Path');
JsonSlurper jsonSlurper = new JsonSlurper();
def parseJson = jsonSlurper.parse(jsonFile)
String json = JsonOutput.toJson(parseJson)
def prettyJson = JsonOutput.prettyPrint(json)
println(prettyJson)
In this table you can see the difference between each model:
See http://www.1keydata.com/datawarehousing/data-modeling-levels.html for more information and some data model examples.
I know its an old question, but in terms of listing untracked files I thought I would add another one which also lists untracked folders:
You can used the git clean operation with -n (dry run) to show you which files it will remove (including the .gitignore files) by:
git clean -xdn
This has the advantage of showing all files and all folders that are not tracked. Parameters:
x
- Shows all untracked files (including ignored by git and others, like build output etc...)d
- show untracked directoriesn
- and most importantly! - dryrun, i.e. don't actually delete anything, just use the clean mechanism to display the results.It can be a little bit unsafe to do it like this incase you forget the -n
. So I usually alias it in git config.
DSO here means Dynamic Shared Object; since the error message says it's missing from the command line, I guess you have to add it to the command line.
That is, try adding -lpthread
to your command line.
Another approach I found is to set a delegate for the NavigationController
:
navigationController.delegate = self;
and use setNavigationBarHidden
in navigationController:willShowViewController:animated:
- (void)navigationController:(UINavigationController *)navigationController
willShowViewController:(UIViewController *)viewController
animated:(BOOL)animated
{
// Hide the nav bar if going home.
BOOL hide = viewController != homeViewController;
[navigationController setNavigationBarHidden:hide animated:animated];
}
Easy way to customize the behavior for each ViewController
all in one place.
Here is a simple functional approach. Specify sort order using array. Prepend minus to specify descending order.
var homes = [
{"h_id":"3", "city":"Dallas", "state":"TX","zip":"75201","price":"162500"},
{"h_id":"4","city":"Bevery Hills", "state":"CA", "zip":"90210", "price":"319250"},
{"h_id":"6", "city":"Dallas", "state":"TX", "zip":"75000", "price":"556699"},
{"h_id":"5", "city":"New York", "state":"NY", "zip":"00010", "price":"962500"}
];
homes.sort(fieldSorter(['city', '-price']));
// homes.sort(fieldSorter(['zip', '-state', 'price'])); // alternative
function fieldSorter(fields) {
return function (a, b) {
return fields
.map(function (o) {
var dir = 1;
if (o[0] === '-') {
dir = -1;
o=o.substring(1);
}
if (a[o] > b[o]) return dir;
if (a[o] < b[o]) return -(dir);
return 0;
})
.reduce(function firstNonZeroValue (p,n) {
return p ? p : n;
}, 0);
};
}
Edit: in ES6 it's even shorter!
"use strict";_x000D_
const fieldSorter = (fields) => (a, b) => fields.map(o => {_x000D_
let dir = 1;_x000D_
if (o[0] === '-') { dir = -1; o=o.substring(1); }_x000D_
return a[o] > b[o] ? dir : a[o] < b[o] ? -(dir) : 0;_x000D_
}).reduce((p, n) => p ? p : n, 0);_x000D_
_x000D_
const homes = [{"h_id":"3", "city":"Dallas", "state":"TX","zip":"75201","price":162500}, {"h_id":"4","city":"Bevery Hills", "state":"CA", "zip":"90210", "price":319250},{"h_id":"6", "city":"Dallas", "state":"TX", "zip":"75000", "price":556699},{"h_id":"5", "city":"New York", "state":"NY", "zip":"00010", "price":962500}];_x000D_
const sortedHomes = homes.sort(fieldSorter(['state', '-price']));_x000D_
_x000D_
document.write('<pre>' + JSON.stringify(sortedHomes, null, '\t') + '</pre>')
_x000D_
This worked well for me. I hope it will fix your issues too.
function toFixedNumber(number) {
const spitedValues = String(number.toLocaleString()).split('.');
let decimalValue = spitedValues.length > 1 ? spitedValues[1] : '';
decimalValue = decimalValue.concat('00').substr(0,2);
return '$'+spitedValues[0] + '.' + decimalValue;
}
// 5.56789 ----> $5.56
// 0.342 ----> $0.34
// -10.3484534 ----> $-10.34
// 600 ----> $600.00
function convertNumber(){_x000D_
var result = toFixedNumber(document.getElementById("valueText").value);_x000D_
document.getElementById("resultText").value = result;_x000D_
}_x000D_
_x000D_
_x000D_
function toFixedNumber(number) {_x000D_
const spitedValues = String(number.toLocaleString()).split('.');_x000D_
let decimalValue = spitedValues.length > 1 ? spitedValues[1] : '';_x000D_
decimalValue = decimalValue.concat('00').substr(0,2);_x000D_
_x000D_
return '$'+spitedValues[0] + '.' + decimalValue;_x000D_
}
_x000D_
<div>_x000D_
<input type="text" id="valueText" placeholder="Input value here..">_x000D_
<br>_x000D_
<button onclick="convertNumber()" >Convert</button>_x000D_
<br><hr>_x000D_
<input type="text" id="resultText" placeholder="result" readonly="true">_x000D_
</div>
_x000D_
Console.WriteLine(string.Join<TYPE>("\n", someObjectList));
For me the .crash file was enough. Without .dSYM file and .app file.
I ran these two commands on the mac where I build the archive and it worked:
export DEVELOPER_DIR="/Applications/Xcode.app/Contents/Developer"
/Applications/Xcode.app/Contents/SharedFrameworks/DVTFoundation.framework/Versions/A/Resources/symbolicatecrash /yourPath/crash1.crash > /yourPath/crash1_symbolicated.crash
C:\....\wildfly-9.0.1.Final\standalone\deployments\YOUR-PROJEKT-FOLDER
you can use regex as the delimiter:
pd.read_csv("whitespace.csv", header=None, delimiter=r"\s+")
I believe that npm install
should not run in a production environment. There are several things that can go wrong - npm outage, download of newer dependencies (shrinkwrap seems to have solved this) are two of them.
On the other hand, folder node_modules should not be committed to Git. Apart from their big size, commits including them can become distracting.
The best solutions would be this: npm install
should run in a CI environment that is similar to the production environment. All tests will run and a zipped release file will be created that will include all dependencies.
Per the docs, the exception types you may need to catch are:
GuzzleHttp\Exception\ClientException
for 400-level errorsGuzzleHttp\Exception\ServerException
for 500-level errorsGuzzleHttp\Exception\BadResponseException
for both (it's their superclass)Code to handle such errors thus now looks something like this:
$client = new GuzzleHttp\Client;
try {
$client->get('http://google.com/nosuchpage');
}
catch (GuzzleHttp\Exception\ClientException $e) {
$response = $e->getResponse();
$responseBodyAsString = $response->getBody()->getContents();
}
If you're looking to also get the port number out of the request you'll need to access it through the Request.Host
property for AspNet Core.
The Request.Host
property is not simply a string but, instead, an object that holds both the host domain and the port number. If the port number is specifically written out in the URL (i.e. "https://example.com:8080/path/to/resource"
), then calling Request.Host
will give you the host domain and the port number like so: "example.com:8080"
.
If you only want the value for the host domain or only want the value for the port number then you can access those properties individually (i.e. Request.Host.Host
or Request.Host.Port
).
UPDATE: Getting the indexPath of the cell containing the button (both section and row):
Using Button Position
Inside of your buttonTapped
method, you can grab the button's position, convert it to a coordinate in the tableView, then get the indexPath of the row at that coordinate.
func buttonTapped(_ sender:AnyObject) {
let buttonPosition:CGPoint = sender.convert(CGPoint.zero, to:self.tableView)
let indexPath = self.tableView.indexPathForRow(at: buttonPosition)
}
NOTE: Sometimes you can run into an edge case when using the function view.convert(CGPointZero, to:self.tableView)
results in finding nil
for a row at a point, even though there is a tableView cell there. To fix this, try passing a real coordinate that is slightly offset from the origin, such as:
let buttonPosition:CGPoint = sender.convert(CGPoint.init(x: 5.0, y: 5.0), to:self.tableView)
Previous Answer: Using Tag Property (only returns row)
Rather than climbing into the superview trees to grab a pointer to the cell that holds the UIButton, there is a safer, more repeatable technique utilizing the button.tag property mentioned by Antonio above, described in this answer, and shown below:
In cellForRowAtIndexPath:
you set the tag property:
button.tag = indexPath.row
button.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)
Then, in the buttonClicked:
function, you reference that tag to grab the row of the indexPath where the button is located:
func buttonClicked(sender:UIButton) {
let buttonRow = sender.tag
}
I prefer this method since I've found that swinging in the superview trees can be a risky way to design an app. Also, for objective-C I've used this technique in the past and have been happy with the result.
On project explorer, right click on the project, Properties -> General -> Encoding. This will allow you to choose the encoding per project.
If you'd like to do this in ggplot
, an API change was made to geom_histogram()
that leads to an error: https://github.com/hadley/ggplot2/issues/1465
To get around this, use geom_bar()
:
animals <- c("cat", "dog", "dog", "dog", "dog", "dog", "dog", "dog", "cat", "cat", "bird")
library(ggplot2)
# counts
ggplot(data.frame(animals), aes(x=animals)) +
geom_bar()
you can use the below code to bring focus to a div, in this example the page scrolls to the <div id="navigation">
$('html, body').animate({ scrollTop: $('#navigation').offset().top }, 'slow');
Close any open projects which are not in current use.
Try to switch off the auto publish mode during development.
If Character.isLetter(ch)
looks a bit wordy/ugly you can use a static import.
import static java.lang.Character.*;
if(isLetter(ch)) {
} else if(isDigit(ch)) {
}
Reread the error message. It says:
sh: mysql_config: not found
If you are on Ubuntu Natty, mysql_config
belongs to package libmysqlclient-dev
public void removeLineFromFile(String file, String lineToRemove) {
try {
File inFile = new File(file);
if (!inFile.isFile()) {
System.out.println("Parameter is not an existing file");
return;
}
//Construct the new file that will later be renamed to the original filename.
File tempFile = new File(inFile.getAbsolutePath() + ".tmp");
BufferedReader br = new BufferedReader(new FileReader(file));
PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
String line = null;
//Read from the original file and write to the new
//unless content matches data to be removed.
while ((line = br.readLine()) != null) {
if (!line.trim().equals(lineToRemove)) {
pw.println(line);
pw.flush();
}
}
pw.close();
br.close();
//Delete the original file
if (!inFile.delete()) {
System.out.println("Could not delete file");
return;
}
//Rename the new file to the filename the original file had.
if (!tempFile.renameTo(inFile))
System.out.println("Could not rename file");
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
This I have found on the internet.
Right click in the query pane, select Query Options...
and in the Execution->General section (the default when you first open it) there is an Execution time-out
setting.
Here is the flex-box approach:
CSS
.parent {
display:flex;
height:100vh;
}
.child{
flex-grow:1;
}
.left{
background:#ddd;
}
.center{
background:#666;
}
.right{
background:#999;
}
HTML
<div class="parent">
<div class="child left">Left</div>
<div class="child center">Center</div>
<div class="child right">Right</div>
</div>
You can try the same in js fiddle.
In one of our API project we decide to set a 409 Status to some request, when we can't full fill it at 100% because of missing parameter.
HTTP Status Code "409 Conflict" was for us a good try because it's definition require to include enough information for the user to recognize the source of the conflict.
Reference: w3.org/Protocols/
So among other response like 400 or 404 we chose 409 to enforce the need for looking over some notes in the request helpful to set up a new and right request.
Any way our case it was particular because we need to send out some data eve if the request was not completely correct, and we need to enforce the client to look at the message and understand what was wrong in the request.
In general if we have only some missing parameter we go for a 400 and an array of missing parameter. But when we need to send some more information, like a particular case message and we want to be more sure the client will take care of it we send a 409
You can use that and adjust the time you want to launch 1= onload 2000= 2 sec
$(document).ready(function(){
$('#click').click(function(){
alert('button clicked');
});
// set time out 2 sec
setTimeout(function(){
$('#click').trigger('click');
}, 2000);
});
_x000D_
.container{
padding-top:50px;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="col text-center">
<button id="click" class="btn btn-danger">Jquery Auto Click</button>
</div>
</div>
_x000D_
ALTER SCHEMA TargetSchema
TRANSFER SourceSchema.TableName;
If you want to move all tables into a new schema, you can use the undocumented (and to be deprecated at some point, but unlikely!) sp_MSforeachtable
stored procedure:
exec sp_MSforeachtable "ALTER SCHEMA TargetSchema TRANSFER ?"
Ref.: ALTER SCHEMA
Update 2016:
Unfortunately most of the above solutions are out of date and no longer maintained.
There are 3 additional options I can suggest that are still actively developed:
A .Net component that can be used to integrate the Chrome engine into your .Net Application. Based on CefGlue but a little faster on updates to the latest Chrome version. Also there is a commercial support option available which might come in handy for some. Of course the component itself is open source.
Another .Net component which can be used to integrate the Firefox engine into your .Net application. This is based on Geckofx but unlike the current version of Geckofx this will work with a normal release build of Firefox. To use Geckofx you will need to build Firefox yourself. Again commercial support is available but the component itself is fully open source.
Need all the different browsers in your .Net Application? Which the BrowseEmAll Core API you can integrate Chrome, Firefox, Webkit and Internet Explorer into your application. This is a commercial product though so be warned.
(Full disclosure: I work for this company so take everything I say with a grain of salt)
You can close files not csv.writer object, it should be:
f = open(fileName, "wb")
writer = csv.writer(f)
String[] entries = "first*second*third".split("*");
writer.writerows(entries)
f.close()
For me the issue was VPN, I disconnected the VPN and "npm i" command worked with no fail.
With props to Rick (second comment down in the blog post mentioned), here's the MSDN article on httpOnlyCookies.
Bottom line is that you just add the following section in your system.web section in your web.config:
<httpCookies domain="" httpOnlyCookies="true|false" requireSSL="true|false" />
Node.js was created explicitly as an experiment in async processing. The theory was that doing async processing on a single thread could provide more performance and scalability under typical web loads than the typical thread-based implementation.
And you know what? In my opinion that theory's been borne out. A node.js app that isn't doing CPU intensive stuff can run thousands more concurrent connections than Apache or IIS or other thread-based servers.
The single threaded, async nature does make things complicated. But do you honestly think it's more complicated than threading? One race condition can ruin your entire month! Or empty out your thread pool due to some setting somewhere and watch your response time slow to a crawl! Not to mention deadlocks, priority inversions, and all the other gyrations that go with multithreading.
In the end, I don't think it's universally better or worse; it's different, and sometimes it's better and sometimes it's not. Use the right tool for the job.
Simply just divide the numbers, it gives yuh the decimal format and even the numerical format. using S<->D
For example: 11/3 gives you 3.666667 and 3 2/3 (Swap using S<->D). Here the '2' from 2/3 is your mod value.
Similarly 18/6 gives you 14.833333 and 14 5/6 (Swap using S<->D). Here the '5' from 5/6 is your mod value.
Er, it's not really a test if you don't add something to your path:
bill@bill-desktop:~$ ls -l /opt/pkg/bin total 12 -rwxr-xr-x 1 root root 28 2009-01-22 18:58 foo bill@bill-desktop:~$ which foo /opt/pkg/bin/foo bill@bill-desktop:~$ sudo su root@bill-desktop:/home/bill# which foo root@bill-desktop:/home/bill#
If I understand the situation correctly, you are just passing json data through the http body, instead of application/x-www-form-urlencoded
data.
You can fetch this data with this snippet:
$request_body = file_get_contents('php://input');
If you are passing json, then you can do:
$data = json_decode($request_body);
$data
then contains the json data is php array.
php://input
is a so called wrapper.
php://input is a read-only stream that allows you to read raw data from the request body. In the case of POST requests, it is preferable to use php://input instead of $HTTP_RAW_POST_DATA as it does not depend on special php.ini directives. Moreover, for those cases where $HTTP_RAW_POST_DATA is not populated by default, it is a potentially less memory intensive alternative to activating always_populate_raw_post_data. php://input is not available with enctype="multipart/form-data".
I want to change or update my ContactNo to 8018070999 where there is 8018070777 using Case statement
update [Contacts] set contactNo=(case
when contactNo=8018070777 then 8018070999
else
contactNo
end)
I would create a property to access the variable, like this:
protected string Test
{
get; set;
}
And in your markup:
<%= this.Test %>
It's an infamous problem: .equals()
for arrays is badly broken, just don't use it, ever.
That said, it's not "broken" as in "someone has done it in a really wrong way" — it's just doing what's defined and not what's usually expected. So for purists: it's perfectly fine, and that also means, don't use it, ever.
Now the expected behaviour for equals
is to compare data. The default behaviour is to compare the identity, as Object
does not have any data (for purists: yes it has, but it's not the point); assumption is, if you need equals
in subclasses, you'll implement it. In arrays, there's no implementation for you, so you're not supposed to use it.
So the difference is, Arrays.equals(array1, array2)
works as you would expect (i.e. compares content), array1.equals(array2)
falls back to Object.equals
implementation, which in turn compares identity, and thus better replaced by ==
(for purists: yes I know about null
).
Problem is, even Arrays.equals(array1, array2)
will bite you hard if elements of array do not implement equals
properly. It's a very naive statement, I know, but there's a very important less-than-obvious case: consider a 2D array.
2D array in Java is an array of arrays, and arrays' equals
is broken (or useless if you prefer), so Arrays.equals(array1, array2)
will not work as you expect on 2D arrays.
Hope that helps.
How about this:
find /some/directory -maxdepth 1 -type f -exec cmd option {} \; > results.out
-maxdepth 1
argument prevents find from recursively descending into
any subdirectories. (If you want such nested directories to get processed, you can omit this.)-type -f
specifies that only plain files will be processed.-exec cmd option {}
tells it to run cmd
with the specified option
for each file found, with the filename substituted for {}
\;
denotes the end of the command.cmd
executions is redirected to
results.out
However, if you care about the order in which the files are processed, you
might be better off writing a loop. I think find
processes the files
in inode order (though I could be wrong about that), which may not be what
you want.
One way might be;
<select name="listbox" id="listbox">
@foreach (var item in Model)
{
<option value="@item.UserRoleId">
@item.UserRole
</option>
}
</select>
code () {
if [[ $# = 0 ]]
then
open -a "Visual Studio Code"
else
echo "Opening: "$@
"/Applications/Visual Studio Code.app/Contents/MacOS/Electron" $@
fi
}
I put that into my .bash_profile
I tested it and it works.
From the menu bar: Project -> Properties -> Java Compiler
Enable project specific settings (checked) Uncheck "use Compliance from execution environment '.... Select the desired "compiler compliance level"
That will allow you to compile "1.5" code using a "1.6" JDK.
If you want to acutally use a 1.5 JDK to produce "1.5" compliant code, then install a suitable 1.5 JDK and tell eclipse where it is installed via:
Window -> preferences -> Installed JREs
And then go back to your project
Project -> properties -> Java Build Path -> libraries
remove the 1.6 system libaries, and: add library... -> JRE System LIbrary -> Alternate JRE -> The JRE you want.
Verify that the correct JRE is on the project's build path, save everything, and enjoy!
I would be very careful with self closing tags as this example demonstrates:
var a = '<span/><span/>';
var d = document.createElement('div');
d.innerHTML = a
console.log(d.innerHTML) // "<span><span></span></span>"
My gut feeling would have been <span></span><span></span>
instead
To list mongodb database on shell
show databases //Print a list of all available databases.
show dbs // Print a list of all databases on the server.
Few more basic commands
use <db> // Switch current database to <db>. The mongo shell variable db is set to the current database.
show collections //Print a list of all collections for current database.
show users //Print a list of users for current database.
show roles //Print a list of all roles, both user-defined and built-in, for the current database.
WHen I run into this problem with it not getting latest and version mismatches I first do a "Get Specific Version" set it to changeset and put in 1. This will then remove all the files from your local workspace (for that project, folder, file, etc) and it will also have TFS update so that it knows you now have NO VERSION DOWNLOADED. You can then do a "Get Latest" and viola, you will actually have the latest
Solve that by using std::basic_string<TCHAR>
instead of std::string
and it should work fine regardless of your character setting.
A new feature, IIF (that we can simply use), was added in SQL Server 2012:
SELECT IIF ( (Obsolete = 'N' OR InStock = 'Y'), 1, 0) AS Saleable, * FROM Product
Use this instead
function timedRefresh(timeoutPeriod) {
setTimeout("location.reload(true);",timeoutPeriod);
}
<a href="javascript:timedRefresh(2000)">image</a>
Structured Query Language - SQL: is an ANSI-standard used by almost all SGBD's vendors around the world. Basically, SQL is a language used to define and manipulate data [DDL and DML].
PL/SQL is a language created by Oracle universe. PL/SQL combine programming procedural instructions and allows the creation of programs that operates directly on database scenario.
T-SQL is Microsoft product align SQL patterns, with some peculiarities. So, feel free to test your limits.
I found that running the npm install
command in the same directory where your Angular project is, eliminates these warnings. I do not know the reason why.
Specifically, I was trying to use ng2-completer
$ npm install ng2-completer --save
npm WARN saveError ENOENT: no such file or directory, open 'C:\Work\foo\package.json'
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN enoent ENOENT: no such file or directory, open 'C:\Work\foo\package.json'
npm WARN [email protected] requires a peer of @angular/common@>= 6.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of @angular/core@>= 6.0.0 but noneis installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of @angular/forms@>= 6.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN foo No description
npm WARN foo No repository field.
npm WARN foo No README data
npm WARN foo No license field.
I was unable to compile. When I tried again, this time in my Angular project directory which was in foo/foo_app, it worked fine.
cd foo/foo_app
$ npm install ng2-completer --save
I know this question is for Bootstrap 3, but as some Bootstrap 4 related question are redirected to this one as duplicates, here's the snippet Bootstrap 4-compatible:
$.validator.setDefaults({
highlight: function(element) {
$(element).closest('.form-group').addClass('has-danger');
},
unhighlight: function(element) {
$(element).closest('.form-group').removeClass('has-danger');
},
errorElement: 'small',
errorClass: 'form-control-feedback d-block',
errorPlacement: function(error, element) {
if(element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else if(element.prop('type') === 'checkbox') {
error.appendTo(element.parent().parent().parent());
} else if(element.prop('type') === 'radio') {
error.appendTo(element.parent().parent().parent());
} else {
error.insertAfter(element);
}
},
});
The few differences are:
has-danger
instead of has-error
Mark circular dependencies as "Warning" in Eclipse tool to avoid "A CYCLE WAS DETECTED IN THE BUILD PATH" error.
In Eclipse go to:
Windows -> Preferences -> Java-> Compiler -> Building -> Circular Dependencies
I tried all the suggestions above, but what worked in the end was changing the Application Pool managed pipeline from Integrated mode to Classic mode.
It runs in its own application pool - but it was the first .NET 4.0 service - all other servicves are on .NET 2.0 using Integrated pipeline mode.
Its just a standard WCF service using is https - but on Server 2008 (not R2) - using IIS 7 (not 7.5) .
I had the same problem (different web app though) with the error message and it turned out to be the MIME-Type for .js files was text/x-js
instead of application/javascript
due to a duplicate entry in mime.types on the server that was responsible for serving the js files. It seems that this is happening if the header X-Content-Type-Options: nosniff
is set, which makes Firefox (and Chrome) block the content of the js files.
Try to change directory to where the .box
is saved
Run vagrant box add my-box downloaded.box
, this may work as it avoids absolute path (on Windows?).
Remember that the MAX aggregate function will work on text as well as numbers. This query will only require the table to be scanned once.
SELECT Action,
MAX( CASE data WHEN 'View' THEN data ELSE '' END ) ViewCol,
MAX( CASE data WHEN 'Edit' THEN data ELSE '' END ) EditCol
FROM t
GROUP BY Action
Try This
$('#twitterSearch').keydown(function(event){
var keyCode = (event.keyCode ? event.keyCode : event.which);
if (keyCode == 13) {
$('#startSearch').trigger('click');
}
});
Hope it helps you
def myfunc(a,b):
c = a.intersection(b)
return bool(c)
bool()
will do something similar to not not
, but more ideomatic and clear.
Use a formatter, if you only want to format it so that it renders nicely when printed. Just use the df.to_string(... formatters
to define custom string-formatting, without needlessly modifying your DataFrame or wasting memory:
df = pd.DataFrame({
'A': ['a', 'b', 'c'],
'B': [np.nan, 1, np.nan],
'C': ['read', 'unread', 'read']})
print df.to_string(
formatters={'B': lambda x: '' if pd.isnull(x) else '{:.0f}'.format(x)})
To get:
A B C
0 a read
1 b 1 unread
2 c read
Yes, use getJSONP. It's the only way to make cross domain/server async calls. (*Or it will be in the near future). Something like
$.getJSON('your-api-url/validate.php?'+$(this).serialize+'callback=?', function(data){
if(data)console.log(data);
});
The callback parameter will be filled in automatically by the browser, so don't worry.
On the server side ('validate.php') you would have something like this
<?php
if(isset($_GET))
{
//if condition is met
echo $_GET['callback'] . '(' . "{'message' : 'success', 'userID':'69', 'serial' : 'XYZ99UAUGDVD&orwhatever'}". ')';
}
else echo json_encode(array('error'=>'failed'));
?>
Open a terminal:
Check MySQL system pref panel, if it says something along the line "Warning, /usr/local/mysql/data is not owned by 'mysql' or '_mysql'
If yes, go to the mysql folder cd /usr/local/mysql
do a sudo chown -R _mysql data/
This will change ownership of the /usr/local/mysql/data and all of its content to own by user '_mysql'
Check MySQL system pref panel, it should be saying it's running now, auto-magically. If not start again.
Another way to confirm is to do a
netstat -na | grep 3306
It should say:
tcp46 0 0 *.3306 *.* LISTEN
To see the process owner and process id of the mysqld:
ps aux | grep mysql
Generic classes are a type of class that takes in a data type as a parameter when it's created. This type parameter is specified using angle brackets and the type can change each time a new instance of the class is instantiated. For instance, let's create an ArrayList for Employee objects and another for Company objects
ArrayList<Employee> employees = new ArrayList<Employee>();
ArrayList<Company> companies = new ArrayList<Company>();
You'll notice that we're using the same ArrayList class to create both lists and we pass in the Employee or Company type using angle brackets. Having one generic class be able to handle multiple types of data cuts down on having a lot of classes that perform similar tasks. Generics also help to cut down on bugs by giving everything a strong type which helps the compiler point out errors. By specifying a type for ArrayList, the compiler will throw an error if you try to add an Employee to the Company list or vice versa.
Set editable
to False
and default
to your default value.
http://docs.djangoproject.com/en/stable/ref/models/fields/#editable
b = models.CharField(max_length=7, default='0000000', editable=False)
Also, your id
field is unnecessary. Django will add it automatically.
If your main objective is doing math, SymPy provides an excellent approach to functional latex expressions that look great.
John's answer won't produce .txt files as the OP wants. Use:
split -b=1M -d file.txt file --additional-suffix=.txt
For me this solution works fine: https://github.com/cruffenach/CRToast
Example how use it:
NSDictionary *options = @{
kCRToastTextKey : @"Hello World!",
kCRToastTextAlignmentKey : @(NSTextAlignmentCenter),
kCRToastBackgroundColorKey : [UIColor redColor],
kCRToastAnimationInTypeKey : @(CRToastAnimationTypeGravity),
kCRToastAnimationOutTypeKey : @(CRToastAnimationTypeGravity),
kCRToastAnimationInDirectionKey : @(CRToastAnimationDirectionLeft),
kCRToastAnimationOutDirectionKey : @(CRToastAnimationDirectionRight)
};
[CRToastManager showNotificationWithOptions:options
completionBlock:^{
NSLog(@"Completed");
}];
You say that you already tried onStatusChanged(), but that does work for me.
Here's the method I use (I let the class itself handle the onStatusChanged):
private void startLocationTracking() {
final int updateTime = 2000; // ms
final int updateDistance = 10; // meter
final Criteria criteria = new Criteria();
criteria.setCostAllowed(false);
criteria.setAccuracy(Criteria.ACCURACY_FINE);
final String p = locationManager.getBestProvider(criteria, true);
locationManager.requestLocationUpdates(p, updateTime, updateDistance,
this);
}
And I handle the onStatusChanged as follows:
void onStatusChanged(final String provider, final int status,
final Bundle extras) {
switch (status) {
case LocationProvider.OUT_OF_SERVICE:
if (location == null || location.getProvider().equals(provider)) {
statusString = "No Service";
location = null;
}
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
if (location == null || location.getProvider().equals(provider)) {
statusString = "no fix";
}
break;
case LocationProvider.AVAILABLE:
statusString = "fix";
break;
}
}
Note that the onProvider{Dis,En}abled() methods are about enabling and disabling GPS tracking by the user; not what you're looking for.
with ES6 you can do:
// `n` is the size you want to initialize your array
// `null` is what the array will be filled with (can be any other value)
Array(n).fill(null)
$st = $data->prepare("SELECT * FROM exampleWHERE example LIKE :search LIMIT 10");
I am using the following script to
.
#!/bin/bash -xe
SRC_ENCODING="iso-8859-1"
DST_ENCODING="utf-8"
FILTER="*.java"
echo "Find all files that match the encoding $SRC_ENCODING and filter $FILTER"
FOUND_FILES=$(find . -iname "$FILTER" -exec file -i {} \; | grep "$SRC_ENCODING" | grep -Eo '^.*\.java')
for FILE in $FOUND_FILES ; do
ORIGINAL_FILE="$FILE.$SRC_ENCODING.bkp"
echo "Backup original file to $ORIGINAL_FILE"
mv "$FILE" "$ORIGINAL_FILE"
echo "converting $FILE from $SRC_ENCODING to $DST_ENCODING"
iconv -f "$SRC_ENCODING" -t "$DST_ENCODING" "$ORIGINAL_FILE" -o "$FILE"
done
echo "Deleting backups"
find . -iname "*.$SRC_ENCODING.bkp" -exec rm {} \;
OpenProcess Function
From MSDN:
To open a handle to another local process and obtain full access rights, you must enable the SeDebugPrivilege privilege.
We have this problem and to solve
Create a script file called to-utf8.sh
#!/bin/bash
TO="UTF-8"; FILE=$1
FROM=$(file -i $FILE | cut -d'=' -f2)
if [[ $FROM = "binary" ]]; then
echo "Skipping binary $FILE..."
exit 0
fi
iconv -f $FROM -t $TO -o $FILE.tmp $FILE; ERROR=$?
if [[ $ERROR -eq 0 ]]; then
echo "Converting $FILE..."
mv -f $FILE.tmp $FILE
else
echo "Error on $FILE"
fi
Set the executable bit
chmod +x to-utf8.sh
Do a conversion
./to-utf8.sh MyFile.txt
If you want to convert all files under a folder, do
find /your/folder/here | xargs -n 1 ./to-utf8.sh
Hope it's help.
Simply by Rails.root or if you want append something we can use it like Rails.root.join('app', 'assets').to_s
You could do this:
(Note! This is CSS3 and the browser support = good!! )
p {
text-overflow: ellipsis; /* will make [...] at the end */
width: 370px; /* change to your preferences */
white-space: nowrap; /* paragraph to one line */
overflow:hidden; /* older browsers */
}
Well even if what suggest by @Tauras just works I don't think it's the correct way to deal with this.
You said you have run php artisan make:auth
which should have also inserted Auth::routes();
in your routes/web.php
routing files. Which comes with default logout
route already defined and is named logout
.
You can see it here on GitHub, but I will also report the code here for simplicity:
/**
* Register the typical authentication routes for an application.
*
* @return void
*/
public function auth()
{
// Authentication Routes...
$this->get('login', 'Auth\LoginController@showLoginForm')->name('login');
$this->post('login', 'Auth\LoginController@login');
$this->post('logout', 'Auth\LoginController@logout')->name('logout');
// Registration Routes...
$this->get('register', 'Auth\RegisterController@showRegistrationForm')->name('register');
$this->post('register', 'Auth\RegisterController@register');
// Password Reset Routes...
$this->get('password/reset', 'Auth\ForgotPasswordController@showLinkRequestForm')->name('password.request');
$this->post('password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail')->name('password.email');
$this->get('password/reset/{token}', 'Auth\ResetPasswordController@showResetForm')->name('password.reset');
$this->post('password/reset', 'Auth\ResetPasswordController@reset');
}
Then again please note that logout
requires POST
as HTTP request method. There are many valid reason behind this, but just to mention one very important is that in this way you can prevent cross-site request forgery.
So according to what I have just pointed out a correct way to implement this could be just this:
<a href="{{ route('logout') }}" onclick="event.preventDefault(); document.getElementById('frm-logout').submit();">
Logout
</a>
<form id="frm-logout" action="{{ route('logout') }}" method="POST" style="display: none;">
{{ csrf_field() }}
</form>
Finally note that I have inserted laravel out of the box ready function {{ csrf_field() }}
!
Suppose your function enters data in columns A and B and you want to a custom Userform to appear if the user selects a cell in column C. One way to do this is to use the SelectionChange
event:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim clickRng As Range
Dim lastRow As Long
lastRow = Range("A1").End(xlDown).Row
Set clickRng = Range("C1:C" & lastRow) //Dynamically set cells that can be clicked based on data in column A
If Not Intersect(Target, clickRng) Is Nothing Then
MyUserForm.Show //Launch custom userform
End If
End Sub
Note that the userform will appear when a user selects any cell in Column C and you might want to populate each cell in Column C with something like "select cell to launch form" to make it obvious that the user needs to perform an action (having a button naturally suggests that it should be clicked)
from keras.models import load_model
h= load_model('FILE_NAME.h5')
you have to include two more jar files.
xmlbeans-2.3.0.jar and dom4j-1.6.1.jar Add try it will work.
Note: It is required for the files with .xlsx formats only, not for just .xlt formats.
One can use base python for this. The code needs a function to flatten lists of lists:
def flatten(B): # function needed for code below;
A = []
for i in B:
if type(i) == list: A.extend(i)
else: A.append(i)
return A
Then one can run:
L = [[1,2,3],[4,5,6],[7,8,9,10]]
outlist =[]; templist =[[]]
for sublist in L:
outlist = templist; templist = [[]]
for sitem in sublist:
for oitem in outlist:
newitem = [oitem]
if newitem == [[]]: newitem = [sitem]
else: newitem = [newitem[0], sitem]
templist.append(flatten(newitem))
outlist = list(filter(lambda x: len(x)==len(L), templist)) # remove some partial lists that also creep in;
print(outlist)
Output:
[[1, 4, 7], [2, 4, 7], [3, 4, 7],
[1, 5, 7], [2, 5, 7], [3, 5, 7],
[1, 6, 7], [2, 6, 7], [3, 6, 7],
[1, 4, 8], [2, 4, 8], [3, 4, 8],
[1, 5, 8], [2, 5, 8], [3, 5, 8],
[1, 6, 8], [2, 6, 8], [3, 6, 8],
[1, 4, 9], [2, 4, 9], [3, 4, 9],
[1, 5, 9], [2, 5, 9], [3, 5, 9],
[1, 6, 9], [2, 6, 9], [3, 6, 9],
[1, 4, 10], [2, 4, 10], [3, 4, 10],
[1, 5, 10], [2, 5, 10], [3, 5, 10],
[1, 6, 10], [2, 6, 10], [3, 6, 10]]
It is recommended to use the spinal-case (which is highlighted by RFC3986), this case is used by Google, PayPal, and other big companies.
source:- https://blog.restcase.com/5-basic-rest-api-design-guidelines/
Demo :
<connectionStrings>
<add name="myConnectionString" connectionString="server=localhost;database=myDb;uid=myUser;password=myPass;" />
</connectionStrings>
Based on your question:
<connectionStrings>
<add name="itmall" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=D:\19-02\ABCC\App_Data\abcc.mdf;Integrated Security=True;User Instance=True" />
</connectionStrings>
Refer links:
http://www.connectionstrings.com/store-connection-string-in-webconfig/
Retrive connection string from web.config file:
write the below code in your file where you want;
string connstring=ConfigurationManager.ConnectionStrings["itmall"].ConnectionString;
SqlConnection con = new SqlConnection(connstring);
or you can go in your way like
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["itmall"].ConnectionString);
Note:
The "name" which you gave in web.config file and name which you used in connection string must be same(like "itmall" in this solution.)
This is super simple, just use dir(
object)
This will return a list of every available function and attribute of the object.
Can't tell you how many times this has caught. me.
Guid myGuid = Guid.NewGuid();
Using HTML5 mode requires URL rewriting on server side, basically you have to rewrite all your links to entry point of your application (e.g. index.html). Requiring a <base>
tag is also important for this case, as it allows AngularJS to differentiate between the part of the url that is the application base and the path that should be handled by the application. For more information, see AngularJS Developer Guide - Using $location HTML5 mode Server Side.
When you have html5Mode enabled, the #
character will no longer be used in your urls. The #
symbol is useful because it requires no server side configuration. Without #
, the url looks much nicer, but it also requires server side rewrites. Here are some examples:
<VirtualHost *:80>
ServerName my-app
DocumentRoot /path/to/app
<Directory /path/to/app>
RewriteEngine on
# Don't rewrite files or directories
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
# Rewrite everything else to index.html to allow html5 state links
RewriteRule ^ index.html [L]
</Directory>
</VirtualHost>
server {
server_name my-app;
index index.html;
root /path/to/app;
location / {
try_files $uri $uri/ /index.html;
}
}
<system.webServer>
<rewrite>
<rules>
<rule name="Main Rule" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="/" />
</rule>
</rules>
</rewrite>
</system.webServer>
var express = require('express');
var app = express();
app.use('/js', express.static(__dirname + '/js'));
app.use('/dist', express.static(__dirname + '/../dist'));
app.use('/css', express.static(__dirname + '/css'));
app.use('/partials', express.static(__dirname + '/partials'));
app.all('/*', function(req, res, next) {
// Just send the index.html for other files to support HTML5Mode
res.sendFile('index.html', { root: __dirname });
});
app.listen(3006); //the port you want to use
See also
<html>
<head>
<title>Testing File Upload Inputs</title>
<script type="text/javascript">
<!--
function showSrc() {
document.getElementById("myframe").href = document.getElementById("myfile").value;
var theexa = document.getElementById("myframe").href.replace("file:///","");
alert(document.getElementById("myframe").href.replace("file:///",""));
}
// -->
</script>
</head>
<body>
<form method="get" action="#" >
<input type="file"
id="myfile"
onChange="javascript:showSrc();"
size="30">
<br>
<a href="#" id="myframe"></a>
</form>
</body>
</html>
On Windows, start up Command Prompt (cmd.exe) or PowerShell (powershell.exe). To do this quickly, open a Run Command window by pressing Windows Key + R. In the Run Command window, type "cmd.exe" to launch Command Prompt; However, to start PowerShell instead, then type "powershell". If you are connecting your Android device to your computer using a USB cable, then you will need to check whether your device is communicating with adb
by entering the command below:
# adb devices -l
Next, pull (copy) the file from your Android device over to Windows. This can be accomplished by entering the following command:
# adb pull /sdcard/log.txt %HOME%\Desktop\log.txt
Optionally, you may enter this command instead:
# adb pull /sdcard/log.txt C:\Users\admin\Desktop\log.txt
You close the second Scanner
which closes the underlying InputStream
, therefore the first Scanner
can no longer read from the same InputStream
and a NoSuchElementException
results.
The solution: For console apps, use a single Scanner
to read from System.in
.
Aside: As stated already, be aware that Scanner#nextInt
does not consume newline characters. Ensure that these are consumed before attempting to call nextLine
again by using Scanner#newLine()
.
See: Do not create multiple buffered wrappers on a single InputStream
In case you use MVC to accomplish it - you will have to do something like this
<form action="/ControllerName/ActionName" method="post">
<a href="javascript:;" onclick="parentNode.submit();"><%=n%></a>
<input type="hidden" name="mess" value=<%=n%>/>
</form>
I just went through some examples here and did not see the MVC one figured it won't hurt to post it.
Then on your Action in the Controller I would just put <HTTPPost>
On the top of it.
I believe if you don't have <HTTPGET>
on the top of it it would still work but explicitly putting it there feels a bit safer.
The most portable way to get the hostname of the current computer in Java is as follows:
import java.net.InetAddress;
import java.net.UnknownHostException;
public class getHostName {
public static void main(String[] args) throws UnknownHostException {
InetAddress iAddress = InetAddress.getLocalHost();
String hostName = iAddress.getHostName();
//To get the Canonical host name
String canonicalHostName = iAddress.getCanonicalHostName();
System.out.println("HostName:" + hostName);
System.out.println("Canonical Host Name:" + canonicalHostName);
}
}
These are my rules of thumb:
If default values can be calculated from other parameters, use default expressions as in:
fun <- function(x,levels=levels(x)){
blah blah blah
}
if otherwise using missing
fun <- function(x,levels){
if(missing(levels)){
[calculate levels here]
}
blah blah blah
}
In the rare case that you thing a user may want to specify a default value
that lasts an entire R session, use getOption
fun <- function(x,y=getOption('fun.y','initialDefault')){# or getOption('pkg.fun.y',defaultValue)
blah blah blah
}
If some parameters apply depending on the class of the first argument, use an S3 generic:
fun <- function(...)
UseMethod(...)
fun.character <- function(x,y,z){# y and z only apply when x is character
blah blah blah
}
fun.numeric <- function(x,a,b){# a and b only apply when x is numeric
blah blah blah
}
fun.default <- function(x,m,n){# otherwise arguments m and n apply
blah blah blah
}
Use ...
only when you are passing additional parameters on to
another function
cat0 <- function(...)
cat(...,sep = '')
Finally, if you do choose the use ...
without passing the dots onto another function, warn the user that your function is ignoring any unused parameters since it can be very confusing otherwise:
fun <- (x,...){
params <- list(...)
optionalParamNames <- letters
unusedParams <- setdiff(names(params),optionalParamNames)
if(length(unusedParams))
stop('unused parameters',paste(unusedParams,collapse = ', '))
blah blah blah
}
You may be able to use the built-in function dir()
to produce similar behavior to PHP's isset()
, something like:
if 'foo' in dir(): # returns False, foo is not defined yet.
pass
foo = 'b'
if 'foo' in dir(): # returns True, foo is now defined and in scope.
pass
dir()
returns a list of the names in the current scope, more information can be found here: http://docs.python.org/library/functions.html#dir.
You did not install the correct Eclipse distribution. Try install the one labeled "Eclipse IDE for Java EE Developers".
I've found a couple other ways you can write these which are a bit more readable IMHO.
- name: check out a git repository
local_action:
module: git
repo: git://foosball.example.org/path/to/repo.git
dest: /local/path
OR
- name: check out a git repository
local_action: git
args:
repo: git://foosball.example.org/path/to/repo.git
dest: /local/path
The easiest way is to redirect the output of the echo
by >>
:
echo 'VNCSERVERS="1:root"' >> /etc/sysconfig/configfile
echo 'VNCSERVERARGS[1]="-geometry 1600x1200"' >> /etc/sysconfig/configfile
react-scripts
is a set of scripts from the create-react-app
starter pack. create-react-app helps you kick off projects without configuring, so you do not have to setup your project by yourself.
react-scripts start
sets up the development environment and starts a server, as well as hot module reloading. You can read here to see what everything it does for you.
with create-react-app you have following features out of the box.
- React, JSX, ES6, and Flow syntax support.
- Language extras beyond ES6 like the object spread operator.
- Autoprefixed CSS, so you don’t need -webkit- or other prefixes.
- A fast interactive unit test runner with built-in support for coverage reporting.
- A live development server that warns about common mistakes.
- A build script to bundle JS, CSS, and images for production, with hashes and sourcemaps.
- An offline-first service worker and a web app manifest, meeting all the Progressive Web App criteria.
- Hassle-free updates for the above tools with a single dependency.
npm start
is a shortcut for npm run start
.
npm run
is used to run scripts that you define in the scripts
object of your package.json
if there is no start
key in the scripts object, it will default to node server.js
Sometimes you want to do more than the react scripts gives you, in this case you can do react-scripts eject
. This will transform your project from a "managed" state into a not managed state, where you have full control over dependencies, build scripts and other configurations.
If you needed only one tab, the following worked for me.
<style>
.tab {
position: absolute;
left: 10em;
}
</style>
with the HTML something like:
<p><b>asdf</b> <span class="tab">99967</span></p>
<p><b>hjkl</b> <span class="tab">88868</span></p>
You can add more "tabs" by adding additional "tab" styles and changing the HTML such as:
<style>
.tab {
position: absolute;
left: 10em;
}
.tab1 {
position: absolute;
left: 20em;
}
</style>
with the HTML something like:
<p><b>asdf</b> <span class="tab">99967</span><span class="tab1">hear</span></p>
<p><b>hjkl</b> <span class="tab">88868</span><span class="tab1">here</span></p>
You can use the MATCH_PARENT constant or its numeric value -1.
str = "/folderA/folderB/folderC/folderD/"
print str.split("/")[-2]
The solutions above are great for interactive use, where you can eyeball the result and weed out false positives that way.
False positives can occur if the executable itself happens to match, or any arguments that are not script names match - the likelihood is greater with scripts that have no filename extensions.
Here's a more robust solution for scripting, using a shell function:
getscript() {
pgrep -lf ".[ /]$1( |\$)"
}
Example use:
# List instance(s) of script "aa.sh" that are running.
getscript "aa.sh" # -> (e.g.): 96112 bash /Users/jdoe/aa.sh
# Use in a test:
if getscript "aa.sh" >/dev/null; then
echo RUNNING
fi
-i
to the pgrep
call to make it case-insensitive; on Linux, that is not an option.)getscript
function also works with full or partial paths that include the filename component; partial paths must not start with /
and each component specified must be complete. The "fuller" the path specified, the lower the risk of false positives. Caveat: path matching will only work if the script was invoked with a path - this is generally true for scripts in the $PATH that are invoked directly.ps
nor pgrep
reflect the original quoting applied to the command line. All the function guarantees is that any match is not the first token (which is the interpreter), and that it occurs as a separate word, optionally preceded by a path.bash
) as well - assuming it is known; e.g.# List instance(s) of a running *bash* script.
getbashscript() {
pgrep -lf "(^|/)bash( | .*/)$1( |\$)"
}
If you're willing to make further assumptions - such as script-interpreter paths never containing embedded spaces - the regexes could be made more restrictive and thus further reduce the risk of false positives.
1.database set 1st single user mode
ALTER DATABASE BOSEVIKRAM SET SINGLE_USER WITH ROLLBACK IMMEDIATE
2.RENAME THE DATABASE
ALTER DATABASE BOSEVIKRAM MODIFY NAME = [BOSEVIKRAM_Deleted]
3.DATABAE SET MULIUSER MODE
ALTER DATABASE BOSEVIKRAM_Deleted SET MULTI_USER WITH ROLLBACK IMMEDIATE
Try this for Amazon Linux AMI or for centOS
sudo service mysqld restart
As replace()
creates/returns a new string rather than modifying the original (tt
), you need to set the variable (tt
) equal to the new string returned from the replace
function.
tt = tt.replace(/,/g, '.')
Are you sure you can't just run cl.exe without any input for it to report its version?
I've just tested running cl.exe in the command prompt for VS 2008, 2005, and .NET 2003 and they all reported its version.
For 2008:
d:\Program Files\Microsoft Visual Studio 9.0\VC>cl
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 15.00.30729.01 for 80x86
For 2005, SP 1 (added Safe Standard C++ classes):
C:\Program Files\Microsoft Visual Studio 8\VC>cl
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 14.00.50727.762 for 80x86
For 2005:
C:\Program Files\Microsoft Visual Studio 8\VC>cl
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 14.00.50727.42 for 80x86
For .NET 2003:
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 13.10.6030 for 80x86
EDIT
For 2010, it will be along the line of:
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.XX.YYYYY.ZZ for 80x86
or depending on targeted platform
Microsoft (R) C/C++ Optimizing Compiler Version 16.XX.YYYYY.ZZ for x64
For 2012:
Microsoft (R) C/C++ Optimizing Compiler Version 17.XX.YYYYY.ZZ for $$$
where $$$ is the targeted platform (e.g. x86, x64, ARM), and XX, YYYYY, and ZZ are minor version numbers.
For 2013:
Microsoft (R) C/C++ Optimizing Compiler Version 18.XX.YYYYY.ZZ for $$$
where $$$ is the targeted platform (e.g. x86, x64, ARM), and XX, YYYYY, and ZZ are minor version numbers.
For 2015:
Microsoft (R) C/C++ Optimizing Compiler Version 19.XX.YYYYY for $$$
where $$$ is the targeted platform (e.g. x86, x64, ARM), and XX and YYYYY are minor version numbers.
I can find one in macOS Mojave (10.14) while playing with virtualenvwrapper-4.8.4
/Library/Frameworks/Python.framework/Versions/3.7/bin/virtualenvwrapper.sh
Rebase and Cherry-pick is the only way you can keep clean commit history. Avoid using merge and avoid creating merge conflict. If you are using gerrit set one project to Merge if necessary and one project to cherry-pick mode and try yourself.
swift version:
var button = UIButton()
newGameButton.setTitle("????? ????", for: .normal)
newGameButton.setImage(UIImage(named: "energi"), for: .normal)
newGameButton.backgroundColor = .blue
newGameButton.imageEdgeInsets.left = -50
Make simple:
@GetMapping("/health")
public ResponseEntity<String> healthCheck() {
LOG.info("REST request health check");
return new ResponseEntity<>("{\"status\" : \"UP\"}", HttpStatus.OK);
}
Is Powershell an option?
Start Powershell:
powershell
Create the VPN Connection: Add-VpnConnection
Add-VpnConnection [-Name] <string> [-ServerAddress] <string> [-TunnelType <string> {Pptp | L2tp | Sstp | Ikev2 | Automatic}] [-EncryptionLevel <string> {NoEncryption | Optional | Required | Maximum}] [-AuthenticationMethod <string[]> {Pap | Chap | MSChapv2 | Eap}] [-SplitTunneling] [-AllUserConnection] [-L2tpPsk <string>] [-RememberCredential] [-UseWinlogonCredential] [-EapConfigXmlStream <xml>] [-Force] [-PassThru] [-WhatIf] [-Confirm]
Edit VPN connections: Set-VpnConnection
Set-VpnConnection [-Name] <string> [[-ServerAddress] <string>] [-TunnelType <string> {Pptp | L2tp | Sstp | Ikev2 | Automatic}] [-EncryptionLevel <string> {NoEncryption | Optional | Required | Maximum}] [-AuthenticationMethod <string[]> {Pap | Chap | MSChapv2 | Eap}] [-SplitTunneling <bool>] [-AllUserConnection] [-L2tpPsk <string>] [-RememberCredential <bool>] [-UseWinlogonCredential <bool>] [-EapConfigXmlStream <xml>] [-PassThru] [-Force] [-WhatIf] [-Confirm]
Lookup VPN Connections: Get-VpnConnection
Get-VpnConnection [[-Name] <string[]>] [-AllUserConnection]
Connect: rasdial [connectionName]
rasdial connectionname [username [password | \]] [/domain:domain*] [/phone:phonenumber] [/callback:callbacknumber] [/phonebook:phonebookpath] [/prefixsuffix**]
You can manage your VPN connections with the powershell commands above, and simply use the connection name to connect via rasdial
.
The results of Get-VpnConnection
can be a little verbose. This can be simplified with a simple Select-Object
filter:
Get-VpnConnection | Select-Object -Property Name
More information can be found here:
an apache server is an http server which can serve any simple http requests, where tomcat server is actually a servlet container which can serve java servlet requests.
Web server [apache] process web client (web browsers) requests and forwards it to servlet container [tomcat] and container process the requests and sends response which gets forwarded by web server to the web client [browser].
Also you can check this link for more clarification:-
https://sites.google.com/site/sureshdevang/servlet-architecture
Also check this answer for further researching :-
Add line-height: 0px;
to your parent div
jsfiddle: http://jsfiddle.net/majZt/
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
This could be a good time to mention the modr() function. It returns both the whole and the remainder parts of a division.
print("\n 17 // 3 =",17//3," # Does the same thing as int(17/3)")
print(" 17 % 3 =",17%3," # Modulo division gives the remainder.")
whole, remain = divmod(17,3)
print(" divmod(17,3) returns ->",divmod(17,3),end="")
print(" because 3 goes into 17,",whole,"times with a remainder of",remain,end=".\n\n")
Use sort -n
or sort --numeric-sort
.
29 = 512 values, because that's how many combinations of zeroes and ones you can have.
What those values represent however will depend on the system you are using. If it's an unsigned integer, you will have:
000000000 = 0 (min)
000000001 = 1
...
111111110 = 510
111111111 = 511 (max)
In two's complement, which is commonly used to represent integers in binary, you'll have:
000000000 = 0
000000001 = 1
...
011111110 = 254
011111111 = 255 (max)
100000000 = -256 (min) <- yay integer overflow
100000001 = -255
...
111111110 = -2
111111111 = -1
In general, with k bits you can represent 2k values. Their range will depend on the system you are using:
Unsigned: 0 to 2k-1
Signed: -2k-1 to 2k-1-1
Using no external commands:
$ FOO=( a b c ) # initialize the array
$ BAR=${FOO[@]} # create a space delimited string from array
$ BAZ=${BAR// /,} # use parameter expansion to substitute spaces with comma
$ echo $BAZ
a,b,c
Warning, it assumes elements don't have whitespaces.
Try These
Call Functions With Dynamic Names, like this:
let dynamic_func_name = 'alert';
(new Function(dynamic_func_name+'()'))()
with parameters:
let dynamic_func_name = 'alert';
let para_1 = 'HAHAHA';
let para_2 = 'ABCD';
(new Function(`${dynamic_func_name}('${para_1}','${para_2}')`))()
Run Dynamic Code:
let some_code = "alert('hahaha');";
(new Function(some_code))()
It doesn't seem anyone has addressed how to specify URLs with embedded parameters. Any URL that contains parameters it won't possible to specify the specific URL in LSApplicationsQueriesSchemes. For example, assume I have an email app that passes the the senders email address:
myemail://[email protected]
The only way it seems to get it to work in iOS9 is to remove any parameters.
If you are using TextEditingController then set the text to it, like below
TextEditingController _controller = new TextEditingController();
_controller.text = 'your initial text';
final your_text_name = TextFormField(
autofocus: false,
controller: _controller,
decoration: InputDecoration(
hintText: 'Hint Value',
),
);
and if you are not using any TextEditingController then you can directly use initialValue like below
final last_name = TextFormField(
autofocus: false,
initialValue: 'your initial text',
decoration: InputDecoration(
hintText: 'Last Name',
),
);
For more reference TextEditingController
The getRequestURL()
omits the port when it is 80 while the scheme is http
, or when it is 443 while the scheme is https
.
So, just use getRequestURL()
if all you want is obtaining the entire URL. This does however not include the GET query string. You may want to construct it as follows then:
StringBuffer requestURL = request.getRequestURL();
if (request.getQueryString() != null) {
requestURL.append("?").append(request.getQueryString());
}
String completeURL = requestURL.toString();
using, for example, "%-d" is not portable even between different versions of the same OS. A better solution would be to extract the date components individually, and choose between date specific formatting operators and date attribute access for each component.
e = datetime.date(2014, 1, 6)
"{date:%A} {date.day} {date:%B}{date.year}".format(date=e)
I've investigated A LOT on how to properly manage 404s in MVC (specifically MVC3), and this, IMHO is the best solution I've come up with:
In global.asax:
public class MvcApplication : HttpApplication
{
protected void Application_EndRequest()
{
if (Context.Response.StatusCode == 404)
{
Response.Clear();
var rd = new RouteData();
rd.DataTokens["area"] = "AreaName"; // In case controller is in another area
rd.Values["controller"] = "Errors";
rd.Values["action"] = "NotFound";
IController c = new ErrorsController();
c.Execute(new RequestContext(new HttpContextWrapper(Context), rd));
}
}
}
ErrorsController:
public sealed class ErrorsController : Controller
{
public ActionResult NotFound()
{
ActionResult result;
object model = Request.Url.PathAndQuery;
if (!Request.IsAjaxRequest())
result = View(model);
else
result = PartialView("_NotFound", model);
return result;
}
}
Edit:
If you're using IoC (e.g. AutoFac), you should create your controller using:
var rc = new RequestContext(new HttpContextWrapper(Context), rd);
var c = ControllerBuilder.Current.GetControllerFactory().CreateController(rc, "Errors");
c.Execute(rc);
Instead of
IController c = new ErrorsController();
c.Execute(new RequestContext(new HttpContextWrapper(Context), rd));
(Optional)
Explanation:
There are 6 scenarios that I can think of where an ASP.NET MVC3 apps can generate 404s.
Generated by ASP.NET:
Generated by ASP.NET MVC:
Scenario 2: URL matches a route, but specifies a controller that doesn't exist.
Scenario 3: URL matches a route, but specifies an action that doesn't exist.
Manually generated:
Scenario 4: An action returns an HttpNotFoundResult by using the method HttpNotFound().
Scenario 5: An action throws an HttpException with the status code 404.
Scenario 6: An actions manually modifies the Response.StatusCode property to 404.
Objectives
(A) Show a custom 404 error page to the user.
(B) Maintain the 404 status code on the client response (specially important for SEO).
(C) Send the response directly, without involving a 302 redirection.
Solution Attempt: Custom Errors
<system.web>
<customErrors mode="On">
<error statusCode="404" redirect="~/Errors/NotFound"/>
</customErrors>
</system.web>
Problems with this solution:
Solution Attempt: HTTP Errors
<system.webServer>
<httpErrors errorMode="Custom">
<remove statusCode="404"/>
<error statusCode="404" path="App/Errors/NotFound" responseMode="ExecuteURL"/>
</httpErrors>
</system.webServer>
Problems with this solution:
Solution Attempt: HTTP Errors with Replace
<system.webServer>
<httpErrors errorMode="Custom" existingResponse="Replace">
<remove statusCode="404"/>
<error statusCode="404" path="App/Errors/NotFound" responseMode="ExecuteURL"/>
</httpErrors>
</system.webServer>
Problems with this solution:
Solution Attempt customErrors and HTTP Errors
<system.web>
<customErrors mode="On">
<error statusCode="404" redirect="~/Errors/NotFound"/>
</customError>
</system.web>
and
<system.webServer>
<httpErrors errorMode="Custom">
<remove statusCode="404"/>
<error statusCode="404" path="App/Errors/NotFound" responseMode="ExecuteURL"/>
</httpErrors>
</system.webServer>
Problems with this solution:
People that have troubled with this before even tried to create their own libraries (see http://aboutcode.net/2011/02/26/handling-not-found-with-asp-net-mvc3.html). But the previous solution seems to cover all the scenarios without the complexity of using an external library.
If you need use React LifeCycle, you need use Class.
Sample:
import React, { Component } from 'react';
class Grid extends Component {
constructor(props){
super(props)
}
componentDidMount () { /* do something */ }
render () {
return <h1>Hello</h1>
}
}
I think this is the most reliable way to get the desktop path which isn't always the same as the username.
MsgBox CreateObject("WScript.Shell").specialfolders("Desktop")
I see a lot of complicated answers, while this is super simple in Bootstrap 3:
Step 1: Use the official example code to create your radio button group, and give the container an id:
<div id="myButtons" class="btn-group" data-toggle="buttons">
<label class="btn btn-primary active">
<input type="radio" name="options" id="option1" autocomplete="off" checked> Radio 1 (preselected)
</label>
<label class="btn btn-primary">
<input type="radio" name="options" id="option2" autocomplete="off"> Radio 2
</label>
<label class="btn btn-primary">
<input type="radio" name="options" id="option3" autocomplete="off"> Radio 3
</label>
</div>
Step 2: Use this jQuery handler:
$("#myButtons :input").change(function() {
console.log(this); // points to the clicked input button
});
You could use linq to xml.
var xmlStr = File.ReadAllText("fileName.xml");
var str = XElement.Parse(xmlStr);
var result = str.Elements("word").
Where(x => x.Element("category").Value.Equals("verb")).ToList();
Console.WriteLine(result);
Although this question is 5 years old I have come across a nice solution.
Use the 'DictionaryEntry' object to pair keys and values.
Set the 'DisplayMember' and 'ValueMember' properties to:
Me.myComboBox.DisplayMember = "Key"
Me.myComboBox.ValueMember = "Value"
To add items to the ComboBox:
Me.myComboBox.Items.Add(New DictionaryEntry("Text to be displayed", 1))
To retreive items like this:
MsgBox(Me.myComboBox.SelectedItem.Key & " " & Me.myComboBox.SelectedItem.Value)
The solution os to ad './' before the name of image before reading it...
JetBrains has a new application called the Toolbox App which quickly and easily installs any JetBrains software you want, assuming you have the license. It also manages your login once to apply across all JetBrains software, a very useful feature.
To use it, download the tar.gz file here, then extract it and run the included executable jetbrains-toolbox.
Then sign in, and press install next to IntelliJ IDEA:
If you want to move the executable to /usr/bin/
feel free, however it works fine out of the box wherever you extract it to.
This will also make the appropriate desktop entries upon install.
Just replace <div class="container">
with <div class="container-fluid">
, which is the container with no margins on both sides.
I think this is the best solution because it avoids some useless overriding and makes use of built-in classes, it's clean.
No, comments of the form //…
or /*…*/
are not allowed in JSON. This answer is based on:
application/json
Media Type for JavaScript Object Notation (JSON)If you try to add a form warping a tr element like this
<table>
<form>
<tr>
<td><input type="text"/></td>
<td><input type="submit"/></td>
</tr>
</form>
</table>
some browsers in the process of rendering will close form tag right after the declaration leaving inputs outside of the element
something like this
<table>
<form></form>
<tr>
<td><input type="text"/></td>
<td><input type="submit"/></td>
</tr>
</table>
This issue is still valid for warping multiple table cells
As stereoscott said above, nesting tables are a possible solution which is not recommended. Avoid using tables.
The _ is the same thing as x. However it's a python idiom that's used to indicate an identifier that you don't intend to use. In python these identifiers don't takes memor or allocate space like variables do in other languages. It's easy to forget that. They're just names that point to objects, in this case an integer on each iteration.
import com.google.common.collect.Lists;
List<List<T>> batches = Lists.partition(List<T>,batchSize)
Use Lists.partition(List,batchSize). You need to import Lists
from google common package (com.google.common.collect.Lists
)
It will return List of List<T>
with and the size of every element equal to your batchSize
.
Strangely, the answer is to keep adding back the property. I was half expecting a setter
method. :S
System.out.println("Before: " + obj.get("DebugLogId")); // original "02352"
obj.addProperty("DebugLogId", "YYY");
System.out.println("After: " + obj.get("DebugLogId")); // now "YYY"
http://www.markrafferty.com/wp-content/w3tc/min/7415c412.e68ae1.css
Line 11:
.postItem img {
height: auto;
width: 450px;
}
You can either edit your CSS, or you can listen to Mageek and use INLINE STYLING to override the CSS styling that's happening:
<img src="theSource" style="width:30px;" />
Avoid setting both width and height, as the image itself might not be scaled proportionally. But you can set the dimensions to whatever you want, as per Mageek's example.
Since 0.11 hive has a NVL function
nvl(T value, T default_value)
which says Returns default value if value is null else returns value
Based on @markhellewell answer I created a couple of alias functions that will do it for you. Just add these to your shell startup file
#list available jdks
alias jdks="/usr/libexec/java_home -V"
# jdk version switching - e.g. `jdk 6` will switch to version 1.6
function jdk() {
echo "Switching java version";
export JAVA_HOME=`/usr/libexec/java_home -v 1.$1`;
java -version;
}
https://gist.github.com/Noyabronok/0a90e1f3c52d1aaa941013d3caa8d0e4
Try to create script with ADD
command and specification of working directory
Like this("script" is the name of script and /root/script.sh
is where you want it in the container, it can be different path:
ADD script.sh /root/script.sh
In this case ADD
has to come before CMD
, if you have one
BTW it's cool way to import scripts to any location in container from host machine
In CMD
place [./script]
It should automatically execute your script
You can also specify WORKDIR
as /root
, then you'l be automatically placed in root, upon starting a container
find . -type f |
sed -n "s/\(.*\)factory\.py$/& \1service\.py/p" |
xargs -p -n 2 mv
eg will rename all files in the cwd with names ending in "factory.py" to be replaced with names ending in "service.py"
explanation:
1) in the sed cmd, the -n flag will suppress normal behavior of echoing input to output after the s/// command is applied, and the p option on s/// will force writing to output if a substitution is made. since a sub will only be made on match, sed will only have output for files ending in "factory.py"
2) in the s/// replacement string, we use "& " to interpolate the entire matching string, followed by a space character, into the replacement. because of this, it's vital that our RE matches the entire filename. after the space char, we use "\1service.py" to interpolate the string we gulped before "factory.py", followed by "service.py", replacing it. So for more complex transformations youll have to change the args to s/// (with an re still matching the entire filename)
example output:
foo_factory.py foo_service.py
bar_factory.py bar_service.py
3) we use xargs with -n 2 to consume the output of sed 2 delimited strings at a time, passing these to mv (i also put the -p option in there so you can feel safe when running this). voila.
You can do this:
satView.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
}
}
);
Note the extra comments.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
class JavaPaintUI extends JFrame {
private int tool = 1;
int currentX, currentY, oldX, oldY;
public JavaPaintUI() {
initComponents();
}
private void initComponents() {
// we want a custom Panel2, not a generic JPanel!
jPanel2 = new Panel2();
jPanel2.setBackground(new java.awt.Color(255, 255, 255));
jPanel2.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
jPanel2.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent evt) {
jPanel2MousePressed(evt);
}
public void mouseReleased(MouseEvent evt) {
jPanel2MouseReleased(evt);
}
});
jPanel2.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent evt) {
jPanel2MouseDragged(evt);
}
});
// add the component to the frame to see it!
this.setContentPane(jPanel2);
// be nice to testers..
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
}// </editor-fold>
private void jPanel2MouseDragged(MouseEvent evt) {
if (tool == 1) {
currentX = evt.getX();
currentY = evt.getY();
oldX = currentX;
oldY = currentY;
System.out.println(currentX + " " + currentY);
System.out.println("PEN!!!!");
}
}
private void jPanel2MousePressed(MouseEvent evt) {
oldX = evt.getX();
oldY = evt.getY();
System.out.println(oldX + " " + oldY);
}
//mouse released//
private void jPanel2MouseReleased(MouseEvent evt) {
if (tool == 2) {
currentX = evt.getX();
currentY = evt.getY();
System.out.println("line!!!! from" + oldX + "to" + currentX);
}
}
//set ui visible//
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new JavaPaintUI().setVisible(true);
}
});
}
// Variables declaration - do not modify
private JPanel jPanel2;
// End of variables declaration
// This class name is very confusing, since it is also used as the
// name of an attribute!
//class jPanel2 extends JPanel {
class Panel2 extends JPanel {
Panel2() {
// set a preferred size for the custom panel.
setPreferredSize(new Dimension(420,420));
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString("BLAH", 20, 20);
g.drawRect(200, 200, 200, 200);
}
}
}
HFOE put a good link as the first comment on this thread. Camickr also has a description of active painting vs. drawing to a BufferedImage
in the Custom Painting Approaches article.
See also this approach using painting in a BufferedImage
.
UPDATE: you don't need to convert your values afterwards, you can do it on-the-fly when reading your CSV:
In [165]: df=pd.read_csv(url, index_col=0, na_values=['(NA)']).fillna(0)
In [166]: df.dtypes
Out[166]:
GeoName object
ComponentName object
IndustryId int64
IndustryClassification object
Description object
2004 int64
2005 int64
2006 int64
2007 int64
2008 int64
2009 int64
2010 int64
2011 int64
2012 int64
2013 int64
2014 float64
dtype: object
If you need to convert multiple columns to numeric dtypes - use the following technique:
Sample source DF:
In [271]: df
Out[271]:
id a b c d e f
0 id_3 AAA 6 3 5 8 1
1 id_9 3 7 5 7 3 BBB
2 id_7 4 2 3 5 4 2
3 id_0 7 3 5 7 9 4
4 id_0 2 4 6 4 0 2
In [272]: df.dtypes
Out[272]:
id object
a object
b int64
c int64
d int64
e int64
f object
dtype: object
Converting selected columns to numeric dtypes:
In [273]: cols = df.columns.drop('id')
In [274]: df[cols] = df[cols].apply(pd.to_numeric, errors='coerce')
In [275]: df
Out[275]:
id a b c d e f
0 id_3 NaN 6 3 5 8 1.0
1 id_9 3.0 7 5 7 3 NaN
2 id_7 4.0 2 3 5 4 2.0
3 id_0 7.0 3 5 7 9 4.0
4 id_0 2.0 4 6 4 0 2.0
In [276]: df.dtypes
Out[276]:
id object
a float64
b int64
c int64
d int64
e int64
f float64
dtype: object
PS if you want to select all string
(object
) columns use the following simple trick:
cols = df.columns[df.dtypes.eq('object')]
As of IE11, you need to use addEventListener
. attachEvent
is deprecated and throws an error.
If you only need the value:
$result = mysql_query("SELECT count(*) from Students;");
echo mysql_result($result, 0);
I've forked a CodePen demo that had the same problem with embedding inline SVG into CSS. A solution that works with SCSS is to build a simple url-encoding function.
A string replacement function can be created from the built-in str-slice, str-index functions (see css-tricks, thanks to Hugo Giraudel).
Then, just replace %
,<
,>
,"
,'
, with the
%xx
codes:
@function svg-inline($string){
$result: str-replace($string, "<svg", "<svg xmlns='http://www.w3.org/2000/svg'");
$result: str-replace($result, '%', '%25');
$result: str-replace($result, '"', '%22');
$result: str-replace($result, "'", '%27');
$result: str-replace($result, ' ', '%20');
$result: str-replace($result, '<', '%3C');
$result: str-replace($result, '>', '%3E');
@return "data:image/svg+xml;utf8," + $result;
}
$mySVG: svg-inline("<svg>...</svg>");
html {
height: 100vh;
background: url($mySVG) 50% no-repeat;
}
There is also a image-inline
helper function available in Compass, but since it is not supported in CodePen, this solution might probably be useful.
Demo on CodePen: http://codepen.io/terabaud/details/PZdaJo/
As mentioned above, a[::-1]
really only creates a view, so it's a constant-time operation (and as such doesn't take longer as the array grows). If you need the array to be contiguous (for example because you're performing many vector operations with it), ascontiguousarray
is about as fast as flipud
/fliplr
:
Code to generate the plot:
import numpy
import perfplot
perfplot.show(
setup=lambda n: numpy.random.randint(0, 1000, n),
kernels=[
lambda a: a[::-1],
lambda a: numpy.ascontiguousarray(a[::-1]),
lambda a: numpy.fliplr([a])[0],
],
labels=["a[::-1]", "ascontiguousarray(a[::-1])", "fliplr"],
n_range=[2 ** k for k in range(25)],
xlabel="len(a)",
)
In most cases, when you find yourself using forEach
on a Stream, you should rethink whether you are using the right tool for your job or whether you are using it the right way.
Generally, you should look for an appropriate terminal operation doing what you want to achieve or for an appropriate Collector. Now, there are Collectors for producing Map
s and List
s, but no out of-the-box collector for combining two different collectors, based on a predicate.
Now, this answer contains a collector for combining two collectors. Using this collector, you can achieve the task as
Pair<Map<KeyType, Animal>, List<KeyType>> pair = animalMap.entrySet().stream()
.collect(conditional(entry -> entry.getValue() != null,
Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue),
Collectors.mapping(Map.Entry::getKey, Collectors.toList()) ));
Map<KeyType,Animal> myMap = pair.a;
List<KeyType> myList = pair.b;
But maybe, you can solve this specific task in a simpler way. One of you results matches the input type; it’s the same map just stripped off the entries which map to null
. If your original map is mutable and you don’t need it afterwards, you can just collect the list and remove these keys from the original map as they are mutually exclusive:
List<KeyType> myList=animalMap.entrySet().stream()
.filter(pair -> pair.getValue() == null)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
animalMap.keySet().removeAll(myList);
Note that you can remove mappings to null
even without having the list of the other keys:
animalMap.values().removeIf(Objects::isNull);
or
animalMap.values().removeAll(Collections.singleton(null));
If you can’t (or don’t want to) modify the original map, there is still a solution without a custom collector. As hinted in Alexis C.’s answer, partitioningBy
is going into the right direction, but you may simplify it:
Map<Boolean,Map<KeyType,Animal>> tmp = animalMap.entrySet().stream()
.collect(Collectors.partitioningBy(pair -> pair.getValue() != null,
Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)));
Map<KeyType,Animal> myMap = tmp.get(true);
List<KeyType> myList = new ArrayList<>(tmp.get(false).keySet());
The bottom line is, don’t forget about ordinary Collection operations, you don’t have to do everything with the new Stream API.
From the 18.03 docs:
I want to connect from a container to a service on the host
The host has a changing IP address (or none if you have no network access). From 18.03 onwards our recommendation is to connect to the special DNS name
host.docker.internal
, which resolves to the internal IP address used by the host.The gateway is also reachable as
gateway.docker.internal
.
EXAMPLE: Here's what I use for my MySQL connection string inside my container to access the MySQL instance on my host:
mysql://host.docker.internal:3306/my_awesome_database
In the second image it looks like you want the image to fill the box, but the example you created DOES keep the aspect ratio (the pets look normal, not slim or fat).
I have no clue if you photoshopped those images as example or the second one is "how it should be" as well (you said IS, while the first example you said "should")
Anyway, I have to assume:
If "the images are not resized keeping the aspect ration" and you show me an image which DOES keep the aspect ratio of the pixels, I have to assume you are trying to accomplish the aspect ratio of the "cropping" area (the inner of the green) WILE keeping the aspect ratio of the pixels. I.e. you want to fill the cell with the image, by enlarging and cropping the image.
If that's your problem, the code you provided does NOT reflect "your problem", but your starting example.
Given the previous two assumptions, what you need can't be accomplished with actual images if the height of the box is dynamic, but with background images. Either by using "background-size: contain" or these techniques (smart paddings in percents that limit the cropping or max sizes anywhere you want): http://fofwebdesign.co.uk/template/_testing/scale-img/scale-img.htm
The only way this is possible with images is if we FORGET about your second iimage, and the cells have a fixed height, and FORTUNATELY, judging by your sample images, the height stays the same!
So if your container's height doesn't change, and you want to keep your images square, you just have to set the max-height of the images to that known value (minus paddings or borders, depending on the box-sizing property of the cells)
Like this:
<div class="content">
<div class="row">
<div class="cell">
<img src="http://lorempixel.com/output/people-q-c-320-320-2.jpg"/>
</div>
<div class="cell">
<img src="http://lorempixel.com/output/people-q-c-320-320-7.jpg"/>
</div>
</div>
</div>
And the CSS:
.content {
background-color: green;
}
.row {
display: -webkit-box;
display: -moz-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
-webkit-box-orient: horizontal;
-moz-box-orient: horizontal;
box-orient: horizontal;
flex-direction: row;
-webkit-box-pack: center;
-moz-box-pack: center;
box-pack: center;
justify-content: center;
-webkit-box-align: center;
-moz-box-align: center;
box-align: center;
align-items: center;
}
.cell {
-webkit-box-flex: 1;
-moz-box-flex: 1;
box-flex: 1;
-webkit-flex: 1 1 auto;
flex: 1 1 auto;
padding: 10px;
border: solid 10px red;
text-align: center;
height: 300px;
display: flex;
align-items: center;
box-sizing: content-box;
}
img {
margin: auto;
width: 100%;
max-width: 300px;
max-height:100%
}
Your code is invalid (opening tags are instead of closing ones, so they output NESTED cells, not siblings, he used a SCREENSHOT of your images inside the faulty code, and the flex box is not holding the cells but both examples in a column (you setup "row" but the corrupt code nesting one cell inside the other resulted in a flex inside a flex, finally working as COLUMNS. I have no idea what you wanted to accomplish, and how you came up with that code, but I'm guessing what you want is this.
I added display: flex to the cells too, so the image gets centered (I think display: table
could have been used here as well with all this markup)
A more "C++"ish version
#include <iostream>
#include <sstream>
#include "openssl/sha.h"
using namespace std;
string to_hex(unsigned char s) {
stringstream ss;
ss << hex << (int) s;
return ss.str();
}
string sha256(string line) {
unsigned char hash[SHA256_DIGEST_LENGTH];
SHA256_CTX sha256;
SHA256_Init(&sha256);
SHA256_Update(&sha256, line.c_str(), line.length());
SHA256_Final(hash, &sha256);
string output = "";
for(int i = 0; i < SHA256_DIGEST_LENGTH; i++) {
output += to_hex(hash[i]);
}
return output;
}
int main() {
cout << sha256("hello, world") << endl;
return 0;
}