Starting with TypeScript 2.2 using dot notation to access indexed properties is allowed. You won't get error TS2339 on your example.
See Dotted property for types with string index signatures in TypeScript 2.2 release note.
According to the docs: May 17, 2017
When your app is in the background, Android directs notification messages to the system tray. A user tap on the notification opens the app launcher by default.
This includes messages that contain both notification and data payload (and all messages sent from the Notifications console). In these cases, the notification is delivered to the device's system tray, and the data payload is delivered in the extras of the intent of your launcher Activity.
So,you should use both of the payload notification + data:
{
"to": "FCM registration ID",
"notification": {
"title" : "title",
"body" : "body text",
"icon" : "ic_notification"
},
"data": {
"someData" : "This is some data",
"someData2" : "etc"
}
}
There is no need to use click_action.You should just get exras from intent on LAUNCHER activity
<activity android:name=".MainActivity">
<intent-filter>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Java code should be on onCreate method on MainActivity :
Intent intent = getIntent();
if (intent != null && intent.getExtras() != null) {
Bundle extras = intent.getExtras();
String someData= extras.getString("someData");
String someData2 = extras.getString("someData2");
}
You can test both of the payload notification + data from Firebase Notifications Console . Don't forget to fill custom data fields on Advanced options section
The SIMPLEST answer is to put "data" into a pair of square brackets (i.e. [data]):
$.getJSON("json/products.json").done(function (data) {
var allProducts = [data].map(function (item) {
return new getData(item);
});
});
Here, [data] is an array, and the ".map" method can be used on it. It works for me!
Note - if you want to pass a data attribute to a React Component, you need to handle them a little differently than other props.
2 options
Don't use camel case
<Option data-img-src='value' ... />
And then in the component, because of the dashes, you need to refer to the prop in quotes.
// @flow
class Option extends React.Component {
props: {
'data-img-src': string
}
And when you refer to it later, you don't use the dot syntax
render () {
return (
<option data-img-src={this.props['data-img-src']} >...</option>
)
}
}
Or use camel case
<Option dataImgSrc='value' ... />
And then in the component, you need to convert.
// @flow
class Option extends React.Component {
props: {
dataImgSrc: string
}
And when you refer to it later, you don't use the dot syntax
render () {
return (
<option data-img-src={this.props.dataImgSrc} >...</option>
)
}
}
Mainly just realize data-
attributes and aria-
attributes are treated specially. You are allowed to use hyphens in the attribute name in those two cases.
You should retrieve RecyclerView
in a Fragment
after inflating core View using that View. Perhaps it can't find your recycler because it's not part of Activity
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_artist_tracks, container, false);
final FragmentActivity c = getActivity();
final RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
LinearLayoutManager layoutManager = new LinearLayoutManager(c);
recyclerView.setLayoutManager(layoutManager);
new Thread(new Runnable() {
@Override
public void run() {
final RecyclerAdapter adapter = new RecyclerAdapter(c);
c.runOnUiThread(new Runnable() {
@Override
public void run() {
recyclerView.setAdapter(adapter);
}
});
}
}).start();
return view;
}
when you define any variable as a optional then you need to unwrap that optional value.Convert ? to !
UPDATED
For python 3, you should use items()
instead of iteritems()
PYTHON 2
for attr, value in k.__dict__.iteritems():
print attr, value
PYTHON 3
for attr, value in k.__dict__.items():
print(attr, value)
This will print
'names', [a list with names]
'tweet', [a list with tweet]
For caching, I would use OkHttp interceptors to gain control over caching policy. Check out this sample that's included in the OkHttp library.
RewriteResponseCacheControl.java
Here's how I'd use it with Picasso -
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.networkInterceptors().add(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder().header("Cache-Control", "max-age=" + (60 * 60 * 24 * 365)).build();
}
});
okHttpClient.setCache(new Cache(mainActivity.getCacheDir(), Integer.MAX_VALUE));
OkHttpDownloader okHttpDownloader = new OkHttpDownloader(okHttpClient);
Picasso picasso = new Picasso.Builder(mainActivity).downloader(okHttpDownloader).build();
picasso.load(imageURL).into(viewHolder.image);
Unless google serves this image with the correct Access-Control-Allow-Origin
header, then you wont be able to use their image in canvas. This is due to not having CORS
approval. You can read more about this here, but it essentially means:
Although you can use images without CORS approval in your canvas, doing so taints the canvas. Once a canvas has been tainted, you can no longer pull data back out of the canvas. For example, you can no longer use the canvas toBlob(), toDataURL(), or getImageData() methods; doing so will throw a security error.
This protects users from having private data exposed by using images to pull information from remote web sites without permission.
I suggest just passing the URL to your server-side language and using curl to download the image. Be careful to sanitise this though!
EDIT:
As this answer is still the accepted answer, you should check out @shadyshrif's answer, which is to use:
var img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.src = url;
This will only work if you have the correct permissions, but will at least allow you to do what you want.
See this tutorial: Loading images with native JavaScript and handling of events for showing loading spinners
It tells you how to load images with native JavaScript and how to handle events for showing loading spinners. Basically, you create a new Image(); and handle the event correctly then. That should work in all browsers, even in IE7 (maybe even below IE7, but I did not test that...)
In view file (HTML or EJS)
<div ng-repeat="item in vm.itemList | filter: myFilter > </div>
and In Controller
$scope.myFilter = function(item) {
return (item.propertyA === 'value' || item.propertyA === 'value');
}
Here's how I would re-align my uiviews to get your solution:
I created a thumb rule of my own. Whenever you have to hide / show any uiview whose constraints might be affected, add all the affected / dependent subviews inside a uiview and update its leading / trailing / top / bottom constraint constant programmatically.
I just want to post my solution. Previous answers was pretty helpful for my research. I use length-stream to get the size of the stream, but the problem here is that the callback is fired near the end of the stream, so i also use stream-cache to cache the stream and pipe it to res object once i know the content-length. In case on an error,
var StreamCache = require('stream-cache');
var lengthStream = require('length-stream');
var _streamFile = function(res , stream , cb){
var cache = new StreamCache();
var lstream = lengthStream(function(length) {
res.header("Content-Length", length);
cache.pipe(res);
});
stream.on('error', function(err){
return cb(err);
});
stream.on('end', function(){
return cb(null , true);
});
return stream.pipe(lstream).pipe(cache);
}
Another alternative (other than binary operators suggested by @jm-) is to use ng-switch:
<span ng-switch on="interface">
<img ng-switch-when="UP" src='green-checkmark.png'>
<img ng-switch-default src='big-black-X.png'>
</span>
ng-switch will likely be better/easier if you have more than two images.
Following is how one can configure $locationProvider using requireBase=false
flag to avoid setting base href <head><base href="/"></head>
:
var app = angular.module("hwapp", ['ngRoute']);
app.config(function($locationProvider){
$locationProvider.html5Mode({
enabled: true,
requireBase: false
})
});
Here is a demo code where there is pagination + Filtering with AngularJS :
https://codepen.io/lamjaguar/pen/yOrVym
JS :
var app=angular.module('myApp', []);
// alternate - https://github.com/michaelbromley/angularUtils/tree/master/src/directives/pagination
// alternate - http://fdietz.github.io/recipes-with-angular-js/common-user-interface-patterns/paginating-through-client-side-data.html
app.controller('MyCtrl', ['$scope', '$filter', function ($scope, $filter) {
$scope.currentPage = 0;
$scope.pageSize = 10;
$scope.data = [];
$scope.q = '';
$scope.getData = function () {
// needed for the pagination calc
// https://docs.angularjs.org/api/ng/filter/filter
return $filter('filter')($scope.data, $scope.q)
/*
// manual filter
// if u used this, remove the filter from html, remove above line and replace data with getData()
var arr = [];
if($scope.q == '') {
arr = $scope.data;
} else {
for(var ea in $scope.data) {
if($scope.data[ea].indexOf($scope.q) > -1) {
arr.push( $scope.data[ea] );
}
}
}
return arr;
*/
}
$scope.numberOfPages=function(){
return Math.ceil($scope.getData().length/$scope.pageSize);
}
for (var i=0; i<65; i++) {
$scope.data.push("Item "+i);
}
// A watch to bring us back to the
// first pagination after each
// filtering
$scope.$watch('q', function(newValue,oldValue){ if(oldValue!=newValue){
$scope.currentPage = 0;
}
},true);
}]);
//We already have a limitTo filter built-in to angular,
//let's make a startFrom filter
app.filter('startFrom', function() {
return function(input, start) {
start = +start; //parse to int
return input.slice(start);
}
});
HTML :
<div ng-app="myApp" ng-controller="MyCtrl">
<input ng-model="q" id="search" class="form-control" placeholder="Filter text">
<select ng-model="pageSize" id="pageSize" class="form-control">
<option value="5">5</option>
<option value="10">10</option>
<option value="15">15</option>
<option value="20">20</option>
</select>
<ul>
<li ng-repeat="item in data | filter:q | startFrom:currentPage*pageSize | limitTo:pageSize">
{{item}}
</li>
</ul>
<button ng-disabled="currentPage == 0" ng-click="currentPage=currentPage-1">
Previous
</button> {{currentPage+1}}/{{numberOfPages()}}
<button ng-disabled="currentPage >= getData().length/pageSize - 1" ng-click="currentPage=currentPage+1">
Next
</button>
</div>
This worked for me, converts to nested JSON to easy to read YAML
string JSONDeserialized {get; set;}
public int indentLevel;
private bool JSONDictionarytoYAML(Dictionary<string, object> dict)
{
bool bSuccess = false;
indentLevel++;
foreach (string strKey in dict.Keys)
{
string strOutput = "".PadLeft(indentLevel * 3) + strKey + ":";
JSONDeserialized+="\r\n" + strOutput;
object o = dict[strKey];
if (o is Dictionary<string, object>)
{
JSONDictionarytoYAML((Dictionary<string, object>)o);
}
else if (o is ArrayList)
{
foreach (object oChild in ((ArrayList)o))
{
if (oChild is string)
{
strOutput = ((string)oChild);
JSONDeserialized += strOutput + ",";
}
else if (oChild is Dictionary<string, object>)
{
JSONDictionarytoYAML((Dictionary<string, object>)oChild);
JSONDeserialized += "\r\n";
}
}
}
else
{
strOutput = o.ToString();
JSONDeserialized += strOutput;
}
}
indentLevel--;
return bSuccess;
}
usage
Dictionary<string, object> JSONDic = new Dictionary<string, object>();
JavaScriptSerializer js = new JavaScriptSerializer();
try {
JSONDic = js.Deserialize<Dictionary<string, object>>(inString);
JSONDeserialized = "";
indentLevel = 0;
DisplayDictionary(JSONDic);
return JSONDeserialized;
}
catch (Exception)
{
return "Could not parse input JSON string";
}
I checked your code and seems to be no problem at all. please make sure Image commandArgument getting value. check it first binding in label whether you are getting value.
However, here is sample which I'm using in my project
<asp:GridView ID="GridViewUserScraps" ItemStyle-VerticalAlign="Top" AutoGenerateColumns="False" Width="100%" runat="server" OnRowCommand="GridViews_RowCommand" >
<Columns>
<asp:TemplateField SortExpression="SendDate">
<ItemTemplate>
<asp:Button ID="btnPost" CssClass="submitButton" Text="Comment" runat="server" CommandName="Comment" CommandArgument='<%#Eval("ScrapId")+","+ Eval("UserId")%>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
first bind the GridView.
public void GetData()
{
//bind ur GridView
GridViewUserScraps.DataSource = dt;
GridViewUserScraps.DataBind();
}
protected void GridViews_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Comment")
{
string[] commandArgs = e.CommandArgument.ToString().Split(new char[] { ',' });
string scrapid = commandArgs[0];
string uid = commandArgs[1];
}
}
You might want to do it like this:
DateTime? lastPostDate = (DateTime?)(reader.IsDbNull(3) ? null : reader[3]);
The problem you are having is that the ternary operator wants a viable cast between the left and right sides. And null can't be cast to DateTime.
Note the above works because both sides of the ternary are object's. The object is explicitly cast to DateTime? which works: as long as reader[3] is in fact a date.
Maybe a fixed height
and overflow-y: scroll;
Just try encodeURI()
and encodeURIComponent()
yourself...
console.log(encodeURIComponent('@#$%^&*'));
_x000D_
Input: @#$%^&*
. Output: %40%23%24%25%5E%26*
. So, wait, what happened to *
? Why wasn't this converted? TLDR: You actually want fixedEncodeURIComponent()
and fixedEncodeURI()
. Long-story...
You should not be using encodeURIComponent()
or encodeURI()
. You should use fixedEncodeURIComponent()
and fixedEncodeURI()
, according to the MDN Documentation.
Regarding encodeURI()
...
If one wishes to follow the more recent RFC3986 for URLs, which makes square brackets reserved (for IPv6) and thus not encoded when forming something which could be part of a URL (such as a host), the following code snippet may help:
function fixedEncodeURI(str) { return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']'); }
Regarding encodeURIComponent()
...
To be more stringent in adhering to RFC 3986 (which reserves !, ', (, ), and *), even though these characters have no formalized URI delimiting uses, the following can be safely used:
function fixedEncodeURIComponent(str) { return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { return '%' + c.charCodeAt(0).toString(16); }); }
So, what is the difference? fixedEncodeURI()
and fixedEncodeURIComponent()
convert the same set of values, but fixedEncodeURIComponent()
also converts this set: +@?=:*#;,$&
. This set is used in GET
parameters (&
, +
, etc.), anchor tags (#
), wildcard tags (*
), email/username parts (@
), etc..
For example -- If you use encodeURI()
, [email protected]/?email=me@home
will not properly send the second @
to the server, except for your browser handling the compatibility (as Chrome naturally does often).
I have done it accessing the controls inside the cell control. Find in all control collections.
ControlCollection cc = (ControlCollection)e.Row.Controls[1].Controls;
Label lbCod = (Label)cc[1];
If you have a built-in command of GridView like insert, update or delete, on row command you can use the following code to get the index:
int index = Convert.ToInt32(e.CommandArgument);
In a custom command, you can set the command argument to yourRow.RowIndex.ToString()
and then get it back in the RowCommand event handler. Unless, of course, you need the command argument for another purpose.
Here is working code for converting an image from a base64 string to an Image
object and storing it in a folder with unique file name:
public void SaveImage()
{
string strm = "R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
//this is a simple white background image
var myfilename= string.Format(@"{0}", Guid.NewGuid());
//Generate unique filename
string filepath= "~/UserImages/" + myfilename+ ".jpeg";
var bytess = Convert.FromBase64String(strm);
using (var imageFile = new FileStream(filepath, FileMode.Create))
{
imageFile.Write(bytess, 0, bytess.Length);
imageFile.Flush();
}
}
It means you have a null reference somewhere in there. Can you debug the app and stop the debugger when it gets here and investigate? Probably img1
is null or ConfigurationManager.AppSettings.Get("Url")
is returning null.
There is no need to involve any image classes, you can simply call WebClient.DownloadFile
:
string localFilename = @"c:\localpath\tofile.jpg";
using(WebClient client = new WebClient())
{
client.DownloadFile("http://www.example.com/image.jpg", localFilename);
}
Update
Since you will want to check whether the file exists and download the file if it does, it's better to do this within the same request. So here is a method that will do that:
private static void DownloadRemoteImageFile(string uri, string fileName)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Check that the remote file was found. The ContentType
// check is performed since a request for a non-existent
// image file might be redirected to a 404-page, which would
// yield the StatusCode "OK", even though the image was not
// found.
if ((response.StatusCode == HttpStatusCode.OK ||
response.StatusCode == HttpStatusCode.Moved ||
response.StatusCode == HttpStatusCode.Redirect) &&
response.ContentType.StartsWith("image",StringComparison.OrdinalIgnoreCase))
{
// if the remote file was found, download oit
using (Stream inputStream = response.GetResponseStream())
using (Stream outputStream = File.OpenWrite(fileName))
{
byte[] buffer = new byte[4096];
int bytesRead;
do
{
bytesRead = inputStream.Read(buffer, 0, buffer.Length);
outputStream.Write(buffer, 0, bytesRead);
} while (bytesRead != 0);
}
}
}
In brief, it makes a request for the file, verifies that the response code is one of OK
, Moved
or Redirect
and also that the ContentType
is an image. If those conditions are true, the file is downloaded.
Probably you use Microsoft SQL Server which support Common Table Expressions (CTE) (see http://msdn.microsoft.com/en-us/library/ms190766.aspx) which are very friendly for query optimization. So I suggest you my favor construction:
WITH GetNumberOfPlans(Id,NumberOfPlans) AS (
SELECT tableA.Id, COUNT(tableC.Id)
FROM tableC
RIGHT OUTER JOIN tableA ON tableC.tableAId = tableA.Id
GROUP BY tableA.Id
),GetUserInformation(Id,Name,Owner,ImageUrl,
CompanyImageUrl,NumberOfUsers) AS (
SELECT tableA.Id, tableA.Name, tableB.Username AS Owner, tableB.ImageUrl,
tableB.CompanyImageUrl,COUNT(tableD.UserId),p.NumberOfPlans
FROM tableA
INNER JOIN tableB ON tableB.Id = tableA.Owner
RIGHT OUTER JOIN tableD ON tableD.tableAId = tableA.Id
GROUP BY tableA.Name, tableB.Username, tableB.ImageUrl, tableB.CompanyImageUrl
)
SELECT u.Id,u.Name,u.Owner,u.ImageUrl,u.CompanyImageUrl
,u.NumberOfUsers,p.NumberOfPlans
FROM GetUserInformation AS u
INNER JOIN GetNumberOfPlans AS p ON p.Id=u.Id
After some experiences with CTE you will be find very easy to write code using CTE and you will be happy with the performance.
It wasn't working well for me. I changed it and now it works smoothly. If anyone interested.
public class ScrollViewForNesting extends ScrollView {
private final int DIRECTION_VERTICAL = 0;
private final int DIRECTION_HORIZONTAL = 1;
private final int DIRECTION_NO_VALUE = -1;
private final int mTouchSlop;
private int mGestureDirection;
private float mDistanceX;
private float mDistanceY;
private float mLastX;
private float mLastY;
public ScrollViewForNesting(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
final ViewConfiguration configuration = ViewConfiguration.get(context);
mTouchSlop = configuration.getScaledTouchSlop();
}
public ScrollViewForNesting(Context context, AttributeSet attrs) {
this(context, attrs,0);
}
public ScrollViewForNesting(Context context) {
this(context,null);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
mDistanceY = mDistanceX = 0f;
mLastX = ev.getX();
mLastY = ev.getY();
mGestureDirection = DIRECTION_NO_VALUE;
break;
case MotionEvent.ACTION_MOVE:
final float curX = ev.getX();
final float curY = ev.getY();
mDistanceX += Math.abs(curX - mLastX);
mDistanceY += Math.abs(curY - mLastY);
mLastX = curX;
mLastY = curY;
break;
}
return super.onInterceptTouchEvent(ev) && shouldIntercept();
}
private boolean shouldIntercept(){
if((mDistanceY > mTouchSlop || mDistanceX > mTouchSlop) && mGestureDirection == DIRECTION_NO_VALUE){
if(Math.abs(mDistanceY) > Math.abs(mDistanceX)){
mGestureDirection = DIRECTION_VERTICAL;
}
else{
mGestureDirection = DIRECTION_HORIZONTAL;
}
}
if(mGestureDirection == DIRECTION_VERTICAL){
return true;
}
else{
return false;
}
}
}
Nothing worked for me for these errors EXCEPT
... was not expected,
... there is an error in XML document (1,2)
... System.FormatException Input String was not in correct format ...
Except this way
1- You need to inspect the xml response as string (the response that you are trying to de-serialize to an object)
2- Use online tools for string unescape and xml prettify/formatter
3- MAKE SURE that the C# Class (main class) you are trying to map/deserialize the xml string to HAS AN XmlRootAttribute that matches the root element of the response.
Exmaple:
My XML Response was staring like :
<ShipmentCreationResponse xmlns="http://ws.aramex.net/ShippingAPI/v1/">
<Transaction i:nil="true" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"/>
....
And the C# class definition + attributes was like :
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ServiceModel.MessageContractAttribute(WrapperName="ShipmentCreationResponse", WrapperNamespace="http://ws.aramex.net/ShippingAPI/v1/", IsWrapped=true)]
public partial class ShipmentCreationResponse {
.........
}
Note that the class definition does not have "XmlRootAttribute"
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://ws.aramex.net/ShippingAPI/v1/", IsNullable = false)]
And when i try to de serialize using a generic method :
public static T Deserialize<T>(string input) where T : class
{
System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(T));
using (System.IO.StringReader sr = new System.IO.StringReader(input))
{
return (T)ser.Deserialize(sr);
}
}
var _Response = GeneralHelper.XMLSerializer.Deserialize<ASRv2.ShipmentCreationResponse>(xml);
I was getting the errors above
... was not expected, ... there is an error in XML document (1,2) ...
Now by just adding the "XmlRootAttribute" that fixed the issue for ever and for every other requests/responses i had a similar issue with:
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://ws.aramex.net/ShippingAPI/v1/", IsNullable = false)]
..
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://ws.aramex.net/ShippingAPI/v1/")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://ws.aramex.net/ShippingAPI/v1/", IsNullable = false)]
public partial class ShipmentCreationResponse
{
........
}
Try modifying the "style" attribute:
$('myObject').attr('style', 'background-image: url("' + imageUrl +'")');
It's pretty hard to say definitively without seeing what the rendered html looks like and what styles are being applied to the elements within the treeview div, but the thing that jumps out at me right away is the
overflow-x: scroll;
What happens if you remove that?
My issues was that I was running mvn compile from a child project directory instead of the parent project.
new WebDriverWait(driver, TimeSpan.FromSeconds(10)).
Until(ExpectedConditions.PresenceOfAllElementsLocatedBy((By.Id("toast-container"))));
If you want to convert a python datetime to seconds since epoch you could do it explicitly:
>>> (datetime.datetime(2012,04,01,0,0) - datetime.datetime(1970,1,1)).total_seconds()
1333238400.0
In Python 3.3+ you can use timestamp()
instead:
>>> datetime.datetime(2012,4,1,0,0).timestamp()
1333234800.0
Why you should not use datetime.strftime('%s')
Python doesn't actually support %s as an argument to strftime (if you check at http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior it's not in the list), the only reason it's working is because Python is passing the information to your system's strftime, which uses your local timezone.
>>> datetime.datetime(2012,04,01,0,0).strftime('%s')
'1333234800'
Old topic, but never clearly answered. I've been working on similar as well, and found the solution:
The pipe (|) in this code sample from Austin isn't the delimiter, but to pipe the ForEach-Object, so if you want to use it as delimiter, you need to do this:
Import-Csv H:\Programs\scripts\SomeText.csv -delimiter "|" |`
ForEach-Object {
$Name += $_.Name
$Phone += $_."Phone Number"
}
Spent a good 15 minutes on this myself before I understood what was going on. Hope the answer helps the next person reading this avoid the wasted minutes! (Sorry for expanding on your comment Austin)
Well, you want to have an answer that is up-to-date and modern.
Here is my answer:
When I need to mail in Python, I use the mailgun API wich get's a lot of the headaches with sending mails sorted out. They have a wonderfull app/api that allows you to send 5,000 free emails per month.
Sending an email would be like this:
def send_simple_message():
return requests.post(
"https://api.mailgun.net/v3/YOUR_DOMAIN_NAME/messages",
auth=("api", "YOUR_API_KEY"),
data={"from": "Excited User <mailgun@YOUR_DOMAIN_NAME>",
"to": ["[email protected]", "YOU@YOUR_DOMAIN_NAME"],
"subject": "Hello",
"text": "Testing some Mailgun awesomness!"})
You can also track events and lots more, see the quickstart guide.
I hope you find this useful!
Here is my full code using tag from remote search. Hope this is helpful.
$('#myInput').selectize({
valueField: 'id',
labelField: 'name',
searchField: 'name',
options: [],
delimiter: ',',
persist: false,
create: false,
load: function(query, callback) {
if (!query.length) return callback();
$.ajax({
url: '/api/all_cities.php',
type: 'GET',
dataType: 'json',
data: {
name: query,
},
error: function() {
callback();
},
success: function(res) {
callback(res);
}
});
},
onInitialize: function(){
var selectize = this;
$.get("/api/selected_cities.php", function( data ) {
selectize.addOption(data); // This is will add to option
var selected_items = [];
$.each(data, function( i, obj) {
selected_items.push(obj.id);
});
selectize.setValue(selected_items); //this will set option values as default
});
}
});
If you have a lot of HTML content (more than just a single div), you might consider building the HTML into the page within a hidden container, then updating it and making it visible when needed. This way, a large portion of your markup can be pre-parsed by the browser and avoid getting bogged down by JavaScript when called. Hope this helps!
This simple mechanism you can use for detecting finishing of a thread without blocking in join method.
std::thread thread([&thread]() {
sleep(3);
thread.detach();
});
while(thread.joinable())
sleep(1);
simply provide the init block for HomeCell class
it's work in my case
in case you are interested in reading some data from a .txt
file and only extract few columns of that file into a new .txt
file with a customized header, the following code might be useful:
# input some data from 2 different .txt files:
civit_gps <- read.csv(file="/path2/gpsFile.csv",head=TRUE,sep=",")
civit_cam <- read.csv(file="/path2/cameraFile.txt",head=TRUE,sep=",")
# assign the name for the output file:
seqName <- "seq1_data.txt"
#=========================================================
# Extract data from imported files
#=========================================================
# From Camera:
frame_idx <- civit_cam$X.frame
qx <- civit_cam$q.x.rad.
qy <- civit_cam$q.y.rad.
qz <- civit_cam$q.z.rad.
qw <- civit_cam$q.w
# From GPS:
gpsT <- civit_gps$X.gpsTime.sec.
latitude <- civit_gps$Latitude.deg.
longitude <- civit_gps$Longitude.deg.
altitude <- civit_gps$H.Ell.m.
heading <- civit_gps$Heading.deg.
pitch <- civit_gps$pitch.deg.
roll <- civit_gps$roll.deg.
gpsTime_corr <- civit_gps[frame_idx,1]
#=========================================================
# Export new data into the output txt file
#=========================================================
myData <- data.frame(c(gpsTime_corr),
c(frame_idx),
c(qx),
c(qy),
c(qz),
c(qw))
# Write :
cat("#GPSTime,frameIdx,qx,qy,qz,qw\n", file=seqName)
write.table(myData, file = seqName,row.names=FALSE,col.names=FALSE,append=TRUE,sep = ",")
Of course, you should modify this sample script based on your own application.
I wanted a text field that only allowed integers. Here's what I ended up with (using info from here and elsewhere):
Create integer number formatter (in UIApplicationDelegate so it can be reused):
@property (nonatomic, retain) NSNumberFormatter *integerNumberFormatter;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Create and configure an NSNumberFormatter for integers
integerNumberFormatter = [[NSNumberFormatter alloc] init];
[integerNumberFormatter setMaximumFractionDigits:0];
return YES;
}
Use filter in UITextFieldDelegate:
@interface MyTableViewController : UITableViewController <UITextFieldDelegate> {
ictAppDelegate *appDelegate;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
// Make sure the proposed string is a number
NSNumberFormatter *inf = [appDelegate integerNumberFormatter];
NSString* proposedString = [textField.text stringByReplacingCharactersInRange:range withString:string];
NSNumber *proposedNumber = [inf numberFromString:proposedString];
if (proposedNumber) {
// Make sure the proposed number is an integer
NSString *integerString = [inf stringFromNumber:proposedNumber];
if ([integerString isEqualToString:proposedString]) {
// proposed string is an integer
return YES;
}
}
// Warn the user we're rejecting the change
AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
return NO;
}
You had a typo: ini_set('max_input_time','200M') - value set needs to be an int, like ini_set('max_input_time','200')
Related, so I thought I would post for others. If you want to find the UTC of the start of today (for your timezone) the following code works for any UTC offset (-23.5 thru +23.5). This looks like we add X hours then subtract X hours, but the important thing is the ".Date" after the add.
double utcOffset= 10.0; // Set to your UTC offset in hours (eg. Melbourne Australia)
var now = DateTime.UtcNow;
var startOfToday = now.AddHours(utcOffset - 24.0).Date;
startOfToday = startOfToday.AddHours(24.0 - utcOffset);
In Ubuntu 18.04 the QtCreator examples and API docs missing, This is my way to solve this problem, should apply to almost every Ubuntu release.
For QtCreator and Examples and API Docs:
sudo apt install `apt-cache search 5-examples | grep qt | grep example | awk '{print $1 }' | xargs `
sudo apt install `apt-cache search 5-doc | grep "Qt 5 " | awk '{print $1}' | xargs`
sudo apt-get install build-essential qtcreator qt5-default
If something is also missing, then:
sudo apt install `apt-cache search qt | grep 5- | grep ^qt | awk '{print $1}' | xargs `
Hope to be helpful.
Also posted in Ask Ubuntu: https://askubuntu.com/questions/450983/ubuntu-14-04-qtcreator-qt5-examples-missing
Lets define px_ratio as below:
px ratio = ratio of physical pixel to css px.
if any one zoom The Page, the viewport pxes (px is different from pixel ) reduces and should be fit to The screen so the ratio (physical pixel / CSS_px ) must get bigger.
but in window Resizing, screen size reduces as well as pxes. so the ratio will maintain.
but
resizing: trigger windows.resize event --> doesn’t change px_ratio
//for zoom detection
px_ratio = window.devicePixelRatio || window.screen.availWidth / document.documentElement.clientWidth;
$(window).resize(function(){isZooming();});
function isZooming(){
var newPx_ratio = window.devicePixelRatio || window.screen.availWidth / document.documentElement.clientWidth;
if(newPx_ratio != px_ratio){
px_ratio = newPx_ratio;
console.log("zooming");
return true;
}else{
console.log("just resizing");
return false;
}
}
The key point is difference between CSS PX and Physical Pixel.
https://gist.github.com/abilogos/66aba96bb0fb27ab3ed4a13245817d1e
Yes, NSDictionary
supports fast enumeration. With Objective-C 2.0, you can do this:
// To print out all key-value pairs in the NSDictionary myDict
for(id key in myDict)
NSLog(@"key=%@ value=%@", key, [myDict objectForKey:key]);
The alternate method (which you have to use if you're targeting Mac OS X pre-10.5, but you can still use on 10.5 and iPhone) is to use an NSEnumerator
:
NSEnumerator *enumerator = [myDict keyEnumerator];
id key;
// extra parens to suppress warning about using = instead of ==
while((key = [enumerator nextObject]))
NSLog(@"key=%@ value=%@", key, [myDict objectForKey:key]);
The following will create a variable length set of arguments of the type of string:
print(String arg1, String... arg2)
You can then refer to arg2
as an array of Strings. This is a new feature in Java 5.
The command setwd("~/")
should set your working directory to your home directory. You might be experiencing problems because the OS you are using does not recognise "~/"
as your home directory: this might be because of the OS, or it might be because of not having set that as your home directory elsewhere.
As you have tagged the post using RStudio:
You will now have set the folder as your working directory. Use the command getwd()
to get the working directory as it is now set, and save that as a variable string at the top of your script. Then use setwd
with that string as the argument, so that each time you run the script you use the same directory.
For example at the top of my script I would have:
work_dir <- "C:/Users/john.smith/Documents"
setwd(work_dir)
A string to char array is as simple as
String str = "someString";
char[] charArray = str.toCharArray();
Can you explain a little more on what you are trying to do?
* Update *
if I am understanding your new comment, you can use a byte array and example is provided.
byte[] bytes = ByteBuffer.allocate(4).putInt(1695609641).array();
for (byte b : bytes) {
System.out.format("0x%x ", b);
}
With the following output
0x65 0x10 0xf3 0x29
I know this discussion is old, but I really like this approach by Google and wanted to share that feeling with others ;)
The other thing is that the better You get the more You try to understand and finally You just don't believe that something is good or bad just because someone said so :) This is a very inspirational video that helped me to think more by myself :) GOOD PRACTICES are good, but don't use them mindelessly :)
Most of the answers in this thread are catered to use with JSON.stringify
specifically -- they do not show how to actually remove circular-references in the original object-tree. (well, short of calling JSON.parse
again afterward -- which requires reassignment, and has a higher performance impact)
For removing circular-references from the source object-tree, you can use a function such as this: https://stackoverflow.com/a/63952549/2441655
These general-purpose circular-reference-remover functions can then be used to make subsequent calls to circular-reference-sensitive functions (like JSON.stringify
) safe:
const objTree = {normalProp: true};
objTree.selfReference = objTree;
RemoveCircularLinks(objTree); // without this line, the JSON.stringify call errors
console.log(JSON.stringify(objTree));
Are you using JTextArea
's append(String)
method to add additional text?
JTextArea txtArea = new JTextArea("Hello, World\n", 20, 20);
txtArea.append("Goodbye Cruel World\n");
Here is the missing piece. You need to pass 'recursive' flag as third argument (boolean true) in mkdir call like this:
mkdir('path/to/directory', 0755, true);
Maybe it's because you have a line break in your PHP code. If you need line breaks in your alert window message, include it as an escaped syntax at the end of each line in your PHP code. I usually do it the following way:
$message = 'line 1.\\n';
$message .= 'line 2.';
/^[a-zA-Z]*$/
Change the *
to +
if you don't want to allow empty matches.
Character classes ([...]
), Anchors (^
and $
), Repetition (+
, *
)
The /
are just delimiters, it denotes the start and the end of the regex. One use of this is now you can use modifiers on it.
select * from table_name ORDER BY primary_id DESC FETCH FIRST 1 ROWS ONLY;
That's the simplest one without doing sub queries
Another option you can go with here:
df.loc["Total", "MyColumn"] = df.MyColumn.sum()
# X MyColumn Y Z
#0 A 84.0 13.0 69.0
#1 B 76.0 77.0 127.0
#2 C 28.0 69.0 16.0
#3 D 28.0 28.0 31.0
#4 E 19.0 20.0 85.0
#5 F 84.0 193.0 70.0
#Total NaN 319.0 NaN NaN
You can also use append()
method:
df.append(pd.DataFrame(df.MyColumn.sum(), index = ["Total"], columns=["MyColumn"]))
Update:
In case you need to append sum for all numeric columns, you can do one of the followings:
Use append
to do this in a functional manner (doesn't change the original data frame):
# select numeric columns and calculate the sums
sums = df.select_dtypes(pd.np.number).sum().rename('total')
# append sums to the data frame
df.append(sums)
# X MyColumn Y Z
#0 A 84.0 13.0 69.0
#1 B 76.0 77.0 127.0
#2 C 28.0 69.0 16.0
#3 D 28.0 28.0 31.0
#4 E 19.0 20.0 85.0
#5 F 84.0 193.0 70.0
#total NaN 319.0 400.0 398.0
Use loc
to mutate data frame in place:
df.loc['total'] = df.select_dtypes(pd.np.number).sum()
df
# X MyColumn Y Z
#0 A 84.0 13.0 69.0
#1 B 76.0 77.0 127.0
#2 C 28.0 69.0 16.0
#3 D 28.0 28.0 31.0
#4 E 19.0 20.0 85.0
#5 F 84.0 193.0 70.0
#total NaN 638.0 800.0 796.0
This code will not work (you can check in firebug jQuery.ui is undefined):
<script src="http://code.jquery.com/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="jquery-ui-1.8.1.custom.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js" type="text/javascript"></script>
Try use follow code:
<script src="http://code.jquery.com/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js" type="text/javascript"></script>
<script src="jquery-ui-1.8.1.custom.min.js" type="text/javascript"></script>
Simply add static
in the declaration of these two methods and the compile time error will disappear!
By default in C# methods are instance methods, and they receive the implicit "self" argument. By making them static, no such argument is needed (nor available), and the method must then of course refrain from accessing any instance (non-static) objects or methods of the class.
More info on static methods
Provided the class and the method's access modifiers (public vs. private) are ok, a static method can then be called from anywhere without having to previously instantiate a instance of the class. In other words static methods are used with the following syntax:
className.classMethod(arguments)
rather than
someInstanceVariable.classMethod(arguments)
A classical example of static methods are found in the System.Math class, whereby we can call a bunch of these methods like
Math.Sqrt(2)
Math.Cos(Math.PI)
without ever instantiating a "Math" class (in fact I don't even know if such an instance is possible)
You have to change column type to varchar
or integer
for indexing.
Is this what you're after?
I added :text-align:center
to the div and image
Negative numbers mean that you count from the right instead of the left. So, list[-1]
refers to the last element, list[-2]
is the second-last, and so on.
See link here. You find your solution. And try:
Creating a Custom Toast View
If a simple text message isn't enough, you can create a customized layout for your toast notification. To create a custom layout, define a View layout, in XML or in your application code, and pass the root View object to the setView (View) method.
For example, you can create the layout for the toast visible in the screenshot to the right with the following XML (saved as toast_layout.xml):
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/toast_layout_root"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:background="#DAAA"
>
<ImageView android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_marginRight="10dp"
/>
<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:textColor="#FFF"
/>
</LinearLayout>
Notice that the ID of the LinearLayout element is "toast_layout". You must use this ID to inflate the layout from the XML, as shown here:
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.toast_layout,
(ViewGroup) findViewById(R.id.toast_layout_root));
ImageView image = (ImageView) layout.findViewById(R.id.image);
image.setImageResource(R.drawable.android);
TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("Hello! This is a custom toast!");
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
First, retrieve the LayoutInflater with getLayoutInflater() (or getSystemService()), and then inflate the layout from XML using inflate(int, ViewGroup). The first parameter is the layout resource ID and the second is the root View. You can use this inflated layout to find more View objects in the layout, so now capture and define the content for the ImageView and TextView elements. Finally, create a new Toast with Toast(Context) and set some properties of the toast, such as the gravity and duration. Then call setView(View) and pass it the inflated layout. You can now display the toast with your custom layout by calling show().
Note: Do not use the public constructor for a Toast unless you are going to define the layout with setView(View). If you do not have a custom layout to use, you must use makeText(Context, int, int) to create the Toast.
Below is some code to format columns A and C as text in SpreadsheetGear for .NET which has an API which is similar to Excel - except for the fact that SpreadsheetGear is frequently more strongly typed. It should not be too hard to figure out how to convert this to work with Excel / COM:
IWorkbook workbook = Factory.GetWorkbook();
IRange cells = workbook.Worksheets[0].Cells;
// Format column A as text.
cells["A:A"].NumberFormat = "@";
// Set A2 to text with a leading '0'.
cells["A2"].Value = "01234567890123456789";
// Format column C as text (SpreadsheetGear uses 0 based indexes - Excel uses 1 based indexes).
cells[0, 2].EntireColumn.NumberFormat = "@";
// Set C3 to text with a leading '0'.
cells[2, 2].Value = "01234567890123456789";
workbook.SaveAs(@"c:\tmp\TextFormat.xlsx", FileFormat.OpenXMLWorkbook);
Disclaimer: I own SpreadsheetGear LLC
Yes, it is possible to run PowerShell through the run window. However, it would be burdensome and you will need to enter in the password for computer. This is similar to how you will need to set up when you run cmd:
runas /user:(ComputerName)\(local admin) powershell.exe
So a basic example would be:
runas /user:MyLaptop\[email protected] powershell.exe
You can find more information on this subject in Runas.
However, you could also do one more thing :
then your system will execute the elevated powershell.
To save a bit time:
1) You can mark your app icon images all in finder and drag them into your Assets catalog all at once by dragging into one of the empty slots of the app icon imageset. When you hold your drag over the slot, several of the other slots look selected and when you drop those all will be filled up at once. Note that this works in XCode 8 (I haven't tried XCode 7), but in XCode 9 beta not yet.
2) The "Technical Q&A QA1686" apple documentation site has the sizes per app icon slot already calculated for you in a nice image and also contains the correct image names conventions.
If you prefer a code with a pretty look, you can do a break:
for(int j = 0; ; j++){
if(j < 6
&& j < ( (int) abc[j] & 0xff)){
break;
}
// Put your code here
}
In tandem with what Pedro Fontez said a few replies up, you seemed to never call the sys module initially, nor did you manage to stick the required () at the end of sys.exit:
so:
import sys
and when finished:
sys.exit()
Create a Requestfactory class
import java.net.URI;
import javax.annotation.PostConstruct;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpUriRequest;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
@Component
public class RequestFactory {
private RestTemplate restTemplate = new RestTemplate();
@PostConstruct
public void init() {
this.restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestWithBodyFactory());
}
private static final class HttpComponentsClientHttpRequestWithBodyFactory extends HttpComponentsClientHttpRequestFactory {
@Override
protected HttpUriRequest createHttpUriRequest(HttpMethod httpMethod, URI uri) {
if (httpMethod == HttpMethod.GET) {
return new HttpGetRequestWithEntity(uri);
}
return super.createHttpUriRequest(httpMethod, uri);
}
}
private static final class HttpGetRequestWithEntity extends HttpEntityEnclosingRequestBase {
public HttpGetRequestWithEntity(final URI uri) {
super.setURI(uri);
}
@Override
public String getMethod() {
return HttpMethod.GET.name();
}
}
public RestTemplate getRestTemplate() {
return restTemplate;
}
}
and @Autowired where ever you require and use, Here is one sample code GET request with RequestBody
@RestController
@RequestMapping("/v1/API")
public class APIServiceController {
@Autowired
private RequestFactory requestFactory;
@RequestMapping(method = RequestMethod.GET, path = "/getData")
public ResponseEntity<APIResponse> getLicenses(@RequestBody APIRequest2 APIRequest){
APIResponse response = new APIResponse();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
Gson gson = new Gson();
try {
StringBuilder createPartUrl = new StringBuilder(PART_URL).append(PART_URL2);
HttpEntity<String> entity = new HttpEntity<String>(gson.toJson(APIRequest),headers);
ResponseEntity<APIResponse> storeViewResponse = requestFactory.getRestTemplate().exchange(createPartUrl.toString(), HttpMethod.GET, entity, APIResponse.class); //.getForObject(createLicenseUrl.toString(), APIResponse.class, entity);
if(storeViewResponse.hasBody()) {
response = storeViewResponse.getBody();
}
return new ResponseEntity<APIResponse>(response, HttpStatus.OK);
}catch (Exception e) {
e.printStackTrace();
return new ResponseEntity<APIResponse>(response, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
You can read file data line by line as below:
String fileLoc = "fileLocationInTheDisk";
List<String> lines = Files.lines(Path.of(fileLoc), StandardCharsets.UTF_8).collect(Collectors.toList());
Try to use the following:
\Request::getRequestUri()
The reason you need to use self.
is because Python does not use the @
syntax to refer to instance attributes. Python decided to do methods in a way that makes the instance to which the method belongs be passed automatically, but not received automatically: the first parameter of methods is the instance the method is called on. That makes methods entirely the same as functions, and leaves the actual name to use up to you (although self
is the convention, and people will generally frown at you when you use something else.) self
is not special to the code, it's just another object.
Python could have done something else to distinguish normal names from attributes -- special syntax like Ruby has, or requiring declarations like C++ and Java do, or perhaps something yet more different -- but it didn't. Python's all for making things explicit, making it obvious what's what, and although it doesn't do it entirely everywhere, it does do it for instance attributes. That's why assigning to an instance attribute needs to know what instance to assign to, and that's why it needs self.
.
See String Formatting Operations:
%d
is the format code for an integer. %f
is the format code for a float.
%s
prints the str()
of an object (What you see when you print(object)
).
%r
prints the repr()
of an object (What you see when you print(repr(object))
.
For a float %s, %r and %f all display the same value, but that isn't the case for all objects. The other fields of a format specifier work differently as well:
>>> print('%10.2s' % 1.123) # print as string, truncate to 2 characters in a 10-place field.
1.
>>> print('%10.2f' % 1.123) # print as float, round to 2 decimal places in a 10-place field.
1.12
Style your change the Submit button to an anchor tag instead and submit using javascript:
<a class="link-button" href="javascript:submit();">Submit</a>
<a class="link-button" href="some_url">Cancel</a>
function submit() {
var form = document.getElementById("form_id");
form.submit();
}
If you'd prefer to do it in SQL, enter this query into the query window:
CREATE SCHEMA Test
Press CTRL + Enter to submit it, and you should see confirmation in the output pane underneath the query window. You'll have to right-click on an existing schema in the Object panel and click "Refresh All" to see it show up, though.
Your problem is not the lack of "dynamic casting". Casting Integer
to Double
isn't possible at all. You seem to want to give Java an object of one type, a field of a possibly incompatible type, and have it somehow automatically figure out how to convert between the types.
This kind of thing is anathema to a strongly typed language like Java, and IMO for very good reasons.
What are you actually trying to do? All that use of reflection looks pretty fishy.
"... that are independent of their timezone"
var timezone = d.getTimezoneOffset() // difference in minutes from GMT
I had the same issue and the reason for that was incorrect marking of the project's sources.
I manually created the Root Content and didn't notice that src/main/test
folder was marked as Sources
instead of Tests
. So that is why my test classes were assumed to have all their test libraries (JUnit
, Mockito
, etc.) with the scope of Compile, not Test.
As soon as I marked src/main/test
as Tests and rebuilt the module all errors were gone.
OpenOffice.org can view HTML tables. Simply use the open command on the HTML file, or select and copy the table in your browser and then Paste Special in OpenOffice.org. It will query you for the file type, one of which should be HTML. Select that and voila!
A bit late to the party, but Krux has created a script for this, called Postscribe. We were able to use this to get past this issue.
Please bear in mind that the formatting of the date is independent of the storage. If it's essential to you that the date is stored in that format you will need to either define a custom data type or store it as a string. Then you can use a combination of extract, typecasting and concatenation to get that format.
However, I suspect that you want to store a date and get the format on output. So, something like this will do the trick for you:
CREATE TABLE my_table
(
id serial PRIMARY KEY not null,
my_date date not null default CURRENT_DATE
);
(CURRENT_DATE is basically a synonym for now() and a cast to date).
(Edited to use to_char).
Then you can get your output like:
SELECT id, to_char(my_date, 'yyyymm') FROM my_table;
Now, if you did really need to store that field as a string and ensure the format you could always do:
CREATE TABLE my_other_table
(
id serial PRIMARY KEY not null,
my_date varchar(6) default to_char(CURRENT_DATE, 'yyyymm')
);
Assuming you're wanting to undo the effects of git rm <file>
or rm <file>
followed by git add -A
or something similar:
# this restores the file status in the index
git reset -- <file>
# then check out a copy from the index
git checkout -- <file>
To undo git add <file>
, the first line above suffices, assuming you haven't committed yet.
You are probably missing the viewport meta tag in the html head:
<meta name="viewport" content="width=device-width, initial-scale=1">
Without it the device assumes and sets the viewport to full size.
More info here.
Well you have a java.lang.ClassNotFoundException. That means a class is missing in the application runtime. You should check wheather you have added all your libs to the build path.
Right click on your project -> properties -> java build path -> libraries, add your libs or create one containing your classes and enable order export for your libs.
You absolutely need to know where the files to be read can be located. However, this information can be relative of course so it may be well adapted to other systems.
So it could relate to the current directory (get it from Directory.GetCurrentDirectory()
) or to the application executable path (eg. Application.ExecutablePath
comes to mind if using Windows Forms or via Assembly.GetEntryAssembly().Location
) or to some special Windows directory like "Documents and Settings" (you should use Environment.GetFolderPath()
with one element of the Environment.SpecialFolder
enumeration).
Note that the "current directory" and the path of the executable are not necessarily identical. You need to know where to look!
In either case, if you need to manipulate a path use the Path class to split or combine parts of the path.
You just need convert your string to a pointer by window[<method name>]
.
example:
var function_name = "string";
function_name = window[function_name];
and now you can use it like a pointer.
First of all, be careful! All of your security depends on the… er… privacy of your private keys. Keytool doesn't have key export built in to avoid accidental disclosure of this sensitive material, so you might want to consider some extra safeguards that could be put in place to protect your exported keys.
Here is some simple code that gives you unencrypted PKCS #8 PrivateKeyInfo that can be used by OpenSSL (see the -nocrypt
option of its pkcs8 utility):
KeyStore keys = ...
char[] password = ...
Enumeration<String> aliases = keys.aliases();
while (aliases.hasMoreElements()) {
String alias = aliases.nextElement();
if (!keys.isKeyEntry(alias))
continue;
Key key = keys.getKey(alias, password);
if ((key instanceof PrivateKey) && "PKCS#8".equals(key.getFormat())) {
/* Most PrivateKeys use this format, but check for safety. */
try (FileOutputStream os = new FileOutputStream(alias + ".key")) {
os.write(key.getEncoded());
os.flush();
}
}
}
If you need other formats, you can use a KeyFactory to get a transparent key specification for different types of keys. Then you can get, for example, the private exponent of an RSA private key and output it in your desired format. That would make a good topic for a follow-up question.
This method uses regexp, it should work:
awk '$2 ~ /findtext/ {print $3}' <infile>
GCC: GNU Compiler Collection
gcc
: GNU C Compiler
g++
: GNU C++ Compiler
The main differences:
gcc
will compile: *.c\*.cpp
files as C and C++ respectively.g++
will compile: *.c\*.cpp
files but they will all be treated as C++ files.g++
to link the object files it automatically links in the std C++ libraries (gcc
does not do this).gcc
compiling C files has fewer predefined macros.gcc
compiling *.cpp
and g++
compiling *.c\*.cpp
files has a few extra macros.Extra Macros when compiling *.cpp
files:
#define __GXX_WEAK__ 1
#define __cplusplus 1
#define __DEPRECATED 1
#define __GNUG__ 4
#define __EXCEPTIONS 1
#define __private_extern__ extern
Try this: B = A ( : )
, or try the reshape
function.
http://www.mathworks.com/access/helpdesk/help/techdoc/ref/reshape.html
Tell the option element to be 13pt
select option{
font-size: 13pt;
}
and then the first option element to be 7pt
select option:first-child {
font-size: 7pt;
}
Running demo: http://jsfiddle.net/VggvD/1/
The environment variable to set is MAVEN_OPTS
, for example MAVEN_OPTS=-Xmx1024m
. The maxmem
configuration in the pom only applies when you set the compiler plugin to fork javac
into a new JVM. Otherwise the plugin runs inside the same VM as Maven and thus within the memory passed on the command line via the MAVEN_OPTS
.
To set MAVEN_OPTS under Windows 7:
-Xmx1024m
(or more)Open a new command window and run mvn
.
The derivedFactor
function from mosaic
package seems to be designed to handle this. Using this example, it would look like:
library(dplyr)
library(mosaic)
df <- mutate(df, g = derivedFactor(
"2" = (a == 2 | a == 5 | a == 7 | (a == 1 & b == 4)),
"3" = (a == 0 | a == 1 | a == 4 | a == 3 | c == 4),
.method = "first",
.default = NA
))
(If you want the result to be numeric instead of a factor, you can wrap derivedFactor
in an as.numeric
call.)
derivedFactor
can be used for an arbitrary number of conditionals, too.
This is code I used in Windows. It works.
for item in COOKIES.split(';'):
name,value = item.split('=', 1)
name=name.replace(' ', '').replace('\r', '').replace('\n', '')
value = value.replace(' ', '').replace('\r', '').replace('\n', '')
cookie_dict={
'name':name,
'value':value,
"domain": "", # Google Chrome
"expires": "",
'path': '/',
'httpOnly': False,
'HostOnly': False,
'Secure': False
}
self.driver_.add_cookie(cookie_dict)
Here is one without parentheses
[io.fileinfo] 'c:\temp\myfile.txt' | % basename
Yes, it is recommended to put the GA code in the footer anyway, as the page shouldnt count as a page visit until its read all the markup.
In order to display the results with the line numbers, you might try this
grep -nr "word to search for" /path/to/file/file
The result should be something like this:
linenumber: other data "word to search for" other data
Visual Studio e.g. 2019 In general be aware that the selected Platform (e.g. x64) in the configuration Dialog is the the same as the Platform You intend to debug with! (see picture for explanation)
Greetings mic enter image description here
The following works on all browsers for my 200 figures, for any width percentage -- despite being illegal. Jukka said 'Use it anyway.' (The class just floats the image left or right and sets margins.) I can't imagine why this isn't the standard approach!
<img class="fl" width="66%"
src="A-Images/0.5_Saltation.jpg"
alt="Schematic models of chromosomes ..." />
Change the window width and the image scales obligingly.
You could do something like this:
htmlComponent.ts
htmlVariable: string = "<b>Some html.</b>";
//this is html in TypeScript code that you need to display
htmlComponent.html
<div [innerHtml]="htmlVariable"></div>
//this is how you display html code from TypeScript in your html
I saw many people interested in and suffering from this code and i know it's really confusing and disrupting for the first time.
"The type System.Web.Mvc.RequiredAttributeAdapter must have a public constructor which accepts three parameters of types System.Web.Mvc.ModelMetadata, System.Web.Mvc.ControllerContext, and ExpressiveAnnotations.Attributes.RequiredIfAttribute Parameter name: adapterType"
Tip #1: make sure that you're inheriting from 'ValidationAttribute' not from 'RequiredAttribute'
public class RequiredIfAttribute : ValidationAttribute, IClientValidatable { ...}
Tip #2: OR remove this entire line from 'Global.asax', It is not needed at all in the newer version of the code (after edit by @Dan_Hunex), and yes this line was a must in the old version ...
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(RequiredIfAttribute), typeof(RequiredAttributeAdapter));
1- put the code in a new js file (ex:requiredIfValidator.js)
2- warp the code inside a $(document).ready(function(){........});
3- include our js file after including the JQuery validation libraries, So it look like this now :
@Scripts.Render("~/bundles/jqueryval")
<script src="~/Content/JS/requiredIfValidator.js"></script>
4- Edit the C# code
from
rule.ValidationParameters["dependentproperty"] = (context as ViewContext).ViewData.TemplateInfo.GetFullHtmlFieldId(PropertyName);
to
rule.ValidationParameters["dependentproperty"] = PropertyName;
and from
if (dependentValue.ToString() == DesiredValue.ToString())
to
if (dependentValue != null && dependentValue.ToString() == DesiredValue.ToString())
Global.asax
Nothing to add here, keep it clean
requiredIfValidator.js
create this file in ~/content or in ~/scripts folder
$.validator.unobtrusive.adapters.add('requiredif', ['dependentproperty', 'desiredvalue'], function (options)
{
options.rules['requiredif'] = options.params;
options.messages['requiredif'] = options.message;
});
$(document).ready(function ()
{
$.validator.addMethod('requiredif', function (value, element, parameters) {
var desiredvalue = parameters.desiredvalue;
desiredvalue = (desiredvalue == null ? '' : desiredvalue).toString();
var controlType = $("input[id$='" + parameters.dependentproperty + "']").attr("type");
var actualvalue = {}
if (controlType == "checkbox" || controlType == "radio") {
var control = $("input[id$='" + parameters.dependentproperty + "']:checked");
actualvalue = control.val();
} else {
actualvalue = $("#" + parameters.dependentproperty).val();
}
if ($.trim(desiredvalue).toLowerCase() === $.trim(actualvalue).toLocaleLowerCase()) {
var isValid = $.validator.methods.required.call(this, value, element, parameters);
return isValid;
}
return true;
});
});
_Layout.cshtml or the View
@Scripts.Render("~/bundles/jqueryval")
<script src="~/Content/JS/requiredIfValidator.js"></script>
RequiredIfAttribute.cs Class
create it some where in your project, For example in ~/models/customValidation/
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
namespace Your_Project_Name.Models.CustomValidation
{
public class RequiredIfAttribute : ValidationAttribute, IClientValidatable
{
private String PropertyName { get; set; }
private Object DesiredValue { get; set; }
private readonly RequiredAttribute _innerAttribute;
public RequiredIfAttribute(String propertyName, Object desiredvalue)
{
PropertyName = propertyName;
DesiredValue = desiredvalue;
_innerAttribute = new RequiredAttribute();
}
protected override ValidationResult IsValid(object value, ValidationContext context)
{
var dependentValue = context.ObjectInstance.GetType().GetProperty(PropertyName).GetValue(context.ObjectInstance, null);
if (dependentValue != null && dependentValue.ToString() == DesiredValue.ToString())
{
if (!_innerAttribute.IsValid(value))
{
return new ValidationResult(FormatErrorMessage(context.DisplayName), new[] { context.MemberName });
}
}
return ValidationResult.Success;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = ErrorMessageString,
ValidationType = "requiredif",
};
rule.ValidationParameters["dependentproperty"] = PropertyName;
rule.ValidationParameters["desiredvalue"] = DesiredValue is bool ? DesiredValue.ToString().ToLower() : DesiredValue;
yield return rule;
}
}
}
The Model
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using Your_Project_Name.Models.CustomValidation;
namespace Your_Project_Name.Models.ViewModels
{
public class CreateOpenActivity
{
public Nullable<int> ORG_BY_CD { get; set; }
[RequiredIf("ORG_BY_CD", "5", ErrorMessage = "Coordinator ID is required")] // This means: IF 'ORG_BY_CD' is equal 5 (for the example) > make 'COR_CI_ID_NUM' required and apply its all validation / data annotations
[RegularExpression("[0-9]+", ErrorMessage = "Enter Numbers Only")]
[MaxLength(9, ErrorMessage = "Enter a valid ID Number")]
[MinLength(9, ErrorMessage = "Enter a valid ID Number")]
public string COR_CI_ID_NUM { get; set; }
}
}
The View
Nothing to note here actually ...
@model Your_Project_Name.Models.ViewModels.CreateOpenActivity
@{
ViewBag.Title = "Testing";
}
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>CreateOpenActivity</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.ORG_BY_CD, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.ORG_BY_CD, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.ORG_BY_CD, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.COR_CI_ID_NUM, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.COR_CI_ID_NUM, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.COR_CI_ID_NUM, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
I may upload a project sample for this later ...
Hope this was helpful
Thank You
Expressed explicitly ...
ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback(CertCheck);
private static bool CertCheck(object sender, X509Certificate cert,
X509Chain chain, System.Net.Security.SslPolicyErrors error)
{
return true;
}
You have to make sure your DLL is in the classpath.
One such way to do so is to put the path to the DLL in PATH environment variable.
Other option is to add it to the VM arguments in the variable LD_LIBRARY_PATH, like this:
java -Djava.library.path=/path/to/my/dll -cp /my/classpath/goes/here MainClass
mysql -u root -p;
And mysql will ask for the password
As to my understanding it help your content adjust with different values of font family and font sizes.Thus making your content scalable. As to the issue of inhering font size we can always override by giving a specific font size for the element.
In iPython 3.0.0, the inline backend needs to be configured in ipython_kernel_config.py
. You need to manually add the c.InlineBackend.rc
... line (as mentioned in Greg's answer). This will affect both the inline backend in the Qt console and the notebook.
using jQuery input mask plugin (6 whole and 2 decimal places):
HTML:
<input class="mask" type="text" />
jQuery:
$(".mask").inputmask('Regex', {regex: "^[0-9]{1,6}(\\.\\d{1,2})?$"});
I hope this helps someone
You don't need an IIF() at all here. The comparisons return true or false anyway.
Also, since this row visibility is on a group row, make sure you use the same aggregate function on the fields as you use in the fields in the row. So if your group row shows sums, then you'd put this in the Hidden property.
=Sum(Fields!OpeningStock.Value) = 0 And
Sum(Fields!GrossDispatched.Value) = 0 And
Sum(Fields!TransferOutToMW.Value) = 0 And
Sum(Fields!TransferOutToDW.Value) = 0 And
Sum(Fields!TransferOutToOW.Value) = 0 And
Sum(Fields!NetDispatched.Value) = 0 And
Sum(Fields!QtySold.Value) = 0 And
Sum(Fields!StockAdjustment.Value) = 0 And
Sum(Fields!ClosingStock.Value) = 0
But with the above version, if one record has value 1 and one has value -1 and all others are zero then sum is also zero and the row could be hidden. If that's not what you want you could write a more complex expression:
=Sum(
IIF(
Fields!OpeningStock.Value=0 AND
Fields!GrossDispatched.Value=0 AND
Fields!TransferOutToMW.Value=0 AND
Fields!TransferOutToDW.Value=0 AND
Fields!TransferOutToOW.Value=0 AND
Fields!NetDispatched.Value=0 AND
Fields!QtySold.Value=0 AND
Fields!StockAdjustment.Value=0 AND
Fields!ClosingStock.Value=0,
0,
1
)
) = 0
This is essentially a fancy way of counting the number of rows in which any field is not zero. If every field is zero for every row in the group then the expression returns true and the row is hidden.
Do you mean altering the table after it has been created? If so you need to use alter table, in particular:
ALTER TABLE tablename MODIFY COLUMN new-column-definition
e.g.
ALTER TABLE test MODIFY COLUMN locationExpect VARCHAR(120);
If I understand you correctly, you want to compose a multipart request manually from an HTTP/REST console. The multipart format is simple; a brief introduction can be found in the HTML 4.01 spec. You need to come up with a boundary, which is a string not found in the content, let’s say HereGoes
. You set request header Content-Type: multipart/form-data; boundary=HereGoes
. Then this should be a valid request body:
--HereGoes
Content-Disposition: form-data; name="myJsonString"
Content-Type: application/json
{"foo": "bar"}
--HereGoes
Content-Disposition: form-data; name="photo"
Content-Type: image/jpeg
Content-Transfer-Encoding: base64
<...JPEG content in base64...>
--HereGoes--
For those from 2018 and beyond, using npm version 5 or later: edit your package-lock.json
: remove the library from "requires"
section and add it under "dependencies".
For example, you want deglob
package to use glob
package version 3.2.11
instead of its current one. You open package-lock.json
and see:
"deglob": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/deglob/-/deglob-2.1.0.tgz",
"integrity": "sha1-TUSr4W7zLHebSXK9FBqAMlApoUo=",
"requires": {
"find-root": "1.1.0",
"glob": "7.1.2",
"ignore": "3.3.5",
"pkg-config": "1.1.1",
"run-parallel": "1.1.6",
"uniq": "1.0.1"
}
},
Remove "glob": "7.1.2",
from "requires"
, add "dependencies"
with proper version:
"deglob": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/deglob/-/deglob-2.1.0.tgz",
"integrity": "sha1-TUSr4W7zLHebSXK9FBqAMlApoUo=",
"requires": {
"find-root": "1.1.0",
"ignore": "3.3.5",
"pkg-config": "1.1.1",
"run-parallel": "1.1.6",
"uniq": "1.0.1"
},
"dependencies": {
"glob": {
"version": "3.2.11"
}
}
},
Now remove your node_modules
folder, run npm install
and it will add missing parts to the "dependencies"
section.
A simple example of testing Tesseract OCR in C#:
public static string GetText(Bitmap imgsource)
{
var ocrtext = string.Empty;
using (var engine = new TesseractEngine(@"./tessdata", "eng", EngineMode.Default))
{
using (var img = PixConverter.ToPix(imgsource))
{
using (var page = engine.Process(img))
{
ocrtext = page.GetText();
}
}
}
return ocrtext;
}
Info: The tessdata folder must exist in the repository: bin\Debug\
You could always use typeof
in the if statement. It is better than working with string values like the answer of Natarajan.
if (dt.Columns[0].DataType == typeof(DateTime))
{
}
There are no data-validation attributes on your input. Make sure you have generated it with a server side helper such as Html.TextBoxFor and that it is inside a form:
@using (Html.BeginForm())
{
...
@Html.TextBoxFor(x => x.AgreementNumber)
}
Also I don't know what the jquery.validate.inline.js
script is but if it somehow depends on the jquery.validate.js
plugin make sure that it is referenced after it.
In all cases look at your javascript console in the browser for potential errors or missing scripts.
Its usually better to whitelist characters you allow, rather than to blacklist characters you don't allow. both from a security standpoint, and from an ease of implementation standpoint.
If you do go down the blacklist route, here is an example, but be warned, the syntax is not simple.
http://groups.google.com/group/regex/browse_thread/thread/0795c1b958561a07
If you want to whitelist all the accent characters, perhaps using unicode ranges would help? Check out this link.
I've faced this issue while undeploying and redeploying a war with glassfish. My class structure was like this,
public interface A{
}
public class AImpl implements A{
}
and it was changed to
public abstract class A{
}
public class AImpl extends A{
}
After stopping and restarting the domain, it worked out fine. I was using glassfish 3.1.43
By iterating I learned that the Token field and the token in an endpoint can be the same. So I set them to be the same as the user token and it works! Also check that the user has privileges to make a job.
Anyway, you can check access.log and see if Bitbucket makes a try or not.
P.S. Also a link to Bitbucket Documentation. May some day it will become more useful.
I ran into the same issue in Ubuntu 18.04.3 LTS. In my case, apt installed gradle version 4.4.1. The already-install java version was 11.0.4
The build message I got was
Could not determine java version from '11.0.4'.
At the time, most of the online docs referenced gradle version 5.6, so I did the following:
sudo add-apt-repository ppa:cwchien/gradle
sudo apt update
sudo apt upgrade gradle
Then I repeated the project initialiation (using "gradle init" with the defaults). After that, "./gradlew build" worked correctly.
I later read a comment regarding a change in format of the output from "java --version" that caused gradle to break, which was fixed in a later version of gradle.
Create AMI -> Boot AMI on large instance.
More info http://docs.amazonwebservices.com/AmazonEC2/gsg/2006-06-26/creating-an-image.html
You can do this all from the admin console too at aws.amazon.com
For those who are able to access cpanel, there is a simpler way getting around it.
log in cpanel => "Remote MySQL" under DATABASES section:
Add the IPs / hostname which you are accessing from
done!!!
There is still quirks and inconsistencies in 2019.
For example with scaled svg and pointer events, between browsers.
None of the answer of this topic are working anymore. (maybe those with jquery)
Here is an alternative, by testing with javascript if a css rule is supported, via the native CSS support api. Might evolve, to be adapted!
Note that it's possible to pass many css rules separated by a semicolon, for the finest detection.
if (CSS.supports("( -webkit-box-reflect:unset )")){
console.log("WEBKIT BROWSER")
// More math...
} else {
console.log("ENJOY")
}
_x000D_
if (CSS.supports("( -moz-user-select:unset )")){
console.log("FIREFOX!!!")
}
_x000D_
Beware to not use it in loops, for performance it's better to populate a constant on load:
const ff = CSS.supports("( -moz-user-select:unset )")
if (ff){ //... }
Using CSS only, the above would be:
@supports (-webkit-box-reflect:unset) {
div {
background: red
}
}
@supports (-moz-user-select:unset) {
div {
background: green
}
}
_x000D_
<div>
Hello world!!
</div>
_x000D_
List of possible -webkit- only css rules.
If you need a recursive search, you have a variety of options. You should consider ack
.
Failing that, if you have GNU find
and xargs
:
find . -name '*.cc' -print0 -o -name '*.h' -print0 | xargs -0 grep hello /dev/null
The use of /dev/null
ensures you get file names printed; the -print0
and -0
deals with file names containing spaces (newlines, etc).
If you don't have obstreperous names (with spaces etc), you can use:
find . -name '*.*[ch]' -print | xargs grep hello /dev/null
This might pick up a few names you didn't intend, because the pattern match is fuzzier (but simpler), but otherwise works. And it works with non-GNU versions of find
and xargs
.
If you are moving to Xcode 7 or 8 and are opening a really old project, I've encountered this problem:
in SomeConstFile.h
NSString * const kAConstant;
in SomeConstFile.m
NSString *const kAConstant = @"a constant";
Earlier versions of the compiler assumed that the definition in the header file was extern and so including SomeConstFile.h all over the place was fine.
Now you need to explicitly declare these consts as extern:
in SomeConstFile.h
extern NSString * const kAConstant;
This was for my own project and I'm sharing it here too.
This one had trouble after 3.2, so the one below may work better for you:
CSS
/* adjust body when menu is open */
body.slide-active {
overflow-x: hidden
}
/*first child of #page-content so it doesn't shift around*/
.no-margin-top {
margin-top: 0px!important
}
/*wrap the entire page content but not nav inside this div if not a fixed top, don't add any top padding */
#page-content {
position: relative;
padding-top: 70px;
left: 0;
}
#page-content.slide-active {
padding-top: 0
}
/* put toggle bars on the left :: not using button */
#slide-nav .navbar-toggle {
cursor: pointer;
position: relative;
line-height: 0;
float: left;
margin: 0;
width: 30px;
height: 40px;
padding: 10px 0 0 0;
border: 0;
background: transparent;
}
/* icon bar prettyup - optional */
#slide-nav .navbar-toggle > .icon-bar {
width: 100%;
display: block;
height: 3px;
margin: 5px 0 0 0;
}
#slide-nav .navbar-toggle.slide-active .icon-bar {
background: orange
}
.navbar-header {
position: relative
}
/* un fix the navbar when active so that all the menu items are accessible */
.navbar.navbar-fixed-top.slide-active {
position: relative
}
/* screw writing importants and shit, just stick it in max width since these classes are not shared between sizes */
@media (max-width:767px) {
#slide-nav .container {
margin: 0;
padding: 0!important;
}
#slide-nav .navbar-header {
margin: 0 auto;
padding: 0 15px;
}
#slide-nav .navbar.slide-active {
position: absolute;
width: 80%;
top: -1px;
z-index: 1000;
}
#slide-nav #slidemenu {
background: #f7f7f7;
left: -100%;
width: 80%;
min-width: 0;
position: absolute;
padding-left: 0;
z-index: 2;
top: -8px;
margin: 0;
}
#slide-nav #slidemenu .navbar-nav {
min-width: 0;
width: 100%;
margin: 0;
}
#slide-nav #slidemenu .navbar-nav .dropdown-menu li a {
min-width: 0;
width: 80%;
white-space: normal;
}
#slide-nav {
border-top: 0
}
#slide-nav.navbar-inverse #slidemenu {
background: #333
}
/* this is behind the navigation but the navigation is not inside it so that the navigation is accessible and scrolls*/
#slide-nav #navbar-height-col {
position: fixed;
top: 0;
height: 100%;
width: 80%;
left: -80%;
background: #eee;
}
#slide-nav.navbar-inverse #navbar-height-col {
background: #333;
z-index: 1;
border: 0;
}
#slide-nav .navbar-form {
width: 100%;
margin: 8px 0;
text-align: center;
overflow: hidden;
/*fast clearfixer*/
}
#slide-nav .navbar-form .form-control {
text-align: center
}
#slide-nav .navbar-form .btn {
width: 100%
}
}
@media (min-width:768px) {
#page-content {
left: 0!important
}
.navbar.navbar-fixed-top.slide-active {
position: fixed
}
.navbar-header {
left: 0!important
}
}
HTML
<div class="navbar navbar-inverse navbar-fixed-top" role="navigation" id="slide-nav">
<div class="container">
<div class="navbar-header">
<a class="navbar-toggle">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="navbar-brand" href="#">Project name</a>
</div>
<div id="slidemenu">
<form class="navbar-form navbar-right" role="form">
<div class="form-group">
<input type="search" placeholder="search" class="form-control">
</div>
<button type="submit" class="btn btn-primary">Search</button>
</form>
<ul class="nav navbar-nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#contact">Contact</a></li>
<li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li class="divider"></li>
<li class="dropdown-header">Nav header</li>
<li><a href="#">Separated link</a></li>
<li><a href="#">One more separated link</a></li>
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li class="divider"></li>
<li class="dropdown-header">Nav header</li>
<li><a href="#">Separated link</a></li>
<li><a href="#">One more separated link</a></li>
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li class="divider"></li>
<li class="dropdown-header">Nav header</li>
<li><a href="#">Separated link test long title goes here</a></li>
<li><a href="#">One more separated link</a></li>
</ul>
</li>
</ul>
</div>
</div>
</div>
jQuery
$(document).ready(function () {
//stick in the fixed 100% height behind the navbar but don't wrap it
$('#slide-nav.navbar .container').append($('<div id="navbar-height-col"></div>'));
// Enter your ids or classes
var toggler = '.navbar-toggle';
var pagewrapper = '#page-content';
var navigationwrapper = '.navbar-header';
var menuwidth = '100%'; // the menu inside the slide menu itself
var slidewidth = '80%';
var menuneg = '-100%';
var slideneg = '-80%';
$("#slide-nav").on("click", toggler, function (e) {
var selected = $(this).hasClass('slide-active');
$('#slidemenu').stop().animate({
left: selected ? menuneg : '0px'
});
$('#navbar-height-col').stop().animate({
left: selected ? slideneg : '0px'
});
$(pagewrapper).stop().animate({
left: selected ? '0px' : slidewidth
});
$(navigationwrapper).stop().animate({
left: selected ? '0px' : slidewidth
});
$(this).toggleClass('slide-active', !selected);
$('#slidemenu').toggleClass('slide-active');
$('#page-content, .navbar, body, .navbar-header').toggleClass('slide-active');
});
var selected = '#slidemenu, #page-content, body, .navbar, .navbar-header';
$(window).on("resize", function () {
if ($(window).width() > 767 && $('.navbar-toggle').is(':hidden')) {
$(selected).removeClass('slide-active');
}
});
});
<div (window:resize)="onResize($event)"
onResize(event) {
event.target.innerWidth;
}
or using the HostListener decorator:
@HostListener('window:resize', ['$event'])
onResize(event) {
event.target.innerWidth;
}
Supported global targets are window
, document
, and body
.
Until https://github.com/angular/angular/issues/13248 is implemented in Angular it is better for performance to subscribe to DOM events imperatively and use RXJS to reduce the amount of events as shown in some of the other answers.
You're looking for the zip builtin function. From the docs:
>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> zipped
[(1, 4), (2, 5), (3, 6)]
Use window.intro
inside of $(document).ready()
.
Try this:
$(".datepicker").on("dp.change", function(e) {
alert('hey');
});
Updated:
I made a library based on my gist code that generates those casting for you by using @CallbackFragment
and @Callback
.
https://github.com/zeroarst/callbackfragment.
And the example give you the example that send a callback from a fragment to another fragment.
Old answer:
I made a BaseCallbackFragment
and annotation @FragmentCallback
. It currently extends Fragment
, you can change it to DialogFragment
and will work. It checks the implementations with the following order: getTargetFragment() > getParentFragment() > context (activity).
Then you just need to extend it and declare your interfaces in your fragment and give it the annotation, and the base fragment will do the rest. The annotation also has a parameter mandatory
for you to determine whether you want to force the fragment to implement the callback.
public class EchoFragment extends BaseCallbackFragment {
private FragmentInteractionListener mListener;
@FragmentCallback
public interface FragmentInteractionListener {
void onEcho(EchoFragment fragment, String echo);
}
}
https://gist.github.com/zeroarst/3b3f32092d58698a4568cdb0919c9a93
According to this message on the GCC mailing list, you can use the file "nul" instead of /dev/null:
#include <stdio.h>
int main ()
{
FILE* outfile = fopen ("/dev/null", "w");
if (outfile == NULL)
{
fputs ("could not open '/dev/null'", stderr);
}
outfile = fopen ("nul", "w");
if (outfile == NULL)
{
fputs ("could not open 'nul'", stderr);
}
return 0;
}
(Credits to Danny for this code; copy-pasted from his message.)
You can also use this special "nul" file through redirection.
Once an image has been loaded in any way into the browser, it will be in the browser cache and will load much faster the next time it is used whether that use is in the current page or in any other page as long as the image is used before it expires from the browser cache.
So, to precache images, all you have to do is load them into the browser. If you want to precache a bunch of images, it's probably best to do it with javascript as it generally won't hold up the page load when done from javascript. You can do that like this:
function preloadImages(array) {
if (!preloadImages.list) {
preloadImages.list = [];
}
var list = preloadImages.list;
for (var i = 0; i < array.length; i++) {
var img = new Image();
img.onload = function() {
var index = list.indexOf(this);
if (index !== -1) {
// remove image from the array once it's loaded
// for memory consumption reasons
list.splice(index, 1);
}
}
list.push(img);
img.src = array[i];
}
}
preloadImages(["url1.jpg", "url2.jpg", "url3.jpg"]);
This function can be called as many times as you want and each time, it will just add more images to the precache.
Once images have been preloaded like this via javascript, the browser will have them in its cache and you can just refer to the normal URLs in other places (in your web pages) and the browser will fetch that URL from its cache rather than over the network.
Eventually over time, the browser cache may fill up and toss the oldest things that haven't been used in awhile. So eventually, the images will get flushed out of the cache, but they should stay there for awhile (depending upon how large the cache is and how much other browsing is done). Everytime the images are actually preloaded again or used in a web page, it refreshes their position in the browser cache automatically so they are less likely to get flushed out of the cache.
The browser cache is cross-page so it works for any page loaded into the browser. So you can precache in one place in your site and the browser cache will then work for all the other pages on your site.
When precaching as above, the images are loaded asynchronously so they will not block the loading or display of your page. But, if your page has lots of images of its own, these precache images can compete for bandwidth or connections with the images that are displayed in your page. Normally, this isn't a noticeable issue, but on a slow connection, this precaching could slow down the loading of the main page. If it was OK for preload images to be loaded last, then you could use a version of the function that would wait to start the preloading until after all other page resources were already loaded.
function preloadImages(array, waitForOtherResources, timeout) {
var loaded = false, list = preloadImages.list, imgs = array.slice(0), t = timeout || 15*1000, timer;
if (!preloadImages.list) {
preloadImages.list = [];
}
if (!waitForOtherResources || document.readyState === 'complete') {
loadNow();
} else {
window.addEventListener("load", function() {
clearTimeout(timer);
loadNow();
});
// in case window.addEventListener doesn't get called (sometimes some resource gets stuck)
// then preload the images anyway after some timeout time
timer = setTimeout(loadNow, t);
}
function loadNow() {
if (!loaded) {
loaded = true;
for (var i = 0; i < imgs.length; i++) {
var img = new Image();
img.onload = img.onerror = img.onabort = function() {
var index = list.indexOf(this);
if (index !== -1) {
// remove image from the array once it's loaded
// for memory consumption reasons
list.splice(index, 1);
}
}
list.push(img);
img.src = imgs[i];
}
}
}
}
preloadImages(["url1.jpg", "url2.jpg", "url3.jpg"], true);
preloadImages(["url99.jpg", "url98.jpg"], true);
That's all you need:
#include <string> //string::pop_back & string::empty
if (!st.empty())
st.pop_back();
Steps:
This gives you three files:
PushChatKey.p12
)aps_development.cer
Go to the folder where you downloaded the files, in my case the Desktop:
$ cd ~/Desktop/
Convert the .cer file into a .pem file:
$ openssl x509 -in aps_development.cer -inform der -out PushChatCert.pem
Convert the private key’s .p12 file into a .pem file:
$ openssl pkcs12 -nocerts -out PushChatKey.pem -in PushChatKey.p12
Enter Import Password:
MAC verified OK
Enter PEM pass phrase:
Verifying - Enter PEM pass phrase:
You first need to enter the passphrase for the .p12 file so that openssl can read it. Then you need to enter a new passphrase that will be used to encrypt the PEM file. Again for this tutorial I used “pushchat” as the PEM passphrase. You should choose something more secure. Note: if you don’t enter a PEM passphrase, openssl will not give an error message but the generated .pem file will not have the private key in it.
Finally, combine the certificate and key into a single .pem file:
$ cat PushChatCert.pem PushChatKey.pem > ck.pem
mainList.get(3);
For future reference, you should refer to the Java API for these types of questions:
http://download.oracle.com/javase/1.4.2/docs/api/java/util/ArrayList.html
It's a useful thing!
do
{
// whatever
} while ( !condition );
Well, in obvious cases like that, you can always tell PHP to suppress messages by using "@" in front of the function.
$monthly_index = @array_shift(unpack('H*', date('m/Y')));
It may not be one of the best programming practices to suppress all errors this way, but in certain cases (like this one) it comes handy and is acceptable.
As result, I am sure your friend 'system administrator' will be pleased with a less polluted error.log
.
Try this...
For Showing keyboard
editText.requestFocus();
InputMethodManager imm = (InputMethodManager) ctx.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
For Hide keyboard
InputMethodManager inputManager = (InputMethodManager) ctx.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
Use distinct-colors.
Written in javascript.
It generates a palette of visually distinct colors.
distinct-colors is highly configurable:
As other posters already indicated; your system clock is probably not synchronized up to microseconds to actual world time. Nonetheless are microsecond precision timestamps useful as a hybrid for both indicating current wall time, and measuring/profiling the duration of things.
I label all events/messages written to a log files using timestamps like "2012-10-21 19:13:45.267128". These convey both when it happened ("wall" time), and can also be used to measure the duration between this and the next event in the log file (relative difference in microseconds).
To achieve this, you need to link System.currentTimeMillis() with System.nanoTime() and work exclusively with System.nanoTime() from that moment forward. Example code:
/**
* Class to generate timestamps with microsecond precision
* For example: MicroTimestamp.INSTANCE.get() = "2012-10-21 19:13:45.267128"
*/
public enum MicroTimestamp
{ INSTANCE ;
private long startDate ;
private long startNanoseconds ;
private SimpleDateFormat dateFormat ;
private MicroTimestamp()
{ this.startDate = System.currentTimeMillis() ;
this.startNanoseconds = System.nanoTime() ;
this.dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS") ;
}
public String get()
{ long microSeconds = (System.nanoTime() - this.startNanoseconds) / 1000 ;
long date = this.startDate + (microSeconds/1000) ;
return this.dateFormat.format(date) + String.format("%03d", microSeconds % 1000) ;
}
}
I encountered a similar problem where I was not able to add event listeners to the player until after it had already started playing, so @Diode's method unfortunately would not work. My solution was check if the player's "paused" property was set to true or not. This works because "paused" is set to true even before the video ever starts playing and after it ends, not just when a user has clicked "pause".
I'm surprised no one's mentioned libraries. Lots of languages can link against C libs and call C functions (including C++ with extern "C"). C++ is pretty much the only thing that can use a C++ lib (defined as 'a lib that uses features in C++ that are not in C [such as overloaded functions, virtual methods, overloaded operators, ...], and does not export everything through C compatible interfaces via extern "C"').
Next time, use a single "alter table" statement to update the primary key.
alter table xx drop primary key, add primary key(k1, k2, k3);
To fix things:
create table fixit (user_2, user_1, type, timestamp, n, primary key( user_2, user_1, type) );
lock table fixit write, user_interactions u write, user_interactions write;
insert into fixit
select user_2, user_1, type, max(timestamp), count(*) n from user_interactions u
group by user_2, user_1, type
having n > 1;
delete u from user_interactions u, fixit
where fixit.user_2 = u.user_2
and fixit.user_1 = u.user_1
and fixit.type = u.type
and fixit.timestamp != u.timestamp;
alter table user_interactions add primary key (user_2, user_1, type );
unlock tables;
The lock should stop further updates coming in while your are doing this. How long this takes obviously depends on the size of your table.
The main problem is if you have some duplicates with the same timestamp.
Based on this blog post I was able to trigger hovering using the following code with Selenium 2 Webdriver:
String javaScript = "var evObj = document.createEvent('MouseEvents');" +
"evObj.initMouseEvent(\"mouseover\",true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);" +
"arguments[0].dispatchEvent(evObj);";
((JavascriptExecutor)driver).executeScript(javaScript, webElement);
There are lots of great recommendations in the answers.
A general best practice is to consider who will be reading the log. In my case it will be an administrator at the client site. So I log messages that gives them something they can act on. For Example, "Unable to initialize application. This is usually caused by ......"
I know this thread is very old but for those not using SQL Server 2012 or above or cannot use the FORMAT function for any reason then the following works.
Also, a lot of the solutions did not work if the number was less than 1 (e.g. 0.01230000).
Please note that the following does not work with negative numbers.
DECLARE @num decimal(28,14) = 10.012345000
SELECT PARSENAME(@num,2) + REPLACE(RTRIM(LTRIM(REPLACE(@num-PARSENAME(@num,2),'0',' '))),' ','0')
set @num = 0.0123450000
SELECT PARSENAME(@num,2) + REPLACE(RTRIM(LTRIM(REPLACE(@num-PARSENAME(@num,2),'0',' '))),' ','0')
Returns 10.012345 and 0.012345 respectively.
There's a simple argument to see where the binary logic gates come from, using truth tables, which have come up already.
There are six that represent commutative operations, in which a op b == b op a. Each binary operator has an associated three column truth table that defines it. The first two columns can be fixed for the defining tables for all the operators.
Consider the third column. It's a sequence of four binary digits. There are sixteen combinations, but the constraint of commutativity effectively removes one row from the truth tables, so it's only eight. Two more get knocked off because all truths or all falses isn't a useful gate. These are the familiar or, and, and xor, plus their negations.
preferences -> mysql -> initialize database -> use legacy password encryption(instead of strong) -> entered same password
as my config.inc.php file, restarted the apache server and it worked. I was still suspicious about it so I stopped the apache and mysql server and started them again and now it's working.
To add some flexibility here, you can achieve more fine-grained control over the level of logging by writing a function that filters out messages however you like:
logging.getLogger('tensorflow').addFilter(my_filter_func)
where my_filter_func
accepts a LogRecord
object as input [LogRecord
docs] and
returns zero if you want the message thrown out; nonzero otherwise.
Here's an example filter that only keeps every nth info message (Python 3 due
to the use of nonlocal
here):
def keep_every_nth_info(n):
i = -1
def filter_record(record):
nonlocal i
i += 1
return int(record.levelname != 'INFO' or i % n == 0)
return filter_record
# Example usage for TensorFlow:
logging.getLogger('tensorflow').addFilter(keep_every_nth_info(5))
All of the above has assumed that TensorFlow has set up its logging state already. You can ensure this without side effects by calling tf.logging.get_verbosity()
before adding a filter.
As far as I understand you need mean terminate as Thread.Abort()
right? In this case, you can just exit the Foo(). Or you can use Process to catch the thread.
Thread myThread = new Thread(DoWork);
myThread.Abort();
myThread.Start();
Process example:
using System;
using System.Diagnostics;
using System.ComponentModel;
using System.Threading;
using Microsoft.VisualBasic;
class PrintProcessClass
{
private Process myProcess = new Process();
private int elapsedTime;
private bool eventHandled;
// Print a file with any known extension.
public void PrintDoc(string fileName)
{
elapsedTime = 0;
eventHandled = false;
try
{
// Start a process to print a file and raise an event when done.
myProcess.StartInfo.FileName = fileName;
myProcess.StartInfo.Verb = "Print";
myProcess.StartInfo.CreateNoWindow = true;
myProcess.EnableRaisingEvents = true;
myProcess.Exited += new EventHandler(myProcess_Exited);
myProcess.Start();
}
catch (Exception ex)
{
Console.WriteLine("An error occurred trying to print \"{0}\":" + "\n" + ex.Message, fileName);
return;
}
// Wait for Exited event, but not more than 30 seconds.
const int SLEEP_AMOUNT = 100;
while (!eventHandled)
{
elapsedTime += SLEEP_AMOUNT;
if (elapsedTime > 30000)
{
break;
}
Thread.Sleep(SLEEP_AMOUNT);
}
}
// Handle Exited event and display process information.
private void myProcess_Exited(object sender, System.EventArgs e)
{
eventHandled = true;
Console.WriteLine("Exit time: {0}\r\n" +
"Exit code: {1}\r\nElapsed time: {2}", myProcess.ExitTime, myProcess.ExitCode, elapsedTime);
}
public static void Main(string[] args)
{
// Verify that an argument has been entered.
if (args.Length <= 0)
{
Console.WriteLine("Enter a file name.");
return;
}
// Create the process and print the document.
PrintProcessClass myPrintProcess = new PrintProcessClass();
myPrintProcess.PrintDoc(args[0]);
}
}
For those who are having trouble with fatal error: ESP8266WiFi.h: No such file or directory
, you can install the package manually.
You may still need to have the http://arduino.esp8266.com/stable/package_esp8266com_index.json package installed beforehand, however.
Edit: That wasn't the full issue, you need to make sure you have the correct ESP8266 Board selected before compiling.
Hope this helps others.
The code provided is correct, I don't see any reason why it wouldn't work.
You could also try if (string1.Equals(string2))
as suggested.
To do if (something OR something else)
, use ||
:
if (condition_1 || condition_2) { ... }
JRE 7 is probably installed in Program Files\Java
and NOT Program Files(x86)\Java
.
thanks to below posts, and I am able to add on the webpage link address to be printed and present time on the PDF generated, no matter how many pages it has.
Add text to Existing PDF using Python
https://github.com/disflux/django-mtr/blob/master/pdfgen/doc_overlay.py
To share the script as below:
import time
from pyPdf import PdfFileWriter, PdfFileReader
import StringIO
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
from xhtml2pdf import pisa
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
url = 'http://www.yahoo.com'
tem_pdf = "c:\\tem_pdf.pdf"
final_file = "c:\\younameit.pdf"
app = QApplication(sys.argv)
web = QWebView()
#Read the URL given
web.load(QUrl(url))
printer = QPrinter()
#setting format
printer.setPageSize(QPrinter.A4)
printer.setOrientation(QPrinter.Landscape)
printer.setOutputFormat(QPrinter.PdfFormat)
#export file as c:\tem_pdf.pdf
printer.setOutputFileName(tem_pdf)
def convertIt():
web.print_(printer)
QApplication.exit()
QObject.connect(web, SIGNAL("loadFinished(bool)"), convertIt)
app.exec_()
sys.exit
# Below is to add on the weblink as text and present date&time on PDF generated
outputPDF = PdfFileWriter()
packet = StringIO.StringIO()
# create a new PDF with Reportlab
can = canvas.Canvas(packet, pagesize=letter)
can.setFont("Helvetica", 9)
# Writting the new line
oknow = time.strftime("%a, %d %b %Y %H:%M")
can.drawString(5, 2, url)
can.drawString(605, 2, oknow)
can.save()
#move to the beginning of the StringIO buffer
packet.seek(0)
new_pdf = PdfFileReader(packet)
# read your existing PDF
existing_pdf = PdfFileReader(file(tem_pdf, "rb"))
pages = existing_pdf.getNumPages()
output = PdfFileWriter()
# add the "watermark" (which is the new pdf) on the existing page
for x in range(0,pages):
page = existing_pdf.getPage(x)
page.mergePage(new_pdf.getPage(0))
output.addPage(page)
# finally, write "output" to a real file
outputStream = file(final_file, "wb")
output.write(outputStream)
outputStream.close()
print final_file, 'is ready.'
I use this on my site and it works great.
<link rel="shortcut icon" type="image/x-icon" href="images/favicon.ico"/>
You may try to put the right database name in connection url in the configuration file. As I had the same error while run the POJO class file and it has been solved by this.
from IPython.display import Image
Image(filename =r'C:\user\path')
I've seen some solutions and some wont work because of the raw directory, when adding codes like the one above, just remember to add 'r' before the directory. this should avoid this kind of error: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
I like the idea from Jakub Jirutka to use Spring Expression Language. If you don't want to add another library/dependency (assuming that you already use Spring), here is a simplified implementation of his idea.
The constraint:
@Constraint(validatedBy=ExpressionAssertValidator.class)
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ExpressionAssert {
String message() default "expression must evaluate to true";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
String value();
}
The validator:
public class ExpressionAssertValidator implements ConstraintValidator<ExpressionAssert, Object> {
private Expression exp;
public void initialize(ExpressionAssert annotation) {
ExpressionParser parser = new SpelExpressionParser();
exp = parser.parseExpression(annotation.value());
}
public boolean isValid(Object value, ConstraintValidatorContext context) {
return exp.getValue(value, Boolean.class);
}
}
Apply like this:
@ExpressionAssert(value="pass == passVerify", message="passwords must be same")
public class MyBean {
@Size(min=6, max=50)
private String pass;
private String passVerify;
}
It looks like there are some problems with that code, Johannes:
getTerminalSize
needs to import os
env
? looks like os.environ
.Also, why switch lines
and cols
before returning? If TIOCGWINSZ
and stty
both say lines
then cols
, I say leave it that way. This confused me for a good 10 minutes before I noticed the inconsistency.
Sridhar, I didn't get that error when I piped output. I'm pretty sure it's being caught properly in the try-except.
pascal, "HHHH"
doesn't work on my machine, but "hh"
does. I had trouble finding documentation for that function. It looks like it's platform dependent.
chochem, incorporated.
Here's my version:
def getTerminalSize():
"""
returns (lines:int, cols:int)
"""
import os, struct
def ioctl_GWINSZ(fd):
import fcntl, termios
return struct.unpack("hh", fcntl.ioctl(fd, termios.TIOCGWINSZ, "1234"))
# try stdin, stdout, stderr
for fd in (0, 1, 2):
try:
return ioctl_GWINSZ(fd)
except:
pass
# try os.ctermid()
try:
fd = os.open(os.ctermid(), os.O_RDONLY)
try:
return ioctl_GWINSZ(fd)
finally:
os.close(fd)
except:
pass
# try `stty size`
try:
return tuple(int(x) for x in os.popen("stty size", "r").read().split())
except:
pass
# try environment variables
try:
return tuple(int(os.getenv(var)) for var in ("LINES", "COLUMNS"))
except:
pass
# i give up. return default.
return (25, 80)
This will find all .c or .cpp files on linux
$ find . -name "*.c" -o -name "*.cpp"
You don't need the escaped parenthesis unless you are doing some additional mods. Here from the man page they are saying if the pattern matches, print it. Perhaps they are trying to control printing. In this case the -print acts as a conditional and becomes an "AND'd" conditional. It will prevent any .c files from being printed.
$ find . -name "*.c" -o -name "*.cpp" -print
But if you do like the original answer you can control the printing. This will find all .c files as well.
$ find . \( -name "*.c" -o -name "*.cpp" \) -print
One last example for all c/c++ source files
$ find . \( -name "*.c" -o -name "*.cpp" -o -name "*.h" -o -name "*.hpp" \) -print
this issue occur for me after downgrade Java JDK, after upgrade JDK my problem resolved.
I use a very old java. Jdk 1.4.08 and I had the same issue. The Node
class for me did not had the getTextContent()
method. I had to use Node.getFirstChild().getNodeValue()
instead of Node.getNodeValue()
to get the value of the node. This fixed for me.
Bulk insert in Node.js can be done using the below code. I have referred lots of blog for getting this work.
please refer this link as well. https://www.technicalkeeda.com/nodejs-tutorials/insert-multiple-records-into-mysql-using-nodejs
The working code.
const educations = request.body.educations;
let queryParams = [];
for (let i = 0; i < educations.length; i++) {
const education = educations[i];
const userId = education.user_id;
const from = education.from;
const to = education.to;
const instituteName = education.institute_name;
const city = education.city;
const country = education.country;
const certificateType = education.certificate_type;
const studyField = education.study_field;
const duration = education.duration;
let param = [
from,
to,
instituteName,
city,
country,
certificateType,
studyField,
duration,
userId,
];
queryParams.push(param);
}
let sql =
"insert into tbl_name (education_from, education_to, education_institute_name, education_city, education_country, education_certificate_type, education_study_field, education_duration, user_id) VALUES ?";
let sqlQuery = dbManager.query(sql, [queryParams], function (
err,
results,
fields
) {
let res;
if (err) {
console.log(err);
res = {
success: false,
message: "Insertion failed!",
};
} else {
res = {
success: true,
id: results.insertId,
message: "Successfully inserted",
};
}
response.send(res);
});
Hope this will help you.
You have a single quotes conflict, so use:
echo "A,B,C" | sed "s/,/','/g"
If using bash, you can do too (<<<
is a here-string
):
sed "s/,/','/g" <<< "A,B,C"
but not
sed "s/,/','/g" "A,B,C"
because sed
expect file(s) as argument(s)
EDIT:
if you use ksh or any other ones :
echo string | sed ...
You should replace your getEnumNameForValue
by a call to the name()
method.
As Nikolai has said you can use the gdb 'set' command to change the value of a variable.
You can also use the 'set' command to change memory locations. eg. Expanding on Nikolai's example:
(gdb) l
6 {
7 int i;
8 struct file *f, *ftmp;
9
(gdb) set variable i = 10
(gdb) p i
$1 = 10
(gdb) p &i
$2 = (int *) 0xbfbb0000
(gdb) set *((int *) 0xbfbb0000) = 20
(gdb) p i
$3 = 20
This should work for any valid pointer, and can be cast to any appropriate data type.
I followed the most of the answers which was recommended here. First I got the following error:
fatal: unable to access 'https://github.com/folder/sample.git/': schannel: next InitializeSecurityContext failed: Unknown error (0x80092012) - The revocation function was unable to check revocation for the certificate.
Then I have tried the following command by @Salim Hamidi
git config --global http.proxy http://proxyuser:[email protected]:8080
But I got the following error:
fatal: unable to access 'https://github.com/folder/sample.git/': Received HTTP code 407 from proxy after CONNECT
This could happen if the proxy server can't verify the SSL certificate. So we want to make sure that the ssl verification is off (not recommended for non trusted sites), so I have done the following steps which was recommended by @Arpit but with slight changes:
1.First make sure to remove any previous proxy settings:
git config --global --unset http.proxy
2.Then list and get the gitconfig content
git config --list --show-origin
3.Last update the content of the gitconfig file as below:
[http]
sslCAInfo = C:/yourfolder/AppData/Local/Programs/Git/mingw64/ssl/certs/ca-bundle.crt
sslBackend = schannel
proxy = http://proxyuser:[email protected]:8080
sslverify = false
[https]
proxy = http://proxyuser:[email protected]:8080
sslverify = false
Either you set LDAP_DOMAIN variable or you misconfigured it. Jump inside of ldap machine/container and run:
slapcat > backup.ldif
If it fails, check punctuation, quotes etc while you assigned variable "LDAP_DOMAIN" Otherwise you will find answer inside on backup.ldif file.
I have solved this problem on my side by 2 ways:
Adding this configuration in pom.xml
<configuration><argLine>-Xmx1024m</argLine></configuration>
Switch to used JDK 1.7 instead of 1.6
Set that particular column's Visible
property = false
dataGridView[ColumnName or Index].Visible = false;
Edit
sorry missed the Columns
Property
dataGridView.Columns[ColumnName or Index].Visible = false;
It will not work like this, put both images as background images:
.bg-img {
background:url(images/yourImg.jpg) no-repeat 0 0;
}
.bg-img:hover {
background:url(images/yourImg-1.jpg) no-repeat 0 0;
}
Instance methods => invoked on specific instance of a specific class. Method wants to know upon which class it was invoked. The way it happens there is a invisible parameter called 'this'. Inside of 'this' we have members of instance class already set with values. 'This' is not a variable. It's a value, you cannot change it and the value is reference to the receiver of the call. Ex: You call repairmen(instance method) to fix your TV(actual program). He comes with tools('this' parameter). He comes with specific tools needed for fixing TV and he can fix other things also.
In static methods => there is no such thing as 'this'. Ex: The same repairman (static method). When you call him you have to specify which repairman to call(like electrician). And he will come and fix your TV only. But, he doesn't have tools to fix other things (there is no 'this' parameter).
Static methods are usually useful for operations that don't require any data from an instance of the class (from 'this') and can perform their intended purpose solely using their arguments.
captain_a is right that your app needs to be public with a developer email address. But if you are still getting the error then make sure that your website is using an SSL certificate.
For more detailed information and workarounds please checkout my answer at Facebook app is Public, but gives error "App not setup" when logging in
@Dougnukem answer helped me a lot. I have taken the Groovy approach (using groovy 2.3.3).
I did some changes on Dougnukem code. This will work with Java 7 and will print two attributes to stdout every 10 sec.
package com.my.company.jmx
import groovy.util.GroovyMBean;
import javax.management.remote.JMXServiceURL
import javax.management.remote.JMXConnectorFactory
import java.lang.management.*
class Monitor {
static main(args) {
def serverUrl = 'service:jmx:rmi:///jndi/rmi://localhost:5019/jmxrmi'
String beanName = "Catalina:type=DataSource,class=javax.sql.DataSource,name=\"jdbc/CommonDB\""
println "numIdle,numActive"
while(1){
def server = JMXConnectorFactory.connect(new JMXServiceURL(serverUrl))
//make sure to reconnect in case the jvm was restrated
server.connect()
GroovyMBean mbean = new GroovyMBean(server.MBeanServerConnection, beanName)
println "${mbean.numIdle},${mbean.numActive}"
server.close()
sleep(10000)
}
}
}
Compile this code into a jar using maven-compiler-plugin so you will not require groovy installation only the groovy-all.jar . Below is the relevant plugin definition and dependency.
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<compilerId>groovy-eclipse-compiler</compilerId>
<source>1.7</source>
<target>1.7</target>
</configuration>
<dependencies>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-eclipse-compiler</artifactId>
<version>2.8.0-01</version>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-eclipse-batch</artifactId>
<version>2.3.4-01</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>2.4.3</version>
</dependency>
</dependencies>
Wrap it with a bat or a shell and it will print the data to stdout.
This is a general solution for all types that conform to the Collection
protocol, which includes String
:
extension Optional where Wrapped: Collection {
var isNilOrEmpty: Bool {
self?.isEmpty ?? true
}
}
On the server.. In our environment, we're running Apache2 on Windows Server 2003.
Suppose Apache is serving our repository from C:\repo\MyProject
The actual repository is in C:\repo\MyProject\db
and the configuration is in C:\repo\MyProject\conf
So the passwords are in: C:\repo\MyProject.htaccess
They're encrypted, a tool similar to this: http://tools.dynamicdrive.com/password/
A common example of this in GUI code is when creating a widget/component and adding a listener to some static/application scoped object and then not removing the listener when the widget is destroyed. Not only do you get a memory leak, but also a performance hit as when whatever you are listening to fires events, all your old listeners are called too.
use uniform js plugin
to style input of any type, select, textarea.
The URL is http://uniformjs.com/
I've tried this 2 options (read/write), with plain objects, array of objects (150 objects), Map:
Option1:
FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(this);
os.close();
Option2:
SharedPreferences mPrefs=app.getSharedPreferences(app.getApplicationInfo().name, Context.MODE_PRIVATE);
SharedPreferences.Editor ed=mPrefs.edit();
Gson gson = new Gson();
ed.putString("myObjectKey", gson.toJson(objectToSave));
ed.commit();
Option 2 is twice quicker than option 1
The option 2 inconvenience is that you have to make specific code for read:
Gson gson = new Gson();
JsonParser parser=new JsonParser();
//object arr example
JsonArray arr=parser.parse(mPrefs.getString("myArrKey", null)).getAsJsonArray();
events=new Event[arr.size()];
int i=0;
for (JsonElement jsonElement : arr)
events[i++]=gson.fromJson(jsonElement, Event.class);
//Object example
pagination=gson.fromJson(parser.parse(jsonPagination).getAsJsonObject(), Pagination.class);
Just try this code this code work with me
var posOptions = {timeout: 10000, enableHighAccuracy: false};
$cordovaGeolocation.getCurrentPosition(posOptions).then(function (position) {
var lat = position.coords.latitude;
var long = position.coords.longitude;
//console.log(lat +" "+long);
$http.get('https://maps.googleapis.com/maps/api/geocode/json?latlng=' + lat + ',' + long + '&key=your key here').success(function (output) {
//console.log( JSON.stringify(output.results[0]));
//console.log( JSON.stringify(output.results[0].address_components[4].short_name));
var results = output.results;
if (results[0]) {
//console.log("results.length= "+results.length);
//console.log("hi "+JSON.stringify(results[0],null,4));
for (var j = 0; j < results.length; j++){
//console.log("j= "+j);
//console.log(JSON.stringify(results[j],null,4));
for (var i = 0; i < results[j].address_components.length; i++){
if(results[j].address_components[i].types[0] == "country") {
//this is the object you are looking for
country = results[j].address_components[i];
}
}
}
console.log(country.long_name);
console.log(country.short_name);
} else {
alert("No results found");
console.log("No results found");
}
});
}, function (err) {
});
If NetBeans haven't created your dist
folder, execute the do-dist
ant target:
In commandline navigate to the directory of your project, the one containing a build.xml file
> ant do-dist
If ant runs fine (most likely), your dist
folder will be created, containing the .war
file.
you can't increase the heap size dynamically.
you can request to use more by using android:largeHeap="true"
in the manifest.
also, you can use native memory (NDK & JNI)
, so you actually bypass the heap size limitation.
here are some posts i've made about it:
and here's a library i've made for it:
Just run this in a console.
@powershell -NoProfile -ExecutionPolicy unrestricted -Command "iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1'))" && SET PATH=%PATH%;%systemdrive%\chocolatey\bin
cinst powershell
It installs the latest version using a Chocolatey repository.
Originally I was using command cinst powershell 3.0.20121027
, but it looks like it later stopped working. Since this question is related to PowerShell 3.0 this was the right way. At this moment (June 26, 2014) cinst powershell
refers to version 3.0 of PowerShell, and that may change in future.
See the Chocolatey PowerShell package page for details on what version will be installed.
Trace.Write("Error Message") and Trace.Warn("Error Message") are the methods to use in web, need to decorate the page header trace=true and in config file to hide the error message text to go to end-user and so as to stay in iis itself for programmer debug.
To evaporate the warning, you can use libxml_use_internal_errors(true)
// create new DOMDocument
$document = new \DOMDocument('1.0', 'UTF-8');
// set error level
$internalErrors = libxml_use_internal_errors(true);
// load HTML
$document->loadHTML($html);
// Restore error level
libxml_use_internal_errors($internalErrors);
The below code illustrates how using a generator returns a result before completion, unlike the traditional non generator approach that returns a complete array after full iteration. With the generator below, the values are returned when ready, no need to wait for an array to be completely filled:
<?php
function sleepiterate($length) {
for ($i=0; $i < $length; $i++) {
sleep(2);
yield $i;
}
}
foreach (sleepiterate(5) as $i) {
echo $i, PHP_EOL;
}
I'm using 4 break points but as ralph.m said each site is unique. You should experiment. There are no magic breakpoints due to so many devices, screens, and resolutions.
Here is what I use as a template. I'm checking the website for each breakpoint on different mobile devices and updating CSS for each element (ul, div, etc.) not displaying correctly for that breakpoint.
So far that was working on multiple responsive websites I've made.
/* SMARTPHONES PORTRAIT */
@media only screen and (min-width: 300px) {
}
/* SMARTPHONES LANDSCAPE */
@media only screen and (min-width: 480px) {
}
/* TABLETS PORTRAIT */
@media only screen and (min-width: 768px) {
}
/* TABLET LANDSCAPE / DESKTOP */
@media only screen and (min-width: 1024px) {
}
UPDATE
As per September 2015, I'm using a better one. I find out that these media queries breakpoints match many more devices and desktop screen resolutions.
Having all CSS for desktop on style.css
All media queries on responsive.css: all CSS for responsive menu + media break points
@media only screen and (min-width: 320px) and (max-width: 479px){ ... }
@media only screen and (min-width: 480px) and (max-width: 767px){ ... }
@media only screen and (min-width: 768px) and (max-width: 991px){ ... }
@media only screen and (min-width: 992px){ ... }
Update 2019: As per Hugo comment below, I removed max-width 1999px because of the new very wide screens.
Follow these steps:
Regular expression
option near the bottom of the dialog.To add a word, such as test
, at the beginning of each line:
- Type
^
in theFind what
textbox- Type
test
in theReplace with
textbox- Place cursor in the first line of the file to ensure all lines are affected
- Click
Replace All
button
To add a word, such as test
, at the end of each line:
- Type
$
in theFind what
textbox- Type
test
in theReplace with
textbox- Place cursor in the first line of the file to ensure all lines are affected
- Click
Replace All
button
You should use the StringBuilder class.
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("Some text");
stringBuilder.append("Some text");
stringBuilder.append("Some text");
String finalString = stringBuilder.toString();
In addition, please visit:
Alternative (Insert tooltip to user):
<style>
a.tooltips {
position: relative;
display: inline;
}
a.tooltips span {
position: absolute;
width: 240px;
color: #FFFFFF;
background: #000000;
height: 30px;
line-height: 30px;
text-align: center;
visibility: hidden;
border-radius: 6px;
}
a.tooltips span:after {
content: '';
position: absolute;
top: 100%;
left: 50%;
margin-left: -8px;
width: 0;
height: 0;
border-top: 8px solid #000000;
border-right: 8px solid transparent;
border-left: 8px solid transparent;
}
a:hover.tooltips span {
visibility: visible;
opacity: 0.8;
bottom: 30px;
left: 50%;
margin-left: -76px;
z-index: 999;
}
</style>
<a class="tooltips" href="#">\\server\share\docs<span>Copy link and open in Explorer</span></a>
I added export VIRTUALENV_PYTHON=/usr/bin/python3
to my ~/.bashrc
like this:
export WORKON_HOME=$HOME/.virtualenvs
export VIRTUALENV_PYTHON=/usr/bin/python3
source /usr/local/bin/virtualenvwrapper.sh
then run source .bashrc
and you can specify the python version for each new env mkvirtualenv --python=python2 env_name
Q1) Here are couple things to read or google more :
Main differences between SOAP and RESTful web services in java http://www.ajaxonomy.com/2008/xml/web-services-part-1-soap-vs-rest
It's up to you what do you want to learn first. I'd recommend you take a look at the CXF framework. You can build both rest/soap services.
Q2) Here are couple of good tutorials for soap (I had them bookmarked) :
http://www.benmccann.com/blog/web-services-tutorial-with-apache-cxf/
http://www.mastertheboss.com/web-interfaces/337-apache-cxf-interceptors.html
Best way to learn is not just reading tutorials. But you would first go trough tutorials to get a basic idea so you can see that you're able to produce something(or not) and that would get you motivated.
SO is great way to learn particular technology (or more), people ask lot of wierd questions, and there are ever weirder answers. But overall you'll learn about ways to solve issues on other way. Maybe you didn't know of that way, maybe you couldn't thought of it by yourself.
Subscribe to couple of tags that are interesting to you and be persistent, ask good questions and try to give good answers and I guarantee you that you'll learn this as time passes (if you're persistent that is).
Q3) You will have to answer this one yourself. First by deciding what you're going to build, after all you will need to think of some mini project or something and take it from there.
If you decide to use CXF as your framework for building either REST/SOAP services I'd recommend you look up this book Apache CXF Web Service Development
.
It's fantastic, not hard to read and not too big either (win win).
If you don't specify indexes on your initial array, you get the regular numric ones. Arrays must have some form of unique index
Previous solutions were not working for me. I handled this issue as shown below.
layer_outputs = []
for i in range(1, len(model.layers)):
tmp_model = Model(model.layers[0].input, model.layers[i].output)
tmp_output = tmp_model.predict(img)[0]
layer_outputs.append(tmp_output)
Because it's been a several years since this question was first asked, the other answers are outdated or incomplete.
Here's the code for a modern implementation using jQuery:
$( 'div#1' ).on( 'click', function( event ) {
if ( event.ctrlKey ) {
//is ctrl + click
} else {
//normal click
}
} );
As for detecting right-clicks, this was correctly provided by another user but I'll list it here just to have everything in one place.
$( 'div#1' ).on( 'contextmenu', function( event ) {
// right-click handler
} ) ;
Just a headsup for anyone who may stumble across this... My h2 was inheriting
text-rendering: optimizelegibility;
//Changed to text-rendering: none; for fix
which was not allowing ellipsis. Apparently this is very finickey eh?
Keep in mind, the change of clock changes because of daylight saving time might give you some problems when only calculating the days.
Here's a little php function which takes care of that:
function add_days($date, $days) {
$timeStamp = strtotime(date('Y-m-d',$date));
$timeStamp+= 24 * 60 * 60 * $days;
// ...clock change....
if (date("I",$timeStamp) != date("I",$date)) {
if (date("I",$date)=="1") {
// summer to winter, add an hour
$timeStamp+= 60 * 60;
} else {
// summer to winter, deduct an hour
$timeStamp-= 60 * 60;
} // if
} // if
$cur_dat = mktime(0, 0, 0,
date("n", $timeStamp),
date("j", $timeStamp),
date("Y", $timeStamp)
);
return $cur_dat;
}
In order to use word-wrap: break-word
, you need to set a width (in px). For example:
div {
width: 250px;
word-wrap: break-word;
}
word-wrap is a CSS3 property, but it should work in all browsers, including IE 5.5-9.
The main differences between github and gists are in terms of number of features and user interface:
One is designed with a great number of features and flexibility in mind, which is a good fit for both small and very big projects, while gists are only a good fit for very small projects.
For example, gists do support multi-files, but the interface is very simple, and they're limited in features, so they don't even have a file browser, nor issues, pull requests or wiki. If you dont need to have that, gists are very nice and more discrete. Like the comments, instead of answers, in SO.
Note: Thanks to @Qwerty for the suggestion of making my comment a real answer.
It would depend on the implementation, but the limit is not defined by the List
interface.
The interface however defines the size()
method, which returns an int
.
Returns the number of elements in this list. If this list contains more than
Integer.MAX_VALUE
elements, returnsInteger.MAX_VALUE
.
So, no limit, but after you reach Integer.MAX_VALUE
, the behaviour of the list changes a bit
ArrayList
(which is tagged) is backed by an array, and is limited to the size of the array - i.e. Integer.MAX_VALUE
For macOS catalina try this : open Xcode. if not existing. download from App store (about 11GB) then open Xcode>open developer tool>more developer tool and used my apple id to download a compatible command line tool. Then, after downloading, I opened Xcode>Preferences>Locations>Command Line Tool and selected the newly downloaded command line tool from downloads.
If you are only interested into finding the position see @Pablo's answer.
pos = myArray.map(function(e) { return e.hello; }).indexOf('stevie');
However, if you are looking forward to finding the element (i.e. if you were thinking of doing something like this myArray[pos]
), there is a more efficient one-line way to do it, using filter
.
element = myArray.filter((e) => e.hello === 'stevie')[0];
See perfomance results (~ +42% ops/sec): http://jsbench.github.io/#7fa01f89a5dc5cc3bee79abfde80cdb3
The solution I use in my SpringMVC webapps is to create a simple DefaultController
class like the following: -
@Controller
public class DefaultController {
private final String redirect;
public DefaultController(String redirect) {
this.redirect = redirect;
}
@RequestMapping(value = "/")
public ModelAndView redirectToMainPage() {
return new ModelAndView("redirect:/" + redirect);
}
}
The redirect can be injected in using the following spring configuration: -
<bean class="com.adoreboard.farfisa.controller.DefaultController">
<constructor-arg name="redirect" value="${default.redirect:loginController}"/>
</bean>
The ${default.redirect:loginController}
will default to loginController
but can be changed by inserting default.redirect=something_else
into a spring properties file / setting an environment variable etc.
As @Mike has mentioned above I have also: -
<welcome-file-list> ... </welcome-file-list>
section in the web.xml
file.index.html
, index.jsp
, default.html
, etc)This solution lets Spring worry more about redirects which may or may not be what you like.
Have you tried to increase output_buffering in your php.ini?
you have problems with " :
<a href=<?php echo "'www.someotherwebsite.com'><img src='". url::file_loc('img'). "media/img/twitter.png' style='vertical-align: middle' border='0'></a>"; ?>
If you want to use less code, you can also use the norm
in the stats
package (the 'F' stands for Forbenius, which is the Euclidean norm):
norm(matrix(x1-x2), 'F')
While this may look a bit neater, it's not faster. Indeed, a quick test on very large vectors shows little difference, though so12311's method is slightly faster. We first define:
set.seed(1234)
x1 <- rnorm(300000000)
x2 <- rnorm(300000000)
Then testing for time yields the following:
> system.time(a<-sqrt(sum((x1-x2)^2)))
user system elapsed
1.02 0.12 1.18
> system.time(b<-norm(matrix(x1-x2), 'F'))
user system elapsed
0.97 0.33 1.31
# Bloqueio facebook
for ip in `whois -h whois.radb.net '!gAS32934' | grep /`
do
iptables -A FORWARD -p all -d $ip -j REJECT
done
Looks like MySQLdb doesn't actually provide a translation for that API call. The relevant C API call is mysql_fetch_fields
, and there is no MySQLdb translation for that
This has been driving me crazy all day (since indeed you can't control the Excel column types before opening the CSV file), and this worked for me, using VB.NET and Excel Interop:
'Convert .csv file to .txt file.
FileName = ConvertToText(FileName)
Dim ColumnTypes(,) As Integer = New Integer(,) {{1, xlTextFormat}, _
{2, xlTextFormat}, _
{3, xlGeneralFormat}, _
{4, xlGeneralFormat}, _
{5, xlGeneralFormat}, _
{6, xlGeneralFormat}}
'We are using OpenText() in order to specify the column types.
mxlApp.Workbooks.OpenText(FileName, , , Excel.XlTextParsingType.xlDelimited, , , True, , True, , , , ColumnTypes)
mxlWorkBook = mxlApp.ActiveWorkbook
mxlWorkSheet = CType(mxlApp.ActiveSheet, Excel.Worksheet)
Private Function ConvertToText(ByVal FileName As String) As String
'Convert the .csv file to a .txt file.
'If the file is a text file, we can specify the column types.
'Otherwise, the Codes are first converted to numbers, which loses trailing zeros.
Try
Dim MyReader As New StreamReader(FileName)
Dim NewFileName As String = FileName.Replace(".CSV", ".TXT")
Dim MyWriter As New StreamWriter(NewFileName, False)
Dim strLine As String
Do While Not MyReader.EndOfStream
strLine = MyReader.ReadLine
MyWriter.WriteLine(strLine)
Loop
MyReader.Close()
MyReader.Dispose()
MyWriter.Close()
MyWriter.Dispose()
Return NewFileName
Catch ex As Exception
MsgBox(ex.Message)
Return ""
End Try
End Function
Android has build-in patterns for email, phone number, etc, that you can use if you are building for Android API level 8 and above.
private boolean isValidEmail(CharSequence email) {
if (!TextUtils.isEmpty(email)) {
return Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
return false;
}
private boolean isValidPhoneNumber(CharSequence phoneNumber) {
if (!TextUtils.isEmpty(phoneNumber)) {
return Patterns.PHONE.matcher(phoneNumber).matches();
}
return false;
}
Yes, You can use gcc to compile your asm code. Use -c for compilation like this:
gcc -c file.S -o file.o
This will give object code file named file.o. To invoke linker perform following after above command:
gcc file.o -o file
As I understand, you want the average value for each id at each pass. The solution is
SELECT id, pass, avg(value) FROM data_r1
GROUP BY id, pass;
Tested and works on SQL 2005 and 2008. Not sure if this works in 2012 and later.
The solution uses DATENAME instead of DATEPART
select datename(dw,getdate()) --Thursday
select datepart(dw,getdate()) --2
This is work in sql 2014 also.
public static function slugify ($text) {
$replace = [
'<' => '', '>' => '', ''' => '', '&' => '',
'"' => '', 'À' => 'A', 'Á' => 'A', 'Â' => 'A', 'Ã' => 'A', 'Ä'=> 'Ae',
'Ä' => 'A', 'Å' => 'A', 'A' => 'A', 'A' => 'A', 'A' => 'A', 'Æ' => 'Ae',
'Ç' => 'C', 'C' => 'C', 'C' => 'C', 'C' => 'C', 'C' => 'C', 'D' => 'D', 'Ð' => 'D',
'Ð' => 'D', 'È' => 'E', 'É' => 'E', 'Ê' => 'E', 'Ë' => 'E', 'E' => 'E',
'E' => 'E', 'E' => 'E', 'E' => 'E', 'E' => 'E', 'G' => 'G', 'G' => 'G',
'G' => 'G', 'G' => 'G', 'H' => 'H', 'H' => 'H', 'Ì' => 'I', 'Í' => 'I',
'Î' => 'I', 'Ï' => 'I', 'I' => 'I', 'I' => 'I', 'I' => 'I', 'I' => 'I',
'I' => 'I', '?' => 'IJ', 'J' => 'J', 'K' => 'K', 'L' => 'K', 'L' => 'K',
'L' => 'K', 'L' => 'K', '?' => 'K', 'Ñ' => 'N', 'N' => 'N', 'N' => 'N',
'N' => 'N', '?' => 'N', 'Ò' => 'O', 'Ó' => 'O', 'Ô' => 'O', 'Õ' => 'O',
'Ö' => 'Oe', 'Ö' => 'Oe', 'Ø' => 'O', 'O' => 'O', 'O' => 'O', 'O' => 'O',
'Œ' => 'OE', 'R' => 'R', 'R' => 'R', 'R' => 'R', 'S' => 'S', 'Š' => 'S',
'S' => 'S', 'S' => 'S', '?' => 'S', 'T' => 'T', 'T' => 'T', 'T' => 'T',
'?' => 'T', 'Ù' => 'U', 'Ú' => 'U', 'Û' => 'U', 'Ü' => 'Ue', 'U' => 'U',
'Ü' => 'Ue', 'U' => 'U', 'U' => 'U', 'U' => 'U', 'U' => 'U', 'U' => 'U',
'W' => 'W', 'Ý' => 'Y', 'Y' => 'Y', 'Ÿ' => 'Y', 'Z' => 'Z', 'Ž' => 'Z',
'Z' => 'Z', 'Þ' => 'T', 'à' => 'a', 'á' => 'a', 'â' => 'a', 'ã' => 'a',
'ä' => 'ae', 'ä' => 'ae', 'å' => 'a', 'a' => 'a', 'a' => 'a', 'a' => 'a',
'æ' => 'ae', 'ç' => 'c', 'c' => 'c', 'c' => 'c', 'c' => 'c', 'c' => 'c',
'd' => 'd', 'd' => 'd', 'ð' => 'd', 'è' => 'e', 'é' => 'e', 'ê' => 'e',
'ë' => 'e', 'e' => 'e', 'e' => 'e', 'e' => 'e', 'e' => 'e', 'e' => 'e',
'ƒ' => 'f', 'g' => 'g', 'g' => 'g', 'g' => 'g', 'g' => 'g', 'h' => 'h',
'h' => 'h', 'ì' => 'i', 'í' => 'i', 'î' => 'i', 'ï' => 'i', 'i' => 'i',
'i' => 'i', 'i' => 'i', 'i' => 'i', 'i' => 'i', '?' => 'ij', 'j' => 'j',
'k' => 'k', '?' => 'k', 'l' => 'l', 'l' => 'l', 'l' => 'l', 'l' => 'l',
'?' => 'l', 'ñ' => 'n', 'n' => 'n', 'n' => 'n', 'n' => 'n', '?' => 'n',
'?' => 'n', 'ò' => 'o', 'ó' => 'o', 'ô' => 'o', 'õ' => 'o', 'ö' => 'oe',
'ö' => 'oe', 'ø' => 'o', 'o' => 'o', 'o' => 'o', 'o' => 'o', 'œ' => 'oe',
'r' => 'r', 'r' => 'r', 'r' => 'r', 'š' => 's', 'ù' => 'u', 'ú' => 'u',
'û' => 'u', 'ü' => 'ue', 'u' => 'u', 'ü' => 'ue', 'u' => 'u', 'u' => 'u',
'u' => 'u', 'u' => 'u', 'u' => 'u', 'w' => 'w', 'ý' => 'y', 'ÿ' => 'y',
'y' => 'y', 'ž' => 'z', 'z' => 'z', 'z' => 'z', 'þ' => 't', 'ß' => 'ss',
'?' => 'ss', '??' => 'iy', '?' => 'A', '?' => 'B', '?' => 'V', '?' => 'G',
'?' => 'D', '?' => 'E', '?' => 'YO', '?' => 'ZH', '?' => 'Z', '?' => 'I',
'?' => 'Y', '?' => 'K', '?' => 'L', '?' => 'M', '?' => 'N', '?' => 'O',
'?' => 'P', '?' => 'R', '?' => 'S', '?' => 'T', '?' => 'U', '?' => 'F',
'?' => 'H', '?' => 'C', '?' => 'CH', '?' => 'SH', '?' => 'SCH', '?' => '',
'?' => 'Y', '?' => '', '?' => 'E', '?' => 'YU', '?' => 'YA', '?' => 'a',
'?' => 'b', '?' => 'v', '?' => 'g', '?' => 'd', '?' => 'e', '?' => 'yo',
'?' => 'zh', '?' => 'z', '?' => 'i', '?' => 'y', '?' => 'k', '?' => 'l',
'?' => 'm', '?' => 'n', '?' => 'o', '?' => 'p', '?' => 'r', '?' => 's',
'?' => 't', '?' => 'u', '?' => 'f', '?' => 'h', '?' => 'c', '?' => 'ch',
'?' => 'sh', '?' => 'sch', '?' => '', '?' => 'y', '?' => '', '?' => 'e',
'?' => 'yu', '?' => 'ya'
];
// make a human readable string
$text = strtr($text, $replace);
// replace non letter or digits by -
$text = preg_replace('~[^\\pL\d.]+~u', '-', $text);
// trim
$text = trim($text, '-');
// remove unwanted characters
$text = preg_replace('~[^-\w.]+~', '', $text);
$text = strtolower($text);
return $text;
}
The ternary operator is the best way to a concise expression. The syntax is variable = value_1 if condition else value_2
. So, for your example, you must apply the ternary operator twice:
i = 23 # set any value for i
x = 2 if i > 100 else 1 if i < 100 else 0
Use [tableView scrollToRowAtIndexPath:indexPath atScrollPosition:scrollPosition animated:YES];
Scrolls the receiver until a row identified by index path is at a particular location on the screen.
And
scrollToNearestSelectedRowAtScrollPosition:animated:
Scrolls the table view so that the selected row nearest to a specified position in the table view is at that position.
Since this is a fatal error and also quite difficult to debug, maybe the fix could be put somewhere (in the provided command line?):
export GPG_TTY=$(tty)
on branchB do $git checkout branchA
to switch to branch A
on branchA do $git merge branchB
That's all you need.
#include <stdio.h>
#include <string.h>
int main(void){
char word[17], outword[33];//17:16+1, 33:16*2+1
int i, len;
printf("Intro word:");
fgets(word, sizeof(word), stdin);
len = strlen(word);
if(word[len-1]=='\n')
word[--len] = '\0';
for(i = 0; i<len; i++){
sprintf(outword+i*2, "%02X", word[i]);
}
printf("%s\n", outword);
return 0;
}
To all who have faced this issue/ will face it in the future:
Click on Build menu -> Select Build Variant -> restore to 'debug'
Outcomment on debuggable in module:app /* debug { debuggable true }*/
Go to Build menu -> generate signed apk -> .... -> build it
There is another asynchronous way use Blob and FileReader.
I didn't test the performance. But it is a different way of thinking.
function arrayBufferToBase64( buffer, callback ) {
var blob = new Blob([buffer],{type:'application/octet-binary'});
var reader = new FileReader();
reader.onload = function(evt){
var dataurl = evt.target.result;
callback(dataurl.substr(dataurl.indexOf(',')+1));
};
reader.readAsDataURL(blob);
}
//example:
var buf = new Uint8Array([11,22,33]);
arrayBufferToBase64(buf, console.log.bind(console)); //"CxYh"
If the to-be-updated component is not inside the same NamingContainer
component (ui:repeat
, h:form
, h:dataTable
, etc), then you need to specify the "absolute" client ID. Prefix with :
(the default NamingContainer
separator character) to start from root.
<p:ajax process="@this" update="count :subTotal"/>
To be sure, check the client ID of the subTotal
component in the generated HTML for the actual value. If it's inside for example a h:form
as well, then it's prefixed with its client ID as well and you would need to fix it accordingly.
<p:ajax process="@this" update="count :formId:subTotal"/>
Space separation of IDs is more recommended as <f:ajax>
doesn't support comma separation and starters would otherwise get confused.
Yes lists and tuples are always ordered while dictionaries are not
Let me help you understand it with an example of "codaddict's algorithm"
'Dictionary in C#' is 'Hashmap in Java' in parallel universe.
Some implementations are different. See the example below to understand better.
Declaring Java HashMap:
Map<Integer, Integer> pairs = new HashMap<Integer, Integer>();
Declaring C# Dictionary:
Dictionary<int, int> Pairs = new Dictionary<int, int>();
Getting a value from a location:
pairs.get(input[i]); // in Java
Pairs[input[i]]; // in C#
Setting a value at location:
pairs.put(k - input[i], input[i]); // in Java
Pairs[k - input[i]] = input[i]; // in C#
An Overall Example can be observed from below Codaddict's algorithm.
codaddict's algorithm in Java:
import java.util.HashMap;
public class ArrayPairSum {
public static void printSumPairs(int[] input, int k)
{
Map<Integer, Integer> pairs = new HashMap<Integer, Integer>();
for (int i = 0; i < input.length; i++)
{
if (pairs.containsKey(input[i]))
System.out.println(input[i] + ", " + pairs.get(input[i]));
else
pairs.put(k - input[i], input[i]);
}
}
public static void main(String[] args)
{
int[] a = { 2, 45, 7, 3, 5, 1, 8, 9 };
printSumPairs(a, 10);
}
}
Codaddict's algorithm in C#
using System;
using System.Collections.Generic;
class Program
{
static void checkPairs(int[] input, int k)
{
Dictionary<int, int> Pairs = new Dictionary<int, int>();
for (int i = 0; i < input.Length; i++)
{
if (Pairs.ContainsKey(input[i]))
{
Console.WriteLine(input[i] + ", " + Pairs[input[i]]);
}
else
{
Pairs[k - input[i]] = input[i];
}
}
}
static void Main(string[] args)
{
int[] a = { 2, 45, 7, 3, 5, 1, 8, 9 };
//method : codaddict's algorithm : O(n)
checkPairs(a, 10);
Console.Read();
}
}
Use .toInt()
for int .toFloat()
for float and .toDouble()
for double
I use >> /dev/null 2>&1
for a silent cronjob. A cronjob will do the job, but not send a report to my email.
As far as I know, don't remove /dev/null
. It's useful, especially when you run cPanel, it can be used for throw-away cronjob reports.
Your log4j.properties file should be on the root level of your capitolo2.ear (not in META-INF), that is, here:
MyProject
¦ build.xml
¦
+---build
¦ ¦ capitolo2-ejb.jar
¦ ¦ capitolo2-war.war
¦ ¦ JBoss4.dpf
¦ ¦ log4j.properties