You should check out this plugin:
https://github.com/kemayo/maphilight
and the demo:
http://davidlynch.org/js/maphilight/docs/demo_usa.html
if anything, you might be able to borrow some code from it to fix yours.
I'm 99% sure that RollingFileAppender/DailyRollingFileAppender, while it gives you the date-rolling functionality you want, doesn't have any way to specify that the current log file should use the DatePattern
as well.
You might just be able to simply subclass RollingFileAppender (or DailyRollingFileAppender, I forget which is which in log4net) and modify the naming logic.
Try doing: INSERT INTO table(data, date) VALUES ('$data', now() + interval 1 day)
There is a "3 of 9"
control on CodeProject: Barcode .NET Control
use
doesn't include anything. It just imports the specified namespace (or class) to the current scope
If you want the classes to be autoloaded - read about autoloading
Dirk has explained how to plot the density function over the histogram. But sometimes you might want to go with the stronger assumption of a skewed normal distribution and plot that instead of density. You can estimate the parameters of the distribution and plot it using the sn package:
> sn.mle(y=c(rep(65, times=5), rep(25, times=5), rep(35, times=10), rep(45, times=4)))
$call
sn.mle(y = c(rep(65, times = 5), rep(25, times = 5), rep(35,
times = 10), rep(45, times = 4)))
$cp
mean s.d. skewness
41.46228 12.47892 0.99527
This probably works better on data that is more skew-normal:
A couple of things to note:
If you want it to be treated as a proper ASP.NET postback, you can call the methods supplied by the framework, namely __doPostBack(eventTarget, eventArgument)
:
<div name="mysubmitbutton" id="mysubmitbutton" class="customButton"
onclick="javascript:__doPostBack('<%=mysubmitbutton.ClientID %>', 'MyCustomArgument');">
Button Text
</div>
URL url = new URL("http://image10.bizrate-images.com/resize?sq=60&uid=2216744464");
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
imageView.setImageBitmap(bmp);
Seems like kind of a homely way of doing things, but if you must... you could restructure it as such to fit your needs:
boolean found = false;
case 1:
for (Element arrayItem : array) {
if (arrayItem == whateverValue) {
found = true;
} // else if ...
}
if (found) {
break;
}
case 2:
Short and sweet. Call an external program:
using System.Diagnostics;
void Shutdown()
{
Process.Start("shutdown.exe", "-s -t 00");
}
Note: This calls Windows' Shutdown.exe program, so it'll only work if that program is available. You might have problems on Windows 2000 (where shutdown.exe is only available in the resource kit) or XP Embedded.
I have had some problems in Swift 5 with this. When using this function I had a wrong alignment with the header cell:
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerCell = tableView.dequeueReusableCell(withIdentifier: "customTableCell") as! CustomTableCell
return headerCell
}
The cell view was shown with a bad alignment and the top part of the tableview was shown. So I had to make some tweak like this:
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = UIView.init(frame: CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: 90))
let headerCell = tableView.dequeueReusableCell(withIdentifier: "YOUR_CELL_IDENTIFIER")
headerCell?.frame = headerView.bounds
headerView.addSubview(headerCell!)
return headerView
}
I am having this problem in Swift 5 and Xcode 12.0.1, I don't know if it is just a problem for me or it is a bug. Hope it helps ! I have lost a morning...
change database collation:
ALTER DATABASE <database_name> CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;
change table collation:
ALTER TABLE <table_name> CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;
change column collation:
ALTER TABLE <table_name> MODIFY <column_name> VARCHAR(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;
utf8mb4_0900_ai_ci
mean?3 bytes -- utf8
4 bytes -- utf8mb4 (new)
v4.0 -- _unicode_
v5.20 -- _unicode_520_
v9.0 -- _0900_ (new)
_bin -- just compare the bits; don't consider case folding, accents, etc
_ci -- explicitly case insensitive (A=a) and implicitly accent insensitive (a=á)
_ai_ci -- explicitly case insensitive and accent insensitive
_as (etc) -- accent-sensitive (etc)
_bin -- simple, fast
_general_ci -- fails to compare multiple letters; eg ss=ß, somewhat fast
... -- slower
_0900_ -- (8.0) much faster because of a rewrite
More info:
Just to round out Reed's answer, you can either get the Button
objects from the Form
or other container and add the handler, or you could create the Button
objects programmatically.
If you get the Button
objects from the Form
or other container, then you can iterate over the Controls
collection of the Form
or other container control, such as Panel
or FlowLayoutPanel
and so on. You can then just add the click handler with
AddHandler ctrl.Click, AddressOf Me.Button_Click
(variables as in the code below),
but I prefer to check the type of the Control
and cast to a Button
so as I'm not adding click handlers for any other controls in the container (such as Labels). Remember that you can add handlers for any event of the Button
at this point using AddHandler
.
Alternatively, you can create the Button
objects programmatically, as in the second block of code below.
Then, of course, you have to write the handler method, as in the third code block below.
Here is an example using Form
as the container, but you're probably better off using a Panel
or some other container control.
Dim btn as Button = Nothing
For Each ctrl As Control in myForm.Controls
If TypeOf ctrl Is Button Then
btn = DirectCast(ctrl, Button)
AddHandler btn.Click, AddressOf Me.Button_Click ' From answer by Reed.
End If
Next
Alternatively creating the Button
s programmatically, this time adding to a Panel
container.
Dim Panel1 As new Panel()
For i As Integer = 1 to 100
btn = New Button()
' Set Button properties or call a method to do so.
Panel1.Controls.Add(btn) ' Add Button to the container.
AddHandler btn.Click, AddressOf Me.Button_Click ' Again from the answer by Reed.
Next
Then your handler will look something like this
Private Sub Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
' Handle your Button clicks here
End Sub
For anyone still having the problem. You could use official Microsoft SMO
using (var connection = new SqlConnection(connectionString))
{
var server = new Server(new ServerConnection(connection));
server.ConnectionContext.ExecuteNonQuery(sql);
}
You have enabled CORS and enabled Access-Control-Allow-Origin : *
in the server.If still you get GET
method working and POST
method is not working then it might be because of the problem of Content-Type
and data
problem.
First AngularJS transmits data using Content-Type: application/json
which is not serialized natively by some of the web servers (notably PHP). For them we have to transmit the data as Content-Type: x-www-form-urlencoded
Example :-
$scope.formLoginPost = function () {
$http({
url: url,
method: "POST",
data: $.param({ 'username': $scope.username, 'Password': $scope.Password }),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function (response) {
// success
console.log('success');
console.log("then : " + JSON.stringify(response));
}, function (response) { // optional
// failed
console.log('failed');
console.log(JSON.stringify(response));
});
};
Note : I am using $.params
to serialize the data to use Content-Type: x-www-form-urlencoded
. Alternatively you can use the following javascript function
function params(obj){
var str = "";
for (var key in obj) {
if (str != "") {
str += "&";
}
str += key + "=" + encodeURIComponent(obj[key]);
}
return str;
}
and use params({ 'username': $scope.username, 'Password': $scope.Password })
to serialize it as the Content-Type: x-www-form-urlencoded
requests only gets the POST data in username=john&Password=12345
form.
This is my working code. you may try with this.
row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/listEmployeeDetails"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:layout_gravity="center"
android:background="#ffffff">
<TextView android:id="@+id/tvEmpId"
android:layout_height="wrap_content"
android:textSize="12sp"
android:padding="2dp"
android:layout_width="0dp"
android:layout_weight="0.3"/>
<TextView android:id="@+id/tvNameEmp"
android:layout_height="wrap_content"
android:textSize="12sp"
android:padding="2dp"
android:layout_width="0dp"
android:layout_weight="0.5"/>
<TextView
android:layout_height="wrap_content"
android:id="@+id/tvStatusEmp"
android:textSize="12sp"
android:padding="2dp"
android:layout_width="0dp"
android:layout_weight="0.2"/>
</LinearLayout>
details.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/listEmployeeDetails"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@color/page_bg"
android:orientation="vertical" >
<LinearLayout
android:id="@+id/lLayoutGrid"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/page_bg"
android:orientation="vertical" >
................... others components here............................
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:alwaysDrawnWithCache="true"
android:dividerHeight="1dp"
android:horizontalSpacing="3dp"
android:scrollingCache="true"
android:smoothScrollbar="true"
android:stretchMode="columnWidth"
android:verticalSpacing="3dp"
android:layout_marginBottom="30dp">
</ListView>
</LinearLayout>
</RelativeLayout>
Adapter class :
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class ListViewAdapter extends BaseAdapter {
private Context context;
private List<EmployeeBean> employeeList;
publicListViewAdapter(Context context, List<EmployeeBean> employeeList) {
this.context = context;
this.employeeList = employeeList;
}
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
EmployeeBeanHolder holder = null;
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(R.layout.row, parent, false);
holder = new EmployeeBeanHolder();
holder.employeeBean = employeeList.get(position);
holder.tvEmpId = (TextView) row.findViewById(R.id.tvEmpId);
holder.tvName = (TextView) row.findViewById(R.id.tvNameEmp);
holder.tvStatus = (TextView) row.findViewById(R.id.tvStatusEmp);
row.setTag(holder);
holder.tvEmpId.setText(holder.employeeBean.getEmpId());
holder.tvName.setText(holder.employeeBean.getName());
holder.tvStatus.setText(holder.employeeBean.getStatus());
if (position % 2 == 0) {
row.setBackgroundColor(Color.rgb(213, 229, 241));
} else {
row.setBackgroundColor(Color.rgb(255, 255, 255));
}
return row;
}
public static class EmployeeBeanHolder {
EmployeeBean employeeBean;
TextView tvEmpId;
TextView tvName;
TextView tvStatus;
}
@Override
public int getCount() {
return employeeList.size();
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
}
employee bean class:
public class EmployeeBean {
private String empId;
private String name;
private String status;
public EmployeeBean(){
}
public EmployeeBean(String empId, String name, String status) {
this.empId= empId;
this.name = name;
this.status = status;
}
public String getEmpId() {
return empId;
}
public void setEmpId(String empId) {
this.empId= empId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status =status;
}
}
in Activity class:
onCreate method:
public static List<EmployeeBean> EMPLOYEE_LIST = new ArrayList<EmployeeBean>();
//create emplyee data
for(int i=0;i<=10;i++) {
EmployeeBean emplyee = new EmployeeBean("EmpId"+i,"Name "+i, "Active");
EMPLOYEE_LIST .add(emplyee );
}
ListView listView;
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(new ListViewAdapter(this, EMPLOYEE_LIST));
You can use download.js (https://github.com/rndme/download and http://danml.com/download.html). If the file is in an external URL, you must make an Ajax request, but if it is not, then you can use the function:
download(Path, name, mime)
Read their documentation for more details in the GitHub.
Or you could try:
propertyInfo.SetValue(ship, Convert.ChangeType(value, propertyInfo.PropertyType), null);
//But this will cause problems if your string value IsNullOrEmplty...
Hard to find a clear answer from the Oracle site. The following is from javax.ws.rs.core.HttpHeaders.java
:
/**
* See {@link <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1">HTTP/1.1 documentation</a>}.
*/
public static final String ACCEPT = "Accept";
/**
* See {@link <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.2">HTTP/1.1 documentation</a>}.
*/
public static final String ACCEPT_CHARSET = "Accept-Charset";
Open Anaconda Prompt (base):
conda update -n base -c defaults conda
conda create -n python38 python=3.8
conda activate python38
python
The original question wants XYZ/ABC/(*files) to become ABC/ABC/(*files). After implementing the accepted answer for my own code, I noticed that it actually changes XYZ/ABC/(*files) into ABC/(*files). The filter-branch man page even says,
The result will contain that directory (and only that) as its project root."
In other words, it promotes the top-level folder "up" one level. That's an important distinction because, for example, in my history I had renamed a top-level folder. By promoting folders "up" one level, git loses continuity at the commit where I did the rename.
My answer to the question then is to make 2 copies of the repository and manually delete the folder(s) you want to keep in each. The man page backs me up with this:
[...] avoid using [this command] if a simple single commit would suffice to fix your problem
I came across this problem on Windows too. The solution for me was to switch from a 32-bit to a 64-bit version of Python. Indeed, a 32-bit software, like a 32-bit CPU, can adress a maximum of 4 GB of RAM (2^32). So if you have more than 4 GB of RAM, a 32-bit version cannot take advantage of it.
With a 64-bit version of Python (the one labeled x86-64 in the download page), the issue disappeared.
You can check which version you have by entering the interpreter. I, with a 64-bit version, now have:
Python 3.7.5rc1 (tags/v3.7.5rc1:4082f600a5, Oct 1 2019, 20:28:14) [MSC v.1916 64 bit (AMD64)]
, where [MSC v.1916 64 bit (AMD64)] means "64-bit Python".
Note : as of the time of this writing (May 2020), matplotlib is not available on python39, so I recommand installing python37, 64 bits.
Sources :
Unfortunately I find none of the existing answers particularly satisfying.
Here is a straightforward and complete Python 3 solution, using the csv module.
import csv
with open('../resources/temp_in.csv', newline='') as f:
reader = csv.reader(f, skipinitialspace=True)
rows = list(reader)
print(rows)
Notice the skipinitialspace=True
argument. This is necessary since, unfortunately, OP's CSV contains whitespace after each comma.
Output:
[['This is the first line', 'Line1'], ['This is the second line', 'Line2'], ['This is the third line', 'Line3']]
I tried Dave Ward's solution. The data part was not being sent from the browser in the payload part of the post request as the contentType is set to "application/json"
. Once I removed this line everything worked great.
var markers = [{ "position": "128.3657142857143", "markerPosition": "7" },
{ "position": "235.1944023323615", "markerPosition": "19" },
{ "position": "42.5978231292517", "markerPosition": "-3" }];
$.ajax({
type: "POST",
url: "/webservices/PodcastService.asmx/CreateMarkers",
// The key needs to match your method's input parameter (case-sensitive).
data: JSON.stringify({ Markers: markers }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){alert(data);},
failure: function(errMsg) {
alert(errMsg);
}
});
You have to use setOnItemClickListener
someone said.
The code should be like this:
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// When clicked, show a toast with the TextView text or do whatever you need.
Toast.makeText(getApplicationContext(), ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});
In Eclipse, eventually I had to add Compatibility/Support Library by right-clicking on my project and selecting:
Android Tools -> Add Support Library
Once it was added, then I was able to use LocalBroadcastManager
class in my code.
You could also check my md5 implementation. It should be approx. the same as the other posted above. Unfortunately, the performance is limited by the inner loop which is impossible to optimize more.
You can also use Gson to convert an object to a JSONObject and pass it on bundle. For me was the most elegant way I found to do this. I haven't tested how it affects performance.
In Initial Activity
Intent activity = new Intent(MyActivity.this,NextActivity.class);
activity.putExtra("myObject", new Gson().toJson(myobject));
startActivity(activity);
In Next Activity
String jsonMyObject;
Bundle extras = getIntent().getExtras();
if (extras != null) {
jsonMyObject = extras.getString("myObject");
}
MyObject myObject = new Gson().fromJson(jsonMyObject, MyObject.class);
The explanation from Scott Meyers in Effective C++ might help understand when to use them:
Public inheritance should model "is-a relationship," whereas private inheritance should be used for "is-implemented-in-terms-of" - so you don't have to adhere to the interface of the superclass, you're just reusing the implementation.
A great way of doing this on WordPress consists of the following steps:
Step 1: Open your Jupyter notebook in a text editor and copy the content which may look like so: Your .ipynb file may look like this when opened in a text editor
Step 2: Ctrl + A and Ctrl + C this content. Then Ctrl + V this to a GitHub Gist that you should create.
Step 3: Create a public gist and embed the gist like you always embed gists on WordPress, viz., go to the HTML editor and add like so:
[gist gist_url]
I have actually implemented this on my blog. You can find the post here
You will have to use javascript, or the JQuery framework to do that. her is an example using Jquery
$('#toggle').click(function () {
//check if checkbox is checked
if ($(this).is(':checked')) {
$('#sendNewSms').removeAttr('disabled'); //enable input
} else {
$('#sendNewSms').attr('disabled', true); //disable input
}
});
I used the same method mentioned by @S-T after the pip uninstall command. And even after that the I got the message that Django was already installed. So i deleted the 'Django-1.7.6.egg-info' folder from '/usr/lib/python2.7/dist-packages' and then it worked for me.
You can just pass a list of the two points you want to connect to plt.plot
. To make this easily expandable to as many points as you want, you could define a function like so.
import matplotlib.pyplot as plt
x=[-1 ,0.5 ,1,-0.5]
y=[ 0.5, 1, -0.5, -1]
plt.plot(x,y, 'ro')
def connectpoints(x,y,p1,p2):
x1, x2 = x[p1], x[p2]
y1, y2 = y[p1], y[p2]
plt.plot([x1,x2],[y1,y2],'k-')
connectpoints(x,y,0,1)
connectpoints(x,y,2,3)
plt.axis('equal')
plt.show()
Note, that function is a general function that can connect any two points in your list together.
To expand this to 2N points, assuming you always connect point i
to point i+1
, we can just put it in a for loop:
import numpy as np
for i in np.arange(0,len(x),2):
connectpoints(x,y,i,i+1)
In that case of always connecting point i
to point i+1
, you could simply do:
for i in np.arange(0,len(x),2):
plt.plot(x[i:i+2],y[i:i+2],'k-')
Just update your eclipse.ini file (you can find it in the root-directory of eclipse) by this:
-vm
path/javaw.exe
for example:
-vm
C:/Program Files/Java/jdk1.7.0_09/jre/bin/javaw.exe
Open a new worksheet on the related instance (Alt-F10)
and run the following query
SELECT view_name, owner
FROM sys.all_views
ORDER BY owner, view_name
I tried the solution of Oskar (and many others) but for me it finaly only worked with:
jQuery(function($){
// Your jQuery code here, using the $
});
See: https://learn.jquery.com/using-jquery-core/avoid-conflicts-other-libraries/
Actually, you just have to use the LIKE operator.
SELECT * FROM mytable WHERE mytextfield LIKE ''
on Jupyter notebook, try this:
pwd #this shows the current directory
if this is not the directory you like and you would like to change, try this:
import os
os.chdir ('THIS SHOULD BE YOUR DESIRED DIRECTORY')
Then try pwd again to see if the directory is what you want.
It works for me.
You can do this easily by adding a Timer to your form (from the designer) and setting it's Tick-function to run your isonline-function.
A pure javascript solution (without jQuery
):
const SEARCH_DELAY = 100; // in ms
// it may run indefinitely. TODO: make it cancellable, using Promise's `reject`
function waitForElementToBeAdded(cssSelector) {
return new Promise((resolve) => {
const interval = setInterval(() => {
if (element = document.querySelector(cssSelector)) {
clearInterval(interval);
resolve(element);
}
}, SEARCH_DELAY);
});
}
console.log(await waitForElementToBeAdded('#main'));
Have a look at File > Preferences > Keyboard Shortcuts (or Ctrl+K Ctrl+S)
Search for cursorColumnSelectDown
or cursorColumnSelectUp
which will give you the relevent keyboard shortcut. For me it is Shift+Alt+Down/Up Arrow
Change ng-disabled="!contractTypeValid"
to [disabled]="!contractTypeValid"
This is just namespacing. Look at the examples for reference - you need to either use the namespaced class or reference it absolutely, for example:
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
//Load composer's autoloader
require 'vendor/autoload.php';
Check out the documentation on MSDN for the Hashtable class.
Represents a collection of key-and-value pairs that are organized based on the hash code of the key.
Also, keep in mind that this is not thread-safe.
You can check out this plugin that tries to solve the problem. It is based on the same approach as described by missemisa and Alastair etc, but uses a hidden iframe instead.
Back references can find interesting solutions here. This regex:
([a-z]+).*(\1)
will find the longest repeated sequence.
This one will find a sequence of 3 letters that is repeated:
([a-z]{3}).*(\1)
Full validation example with javascript:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Radio button: full validation example with javascript</title>
<script>
function send() {
var genders = document.getElementsByName("gender");
if (genders[0].checked == true) {
alert("Your gender is male");
} else if (genders[1].checked == true) {
alert("Your gender is female");
} else {
// no checked
var msg = '<span style="color:red;">You must select your gender!</span><br /><br />';
document.getElementById('msg').innerHTML = msg;
return false;
}
return true;
}
function reset_msg() {
document.getElementById('msg').innerHTML = '';
}
</script>
</head>
<body>
<form action="" method="POST">
<label>Gender:</label>
<br />
<input type="radio" name="gender" value="m" onclick="reset_msg();" />Male
<br />
<input type="radio" name="gender" value="f" onclick="reset_msg();" />Female
<br />
<div id="msg"></div>
<input type="submit" value="send>>" onclick="return send();" />
</form>
</body>
</html>
Regards,
Fernando
The first solution, with keeping the state in parent component, is the correct one. However, for more complex problems, you should think about some state management library, redux is the most popular one used with react.
if your int variable is declared as a class level variable (instance variable) it would be defaulted to 0. But that does not indicate if the value sent from the client was 0 or a null. may be you could have a setter method which could be called to initialize/set the value sent by the client. then you can define your indicator value , may be a some negative value to indicate the null..
I incurred this error once.
It turns out I had named my program ProgramMame.ccp instead of ProgramName.cpp
easy to do ...
Hope this may help
My advice is to stick to rule 0 and not redo what standard libraries already do, if this is enough. Look at math.h (cmath in standard C++) and functions frexp, frexpf, frexpl, that break a floating point value (double, float, or long double) in its significand and exponent part. To extract the sign from the significand you can use signbit, also in math.h / cmath, or copysign (only C++11). Some alternatives, with slighter different semantics, are modf and ilogb/scalbn, available in C++11; http://en.cppreference.com/w/cpp/numeric/math/logb compares them, but I didn't find in the documentation how all these functions behave with +/-inf and NaNs. Finally, if you really want to use bitmasks (e.g., you desperately need to know the exact bits, and your program may have different NaNs with different representations, and you don't trust the above functions), at least make everything platform-independent by using the macros in float.h/cfloat.
I read this question looking for an answer, and didn't like any of them.
So I wrote a quick and dirty solution. Just put this somewhere on your sys.path, and it'll add any directory under folder
(from the current working directory), or under abspath
:
#using.py
import sys, os.path
def all_from(folder='', abspath=None):
"""add all dirs under `folder` to sys.path if any .py files are found.
Use an abspath if you'd rather do it that way.
Uses the current working directory as the location of using.py.
Keep in mind that os.walk goes *all the way* down the directory tree.
With that, try not to use this on something too close to '/'
"""
add = set(sys.path)
if abspath is None:
cwd = os.path.abspath(os.path.curdir)
abspath = os.path.join(cwd, folder)
for root, dirs, files in os.walk(abspath):
for f in files:
if f[-3:] in '.py':
add.add(root)
break
for i in add: sys.path.append(i)
>>> import using, sys, pprint
>>> using.all_from('py') #if in ~, /home/user/py/
>>> pprint.pprint(sys.path)
[
#that was easy
]
And I like it because I can have a folder for some random tools and not have them be a part of packages or anything, and still get access to some (or all) of them in a couple lines of code.
You need to perform two steps -
git remote remove origin
git remote add origin [email protected]:NuggetAI/nugget.git
Notice the Git URL is a SSH URL and not an HTTPS URL... Which you can select from here:
Based on Daniel's answer, I think I've got something that works:
^(.(?!test))*$
The key is that you need to make the negative assertion on every character in the string
jQuery.each
is just looping over the array, it doesn't do anything with the return value?. You are looking for jQuery.map
(I also think that get()
is unnecessary as you are not dealing with jQuery objects):
var blkstr = $.map(value, function(val,index) {
var str = index + ":" + val;
return str;
}).join(", ");
But why use jQuery at all in this case? map
only introduces an unnecessary function call per element.
var values = [];
for(var i = 0, l = value.length; i < l; i++) {
values.push(i + ':' + value[i]);
}
// or if you actually have an object:
for(var id in value) {
if(value.hasOwnProperty(id)) {
values.push(id + ':' + value[id]);
}
}
var blkstr = values.join(', ');
?: It only uses the return value whether it should continue to loop over the elements or not. Returning a "falsy" value will stop the loop.
When using a string-typed variable in PHP containing a date, the variable must be enclosed in single quotes:
$NEW_DATE = '1997-07-15';
$sql = "INSERT INTO tbl (NEW_DATE, ...) VALUES ('$NEW_DATE', ...)";
You have a JSON string, not an object. Tell jQuery that you expect a JSON response and it will parse it for you. Either use $.getJSON instead of $.get, or pass the dataType argument to $.get
:
$.get(
'index.php?r=admin/post/ajax',
{"parentCatId":parentCatId},
function(data){
$.each(data, function(key, value){
console.log(key + ":" + value)
})
},
'json'
);
I was trying to select an area of svg with a rectangle and get all the elements from it. For this, element.getBoundingClientRect() worked perfectly for me. It returns current coordinates of svg elements regardless of whether svg is scaled or transformed.
A hacky way of doing JSON_UNESCAPED_UNICODE in PHP 5.3. Really disappointed by PHP json support. Maybe this will help someone else.
$array = some_json();
// Encode all string children in the array to html entities.
array_walk_recursive($array, function(&$item, $key) {
if(is_string($item)) {
$item = htmlentities($item);
}
});
$json = json_encode($array);
// Decode the html entities and end up with unicode again.
$json = html_entity_decode($rson);
I found the problem was you can't use short URL for image "img/image.jpg"
you should use the full URL "http://www.website.com/img/image.jpg", yet I don't know why !!
The .c is the source file and .h is the header file.
I had the same issue with firefox, when I searched for a solution I didn't find anything, but then I tried to load the script from a cdn, it worked properly, so I think you should try loading it from a cdn link, I mean if you are trying to load a script that you havn't created. because in my case, when tried to load a script that is mine, it worked and imported successfully, for now I don't know why, but I think there is something in the scripts from network, so just try cdn, you won't lose anything.
I wish it help you.
Go to this file in: WampFolder\apps\phpmyadmin[phpmyadmin version]\config.inc.php
Usually wamp is in your main hard drive folder C:\wamp\
You will see something like:
$cfg['Servers'][$i]['user'] = 'YOUR USER NAME IS HERE';
$cfg['Servers'][$i]['password'] = 'AND YOU PASSWORD IS HERE';
Try using the password and username that you have on that file.
USE Master GO
ALTER Server Role [bulkadmin] ADD MEMBER [username] GO Command failed even tried several command parameters
master..sp_addsrvrolemember @loginame = N'username', @rolename = N'bulkadmin' GO Command was successful..
SELECT
CASE
WHEN LastName IS NULL THEN FirstName
WHEN LastName IS NOT NULL THEN LastName + ', ' + FirstName
END AS 'FullName'
FROM
customers
GROUP BY
LastName,
FirstName
This works because the formula you use (the CASE statement) can never give the same answer for two different inputs.
This is not the case if you used something like:
LEFT(FirstName, 1) + ' ' + LastName
In such a case "James Taylor" and "John Taylor" would both result in "J Taylor".
If you wanted your output to have "J Taylor" twice (one for each person):
GROUP BY LastName, FirstName
If, however, you wanted just one row of "J Taylor" you'd want:
GROUP BY LastName, LEFT(FirstName, 1)
Try this:
<img src="images/background.jpg"
style="width:100%;height:100%;position:absolute;top:0;left:0;z-index:-5000;">
http://thewebthought.blogspot.com/2010/10/css-making-background-image-fit-any.html
As @hitec said, you have to be sure that you have the right permissions, if you do, you can use this line to ensure the existence of the directory:
Directory.CreateDirectory(Path.GetDirectoryName(filePath))
On Oracle 12c (see row limiting clause in SQL reference):
SELECT *
FROM sometable
ORDER BY name
OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY;
Another possible cause of similar issue could be wrong processorArchitecture
in the cx_freeze manifest, trying to load x86 common controls dll in x64 process - should be fixed by this patch:
You can put the username() function in another page, and send the form to that page...
JAVA_OPTS
is environment variable used by tomcat in its startup/shutdown script to configure params.
You can set it in linux by
export JAVA_OPTS="-Djava.awt.headless=true"
What about just using virtual desktops? You can spread your windows around among multiple workspaces. Something like Virtual Dimension should give you most of that functionality. I use virtual desktops all the time on Linux, and it's the next best thing to multiple monitors.
Yes, in Pandas we have many functions has the parameter inplace
but by default it is assigned to False
.
So, when you do df.dropna(axis='index', how='all', inplace=False)
it thinks that you do not want to change the orignial DataFrame
, therefore it instead creates a new copy for you with the required changes.
But, when you change the inplace
parameter to True
Then it is equivalent to explicitly say that I do not want a new copy of the
DataFrame
instead do the changes on the givenDataFrame
This forces the Python interpreter to not to create a new DataFrame
But you can also avoid using the inplace
parameter by reassigning the result to the orignal DataFrame
df = df.dropna(axis='index', how='all')
You can do it for center transparent progress indicator
Future<Null> _submitDialog(BuildContext context) async {
return await showDialog<Null>(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return SimpleDialog(
elevation: 0.0,
backgroundColor: Colors.transparent,
children: <Widget>[
Center(
child: CircularProgressIndicator(),
)
],
);
});
}
This is what I ended up using a variation of, which checks for IE8 and below:
if (preg_match('/MSIE\s(?P<v>\d+)/i', @$_SERVER['HTTP_USER_AGENT'], $B) && $B['v'] <= 8) {
// Browsers IE 8 and below
} else {
// All other browsers
}
A couple problems, you aren't delaying by much (.sleep
is milliseconds, not seconds), and you're attempting to print in your catch
statement. Your code should look more like:
if (i==1) {
try {
System.out.println("Scanning...");
Thread.sleep(1000); // 1 second
} catch (InterruptedException ex) {
// handle error
}
}
This happened to me today as well. I was using EF and returning an Entity in response to an AJAX call. The virtual properties on my entity was causing a cyclical dependency error that was not being detected on the server. By adding the [ScriptIgnore] attribute on the virtual properties, the problem was fixed.
Instead of using the ScriptIgnore attribute, it would probably be better to just return a DTO.
None of the other solutions worked for me. In my app, I'm adding the date range elements to the document using jquery and then applying datepicker to them. So none of the event solutions worked for some reason.
This is what finally worked:
$(document).on('changeDate',"#elementid", function(){
alert('event fired');
});
Hope this helps someone because this set me back a bit.
Swift String
ranges and NSString
ranges are not "compatible".
For example, an emoji like counts as one Swift character, but as two NSString
characters (a so-called UTF-16 surrogate pair).
Therefore your suggested solution will produce unexpected results if the string contains such characters. Example:
let text = "Long paragraph saying!"
let textRange = text.startIndex..<text.endIndex
let attributedString = NSMutableAttributedString(string: text)
text.enumerateSubstringsInRange(textRange, options: NSStringEnumerationOptions.ByWords, { (substring, substringRange, enclosingRange, stop) -> () in
let start = distance(text.startIndex, substringRange.startIndex)
let length = distance(substringRange.startIndex, substringRange.endIndex)
let range = NSMakeRange(start, length)
if (substring == "saying") {
attributedString.addAttribute(NSForegroundColorAttributeName, value: NSColor.redColor(), range: range)
}
})
println(attributedString)
Output:
Long paragra{ }ph say{ NSColor = "NSCalibratedRGBColorSpace 1 0 0 1"; }ing!{ }
As you see, "ph say" has been marked with the attribute, not "saying".
Since NS(Mutable)AttributedString
ultimately requires an NSString
and an NSRange
, it is actually
better to convert the given string to NSString
first. Then the substringRange
is an NSRange
and you don't have to convert the ranges anymore:
let text = "Long paragraph saying!"
let nsText = text as NSString
let textRange = NSMakeRange(0, nsText.length)
let attributedString = NSMutableAttributedString(string: nsText)
nsText.enumerateSubstringsInRange(textRange, options: NSStringEnumerationOptions.ByWords, { (substring, substringRange, enclosingRange, stop) -> () in
if (substring == "saying") {
attributedString.addAttribute(NSForegroundColorAttributeName, value: NSColor.redColor(), range: substringRange)
}
})
println(attributedString)
Output:
Long paragraph { }saying{ NSColor = "NSCalibratedRGBColorSpace 1 0 0 1"; }!{ }
Update for Swift 2:
let text = "Long paragraph saying!"
let nsText = text as NSString
let textRange = NSMakeRange(0, nsText.length)
let attributedString = NSMutableAttributedString(string: text)
nsText.enumerateSubstringsInRange(textRange, options: .ByWords, usingBlock: {
(substring, substringRange, _, _) in
if (substring == "saying") {
attributedString.addAttribute(NSForegroundColorAttributeName, value: NSColor.redColor(), range: substringRange)
}
})
print(attributedString)
Update for Swift 3:
let text = "Long paragraph saying!"
let nsText = text as NSString
let textRange = NSMakeRange(0, nsText.length)
let attributedString = NSMutableAttributedString(string: text)
nsText.enumerateSubstrings(in: textRange, options: .byWords, using: {
(substring, substringRange, _, _) in
if (substring == "saying") {
attributedString.addAttribute(NSForegroundColorAttributeName, value: NSColor.red, range: substringRange)
}
})
print(attributedString)
Update for Swift 4:
As of Swift 4 (Xcode 9), the Swift standard library
provides method to convert between Range<String.Index>
and NSRange
.
Converting to NSString
is no longer necessary:
let text = "Long paragraph saying!"
let attributedString = NSMutableAttributedString(string: text)
text.enumerateSubstrings(in: text.startIndex..<text.endIndex, options: .byWords) {
(substring, substringRange, _, _) in
if substring == "saying" {
attributedString.addAttribute(.foregroundColor, value: NSColor.red,
range: NSRange(substringRange, in: text))
}
}
print(attributedString)
Here substringRange
is a Range<String.Index>
, and that is converted to the
corresponding NSRange
with
NSRange(substringRange, in: text)
More on Windows... variable java.home is not always the same location as the binary that is run.
As Denis The Menace says, the installer puts Java files into Program Files, but also java.exe into System32. With nothing Java related on the path java -version can still work. However when PeterMmm's program is run it reports the value of Program Files as java.home, this is not wrong (Java is installed there) but the actual binary being run is located in System32.
One way to hunt down the location of the java.exe binary, add the following line to PeterMmm's code to keep the program running a while longer:
try{Thread.sleep(60000);}catch(Exception e) {}
Compile and run it, then hunt down the location of the java.exe image. E.g. in Windows 7 open the task manager, find the java.exe entry, right click and select 'open file location', this opens the exact location of the Java binary. In this case it would be System32.
contentType
option to false
is used for multipart/form-data
forms that pass files.
When one sets the contentType
option to false
, it forces jQuery not to add a Content-Type header, otherwise, the boundary string will be missing from it. Also, when submitting files via multipart/form-data, one must leave the processData
flag set to false, otherwise, jQuery will try to convert your FormData into a string, which will fail.
Use jQuery's .serialize()
method which creates a text string in standard URL-encoded notation.
You need to pass un-encoded data when using contentType: false
.
Try using new FormData
instead of .serialize():
var formData = new FormData($(this)[0]);
See for yourself the difference of how your formData is passed to your php page by using console.log()
.
var formData = new FormData($(this)[0]);
console.log(formData);
var formDataSerialized = $(this).serialize();
console.log(formDataSerialized);
you can use background-origin:padding-box; and then add some padding where you want, for example: #logo {background-image: url(your/image.jpg); background-origin:padding-box; padding-left: 15%;}
This way you attach the image to the div padding box that contains it so you can position it wherever you want.
We can simply map a Controller method for the default view. For eg, we have a index.html as the default page.
@RequestMapping(value = "/", method = GET)
public String index() {
return "index";
}
once done we can access the page with default application context.
E.g http://localhost:8080/myapp
itoa
or itof
functions because they are non-standard and therefore not portable.Use string streams
#include <sstream> //include this to use string streams
#include <string>
int main()
{
int number = 1234;
std::ostringstream ostr; //output string stream
ostr << number; //use the string stream just like cout,
//except the stream prints not to stdout but to a string.
std::string theNumberString = ostr.str(); //the str() function of the stream
//returns the string.
//now theNumberString is "1234"
}
Note that you can use string streams also to convert floating-point numbers to string, and also to format the string as you wish, just like with cout
std::ostringstream ostr;
float f = 1.2;
int i = 3;
ostr << f << " + " i << " = " << f + i;
std::string s = ostr.str();
//now s is "1.2 + 3 = 4.2"
You can use stream manipulators, such as std::endl
, std::hex
and functions std::setw()
, std::setprecision()
etc. with string streams in exactly the same manner as with cout
Do not confuse std::ostringstream
with std::ostrstream
. The latter is deprecated
Use boost lexical cast. If you are not familiar with boost, it is a good idea to start with a small library like this lexical_cast. To download and install boost and its documentation go here. Although boost isn't in C++ standard many libraries of boost get standardized eventually and boost is widely considered of the best C++ libraries.
Lexical cast uses streams underneath, so basically this option is the same as the previous one, just less verbose.
#include <boost/lexical_cast.hpp>
#include <string>
int main()
{
float f = 1.2;
int i = 42;
std::string sf = boost::lexical_cast<std::string>(f); //sf is "1.2"
std::string si = boost::lexical_cast<std::string>(i); //sf is "42"
}
The most lightweight option, inherited from C, is the functions atoi
(for integers (alphabetical to integer)) and atof
(for floating-point values (alphabetical to float)). These functions take a C-style string as an argument (const char *
) and therefore their usage may be considered a not exactly good C++ practice. cplusplus.com has easy-to-understand documentation on both atoi and atof including how they behave in case of bad input. However the link contains an error in that according to the standard if the input number is too large to fit in the target type, the behavior is undefined.
#include <cstdlib> //the standard C library header
#include <string>
int main()
{
std::string si = "12";
std::string sf = "1.2";
int i = atoi(si.c_str()); //the c_str() function "converts"
double f = atof(sf.c_str()); //std::string to const char*
}
Use string streams (this time input string stream, istringstream
). Again, istringstream is used just like cin
. Again, do not confuse istringstream
with istrstream
. The latter is deprecated.
#include <sstream>
#include <string>
int main()
{
std::string inputString = "1234 12.3 44";
std::istringstream istr(inputString);
int i1, i2;
float f;
istr >> i1 >> f >> i2;
//i1 is 1234, f is 12.3, i2 is 44
}
Use boost lexical cast.
#include <boost/lexical_cast.hpp>
#include <string>
int main()
{
std::string sf = "42.2";
std::string si = "42";
float f = boost::lexical_cast<float>(sf); //f is 42.2
int i = boost::lexical_cast<int>(si); //i is 42
}
In case of a bad input, lexical_cast
throws an exception of type boost::bad_lexical_cast
//c++0x too
std::map<int,int> mapints;
std::vector<int> vints;
for(auto const& imap: mapints)
vints.push_back(imap.first);
Use the OutputDebugString
function or the TRACE
macro (MFC) which lets you do printf
-style formatting:
int x = 1;
int y = 16;
float z = 32.0;
TRACE( "This is a TRACE statement\n" );
TRACE( "The value of x is %d\n", x );
TRACE( "x = %d and y = %d\n", x, y );
TRACE( "x = %d and y = %x and z = %f\n", x, y, z );
Isn't this the normal way to free the memory associated with an object?
Yes, it is.
I realized that it automatically invokes the destructor... is this normal?
Make sure that you did not double delete your object.
There's a setting in Safari under "Tabs" that labeled Open pages in tabs instead of windows:
with a drop down with a few options. I'm thinking yours may be set to Always
. Bottom line is you can't rely on a browser opening a new window.
As of Node.js v6.0.0 using the constructor method has been deprecated and the following method should instead be used to construct a new buffer from a base64 encoded string:
var b64string = /* whatever */;
var buf = Buffer.from(b64string, 'base64'); // Ta-da
For Node.js v5.11.1 and below
Construct a new Buffer
and pass 'base64'
as the second argument:
var b64string = /* whatever */;
var buf = new Buffer(b64string, 'base64'); // Ta-da
If you want to be clean, you can check whether from
exists :
if (typeof Buffer.from === "function") {
// Node 5.10+
buf = Buffer.from(b64string, 'base64'); // Ta-da
} else {
// older Node versions, now deprecated
buf = new Buffer(b64string, 'base64'); // Ta-da
}
Just as reference let me quote the osxfuse FAQ
4.8. How should I unmount my "FUSE for OS X" file system? I cannot find the fusermount program anywhere.
Just use the standard umount command in OS X. You do not need the Linux-specific fusermount with "FUSE for OS X".
As mentioned above, either diskutil unmount
or umount
should work
First, put the app into the background (press the device's home button)
Then....in a terminal....
adb shell am kill com.your.package
I think it's first worth noting that without javascript (plain html), the form
element submits when clicking either the <input type="submit" value="submit form">
or <button>submits form too</button>
. In javascript you can prevent that by using an event handler and calling e.preventDefault()
on button click, or form submit. e
is the event object passed into the event handler. With react, the two relevant event handlers are available via the form as onSubmit
, and the other on the button via onClick
.
Example: http://jsbin.com/vowuley/edit?html,js,console,output
Wanting to initalize an array of fixed size is a perfectly acceptable thing to do in any programming language; it isn't like the programmer wants to put a break statement in a while(true) loop. Believe me, especially if the elements are just going to be overwritten and not merely added/subtracted, like is the case of many dynamic programming algorithms, you don't want to mess around with append statements and checking if the element hasn't been initialized yet on the fly (that's a lot of code gents).
object = [0 for x in range(1000)]
This will work for what the programmer is trying to achieve.
I have had this issue before. I usually just hit enter to add a line and then wait for the plus/minus to show on the html page and the designer should add what you need. I have also had to close the project and reopen it to get it to work.
DataRow's are nice in the way that they have their underlying table linked to them. With the underlying table you can verify that a specific row has a specific column in it.
If DataRow.Table.Columns.Contains("column") Then
MsgBox("YAY")
End If
If you want to remove the namespace you may also want to remove the version, to save you searching I've added that functionality so the below code will do both.
I've also wrapped it in a generic method as I'm creating very large xml files which are too large to serialize in memory so I've broken my output file down and serialize it in smaller "chunks":
public static string XmlSerialize<T>(T entity) where T : class
{
// removes version
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
XmlSerializer xsSubmit = new XmlSerializer(typeof(T));
using (StringWriter sw = new StringWriter())
using (XmlWriter writer = XmlWriter.Create(sw, settings))
{
// removes namespace
var xmlns = new XmlSerializerNamespaces();
xmlns.Add(string.Empty, string.Empty);
xsSubmit.Serialize(writer, entity, xmlns);
return sw.ToString(); // Your XML
}
}
If the path you want is the one to the workbook running the macro, and that workbook has been saved, then
ThisWorkbook.Path
is what you would use.
I'm probably late but this worked for me:
<target name="build" />
In my case, I took an android
project from one computer to another and had this problem. What worked for me was a combination of some of the answers I've seen:
Mine ran fine after these steps.
Check out snakecase from Ruby Facets
The following cases are handled, as seen below:
"SnakeCase".snakecase #=> "snake_case"
"Snake-Case".snakecase #=> "snake_case"
"Snake Case".snakecase #=> "snake_case"
"Snake - Case".snakecase #=> "snake_case"
From: https://github.com/rubyworks/facets/blob/master/lib/core/facets/string/snakecase.rb
class String
# Underscore a string such that camelcase, dashes and spaces are
# replaced by underscores. This is the reverse of {#camelcase},
# albeit not an exact inverse.
#
# "SnakeCase".snakecase #=> "snake_case"
# "Snake-Case".snakecase #=> "snake_case"
# "Snake Case".snakecase #=> "snake_case"
# "Snake - Case".snakecase #=> "snake_case"
#
# Note, this method no longer converts `::` to `/`, in that case
# use the {#pathize} method instead.
def snakecase
#gsub(/::/, '/').
gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
gsub(/([a-z\d])([A-Z])/,'\1_\2').
tr('-', '_').
gsub(/\s/, '_').
gsub(/__+/, '_').
downcase
end
#
alias_method :underscore, :snakecase
# TODO: Add *separators to #snakecase, like camelcase.
end
I was checking for solutions to encoding since ages, and this page is probably the conclusion of years of search! I tested some of the suggestions you mentioned and here's my notes:
This is my test string:
this is a "wròng wrìtten" string bùt I nèed to pù 'sòme' special chàrs to see thèm, convertèd by fùnctìon!! & that's it!
I do an INSERT to save this string on a database in a field that is set as utf8_general_ci
The character set of my page is UTF-8.
If I do an INSERT just like that, in my database, I have some characters probably coming from Mars...
So I need to convert them into some "sane" UTF-8. I tried utf8_encode()
, but still aliens chars were invading my database...
So I tried to use the function forceUTF8
posted on number 8, but in the database the string saved looks like this:
this is a "wròng wrìtten" string bùt I nèed to pù 'sòme' special chà rs to see thèm, convertèd by fùnctìon!! & that's it!
So collecting some more information on this page and merging them with other information on other pages I solved my problem with this solution:
$finallyIDidIt = mb_convert_encoding(
$string,
mysql_client_encoding($resourceID),
mb_detect_encoding($string)
);
Now in my database I have my string with correct encoding.
NOTE:
Only note to take care of is in function mysql_client_encoding
!
You need to be connected to the database, because this function wants a resource ID as a parameter.
But well, I just do that re-encoding before my INSERT so for me it is not a problem.
Try the notepad++ plugin JSMinNpp(Changed name to JSTool since 1.15)
A 302 status code is HTTP response status code indicating that the requested resource has been temporarily moved to a different URI. Since the location or current redirection directive might be changed in the future, a client that receives a 302 Found response code should continue to use the original URI for future requests.
An HTTP response with this status code will additionally provide a URL in the header field Location. This is an invitation to the user agent (e.g. a web browser) to make a second, otherwise identical, request to the new URL specified in the location field. The end result is a redirection to the new URL.
You'll need some kind of abstract factory of one sort or another to pass the buck to:
interface Factory<E> {
E create();
}
class SomeContainer<E> {
private final Factory<E> factory;
SomeContainer(Factory<E> factory) {
this.factory = factory;
}
E createContents() {
return factory.create();
}
}
$mysql -u root --host=127.0.0.1 -p
mysql>use mysql
mysql>GRANT ALL ON *.* to root@'%' IDENTIFIED BY 'redhat@123';
mysql>FLUSH PRIVILEGES;
mysql> SELECT host FROM mysql.user WHERE User = 'root';
We implemented a ngModelChange observable directive that sends all model changes through an event emitter that you instantiate in your own component. You simply have to bind your event emitter to the directive.
See: https://github.com/atomicbits/angular2-modelchangeobservable
In html, bind your event emitter (countryChanged in this example):
<input [(ngModel)]="country.name"
[modelChangeObservable]="countryChanged"
placeholder="Country"
name="country" id="country"></input>
In your typescript component, do some async operations on the EventEmitter:
import ...
import {ModelChangeObservable} from './model-change-observable.directive'
@Component({
selector: 'my-component',
directives: [ModelChangeObservable],
providers: [],
templateUrl: 'my-component.html'
})
export class MyComponent {
@Input()
country: Country
selectedCountries:Country[]
countries:Country[] = <Country[]>[]
countryChanged:EventEmitter<string> = new EventEmitter<string>()
constructor() {
this.countryChanged
.filter((text:string) => text.length > 2)
.debounceTime(300)
.subscribe((countryName:string) => {
let query = new RegExp(countryName, 'ig')
this.selectedCountries = this.countries.filter((country:Country) => {
return query.test(country.name)
})
})
}
}
decimal value = 0.00M;
value = Convert.ToDecimal(12345.12345);
Console.WriteLine(".ToString(\"C\") Formates With Currency $ Sign");
Console.WriteLine(value.ToString("C"));
//OutPut : $12345.12
Console.WriteLine(value.ToString("C1"));
//OutPut : $12345.1
Console.WriteLine(value.ToString("C2"));
//OutPut : $12345.12
Console.WriteLine(value.ToString("C3"));
//OutPut : $12345.123
Console.WriteLine(value.ToString("C4"));
//OutPut : $12345.1234
Console.WriteLine(value.ToString("C5"));
//OutPut : $12345.12345
Console.WriteLine(value.ToString("C6"));
//OutPut : $12345.123450
Console.WriteLine();
Console.WriteLine(".ToString(\"F\") Formates With out Currency Sign");
Console.WriteLine(value.ToString("F"));
//OutPut : 12345.12
Console.WriteLine(value.ToString("F1"));
//OutPut : 12345.1
Console.WriteLine(value.ToString("F2"));
//OutPut : 12345.12
Console.WriteLine(value.ToString("F3"));
//OutPut : 12345.123
Console.WriteLine(value.ToString("F4"));
//OutPut : 12345.1234
Console.WriteLine(value.ToString("F5"));
//OutPut : 12345.12345
Console.WriteLine(value.ToString("F6"));
//OutPut : 12345.123450
Console.Read();
Notice Allowed methods in the response
Connection: close
Date: Tue, 11 Feb 2014 15:17:24 GMT
Content-Length: 34
Content-Type: text/html
Allow: GET, DELETE
X-Powered-By: Servlet/2.5 JSP/2.1
It accepts only GET and DELETE. Hence, you need to tweak the server to enable PUT and POST as well.
Allow: GET, DELETE
Can I use a field of the type ... and retrieve it after the GET / POST method ...
Yes (haven't you tried?)
Are there any other ways of using hidden fields in PHP?
You mean other ways of retrieving the value? No.
Of course you can use hidden fields for what ever you want.
Btw. input
fiels have no end tag. So write either just <input ...>
or as self-closing tag <input .../>
.
Thanks @all!
don't use: query("SET NAMES utf8"); this is setup stuff and not a query. put it right afte a connection start with setCharset() (or similar method)
some little thing in parctice:
status:
Store and read data is no problem as long mysql can handle the characters. if you look in the db you will already see there is crap in it (e.g.using phpmyadmin).
until now this is not a problem! (wrong but works often (in europe)) ..
..unless another client/programm or a changed library, which works correct, will read/save data. then you are in big trouble!
str_replace('"', "", $string);
str_replace("'", "", $string);
I assume you mean quotation marks?
Otherwise, go for some regex, this will work for html quotes for example:
preg_replace("/<!--.*?-->/", "", $string);
C-style quotes:
preg_replace("/\/\/.*?\n/", "\n", $string);
CSS-style quotes:
preg_replace("/\/*.*?\*\//", "", $string);
bash-style quotes:
preg-replace("/#.*?\n/", "\n", $string);
Etc etc...
As Tasnim Fabiha mentioned, it is possible to change font for TextBox in order to show only dots/asterisks. But I wasn't able to find his font...so I give you my working example:
<TextBox Text="{Binding Password}"
FontFamily="pack://application:,,,/Resources/#password" />
Just copy-paste won't work. Firstly you have to download mentioned font "password.ttf" link: https://github.com/davidagraf/passwd/blob/master/public/ttf/password.ttf Then copy that to your project Resources folder (Project->Properties->Resources->Add resource->Add existing file). Then set it's Build Action to: Resource.
After this you will see just dots, but you can still copy text from that, so it is needed to disable CTRL+C shortcut like this:
<TextBox Text="{Binding Password}"
FontFamily="pack://application:,,,/Resources/#password" >
<TextBox.InputBindings>
<!--Disable CTRL+C -->
<KeyBinding Command="ApplicationCommands.NotACommand"
Key="C"
Modifiers="Control" />
</TextBox.InputBindings>
</TextBox>
F5 is a standard shortcut to run a macro in VBA editor. I don't think you can add a shortcut key in editor itself. If you want to run the macro from excel, you can assign a shortcut from there.
In excel press alt+F8 to open macro dialog box. select the macro for which you want to assign shortcut key and click options. there you can assign a shortcut to the macro.
I followed this tutorial, and everything is OK.
As many of the answers here show, the 'right' answer depends on exactly what you need. In my case, I need to round to the closest whole number.
Consider these examples: 1st January -> 31st January: It's 0 whole months, and almost 1 month long. 1st January -> 1st February? It's 1 whole month, and exactly 1 month long.
To get the number of whole (complete) months, use:
SELECT TIMESTAMPDIFF(MONTH, '2018-01-01', '2018-01-31'); => 0
SELECT TIMESTAMPDIFF(MONTH, '2018-01-01', '2018-02-01'); => 1
To get a rounded duration in months, you could use:
SELECT ROUND(TIMESTAMPDIFF(DAY, '2018-01-01', '2018-01-31')*12/365.24); => 1
SELECT ROUND(TIMESTAMPDIFF(DAY, '2018-01-01', '2018-01-31')*12/365.24); => 1
This is accurate to +/- 5 days and for ranges over 1000 years. Zane's answer is obviously more accurate, but it's too verbose for my liking.
you should to delete your the Override onOptionsItemSelected and replate your onCreateOptionsMenu with this code
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_action_bar_finish_order_stop, menu);
menu.getItem(0).setOnMenuItemClickListener(new FinishOrderStopListener(this, getApplication(), selectedChild));
return true;
}
I came across the same message and here is what we have found: We use third party dlls in our project. After a new release of those was out we changed our project to point to the new set of dlls and compiled successfully.
The exception was thrown when I tried to instatiate one of the their interfaced classes during run time. We made sure that all the other references were up to date, but still no luck. We needed a while to spot (using the Object Browser) that the return type of the method in the error message was a completely new type from a new, unreferenced assembly.
We added a reference to the assembly and the error disappeared.
It is possible using Apex Recovery Tool,i have successfully recovered my table rows which i accidentally deleted
if you download the trial version it will recover only 10th row
check here http://www.apexsql.com/sql_tools_log.aspx
pandas.DataFrame.plot()
, matplotlib.axes.Axes
is returned when creating a plot from a dataframe. As such, the dataframe plot can be assigned to a variable, ax
, which enables the usage of the associated formatting methods.pandas
, is matplotlib
.import pandas as pd
# test dataframe
data = {'a': range(20), 'date': pd.bdate_range('2021-01-09', freq='D', periods=20)}
df = pd.DataFrame(data)
# plot the dataframe and assign the returned axes
ax = df.plot(x='date', color='green', ylabel='values', xlabel='date', figsize=(8, 6))
# set various colors
ax.spines['bottom'].set_color('blue')
ax.spines['top'].set_color('red')
ax.spines['right'].set_color('magenta')
ax.spines['left'].set_color('orange')
ax.xaxis.label.set_color('purple')
ax.yaxis.label.set_color('silver')
ax.tick_params(colors='red', which='both') # 'both' refers to minor and major axes
You can examine the url through several Request
fields:
Imagine your application is listening on the following application root:
http://www.example.com/myapplication
And a user requests the following URI:
http://www.example.com/myapplication/foo/page.html?x=y
In this case the values of the above mentioned attributes would be the following:
path /foo/page.html full_path /foo/page.html?x=y script_root /myapplication base_url http://www.example.com/myapplication/foo/page.html url http://www.example.com/myapplication/foo/page.html?x=y url_root http://www.example.com/myapplication/
You can easily extract the host part with the appropriate splits.
the proper way is:
.attr({target:'nw', title:'Opens in a new window'})
You can create the ipa for ad hoc distribution and use diawi to create a link for the your ipad. You just upload the .ipa and the provisioning profile, then a link is generated and you can visit it from your ipad in order to install the app (if the provisioning profile is for development you have to add your ipad's UDID to it).
The Chrome Browser versión should matches with the chromeDriver versión. Go to : chrome://settings/help
How do I confirm I'm using the right chromedriver?
THis could be another way to browse through the directory structures and provide depth results.
find . -type d | awk '{print "echo -n \""$0" \";ls -l "$0" | grep -v total | wc -l" }' | sh
If you have access to you httpd.conf file (in ubuntu it is in the /etc/apache2 directory), you should add the same lines that you would to the .htaccess
file in the specific directory. That is (for example):
ServerName YOURSERVERNAMEHERE
<Directory /var/www/>
AllowOverride None
order deny,allow
Options -Indexes FollowSymLinks
</Directory>
Do this for every directory that you want to control the information, and you will have one file in one spot to manage all access. It the example above, I did it for the root directory, /var/www.
This option may not be available with outsourced hosting, especially shared hosting. But it is a better option than adding many .htaccess
files.
Here is how I did it with Visual Studio 2010, .NET 4
This is a quick efficient one:
bool isPrimeNumber(int n) {
int divider = 2;
while (n % divider != 0) {
divider++;
}
if (n == divider) {
return true;
}
else {
return false;
}
}
It will start finding a divisible number of n, starting by 2. As soon as it finds one, if that number is equal to n then it's prime, otherwise it's not.
If you wanted to use this without completely destroying your SVN repository, you can tell 'find' to ignore all hidden files by doing:
find . \( ! -regex '.*/\..*' \) -type f -print0 | xargs -0 sed -i 's/subdomainA.example.com/subdomainB.example.com/g'
In my case, cleaning and rebuilding the project resolved the problem.
My solution for changing seconds (number) to string format (for example: 'mm:ss'):
const formattedSeconds = moment().startOf('day').seconds(S).format('mm:ss');
Write your seconds instead 'S' in example. And just use the 'formattedSeconds' where you need.
Array's include?
method accepts any object, not just a string. This should work:
@suggested_horses = []
@suggested_horses << Horse.first(:offset => rand(Horse.count))
while @suggested_horses.length < 8
horse = Horse.first(:offset => rand(Horse.count))
@suggested_horses << horse unless @suggested_horses.include?(horse)
end
FWIW, I was able to setup a local RTSP server for testing purposes using simple-rtsp-server and ffmpeg following these steps:
rtsp-simple-server.yml
with this single line:
protocols: [tcp]
$ docker run --rm -it -v $PWD/rtsp-simple-server.yml:/rtsp-simple-server.yml -p 8554:8554 aler9/rtsp-simple-server
$ ffmpeg -re -stream_loop -1 -i test.mp4 -f rtsp -rtsp_transport tcp rtsp://localhost:8554/live.stream
Once you have that running you can use ffplay to view the stream:
$ ffplay -rtsp_transport tcp rtsp://localhost:8554/live.stream
Note that simple-rtsp-server can also handle UDP streams (i.s.o. TCP) but that's tricky running the server as a Docker container.
It's not clear what you want, or whether you want this trick to work with different targets, or whether you've defined these targets elsewhere, or what version of Make you're using, but what the heck, I'll go out on a limb:
ifeq (yes, ${TEST})
CXXFLAGS := ${CXXFLAGS} -DDESKTOP_TEST
test:
$(info ************ TEST VERSION ************)
else
release:
$(info ************ RELEASE VERSIOIN **********)
endif
I'm using Chrome and print() literally prints the text on paper. This is what works for me:
document.write("My message");
Well, since you can currently only have one ngView directive... I use nested directive controls. This allows you to set up templating and inherit (or isolate) scopes among them. Outside of that I use ng-switch or even just ng-show to choose which controls I'm displaying based on what's coming in from $routeParams.
EDIT Here's some example pseudo-code to give you an idea of what I'm talking about. With a nested sub navigation.
Here's the main app page
<!-- primary nav -->
<a href="#/page/1">Page 1</a>
<a href="#/page/2">Page 2</a>
<a href="#/page/3">Page 3</a>
<!-- display the view -->
<div ng-view>
</div>
Directive for the sub navigation
app.directive('mySubNav', function(){
return {
restrict: 'E',
scope: {
current: '=current'
},
templateUrl: 'mySubNav.html',
controller: function($scope) {
}
};
});
template for the sub navigation
<a href="#/page/1/sub/1">Sub Item 1</a>
<a href="#/page/1/sub/2">Sub Item 2</a>
<a href="#/page/1/sub/3">Sub Item 3</a>
template for a main page (from primary nav)
<my-sub-nav current="sub"></my-sub-nav>
<ng-switch on="sub">
<div ng-switch-when="1">
<my-sub-area1></my-sub-area>
</div>
<div ng-switch-when="2">
<my-sub-area2></my-sub-area>
</div>
<div ng-switch-when="3">
<my-sub-area3></my-sub-area>
</div>
</ng-switch>
Controller for a main page. (from the primary nav)
app.controller('page1Ctrl', function($scope, $routeParams) {
$scope.sub = $routeParams.sub;
});
Directive for a Sub Area
app.directive('mySubArea1', function(){
return {
restrict: 'E',
templateUrl: 'mySubArea1.html',
controller: function($scope) {
//controller for your sub area.
}
};
});
Pay attention to all warnings . Do not only solve errors.
GCC shows this Warning
warning: address of local variable 'a' returned
This is power of C++. You should care about memory. With the -Werror
flag, this warning becames an error and now you have to debug it.
In python there are no arrays, lists are used instead. There are various ways to delete an object from a list:
my_list = [1,2,4,6,7]
del my_list[1] # Removes index 1 from the list
print my_list # [1,4,6,7]
my_list.remove(4) # Removes the integer 4 from the list, not the index 4
print my_list # [1,6,7]
my_list.pop(2) # Removes index 2 from the list
In your case the appropriate method to use is pop, because it takes the index to be removed:
x = object()
y = object()
array = [x, y]
array.pop(0)
# Using the del statement
del array[0]
The m2e plugin uses it's own distribution of Maven, packaged with the plugin.
In order to use Maven from command line, you need to have it installed as a standalone application. Here is an instruction explaining how to do it in Windows
Once Maven is properly installed (i.e. be sure that MAVEN_HOME
, JAVA_HOME
and PATH
variables are set correctly): you must run mvn eclipse:eclipse
from the directory containing the pom.xml
.
Based on the link provided by @better_use_mkstemp, here's a fiddle where nested iframe resizes to fill parent div: http://jsfiddle.net/orlenko/HNyJS/
Html:
<div id="content">
<iframe src="http://www.microsoft.com" name="frame2" id="frame2" frameborder="0" marginwidth="0" marginheight="0" scrolling="auto" onload="" allowtransparency="false"></iframe>
</div>
<div id="block"></div>
<div id="header"></div>
<div id="footer"></div>
Relevant parts of CSS:
div#content {
position: fixed;
top: 80px;
left: 40px;
bottom: 25px;
min-width: 200px;
width: 40%;
background: black;
}
div#content iframe {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
height: 100%;
width: 100%;
}
React.version
is what you are looking for.
It is undocumented though (as far as I know) so it may not be a stable feature (i.e. though unlikely, it may disappear or change in future releases).
Example with React
imported as a script
const REACT_VERSION = React.version;
ReactDOM.render(
<div>React version: {REACT_VERSION}</div>,
document.getElementById('root')
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
_x000D_
Example with React
imported as a module
import React from 'react';
console.log(React.version);
Obviously, if you import React
as a module, it won't be in the global scope. The above code is intended to be bundled with the rest of your app, e.g. using webpack. It will virtually never work if used in a browser's console (it is using bare imports).
This second approach is the recommended one. Most websites will use it. create-react-app does this (it's using webpack behind the scene). In this case, React
is encapsulated and is generally not accessible at all outside the bundle (e.g. in a browser's console).
@echo off
setlocal enableextensions
set count=0
for %%x in (*.txt) do set /a count+=1
echo %count%
endlocal
pause
This is the best.... your variable is: %count%
NOTE: you can change (*.txt
) to any other file extension to count other files.....
Mono comes with a wrapper, use theirs!
https://github.com/mono/mono/tree/master/mcs/class/Mono.Data.Sqlite/Mono.Data.Sqlite_2.0 gives code to wrap the actual SQLite dll ( http://www.sqlite.org/sqlite-shell-win32-x86-3071300.zip found on the download page http://www.sqlite.org/download.html/ ) in a .net friendly way. It works on Linux or Windows.
This seems the thinnest of all worlds, minimizing your dependence on third party libraries. If I had to do this project from scratch, this is the way I would do it.
Use this.
$('#mydiv').load(document.URL + ' #mydiv');
Note, include a space before the hastag.
"location" : null // this is not really an array it's a null object
"location" : [] // this is an empty array
It looks like this API returns null when there is no location defined - instead of returning an empty array, not too unusual really - but they should tell you if they're going to do this.
Use the super keyword.
Just expanding on Brent's solution.
You can do the following for a pure CSS solution, it also makes the img box actually behave like an img box in a responsive design setting (that's what the transparent png is for), which is especially useful if your design uses responsive-dynamically-resizing images.
<img style="display: none; height: auto; width:100%; background-image:
url('img/1078x501_1.jpg'); background-size: cover;" class="center-block
visible-lg-block" src="img/400x186_trans.png" alt="pic 1 mofo">
The image will only be loaded when the media query tied to visible-lg-block is triggered and display:none is changed to display:block. The transparent png is used to allow the browser to set appropriate height:width ratios for your <img> block (and thus the background-image) in a fluid design (height: auto; width: 100%).
1078/501 = ~2.15 (large screen)
400/186 = ~2.15 (small screen)
So you end up with something like the following, for 3 different viewports:
<img style="display: none; height: auto; width:100%; background-image: url('img/1078x501_1.jpg'); background-size: cover;" class="center-block visible-lg-block" src="img/400x186_trans.png" alt="pic 1">
<img style="display: none; height: auto; width:100%; background-image: url('img/517x240_1.jpg'); background-size: cover;" class="center-block visible-md-block" src="img/400x186_trans.png" alt="pic 1">
<img style="display: none; height: auto; width:100%; background-image: url('img/400x186_1.jpg'); background-size: cover;" class="center-block visible-sm-block" src="img/400x186_trans.png" alt="pic 1">
And only your default media viewport size images load during the initial load, then afterwards, depending on your viewport, images will dynamically load.
And no javascript!
Why not just change the second line to
document.location.href="www.example.com/index.php?id=" + $(this).attr('id');
The DataView object itself is used to loop through DataView rows.
DataView rows are represented by the DataRowView object. The DataRowView.Row property provides access to the original DataTable row.
C#
foreach (DataRowView rowView in dataView)
{
DataRow row = rowView.Row;
// Do something //
}
VB.NET
For Each rowView As DataRowView in dataView
Dim row As DataRow = rowView.Row
' Do something '
Next
If you read a string from an XML file, the line break \n
in this string will not work in UILabel
text. The \n
is not parsed to a line break.
Here is a little trick to solve this issue:
// correct next line \n in string from XML file
NSString *myNewLineStr = @"\n";
myLabelText = [myLabelText stringByReplacingOccurrencesOfString:@"\\n" withString:myNewLineStr];
myLabel.text = myLabelText;
So you have to replace the unparsed \n
part in your string by a parsed \n
in a hardcoded NSString
.
Here are my other label settings:
myLabel.numberOfLines = 0;
myLabel.backgroundColor = [UIColor lightGrayColor];
myLabel.textColor = [UIColor redColor];
myLabel.font = [UIFont fontWithName:@"Helvetica Neue" size:14.0];
myLabel.textAlignment = UITextAlignmentCenter;
Most important is to set numberOfLines
to 0
(= unlimited number of lines in label).
No idea why Apple has chosen to not parse \n
in strings read from XML?
Hope this helps.
I just borrow some other guys' idea and write some code below that may be helpful.
import android.content.Context;
import android.graphics.Canvas;
import android.text.Layout.Alignment;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.TextView;
public class AutoResizeTextView extends TextView {
private static final int MAX_SIZE = 1000;
private static final int MIN_SIZE = 5;
private TextPaint mTextPaint;
private float mSpacingMult = 1.0f;
private float mSpacingAdd = 0.0f;
private boolean needAdapt = false;
private boolean adapting = false;
public AutoResizeTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public AutoResizeTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public AutoResizeTextView(Context context) {
super(context);
init();
}
private void init() {
mTextPaint = new TextPaint();
}
@Override
protected void onDraw(Canvas canvas) {
if (adapting) {
return;
}
if (needAdapt) {
adaptTextSize();
} else {
super.onDraw(canvas);
}
}
private void adaptTextSize() {
CharSequence text = getText();
int viewWidth = getMeasuredWidth();
int viewHeight = getMeasuredHeight();
if (viewWidth==0 || viewHeight==0
|| TextUtils.isEmpty(text)) {
return;
}
adapting = true;
/* binary search */
int bottom=MIN_SIZE, top=MAX_SIZE, mid = 0;
while (bottom <= top) {
mid = (bottom + top)/2;
mTextPaint.setTextSize(mid);
int textWidth = (int) mTextPaint.measureText(text, 0, text.length());
int textHeight = getTextHeight(text, viewWidth);
if (textWidth<viewWidth && textHeight<viewHeight) {
bottom = mid+1;
} else {
top = mid-1;
}
}
int newSize = mid-1;
setTextSize(TypedValue.COMPLEX_UNIT_PX, newSize);
adapting=false;
needAdapt = false;
invalidate();
}
private int getTextHeight(CharSequence text, int targetWidth) {
StaticLayout layout = new StaticLayout(text, mTextPaint, targetWidth,
Alignment.ALIGN_NORMAL, mSpacingMult, mSpacingAdd, true);
return layout.getHeight();
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
needAdapt = true;
}
@Override
protected void onTextChanged(CharSequence text, int start,
int lengthBefore, int lengthAfter) {
super.onTextChanged(text, start, lengthBefore, lengthAfter);
needAdapt = true;
}
@Override
public void setLineSpacing(float add, float mult) {
super.setLineSpacing(add, mult);
mSpacingMult = mult;
mSpacingAdd = add;
}
}
First of all, I don't see the reason for having an ID that's not unique, but I guess it's an ID that connects to another table. Second there is no need for subqueries, which beats up the server. You do this in one query, like this
SELECT id,GROUP_CONCAT(name, ':', value SEPARATOR "|") FROM sample GROUP BY id
You get fast and correct results, and you can split the result by that SEPARATOR "|". I always use this separator, because it's impossible to find it inside a string, therefor it's unique. There is no problem having two A's, you identify only the value. Or you can have one more colum, with the letter, which is even better. Like this :
SELECT id,GROUP_CONCAT(DISTINCT(name)), GROUP_CONCAT(value SEPARATOR "|") FROM sample GROUP BY name
[2012-07-04 11:24:25 - The connection to adb is down, and a severe error has occurred.
[2012-07-04 11:24:25 - You must restart adb and Eclipse.
[2012-07-04 11:24:25 - Please ensure that adb is correctly located at '/home/ASDK/platform-tools/adb' and can be executed
I realized the folder of the project in Eclipse was closed. I expanded the directory and the project launched. I know this may sound like a "no-brainer". I had the .java files open on the workspace, and that was enough to make me think the project was open.
This may be old but I got this working by implenting a custom class
public class DismissKeyboardListener implements OnClickListener {
Activity mAct;
public DismissKeyboardListener(Activity act) {
this.mAct = act;
}
@Override
public void onClick(View v) {
if ( v instanceof ViewGroup ) {
hideSoftKeyboard( this.mAct );
}
}
}
public void hideSoftKeyboard(Activity activity) {
InputMethodManager imm = (InputMethodManager)
getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
}
the best practice here is to create a Helper class and every container Relative / Linear Layouts should implement this.
**** Take note only the main Container should implement this class (For optimization) ****
and implement it like this :
Parent.setOnClickListener( new DismissKeyboardListener(this) );
the keyword this is for Activity. so if you are on fragment you use like getActivity();
---thumbs up if it help you... --- cheers Ralph ---
By design the body content in ASP.NET Web API is treated as forward-only stream that can be read only once.
The first read in your case is being done when Web API is binding your model, after that the Request.Content
will not return anything.
You can remove the contact
from your action parameters, get the content and deserialize it manually into object (for example with Json.NET):
[HttpPut]
public HttpResponseMessage Put(int accountId)
{
HttpContent requestContent = Request.Content;
string jsonContent = requestContent.ReadAsStringAsync().Result;
CONTACT contact = JsonConvert.DeserializeObject<CONTACT>(jsonContent);
...
}
That should do the trick (assuming that accountId
is URL parameter so it will not be treated as content read).
You don't really need the MockitoAnnotations.initMocks(this);
if you're using mockito 1.9 ( or newer ) - all you need is this:
@InjectMocks
private MyTestObject testObject;
@Mock
private MyDependentObject mockedObject;
The @InjectMocks
annotation will inject all your mocks to the MyTestObject
object.
Use EnumerableEx.TakeLast in RX's System.Interactive assembly. It's an O(N) implementation like @Mark's, but it uses a queue rather than a ring-buffer construct (and dequeues items when it reaches buffer capacity).
(NB: This is the IEnumerable version - not the IObservable version, though the implementation of the two is pretty much identical)
you can create a function. Add maxdepth as you like for traversing subdirectories.
def findNremove(path,pattern,maxdepth=1):
cpath=path.count(os.sep)
for r,d,f in os.walk(path):
if r.count(os.sep) - cpath <maxdepth:
for files in f:
if files.endswith(pattern):
try:
print "Removing %s" % (os.path.join(r,files))
#os.remove(os.path.join(r,files))
except Exception,e:
print e
else:
print "%s removed" % (os.path.join(r,files))
path=os.path.join("/home","dir1","dir2")
findNremove(path,".bak")
If the culture of the result doesn't matters or we're only talking of integer values, CONVERT
or CAST
will be fine.
However, if the result must match a specific culture, FORMAT
might be the function to go:
DECLARE @value DECIMAL(19,4) = 1505.5698
SELECT CONVERT(NVARCHAR, @value) --> 1505.5698
SELECT FORMAT(@value, 'N2', 'en-us') --> 1,505.57
SELECT FORMAT(@value, 'N2', 'de-de') --> 1.505,57
For more information on FORMAT
see here.
Of course, formatting the result should be a matter of the UI layer of the software.
Here's a very minimal and secure implementation of a Claims based Authentication using JWT token in an ASP.NET Core Web API.
first of all, you need to expose an endpoint that returns a JWT token with claims assigned to a user:
/// <summary>
/// Login provides API to verify user and returns authentication token.
/// API Path: api/account/login
/// </summary>
/// <param name="paramUser">Username and Password</param>
/// <returns>{Token: [Token] }</returns>
[HttpPost("login")]
[AllowAnonymous]
public async Task<IActionResult> Login([FromBody] UserRequestVM paramUser, CancellationToken ct)
{
var result = await UserApplication.PasswordSignInAsync(paramUser.Email, paramUser.Password, false, lockoutOnFailure: false);
if (result.Succeeded)
{
UserRequestVM request = new UserRequestVM();
request.Email = paramUser.Email;
ApplicationUser UserDetails = await this.GetUserByEmail(request);
List<ApplicationClaim> UserClaims = await this.ClaimApplication.GetListByUser(UserDetails);
var Claims = new ClaimsIdentity(new Claim[]
{
new Claim(JwtRegisteredClaimNames.Sub, paramUser.Email.ToString()),
new Claim(UserId, UserDetails.UserId.ToString())
});
//Adding UserClaims to JWT claims
foreach (var item in UserClaims)
{
Claims.AddClaim(new Claim(item.ClaimCode, string.Empty));
}
var tokenHandler = new JwtSecurityTokenHandler();
// this information will be retrived from you Configuration
//I have injected Configuration provider service into my controller
var encryptionkey = Configuration["Jwt:Encryptionkey"];
var key = Encoding.ASCII.GetBytes(encryptionkey);
var tokenDescriptor = new SecurityTokenDescriptor
{
Issuer = Configuration["Jwt:Issuer"],
Subject = Claims,
// this information will be retrived from you Configuration
//I have injected Configuration provider service into my controller
Expires = DateTime.UtcNow.AddMinutes(Convert.ToDouble(Configuration["Jwt:ExpiryTimeInMinutes"])),
//algorithm to sign the token
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
var tokenString = tokenHandler.WriteToken(token);
return Ok(new
{
token = tokenString
});
}
return BadRequest("Wrong Username or password");
}
now you need to Add Authentication to your services in your ConfigureServices
inside your startup.cs to add JWT authentication as your default authentication service like this:
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(cfg =>
{
cfg.RequireHttpsMetadata = false;
cfg.SaveToken = true;
cfg.TokenValidationParameters = new TokenValidationParameters()
{
//ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JWT:Encryptionkey"])),
ValidateAudience = false,
ValidateLifetime = true,
ValidIssuer = configuration["Jwt:Issuer"],
//ValidAudience = Configuration["Jwt:Audience"],
//IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWT:Key"])),
};
});
now you can add policies to your authorization services like this:
services.AddAuthorization(options =>
{
options.AddPolicy("YourPolicyNameHere",
policy => policy.RequireClaim("YourClaimNameHere"));
});
ALTERNATIVELY, You can also (not necessary) populate all of your claims from your database as this will only run once on your application startup and add them to policies like this:
services.AddAuthorization(async options =>
{
var ClaimList = await claimApplication.GetList(applicationClaim);
foreach (var item in ClaimList)
{
options.AddPolicy(item.ClaimCode, policy => policy.RequireClaim(item.ClaimCode));
}
});
now you can put the Policy filter on any of the methods that you want to be authorized like this:
[HttpPost("update")]
[Authorize(Policy = "ACC_UP")]
public async Task<IActionResult> Update([FromBody] UserRequestVM requestVm, CancellationToken ct)
{
//your logic goes here
}
Hope this helps
Here's a really helpful overview of when to base64 encode and when not to by David Calhoun.
Basic answer = gzipped base64 encoded files will be roughly comparable in file size to standard binary (jpg/png). Gzip'd binary files will have a smaller file size.
Takeaway = There's some advantage to encoding and gzipping your UI icons, etc, but unwise to do this for larger images.
Try:
SELECT COALESCE(NULLIF(field, ''), another_field) FROM table_name
Run ps aux | grep nodejs
, find the PID of the process you're looking for, then run kill
starting with SIGTERM (kill -15 25239
). If that doesn't work then use SIGKILL instead, replacing -15
with -9
.
int val1 = [textBox1.text integerValue];
int val2 = [textBox2.text integerValue];
int resultValue = val1 * val2;
textBox3.text = [NSString stringWithFormat: @"%d", resultValue];
For me it didn't work , it was related to a path problem happened after android studio 2.0 preview 1, I needed to update genymotion and virtual box, and apparently they tried to use same port for adb.
Solution is explained here link! Basically you just need to:
1) open genymotion settings
2) specify sdk path for the adb manually
3) adb kill-server
4) adb start-server
std::hex
is defined in <ios>
which is included by <iostream>
. But to use things like std::setprecision/std::setw/std::setfill
/etc you have to include <iomanip>
.
#import "E_LabelWithPadding.h"
#define padding UIEdgeInsetsMake(2, 0, 2, 0)
#define padding1 UIEdgeInsetsMake(0, 0, 0, 0)
@implementation E_LabelWithPadding
- (void)drawTextInRect:(CGRect)rect {
if (![self.text isEqualToString:@""]) {
[super drawTextInRect:UIEdgeInsetsInsetRect(rect, padding)];
}else {
[super drawTextInRect:UIEdgeInsetsInsetRect(rect, padding1)];
}
}
- (CGSize) intrinsicContentSize {
if (![self.text isEqualToString:@""]) {
CGSize superContentSize = [super intrinsicContentSize];
CGFloat width = superContentSize.width + padding.left + padding.right;
CGFloat height = superContentSize.height + padding.top + padding.bottom;
return CGSizeMake(width, height);
}else {
CGSize superContentSize = [super intrinsicContentSize];
CGFloat width = superContentSize.width + padding1.left + padding1.right;
CGFloat height = superContentSize.height + padding1.top + padding1.bottom;
return CGSizeMake(width, height);
}
}
- (CGSize) sizeThatFits:(CGSize)size {
if (![self.text isEqualToString:@""]) {
CGSize superSizeThatFits = [super sizeThatFits:size];
CGFloat width = superSizeThatFits.width + padding.left + padding.right;
CGFloat height = superSizeThatFits.height + padding.top + padding.bottom;
return CGSizeMake(width, height);
}else {
CGSize superSizeThatFits = [super sizeThatFits:size];
CGFloat width = superSizeThatFits.width + padding1.left + padding1.right;
CGFloat height = superSizeThatFits.height + padding1.top + padding1.bottom;
return CGSizeMake(width, height);
}
}
@end
TMTOWTDI, chose the method that best fits how you work. I use the environment method so I don't have to think about it.
In the environment:
export PERL_UNICODE=SDL
on the command line:
perl -CSDL -le 'print "\x{1815}"';
or with binmode:
binmode(STDOUT, ":utf8"); #treat as if it is UTF-8
binmode(STDIN, ":encoding(utf8)"); #actually check if it is UTF-8
or with PerlIO:
open my $fh, ">:utf8", $filename
or die "could not open $filename: $!\n";
open my $fh, "<:encoding(utf-8)", $filename
or die "could not open $filename: $!\n";
or with the open pragma:
use open ":encoding(utf8)";
use open IN => ":encoding(utf8)", OUT => ":utf8";
Stuart's answer provides a great explanation, but I'd like to provide another example.
I ran into this issue when attempting to perform a reduce
on a Stream containing null values (actually it was LongStream.average()
, which is a type of reduction). Since average() returns OptionalDouble
, I assumed the Stream could contain nulls but instead a NullPointerException was thrown. This is due to Stuart's explanation of null v. empty.
So, as the OP suggests, I added a filter like so:
list.stream()
.filter(o -> o != null)
.reduce(..);
Or as tangens pointed out below, use the predicate provided by the Java API:
list.stream()
.filter(Objects::nonNull)
.reduce(..);
From the mailing list discussion Stuart linked: Brian Goetz on nulls in Streams
It seems like You haven't set the Mysql server path, Set Environment Variable For MySql Server. Then restart the command prompt and enter mysql -u root-p then it asks for a password enter it. Thank you. Happy learning!
You can use options.display.max_colwidth
to specify you want to see more in the default representation:
In [2]: df
Out[2]:
one
0 one
1 two
2 This is very long string very long string very...
In [3]: pd.options.display.max_colwidth
Out[3]: 50
In [4]: pd.options.display.max_colwidth = 100
In [5]: df
Out[5]:
one
0 one
1 two
2 This is very long string very long string very long string veryvery long string
And indeed, if you just want to inspect the one value, by accessing it (as a scalar, not as a row as df.iloc[2]
does) you also see the full string:
In [7]: df.iloc[2,0] # or df.loc[2,'one']
Out[7]: 'This is very long string very long string very long string veryvery long string'
I use following mixin:
from django.forms.models import model_to_dict
class ModelDiffMixin(object):
"""
A model mixin that tracks model fields' values and provide some useful api
to know what fields have been changed.
"""
def __init__(self, *args, **kwargs):
super(ModelDiffMixin, self).__init__(*args, **kwargs)
self.__initial = self._dict
@property
def diff(self):
d1 = self.__initial
d2 = self._dict
diffs = [(k, (v, d2[k])) for k, v in d1.items() if v != d2[k]]
return dict(diffs)
@property
def has_changed(self):
return bool(self.diff)
@property
def changed_fields(self):
return self.diff.keys()
def get_field_diff(self, field_name):
"""
Returns a diff for field if it's changed and None otherwise.
"""
return self.diff.get(field_name, None)
def save(self, *args, **kwargs):
"""
Saves model and set initial state.
"""
super(ModelDiffMixin, self).save(*args, **kwargs)
self.__initial = self._dict
@property
def _dict(self):
return model_to_dict(self, fields=[field.name for field in
self._meta.fields])
Usage:
>>> p = Place()
>>> p.has_changed
False
>>> p.changed_fields
[]
>>> p.rank = 42
>>> p.has_changed
True
>>> p.changed_fields
['rank']
>>> p.diff
{'rank': (0, 42)}
>>> p.categories = [1, 3, 5]
>>> p.diff
{'categories': (None, [1, 3, 5]), 'rank': (0, 42)}
>>> p.get_field_diff('categories')
(None, [1, 3, 5])
>>> p.get_field_diff('rank')
(0, 42)
>>>
Please note that this solution works well in context of current request only. Thus it's suitable primarily for simple cases. In concurrent environment where multiple requests can manipulate the same model instance at the same time, you definitely need a different approach.
Actually the answer to the first part of the question is "Yes" in every programming language. For example, this is in the case of C/C++:
#define a (b++)
int b = 1;
if (a ==1 && a== 2 && a==3) {
std::cout << "Yes, it's possible!" << std::endl;
} else {
std::cout << "it's impossible!" << std::endl;
}
//Sets the row color depending on the value in the "Status" column.
function setRowColors() {
var range = SpreadsheetApp.getActiveSheet().getDataRange();
var statusColumnOffset = getStatusColumnOffset();
for (var i = range.getRow(); i < range.getLastRow(); i++) {
rowRange = range.offset(i, 0, 1);
status = rowRange.offset(0, statusColumnOffset).getValue();
if (status == 'Completed') {
rowRange.setBackgroundColor("#99CC99");
} else if (status == 'In Progress') {
rowRange.setBackgroundColor("#FFDD88");
} else if (status == 'Not Started') {
rowRange.setBackgroundColor("#CC6666");
}
}
}
//Returns the offset value of the column titled "Status"
//(eg, if the 7th column is labeled "Status", this function returns 6)
function getStatusColumnOffset() {
lastColumn = SpreadsheetApp.getActiveSheet().getLastColumn();
var range = SpreadsheetApp.getActiveSheet().getRange(1,1,1,lastColumn);
for (var i = 0; i < range.getLastColumn(); i++) {
if (range.offset(0, i, 1, 1).getValue() == "Status") {
return i;
}
}
}
You're after the zip function.
Taken directly from the question: How to merge lists into a list of tuples in Python?
>>> list_a = [1, 2, 3, 4]
>>> list_b = [5, 6, 7, 8]
>>> zip(list_a,list_b)
[(1, 5), (2, 6), (3, 7), (4, 8)]
Couldn't find any definitive reference, but I see that the example code for os.walk uses os.path but only imports os
1 You can use a drawable
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/menu_item1"
android:icon="@drawable/my_item_drawable"
android:title="@string/menu_item1"
android:showAsAction="ifRoom" />
</menu>
2 Create a style for the action bar and use a custom background:
<resources>
<!-- the theme applied to the application or activity -->
<style name="CustomActivityTheme" parent="@android:style/Theme.Holo">
<item name="android:actionBarStyle">@style/MyActionBar</item>
<!-- other activity and action bar styles here -->
</style>
<!-- style for the action bar backgrounds -->
<style name="MyActionBar" parent="@android:style/Widget.Holo.ActionBar">
<item name="android:background">@drawable/background</item>
<item name="android:backgroundStacked">@drawable/background</item>
<item name="android:backgroundSplit">@drawable/split_background</item>
</style>
</resources>
3 Style again android:actionBarDivider
The android documentation is very usefull for that.
Yes, you should think of defining both your functions in a Class, and making word a member. This is cleaner :
class Spam:
def oneFunction(self,lists):
category=random.choice(list(lists.keys()))
self.word=random.choice(lists[category])
def anotherFunction(self):
for letter in self.word:
print("_", end=" ")
Once you make a Class you have to Instantiate it to an Object and access the member functions
s = Spam()
s.oneFunction(lists)
s.anotherFunction()
Another approach would be to make oneFunction
return the word so that you can use oneFunction
instead of word
in anotherFunction
>>> def oneFunction(lists):
category=random.choice(list(lists.keys()))
return random.choice(lists[category])
>>> def anotherFunction():
for letter in oneFunction(lists):
print("_", end=" ")
And finally, you can also make anotherFunction
, accept word
as a parameter which you can pass from the result of calling oneFunction
>>> def anotherFunction(words):
for letter in words:
print("_",end=" ")
>>> anotherFunction(oneFunction(lists))
The first time I realized that the Unit testing project referenced the app.config in that project rather then the app.config associated with my production code project (off course, DOH) I just added a line in the Post Build Event of the Prod project that will copy the app.config to the bin folder of the test project.
Problem solved
I haven't noticed any weird side effects so far, but I am not sure that this is the right solution, but at least it seems to work.
Arguments
property in Execute Process Task available on the Control Flow tab is expecting a value of data type DT_WSTR
and not DT_STR
.
Create an SSIS package in Business Intelligence Development Studio (BIDS) 2008 R2 and name it as SO_13177007.dtsx
. Create a package variable with the following information.
Name Scope Data Type Value
------ ------------ ---------- -----
IdVar SO_13177007 Int32 123
Drag and drop an Execute Process Task onto the Control Flow tab and name it as Pass arguments
Double-click the Execute Process Task to open the Execute Process Task Editor
. Click Expressions page and then click the Ellipsis button against the Expressions property to view the Property Expression Editor
.
On the Property Expression Editor, select the property Arguments
and click the Ellipsis button against the property to open the Expression Builder
.
On the Expression Builder, enter the following expression and click Evaluate Expression
. This expression tries to convert the integer value in the variable IdVar
to string data type.
(DT_STR, 10, 1252) @[User::IdVar]
Clicking Evaluate Expression will display the following error message because the Arguments property on Execute Process Task expects a value of data type DT_WSTR
.
To fix the issue, update the expression as shown below to convert the integer value to data type DT_WSTR
. Clicking Evaluate Expression will display the value in the Evaluated value text area.
(DT_WSTR, 10) @[User::IdVar]
To understand the differences between the data types DT_STR
and DT_WSTR
in SSIS, read the documentation Integration Services Data Types on MSDN. Here are the quotes from the documentation about these two string data types.
A null-terminated ANSI/MBCS character string with a maximum length of 8000 characters. (If a column value contains additional null terminators, the string will be truncated at the occurrence of the first null.)
A null-terminated Unicode character string with a maximum length of 4000 characters. (If a column value contains additional null terminators, the string will be truncated at the occurrence of the first null.)
You could try this:
SELECT *
FROM table
ORDER BY (c_counts+f_counts)
LIMIT 20
A default/non-bare Git repo contains two pieces of state:
The snapshot is what you probably think of as your project: your code files, build files, helper scripts, and anything else you version with Git.
The history is the state that allows you to check out a different commit and get a complete snapshot of what the files in your repository looked like when that commit was added. It consists of a bunch of data structures that are internal to Git that you've probably never interacted with directly. Importantly, the history doesn't just store metadata (e.g. "User U added this many lines to File F at Time T as part of Commit C"), it also stores data (e.g. "User U added these exact lines to File F").
The key idea of a bare repository is that you don't actually need to have the snapshot. Git keeps the snapshot around because it's convenient for humans and other non-Git processes that want to interact with your code, but the snapshot is just duplicating state that's already in the history.
A bare repository is a Git repository that does not have a snapshot. It just stores the history.
Why would you want this? Well, if you're only going to interact with your files using Git (that is, you're not going to edit your files directly or use them to build an executable), you can save space by not keeping around the snapshot. In particular, if you're maintaining a centralized version of your repo on a server somewhere (i.e. you're basically hosting your own GitHub), that server should probably have a bare repo (you would still use a non-bare repo on your local machine though, since you'll presumably want to edit your snapshot).
If you want a more in-depth explanation of bare repos and another example use case, I wrote up a blog post here: https://stegosaurusdormant.com/bare-git-repo/
Take a look at TOMEE
It has all the features that you need to build a complete Java EE app.
This can also happen when using an old version of Java that isn't capable of communicating properly with the HTTPS protocol that is now required. Version 8 and above should work as of the time writing this.
Use to_datetime
, there is no need for a format string the parser is man/woman enough to handle it:
In [51]:
pd.to_datetime(df['I_DATE'])
Out[51]:
0 2012-03-28 14:15:00
1 2012-03-28 14:17:28
2 2012-03-28 14:50:50
Name: I_DATE, dtype: datetime64[ns]
To access the date/day/time component use the dt
accessor:
In [54]:
df['I_DATE'].dt.date
Out[54]:
0 2012-03-28
1 2012-03-28
2 2012-03-28
dtype: object
In [56]:
df['I_DATE'].dt.time
Out[56]:
0 14:15:00
1 14:17:28
2 14:50:50
dtype: object
You can use strings to filter as an example:
In [59]:
df = pd.DataFrame({'date':pd.date_range(start = dt.datetime(2015,1,1), end = dt.datetime.now())})
df[(df['date'] > '2015-02-04') & (df['date'] < '2015-02-10')]
Out[59]:
date
35 2015-02-05
36 2015-02-06
37 2015-02-07
38 2015-02-08
39 2015-02-09
If you want to kill the Sticky Service,the following command NOT WORKING:
adb shell am force-stop <PACKAGE>
adb shell kill <PID>
The following command is WORKING:
adb shell pm disable <PACKAGE>
If you want to restart the app,you must run command below first:
adb shell pm enable <PACKAGE>
Here's a function I made as part of a new String class... It allows adding a suffix ( if the string is size after trimming and adding it is long enough - although you don't need to force the absolute size )
I was in the process of changing a few things around so there are some useless logic costs ( if _truncate ... for instance ) where it is no longer necessary and there is a return at the top...
But, it is still a good function for truncating data...
##
## Truncate characters of a string after _len'nth char, if necessary... If _len is less than 0, don't truncate anything... Note: If you attach a suffix, and you enable absolute max length then the suffix length is subtracted from max length... Note: If the suffix length is longer than the output then no suffix is used...
##
## Usage: Where _text = 'Testing', _width = 4
## _data = String.Truncate( _text, _width ) == Test
## _data = String.Truncate( _text, _width, '..', True ) == Te..
##
## Equivalent Alternates: Where _text = 'Testing', _width = 4
## _data = String.SubStr( _text, 0, _width ) == Test
## _data = _text[ : _width ] == Test
## _data = ( _text )[ : _width ] == Test
##
def Truncate( _text, _max_len = -1, _suffix = False, _absolute_max_len = True ):
## Length of the string we are considering for truncation
_len = len( _text )
## Whether or not we have to truncate
_truncate = ( False, True )[ _len > _max_len ]
## Note: If we don't need to truncate, there's no point in proceeding...
if ( not _truncate ):
return _text
## The suffix in string form
_suffix_str = ( '', str( _suffix ) )[ _truncate and _suffix != False ]
## The suffix length
_len_suffix = len( _suffix_str )
## Whether or not we add the suffix
_add_suffix = ( False, True )[ _truncate and _suffix != False and _max_len > _len_suffix ]
## Suffix Offset
_suffix_offset = _max_len - _len_suffix
_suffix_offset = ( _max_len, _suffix_offset )[ _add_suffix and _absolute_max_len != False and _suffix_offset > 0 ]
## The truncate point.... If not necessary, then length of string.. If necessary then the max length with or without subtracting the suffix length... Note: It may be easier ( less logic cost ) to simply add the suffix to the calculated point, then truncate - if point is negative then the suffix will be destroyed anyway.
## If we don't need to truncate, then the length is the length of the string.. If we do need to truncate, then the length depends on whether we add the suffix and offset the length of the suffix or not...
_len_truncate = ( _len, _max_len )[ _truncate ]
_len_truncate = ( _len_truncate, _max_len )[ _len_truncate <= _max_len ]
## If we add the suffix, add it... Suffix won't be added if the suffix is the same length as the text being output...
if ( _add_suffix ):
_text = _text[ 0 : _suffix_offset ] + _suffix_str + _text[ _suffix_offset: ]
## Return the text after truncating...
return _text[ : _len_truncate ]
So far the best solution to accept seems to be <img class="center-block" ... />
. But no one has mentioned how center-block
works.
Take Bootstrap v3.3.6 for example:
.center-block {
display: block;
margin-right: auto;
margin-left: auto;
}
The default value of dispaly
for <img>
is inline
. Value block
will display an element as a block element (like <p>
). It starts on a new line, and takes up the whole width. In this way, the two margin settings let the image stay in the middle horizontally.
It's probably easiest to create your query object directly as:
Test.find({
$and: [
{ $or: [{a: 1}, {b: 1}] },
{ $or: [{c: 1}, {d: 1}] }
]
}, function (err, results) {
...
}
But you can also use the Query#and
helper that's available in recent 3.x Mongoose releases:
Test.find()
.and([
{ $or: [{a: 1}, {b: 1}] },
{ $or: [{c: 1}, {d: 1}] }
])
.exec(function (err, results) {
...
});
There is also a convenient shortcut to get all elements of the array starting with specified index. For example "${A[@]:1}" would be the "tail" of the array, that is the array without its first element.
version=4.7.1
A=( ${version//\./ } )
echo "${A[@]}" # 4 7 1
B=( "${A[@]:1}" )
echo "${B[@]}" # 7 1
From C# specifications:
var f = 0f; // float
var d = 0d; // double
var m = 0m; // decimal (money)
var u = 0u; // unsigned int
var l = 0l; // long
var ul = 0ul; // unsigned long
Note that you can use an uppercase or lowercase notation.
You could probably use a set object instead. Just add
numbers to the set. They inherently do not replicate.
You code is ok only except that you can't add same class test1
.
$('.page-address-edit').addClass('test1').addClass('test2'); //this will add test1 and test2
And you could also do
$('.page-address-edit').addClass('test1 test2');
Here is an elegant way to do similar thing. But why do partly JSON unmarshal? That doesn't make sense.
Look below at the working code. Copy and paste it.
import (
"bytes"
"encoding/json" // Encoding and Decoding Package
"fmt"
)
var messeging = `{
"say":"Hello",
"sendMsg":{
"user":"ANisus",
"msg":"Trying to send a message"
}
}`
type SendMsg struct {
User string `json:"user"`
Msg string `json:"msg"`
}
type Chat struct {
Say string `json:"say"`
SendMsg *SendMsg `json:"sendMsg"`
}
func main() {
/** Clean way to solve Json Decoding in Go */
/** Excellent solution */
var chat Chat
r := bytes.NewReader([]byte(messeging))
chatErr := json.NewDecoder(r).Decode(&chat)
errHandler(chatErr)
fmt.Println(chat.Say)
fmt.Println(chat.SendMsg.User)
fmt.Println(chat.SendMsg.Msg)
}
func errHandler(err error) {
if err != nil {
fmt.Println(err)
return
}
}
Cygwin mount
now support bind method which lets you mount a directory. Hence you can simply add the following line to /etc/fstab
, then restart your shell:
c:/Users /home none bind 0 0
print my_string[0:100]
$scope
objectAngular maintains a simple array
of watchers in the $scope
objects. If you inspect any $scope
you will find that it contains an array
called $$watchers
.
Each watcher is an object
that contains among other things
attribute
name, or something more complicated.$scope
as dirty.There are many different ways of defining a watcher in AngularJS.
You can explicitly $watch
an attribute
on $scope
.
$scope.$watch('person.username', validateUnique);
You can place a {{}}
interpolation in your template (a watcher will be created for you on the current $scope
).
<p>username: {{person.username}}</p>
You can ask a directive such as ng-model
to define the watcher for you.
<input ng-model="person.username" />
$digest
cycle checks all watchers against their last valueWhen we interact with AngularJS through the normal channels (ng-model, ng-repeat, etc) a digest cycle will be triggered by the directive.
A digest cycle is a depth-first traversal of $scope
and all its children. For each $scope
object
, we iterate over its $$watchers
array
and evaluate all the expressions. If the new expression value is different from the last known value, the watcher's function is called. This function might recompile part of the DOM, recompute a value on $scope
, trigger an AJAX
request
, anything you need it to do.
Every scope is traversed and every watch expression evaluated and checked against the last value.
$scope
is dirtyIf a watcher is triggered, the app knows something has changed, and the $scope
is marked as dirty.
Watcher functions can change other attributes on $scope
or on a parent $scope
. If one $watcher
function has been triggered, we can't guarantee that our other $scope
s are still clean, and so we execute the entire digest cycle again.
This is because AngularJS has two-way binding, so data can be passed back up the $scope
tree. We may change a value on a higher $scope
that has already been digested. Perhaps we change a value on the $rootScope
.
$digest
is dirty, we execute the entire $digest
cycle againWe continually loop through the $digest
cycle until either the digest cycle comes up clean (all $watch
expressions have the same value as they had in the previous cycle), or we reach the digest limit. By default, this limit is set at 10.
If we reach the digest limit AngularJS will raise an error in the console:
10 $digest() iterations reached. Aborting!
As you can see, every time something changes in an AngularJS app, AngularJS will check every single watcher in the $scope
hierarchy to see how to respond. For a developer this is a massive productivity boon, as you now need to write almost no wiring code, AngularJS will just notice if a value has changed, and make the rest of the app consistent with the change.
From the perspective of the machine though this is wildly inefficient and will slow our app down if we create too many watchers. Misko has quoted a figure of about 4000 watchers before your app will feel slow on older browsers.
This limit is easy to reach if you ng-repeat
over a large JSON
array
for example. You can mitigate against this using features like one-time binding to compile a template without creating watchers.
Each time your user interacts with your app, every single watcher in your app will be evaluated at least once. A big part of optimising an AngularJS app is reducing the number of watchers in your $scope
tree. One easy way to do this is with one time binding.
If you have data which will rarely change, you can bind it only once using the :: syntax, like so:
<p>{{::person.username}}</p>
or
<p ng-bind="::person.username"></p>
The binding will only be triggered when the containing template is rendered and the data loaded into $scope
.
This is especially important when you have an ng-repeat
with many items.
<div ng-repeat="person in people track by username">
{{::person.username}}
</div>
Usually two arrays will have some small numeric errors,
You can use numpy.allclose(A,B)
, instead of (A==B).all()
. This returns a bool True/False
Close Android Studio and delete .idea and .gradle folder from project structure and start Studio again.